python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
---|---|---|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `utils.py`."""
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import utils
def _shape_to_tuple(shape):
if isinstance(shape, tuple):
return shape
return tuple([shape])
class ScaleGradientTest(parameterized.TestCase):
@parameterized.product(inputs=[-1., 0., 1.], scale=[-0.5, 0., 0.5, 1., 2.])
@mock.patch.object(jax.lax, 'stop_gradient', wraps=jax.lax.stop_gradient)
def test_scale_gradient(self, mock_sg, inputs, scale):
def fn(inputs):
outputs = utils.scale_gradient(inputs, scale)
return outputs ** 2
grad = jax.grad(fn)
self.assertEqual(grad(inputs), 2 * inputs * scale)
if scale == 0.:
mock_sg.assert_called_once_with(inputs)
else:
self.assertFalse(mock_sg.called)
self.assertEqual(fn(inputs), inputs ** 2)
@parameterized.product(scale=[-0.5, 0., 0.5, 1., 2.])
def test_scale_gradient_pytree(self, scale):
def fn(inputs):
outputs = utils.scale_gradient(inputs, scale)
outputs = jax.tree_util.tree_map(lambda x: x ** 2, outputs)
return sum(jax.tree_util.tree_leaves(outputs))
inputs = dict(a=-1., b=dict(c=(2.,), d=0.))
grad = jax.grad(fn)
grads = grad(inputs)
jax.tree_util.tree_map(
lambda i, g: self.assertEqual(g, 2 * i * scale), inputs, grads)
self.assertEqual(
fn(inputs),
sum(jax.tree_util.tree_leaves(
jax.tree_util.tree_map(lambda x: x**2, inputs))))
class MultiNormalDiagFromLogScaleTest(parameterized.TestCase):
def _get_loc_scale(self, loc_shape, scale_shape):
loc = 1.5 * jnp.ones(shape=loc_shape, dtype=jnp.float32)
scale = 0.5 * jnp.ones(shape=scale_shape, dtype=jnp.float32)
return loc, scale
@parameterized.parameters(
(1, 1, 1),
(5, 5, 5),
((2, 3), (2, 3), (2, 3)),
((1, 4), (3, 4), (3, 4)),
((1, 2, 1, 3), (2, 1, 4, 3), (2, 2, 4, 3)),
)
def test_init_successful_broadcast(
self, loc_shape, scale_shape, broadcasted_shape
):
loc, scale = self._get_loc_scale(loc_shape, scale_shape)
dist = utils.multi_normal(loc, scale)
self.assertIsInstance(dist, utils.MultiNormalDiagFromLogScale)
mean, log_scale = dist.params
self.assertEqual(tuple(mean.shape), _shape_to_tuple(loc_shape))
self.assertEqual(tuple(log_scale.shape), _shape_to_tuple(scale_shape))
self.assertEqual(
tuple(dist._param_shape), _shape_to_tuple(broadcasted_shape)
)
@parameterized.parameters(
(2, 3),
((2, 3), (3, 2)),
((2, 4), (3, 4)),
((1, 2, 1, 3), (2, 1, 4, 4)),
)
def test_init_unsuccessful_broadcast(self, loc_shape, scale_shape):
loc, scale = self._get_loc_scale(loc_shape, scale_shape)
with self.assertRaisesRegex(
ValueError, 'Incompatible shapes for broadcasting'
):
utils.multi_normal(loc, scale)
@parameterized.parameters(list, tuple)
def test_sample_input_sequence_types(self, sample_type):
sample_shape = sample_type((4, 5))
loc_shape = scale_shape = (2, 3)
loc, scale = self._get_loc_scale(loc_shape, scale_shape)
dist = utils.multi_normal(loc, scale)
samples = dist.sample(sample_shape, jax.random.PRNGKey(239))
self.assertEqual(samples.shape, tuple(sample_shape) + loc_shape)
@parameterized.named_parameters([
('1d', 1),
('2d', (2, 3)),
('4d', (1, 2, 3, 4)),
])
def test_log_prob(self, shape):
loc, scale = self._get_loc_scale(shape, shape)
dist = utils.multi_normal(loc, scale)
probs = dist.log_prob(jnp.ones(shape=shape, dtype=jnp.float32))
self.assertEqual(probs.shape, ())
class HelpersTest(parameterized.TestCase):
@parameterized.parameters([
(1, 1),
(3, 3),
(1, 3),
(2, 3),
])
def test_set_diags_valid(self, n, d):
def _all_but_diag(matrix):
return matrix - jnp.diag(jnp.diag(matrix))
a = jnp.ones(shape=(n, d, d)) * 10
new_diags = jnp.arange(n * d).reshape((n, d))
res = utils.set_diags(a, new_diags)
for i in range(n):
np.testing.assert_array_equal(jnp.diag(res[i]), new_diags[i])
np.testing.assert_array_equal(_all_but_diag(res[i]), _all_but_diag(a[i]))
@parameterized.named_parameters([
('1d', 1),
('2d', (2, 3)),
('4d', (1, 2, 3, 4)),
])
def test_set_diag_a_raises(self, a_shape):
a = jnp.ones(shape=a_shape)
new_diags = jnp.zeros(shape=(2, 2))
with self.assertRaisesRegex(ValueError, 'Expected `a` to be a 3D tensor'):
utils.set_diags(a, new_diags)
@parameterized.named_parameters([
('1d', 1),
('3d', (2, 3, 4)),
('4d', (1, 2, 3, 4)),
])
def test_set_diag_new_diags_raises(self, new_diags_shape):
a = jnp.ones(shape=(3, 2, 2))
new_diags = jnp.zeros(shape=new_diags_shape)
with self.assertRaisesRegex(
ValueError, 'Expected `new_diags` to be a 2D array'
):
utils.set_diags(a, new_diags)
@parameterized.parameters([
(1, 1, 2),
(3, 3, 4),
(1, 3, 5),
(2, 3, 2),
])
def test_set_diag_a_shape_mismatch_raises(self, n, d, d1):
a = jnp.ones(shape=(n, d, d1))
new_diags = jnp.zeros(shape=(n, d))
with self.assertRaisesRegex(
ValueError, 'Shape mismatch: expected `a.shape`'
):
utils.set_diags(a, new_diags)
@parameterized.parameters([
(1, 1, 1, 3),
(3, 3, 4, 3),
(1, 3, 1, 5),
(2, 3, 6, 7),
])
def test_set_diag_new_diags_shape_mismatch_raises(self, n, d, n1, d1):
a = jnp.ones(shape=(n, d, d))
new_diags = jnp.zeros(shape=(n1, d1))
with self.assertRaisesRegex(
ValueError, 'Shape mismatch: expected `new_diags.shape`'
):
utils.set_diags(a, new_diags)
@parameterized.parameters([
(jnp.float32, [1.3, 2.001, 3.6], [-3.3], [1.3, 2.001, 3.6], [-3.3]),
(jnp.float32, [1.3, 2.001, 3.6], [-3], [1.3, 2.001, 3.6], [-3.0]),
(jnp.int32, [1.3, 2.001, 3.6], [-3.3], [1, 2, 3], [-3]),
(jnp.int32, [1.3, 2.001, 3.6], [-3], [1, 2, 3], [-3]),
(None, [1.123, 2.33], [0.0], [1.123, 2.33], [0.0]),
(None, [1, 2, 3], [0.0], [1, 2, 3], [0.0]),
])
def test_cast_tree(self, dtype, b, c, new_b, new_c):
def _build_tree(val1, val2):
dict_tree = {'a': {'b': jnp.array(val1)}, 'c': jnp.array(val2)}
return jax.tree_util.tree_map(lambda x: x, dict_tree)
tree = _build_tree(b, c)
tree = utils.cast_tree(tree, dtype=dtype)
jax.tree_util.tree_map(
np.testing.assert_array_equal, tree, _build_tree(new_b, new_c)
)
@parameterized.named_parameters([
('1d-single', 1),
('1d', 10),
('2d', (1, 2)),
('3d', (10, 3, 2)),
('4d', (2, 3, 4, 5)),
('6d', (1, 2, 3, 4, 5, 6)),
('8d', (5, 4, 7, 6, 1, 2, 3, 1)),
])
def test_tile_second_to_last_dim(self, shape):
shape = _shape_to_tuple(shape)
elems = jnp.prod(jnp.array(shape))
matrix = jnp.arange(elems).reshape(shape)
result = utils.tile_second_to_last_dim(matrix)
self.assertEqual(result.shape, shape + (shape[-1],))
np.testing.assert_array_equal(result[..., -1], matrix)
np.testing.assert_array_equal(result[..., 0], matrix)
@parameterized.parameters([
(None, None),
(jnp.float32, np.dtype('float32')),
(jnp.int32, np.dtype('int32')),
(jnp.bfloat16, np.dtype('bfloat16')),
])
def test_canonicalize_dtype(self, dtype, expected_dtype):
canonical = utils.canonicalize_dtype(dtype)
self.assertIs(canonical, expected_dtype)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/utils_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `transform.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import alias
from optax._src import combine
from optax._src import transform
from optax._src import update
STEPS = 50
LR = 1e-2
class TransformTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.init_params = (jnp.array([1., 2.]), jnp.array([3., 4.]))
self.per_step_updates = (jnp.array([500., 5.]), jnp.array([300., 3.]))
@chex.all_variants
@parameterized.named_parameters([
('adam', transform.scale_by_adam),
('adamax', transform.scale_by_adamax),
('lion', transform.scale_by_lion),
('rmsprop', transform.scale_by_rms),
('stddev', transform.scale_by_stddev),
('trust_ratio', transform.scale_by_trust_ratio),
('param_block_norm', transform.scale_by_param_block_norm),
('param_block_rms', transform.scale_by_param_block_rms),
('distance_over_gradients', transform.scale_by_distance_over_gradients),
])
def test_scalers(self, scaler_constr):
params = self.init_params
scaler = scaler_constr()
init_fn = self.variant(scaler.init)
transform_fn = self.variant(scaler.update)
state = init_fn(params)
chex.assert_tree_all_finite(state)
updates, state = transform_fn(self.per_step_updates, state, params)
chex.assert_tree_all_finite((params, updates, state))
jax.tree_util.tree_map(
lambda *args: chex.assert_equal_shape(args), params, updates)
@chex.all_variants
def test_add_decayed_weights(self):
# Define a transform that add decayed weights.
# We can define a mask either as a pytree, or as a function that
# returns the pytree. Below we define the pytree directly.
mask = (True, dict(a=True, b=False))
tx = transform.add_decayed_weights(0.1, mask=mask)
# Define input updates and weights.
updates = (
jnp.zeros((2,), dtype=jnp.float32),
dict(
a=jnp.zeros((2,), dtype=jnp.float32),
b=jnp.zeros((2,), dtype=jnp.float32),))
weights = (
jnp.ones((2,), dtype=jnp.float32),
dict(
a=jnp.ones((2,), dtype=jnp.float32),
b=jnp.ones((2,), dtype=jnp.float32),))
# This mask means that we will add decayed weights to the first two
# terms in the input updates, but not to the last element.
expected_tx_updates = (
0.1*jnp.ones((2,), dtype=jnp.float32),
dict(
a=0.1*jnp.ones((2,), dtype=jnp.float32),
b=jnp.zeros((2,), dtype=jnp.float32),))
# Apply transform
state = tx.init(weights)
transform_fn = self.variant(tx.update)
new_updates, _ = transform_fn(updates, state, weights)
# Assert output as expected.
chex.assert_trees_all_close(new_updates, expected_tx_updates)
@chex.all_variants
def test_ema(self):
values = jnp.array([5.0, 7.0])
decay = 0.9
d = decay
ema = transform.ema(decay=decay, debias=False)
state = ema.init(values[0]) # init to zeroes
transform_fn = self.variant(ema.update)
mean, state = transform_fn(values[0], state)
np.testing.assert_allclose(mean, (1-d) * values[0], atol=1e-4)
mean, state = transform_fn(values[1], state)
np.testing.assert_allclose(
mean,
(1 - d) * (values[1] + d * values[0]), atol=1e-2)
@chex.all_variants
def test_ema_debias(self):
values = jnp.array([5.0, 7.0])
decay = 0.9
d = decay
ema = transform.ema(decay=decay)
state = ema.init(values[0])
transform_fn = self.variant(ema.update)
mean, state = transform_fn(values[0], state)
np.testing.assert_allclose(mean, values[0], atol=1e-4)
mean, state = transform_fn(values[1], state)
np.testing.assert_allclose(
mean,
((1 - d) * values[1] + d * (1 - d) * values[0]) / (1 - d**2),
atol=1e-2)
# The state must not be debiased.
np.testing.assert_allclose(
state.ema,
(1 - d) * values[1] + d * (1 - d) * values[0],
atol=1e-2)
@chex.all_variants
def test_update_infinity_moment(self):
values = jnp.array([5.0, 7.0])
decay = 0.9
d = decay
transform_fn = self.variant(transform.update_infinity_moment)
# identity if updating with itself (and positive decay)
np.testing.assert_allclose(
transform_fn(values, values, decay=d, eps=0.),
values,
atol=1e-4
)
# return (decayed) max when updating with zeros
np.testing.assert_allclose(
transform_fn(jnp.zeros_like(values), values, decay=d, eps=0.),
d * values,
atol=1e-4
)
# infinity norm takes absolute values
np.testing.assert_allclose(
transform_fn(-values, jnp.zeros_like(values), decay=d, eps=0.),
values,
atol=1e-4
)
# return at least `eps`
np.testing.assert_allclose(
transform_fn(jnp.zeros_like(values), jnp.zeros_like(values),
decay=d, eps=1e-2),
jnp.ones_like(values) * 1e-2,
atol=1e-4
)
@chex.all_variants
def test_apply_every(self):
# The frequency of the application of sgd
k = 4
zero_update = (jnp.array([0., 0.]), jnp.array([0., 0.]))
# optax sgd
optax_sgd_params = self.init_params
sgd = alias.sgd(LR, 0.0)
state_sgd = sgd.init(optax_sgd_params)
# optax sgd plus apply every
optax_sgd_apply_every_params = self.init_params
sgd_apply_every = combine.chain(
transform.apply_every(k=k),
transform.trace(decay=0, nesterov=False),
transform.scale(-LR))
state_sgd_apply_every = sgd_apply_every.init(optax_sgd_apply_every_params)
transform_fn = self.variant(sgd_apply_every.update)
for i in range(STEPS):
# Apply a step of sgd
updates_sgd, state_sgd = sgd.update(self.per_step_updates, state_sgd)
optax_sgd_params = update.apply_updates(optax_sgd_params, updates_sgd)
# Apply a step of sgd_apply_every
updates_sgd_apply_every, state_sgd_apply_every = transform_fn(
self.per_step_updates, state_sgd_apply_every)
optax_sgd_apply_every_params = update.apply_updates(
optax_sgd_apply_every_params, updates_sgd_apply_every)
# Every k steps, check equivalence.
if i % k == k-1:
chex.assert_trees_all_close(
optax_sgd_apply_every_params, optax_sgd_params,
atol=1e-6, rtol=1e-5)
# Otherwise, check update is zero.
else:
chex.assert_trees_all_close(
updates_sgd_apply_every, zero_update, atol=0.0, rtol=0.0)
def test_scale(self):
updates = self.per_step_updates
for i in range(1, STEPS + 1):
factor = 0.1 ** i
rescaler = transform.scale(factor)
# Apply rescaling.
scaled_updates, _ = rescaler.update(updates, {})
# Manually scale updates.
def rescale(t):
return t * factor # pylint:disable=cell-var-from-loop
manual_updates = jax.tree_util.tree_map(rescale, updates)
# Check the rescaled updates match.
chex.assert_trees_all_close(scaled_updates, manual_updates)
@parameterized.named_parameters([
('1d', [1.0, 2.0], [1.0, 2.0]),
('2d', [[1.0, 2.0], [3.0, 4.0]], [[-0.5, 0.5], [-0.5, 0.5]]),
('3d', [[[1., 2.], [3., 4.]],
[[5., 6.], [7., 8.]]], [[[-1.5, -0.5], [0.5, 1.5]],
[[-1.5, -0.5], [0.5, 1.5]]]),
])
def test_centralize(self, inputs, outputs):
inputs = jnp.asarray(inputs)
outputs = jnp.asarray(outputs)
centralizer = transform.centralize()
centralized_inputs, _ = centralizer.update(inputs, {})
chex.assert_trees_all_close(centralized_inputs, outputs)
@chex.all_variants
def test_add_noise_has_correct_variance_scaling(self):
# Prepare to compare noise with a rescaled unit-variance substitute.
eta = 0.3
gamma = 0.55
seed = 314
noise = transform.add_noise(eta, gamma, seed)
noise_unit = transform.add_noise(1.0, 0.0, seed)
params = self.init_params
state = noise.init(params)
state_unit = noise_unit.init(params)
# Check the noise itself by adding it to zeros.
updates = jax.tree_util.tree_map(jnp.zeros_like, params)
for i in range(1, STEPS + 1):
updates_i, state = self.variant(noise.update)(updates, state)
updates_i_unit, state_unit = noise_unit.update(updates, state_unit)
scale = jnp.sqrt(eta / i**gamma)
updates_i_rescaled = jax.tree_util.tree_map(
lambda g, s=scale: g * s, updates_i_unit)
chex.assert_trees_all_close(updates_i, updates_i_rescaled, rtol=1e-4)
def test_scale_by_optimistic_gradient(self):
def f(params: jnp.ndarray) -> jnp.ndarray:
return params['x'] ** 2
initial_params = {
'x': jnp.array(2.0)
}
og = transform.scale_by_optimistic_gradient()
og_state = og.init(initial_params)
# Provide some arbitrary previous gradient.
getattr(og_state, 'trace')['x'] = 1.5
g = jax.grad(f)(initial_params)
og_true = 2 * g['x'] - getattr(og_state, 'trace')['x']
og, og_state = og.update(g, og_state)
# Compare transformation output with manually computed optimistic gradient.
chex.assert_trees_all_close(og_true, og['x'])
@chex.all_variants
def test_bias_correction_bf16(self):
bias_correction_fn = self.variant(transform.bias_correction)
m = jnp.logspace(-10, 10, num=21, dtype=jnp.bfloat16) # 1e-10 ... 1e10
for decay in (0.9, 0.99, 0.999, 0.9995):
for count in (1, 10, 100, 1000):
chex.assert_tree_all_finite(
bias_correction_fn(m, decay, count),
custom_message=f'failed with decay={decay}, count={count}')
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/transform_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
r"""Implementation of control variates.
We are interested in computing the gradient using control variates:
\nabla_{\theta} E_{p(x; \theta)} f(x)
= \nabla_{\theta} [E_{p(x; \theta)} f(x) - h(x; \theta) + E_{p(x; \theta)}]
= \nabla_{\theta} [E_{p(x; \theta)} f(x) - h(x; \theta)]
+ \nabla_{\theta} E_{p(x; \theta)}]
= \nabla_{\theta} [E_{p(x; \theta)} f(x) - h(x; \theta)]
+ \nabla_{\theta} E_{p(x; \theta)}]
= \nabla_{\theta} \int {p(x; \theta)} (f(x) - h(x; \theta)) dx
+ \nabla_{\theta} E_{p(x; \theta)}]
= \int \nabla_{\theta} {p(x; \theta)} (f(x) - h(x; \theta)) dx
+ [E_{p(x; \theta)} \nabla_{\theta} (f(x) - h(x; \theta))
+ \nabla_{\theta} E_{p(x; \theta)}]
= \int \nabla_{\theta} {p(x; \theta)} (f(x) - h(x; \theta)) dx
- [E_{p(x; \theta)} \nabla_{\theta} h(x; \theta)
+ \nabla_{\theta} E_{p(x; \theta)}]
The above computation is performed in `control_variates_jacobians`.
When adding a new control variate, one does not need to implement the jacobian
computation, but instead has to implement the forward computation.
Each control variate implemented has to satisfy the following API:
* control_variate(function)
This returns a tuple of three functions:
* The first element of the tuple is a function which returns the
control variate value for a set of samples. It takes in as
arguments the parameters used to construct the distribution,
the distributional samples, and the state of the control variate
(if any). The return value of this function will have shape
`num_samples`, where `num_samples` is the number of samples
provided as input.
* The second is a function returns the expected value of the control
variate. The input arguments of this function are the parameters
of the distribution and the state of the control variate.
* The third is a function which updates the state of the control
variate, and returns the updated states.
For examples, see `control_delta_method` and `moving_avg_baseline`.
"""
from typing import Any, Callable, Sequence, Tuple
import chex
import jax
import jax.numpy as jnp
from optax._src import base
CvState = Any
ComputeCv = Callable[[base.Params, chex.Array, CvState], chex.Array]
CvExpectedValue = Callable[[base.Params, CvState], CvState]
UpdateCvState = Callable[[base.Params, chex.Array, CvState], CvState]
ControlVariate = Tuple[ComputeCv, CvExpectedValue, UpdateCvState]
def control_delta_method(
function: Callable[[chex.Array], float]) -> ControlVariate:
"""The control delta covariate method.
Control variate obtained by performing a second order Taylor expansion
on the cost function f at the mean of the input distribution.
Only implemented for Gaussian random variables.
For details, see: https://icml.cc/2012/papers/687.pdf
Args:
function: The function for which to compute the control variate.
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
Returns:
A tuple of three functions, to compute the control variate, the
expected value of the control variate, and to update the control variate
state.
"""
def delta(
params: base.Params,
sample: chex.Array,
state: CvState = None) -> chex.Array:
""""Second order expansion of `function` at the mean of the input dist."""
del state
mean_dist = params[0]
centered_sample = sample - mean_dist
# Function is a function of samples. Here, we use the mean as the input
# since we do a Taylor expansion of function around the mean.
grads = jax.grad(function)(mean_dist)
hessians = jax.hessian(function)(mean_dist)
assert hessians.ndim == 2
control_variate = function(mean_dist)
control_variate += jnp.dot(centered_sample, grads)
control_variate += jnp.dot(
jnp.dot(centered_sample, hessians), centered_sample) / 2.
return control_variate
def expected_value_delta(
params: base.Params, state: CvState) -> jax.Array:
""""Expected value of second order expansion of `function` at dist mean."""
del state
mean_dist = params[0]
var_dist = jnp.square(jnp.exp(params[1]))
hessians = jax.hessian(function)(mean_dist)
assert hessians.ndim == 2
hess_diags = jnp.diag(hessians)
assert hess_diags.ndim == 1
# Trace (Hessian * Sigma) and we use that Sigma is diagonal.
expected_second_order_term = jnp.sum(var_dist * hess_diags) / 2.
expected_control_variate = function(mean_dist)
expected_control_variate += expected_second_order_term
return expected_control_variate
def update_state(
params: base.Params,
samples: chex.Array,
state: CvState = None) -> CvState:
""""No state kept, so no operation is done."""
del params, samples
return state
return delta, expected_value_delta, update_state
def moving_avg_baseline(
function: Callable[[chex.Array], float],
decay: float = 0.99,
zero_debias: bool = True,
use_decay_early_training_heuristic=True) -> ControlVariate:
"""A moving average baseline.
It has no effect on the pathwise or measure valued estimator.
Args:
function: The function for which to compute the control variate.
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
decay: The decay rate for the moving average.
zero_debias: Whether or not to use zero debiasing for the moving average.
use_decay_early_training_heuristic: Whether or not to use a heuristic which
overrides the decay value early in training based on
min(decay, (1.0 + i) / (10.0 + i)). This stabilises training and was
adapted from the Tensorflow codebase.
Returns:
A tuple of three functions, to compute the control variate, the
expected value of the control variate, and to update the control variate
state.
"""
def moving_avg(
params: base.Params,
samples: chex.Array,
state: CvState = None) -> CvState:
""""Return the moving average."""
del params, samples
return state[0]
def expected_value_moving_avg(
params: base.Params, state: CvState) -> chex.Array:
""""Return the moving average."""
del params
return state[0]
def update_state(
params: base.Params,
samples: chex.Array,
state: CvState = None) -> CvState:
""""Update the moving average."""
del params
value, i = state
if use_decay_early_training_heuristic:
iteration_decay = jnp.minimum(decay, (1.0 + i) / (10.0 + i))
else:
iteration_decay = decay
updated_value = iteration_decay * value
updated_value += (1 - iteration_decay) * jnp.mean(
jax.vmap(function)(samples))
if zero_debias:
updated_value /= (jnp.ones([]) - jnp.power(iteration_decay, i + 1))
return (jax.lax.stop_gradient(updated_value), i + 1)
return moving_avg, expected_value_moving_avg, update_state
def _map(cv, params, samples, state):
return jax.vmap(lambda x: cv(params, x, state))(samples)
def control_variates_jacobians(
function: Callable[[chex.Array], float],
control_variate_from_function: Callable[
[Callable[[chex.Array], float]], ControlVariate
],
grad_estimator: Callable[..., jnp.ndarray],
params: base.Params,
dist_builder: Callable[..., Any],
rng: chex.PRNGKey,
num_samples: int,
control_variate_state: CvState = None,
estimate_cv_coeffs: bool = False,
estimate_cv_coeffs_num_samples: int = 20,
) -> Tuple[Sequence[chex.Array], CvState]:
r"""Obtain jacobians using control variates.
We will compute each term individually. The first term will use stochastic
gradient estimation. The second term will be computes using Monte
Carlo estimation and automatic differentiation to compute
\nabla_{\theta} h(x; \theta). The the third term will be computed using
automatic differentiation, as we restrict ourselves to control variates
which compute this expectation in closed form.
This function updates the state of the control variate (once), before
computing the control variate coefficients.
Args:
function: Function f(x) for which to estimate grads_{params} E_dist f(x).
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
control_variate_from_function: The control variate to use to reduce
variance. See `control_delta_method` and `moving_avg_baseline` examples.
grad_estimator: The gradient estimator to be used to compute the gradients.
Note that not all control variates will reduce variance for all
estimators. For example, the `moving_avg_baseline` will make no difference
to the measure valued or pathwise estimators.
params: A tuple of jnp arrays.
The parameters for which to construct the distribution and for which we
want to compute the jacobians.
dist_builder: a constructor which builds a distribution given the input
parameters specified by params. `dist_builder(params)` should return a
valid distribution.
rng: a PRNGKey key.
num_samples: Int, the number of samples used to compute the grads.
control_variate_state: The control variate state. This is used for control
variates which keep states (such as the moving average baselines).
estimate_cv_coeffs: Boolean. Whether or not to estimate the optimal control
variate coefficient via `estimate_control_variate_coefficients`.
estimate_cv_coeffs_num_samples: The number of samples to use to estimate
the optimal coefficient. These need to be new samples to ensure that the
objective is unbiased.
Returns:
A tuple of size two:
* A tuple of size `params`, each element is `num_samples x param.shape`
jacobian vector containing the estimates of the gradients obtained
for each sample.
The mean of this vector is the gradient wrt to parameters that can be
used for learning. The entire jacobian vector can be used to assess
estimator variance.
* The updated CV state.
"""
control_variate = control_variate_from_function(function)
stochastic_cv, expected_value_cv, update_state_cv = control_variate
data_dim = jax.tree_util.tree_leaves(params)[0].shape[0]
if estimate_cv_coeffs:
cv_coeffs = estimate_control_variate_coefficients(
function, control_variate_from_function, grad_estimator, params,
dist_builder, rng, estimate_cv_coeffs_num_samples,
control_variate_state)
else:
cv_coeffs = [1.0] * len(params)
# \int \nabla_{\theta} {p(x; \theta)} (f(x) - h(x; \theta)) dx
function_jacobians = grad_estimator(
function, params, dist_builder, rng, num_samples)
# Chain rule since CVs can also depend on parameters - for example, for the
# pathwise gradient estimator they have in order to have an effect on
# gradient.
# The rng has to be the same as passed to the grad_estimator above so that we
# obtain the same samples.
samples = dist_builder(*params).sample((num_samples,), seed=rng)
# If the CV has state, update it.
control_variate_state = update_state_cv(
params, samples, control_variate_state)
def samples_fn(x):
return stochastic_cv(
jax.lax.stop_gradient(params), x, control_variate_state)
cv_jacobians = grad_estimator(
samples_fn, params, dist_builder, rng, num_samples)
# The gradients of the stochastic covariate with respect to the parameters.
def param_fn(x):
return jnp.mean(_map(
stochastic_cv, x,
jax.lax.stop_gradient(samples), control_variate_state))
# [E_{p(x; \theta)} \nabla_{\theta} h(x; \theta)
cv_param_grads = jax.grad(param_fn)(params)
# The gradients of the closed form expectation of the control variate
# with respect to the parameters: # \nabla_{\theta} E_{p(x; \theta)}].
expected_value_grads = jax.grad(
lambda x: expected_value_cv(x, control_variate_state))(params)
jacobians = []
for param_index, param in enumerate(jax.tree_util.tree_leaves(params)):
chex.assert_shape(function_jacobians[param_index], (num_samples, data_dim))
chex.assert_shape(cv_jacobians[param_index], (num_samples, data_dim))
chex.assert_shape(cv_param_grads[param_index], (data_dim,))
chex.assert_shape(expected_value_grads[param_index], (data_dim,))
cv_coeff = cv_coeffs[param_index]
# \int \nabla_{\theta} {p(x; \theta)} (f(x) - h(x; \theta)) dx
param_jacobians = function_jacobians[param_index]
param_jacobians -= cv_coeff * cv_jacobians[param_index]
# - [E_{p(x; \theta)} \nabla_{\theta} h(x; \theta)
param_jacobians -= cv_coeff * cv_param_grads[param_index]
# \nabla_{\theta} E_{p(x; \theta)}]
param_jacobians += cv_coeff * expected_value_grads[param_index]
chex.assert_shape(param_jacobians, (num_samples,) + param.shape)
jacobians.append(param_jacobians)
return jacobians, control_variate_state
def estimate_control_variate_coefficients(
function: Callable[[chex.Array], float],
control_variate_from_function: Callable[
[Callable[[chex.Array], float]], ControlVariate
],
grad_estimator: Callable[..., jnp.ndarray],
params: base.Params,
dist_builder: Callable[..., Any],
rng: chex.PRNGKey,
num_samples: int,
control_variate_state: CvState = None,
eps: float = 1e-3,
) -> Sequence[float]:
r"""Estimates the control variate coefficients for the given parameters.
For each variable `var_k`, the coefficient is given by:
\sum_k cov(df/d var_k, d cv/d var_k) / (\sum var(d cv/d var_k) + eps)
Where var_k is the k'th element of the parameters in `params`.
The covariance and variance calculations are done from samples obtained
from the distribution obtained by calling `dist_builder` on the input
`params`.
This function does not update the state of the control variate.
Args:
function: Function f(x) for which to estimate grads_{params} E_dist f(x).
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
control_variate_from_function: The control variate to use to reduce
variance. See `control_delta_method` and `moving_avg_baseline` examples.
grad_estimator: The gradient estimator to be used to compute the gradients.
Note that not all control variates will reduce variance for all
estimators. For example, the `moving_avg_baseline` will make no difference
to the measure valued or pathwise estimators.
params: A tuple of jnp arrays.
The parameters for which to construct the distribution and for which we
want to compute the jacobians.
dist_builder: a constructor which builds a distribution given the input
parameters specified by params. `dist_builder(params)` should return a
valid distribution.
rng: a PRNGKey key.
num_samples: Int, the number of samples used to compute the grads.
control_variate_state: The control variate state. This is used for control
variates which keep states (such as the moving average baselines).
eps: A small constant used to avoid numerical issues. Float.
Returns:
A list of control variate coefficients (each a scalar), for each parameter
in `params`.
"""
# Resample to avoid biased gradients.
cv_rng, _ = jax.random.split(rng)
del rng # Avoid using rng in this function.
stochastic_cv, _, _ = control_variate_from_function(function)
# Samples have to be the same so we use the same rng.
cv_jacobians = grad_estimator(
lambda x: stochastic_cv(params, x, control_variate_state),
params, dist_builder, cv_rng, num_samples)
function_jacobians = grad_estimator(
function, params, dist_builder, cv_rng, num_samples)
def compute_coeff(param_cv_jacs, param_f_jacs):
assert param_f_jacs.ndim == 2
assert param_cv_jacs.ndim == 2
mean_f = jnp.mean(param_f_jacs, axis=0)
mean_cv = jnp.mean(param_cv_jacs, axis=0)
cov = jnp.mean((param_f_jacs - mean_f) * (param_cv_jacs - mean_cv), axis=0)
assert cov.ndim == 1
# Compute the coefficients which minimize variance.
# Since we want to minimize the variances across parameter dimensions,
# the optimal coefficients are given by the sum of covariances per
# dimensions over the sum of variances per dimension.
cv_coeff = jnp.sum(cov) / (jnp.sum(jnp.var(param_cv_jacs, axis=0)) + eps)
return jax.lax.stop_gradient(cv_coeff)
return [compute_coeff(cv_jacobians[i], function_jacobians[i])
for i in range(len(params))]
| optax-master | optax/_src/control_variates.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `alias.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
from optax._src import alias
from optax._src import numerics
from optax._src import schedule
from optax._src import state_utils
from optax._src import update
_OPTIMIZERS_UNDER_TEST = (
dict(opt_name='sgd', opt_kwargs=dict(learning_rate=1e-3, momentum=0.9)),
dict(opt_name='adafactor', opt_kwargs=dict(learning_rate=5e-3)),
dict(opt_name='adagrad', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='adam', opt_kwargs=dict(learning_rate=1e-1)),
dict(opt_name='adamw', opt_kwargs=dict(learning_rate=1e-1)),
dict(opt_name='adamax', opt_kwargs=dict(learning_rate=1e-1)),
dict(opt_name='adamaxw', opt_kwargs=dict(learning_rate=1e-1)),
dict(opt_name='amsgrad', opt_kwargs=dict(learning_rate=1e-1)),
dict(opt_name='lars', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='lamb', opt_kwargs=dict(learning_rate=1e-3)),
dict(
opt_name='lion', opt_kwargs=dict(learning_rate=1e-2, weight_decay=1e-4),
),
dict(opt_name='noisy_sgd', opt_kwargs=dict(learning_rate=1e-3, eta=1e-4)),
dict(opt_name='novograd', opt_kwargs=dict(learning_rate=1e-3)),
dict(
opt_name='optimistic_gradient_descent',
opt_kwargs=dict(learning_rate=2e-3, alpha=0.7, beta=0.1),
),
dict(opt_name='rmsprop', opt_kwargs=dict(learning_rate=5e-3)),
dict(opt_name='rmsprop', opt_kwargs=dict(learning_rate=5e-3, momentum=0.9)),
dict(opt_name='fromage', opt_kwargs=dict(learning_rate=5e-3)),
dict(opt_name='adabelief', opt_kwargs=dict(learning_rate=1e-2)),
dict(opt_name='radam', opt_kwargs=dict(learning_rate=5e-3)),
dict(opt_name='sm3', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='yogi', opt_kwargs=dict(learning_rate=1e-1)),
dict(
opt_name='dpsgd',
opt_kwargs=dict(
learning_rate=1e-3,
l2_norm_clip=10.0,
noise_multiplier=1e-3,
seed=0,
momentum=0.2,
),
),
)
def _setup_parabola(dtype):
"""Quadratic function as an optimization target."""
initial_params = jnp.array([-1.0, 10.0, 1.0], dtype=dtype)
final_params = jnp.array([1.0, -1.0, 1.0], dtype=dtype)
if jnp.iscomplexobj(dtype):
final_params *= 1 + 1j
@jax.grad
def get_updates(params):
return jnp.sum(numerics.abs_sq(params - final_params))
return initial_params, final_params, get_updates
def _setup_rosenbrock(dtype):
"""Rosenbrock function as an optimization target."""
a = 1.0
b = 100.0
if jnp.iscomplexobj(dtype):
a *= 1 + 1j
initial_params = jnp.array([0.0, 0.0], dtype=dtype)
final_params = jnp.array([a, a**2], dtype=dtype)
@jax.grad
def get_updates(params):
return (numerics.abs_sq(a - params[0]) +
b * numerics.abs_sq(params[1] - params[0]**2))
return initial_params, final_params, get_updates
class AliasTest(chex.TestCase):
@parameterized.product(
_OPTIMIZERS_UNDER_TEST,
target=(_setup_parabola, _setup_rosenbrock),
dtype=(jnp.float32, jnp.complex64),
)
def test_optimization(self, opt_name, opt_kwargs, target, dtype):
if opt_name in (
'fromage',
'noisy_sgd',
'sm3',
'optimistic_gradient_descent',
'lion',
) and jnp.iscomplexobj(dtype):
raise absltest.SkipTest(
f'{opt_name} does not support complex parameters.'
)
opt = getattr(alias, opt_name)(**opt_kwargs)
initial_params, final_params, get_updates = target(dtype)
@jax.jit
def step(params, state):
updates = get_updates(params)
if opt_name == 'dpsgd':
updates = updates[None]
# Complex gradients need to be conjugated before being added to parameters
# https://gist.github.com/wdphy16/118aef6fb5f82c49790d7678cf87da29
updates = jax.tree_util.tree_map(lambda x: x.conj(), updates)
updates, state = opt.update(updates, state, params)
params = update.apply_updates(params, updates)
return params, state
params = initial_params
state = opt.init(params)
# A no-op change, to verify that tree map works.
state = state_utils.tree_map_params(opt, lambda v: v, state)
for _ in range(10000):
params, state = step(params, state)
chex.assert_trees_all_close(params, final_params, rtol=3e-2, atol=3e-2)
@chex.all_variants
@parameterized.product(_OPTIMIZERS_UNDER_TEST)
def test_optimizers_can_be_wrapped_in_inject_hyperparams(
self, opt_name, opt_kwargs):
"""Checks that optimizers can be wrapped in inject_hyperparams."""
# See also https://github.com/deepmind/optax/issues/412.
opt_factory = getattr(alias, opt_name)
opt = opt_factory(**opt_kwargs)
if opt_name == 'adafactor':
# Adafactor wrapped in inject_hyperparams currently needs a static
# argument to be specified in order to be jittable. See issue
# https://github.com/deepmind/optax/issues/412.
opt_inject = schedule.inject_hyperparams(
opt_factory, static_args=('min_dim_size_to_factor',))(**opt_kwargs)
else:
opt_inject = schedule.inject_hyperparams(opt_factory)(**opt_kwargs)
params = [-jnp.ones((2, 3)), jnp.ones((2, 5, 2))]
grads = [jnp.ones((2, 3)), -jnp.ones((2, 5, 2))]
state = self.variant(opt.init)(params)
updates, new_state = self.variant(opt.update)(grads, state, params)
state_inject = self.variant(opt_inject.init)(params)
updates_inject, new_state_inject = self.variant(opt_inject.update)(
grads, state_inject, params)
with self.subTest('Equality of updates.'):
chex.assert_trees_all_close(updates_inject, updates, rtol=1e-4)
with self.subTest('Equality of new optimizer states.'):
chex.assert_trees_all_close(
new_state_inject.inner_state, new_state, rtol=1e-4)
@parameterized.named_parameters([
('float32', 'float32'),
('bfloat16', 'bfloat16'),
('complex64', 'complex64'),
('None', None),
])
def test_explicit_dtype(self, dtype):
expected_dtype = jax.dtypes.canonicalize_dtype(dtype) # None -> float32
tx = alias.sgd(0.1, momentum=0.9, accumulator_dtype=dtype)
trace_state, _ = tx.init(jnp.array([0.0, 0.0]))
self.assertEqual(expected_dtype, getattr(trace_state, 'trace').dtype)
tx = alias.adam(0.1, mu_dtype=dtype)
adam_state, _ = tx.init(jnp.array([0.0, 0.0]))
self.assertEqual(expected_dtype, getattr(adam_state, 'mu').dtype)
tx = alias.adamw(0.1, mu_dtype=dtype)
adam_state, _, _ = tx.init(jnp.array([0.0, 0.0]))
self.assertEqual(expected_dtype, getattr(adam_state, 'mu').dtype)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/alias_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `wrappers.py`."""
import copy
from typing import cast
from absl.testing import absltest
from absl.testing import parameterized
import chex
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import alias
from optax._src import base
from optax._src import combine
from optax._src import constrain
from optax._src import state_utils
from optax._src import transform
from optax._src import update
from optax._src import wrappers
import tree
def _build_sgd():
return alias.sgd(1.)
def _build_stateful_sgd():
# This SGD behaves like _build_sgd but also tests the optimizer state. The
# momentum is set to zero rather than None so that the momentum terms are
# calculated, but do not change the results.
return alias.sgd(1., momentum=0.)
def _build_sgd_extra_args():
def init_fn(params):
del params
return {'foo': 1}
def update_fn(grads, state, params=None, *, foo=None, **extra_args):
del extra_args, foo, params
return grads, state
t = base.GradientTransformationExtraArgs(init_fn, update_fn)
return combine.chain(_build_sgd(), t)
class WrappersTest(parameterized.TestCase):
def test_flatten(self):
def init_params():
return (jnp.array([1., 2.]), jnp.array([3., 4.]))
per_step_updates = (jnp.array([500., 5.]), jnp.array([300., 3.]))
# First calculate new params without flattening
optax_sgd_params = init_params()
sgd = alias.sgd(1e-2, 0.0)
state_sgd = sgd.init(optax_sgd_params)
updates_sgd, state_sgd = sgd.update(per_step_updates, state_sgd)
sgd_params_no_flatten = update.apply_updates(optax_sgd_params, updates_sgd)
# And now calculate new params with flattening
optax_sgd_params = init_params()
sgd = wrappers.flatten(sgd)
state_sgd = sgd.init(optax_sgd_params)
updates_sgd, state_sgd = sgd.update(per_step_updates, state_sgd)
sgd_params_flatten = update.apply_updates(optax_sgd_params, updates_sgd)
# Test that both give the same result
chex.assert_trees_all_close(
sgd_params_no_flatten, sgd_params_flatten, atol=1e-7, rtol=1e-7)
@chex.variants(with_jit=True, without_jit=True, with_pmap=True)
@parameterized.named_parameters(
('sgd', _build_sgd),
('stateful_sgd', _build_stateful_sgd),
('sgd_extra_args', _build_sgd_extra_args),
)
def test_apply_if_finite(self, opt_builder):
one = jnp.ones([])
nan = jnp.array(jnp.nan)
def fn(x):
return x * hk.get_parameter('p', [], init=hk.initializers.Constant(0.))
fn = hk.without_apply_rng(hk.transform(fn))
params = fn.init(jax.random.PRNGKey(1905), one)
opt = wrappers.apply_if_finite(opt_builder(), 2)
state = opt.init(params)
grads_fn = jax.grad(self.variant(fn.apply))
# Do one successful param update
grads = grads_fn(params, one)
updates, state = opt.update(grads, state, params)
params = update.apply_updates(params, updates)
# We know exactly what should be the value of params since we are
# effectively using sgd in all cases.
self.assertEqual(-1., float(jax.tree_util.tree_flatten(params)[0][0]))
self.assertTrue(bool(getattr(state, 'last_finite')))
# Check 2 rejected param updates
for step in range(2):
grads = grads_fn(params, nan)
updates, state = opt.update(grads, state, params)
params = update.apply_updates(params, updates)
self.assertEqual(-1., float(jax.tree_util.tree_flatten(params)[0][0]))
self.assertFalse(bool(getattr(state, 'last_finite')))
self.assertEqual(step + 1, int(getattr(state, 'notfinite_count')))
# Next successful param update
grads = grads_fn(params, one)
updates, state = opt.update(grads, state, params)
params = update.apply_updates(params, updates)
self.assertEqual(-2., float(jax.tree_util.tree_flatten(params)[0][0]))
self.assertTrue(bool(getattr(state, 'last_finite')))
# Again 2 rejected param updates
for step in range(2):
grads = grads_fn(params, nan)
updates, state = opt.update(grads, state, params)
params = update.apply_updates(params, updates)
self.assertEqual(-2., float(jax.tree_util.tree_flatten(params)[0][0]))
self.assertFalse(bool(getattr(state, 'last_finite')))
self.assertEqual(step + 1, int(getattr(state, 'notfinite_count')))
# Next param update with NaN is accepted since we reached maximum
grads = grads_fn(params, nan)
updates, state = opt.update(grads, state, params)
params = update.apply_updates(params, updates)
self.assertTrue(bool(jnp.isnan(jax.tree_util.tree_flatten(params)[0][0])))
self.assertEqual(5, int(getattr(state, 'total_notfinite')))
def test_apply_if_finite_pmap(self):
# Unlike in `test_apply_if_finite`:
# * pmap is applied to the gradient computation and the optimisation;
# * the NaNs are caused inside the function and do not come from the inputs.
half = jnp.ones([1]) / 2.
two = jnp.ones([1]) * 2. # Causes a NaN in arctanh
def fn(x):
return jnp.arctanh(x) * hk.get_parameter(
'p', [], init=hk.initializers.Constant(0.))
fn = hk.without_apply_rng(hk.transform(fn))
opt = wrappers.apply_if_finite(alias.sgd(1.), 2)
def fn_update(params, opt_state, x):
grads = jax.grad(fn.apply)(params, x)
grads = jax.lax.psum(grads, axis_name='i')
updates, new_opt_state = opt.update(grads, opt_state, params)
new_params = update.apply_updates(params, updates)
return new_params, new_opt_state
fn_update = jax.pmap(fn_update, axis_name='i')
params = fn.init(jax.random.PRNGKey(1905), half)
opt_state = opt.init(params)
params = jax.tree_util.tree_map(lambda x: x[None], params)
opt_state = jax.tree_util.tree_map(lambda x: x[None], opt_state)
# Do one successful param update
params, opt_state = fn_update(params, opt_state, half)
self.assertTrue(bool(opt_state.last_finite))
# Check 2 rejected param updates
for step in range(2):
params, opt_state = fn_update(params, opt_state, two)
self.assertFalse(bool(opt_state.last_finite))
self.assertEqual(step + 1, int(opt_state.notfinite_count))
# Next successful param update
params, opt_state = fn_update(params, opt_state, half)
self.assertTrue(bool(opt_state.last_finite))
# Again 2 rejected param updates
for step in range(2):
params, opt_state = fn_update(params, opt_state, two)
self.assertFalse(bool(opt_state.last_finite))
self.assertEqual(step + 1, int(opt_state.notfinite_count))
# Next param update with NaN is accepted since we reached maximum
params, opt_state = fn_update(params, opt_state, two)
self.assertEqual(5, int(opt_state.total_notfinite))
@chex.variants(with_jit=True, without_jit=True, with_pmap=True)
def test_multi_steps(self):
batch_size = 32
x_size = 7
# Parameters should be updated only every `k_steps` optimisation steps.
k_steps = 4
data = jnp.ones([batch_size, x_size])
def get_loss(x):
loss = jnp.sum(hk.Linear(10)(x)**2)
return loss
loss_init, loss_apply = hk.without_apply_rng(hk.transform(get_loss))
params = loss_init(jax.random.PRNGKey(1915), data)
ms_opt = wrappers.MultiSteps(
# Use a non-trivial inner optimiser:
# * it has a state,
# * it requires the params for the update.
combine.chain(transform.scale_by_adam(),
transform.add_decayed_weights(1e-2),
transform.scale(-1e-4)), k_steps)
opt_init, opt_update = ms_opt.gradient_transformation()
# Put the training in one function, to check that the update is indeed
# jittable.
def train_step(data, opt_state, params):
grad = jax.grad(loss_apply)(params, data)
updates, opt_state = opt_update(grad, opt_state, params)
return updates, opt_state
opt_state = opt_init(params)
prev_loss = loss_apply(params, data)
for idx in range(5 * k_steps):
updates, opt_state = self.variant(train_step)(data, opt_state, params)
new_params = update.apply_updates(params, updates)
new_loss = loss_apply(new_params, data)
if idx % k_steps < k_steps - 1:
# The parameters should not have changed and the loss should be
# constant.
jax.tree_util.tree_map(
np.testing.assert_array_equal, new_params, params)
np.testing.assert_equal(new_loss, prev_loss)
self.assertFalse(ms_opt.has_updated(opt_state))
else:
# This is a step where parameters should actually have been updated, and
# the loss should accordingly go down.
np.testing.assert_array_less(new_loss, prev_loss)
prev_loss = new_loss
self.assertTrue(ms_opt.has_updated(opt_state))
params = new_params
def test_multi_steps_every_k_schedule(self):
# Test a non-trivial schedule which varies over time.
ms_opt = wrappers.MultiSteps(
alias.sgd(1e-4), lambda grad_step: jnp.where(grad_step < 2, 1, 3))
opt_init, opt_update = ms_opt.gradient_transformation()
params = dict(a=jnp.zeros([]))
opt_state = opt_init(params)
grad = dict(a=jnp.zeros([]))
self.assertFalse(ms_opt.has_updated(opt_state))
# First two steps have 1 mini-step per update.
for _ in range(2):
_, opt_state = opt_update(grad, opt_state, params)
self.assertTrue(ms_opt.has_updated(opt_state))
# Subsequently, mini-steps should have 3 mini-steps per update.
for _ in range(5):
for _ in range(2):
_, opt_state = opt_update(grad, opt_state, params)
self.assertFalse(ms_opt.has_updated(opt_state))
_, opt_state = opt_update(grad, opt_state, params)
self.assertTrue(ms_opt.has_updated(opt_state))
def test_multi_steps_computes_mean(self):
k_steps = 4
ms_opt = wrappers.MultiSteps(
transform.scale(1.0), k_steps, use_grad_mean=True)
opt_init, opt_update = ms_opt.gradient_transformation()
params = dict(a=jnp.zeros([]))
opt_state = opt_init(params)
grads = [dict(a=jnp.ones([]) * i) for i in [1, 2, 3, 4]]
self.assertFalse(ms_opt.has_updated(opt_state))
# First 3 steps don't update.
for grad in grads[:-1]:
_, opt_state = opt_update(grad, opt_state, params)
self.assertFalse(ms_opt.has_updated(opt_state))
# Actual update.
new_params, opt_state = opt_update(grads[-1], opt_state, params)
self.assertTrue(ms_opt.has_updated(opt_state))
np.testing.assert_array_equal(new_params['a'], 2.5)
def test_skip_not_finite(self):
step = jnp.zeros([], dtype=jnp.int32)
with self.subTest('test_pos_inf'):
should_skip, skip_state = wrappers.skip_not_finite(
[jnp.array(float('inf')), jnp.zeros([])], step, None)
self.assertTrue(bool(should_skip))
self.assertTrue(bool(skip_state['should_skip']))
self.assertEqual(int(skip_state['num_not_finite']), 1)
with self.subTest('test_neg_inf'):
should_skip, skip_state = wrappers.skip_not_finite(
[jnp.array(-float('inf')), jnp.zeros([])], step, None)
self.assertTrue(bool(should_skip))
self.assertTrue(bool(skip_state['should_skip']))
self.assertEqual(int(skip_state['num_not_finite']), 1)
with self.subTest('test_nan'):
should_skip, skip_state = wrappers.skip_not_finite(
[jnp.array(float('nan')), jnp.zeros([])], step, None)
self.assertTrue(bool(should_skip))
self.assertTrue(bool(skip_state['should_skip']))
self.assertEqual(int(skip_state['num_not_finite']), 1)
with self.subTest('test_finite'):
should_skip, skip_state = wrappers.skip_not_finite(
[jnp.array(11.), jnp.zeros([])], step, None)
self.assertFalse(bool(should_skip))
self.assertFalse(bool(skip_state['should_skip']))
self.assertEqual(int(skip_state['num_not_finite']), 0)
def test_skip_large_updates(self):
step = jnp.zeros([], dtype=jnp.int32)
with self.subTest('test_inf'):
should_skip, skip_state = wrappers.skip_large_updates(
[jnp.array(float('inf')), jnp.zeros([])], step, None, 100.)
self.assertTrue(bool(should_skip))
self.assertTrue(bool(skip_state['should_skip']))
self.assertEqual(float(skip_state['norm_squared']), float('inf'))
with self.subTest('test_nan'):
should_skip, skip_state = wrappers.skip_large_updates(
[jnp.array(float('nan')), jnp.zeros([])], step, None, 100.)
self.assertTrue(bool(should_skip))
self.assertTrue(bool(skip_state['should_skip']))
# Recall that NaN != NaN.
norm_squared = float(skip_state['norm_squared'])
self.assertNotEqual(norm_squared, norm_squared)
with self.subTest('test_large'):
should_skip, skip_state = wrappers.skip_large_updates(
[jnp.array(11.), jnp.zeros([])], step, None, 100.)
self.assertTrue(bool(should_skip))
self.assertTrue(bool(skip_state['should_skip']))
self.assertEqual(float(skip_state['norm_squared']), 121.)
with self.subTest('test_small'):
should_skip, skip_state = wrappers.skip_large_updates(
[jnp.zeros([]), jnp.zeros([])], step, None, 100.)
self.assertFalse(bool(should_skip))
self.assertFalse(bool(skip_state['should_skip']))
self.assertEqual(float(skip_state['norm_squared']), 0.)
def test_multi_steps_skip_not_finite(self):
k_steps = 2
ms_opt = wrappers.MultiSteps(
alias.sgd(1.), k_steps, should_skip_update_fn=wrappers.skip_not_finite)
opt_init, opt_update = ms_opt.gradient_transformation()
opt_init = jax.jit(opt_init)
opt_update = jax.jit(opt_update)
params = dict(a=jnp.zeros([]))
opt_state = opt_init(params)
with self.subTest('test_good_updates'):
updates, opt_state = opt_update(dict(a=jnp.ones([])), opt_state, params)
self.assertEqual(int(opt_state.mini_step), 1)
params = update.apply_updates(params, updates)
updates, opt_state = opt_update(dict(a=jnp.ones([])), opt_state, params)
self.assertEqual(int(opt_state.mini_step), 0)
params = update.apply_updates(params, updates)
np.testing.assert_array_equal(params['a'], -jnp.ones([]))
with self.subTest('test_inf_updates'):
updates, opt_state = opt_update(
dict(a=jnp.array(float('inf'))), opt_state, params)
self.assertEqual(int(opt_state.mini_step), 0) # No increase in mini_step
params = update.apply_updates(params, updates)
np.testing.assert_array_equal(params['a'], -jnp.ones([]))
with self.subTest('test_nan_updates'):
updates, opt_state = opt_update(
dict(a=jnp.full([], float('nan'))), opt_state, params)
self.assertEqual(int(opt_state.mini_step), 0) # No increase in mini_step
params = update.apply_updates(params, updates)
np.testing.assert_array_equal(params['a'], -jnp.ones([]))
with self.subTest('test_final_good_updates'):
updates, opt_state = opt_update(dict(a=jnp.ones([])), opt_state, params)
self.assertEqual(int(opt_state.mini_step), 1)
params = update.apply_updates(params, updates)
updates, opt_state = opt_update(dict(a=jnp.ones([])), opt_state, params)
self.assertEqual(int(opt_state.mini_step), 0)
params = update.apply_updates(params, updates)
np.testing.assert_array_equal(params['a'], -jnp.full([], 2.))
class MaskedTest(chex.TestCase):
"""Tests for the masked wrapper."""
def test_tree_map_params(self):
params = {
'a': {
'b': (jnp.zeros((1, 2)), jnp.zeros((2, 2))),
},
'c': {
'd': jnp.zeros((1, 2)),
'e': (jnp.zeros((1, 2)), jnp.zeros((1, 2))),
},
}
sharding_axes = {
'a': {
'b': (1, 2),
},
'c': {
'd': 1,
'e': (1, 2),
},
}
mask = {
'a': {
'b': (True, False),
},
'c': {
'd': True,
'e': (False, True),
},
}
expected = {
'a': {
'b': (jnp.ones((1, 2)), jnp.zeros((2, 2))),
},
'c': {
'd': jnp.ones((1, 2)),
'e': (jnp.ones((1, 2)), jnp.ones((1, 2))),
},
}
def init_fn(params):
return {'count': 1, 'params': params, 'params_copy': params}
def update_fn(updates, state, params=None):
del params
return updates, state
inner = base.GradientTransformation(init_fn, update_fn)
masked = wrappers.masked(inner, mask)
def increment_dim_1(v):
return v + 1 if v.shape[0] == 1 else v
# For this optimizer, tree_map_params should have the same effect on a
# masked optimizer state as it does on an unmasked optimizer state.
with self.subTest('inner'):
state = inner.init(params)
result = state_utils.tree_map_params(inner, increment_dim_1, state)
chex.assert_trees_all_equal(result, inner.init(expected))
with self.subTest('masked'):
state = masked.init(params)
result = state_utils.tree_map_params(masked, increment_dim_1, state)
chex.assert_trees_all_equal(result, masked.init(expected))
with self.subTest('masked_with_extra_args'):
# Users wishing to pass additional arguments with the same tree structure
# as the original params pytree will need to add the additional `is_leaf`
# callable. This makes it possible to ignore the masked parts of the
# pytree.
# Replace all non-masked parameters in the opt-state tree with the
# sharding axis values given in the tree above. Everything else is set to
# None.
new_state = state_utils.tree_map_params(
masked,
lambda p, axis: None if isinstance(p, wrappers.MaskedNode) else axis,
state,
sharding_axes,
is_leaf=lambda v: isinstance(v, wrappers.MaskedNode),
transform_non_params=lambda v: None,
)
sharded_params = {
'a': {
'b': (1, None),
},
'c': {
'd': 1,
'e': (None, 2),
},
}
# Required to make pytype happy
new_state = cast(wrappers.MaskedState, new_state)
chex.assert_equal(None, new_state.inner_state['count'])
chex.assert_equal(sharded_params, new_state.inner_state['params'])
chex.assert_equal(sharded_params, new_state.inner_state['params_copy'])
@chex.all_variants
@parameterized.named_parameters(
('sgd', _build_sgd, False),
('stateful_sgd', _build_stateful_sgd, False),
('sgd_w_mask_fn', _build_sgd, True),
('stateful_sgd_w_mask_fn', _build_stateful_sgd, True),
)
def test_masked(self, opt_builder, use_fn):
mask = {'a': True,
'b': [False, True],
'c': {'d': True, 'e': (False, True)}}
mask_arg = lambda _: mask if use_fn else mask
params = {'a': 1., 'b': [2., 3.], 'c': {'d': 4., 'e': (5., 6.)}}
params = jax.tree_util.tree_map(jnp.asarray, params)
input_updates = jax.tree_util.tree_map(lambda x: x/10., params)
# Negate the updates wherever the mask is True
def masked_negate(updates):
return jax.tree_util.tree_map(
lambda upd, m: -upd if m else upd, updates, mask)
correct_updates = masked_negate(input_updates)
init_fn, update_fn = wrappers.masked(opt_builder(), mask_arg)
update_fn = self.variant(update_fn)
state = self.variant(init_fn)(params)
with self.subTest('tree_map_params'):
result = state_utils.tree_map_params(init_fn, lambda v: v, state)
chex.assert_trees_all_equal_structs(result, state)
updates, state = update_fn(input_updates, state, params)
chex.assert_trees_all_close(updates, correct_updates)
# Check repeated application, this time with no params.
correct_updates = masked_negate(correct_updates)
updates, state = update_fn(updates, state)
chex.assert_trees_all_close(updates, correct_updates)
@chex.all_variants
@parameterized.named_parameters(
('sgd', _build_sgd),
('stateful_sgd', _build_stateful_sgd),
)
def test_prefix_mask(self, opt_builder):
"""Test when the mask is a prefix of the updates PyTree."""
mask = {'a': True, 'b': False, 'c': {'d': False, 'e': True}}
params = {'a': 1., 'b': {'f': 2.}, 'c': {'d': 3., 'e': ([4., 5.], 6.)}}
params = jax.tree_util.tree_map(jnp.asarray, params)
input_updates = jax.tree_util.tree_map(lambda x: x/10., params)
# Negate the updates wherever the mask (or mask parent) is True
def _masked_sgd_on_updates(m, upd):
return jax.tree_util.tree_map(lambda x: -x, upd) if m else upd
correct_updates = jax.tree_util.tree_map(
_masked_sgd_on_updates, mask, input_updates)
init_fn, update_fn = wrappers.masked(opt_builder(), mask)
update_fn = self.variant(update_fn)
state = self.variant(init_fn)(params)
updates, state = update_fn(input_updates, state, params)
chex.assert_trees_all_close(updates, correct_updates)
# Check repeated application, this time with no params.
correct_updates = jax.tree_util.tree_map(
_masked_sgd_on_updates, mask, correct_updates)
updates, _ = update_fn(updates, state)
chex.assert_trees_all_close(updates, correct_updates)
@chex.all_variants
def test_update_requires_params(self):
weight_decay = 0.1
mask = {'a': True,
'b': [False, True],
'c': {'d': True, 'e': (False, True)}}
params = {'a': 1., 'b': [2., 3.], 'c': {'d': 4., 'e': (5., 6.)}}
params = jax.tree_util.tree_map(jnp.asarray, params)
input_updates = jax.tree_util.tree_map(lambda x: x/10., params)
correct_updates = jax.tree_util.tree_map(
lambda m, u, p: u + weight_decay * p if m else u,
mask, input_updates, params)
init_fn, update_fn = wrappers.masked(
transform.add_decayed_weights(weight_decay), mask)
update_fn = self.variant(update_fn)
state = self.variant(init_fn)(params)
updates, state = update_fn(input_updates, state, params)
chex.assert_trees_all_close(updates, correct_updates)
params = update.apply_updates(params, updates)
# Test repeated application
new_correct_updates = jax.tree_util.tree_map(
lambda m, u, p: u + weight_decay * p if m else u,
mask, correct_updates, params)
updates, state = update_fn(correct_updates, state, params)
chex.assert_trees_all_close(updates, new_correct_updates)
@parameterized.parameters(list, tuple, dict)
def test_empty(self, container):
init_fn, update_fn = wrappers.masked(_build_sgd(), container())
update_fn(container(), init_fn(container()))
@parameterized.parameters(
(False, False), (False, True), (True, False), (True, True))
def test_tree_mismatch_fails(self, extra_key_in_mask, use_fn):
mask = {'a': True,
'b': [False, True],
'c': {'d': True, 'e': (False, True)}}
mask_arg = lambda _: mask if use_fn else mask
params = {'a': 1., 'b': [2., 3.], 'c': {'d': 4., 'e': (5., 6.)}}
params = jax.tree_util.tree_map(jnp.asarray, params)
if extra_key_in_mask:
mask['c']['extra'] = True
else:
params['c']['extra'] = 7
init_fn = wrappers.masked(_build_sgd(), mask_arg)[0]
with self.assertRaises(ValueError):
init_fn(params)
@chex.all_variants
def test_mask_fn(self):
params = {'a': jnp.ones((1, 2)), 'b': (jnp.ones((1,)), np.ones((1, 2, 3)))}
mask_fn = lambda p: jax.tree_util.tree_map(lambda x: x.ndim > 1, p)
init_fn, update_fn = wrappers.masked(transform.add_decayed_weights(0.1),
mask_fn)
update_fn = self.variant(update_fn)
state = self.variant(init_fn)(params)
grads = jax.tree_util.tree_map(lambda x: x*2, params)
updates, state = update_fn(grads, state, params)
np.testing.assert_allclose(updates['a'], grads['a'] + 0.1*params['a'])
np.testing.assert_allclose(updates['b'][0], grads['b'][0])
np.testing.assert_allclose(updates['b'][1],
grads['b'][1] + 0.1*params['b'][1])
@chex.all_variants
@parameterized.named_parameters(
('sgd', _build_sgd),
('stateful_sgd', _build_stateful_sgd),
)
def test_nested_mask(self, opt_builder):
# https://github.com/deepmind/optax/issues/271
params = {'linear_1': {'w': jnp.zeros((1, 1)), 'b': jnp.zeros(1)},
'linear_2': {'w': jnp.zeros((1, 2)), 'b': jnp.zeros(2)},
'linear_3': {'w': jnp.zeros((2, 3)), 'b': jnp.zeros(3)}}
outer_mask = lambda p: jax.tree_util.tree_map(lambda x: x.ndim > 1, p)
inner_mask = jax.tree_util.tree_map(lambda _: True, params)
inner_mask['linear_2'] = False
inner = wrappers.masked(opt_builder(), inner_mask)
init_fn, update_fn = wrappers.masked(inner, outer_mask)
input_updates = jax.tree_util.tree_map(jnp.ones_like, params)
correct_updates = copy.deepcopy(input_updates)
correct_updates['linear_1']['w'] *= -1.0
correct_updates['linear_3']['w'] *= -1.0
state = self.variant(init_fn)(params)
updates, state = self.variant(update_fn)(input_updates, state, params)
chex.assert_trees_all_close(updates, correct_updates)
@chex.all_variants
def test_masked_state_structure(self):
# https://github.com/deepmind/optax/issues/271
params = {'a': [jnp.ones(1), (jnp.ones(2), jnp.ones(3))],
'b': {'c': jnp.ones(4), 'd': jnp.ones(5)}}
mask = {'a': [True, (True, False)], 'b': False}
tx = wrappers.masked(_build_stateful_sgd(), mask)
trace = self.variant(tx.init)(params).inner_state[0].trace
expected_trace = {
'a': [jnp.zeros(1), (jnp.zeros(2), wrappers.MaskedNode())],
'b': wrappers.MaskedNode()
}
chex.assert_trees_all_equal_structs(trace, expected_trace)
def test_masked_state_is_compatible_with_deepmind_tree(self):
"""Checks that the masked state is compatible with deepmind/tree.
DeepMind's tree library and `jax.tree_util` have slightly different
behavior: jax treats `None`s as tree nodes without children while
deepmind/tree treats them as leaves with `None` values. This has led to bugs
when users used deepmind/tree to manipulate masked optimizer states.
This test ensures that masked parts of the optimizer state are also ignored
by deepmind/tree.
"""
params = {
'a': [jnp.ones(1), (jnp.ones(2), jnp.ones(3))],
'b': [jnp.ones(4)]
}
mask = {'a': [True, (True, False)], 'b': False}
opt_init, _ = wrappers.masked(_build_stateful_sgd(), mask)
state = opt_init(params)
chex.assert_trees_all_equal(tree.map_structure(np.array, state), state)
class MaybeUpdateTest(chex.TestCase):
"""Tests for the maybe_update wrapper."""
NUM_STEPS = 3
@chex.all_variants
def test_stateless_inner(self):
params = jnp.zeros([])
grads = jnp.ones([])
def should_update(step):
return step < MaybeUpdateTest.NUM_STEPS
opt = wrappers.maybe_update(transform.scale(2.), should_update)
state = opt.init(params)
update_fn = self.variant(opt.update)
for _ in range(MaybeUpdateTest.NUM_STEPS):
updates, state = update_fn(grads, state)
self.assertEqual(updates, 2.)
# Further updates stop calling the inner optimiser.
for _ in range(5):
updates, state = update_fn(grads, state)
self.assertEqual(updates, 1.)
@chex.all_variants
def test_statefull_inner(self):
params = jnp.zeros([])
grads_with_nan = jnp.array(float('nan'))
grads = jnp.ones([])
def should_update(step):
return step < MaybeUpdateTest.NUM_STEPS
opt = wrappers.maybe_update(constrain.zero_nans(), should_update)
state = opt.init(params)
update_fn = self.variant(opt.update)
for _ in range(MaybeUpdateTest.NUM_STEPS - 1):
updates, state = update_fn(grads_with_nan, state)
self.assertEqual(updates, 0.)
self.assertEqual(state.inner_state.found_nan, True)
updates, state = update_fn(grads, state)
self.assertEqual(updates, 1.)
self.assertEqual(state.inner_state.found_nan, False)
# Further updates stop calling the inner optimiser.
for _ in range(5):
updates, state = update_fn(grads_with_nan, state)
# Warning: do not use assertEqual with a NaN as NaN == NaN returns False.
self.assertTrue(jnp.isnan(updates))
# Inner state is not be updated.
self.assertEqual(state.inner_state.found_nan, False)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/wrappers_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests that types are preserved by the `update` calls when jax_enbable_x64."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
from jax.config import config
import jax.numpy as jnp
from optax._src import alias
from optax._src import base
from optax._src import clipping
from optax._src import transform
from optax._src import update
ALL_MODULES = [
('identity', base.identity, {}),
('clip', clipping.clip, dict(max_delta=1.0)),
('clip_by_global_norm', clipping.clip_by_global_norm, dict(max_norm=1.0)),
('trace', transform.trace, dict(decay=0.5, nesterov=False)),
('trace_with_nesterov', transform.trace, dict(decay=0.5, nesterov=True)),
('scale_by_rss', transform.scale_by_rss, {}),
('scale_by_rms', transform.scale_by_rms, {}),
('scale_by_stddev', transform.scale_by_stddev, {}),
('adam', transform.scale_by_adam, {}),
('scale', transform.scale, dict(step_size=3.0)),
('add_decayed_weights', transform.add_decayed_weights,
dict(weight_decay=0.1)),
('scale_by_schedule', transform.scale_by_schedule,
dict(step_size_fn=lambda x: x * 0.1)),
('scale_by_trust_ratio', transform.scale_by_trust_ratio, {}),
('add_noise', transform.add_noise, dict(eta=1.0, gamma=0.1, seed=42)),
('apply_every_k', transform.apply_every, {}),
('adagrad', alias.adagrad, dict(learning_rate=0.1)),
('adam', alias.adam, dict(learning_rate=0.1)),
('adamw', alias.adamw, dict(learning_rate=0.1)),
('fromage', alias.fromage, dict(learning_rate=0.1)),
('lamb', alias.lamb, dict(learning_rate=0.1)),
('noisy_sgd', alias.noisy_sgd, dict(learning_rate=0.1)),
('rmsprop', alias.rmsprop, dict(learning_rate=0.1)),
('sgd', alias.sgd, dict(learning_rate=0.1)),
('dpsgd', alias.dpsgd,
dict(learning_rate=0.1, l2_norm_clip=0.9, noise_multiplier=1.1, seed=42)),
]
class Float64Test(parameterized.TestCase):
def _assert_dtype_equals(self, tree1, tree2):
tree1_types = jax.tree_util.tree_map(lambda t: t.dtype, tree1)
tree2_types = jax.tree_util.tree_map(lambda t: t.dtype, tree2)
self.assertEqual(tree1_types, tree2_types)
@chex.all_variants
@parameterized.named_parameters(ALL_MODULES)
def test_mixed_dtype_input_outputs(self, transform_constr, transform_kwargs):
initial_params = (
jnp.array([1., 2.], dtype=jnp.float32),
jnp.array([3., 4.], dtype=jnp.float64))
updates = (
jnp.array([10., 21.], dtype=jnp.float32),
jnp.array([33., 42.], dtype=jnp.float64))
scaler = transform_constr(**transform_kwargs)
init_fn = self.variant(scaler.init)
update_fn = self.variant(scaler.update)
initial_state = init_fn(initial_params)
updates, new_state = update_fn(
updates, initial_state, params=initial_params)
new_params = update.apply_updates(initial_params, updates)
self._assert_dtype_equals(initial_state, new_state)
self._assert_dtype_equals(initial_params, new_params)
if __name__ == '__main__':
config.update('jax_enable_x64', True)
absltest.main()
| optax-master | optax/_src/float64_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `clipping.py`."""
from absl.testing import absltest
import chex
import jax
import jax.numpy as jnp
from optax._src import clipping
from optax._src import linear_algebra
STEPS = 50
LR = 1e-2
class ClippingTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.init_params = (jnp.array([1., 2.]), jnp.array([3., 4.]))
self.per_step_updates = (jnp.array([500., 5.]), jnp.array([300., 3.]))
def test_clip(self):
updates = self.per_step_updates
# For a sufficiently high delta the update should not be changed.
clipper = clipping.clip(1e6)
clipped_updates, _ = clipper.update(updates, None)
chex.assert_trees_all_close(clipped_updates, clipped_updates)
# Clipping at delta=1 should make all updates exactly 1.
clipper = clipping.clip(1.)
clipped_updates, _ = clipper.update(updates, None)
chex.assert_trees_all_close(
clipped_updates, jax.tree_util.tree_map(jnp.ones_like, updates))
def test_clip_by_block_rms(self):
rmf_fn = lambda t: jnp.sqrt(jnp.mean(t**2))
updates = self.per_step_updates
for i in range(1, STEPS + 1):
clipper = clipping.clip_by_block_rms(1. / i)
# Check that the clipper actually works and block rms is <= threshold
updates, _ = clipper.update(updates, None)
self.assertAlmostEqual(rmf_fn(updates[0]), 1. / i)
self.assertAlmostEqual(rmf_fn(updates[1]), 1. / i)
# Check that continuously clipping won't cause numerical issues.
updates_step, _ = clipper.update(self.per_step_updates, None)
chex.assert_trees_all_close(updates, updates_step)
def test_clip_by_global_norm(self):
updates = self.per_step_updates
for i in range(1, STEPS + 1):
clipper = clipping.clip_by_global_norm(1. / i)
# Check that the clipper actually works and global norm is <= max_norm
updates, _ = clipper.update(updates, None)
self.assertAlmostEqual(
linear_algebra.global_norm(updates), 1. / i, places=6)
# Check that continuously clipping won't cause numerical issues.
updates_step, _ = clipper.update(self.per_step_updates, None)
chex.assert_trees_all_close(updates, updates_step)
def test_adaptive_grad_clip(self):
updates = self.per_step_updates
params = self.init_params
for i in range(1, STEPS + 1):
clip_r = 1. / i
clipper = clipping.adaptive_grad_clip(clip_r)
# Check that the clipper actually works and upd_norm is < c * param_norm.
updates, _ = clipper.update(updates, None, params)
u_norm, p_norm = jax.tree_util.tree_map(
clipping.unitwise_norm, (updates, params))
cmp = jax.tree_util.tree_map(
lambda u, p, c=clip_r: u - c * p < 1e-6, u_norm, p_norm)
for leaf in jax.tree_util.tree_leaves(cmp):
self.assertTrue(leaf.all())
# Check that continuously clipping won't cause numerical issues.
updates_step, _ = clipper.update(self.per_step_updates, None, params)
chex.assert_trees_all_close(updates, updates_step)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/clipping_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for state_utils."""
import dataclasses
from typing import Optional, TypedDict, cast
from absl.testing import absltest
import chex
import jax
import jax.numpy as jnp
from optax._src import alias
from optax._src import base
from optax._src import combine
from optax._src import schedule
from optax._src import state_utils
from optax._src import transform
@dataclasses.dataclass
class FakeShardSpec:
sharding_axis: Optional[int]
class ScaleByAdamStateDict(TypedDict):
"""An opt state that uses dictionaries instead of classes."""
count: chex.Array
params: TypedDict('Params', {'mu': chex.ArrayTree, 'nu': chex.ArrayTree})
def _scale_by_adam_with_dicts():
"""An implementation of adam using dictionary-based opt states."""
t = transform.scale_by_adam()
def init(params):
state = t.init(params)
state = cast(transform.ScaleByAdamState, state)
return ScaleByAdamStateDict(
count=state.count,
params={'mu': state.mu, 'nu': state.nu},
)
def update(updates, state, params=None):
state = transform.ScaleByAdamState(
count=state['count'],
mu=state['params']['mu'],
nu=state['params']['nu'],
)
updates, state = t.update(updates, state, params)
state = cast(transform.ScaleByAdamState, state)
return ScaleByAdamStateDict(
count=state.count,
params={'mu': state.mu, 'nu': state.nu},
)
return base.GradientTransformation(init, update)
class StateUtilsTest(absltest.TestCase):
def test_dict_based_optimizers(self):
"""Test we can map over params also for optimizer states using dicts."""
opt = combine.chain(
_scale_by_adam_with_dicts(),
transform.add_decayed_weights(1e-3),
)
params = _fake_params()
params_sharding_spec = _fake_param_sharding()
opt_state = opt.init(params)
opt_state_sharding_spec = state_utils.tree_map_params(
opt,
lambda _, spec: spec,
opt_state,
params_sharding_spec,
transform_non_params=lambda _: FakeShardSpec(None),
)
expected = (
{
'count': FakeShardSpec(sharding_axis=None),
'params': {
'mu': {
'my/fake/module': {
'b': FakeShardSpec(sharding_axis=1),
'w': FakeShardSpec(sharding_axis=0),
},
'my/other/fake/module': {
'b': FakeShardSpec(sharding_axis=3),
'w': FakeShardSpec(sharding_axis=2),
},
},
'nu': {
'my/fake/module': {
'b': FakeShardSpec(sharding_axis=1),
'w': FakeShardSpec(sharding_axis=0),
},
'my/other/fake/module': {
'b': FakeShardSpec(sharding_axis=3),
'w': FakeShardSpec(sharding_axis=2),
},
},
},
},
base.EmptyState(),
)
self.assertEqual(expected, opt_state_sharding_spec)
def test_state_chex_dataclass(self):
@chex.dataclass
class Foo:
count: int
v: chex.ArrayTree
def init(params):
return Foo(count=0, v=params)
params = {
'w': 0,
}
state = init(params)
state = state_utils.tree_map_params(init, lambda v: v+1, state)
state = cast(Foo, state)
self.assertEqual(int(state.count), 0)
self.assertEqual(state.v, {'w': jnp.array(1)})
def test_adam(self):
params = _fake_params()
params_sharding_spec = _fake_param_sharding()
opt = alias.adam(1e-4)
opt_state = opt.init(params)
opt_state_sharding_spec = state_utils.tree_map_params(
opt,
lambda _, spec: spec,
opt_state,
params_sharding_spec,
transform_non_params=lambda _: FakeShardSpec(None),
)
expected = (
transform.ScaleByAdamState( # pytype:disable=wrong-arg-types
count=FakeShardSpec(sharding_axis=None),
mu={
'my/fake/module': {
'w': FakeShardSpec(sharding_axis=0),
'b': FakeShardSpec(sharding_axis=1),
},
'my/other/fake/module': {
'w': FakeShardSpec(sharding_axis=2),
'b': FakeShardSpec(sharding_axis=3),
},
},
nu={
'my/fake/module': {
'w': FakeShardSpec(sharding_axis=0),
'b': FakeShardSpec(sharding_axis=1),
},
'my/other/fake/module': {
'w': FakeShardSpec(sharding_axis=2),
'b': FakeShardSpec(sharding_axis=3),
},
},
),
base.EmptyState(),
)
self.assertEqual(expected, opt_state_sharding_spec)
def test_inject_hparams(self):
opt = schedule.inject_hyperparams(alias.adamw)(learning_rate=1e-3)
params = _fake_params()
state = opt.init(params)
state = state_utils.tree_map_params(opt, lambda v: v+1, state)
state = cast(schedule.InjectHyperparamsState, state)
self.assertEqual(1e-3, state.hyperparams['learning_rate'])
params_plus_one = jax.tree_map(lambda v: v+1, params)
mu = getattr(state.inner_state[0], 'mu')
chex.assert_trees_all_close(mu, params_plus_one)
def test_map_params_to_none(self):
opt = alias.adagrad(1e-4)
params = {'a': jnp.zeros((1, 2))}
state = opt.init(params)
state = state_utils.tree_map_params(opt, lambda _: None, state)
self.assertEqual(
state,
(
transform.ScaleByRssState(sum_of_squares={'a': None}),
base.EmptyState(),
),
)
def test_map_non_params_to_none(self):
"""Test for dangerous edge-cases in tree when returning None values."""
opt = alias.adam(schedule.linear_schedule(1e-2, 1e-4, 10))
params = {'a': jnp.zeros((1, 2))}
state = opt.init(params)
state = state_utils.tree_map_params(
opt,
lambda v: 1, state, transform_non_params=lambda _: None
)
expected = (
transform.ScaleByAdamState( # pytype:disable=wrong-arg-types
count=None,
mu={'a': 1},
nu={'a': 1},
),
transform.ScaleByScheduleState( # pytype:disable=wrong-arg-types
count=None),
)
self.assertEqual(state, expected)
def _fake_params():
return {
'my/fake/module': {
'w': jnp.zeros((1, 2)),
'b': jnp.zeros((3, 4)),
},
'my/other/fake/module': {
'w': jnp.zeros((1, 2)),
'b': jnp.zeros((3, 4)),
},
}
def _fake_param_sharding():
return {
'my/fake/module': {
'w': FakeShardSpec(0),
'b': FakeShardSpec(1),
},
'my/other/fake/module': {
'w': FakeShardSpec(2),
'b': FakeShardSpec(3),
},
}
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/state_utils_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `control_variates.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import control_variates
from optax._src import stochastic_gradient_estimators as sge
from optax._src import utils
# Set seed for deterministic sampling.
np.random.seed(42)
def _assert_equal(actual, expected, rtol=1e-2, atol=1e-2):
"""Asserts that arrays are equal."""
# Note: assert_allclose does not check shapes
chex.assert_equal_shape((actual, expected))
# Scalar.
if not actual.shape:
np.testing.assert_allclose(
np.asarray(actual), np.asarray(expected), rtol, atol)
return
# We get around the bug https://github.com/numpy/numpy/issues/13801
zero_indices = np.argwhere(expected == 0)
if not np.all(np.abs(actual[zero_indices]) <= atol):
raise AssertionError(f'Larger than {atol} diff in {actual[zero_indices]}')
non_zero_indices = np.argwhere(expected != 0)
np.testing.assert_allclose(
np.asarray(actual)[non_zero_indices],
expected[non_zero_indices], rtol, atol)
def _map(cv, params, samples, state=None):
return jax.vmap(lambda x: cv(params, x, state))(samples)
def _map_variant(variant):
return variant(_map, static_argnums=0)
def _cv_jac_variant(variant):
return variant(
control_variates.control_variates_jacobians,
static_argnums=(0, 1, 2, 4, 6, 7, 8))
class DeltaControlVariateTest(chex.TestCase):
@chex.all_variants
@parameterized.parameters([(1.0, 0.5)])
def testQuadraticFunction(self, effective_mean, effective_log_scale):
data_dims = 20
num_samples = 10**6
rng = jax.random.PRNGKey(1)
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
dist = utils.multi_normal(*params)
dist_samples = dist.sample((num_samples,), rng)
function = lambda x: jnp.sum(x**2)
cv, expected_cv, _ = control_variates.control_delta_method(function)
avg_cv = jnp.mean(_map_variant(self.variant)(cv, params, dist_samples))
expected_cv_value = jnp.sum(dist_samples**2) / num_samples
# This should be an analytical computation, the result needs to be
# accurate.
_assert_equal(avg_cv, expected_cv_value, rtol=1e-1, atol=1e-3)
_assert_equal(expected_cv(params, None), expected_cv_value, rtol=0.02)
@chex.all_variants
@parameterized.parameters([(1.0, 1.0)])
def testPolinomialFunction(self, effective_mean, effective_log_scale):
data_dims = 10
num_samples = 10**3
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
dist = utils.multi_normal(*params)
rng = jax.random.PRNGKey(1)
dist_samples = dist.sample((num_samples,), rng)
function = lambda x: jnp.sum(x**5)
cv, expected_cv, _ = control_variates.control_delta_method(function)
avg_cv = jnp.mean(_map_variant(self.variant)(cv, params, dist_samples))
# Check that the average value of the control variate is close to the
# expected value.
_assert_equal(avg_cv, expected_cv(params, None), rtol=1e-1, atol=1e-3)
@chex.all_variants
def testNonPolynomialFunction(self):
data_dims = 10
num_samples = 10**3
mean = jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = jnp.ones(shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
rng = jax.random.PRNGKey(1)
dist = utils.multi_normal(*params)
dist_samples = dist.sample((num_samples,), rng)
function = lambda x: jnp.sum(jnp.log(x**2))
cv, expected_cv, _ = control_variates.control_delta_method(function)
avg_cv = jnp.mean(_map_variant(self.variant)(cv, params, dist_samples))
# Check that the average value of the control variate is close to the
# expected value.
_assert_equal(avg_cv, expected_cv(params, None), rtol=1e-1, atol=1e-3)
# Second order expansion is log(\mu**2) + 1/2 * \sigma**2 (-2 / \mu**2)
expected_cv_val = - np.exp(1.) ** 2 * data_dims
_assert_equal(
expected_cv(params, None), expected_cv_val, rtol=1e-1, atol=1e-3)
class MovingAverageBaselineTest(chex.TestCase):
@chex.all_variants
@parameterized.parameters(
[(1.0, 0.5, 0.9),
(1.0, 0.5, 0.99)])
def testLinearFunction(
self, effective_mean, effective_log_scale, decay):
weights = jnp.array([1., 2., 3.], dtype=jnp.float32)
num_samples = 10**4
data_dims = len(weights)
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
function = lambda x: jnp.sum(weights * x)
rng = jax.random.PRNGKey(1)
dist = utils.multi_normal(*params)
dist_samples = dist.sample((num_samples,), rng)
cv, expected_cv, update_state = control_variates.moving_avg_baseline(
function, decay=decay, zero_debias=False,
use_decay_early_training_heuristic=False)
state_1 = jnp.array(1.)
avg_cv = jnp.mean(_map_variant(self.variant)(
cv, params, dist_samples, (state_1, 0)))
_assert_equal(avg_cv, state_1)
_assert_equal(expected_cv(params, (state_1, 0)), state_1)
state_2 = jnp.array(2.)
avg_cv = jnp.mean(
_map_variant(self.variant)(cv, params, dist_samples, (state_2, 0)))
_assert_equal(avg_cv, state_2)
_assert_equal(expected_cv(params, (state_2, 0)), state_2)
update_state_1 = update_state(params, dist_samples, (state_1, 0))[0]
_assert_equal(
update_state_1,
decay * state_1 + (1 - decay) * function(mean))
update_state_2 = update_state(params, dist_samples, (state_2, 0))[0]
_assert_equal(
update_state_2,
decay * state_2 + (1 - decay) * function(mean))
@chex.all_variants
@parameterized.parameters(
[(1.0, 0.5, 0.9),
(1.0, 0.5, 0.99)])
def testLinearFunctionWithHeuristic(
self, effective_mean, effective_log_scale, decay):
weights = jnp.array([1., 2., 3.], dtype=jnp.float32)
num_samples = 10**5
data_dims = len(weights)
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
function = lambda x: jnp.sum(weights * x)
rng = jax.random.PRNGKey(1)
dist = utils.multi_normal(*params)
dist_samples = dist.sample((num_samples,), rng)
cv, expected_cv, update_state = control_variates.moving_avg_baseline(
function, decay=decay, zero_debias=False,
use_decay_early_training_heuristic=True)
state_1 = jnp.array(1.)
avg_cv = jnp.mean(_map_variant(self.variant)(
cv, params, dist_samples, (state_1, 0)))
_assert_equal(avg_cv, state_1)
_assert_equal(expected_cv(params, (state_1, 0)), state_1)
state_2 = jnp.array(2.)
avg_cv = jnp.mean(
_map_variant(self.variant)(cv, params, dist_samples, (state_2, 0)))
_assert_equal(avg_cv, state_2)
_assert_equal(expected_cv(params, (state_2, 0)), state_2)
first_step_decay = 0.1
update_state_1 = update_state(params, dist_samples, (state_1, 0))[0]
_assert_equal(
update_state_1,
first_step_decay * state_1 + (1 - first_step_decay) * function(mean))
second_step_decay = 2. / 11
update_state_2 = update_state(params, dist_samples, (state_2, 1))[0]
_assert_equal(
update_state_2,
second_step_decay * state_2 + (1 - second_step_decay) * function(mean))
@parameterized.parameters(
[(1.0, 0.5, 0.9),
(1.0, 0.5, 0.99)])
def testLinearFunctionZeroDebias(
self, effective_mean, effective_log_scale, decay):
weights = jnp.array([1., 2., 3.], dtype=jnp.float32)
num_samples = 10**5
data_dims = len(weights)
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
function = lambda x: jnp.sum(weights * x)
rng = jax.random.PRNGKey(1)
dist = utils.multi_normal(*params)
dist_samples = dist.sample((num_samples,), rng)
update_state = control_variates.moving_avg_baseline(
function, decay=decay, zero_debias=False,
use_decay_early_training_heuristic=False)[-1]
update_state_zero_debias = control_variates.moving_avg_baseline(
function, decay=decay, zero_debias=True,
use_decay_early_training_heuristic=False)[-1]
updated_state = update_state(params, dist_samples, (jnp.array(0.), 0))[0]
_assert_equal(updated_state, (1 - decay) * function(mean))
updated_state_zero_debias = update_state_zero_debias(
params, dist_samples, (jnp.array(0.), 0))[0]
_assert_equal(
updated_state_zero_debias, function(mean))
class DeltaMethodAnalyticalExpectedGrads(chex.TestCase):
"""Tests for grads approximations."""
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', 1.0, 1.0, sge.score_function_jacobians),
('_pathwise_jacobians', 1.0, 1.0, sge.pathwise_jacobians),
('_measure_valued_jacobians', 1.0, 1.0, sge.measure_valued_jacobians),
], [
('estimate_cv_coeffs', True),
('no_estimate_cv_coeffs', False),
],
named=True))
def testQuadraticFunction(self, effective_mean, effective_log_scale,
grad_estimator, estimate_cv_coeffs):
data_dims = 3
num_samples = 10**3
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
function = lambda x: jnp.sum(x**2)
rng = jax.random.PRNGKey(1)
jacobians = _cv_jac_variant(self.variant)(
function,
control_variates.control_delta_method,
grad_estimator,
params,
utils.multi_normal, # dist_builder
rng,
num_samples,
None, # No cv state.
estimate_cv_coeffs)[0]
expected_mean_grads = 2 * effective_mean * np.ones(
data_dims, dtype=np.float32)
expected_log_scale_grads = 2 * np.exp(2 * effective_log_scale) * np.ones(
data_dims, dtype=np.float32)
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads_from_jacobian = jnp.mean(mean_jacobians, axis=0)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads_from_jacobian = jnp.mean(log_scale_jacobians, axis=0)
_assert_equal(mean_grads_from_jacobian, expected_mean_grads,
rtol=1e-1, atol=1e-3)
_assert_equal(log_scale_grads_from_jacobian, expected_log_scale_grads,
rtol=1e-1, atol=1e-3)
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', 1.0, 1.0, sge.score_function_jacobians),
('_pathwise_jacobians', 1.0, 1.0, sge.pathwise_jacobians),
('_measure_valued_jacobians', 1.0, 1.0, sge.measure_valued_jacobians),
], [
('estimate_cv_coeffs', True),
('no_estimate_cv_coeffs', False),
],
named=True))
def testCubicFunction(
self, effective_mean, effective_log_scale, grad_estimator,
estimate_cv_coeffs):
data_dims = 1
num_samples = 10**5
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
function = lambda x: jnp.sum(x**3)
rng = jax.random.PRNGKey(1)
jacobians = _cv_jac_variant(self.variant)(
function,
control_variates.control_delta_method,
grad_estimator,
params,
utils.multi_normal,
rng,
num_samples,
None, # No cv state.
estimate_cv_coeffs)[0]
# The third order uncentered moment of the Gaussian distribution is
# mu**3 + 2 mu * sigma **2. We use that to compute the expected value
# of the gradients. Note: for the log scale we need use the chain rule.
expected_mean_grads = (
3 * effective_mean**2 + 3 * np.exp(effective_log_scale)**2)
expected_mean_grads *= np.ones(data_dims, dtype=np.float32)
expected_log_scale_grads = (
6 * effective_mean * np.exp(effective_log_scale) ** 2)
expected_log_scale_grads *= np.ones(data_dims, dtype=np.float32)
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads_from_jacobian = jnp.mean(mean_jacobians, axis=0)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads_from_jacobian = jnp.mean(log_scale_jacobians, axis=0)
_assert_equal(mean_grads_from_jacobian, expected_mean_grads,
rtol=1e-1, atol=1e-3)
_assert_equal(log_scale_grads_from_jacobian, expected_log_scale_grads,
rtol=1e-1, atol=1e-3)
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', 1.0, 1.0, sge.score_function_jacobians),
('_pathwise_jacobians', 1.0, 1.0, sge.pathwise_jacobians),
('_measure_valued_jacobians', 1.0, 1.0, sge.measure_valued_jacobians),
], [
('estimate_cv_coeffs', True),
('no_estimate_cv_coeffs', False),
],
named=True))
def testForthPowerFunction(
self, effective_mean, effective_log_scale, grad_estimator,
estimate_cv_coeffs):
data_dims = 1
num_samples = 10**5
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
function = lambda x: jnp.sum(x**4)
rng = jax.random.PRNGKey(1)
jacobians = _cv_jac_variant(self.variant)(
function,
control_variates.control_delta_method,
grad_estimator,
params,
utils.multi_normal,
rng,
num_samples,
None, # No cv state
estimate_cv_coeffs)[0]
# The third order uncentered moment of the Gaussian distribution is
# mu**4 + 6 mu **2 sigma **2 + 3 sigma**4. We use that to compute the
# expected value of the gradients.
# Note: for the log scale we need use the chain rule.
expected_mean_grads = (
3 * effective_mean**3
+ 12 * effective_mean * np.exp(effective_log_scale)**2)
expected_mean_grads *= np.ones(data_dims, dtype=np.float32)
expected_log_scale_grads = 12 * (
effective_mean**2 * np.exp(effective_log_scale) +
np.exp(effective_log_scale) ** 3) * np.exp(effective_log_scale)
expected_log_scale_grads *= np.ones(data_dims, dtype=np.float32)
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads_from_jacobian = jnp.mean(mean_jacobians, axis=0)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads_from_jacobian = jnp.mean(log_scale_jacobians, axis=0)
_assert_equal(mean_grads_from_jacobian, expected_mean_grads,
rtol=1e-1, atol=1e-3)
_assert_equal(log_scale_grads_from_jacobian, expected_log_scale_grads,
rtol=1e-1, atol=1e-3)
class ConsistencyWithStandardEstimators(chex.TestCase):
"""Tests for consistency between estimators."""
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', 1, 1, sge.score_function_jacobians,
10**6),
('_pathwise_jacobians', 1, 1, sge.pathwise_jacobians, 10**5),
('_measure_valued_jacobians', 1, 1, sge.measure_valued_jacobians,
10**5),
], [
('control_delta_method', control_variates.control_delta_method),
('moving_avg_baseline', control_variates.moving_avg_baseline),
],
named=True))
def testWeightedLinearFunction(self, effective_mean, effective_log_scale,
grad_estimator, num_samples,
control_variate_from_function):
"""Check that the gradients are consistent between estimators."""
weights = jnp.array([1., 2., 3.], dtype=jnp.float32)
data_dims = len(weights)
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
function = lambda x: jnp.sum(weights * x)
rng = jax.random.PRNGKey(1)
cv_rng, ge_rng = jax.random.split(rng)
jacobians = _cv_jac_variant(self.variant)(
function,
control_variate_from_function,
grad_estimator,
params,
utils.multi_normal, # dist_builder
cv_rng, # rng
num_samples,
(0., 0), # control_variate_state
False)[0]
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads = jnp.mean(mean_jacobians, axis=0)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads = jnp.mean(log_scale_jacobians, axis=0)
# We use a different random number generator for the gradient estimator
# without the control variate.
no_cv_jacobians = grad_estimator(
function, [mean, log_scale],
utils.multi_normal, ge_rng, num_samples=num_samples)
no_cv_mean_jacobians = no_cv_jacobians[0]
chex.assert_shape(no_cv_mean_jacobians, (num_samples, data_dims))
no_cv_mean_grads = jnp.mean(no_cv_mean_jacobians, axis=0)
no_cv_log_scale_jacobians = no_cv_jacobians[1]
chex.assert_shape(no_cv_log_scale_jacobians, (num_samples, data_dims))
no_cv_log_scale_grads = jnp.mean(no_cv_log_scale_jacobians, axis=0)
_assert_equal(mean_grads, no_cv_mean_grads, rtol=1e-1, atol=5e-2)
_assert_equal(log_scale_grads, no_cv_log_scale_grads, rtol=1, atol=5e-2)
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', 1, 1, sge.score_function_jacobians,
10**5),
('_pathwise_jacobians', 1, 1, sge.pathwise_jacobians, 10**5),
('_measure_valued_jacobians', 1, 1, sge.measure_valued_jacobians,
10**5),
], [
('control_delta_method', control_variates.control_delta_method),
('moving_avg_baseline', control_variates.moving_avg_baseline),
],
named=True))
def testNonPolynomialFunction(
self, effective_mean, effective_log_scale,
grad_estimator, num_samples, control_variate_from_function):
"""Check that the gradients are consistent between estimators."""
data_dims = 3
mean = effective_mean * jnp.ones(shape=(data_dims), dtype=jnp.float32)
log_scale = effective_log_scale * jnp.ones(
shape=(data_dims), dtype=jnp.float32)
params = [mean, log_scale]
function = lambda x: jnp.log(jnp.sum(x**2))
rng = jax.random.PRNGKey(1)
cv_rng, ge_rng = jax.random.split(rng)
jacobians = _cv_jac_variant(self.variant)(
function,
control_variate_from_function,
grad_estimator,
params,
utils.multi_normal,
cv_rng,
num_samples,
(0., 0), # control_variate_state
False)[0]
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads = jnp.mean(mean_jacobians, axis=0)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads = jnp.mean(log_scale_jacobians, axis=0)
# We use a different random number generator for the gradient estimator
# without the control variate.
no_cv_jacobians = grad_estimator(
function, [mean, log_scale],
utils.multi_normal, ge_rng, num_samples=num_samples)
no_cv_mean_jacobians = no_cv_jacobians[0]
chex.assert_shape(no_cv_mean_jacobians, (num_samples, data_dims))
no_cv_mean_grads = jnp.mean(no_cv_mean_jacobians, axis=0)
no_cv_log_scale_jacobians = no_cv_jacobians[1]
chex.assert_shape(no_cv_log_scale_jacobians, (num_samples, data_dims))
no_cv_log_scale_grads = jnp.mean(no_cv_log_scale_jacobians, axis=0)
_assert_equal(mean_grads, no_cv_mean_grads, rtol=1e-1, atol=5e-2)
_assert_equal(log_scale_grads, no_cv_log_scale_grads, rtol=1e-1, atol=5e-2)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/control_variates_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `second_order.py`."""
import collections
import functools
import itertools
from absl.testing import absltest
import chex
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import second_order
NUM_CLASSES = 2
NUM_SAMPLES = 3
NUM_FEATURES = 4
class SecondOrderTest(chex.TestCase):
def setUp(self):
super().setUp()
self.data = np.random.rand(NUM_SAMPLES, NUM_FEATURES)
self.labels = np.random.randint(NUM_CLASSES, size=NUM_SAMPLES)
def net_fn(z):
mlp = hk.Sequential(
[hk.Linear(10), jax.nn.relu, hk.Linear(NUM_CLASSES)], name='mlp')
return jax.nn.log_softmax(mlp(z))
net = hk.without_apply_rng(hk.transform(net_fn))
self.parameters = net.init(jax.random.PRNGKey(0), self.data)
def loss(params, inputs, targets):
log_probs = net.apply(params, inputs)
return -jnp.mean(hk.one_hot(targets, NUM_CLASSES) * log_probs)
self.loss_fn = loss
def jax_hessian_diag(loss_fun, params, inputs, targets):
"""This is the 'ground-truth' obtained via the JAX library."""
hess = jax.hessian(loss_fun)(params, inputs, targets)
# Extracts the diagonal components.
hess_diag = collections.defaultdict(dict)
for k0, k1 in itertools.product(params.keys(), ['w', 'b']):
params_shape = params[k0][k1].shape
n_params = np.prod(params_shape)
hess_diag[k0][k1] = jnp.diag(hess[k0][k1][k0][k1].reshape(
n_params, n_params)).reshape(params_shape)
for k, v in hess_diag.items():
hess_diag[k] = v
return second_order.ravel(hess_diag)
self.hessian = jax_hessian_diag(
self.loss_fn, self.parameters, self.data, self.labels)
@chex.all_variants
def test_hessian_diag(self):
hessian_diag_fn = self.variant(
functools.partial(second_order.hessian_diag, self.loss_fn))
actual = hessian_diag_fn(self.parameters, self.data, self.labels)
np.testing.assert_array_almost_equal(self.hessian, actual, 5)
@chex.all_variants
def test_fisher_diag_shape(self):
fisher_diag_fn = self.variant(
functools.partial(second_order.fisher_diag, self.loss_fn))
fisher_diagonal = fisher_diag_fn(self.parameters, self.data, self.labels)
chex.assert_equal_shape([fisher_diagonal, self.hessian])
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/second_order_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for computing diagonals of Hessians & Fisher info of parameters.
Computing the Hessian or Fisher information matrices for neural networks is
typically intractible due to the quadratic memory requirements. Solving for the
diagonals of these matrices is often a better solution.
This module provides two functions for computing these diagonals, `hessian_diag`
and `fisher_diag`., each with sub-quadratic memory requirements.
"""
from typing import Any, Callable
import jax
from jax.flatten_util import ravel_pytree
import jax.numpy as jnp
# This covers both Jax and Numpy arrays.
# TODO(b/160876114): use the pytypes defined in Chex.
Array = jnp.ndarray
# LossFun of type f(params, inputs, targets).
LossFun = Callable[[Any, Array, Array], Array]
def ravel(p: Any) -> Array:
return ravel_pytree(p)[0]
def hvp(
loss: LossFun,
v: jax.Array,
params: Any,
inputs: jax.Array,
targets: jax.Array,
) -> jax.Array:
"""Performs an efficient vector-Hessian (of `loss`) product.
Args:
loss: the loss function.
v: a vector of size `ravel(params)`.
params: model parameters.
inputs: inputs at which `loss` is evaluated.
targets: targets at which `loss` is evaluated.
Returns:
An Array corresponding to the product of `v` and the Hessian of `loss`
evaluated at `(params, inputs, targets)`.
"""
_, unravel_fn = ravel_pytree(params)
loss_fn = lambda p: loss(p, inputs, targets)
return jax.jvp(jax.grad(loss_fn), [params], [unravel_fn(v)])[1]
def hessian_diag(
loss: LossFun,
params: Any,
inputs: jax.Array,
targets: jax.Array,
) -> jax.Array:
"""Computes the diagonal hessian of `loss` at (`inputs`, `targets`).
Args:
loss: the loss function.
params: model parameters.
inputs: inputs at which `loss` is evaluated.
targets: targets at which `loss` is evaluated.
Returns:
A DeviceArray corresponding to the product to the Hessian of `loss`
evaluated at `(params, inputs, targets)`.
"""
vs = jnp.eye(ravel(params).size)
comp = lambda v: jnp.vdot(v, ravel(hvp(loss, v, params, inputs, targets)))
return jax.vmap(comp)(vs)
def fisher_diag(
negative_log_likelihood: LossFun,
params: Any,
inputs: jnp.ndarray,
targets: jnp.ndarray,
) -> jax.Array:
"""Computes the diagonal of the (observed) Fisher information matrix.
Args:
negative_log_likelihood: the negative log likelihood function.
params: model parameters.
inputs: inputs at which `negative_log_likelihood` is evaluated.
targets: targets at which `negative_log_likelihood` is evaluated.
Returns:
An Array corresponding to the product to the Hessian of
`negative_log_likelihood` evaluated at `(params, inputs, targets)`.
"""
return jnp.square(
ravel(jax.grad(negative_log_likelihood)(params, inputs, targets)))
| optax-master | optax/_src/second_order.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for optax._src.loss."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import loss
class SquaredErrorTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.ys = jnp.array([-2., -1., 0.5, 1.])
self.ts = jnp.array([-1.5, 0., -1, 1.])
# compute expected outputs in numpy.
self.exp = (self.ts - self.ys) ** 2
@chex.all_variants
def test_scalar(self):
np.testing.assert_allclose(
self.variant(loss.squared_error)(
self.ys[0], self.ts[0]), self.exp[0])
@chex.all_variants
def test_batched(self):
np.testing.assert_allclose(
self.variant(loss.squared_error)(
self.ys, self.ts), self.exp)
@chex.all_variants
def test_shape_mismatch(self):
with self.assertRaises(AssertionError):
_ = self.variant(loss.squared_error)(
self.ys, jnp.expand_dims(self.ts, axis=-1))
class L2LossTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.ys = jnp.array([-2., -1., 0.5, 1.])
self.ts = jnp.array([-1.5, 0., -1, 1.])
# compute expected outputs in numpy.
self.exp = 0.5 * (self.ts - self.ys) ** 2
@chex.all_variants
def test_scalar(self):
np.testing.assert_allclose(
self.variant(loss.l2_loss)(self.ys[0], self.ts[0]), self.exp[0])
@chex.all_variants
def test_batched(self):
np.testing.assert_allclose(
self.variant(loss.l2_loss)(self.ys, self.ts), self.exp)
@chex.all_variants
def test_shape_mismatch(self):
with self.assertRaises(AssertionError):
_ = self.variant(loss.l2_loss)(self.ys, jnp.expand_dims(self.ts, axis=-1))
class HuberLossTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.ys = np.array([-2.0, 0.5, 0., 0.5, 2.0, 4.0, 132.])
self.ts = np.array([0.0, -0.5, 0., 1., 1.0, 2.0, 0.3])
# computed expected outputs manually.
self.exp = np.array([1.5, 0.5, 0., 0.125, 0.5, 1.5, 131.2])
@chex.all_variants
def test_scalar(self):
np.testing.assert_allclose(
self.variant(loss.huber_loss)(self.ys[0], self.ts[0], delta=1.0),
self.exp[0])
@chex.all_variants
def test_batched(self):
np.testing.assert_allclose(
self.variant(loss.huber_loss)(self.ys, self.ts, delta=1.0),
self.exp)
class SmoothLabelsTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.ts = np.array([[0., 1., 0.], [1., 0., 0.]], dtype=np.float32)
# compute expected outputs in numpy.
self.exp_alpha_zero = self.ts
self.exp_alpha_zero_point_one = 0.9 * self.ts + 0.1 / self.ts.shape[-1]
self.exp_alpha_one = jnp.ones_like(self.ts) / self.ts.shape[-1]
@chex.all_variants
def test_scalar(self):
"""Tests for a full batch."""
np.testing.assert_allclose(
self.variant(loss.smooth_labels)(self.ts[0], 0.),
self.exp_alpha_zero[0], atol=1e-4)
np.testing.assert_allclose(
self.variant(loss.smooth_labels)(self.ts[0], 0.1),
self.exp_alpha_zero_point_one[0], atol=1e-4)
np.testing.assert_allclose(
self.variant(loss.smooth_labels)(self.ts[0], 1.),
self.exp_alpha_one[0], atol=1e-4)
@chex.all_variants
def test_batched(self):
"""Tests for a full batch."""
np.testing.assert_allclose(
self.variant(loss.smooth_labels)(self.ts, 0.),
self.exp_alpha_zero, atol=1e-4)
np.testing.assert_allclose(
self.variant(loss.smooth_labels)(self.ts, 0.1),
self.exp_alpha_zero_point_one, atol=1e-4)
np.testing.assert_allclose(
self.variant(loss.smooth_labels)(self.ts, 1.),
self.exp_alpha_one, atol=1e-4)
class SoftmaxCrossEntropyTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.ys = np.array([[10., 1., -2.], [1., 4., 0.2]], dtype=np.float32)
self.ts = np.array([[0., 1., 0.], [1., 0., 0.]], dtype=np.float32)
# taken expected outputs from rlax.
self.exp = np.array([9.00013, 3.0696733], dtype=np.float32)
@chex.all_variants
def test_scalar(self):
"""Tests for a full batch."""
np.testing.assert_allclose(
self.variant(loss.softmax_cross_entropy)(self.ys[0], self.ts[0]),
self.exp[0], atol=1e-4)
@chex.all_variants
def test_batched(self):
"""Tests for a full batch."""
np.testing.assert_allclose(
self.variant(loss.softmax_cross_entropy)(self.ys, self.ts),
self.exp, atol=1e-4)
class SoftmaxCrossEntropyWithIntegerLabelsTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.ys = np.array([[10., 1., -2.], [1., 4., 0.2]], dtype=np.float32)
self.ts = np.array([1, 0], dtype=np.int32)
@chex.all_variants
def test_consistent_with_softmax_cross_entropy_scalar(self):
"""Tests for a scalar."""
exp = loss.softmax_cross_entropy(self.ys[0], jax.nn.one_hot(self.ts[0], 3))
np.testing.assert_allclose(
self.variant(loss.softmax_cross_entropy_with_integer_labels)(
self.ys[0], self.ts[0]),
exp, rtol=1e-6)
@chex.all_variants
def test_consistent_with_softmax_cross_entropy_batched(self):
"""Tests for a full batch."""
exp = loss.softmax_cross_entropy(self.ys, jax.nn.one_hot(self.ts, 3))
np.testing.assert_allclose(
self.variant(loss.softmax_cross_entropy_with_integer_labels)(
self.ys, self.ts),
exp, rtol=1e-6)
class SigmoidCrossEntropyTest(parameterized.TestCase):
@parameterized.parameters(
dict(preds=np.array([-1e+09, -1e-09]),
labels=np.array([1., 0.]),
expected=5e+08),
dict(preds=np.array([-1e+09, -1e-09]),
labels=np.array([0., 1.]),
expected=0.3465736),
dict(preds=np.array([1e+09, 1e-09]),
labels=np.array([1., 0.]),
expected=0.3465736),
dict(preds=np.array([1e+09, 1e-09]),
labels=np.array([0., 1.]),
expected=5e+08),
dict(preds=np.array([-1e+09, 1e-09]),
labels=np.array([1., 0.]),
expected=5e+08),
dict(preds=np.array([-1e+09, 1e-09]),
labels=np.array([0., 1.]),
expected=0.3465736),
dict(preds=np.array([1e+09, -1e-09]),
labels=np.array([1., 0.]),
expected=0.3465736),
dict(preds=np.array([1e+09, -1e-09]),
labels=np.array([0., 1.]),
expected=5e+08),
dict(preds=np.array([0., 0.]),
labels=np.array([1., 0.]),
expected=0.6931472),
dict(preds=np.array([0., 0.]),
labels=np.array([0., 1.]),
expected=0.6931472),
)
def testSigmoidCrossEntropy(self, preds, labels, expected):
tested = jnp.mean(loss.sigmoid_binary_cross_entropy(preds, labels))
np.testing.assert_allclose(tested, expected, rtol=1e-6, atol=1e-6)
class CosineDistanceTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.ys = np.array([[10., 1., -2.], [1., 4., 0.2]], dtype=np.float32)
self.ts = np.array([[0., 1.2, 0.2], [1., -0.3, 0.]], dtype=np.float32)
# distance computed expected output from `scipy 1.20`.
self.exp = np.array([0.9358251989, 1.0464068465], dtype=np.float32)
@chex.all_variants
def test_scalar_distance(self):
"""Tests for a full batch."""
np.testing.assert_allclose(
self.variant(loss.cosine_distance)(self.ys[0], self.ts[0]),
self.exp[0], atol=1e-4)
@chex.all_variants
def test_scalar_similarity(self):
"""Tests for a full batch."""
np.testing.assert_allclose(
self.variant(loss.cosine_similarity)(self.ys[0], self.ts[0]),
1. - self.exp[0], atol=1e-4)
@chex.all_variants
def test_batched_distance(self):
"""Tests for a full batch."""
np.testing.assert_allclose(
self.variant(loss.cosine_distance)(self.ys, self.ts),
self.exp, atol=1e-4)
@chex.all_variants
def test_batched_similarity(self):
"""Tests for a full batch."""
np.testing.assert_allclose(
self.variant(loss.cosine_similarity)(self.ys, self.ts),
1. - self.exp, atol=1e-4)
# TODO(b/188419459): add test for grad and second order grad.
class LogCoshTest(parameterized.TestCase):
def setUp(self):
super().setUp()
# Test large values for overflow
self.ys = jnp.array([500, -2., -1., 0.5, 1.])
self.ts = jnp.array([-200, -1.5, 0., -1, 1.])
# computed using tensorflow.keras.losses.log_cosh v2.4.1
self.exp = jnp.array([699.3068, 0.12011445, 0.4337809, 0.85544014, 0.])
self.exp_ys_only = jnp.array(
[499.30685, 1.3250027, 0.4337809, 0.12011451, 0.43378082])
@chex.all_variants
def test_scalar(self):
out = self.variant(loss.log_cosh)(self.ys[0], self.ts[0])
np.testing.assert_allclose(out, self.exp[0], atol=1e-5)
@chex.all_variants
def test_batched(self):
out = self.variant(loss.log_cosh)(self.ys, self.ts)
np.testing.assert_allclose(out, self.exp, atol=1e-5)
@chex.all_variants
def test_scalar_predictions_only(self):
out = self.variant(loss.log_cosh)(self.ys[0])
np.testing.assert_allclose(out, self.exp_ys_only[0], atol=1e-5)
@chex.all_variants
def test_batched_predictions_only(self):
out = self.variant(loss.log_cosh)(self.ys)
np.testing.assert_allclose(out, self.exp_ys_only, atol=1e-5)
def _lengths_to_paddings(lengths: chex.Array, maxlength: int) -> chex.Array:
indices = jnp.arange(maxlength).reshape((1,) * lengths.ndim + (maxlength,))
lengths = jnp.expand_dims(lengths, axis=-1)
elem_valid = indices < lengths
return np.logical_not(elem_valid).astype(np.float32)
def _average_ctc_loss(logprobs: chex.Array, logprob_paddings: chex.Array,
labels: chex.Array,
label_paddings: chex.Array) -> chex.Array:
return jnp.average(
loss.ctc_loss(logprobs, logprob_paddings, labels, label_paddings))
class CTCTest(parameterized.TestCase):
def setUp(self):
super().setUp()
np.random.seed(1234)
self._rtol = 5e-3 if jax.default_backend() != 'cpu' else 1e-6
@chex.all_variants
def test_with_one_to_one_alignment(self):
# when inputsteps and outputsteps are equal, no blank will be allowed.
batchsize = 8
steps = 50
nclasses = 40
logits = np.random.randn(batchsize, steps, nclasses)
labels = np.random.uniform(
1, nclasses, size=(batchsize, steps)).astype(np.int32)
# This function only covers the cases without same-label repetition.
# `test_repeat_with_one_to_one_alignment` below complements those cases.
# So, redraw the samples for satisfying the non-repetition constraint.
for n in range(labels.shape[0]):
for t in range(1, labels.shape[1]):
while labels[n, t] == labels[n, t - 1]:
labels[n, t] = np.random.uniform(1, nclasses)
results = self.variant(loss.ctc_loss_with_forward_probs)(
logits, np.zeros(logits.shape[:2]),
labels, np.zeros(labels.shape))
(per_seq_loss, logalpha_blank, logalpha_emit) = results
logprobs = jax.nn.log_softmax(logits)
for b in range(batchsize):
p = 0.0
for t in range(steps):
p += logprobs[b, t, labels[b, t]]
np.testing.assert_allclose(
np.array(-p), per_seq_loss[b], rtol=self._rtol)
# Check forward-probabilities.
# 1. All-phi path: logalpha_blank[-1, b, 0] must be a probability of
# the path that outputs blank symbols for all the frames.
np.testing.assert_allclose(logalpha_blank[-1, b, 0],
np.sum(logprobs[b, :, 0]),
rtol=self._rtol)
# 2. After emitting all the labels
# the negated loss must be identical with the forward probability of
# paths after consuming all the labels (because one-to-one alignment
# doesn't allow extra blank symbols)
np.testing.assert_allclose(logalpha_emit[-1, b, steps - 1],
-per_seq_loss[b],
rtol=self._rtol)
# and, this forward probability must be copied to the blank forward
# probability of the next step.
np.testing.assert_allclose(logalpha_blank[-1, b, steps],
-per_seq_loss[b],
rtol=self._rtol)
@chex.all_variants
def test_with_one_to_one_alignment_and_paddings(self):
batch_size = 5
nclasses = 13
steps = 7
logits = np.random.normal(size=[batch_size, steps, nclasses])
logprobs = jax.nn.log_softmax(logits)
labels = []
for n in range(batch_size):
row = list(range(1, nclasses))
np.random.shuffle(row)
labels.append(row[:steps])
labels = np.array(labels)
lengths = np.random.randint(3, 6, size=(batch_size,))
paddings = _lengths_to_paddings(lengths, steps)
actual_loss = self.variant(loss.ctc_loss)(logits, paddings, labels,
paddings)
value_and_grad = self.variant(jax.value_and_grad(_average_ctc_loss))
unused_avg_loss, actual_gradients = value_and_grad(logits, paddings, labels,
paddings)
for n in range(batch_size):
expected_loss = -sum(logprobs[n, t, k]
for t, k in enumerate(labels[n, :lengths[n]]))
np.testing.assert_allclose(expected_loss, actual_loss[n], rtol=self._rtol)
expected_gradients = np.array(jax.nn.softmax(logits[n]))
expected_gradients[lengths[n]:] = 0.0
for t, k in enumerate(labels[n, :lengths[n]]):
expected_gradients[t, k] -= 1.0
expected_gradients /= batch_size
np.testing.assert_allclose(
expected_gradients, actual_gradients[n], rtol=self._rtol)
@chex.all_variants
def test_repeat_with_one_to_one_alignment(self):
# test if it can correctly handle the same-label repetition.
nclasses = 5
labels = np.array([
[1, 2, 2, 3],
[2, 3, 4, 4],
[1, 1, 1, 1],
[1, 1, 2, 3],
[1, 1, 1, 2],
])
expected_alignment = [ # expected minimal alignment
[1, 2, 0, 2, 3],
[2, 3, 4, 0, 4],
[1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 2, 3],
[1, 0, 1, 0, 1, 2],
]
batch_size = len(labels)
label_lens = np.array([4] * batch_size)
label_steps = 6
# Designed to have two padding elements on the right.
labels = np.pad(labels, [(0, 0), (0, label_steps - labels.shape[1])])
label_paddings = _lengths_to_paddings(label_lens, label_steps)
logit_lengths = np.array([len(seq) for seq in expected_alignment])
logit_steps = max(logit_lengths)
logits = np.random.randn(batch_size, logit_steps, nclasses)
logit_paddings = _lengths_to_paddings(logit_lengths, logit_steps)
per_seq_loss = self.variant(loss.ctc_loss)(logits, logit_paddings, labels,
label_paddings)
logprobs = jax.nn.log_softmax(logits)
for n in range(batch_size):
expected_loss = -sum(logprobs[n, t, k]
for t, k in enumerate(expected_alignment[n]))
np.testing.assert_allclose(
jnp.array(expected_loss), per_seq_loss[n], rtol=self._rtol)
class ConvexKLDivergenceTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.log_ps = np.array([
[-2.9957, -3.5066, -3.9120, -1.2040, -0.6931, -2.3026],
[-1.6094, -1.6094, -1.6094, -2.3026, -1.8971, -1.8971],
])
self.qs = np.array(
[[0.2, 0.2, 0.2, 0.1, 0.15, 0.15], [0.05, 0.03, 0.02, 0.3, 0.5, 0.0]]
)
# Computed convex kullback-leibler divergence of P from Q.
self.exp = np.array([0.88757247, 0.859308])
@chex.all_variants
def test_scalar(self):
np.testing.assert_allclose(
self.variant(loss.convex_kl_divergence)(self.log_ps[0], self.qs[0]),
self.exp[0],
atol=1e-4,
)
@chex.all_variants
def test_batched(self):
np.testing.assert_allclose(
self.variant(loss.convex_kl_divergence)(self.log_ps, self.qs),
self.exp,
atol=1e-4,
)
class KLDivergenceTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.log_ps = np.array(
[[-2.9957, -3.5066, -3.9120, -1.2040, -0.6931, -2.3026],
[-1.6094, -1.6094, -1.6094, -2.3026, -1.8971, -1.8971]])
self.qs = np.array([[0.2, 0.2, 0.2, 0.1, 0.15, 0.15],
[0.05, 0.03, 0.02, 0.3, 0.5, 0.]])
# Computed kullback-leibler divergence of P from Q.
self.exp = np.array([0.8875577, 0.7592807])
@chex.all_variants
def test_scalar(self):
np.testing.assert_allclose(
self.variant(loss.kl_divergence)(self.log_ps[0], self.qs[0]),
self.exp[0],
atol=1e-4)
@chex.all_variants
def test_batched(self):
np.testing.assert_allclose(
self.variant(loss.kl_divergence)(self.log_ps, self.qs),
self.exp,
atol=1e-4)
class KLDivergenceWithLogTargetsTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.log_ps = np.array(
[[-2.9957, -3.5066, -3.9120, -1.2040, -0.6931, -2.3026],
[-1.6094, -1.6094, -1.6094, -2.3026, -1.8971, -1.8971]])
self.qs = np.array([[-1.6094, -1.6094, -1.6094, -2.3026, -1.8971, -1.8971],
[-2.9957, -3.5066, -3.9120, -1.2040, -0.6931, -2.3026]])
# Computed kullback-leibler divergence of P from Q.
self.exp = np.array([0.8875625, 0.7187435584901326])
@chex.all_variants
def test_scalar(self):
np.testing.assert_allclose(
self.variant(loss.kl_divergence_with_log_targets)(self.log_ps[0],
self.qs[0]),
self.exp[0],
atol=1e-4)
@chex.all_variants
def test_batched(self):
np.testing.assert_allclose(
self.variant(loss.kl_divergence_with_log_targets)(self.log_ps, self.qs),
self.exp,
atol=1e-4)
class HingeLossTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.ys = np.array([
-0.97740268, -1.01812625, -0.81675726, -0.73605974, 2.08235648,
1.84101354, -1.0581002
])
self.ts = np.array([-1, -1, -1, -1, 1, 1, -1])
# Computed expected outputs.
self.correct_result = np.array(
[0.02259731, 0., 0.18324274, 0.26394027, 0., 0., 0.])
@chex.all_variants
def test_batched(self):
np.testing.assert_allclose(
self.variant(loss.hinge_loss)(self.ys, self.ts),
self.correct_result,
atol=1e-4)
class PolyLossTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.logits = np.array([0.14, 1.456, 2.356, -0.124, -2.47])
self.labels = np.array([0.1, 0.15, 0.2, 0.25, 0.3])
self.batched_logits = np.array([[4.0, 2.0, 1.0], [0.0, 5.0, 1.0]])
self.batched_labels = np.array([[1.0, 0.0, 0.0], [0.0, 0.8, 0.2]])
# all expected values are computed using tf version of `poly1_cross_entropy`
# see page 10 here https://arxiv.org/pdf/2204.12511.pdf for more
@chex.all_variants
@parameterized.parameters(
dict(eps=2, expected=4.5317),
dict(eps=1, expected=3.7153),
dict(eps=-1, expected=2.0827),
dict(eps=0, expected=2.8990),
dict(eps=-0.5, expected=2.4908),
dict(eps=1.15, expected=3.8378),
dict(eps=1.214, expected=3.8900),
dict(eps=5.45, expected=7.3480),
)
def test_scalar(self, eps, expected):
np.testing.assert_allclose(
self.variant(loss.poly_loss_cross_entropy)(
self.logits, self.labels, eps
),
expected,
atol=1e-4,
)
@chex.all_variants
@parameterized.parameters(
dict(eps=2, expected=np.array([0.4823, 1.2567])),
dict(eps=1, expected=np.array([0.3261, 1.0407])),
dict(eps=0, expected=np.array([0.1698, 0.8247])),
dict(eps=-0.5, expected=np.array([0.0917, 0.7168])),
dict(eps=1.15, expected=np.array([0.3495, 1.0731])),
dict(eps=1.214, expected=np.array([0.3595, 1.0870])),
dict(eps=5.45, expected=np.array([1.0211, 2.0018])),
)
def test_batched(self, eps, expected):
np.testing.assert_allclose(
self.variant(loss.poly_loss_cross_entropy)(
self.batched_logits, self.batched_labels, eps
),
expected,
atol=1e-4,
)
@chex.all_variants
@parameterized.parameters(
dict(
logits=np.array(
[[4.0, 2.0, 1.0], [0.0, 5.0, 1.0], [0.134, 1.234, 3.235]]
),
labels=np.array(
[[1.0, 0.0, 0.0], [0.0, 0.8, 0.2], [0.34, 0.33, 0.33]]
),
),
dict(
logits=np.array([[4.0, 2.0, 1.0], [0.0, 5.0, 1.0]]),
labels=np.array([[1.0, 0.0, 0.0], [0.0, 0.8, 0.2]]),
),
dict(
logits=np.array(
[[4.0, 2.0, 1.0, 0.134, 1.3515], [0.0, 5.0, 1.0, 0.5215, 5.616]]
),
labels=np.array(
[[0.5, 0.0, 0.0, 0.0, 0.5], [0.0, 0.12, 0.2, 0.56, 0.12]]
),
),
dict(logits=np.array([1.89, 2.39]), labels=np.array([0.34, 0.66])),
dict(logits=np.array([0.314]), labels=np.array([1.0])),
)
def test_equals_to_cross_entropy_when_eps0(self, logits, labels):
np.testing.assert_allclose(
self.variant(loss.poly_loss_cross_entropy)(logits, labels, epsilon=0.0),
self.variant(loss.softmax_cross_entropy)(logits, labels),
atol=1e-4,
)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/loss_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Gradient transformations used to enforce specific constraints."""
from typing import Any, NamedTuple
import jax
import jax.numpy as jnp
from optax._src import base
# pylint:disable=no-value-for-parameter
NonNegativeParamsState = base.EmptyState
def keep_params_nonnegative() -> base.GradientTransformation:
"""Modifies the updates to keep parameters non-negative, i.e. >= 0.
This transformation ensures that parameters after the update will be
larger than or equal to zero.
In a chain of transformations, this should be the last one.
WARNING: the transformation expects input params to be non-negative.
When params is negative the transformed update will move them to 0.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return NonNegativeParamsState()
def update_fn(updates, state, params):
if params is None:
raise ValueError(base.NO_PARAMS_MSG)
updates = jax.tree_util.tree_map(
lambda p, u: jnp.where((p + u) < 0., -p, u), params, updates)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
class ZeroNansState(NamedTuple):
"""Contains a tree.
The entry `found_nan` has the same tree structure as that of the parameters.
Each leaf is a single boolean which contains True iff a NaN was detected in
the corresponding parameter array at the last call to `update`.
"""
found_nan: Any
def zero_nans() -> base.GradientTransformation:
"""A transformation which replaces NaNs with 0.
Zeroing values in gradients is guaranteed to produce a direction of
non-increasing loss.
The state of the transformation has the same tree structure as that of the
parameters. Each leaf is a single boolean which contains True iff a NaN was
detected in the corresponding parameter array at the last call to `update`.
This state is not used by the transformation internally, but lets users be
aware when NaNs have been zeroed out.
Returns:
A `GradientTransformation`.
"""
def init_fn(params):
return ZeroNansState(jax.tree_util.tree_map(
lambda p: jnp.array(False, dtype=jnp.bool_), params))
def update_fn(updates, opt_state, params=None):
del params
opt_state = ZeroNansState(
jax.tree_util.tree_map(lambda p: jnp.any(jnp.isnan(p)), updates))
updates = jax.tree_util.tree_map(
lambda p: jnp.where(jnp.isnan(p), jnp.zeros_like(p), p), updates)
return updates, opt_state
return base.GradientTransformation(init=init_fn, update=update_fn)
| optax-master | optax/_src/constrain.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tools for mapping over optimizer states."""
import typing
from typing import Any, Callable, Optional, Protocol, Union, cast
import jax
from optax._src import base
@typing.runtime_checkable
class Initable(Protocol):
"""An object with an init function."""
def init(self, params: base.Params) -> base.OptState:
"""Calling the init for given parameters returns a fresh opt state."""
def tree_map_params(
initable: Union[
Callable[[base.Params], base.OptState],
Initable,
],
f: Callable[..., Any],
state: base.OptState,
/,
*rest: Any,
transform_non_params: Optional[Callable[..., Any]] = None,
is_leaf: Optional[Callable[[base.Params], bool]] = None,
) -> base.OptState:
"""Apply a callable over all params in the given optimizer state.
This function exists to help construct partition specs over optimizer
states, in the case that a partition spec is already known for the parameters.
For example, the following will replace all optimizer state parameter trees
with copies of the given partition spec instead. The argument
`transform_non_params` can be used to replace any remaining fields as
required, in this case, we replace those fields by None.
>>> params, specs = ... # Trees with the same shape
>>> state = opt.init(params)
>>>
>>> opt_specs = optax.tree_map_params(
>>> opt,
>>> lambda _, spec: spec,
>>> state,
>>> specs,
>>> transform_non_params=lambda _: None,
>>> )
Args:
initable: A callable taking parameters and returning an optimizer state, or
an object with an `init` attribute having the same function.
f: A callable that will be applied for all copies of the parameter tree
within this optimizer state.
state: The optimizer state to map over.
*rest: Additional arguments, having the same shape as the parameter tree,
that will be passed to f.
transform_non_params: An optional function that will be called on all
non-parameter fields within the optimizer state.
is_leaf: Passed through to `jax.tree_map`. This makes it possible to ignore
parts of the parameter tree e.g. when the gradient transformations modify
the shape of the original pytree, such as for ``optax.masked``.
Returns:
The result of applying the function f on all trees in the optimizer's state
that have the same shape as the parameter tree, along with the given
optional extra arguments.
"""
# Cast for pytype checks (no-op for other usages).
placeholder = cast(base.chex.ArrayTree, _ParamsPlaceholder())
if isinstance(initable, Initable):
initable = cast(Initable, initable) # for pytype checks
state_with_placeholders = initable.init(placeholder)
else:
state_with_placeholders = initable(placeholder)
def map_params(maybe_placeholder_value, value):
if isinstance(maybe_placeholder_value, _ParamsPlaceholder):
return jax.tree_map(f, value, *rest, is_leaf=is_leaf)
elif transform_non_params is not None:
return transform_non_params(value)
else:
return value
return jax.tree_map(
map_params,
state_with_placeholders,
state,
is_leaf=lambda v: isinstance(v, _ParamsPlaceholder),
)
@jax.tree_util.register_pytree_node_class
class _ParamsPlaceholder:
def tree_flatten(self):
return ((), None)
@classmethod
def tree_unflatten(cls, aux, children):
del aux, children
return cls()
| optax-master | optax/_src/state_utils.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Gradient clipping transformations.
Note that complex numbers are also supported, see
https://gist.github.com/wdphy16/118aef6fb5f82c49790d7678cf87da29
"""
from typing import List, Tuple
import chex
import jax
import jax.numpy as jnp
from optax._src import base
from optax._src import linear_algebra
from optax._src import numerics
ClipState = base.EmptyState
def clip(max_delta: chex.Numeric) -> base.GradientTransformation:
"""Clips updates element-wise, to be in ``[-max_delta, +max_delta]``.
Args:
max_delta: The maximum absolute value for each element in the update.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return ClipState()
def update_fn(updates, state, params=None):
del params
updates = jax.tree_util.tree_map(
lambda g: jnp.clip(g, -max_delta, max_delta), updates)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
def clip_by_block_rms(threshold: float) -> base.GradientTransformation:
"""Clips updates to a max rms for the gradient of each param vector or matrix.
A `block` is here a weight vector (e.g. in a Linear layer) or a weight matrix
(e.g. in a convolutional layer) appearing as a leaf in the grads/param pytree.
Args:
threshold: The maximum rms for the gradient of each param vector or matrix.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return base.EmptyState()
def update_fn(updates, state, params=None):
del params
def _clip_fn(u):
clip_denom = jnp.maximum(
1.0,
jnp.sqrt(jnp.mean(numerics.abs_sq(u))) / threshold)
return u / clip_denom
updates = jax.tree_util.tree_map(_clip_fn, updates)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
ClipByGlobalNormState = base.EmptyState
def clip_by_global_norm(max_norm: float) -> base.GradientTransformation:
"""Clips updates using their global norm.
References:
[Pascanu et al, 2012](https://arxiv.org/abs/1211.5063)
Args:
max_norm: The maximum global norm for an update.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return ClipByGlobalNormState()
def update_fn(updates, state, params=None):
del params
g_norm = linear_algebra.global_norm(updates)
# TODO(b/163995078): revert back to the following (faster) implementation
# once analysed how it affects backprop through update (e.g. meta-gradients)
# g_norm = jnp.maximum(max_norm, g_norm)
# updates = jax.tree_util.tree_map(
# lambda t: (t / g_norm) * max_norm, updates)
trigger = jnp.squeeze(g_norm < max_norm)
chex.assert_shape(trigger, ()) # A scalar.
def clip_fn(t):
return jax.lax.select(trigger, t, (t / g_norm.astype(t.dtype)) * max_norm)
updates = jax.tree_util.tree_map(clip_fn, updates)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
def per_example_global_norm_clip(
grads: List[chex.Array], l2_norm_clip: float
) -> Tuple[List[chex.Array], jax.Array]:
"""Applies gradient clipping per-example using their global norm.
References:
[Abadi et al, 2016](https://arxiv.org/abs/1607.00133)
Args:
grads: flattened update; the function expects these to have a batch
dimension on the 0th axis.
l2_norm_clip: maximum L2 norm of the per-example gradients.
Returns:
A tuple containing sum of the clipped per-example grads, and the number of
per-example grads that were clipped.
"""
bsize = grads[0].shape[0]
if any(g.ndim == 0 or bsize != g.shape[0] for g in grads):
raise ValueError(
'Unlike other transforms, `per_example_global_norm_clip` expects'
' `grads` to have a batch dimension in the 0th axis.')
global_grad_norms = jax.vmap(linear_algebra.global_norm)(grads)
divisors = jnp.maximum(global_grad_norms / l2_norm_clip, 1.0)
num_clipped = jnp.greater(divisors, 1.0).sum()
clipped_sum = [(jnp.moveaxis(g, 0, -1) / divisors).sum(-1) for g in grads]
return clipped_sum, num_clipped
def unitwise_norm(x: chex.Array) -> chex.Array:
"""Computes norms of each output unit separately."""
if jnp.squeeze(x).ndim <= 1: # Scalars and vectors
squared_norm = jnp.sum(numerics.abs_sq(x), keepdims=True)
# Note that this assumes parameters with a shape of length 3 are multihead
# linear parameters--if you wish to apply AGC to 1D convs, you may need
# to modify this line.
elif x.ndim in (2, 3): # Linear layers of shape IO or multihead linear
squared_norm = jnp.sum(numerics.abs_sq(x), axis=0, keepdims=True)
elif x.ndim == 4: # Conv kernels of shape HWIO
squared_norm = jnp.sum(numerics.abs_sq(x), axis=(0, 1, 2), keepdims=True)
else:
raise ValueError(
f'Expected parameter with shape in {1, 2, 3, 4}, got {x.shape}.')
chex.assert_is_broadcastable(squared_norm.shape, x.shape)
return jnp.broadcast_to(jnp.sqrt(squared_norm), x.shape)
def unitwise_clip(g_norm: chex.Array,
max_norm: chex.Array,
grad: chex.Array,
div_eps: float = 1e-6) -> chex.Array:
"""Applies gradient clipping unit-wise."""
# This little max(., div_eps) is distinct from the normal eps and just
# prevents division by zero. It technically should be impossible to engage.
clipped_grad = grad * (max_norm / jnp.maximum(g_norm, div_eps))
chex.assert_equal_shape((g_norm, max_norm, grad, clipped_grad))
return jnp.where(g_norm < max_norm, grad, clipped_grad)
AdaptiveGradClipState = base.EmptyState
def adaptive_grad_clip(clipping: float,
eps: float = 1e-3) -> base.GradientTransformation:
"""Clips updates to be at most ``clipping * parameter_norm``, unit-wise.
References:
[Brock, Smith, De, Simonyan 2021] High-Performance Large-Scale Image
Recognition Without Normalization. (https://arxiv.org/abs/2102.06171)
Args:
clipping: The maximum allowed ratio of update norm to parameter norm.
eps: An epsilon term to prevent clipping of zero-initialized params.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return AdaptiveGradClipState()
def update_fn(updates, state, params):
if params is None:
raise ValueError(base.NO_PARAMS_MSG)
g_norm, p_norm = jax.tree_util.tree_map(unitwise_norm, (updates, params))
# Maximum allowable norm.
max_norm = jax.tree_util.tree_map(
lambda x: clipping * jnp.maximum(x, eps), p_norm)
# If grad norm > clipping * param_norm, rescale.
updates = jax.tree_util.tree_map(unitwise_clip, g_norm, max_norm, updates)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
| optax-master | optax/_src/clipping.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Standard losses used in optimisation.
We provide implementations of the most canonical losses used in deep
learning. These operate transparently on batches, and do not perform any
reduction over the batch dimensions, leaving it to the user to, for instance,
mean or sum losses across batch dimensions.
"""
from typing import Optional, Tuple
import chex
import jax
import jax.numpy as jnp
from optax._src import utils
def squared_error(
predictions: chex.Array,
targets: Optional[chex.Array] = None,
) -> chex.Array:
"""Calculates the squared error for a set of predictions.
Mean Squared Error can be computed as squared_error(a, b).mean().
Note: l2_loss = 0.5 * squared_error, where the 0.5 term is standard in
"Pattern Recognition and Machine Learning" by Bishop, but not
"The Elements of Statistical Learning" by Tibshirani.
References:
[Chris Bishop, 2006](https://bit.ly/3eeP0ga)
Args:
predictions: a vector of arbitrary shape `[...]`.
targets: a vector with shape broadcastable to that of `predictions`;
if not provided then it is assumed to be a vector of zeros.
Returns:
elementwise squared differences, with same shape as `predictions`.
"""
chex.assert_type([predictions], float)
if targets is not None:
# Avoid broadcasting logic for "-" operator.
chex.assert_equal_shape((predictions, targets))
errors = predictions - targets if targets is not None else predictions
return errors ** 2
def l2_loss(
predictions: chex.Array,
targets: Optional[chex.Array] = None,
) -> chex.Array:
"""Calculates the L2 loss for a set of predictions.
Note: the 0.5 term is standard in "Pattern Recognition and Machine Learning"
by Bishop, but not "The Elements of Statistical Learning" by Tibshirani.
References:
[Chris Bishop, 2006](https://bit.ly/3eeP0ga)
Args:
predictions: a vector of arbitrary shape `[...]`.
targets: a vector with shape broadcastable to that of `predictions`;
if not provided then it is assumed to be a vector of zeros.
Returns:
elementwise squared differences, with same shape as `predictions`.
"""
return 0.5 * squared_error(predictions, targets)
def huber_loss(
predictions: chex.Array,
targets: Optional[chex.Array] = None,
delta: float = 1.) -> chex.Array:
"""Huber loss, similar to L2 loss close to zero, L1 loss away from zero.
If gradient descent is applied to the `huber loss`, it is equivalent to
clipping gradients of an `l2_loss` to `[-delta, delta]` in the backward pass.
References:
[Huber, 1964](www.projecteuclid.org/download/pdf_1/euclid.aoms/1177703732)
Args:
predictions: a vector of arbitrary shape `[...]`.
targets: a vector with shape broadcastable to that of `predictions`;
if not provided then it is assumed to be a vector of zeros.
delta: the bounds for the huber loss transformation, defaults at 1.
Returns:
elementwise huber losses, with the same shape of `predictions`.
"""
chex.assert_type([predictions], float)
errors = (predictions - targets) if (targets is not None) else predictions
# 0.5 * err^2 if |err| <= d
# 0.5 * d^2 + d * (|err| - d) if |err| > d
abs_errors = jnp.abs(errors)
quadratic = jnp.minimum(abs_errors, delta)
# Same as max(abs_x - delta, 0) but avoids potentially doubling gradient.
linear = abs_errors - quadratic
return 0.5 * quadratic ** 2 + delta * linear
def smooth_labels(
labels: chex.Array,
alpha: float,
) -> jnp.ndarray:
"""Apply label smoothing.
Label smoothing is often used in combination with a cross-entropy loss.
Smoothed labels favour small logit gaps, and it has been shown that this can
provide better model calibration by preventing overconfident predictions.
References:
[Müller et al, 2019](https://arxiv.org/pdf/1906.02629.pdf)
Args:
labels: One hot labels to be smoothed.
alpha: The smoothing factor.
Returns:
a smoothed version of the one hot input labels.
"""
chex.assert_type([labels], float)
num_categories = labels.shape[-1]
return (1.0 - alpha) * labels + alpha / num_categories
def sigmoid_binary_cross_entropy(logits, labels):
"""Computes element-wise sigmoid cross entropy given logits and labels.
This function can be used for binary or multiclass classification (where each
class is an independent binary prediction and different classes are not
mutually exclusive e.g. predicting that an image contains both a cat
and a dog.)
Because this function is overloaded, please ensure your `logits` and `labels`
are compatible with each other. If you're passing in binary `labels` (values
in {0, 1}), ensure your `logits` correspond to class 1 only. If you're
passing in per-class target probabilities or one-hot `labels`, please ensure
your `logits` are also multiclass. Be particularly careful if you're relying
on implicit broadcasting to reshape `logits` or `labels`.
References:
[Goodfellow et al, 2016](http://www.deeplearningbook.org/contents/prob.html)
Args:
logits: Each element is the unnormalized log probability of a binary
prediction. See note about compatibility with `labels` above.
labels: Binary labels whose values are {0,1} or multi-class target
probabilities. See note about compatibility with `logits` above.
Returns:
cross entropy for each binary prediction, same shape as `logits`.
"""
chex.assert_type([logits], float)
labels = labels.astype(logits.dtype)
log_p = jax.nn.log_sigmoid(logits)
# log(1 - sigmoid(x)) = log_sigmoid(-x), the latter more numerically stable
log_not_p = jax.nn.log_sigmoid(-logits)
return -labels * log_p - (1. - labels) * log_not_p
def softmax_cross_entropy(
logits: chex.Array,
labels: chex.Array,
) -> chex.Array:
"""Computes the softmax cross entropy between sets of logits and labels.
Measures the probability error in discrete classification tasks in which
the classes are mutually exclusive (each entry is in exactly one class).
For example, each CIFAR-10 image is labeled with one and only one label:
an image can be a dog or a truck, but not both.
References:
[Goodfellow et al, 2016](http://www.deeplearningbook.org/contents/prob.html)
Args:
logits: Unnormalized log probabilities, with shape `[..., num_classes]`.
labels: Valid probability distributions (non-negative, sum to 1), e.g a
one hot encoding specifying the correct class for each input;
must have a shape broadcastable to `[..., num_classes]`.
Returns:
cross entropy between each prediction and the corresponding target
distributions, with shape `[...]`.
"""
chex.assert_type([logits], float)
return -jnp.sum(labels * jax.nn.log_softmax(logits, axis=-1), axis=-1)
def softmax_cross_entropy_with_integer_labels(
logits: chex.Array,
labels: chex.Array,
) -> chex.Array:
"""Computes softmax cross entropy between sets of logits and integer labels.
Measures the probability error in discrete classification tasks in which
the classes are mutually exclusive (each entry is in exactly one class).
For example, each CIFAR-10 image is labeled with one and only one label:
an image can be a dog or a truck, but not both.
References:
[Goodfellow et al, 2016](http://www.deeplearningbook.org/contents/prob.html)
Args:
logits: Unnormalized log probabilities, with shape `[..., num_classes]`.
labels: Integers specifying the correct class for each input, with shape
`[...]`.
Returns:
Cross entropy between each prediction and the corresponding target
distributions, with shape `[...]`.
"""
chex.assert_type([logits], float)
chex.assert_type([labels], int)
# This is like jnp.take_along_axis(jax.nn.log_softmax(...), ...) except that
# we avoid subtracting the normalizer from all values, just from the values
# for the correct labels.
logits_max = jnp.max(logits, axis=-1, keepdims=True)
logits -= jax.lax.stop_gradient(logits_max)
label_logits = jnp.take_along_axis(logits, labels[..., None], axis=-1)[..., 0]
log_normalizers = jnp.log(jnp.sum(jnp.exp(logits), axis=-1))
return log_normalizers - label_logits
def cosine_similarity(
predictions: chex.Array,
targets: chex.Array,
epsilon: float = 0.,
) -> chex.Array:
r"""Computes the cosine similarity between targets and predictions.
The cosine **similarity** is a measure of similarity between vectors defined
as the cosine of the angle between them, which is also the inner product of
those vectors normalized to have unit norm.
References:
[Wikipedia, 2021](https://en.wikipedia.org/wiki/Cosine_similarity)
Args:
predictions: The predicted vectors, with shape `[..., dim]`.
targets: Ground truth target vectors, with shape `[..., dim]`.
epsilon: minimum norm for terms in the denominator of the cosine similarity.
Returns:
cosine similarity measures, with shape `[...]`.
"""
chex.assert_type([predictions, targets], float)
# vectorize norm fn, to treat all dimensions except the last as batch dims.
batched_norm_fn = jnp.vectorize(
utils.safe_norm, signature='(k)->()', excluded={1})
# normalise the last dimension of targets and predictions.
unit_targets = targets / jnp.expand_dims(
batched_norm_fn(targets, epsilon), axis=-1)
unit_predictions = predictions / jnp.expand_dims(
batched_norm_fn(predictions, epsilon), axis=-1)
# return cosine similarity.
return jnp.sum(unit_targets * unit_predictions, axis=-1)
def cosine_distance(
predictions: chex.Array,
targets: chex.Array,
epsilon: float = 0.,
) -> chex.Array:
r"""Computes the cosine distance between targets and predictions.
The cosine **distance**, implemented here, measures the **dissimilarity**
of two vectors as the opposite of cosine **similarity**: `1 - cos(\theta)`.
References:
[Wikipedia, 2021](https://en.wikipedia.org/wiki/Cosine_similarity)
Args:
predictions: The predicted vectors, with shape `[..., dim]`.
targets: Ground truth target vectors, with shape `[..., dim]`.
epsilon: minimum norm for terms in the denominator of the cosine similarity.
Returns:
cosine distances, with shape `[...]`.
"""
chex.assert_type([predictions, targets], float)
# cosine distance = 1 - cosine similarity.
return 1. - cosine_similarity(predictions, targets, epsilon)
def log_cosh(
predictions: chex.Array,
targets: Optional[chex.Array] = None,
) -> chex.Array:
"""Calculates the log-cosh loss for a set of predictions.
log(cosh(x)) is approximately `(x**2) / 2` for small x and `abs(x) - log(2)`
for large x. It is a twice differentiable alternative to the Huber loss.
References:
[Chen et al, 2019](https://openreview.net/pdf?id=rkglvsC9Ym)
Args:
predictions: a vector of arbitrary shape `[...]`.
targets: a vector with shape broadcastable to that of `predictions`;
if not provided then it is assumed to be a vector of zeros.
Returns:
the log-cosh loss, with same shape as `predictions`.
"""
chex.assert_type([predictions], float)
errors = (predictions - targets) if (targets is not None) else predictions
# log(cosh(x)) = log((exp(x) + exp(-x))/2) = log(exp(x) + exp(-x)) - log(2)
return jnp.logaddexp(errors, -errors) - jnp.log(2.0).astype(errors.dtype)
def ctc_loss_with_forward_probs(
logits: chex.Array,
logit_paddings: chex.Array,
labels: chex.Array,
label_paddings: chex.Array,
blank_id: int = 0,
log_epsilon: float = -1e5) -> Tuple[chex.Array, chex.Array, chex.Array]:
r"""Computes CTC loss and CTC forward-probabilities.
The CTC loss is a loss function based on log-likelihoods of the model that
introduces a special blank symbol :math:`\phi` to represent variable-length
output sequences.
Forward probabilities returned by this function, as auxiliary results, are
grouped into two part: blank alpha-probability and non-blank alpha
probability. Those are defined as follows:
.. math::
\alpha_{\mathrm{BLANK}}(t, n) =
\sum_{\pi_{1:t-1}} p(\pi_t = \phi | \pi_{1:t-1}, y_{1:n-1}, \cdots), \\
\alpha_{\mathrm{LABEL}}(t, n) =
\sum_{\pi_{1:t-1}} p(\pi_t = y_n | \pi_{1:t-1}, y_{1:n-1}, \cdots).
Here, :math:`\pi` denotes the alignment sequence in the reference
[Graves et al, 2006] that is blank-inserted representations of ``labels``.
The return values are the logarithms of the above probabilities.
References:
[Graves et al, 2006](https://dl.acm.org/doi/abs/10.1145/1143844.1143891)
Args:
logits: (B, T, K)-array containing logits of each class where B denotes
the batch size, T denotes the max time frames in ``logits``, and K
denotes the number of classes including a class for blanks.
logit_paddings: (B, T)-array. Padding indicators for ``logits``. Each
element must be either 1.0 or 0.0, and ``logitpaddings[b, t] == 1.0``
denotes that ``logits[b, t, :]`` are padded values.
labels: (B, N)-array containing reference integer labels where N denotes
the max time frames in the label sequence.
label_paddings: (B, N)-array. Padding indicators for ``labels``. Each
element must be either 1.0 or 0.0, and ``labelpaddings[b, n] == 1.0``
denotes that ``labels[b, n]`` is a padded label. In the current
implementation, ``labels`` must be right-padded, i.e. each row
``labelpaddings[b, :]`` must be repetition of zeroes, followed by
repetition of ones.
blank_id: Id for blank token. ``logits[b, :, blank_id]`` are used as
probabilities of blank symbols.
log_epsilon: Numerically-stable approximation of log(+0).
Returns:
A tuple ``(loss_value, logalpha_blank, logalpha_nonblank)``. Here,
``loss_value`` is a (B,)-array containing the loss values for each sequence
in the batch, ``logalpha_blank`` and ``logalpha_nonblank`` are
(T, B, N+1)-arrays where the (t, b, n)-th element denotes
\log \alpha_B(t, n) and \log \alpha_L(t, n), respectively, for ``b``-th
sequence in the batch.
"""
chex.assert_rank(logits, 3)
chex.assert_rank(labels, 2)
batchsize, unused_maxinputlen, num_classes = logits.shape
batchsize_of_labels, maxlabellen = labels.shape
chex.assert_equal(batchsize, batchsize_of_labels)
chex.assert_equal(labels.shape, label_paddings.shape)
chex.assert_equal(logits.shape[:2], logit_paddings.shape)
logprobs = jax.nn.log_softmax(logits)
labellens = maxlabellen - jnp.sum(label_paddings, axis=1).astype(jnp.int32)
# repeat[b, n] == 1.0 when label[b, n] == label[b, n+1].
repeat = (labels[:, :-1] == labels[:, 1:]).astype(jnp.float32)
repeat = jnp.pad(repeat, ((0, 0), (0, 1)))
logprobs_phi = logprobs[:, :, blank_id:blank_id + 1] # [B, T, 1]
logprobs_phi = jnp.transpose(logprobs_phi, (1, 0, 2)) # [T, B, 1]
one_hot = jax.nn.one_hot(labels, num_classes=num_classes) # [B, N, K]
logprobs_emit = jnp.einsum('btk,bnk->btn', logprobs, one_hot)
logprobs_emit = jnp.transpose(logprobs_emit, (1, 0, 2)) # [T, B, N]
logalpha_phi_init = jnp.ones(
(batchsize, maxlabellen + 1)) * log_epsilon # [B, N]
logalpha_phi_init = logalpha_phi_init.at[:, 0].set(0.0)
logalpha_emit_init = jnp.ones((batchsize, maxlabellen)) * log_epsilon
def update_phi_score(phi, added_score):
# Update `phi[:, 1:]`` with adding `added_score` in log space.
return jnp.concatenate(
[phi[:, :1], jnp.logaddexp(phi[:, 1:], added_score)], axis=-1)
def loop_body(prev, x):
prev_phi, prev_emit = prev
# emit-to-phi epsilon transition, except if the next label is repetition
prev_phi_orig = prev_phi
prev_phi = update_phi_score(prev_phi, prev_emit + log_epsilon * repeat)
logprob_emit, logprob_phi, pad = x
# phi-to-emit transition
next_emit = jnp.logaddexp(prev_phi[:, :-1] + logprob_emit,
prev_emit + logprob_emit)
# self-loop transition
next_phi = prev_phi + logprob_phi
# emit-to-phi blank transition only when the next label is repetition
next_phi = update_phi_score(
next_phi, prev_emit + logprob_phi + log_epsilon * (1.0 - repeat))
pad = pad.reshape((batchsize, 1))
next_emit = pad * prev_emit + (1.0 - pad) * next_emit
next_phi = pad * prev_phi_orig + (1.0 - pad) * next_phi
return (next_phi, next_emit), (next_phi, next_emit)
xs = (logprobs_emit, logprobs_phi, logit_paddings.transpose((1, 0)))
_, (logalpha_phi,
logalpha_emit) = jax.lax.scan(loop_body,
(logalpha_phi_init, logalpha_emit_init), xs)
# last row needs to be updated with the last epsilon transition
logalpha_phi_last = update_phi_score(logalpha_phi[-1], logalpha_emit[-1])
logalpha_phi = logalpha_phi.at[-1].set(logalpha_phi_last)
# extract per_seq_loss
one_hot = jax.nn.one_hot(labellens, num_classes=maxlabellen + 1) # [B, N+1]
per_seq_loss = -jnp.einsum('bn,bn->b', logalpha_phi_last, one_hot) # pylint:disable=invalid-unary-operand-type
return per_seq_loss, logalpha_phi, logalpha_emit
def ctc_loss(logits: chex.Array,
logit_paddings: chex.Array,
labels: chex.Array,
label_paddings: chex.Array,
blank_id: int = 0,
log_epsilon: float = -1e5) -> chex.Array:
"""Computes CTC loss.
See docstring for ``ctc_loss_with_forward_probs`` for details.
Args:
logits: (B, T, K)-array containing logits of each class where B denotes
the batch size, T denotes the max time frames in ``logits``, and K
denotes the number of classes including a class for blanks.
logit_paddings: (B, T)-array. Padding indicators for ``logits``. Each
element must be either 1.0 or 0.0, and ``logitpaddings[b, t] == 1.0``
denotes that ``logits[b, t, :]`` are padded values.
labels: (B, N)-array containing reference integer labels where N denotes
the max time frames in the label sequence.
label_paddings: (B, N)-array. Padding indicators for ``labels``. Each
element must be either 1.0 or 0.0, and ``labelpaddings[b, n] == 1.0``
denotes that ``labels[b, n]`` is a padded label. In the current
implementation, ``labels`` must be right-padded, i.e. each row
``labelpaddings[b, :]`` must be repetition of zeroes, followed by
repetition of ones.
blank_id: Id for blank token. ``logits[b, :, blank_id]`` are used as
probabilities of blank symbols.
log_epsilon: Numerically-stable approximation of log(+0).
Returns:
(B,)-array containing loss values for each sequence in the batch.
"""
per_seq_loss, _, _ = ctc_loss_with_forward_probs(
logits, logit_paddings, labels, label_paddings,
blank_id=blank_id, log_epsilon=log_epsilon)
return per_seq_loss
def convex_kl_divergence(
log_predictions: chex.Array, targets: chex.Array
) -> chex.Array:
"""Computes a convex version of the Kullback-Leibler divergence loss.
Measures the information gain achieved if target probability distribution
would be used instead of predicted probability distribution.
This version is jointly convex in p (targets) and q (log_predictions).
References:
[Kullback, Leibler, 1951](https://www.jstor.org/stable/2236703)
Args:
log_predictions: Probabilities of predicted distribution with shape [...,
dim]. Expected to be in the log-space to avoid underflow.
targets: Probabilities of target distribution with shape [..., dim].
Expected to be strictly positive.
Returns:
Kullback-Leibler divergence of predicted distribution from target
distribution with shape [...].
"""
return kl_divergence(log_predictions, targets) + jnp.sum(
jnp.exp(log_predictions) - targets, axis=-1
)
def kl_divergence(
log_predictions: chex.Array, targets: chex.Array
) -> chex.Array:
"""Computes the Kullback-Leibler divergence (relative entropy) loss.
Measures the information gain achieved if target probability distribution
would be used instead of predicted probability distribution.
References:
[Kullback, Leibler, 1951](https://www.jstor.org/stable/2236703)
Args:
log_predictions: Probabilities of predicted distribution with shape [...,
dim]. Expected to be in the log-space to avoid underflow.
targets: Probabilities of target distribution with shape [..., dim].
Expected to be strictly positive.
Returns:
Kullback-Leibler divergence of predicted distribution from target
distribution with shape [...].
"""
chex.assert_type([log_predictions, targets], float)
loss = targets * (
jnp.where(targets == 0, 0, jnp.log(targets)) - log_predictions
)
return jnp.sum(loss, axis=-1)
def kl_divergence_with_log_targets(log_predictions: chex.Array,
log_targets: chex.Array) -> chex.Array:
"""Computes the Kullback-Leibler divergence (relative entropy) loss.
Version of kl_div_loss where targets are given in log-space.
Args:
log_predictions: Probabilities of predicted distribution with shape
[..., dim]. Expected to be in the log-space to avoid underflow.
log_targets: Probabilities of target distribution with shape [..., dim].
Expected to be in the log-space.
Returns:
Kullback-Leibler divergence of predicted distribution from target
distribution with shape [...].
"""
chex.assert_type([log_predictions, log_targets], float)
loss = jnp.exp(log_targets) * (log_targets - log_predictions)
return jnp.sum(loss, axis=-1)
def hinge_loss(predictor_outputs: chex.Array,
targets: chex.Array) -> chex.Array:
"""Computes the hinge loss for binary classification.
Args:
predictor_outputs: Outputs of the decision function.
targets: Target values. Target values should be strictly in the set {-1, 1}.
Returns:
Binary Hinge Loss.
"""
return jnp.maximum(0, 1 - predictor_outputs * targets)
def poly_loss_cross_entropy(
logits: chex.Array, labels: chex.Array, epsilon: float = 2.0
) -> chex.Array:
r"""Computes PolyLoss between logits and labels.
The PolyLoss is a loss function that decomposes commonly
used classification loss functions into a series of weighted
polynomial bases. It is inspired by the Taylor expansion of
cross-entropy loss and focal loss in the bases of :math:`(1 − P_t)^j`.
.. math::
L_{Poly} = \sum_1^\infty \alpha_j \cdot (1 - P_t)^j \\
L_{Poly-N} = (\epsilon_1 + 1) \cdot (1 - P_t) + \ldots + \\
(\epsilon_N + \frac{1}{N}) \cdot (1 - P_t)^N +
\frac{1}{N + 1} \cdot (1 - P_t)^{N + 1} + \ldots = \\
- \log(P_t) + \sum_{j = 1}^N \epsilon_j \cdot (1 - P_t)^j
This function provides a simplified version of :math:`L_{Poly-N}`
with only the coefficient of the first polynomial term being changed.
References:
[Zhaoqi Leng et al, 2022](https://arxiv.org/pdf/2204.12511.pdf)
Args:
logits: Unnormalized log probabilities, with shape `[..., num_classes]`.
labels: Valid probability distributions (non-negative, sum to 1), e.g. a
one hot encoding specifying the correct class for each input;
must have a shape broadcastable to `[..., num_classes]`.
epsilon: The coefficient of the first polynomial term.
According to the paper, the following values are recommended:
- For the ImageNet 2d image classification, epsilon = 2.0.
- For the 2d Instance Segmentation and object detection, epsilon = -1.0.
- It is also recommended to adjust this value based on the task, e.g. by
using grid search.
Returns:
Poly loss between each prediction and the corresponding target
distributions, with shape `[...]`.
"""
chex.assert_type([logits, labels], float)
one_minus_pt = jnp.sum(labels * (1 - jax.nn.softmax(logits)), axis=-1)
cross_entropy = softmax_cross_entropy(logits=logits, labels=labels)
return cross_entropy + epsilon * one_minus_pt
| optax-master | optax/_src/loss.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
r"""Stochastic Monte Carlo gradient estimators.
Utility functions to approximate gradients of the form using Monte Carlo
estimation:
\nabla_{\theta} E_{p(x; \theta)} f(x)
Here f is assumed to have no dependence on the parameters theta - if f has
dependence on theta, the functions below need to be called with `stop_grad(f)`
and the chain rule needs to be applied outside these functions in order
to obtain unbiased gradient.
For more details, see:
S. Mohamed, M. Rosca, M. Figurnov, A Mnih.
Monte Carlo Gradient Estimation in Machine Learning. JMLR, 2020.
"""
import math
from typing import Any, Callable, Sequence
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import base
from optax._src import utils
def score_function_jacobians(
function: Callable[[chex.Array], float],
params: base.Params,
dist_builder: Callable[..., Any],
rng: chex.PRNGKey,
num_samples: int) -> Sequence[chex.Array]:
r"""Score function gradient estimation.
Approximates:
\nabla_{\theta} E_{p(x; \theta)} f(x)
With:
E_{p(x; \theta)} f(x) \nabla_{\theta} \log p(x; \theta)
Requires: p to be differentiable wrt to theta. Applicable to both continuous
and discrete random variables. No requirements on f.
Args:
function: Function f(x) for which to estimate grads_{params} E_dist f(x).
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
params: A tuple of jnp arrays.
The parameters for which to construct the distribution.
dist_builder: a constructor which builds a distribution given the input
parameters specified by params. `dist_builder(params)` should return a
valid distribution.
rng: a PRNGKey key.
num_samples: Int, the number of samples used to compute the grads.
Returns:
A tuple of size `params`, each element is `num_samples x param.shape`
jacobian vector containing the estimates of the gradients obtained for
each sample.
The mean of this vector is the gradient wrt to parameters that can be used
for learning. The entire jacobian vector can be used to assess estimator
variance.
"""
def surrogate(params):
dist = dist_builder(*params)
one_sample_surrogate_fn = lambda x: function(x) * dist.log_prob(x)
samples = jax.lax.stop_gradient(dist.sample((num_samples,), seed=rng))
# We vmap the function application over samples - this ensures that the
# function we use does not have to be vectorized itself.
return jax.vmap(one_sample_surrogate_fn)(samples)
return jax.jacfwd(surrogate)(params)
def pathwise_jacobians(
function: Callable[[chex.Array], float],
params: base.Params,
dist_builder: Callable[..., Any],
rng: chex.PRNGKey,
num_samples: int) -> Sequence[chex.Array]:
r"""Pathwise gradient estimation.
Approximates:
\nabla_{\theta} E_{p(x; \theta)} f(x)
With:
E_{p(\epsilon)} \nabla_{\theta} f(g(\epsilon, \theta))
where x = g(\epsilon, \theta). g depends on the distribution p.
Requires: p to be reparametrizable and the reparametrization to be implemented
in tensorflow_probability. Applicable to continuous random variables.
f needs to be differentiable.
Args:
function: Function f(x) for which to estimate grads_{params} E_dist f(x).
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
params: A tuple of jnp arrays.
The parameters for which to construct the distribution.
dist_builder: a constructor which builds a distribution given the input
parameters specified by params. `dist_builder(params)` should return a
valid distribution.
rng: a PRNGKey key.
num_samples: Int, the number of samples used to compute the grads.
Returns:
A tuple of size `params`, each element is `num_samples x param.shape`
jacobian vector containing the estimates of the gradients obtained for
each sample.
The mean of this vector is the gradient wrt to parameters that can be used
for learning. The entire jacobian vector can be used to assess estimator
variance.
"""
def surrogate(params):
# We vmap the function application over samples - this ensures that the
# function we use does not have to be vectorized itself.
dist = dist_builder(*params)
return jax.vmap(function)(dist.sample((num_samples,), seed=rng))
return jax.jacfwd(surrogate)(params)
def measure_valued_jacobians(
function: Callable[[chex.Array], float],
params: base.Params,
dist_builder: Callable[..., Any],
rng: chex.PRNGKey,
num_samples: int,
coupling: bool = True) -> Sequence[chex.Array]:
r"""Measure valued gradient estimation.
Approximates:
\nabla_{\theta} E_{p(x; \theta)} f(x)
With:
1./ c (E_{p1(x; \theta)} f(x) - E_{p2(x; \theta)} f(x)) where p1 and p2 are
measures which depend on p.
Currently only supports computing gradients of expectations of Gaussian RVs.
Args:
function: Function f(x) for which to estimate grads_{params} E_dist f(x).
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
params: A tuple of jnp arrays.
The parameters for which to construct the distribution.
dist_builder: a constructor which builds a distribution given the input
parameters specified by params. `dist_builder(params)` should return a
valid distribution.
rng: a PRNGKey key.
num_samples: Int, the number of samples used to compute the grads.
coupling: A boolean. Whether or not to use coupling for the positive and
negative samples. Recommended: True, as this reduces variance.
Returns:
A tuple of size `params`, each element is `num_samples x param.shape`
jacobian vector containing the estimates of the gradients obtained for
each sample.
The mean of this vector is the gradient wrt to parameters that can be used
for learning. The entire jacobian vector can be used to assess estimator
variance.
"""
if dist_builder is not utils.multi_normal:
raise ValueError(
'Unsupported distribution builder for measure_valued_jacobians!')
dist = dist_builder(*params)
# Need to apply chain rule for log scale grad (instead of scale grad).
return [
measure_valued_estimation_mean(
function, dist, rng, num_samples, coupling=coupling),
jnp.exp(dist.log_scale) * measure_valued_estimation_std(
function, dist, rng, num_samples, coupling=coupling)]
def measure_valued_estimation_mean(
function: Callable[[chex.Array], float],
dist: Any,
rng: chex.PRNGKey,
num_samples: int,
coupling: bool = True) -> chex.Array:
"""Measure valued grads of a Gaussian expectation of `function` wrt the mean.
Args:
function: Function f(x) for which to estimate grads_{mean} E_dist f(x).
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
dist: a distribution on which we can call `sample`.
rng: a PRNGKey key.
num_samples: Int, the number of samples used to compute the grads.
coupling: A boolean. Whether or not to use coupling for the positive and
negative samples. Recommended: True, as this reduces variance.
Returns:
A `num_samples x D` vector containing the estimates of the gradients
obtained for each sample. The mean of this vector can be used to update
the mean parameter. The entire vector can be used to assess estimator
variance.
"""
mean, log_std = dist.params
std = jnp.exp(log_std)
dist_samples = dist.sample((num_samples,), seed=rng)
pos_rng, neg_rng = jax.random.split(rng)
pos_sample = jax.random.weibull_min(
pos_rng, scale=math.sqrt(2.), concentration=2., shape=dist_samples.shape)
if coupling:
neg_sample = pos_sample
else:
neg_sample = jax.random.weibull_min(
neg_rng,
scale=math.sqrt(2.),
concentration=2.,
shape=dist_samples.shape)
# N x D
positive_diag = mean + std * pos_sample
# N x D
negative_diag = mean - std * neg_sample
# NOTE: you can sample base samples here if you use the same rng
# Duplicate the D dimension - N x D x D.
base_dist_samples = utils.tile_second_to_last_dim(dist_samples)
positive = utils.set_diags(base_dist_samples, positive_diag)
negative = utils.set_diags(base_dist_samples, negative_diag)
c = np.sqrt(2 * np.pi) * std # D
# Apply function. We apply the function to each element of N x D x D.
# We apply a function that takes a sample and returns one number, so the
# output will be N x D (which is what we want, batch by dimension).
# We apply a function in parallel to the batch.
# Broadcast the division.
vmaped_function = jax.vmap(jax.vmap(function, 1, 0))
grads = (vmaped_function(positive) - vmaped_function(negative)) / c
chex.assert_shape(grads, (num_samples,) + std.shape)
return grads
def measure_valued_estimation_std(
function: Callable[[chex.Array], float],
dist: Any,
rng: chex.PRNGKey,
num_samples: int,
coupling: bool = True) -> chex.Array:
"""Measure valued grads of a Gaussian expectation of `function` wrt the std.
Args:
function: Function f(x) for which to estimate grads_{std} E_dist f(x).
The function takes in one argument (a sample from the distribution) and
returns a floating point value.
dist: a distribution on which we can call `sample`.
rng: a PRNGKey key.
num_samples: Int, the number of samples used to compute the grads.
coupling: A boolean. Whether or not to use coupling for the positive and
negative samples. Recommended: True, as this reduces variance.
Returns:
A `num_samples x D` vector containing the estimates of the gradients
obtained for each sample. The mean of this vector can be used to update
the scale parameter. The entire vector can be used to assess estimator
variance.
"""
mean, log_std = dist.params
std = jnp.exp(log_std)
dist_samples = dist.sample((num_samples,), seed=rng)
pos_rng, neg_rng = jax.random.split(rng)
# The only difference between mean and std gradients is what we sample.
pos_sample = jax.random.double_sided_maxwell(
pos_rng, loc=0.0, scale=1.0, shape=dist_samples.shape)
if coupling:
unif_rvs = jax.random.uniform(neg_rng, dist_samples.shape)
neg_sample = unif_rvs * pos_sample
else:
neg_sample = jax.random.normal(neg_rng, dist_samples.shape)
# Both need to be positive in the case of the scale.
# N x D
positive_diag = mean + std * pos_sample
# N x D
negative_diag = mean + std * neg_sample
# NOTE: you can sample base samples here if you use the same rng
# Duplicate the D dimension - N x D x D.
base_dist_samples = utils.tile_second_to_last_dim(dist_samples)
positive = utils.set_diags(base_dist_samples, positive_diag)
negative = utils.set_diags(base_dist_samples, negative_diag)
# Different C for the scale
c = std # D
# Apply function. We apply the function to each element of N x D x D.
# We apply a function that takes a sample and returns one number, so the
# output will be N x D (which is what we want, batch by dimension).
# We apply a function in parallel to the batch.
# Broadcast the division.
vmaped_function = jax.vmap(jax.vmap(function, 1, 0))
grads = (vmaped_function(positive) - vmaped_function(negative)) / c
chex.assert_shape(grads, (num_samples,) + std.shape)
return grads
| optax-master | optax/_src/stochastic_gradient_estimators.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for optax._src.linear_algebra."""
from absl.testing import absltest
import jax.numpy as jnp
import numpy as np
from optax._src import linear_algebra
import scipy.stats
class LinearAlgebraTest(absltest.TestCase):
def test_global_norm(self):
flat_updates = jnp.array([2., 4., 3., 5.], dtype=jnp.float32)
nested_updates = dict(
a=jnp.array([2., 4.], dtype=jnp.float32),
b=jnp.array([3., 5.], dtype=jnp.float32))
np.testing.assert_array_equal(
jnp.sqrt(jnp.sum(flat_updates**2)),
linear_algebra.global_norm(nested_updates))
def test_matrix_inverse_pth_root(self):
"""Test for matrix inverse pth root."""
def _gen_symmetrix_matrix(dim, condition_number):
u = scipy.stats.ortho_group.rvs(dim=dim).astype(np.float64)
v = u.T
diag = np.diag([condition_number ** (-i/(dim-1)) for i in range(dim)])
return u @ diag @ v
# Fails after it reaches a particular condition number.
for e in range(2, 12):
condition_number = 10 ** e
ms = _gen_symmetrix_matrix(16, condition_number)
self.assertLess(
np.abs(np.linalg.cond(ms) - condition_number),
condition_number * 0.01)
error = linear_algebra.matrix_inverse_pth_root(
ms.astype(np.float32), 4, ridge_epsilon=1e-12)[1]
if e < 7:
self.assertLess(error, 0.1)
else:
# No guarantee of success after e >= 7
pass
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/linear_algebra_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utility functions for testing."""
from typing import Optional, Tuple, Sequence
import chex
import jax
import jax.numpy as jnp
import jax.scipy.stats.norm as multivariate_normal
from optax._src import linear_algebra
from optax._src import numerics
def tile_second_to_last_dim(a: chex.Array) -> chex.Array:
ones = jnp.ones_like(a)
a = jnp.expand_dims(a, axis=-1)
return jnp.expand_dims(ones, axis=-2) * a
def canonicalize_dtype(
dtype: Optional[chex.ArrayDType]) -> Optional[chex.ArrayDType]:
"""Canonicalise a dtype, skip if None."""
if dtype is not None:
return jax.dtypes.canonicalize_dtype(dtype)
return dtype
def cast_tree(tree: chex.ArrayTree,
dtype: Optional[chex.ArrayDType]) -> chex.ArrayTree:
"""Cast tree to given dtype, skip if None."""
if dtype is not None:
return jax.tree_util.tree_map(lambda t: t.astype(dtype), tree)
else:
return tree
def set_diags(a: chex.Array, new_diags: chex.Array) -> chex.Array:
"""Set the diagonals of every DxD matrix in an input of shape NxDxD.
Args:
a: rank 3, tensor NxDxD.
new_diags: NxD matrix, the new diagonals of each DxD matrix.
Returns:
NxDxD tensor, with the same contents as `a` but with the diagonal
changed to `new_diags`.
"""
a_dim, new_diags_dim = len(a.shape), len(new_diags.shape)
if a_dim != 3:
raise ValueError(f'Expected `a` to be a 3D tensor, got {a_dim}D instead')
if new_diags_dim != 2:
raise ValueError(
f'Expected `new_diags` to be a 2D array, got {new_diags_dim}D instead'
)
n, d, d1 = a.shape
n_diags, d_diags = new_diags.shape
if d != d1:
raise ValueError(
f'Shape mismatch: expected `a.shape` to be {(n, d, d)}, '
f'got {(n, d, d1)} instead'
)
if d_diags != d or n_diags != n:
raise ValueError(
f'Shape mismatch: expected `new_diags.shape` to be {(n, d)}, '
f'got {(n_diags, d_diags)} instead'
)
indices1 = jnp.repeat(jnp.arange(n), d)
indices2 = jnp.tile(jnp.arange(d), n)
indices3 = indices2
# Use numpy array setting
a = a.at[indices1, indices2, indices3].set(new_diags.flatten())
return a
class MultiNormalDiagFromLogScale():
"""MultiNormalDiag which directly exposes its input parameters."""
def __init__(self, loc: chex.Array, log_scale: chex.Array):
self._log_scale = log_scale
self._scale = jnp.exp(log_scale)
self._mean = loc
self._param_shape = jax.lax.broadcast_shapes(
self._mean.shape, self._scale.shape)
def sample(self, shape: Sequence[int],
seed: chex.PRNGKey) -> chex.Array:
sample_shape = tuple(shape) + self._param_shape
return jax.random.normal(
seed, shape=sample_shape) * self._scale + self._mean
def log_prob(self, x: chex.Array) -> chex.Array:
log_prob = multivariate_normal.logpdf(x, loc=self._mean, scale=self._scale)
# Sum over parameter axes.
sum_axis = [-(i + 1) for i in range(len(self._param_shape))]
return jnp.sum(log_prob, axis=sum_axis)
@property
def log_scale(self) -> chex.Array:
return self._log_scale
@property
def params(self) -> Sequence[chex.Array]:
return [self._mean, self._log_scale]
def multi_normal(loc: chex.Array,
log_scale: chex.Array) -> MultiNormalDiagFromLogScale:
return MultiNormalDiagFromLogScale(loc=loc, log_scale=log_scale)
@jax.custom_vjp
def _scale_gradient(inputs: chex.ArrayTree, scale: float) -> chex.ArrayTree:
"""Internal gradient scaling implementation."""
del scale # Only used for the backward pass defined in _scale_gradient_bwd.
return inputs
def _scale_gradient_fwd(inputs: chex.ArrayTree,
scale: float) -> Tuple[chex.ArrayTree, float]:
return _scale_gradient(inputs, scale), scale
def _scale_gradient_bwd(scale: float,
g: chex.ArrayTree) -> Tuple[chex.ArrayTree, None]:
return (jax.tree_util.tree_map(lambda g_: g_ * scale, g), None)
_scale_gradient.defvjp(_scale_gradient_fwd, _scale_gradient_bwd)
def scale_gradient(inputs: chex.ArrayTree, scale: float) -> chex.ArrayTree:
"""Scales gradients for the backwards pass.
Args:
inputs: A nested array.
scale: The scale factor for the gradient on the backwards pass.
Returns:
An array of the same structure as `inputs`, with scaled backward gradient.
"""
# Special case scales of 1. and 0. for more efficiency.
if scale == 1.:
return inputs
elif scale == 0.:
return jax.lax.stop_gradient(inputs)
else:
return _scale_gradient(inputs, scale)
# TODO(b/183800387): remove legacy aliases.
safe_norm = numerics.safe_norm
safe_int32_increment = numerics.safe_int32_increment
global_norm = linear_algebra.global_norm
| optax-master | optax/_src/utils.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Transformation wrappers."""
from typing import Any, Callable, NamedTuple, Optional, Protocol, Tuple, Union
import chex
import jax
from jax import lax
import jax.numpy as jnp
import numpy as np
from optax._src import base
from optax._src import numerics
from optax._src import state_utils
Array = jnp.ndarray
def flatten(
inner: base.GradientTransformation
) -> base.GradientTransformationExtraArgs:
"""Flattens parameters and gradients for init and update of inner transform.
This can reduce the overhead of performing many calculations on lots of small
variables, at the cost of slightly increased memory usage.
Args:
inner: Inner transformation to flatten inputs for.
Returns:
New ``GradientTransformationExtraArgs``
"""
inner = base.with_extra_args_support(inner)
def _flatten(params):
"""Flattens and concatenates all tensors in params to a single vector."""
params, _ = jax.tree_util.tree_flatten(params)
return jnp.concatenate([jnp.reshape(param, [-1]) for param in params])
def _unflatten(updates, flat):
"""Extracts tensors from flat, using the structure and shapes of params."""
updates_flat, treedef = jax.tree_util.tree_flatten(updates)
offsets = []
for update in updates_flat:
size = np.prod(update.shape)
if offsets:
offsets.append(size + offsets[-1])
else:
offsets.append(size)
del offsets[-1]
flat_split = jnp.split(flat, offsets)
reshaped = [
jnp.reshape(flat_update, update.shape)
for flat_update, update in zip(flat_split, updates_flat)
]
return jax.tree_util.tree_unflatten(treedef, reshaped)
def init_fn(params):
flat = _flatten(params)
return inner.init(flat)
def update_fn(updates, state, params=None, **extra_args):
if params is not None:
params = _flatten(params)
updates_flat, state = inner.update(
_flatten(updates), state, params, **extra_args
)
updates = _unflatten(updates, updates_flat)
return updates, state
return base.GradientTransformationExtraArgs(init_fn, update_fn)
class ApplyIfFiniteState(NamedTuple):
"""State of the `GradientTransformation` returned by `apply_if_finite`.
Fields:
notfinite_count: Number of consecutive gradient updates containing an Inf or
a NaN. This number is reset to 0 whenever a gradient update without an Inf
or a NaN is done.
last_finite: Whether or not the last gradient update contained an Inf of a
NaN.
total_notfinite: Total number of gradient updates containing an Inf or
a NaN since this optimizer was initialised. This number is never reset.
inner_state: The state of the inner `GradientTransformation`.
"""
# TODO(optax-dev): notfinite_count, last_finite and inner_state used to be
# annotated as `jnp.array` but that is not a valid annotation (it's a function
# and secretely resolved to `Any`. We should add back typing.
notfinite_count: Any
last_finite: Any
total_notfinite: Any
inner_state: Any
def apply_if_finite(
inner: base.GradientTransformation,
max_consecutive_errors: int
) -> base.GradientTransformation:
"""A function that wraps an optimizer to make it robust to a few NaNs or Infs.
The purpose of this function is to prevent any optimization to happen if the
gradients contain NaNs or Infs. That is, when a NaN of Inf is detected in the
gradients, the wrapped optimizer ignores that gradient update. If the NaNs or
Infs persist after a given number of updates, the wrapped optimizer gives up
and accepts the update.
Args:
inner: Inner transformation to be wrapped.
max_consecutive_errors: Maximum number of consecutive gradient updates
containing NaNs of Infs that the wrapped optimizer will ignore. After
that many ignored updates, the optimizer will give up and accept.
Returns:
New ``GradientTransformationExtraArgs``.
"""
inner = base.with_extra_args_support(inner)
def init(params):
return ApplyIfFiniteState(
notfinite_count=jnp.zeros([], jnp.int32),
last_finite=jnp.array(True, jnp.bool_),
total_notfinite=jnp.zeros([], jnp.int32),
inner_state=inner.init(params))
def update(updates, state, params=None, **extra_args):
inner_state = state.inner_state
flat_updates = jax.tree_util.tree_flatten(updates)[0]
isfinite = jnp.all(
jnp.array([jnp.all(jnp.isfinite(p)) for p in flat_updates]))
notfinite_count = jnp.where(
isfinite, jnp.zeros([], jnp.int32),
numerics.safe_int32_increment(state.notfinite_count))
def do_update(_):
return inner.update(updates, inner_state, params, **extra_args)
def reject_update(_):
return (jax.tree_util.tree_map(jnp.zeros_like, updates), inner_state)
updates, new_inner_state = lax.cond(
jnp.logical_or(isfinite, notfinite_count > max_consecutive_errors),
do_update, reject_update, operand=None)
return updates, ApplyIfFiniteState(
notfinite_count=notfinite_count,
last_finite=isfinite,
total_notfinite=jnp.where(
isfinite, state.total_notfinite,
numerics.safe_int32_increment(state.total_notfinite)),
inner_state=new_inner_state)
return base.GradientTransformationExtraArgs(init=init, update=update)
def _zeros_tree_like(inp_tree: chex.ArrayTree) -> chex.ArrayTree:
return jax.tree_util.tree_map(jnp.zeros_like, inp_tree)
class MultiStepsState(NamedTuple):
"""State of the `GradientTransformation` returned by `MultiSteps`.
Fields:
mini_step: current mini-step counter. At an update, this either increases by
1 or is reset to 0.
gradient_step: gradient step counter. This only increases after enough
mini-steps have been accumulated.
inner_opt_state: the state of the wrapped otpimiser.
acc_grads: accumulated gradients over multiple mini-steps.
skip_state: an arbitrarily nested tree of arrays. This is only
relevant when passing a `should_skip_update_fn` to `MultiSteps`. This
structure will then contain values for debugging and or monitoring. The
actual structure will vary depending on the choice of
`ShouldSkipUpdateFunction`.
"""
mini_step: Array
gradient_step: Array
inner_opt_state: Any
acc_grads: Any
skip_state: chex.ArrayTree = ()
class ShouldSkipUpdateFunction(Protocol):
def __call__(self, updates: base.Updates, gradient_step: Array,
params: Optional[base.Params]) -> Tuple[Array, chex.ArrayTree]:
"""Returns true to indicate that updates should be skipped in a multi-step.
Args:
updates: The updates that the gradient transformation has proposed
to apply
gradient_step: The current gradient step (see
`MultiStepsState.gradient_step`). This can be used for example to reject
large gradients with an annealed maximum allowed gradient norm.
params: If known, the current parameter tree of the function being
transformed.
Returns:
A tuple:
* First element is an array with a single bool indicating whether or not
the updates should be applied.
* Second element is an arbitrarily nested structure of arrays that will be
stored in `MultiStepsState.skip_state`. The structure will vary from
function to function. Debugging info, or values to monitor, can be put
in this structure.
"""
def skip_not_finite(
updates: base.Updates, gradient_step: Array,
params: Optional[base.Params]) -> Tuple[Array, chex.ArrayTree]:
"""Returns True iff any of the `updates` contains an inf or a NaN.
Args:
updates: see `ShouldSkipUpdateFunction`.
gradient_step: see `ShouldSkipUpdateFunction`.
params: see `ShouldSkipUpdateFunction`.
Returns:
A tuple:
* First element is a scalar array of type bool.
* Second element is a dictionary with keys:
- `should_skip`: True iff `updates` contains an inf or a NaN.
- `num_not_finite`: total number of inf and NaN found in `updates`.
"""
del gradient_step, params
all_is_finite = [jnp.sum(jnp.logical_not(jnp.isfinite(p)))
for p in jax.tree_util.tree_leaves(updates)]
num_not_finite = jnp.sum(jnp.array(all_is_finite))
should_skip = num_not_finite > 0
return should_skip, dict(should_skip=should_skip,
num_not_finite=num_not_finite)
def skip_large_updates(updates: base.Updates,
gradient_step: Array,
params: Optional[base.Params],
max_squared_norm: float) -> Tuple[Array, chex.ArrayTree]:
"""Returns True if the global norm square of `updates` is small enough.
Args:
updates: see `ShouldSkipUpdateFunction`.
gradient_step: see `ShouldSkipUpdateFunction`.
params: see `ShouldSkipUpdateFunction`.
max_squared_norm: only updates with a norm square strictly less than this
value will be accepted.
Returns:
A tuple:
* First element is a scalar array of type bool.
* Second element is a dictionary with keys:
- `should_skip`: True iff square norm of `updates` is larger or equal than
`max_squared_norm`.
- `norm_squared`: overall norm square of the `updates`.
"""
del gradient_step, params
norm_sq = jnp.sum(
jnp.array([jnp.sum(p**2) for p in jax.tree_util.tree_leaves(updates)]))
# This will also return True if `norm_sq` is NaN.
should_skip = jnp.logical_not(norm_sq < max_squared_norm)
return should_skip, dict(should_skip=should_skip, norm_squared=norm_sq)
class MultiSteps:
"""An optimizer wrapper to accumulate gradients over multiple steps.
This wrapper collects together the updates passed to its `update` function
over consecutive steps until a given number of scheduled steps is reached.
In each of these intermediate steps, the returned value from the optimizer is
a tree of zeros of the same shape of the updates passed as input.
Once the scheduled number of intermediate 'mini-steps' has been reached, the
gradients accumulated to the current time will be passed to the wrapped
optimizer's update function, (with the inner optimizer's state being updated
appropriately) and then returned to the caller. The wrapper's accumulated
gradients are then set back to zero and the process starts again.
The number of mini-steps per gradient update is controlled by a function, and
it can vary over training. This offers a means of varying batch size over
training.
"""
def __init__(
self,
opt: base.GradientTransformation,
every_k_schedule: Union[int, Callable[[Array], Array]],
use_grad_mean: bool = True,
should_skip_update_fn: Optional[ShouldSkipUpdateFunction] = None):
"""Initialiser.
Args:
opt: the wrapped optimizer.
every_k_schedule: an int or f a function.
* As a function, it returns how many mini-steps should be accumulated
in a single gradient step. Its only argument is the current
gradient step count. By varying the returned value, users can vary the
overall training batch size.
* If an `int`, this is the constant number of mini-steps per gradient
update.
use_grad_mean: if `True` (the default), gradients accumulated over
multiple mini-steps are averaged. Otherwise, they are summed.
should_skip_update_fn: if provided, this function is used to decide when
to accept or reject the updates from a mini-step. When a mini-step is
rejected, the inner state of `MultiSteps` is not updated. In other
words, it is as if this mini-step never happened. For example:
* to ignore updates containing inf or NaN, do
`should_skip_update_fn=skip_not_finite`;
* to ignore updates with a norm square larger then 42, do
`should_skip_update_fn=functools.partial(skip_large_updates,
max_norm_sq=42.)`.
Note that the optimizer's state `MultiStepsState` contains a field
`skip_state` in which debugging and monitoring information returned
by `should_skip_update_fn` is written.
"""
self._opt = base.with_extra_args_support(opt)
if isinstance(every_k_schedule, int):
self._every_k_schedule = lambda step: every_k_schedule
else:
self._every_k_schedule = every_k_schedule
self._use_grad_mean = use_grad_mean
if self._use_grad_mean:
# Use Welford algorithm for numerically stable aggregation of mean.
self._acc_update = (
lambda grad, acc, *, n_acc: acc + (grad - acc) / (n_acc + 1))
else:
self._acc_update = lambda grad, acc, *, n_acc: grad + acc
if should_skip_update_fn is None:
def should_skip_update_fn(*unused_args, **unused_kwargs):
return jnp.array(False, dtype=jnp.bool_), ()
self._should_skip_update_fn = should_skip_update_fn
@property
def inner_opt(self):
return self._opt
def init(self, params: Any) -> MultiStepsState:
"""Builds and returns initial `MultiStepsState`."""
updates = _zeros_tree_like(params)
gradient_step = jnp.zeros([], dtype=jnp.int32)
_, skip_state = self._should_skip_update_fn(updates, gradient_step, params)
init_state = MultiStepsState(
mini_step=jnp.zeros([], dtype=jnp.int32),
gradient_step=gradient_step,
inner_opt_state=self._opt.init(params),
acc_grads=updates,
skip_state=skip_state)
return init_state
def update(self,
updates: base.Updates,
state: MultiStepsState,
params: Optional[base.Params] = None,
**extra_args: Any,
) -> Tuple[base.Updates, MultiStepsState]:
"""Accumulates gradients and proposes non-zero updates every `k_steps`."""
k_steps = self._every_k_schedule(state.gradient_step)
should_skip_update, skip_state = self._should_skip_update_fn(
updates, state.gradient_step, params)
if (should_skip_update.dtype, should_skip_update.shape) != (jnp.bool_, ()):
raise ValueError(
'The `should_skip_update_fn` function should return a boolean scalar '
f'array, but it returned an array of dtype {should_skip_update.dtype}'
f' and shape {should_skip_update.shape}'
)
# Note: we do not enclose variables to allow JAX to re-use memory buffers.
def _final_step(state, params, acc_grads):
final_updates, new_inner_state = self._opt.update(
acc_grads, state.inner_opt_state, params=params, **extra_args)
new_state = MultiStepsState(
mini_step=jnp.zeros([], dtype=jnp.int32),
gradient_step=numerics.safe_int32_increment(state.gradient_step),
inner_opt_state=new_inner_state,
acc_grads=_zeros_tree_like(acc_grads),
skip_state=skip_state)
return final_updates, new_state
def _mid_step(state, params, acc_grads):
updates_shape_dtype, _ = jax.eval_shape(
self._opt.update, acc_grads, state.inner_opt_state, params=params)
mid_updates = jax.tree_util.tree_map(
lambda sd: jnp.zeros(sd.shape, sd.dtype), updates_shape_dtype)
new_state = MultiStepsState(
mini_step=numerics.safe_int32_increment(state.mini_step),
gradient_step=state.gradient_step,
inner_opt_state=state.inner_opt_state,
acc_grads=acc_grads,
skip_state=skip_state)
return mid_updates, new_state
def _do_update(updates, state, params):
acc_grads = jax.tree_util.tree_map(
lambda upd, acc: self._acc_update(upd, acc, n_acc=state.mini_step),
updates, state.acc_grads)
new_updates, new_state = jax.lax.cond(
state.mini_step < k_steps - 1,
_mid_step, _final_step, *(state, params, acc_grads))
return new_updates, new_state
def _skip_update(updates, state, params):
del updates, params
multi_state_when_skip = MultiStepsState(
mini_step=state.mini_step,
gradient_step=state.gradient_step,
inner_opt_state=state.inner_opt_state,
acc_grads=state.acc_grads,
skip_state=skip_state,
)
zero_updates = _zeros_tree_like(state.acc_grads)
return zero_updates, multi_state_when_skip
new_updates, new_state = jax.lax.cond(
should_skip_update, _skip_update, _do_update, *(updates, state, params)
)
return new_updates, new_state
def has_updated(self, state: Union[MultiStepsState, chex.ArrayTree]) -> Array:
# Use `getattr` to bypass pytype checks.
return jnp.logical_and(
getattr(state, 'mini_step') == 0, getattr(state, 'gradient_step') > 0
)
def gradient_transformation(self) -> base.GradientTransformation:
return base.GradientTransformation(init=self.init, update=self.update)
class MaskedState(NamedTuple):
"""Maintains inner transform state for masked transformations."""
inner_state: Any
class MaskedNode(NamedTuple):
"""A node used to mask out unspecified parts of a tree.
This node is ignored when mapping functions across the tree e.g. using
`jax.tree_util.tree_map` since it is a container without children. It can
therefore be used to mask out parts of a tree.
"""
def masked(
inner: base.GradientTransformation,
mask: Union[base.PyTree, Callable[[base.Params], base.PyTree]]
) -> base.GradientTransformationExtraArgs:
"""Mask updates so only some are transformed, the rest are passed through.
For example, it is common to skip weight decay for BatchNorm scale and all
bias parameters. In many networks, these are the only parameters with only
one dimension. So, you may create a mask function to mask these out as
follows::
mask_fn = lambda p: jax.tree_util.tree_map(lambda x: x.ndim != 1, p)
weight_decay = optax.masked(optax.add_decayed_weights(0.001), mask_fn)
You may alternatively create the mask pytree upfront::
mask = jax.tree_util.tree_map(lambda x: x.ndim != 1, params)
weight_decay = optax.masked(optax.add_decayed_weights(0.001), mask)
For the ``inner`` transform, state will only be stored for the parameters that
have a mask value of ``True``.
Note that, when using ``tree_map_params``, it may be required to pass the
argument `is_leaf=lambda v: isinstance(v, optax.MaskedNode)`, if the tree
map needs to take additional arguments with the same shape as the original
input tree.
Args:
inner: Inner transformation to mask.
mask: a PyTree with same structure as (or a prefix of) the params PyTree, or
a Callable that returns such a pytree given the params/updates. The leaves
should be booleans, ``True`` for leaves/subtrees you want to apply the
transformation to, and ``False`` for those you want to skip. The mask must
be static for the gradient transformation to be jit-compilable.
Returns:
New ``GradientTransformationExtraArgs`` wrapping ``inner``.
"""
inner = base.with_extra_args_support(inner)
def mask_pytree(pytree, mask_tree):
return jax.tree_util.tree_map(
lambda m, p: p if m else MaskedNode(), mask_tree, pytree
)
def init_fn(params):
# This is a workaround to make tree_map_params work with masking.
# The API of `masked` takes a mask on construction, instead of at init.
# This means that this gradient transformation can only work for parameter
# trees that match the shape of the mask. Technically this breaks the API
# of optax, and this causes tree_map_params to break. This is because
# tree_map_params calls init with a placeholder in order to detect copies
# of the parameter tree. As a (slightly ugly) workaround, we detect when
# the init is being called by tree_map_params, and pass the placeholder
# down without masking. This is safe, since tree_map_params does not impose
# any particular constraints on the shape of the parameter tree, as long
# as tree_map_params is being called on a tree with the correct structure.
# See wrappers_test for proof that this works!
if isinstance(params, state_utils._ParamsPlaceholder): # pylint:disable=protected-access
return MaskedState(inner_state=inner.init(params))
mask_tree = mask(params) if callable(mask) else mask
masked_params = mask_pytree(params, mask_tree)
return MaskedState(inner_state=inner.init(masked_params))
def update_fn(updates, state, params=None, **extra_args):
mask_tree = mask(updates) if callable(mask) else mask
masked_updates = mask_pytree(updates, mask_tree)
masked_params = None if params is None else mask_pytree(params, mask_tree)
new_masked_updates, new_inner_state = inner.update(
masked_updates, state.inner_state, masked_params, **extra_args)
new_updates = jax.tree_util.tree_map(
lambda m, new_u, old_u: new_u if m else old_u,
mask_tree, new_masked_updates, updates)
return new_updates, MaskedState(inner_state=new_inner_state)
return base.GradientTransformationExtraArgs(init_fn, update_fn)
class MaybeUpdateState(NamedTuple):
"""Maintains inner transform state and adds a step counter."""
inner_state: Any
step: Array
def maybe_update(
inner: base.GradientTransformation,
should_update_fn: Callable[[Array], Array]
) -> base.GradientTransformationExtraArgs:
"""Calls the inner update function only at certain steps.
Creates a transformation wrapper which counts the number of times the `update`
function has been called. This counter is passed to the `should_update_fn` to
decide when to call the inner update function.
When not calling the inner update function, the `updates` and the inner state
are left untouched and just passed through. The step counter is increased
regardless.
Args:
inner: the inner transformation.
should_update_fn: this function takes in a step counter (array of shape []
and dtype int32), and returns a boolean array of shape [].
Returns:
A new ``GradientTransformationExtraArgs``.
"""
inner = base.with_extra_args_support(inner)
def init_fn(params):
return MaybeUpdateState(
inner_state=inner.init(params), step=jnp.zeros([], dtype=jnp.int32))
def update_fn(updates, state, params=None, **extra_args):
def do_update(_):
return inner.update(updates, state.inner_state, params, **extra_args)
def reject_update(_):
return updates, state.inner_state
updates, new_inner_state = lax.cond(
should_update_fn(state.step), do_update, reject_update, operand=None)
return updates, MaybeUpdateState(new_inner_state,
numerics.safe_int32_increment(state.step))
return base.GradientTransformationExtraArgs(init_fn, update_fn)
| optax-master | optax/_src/wrappers.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `update.py`."""
from absl.testing import absltest
import chex
import jax
import jax.numpy as jnp
from optax._src import update
class UpdateTest(chex.TestCase):
@chex.all_variants
def test_apply_updates(self):
params = ({'a': jnp.ones((3, 2))}, jnp.ones((1,)))
grads = jax.tree_util.tree_map(lambda t: 2 * t, params)
exp_params = jax.tree_util.tree_map(lambda t: 3 * t, params)
new_params = self.variant(update.apply_updates)(params, grads)
chex.assert_trees_all_close(
exp_params, new_params, atol=1e-10, rtol=1e-5)
@chex.all_variants
def test_apply_updates_mixed_precision(self):
params = (
{'a': jnp.ones((3, 2), dtype=jnp.bfloat16)},
jnp.ones((1,), dtype=jnp.bfloat16))
grads = jax.tree_util.tree_map(
lambda t: (2 * t).astype(jnp.float32), params)
new_params = self.variant(update.apply_updates)(params, grads)
for leaf in jax.tree_util.tree_leaves(new_params):
assert leaf.dtype == jnp.bfloat16
@chex.all_variants
def test_incremental_update(self):
params_1 = ({'a': jnp.ones((3, 2))}, jnp.ones((1,)))
params_2 = jax.tree_util.tree_map(lambda t: 2 * t, params_1)
exp_params = jax.tree_util.tree_map(lambda t: 1.5 * t, params_1)
new_params = self.variant(
update.incremental_update)(params_2, params_1, 0.5)
chex.assert_trees_all_close(
exp_params, new_params, atol=1e-10, rtol=1e-5)
@chex.all_variants
def test_periodic_update(self):
params_1 = ({'a': jnp.ones((3, 2))}, jnp.ones((1,)))
params_2 = jax.tree_util.tree_map(lambda t: 2 * t, params_1)
update_period = 5
update_fn = self.variant(update.periodic_update)
for j in range(3):
for i in range(1, update_period):
new_params = update_fn(
params_2, params_1, j*update_period+i, update_period)
chex.assert_trees_all_close(
params_1, new_params, atol=1e-10, rtol=1e-5)
new_params = update_fn(
params_2, params_1, (j+1)*update_period, update_period)
chex.assert_trees_all_close(
params_2, new_params, atol=1e-10, rtol=1e-5)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/update_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Gradient transformations."""
import functools
from typing import Any, Callable, NamedTuple, Optional, Union
import chex
import jax
import jax.numpy as jnp
from optax._src import base
from optax._src import clipping
from optax._src import numerics
from optax._src import utils
from optax._src import wrappers
# pylint:disable=no-value-for-parameter
_abs_sq = numerics.abs_sq
class TraceState(NamedTuple):
"""Holds an aggregation of past updates."""
trace: base.Params
def trace(
decay: float,
nesterov: bool = False,
accumulator_dtype: Optional[Any] = None,
) -> base.GradientTransformation:
"""Compute a trace of past updates.
Note: `trace` and `ema` have very similar but distinct updates;
`trace = decay * trace + t`, while `ema = decay * ema + (1-decay) * t`.
Both are frequently found in the optimization literature.
Args:
decay: Decay rate for the trace of past updates.
nesterov: Whether to use Nesterov momentum.
accumulator_dtype: Optional `dtype` to be used for the accumulator; if
`None` then the `dtype` is inferred from `params` and `updates`.
Returns:
A `GradientTransformation` object.
"""
accumulator_dtype = utils.canonicalize_dtype(accumulator_dtype)
def init_fn(params):
return TraceState(
trace=jax.tree_util.tree_map(
lambda t: jnp.zeros_like(t, dtype=accumulator_dtype), params))
def update_fn(updates, state, params=None):
del params
f = lambda g, t: g + decay * t
new_trace = jax.tree_util.tree_map(f, updates, state.trace)
updates = (
jax.tree_util.tree_map(f, updates, new_trace) if nesterov
else new_trace)
new_trace = utils.cast_tree(new_trace, accumulator_dtype)
return updates, TraceState(trace=new_trace)
return base.GradientTransformation(init_fn, update_fn)
def update_moment(updates, moments, decay, order):
"""Compute the exponential moving average of the `order`-th moment."""
return jax.tree_util.tree_map(
lambda g, t: (1 - decay) * (g ** order) + decay * t, updates, moments)
def update_infinity_moment(updates, moments, decay, eps):
"""Compute the exponential moving average of the infinity norm."""
return jax.tree_util.tree_map(
lambda g, t: jnp.maximum(jnp.abs(g) + eps, decay * t), updates, moments)
def update_moment_per_elem_norm(updates, moments, decay, order):
"""Compute the EMA of the `order`-th moment of the element-wise norm."""
def orderth_norm(g):
if jnp.isrealobj(g):
return g ** order
else:
half_order = order / 2
# JAX generates different HLO for int and float `order`
if half_order.is_integer():
half_order = int(half_order)
return _abs_sq(g) ** half_order
return jax.tree_util.tree_map(
lambda g, t: (1 - decay) * orderth_norm(g) + decay * t, updates, moments)
@functools.partial(jax.jit, inline=True)
def bias_correction(moment, decay, count):
"""Performs bias correction. It becomes a no-op as count goes to infinity."""
# The conversion to the data type of the moment ensures that bfloat16 remains
# bfloat16 in the optimizer state. This conversion has to be done after
# `bias_correction_` is calculated as calculating `decay**count` in low
# precision can result in it being rounded to 1 and subsequently a
# "division by zero" error.
bias_correction_ = 1 - decay**count
# Perform division in the original precision.
return jax.tree_util.tree_map(
lambda t: t / bias_correction_.astype(t.dtype), moment)
def _reject_complex(params):
if any(jnp.iscomplexobj(x) for x in jax.tree_util.tree_leaves(params)):
raise ValueError('This transformation does not support complex parameters.')
class EmaState(NamedTuple):
"""Holds an exponential moving average of past updates."""
count: chex.Array # shape=(), dtype=jnp.int32.
ema: base.Params
def ema(
decay: float,
debias: bool = True,
accumulator_dtype: Optional[Any] = None
) -> base.GradientTransformation:
"""Compute an exponential moving average of past updates.
Note: `trace` and `ema` have very similar but distinct updates;
`ema = decay * ema + (1-decay) * t`, while `trace = decay * trace + t`.
Both are frequently found in the optimization literature.
Args:
decay: Decay rate for the exponential moving average.
debias: Whether to debias the transformed gradient.
accumulator_dtype: Optional `dtype` to used for the accumulator; if `None`
then the `dtype` is inferred from `params` and `updates`.
Returns:
A `GradientTransformation` object.
"""
accumulator_dtype = utils.canonicalize_dtype(accumulator_dtype)
def init_fn(params):
return EmaState(
count=jnp.zeros([], jnp.int32),
ema=jax.tree_util.tree_map(
lambda t: jnp.zeros_like(t, dtype=accumulator_dtype), params))
def update_fn(updates, state, params=None):
del params
updates = new_ema = update_moment(updates, state.ema, decay, order=1)
count_inc = utils.safe_int32_increment(state.count)
if debias:
updates = bias_correction(new_ema, decay, count_inc)
state_ema = utils.cast_tree(new_ema, accumulator_dtype)
return updates, EmaState(count=count_inc, ema=state_ema)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByRssState(NamedTuple):
"""State holding the sum of gradient squares to date."""
sum_of_squares: base.Updates
def scale_by_rss(
initial_accumulator_value: float = 0.1,
eps: float = 1e-7
) -> base.GradientTransformation:
"""Rescale updates by the root of the sum of all squared gradients to date.
References:
[Duchi et al, 2011](https://jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
[McMahan et al., 2010](https://arxiv.org/abs/1002.4908)
Args:
initial_accumulator_value: Starting value for accumulators, must be >= 0.
eps: A small floating point value to avoid zero denominator.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
sum_of_squares = jax.tree_util.tree_map(
lambda t: jnp.full_like(t, initial_accumulator_value), params)
return ScaleByRssState(sum_of_squares=sum_of_squares)
def update_fn(updates, state, params=None):
del params
sum_of_squares = jax.tree_util.tree_map(
lambda g, t: _abs_sq(g) + t, updates, state.sum_of_squares)
inv_sqrt_g_square = jax.tree_util.tree_map(
lambda t: jnp.where(t > 0, jax.lax.rsqrt(t + eps), 0.0), sum_of_squares)
updates = jax.tree_util.tree_map(
lambda scale, g: scale * g, inv_sqrt_g_square, updates)
return updates, ScaleByRssState(sum_of_squares=sum_of_squares)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByRmsState(NamedTuple):
"""State for exponential root mean-squared (RMS)-normalized updates."""
nu: base.Updates
def scale_by_rms(
decay: float = 0.9,
eps: float = 1e-8,
initial_scale: float = 0.
) -> base.GradientTransformation:
"""Rescale updates by the root of the exp. moving avg of the square.
References:
[Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
Args:
decay: Decay rate for the exponentially weighted average of squared grads.
eps: Term added to the denominator to improve numerical stability.
initial_scale: Initial value for second moment.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
nu = jax.tree_util.tree_map(
lambda n: jnp.full_like(n, initial_scale), params) # second moment
return ScaleByRmsState(nu=nu)
def update_fn(updates, state, params=None):
del params
nu = update_moment_per_elem_norm(updates, state.nu, decay, 2)
updates = jax.tree_util.tree_map(
lambda g, n: g * jax.lax.rsqrt(n + eps), updates, nu)
return updates, ScaleByRmsState(nu=nu)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByRStdDevState(NamedTuple):
"""State for centered exponential moving average of squares of updates."""
mu: base.Updates
nu: base.Updates
def scale_by_stddev(
decay: float = 0.9,
eps: float = 1e-8,
initial_scale: float = 0.
) -> base.GradientTransformation:
"""Rescale updates by the root of the centered exp. moving average of squares.
References:
[Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
Args:
decay: Decay rate for the exponentially weighted average of squared grads.
eps: Term added to the denominator to improve numerical stability.
initial_scale: Initial value for second moment.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
mu = jax.tree_util.tree_map(jnp.zeros_like, params) # First moment
nu = jax.tree_util.tree_map(
lambda n: jnp.full_like(n, initial_scale), params) # second moment
return ScaleByRStdDevState(mu=mu, nu=nu)
def update_fn(updates, state, params=None):
del params
mu = update_moment(updates, state.mu, decay, 1)
nu = update_moment_per_elem_norm(updates, state.nu, decay, 2)
updates = jax.tree_util.tree_map(
lambda g, m, n: g * jax.lax.rsqrt(n - _abs_sq(m) + eps),
updates, mu, nu)
return updates, ScaleByRStdDevState(mu=mu, nu=nu)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByAdamState(NamedTuple):
"""State for the Adam algorithm."""
count: chex.Array # shape=(), dtype=jnp.int32.
mu: base.Updates
nu: base.Updates
def scale_by_adam(
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-8,
eps_root: float = 0.0,
mu_dtype: Optional[chex.ArrayDType] = None,
) -> base.GradientTransformation:
"""Rescale updates according to the Adam algorithm.
References:
[Kingma et al, 2014](https://arxiv.org/abs/1412.6980)
Args:
b1: Decay rate for the exponentially weighted average of grads.
b2: Decay rate for the exponentially weighted average of squared grads.
eps: Term added to the denominator to improve numerical stability.
eps_root: Term added to the denominator inside the square-root to improve
numerical stability when backpropagating gradients through the rescaling.
mu_dtype: Optional `dtype` to be used for the first order accumulator; if
`None` then the `dtype` is inferred from `params` and `updates`.
Returns:
A `GradientTransformation` object.
"""
mu_dtype = utils.canonicalize_dtype(mu_dtype)
def init_fn(params):
mu = jax.tree_util.tree_map( # First moment
lambda t: jnp.zeros_like(t, dtype=mu_dtype), params)
nu = jax.tree_util.tree_map(jnp.zeros_like, params) # Second moment
return ScaleByAdamState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu)
def update_fn(updates, state, params=None):
del params
mu = update_moment(updates, state.mu, b1, 1)
nu = update_moment_per_elem_norm(updates, state.nu, b2, 2)
count_inc = numerics.safe_int32_increment(state.count)
mu_hat = bias_correction(mu, b1, count_inc)
nu_hat = bias_correction(nu, b2, count_inc)
updates = jax.tree_util.tree_map(
lambda m, v: m / (jnp.sqrt(v + eps_root) + eps), mu_hat, nu_hat)
mu = utils.cast_tree(mu, mu_dtype)
return updates, ScaleByAdamState(count=count_inc, mu=mu, nu=nu)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByAmsgradState(NamedTuple):
"""State for the AMSGrad algorithm."""
count: chex.Array # shape=(), dtype=jnp.int32.
mu: base.Updates
nu: base.Updates
nu_max: base.Updates
def scale_by_amsgrad(
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-8,
eps_root: float = 0.0,
mu_dtype: Optional[chex.ArrayDType] = None,
) -> base.GradientTransformation:
"""Rescale updates according to the AMSGrad algorithm.
References:
[Reddi et al, 2018](https://openreview.net/forum?id=ryQu7f-RZ)
Args:
b1: Decay rate for the exponentially weighted average of grads.
b2: Decay rate for the exponentially weighted average of squared grads.
eps: Term added to the denominator to improve numerical stability.
eps_root: Term added to the denominator inside the square-root to improve
numerical stability when backpropagating gradients through the rescaling.
mu_dtype: Optional `dtype` to be used for the first order accumulator; if
`None` then the `dtype` is inferred from `params` and `updates`.
Returns:
A `GradientTransformation` object.
"""
mu_dtype = utils.canonicalize_dtype(mu_dtype)
def init_fn(params):
mu = jax.tree_util.tree_map( # First moment
lambda t: jnp.zeros_like(t, dtype=mu_dtype), params)
nu = jax.tree_util.tree_map(jnp.zeros_like, params) # Second moment
nu_max = jax.tree_util.tree_map(jnp.zeros_like, params)
return ScaleByAmsgradState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu,
nu_max=nu_max)
def update_fn(updates, state, params=None):
del params
mu = update_moment(updates, state.mu, b1, 1)
nu = update_moment_per_elem_norm(updates, state.nu, b2, 2)
count_inc = numerics.safe_int32_increment(state.count)
mu_hat = bias_correction(mu, b1, count_inc)
nu_hat = bias_correction(nu, b2, count_inc)
nu_max = jax.tree_util.tree_map(jnp.maximum, state.nu_max, nu_hat)
updates = jax.tree_util.tree_map(
lambda m, v: m / (jnp.sqrt(v + eps_root) + eps), mu_hat, nu_max)
mu = utils.cast_tree(mu, mu_dtype)
return updates, ScaleByAmsgradState(count=count_inc, mu=mu, nu=nu,
nu_max=nu_max)
return base.GradientTransformation(init_fn, update_fn)
def scale_by_adamax(
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-8
) -> base.GradientTransformation:
"""Rescale updates according to the Adamax algorithm.
References:
[Kingma et al, 2014](https://arxiv.org/abs/1412.6980)
Args:
b1: Decay rate for the exponentially weighted average of grads.
b2: Decay rate for the exponentially weighted maximum of grads.
eps: Term added to the denominator to improve numerical stability.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
mu = jax.tree_util.tree_map(jnp.zeros_like, params) # First moment
nu = jax.tree_util.tree_map(jnp.zeros_like, params) # Infinite moment
return ScaleByAdamState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu)
def update_fn(updates, state, params=None):
del params
count_inc = numerics.safe_int32_increment(state.count)
mu = update_moment(updates, state.mu, b1, 1)
nu = update_infinity_moment(updates, state.nu, b2, eps)
# Bias correction for mean. No bias correction needed for infinity moment.
mu_hat = bias_correction(mu, b1, count_inc)
updates = jax.tree_util.tree_map(lambda m, v: m / v, mu_hat, nu)
return updates, ScaleByAdamState(count=count_inc, mu=mu, nu=nu)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByLionState(NamedTuple):
"""State for the Lion algorithm."""
count: chex.Array # shape=(), dtype=jnp.int32.
mu: base.Updates
def scale_by_lion(
b1: float = 0.9,
b2: float = 0.99,
mu_dtype: Optional[chex.ArrayDType] = None,
) -> base.GradientTransformation:
"""Rescale updates according to the Lion algorithm.
References:
[Chen et al, 2023](https://arxiv.org/abs/2302.06675)
Args:
b1: Rate for combining the momentum and the current grad.
b2: Decay rate for the exponentially weighted average of grads.
mu_dtype: Optional `dtype` to be used for the momentum; if
`None` then the `dtype is inferred from `params` and `updates`.
Returns:
A `GradientTransformation` object.
"""
mu_dtype = utils.canonicalize_dtype(mu_dtype)
def init_fn(params):
mu = jax.tree_util.tree_map( # moment
lambda t: jnp.zeros_like(t, dtype=mu_dtype), params)
return ScaleByLionState(count=jnp.zeros([], jnp.int32), mu=mu)
def update_fn(updates, state, params=None):
del params
updates_new = jax.tree_util.tree_map(
lambda g, m: jnp.sign((1. - b1) * g + b1 * m), updates, state.mu)
mu = update_moment(updates, state.mu, b2, 1)
mu = utils.cast_tree(mu, mu_dtype)
count_inc = numerics.safe_int32_increment(state.count)
return updates_new, ScaleByLionState(count=count_inc, mu=mu)
return base.GradientTransformation(init_fn, update_fn)
ScaleState = base.EmptyState
def scale(
step_size: float
) -> base.GradientTransformation:
"""Scale updates by some fixed scalar `step_size`.
Args:
step_size: A scalar corresponding to a fixed scaling factor for updates.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return ScaleState()
def update_fn(updates, state, params=None):
del params
updates = jax.tree_util.tree_map(lambda g: step_size * g, updates)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
def scale_by_param_block_norm(
min_scale: float = 1e-3
) -> base.GradientTransformation:
"""Scale updates for each param block by the norm of that block's parameters.
A `block` is here a weight vector (e.g. in a Linear layer) or a weight matrix
(e.g. in a convolutional layer) appearing as a leaf in the grads/param pytree.
Args:
min_scale: Minimum scaling factor.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return base.EmptyState()
def update_fn(updates, state, params):
if params is None:
raise ValueError(base.NO_PARAMS_MSG)
updates = jax.tree_util.tree_map(
lambda u, p: u * numerics.safe_norm(p, min_scale),
updates, params)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
def scale_by_param_block_rms(
min_scale: float = 1e-3
) -> base.GradientTransformation:
"""Scale updates by rms of the gradient for each param vector or matrix.
A `block` is here a weight vector (e.g. in a Linear layer) or a weight matrix
(e.g. in a convolutional layer) appearing as a leaf in the grads/param pytree.
Args:
min_scale: Minimum scaling factor.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return base.EmptyState()
def update_fn(updates, state, params):
if params is None:
raise ValueError(base.NO_PARAMS_MSG)
updates = jax.tree_util.tree_map(
lambda u, p: u * numerics.safe_root_mean_squares(p, min_scale),
updates, params)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
class ScaleByBeliefState(NamedTuple):
"""State for the rescaling by AdaBelief algorithm."""
count: chex.Array # shape=(), dtype=jnp.int32.
mu: base.Updates
nu: base.Updates
def scale_by_belief(
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-16,
eps_root: float = 1e-16
) -> base.GradientTransformation:
"""Rescale updates according to the AdaBelief algorithm.
References:
[Zhuang et al, 2020](https://arxiv.org/abs/2010.07468)
Args:
b1: Decay rate for the exponentially weighted average of grads.
b2: Decay rate for the exponentially weighted average of variance of grads.
eps: Term added to the denominator to improve numerical stability.
eps_root: Term added to the second moment of the prediction error to
improve numerical stability. If backpropagating gradients through the
gradient transformation (e.g. for meta-learning), this must be non-zero.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
mu = jax.tree_util.tree_map(jnp.zeros_like, params) # First moment
s = jax.tree_util.tree_map(jnp.zeros_like, params) # Second Central moment
return ScaleByBeliefState(count=jnp.zeros([], jnp.int32), mu=mu, nu=s)
def update_fn(updates, state, params=None):
del params
mu = update_moment(updates, state.mu, b1, 1)
prediction_error = jax.tree_util.tree_map(
lambda g, m: g-m, updates, state.mu)
nu = update_moment_per_elem_norm(prediction_error, state.nu, b2, 2)
nu = jax.tree_util.tree_map(lambda v: v + eps_root, nu)
count_inc = numerics.safe_int32_increment(state.count)
mu_hat = bias_correction(mu, b1, count_inc)
nu_hat = bias_correction(nu, b2, count_inc)
updates = jax.tree_util.tree_map(
lambda m, v: m / (jnp.sqrt(v) + eps), mu_hat, nu_hat)
return updates, ScaleByBeliefState(count=count_inc, mu=mu, nu=nu)
return base.GradientTransformation(init_fn, update_fn)
def scale_by_yogi(
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-3,
eps_root: float = 0.0,
initial_accumulator_value: float = 1e-6
) -> base.GradientTransformation:
"""Rescale updates according to the Yogi algorithm.
Supports complex numbers, see
https://gist.github.com/wdphy16/118aef6fb5f82c49790d7678cf87da29
References:
[Zaheer et al, 2018](https://papers.nips.cc/paper/2018/hash/90365351ccc7437a1309dc64e4db32a3-Abstract.html) #pylint:disable=line-too-long
Args:
b1: Decay rate for the exponentially weighted average of grads.
b2: Decay rate for the exponentially weighted average of variance of grads.
eps: Term added to the denominator to improve numerical stability.
eps_root: Term added to the denominator inside the square-root to improve
numerical stability when backpropagating gradients through the rescaling.
initial_accumulator_value: The starting value for accumulators.
Only positive values are allowed.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
value_like = lambda p: jnp.full_like(p, initial_accumulator_value)
mu = jax.tree_util.tree_map(value_like, params) # First moment
nu = jax.tree_util.tree_map(value_like, params) # Second Central moment
return ScaleByAdamState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu)
def update_fn(updates, state, params=None):
del params
mu = update_moment(updates, state.mu, b1, 1)
nu = jax.tree_util.tree_map(
lambda g, v: v - (1 - b2) * jnp.sign(v - _abs_sq(g)) * _abs_sq(g),
updates, state.nu)
count_inc = numerics.safe_int32_increment(state.count)
mu_hat = bias_correction(mu, b1, count_inc)
nu_hat = bias_correction(nu, b2, count_inc)
updates = jax.tree_util.tree_map(
lambda m, v: m / (jnp.sqrt(v + eps_root) + eps), mu_hat, nu_hat)
return updates, ScaleByAdamState(count=count_inc, mu=mu, nu=nu)
return base.GradientTransformation(init_fn, update_fn)
def scale_by_radam(
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-8,
eps_root: float = 0.0,
threshold: float = 5.0
) -> base.GradientTransformation:
"""Rescale updates according to the Rectified Adam algorithm.
References:
[Liu et al, 2020](https://arxiv.org/abs/1908.03265)
Args:
b1: Decay rate for the exponentially weighted average of grads.
b2: Decay rate for the exponentially weighted average of squared grads.
eps: Term added to the denominator to improve numerical stability.
eps_root: Term added to the denominator inside the square-root to improve
numerical stability when backpropagating gradients through the rescaling.
threshold: Threshold for variance tractability.
Returns:
A `GradientTransformation` object.
"""
ro_inf = 2./(1 - b2) - 1
def _radam_update(params):
ro = params[0]
mu_hat = params[1]
nu_hat = params[2]
r = jnp.sqrt((ro - 4)*(ro - 2)*ro_inf/((ro_inf - 4)*(ro_inf - 2)*ro))
updates = jax.tree_util.tree_map(
lambda m, v: r*m / (jnp.sqrt(v + eps_root) + eps), mu_hat, nu_hat)
return updates
def init_fn(params):
mu = jax.tree_util.tree_map(jnp.zeros_like, params) # First moment
nu = jax.tree_util.tree_map(jnp.zeros_like, params) # Second moment
return ScaleByAdamState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu)
def update_fn(updates, state, params=None):
del params
mu = update_moment(updates, state.mu, b1, 1)
nu = update_moment_per_elem_norm(updates, state.nu, b2, 2)
count_inc = numerics.safe_int32_increment(state.count)
b2t = b2**count_inc
ro = ro_inf - 2 * count_inc * b2t / (1 - b2t)
mu_hat = bias_correction(mu, b1, count_inc)
nu_hat = bias_correction(nu, b2, count_inc)
updates = jax.lax.cond(
ro >= threshold, _radam_update, lambda _: mu_hat,
(ro, mu_hat, nu_hat))
return updates, ScaleByAdamState(count=count_inc, mu=mu, nu=nu)
return base.GradientTransformation(init_fn, update_fn)
AddDecayedWeightsState = base.EmptyState
def add_decayed_weights(
weight_decay: Union[float, jax.Array] = 0.0,
mask: Optional[Union[Any, Callable[[base.Params], Any]]] = None
) -> base.GradientTransformation:
"""Add parameter scaled by `weight_decay`.
Args:
weight_decay: A scalar weight decay rate.
mask: A tree with same structure as (or a prefix of) the params PyTree,
or a Callable that returns such a pytree given the params/updates.
The leaves should be booleans, `True` for leaves/subtrees you want to
apply the transformation to, and `False` for those you want to skip.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return AddDecayedWeightsState()
def update_fn(updates, state, params):
if params is None:
raise ValueError(base.NO_PARAMS_MSG)
updates = jax.tree_util.tree_map(
lambda g, p: g + weight_decay * p, updates, params)
return updates, state
# If mask is not `None`, apply mask to the gradient transformation.
# E.g. it is common to skip weight decay on bias units and batch stats.
if mask is not None:
return wrappers.masked(
base.GradientTransformation(init_fn, update_fn), mask)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByScheduleState(NamedTuple):
"""Maintains count for scale scheduling."""
count: chex.Array # shape=(), dtype=jnp.int32
def scale_by_schedule(
step_size_fn: base.Schedule
) -> base.GradientTransformation:
"""Scale updates using a custom schedule for the `step_size`.
Args:
step_size_fn: A function that takes an update count as input and proposes
the step_size to multiply the updates by.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return ScaleByScheduleState(count=jnp.zeros([], jnp.int32))
def update_fn(updates, state, params=None):
del params
step_size = step_size_fn(state.count)
updates = jax.tree_util.tree_map(
lambda g: jnp.array(step_size, dtype=g.dtype) * g, updates)
return updates, ScaleByScheduleState(
count=numerics.safe_int32_increment(state.count))
return base.GradientTransformation(init_fn, update_fn)
class ScaleByTrustRatioState(NamedTuple):
"""The scale and decay trust ratio transformation is stateless."""
def scale_by_trust_ratio(
min_norm: float = 0.0,
trust_coefficient: float = 1.,
eps: float = 0.,
) -> base.GradientTransformation:
"""Scale updates by `trust ratio`.
References:
[You et. al 2020](https://arxiv.org/abs/1904.00962)
Args:
min_norm: Minimum norm for params and gradient norms; by default is zero.
trust_coefficient: A multiplier for the trust ratio.
eps: Additive constant added to the denominator for numerical stability.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return ScaleByTrustRatioState()
def update_fn(updates, state, params):
if params is None:
raise ValueError(base.NO_PARAMS_MSG)
def _scale_update(update, param):
# Clip norms to minimum value, by default no clipping.
param_norm = numerics.safe_norm(param, min_norm)
update_norm = numerics.safe_norm(update, min_norm)
trust_ratio = trust_coefficient * param_norm / (update_norm + eps)
# If no minimum norm clipping is used
# Set trust_ratio to 1 in case where parameters would never be updated.
zero_norm = jnp.logical_or(param_norm == 0., update_norm == 0.)
safe_trust_ratio = jnp.where(
zero_norm, jnp.array(1.0, dtype=param.dtype), trust_ratio)
return update * safe_trust_ratio
updates = jax.tree_util.tree_map(_scale_update, updates, params)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
class AddNoiseState(NamedTuple):
"""State for adding gradient noise. Contains a count for annealing."""
count: chex.Array
rng_key: chex.PRNGKey
def add_noise(
eta: float,
gamma: float,
seed: int
) -> base.GradientTransformation:
"""Add gradient noise.
References:
[Neelakantan et al, 2014](https://arxiv.org/abs/1511.06807)
Args:
eta: Base variance of the gaussian noise added to the gradient.
gamma: Decay exponent for annealing of the variance.
seed: Seed for random number generation.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return AddNoiseState(
count=jnp.zeros([], jnp.int32), rng_key=jax.random.PRNGKey(seed))
def update_fn(updates, state, params=None): # pylint: disable=missing-docstring
del params
num_vars = len(jax.tree_util.tree_leaves(updates))
treedef = jax.tree_util.tree_structure(updates)
count_inc = numerics.safe_int32_increment(state.count)
variance = eta / count_inc**gamma
standard_deviation = jnp.sqrt(variance)
all_keys = jax.random.split(state.rng_key, num=num_vars + 1)
noise = jax.tree_util.tree_map(
lambda g, k: jax.random.normal(k, shape=g.shape, dtype=g.dtype),
updates, jax.tree_util.tree_unflatten(treedef, all_keys[1:]))
updates = jax.tree_util.tree_map(
lambda g, n: g + standard_deviation.astype(g.dtype) * n,
updates, noise)
return updates, AddNoiseState(count=count_inc, rng_key=all_keys[0])
return base.GradientTransformation(init_fn, update_fn)
class ApplyEvery(NamedTuple):
"""Contains a counter and a gradient accumulator."""
count: chex.Array
grad_acc: base.Updates
def apply_every(
k: int = 1
) -> base.GradientTransformation:
"""Accumulate gradients and apply them every k steps.
Note that if this transformation is part of a chain, the states of the other
transformations will still be updated at every step. In particular, using
`apply_every` with a batch size of N/2 and k=2 is not necessarily equivalent
to not using `apply_every` with a batch size of N. If this equivalence is
important for you, consider using the `optax.MultiSteps`.
Args:
k: Emit non-zero gradients every k steps, otherwise accumulate them.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
grad_acc = jax.tree_util.tree_map(jnp.zeros_like, params)
return ApplyEvery(count=jnp.zeros([], jnp.int32), grad_acc=grad_acc)
def update_fn(updates, state, params=None):
del params
c = state.count % k
acc = c != 0
grad_acc = jax.tree_util.tree_map(
lambda g, ga: acc * ga + g, updates, state.grad_acc)
emit = c == (k - 1)
updates = jax.tree_util.tree_map(lambda ga: emit * ga, grad_acc)
count_inc = numerics.safe_int32_increment(state.count)
return updates, ApplyEvery(count=count_inc % k, grad_acc=grad_acc)
return base.GradientTransformation(init_fn, update_fn)
def _subtract_mean(g):
if len(g.shape) > 1:
return g - g.mean(tuple(range(1, len(g.shape))), keepdims=True)
else:
return g
CentralState = base.EmptyState
def centralize() -> base.GradientTransformation:
"""Centralize gradients.
References:
[Yong et al, 2020](https://arxiv.org/abs/2004.01461)
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return CentralState()
def update_fn(updates, state, params=None):
del params
updates = jax.tree_util.tree_map(_subtract_mean, updates)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
class ScaleBySM3State(NamedTuple):
"""State for the SM3 algorithm."""
mu: base.Updates
nu: base.Updates
def scale_by_sm3(
b1: float = 0.9,
b2: float = 1.0,
eps: float = 1e-8
) -> base.GradientTransformation:
"""Scale updates by `sm3`.
References:
[Anil et. al 2019](https://arxiv.org/abs/1901.11150)
Args:
b1: Decay rate for the exponentially weighted average of grads.
b2: Decay rate for the exponentially weighted average of squared grads.
eps: Term added to the denominator to improve numerical stability.
Returns:
A `GradientTransformation` object.
"""
def zeros_for_dim(p):
return [jnp.zeros([s]) for s in p.shape]
def init_fn(params):
_reject_complex(params)
mu = jax.tree_util.tree_map(zeros_for_dim, params)
nu = jax.tree_util.tree_map(jnp.zeros_like, params)
return ScaleBySM3State(mu, nu)
def _expanded_shape(shape, axis):
# Replaces a `shape` of [M, N, K] with 1 in all dimensions except for i.
# For eg: i = 1 returns [1, N, 1].
rank = len(shape)
return [1] * axis + [shape[axis]] + [1] * (rank - axis - 1)
def _new_accum(g, v):
coeffs = ((1.0 - b2) if b2 != 1.0 else 1.0, b2)
if g.ndim < 2:
return coeffs[0]*g**2 + coeffs[1]*v[0]
else:
return coeffs[0]*g**2 + coeffs[1]*functools.reduce(jnp.minimum, v)
def _new_mu(g, i):
if g.ndim < 2:
return g
else:
return jnp.max(g, axis=other_axes(i, g.ndim))
def other_axes(idx, ndim):
return list(range(idx)) + list(range(idx+1, ndim))
def update_fn(updates, state, params=None):
del params
mu = jax.tree_util.tree_map(
lambda g, v: # pylint:disable=g-long-lambda
[jnp.reshape(v[i], _expanded_shape(g.shape, i)) for i in range(g.ndim)],
updates, state.mu)
accum = jax.tree_util.tree_map(_new_accum, updates, mu)
accum_inv_sqrt = jax.tree_util.tree_map(
lambda t: jnp.where(t > 0, jax.lax.rsqrt(t + eps), 0.0), accum)
up = jax.tree_util.tree_map(lambda g, a: g*a, updates, accum_inv_sqrt)
nu = update_moment(up, state.nu, b1, 1)
mu = jax.tree_util.tree_map(
lambda g: [_new_mu(g, i) for i in range(g.ndim)], accum)
return nu, ScaleBySM3State(mu=mu, nu=nu)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByNovogradState(NamedTuple):
"""State for Novograd."""
count: chex.Array
mu: base.Updates
nu: base.Updates
def scale_by_novograd(
b1: float = 0.9,
b2: float = 0.25,
eps: float = 1e-8,
eps_root: float = 0.0,
weight_decay: float = 0.0,
mu_dtype: Optional[chex.ArrayDType] = None,
) -> base.GradientTransformation:
"""Computes NovoGrad updates.
References:
[Ginsburg et al, 2019](https://arxiv.org/abs/1905.11286)
Args:
b1: A decay rate for the exponentially weighted average of grads.
b2: A decay rate for the exponentially weighted average of squared grads.
eps: A term added to the denominator to improve numerical stability.
eps_root: A term added to the denominator inside the square-root to improve
numerical stability when backpropagating gradients through the rescaling.
weight_decay: A scalar weight decay rate.
mu_dtype: An optional `dtype` to be used for the first order accumulator; if
`None` then the `dtype` is inferred from `params` and `updates`.
Returns:
The corresponding `GradientTransformation`.
"""
mu_dtype = utils.canonicalize_dtype(mu_dtype)
def init_fn(params):
mu = jax.tree_util.tree_map( # First moment
lambda t: jnp.zeros_like(t, dtype=mu_dtype), params)
nu = jax.tree_util.tree_map(lambda _: 0.0, params) # Second moment
return ScaleByNovogradState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu)
def nu_addition(grads):
return jnp.linalg.norm(grads)**2
def mu_addition(grads, params, nu):
return grads / (jnp.sqrt(nu + eps_root) + eps) + weight_decay * params
def init_nu(grads, nu):
del nu
return jax.tree_util.tree_map(nu_addition, grads)
def update_nu(grads, nu):
updates = jax.tree_util.tree_map(nu_addition, grads)
return update_moment(updates, nu, b2, 1)
def init_mu(grads, params, mu, nu):
del mu
return jax.tree_util.tree_map(mu_addition, grads, params, nu)
def update_mu(grads, params, mu, nu):
updates = jax.tree_util.tree_map(mu_addition, grads, params, nu)
return jax.tree_util.tree_map(lambda m, u: b1 * m + u, mu, updates)
# Second moment
def update_fn(updates, state, params):
count_inc = numerics.safe_int32_increment(state.count)
nu = jax.lax.cond(count_inc == 1, init_nu, update_nu, updates, state.nu)
mu = jax.lax.cond(count_inc == 1, init_mu, update_mu, updates, params,
state.mu, nu)
mu = utils.cast_tree(mu, mu_dtype)
updates = mu
return updates, ScaleByNovogradState(count=count_inc, mu=mu, nu=nu)
return base.GradientTransformation(init_fn, update_fn)
def scale_by_optimistic_gradient(alpha: float = 1.0,
beta: float = 1.0
) -> base.GradientTransformation:
"""Compute generalized optimistic gradients.
References:
[Mokhtari et al, 2019](https://arxiv.org/abs/1901.08511v2)
Args:
alpha: Coefficient for generalized optimistic gradient descent.
beta: Coefficient for negative momentum.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
prev_grads = jax.tree_util.tree_map(jnp.zeros_like, params)
return TraceState(trace=prev_grads)
def update_fn(updates, state, params=None):
del params
new_updates = jax.tree_util.tree_map(
lambda grad_t, grad_tm1: (alpha + beta) * grad_t - beta * grad_tm1,
updates, state.trace)
return new_updates, TraceState(trace=updates)
return base.GradientTransformation(init_fn, update_fn)
class ScaleByDistanceOverGradientsState(NamedTuple):
"""State for scale_by_distance_over_gradients."""
max_dist: base.OptState
grad_sum_of_squares: base.OptState
init_params: base.OptState
def scale_by_distance_over_gradients(
reps_rel=1e-6, eps=1e-8, param_dtype=jnp.float32, global_scale=1.0
) -> base.GradientTransformation:
"""Distance-over-gradients learning rate-free optimizer.
This implementation stores a single copy of the model parameters, plus two
scalars per parameter array. It is equivalent to "Layer-wise DoG" (LDoG)
in the paper.
The authors recommend using model averaging with this optimizer.
References:
["DoG is SGD’s Best Friend: A Parameter-Free Dynamic Step Size
Schedule"](https://arxiv.org/pdf/2302.12022.pdf)
Args:
reps_rel: Used to compute initial learning rate. Recommended values are 1e-4
for models using batch norm, 1e-6 otherwise.
eps: Small loading term to avoid divide-by-zero errors.
param_dtype: dtype for storing initial parameters.
global_scale: Global scale factor, typically 1.0 or -1.0
Returns:
A `GradientTransformation` object.
"""
def _l2(x, y=0.0):
return jnp.sqrt(jnp.square(x - y).sum())
def init_fn(params):
return ScaleByDistanceOverGradientsState(
# Initial distance (needed to prevent zero step sizes).
jax.tree_util.tree_map(lambda x: reps_rel * (1 + _l2(x)), params),
# Initial gradient sum-of-squares.
jax.tree_util.tree_map(lambda x: jnp.zeros(1), params),
# Initial params, cast to preferred precision.
jax.tree_map(lambda x: x.astype(param_dtype), params),
)
def update_fn(updates, state: ScaleByDistanceOverGradientsState, params):
# update max distance
max_dist = jax.tree_map(
lambda d, x, y: jnp.maximum(d, _l2(x, y)),
state.max_dist,
params,
state.init_params,
)
# update gradient sum-of-squares
g_sos = jax.tree_map(
lambda x, y: x + jnp.square(y).sum(), state.grad_sum_of_squares, updates
)
def _tx(g, d, g_sos):
"""Apply the transformation."""
eta = global_scale * (d / jnp.sqrt(g_sos + eps))
return eta * g
updates = jax.tree_map(_tx, max_dist, g_sos, updates)
# new state
state = ScaleByDistanceOverGradientsState(
max_dist, g_sos, state.init_params
)
return updates, state
return base.GradientTransformation(init_fn, update_fn)
# TODO(b/183800387): remove legacy aliases.
# These legacy aliases are here for checkpoint compatibility
# To be removed once checkpoints have updated.
safe_int32_increment = numerics.safe_int32_increment
ClipState = clipping.ClipState
ClipByGlobalNormState = clipping.ClipByGlobalNormState
| optax-master | optax/_src/transform.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for optax._src.constrain."""
from absl.testing import absltest
import chex
import jax.numpy as jnp
from optax._src import combine
from optax._src import constrain
from optax._src import transform
from optax._src import update
STEPS = 50
LR = 1e-2
class ConstraintsTest(chex.TestCase):
def test_keep_params_nonnegative(self):
grads = (jnp.array([500., -500., 0.]),
jnp.array([500., -500., 0.]),
jnp.array([500., -500., 0.]))
params = (jnp.array([-1., -1., -1.]),
jnp.array([1., 1., 1.]),
jnp.array([0., 0., 0.]))
# vanilla sgd
opt = combine.chain(
transform.trace(decay=0, nesterov=False), transform.scale(-LR))
opt_state = opt.init(params)
updates, _ = opt.update(grads, opt_state, params)
new_params = update.apply_updates(params, updates)
chex.assert_trees_all_close(new_params, (jnp.array([-6., 4., -1.]),
jnp.array([-4., 6., 1.]),
jnp.array([-5., 5., 0.])))
# sgd with keeping parameters non-negative
opt = combine.chain(
transform.trace(decay=0, nesterov=False), transform.scale(-LR),
constrain.keep_params_nonnegative())
opt_state = opt.init(params)
updates, _ = opt.update(grads, opt_state, params)
new_params = update.apply_updates(params, updates)
chex.assert_trees_all_close(new_params, (jnp.array([0., 4., 0.]),
jnp.array([0., 6., 1.]),
jnp.array([0., 5., 0.])))
@chex.all_variants
def test_zero_nans(self):
params = (jnp.zeros([3]), jnp.zeros([3]), jnp.zeros([3]))
opt = constrain.zero_nans()
opt_state = self.variant(opt.init)(params)
update_fn = self.variant(opt.update)
chex.assert_trees_all_close(
opt_state,
constrain.ZeroNansState((jnp.array(False),) * 3))
# Check an upate with nans
grads_with_nans = (jnp.ones([3]),
jnp.array([1., float('nan'), float('nan')]),
jnp.array([float('nan'), 1., 1.]))
updates, opt_state = update_fn(grads_with_nans, opt_state)
chex.assert_trees_all_close(
opt_state,
constrain.ZeroNansState(
(jnp.array(False), jnp.array(True), jnp.array(True))))
chex.assert_trees_all_close(
updates,
(jnp.ones([3]), jnp.array([1., 0., 0.]), jnp.array([0., 1., 1.])))
# Check an upate with nans and infs
grads_with_nans_infs = (jnp.ones([3]),
jnp.array([1., float('nan'),
float('nan')]),
jnp.array([float('inf'), 1., 1.]))
updates, opt_state = update_fn(grads_with_nans_infs, opt_state)
chex.assert_trees_all_close(
opt_state,
constrain.ZeroNansState(
(jnp.array(False), jnp.array(True), jnp.array(False))))
chex.assert_trees_all_close(updates, (jnp.ones([3]), jnp.array(
[1., 0., 0.]), jnp.array([float('inf'), 1., 1.])))
# Check an upate with only good values
grads = (jnp.ones([3]), jnp.ones([3]), jnp.ones([3]))
updates, opt_state = update_fn(grads, opt_state)
chex.assert_trees_all_close(
opt_state,
constrain.ZeroNansState(
(jnp.array(False), jnp.array(False), jnp.array(False))))
chex.assert_trees_all_close(updates, grads)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/constrain_test.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `privacy.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
from optax._src import privacy
class DifferentiallyPrivateAggregateTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.batch_size = 8
self.params = {'key_a': (jnp.zeros((2, 3, 4)), jnp.zeros([])),
'key_b': jnp.zeros((6, 7))}
# Example `i`'s grads are full of `i`s. Important to include 0 to ensure
# there are no divisons by 0 (e.g. in norm clipping)
a = jnp.arange(self.batch_size)
self.per_eg_grads = jax.tree_util.tree_map(
lambda p: jnp.moveaxis(a * jnp.ones(p.shape+(self.batch_size,)), -1, 0),
self.params)
@chex.all_variants
def test_no_privacy(self):
"""l2_norm_clip=MAX_FLOAT32 and noise_multiplier=0 should recover SGD."""
dp_agg = privacy.differentially_private_aggregate(
l2_norm_clip=jnp.finfo(jnp.float32).max,
noise_multiplier=0.,
seed=0)
state = dp_agg.init(self.params)
update_fn = self.variant(dp_agg.update)
mean_grads = jax.tree_util.tree_map(lambda g: g.mean(0), self.per_eg_grads)
for _ in range(3):
updates, state = update_fn(self.per_eg_grads, state)
chex.assert_trees_all_close(updates, mean_grads)
@chex.all_variants
@parameterized.parameters(0.5, 10.0, 20.0, 40.0, 80.0)
def test_clipping_norm(self, l2_norm_clip):
dp_agg = privacy.differentially_private_aggregate(
l2_norm_clip=l2_norm_clip,
noise_multiplier=0.,
seed=42)
state = dp_agg.init(self.params)
update_fn = self.variant(dp_agg.update)
# Shape of the three arrays below is (self.batch_size, )
norms = [jnp.linalg.norm(g.reshape(self.batch_size, -1), axis=1)
for g in jax.tree_util.tree_leaves(self.per_eg_grads)]
global_norms = jnp.linalg.norm(jnp.stack(norms), axis=0)
divisors = jnp.maximum(global_norms / l2_norm_clip, 1.)
# Since the values of all the parameters are the same within each example,
# we can easily compute what the values should be:
expected_val = jnp.mean(jnp.arange(self.batch_size) / divisors)
expected_tree = jax.tree_util.tree_map(
lambda p: jnp.broadcast_to(expected_val, p.shape), self.params)
for _ in range(3):
updates, state = update_fn(self.per_eg_grads, state, self.params)
chex.assert_trees_all_close(updates, expected_tree, rtol=2e-7)
@chex.all_variants
@parameterized.parameters((3.0, 2.0), (1.0, 5.0), (100.0, 4.0), (1.0, 90.0))
def test_noise_multiplier(self, l2_norm_clip, noise_multiplier):
"""Standard dev. of noise should be l2_norm_clip * noise_multiplier."""
dp_agg = privacy.differentially_private_aggregate(
l2_norm_clip=l2_norm_clip,
noise_multiplier=noise_multiplier,
seed=1337)
state = dp_agg.init(None)
update_fn = self.variant(dp_agg.update)
expected_std = l2_norm_clip * noise_multiplier
grads = [jnp.ones((1, 100, 100))] # batch size 1
for _ in range(3):
updates, state = update_fn(grads, state)
chex.assert_trees_all_close(expected_std,
jnp.std(updates[0]),
atol=0.1 * expected_std)
def test_aggregated_updates_as_input_fails(self):
"""Expect per-example gradients as input to this transform."""
dp_agg = privacy.differentially_private_aggregate(l2_norm_clip=0.1,
noise_multiplier=1.1,
seed=2021)
state = dp_agg.init(self.params)
mean_grads = jax.tree_util.tree_map(lambda g: g.mean(0), self.per_eg_grads)
with self.assertRaises(ValueError):
dp_agg.update(mean_grads, state, self.params)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/privacy_test.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `factorized.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax.numpy as jnp
from optax._src import factorized
class FactorizedTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.init_params = (jnp.array([1., 2.]), jnp.array([3., 4.]))
self.per_step_updates = (jnp.array([500., 5.]), jnp.array([300., 3.]))
@chex.all_variants
def test_scale_by_factored_rms(self):
params = self.init_params
scaler = factorized.scale_by_factored_rms()
init_fn = self.variant(scaler.init)
transform_fn = self.variant(scaler.update)
state = init_fn(params)
chex.assert_tree_all_finite(state)
updates, state = transform_fn(self.per_step_updates, state, params)
chex.assert_tree_all_finite((params, updates, state))
chex.assert_trees_all_equal_shapes(params, updates)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/factorized_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `stochastic_gradient_estimators.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import stochastic_gradient_estimators as sge
from optax._src import utils
# Set seed for deterministic sampling.
np.random.seed(42)
_estimator_to_num_samples = {
sge.score_function_jacobians: 5 * 10**5,
sge.measure_valued_jacobians: 10**5,
sge.pathwise_jacobians: 5 * 10**4,
}
_weighted_estimator_to_num_samples = {
sge.score_function_jacobians: 5 * 10**6,
sge.measure_valued_jacobians: 5 * 10**5,
sge.pathwise_jacobians: 5 * 10**4,
}
def _ones(dims):
return jnp.ones(shape=(dims), dtype=jnp.float32)
def _assert_equal(actual, expected, rtol=1e-2, atol=1e-2):
"""Asserts that arrays are equal."""
# Note: assert_allclose does not check shapes
chex.assert_equal_shape((actual, expected))
# We get around the bug https://github.com/numpy/numpy/issues/13801
zero_indices = np.argwhere(expected == 0)
if not np.all(np.abs(actual[zero_indices]) <= atol):
raise AssertionError(f'Larger than {atol} diff in {actual[zero_indices]}')
non_zero_indices = np.argwhere(expected != 0)
np.testing.assert_allclose(
np.asarray(actual)[non_zero_indices],
expected[non_zero_indices], rtol, atol)
def _estimator_variant(variant, estimator):
return variant(estimator, static_argnums=(0, 2, 4))
def _measure_valued_variant(variant):
return variant(
sge.measure_valued_jacobians,
static_argnums=(0, 2, 4, 5))
class GradientEstimatorsTest(chex.TestCase):
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', sge.score_function_jacobians),
('_pathwise_jacobians', sge.pathwise_jacobians),
('_measure_valued_jacobians', sge.measure_valued_jacobians),
], [
('0.1', 0.1),
('0.5', 0.5),
('0.9', 0.9),
],
named=True))
def testConstantFunction(self, estimator, constant):
data_dims = 3
num_samples = _estimator_to_num_samples[estimator]
effective_mean = 1.5
mean = effective_mean * _ones(data_dims)
effective_log_scale = 0.0
log_scale = effective_log_scale * _ones(data_dims)
rng = jax.random.PRNGKey(1)
jacobians = _estimator_variant(self.variant, estimator)(
lambda x: jnp.array(constant), [mean, log_scale],
utils.multi_normal, rng, num_samples)
# Average over the number of samples.
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads = np.mean(mean_jacobians, axis=0)
expected_mean_grads = np.zeros(data_dims, dtype=np.float32)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads = np.mean(log_scale_jacobians, axis=0)
expected_log_scale_grads = np.zeros(data_dims, dtype=np.float32)
_assert_equal(mean_grads, expected_mean_grads, atol=5e-3)
_assert_equal(log_scale_grads, expected_log_scale_grads, atol=5e-3)
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', sge.score_function_jacobians),
('_pathwise_jacobians', sge.pathwise_jacobians),
('_measure_valued_jacobians', sge.measure_valued_jacobians),
], [
('0.5_-1.', 0.5, -1.),
('0.7_0.0)', 0.7, 0.0),
('0.8_0.1', 0.8, 0.1),
],
named=True))
def testLinearFunction(self, estimator, effective_mean, effective_log_scale):
data_dims = 3
num_samples = _estimator_to_num_samples[estimator]
rng = jax.random.PRNGKey(1)
mean = effective_mean * _ones(data_dims)
log_scale = effective_log_scale * _ones(data_dims)
jacobians = _estimator_variant(self.variant, estimator)(
np.sum, [mean, log_scale],
utils.multi_normal, rng, num_samples)
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads = np.mean(mean_jacobians, axis=0)
expected_mean_grads = np.ones(data_dims, dtype=np.float32)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads = np.mean(log_scale_jacobians, axis=0)
expected_log_scale_grads = np.zeros(data_dims, dtype=np.float32)
_assert_equal(mean_grads, expected_mean_grads)
_assert_equal(log_scale_grads, expected_log_scale_grads)
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', sge.score_function_jacobians),
('_pathwise_jacobians', sge.pathwise_jacobians),
('_measure_valued_jacobians', sge.measure_valued_jacobians),
], [
('1.0_0.3', 1.0, 0.3),
],
named=True))
def testQuadraticFunction(
self, estimator, effective_mean, effective_log_scale):
data_dims = 3
num_samples = _estimator_to_num_samples[estimator]
rng = jax.random.PRNGKey(1)
mean = effective_mean * _ones(data_dims)
log_scale = effective_log_scale * _ones(data_dims)
jacobians = _estimator_variant(self.variant, estimator)(
lambda x: np.sum(x**2) / 2, [mean, log_scale],
utils.multi_normal, rng, num_samples)
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads = np.mean(mean_jacobians, axis=0)
expected_mean_grads = effective_mean * np.ones(
data_dims, dtype=np.float32)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads = np.mean(log_scale_jacobians, axis=0)
expected_log_scale_grads = np.exp(2 * effective_log_scale) * np.ones(
data_dims, dtype=np.float32)
_assert_equal(mean_grads, expected_mean_grads, atol=5e-2)
_assert_equal(log_scale_grads, expected_log_scale_grads, atol=5e-2)
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', sge.score_function_jacobians),
('_pathwise_jacobians', sge.pathwise_jacobians),
('_measure_valued_jacobians', sge.measure_valued_jacobians),
], [
('case_1', [1.0, 2.0, 3.], [-1., 0.3, -2.], [1., 1., 1.]),
('case_2', [1.0, 2.0, 3.], [-1., 0.3, -2.], [4., 2., 3.]),
('case_3', [1.0, 2.0, 3.], [0.1, 0.2, 0.1], [10., 5., 1.]),
],
named=True))
def testWeightedLinear(
self, estimator, effective_mean, effective_log_scale, weights):
num_samples = _weighted_estimator_to_num_samples[estimator]
rng = jax.random.PRNGKey(1)
mean = jnp.array(effective_mean)
log_scale = jnp.array(effective_log_scale)
weights = jnp.array(weights)
data_dims = len(effective_mean)
function = lambda x: jnp.sum(x * weights)
jacobians = _estimator_variant(self.variant, estimator)(
function, [mean, log_scale],
utils.multi_normal, rng, num_samples)
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads = np.mean(mean_jacobians, axis=0)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads = np.mean(log_scale_jacobians, axis=0)
expected_mean_grads = weights
expected_log_scale_grads = np.zeros(data_dims, dtype=np.float32)
_assert_equal(mean_grads, expected_mean_grads, atol=5e-2)
_assert_equal(log_scale_grads, expected_log_scale_grads, atol=5e-2)
@chex.all_variants
@parameterized.named_parameters(
chex.params_product([
('_score_function_jacobians', sge.score_function_jacobians),
('_pathwise_jacobians', sge.pathwise_jacobians),
('_measure_valued_jacobians', sge.measure_valued_jacobians),
], [
('case_1', [1.0, 2.0, 3.], [-1., 0.3, -2.], [1., 1., 1.]),
('case_2', [1.0, 2.0, 3.], [-1., 0.3, -2.], [4., 2., 3.]),
('case_3', [1.0, 2.0, 3.], [0.1, 0.2, 0.1], [3., 5., 1.]),
],
named=True))
def testWeightedQuadratic(
self, estimator, effective_mean, effective_log_scale, weights):
num_samples = _weighted_estimator_to_num_samples[estimator]
rng = jax.random.PRNGKey(1)
mean = jnp.array(effective_mean, dtype=jnp.float32)
log_scale = jnp.array(effective_log_scale, dtype=jnp.float32)
weights = jnp.array(weights, dtype=jnp.float32)
data_dims = len(effective_mean)
function = lambda x: jnp.sum(x * weights) ** 2
jacobians = _estimator_variant(self.variant, estimator)(
function, [mean, log_scale],
utils.multi_normal, rng, num_samples)
mean_jacobians = jacobians[0]
chex.assert_shape(mean_jacobians, (num_samples, data_dims))
mean_grads = np.mean(mean_jacobians, axis=0)
log_scale_jacobians = jacobians[1]
chex.assert_shape(log_scale_jacobians, (num_samples, data_dims))
log_scale_grads = np.mean(log_scale_jacobians, axis=0)
expected_mean_grads = 2 * weights * np.sum(weights * mean)
effective_scale = np.exp(log_scale)
expected_scale_grads = 2 * weights ** 2 * effective_scale
expected_log_scale_grads = expected_scale_grads * effective_scale
_assert_equal(mean_grads, expected_mean_grads, atol=1e-1, rtol=1e-1)
_assert_equal(
log_scale_grads, expected_log_scale_grads, atol=1e-1, rtol=1e-1)
@chex.all_variants
@parameterized.named_parameters(
chex.params_product(
[
('_sum_cos_x', [1.0], [1.0], lambda x: jnp.sum(jnp.cos(x))),
# Need to ensure that the mean is not too close to 0.
('_sum_log_x', [10.0], [0.0], lambda x: jnp.sum(jnp.log(x))),
('_sum_cos_2x', [1.0, 2.0], [1.0, -2
], lambda x: jnp.sum(jnp.cos(2 * x))),
('_cos_sum_2x', [1.0, 2.0], [1.0, -2
], lambda x: jnp.cos(jnp.sum(2 * x))),
],
[
('coupling', True),
('nocoupling', False),
],
named=True))
def testNonPolynomialFunctionConsistencyWithPathwise(self, effective_mean,
effective_log_scale,
function, coupling):
num_samples = 10**5
rng = jax.random.PRNGKey(1)
measure_rng, pathwise_rng = jax.random.split(rng)
mean = jnp.array(effective_mean, dtype=jnp.float32)
log_scale = jnp.array(effective_log_scale, dtype=jnp.float32)
data_dims = len(effective_mean)
measure_valued_jacobians = _measure_valued_variant(self.variant)(
function, [mean, log_scale],
utils.multi_normal, measure_rng, num_samples, coupling)
measure_valued_mean_jacobians = measure_valued_jacobians[0]
chex.assert_shape(measure_valued_mean_jacobians, (num_samples, data_dims))
measure_valued_mean_grads = np.mean(measure_valued_mean_jacobians, axis=0)
measure_valued_log_scale_jacobians = measure_valued_jacobians[1]
chex.assert_shape(
measure_valued_log_scale_jacobians, (num_samples, data_dims))
measure_valued_log_scale_grads = np.mean(
measure_valued_log_scale_jacobians, axis=0)
pathwise_jacobians = _estimator_variant(
self.variant, sge.pathwise_jacobians)(function, [mean, log_scale],
utils.multi_normal, pathwise_rng,
num_samples)
pathwise_mean_jacobians = pathwise_jacobians[0]
chex.assert_shape(pathwise_mean_jacobians, (num_samples, data_dims))
pathwise_mean_grads = np.mean(pathwise_mean_jacobians, axis=0)
pathwise_log_scale_jacobians = pathwise_jacobians[1]
chex.assert_shape(pathwise_log_scale_jacobians, (num_samples, data_dims))
pathwise_log_scale_grads = np.mean(pathwise_log_scale_jacobians, axis=0)
_assert_equal(
pathwise_mean_grads, measure_valued_mean_grads, rtol=5e-1, atol=1e-1)
_assert_equal(
pathwise_log_scale_grads, measure_valued_log_scale_grads,
rtol=5e-1, atol=1e-1)
class MeasuredValuedEstimatorsTest(chex.TestCase):
@chex.all_variants
@parameterized.parameters([True, False])
def testRaisesErrorForNonGaussian(self, coupling):
num_samples = 10**5
rng = jax.random.PRNGKey(1)
function = lambda x: jnp.sum(x) ** 2
mean = jnp.array(0, dtype=jnp.float32)
log_scale = jnp.array(0., dtype=jnp.float32)
class TestDist():
def __init__(self, params):
self._params = params
def sample(self, n):
return np.zeros(n)
with self.assertRaises(ValueError):
_measure_valued_variant(self.variant)(
function, [mean, log_scale],
TestDist, rng, num_samples, coupling)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/stochastic_gradient_estimators_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""JAX Schedules.
Schedules may be used to anneal the value of a hyper-parameter over time; for
instance, they may be used to anneal the learning rate used to update an agent's
parameters or the exploration factor used to select actions.
"""
import functools
import inspect
from typing import Callable, Dict, Union, NamedTuple, Optional, Iterable, Sequence
from absl import logging
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import base
from optax._src import numerics
def constant_schedule(
value: Union[float, int]
) -> base.Schedule:
"""Constructs a constant schedule.
Args:
value: value to be held constant throughout.
Returns:
schedule: A function that maps step counts to values.
"""
return lambda count: value
def polynomial_schedule(
init_value: chex.Scalar,
end_value: chex.Scalar,
power: chex.Scalar,
transition_steps: int,
transition_begin: int = 0
) -> base.Schedule:
"""Constructs a schedule with polynomial transition from init to end value.
Args:
init_value: initial value for the scalar to be annealed.
end_value: end value of the scalar to be annealed.
power: the power of the polynomial used to transition from init to end.
transition_steps: number of steps over which annealing takes place,
the scalar starts changing at `transition_begin` steps and completes
the transition by `transition_begin + transition_steps` steps.
If `transition_steps <= 0`, then the entire annealing process is disabled
and the value is held fixed at `init_value`.
transition_begin: must be positive. After how many steps to start annealing
(before this many steps the scalar value is held fixed at `init_value`).
Returns:
schedule: A function that maps step counts to values.
"""
if transition_steps <= 0:
logging.info(
'A polynomial schedule was set with a non-positive `transition_steps` '
'value; this results in a constant schedule with value `init_value`.')
return lambda count: init_value
if transition_begin < 0:
logging.info(
'An exponential schedule was set with a negative `transition_begin` '
'value; this will result in `transition_begin` falling back to `0`.')
transition_begin = 0
def schedule(count):
count = jnp.clip(count - transition_begin, 0, transition_steps)
frac = 1 - count / transition_steps
return (init_value - end_value) * (frac**power) + end_value
return schedule
# Alias polynomial schedule to linear schedule for convenience.
def linear_schedule(
init_value: chex.Scalar,
end_value: chex.Scalar,
transition_steps: int,
transition_begin: int = 0
) -> base.Schedule:
return polynomial_schedule(
init_value=init_value, end_value=end_value, power=1,
transition_steps=transition_steps, transition_begin=transition_begin)
def piecewise_constant_schedule(
init_value: float,
boundaries_and_scales: Optional[Dict[int, float]] = None
) -> base.Schedule:
"""Returns a function which implements a piecewise constant schedule.
Args:
init_value: An initial value `init_v`.
boundaries_and_scales: A map from boundaries `b_i` to non-negative scaling
factors `f_i`. For any step count `s`, the schedule returns `init_v`
scaled by the product of all factors `f_i` such that `b_i` < `s`.
Returns:
schedule: A function that maps step counts to values.
"""
if boundaries_and_scales is not None:
all_positive = all(scale >= 0. for scale in boundaries_and_scales.values())
if not all_positive:
raise ValueError(
'`piecewise_constant_schedule` expects non-negative scale factors')
def schedule(count):
v = init_value
if boundaries_and_scales is not None:
for threshold, scale in sorted(boundaries_and_scales.items()):
indicator = jnp.maximum(0., jnp.sign(threshold - count))
v = v * indicator + (1 - indicator) * scale * v
return v
return schedule
def exponential_decay(
init_value: float,
transition_steps: int,
decay_rate: float,
transition_begin: int = 0,
staircase: bool = False,
end_value: Optional[float] = None
) -> base.Schedule:
"""Constructs a schedule with either continuous or discrete exponential decay.
This function applies an exponential decay function to a provided initial
value. The function returns the decayed value as follows:
```
decayed_value = init_value * decay_rate ^ (count / transition_steps)
```
If the argument `staircase` is `True`, then `count / transition_steps` is
an integer division and the decayed value follows a staircase function.
Args:
init_value: the initial learning rate.
transition_steps: must be positive. See the decay computation above.
decay_rate: must not be zero. The decay rate.
transition_begin: must be positive. After how many steps to start annealing
(before this many steps the scalar value is held fixed at `init_value`).
staircase: if `True`, decay the values at discrete intervals.
end_value: the value at which the exponential decay stops. When
`decay_rate` < 1, `end_value` is treated as a lower bound, otherwise as
an upper bound. Has no effect when `decay_rate` = 0.
Returns:
schedule: A function that maps step counts to values.
"""
if transition_steps <= 0:
logging.info(
'An exponential schedule was set with a non-positive `transition_steps`'
' value; this will result in a constant schedule with value '
'`init_value`.')
return lambda count: init_value
if decay_rate == 0:
logging.info(
'An exponential schedule was set with a zero `decay_rate` value; '
'this will result in a constant schedule with value `init_value`.')
return lambda count: init_value
if transition_begin < 0:
logging.info(
'An exponential schedule was set with a negative `transition_begin` '
'value; this will result in `transition_begin` falling back to `0`.')
transition_begin = 0
if end_value is not None:
clip_fn = jnp.maximum if decay_rate < 1.0 else jnp.minimum
def schedule(count):
decreased_count = count - transition_begin
p = decreased_count / transition_steps
if staircase:
p = jnp.floor(p)
decayed_value = jnp.where(
decreased_count <= 0, init_value, init_value * jnp.power(decay_rate, p))
if end_value is not None:
decayed_value = clip_fn(decayed_value, end_value)
return decayed_value
return schedule
def cosine_decay_schedule(
init_value: float,
decay_steps: int,
alpha: float = 0.0,
exponent: float = 1.0,
) -> base.Schedule:
"""Returns a function which implements cosine learning rate decay.
The schedule does not restart when ``decay_steps`` has been reached. Instead,
the learning rate remains constant afterwards. For a cosine schedule with
restarts, :func:`optax.join_schedules` can be used to join several cosine
decay schedules.
For more details see: https://arxiv.org/abs/1608.03983.
Args:
init_value: An initial value `init_v`.
decay_steps: Positive integer - the number of steps for which to apply
the decay for.
alpha: Float. The minimum value of the multiplier used to adjust the
learning rate.
exponent: Float. The default decay is 0.5 * (1 + cos(pi * t/T)), where t is
the current timestep and T is the `decay_steps`. The exponent modifies
this to be (0.5 * (1 + cos(pi * t/T))) ** exponent. Defaults to 1.0.
Returns:
schedule: A function that maps step counts to values.
"""
if not decay_steps > 0:
raise ValueError('The cosine_decay_schedule requires positive decay_steps!')
def schedule(count):
count = jnp.minimum(count, decay_steps)
cosine_decay = 0.5 * (1 + jnp.cos(jnp.pi * count / decay_steps))
decayed = (1 - alpha) * cosine_decay ** exponent + alpha
return init_value * decayed
return schedule
def _linear_interpolate(start: float, end: float, pct: float):
return (end-start) * pct + start
def _cosine_interpolate(start: float, end: float, pct: float):
return end + (start-end) / 2.0 * (jnp.cos(jnp.pi * pct) + 1)
def piecewise_interpolate_schedule(
interpolate_type: str,
init_value: float,
boundaries_and_scales: Optional[Dict[int, float]] = None
) -> base.Schedule:
"""Returns a function which implements a piecewise interpolated schedule.
Args:
interpolate_type: 'linear' or 'cosine', specifying the interpolation
strategy.
init_value: An initial value `init_v`.
boundaries_and_scales: A map from boundaries `b_i` to non-negative scaling
factors `f_i`. At boundary step `b_i`, the schedule returns `init_v`
scaled by the product of all factors `f_j` such that `b_j` <= `b_i`. The
values in between each boundary will be interpolated as per `type`.
Returns:
schedule: A function that maps step counts to values.
"""
if interpolate_type == 'linear':
interpolate_fn = _linear_interpolate
elif interpolate_type == 'cosine':
interpolate_fn = _cosine_interpolate
else:
raise ValueError('`interpolate_type` must be either \'cos\' or \'linear\'')
if boundaries_and_scales:
boundaries, scales = zip(*sorted(boundaries_and_scales.items()))
if not all(scale >= 0. for scale in scales):
raise ValueError(
'`piecewise_interpolate_schedule` expects non-negative scale factors')
else:
boundaries, scales = (), ()
bounds = np.stack((0,) + boundaries)
values = np.cumprod(np.stack((init_value,) + scales))
interval_sizes = bounds[1:] - bounds[:-1]
def schedule(count):
indicator = (bounds[:-1] <= count) & (count < bounds[1:])
pct = (count - bounds[:-1]) / interval_sizes
interp_vals = interpolate_fn(values[:-1], values[1:], pct)
return indicator.dot(interp_vals) + (bounds[-1] <= count) * values[-1]
return schedule
def linear_onecycle_schedule(
transition_steps: int,
peak_value: float,
pct_start: float = 0.3,
pct_final: float = 0.85,
div_factor: float = 25.0,
final_div_factor: float = 1e4
) -> base.Schedule:
"""Returns a function which implements the onecycle learning rate schedule.
This function uses a linear annealing strategy.
For more details see: https://arxiv.org/abs/1708.07120
Args:
transition_steps: Number of steps over which annealing takes place.
peak_value: Maximum value attained by schedule at pct_start percent
of the cycle (in number of steps).
pct_start: The percentage of the cycle (in number of steps) spent
increasing the learning rate.
pct_final: The percentage of the cycle (in number of steps) spent
increasing to peak_value then decreasing back to init_value.
div_factor: Determines the initial value via init_value =
peak_value / div_factor
final_div_factor: Determines the final value via final_value =
init_value / final_div_factor
Returns:
schedule: A function that maps step counts to values.
"""
if transition_steps <= 0:
raise ValueError(
'A linear onecycle schedule was set with a non-positive '
'`transition_steps`')
return piecewise_interpolate_schedule(
'linear',
peak_value / div_factor,
{int(pct_start * transition_steps): div_factor,
int(pct_final * transition_steps): 1. / div_factor,
transition_steps: 1. / final_div_factor})
def cosine_onecycle_schedule(
transition_steps: int,
peak_value: float,
pct_start: float = 0.3,
div_factor: float = 25.0,
final_div_factor: float = 1e4
) -> base.Schedule:
"""Returns a function which implements the onecycle learning rate schedule.
This function uses a cosine annealing strategy.
For more details see: https://arxiv.org/abs/1708.07120
Args:
transition_steps: Number of steps over which annealing takes place.
peak_value: Maximum value attained by schedule at pct_start percent
of the cycle (in number of steps).
pct_start: The percentage of the cycle (in number of steps) spent
increasing the learning rate.
div_factor: Determines the initial value via init_value =
peak_value / div_factor
final_div_factor: Determines the final value via final_value =
init_value / final_div_factor
Returns:
schedule: A function that maps step counts to values.
"""
if transition_steps <= 0:
raise ValueError(
'A linear onecycle schedule was set with a non-positive '
'`transition_steps`')
return piecewise_interpolate_schedule(
'cosine',
peak_value / div_factor,
{int(pct_start * transition_steps): div_factor,
int(transition_steps): 1. / (div_factor * final_div_factor)})
def join_schedules(schedules: Sequence[base.Schedule],
boundaries: Sequence[int]) -> base.Schedule:
"""Sequentially apply multiple schedules.
Args:
schedules: A list of callables (expected to be optax schedules). Each
schedule will receive a step count indicating the number of steps since
the previous boundary transition.
boundaries: A list of integers (of length one less than schedules) that
indicate when to transition between schedules.
Returns:
schedule: A function that maps step counts to values.
"""
def schedule(step: chex.Numeric) -> chex.Numeric:
output = schedules[0](step)
for boundary, schedule in zip(boundaries, schedules[1:]):
output = jnp.where(step < boundary, output, schedule(step - boundary))
return output
return schedule
def warmup_cosine_decay_schedule(
init_value: float,
peak_value: float,
warmup_steps: int,
decay_steps: int,
end_value: float = 0.0,
exponent: float = 1.0,
) -> base.Schedule:
"""Linear warmup followed by cosine decay.
Args:
init_value: Initial value for the scalar to be annealed.
peak_value: Peak value for scalar to be annealed at end of warmup.
warmup_steps: Positive integer, the length of the linear warmup.
decay_steps: Positive integer, the total length of the schedule. Note that
this includes the warmup time, so the number of steps during which cosine
annealing is applied is `decay_steps - warmup_steps`.
end_value: End value of the scalar to be annealed.
exponent: Float. The default decay is 0.5 * (1 + cos(pi * t/T)), where t is
the current timestep and T is the `decay_steps`. The exponent modifies
this to be (0.5 * (1 + cos(pi * t/T))) ** exponent. Defaults to 1.0.
Returns:
schedule: A function that maps step counts to values.
"""
schedules = [
linear_schedule(
init_value=init_value,
end_value=peak_value,
transition_steps=warmup_steps),
cosine_decay_schedule(
init_value=peak_value,
decay_steps=decay_steps - warmup_steps,
alpha=end_value/peak_value,
exponent=exponent)]
return join_schedules(schedules, [warmup_steps])
def warmup_exponential_decay_schedule(
init_value: float,
peak_value: float,
warmup_steps: int,
transition_steps: int,
decay_rate: float,
transition_begin: int = 0,
staircase: bool = False,
end_value: Optional[float] = None
) -> base.Schedule:
"""Linear warmup followed by exponential decay.
Args:
init_value: Initial value for the scalar to be annealed.
peak_value: Peak value for scalar to be annealed at end of warmup.
warmup_steps: Positive integer, the length of the linear warmup.
transition_steps: must be positive. See `exponential_decay` for more
details.
decay_rate: must not be zero. The decay rate.
transition_begin: must be positive. After how many steps to start annealing
(before this many steps the scalar value is held fixed at `peak_value`).
staircase: if `True`, decay the values at discrete intervals.
end_value: the value at which the exponential decay stops. When
`decay_rate` < 1, `end_value` is treated as a lower bound, otherwise as
an upper bound. Has no effect when `decay_rate` = 0.
Returns:
schedule: A function that maps step counts to values.
"""
schedules = [
linear_schedule(
init_value=init_value,
end_value=peak_value,
transition_steps=warmup_steps),
exponential_decay(
init_value=peak_value,
transition_steps=transition_steps,
decay_rate=decay_rate,
transition_begin=transition_begin,
staircase=staircase,
end_value=end_value)]
return join_schedules(schedules, [warmup_steps])
def sgdr_schedule(cosine_kwargs: Iterable[Dict[str, chex.Numeric]]
) -> base.Schedule:
"""SGD with warm restarts, from Loschilov & Hutter (arXiv:1608.03983).
This learning rate schedule applies multiple joined cosine decay cycles.
For more details see: https://arxiv.org/abs/1608.03983
Args:
cosine_kwargs: An Iterable of dicts, where each element specifies the
arguments to pass to each cosine decay cycle. The `decay_steps` kwarg
will specify how long each cycle lasts for, and therefore when to
transition to the next cycle.
Returns:
schedule: A function that maps step counts to values.
"""
boundaries = []
schedules = []
step = 0
for kwargs in cosine_kwargs:
schedules += [warmup_cosine_decay_schedule(**kwargs)]
boundaries += [step + kwargs['decay_steps']]
step += kwargs['decay_steps']
return join_schedules(schedules, boundaries[:-1])
def _convert_floats(x, dtype):
"""Convert float-like inputs to dtype, rest pass through."""
if jax.dtypes.scalar_type_of(x) == float:
return jnp.asarray(x, dtype=dtype)
return x
class InjectHyperparamsState(NamedTuple):
"""Maintains inner transform state, hyperparameters, and step count."""
count: jnp.ndarray # shape=(), dtype=jnp.int32
hyperparams: Dict[str, chex.Numeric]
inner_state: base.OptState
def inject_hyperparams(
inner_factory: Callable[..., base.GradientTransformation],
static_args: Union[str, Iterable[str]] = (),
hyperparam_dtype: Optional[jnp.dtype] = None,
) -> Callable[..., base.GradientTransformation]:
"""Wrapper that injects hyperparameters into the inner GradientTransformation.
This wrapper allows you to pass schedules (i.e. a function that returns a
numeric value given a step count) instead of constants for
hyperparameters. You may only schedule numeric hyperparameters (i.e. boolean
flags cannot be scheduled).
For example, to use ``scale_by_adam`` with a piecewise linear
schedule for beta_1 and constant for beta_2::
scheduled_adam = optax.inject_hyperparams(optax.scale_by_adam)(
b1=optax.piecewise_linear_schedule(...),
b2=0.99)
You may manually change numeric hyperparameters that were not scheduled
through the ``hyperparams`` dict in the ``InjectHyperparamState``::
state = scheduled_adam.init(params)
updates, state = scheduled_adam.update(grads, state)
state.hyperparams['b2'] = 0.95
updates, state = scheduled_adam.update(updates, state) # uses b2 = 0.95
Manually overriding scheduled hyperparameters will have no effect (e.g.
in the code sample above, you cannot manually adjust ``b1``).
Args:
inner_factory: a function that returns the inner
``optax.GradientTransformation`` given the hyperparameters.
static_args: a string or iterable of strings specifying which
callable parameters are not schedules. inject_hyperparams treats all
callables as schedules by default, so if a hyperparameter is a
non-schedule callable, you must specify that using this argument.
hyperparam_dtype: Optional datatype override. If specified, all float
hyperparameters will be cast to this type.
Returns:
A callable that returns a ``optax.GradientTransformation``. This callable
accepts the same arguments as ``inner_factory``, except you may provide
schedules in place of the constant arguments.
"""
static_args = ({static_args} if isinstance(static_args, str) else
set(static_args))
inner_signature = inspect.signature(inner_factory)
if not static_args.issubset(inner_signature.parameters):
raise ValueError(
'`static_args` must specify a subset of `inner_factory`\'s parameters. '
f'Given `static_args`: {static_args}. `inner_factory` parameters: '
f'{set(inner_signature.parameters.keys())}')
@functools.wraps(inner_factory)
def wrapped_transform(*args, **kwargs) -> base.GradientTransformation:
bound_arguments = inner_signature.bind(*args, **kwargs)
bound_arguments.apply_defaults()
sched_hps, numeric_hps, other_hps = {}, {}, {}
for name, value in bound_arguments.arguments.items():
if name in static_args or isinstance(value, bool):
other_hps[name] = value
elif callable(value):
sched_hps[name] = value
elif isinstance(value, (int, float, jax.Array, np.ndarray)):
numeric_hps[name] = value
else:
other_hps[name] = value
def schedule_fn(count, dtype):
return {k: _convert_floats(f(count), dtype) for k, f in sched_hps.items()}
def init_fn(params):
count = jnp.zeros([], jnp.int32)
if hyperparam_dtype is None:
dtype = getattr(next(iter(
jax.tree_util.tree_leaves(params)), None), 'dtype', None)
else:
dtype = hyperparam_dtype
hparams = {
k: jnp.asarray(_convert_floats(v, dtype))
for k, v in numeric_hps.items()}
hparams.update(schedule_fn(count, dtype))
return InjectHyperparamsState( # pylint:disable=too-many-function-args
count, hparams, inner_factory(**other_hps, **hparams).init(params))
def update_fn(updates, state, params=None):
if hyperparam_dtype is None:
dtype = getattr(next(iter(
jax.tree_util.tree_leaves(updates)), None), 'dtype', None)
else:
dtype = hyperparam_dtype
hparams = {k: _convert_floats(v, dtype)
for k, v in state.hyperparams.items()}
hparams.update(schedule_fn(state.count, dtype))
updates, inner_state = inner_factory(**other_hps, **hparams).update(
updates, state.inner_state, params)
count_inc = numerics.safe_int32_increment(state.count)
# pylint:disable=too-many-function-args
return updates, InjectHyperparamsState(count_inc, hparams, inner_state)
# pylint:enable=too-many-function-args
return base.GradientTransformation(init_fn, update_fn)
return wrapped_transform
| optax-master | optax/_src/schedule.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A lookahead optimization wrapper."""
from typing import NamedTuple, Tuple, Union
from absl import logging
import jax
import jax.numpy as jnp
from optax._src import base
# pylint:disable=no-value-for-parameter
class LookaheadState(NamedTuple):
"""State of the `GradientTransformation` returned by `lookahead`.
Attributes:
fast_state: Optimizer state of the fast optimizer.
steps_since_sync: Number of fast optimizer steps taken since slow and fast
parameters were synchronized.
"""
fast_state: base.OptState
steps_since_sync: jnp.ndarray
class LookaheadParams(NamedTuple):
"""Holds a pair of slow and fast parameters for the lookahead optimizer.
Gradients should always be calculated with the fast parameters. The slow
parameters should be used for testing and inference as they generalize better.
See the reference for a detailed discussion.
References:
[Zhang et al, 2019](https://arxiv.org/pdf/1907.08610v1.pdf)
Attributes:
fast: Fast parameters.
slow: Slow parameters.
"""
fast: base.Params
slow: base.Params
@classmethod
def init_synced(cls, params: base.Params) -> 'LookaheadParams':
"""Initialize a pair of synchronized lookahead parameters."""
return cls(slow=params, fast=params)
def lookahead(
fast_optimizer: base.GradientTransformation,
sync_period: int,
slow_step_size: float,
reset_state: bool = False
) -> base.GradientTransformation:
"""Lookahead optimizer.
Performs steps with a fast optimizer and periodically updates a set of slow
parameters. Optionally resets the fast optimizer state after synchronization
by calling the init function of the fast optimizer.
Updates returned by the lookahead optimizer should not be modified before they
are applied, otherwise fast and slow parameters are not synchronized
correctly.
References:
[Zhang et al, 2019](https://arxiv.org/pdf/1907.08610v1.pdf)
Args:
fast_optimizer: The optimizer to use in the inner loop of lookahead.
sync_period: Number of fast optimizer steps to take before synchronizing
parameters. Must be >= 1.
slow_step_size: Step size of the slow parameter updates.
reset_state: Whether to reset the optimizer state of the fast opimizer after
each synchronization.
Returns:
A `GradientTransformation` with init and update functions. The updates
passed to the update function should be calculated using the fast lookahead
parameters only.
"""
if sync_period < 1:
raise ValueError('Synchronization period must be >= 1.')
def init_fn(params: base.Params) -> LookaheadState:
fast_params = getattr(params, 'fast', None)
if fast_params is None:
# Allowing init_fn to be called with fast parameters reduces the
# modifications necessary to adapt code to use lookahead in some cases.
logging.warning(
'`params` has no attribute `fast`. Continuing by assuming that '
'only fast parameters were passed to lookahead init.')
fast_params = params
return LookaheadState(
fast_state=fast_optimizer.init(fast_params),
steps_since_sync=jnp.zeros(shape=(), dtype=jnp.int32))
def update_fn(
updates: base.Updates, state: LookaheadState,
params: LookaheadParams) -> Tuple[LookaheadParams, LookaheadState]:
updates, fast_state = fast_optimizer.update(updates, state.fast_state,
params.fast)
sync_next = state.steps_since_sync == sync_period - 1
updates = _lookahead_update(updates, sync_next, params, slow_step_size)
if reset_state:
# Jittable way of resetting the fast optimizer state if parameters will be
# synchronized after this update step.
initial_state = fast_optimizer.init(params.fast)
fast_state = jax.tree_util.tree_map(
lambda current, init: (1 - sync_next) * current + sync_next * init,
fast_state, initial_state)
steps_since_sync = (state.steps_since_sync + 1) % sync_period
return updates, LookaheadState(fast_state, steps_since_sync)
return base.GradientTransformation(init_fn, update_fn)
def _lookahead_update(
updates: base.Updates, sync_next: Union[bool, jax.Array],
params: LookaheadParams, slow_step_size: float) -> LookaheadParams:
"""Returns the updates corresponding to one lookahead step.
References:
[Zhang et al, 2019](https://arxiv.org/pdf/1907.08610v1.pdf)
Args:
updates: Updates returned by the fast optimizer.
sync_next: Wether fast and slow parameters should be synchronized after the
fast optimizer step.
params: Current fast and slow parameters as `LookaheadParams` object.
slow_step_size: Step size of the slow optimizer.
Returns:
The updates for the lookahead parameters.
"""
# In the paper, lookahead is presented as two nested loops. To write lookahead
# as optax wrapper, these loops have to be broken into successive updates.
# This leads to two types of update steps:
#
# Non-synchronization steps (sync_next == False):
# The updates returned by the fast optimizer are used for the fast parameters
# without change and the slow parameter updates are zero (i.e. fast_updates =
# updates, slow_updates = 0).
#
# Synchronisation step (sync_next == True):
# This consists of two substeps: a last fast optimizer step and the
# synchronization.
# Substep 1 (last fast optimizer step):
# last_fast_params = fast_params + updates
# Substep 2 (synchronization):
# new_slow_params = slow_params + slow_step_size * (
# last_fast_params - slow_params)
# new_fast_params = new_slow_params
#
# Merging into a single update step we get the update rules:
# slow_updates = slow_step_size * (fast_params + updates - slow_params)
# fast_updates = new_slow_params - fast_params = updates - (1 -
# slow_step_size) * (fast_params + updates - slow_params)
#
# To make the equations jittable, the two types of steps are merged. Defining
# last_difference = fast_params + updates - slow_params, this yields the
# following equtions which are implemented below:
# slow_updates = slow_step_size * sync_next * last_difference
# fast_updates = updates - (
# 1 - slow_step_size) * sync_next * last_difference
last_difference = jax.tree_util.tree_map(
lambda f, u, s: f + u - s, params.fast, updates, params.slow)
slow_updates = jax.tree_util.tree_map(
lambda diff: slow_step_size * sync_next * diff, last_difference)
fast_updates = jax.tree_util.tree_map(
lambda up, diff: up - sync_next * (1 - slow_step_size) * diff, updates,
last_difference)
return LookaheadParams(fast=fast_updates, slow=slow_updates)
| optax-master | optax/_src/lookahead.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests of equivalence between optax and other optimiser libraries."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
from jax.example_libraries import optimizers
import jax.numpy as jnp
from optax._src import alias
from optax._src import update
STEPS = 50
LR = 1e-2
LR_SCHED = lambda _: LR # Trivial constant "schedule".
class OptimizersEquivalenceTest(chex.TestCase):
def setUp(self):
super().setUp()
self.init_params = (jnp.array([1., 2.]), jnp.array([3., 4., 5.]))
self.per_step_updates = (jnp.array([500., 5.]), jnp.array([300., 3., 1.]))
@chex.all_variants
@parameterized.named_parameters(
('sgd', alias.sgd(LR, 0.0),
optimizers.sgd(LR), 1e-5),
('adam', alias.adam(LR, 0.9, 0.999, 1e-8),
optimizers.adam(LR, 0.9, 0.999), 1e-4),
('rmsprop', alias.rmsprop(LR, decay=.9, eps=0.1),
optimizers.rmsprop(LR, .9, 0.1), 1e-5),
('rmsprop_momentum', alias.rmsprop(
LR, decay=.9, eps=0.1, momentum=0.9),
optimizers.rmsprop_momentum(LR, .9, 0.1, 0.9), 1e-5),
('adagrad', alias.adagrad(LR, 0., 0.,),
optimizers.adagrad(LR, 0.), 1e-5),
('sgd', alias.sgd(LR_SCHED, 0.0),
optimizers.sgd(LR), 1e-5),
('adam', alias.adam(LR_SCHED, 0.9, 0.999, 1e-8),
optimizers.adam(LR, 0.9, 0.999), 1e-4),
('rmsprop', alias.rmsprop(LR_SCHED, decay=.9, eps=0.1),
optimizers.rmsprop(LR, .9, 0.1), 1e-5),
('rmsprop_momentum', alias.rmsprop(
LR_SCHED, decay=.9, eps=0.1, momentum=0.9),
optimizers.rmsprop_momentum(LR, .9, 0.1, 0.9), 1e-5),
('adagrad', alias.adagrad(LR_SCHED, 0., 0.,),
optimizers.adagrad(LR, 0.), 1e-5),
('sm3', alias.sm3(LR), optimizers.sm3(LR), 1e-2),
)
def test_jax_optimizer_equivalent(self, optax_optimizer, jax_optimizer, rtol):
# example_libraries/optimizers.py
jax_params = self.init_params
opt_init, opt_update, get_params = jax_optimizer
state = opt_init(jax_params)
for i in range(STEPS):
state = opt_update(i, self.per_step_updates, state)
jax_params = get_params(state)
# optax
optax_params = self.init_params
state = optax_optimizer.init(optax_params)
@self.variant
def step(updates, state):
return optax_optimizer.update(updates, state)
for _ in range(STEPS):
updates, state = step(self.per_step_updates, state)
optax_params = update.apply_updates(optax_params, updates)
# Check equivalence.
chex.assert_trees_all_close(jax_params, optax_params, rtol=rtol)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/equivalence_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `combine.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
from optax._src import alias
from optax._src import base
from optax._src import combine
from optax._src import transform
from optax._src import update
STEPS = 50
LR = 1e-2
class ComposeTest(chex.TestCase):
def setUp(self):
super().setUp()
self.init_params = (jnp.array([1., 2.]), jnp.array([3., 4.]))
self.per_step_updates = (jnp.array([500., 5.]), jnp.array([300., 3.]))
@chex.all_variants
def test_chain(self):
transformations = [
transform.scale_by_adam(),
transform.trace(decay=0, nesterov=False),
transform.scale(-LR)]
# Apply updates with chain.
chain_params = self.init_params
chained_transforms = combine.chain(*transformations)
state = chained_transforms.init(chain_params)
self.assertIsInstance(state, tuple)
@self.variant
def update_fn(updates, state):
return chained_transforms.update(updates, state)
for _ in range(STEPS):
updates, state = update_fn(self.per_step_updates, state)
self.assertIsInstance(state, tuple)
chain_params = update.apply_updates(chain_params, updates)
# Manually apply sequence of transformations.
manual_params = self.init_params
states = [t.init(manual_params) for t in transformations]
for _ in range(STEPS):
updates = self.per_step_updates
new_states = []
for t, s in zip(transformations, states):
updates, state = t.update(updates, s)
new_states.append(state)
manual_params = update.apply_updates(manual_params, updates)
states = new_states
# Check equivalence.
chex.assert_trees_all_close(manual_params, chain_params, rtol=1e-4)
def _map_keys_fn(fn):
def map_fn(nested_dict):
return {k: (map_fn(v) if isinstance(v, dict) else fn(k, v))
for k, v in nested_dict.items()}
return map_fn
class ExtraArgsTest(chex.TestCase):
def test_extra_args(self):
def init_fn(params):
del params
return tuple()
# Arguments required by a transformation should be keyword-only.
# For example, the loss argument in this transformation.
def update_fn(updates, state, params=None, *, loss, **extra_args):
# Extra args should always be accepted.
del extra_args, params
assert loss == 1
return updates, state
t = base.GradientTransformationExtraArgs(init_fn, update_fn)
result = combine.chain(alias.adam(1e-3), t)
self.assertIsInstance(result, base.GradientTransformationExtraArgs)
params = {'a': 1, 'b': 2}
state = result.init(params)
result.update(params, state, loss=1, ignored_kwarg='hi')
def test_extra_args_chaining(self):
def init_fn(params):
del params
return {}
def update_fn(updates, state, params=None):
del params
return updates, state
# Possible gotcha: Chaining regular gradient transformations results in
# a transformation that supports extra args.
t1 = base.GradientTransformation(init_fn, update_fn)
t2 = combine.chain(t1, t1)
self.assertIsInstance(t2, base.GradientTransformation)
self.assertIsInstance(t2, base.GradientTransformationExtraArgs)
t3 = base.with_extra_args_support(t2)
self.assertIsInstance(t3, base.GradientTransformationExtraArgs)
def test_extra_args_positional_params(self):
def init_fn(params):
del params
return tuple()
def update_fn(updates, state, params=None):
assert params is not None
return updates, state
def update_fn_kwargs(updates, state, params=None, **extra_args):
del extra_args
assert params is not None
return updates, state
t1 = base.GradientTransformation(init_fn, update_fn)
t2 = base.GradientTransformationExtraArgs(init_fn, update_fn_kwargs)
opt = combine.chain(t1, t2)
params = {'a': 1, 'b': 2}
state = opt.init(params)
opt.update(params, state, params, ignored_kwarg='hi')
opt.update(params, state, params=params, ignored_kwarg='hi')
class MultiTransformTest(chex.TestCase):
"""Tests for the multi_transform wrapper."""
@chex.all_variants
@parameterized.parameters(True, False)
def test_multi_transform(self, use_fn):
params = {'a1': 1., 'b1': 2., 'z1': {'a2': 3., 'z2': {'c1': 4.}}}
params = jax.tree_util.tree_map(jnp.asarray, params)
input_updates = jax.tree_util.tree_map(lambda x: x / 10.0, params)
tx_dict = {'a': transform.scale(-1.0),
'b': transform.ema(0.0), # stateful
'c': transform.scale(2.0)}
param_labels = _map_keys_fn(lambda k, _: k[0])
if not use_fn:
param_labels = param_labels(params)
tx = combine.multi_transform(tx_dict, param_labels)
update_fn = self.variant(tx.update)
state = self.variant(tx.init)(params)
correct_update_fn = _map_keys_fn(
lambda k, v: {'a': -v, 'b': v, 'c': 2.0*v}[k[0]])
updates, state = update_fn(input_updates, state, params)
correct_updates = correct_update_fn(input_updates)
chex.assert_trees_all_close(updates, correct_updates)
# Check repeated application, this time with no params.
correct_updates = correct_update_fn(correct_updates)
updates, state = update_fn(updates, state)
chex.assert_trees_all_close(updates, correct_updates)
def test_extra_args(self):
class ArgNotEqual1Error(ValueError):
"""Raised when argument not set as expected."""
def init(params):
return {'mu': params}
def update_with_arg(updates, state, params=None, *, arg, **extra_args):
del params, extra_args
if arg != 1:
raise ArgNotEqual1Error()
return updates, state
def update_without_arg(updates, state, params=None):
del params
return updates, state
opt_no_arg = base.GradientTransformation(init, update_without_arg)
opt_extra_arg = base.GradientTransformationExtraArgs(init, update_with_arg)
opt = combine.multi_transform(
{
'a': opt_no_arg,
'b': opt_extra_arg,
},
('a', 'b'),
)
fake_params = ({'u': jnp.array([1])}, {'v': jnp.array([1])})
state = opt.init(fake_params)
with self.assertRaises(TypeError):
opt.update(fake_params, state)
with self.assertRaises(ArgNotEqual1Error):
opt.update(fake_params, state, arg=2, ignored_kwarg='hi')
opt.update(fake_params, state, arg=1, ignored_kwarg='hi')
@parameterized.parameters(list, tuple, dict)
def test_empty(self, container):
init_fn, update_fn = combine.multi_transform(
{0: alias.sgd(1.)}, lambda _: 0)
updates, _ = update_fn(container(), init_fn(container()))
self.assertEqual(updates, container())
@chex.all_variants
@parameterized.parameters(
(False, False), (False, True), (True, False), (True, True))
def test_labels_mismatch(self, use_extra_label, use_fn):
# The labels from label_fn must be a subet of the keys for the tx.
params = {'a': 1., 'b': [2., 3.], 'c': {'d': 4., 'e': (5., 6.)}}
params = jax.tree_util.tree_map(jnp.asarray, params)
label_tree = {'a': 0, 'b': [1, 0], 'c': 1} # prefix of params
if use_extra_label:
label_tree['a'] = 3
transforms = {0: alias.sgd(1.),
1: alias.adam(1., b1=0., b2=0.),
2: transform.trace(1.0)}
init_fn, update_fn = combine.multi_transform(
transforms, (lambda _: label_tree) if use_fn else label_tree)
if use_extra_label:
with self.assertRaises(ValueError):
self.variant(init_fn)(params)
else:
state = self.variant(init_fn)(params)
updates = jax.tree_util.tree_map(lambda x: x / 10.0, params)
self.variant(update_fn)(updates, state)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/combine_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Factorized optimizers."""
import dataclasses
from typing import NamedTuple, Optional, Tuple, Callable
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import base
from optax._src import numerics
from optax._src import utils
# pylint:disable=no-value-for-parameter
def _decay_rate_pow(i: int, exponent: float = 0.8) -> chex.Array:
"""Second-order moment decay schedule."""
t = jnp.array(i + 1, jnp.float32)
return 1.0 - t**(-exponent)
def _factored_dims(
shape: base.Shape,
factored: bool,
min_dim_size_to_factor: int
) -> Optional[Tuple[int, int]]:
"""Whether to use a factored second moment estimator.
This function returns a tuple with the two largest axes to reduce over.
If no two dimensions have size >= min_dim_size_to_factor, return None.
Args:
shape: an input shape
factored: whether to use factored second-moment estimator for 2d vars.
min_dim_size_to_factor: only factor accumulator if two array dimensions
have at least this size.
Returns:
None or a tuple of ints
"""
if not factored or len(shape) < 2:
return None
sorted_dims = np.argsort(shape)
if shape[sorted_dims[-2]] < min_dim_size_to_factor:
return None
return int(sorted_dims[-2]), int(sorted_dims[-1])
@dataclasses.dataclass
class _UpdateResult:
"""Opaque containter that is not traversed by jax.tree_util.tree_map."""
update: chex.Array # the update to apply to params
v_row: chex.Array # used for factored params.
v_col: chex.Array # used for factored params.
v: chex.Array # used for params where factoring is skipped.
class FactoredState(NamedTuple):
"""Overall state of the gradient transformation."""
count: chex.Array # number of update steps.
v_row: chex.ArrayTree # Tree of factored params.
v_col: chex.ArrayTree # Tree of factored params.
v: chex.ArrayTree # Tree for params where factoring is skipped.
def scale_by_factored_rms(
factored: bool = True,
decay_rate: float = 0.8,
step_offset: int = 0,
min_dim_size_to_factor: int = 128,
epsilon: float = 1e-30,
decay_rate_fn: Callable[[int, float], chex.Array] = _decay_rate_pow):
"""Scaling by a factored estimate of the gradient rms (as in Adafactor).
This is a so-called "1+epsilon" scaling algorithms, that is extremely memory
efficient compared to RMSProp/Adam, and has had wide success when applied to
large-scale training of attention-based models.
References:
[Shazeer et al, 2018](https://arxiv.org/abs/1804.04235)
Args:
factored: boolean: whether to use factored second-moment estimates..
decay_rate: float: controls second-moment exponential decay schedule.
step_offset: for finetuning, one may set this to the starting step-number
of the fine tuning phase.
min_dim_size_to_factor: only factor accumulator if two array dimensions
are at least this size.
epsilon: Regularization constant for squared gradient.
decay_rate_fn: A function that accepts the current step, the decay rate
parameter and controls the schedule for the second momentum. Defaults to
the original adafactor's power decay schedule. One potential shortcoming
of the orignal schedule is the fact that second momentum converges to 1,
which effectively freezes the second momentum. To prevent this the user
can opt for a custom schedule that sets an upper bound for the second
momentum, like in [Zhai et al., 2021](https://arxiv.org/abs/2106.04560).
Returns:
the corresponding `GradientTransformation`.
"""
def _to_state(count: chex.Array, result_tree):
"""Maps from a tree of (factored) values to separate trees of values."""
return FactoredState(
count=count,
v_row=jax.tree_util.tree_map(lambda o: o.v_row, result_tree),
v_col=jax.tree_util.tree_map(lambda o: o.v_col, result_tree),
v=jax.tree_util.tree_map(lambda o: o.v, result_tree))
def init_fn(params):
"""Initialise the optimiser's state."""
def _init(param):
shape = param.shape
factored_dims = _factored_dims(shape, factored, min_dim_size_to_factor)
if factored_dims is not None:
d1, d0 = factored_dims
vr_shape = np.delete(shape, d0)
vc_shape = np.delete(shape, d1)
return _UpdateResult(
update=jnp.zeros((1,)),
v_row=jnp.zeros(vr_shape),
v_col=jnp.zeros(vc_shape),
v=jnp.zeros((1,)))
else:
return _UpdateResult(
update=jnp.zeros((1,)),
v_row=jnp.zeros((1,)),
v_col=jnp.zeros((1,)),
v=jnp.zeros(param.shape))
return _to_state(
jnp.zeros([], jnp.int32), jax.tree_util.tree_map(_init, params))
def update_fn(grads, state, params):
"""Apply gradient transformation."""
if params is None:
raise ValueError(base.NO_PARAMS_MSG)
def _update(grad, v_row, v_col, v, param, step):
shape = param.shape
decay_rate_t = decay_rate_fn(step - step_offset, decay_rate)
# Scaled by factorized second moment statistics.
new_v_row = jnp.zeros((1,))
new_v_col = jnp.zeros((1,))
new_v = jnp.zeros((1,))
factored_dims = _factored_dims(shape, factored, min_dim_size_to_factor)
if factored_dims is not None:
d1, d0 = factored_dims
grad_sqr = numerics.abs_sq(grad) + epsilon
new_v_row = (
decay_rate_t * v_row +
(1. - decay_rate_t) * jnp.mean(grad_sqr, axis=d0))
new_v_col = (
decay_rate_t * v_col +
(1. - decay_rate_t) * jnp.mean(grad_sqr, axis=d1))
reduced_d1 = d1-1 if d1 > d0 else d1
row_col_mean = jnp.mean(new_v_row, axis=reduced_d1, keepdims=True)
row_factor = (new_v_row / row_col_mean) ** -0.5
col_factor = (new_v_col) ** -0.5
update = (
grad *
jnp.expand_dims(row_factor, axis=d0) *
jnp.expand_dims(col_factor, axis=d1))
else:
grad_sqr = numerics.abs_sq(grad) + epsilon
new_v = decay_rate_t * v + (1. - decay_rate_t) * grad_sqr
update = grad * (new_v)**-0.5
return _UpdateResult(update, new_v_row, new_v_col, new_v)
# Transform grad and compute new per-parameter stats.
output = jax.tree_util.tree_map(
lambda *args: _update(*args, state.count),
grads, state.v_row, state.v_col, state.v, params)
# Unpack updates / stats and return.
updates = jax.tree_util.tree_map(lambda o: o.update, output)
return updates, _to_state(utils.safe_int32_increment(state.count), output)
return base.GradientTransformation(init_fn, update_fn)
| optax-master | optax/_src/factorized.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Base interfaces and datatypes."""
from typing import Any, Callable, NamedTuple, Optional, Protocol, Sequence, Tuple
import chex
import jax
import jax.numpy as jnp
NO_PARAMS_MSG = (
'You are using a transformation that requires the current value of '
'parameters, but you are not passing `params` when calling `update`.')
PyTree = Any
Shape = Sequence[int]
OptState = chex.ArrayTree # States are arbitrary nests of `jnp.ndarrays`.
Params = chex.ArrayTree # Parameters are arbitrary nests of `jnp.ndarrays`.
Updates = Params # Gradient updates are of the same type as parameters.
Schedule = Callable[[chex.Numeric], chex.Numeric]
class TransformInitFn(Protocol):
"""A callable type for the `init` step of a `GradientTransformation`.
The `init` step takes a tree of `params` and uses these to construct an
arbitrary structured initial `state` for the gradient transformation. This
may hold statistics of the past updates or any other non static information.
"""
def __call__(self, params: Params) -> OptState:
"""The `init` function.
Args:
params: The initial value of the parameters.
Returns:
The initial state of the gradient transformation.
"""
class TransformUpdateFn(Protocol):
"""A callable type for the `update` step of a `GradientTransformation`.
The `update` step takes a tree of candidate parameter `updates` (e.g. their
gradient with respect to some loss), an arbitrary structured `state`, and the
current `params` of the model being optimised. The `params` argument is
optional, it must however be provided when using transformations that require
access to the current values of the parameters.
For the case where additional arguments are required, an alternative interface
may be used, see ``TransformUpdateExtraArgsFn`` for details.
"""
def __call__(
self,
updates: Updates,
state: OptState,
params: Optional[Params] = None
) -> Tuple[Updates, OptState]:
"""The `update` function.
Args:
updates: A tree of candidate updates.
state: The state of the gradient transformation.
params: (Optionally) the current value of the parameters.
Returns:
The transformed updates, and the updated state.
"""
class TransformUpdateExtraArgsFn(Protocol):
"""An update function accepting additional keyword arguments."""
def __call__(
self,
updates: Updates,
state: OptState,
params: Optional[Params] = None,
**extra_args: Any,
) -> Tuple[Updates, OptState]:
"""Update function with optional extra arguments.
For example, an update function that requires an additional loss parameter
(which might be useful for implementing learning rate schedules that depend
on the current loss value) could be expressed as follows.
>>> def update(updates, state, params=None, *, loss, **extra_args):
>>> del extra_args
>>> # use loss value
Note that the loss value is keyword only, (it follows a `*` in the
signature of the function). This means users will get explicit errors if
they try to use this gradient transformation without providing the required
argument.
Args:
updates: The gradient updates passed to this transformation.
state: The state associated with this transformation
params: Optional params.
**extra_args: Additional keyword arguments passed to this transform. All
implementors of this interface should accept arbitrary keyword
arguments, ignoring those that are not needed for the current
transformation. Transformations that require specific extra args should
specify these using keyword-only arguments.
Returns:
Transformed updates, and an updated value for the state.
"""
class GradientTransformation(NamedTuple):
"""A pair of pure functions implementing a gradient transformation.
Optax optimizers are all implemented as _gradient transformations_.
A gradient transformation is defined to be a pair of pure functions, which
are combined together in a `NamedTuple` so that they can be referred to by
name.
Note that an extended API is provided for users wishing to build optimizers
that take additional arguments during the update step. For more details,
see ``GradientTransoformationExtraArgs``.
Since gradient transformations do not contain any internal state, all stateful
optimizer properties (such as the current step count when using optimizer
scheduels, or momemtum values) are passed through optax gradient
transformations by using the optimizer _state_ pytree. Each time a gradient
transformation is applied, a new state is computed and returned, ready to be
passed to the next call to the gradient transformation.
Since gradient transformations are pure, idempotent functions, the only way
to change the behaviour of a gradient transformation between steps, is to
change the values in the optimizer state. To see an example of mutating the
optimizer state in order to control the behaviour of an optax gradient
transformation, see the meta-learning example in the optax documentation.
Attributes:
init: A pure function which, when called with an example instance of the
parameters whose gradients will be transformed, returns a pytree
containing the initial value for the optimizer state.
update: A pure function which takes as input a pytree of updates (with the
same tree structure as the original params pytree passed to init), the
previous optimizer state (which may have been initialized using the init
function), and optionally the current params. The update function then
returns the computed gradient updates, and a new optimizer state.
"""
init: TransformInitFn
update: TransformUpdateFn
class GradientTransformationExtraArgs(GradientTransformation):
"""A specialization of GradientTransformation that supports extra args.
Extends the existing GradientTransformation interface by adding support for
passing extra arguments to the update function.
Note that if no extra args are provided, then the API of this function is
identical to the case of ``TransformUpdateFn``. This means that we can safely
wrap any gradient transformation (that does not support extra args) as one
that does. The new gradient transformation will accept (and ignore) any
extra arguments that a user might pass to it. This is the behavior implemented
by ``optax.with_extra_args_support()``.
Attributes:
update: Overrides the type signature of the update in the base type to
accept extra arguments.
"""
update: TransformUpdateExtraArgsFn
class EmptyState(NamedTuple):
"""An empty state for the simplest stateless transformations."""
def identity() -> GradientTransformation:
"""Stateless identity transformation that leaves input gradients untouched.
This function passes through the *gradient updates* unchanged.
Note, this should not to be confused with `set_to_zero`, which maps the input
updates to zero - which is the transform required for the *model parameters*
to be left unchanged when the updates are applied to them.
Returns:
A `GradientTransformation` object.
"""
def init_fn(_):
return EmptyState()
def update_fn(updates, state, params=None):
del params
return updates, state
return GradientTransformation(init_fn, update_fn)
def set_to_zero() -> GradientTransformation:
"""Stateless transformation that maps input gradients to zero.
The resulting update function, when called, will return a tree of zeros
matching the shape of the input gradients. This means that when the updates
returned from this transformation are applied to the model parameters, the
model parameters will remain unchanged.
This can be used in combination with `multi_transform` or `masked` to freeze
(i.e. keep fixed) some parts of the tree of model parameters while applying
gradient updates to other parts of the tree.
When updates are set to zero inside the same jit-compiled function as the
calculation of gradients, optax transformations, and application of updates to
parameters, unnecessary computations will in general be dropped.
Returns:
A `GradientTransformation` object.
"""
def init_fn(params):
del params
return EmptyState()
def update_fn(updates, state, params=None):
del params # Unused by the zero transform.
return jax.tree_util.tree_map(jnp.zeros_like, updates), state
return GradientTransformation(init_fn, update_fn)
def stateless(
f: Callable[[Updates, Optional[Params]], Updates],
) -> GradientTransformation:
"""Creates a stateless transformation from an update-like function.
This wrapper eliminates the boilerplate needed to create a transformation that
does not require saved state between iterations.
Args:
f: Update function that takes in updates (e.g. gradients) and parameters
and returns updates. The parameters may be `None`.
Returns:
An `optax.GradientTransformation`.
"""
def init_fn(_):
return EmptyState()
def update_fn(updates, state, params=None):
del state
return f(updates, params), EmptyState()
return GradientTransformation(init_fn, update_fn)
def stateless_with_tree_map(
f: Callable[[chex.Array, Optional[chex.Array]], chex.Array],
) -> GradientTransformation:
"""Creates a stateless transformation from an update-like function for arrays.
This wrapper eliminates the boilerplate needed to create a transformation that
does not require saved state between iterations, just like optax.stateless.
In addition, this function will apply the tree_map over update/params for you.
Args:
f: Update function that takes in an update array (e.g. gradients) and
parameter array and returns an update array. The parameter array may be
`None`.
Returns:
An `optax.GradientTransformation`.
"""
def init_fn(_):
return EmptyState()
def update_fn(updates, state, params=None):
del state
if params is not None:
return jax.tree_util.tree_map(f, updates, params), EmptyState()
else:
f_ = lambda u: f(u, None)
return jax.tree_util.tree_map(f_, updates), EmptyState()
return GradientTransformation(init_fn, update_fn)
def with_extra_args_support(
tx: GradientTransformation,
) -> GradientTransformationExtraArgs:
"""Wraps a gradient transformation, so that it ignores extra args."""
if isinstance(tx, GradientTransformationExtraArgs):
return tx
def update(updates, state, params=None, **extra_args):
del extra_args
return tx.update(updates, state, params)
return GradientTransformationExtraArgs(tx.init, update)
| optax-master | optax/_src/base.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities to ensure the implementation is safe wrt numerical issues.
Note that complex numbers are also supported, see
https://gist.github.com/wdphy16/118aef6fb5f82c49790d7678cf87da29
"""
from typing import Optional, Tuple, Union
import chex
import jax.numpy as jnp
import numpy as np
# TODO(jscholz) Promote these functions to jax core lib?
def abs_sq(x: chex.Array) -> chex.Array:
"""Returns the squared norm of a (maybe complex) array.
For real `x`, JAX generates the same HLO from this, `jnp.square(x)`, `x * x`,
or `x**2`.
Args:
x: a (maybe complex) array.
Returns:
The squared norm of `x`.
"""
if not isinstance(x, (np.ndarray, jnp.ndarray)):
raise ValueError(f"`abs_sq` accepts only NDarrays, got: {x}.")
return (x.conj() * x).real
def safe_norm(x: chex.Array,
min_norm: chex.Numeric,
ord: Optional[Union[int, float, str]] = None, # pylint: disable=redefined-builtin
axis: Union[None, Tuple[int, ...], int] = None,
keepdims: bool = False) -> chex.Array:
"""Returns jnp.maximum(jnp.linalg.norm(x), min_norm) with correct gradients.
The gradients of `jnp.maximum(jnp.linalg.norm(x), min_norm)` at 0.0 is `NaN`,
because jax will evaluate both branches of the `jnp.maximum`. This function
will instead return the correct gradient of 0.0 also in such setting.
Args:
x: jax array.
min_norm: lower bound for the returned norm.
ord: {non-zero int, inf, -inf, ‘fro’, ‘nuc’}, optional. Order of the norm.
inf means numpy’s inf object. The default is None.
axis: {None, int, 2-tuple of ints}, optional. If axis is an integer, it
specifies the axis of x along which to compute the vector norms. If axis
is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix
norms of these matrices are computed. If axis is None then either a vector
norm (when x is 1-D) or a matrix norm (when x is 2-D) is returned. The
default is None.
keepdims: bool, optional. If this is set to True, the axes which are normed
over are left in the result as dimensions with size one. With this option
the result will broadcast correctly against the original x.
Returns:
The safe norm of the input vector, accounting for correct gradient.
"""
norm = jnp.linalg.norm(x, ord=ord, axis=axis, keepdims=True)
x = jnp.where(norm <= min_norm, jnp.ones_like(x), x)
norm = jnp.squeeze(norm, axis=axis) if not keepdims else norm
masked_norm = jnp.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims)
return jnp.where(norm <= min_norm, min_norm, masked_norm)
def safe_root_mean_squares(x: chex.Array, min_rms: chex.Numeric) -> chex.Array:
"""Returns `maximum(sqrt(mean(abs_sq(x))), min_norm)` with correct grads.
The gradients of `maximum(sqrt(mean(abs_sq(x))), min_norm)` at 0.0
is `NaN`, because jax will evaluate both branches of the `jnp.maximum`. This
function will instead return the correct gradient of 0.0 also in such setting.
Args:
x: jax array.
min_rms: lower bound for the returned norm.
Returns:
The safe RMS of the input vector, accounting for correct gradient.
"""
rms = jnp.sqrt(jnp.mean(abs_sq(x)))
x = jnp.where(rms <= min_rms, jnp.ones_like(x), x)
return jnp.where(rms <= min_rms, min_rms, jnp.sqrt(jnp.mean(abs_sq(x))))
def safe_int32_increment(count: chex.Numeric) -> chex.Numeric:
"""Increments int32 counter by one.
Normally `max_int + 1` would overflow to `min_int`. This functions ensures
that when `max_int` is reached the counter stays at `max_int`.
Args:
count: a counter to be incremented.
Returns:
A counter incremented by 1, or max_int if the maximum precision is reached.
"""
chex.assert_type(count, jnp.int32)
max_int32_value = jnp.iinfo(jnp.int32).max
one = jnp.array(1, dtype=jnp.int32)
return jnp.where(count < max_int32_value, count + one, max_int32_value)
| optax-master | optax/_src/numerics.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `lookahead.py`."""
from typing import NamedTuple
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import alias
from optax._src import base
from optax._src import lookahead
from optax._src import state_utils
from optax._src import update
def _build_sgd():
return alias.sgd(1.)
class TestOptimizerState(NamedTuple):
"""Fast optimizer state for the lookahead tests."""
aggregate_grads: base.Params
# Include a variable with non-zero initial value to check that it is reset
# correctly by the lookahead optimizer.
is_reset: bool = True
def _test_optimizer(step_size: float) -> base.GradientTransformation:
"""Fast optimizer for the lookahead tests."""
# Use SGD for simplicity but add non-trivial optimizer state so that the
# resetting behaviour of lookahead can be tested.
def init_fn(params):
aggregate_grads = jax.tree_util.tree_map(jnp.zeros_like, params)
return TestOptimizerState(aggregate_grads, is_reset=True)
def update_fn(updates, state, params):
# The test optimizer does not use the parameters, but we check that they
# have been passed correctly.
chex.assert_trees_all_equal_shapes(updates, params)
aggregate_grads = update.apply_updates(state.aggregate_grads, updates)
updates = jax.tree_util.tree_map(lambda u: step_size * u, updates)
return updates, TestOptimizerState(aggregate_grads, is_reset=False)
return base.GradientTransformation(init_fn, update_fn)
class LookaheadTest(chex.TestCase):
"""Tests for the lookahead optimizer."""
def setUp(self):
super().setUp()
self.grads = {'x': np.array(2.), 'y': np.array(-2.)}
self.initial_params = {'x': np.array(3.), 'y': np.array(-3.)}
self.synced_initial_params = lookahead.LookaheadParams.init_synced(
self.initial_params)
def loop(self, optimizer, num_steps, params):
"""Performs a given number of optimizer steps."""
init_fn, update_fn = optimizer
# Use the chex variant to check various function versions (jit, pmap, etc).
step = self.variant(update_fn)
opt_state = self.variant(init_fn)(params)
# A no-op change, to verify that tree map works.
opt_state = state_utils.tree_map_params(init_fn, lambda v: v, opt_state)
for _ in range(num_steps):
updates, opt_state = step(self.grads, opt_state, params)
params = update.apply_updates(params, updates)
return params, opt_state
@chex.all_variants
def test_lookahead(self):
"""Tests the lookahead optimizer in an analytically tractable setting."""
sync_period = 3
optimizer = lookahead.lookahead(
_test_optimizer(-0.5), sync_period=sync_period, slow_step_size=1 / 3)
final_params, _ = self.loop(optimizer, 2 * sync_period,
self.synced_initial_params)
# x steps must be: 3 -> 2 -> 1 -> 2 (sync) -> 1 -> 0 -> 1 (sync).
# Similarly for y (with sign flipped).
correct_final_params = {'x': 1, 'y': -1}
chex.assert_trees_all_close(final_params.slow, correct_final_params)
@chex.all_variants
@parameterized.parameters([False], [True])
def test_lookahead_state_reset(self, reset_state):
"""Checks that lookahead resets the fast optimizer state correctly."""
num_steps = sync_period = 3
fast_optimizer = _test_optimizer(-0.5)
optimizer = lookahead.lookahead(
fast_optimizer,
sync_period=sync_period,
slow_step_size=0.5,
reset_state=reset_state)
_, opt_state = self.loop(optimizer, num_steps, self.synced_initial_params)
# A no-op change, to verify that this does not break anything
opt_state = state_utils.tree_map_params(optimizer, lambda v: v, opt_state)
fast_state = opt_state.fast_state
if reset_state:
correct_state = fast_optimizer.init(self.initial_params)
else:
_, correct_state = self.loop(fast_optimizer, num_steps,
self.initial_params)
chex.assert_trees_all_close(fast_state, correct_state)
@chex.all_variants
@parameterized.parameters(
[1, 0.5, {'x': np.array(1.), 'y': np.array(-1.)}],
[1, 0, {'x': np.array(3.), 'y': np.array(-3.)}],
[1, 1, {'x': np.array(-1.), 'y': np.array(1.)}],
[2, 1, {'x': np.array(-1.), 'y': np.array(1.)}]) # pyformat: disable
def test_lookahead_edge_cases(self, sync_period, slow_step_size,
correct_result):
"""Checks special cases of the lookahed optimizer parameters."""
# These edge cases are important to check since users might use them as
# simple ways of disabling lookahead in experiments.
optimizer = lookahead.lookahead(
_test_optimizer(-1), sync_period, slow_step_size)
final_params, _ = self.loop(
optimizer, num_steps=2, params=self.synced_initial_params)
chex.assert_trees_all_close(final_params.slow, correct_result)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/lookahead_test.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Differential Privacy utilities."""
from typing import Any, NamedTuple
import jax
from optax._src import base
from optax._src import clipping
# pylint:disable=no-value-for-parameter
class DifferentiallyPrivateAggregateState(NamedTuple):
"""State containing PRNGKey for `differentially_private_aggregate`."""
# TODO(optax-dev): rng_key used to be annotated as `jnp.array` but that is
# not a valid annotation (it's a function and secretely resolved to `Any`).
# We should add back typing.
rng_key: Any
def differentially_private_aggregate(
l2_norm_clip: float,
noise_multiplier: float,
seed: int
) -> base.GradientTransformation:
"""Aggregates gradients based on the DPSGD algorithm.
WARNING: Unlike other transforms, `differentially_private_aggregate` expects
the input updates to have a batch dimension in the 0th axis. That is, this
function expects per-example gradients as input (which are easy to obtain in
JAX using `jax.vmap`). It can still be composed with other transformations as
long as it is the first in the chain.
References:
[Abadi et al, 2016](https://arxiv.org/abs/1607.00133)
Args:
l2_norm_clip: maximum L2 norm of the per-example gradients.
noise_multiplier: ratio of standard deviation to the clipping norm.
seed: initial seed used for the jax.random.PRNGKey
Returns:
A `GradientTransformation`.
"""
noise_std = l2_norm_clip * noise_multiplier
def init_fn(params):
del params
return DifferentiallyPrivateAggregateState(rng_key=jax.random.PRNGKey(seed))
def update_fn(updates, state, params=None):
del params
grads_flat, grads_treedef = jax.tree_util.tree_flatten(updates)
bsize = grads_flat[0].shape[0]
clipped, _ = clipping.per_example_global_norm_clip(grads_flat, l2_norm_clip)
new_key, *rngs = jax.random.split(state.rng_key, len(grads_flat) + 1)
noised = [(g + noise_std * jax.random.normal(r, g.shape, g.dtype)) / bsize
for g, r in zip(clipped, rngs)]
return (jax.tree_util.tree_unflatten(grads_treedef, noised),
DifferentiallyPrivateAggregateState(rng_key=new_key))
return base.GradientTransformation(init_fn, update_fn)
| optax-master | optax/_src/privacy.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Complex-valued optimization.
When using `split_real_and_imaginary` to wrap an optimizer, we split the complex
parameters and updates into pairs of real ones before sending them to the
`update` of the wrapped optimizer, and merge the pairs of transformed real
updates into complex ones afterward. In this way, optimizers on complex
parameters behave the same way as if they were running on two real parameters.
Note that the convention of conjugate for complex gradients in JAX is different
from that in PyTorch and other frameworks, and we need to manually conjugate the
gradients between `jax.grad` and `optimizer.update`.
See details at https://github.com/deepmind/optax/issues/196
"""
from typing import NamedTuple, Union
import chex
import jax
import jax.numpy as jnp
from optax._src import base
class SplitRealAndImaginaryArrays(NamedTuple):
"""A pair of real arrays split from a complex array."""
real: chex.Array
imaginary: chex.Array
def _complex_to_real_pair(
x: chex.Array
) -> Union[chex.Array, SplitRealAndImaginaryArrays]:
"""Splits a complex array into a `SplitRealAndImaginaryArrays`.
Args:
x: The input array, can be complex or real.
Returns:
`SplitRealAndImaginaryArrays` if the input is a complex array. If the
input is a real array, it is passed through unmodified.
"""
if jnp.iscomplexobj(x):
return SplitRealAndImaginaryArrays(x.real, x.imag)
else:
return x
def _real_pair_to_complex(
x: Union[chex.Array, SplitRealAndImaginaryArrays]
) -> chex.Array:
"""Merges a `SplitRealAndImaginaryArrays` into a complex array.
Args:
x: The input `SplitRealAndImaginaryArrays` or array.
Returns:
A complex array obtained from the real and imaginary parts of the
`SplitRealAndImaginaryArrays`. If the input is not a
`SplitRealAndImaginaryArrays`, it is passed through unmodified.
"""
if isinstance(x, SplitRealAndImaginaryArrays):
return x.real + x.imaginary * 1j
else:
return x
class SplitRealAndImaginaryState(NamedTuple):
"""Maintains the inner transformation state for `split_real_and_imaginary`."""
inner_state: base.OptState
def split_real_and_imaginary(
inner: base.GradientTransformation
) -> base.GradientTransformation:
"""Splits the real and imaginary components of complex updates into two.
The inner transformation processes real parameters and updates, and the
pairs of transformed real updates are merged into complex updates.
Parameters and updates that are real before splitting are passed through
unmodified.
Args:
inner: The inner transformation.
Returns:
An `optax.GradientTransformation`.
"""
def init_fn(params):
params = jax.tree_util.tree_map(_complex_to_real_pair, params)
inner_state = inner.init(params)
return SplitRealAndImaginaryState(inner_state)
def update_fn(updates, state, params=None):
inner_state = state.inner_state
updates = jax.tree_util.tree_map(_complex_to_real_pair, updates)
params = jax.tree_util.tree_map(_complex_to_real_pair, params)
updates, inner_state = inner.update(updates, inner_state, params)
updates = jax.tree_util.tree_map(
_real_pair_to_complex,
updates,
is_leaf=lambda x: isinstance(x, SplitRealAndImaginaryArrays))
return updates, SplitRealAndImaginaryState(inner_state)
return base.GradientTransformation(init_fn, update_fn)
| optax-master | optax/_src/experimental/complex_valued.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for extra_kwargs."""
from absl.testing import absltest
import chex
import jax
import jax.numpy as jnp
from optax._src import base
from optax._src import transform
from optax._src.experimental import extra_args as extra
def scale_by_loss():
"""Scale the gradient by the absolute value of the loss."""
def init_fn(params, *, extra_args):
del params, extra_args
return base.EmptyState()
def update_fn(updates, state, params, *, extra_args):
del params
updates = jax.tree_util.tree_map(
lambda u: u / extra_args['loss'], updates)
return updates, state
return extra.GradientTransformationWithExtraArgs(init_fn, update_fn)
class ExtraArgsTest(absltest.TestCase):
def test_named_chain(self):
tx = extra.named_chain(
('scale', transform.scale(0.1)),
('scale_by_policy_loss', scale_by_loss()),
('scale_by_value_loss', scale_by_loss()),
)
params = {'a': jnp.ones((4,))}
grads = params
extra_args = {
'scale_by_policy_loss': {'loss': 0.01},
'scale_by_value_loss': {'loss': 10.0}}
opt_state = tx.init(params, extra_args=extra_args)
updates, opt_state = tx.update(
grads, opt_state, params, extra_args=extra_args)
chex.assert_trees_all_close(updates, {'a': jnp.ones((4,))})
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/experimental/extra_args_test.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Support for extra kwargs in a gradient transformation's `init` and `update`.
Some users have the need to condition the behavior of a gradient
transformations on dynamical quantities such as the loss. With this experimental
feature we support passing additional kwargs to `init` and `update`.
We introduce `GradientTransformationWithExtraArgs` as an experimental feature.
You can use the new `named_chain` to combine both old-style and new-style
transformations. We will then monitor users to understand how they use it and
gather feedback from optax users before merging this into the stable API.
"""
from typing import Any, Mapping, Optional, Protocol, Tuple, Union, NamedTuple
from optax._src import base
class InitFnWithExtraArgs(Protocol):
"""Like `TransformInitFn` but with optional `extra_args`."""
def __call__(
self,
params: base.Params,
*,
extra_args: Optional[Mapping[str, Any]] = None,
) -> base.OptState:
"""The `init` function."""
class UpdateFnWithExtraArgs(Protocol):
"""Like `TransformUpdateFn` but with optional `extra_args`."""
def __call__(
self,
updates: base.Updates,
state: base.OptState,
params: Optional[base.Params] = None,
*,
extra_args: Optional[Mapping[str, Any]] = None,
) -> Tuple[base.Updates, base.OptState]:
"""The `update` function."""
class GradientTransformationWithExtraArgs(NamedTuple):
"""A pair of pure functions implementing a gradient transformation.
GradientTransformationWithExtraArgs is just like GradientTransformation but
both the `init` and `update` functions accept an additional `extra_args` dict.
This can be used to provide additional dynamic information that is not
computed by the GradientTransformation itself (e.g. loss) but that may be
needed by specific algorithms.
"""
init: InitFnWithExtraArgs
update: UpdateFnWithExtraArgs
AnyGradientTransformation = Union[
base.GradientTransformation, GradientTransformationWithExtraArgs]
NamedTransform = Tuple[str, AnyGradientTransformation]
def named_chain(
*transforms: NamedTransform) -> GradientTransformationWithExtraArgs:
"""Chains optax gradient transformations.
The `transforms` are `(name, transformation)` pairs, constituted of a string
`name` and an associated gradient transformation `transformation`. The
gradient transformation must be an instance of either
`GradientTransformation` or `GradientTransformationWithExtraArgs`.
Each `name` is used as key for the state of the corresponding transformation
within the `named_chain` state. Thus the state of the gradient transformation
with a given `name` can be retrieved as `opt_state[name]`.
The `named_chain` accepts an `extra_args` meta-dictionary whose fields are
the transformations' names and its values are the corresponding extra_args:
Example:
tx = named_chain(('one', tx1), ('two', tx2))
extra_args={
'one': {'loss': 0.1},
'two': {'loss': 0.3, 'temperature': 0.01}}
tx.init(params, extra_args=extra_args}
tx.update(grads, state, params, extra_args=extra_args)
# tx1 receives {'loss': 0.1} as extra_args
# tx2 receives {'loss': 0.3, 'temperature': 0.01} as extra_args
If one of the transformations does not need extra_args the corresponding
name can just be skipped in the `named_chain` extra_args:
Example:
tx = named_chain(('one', tx1), ('two', tx2))
extra_args={'one': {'loss': 0.1}}
tx.init(params, extra_args=extra_args}
tx.update(grads, state, params, extra_args=extra_args)
# tx1 receives {'loss': 0.1} as extra_args.
# tx2 is called without passing the extra_args.
Args:
*transforms: an arbitrary number of `(name, tx)` pairs, constituted of a
string `name` and an associated gradient transformation `tx`. The latter
is a `GradientTransformation` or `GradientTransformationWithExtraArgs`.
Returns:
A single (init_fn, update_fn) tuple.
"""
names = [name for name, _ in transforms]
if len(names) != len(set(names)):
raise ValueError(
f'Named transformations must have unique names, but got {names}')
def init_fn(params, *, extra_args=None):
states = {}
for (name, tx) in transforms:
_assert_is_gradient_transformation(tx)
if (extra_args is not None and
isinstance(tx, GradientTransformationWithExtraArgs)):
states[name] = tx.init(
params, extra_args=extra_args.get(name))
else:
states[name] = tx.init(params)
return states
def update_fn(updates, state, params=None, *, extra_args=None):
new_state = {}
for (name, tx) in transforms:
_assert_is_gradient_transformation(tx)
if (extra_args is not None and
isinstance(tx, GradientTransformationWithExtraArgs)):
updates, new_state[name] = tx.update(
updates, state[name], params, extra_args=extra_args.get(name))
else:
updates, new_state[name] = tx.update(updates, state[name], params)
return updates, new_state
return GradientTransformationWithExtraArgs(init_fn, update_fn)
def _assert_is_gradient_transformation(tx):
valid_types = (
base.GradientTransformation,
GradientTransformationWithExtraArgs)
if not isinstance(tx, valid_types):
raise ValueError(
'The transformation `tx` must be a valid gradient transformation, '
'that is an instance of either `GradientTransformation` or '
'an instance of `GradientTransformationWithExtraArgs`')
| optax-master | optax/_src/experimental/extra_args.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `complex_valued.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import transform
from optax._src import update
from optax._src.experimental import complex_valued
def _loss_fun_complex_to_real(z):
return (z.conj() * z).real.sum()
def _loss_fun_real_to_real(params):
x, y = params
return _loss_fun_complex_to_real(x + y * 1j)
class ComplexValuedTest(parameterized.TestCase):
@chex.all_variants
@parameterized.named_parameters([
('adam', transform.scale_by_adam),
('param_block_norm', transform.scale_by_param_block_norm),
])
def test_split_real_and_imaginary(self, scaler_constr):
def do_update(loss_fun, optimizer, params, opt_state):
loss, grads = jax.value_and_grad(loss_fun)(params)
# Complex gradients need to be conjugated before being added to parameters
grads = jax.tree_util.tree_map(lambda x: x.conj(), grads)
updates, opt_state = self.variant(optimizer.update)(
grads, opt_state, params)
params = update.apply_updates(params, updates)
return loss, grads, params, opt_state
x = jnp.array([[0.1, 0.2, 0.3], [-0.1, -0.2, -0.3]])
y = jnp.array([[0.5, -0.5, 0], [0.1, 0.3, -0.2]])
z = x + y * 1j
optimizer = scaler_constr()
optimizer_complex = complex_valued.split_real_and_imaginary(optimizer)
opt_state = self.variant(optimizer.init)((x, y))
opt_state_complex = self.variant(optimizer_complex.init)(z)
# Check that the loss, the gradients, and the parameters are the same for
# real-to-real and complex-to-real loss functions in each step
for _ in range(3):
loss, (gx, gy), (x, y), opt_state = do_update(
_loss_fun_real_to_real, optimizer, (x, y), opt_state)
loss_complex, gz, z, opt_state_complex = do_update(
_loss_fun_complex_to_real, optimizer_complex, z, opt_state_complex)
np.testing.assert_allclose(loss, loss_complex)
np.testing.assert_allclose(gx + gy * 1j, gz)
np.testing.assert_allclose(x + y * 1j, z)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/experimental/complex_valued_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `mechanic.py`."""
from typing import NamedTuple
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from optax._src import alias
from optax._src import base
from optax._src import numerics
from optax._src import state_utils
from optax._src import update
from optax._src.contrib import mechanic
# TODO(harshm): make LARS and Fromage work with mechanic.
_OPTIMIZERS_UNDER_TEST = (
dict(opt_name='sgd', opt_kwargs=dict(learning_rate=1.0, momentum=0.9)),
dict(opt_name='adam', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='adamw', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='adamax', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='adamaxw', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='amsgrad', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='lamb', opt_kwargs=dict(learning_rate=1.0)),
dict(
opt_name='lion', opt_kwargs=dict(learning_rate=1.0, b1=0.99),
),
dict(opt_name='noisy_sgd', opt_kwargs=dict(learning_rate=1.0, eta=1e-4)),
dict(opt_name='novograd', opt_kwargs=dict(learning_rate=1.0)),
dict(
opt_name='optimistic_gradient_descent',
opt_kwargs=dict(learning_rate=1.0, alpha=0.7, beta=0.1),
),
dict(opt_name='rmsprop', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='rmsprop', opt_kwargs=dict(learning_rate=1.0, momentum=0.9)),
dict(opt_name='adabelief', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='radam', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='sm3', opt_kwargs=dict(learning_rate=1.0)),
dict(opt_name='yogi', opt_kwargs=dict(learning_rate=1.0, b1=0.99)),
)
def _setup_parabola(dtype):
"""Quadratic function as an optimization target."""
initial_params = jnp.array([-1.0, 10.0, 1.0], dtype=dtype)
final_params = jnp.array([1.0, -1.0, 1.0], dtype=dtype)
@jax.grad
def get_updates(params):
return jnp.sum(numerics.abs_sq(params - final_params))
return initial_params, final_params, get_updates
def _setup_rosenbrock(dtype):
"""Rosenbrock function as an optimization target."""
a = 1.0
b = 100.0
initial_params = jnp.array([0.0, 0.0], dtype=dtype)
final_params = jnp.array([a, a**2], dtype=dtype)
@jax.grad
def get_updates(params):
return (numerics.abs_sq(a - params[0]) +
b * numerics.abs_sq(params[1] - params[0]**2))
return initial_params, final_params, get_updates
class TestOptimizerState(NamedTuple):
"""Inner optimizer state for the Mechanic tests."""
aggregate_grads: base.Params
def _test_optimizer(step_size: float) -> base.GradientTransformation:
"""Inner optimizer for the Mechanic tests."""
# Use SGD for simplicity but add non-trivial optimizer state so that the
# resetting behaviour of lookahead can be tested.
def init_fn(params):
aggregate_grads = jax.tree_util.tree_map(jnp.zeros_like, params)
return TestOptimizerState(aggregate_grads)
def update_fn(updates, state, params):
# The test optimizer does not use the parameters, but we check that they
# have been passed correctly.
chex.assert_trees_all_equal_shapes(updates, params)
aggregate_grads = update.apply_updates(state.aggregate_grads, updates)
updates = jax.tree_util.tree_map(lambda u: step_size * u, updates)
return updates, TestOptimizerState(aggregate_grads)
return base.GradientTransformation(init_fn, update_fn)
class MechanicTest(chex.TestCase):
def setUp(self):
super().setUp()
rng = np.random.RandomState(0)
self.tree_a = (rng.randn(20, 10), rng.randn(20))
self.tree_b = (rng.randn(20, 10), rng.randn(20))
self.tree_a_dict = (1.0, {'k1': 1.0, 'k2': (1.0, 1.0)}, 1.0)
self.tree_b_dict = (1.0, {'k1': 2.0, 'k2': (3.0, 4.0)}, 5.0)
self.array_a = rng.randn(20)
self.array_b = rng.randn(20)
self.grads = {'x': np.array(2.), 'y': np.array(-2.)}
self.initial_params = {'x': np.array(3.), 'y': np.array(-3.)}
def loop(self, optimizer, num_steps, params):
"""Performs a given number of optimizer steps."""
init_fn, update_fn = optimizer
# Use the chex variant to check various function versions (jit, pmap, etc).
step = self.variant(update_fn)
opt_state = self.variant(init_fn)(params)
# A no-op change, to verify that tree map works.
opt_state = state_utils.tree_map_params(init_fn, lambda v: v, opt_state)
for _ in range(num_steps):
updates, opt_state = step(self.grads, opt_state, params)
print(updates)
params = update.apply_updates(params, updates)
return params, opt_state
@chex.all_variants(with_pmap=False)
def test_mechanized(self):
params = self.initial_params
num_betas = 6
inner_optimizer = _test_optimizer(-0.1)
optimizer = mechanic.mechanize(
inner_optimizer,
weight_decay=1e-2,
eps=1e-10,
s_init=1e-8,
num_betas=num_betas,
)
final_params, final_state = self.loop(
optimizer=optimizer, num_steps=1, params=params
)
expected_m = np.array([1.0e-10] * num_betas)
expected_v = np.array([0.0] * num_betas)
expected_s = np.array([1.6666667e-09] * num_betas)
chex.assert_trees_all_close(expected_m, final_state.m)
chex.assert_trees_all_close(expected_v, final_state.v)
chex.assert_trees_all_close(expected_s, final_state.s)
chex.assert_trees_all_close(final_params, params)
chex.assert_tree_all_finite((final_params, final_state))
@parameterized.product(
_OPTIMIZERS_UNDER_TEST,
target=(_setup_parabola, _setup_rosenbrock),
dtype=(jnp.float32,),
)
def test_optimization(self, opt_name, opt_kwargs, target, dtype):
opt = getattr(alias, opt_name)(**opt_kwargs)
opt = mechanic.mechanize(opt, weight_decay=0.0)
initial_params, final_params, get_updates = target(dtype)
@jax.jit
def step(params, state):
updates = get_updates(params)
updates, state = opt.update(updates, state, params)
params = update.apply_updates(params, updates)
return params, state
params = initial_params
state = opt.init(params)
# A no-op change, to verify that tree map works.
state = state_utils.tree_map_params(opt, lambda v: v, state)
for _ in range(25000):
params, state = step(params, state)
chex.assert_trees_all_close(params, final_params, rtol=3e-2, atol=3e-2)
if __name__ == '__main__':
absltest.main()
| optax-master | optax/_src/contrib/mechanic_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Mechanic wrapper for automatic black box learning rate tuning.
Mechanic is a contributed optimizer implemented from
https://arxiv.org/pdf/2306.00144.pdf.
This implementation matches the paper exactly and implemented by the original
authors. More specifically, mechanic is implemented to work well with other
optax optimizers that it can wrap to learn the learning rate.
Mechanic incurs an extra O(d) slot to store the initial weights and a handful
of O(d) computations. We largely expect the wall clock time with and without
using Mechanic to be the same for reasonably large batch sizes (>1k).
"""
import functools
import operator
from typing import NamedTuple, Optional, Tuple
import chex
import jax
import jax.numpy as jnp
from optax._src import base
from optax._src import utils
def _vdot_safe(a, b):
vdot = functools.partial(jnp.vdot, precision=jax.lax.Precision.HIGHEST)
cvdot = vdot(jnp.asarray(a), jnp.asarray(b))
return cvdot
@jax.jit
def _tree_vdot(tree_x, tree_y):
"""Compute the inner product <tree_x, tree_y>."""
vdots = jax.tree_util.tree_map(_vdot_safe, tree_x, tree_y)
return jax.tree_util.tree_reduce(operator.add, vdots)
@jax.jit
def _tree_sum(tree_x):
"""Compute sum(tree_x)."""
sums = jax.tree_util.tree_map(jnp.sum, tree_x)
return jax.tree_util.tree_reduce(operator.add, sums)
@jax.jit
def _tree_norm(tree):
"""Compute the l2 norm ||tree_x||."""
return jnp.sqrt(_tree_sum(jax.tree_map(lambda x: jnp.sum(x**2), tree)))
class MechanicState(NamedTuple):
"""State of the `GradientTransformation` returned by `mechanize`."""
base_optimizer_state: base.OptState
count: chex.Array # shape=(), dtype=jnp.int32.
r: chex.Array
m: chex.Array
v: chex.Array
s: chex.Array
x0: base.Updates
def mechanize(
base_optimizer: base.GradientTransformation,
weight_decay: float = 1e-2,
eps: float = 1e-8,
s_init: float = 1e-6,
num_betas: int = 6,
) -> base.GradientTransformation:
"""Mechanic - a black box learning rate tuner/optimizer.
Accumulates updates returned by the base_optimizer and learns the scale of
the updates (also know as learning rate or step size) to apply on a per
iteration basis.
Note that Mechanic does NOT eschew the need for a learning rate schedule,
you are free to apply a learning rate schedule with base learning rate set to
1.0 (or any other constant) and Mechanic will learn the right scale factor
automatically.
For example, change this::
learning_rate_fn = optax.warmup_cosine_decay_schedule(peak_value=tuned_lr)
optimizer = optax.adam(learning_rate_fn)
To::
learning_rate_fn = optax.warmup_cosine_decay_schedule(peak_value=1.0)
optimizer = optax.adam(learning_rate_fn)
optimizer = optax.contrib.mechanize(optimizer)
As of June, 2023, Mechanic is tested with SGD, Momentum, Adam and Lion as
inner optimizers but we expect it to work with almost any first-order
optimizer (except for normalized gradient optimizer like LARS or LAMB).
References:
[Cutkosky et al, 2023](https://arxiv.org/pdf/2306.00144.pdf)
Args:
base_optimizer: Base optimizer to compute updates from.
weight_decay: A scalar weight decay rate. Note that this weight decay is not
the same as the weight decay one would use for the base_optimizer. In
addition to sometimes helping converge faster, this helps Mechanic reduce
the variance between training runs using different seeds. You likely would
not need to tune this, the default should work in most cases.
eps: epsilon for mechanic.
s_init: initial scale factor. Default should work almost all the time.
num_betas: unlike traditional exp accumulators (like 1st or 2nd moment of
adam), where one has to choose an explicit beta, mechanic has a clever way
to automatically learn the right beta for all accumulators. We only
provide the range of possible betas, and not the tuned value. For
instance, if you set num_betas to 3, it will use betas = [0.9, 0.99,
0.999].
Returns:
A `GradientTransformation` with init and update functions.
"""
def init_fn(params: base.Params) -> MechanicState:
x0 = params
r = jnp.zeros([num_betas,], jnp.float32)
v = jnp.zeros([num_betas,], jnp.float32)
m = jnp.zeros([num_betas,], jnp.float32)
s = jnp.ones([num_betas,], jnp.float32) * s_init
return MechanicState(
base_optimizer_state=base_optimizer.init(params),
count=jnp.zeros([], jnp.int32),
r=r,
m=m,
v=v,
s=s,
x0=x0,
)
def update_fn(
updates: base.Updates,
state: MechanicState,
params: Optional[base.Params] = None,
) -> Tuple[base.Params, MechanicState]:
if params is None:
raise ValueError(base.NO_PARAMS_MSG)
count_inc = utils.safe_int32_increment(state.count)
new_neg_updates, base_optimizer_state = base_optimizer.update(
updates, state.base_optimizer_state, params
)
# Since a lot of training loops unfreezes weights to replace it with
# pre-trained weights, we want to make sure we start from actually used
# weights instead of what they were initialized with.
x0 = jax.lax.cond(state.count == 0, lambda: params, lambda: state.x0)
# Add weight decay to raw gradients, note that this is othogonal to any
# weight decay applied to inner_optimizer updates.
s_sum = jnp.sum(state.s)
grad_norm = _tree_norm(updates)
param_norm = _tree_norm(params)
def add_weight_decay(gi, pi):
return gi + weight_decay * s_sum * grad_norm / (param_norm + eps) * pi
updates = jax.tree_util.tree_map(
add_weight_decay,
updates,
params,
)
# We use the memory efficient version of Mechanic where we re-compute
# \Delta every iteration.
delta_prev = jax.tree_util.tree_map(
lambda xti, x0i: (x0i - xti) / (s_sum + eps), params, x0
)
# We actually want to add the updates, but since optax by default flips
# signs when applying the learning rate, we substract instead.
delta = jax.tree_util.tree_map(
lambda si, ui: si - ui, delta_prev, new_neg_updates
)
# Now we are ready to run the actual Mechanic algorithm.
h = _tree_vdot(updates, delta_prev)
# This clipping was not part of the original paper but we introduced it
# a little later.
clipped_h = jax.lax.clamp(-state.m, jnp.ones_like(state.m) * h, state.m)
betas = jnp.array([1.0 - 0.1**betai for betai in range(1, num_betas + 1)])
m = jnp.maximum(betas * state.m, jnp.abs(h) + eps)
v = (betas**2) * state.v + h**2
r = betas * state.r + clipped_h * state.s
rc = jnp.maximum(0.0, r)
wealth = (s_init / jnp.size(betas)) * m + rc
s = wealth / (jnp.sqrt(v) + eps)
# Once we have the scale factor s, we produce new params with it.
new_x0 = x0
new_params = jax.tree_util.tree_map(
lambda x0, deltai: x0 - jnp.sum(s) * deltai, new_x0, delta
)
new_neg_updates = jax.tree_util.tree_map(
lambda np, op: np - op, new_params, params
)
return new_neg_updates, MechanicState(
base_optimizer_state=base_optimizer_state,
count=count_inc,
r=r,
m=m,
v=v,
s=s,
x0=new_x0,
)
return base.GradientTransformation(init_fn, update_fn)
| optax-master | optax/_src/contrib/mechanic.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Contributed optimizers in Optax."""
from optax._src.contrib.mechanic import MechanicState
from optax._src.contrib.mechanic import mechanize
| optax-master | optax/contrib/__init__.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A simple example of using Optax to train the parameters of a Flax module."""
from absl import app
from flax import linen as nn
import jax
import jax.numpy as jnp
import optax
def main(argv):
del argv
learning_rate = 1e-2
n_training_steps = 100
# Random number generator sequence.
rng = jax.random.PRNGKey(0)
rng1, rng2 = jax.random.split(rng)
# Create a one linear layer instance.
model = nn.Dense(features=5)
# Initialise the parameters.
params = model.init(rng2, jax.random.normal(rng1, (10,)))
# Set problem dimensions.
nsamples = 20
xdim = 10
ydim = 5
# Generate random ground truth w and b.
w = jax.random.normal(rng1, (xdim, ydim))
b = jax.random.normal(rng2, (ydim,))
# Generate samples with additional noise.
ksample, knoise = jax.random.split(rng1)
x_samples = jax.random.normal(ksample, (nsamples, xdim))
y_samples = jnp.dot(x_samples, w) + b
y_samples += 0.1 * jax.random.normal(knoise, (nsamples, ydim))
# Define an MSE loss function.
def make_mse_func(x_batched, y_batched):
def mse(params):
# Define the squared loss for a single (x, y) pair.
def squared_error(x, y):
pred = model.apply(params, x)
return jnp.inner(y-pred, y-pred) / 2.0
# Vectorise the squared error and compute the average of the loss.
return jnp.mean(jax.vmap(squared_error)(x_batched, y_batched), axis=0)
return jax.jit(mse) # `jit` the result.
# Instantiate the sampled loss.
loss = make_mse_func(x_samples, y_samples)
# Construct a simple Adam optimiser using the transforms in optax.
# You could also just use the `optax.adam` alias, but we show here how
# to do so manually so that you may construct your own `custom` optimiser.
tx = optax.chain(
# Set the parameters of Adam. Note the learning_rate is not here.
optax.scale_by_adam(b1=0.9, b2=0.999, eps=1e-8),
# Put a minus sign to *minimise* the loss.
optax.scale(-learning_rate)
)
# Create optimiser state.
opt_state = tx.init(params)
# Compute the gradient of the loss function.
loss_grad_fn = jax.value_and_grad(loss)
# Minimise the loss.
for step in range(n_training_steps):
# Compute gradient of the loss.
loss_val, grads = loss_grad_fn(params)
# Update the optimiser state, create an update to the params.
updates, opt_state = tx.update(grads, opt_state)
# Update the parameters.
params = optax.apply_updates(params, updates)
print(f'Loss[{step}] = {loss_val}')
if __name__ == '__main__':
app.run(main)
| optax-master | examples/flax_example.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
r"""Trains a differentially private convolutional neural network on MNIST.
A large portion of this code is forked from the differentially private SGD
example in the JAX repo:
https://github.com/google/jax/blob/master/examples/differentially_private_sgd.py
Differentially Private Stochastic Gradient Descent
(https://arxiv.org/abs/1607.00133) requires clipping the per-example parameter
gradients, which is non-trivial to implement efficiently for convolutional
neural networks. The JAX XLA compiler shines in this setting by optimizing the
minibatch-vectorized computation for convolutional architectures. Train time
takes a few seconds per epoch on a commodity GPU.
The results match those in the reference TensorFlow baseline implementation:
https://github.com/tensorflow/privacy/tree/master/tutorials
Example invocations from within the `examples/` directory:
# this non-private baseline should get ~99% acc
python differentially_private_sgd.py \
--dpsgd=False \
--learning_rate=.1 \
--epochs=20
# this private baseline should get ~95% acc
python differentially_private_sgd.py \
--dpsgd=True \
--noise_multiplier=1.3 \
--l2_norm_clip=1.5 \
--epochs=15 \
--learning_rate=.25
# this private baseline should get ~96.6% acc
python differentially_private_sgd.py \
--dpsgd=True \
--noise_multiplier=1.1 \
--l2_norm_clip=1.0 \
--epochs=60 \
--learning_rate=.15
# this private baseline should get ~97% acc
python differentially_private_sgd.py \
--dpsgd=True \
--noise_multiplier=0.7 \
--l2_norm_clip=1.5 \
--epochs=45 \
--learning_rate=.25
"""
import time
import warnings
from absl import app
from absl import flags
import dp_accounting
import jax
from jax.example_libraries import stax
import jax.numpy as jnp
import optax
# pylint: disable=g-bad-import-order
import datasets # Located in the examples folder.
# pylint: enable=g-bad-import-order
NUM_EXAMPLES = 60_000
FLAGS = flags.FLAGS
flags.DEFINE_boolean(
'dpsgd', True, 'If True, train with DP-SGD. If False, '
'train with vanilla SGD.')
flags.DEFINE_float('learning_rate', .15, 'Learning rate for training')
flags.DEFINE_float('noise_multiplier', 1.1,
'Ratio of the standard deviation to the clipping norm')
flags.DEFINE_float('l2_norm_clip', 1.0, 'Clipping norm')
flags.DEFINE_integer('batch_size', 256, 'Batch size')
flags.DEFINE_integer('epochs', 60, 'Number of epochs')
flags.DEFINE_integer('seed', 1337, 'Seed for JAX PRNG')
flags.DEFINE_float('delta', 1e-5, 'Target delta used to compute privacy spent.')
init_random_params, predict = stax.serial(
stax.Conv(16, (8, 8), padding='SAME', strides=(2, 2)),
stax.Relu,
stax.MaxPool((2, 2), (1, 1)),
stax.Conv(32, (4, 4), padding='VALID', strides=(2, 2)),
stax.Relu,
stax.MaxPool((2, 2), (1, 1)),
stax.Flatten,
stax.Dense(32),
stax.Relu,
stax.Dense(10),
)
def compute_epsilon(steps, target_delta=1e-5):
if NUM_EXAMPLES * target_delta > 1.:
warnings.warn('Your delta might be too high.')
q = FLAGS.batch_size / float(NUM_EXAMPLES)
orders = list(jnp.linspace(1.1, 10.9, 99)) + list(range(11, 64))
accountant = dp_accounting.rdp.RdpAccountant(orders)
accountant.compose(dp_accounting.PoissonSampledDpEvent(
q, dp_accounting.GaussianDpEvent(FLAGS.noise_multiplier)), steps)
return accountant.get_epsilon(target_delta)
def loss_fn(params, batch):
logits = predict(params, batch['image'])
return optax.softmax_cross_entropy(logits, batch['label']).mean(), logits
@jax.jit
def test_step(params, batch):
loss, logits = loss_fn(params, batch)
accuracy = (logits.argmax(1) == batch['label'].argmax(1)).mean()
return loss, accuracy * 100
def main(_):
train_dataset = datasets.load_image_dataset('mnist', FLAGS.batch_size)
test_dataset = datasets.load_image_dataset('mnist', NUM_EXAMPLES,
datasets.Split.TEST)
full_test_batch = next(test_dataset.as_numpy_iterator())
if FLAGS.dpsgd:
tx = optax.dpsgd(learning_rate=FLAGS.learning_rate,
l2_norm_clip=FLAGS.l2_norm_clip,
noise_multiplier=FLAGS.noise_multiplier,
seed=FLAGS.seed)
else:
tx = optax.sgd(learning_rate=FLAGS.learning_rate)
@jax.jit
def train_step(params, opt_state, batch):
grad_fn = jax.grad(loss_fn, has_aux=True)
if FLAGS.dpsgd:
# Insert dummy dimension in axis 1 to use jax.vmap over the batch
batch = jax.tree_util.tree_map(lambda x: x[:, None], batch)
# Use jax.vmap across the batch to extract per-example gradients
grad_fn = jax.vmap(grad_fn, in_axes=(None, 0))
grads, _ = grad_fn(params, batch)
updates, new_opt_state = tx.update(grads, opt_state, params)
new_params = optax.apply_updates(params, updates)
return new_params, new_opt_state
key = jax.random.PRNGKey(FLAGS.seed)
_, params = init_random_params(key, (-1, 28, 28, 1))
opt_state = tx.init(params)
print('\nStarting training...')
for epoch in range(1, FLAGS.epochs + 1):
start_time = time.time()
for batch in train_dataset.as_numpy_iterator():
params, opt_state = train_step(params, opt_state, batch)
epoch_time = time.time() - start_time
print(f'Epoch {epoch} in {epoch_time:0.2f} seconds.')
# Evaluate test accuracy
test_loss, test_acc = test_step(params, full_test_batch)
print(f'Test Loss: {test_loss:.2f} Test Accuracy (%): {test_acc:.2f}).')
# Determine privacy loss so far
if FLAGS.dpsgd:
steps = epoch * NUM_EXAMPLES // FLAGS.batch_size
eps = compute_epsilon(steps, FLAGS.delta)
print(f'For delta={FLAGS.delta:.0e}, the current epsilon is: {eps:.2f}.')
else:
print('Trained with vanilla non-private SGD optimizer.')
if __name__ == '__main__':
app.run(main)
| optax-master | examples/differentially_private_sgd.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for optax.examples.lookahead_mnist."""
from absl.testing import absltest
from absl.testing.absltest import mock
import numpy as np
import tensorflow as tf
# pylint: disable=g-bad-import-order
import datasets # Located in the examples folder.
import lookahead_mnist # Located in the examples folder.
# pylint: enable=g-bad-import-order
class LookaheadMnistTest(absltest.TestCase):
def test_lookahead_example_can_fit_linear_mock_data(self):
"""Checks that the lookahead example can fit linear mock data."""
lookahead_mnist.LEARNING_RATE = 1e-2
lookahead_mnist.HIDDEN_SIZES = (1,)
data = {
'image': np.arange(-0.5, 0.5, 0.1).reshape(10, 1, 1),
'label': np.array([[1, 0]] * 4 + [[0, 1]] * 6)
}
dataset = tf.data.Dataset.from_tensor_slices(data).repeat(8).batch(10)
with mock.patch.object(
datasets, 'load_image_dataset', return_value=dataset):
final_accuracy = lookahead_mnist.main({})
self.assertEqual(final_accuracy, 1.)
if __name__ == '__main__':
absltest.main()
| optax-master | examples/lookahead_mnist_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""An MNIST example using the Adam optimizer and lookahead wrapper."""
import functools
from absl import app
import jax
from jax import random
import jax.numpy as jnp
import optax
# pylint: disable=g-bad-import-order
import datasets # Located in the examples folder.
import mnist # Located in the examples folder.
# pylint: enable=g-bad-import-order
LEARNING_RATE = 0.002
SLOW_LEARNING_RATE = 0.5
SYNC_PERIOD = 5
HIDDEN_SIZES = (1000, 1000)
BATCH_SIZE = 128
N_EPOCHS = 5
SEED = 1
def main(unused_argv) -> None:
train_dataset = datasets.load_image_dataset('mnist', BATCH_SIZE)
test_dataset = datasets.load_image_dataset('mnist', BATCH_SIZE,
datasets.Split.TEST)
num_classes = train_dataset.element_spec['label'].shape[1]
init_params_fn, apply_params_fn = mnist.build_model(
(*HIDDEN_SIZES, num_classes))
# Set up the fast optimizer (adam) and wrap lookahead around it.
fast_optimizer = optax.adam(LEARNING_RATE)
optimizer = optax.lookahead(fast_optimizer, SYNC_PERIOD, SLOW_LEARNING_RATE)
def get_loss(fast_params, batch):
logits = apply_params_fn(fast_params, batch['image'])
return jnp.mean(optax.softmax_cross_entropy(logits, batch['label']))
@jax.jit
def train_step(params, optimizer_state, batch):
grads = jax.grad(get_loss)(params.fast, batch)
updates, opt_state = optimizer.update(grads, optimizer_state, params)
return optax.apply_updates(params, updates), opt_state
example_input = next(train_dataset.as_numpy_iterator())['image']
initial_params = init_params_fn(random.PRNGKey(SEED), example_input)
# The lookahead optimizer wrapper keeps a pair of slow and fast parameters. To
# initialize them, we create a pair of synchronized parameters from the
# initial model parameters. The first line below is only necessary for the
# lookahead wrapper; without it the initial parameters could be used in the
# initialization function of the optimizer directly.
params = optax.LookaheadParams.init_synced(initial_params)
opt_state = optimizer.init(params)
# Training loop
for epoch in range(N_EPOCHS):
for batch in train_dataset.as_numpy_iterator():
params, opt_state = train_step(params, opt_state, batch)
# Validation is done on the slow lookahead parameters.
eval_model = functools.partial(apply_params_fn, params.slow)
test_acc = mnist.model_accuracy(eval_model,
test_dataset.as_numpy_iterator())
print(f'Epoch {epoch+1}: test acc: {test_acc:.2f}')
return test_acc # pytype: disable=bad-return-type # numpy-scalars
if __name__ == '__main__':
app.run(main)
| optax-master | examples/lookahead_mnist.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Datasets used in the examples."""
import functools
from typing import Dict, Mapping
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
Split = tfds.Split
def _preprocess_image_dataset(element: Mapping[str, tf.Tensor],
num_labels: int) -> Dict[str, tf.Tensor]:
"""Casts image to floats in the range [0,1] and one-hot encodes the label."""
rescaled_image = tf.cast(element['image'], tf.float32) / 255.
one_hot_label = tf.one_hot(
tf.cast(element['label'], tf.int32), num_labels, on_value=1, off_value=0)
return {'image': rescaled_image, 'label': one_hot_label}
def load_image_dataset(dataset_name: str,
batch_size: int,
split: Split = Split.TRAIN,
*,
shuffle: bool = True,
buffer_size: int = 10000,
cache: bool = True) -> tf.data.Dataset:
"""Loads an pre-processes an image dataset from tensorflow_datasets.
The dataset is pre-processed so as to be ready for training a model: the
images are converted to tensors of floats in the range [0, 1] and the labels
are one-hot encoded.
Args:
dataset_name: Name of the dataset to load.
batch_size: Batch size to be used for training.
split: Split of the dataset that should be loaded.
shuffle: Whether to shuffle the dataset.
buffer_size: Size of the shuffle buffer.
cache: Whether to cache the dataset after pre-processing.
Returns:
The batched pre-processed dataset.
"""
dataset = tfds.load(dataset_name, split=split)
max_label = dataset.reduce(
np.int64(0), lambda state, x: tf.maximum(state, x['label']))
num_labels = int(max_label) + 1
dataset = dataset.map(
functools.partial(_preprocess_image_dataset, num_labels=num_labels))
if cache:
dataset = dataset.cache()
if shuffle:
dataset = dataset.shuffle(buffer_size)
return dataset.batch(batch_size).prefetch(tf.data.AUTOTUNE)
| optax-master | examples/datasets.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for optax.examples.datasets."""
from typing import Iterable, List
from absl.testing import absltest
from absl.testing.absltest import mock
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
# pylint: disable=g-bad-import-order
import datasets # Located in the examples folder.
# pylint: enable=g-bad-import-order
def _batch_array(array: np.ndarray, batch_size: int) -> List[np.ndarray]:
"""Splits an array into batches."""
split_indices = np.arange(batch_size, array.shape[0], batch_size)
return np.split(array, split_indices)
def _assert_batches_almost_equal(actual: Iterable[np.ndarray],
desired: Iterable[np.ndarray]) -> None:
"""Asserts that two dataset iterables are almost equal per batch."""
for batch, correct_batch in zip(actual, desired):
np.testing.assert_almost_equal(batch, correct_batch)
class DatasetsTest(absltest.TestCase):
def setUp(self) -> None:
super().setUp()
self._images = np.array([[50], [150], [250]])
self._one_hot_labels = np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
self._test_dataset = tf.data.Dataset.from_tensor_slices({
'image': self._images,
'label': np.argmax(self._one_hot_labels, axis=1),
})
self._batch_size = 2
def test_load_image_dataset(self) -> None:
"""Checks datasets are loaded and preprocessed correctly."""
with mock.patch.object(tfds, 'load', return_value=self._test_dataset):
dataset = datasets.load_image_dataset(
'unused_by_mock', self._batch_size, shuffle=False)
with self.subTest('test_images'):
image_batches = dataset.map(lambda x: x['image']).as_numpy_iterator()
correct_image_batches = _batch_array(self._images / 255.,
self._batch_size)
_assert_batches_almost_equal(image_batches, correct_image_batches)
with self.subTest('test_labels'):
label_batches = dataset.map(lambda x: x['label']).as_numpy_iterator()
correct_label_batches = _batch_array(self._one_hot_labels,
self._batch_size)
_assert_batches_almost_equal(label_batches, correct_label_batches)
if __name__ == '__main__':
absltest.main()
| optax-master | examples/datasets_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for optax.examples.mnist."""
from absl.testing import absltest
from absl.testing.absltest import mock
import chex
import haiku as hk
import jax
import numpy as np
import optax
import tensorflow as tf
# pylint: disable=g-bad-import-order
import datasets # Located in the examples folder.
import mnist # Located in the examples folder.
# pylint: enable=g-bad-import-order
class MnistTest(chex.TestCase):
def test_model_accuracy_returns_correct_result(self):
"""Checks that model_accuracy returns the correct result."""
dataset = (
dict(
image=np.array([[-1, 0, 0], [-1, 0, 1]]),
label=np.array([[1, 0, 0], [0, 1, 0]])),
dict(
image=np.array([[2, 2, 1], [-2, -1, 0]]),
label=np.array([[0, 0, 1], [1, 0, 0]])),
)
self.assertEqual(
mnist.model_accuracy(model=lambda x: -x, dataset=dataset), 0.75)
@chex.all_variants
def test_build_model_returns_mlp_with_correct_number_of_parameters(self):
"""Checks that the MLP has the correct number of parameters."""
model = mnist.build_model(layer_dims=(4, 5))
params = self.variant(model.init)(jax.random.PRNGKey(1), np.ones((9, 3, 2)))
self.assertEqual(
hk.data_structures.tree_size(params), (3 * 2 + 1) * 4 + (4 + 1) * 5)
@chex.all_variants
def test_build_model_returns_mlp_with_correct_output_shape(self):
"""Checks that the MLP has the correct output shape."""
model = mnist.build_model(layer_dims=(4, 5))
inputs = np.ones((9, 3, 2))
params = model.init(jax.random.PRNGKey(1), inputs)
outputs = self.variant(model.apply)(params, inputs)
self.assertEqual(outputs.shape, (9, 5))
def test_train_on_mnist_can_fit_linear_mock_data(self):
"""Checks that train_on_mnist can fit linear mock data."""
data = {
'image': np.arange(-0.5, 0.5, 0.1).reshape(10, 1, 1),
'label': np.array([[1, 0]] * 4 + [[0, 1]] * 6)
}
dataset = tf.data.Dataset.from_tensor_slices(data).repeat(8).batch(10)
with mock.patch.object(
datasets, 'load_image_dataset', return_value=dataset):
final_accuracy = mnist.train_on_mnist(optax.adam(0.01), hidden_sizes=(1,))
self.assertEqual(final_accuracy, 1.)
if __name__ == '__main__':
absltest.main()
| optax-master | examples/mnist_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""An example showing how to train an MLP classifier on MNIST using optax."""
import functools
from typing import Callable, Iterable, Mapping, Sequence
from absl import app
import chex
import haiku as hk
import jax
from jax import random
import jax.numpy as jnp
import optax
# pylint: disable=g-bad-import-order
import datasets # Located in the examples folder.
# pylint: enable=g-bad-import-order
LEARNING_RATE = 0.002
DEFAULT_HIDDEN_SIZES = (1000, 1000)
BATCH_SIZE = 128
N_EPOCHS = 5
SEED = 1
@jax.jit
def _single_batch_accuracy(logits: chex.Array,
labels: chex.Array) -> chex.Array:
"""Returns the accuracy for a batch of logits and labels."""
predictions = jnp.argmax(logits, axis=-1)
return jnp.mean(jnp.argmax(labels, axis=-1) == predictions)
def model_accuracy(model: Callable[[chex.Array], chex.Array],
dataset: Iterable[Mapping[str, chex.Array]]) -> chex.Array:
"""Returns the accuracy of a model on a batched dataset."""
accuracy_sum = dataset_size = 0
for batch in dataset:
# Take batch size into account in case there is a smaller remainder batch.
batch_size = batch['image'].shape[0]
logits = model(batch['image'])
accuracy_sum += _single_batch_accuracy(logits, batch['label']) * batch_size
dataset_size += batch_size
return accuracy_sum / dataset_size # pytype: disable=bad-return-type # numpy-scalars # pylint: disable=line-too-long
# Optax is agnostic to which (if any) neural network library is used. Below we
# provide a Haiku version.
def build_model(layer_dims: Sequence[int]) -> hk.Transformed:
"""Simple multi-layer perceptron model for image classification."""
@hk.transform
def mlp_model(inputs: chex.Array) -> chex.Array:
flattened = hk.Flatten()(inputs)
return hk.nets.MLP(layer_dims)(flattened)
return hk.without_apply_rng(mlp_model)
def train_on_mnist(optimizer: optax.GradientTransformation,
hidden_sizes: Sequence[int]) -> float:
"""Trains an MLP on MNIST using a given optimizer.
Args:
optimizer: Optax optimizer to use for training.
hidden_sizes: Hidden layer sizes of the MLP.
Returns:
The final test accuracy.
"""
train_dataset = datasets.load_image_dataset('mnist', BATCH_SIZE)
test_dataset = datasets.load_image_dataset('mnist', BATCH_SIZE,
datasets.Split.TEST)
num_classes = train_dataset.element_spec['label'].shape[1]
init_params_fn, apply_params_fn = build_model((*hidden_sizes, num_classes))
def get_loss(params, batch):
logits = apply_params_fn(params, batch['image'])
return jnp.mean(optax.softmax_cross_entropy(logits, batch['label']))
@jax.jit
def train_step(params, optimizer_state, batch):
grads = jax.grad(get_loss)(params, batch)
updates, opt_state = optimizer.update(grads, optimizer_state, params)
return optax.apply_updates(params, updates), opt_state
example_input = next(train_dataset.as_numpy_iterator())['image']
params = init_params_fn(random.PRNGKey(SEED), example_input)
opt_state = optimizer.init(params)
# Training loop
for epoch in range(N_EPOCHS):
for batch in train_dataset.as_numpy_iterator():
params, opt_state = train_step(params, opt_state, batch)
eval_model = functools.partial(apply_params_fn, params)
test_acc = model_accuracy(eval_model, test_dataset.as_numpy_iterator())
print(f'Epoch {epoch+1}: test acc: {test_acc:.2f}')
return test_acc # pytype: disable=bad-return-type # numpy-scalars
def main(unused_argv):
"""Trains an MLP on MNIST using the adam optimizers."""
return train_on_mnist(optax.adam(LEARNING_RATE), DEFAULT_HIDDEN_SIZES)
if __name__ == '__main__':
app.run(main)
| optax-master | examples/mnist.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A simple example of using Optax to train the parameters of a Haiku module."""
from absl import app
import haiku as hk
import jax
import jax.numpy as jnp
import optax
def main(argv):
del argv
learning_rate = 1e-2
batch_size = 64
input_size = 8
n_training_steps = 100
# Random number generator sequence.
key_seq = hk.PRNGSequence(1729)
# A simple Linear function.
def forward_pass(x):
return hk.Linear(10)(x)
network = hk.without_apply_rng(hk.transform(forward_pass))
# Some arbitrary loss.
def mean_square_loss(params, x):
output = network.apply(params, x)
loss = jnp.sum(output**2)
return loss
# Construct a simple Adam optimiser using the transforms in optax.
# You could also just use the `optax.adam` alias, but we show here how
# to do so manually so that you may construct your own `custom` optimiser.
opt_init, opt_update = optax.chain(
# Set the parameters of Adam. Note the learning_rate is not here.
optax.scale_by_adam(b1=0.9, b2=0.999, eps=1e-8),
# Put a minus sign to *minimise* the loss.
optax.scale(-learning_rate)
)
# Initialise the model's parameters and the optimiser's state.
# The `state` of an optimiser contains all statistics used by the
# stateful transformations in the `chain` (in this case just `scale_by_adam`).
params = network.init(next(key_seq), jnp.zeros([1, input_size]))
opt_state = opt_init(params)
# Minimise the loss.
for step in range(n_training_steps):
# Get input. Learn to minimize the input to 0.
data = jax.random.normal(next(key_seq), [batch_size, input_size])
# Compute gradient and loss.
loss, grad = jax.value_and_grad(mean_square_loss)(params, data)
print(f'Loss[{step}] = {loss}')
# Transform the gradients using the optimiser.
updates, opt_state = opt_update(grad, opt_state, params)
# Update parameters.
params = optax.apply_updates(params, updates)
if __name__ == '__main__':
app.run(main)
| optax-master | examples/haiku_example.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""pytest configuration for fancyflags."""
from absl import flags
collect_ignore = [
'conftest.py',
'setup.py',
]
def pytest_configure(config):
del config # Unused.
# We need to skip flag parsing when executing under pytest.
flags.FLAGS.mark_as_parsed()
| fancyflags-master | conftest.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Install script for fancyflags."""
from importlib import util
import setuptools
def _get_version():
spec = util.spec_from_file_location('_metadata', 'fancyflags/_metadata.py')
mod = util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod.__version__
setuptools.setup(
name='fancyflags',
version=_get_version(),
description='A Python library for defining dictionary-valued flags.',
author='DeepMind',
license='Apache License, Version 2.0',
packages=setuptools.find_packages(),
install_requires=['absl-py'],
tests_require=['pytest'],
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
],
)
| fancyflags-master | setup.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for definitions."""
import copy
import datetime
import enum
from typing import Any, Callable
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
# definitions almost exactly corresponds to the public API, so aliasing the
# import here for better illustrative tests.
from fancyflags import _definitions as ff
from fancyflags import _flags
FLAGS = flags.FLAGS
class MyEnum(enum.Enum):
A = 1
B = 2
class DifferentEnum(enum.Enum):
C = 1
D = 2
class FancyflagsTest(absltest.TestCase):
def test_define_with_global_flagvalues(self):
# Since ff.DEFINE_dict uses an optional positional argument to specify a
# custom FlagValues instance, we run nearly the same test as below to make
# sure both global (default) and custom FlagValues work.
unused_flagholder = ff.DEFINE_dict(
"flat_dict",
integer_field=ff.Integer(1, "integer field"),
string_field=ff.String(""),
string_list_field=ff.StringList(["a", "b", "c"], "string list field"),
)
expected = {
"integer_field": 1,
"string_field": "",
"string_list_field": ["a", "b", "c"],
}
self.assertEqual(FLAGS.flat_dict, expected)
# These flags should also exist, although we won't access them in practice.
self.assertEqual(FLAGS["flat_dict.integer_field"].value, 1)
self.assertEqual(FLAGS["flat_dict.string_field"].value, "")
# Custom help string.
self.assertEqual(FLAGS["flat_dict.integer_field"].help, "integer field")
# Default help string.
self.assertEqual(
FLAGS["flat_dict.string_field"].help, "flat_dict.string_field"
)
def test_define_with_custom_flagvalues(self):
# Since ff.DEFINE_dict uses an optional positional argument to specify a
# custom FlagValues instance, we run nearly the same test as above to make
# sure both global (default) and custom FlagValues work.
flag_values = flags.FlagValues()
unused_flagholder = ff.DEFINE_dict(
"flat_dict",
flag_values,
integer_field=ff.Integer(1, "integer field"),
string_field=ff.String(""),
string_list_field=ff.StringList(["a", "b", "c"], "string list field"),
)
expected = {
"integer_field": 1,
"string_field": "",
"string_list_field": ["a", "b", "c"],
}
flag_values(("./program", ""))
self.assertEqual(flag_values.flat_dict, expected)
# These flags should also exist, although we won't access them in practice.
self.assertEqual(flag_values["flat_dict.integer_field"].value, 1)
self.assertEqual(flag_values["flat_dict.string_field"].value, "")
# Custom help string.
self.assertEqual(
flag_values["flat_dict.integer_field"].help, "integer field"
)
# Default help string.
self.assertEqual(
flag_values["flat_dict.string_field"].help, "flat_dict.string_field"
)
def test_define_flat(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"flat_dict",
flag_values,
integer_field=ff.Integer(1, "integer field"),
string_field=ff.String(""),
string_list_field=ff.StringList(["a", "b", "c"], "string list field"),
)
# This should return a single dict with the default values specified above.
expected = {
"integer_field": 1,
"string_field": "",
"string_list_field": ["a", "b", "c"],
}
flag_values(("./program", ""))
self.assertEqual(flag_values.flat_dict, expected)
self.assertEqual(flag_holder.value, expected)
def test_define_nested(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"nested_dict",
flag_values,
integer_field=ff.Integer(1, "integer field"),
sub_dict=dict(string_field=ff.String("", "string field")),
)
# This should return a single dict with the default values specified above.
expected = {"integer_field": 1, "sub_dict": {"string_field": ""}}
flag_values(("./program", ""))
self.assertEqual(flag_values.nested_dict, expected)
self.assertEqual(flag_holder.value, expected)
# These flags should also exist, although we won't access them in practice.
self.assertEqual(flag_values["nested_dict.integer_field"].value, 1)
self.assertEqual(flag_values["nested_dict.sub_dict.string_field"].value, "")
def test_no_name_error(self):
with self.assertRaisesRegex(ValueError, "one positional argument"):
ff.DEFINE_dict(
integer_field=ff.Integer(1, "integer field"),
)
def test_no_kwargs_error(self):
with self.assertRaisesRegex(ValueError, "one keyword argument"):
ff.DEFINE_dict("no_kwargs")
def test_too_many_positional_args_error(self):
with self.assertRaisesRegex(ValueError, "at most two positional"):
ff.DEFINE_dict(
"name",
ff.String("foo", "string"),
ff.String("bar", "string"),
integer_field=ff.Integer(1, "integer field"),
)
def test_flag_name_error(self):
with self.assertRaisesRegex(ValueError, "must be a string"):
ff.DEFINE_dict(
ff.String("name", "string flag"),
ff.String("stringflag", "string"),
integer_field=ff.Integer(1, "integer field"),
)
def test_flag_values_error(self):
with self.assertRaisesRegex(ValueError, "FlagValues instance"):
ff.DEFINE_dict(
"name",
ff.String("stringflag", "string"),
integer_field=ff.Integer(1, "integer field"),
)
def test_define_valid_enum(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"valid_enum",
flag_values,
padding=ff.Enum("same", ["same", "valid"], "enum field"),
)
flag_values(("./program", ""))
self.assertEqual(flag_holder.value, {"padding": "same"})
def test_define_valid_case_insensitive_enum(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"valid_case_sensitive",
flag_values,
padding=ff.Enum(
"Same", ["same", "valid"], "enum field", case_sensitive=False
),
)
flag_values(("./program", ""))
self.assertEqual(flag_holder.value, {"padding": "same"})
def test_define_invalid_enum(self):
with self.assertRaises(ValueError):
ff.Enum("invalid", ["same", "valid"], "enum field")
def test_define_invalid_case_sensitive_enum(self):
with self.assertRaises(ValueError):
ff.Enum("Same", ["same", "valid"], "enum field")
def test_define_valid_enum_class(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"valid_enum_class",
flag_values,
my_enum=ff.EnumClass(MyEnum.A, MyEnum, "enum class field"),
)
flag_values(("./program", ""))
self.assertEqual(flag_holder.value, {"my_enum": MyEnum.A})
def test_define_invalid_enum_class(self):
with self.assertRaises(ValueError):
ff.EnumClass(DifferentEnum.C, MyEnum)
class ExtractDefaultsTest(absltest.TestCase):
def test_valid_flat(self):
result = ff._extract_defaults({
"integer_field": ff.Integer(10, "Integer field"),
"string_field": ff.String("default", "String field"),
})
expected = {"integer_field": 10, "string_field": "default"}
self.assertEqual(result, expected)
def test_valid_nested(self):
result = ff._extract_defaults({
"integer_field": ff.Integer(10, "Integer field"),
"string_field": ff.String("default", "String field"),
"nested": {
"float_field": ff.Float(3.1, "Float field"),
},
})
expected = {
"integer_field": 10,
"string_field": "default",
"nested": {"float_field": 3.1},
}
self.assertEqual(result, expected)
def test_invalid_container(self):
expected_message = ff._NOT_A_DICT_OR_ITEM.format("list")
with self.assertRaisesWithLiteralMatch(TypeError, expected_message):
ff._extract_defaults({
"integer_field": ff.Integer(10, "Integer field"),
"string_field": ff.String("default", "String field"),
"nested": [ff.Float(3.1, "Float field")],
})
def test_invalid_flat_leaf(self):
expected_message = ff._NOT_A_DICT_OR_ITEM.format("int")
with self.assertRaisesWithLiteralMatch(TypeError, expected_message):
ff._extract_defaults({
"string_field": ff.String("default", "String field"),
"naughty_field": 100,
})
def test_invalid_nested_leaf(self):
expected_message = ff._NOT_A_DICT_OR_ITEM.format("bool")
with self.assertRaisesWithLiteralMatch(TypeError, expected_message):
ff._extract_defaults({
"string_field": ff.String("default", "String field"),
"nested": {
"naughty_field": True,
},
})
def test_overriding_top_level_dict_flag_fails(self):
flag_values = flags.FlagValues()
ff.DEFINE_dict(
"top_level_dict",
flag_values,
integer_field=ff.Integer(1, "integer field"),
)
# The error type and message get converted in the process.
with self.assertRaisesRegex(
flags.IllegalFlagValueError, "Can't override a dict flag directly"
):
flag_values(("./program", "--top_level_dict=3"))
class DateTimeTest(parameterized.TestCase):
@parameterized.named_parameters(
dict(
testcase_name="default_str",
default="2001-01-01",
expected=datetime.datetime(2001, 1, 1),
),
dict(
testcase_name="default_datetime",
default=datetime.datetime(2001, 1, 1),
expected=datetime.datetime(2001, 1, 1),
),
dict(testcase_name="no_default", default=None, expected=None),
)
def test_define_datetime_default(self, default, expected):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"dict_with_datetime",
flag_values,
my_datetime=ff.DateTime(default, "datetime field"),
)
flag_values(("./program", ""))
self.assertEqual(flag_holder.value, {"my_datetime": expected})
def test_define_datetime_invalid_default_raises(self):
with self.assertRaisesRegex(ValueError, r"invalid"):
ff.DEFINE_dict(
"dict_with_datetime",
my_datetime=ff.DateTime("42", "datetime field"),
)
def test_define_and_parse_invalid_value_raises(self):
flag_name = "dict_with_datetime"
flag_values = flags.FlagValues()
ff.DEFINE_dict(
flag_name,
flag_values,
my_datetime=ff.DateTime(None, "datetime field"),
)
with self.assertRaisesRegex(flags.IllegalFlagValueError, r"invalid"):
flag_values["dict_with_datetime.my_datetime"].parse("2001")
class SequenceTest(absltest.TestCase):
def test_sequence_defaults(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"dict_with_sequences",
flag_values,
int_sequence=ff.Sequence([1, 2, 3], "integer field"),
float_sequence=ff.Sequence([3.14, 2.718], "float field"),
mixed_sequence=ff.Sequence([100, "hello", "world"], "mixed field"),
)
flag_values(("./program", ""))
self.assertEqual(
flag_holder.value,
{
"int_sequence": [1, 2, 3],
"float_sequence": [3.14, 2.718],
"mixed_sequence": [100, "hello", "world"],
},
)
class MultiEnumTest(parameterized.TestCase):
def test_defaults_parsing(self):
flag_values = flags.FlagValues()
enum_values = [1, 2, 3, 3.14, 2.718, 100, "hello", ["world"], {"planets"}]
ff.DEFINE_dict(
"dict_with_multienums",
flag_values,
int_sequence=ff.MultiEnum([1, 2, 3], enum_values, "integer field"),
float_sequence=ff.MultiEnum([3.14, 2.718], enum_values, "float field"),
mixed_sequence=ff.MultiEnum(
[100, "hello", ["world"], {"planets"}], enum_values, "mixed field"
),
enum_sequence=ff.MultiEnum([MyEnum.A], MyEnum, "enum field"),
)
expected = {
"int_sequence": [1, 2, 3],
"float_sequence": [3.14, 2.718],
"mixed_sequence": [100, "hello", ["world"], {"planets"}],
"enum_sequence": [MyEnum.A],
}
flag_values(("./program", ""))
self.assertEqual(flag_values.dict_with_multienums, expected)
class DefineSequenceTest(absltest.TestCase):
# Follows test code in absl/flags/tests/flags_test.py
def test_definition(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_sequence(
name="sequence",
default=[1, 2, 3],
help="sequence flag",
flag_values=flag_values,
)
flag_values(("./program", ""))
self.assertEqual(flag_holder.value, [1, 2, 3])
self.assertEqual(flag_values.flag_values_dict()["sequence"], [1, 2, 3])
self.assertEqual(flag_values["sequence"].default_as_str, "'[1, 2, 3]'") # pytype: disable=attribute-error
def test_end_to_end_with_default(self):
# There are more extensive tests for the parser in argument_parser_test.py.
# Here we just include a couple of end-to-end examples.
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_sequence(
"sequence",
[1, 2, 3],
"sequence flag",
flag_values=flag_values,
)
flag_values(("./program", "--sequence=[4,5]"))
self.assertEqual(flag_holder.value, [4, 5])
def test_end_to_end_without_default(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_sequence(
"sequence",
None,
"sequence flag",
flag_values=flag_values,
)
flag_values(("./program", "--sequence=(4, 5)"))
self.assertEqual(flag_holder.value, (4, 5))
class DefineMultiEnumTest(absltest.TestCase):
# Follows test code in absl/flags/tests/flags_test.py
def test_definition(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_multi_enum(
"multienum",
[1, 2, 3],
[1, 2, 3],
"multienum flag",
flag_values=flag_values,
)
flag_values(("./program", ""))
self.assertEqual(flag_holder.value, [1, 2, 3])
self.assertEqual(flag_values.multienum, [1, 2, 3])
self.assertEqual(flag_values.flag_values_dict()["multienum"], [1, 2, 3])
self.assertEqual(flag_values["multienum"].default_as_str, "'[1, 2, 3]'") # pytype: disable=attribute-error
def test_end_to_end_with_default(self):
# There are more extensive tests for the parser in argument_parser_test.py.
# Here we just include a couple of end-to-end examples.
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_multi_enum(
"multienum0",
[1, 2, 3],
[1, 2, 3, 4, 5],
"multienum flag",
flag_values=flag_values,
)
flag_values(("./program", "--multienum0=[4,5]"))
self.assertEqual(flag_holder.value, [4, 5])
def test_end_to_end_without_default(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_multi_enum(
"multienum1",
None,
[1, 2, 3, 4, 5],
"multienum flag",
flag_values=flag_values,
)
flag_values(("./program", "--multienum1=(4, 5)"))
self.assertEqual(flag_holder.value, (4, 5))
class MultiEnumClassTest(parameterized.TestCase):
def test_multi_enum_class(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"dict_with_multi_enum_class",
flag_values,
item=ff.MultiEnumClass(
[MyEnum.A],
MyEnum,
"multi enum",
),
)
flag_values((
"./program",
"--dict_with_multi_enum_class.item=A",
"--dict_with_multi_enum_class.item=B",
"--dict_with_multi_enum_class.item=A",
))
expected = {"item": [MyEnum.A, MyEnum.B, MyEnum.A]}
self.assertEqual(flag_holder.value, expected)
class MultiStringTest(parameterized.TestCase):
def test_defaults_parsing(self):
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
"dict_with_multistrings",
flag_values,
no_default=ff.MultiString(None, "no default"),
single_entry=ff.MultiString("a", "single entry"),
single_entry_list=ff.MultiString(["a"], "single entry list"),
multiple_entry_list=ff.MultiString(["a", "b"], "multiple entry list"),
)
flag_values(("./program", ""))
expected = {
"no_default": None,
"single_entry": ["a"],
"single_entry_list": ["a"],
"multiple_entry_list": ["a", "b"],
}
self.assertEqual(flag_holder.value, expected)
class SerializationTest(absltest.TestCase):
def test_basic_serialization(self):
flag_values = flags.FlagValues()
ff.DEFINE_dict(
"to_serialize",
flag_values,
integer_field=ff.Integer(1, "integer field"),
boolean_field=ff.Boolean(False, "boolean field"),
string_list_field=ff.StringList(["a", "b", "c"], "string list field"),
enum_class_field=ff.EnumClass(MyEnum.A, MyEnum, "my enum field"),
)
initial_dict_value = copy.deepcopy(flag_values["to_serialize"].value)
# Parse flags, then serialize.
flag_values([
"./program",
"--to_serialize.boolean_field=True",
"--to_serialize.integer_field",
"1337",
"--to_serialize.string_list_field=d,e,f",
"--to_serialize.enum_class_field=B",
])
self.assertEqual(flag_values["to_serialize"].serialize(), _flags._EMPTY)
self.assertEqual(
flag_values["to_serialize.boolean_field"].serialize(),
"--to_serialize.boolean_field",
)
self.assertEqual(
flag_values["to_serialize.string_list_field"].serialize(),
"--to_serialize.string_list_field=d,e,f",
)
parsed_dict_value = copy.deepcopy(flag_values["to_serialize"].value)
self.assertDictEqual(
parsed_dict_value,
{
"boolean_field": True,
"integer_field": 1337,
"string_list_field": ["d", "e", "f"],
"enum_class_field": MyEnum.B,
},
)
self.assertNotEqual(flag_values["to_serialize"].value, initial_dict_value)
# test a round trip
serialized_args = [
flag_values[name].serialize()
for name in flag_values
if name.startswith("to_serialize.")
]
flag_values.unparse_flags() # Reset to defaults
self.assertDictEqual(flag_values["to_serialize"].value, initial_dict_value)
flag_values(["./program"] + serialized_args)
self.assertDictEqual(flag_values["to_serialize"].value, parsed_dict_value)
NAMES_ITEMS_AND_FLAGS = (
dict(
testcase_name="boolean",
define_function=flags.DEFINE_boolean,
item_constructor=ff.Boolean,
default=True,
override="false",
),
dict(
testcase_name="integer",
define_function=flags.DEFINE_integer,
item_constructor=ff.Integer,
default=1,
override="2",
),
dict(
testcase_name="float",
define_function=flags.DEFINE_float,
item_constructor=ff.Float,
default=1.0,
override="2.0",
),
dict(
testcase_name="sequence",
define_function=ff.DEFINE_sequence,
item_constructor=ff.Sequence,
default=(1, "x"),
override=(2.0, "y"),
),
dict(
testcase_name="string",
define_function=flags.DEFINE_string,
item_constructor=ff.String,
default="one",
override="two",
),
dict(
testcase_name="stringlist",
define_function=flags.DEFINE_list,
item_constructor=ff.StringList,
default=["a", "b"],
override="['c', 'd']",
),
)
class FlagAndItemEquivalence(parameterized.TestCase):
@parameterized.named_parameters(*NAMES_ITEMS_AND_FLAGS)
def test_equivalence(
self,
define_function: Callable[..., flags.FlagHolder],
item_constructor: type(ff.Item),
default: Any,
override: str,
):
flag_values = flags.FlagValues()
flag_holder = define_function(
"name.item",
default,
"help string",
flag_values=flag_values,
)
ff_flagvalues = flags.FlagValues()
shared_values = ff.define_flags(
"name",
{"item": item_constructor(default, "help string")},
flag_values=ff_flagvalues,
)
with self.subTest("Check serialisation equivalence before parsing"):
self.assertEqual(
flag_values["name.item"].serialize(),
ff_flagvalues["name.item"].serialize(),
)
self.assertEqual(
flag_values.flags_into_string(), ff_flagvalues.flags_into_string()
)
with self.subTest("Apply overrides and check equivalence after parsing"):
# The flag holder gets updated at this point:
flag_values(("./program", f"--name.item={override}"))
# The shared_values dict gets updated at this point:
ff_flagvalues(("./program", f"--name.item={override}"))
self.assertNotEqual(flag_holder.value, default)
self.assertEqual(flag_holder.value, shared_values["item"])
if __name__ == "__main__":
absltest.main()
| fancyflags-master | fancyflags/_definitions_test.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Argument parsers."""
import ast
import datetime
import enum
from absl import flags
BASIC_SEQUENCE_TYPES = (list, tuple)
# We assume a sequence contains only these types. Python has no primitive types.
SIMPLE_TYPES = (bool, float, int, str)
NOT_A_SIMPLE_TYPE_MESSAGE = """
Input list contains unsupported type {{}}, however each element in a sequence
must be a {} or {}.
""".format(
", ".join(type_.__name__ for type_ in SIMPLE_TYPES[:-1]),
SIMPLE_TYPES[-1].__name__,
)
_EMPTY_STRING_ERROR_MESSAGE = """
Empty sequences should be given explicitly as [] or () and not as an empty
string"""
class SequenceParser(flags.ArgumentParser):
"""Parser of simple sequences containing simple Python values."""
def parse(self, argument):
"""Parses the argument as a string-formatted sequence (list or tuple).
Essentially reverses the result of `"{}".format(a_sequence)`
Args:
argument: The flag value as a string, list, tuple or None. Examples of
valid input strings are `"(1,2,3)"` and `[0.2, 0.3, 1.0]`.
Returns:
The parsed sequence.
Raises:
TypeError: If the input type is not supported, or if the input is not a
flat sequence that only contains simple Python values.
ValueError: If the input is an empty string.
"""
if argument is None:
return []
elif isinstance(argument, BASIC_SEQUENCE_TYPES):
result = argument[:]
elif isinstance(argument, str):
if not argument:
raise ValueError(_EMPTY_STRING_ERROR_MESSAGE)
try:
result = ast.literal_eval(argument)
except (ValueError, SyntaxError) as e:
raise ValueError(
f'Failed to parse "{argument}" as a python literal.'
) from e
if not isinstance(result, BASIC_SEQUENCE_TYPES):
raise TypeError(
"Input string should represent a list or tuple, however it "
"evaluated as a {}.".format(type(result).__name__)
)
else:
raise TypeError("Unsupported type {}.".format(type(argument).__name__))
# Make sure the result is a flat sequence of simple types.
for value in result:
if not isinstance(value, SIMPLE_TYPES):
raise TypeError(NOT_A_SIMPLE_TYPE_MESSAGE.format(type(value).__name__))
return result
def flag_type(self):
"""See base class."""
return "sequence"
class MultiEnumParser(flags.ArgumentParser):
"""Parser of multiple enum values.
This parser allows the flag values to be sequences of any type, unlike
flags.DEFINE_multi_enum which only allows strings.
"""
def __init__(self, enum_values):
if not enum_values:
raise ValueError("enum_values cannot be empty")
if any(not value for value in enum_values):
raise ValueError("No element of enum_values can be empty")
super().__init__()
self.enum_values = enum_values
def parse(self, arguments):
"""Determines validity of arguments.
Args:
arguments: list, tuple, or enum of flag values. Each value may be any type
Returns:
The input list, tuple or enum if valid.
Raises:
TypeError: If the input type is not supported.
ValueError: Raised if an argument element didn't match anything in enum.
"""
if arguments is None:
return []
elif isinstance(arguments, BASIC_SEQUENCE_TYPES):
result = arguments[:]
elif isinstance(arguments, enum.EnumMeta):
result = arguments
elif isinstance(arguments, str):
result = ast.literal_eval(arguments)
if not isinstance(result, BASIC_SEQUENCE_TYPES):
raise TypeError(
"Input string should represent a list or tuple, however it "
"evaluated as a {}.".format(type(result).__name__)
)
else:
raise TypeError("Unsupported type {}.".format(type(arguments).__name__))
if not all(arg in self.enum_values for arg in result):
raise ValueError(
"Argument values should be one of <{}>".format(
"|".join(str(value) for value in self.enum_values)
)
)
else:
return result
def flag_type(self):
return "multi enum"
class PossiblyNaiveDatetimeParser(flags.ArgumentParser):
"""Parses an ISO format datetime string into a datetime.datetime."""
def parse(self, value) -> datetime.datetime:
if isinstance(value, datetime.datetime):
return value
# Handle ambiguous cases such as 2000-01-01+01:00, where the part after the
# '+' sign looks like timezone info but is actually just the time.
if value[10:11] in ("+", "-"):
# plus/minus as separator between date and time (can be any character)
raise ValueError(
f"datetime value {value!r} uses {value[10]!r} as separator "
"between date and time (excluded to avoid confusion between "
"time and offset). Use any other character instead, e.g. "
f"{value[:10] + 'T' + value[11:]!r}"
)
try:
return datetime.datetime.fromisoformat(value)
except ValueError as e:
raise ValueError(f"invalid datetime value {value!r}: {e}") from None
def flag_type(self) -> str:
return "datetime.datetime"
| fancyflags-master | fancyflags/_argument_parsers.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Package metadata.
This is kept in a separate module so that it can be imported from setup.py, at
a time when the package dependencies may not have been installed yet.
"""
__version__ = '1.2' # https://www.python.org/dev/peps/pep-0440/
| fancyflags-master | fancyflags/_metadata.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Automatically builds flags from a callable signature."""
import datetime
import enum
import functools
import inspect
import sys
import typing
from typing import Any, Callable, Collection, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple
import warnings
from fancyflags import _definitions
# TODO(b/178129474): Improve support for typing.Sequence subtypes.
_TYPE_MAP = {
List[bool]: _definitions.Sequence, # pylint: disable=unhashable-member
List[float]: _definitions.Sequence, # pylint: disable=unhashable-member
List[int]: _definitions.Sequence, # pylint: disable=unhashable-member
List[str]: _definitions.Sequence, # pylint: disable=unhashable-member
Sequence[bool]: _definitions.Sequence,
Sequence[float]: _definitions.Sequence,
Sequence[int]: _definitions.Sequence,
Sequence[str]: _definitions.Sequence,
Tuple[bool, ...]: _definitions.Sequence,
Tuple[bool]: _definitions.Sequence,
Tuple[float, ...]: _definitions.Sequence,
Tuple[float]: _definitions.Sequence,
Tuple[int, ...]: _definitions.Sequence,
Tuple[int]: _definitions.Sequence,
Tuple[str, ...]: _definitions.Sequence,
Tuple[str]: _definitions.Sequence,
bool: _definitions.Boolean,
datetime.datetime: _definitions.DateTime,
float: _definitions.Float,
int: _definitions.Integer,
str: _definitions.String,
}
if sys.version_info >= (3, 9):
# Support PEP 585 type hints.
_TYPE_MAP.update(
{
list[bool]: _definitions.Sequence,
list[float]: _definitions.Sequence,
list[int]: _definitions.Sequence,
list[str]: _definitions.Sequence,
tuple[bool, ...]: _definitions.Sequence,
tuple[bool]: _definitions.Sequence,
tuple[float, ...]: _definitions.Sequence,
tuple[float]: _definitions.Sequence,
tuple[int, ...]: _definitions.Sequence,
tuple[int]: _definitions.Sequence,
tuple[str, ...]: _definitions.Sequence,
tuple[str]: _definitions.Sequence,
}
)
# Add optional versions of all types as well
_TYPE_MAP.update({Optional[tp]: parser for tp, parser in _TYPE_MAP.items()})
_MISSING_TYPE_ANNOTATION = "Missing type annotation for argument {name!r}"
_UNSUPPORTED_ARGUMENT_TYPE = (
"No matching flag type for argument {{name!r}} with type annotation: "
"{{annotation}}\n"
"Supported types:\n{}".format("\n".join(str(t) for t in _TYPE_MAP))
)
_MISSING_DEFAULT_VALUE = "Missing default value for argument {name!r}"
_is_enum = lambda type_: inspect.isclass(type_) and issubclass(type_, enum.Enum)
_is_unsupported_type = lambda type_: not (type_ in _TYPE_MAP or _is_enum(type_))
def get_typed_signature(fn: Callable[..., Any]) -> inspect.Signature:
"""Returns the signature of a callable with type annotations resolved.
If postponed evaluation of type annotations (PEP 563) is enabled (e.g. via
`from __future__ import annotations` in Python >= 3.7) then we will need to
resolve the annotations from their string forms in order to access the real
types within the signature.
https://www.python.org/dev/peps/pep-0563/#resolving-type-hints-at-runtime
Args:
fn: A callable to get the signature of.
Returns:
An instance of `inspect.Signature`.
"""
type_hints = typing.get_type_hints(fn) or {}
orig_signature = inspect.signature(fn)
new_params = []
for key, orig_param in orig_signature.parameters.items():
new_params.append(
inspect.Parameter(
name=key,
default=orig_param.default,
annotation=type_hints.get(key, orig_param.annotation),
kind=orig_param.kind,
)
)
return orig_signature.replace(parameters=new_params)
def auto(
callable_fn: Callable[..., Any],
*,
strict: bool = True,
skip_params: Collection[str] = (),
) -> Mapping[str, _definitions.Item]:
"""Automatically builds fancyflag definitions from a callable's signature.
Example usage:
```python
# Function
ff.DEFINE_dict('my_function_settings', **ff.auto(my_module.my_function))
# Class constructor
ff.DEFINE_dict('my_class_settings', **ff.auto(my_module.MyClass))
```
Args:
callable_fn: Generates flag definitions from this callable's signature. All
arguments must have type annotations and default values. The following
argument types are supported: * `bool`, `float`, `int`, or `str` scalars
* Homogeneous sequences of these types * Optional scalars or sequences of
these types
strict: A bool, whether invalid input types and defaults should trigger an
error (the default) or be silently ignored. Setting strict=False might
silence real errors, but will allow decorated functions to contain
non-default values, or values with defaults that can not be easily turned
into a flag or overriden on the CLI.
skip_params: Optional parameter names to skip defining flags for.
Returns:
Mapping from parameter names to fancyflags `Item`s, to be splatted into
`ff.DEFINE_dict`.
Raises:
ValueError: If any of the arguments to `callable_fn` lacks a default value.
TypeError: If any of the arguments to `callable_fn` lacks a type annotation.
TypeError: If any of the arguments to `callable_fn` has an unsupported type.
TypeError: If `callable_fn` is not callable.
"""
if not callable(callable_fn):
raise TypeError(f"Not a callable: {callable_fn}.")
# Work around issue with metaclass-wrapped classes, such as Sonnet v2 modules.
if isinstance(callable_fn, type):
signature = get_typed_signature(callable_fn.__init__)
# Remove `self` from start of __init__ signature.
unused_self, *parameters = signature.parameters.values()
else:
signature = get_typed_signature(callable_fn)
parameters = signature.parameters.values()
items: MutableMapping[str, _definitions.Item] = {}
parameters: Iterable[inspect.Parameter]
for param in parameters:
if param.name in skip_params:
continue
# Check for potential errors.
if param.annotation is inspect.Signature.empty:
exception = TypeError(_MISSING_TYPE_ANNOTATION.format(name=param.name))
elif _is_unsupported_type(param.annotation):
exception = TypeError(
_UNSUPPORTED_ARGUMENT_TYPE.format(
name=param.name, annotation=param.annotation
)
)
else:
exception = None
# If we saw an error, decide whether to raise or skip based on strictness.
if exception:
if strict:
raise exception
else:
warnings.warn(
f"Caught an exception ({exception}) when defining flags for "
f"parameter {param}; skipping because strict=False..."
)
continue
# Look up the corresponding Item to create.
if _is_enum(param.annotation):
item_constructor = functools.partial(
_definitions.EnumClass, enum_class=param.annotation
)
else:
item_constructor = _TYPE_MAP[param.annotation]
# If there is no default argument for this parameter, we set the
# corresponding `Flag` as `required`.
if param.default is inspect.Signature.empty:
default = None
required = True
else:
default = param.default
required = False
# TODO(b/177673667): Parse the help string from docstring.
items[param.name] = item_constructor(
default,
help_string=param.name,
required=required,
)
return items
| fancyflags-master | fancyflags/_auto.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Flag classes for defining dict, Item, MultiItem and Auto flags."""
import copy
import functools
from absl import flags
_EMPTY = ""
class DictFlag(flags.Flag):
"""Implements the shared dict mechanism. See also `ItemFlag`."""
def __init__(self, shared_dict, *args, **kwargs):
self._shared_dict = shared_dict
super().__init__(*args, **kwargs)
def _parse(self, value):
# A `DictFlag` should not be overridable from the command line; only the
# dotted `Item` flags should be. However, the _parse() method will still be
# called in two situations:
# 1. Via the base `Flag`'s constructor, which calls `_parse()` to process
# the default value, which will be the shared dict.
# 2. When processing command line overrides. We don't want to allow this
# normally, however some libraries will serialize and deserialize all
# flags, e.g. to pass values between processes, so we accept a dummy
# empty serialized value for these cases. It's unlikely users will try to
# set the dict flag to an empty string from the command line.
if value is self._shared_dict or value == _EMPTY:
return self._shared_dict
raise flags.IllegalFlagValueError(
"Can't override a dict flag directly. Did you mean to override one of "
"its `Item`s instead?"
)
def serialize(self):
# When serializing flags, we return a sentinel value that the `DictFlag`
# will ignore when parsing. The value of this flag is determined by the
# corresponding `Item` flags for serialization and deserialization.
return _EMPTY
def flag_type(self):
return "dict"
# TODO(b/170423907): Pytype doesn't correctly infer that these have type
# `property`.
_flag_value_property = flags.Flag.value # type: property # pytype: disable=annotation-type-mismatch,unbound-type-param
_multi_flag_value_property = flags.MultiFlag.value # type: property # pytype: disable=annotation-type-mismatch
class ItemFlag(flags.Flag):
"""Updates a shared dict whenever its own value changes.
See also the `DictFlag` and `ff.Item` classes for usage.
"""
def __init__(self, shared_dict, namespace, parser, *args, **kwargs):
self._shared_dict = shared_dict
self._namespace = namespace
super().__init__(
*args,
parser=parser,
# absl treats boolean flags as a special case in order to support the
# alternative `--foo`/`--nofoo` syntax.
boolean=isinstance(parser, flags.BooleanParser),
**kwargs
)
# `super().value = value` doesn't work, see https://bugs.python.org/issue14965
@_flag_value_property.setter
def value(self, value):
_flag_value_property.fset(self, value)
self._update_shared_dict()
def parse(self, argument):
super().parse(argument)
self._update_shared_dict()
def _update_shared_dict(self):
d = self._shared_dict
for name in self._namespace[:-1]:
d = d[name]
d[self._namespace[-1]] = self.value
class MultiItemFlag(flags.MultiFlag):
"""Updates a shared dict whenever its own value changes.
Used for flags that can appear multiple times on the command line.
See also the `DictFlag` and `ff.Item` classes for usage.
"""
def __init__(self, shared_dict, namespace, *args, **kwargs):
self._shared_dict = shared_dict
self._namespace = namespace
super().__init__(*args, **kwargs)
# `super().value = value` doesn't work, see https://bugs.python.org/issue14965
@_multi_flag_value_property.setter
def value(self, value):
_multi_flag_value_property.fset(self, value)
self._update_shared_dict()
def parse(self, argument):
super().parse(argument)
self._update_shared_dict()
def _update_shared_dict(self):
d = self._shared_dict
for name in self._namespace[:-1]:
d = d[name]
d[self._namespace[-1]] = self.value
class AutoFlag(flags.Flag):
"""Implements the shared dict mechanism."""
def __init__(self, fn, fn_kwargs, *args, **kwargs):
self._fn = fn
self._fn_kwargs = fn_kwargs
super().__init__(*args, **kwargs)
@property
def value(self):
kwargs = copy.deepcopy(self._fn_kwargs)
return functools.partial(self._fn, **kwargs)
@value.setter
def value(self, value):
# The flags `.value` gets set as part of the `flags.FLAG` constructor to a
# default value. However the default value should be given by the initial
# `fn_kwargs` instead, so a) the semantics of setting the value are unclear
# and b) we may not be able to call `self._fn` at this point in execution.
del value
def _parse(self, value):
# An `AutoFlag` should not be overridable from the command line; only the
# dotted `Item` flags should be. However, the `_parse()` method will still
# be called in two situations:
# 1. In the base `Flag`'s constructor, which calls `_parse()` to process the
# default value, which will be None (as set in `DEFINE_auto`).
# 2. When processing command line overrides. We don't want to allow this
# normally, however some libraries will serialize and deserialize all
# flags, e.g. to pass values between processes, so we accept a dummy
# empty serialized value for these cases. It's unlikely users will try to
# set the auto flag to an empty string from the command line.
if value is None or value == _EMPTY:
return None
raise flags.IllegalFlagValueError(
"Can't override an auto flag directly. Did you mean to override one of "
"its `Item`s instead?"
)
def serialize(self):
# When serializing a `FlagHolder` container, we must return *some* value for
# this flag. We return an empty value that the `AutoFlag` will ignore when
# parsing. The value of this flag is instead determined by the
# corresponding `Item` flags for serialization and deserialization.
return _EMPTY
def flag_type(self):
return "auto"
| fancyflags-master | fancyflags/_flags.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Functionality for defining `Item`s and dict flags."""
import collections
import enum
from typing import Any, Generic, Iterable, Mapping, Optional, Type, TypeVar, Union
from absl import flags
from fancyflags import _argument_parsers
from fancyflags import _flags
_T = TypeVar("_T")
_EnumT = TypeVar("_EnumT", bound=enum.Enum)
_MappingT = TypeVar("_MappingT", bound=Mapping[str, Any])
SEPARATOR = "."
_NOT_A_DICT_OR_ITEM = """
DEFINE_dict only supports flat or nested dictionaries, and these must contain
`ff.Item`s or `ff.MultiItems. Found type {} in this definition.
"""
# Add this module to absl's exclusion set for determining the calling modules.
flags.disclaim_key_flags()
def DEFINE_dict(*args, **kwargs): # pylint: disable=invalid-name
"""Defines a flat or nested dictionary flag.
Usage example:
```python
import fancyflags as ff
ff.DEFINE_dict(
"image_settings",
mode=ff.String("pad"),
sizes=dict(
width=ff.Integer(5),
height=ff.Integer(7),
scale=ff.Float(0.5),
)
)
This creates a flag `FLAGS.image_settings`, with a default value of
```python
{
"mode": "pad",
"sizes": {
"width": 5,
"height": 7,
"scale": 0.5,
}
}
```
Each item in the definition (e.g. ff.Integer(...)) corresponds to a flag that
can be overridden from the command line using "dot" notation. For example, the
following command overrides the `height` item in the nested dictionary defined
above:
```
python script_name.py -- --image_settings.sizes.height=10
```
Args:
*args: One or two positional arguments are expected: 1. A string containing
the root name for this flag. This must be set. 2. Optionally, a
`flags.FlagValues` object that will hold the Flags. If not set, the usual
global `flags.FLAGS` object will be used.
**kwargs: One or more keyword arguments, where the value is either an
`ff.Item` such as `ff.String(...)` or `ff.Integer(...)` or a dict with the
same constraints.
Returns:
A `FlagHolder` instance.
"""
if not args:
raise ValueError(
"Please supply one positional argument containing the "
"top-level flag name for the dict."
)
if not kwargs:
raise ValueError(
"Please supply at least one keyword argument defining a flag."
)
if len(args) > 2:
raise ValueError(
"Please supply at most two positional arguments, the "
"first containing the top-level flag name for the dict "
"and, optionally and unusually, a second positional "
"argument to override the flags.FlagValues instance to "
"use."
)
if not isinstance(args[0], str):
raise ValueError(
"The first positional argument must be a string "
"containing top-level flag name for the dict. Got a {}.".format(
type(args[0]).__name__
)
)
if len(args) == 2:
if not isinstance(args[1], flags.FlagValues):
raise ValueError(
"If supplying a second positional argument, this must "
"be a flags.FlagValues instance. Got a {}. If you meant "
"to define a flag, note these must be supplied as "
"keyword arguments. ".format(type(args[1]).__name__)
)
flag_values = args[1]
else:
flag_values = flags.FLAGS
flag_name = args[0]
shared_dict = define_flags(flag_name, kwargs, flag_values=flag_values)
# TODO(b/177672282): Can we persuade pytype to correctly infer the type of the
# flagholder's .value attribute?
# We register a dummy flag that returns `shared_dict` as a value.
return flags.DEFINE_flag(
_flags.DictFlag(
shared_dict,
name=flag_name,
default=shared_dict,
parser=flags.ArgumentParser(),
serializer=None,
help_string="Unused help string.",
),
flag_values=flag_values,
)
def define_flags(
name: str,
name_to_item: _MappingT,
flag_values: flags.FlagValues = flags.FLAGS,
) -> _MappingT:
"""Defines dot-delimited flags from a flat or nested dict of `ff.Item`s.
Args:
name: The top-level name to prepend to each flag.
name_to_item: A flat or nested dictionary, where each final value is an
`ff.Item` such as `ff.String(...)` or `ff.Integer(...)`.
flag_values: The `flags.FlagValues` instance to use. By default this is
`flags.FLAGS`. Most users will not need to override this.
Returns:
A flat or nested dictionary containing the default values in `name_to_item`.
Overriding any of the flags defined by this function will also update the
corresponding entry in the returned dictionary.
"""
# Each flag that we will define holds a reference to `shared_dict`, which is
# a flat or nested dictionary containing the default values.
shared_dict = _extract_defaults(name_to_item)
# We create flags for each leaf item (e.g. ff.Integer(...)).
# These are the flags that users will actually interact with when overriding
# flags from the command line, however they will not access directly in their
# scripts. It is also the job of these flags to update the corresponding
# values in `shared_dict`, whenever their own values change.
def recursively_define_flags(namespace, maybe_item):
if isinstance(maybe_item, collections.abc.Mapping):
for key, value in maybe_item.items():
recursively_define_flags(namespace + (key,), value)
else:
assert isinstance(maybe_item, (Item, MultiItem))
maybe_item.define(namespace, {name: shared_dict}, flag_values)
for key, value in name_to_item.items():
recursively_define_flags(namespace=(name, key), maybe_item=value)
return shared_dict
def _extract_defaults(name_to_item):
"""Converts a flat or nested dict into a flat or nested dict of defaults."""
result = {}
for key, value in name_to_item.items():
if isinstance(value, (Item, MultiItem)):
result[key] = value.default
elif isinstance(value, dict):
result[key] = _extract_defaults(value)
else:
type_name = type(value).__name__
raise TypeError(_NOT_A_DICT_OR_ITEM.format(type_name))
return result
class Item(Generic[_T]):
"""Defines a flag for leaf items in the dictionary."""
def __init__(
self,
default: Optional[_T],
help_string: str,
parser: flags.ArgumentParser,
serializer: Optional[flags.ArgumentSerializer] = None,
*,
required: bool = False,
):
"""Initializes a new `Item`.
Args:
default: Default value of the flag that this instance will create.
help_string: Help string for the flag that this instance will create. If
`None`, then the dotted flag name will be used as the help string.
parser: A `flags.ArgumentParser` used to parse command line input.
serializer: An optional custom `flags.ArgumentSerializer`. By default, the
flag defined by this class will use an instance of the base
`flags.ArgumentSerializer`.
required: Whether or not this item is required. If True, the corresponding
abseil flag will be marked as required.
"""
# Flags run the following lines of parsing code during initialization.
# See Flag._set_default in absl/flags/_flag.py
# It's useful to repeat it here so that users will see any errors when the
# Item is initialized, rather than when define() is called later.
# The only minor difference is that Flag._set_default calls Flag._parse,
# which also catches and modifies the exception type.
if default is None:
self.default = default
else:
if required:
# Mirror the strict behavior of abseil flags.
raise ValueError(
"If marking an Item as required, the default must be None."
)
self.default = parser.parse(default) # pytype: disable=wrong-arg-types
self.required = required
self._help_string = help_string
self._parser = parser
if serializer is None:
self._serializer = flags.ArgumentSerializer()
else:
self._serializer = serializer
def define(
self,
namespace: str,
shared_dict,
flag_values: flags.FlagValues,
) -> flags.FlagHolder[_T]:
"""Defines a flag that when parsed will update a shared dictionary.
Args:
namespace: A sequence of strings that define the name of this flag. For
example, `("foo", "bar")` will correspond to a flag named `foo.bar`.
shared_dict: A dictionary that is shared by the top level dict flag. When
the individual flag created by this method is parsed, it will also write
the parsed value into `shared_dict`. The `namespace` determines the flat
or nested key when storing the parsed value.
flag_values: The `flags.FlagValues` instance to use.
Returns:
A new flags.FlagHolder instance.
"""
name = SEPARATOR.join(namespace)
help_string = name if self._help_string is None else self._help_string
return flags.DEFINE_flag(
_flags.ItemFlag(
shared_dict,
namespace,
parser=self._parser,
serializer=self._serializer,
name=name,
default=self.default,
help_string=help_string,
),
flag_values=flag_values,
required=self.required,
)
class Boolean(Item[bool]):
"""Matches behaviour of flags.DEFINE_boolean."""
def __init__(
self,
default: Optional[bool],
help_string: Optional[str] = None,
*,
required: bool = False,
):
super().__init__(
default,
help_string,
flags.BooleanParser(),
required=required,
)
# TODO(b/177673597) Better document the different enum class options and
# possibly recommend some over others.
class Enum(Item[str]):
"""Matches behaviour of flags.DEFINE_enum."""
def __init__(
self,
default: Optional[str],
enum_values: Iterable[str],
help_string: Optional[str] = None,
*,
case_sensitive: bool = True,
required: bool = False,
):
parser = flags.EnumParser(tuple(enum_values), case_sensitive)
super().__init__(default, help_string, parser, required=required)
class EnumClass(Item[_EnumT]):
"""Matches behaviour of flags.DEFINE_enum_class."""
def __init__(
self,
default: Optional[_EnumT],
enum_class: Type[_EnumT],
help_string: Optional[str] = None,
*,
case_sensitive: bool = False,
required: bool = False,
):
parser = flags.EnumClassParser(enum_class, case_sensitive=case_sensitive)
super().__init__(
default,
help_string,
parser,
flags.EnumClassSerializer(lowercase=False),
required=required,
)
class Float(Item[float]):
"""Matches behaviour of flags.DEFINE_float."""
def __init__(
self,
default: Optional[float],
help_string: Optional[str] = None,
*,
required: bool = False,
):
super().__init__(
default, help_string, flags.FloatParser(), required=required
)
class Integer(Item[int]):
"""Matches behaviour of flags.DEFINE_integer."""
def __init__(
self,
default: Optional[int],
help_string: Optional[str] = None,
required: bool = False,
):
super().__init__(
default, help_string, flags.IntegerParser(), required=required
)
class Sequence(Item, Generic[_T]):
r"""Defines a flag for a list or tuple of simple numeric types or strings.
Here is an example of overriding a Sequence flag within a dict-flag named
"settings" from the command line, with a list of values.
```
--settings.sequence=[1,2,3]
```
To include spaces, either quote the entire literal, or escape spaces as:
```
--settings.sequence="[1, 2, 3]"
--settings.sequence=[1,\ 2,\ 3]
```
"""
def __init__(
self,
default: Optional[Iterable[_T]],
help_string: Optional[str] = None,
required: bool = False,
):
super().__init__(
default,
help_string,
_argument_parsers.SequenceParser(),
required=required,
)
class String(Item[str]):
"""Matches behaviour of flags.DEFINE_string."""
def __init__(
self,
default: Optional[str],
help_string: Optional[str] = None,
*,
required: bool = False,
):
super().__init__(
default,
help_string,
flags.ArgumentParser(),
required=required,
)
class DateTime(Item):
def __init__(
self,
default: Optional[str],
help_string: Optional[str] = None,
*,
required: bool = False,
):
super(DateTime, self).__init__(
default,
help_string,
_argument_parsers.PossiblyNaiveDatetimeParser(),
required=required,
)
class StringList(Item[Iterable[str]]):
"""A flag that implements the same behavior as absl.flags.DEFINE_list.
Can be overwritten as --my_flag="a,list,of,commaseparated,strings"
"""
def __init__(
self,
default: Optional[Iterable[str]],
help_string: Optional[str] = None,
):
serializer = flags.CsvListSerializer(",")
super().__init__(default, help_string, flags.ListParser(), serializer)
# MultiFlag-related functionality.
class MultiItem(Generic[_T]):
"""Class for items that can appear multiple times on the command line.
See Item class for more details on methods and usage.
"""
def __init__(
self,
default: Union[None, _T, Iterable[_T]],
help_string: str,
parser: flags.ArgumentParser,
serializer: Optional[flags.ArgumentSerializer] = None,
):
if default is None:
self.default = default
else:
if isinstance(default, collections.abc.Iterable) and not isinstance(
default, (str, bytes)
):
# Convert all non-string iterables to lists.
default = list(default)
if not isinstance(default, list):
# Turn single items into single-value lists.
default = [default]
# Ensure each individual value is well-formed.
self.default = [parser.parse(item) for item in default]
self._help_string = help_string
self._parser = parser
if serializer is None:
self._serializer = flags.ArgumentSerializer()
else:
self._serializer = serializer
def define(
self,
namespace: str,
shared_dict,
flag_values,
) -> flags.FlagHolder[Iterable[_T]]:
name = SEPARATOR.join(namespace)
help_string = name if self._help_string is None else self._help_string
return flags.DEFINE_flag(
_flags.MultiItemFlag(
shared_dict,
namespace,
parser=self._parser,
serializer=self._serializer,
name=name,
default=self.default,
help_string=help_string,
),
flag_values=flag_values,
)
class MultiEnum(Item[_T]):
"""Defines a flag for lists of values of any type, matched to enum_values."""
def __init__(
self,
default: Union[None, _T, Iterable[_T]],
enum_values: Iterable[_T],
help_string: Optional[str] = None,
):
parser = _argument_parsers.MultiEnumParser(enum_values)
serializer = flags.ArgumentSerializer()
_ = parser.parse(enum_values)
super().__init__(default, help_string, parser, serializer)
class MultiEnumClass(MultiItem):
"""Matches behaviour of flags.DEFINE_multi_enum_class."""
def __init__(
self,
default: Union[None, _EnumT, Iterable[_EnumT]],
enum_class: Type[_EnumT],
help_string: Optional[str] = None,
):
parser = flags.EnumClassParser(enum_class)
serializer = flags.EnumClassListSerializer(",", lowercase=False)
super().__init__(default, help_string, parser, serializer)
class MultiString(MultiItem):
"""Matches behaviour of flags.DEFINE_multi_string."""
def __init__(self, default, help_string=None):
parser = flags.ArgumentParser()
serializer = flags.ArgumentSerializer()
super().__init__(default, help_string, parser, serializer)
# Misc DEFINE_*s.
def DEFINE_multi_enum( # pylint: disable=invalid-name,redefined-builtin
name: str,
default: Optional[Iterable[_T]],
enum_values: Iterable[_T],
help: str,
flag_values=flags.FLAGS,
**args,
) -> flags.FlagHolder[_T]:
"""Defines flag for MultiEnum."""
parser = _argument_parsers.MultiEnumParser(enum_values)
serializer = flags.ArgumentSerializer()
return flags.DEFINE(
parser,
name,
default,
help,
flag_values,
serializer,
**args,
)
def DEFINE_sequence( # pylint: disable=invalid-name,redefined-builtin
name: str,
default: Optional[Iterable[_T]],
help: str,
flag_values=flags.FLAGS,
**args,
) -> flags.FlagHolder[Iterable[_T]]:
"""Defines a flag for a list or tuple of simple types. See `Sequence` docs."""
parser = _argument_parsers.SequenceParser()
serializer = flags.ArgumentSerializer()
return flags.DEFINE(
parser,
name,
default,
help,
flag_values,
serializer,
**args,
)
| fancyflags-master | fancyflags/_definitions.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for fancyflags._flags."""
from absl import flags
from absl.testing import absltest
from fancyflags import _flags
class FlagsTest(absltest.TestCase):
def test_update_shared_dict(self):
# Tests that the shared dict is updated when the flag value is updated.
shared_dict = {'a': {'b': 'value'}}
namespace = ('a', 'b')
flag_values = flags.FlagValues()
flags.DEFINE_flag(
_flags.ItemFlag(
shared_dict,
namespace,
parser=flags.ArgumentParser(),
serializer=flags.ArgumentSerializer(),
name='a.b',
default='bar',
help_string='help string',
),
flag_values=flag_values,
)
flag_values['a.b'].value = 'new_value'
with self.subTest(name='setter'):
self.assertEqual(shared_dict, {'a': {'b': 'new_value'}})
flag_values(('./program', '--a.b=override'))
with self.subTest(name='override_parse'):
self.assertEqual(shared_dict, {'a': {'b': 'override'}})
def test_update_shared_dict_multi(self):
# Tests that the shared dict is updated when the flag value is updated.
shared_dict = {'a': {'b': ['value']}}
namespace = ('a', 'b')
flag_values = flags.FlagValues()
flags.DEFINE_flag(
_flags.MultiItemFlag(
shared_dict,
namespace,
parser=flags.ArgumentParser(),
serializer=flags.ArgumentSerializer(),
name='a.b',
default=['foo', 'bar'],
help_string='help string',
),
flag_values=flag_values,
)
flag_values['a.b'].value = ['new', 'value']
with self.subTest(name='setter'):
self.assertEqual(shared_dict, {'a': {'b': ['new', 'value']}})
flag_values(('./program', '--a.b=override1', '--a.b=override2'))
with self.subTest(name='override_parse'):
self.assertEqual(shared_dict, {'a': {'b': ['override1', 'override2']}})
if __name__ == '__main__':
absltest.main()
| fancyflags-master | fancyflags/_flags_test.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for fancyflags._define_auto."""
import copy
import dataclasses
from typing import Sequence
from absl import flags
from absl.testing import absltest
from fancyflags import _define_auto
from fancyflags import _flags
@dataclasses.dataclass
class Point:
x: float = 0.0
y: float = 0.0
label: str = ''
enable: bool = False
def greet(greeting: str = 'Hello', targets: Sequence[str] = ('world',)) -> str:
return greeting + ' ' + ', '.join(targets) # pytype: disable=unsupported-operands
class DefineAutoTest(absltest.TestCase):
def test_dataclass(self):
flag_values = flags.FlagValues()
flag_holder = _define_auto.DEFINE_auto(
'point', Point, flag_values=flag_values
)
flag_values((
'./program',
'--point.x=2.0',
'--point.y=-1.5',
'--point.label=p',
'--nopoint.enable',
))
expected = Point(2.0, -1.5, 'p', False)
self.assertEqual(expected, flag_holder.value())
def test_dataclass_nodefaults(self):
# Given a class constructor with non-default (required) argument(s)...
@dataclasses.dataclass
class MySettings:
foo: str
bar: int = 3
# If we define auto flags for it...
flag_values = flags.FlagValues()
flag_holder = _define_auto.DEFINE_auto(
'thing', MySettings, flag_values=flag_values
)
# Then the corresponding flag is required: not passing it should error.
with self.assertRaisesRegex(flags.IllegalFlagValueError, 'thing.foo'):
flag_values(('./program', ''))
# Passing the required flag should work as normal.
flag_values(('./program', '--thing.foo=hello'))
expected = MySettings('hello', 3)
self.assertEqual(expected, flag_holder.value())
def test_function(self):
flag_values = flags.FlagValues()
flag_holder = _define_auto.DEFINE_auto(
'greet', greet, flag_values=flag_values
)
flag_values((
'./program',
'--greet.greeting=Hi there',
"--greet.targets=('Alice', 'Bob')",
))
expected = 'Hi there Alice, Bob'
self.assertEqual(expected, flag_holder.value())
def test_override_kwargs(self):
flag_values = flags.FlagValues()
flag_holder = _define_auto.DEFINE_auto(
'point', Point, flag_values=flag_values
)
flag_values((
'./program',
'--point.x=2.0',
'--point.y=-1.5',
'--point.label=p',
'--point.enable',
))
expected = Point(3.0, -1.5, 'p', True)
# Here we override one of the arguments.
self.assertEqual(expected, flag_holder.value(x=3.0))
def test_overriding_top_level_auto_flag_fails(self):
flag_values = flags.FlagValues()
_define_auto.DEFINE_auto('point', Point, flag_values=flag_values)
with self.assertRaisesRegex(
flags.IllegalFlagValueError, "Can't override an auto flag directly"
):
flag_values(('./program', '--point=2.0'))
def test_basic_serialization(self):
flag_values = flags.FlagValues()
_define_auto.DEFINE_auto('point', Point, flag_values=flag_values)
# Accessing flag_holder.value would raise an error here, since flags haven't
# been parsed yet. For consistency we access the value via flag_values
# throughout the test, rather than through a returned `FlagHolder`.
initial_point_value = copy.deepcopy(flag_values['point'].value())
# Parse flags, then serialize.
flag_values((
'./program',
'--point.x=1.2',
'--point.y=3.5',
'--point.label=p',
'--point.enable=True',
))
self.assertEqual(flag_values['point'].serialize(), _flags._EMPTY)
self.assertEqual(flag_values['point.x'].serialize(), '--point.x=1.2')
self.assertEqual(flag_values['point.label'].serialize(), '--point.label=p')
self.assertEqual(flag_values['point.enable'].serialize(), '--point.enable')
parsed_point_value = copy.deepcopy(flag_values['point'].value())
self.assertEqual(
parsed_point_value, Point(x=1.2, y=3.5, label='p', enable=True)
)
self.assertNotEqual(parsed_point_value, initial_point_value)
# Test a round trip.
serialized_args = [
flag_values[name].serialize()
for name in flag_values
if name.startswith('point.')
]
flag_values.unparse_flags() # Reset to defaults
self.assertEqual(flag_values['point'].value(), initial_point_value)
flag_values(['./program'] + serialized_args)
self.assertEqual(flag_values['point'].value(), parsed_point_value)
def test_disclaimed_module(self):
flag_values = flags.FlagValues()
_ = _define_auto.DEFINE_auto(
'greet', greet, 'help string', flag_values=flag_values
)
defining_module = flag_values.find_module_defining_flag('greet')
# The defining module should be the calling module, not the module where
# the flag is defined. Otherwise the help for a module's flags will not be
# printed unless the user uses --helpfull.
self.assertIn('_define_auto_test', defining_module)
def test_help_strings(self):
flag_values = flags.FlagValues()
# Should default to module.name, since the `greet` docstring is empty.
_define_auto.DEFINE_auto('greet', greet, flag_values=flag_values)
# Should use the custom help string.
_define_auto.DEFINE_auto(
'point', Point, help_string='custom', flag_values=flag_values
)
self.assertEqual(flag_values['greet'].help, f'{greet.__module__}.greet')
self.assertEqual(flag_values['point'].help, 'custom')
def test_manual_nostrict_overrides_no_default(self):
# Given a function without type hints...
def my_function(a):
return a + 1 # pytype: disable=unsupported-operands
# If we define an auto flag using this function in non-strict mode...
flag_values = flags.FlagValues()
flag_holder = _define_auto.DEFINE_auto(
'foo', my_function, flag_values=flag_values, strict=False
)
# Calling the function without arguments should error.
flag_values(('./program', ''))
with self.assertRaises(TypeError):
flag_holder.value() # pytype: disable=missing-parameter
# Calling with arguments should work fine.
self.assertEqual(flag_holder.value(a=2), 3) # pytype: disable=wrong-arg-types
def test_skip_params(self):
flag_values = flags.FlagValues()
_define_auto.DEFINE_auto(
'greet', greet, flag_values=flag_values, skip_params=('targets',)
)
self.assertNotIn('greet.targets', flag_values)
if __name__ == '__main__':
absltest.main()
| fancyflags-master | fancyflags/_define_auto_test.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""An extended flags library. The main component is a nested dict flag."""
# pylint: disable=g-bad-import-order,g-import-not-at-top
# Add current module to disclaimed module ids.
from absl import flags
flags.disclaim_key_flags()
from fancyflags._metadata import __version__
# Define flags based on a dictionary or sequence.
from fancyflags._definitions import DEFINE_dict
from fancyflags._definitions import DEFINE_sequence
from fancyflags._definitions import define_flags
# Automatically build fancyflags defs from a callable signature.
from fancyflags._auto import auto
from fancyflags._define_auto import DEFINE_auto
# `Item` definitions for supported types.
from fancyflags._definitions import Boolean
from fancyflags._definitions import DateTime
from fancyflags._definitions import Enum
from fancyflags._definitions import EnumClass
from fancyflags._definitions import Float
from fancyflags._definitions import Integer
from fancyflags._definitions import MultiEnum
from fancyflags._definitions import MultiEnumClass
from fancyflags._definitions import MultiString
from fancyflags._definitions import Sequence
from fancyflags._definitions import String
from fancyflags._definitions import StringList
# Class for adding new flag types.
from fancyflags._definitions import Item
# usage_logging: import
# experimental: import
| fancyflags-master | fancyflags/__init__.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Automatic flags via ff.auto-compatible callables."""
from typing import Callable, Collection, Optional, TypeVar
from absl import flags
from fancyflags import _auto
from fancyflags import _definitions
from fancyflags import _flags
_F = TypeVar('_F', bound=Callable)
# Add current module to disclaimed module ids.
flags.disclaim_key_flags()
def DEFINE_auto( # pylint: disable=invalid-name
name: str,
fn: _F,
help_string: Optional[str] = None,
flag_values: flags.FlagValues = flags.FLAGS,
*,
strict: bool = True,
skip_params: Collection[str] = (),
) -> flags.FlagHolder[_F]:
"""Defines a flag for an `ff.auto`-compatible constructor or callable.
Automatically defines a set of dotted `ff.Item` flags corresponding to the
constructor arguments and their default values.
Overriding the value of a dotted flag will update the arguments used to invoke
`fn`. This flag's value returns a callable `fn` with these values as bound
arguments,
Example usage:
```python
# Defined in, e.g., datasets library.
@dataclasses.dataclass
class DataSettings:
dataset_name: str = 'mnist'
split: str = 'train'
batch_size: int = 128
# In main script.
# Exposes flags: --data.dataset_name --data.split and --data.batch_size.
DATA_SETTINGS = ff.DEFINE_auto('data', datasets.DataSettings, 'Data config')
def main(argv):
# del argv # Unused.
dataset = datasets.load(DATA_SETTINGS.value())
# ...
```
Args:
name: The name for the top-level flag.
fn: An `ff.auto`-compatible `Callable`.
help_string: Optional help string for this flag. If not provided, this will
default to '{fn's module}.{fn's name}'.
flag_values: An optional `flags.FlagValues` instance.
strict: Whether to skip flag definitions for arguments without type hints,
or for arguments with unknown types.
skip_params: Optional parameter names to skip defining flags for.
Returns:
A `flags.FlagHolder`.
"""
arguments = _auto.auto(fn, strict=strict, skip_params=skip_params)
# Define the individual flags.
defaults = _definitions.define_flags(name, arguments, flag_values=flag_values)
help_string = help_string or f'{fn.__module__}.{fn.__name__}'
# Define a holder flag.
return flags.DEFINE_flag(
flag=_flags.AutoFlag(
fn,
defaults,
name=name,
default=None,
parser=flags.ArgumentParser(),
serializer=None,
help_string=help_string,
),
flag_values=flag_values,
)
| fancyflags-master | fancyflags/_define_auto.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for argument_parsers."""
import datetime
from absl.testing import absltest
from absl.testing import parameterized
from fancyflags import _argument_parsers
UTC = datetime.timezone.utc
TZINFO_4HRS = datetime.timezone(datetime.timedelta(hours=4))
class SequenceParserTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.parser = _argument_parsers.SequenceParser()
@parameterized.parameters(
([1, 2, 3],),
([],),
((),),
(["hello", "world"],),
((3.14, 2.718),),
((1, -1.0),),
)
def test_parse_input_sequence(self, input_sequence):
result = self.parser.parse(input_sequence)
self.assertEqual(result, input_sequence)
@parameterized.parameters(
("[1, 2, 3]", [1, 2, 3]),
("[]", []),
("()", ()),
("['hello', 'world']", ["hello", "world"]),
("(3.14, 2.718)", (3.14, 2.718)),
(
"(1, -1.0)",
(1, -1.0),
),
)
def test_parse_input_string(self, input_string, expected):
result = self.parser.parse(input_string)
self.assertEqual(result, expected)
# Check that the string-formatted expected result also matches the input
self.assertEqual("{}".format(expected), input_string)
@parameterized.parameters(
('["hello", u"world"]', ["hello", "world"]),
("(1,2,3)", (1, 2, 3)),
)
def test_parse_input_string_different_format(self, input_string, expected):
# The parser/ast result should also work for slightly different formatting.
result = self.parser.parse(input_string)
self.assertEqual(result, expected)
def test_parse_none(self):
result = self.parser.parse(None)
self.assertEqual(result, [])
@parameterized.parameters(
({1, 2, 3},),
(100,),
)
def test_parse_invalid_input_type(self, input_item):
with self.assertRaisesRegex(TypeError, "Unsupported type"):
self.parser.parse(input_item)
@parameterized.parameters(
("'hello world'",),
("{1: 3}",),
)
def test_parse_invalid_evaluated_type(self, input_string):
with self.assertRaisesRegex(TypeError, "evaluated as"):
self.parser.parse(input_string)
@parameterized.parameters(
# No nested anything.
([1, [2, 3]],),
([1, (2, 3)],),
((1, [2, 3]),),
((1, (2, 3)),),
# Nothing outside the listed primitive types.
([1, set()],),
)
def test_parse_invalid_entries(self, input_item):
with self.assertRaisesRegex(TypeError, "contains unsupported"):
self.parser.parse(input_item)
def test_empty_string(self):
with self.assertRaisesWithLiteralMatch(
ValueError, _argument_parsers._EMPTY_STRING_ERROR_MESSAGE
):
self.parser.parse("")
@parameterized.parameters(
# ValueError from ast.literal_eval
"[foo, bar]",
# SyntaxError from ast.literal_eval
"['foo', 'bar'",
"[1 2]",
)
def test_parse_string_literal_error(self, input_string):
with self.assertRaisesRegex(ValueError, ".*as a python literal.*"):
self.parser.parse(input_string)
class MultiEnumParserTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.parser = _argument_parsers.MultiEnumParser(
["a", "a", ["a"], "b", "c", 1, [2], {"a": "d"}]
)
@parameterized.parameters(
('["a"]', ["a"]),
('[["a"], "a"]', [["a"], "a"]),
('[1, "a", {"a": "d"}]', [1, "a", {"a": "d"}]),
)
def test_parse_input(self, inputs, target):
self.assertEqual(self.parser.parse(inputs), target)
@parameterized.parameters(
("'a'", "evaluated as a"),
(1, "Unsupported type"),
({"a"}, "Unsupported type"),
("''", "evaluated as a"),
)
def test_invalid_input_type(self, input_item, regex):
with self.assertRaisesRegex(TypeError, regex):
self.parser.parse(input_item)
@parameterized.parameters("[1, 2]", '["a", ["b"]]')
def test_out_of_enum_values(self, inputs):
with self.assertRaisesRegex(ValueError, "Argument values should be one of"):
self.parser.parse(inputs)
with self.assertRaisesRegex(ValueError, "Argument values should be one of"):
self.parser.parse(inputs)
class PossiblyNaiveDatetimeFlagTest(parameterized.TestCase):
def test_parser_flag_type(self):
parser = _argument_parsers.PossiblyNaiveDatetimeParser()
self.assertEqual("datetime.datetime", parser.flag_type())
@parameterized.named_parameters(
dict(
testcase_name="date_string",
value="2011-11-04",
expected=datetime.datetime(2011, 11, 4, 0, 0),
),
dict(
testcase_name="second_string",
value="2011-11-04T00:05:23",
expected=datetime.datetime(2011, 11, 4, 0, 5, 23),
),
dict(
testcase_name="fractions_string",
value="2011-11-04 00:05:23.283",
expected=datetime.datetime(2011, 11, 4, 0, 5, 23, 283000),
),
dict(
testcase_name="utc_string",
value="2011-11-04 00:05:23.283+00:00",
expected=datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=UTC),
),
dict(
testcase_name="offset_string",
value="2011-11-04T00:05:23+04:00",
expected=datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=TZINFO_4HRS),
),
dict(
testcase_name="datetime",
value=datetime.datetime(2011, 11, 4, 0, 0),
expected=datetime.datetime(2011, 11, 4, 0, 0),
),
)
def test_parse(self, value, expected):
parser = _argument_parsers.PossiblyNaiveDatetimeParser()
result = parser.parse(value)
self.assertIsInstance(result, datetime.datetime)
self.assertEqual(expected, result)
def test_parse_separator_plus_or_minus_raises(self):
parser = _argument_parsers.PossiblyNaiveDatetimeParser()
with self.assertRaisesRegex(ValueError, r"separator between date and time"):
# Avoid confusion of 1970-01-01T08:00:00 vs. 1970-01-01T00:00:00-08:00
parser.parse("1970-01-01-08:00")
if __name__ == "__main__":
absltest.main()
| fancyflags-master | fancyflags/_argument_parsers_test.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for fancyflags.auto."""
# Test that `auto` can still correctly infer parameter types when postponed
# evaluation of type annotations (PEP 563) is enabled.
from __future__ import annotations
import abc
import enum
import sys
from typing import List, Optional, Sequence, Tuple
from absl import flags
from absl.testing import absltest
import fancyflags as ff
from fancyflags import _auto
FLAGS = flags.FLAGS
class MyEnum(enum.Enum):
ZERO = 0
ONE = 1
class AutoTest(absltest.TestCase):
def test_works_fn(self):
# pylint: disable=unused-argument
def my_function(
str_: str = 'foo',
int_: int = 10,
float_: float = 1.0,
bool_: bool = False,
list_int: List[int] = [1, 2, 3],
tuple_str: Tuple[str] = ('foo',),
variadic_tuple_str: Tuple[str, ...] = ('foo', 'bar'),
sequence_bool: Sequence[bool] = [True, False],
optional_int: Optional[int] = None,
optional_float: Optional[float] = None,
optional_list_int: Optional[List[int]] = None,
): # pylint: disable=dangerous-default-value
pass
# pylint: enable=unused-argument
expected_settings = {
'str_': 'foo',
'int_': 10,
'float_': 1.0,
'bool_': False,
'list_int': [1, 2, 3],
'tuple_str': ('foo',),
'variadic_tuple_str': ('foo', 'bar'),
'sequence_bool': [True, False],
'optional_int': None,
'optional_float': None,
'optional_list_int': None,
}
ff_dict = ff.auto(my_function)
self.assertEqual(expected_settings.keys(), ff_dict.keys())
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
'my_function_settings',
flag_values,
**ff_dict,
)
flag_values(('./program', ''))
self.assertEqual(flag_holder.value, expected_settings)
@absltest.skipIf(
condition=sys.version_info < (3, 9),
reason='Generics syntax for standard collections requires Python >= 3.9',
)
def test_works_fn_pep585(self):
def my_function(
list_int: list[int] = [1, 2, 3],
tuple_str: tuple[str] = ('foo',),
variadic_tuple_str: tuple[str, ...] = ('foo', 'bar'),
optional_list_int: Optional[list[int]] = None,
): # pylint: disable=dangerous-default-value
del list_int, tuple_str, variadic_tuple_str, optional_list_int # Unused.
expected_settings = {
'list_int': [1, 2, 3],
'tuple_str': ('foo',),
'variadic_tuple_str': ('foo', 'bar'),
'optional_list_int': None,
}
ff_dict = ff.auto(my_function)
self.assertEqual(expected_settings.keys(), ff_dict.keys())
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
'my_function_settings',
flag_values,
**ff_dict,
)
flag_values(('./program', ''))
self.assertEqual(flag_holder.value, expected_settings)
def test_works_enum_fn(self):
# pylint: disable=unused-argument
def my_function(
str_: str = 'foo', int_: int = 10, enum_: MyEnum = MyEnum.ZERO
):
pass
# pylint: enable=unused-argument
expected_settings = {
'str_': 'foo',
'int_': 10,
'enum_': MyEnum.ZERO,
}
ff_dict = ff.auto(my_function)
self.assertCountEqual(expected_settings, ff_dict)
def test_works_class(self):
class MyClass:
# pylint: disable=unused-argument
def __init__(
self,
str_: str = 'foo',
int_: int = 10,
float_: float = 1.0,
bool_: bool = False,
list_int: List[int] = [1, 2, 3],
tuple_str: Tuple[str] = ('foo',),
variadic_tuple_str: Tuple[str, ...] = ('foo', 'bar'),
sequence_bool: Sequence[bool] = [True, False],
optional_int: Optional[int] = None,
optional_float: Optional[float] = None,
optional_list_int: Optional[List[int]] = None,
): # pylint: disable=dangerous-default-value
pass
# pylint: enable=unused-argument
expected_settings = {
'str_': 'foo',
'int_': 10,
'float_': 1.0,
'bool_': False,
'list_int': [1, 2, 3],
'tuple_str': ('foo',),
'variadic_tuple_str': ('foo', 'bar'),
'sequence_bool': [True, False],
'optional_int': None,
'optional_float': None,
'optional_list_int': None,
}
ff_dict = ff.auto(MyClass)
self.assertEqual(expected_settings.keys(), ff_dict.keys())
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
'my_class_settings',
flag_values,
**ff_dict,
)
flag_values(('./program', ''))
self.assertEqual(flag_holder.value, expected_settings)
@absltest.skipIf(
condition=sys.version_info < (3, 9),
reason='Generics syntax for standard collections requires Python >= 3.9',
)
def test_works_class_pep585(self):
class MyClass:
def __init__(
self,
list_int: list[int] = [1, 2, 3],
tuple_str: tuple[str] = ('foo',),
variadic_tuple_str: tuple[str, ...] = ('foo', 'bar'),
optional_list_int: Optional[list[int]] = None,
): # pylint: disable=dangerous-default-value
# Unused.
del list_int, tuple_str, variadic_tuple_str, optional_list_int
expected_settings = {
'list_int': [1, 2, 3],
'tuple_str': ('foo',),
'variadic_tuple_str': ('foo', 'bar'),
'optional_list_int': None,
}
ff_dict = ff.auto(MyClass)
self.assertEqual(expected_settings.keys(), ff_dict.keys())
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
'my_class_settings',
flag_values,
**ff_dict,
)
flag_values(('./program', ''))
self.assertEqual(flag_holder.value, expected_settings)
def test_works_metaclass(self):
# This replicates an issue with Sonnet v2 modules, where the constructor
# arguments are hidden by the metaclass.
class MyMetaclass(abc.ABCMeta):
def __call__(cls, *args, **kwargs):
del args, kwargs
class MyClass(metaclass=MyMetaclass):
def __init__(
self, a: int = 10, b: float = 1.0, c: Sequence[int] = (1, 2, 3)
):
del a, b, c
expected = {'a': 10, 'b': 1.0, 'c': (1, 2, 3)}
ff_dict = ff.auto(MyClass)
self.assertEqual(ff_dict.keys(), expected.keys())
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
'my_meta_class_settings',
flag_values,
**ff_dict,
)
flag_values(('./program', ''))
self.assertEqual(flag_holder.value, expected)
def test_required_item_with_no_default(self):
def my_function(a: int, b: float = 1.0, c: Sequence[int] = (1, 2, 3)):
del a, b, c
items = ff.auto(my_function)
self.assertTrue(items['a'].required)
self.assertFalse(items['b'].required)
self.assertFalse(items['c'].required)
def test_error_if_missing_type_annotation(self):
def my_function(a: int = 10, b=1.0, c: Sequence[int] = (1, 2, 3)):
del a, b, c
with self.assertRaisesWithLiteralMatch(
TypeError, _auto._MISSING_TYPE_ANNOTATION.format(name='b')
):
ff.auto(my_function)
def test_error_if_unsupported_type(self):
def my_function(
a: int = 10, b: float = 1.0, c: Sequence[object] = (1, 2, 3)
):
del a, b, c
with self.assertRaisesWithLiteralMatch(
TypeError,
_auto._UNSUPPORTED_ARGUMENT_TYPE.format(
name='c', annotation=Sequence[object]
),
):
ff.auto(my_function)
def test_no_error_if_nonstrict_unsupported_type(self):
def my_function(
a: int = 10, b: float = 1.0, c: Sequence[object] = (1, 2, 3)
):
del a, b, c
items = ff.auto(my_function, strict=False)
self.assertSetEqual(set(items.keys()), {'a', 'b'})
def test_no_error_if_nonstrict_no_type_annotation(self):
def my_function(a, b: int = 3):
del a, b
items = ff.auto(my_function, strict=False)
self.assertSetEqual(set(items.keys()), {'b'})
def test_error_if_not_callable(self):
with self.assertRaises(TypeError):
ff.auto(3) # pytype: disable=wrong-arg-types
# TODO(b/178129474): Improve support for typing.Sequence subtypes.
@absltest.expectedFailure
def test_supports_tuples_with_more_than_one_element(self):
def my_function(
three_ints: Tuple[int, int, int] = (1, 2, 3),
zero_or_more_strings: Tuple[str, ...] = ('foo', 'bar'),
):
del three_ints, zero_or_more_strings
expected = {
'three_ints': (1, 2, 3),
'zero_or_more_strings': ('foo', 'bar'),
}
ff_dict = ff.auto(my_function)
self.assertEqual(expected.keys(), ff_dict.keys())
flag_values = flags.FlagValues()
flag_holder = ff.DEFINE_dict(
'my_function_settings',
flag_values,
**ff_dict,
)
flag_values(('./program', ''))
self.assertEqual(flag_holder.value, expected)
def test_skip_params(self):
def my_function(a: int, b: str = 'hi'):
del a, b
items = ff.auto(my_function, skip_params={'b'})
self.assertSetEqual(set(items.keys()), {'a'})
if __name__ == '__main__':
absltest.main()
| fancyflags-master | fancyflags/_auto_test.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for compatibility with absl.testing.flagsaver."""
from absl import flags
from absl.testing import absltest
from absl.testing import flagsaver
import fancyflags as ff
flags.DEFINE_string("string_flag", "unchanged", "flag to test with")
ff.DEFINE_dict(
"test_dict_flag",
dict=dict(
nested=ff.Float(1.0, "nested flag"),
),
unnested=ff.Integer(4, "unnested flag"),
)
FLAGS = flags.FLAGS
class FlagSaverTest(absltest.TestCase):
def test_flagsaver_with_context_overrides(self):
with flagsaver.flagsaver(
**{
"string_flag": "new value",
"test_dict_flag.dict.nested": -1.0,
}
):
self.assertEqual("new value", FLAGS.string_flag)
self.assertEqual(-1.0, FLAGS.test_dict_flag["dict"]["nested"])
self.assertEqual(4, FLAGS.test_dict_flag["unnested"])
FLAGS.string_flag = "another value"
self.assertEqual("unchanged", FLAGS.string_flag)
self.assertEqual(1.0, FLAGS.test_dict_flag["dict"]["nested"])
def test_flagsaver_with_decorator_overrides(self):
# Modeled after test_decorator_with_overrides in
# https://github.com/abseil/abseil-py/blob/master/absl/testing/tests/flagsaver_test.py # pylint: disable=line-too-long
@flagsaver.flagsaver(
**{
"string_flag": "new value",
"test_dict_flag.dict.nested": -1.0,
}
)
def mutate_flags():
return FLAGS.string_flag, FLAGS.test_dict_flag["dict"]["nested"]
# Values should be overridden in the function.
self.assertEqual(("new value", -1.0), mutate_flags())
# But unchanged here.
self.assertEqual("unchanged", FLAGS.string_flag)
self.assertEqual(1.0, FLAGS.test_dict_flag["dict"]["nested"])
def test_flagsaver_with_context_overrides_twice(self):
# Checking that the flat -> dict flag sync works again after restoration.
# This might fail if the underlying absl functions copied the dict as part
# of restoration.
with flagsaver.flagsaver(
**{
"string_flag": "new value",
"test_dict_flag.dict.nested": -1.0,
}
):
self.assertEqual("new value", FLAGS.string_flag)
self.assertEqual(-1.0, FLAGS.test_dict_flag["dict"]["nested"])
self.assertEqual(4, FLAGS.test_dict_flag["unnested"])
FLAGS.string_flag = "another value"
self.assertEqual("unchanged", FLAGS.string_flag)
self.assertEqual(1.0, FLAGS.test_dict_flag["dict"]["nested"])
# Same again!
with flagsaver.flagsaver(
**{
"string_flag": "new value",
"test_dict_flag.dict.nested": -1.0,
}
):
self.assertEqual("new value", FLAGS.string_flag)
self.assertEqual(-1.0, FLAGS.test_dict_flag["dict"]["nested"])
self.assertEqual(4, FLAGS.test_dict_flag["unnested"])
FLAGS.string_flag = "another value"
self.assertEqual("unchanged", FLAGS.string_flag)
self.assertEqual(1.0, FLAGS.test_dict_flag["dict"]["nested"])
@absltest.skip("This fails because flagsaver does not do deep copies")
def test_flagsaver_with_changes_within_context(self):
"""Overrides within a flagsaver context should be correctly restored."""
with flagsaver.flagsaver():
FLAGS.string_flag = "new_value"
FLAGS["test_dict_flag.dict.nested"].value = -1.0
FLAGS.test_dict_flag["unnested"] = -1.0
self.assertEqual("unchanged", FLAGS.string_flag) # Works.
self.assertEqual(1.0, FLAGS.test_dict_flag["dict"]["nested"]) # Works.
# TODO(b/177927157) Fix this behaviour.
self.assertEqual(4, FLAGS.test_dict_flag["unnested"]) # Broken.
if __name__ == "__main__":
absltest.main()
| fancyflags-master | fancyflags/_flagsaver_test.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A module that defines a dict flag, for testing purposes."""
import fancyflags as ff
ff.DEFINE_dict(
"settings",
integer_field=ff.Integer(1, "integer field"),
string_field=ff.String(None, "string field"),
)
| fancyflags-master | fancyflags/examples/example_module.py |
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Test for flag overrides in fancyflags.."""
from absl import flags
from absl.testing import absltest
import fancyflags as ff
SETTINGS = ff.DEFINE_dict(
"settings",
integer_field=ff.Integer(1, "integer field"),
string_field=ff.String(None, "string field"),
nested=dict(float_field=ff.Float(0.0, "float field")),
sequence_field=ff.Sequence([1, 2, 3], "sequence field"),
another_sequence_field=ff.Sequence((3.14, 2.718), "another sequence field"),
string_list_field=ff.StringList(["a"], "string list flag."),
)
class OverrideTest(absltest.TestCase):
def test_give_me_a_name(self):
expected = dict(
integer_field=5,
string_field=None, # Not overridden in BUILD args.
nested=dict(
float_field=3.2,
),
sequence_field=[4, 5, 6],
another_sequence_field=[3.0, 2.0],
string_list_field=["a", "bunch", "of", "overrides"],
)
self.assertEqual(flags.FLAGS.settings, expected)
self.assertEqual(SETTINGS.value, expected)
if __name__ == "__main__":
absltest.main()
| fancyflags-master | fancyflags/examples/override_test.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Install script for setuptools."""
from setuptools import find_packages
from setuptools import setup
setup(
name='additive_cbug',
version='1.0',
description='Code reproducing the experiments of the paper'
'Malek, Aglietti, Chiappa. "Additive Causal Bandits with Unknown Graph". '
'ICML 2023.',
author='DeepMind',
author_email='[email protected]',
license='Apache License, Version 2.0',
url='https://github.com/deepmind/additive_cbug',
packages=find_packages(),
install_requires=[
'absl-py',
'numpy',
'networkx',
'matplotlib',
],
tests_require=['mock'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
| additive_cbug-main | setup.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for the algorithms."""
from absl.testing import absltest
from cbug import base
from cbug import scm
from cbug import utils
import numpy as np
class CBUGTest(absltest.TestCase):
"""Unit test for the CBUG algorithm."""
def test_reduce_actions(self):
s_marginal = {'X': np.array([0, 1, 2]), 'Z': np.array([1, 2, 3])}
support_sizes = {'X': 3, 'Z': 4}
name_to_idx = utils.get_name_to_idx(support_sizes)
mean_est = np.array([1.9, 2.7, 3, 2, 1.2, 1, 1.8])
# The gaps are: 1.1, .3, 0, 0, .8, 1, .2.
gamma = .1
returned = base.reduce_actions(s_marginal, name_to_idx, mean_est, gamma)
ans = {
'X': np.array([2]),
'Z': np.array([0]),
}
self.assertDictEqual(returned, ans)
gamma = .4
returned = base.reduce_actions(s_marginal, name_to_idx, mean_est, gamma)
ans = {
'X': np.array([1, 2]),
'Z': np.array([0, 3]),
}
self.assertDictEqual(returned, ans)
gamma = 1
returned = base.reduce_actions(s_marginal, name_to_idx, mean_est, gamma)
ans = {
'X': np.array([1, 2]),
'Z': np.array([0, 1, 3]),
}
self.assertDictEqual(returned, ans)
def test_xy_optimal_design(self):
s_marginal = {'X': np.array([0, 1, 2]), 'Z': np.array([0, 1, 2, 3])}
support_sizes = {'X': 3, 'Z': 4}
gamma = 1
delta = .5
sigma2 = 1.2
covariates = base.xy_optimal_design(
s_marginal,
support_sizes,
gamma,
delta,
sigma2,
)
np.testing.assert_allclose(len(covariates['X']), 24)
_, counts = np.unique(covariates['X'], return_counts=True)
np.testing.assert_allclose(counts, 8)
_, counts = np.unique(covariates['Z'], return_counts=True)
np.testing.assert_allclose(counts, 6)
s_marginal = {'X': np.array([0, 1]), 'Z': np.array([0, 1, 2])}
covariates = base.xy_optimal_design(
s_marginal,
support_sizes,
gamma,
delta,
sigma2,
)
np.testing.assert_allclose(len(covariates['X']), 17)
_, counts = np.unique(covariates['X'], return_counts=True)
np.testing.assert_allclose(counts, 8, atol=1)
_, counts = np.unique(covariates['Z'], return_counts=True)
np.testing.assert_allclose(counts, 6, atol=1)
def test_run_modl(self):
support_sizes = {'X1': 3, 'X2': 4}
cov_variables = ['X1', 'X2']
var_names = ['X1', 'X2', 'Y']
parents = {'X1': [],
'X2': ['X1'],
'Y': ['X1', 'X2'],
}
strc_fn_probs = {}
strc_fn_probs['X1'] = np.array([0, 1, 0])
strc_fn_probs['X2'] = np.array([[0, 1, 0], [1, 0, 0]])
additive_means = {'X1': np.array([0, 1, 0]),
'X2': np.array([0, .2, .4]),
}
support_sizes = {'X1': 3, 'X2': 3}
model = scm.DiscreteAdditiveSCM(
'test',
var_names,
parents,
strc_fn_probs,
additive_means,
cov_variables,
'Y',
support_sizes,
cov=0,
)
results = base.run_modl(delta=.5,
epsilon=.1,
model=model,
sigma2=1,
outcome_bound=2,
num_parents_bound=None,
)
np.testing.assert_equal(results.n_samples_t, [72, 288, 767])
np.testing.assert_equal(results.gamma_t, [1, .5, .25])
np.testing.assert_equal(results.best_action_t[-1], {'X1': [1], 'X2': [2]})
np.testing.assert_equal(results.s_t[0], {'X1': [0, 1, 2], 'X2': [0, 1, 2]})
np.testing.assert_equal(results.s_t[-1], {'X1': [1], 'X2': [1, 2]})
| additive_cbug-main | cbug/base_test.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for building discreteSCM objects."""
import itertools
from typing import List, Mapping, Optional, Tuple
from cbug import discrete_scm
from cbug import scm
from cbug import stoc_fn_utils as sf
import numpy as np
def sample_discrete_additive_scm(
num_variables: int,
degree: float,
num_parents: int,
prob_outcome_child: float = .5,
cov: float = 1,
mean_bound: float = 1,
support_size_min: int = 3,
support_size_max: int = 6,
alpha: float = 2,
beta: float = 5,
dir_alpha: float = .5,
interactions: Optional[List[int]] = None,
interaction_magnitude: Optional[float] = None,
) -> discrete_scm.DiscreteSCM:
"""Generates a discrete additive SCM randomly.
All variables in the SCM are discrete except for the outcome variable, Y.
The stoc_fn of the outcome variable is additive with Gaussian noise of
covariance cov.
This function samples an SCM with a graph generated by the Erdos-Renyi process
with the specified degree and where all the random variables are discrete.
The number of discinct values a variable can take, known as its support_size,
is sampled i.i.d. for each variable unifomly betwen support_size_min and
support_size_max. All variables with no
parents are have a categorical distribution with a parameter vector sampled
from a Dirichlet with parameter dir_alpha, and the conditional distributions
are sampled from a normalized Beta distribution with parameters alpha, beta.
The Y variable is randomly connected to num_parents parents, and Y is equal to
a linear function of its parents, with randomly sampled parameters less than
mean_bound and added Gaussian noise of covariance cov.
All variables topoligically after Y are made children of Y with probability
prob_y_child, and have the same discrete categorical distribution with a
discretized version of Y.
If interactions and interaction_magnitude are not None, then a non-linear
component to the stoc_fn of Y is added. The interactions term is
the sum of several interaction terms, as specified by the interactions
argument. Each element in interactions will create a separate interaction term
with size equal to the element's value, e.g. an interaction term with size 3
will be x_1 * x_2 * x_3, where x_1, x_2, and x_3 are randomly chosen from
y's parents.
For example, if interactions = [2, 3], then the non-linear term could be
x_2 * x_4 + x_0 * x_1 * x_5.
Args:
num_variables: The number of variables, excluding the output variable Y.
degree: The average degree used to same on the Erdos-Renyi graph.
num_parents: The number of parents of Y.
prob_outcome_child: The probability of adding an edge from Y to any eligible
variable.
cov: covariance of Y's Gaussian noise.
mean_bound: Maximum coefficient for Y's linear term.
support_size_min: Lower bound on support size for each variable.
support_size_max: Upper bound on support size for each variable.
alpha: Y's values are sampled from a beta(alpha, beta) distribution.
beta: Y's values are sampled from a beta(alpha, beta) distribution.
dir_alpha: The dirichlet parameter used to sample the probabilities for
categorical variables with no parents.
interactions: A list of integers where each element will correspond to an
interaction term between that many parents of Y. Only used when
interaction_magnitude > 0.
interaction_magnitude: The amount of model mispecification that breaks the
additivity assumption in the outcome variable's stoc_fn.
Returns:
An SCM with a graph with the given properties.
"""
cov_variables = ['X' + str(i) for i in range(num_variables)]
outcome_variable = 'Y'
# Create an extra column for Y.
adj = np.zeros((num_variables, num_variables + 1))
adj[:, :num_variables] = sample_dag_matrix(num_variables, degree)
# The nodes are in reverse topological order; e.g. node 0 has no children,
# node num_variables-1 has no parents.
# Sample the parents of Y.
outcome_parent_idx = np.random.choice(
num_variables, size=num_parents, replace=False
)
outcome_parents = [cov_variables[i] for i in outcome_parent_idx]
# Sample the children of Y. We need to ensure we add no cycles.
max_idx = max(outcome_parent_idx)
if max_idx < num_variables:
# Randomly add Y as a parent to variables > Y, topologically.
for idx in range(max_idx + 1, num_variables):
if np.random.binomial(1, prob_outcome_child):
adj[idx, num_variables] = 1
# Sample the support sizes (the number of distinct values the variable can
# take) for all variables.
support_sizes = {
var: np.random.randint(support_size_min, support_size_max + 1)
for var in cov_variables
}
support_sizes['Y'] = int(np.ceil(mean_bound * len(outcome_parent_idx))) + 1
# For each variable, randomly construct its stochastic function.
stoc_fns = {}
for i, var in enumerate(cov_variables):
# Enumerate the parents.
parents = []
for j in range(num_variables):
if adj[i, j]:
parents.append(cov_variables[j])
if adj[i, num_variables]:
parents.append('Y')
if not parents:
probs = np.random.dirichlet([dir_alpha] * support_sizes[var])
stoc_fns[var] = sf.create_categorical_stoc_fn(probs=probs)
# stoc_fn has one input, n_samples, since it has no parents.
else:
# Sample probs.
if len(parents) == 1:
probs = np.ones(support_sizes[var]) / support_sizes[var]
else:
probs = generate_beta_cpd(support_sizes, parents, var)
# Create the stoc_fn.
stoc_fn = sf.create_categorical_conditional_stoc_fn(probs, parents)
stoc_fns[var] = scm.StocFnRecipe(stoc_fn, parents)
# Sample the linear part of the outcome stoc_fn.
means = {}
for var in outcome_parents:
means[var] = mean_bound * np.random.beta(
alpha, beta, size=support_sizes[var]
)
# If interaction is not present, we generate a linear function.
if interaction_magnitude is None or interaction_magnitude == 0:
# Find the best action and best value.
outcome_expected_value_fn = sf.create_discrete_to_linear_stoc_fn(means)
outcome_stoc_fn = sf.add_gaussian_noise_to_stoc_fn(
outcome_expected_value_fn, cov
)
stoc_fns[outcome_variable] = scm.StocFnRecipe(
outcome_stoc_fn, outcome_parents
)
interaction_mean_fn = None
elif interaction_magnitude is not None and interaction_magnitude != 0:
assert all(np.array(interactions) <= num_parents)
# Each non-linear interaction term will be the product of more than one
# of Y's parents. Here, we randomly choose between them.
domains = [
np.random.choice(outcome_parents, num, replace=False)
for num in interactions
]
# The stoc_fn of the outcome is formed by the sum of an interaction term,
# a linear term, and Gaussian noise.
interaction_mean_fn = sf.create_interaction_mean_stoc_fn(
interaction_magnitude,
domains,
)
linear_mean_fn = sf.create_discrete_to_linear_stoc_fn(means)
outcome_expected_value_fn = sf.add_stoc_fns(
[interaction_mean_fn, linear_mean_fn]
)
stoc_fns[outcome_variable] = scm.StocFnRecipe(
sf.add_gaussian_noise_to_stoc_fn(outcome_expected_value_fn, cov),
outcome_parents,
)
best_action, best_action_value = find_best_action_and_value(
outcome_parents,
support_sizes,
means,
interaction_mean_fn=interaction_mean_fn,
)
return discrete_scm.DiscreteSCM(
stoc_fns=stoc_fns,
support_sizes=support_sizes,
outcome_variable='Y',
best_action=best_action,
best_action_value=best_action_value,
outcome_expected_value_fn=outcome_expected_value_fn,
)
def get_expected_value_of_outcome(
model: discrete_scm.DiscreteSCM,
action: Mapping[str, int],
n: int = 1000,
) -> float:
"""Computes or estimates the value of an action.
If the action specifies all the parents of the outcome variable, then
the expected value can be read off from the model's outcome_expected_value_fn.
Otherwise, the value is approximated.
Args:
model: The DiscreteSCM that generates the value.
action: A Dictionary specifying the action for each variable in model.
n: The sample size used to estimate the value if an exact value cannot be
calculated.
Returns:
Either the exact expected value of the outcome variable or an approximation.
"""
if action.keys() >= set(model.parents[model.outcome_variable]):
return float(model.outcome_expected_value_fn(**action))
else: # We need to sample.
return np.mean(model.sample(n, action)[model.outcome_variable])
def find_best_action_and_value(
outcome_parents: List[str],
support_sizes: Mapping[str, int],
means: Mapping[str, np.ndarray],
interaction_mean_fn: Optional[scm.StocFn] = None,
) -> Tuple[Mapping[str, int], float]:
"""Finds the best mean action for a linear + optional interaction fn.
Args:
outcome_parents: A list of the parents of the outcome variable
support_sizes: A mapping from variable names to the support size.
means: Dictionary of means for the value of every parent of the
outcome_variable.
interaction_mean_fn: A callable that accepts an action dictionary and
returns a float equal to the mean of the interaction term for that action.
Returns:
The best action (as a dictionary) and its value.
"""
if interaction_mean_fn is None:
best_action = {var: np.argmax(var_mean) for var, var_mean in means.items()}
best_action_value = np.sum(
[np.max(var_mean) for var_mean in means.values()]
)
return (best_action, best_action_value)
parent_values = {
par: np.arange(support_sizes[par]) for par in outcome_parents
}
best_value = -np.inf
# Loop through all values of the parents.
for val in itertools.product(*parent_values.values()):
# Simulate average return.
action = {parent: val for parent, val in zip(outcome_parents, val)}
# Compute the value of the action.
linear_terms = [means[parent][val] for (parent, val) in action.items()]
# Compute the means from the non-linear part.
interaction = interaction_mean_fn(**action) if interaction_mean_fn else 0
value = np.sum(linear_terms) + interaction
if value > best_value:
best_value = value
best_action = action
return (best_action, best_value)
def generate_beta_cpd(
support_sizes: Mapping[str, int],
parents: List[str],
var_name: str,
alpha: float = 2,
beta: float = 5,
) -> np.ndarray:
"""Generates a random discrete probability distribution of variable name.
Uses support_sizes and parents to calculate the appropriate parameters.
Returns an np.ndarray where array[i,j,...,k,:] is the probability vector for
variable name when its parents have discrete values (i,j,...,k).
Args:
support_sizes: A dictionary of support sizes, indexed by variable name.
parents: A dict, indexed by variable name, with values of a list of the
names of the parents.
var_name: The name of the variable this cpd is for.
alpha: Parameter of the beta distribution.
beta: Parameter of the beta distribution.
Returns:
A np.ndarray describing the marginal probability of variable name
conditioned on the support value of the parents.
"""
sizes = [support_sizes[parent] for parent in parents]
sizes.append(support_sizes[var_name])
probs = np.random.beta(alpha, beta, size=sizes)
# Normalize probability.
return probs / np.repeat(
np.sum(probs, axis=-1)[..., np.newaxis],
support_sizes[var_name],
axis=-1,
)
def sample_dag_matrix(num_variabless: int, degree: float = 3.0) -> np.ndarray:
"""Produces an Erdos-Renyi graph's adjacency matrix.
Args:
num_variabless: the number of variables to include in the dag.
degree: the average degree of the graph
Returns:
An adjacency matrix.
"""
prob = float(degree) / (num_variabless - 1)
graph = np.tril(
(np.random.rand(num_variabless, num_variabless) < prob).astype(float),
k=-1,
)
return graph
| additive_cbug-main | cbug/discrete_scm_utils.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Code to run all algorithms in the paper on a SCM."""
from typing import Any, List, Mapping, Optional, Union
from cbug import base
from cbug import discrete_scm_utils as scm_utils
import numpy as np
def single_experiment(
scm_params: Mapping[str, Union[int, float, List[int]]],
scm_starting_seed: int = 0,
alg_starting_seed: int = 0,
num_scms: int = 1,
num_seeds: int = 1,
epsilon: float = .5,
delta: float = 0.1,
include_se: bool = False,
num_parents_bound: Optional[int] = None,
known_num_parents: bool = False,
) -> Mapping[str, Any]:
"""Returns the average sample complexity of several algorithms.
Algorithms included:
MODL
parents-first: learn the parents then run MODL
oracle: run MODL with the true parents given
bandit: run a bandit ignoring the causal structure.
Args:
scm_params: Dictionary of parameters to generate the scm.
scm_starting_seed: Seed to generate the scm using utils.sample_discrete_scm.
alg_starting_seed: Seed to run the algorithm.
num_scms: The number of different scms.
num_seeds: The number of different runs of the algorithm.
epsilon: Error tolerance.
delta: Error probability.
include_se: Whether to include the Successive Elimination baseline (needs
very few, <8 nodes to be able to run).
num_parents_bound: An upper bound on the number of parents. None indicates
no bound.
known_num_parents: Whether the true number of parents is given to the
algorithm.
The scm_params dictionary should include:
num_variables: Number of variables.
num_parents: Number of parents of Y.
degree: Erdos-Renyi degree.
mean_bound: Scale of linear coefficients.
cov: Covariance of noise for Y.
interaction_magnitude: float > 0 and typically < 1. The amount of model
mispecification.
interactions: A list of sizes of interaction. Each element is this list
will be turned into an interaction term that is the multiple of the
element number of parents * interaction_magnitude. Only relevant when
interaction_magnitude != 0. The stoc_fn of y is set to be this interaction
function.
alpha: Y values are sampled from a beta(alpha, beta) distribution.
beta: Y values are sampled from a beta(alpha, beta) distribution.
support_size_min: Lower bound on support size for each variable.
support_size_max: Upper bound on support size for each variable.
Returns:
Dictionary of: number of samples, final value, for each algorithm
"""
assert scm_params["num_parents"] <= scm_params["num_variables"]
results = {
"num_variables": scm_params["num_variables"],
"num_parents": scm_params["num_parents"],
"degree": scm_params["degree"],
"epsilon": epsilon,
"delta": delta,
"mean_bound": scm_params["mean_bound"],
"cov": scm_params["cov"],
}
results["oracle_samples"] = []
results["MODL_samples"] = []
results["parents_first_samples"] = []
results["se_samples"] = []
results["oracle_value"] = []
results["MODL_value"] = []
results["parents_first_value"] = []
results["se_value"] = []
results["oracle_gap"] = []
results["MODL_gap"] = []
results["parents_first_gap"] = []
results["se_gap"] = []
results["true_value"] = []
results["instance"] = []
results["seed"] = []
outcome_bound = scm_params["mean_bound"] * scm_params["num_variables"]
for instance in range(num_scms):
scm_seed = instance + scm_starting_seed
np.random.seed(scm_seed)
model = scm_utils.sample_discrete_additive_scm(**scm_params)
if known_num_parents:
modl_parents_bound = len(model.parents["Y"])
else:
modl_parents_bound = num_parents_bound
for alg_seed in range(num_seeds):
results["instance"].append(scm_seed)
results["true_value"].append(model.best_action_value)
results["seed"].append(alg_seed + alg_starting_seed)
np.random.seed(alg_seed + alg_starting_seed)
# Run the MODL algorithm.
modl_results = base.run_modl(
delta=delta,
epsilon=epsilon,
model=model,
cov=scm_params["cov"],
outcome_bound=outcome_bound,
num_parents_bound=modl_parents_bound,
)
results["MODL_samples"].append(sum(modl_results.n_samples_t))
results["MODL_value"].append(
scm_utils.get_expected_value_of_outcome(
model, modl_results.best_action_t[-1]
)
)
results["MODL_gap"].append(
model.best_action_value - results["MODL_value"][-1]
)
# Run the algorithm with knowledge of the parents.
oracle_results = base.run_modl(
delta=delta,
epsilon=epsilon,
model=model,
cov=scm_params["cov"],
outcome_bound=outcome_bound,
opt_scope=model.parents["Y"],
)
results["oracle_samples"].append(sum(oracle_results.n_samples_t))
results["oracle_value"].append(
scm_utils.get_expected_value_of_outcome(
model, oracle_results.best_action_t[-1]
)
)
results["oracle_gap"].append(
model.best_action_value - results["oracle_value"][-1]
)
# Run the parents-first algorithm.
(parents_hat, parents_first_samples) = base.find_parents(
target_var="Y",
delta=delta / 2,
epsilon=epsilon / 2,
model=model,
cov=scm_params["cov"],
num_parents_bound=num_parents_bound,
)
if not parents_hat: # Find_parents failed.
parents_hat = model.var_names.copy()
parents_hat.remove("Y")
parents_first_results = base.run_modl(
delta=delta / 2,
epsilon=epsilon,
model=model,
cov=scm_params["cov"],
outcome_bound=outcome_bound,
opt_scope=parents_hat,
num_parents_bound=num_parents_bound,
)
parents_first_samples += sum(parents_first_results.n_samples_t)
results["parents_first_samples"].append(parents_first_samples)
results["parents_first_value"].append(
scm_utils.get_expected_value_of_outcome(
model, parents_first_results.best_action_t[-1]
)
)
results["parents_first_gap"].append(
model.best_action_value - results["parents_first_value"][-1]
)
if include_se:
se_results = base.run_se(
delta=delta / 2,
epsilon=epsilon,
model=model,
cov=scm_params["cov"],
outcome_bound=outcome_bound,
)
results["se_samples"].append(se_results.n_samples_t[-1])
results["se_value"].append(
scm_utils.get_expected_value_of_outcome(
model, se_results.best_action_t[-1]
)
)
results["se_gap"].append(
model.best_action_value - results["se_value"][-1]
)
else:
results["se_samples"].append(np.nan)
results["se_value"].append(np.nan)
results["se_gap"].append(np.nan)
results["MODL_mean_samples"] = np.mean(results["MODL_samples"])
results["oracle_mean_samples"] = np.mean(results["oracle_samples"])
results["parents_first_mean_samples"] = np.mean(
results["parents_first_samples"]
)
results["se_mean_samples"] = np.mean(results["se_samples"])
results["oracle_mean_gap"] = np.mean(results["oracle_gap"])
results["MODL_mean_gap"] = np.mean(results["MODL_gap"])
results["parents_first_mean_gap"] = np.mean(results["parents_first_gap"])
results["se_mean_gap"] = np.mean(results["se_gap"])
return results
def sweep(
scm_params: Mapping[str, Union[int, float, List[int]]],
parameter_name: str,
parameter_values: np.array,
num_parents_bound: Optional[bool] = None,
known_num_parents: bool = False,
include_se: bool = False,
num_scms: int = 20,
num_seeds: int = 5,
) -> List[Mapping[str, Any]]:
"""Runs algorithms across a sweep of parameter_values.
Args:
scm_params: A dictionary of scm parameters.
parameter_name: The name of the parameter to sweep over. Must be a parameter
in scm_params.
parameter_values: The values to sweep over.
num_parents_bound: An optional upper bound on the number of parents provided
to the algorithms.
known_num_parents: Whether the algorithms are given the number of parents.
include_se: Whether to run the Successive Elimination algorithm; it becomes
intractable for more than ~7 variables.
num_scms: The number of scms to sample.
num_seeds: the number of reruns of the algorithms for each scm.
Returns:
A results dictionary for every value in parameter_values.
"""
results = []
for value in parameter_values:
scm_params[parameter_name] = value
results.append(single_experiment(
scm_params,
num_scms=num_scms,
num_seeds=num_seeds,
epsilon=.5,
delta=.1,
include_se=include_se,
num_parents_bound=num_parents_bound,
known_num_parents=known_num_parents,
))
return results
| additive_cbug-main | cbug/run.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for building stoc_fns especially for discrete SCMs."""
from typing import List, Mapping
from cbug import scm
import numpy as np
def create_interaction_mean_stoc_fn(
scale: float,
input_domains: List[List[str]],
) -> scm.StocFn:
"""Creates a deterministic stoc_fn for the interaction terms.
Args:
scale: The magnitude of the maximum function value.
input_domains: The variable names of the inputs to each interaction term.
Returns:
A stoc_fn that computes the interaction terms.
"""
def f(**kwargs):
first_parent = [val for val in kwargs.values()][0]
if isinstance(first_parent, np.ndarray):
n_samples = first_parent.shape
else:
# Not an array but a single sample.
n_samples = (1, 1)
# Compute the non-linear term.
samples = np.zeros(n_samples)
for domain in input_domains:
# For each domain, take a product.
interaction_term = scale * np.ones(n_samples)
for var in domain:
interaction_term *= kwargs[var]
samples += interaction_term
return samples
return f
def create_discrete_to_linear_stoc_fn(
means: Mapping[str, np.ndarray],
) -> scm.StocFn:
"""Returns a deterministic stoc_fn equal to a linear function of the parents.
Args:
means: A dictionary with parent names key and np.arrays of shape (dim_i,)
values, where means[par][i] specifies the amount to add to the function's
return values when the parent par has value i.
Returns:
Function that generates means for all tuples of values of the parents with
shape (n_samples,).
"""
def stoc_fn(**kwargs):
first_parent = [val for val in kwargs.values()][0]
if isinstance(first_parent, (int, float, np.integer, np.floating)):
# Not an array but a single sample.
n_samples = 1
else:
n_samples = len(first_parent)
samples = np.zeros(n_samples)
for parent, mean in means.items():
samples += mean[kwargs[parent]].flatten()
return samples
return stoc_fn
def add_gaussian_noise_to_stoc_fn(
stoc_fn: scm.StocFn, cov: float
) -> scm.StocFn:
def new_stoc_fn(**kwargs):
samples = stoc_fn(**kwargs)
return samples + np.random.normal(0, cov, size=samples.shape)
return new_stoc_fn
def add_stoc_fns(stoc_fn_list: List[scm.StocFn]) -> scm.StocFn:
def new_stoc_fn(**kwargs):
samples = stoc_fn_list[0](**kwargs)
for stoc_fn in stoc_fn_list[1:]:
samples += stoc_fn(**kwargs)
return samples
return new_stoc_fn
def create_categorical_stoc_fn(
probs: np.ndarray,
) -> scm.StocFn:
"""Returns a stochastic function for a categorical random variable.
Args:
probs: the probability of each outcome
"""
# Set the function parameters with a closure.
def stoc_fn(n_samples):
return np.random.choice(len(probs), size=n_samples, p=probs)
return stoc_fn
def create_categorical_conditional_stoc_fn(
probs: np.ndarray,
parent_names: List[str],
) -> scm.StocFn:
"""Returns a stoc_fn for a categorical random variable with parents.
Args:
probs: A tensor of dimension (parents[0].dim, ..., parents[end].dim, dim).
parent_names: A list of the names of the parents in the same order.
Returns: A function from a dictionary of parents to an np.ndarray where value
of the variable is chosen from the categorical distribution specified in the
probs tensor using the corresponding value of the parents. E.g. if the
parents are {'x0': [2], 'x1': [5], 'x2': [3]}, then the value is sampled as
a categorical distribution with p=probs[2, 5, 3, :]. If vectors are passed
as the parents, a vector of samples with the corresponding shape is
returned.
"""
def stoc_fn(**kwargs) -> np.ndarray:
first_parent = [val for val in kwargs.values()][0]
if isinstance(first_parent, (int, float, np.integer, np.floating)):
# Not an array but a single sample.
n_samples = 1
else:
n_samples = len(first_parent)
support_size = probs.shape[-1]
try:
parents_matrix = np.vstack(
[kwargs[var].flatten() for var in parent_names]
).transpose()
except Exception as exc:
raise ValueError('Parents do not have compatible size.') from exc
# We need to make parents_matrix integer valued where each column
# obeys the corresponding support_size constraint.
upper_bound = np.tile(np.array(probs.shape[:-1]) - 1, (n_samples, 1))
parents_matrix = np.minimum(
np.round(np.abs(parents_matrix)), upper_bound
).astype(int)
return np.array(
[
np.random.choice(support_size, p=probs[tuple(p_vals)])
for p_vals in parents_matrix
]
)
return stoc_fn
| additive_cbug-main | cbug/stoc_fn_utils.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A unit test for the utils implementation."""
import inspect
from absl.testing import absltest
from cbug import scm
from cbug import utils
import numpy as np
class UtilsTest(absltest.TestCase):
"""Unit test for the CBUG utilities."""
def test_name_to_idx(self):
support_sizes = {
'X1': 2,
'X2': 3,
'X3': 4,
}
name_to_idx = utils.get_name_to_idx(support_sizes)
answer = {
'X1': [0, 1],
'X2': [2, 3, 4],
'X3': [5, 6, 7],
}
self.assertDictEqual(name_to_idx, answer)
def test_generate_beta_cpd(self):
support_sizes = {'X': 2, 'Y': 3}
parents = {'X': [], 'Y': ['X']}
probs = utils.generate_beta_cpd(
support_sizes,
parents,
'Y',
)
assert len(probs) == 2
for p in probs:
assert sum(p) == 1
assert len(p) == 3
def test_sample_discrete_scm_graph(self):
np.random.seed(2) # Y will have children with this seed.
model = utils.sample_discrete_scm(num_var=2, degree=2, num_parents=2)
correct_parents = {
'X0': [],
'X1': ['X0'],
'X2': ['X0', 'X1', 'Y'],
'Y': ['X1', 'X0'],
}
self.assertDictEqual(model.parents, correct_parents)
self.assertListEqual(['X0', 'X1', 'Y', 'X2'], model.var_names)
def test_sample_discrete_scm_signatures(self):
np.random.seed(2) # Y will have children with this seed
model = utils.sample_discrete_scm(num_var=2, degree=2, num_parents=2)
# Check Signature for X0.
args = inspect.signature(model.stoc_fns['X0']).parameters.keys()
self.assertListEqual(args, [scm.N_SAMPLES_NAME])
# Check Signature for X1.
args = inspect.signature(model.stoc_fns['X1']).parameters.keys()
self.assertListEqual(args, ['kwargs'])
assert model.stoc_fns['X1'](X0=np.array([0, 1])).shape == (2,)
self.assertRaises(KeyError, model.stoc_fns['X1'](X1=0)) # Wrong parent.
# Check Signature for X2.
args = inspect.signature(model.stoc_fns['X2']).parameters.keys()
self.assertListEqual(args, ['kwargs'])
parent_values = {'X0': np.array([0, 1]),
'X1': np.array([0, 1]),
'Y': np.array([0, 1]),
}
assert model.stoc_fns['X2'](**parent_values).shape == (2,)
self.assertRaises(KeyError, model.stoc_fns['X1'](Z=0)) # wrong parent
# Check Signature for Y.
args = inspect.signature(model.stoc_fns['Y']).parameters.keys()
self.assertListEqual(args, ['kwargs'])
parent_values = {'X0': np.array([0, 1]),
'X1': np.array([0, 1]),
}
assert model.stoc_fns['Y'](**parent_values).shape == (2,)
self.assertRaises(KeyError, model.stoc_fns['Y'](X2=0)) # Wrong parent.
def test_sample_discrete_scm_sample_shapes(self):
np.random.seed(2) # Y will have children with this seed.
model = utils.sample_discrete_scm(num_var=2, degree=2, num_parents=2)
# Check shape of the stoc_fns.
n_samples = 3
samples = model.sample(n_samples)
assert samples['X0'].shape == (n_samples,)
assert samples['X1'].shape == (n_samples,)
assert samples['X2'].shape == (n_samples,)
assert samples['Y'].shape == (n_samples,)
def test_interval_intersection(self):
returned = utils.interval_intersection((0, 1), (1, 2))
np.testing.assert_allclose(returned, (1, 1))
returned = utils.interval_intersection((1, 3), (-2, 1))
np.testing.assert_allclose(returned, (1, 1))
returned = utils.interval_intersection((0, 1), (0, 2))
np.testing.assert_allclose(returned, (0, 1))
returned = utils.interval_intersection((0, 1), (2, 3))
assert returned is None
returned = utils.interval_intersection((0, 1), (2, 3))
assert returned is None
def test_one_hot_encoding(self):
covariate_values = {'x': np.array([1, 2, 3]), 'y': np.array([0, 1, 2])}
support_sizes = {'x': 4, 'y': 3}
variable_names = ['x', 'y']
results = utils.form_data_matrix(
covariate_values, support_sizes, variable_names
)
answers = np.array([[0, 1, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0, 1]])
np.testing.assert_array_equal(answers, results)
results = utils.form_data_matrix(
covariate_values, support_sizes, ['y', 'x']
)
answers = np.array([[1, 0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 1]])
np.testing.assert_array_equal(answers, results)
| additive_cbug-main | cbug/utils_test.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for scm."""
from absl.testing import absltest
from cbug import scm
import numpy as np
class SCMTest(absltest.TestCase):
def test_scm(self):
def x3_fn(x1, x2):
return x1 + x2
stoc_fns = {
'x0': lambda n_samples: np.random.binomial(1, 0.5, size=n_samples),
'x1': lambda n_samples: np.random.binomial(1, 0.25, size=n_samples),
'x2': lambda x0, x1: x1 + x0,
'x3': scm.StocFnRecipe(x3_fn, ['x1', 'x2']),
}
model = scm.SCM(stoc_fns)
parents = {
'x0': [],
'x1': [],
'x2': ['x0', 'x1'],
'x3': ['x1', 'x2'],
}
np.testing.assert_equal(model.parents, parents)
np.testing.assert_equal(model.var_names, ['x0', 'x1', 'x2', 'x3'])
def test_pure_sample(self):
def x3_fn(x1, x2):
return x1 * x2
stoc_fns = {
'x0': lambda n_samples: np.random.binomial(1, 0.5, size=n_samples),
'x1': lambda n_samples: np.random.binomial(1, 0.25, size=n_samples),
'x2': lambda x0, x1: x1 + x0,
'x3': scm.StocFnRecipe(x3_fn, ['x1', 'x2']),
}
model = scm.SCM(stoc_fns)
np.random.seed(3)
samples = model.sample(4)
answer = {
'x0': [1, 1, 0, 1],
'x1': [1, 1, 0, 0],
'x2': [2, 2, 0, 1],
'x3': [2, 2, 0, 0],
}
np.testing.assert_equal(samples, answer)
def test_pure_sample2(self):
def x3_fn(**kwargs):
return sum(list(kwargs.values()))
stoc_fns = {
'x0': lambda n_samples: np.random.binomial(1, 0.5, size=n_samples),
'x1': lambda n_samples: np.random.binomial(1, 0.25, size=n_samples),
'x2': lambda x0, x1: x1 + x0,
'x3': scm.StocFnRecipe(x3_fn, ['x0', 'x1', 'x2']),
}
model = scm.SCM(stoc_fns)
np.random.seed(3)
samples = model.sample(4)
answer = {
'x0': [1, 1, 0, 1],
'x1': [1, 1, 0, 0],
'x2': [2, 2, 0, 1],
'x3': [4, 4, 0, 2],
}
np.testing.assert_equal(samples, answer)
def test_sample_with_intervention(self):
def x3_fn(x1, x2):
return x1 * x2
stoc_fns = {
'x0': lambda n_samples: np.random.binomial(1, 0.5, size=n_samples),
'x1': lambda n_samples: np.random.binomial(1, 0.25, size=n_samples),
'x2': lambda x0, x1: x1 + x0,
'x3': scm.StocFnRecipe(x3_fn, ['x1', 'x2']),
}
model = scm.SCM(stoc_fns)
np.random.seed(4)
samples = model.sample(4, intervention={'x0': 1})
answer = {
'x0': [1, 1, 1, 1],
'x1': [1, 0, 1, 0],
'x2': [2, 1, 2, 1],
'x3': [2, 0, 2, 0],
}
np.testing.assert_equal(samples, answer)
np.random.seed(3)
samples = model.sample(4, intervention={'x1': 2})
answer = {
'x0': [1, 1, 0, 1],
'x1': [2, 2, 2, 2],
'x2': [3, 3, 2, 3],
'x3': [6, 6, 4, 6],
}
np.testing.assert_equal(samples, answer)
np.random.seed(4)
samples = model.sample(4, intervention={'x0': 0, 'x2': 2})
answer = {
'x0': [0, 0, 0, 0],
'x1': [1, 0, 1, 0],
'x2': [2, 2, 2, 2],
'x3': [2, 0, 2, 0],
}
np.testing.assert_equal(samples, answer)
if __name__ == '__main__':
absltest.main()
| additive_cbug-main | cbug/scm_test.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Init file for cbug package."""
from cbug import base
from cbug import discrete_scm
from cbug import discrete_scm_utils
from cbug import run
from cbug import scm
from cbug import stoc_fn_utils
from cbug import utils
| additive_cbug-main | cbug/__init__.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for cbug experiments."""
import itertools
from typing import List, Mapping, Tuple, Union
import numpy as np
def form_data_matrix(
values: Mapping[str, np.ndarray],
support_sizes: Mapping[str, int],
variable_names: list[str],
) -> np.ndarray:
"""Returns covariates with one-hot encoding.
Specifically, a dictionary of covariate_values, where covariate_values[var] is
a np-array of values corresponding to the covariate.
This function returns a matrix where the first row corresponds to
(covariate_values[variable_names[0]][0], ...,
covariate_values[variable_names[-1]][0])
and the last row corresponds to
(covariate_values[variable_names[0]][-1], ...,
covariate_values[variable_names[-1]][-1]),
and each row is transformed to one-hot encoding. The ith row is mapped to
e_{x_0}, ..., e_{x_k}
where x_i = covariate_values[variable_names[i]][j], and e_i is zero except
for a 1 in the i'th place.
Args:
values: A np.ndarray of ints of size (n_samples, n_vars). Each row
specifies a datapoint with values (x0, x1, ..., x_k).
support_sizes: Dictionary with variable name keys and support size values.
The support size specified the number of values the corresponding variable
can take, assumed to be (0, ..., n-1).
variable_names: The names, and order, of the variables to include.
Returns:
A np.ndarray of shape (n_samples, sum(support_size_list)), where each
row in data has been one-hot-encoded separately.
"""
one_hot_vector = []
for var in variable_names:
one_hot_vector.append(
np.eye(support_sizes[var])[values[var]]
)
return np.hstack(one_hot_vector)
def get_name_to_idx(
support_sizes: Mapping[str, int],
) -> Mapping[str, List[int]]:
"""Given a support size map, returns the indices in a one-hot encoding.
If we transform a series of data using one-hot encoding, such as in the
form_data_matrix function, each variable gets mapped to a certain range of
rows. This function returns a dictionary where each value specifies the
indices corresponding to the key variable.
Args:
support_sizes: Dictionary specifying the support size of each variable.
Returns:
A dictionary with a list of all the indices corresponding to each variable.
"""
name_to_idx = {}
start_idx = 0
for var, support_size in support_sizes.items():
name_to_idx[var] = np.arange(
int(start_idx), int(start_idx + support_size))
start_idx += support_size
return name_to_idx
def interval_intersection(
int1: Tuple[float, float],
int2: Tuple[float, float],
) -> Union[Tuple[float, float], None]:
"""Finds the intersection of two real-valued intervals.
Args:
int1: Tuple of floats: the first interval.
int2: Tuple of floats: the second interval.
Returns:
A tuple of floats indicating the interection of the intervals
or None if it is empty. Intervals are assumed to be closed.
"""
if int1[1] < int2[0] or int1[0] > int2[1]:
return None
else:
return (max(int1[0], int2[0]), min(int1[1], int2[1]))
def get_full_action_set(
support_sizes: Mapping[str, int],
outcome_variable: str = 'Y',
) -> List[Mapping[str, int]]:
"""Returns the product actions set."""
# Don't include the outcome variable in the action set.
sizes = [
list(range(support_sizes[var]))
for var in support_sizes
if var != outcome_variable
]
cartesian_product = itertools.product(*sizes)
actions = []
# Translate tuples of ints into a dictionary.
for action in cartesian_product:
actions.append({var: i for var, i in zip(support_sizes.keys(), action)})
return actions
| additive_cbug-main | cbug/utils.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A simple Structural Causal Model (SCM) specified with stochastic functions.
The building block is a stochastic function, which is a potentially random
mapping from values of parents to values of a variable. These functions
generalize:
-sampling from conditional probability distributions
-structural functions in SCMs.
Stochastic functions (stoc_fns) are either parent-less, in which case they only
output a random sample, or are specified by the values of their parents with
the option of additional randomness (e.g. they may be a linear function of the
parents with Gaussian noise). In this way, these function differs form the
structural functions found in SCMs which are always deterministic.
If the stochastic function has no parents, then it must take exactly one
integer-values argument, n_samples. For example, a 3-D standard normal would
be generated by
lamdda n_samples: np.random.normal(size=(n_samples,3 )).
All samples are always of the shape (n_samples,) or (n_samples, dimension).
If the stochastic function has parents, then the parents can be specified in
two ways:
1. Using the signature; e.g.
def fn(x1, x2):
return x1 + x2
2. Using the StocFnRecipe class, which specifies the function with kwargs
and the parents as metadata, e.g.
StocFnRecipe(lambda **kwargs; kwargs['x1'] + kwargs['x2'], ['x1', 'x2'])
The second method is helpful when you want to create procedural functions,
e.g. when the graph is generated first so the parents of a random variable
are not known apriori.
All data are assumed to be np.ndarrays, and the number of samples returned by
a stoc_fn with parents is infered from the size of the parents which is why no
n_samples argument is provided.
Finally, a SCM is specified with a dictionary of stochastic functions.
Example: We have the linear Gaussian SCM with X<-Z->Y and X->Y. We would call
stoc_fns = {
'Z': lambda n_samples: np.random.normal(size=n_samples)},
'X': lambda Z: 2*Z + np.random.normal(size=Z.shape)},
'Y': lambda X, Z: Z - 2 * X,
}
scm = SCM(stoc_fns)
Alternatively, we could use:
def f_y(**kwargs):
return kwargs['Z'] - 2 * kwargs['X']
stoc_fns = {
'Z': lambda n_samples: np.random.normal(size=n_samples)},
'X': lambda Z: 2*Z + np.random.normal(size=X.shape)},
'Y': StocFnRecipe(f_y, ['Z'' 'X'])
}
scm = SCM(stoc_fns).
N.B. If you are defining functions with mutable parameters, e.g. for some
mutable variable a
def f_y(**kwargs):
return kwargs['Z'] - a * kwargs['X']
you will need to either ensure that the value of a never changes (by making
a copy specifically for this function) or by definit the function in a
closure:
def f_y(a):
def f(**kwargs):
return kwargs['Z'] - a * kwargs['X']
return f
which ensures that a local copy of a in created and bound to the function f_y.
"""
import dataclasses
import inspect
from typing import Any, Callable, Mapping, Optional, Union, List
import networkx as nx
import numpy as np
StocFn = Callable[..., Any] # [[np.ndarray, ..., np.ndarray], np.ndarray]
N_SAMPLES_NAME = 'n_samples' # Constant for functions that do not have parents.
@dataclasses.dataclass
class StocFnRecipe:
"""Provides metadata needed to construct a stoc_fn."""
stoc_fn: StocFn
stoc_fn_inputs: Optional[List[str]] = None
class SCM:
"""Implements a simple SCM using stochastic functions.
Attributes:
var_names: A list of variable names.
parents: Mapping[str, List[str]]
parents[var] is a list of all names of all the parents of the variable
var. If var has no parents, parents[var] is an empty list.
stoc_fns: a dictionary of Callable objects.
With samples: Mapping[str, np.ndarray] is a dictionary of values,
stoc_fns[var](**parent_dict),
where parent_dict is a dictionary of the parent values, will provide the
values of the variable var. Recall that this function need not be
deterministic.
"""
def __init__(self,
stoc_fns: Mapping[str, Union[StocFnRecipe, StocFn]],
):
self._stoc_fns = {}
self._stoc_fn_inputs = {}
for var, stoc_fn in stoc_fns.items():
if callable(stoc_fn):
sig = inspect.signature(stoc_fn)
self._stoc_fn_inputs[var] = list(sig.parameters.keys())
self._stoc_fns[var] = stoc_fn
elif isinstance(stoc_fn, StocFnRecipe):
if stoc_fn.stoc_fn_inputs is not None:
self._stoc_fn_inputs[var] = stoc_fn.stoc_fn_inputs
else:
self._stoc_fn_inputs[var] = [N_SAMPLES_NAME]
self._stoc_fns[var] = stoc_fn.stoc_fn
else:
raise ValueError(
'Must be a callable with a signature specifying the parents or a'
' StocFnRecipe.'
)
self._var_names_ordered = self._topological_sort(self._stoc_fn_inputs)
def sample(self,
n_samples: int,
intervention: Optional[Union[Mapping[str, np.ndarray],
Mapping[str, int],
Mapping[str, float],
]] = None,
) -> Mapping[str, np.ndarray]:
"""Generates a sample from the SCM.
Args:
n_samples: The number of samples.
intervention (optional):
For each key, the corresponding variable is set to the value instead of
being sampled from the SCM.
Returns:
Dictionary with {var_name: sample of var_name} for all var_names
"""
samples = {N_SAMPLES_NAME: np.array([n_samples], dtype=int)}
if intervention is None:
intervention = {}
for var in self._var_names_ordered:
if var in intervention:
val = np.array(intervention[var])
if val.size == 1:
samples[var] = np.repeat(val.flatten(), n_samples, axis=0)
else:
samples[var] = np.repeat(val.reshape((1, -1)), n_samples, axis=0)
else:
parent_samples = {v: samples[v] for v in self._stoc_fn_inputs[var]}
samples[var] = self._stoc_fns[var](**parent_samples)
samples.pop(N_SAMPLES_NAME) # Remove integer inputs.
return samples
def _topological_sort(
self, stoc_fn_inputs: Mapping[str, List[str]]
) -> List[str]:
"""Topologically sorts the nodes."""
edges = []
nodes = list(stoc_fn_inputs.keys())
for var, curr_parent_names in stoc_fn_inputs.items():
edges.extend([(p, var) for p in curr_parent_names])
dag = nx.DiGraph()
dag.add_nodes_from(nodes)
dag.add_edges_from(edges)
return [var for var in nx.topological_sort(dag) if var != N_SAMPLES_NAME]
def draw(self):
"""Draws the adjacency graph of the SCM."""
edges = []
nodes = list(self.var_names)
for var, curr_parent_names in self.parents.items():
edges.extend([(p, var) for p in curr_parent_names])
dag = nx.DiGraph()
dag.add_nodes_from(nodes)
dag.add_edges_from(edges)
nx.draw(dag, with_labels=True)
@property
def parents(self) -> Mapping[str, List[str]]:
return {
v: [] if item == [N_SAMPLES_NAME] else item
for v, item in self._stoc_fn_inputs.items()
}
@property
def stoc_fns(self) -> Mapping[str, Callable[..., any]]:
return self._stoc_fns
@property
def var_names(self) -> List[str]:
"""Returns all the variable names in topological order."""
return self._var_names_ordered
| additive_cbug-main | cbug/scm.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements a Discrete Structural Causal Model (SCM).
Builds on scm.SCM class.
This SCM assumes all variables, except for the outcome variable, are discrete.
As such, it includes a few extra attributes on top of scm.SCM
- outcome_variable: The real-valued variable that we are optimizing.
- support_size: Mapping[str, int] specifies the number of distinct values all
the non-outcome variables can take.
- best_action: stores the intervention that induces the highest expected value
of the outcome variable.
"""
from typing import Callable, Mapping, Optional, Union
from cbug import scm
class DiscreteSCM(scm.SCM):
"""Implements a discrete SCM using stochastic functions.
All variables, except for the outcome_variable, are assumed to take on
discrete values.
Attributes:
var_names: List[str] All variable names sorted to be in topological order.
parents: Mapping[str, List[str]] parents[var] is a list of all names of all
the parents of the variable var. If var has no parents, parents[var] is an
empty list.
stoc_fns: A dictionary of Callable object, where evaluating
stoc_fns[var](**parent_dict) will provide the values of the variable var.
Recall that this function need not be deterministic.
outcome_variable: the real-valued variable that we are optimizing.
support_size: A dictionary specifying the number of distinct values all
the non-outcome variables can take.
best_action: A mapping from variable names to a value for each variable that
corresponds to the intervention that results in the highest expected value
of the outcome variable.
best_action_value: The expected value of the best action.
outcome_expected_value_fn: A function that returns the expected value of the
stoc_fn of the outcome_variable.
"""
def __init__(self,
stoc_fns: Mapping[str, Union[scm.StocFnRecipe, scm.StocFn]],
support_sizes: Mapping[str, int],
outcome_variable: str,
best_action: Optional[Mapping[str, int]] = None,
best_action_value: Optional[float] = None,
outcome_expected_value_fn:
Optional[Callable[[Mapping[str, int]], float]] = None,
):
super().__init__(stoc_fns)
if support_sizes is None:
self._support_sizes = {}
else:
self._support_sizes = support_sizes
self._outcome_variable = outcome_variable
self.best_action = best_action
self.best_action_value = best_action_value
self.outcome_expected_value_fn = outcome_expected_value_fn
@property
def support_sizes(self) -> Mapping[str, int]:
"""Number of distinct values for each variable."""
return self._support_sizes
@property
def outcome_variable(self) -> str:
return self._outcome_variable
| additive_cbug-main | cbug/discrete_scm.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of algorithms from the paper."""
import random
from typing import List, Mapping, Tuple, Optional, Union
from cbug import discrete_scm
from cbug import scm
from cbug import utils
import numpy as np
class Results:
"""Stores results generated from running action-elimination algorithms.
In particular, both the run_modl algorithm and run_se returns Results objects.
Attributes:
s_t: A list of sets of plausibly best actions, as produced by running an
action-elimination algorithm.
num_actions_t: A list of ints of the number of actions remaining.
gamma_t: A list of floats of the confidence-widths.
n_samples_t: A list of ints of the tutal number of samples used.
mean_est_t: A list of np.ndarrays of the mean estimates.
true_value_t: A list of floats of the true reward generated by the
empirically best action so far.
best_action_t: A list of dictionaries of the empirically best action.
"""
def __init__(self):
# _t denotes a sequence indexed by rounds.
self.s_t = []
self.num_actions_t = []
self.gamma_t = []
self.n_samples_t = []
self.mean_est_t = None
self.true_value_t = []
self.best_action_t = []
def update(
self,
action_set: Union[Mapping[str, List[int]], List[Mapping[str, int]]],
num_actions: int,
gamma: float,
n_samples: int,
mean_est: np.ndarray,
true_value: float,
best_action: Mapping[str, int],
):
"""Adds an additional observation to the Results class.
Args:
action_set: A representation of the plausibly best actions left, either
through a marginal action set or a list of actions.
num_actions: The number of actions remaining.
gamma: The confidence width.
n_samples: The number of samples used.
mean_est: A vector of mean-estimates for every value of every variable.
true_value: The true value of the empirically best action.
best_action: The empirically best action.
"""
self.s_t.append(action_set)
self.num_actions_t.append(num_actions)
self.gamma_t.append(gamma)
self.n_samples_t.append(n_samples)
if self.mean_est_t is None:
self.mean_est_t = mean_est.reshape(-1, 1)
else:
self.mean_est_t = np.hstack((self.mean_est_t, mean_est.reshape(-1, 1)))
self.true_value_t.append(float(true_value))
self.best_action_t.append(best_action)
def __str__(self):
final_action = {var: list(self.s_t[-1][var]) for var in self.s_t[-1]}
string = (
f"Displaying experimental results with {len(self.s_t)} rounds and total"
f" samples {sum(self.n_samples_t)}.\nThe samples needed were"
f" {self.n_samples_t}\nat gammas {self.gamma_t}.\nThe expected outcome"
f" of the empirically best values are {self.true_value_t}\nand the"
f" final actions are {final_action}\nwith a parameter"
f" estimate\n{self.mean_est_t[:, -1]}"
)
return string
def reduce_actions(
s_marginal: Mapping[str, np.ndarray],
name_to_idx: Mapping[str, List[int]],
mean_est: np.ndarray,
gamma: float,
) -> Tuple[Mapping[str, List[int]], Mapping[str, int]]:
"""Uses a parameter estimate to prune the marginal action set.
Starting from a marginal action set, this method computes the gaps for each
variable separately then eliminates all values from the variable that have a
gap bigger than gamma.
Args:
s_marginal: A dictionary of remaining actions for each variable in a
sorted-in-ascending-order list.
name_to_idx: A dictionary specifying which positions of mean_est correspond
to each variable. This encoding is the same one-hot encoding by
utils.form_data_matrix.
mean_est: An nd.array of mean estimates. Assumed to be in the one-hot
encoding order.
gamma: The width of the confidence intervals for the means estimates.
Returns:
A new, pruned s_marginal and a guess of the best action.
"""
new_s_marginal = {}
best_action = {}
# Eliminate actions variable-by-variable.
for var in s_marginal:
# Compute gaps.
marginal_means = mean_est[name_to_idx[var]][s_marginal[var]]
gaps = np.array(max(marginal_means) - marginal_means).flatten()
idx_to_keep = np.argwhere(gaps < gamma)
best_pos = np.argwhere(gaps == 0)[0]
new_s_marginal[var] = s_marginal[var][idx_to_keep.flatten()]
best_action[var] = s_marginal[var][best_pos]
return (new_s_marginal, best_action)
def xy_optimal_design(
s_marginal: Mapping[str, List[int]],
support_sizes: Mapping[str, int],
gamma: float,
delta: float,
cov: float,
) -> Mapping[str, np.ndarray]:
"""Solves an XY optimal design problem.
The optimal design problem chooses a sequences of actions that will reveal as
much information as possible about the gaps between values of the actions.
If there is only one action remaining for a variable, then a uniform
distribution over all the variable's actions is assumed, which provides a
more informative mean estimate from the linear regression.
Args:
s_marginal: A marginal action set; composed of a dictionary of lists, each
list representing the actions of the corresponding variable that haven't
been eliminated yet.
support_sizes: Dictionary of support sizes of every variable.
gamma: Error tolerance.
delta: Probability bound.
cov: Scale of noise.
Returns:
A dictionary of a sequence of actions for each variable.
"""
num_s = sum([len(s_marginal[var]) for var in s_marginal])
num_samples = int(np.ceil(4 * cov * num_s * np.log(1 / delta) / gamma**2))
marginal_points = {}
for var in s_marginal:
support = len(s_marginal[var])
if support == 1: # Make this uniform.
num_cycles = int(np.ceil(num_samples / support_sizes[var]))
samples = []
for _ in range(num_cycles):
new_list = list(np.arange(support_sizes[var]))
np.random.shuffle(new_list)
samples.append(new_list)
else:
num_cycles = int(np.ceil(num_samples / support))
samples = []
for _ in range(num_cycles):
new_list = list(s_marginal[var])
np.random.shuffle(new_list)
samples.append(new_list)
marginal_points[var] = np.array(samples).flatten()[:num_samples]
return marginal_points
def run_modl(
delta: float,
epsilon: float,
model: discrete_scm.DiscreteSCM,
cov: float,
outcome_bound: float,
lambda_ridge: Optional[float] = .1,
opt_scope: Optional[List[str]] = None,
num_parents_bound: Optional[int] = None,
) -> Results:
"""Runs the MODL algorithm, Algorithm 1 of the paper.
Args:
delta: High probability requirement.
epsilon: Error bound.
model: A scm.SCM.
cov: Noise scale parameter.
outcome_bound: Bound of sum_i f_i.
lambda_ridge: The regularization parameter for ridge regression.
opt_scope: A list of variable names to include in the optimization. If
unspecified, all variables are included.
num_parents_bound: An upper bound on the number of parents.
Returns:
A Results object summarizing the experiment.
"""
if opt_scope is None:
opt_scope = model.var_names.copy()
opt_scope.remove(model.outcome_variable)
s_marginal_size = np.sum([model.support_sizes[var] for var in opt_scope])
name_to_idx = utils.get_name_to_idx(
{var: model.support_sizes[var] for var in opt_scope}
)
# Construct a full marginal.
s_marginal = {
name: np.arange(model.support_sizes[name]) for name in opt_scope
}
num_actions = sum([len(s_marginal[var]) for var in s_marginal])
results = Results()
mean_est = np.empty(s_marginal_size)
mean_est[:] = np.nan
num_phases = np.ceil(np.log2(outcome_bound / epsilon))
current_phase = 0
true_value = 0
best_action = {}
while current_phase <= num_phases:
gamma = epsilon * 2**(num_phases - current_phase - 1)
# Solve optimization problem.
covariates = xy_optimal_design(
s_marginal,
model.support_sizes,
gamma,
delta / num_phases,
cov,
)
# Collect data.
n = len(covariates[opt_scope[0]])
if n < num_actions: # We cannot have enough data coverage.
current_phase += 1
results.update(
s_marginal, num_actions, gamma, n, mean_est, true_value, best_action
)
continue
samples = model.sample(n)
data_matrix = utils.form_data_matrix(
samples, model.support_sizes, opt_scope
)
# Update linear parameter vector.
mean_est = np.linalg.inv(
data_matrix.transpose().dot(data_matrix)
+ lambda_ridge * np.eye(s_marginal_size)
).dot(
data_matrix.transpose().dot(
samples[model.outcome_variable].reshape(-1, 1)
)
)
# Eliminate the arms with dynamic algorithm.
(s_marginal, best_action) = reduce_actions(
s_marginal,
name_to_idx,
mean_est,
gamma,
)
num_actions = sum([len(s_marginal[var]) for var in s_marginal])
# Estimate the true value of the best_action.
true_value = estimate_value(model, best_action, model.outcome_variable)
results.update(s_marginal, num_actions, gamma, n, mean_est, true_value,
best_action)
if num_actions == len(opt_scope): # We have eliminated all but one action.
break
if num_parents_bound is not None:
# Count the number of variables with a single remaining action.
single_action = [len(s_marginal[var]) == 1 for var in s_marginal]
if sum(single_action) >= num_parents_bound: # All the parents are found.
return results
current_phase += 1
return results
def run_se(
delta: float,
epsilon: float,
model: discrete_scm.DiscreteSCM,
cov: float,
outcome_bound: float,
opt_scope: Optional[List[str]] = None,
batch_size: int = 100,
sample_limit: int = 10000000,
max_num_actions: int = 10000,
) -> Results:
"""Runs the successive elimination algorithm.
Warning: this algorithm has exponential complexity in the number of parents:
please be careful with the size of the input problem.
Args:
delta: High probability requirement.
epsilon: Error bound.
model: An scm.SCM; action variables are assumed to be discrete.
cov: Noise scale parameter.
outcome_bound: Bound of sum_i f_i.
opt_scope: A list of variable names to include in the optimization. If
unspecified, all variables are included.
batch_size: The number of samples to gather between elimination rounds.
sample_limit: The algorithm terminates after sample_limit total samples have
been collected.
max_num_actions: The total number of actions (arms) allowed; if the product
of all actions support is larger, the method terminates.
Returns:
A Results object.
"""
if opt_scope is None:
opt_scope = model.var_names.copy()
opt_scope.remove(model.outcome_variable)
results = Results()
# If the number of actions is too large, abort.
num_actions = np.product(list(model.support_sizes.values()))
if num_actions > max_num_actions:
print(f"Warning: {num_actions} actions: termination could be slow.")
actions = utils.get_full_action_set(model.support_sizes)
candidate_arm_idx = list(range(len(actions)))
means = [] # Dicts are not hashable.
total_samples = 0
# Pull every arm once.
for action in actions:
values = {var: action[var] for var in action}
rewards = model.sample(batch_size, values)[model.outcome_variable]
means.append(np.mean(rewards))
total_samples += batch_size * len(actions)
num_samples_per_arm = batch_size
means = np.array(means)
while len(candidate_arm_idx) > 1:
# Pull all remaining arms.
for arm_idx in candidate_arm_idx:
values = {var: actions[arm_idx][var]for var in actions[arm_idx]}
rewards = model.sample(batch_size, values)[model.outcome_variable]
total_samples += batch_size
means[arm_idx] = (
means[arm_idx] * num_samples_per_arm + np.mean(rewards) * batch_size
) / (num_samples_per_arm + batch_size)
num_samples_per_arm += batch_size
# Do elimination.
width = np.sqrt(
cov * outcome_bound
* np.log(2 * len(actions) * num_samples_per_arm**2 / delta)
/ num_samples_per_arm
)
best_mean = np.max([means[idx] for idx in candidate_arm_idx])
new_candidate_arms = []
for idx in candidate_arm_idx:
if means[idx] > best_mean - 2 * width:
new_candidate_arms.append(idx)
if means[idx] == best_mean:
best_action = actions[idx]
candidate_arms = new_candidate_arms
# Calculate the true value of the best_action.
true_value = estimate_value(model, best_action, model.outcome_variable)
results.update(
[],
len(candidate_arms),
width,
total_samples,
means,
true_value,
best_action,
)
if width < epsilon / 2: # All remaining arms are approximately optimal.
return results
if total_samples > sample_limit:
print("Sample limit for successive elimination reached.")
return results
return results
def find_parents(
target_var: str,
delta: float,
epsilon: float,
model: discrete_scm.DiscreteSCM,
cov: float,
num_parents_bound: Optional[int] = None,
) -> Tuple[List[str], int]:
"""Finds the parents of Y in a discrete SCM variable-by-variable.
For each variable, an arbitrary point in the support is chosen, and a
hypothesis test for parenthood of that variable is conducted. The method can
terminate early when enough parents have been found.
This method assumes that the SCM is discrete and the causal effects on
var_name are additive.
Args:
target_var: The name of the variable whose parents we want to find.
delta: Desired error probability bound.
epsilon: The minimum detectable effect.
model: A DiscreteSCM.
cov: Scale of the noise.
num_parents_bound: An upper bound on the number of parents.
Returns:
A list of parents of the target variable.
"""
opt_scope = model.var_names.copy()
opt_scope.remove(target_var)
num_vars = len(opt_scope)
parents = []
total_samples = 0
var_order = random.sample(opt_scope, len(opt_scope))
for var in var_order:
# Calculate number of samples.
n = int(
np.ceil(
8 * cov * np.log(2 * model.support_sizes[var] * num_vars / delta)
)
/ epsilon**2
)
conf_set = (-np.inf, np.inf)
action = {var: 0 for var in opt_scope}
for value in range(model.support_sizes[var]):
action[var] = value
# Collect n samples.
sample = model.sample(n, action)
total_samples += n
y_mean = np.mean(sample[target_var])
conf_set = utils.interval_intersection(
conf_set,
(y_mean - epsilon / 2, y_mean + epsilon / 2),
)
if conf_set is None: # Empty intersection.
parents.append(var)
break
if num_parents_bound is not None:
if len(parents) >= num_parents_bound:
break
return (parents, total_samples)
def estimate_value(model: scm.SCM,
best_action: Mapping[str, int],
outcome_variable: str,
n: int = 1000,
) -> float:
"""Estimates the true value of the best_action."""
return np.mean(model.sample(n, best_action)[outcome_variable])
| additive_cbug-main | cbug/base.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Renderer for NetHack with customizable foreground and background colors."""
import struct
from typing import Mapping, Tuple, Optional
from nle import _pynethack
import numpy as np
import pygame as pg
FOREGROUND_COLORS = [
# Dark
'#000000',
'#770000',
'#007700',
'#aa7700',
'#000077',
'#aa00aa',
'#00aaaa',
'#ffffff',
# Bright
'#888888',
'#ff0000',
'#00ff00',
'#ffff00',
'#0000ff',
'#ff00ff',
'#00ffff',
'#ffffff',
]
BACKGROUND_COLORS = dict(
cursor='#555555', # Gray.
corpse='#0000aa', # Blue.
invis='#333333', # Gray.
detect='#333333', # Gray.
pet='#ffffff', # White.
ridden='#333333', # Gray.
statue='#333333', # Gray.
objpile='#333333', # Gray.
bwlava='#330000', # Red.
default='#000000', # Black.
)
# Rendered tiles are cached in this dictionary to avoid re-rendering later.
TILE_CACHE = {}
def hex_string_to_color_tuple(hex_string: str) -> Tuple[int, int, int]:
"""Convert a hex string prefixed with '#' to RGB tuple."""
color_three_bytes = int(hex_string[1:], 16)
blue, green, red, _ = struct.unpack('4B', struct.pack('I', color_three_bytes))
return (red, green, blue)
def get_special_background(special: int) -> str:
"""Color the character and background based on its special flags."""
if bool(special & _pynethack.nethack.MG_CORPSE):
return 'corpse'
elif bool(special & _pynethack.nethack.MG_INVIS):
return 'invis'
elif bool(special & _pynethack.nethack.MG_DETECT):
return 'detect'
elif bool(special & _pynethack.nethack.MG_PET):
return 'pet'
elif bool(special & _pynethack.nethack.MG_RIDDEN):
return 'ridden'
elif bool(special & _pynethack.nethack.MG_STATUE):
return 'statue'
elif bool(special & _pynethack.nethack.MG_OBJPILE):
return 'objpile'
elif bool(special & _pynethack.nethack.MG_BW_LAVA):
return 'bwlava'
else:
return 'default'
def represent_char(c: int) -> int:
"""Change the representation of certain characters to curses UI forms."""
if c == 0: # Represent invalid characters with blank space.
return ord(' ')
elif c == ord('`'): # Represent boulders as 0 for readability.
return ord('0')
else:
return c
class ImageRenderer:
"""Renderer using headless PyGame to render TTY observations as images."""
def __init__(self):
pg.font.init()
self._font = pg.font.SysFont('couriernew', 14, bold=True)
# Make color tuples from the hex strings above.
self._colors_map = np.array(list(map(hex_string_to_color_tuple,
FOREGROUND_COLORS)))
self._bgcolors = {k: hex_string_to_color_tuple(v)
for k, v in BACKGROUND_COLORS.items()}
# `specials` is a uint8 bitfield. Map all possible values of `specials` to
# the background color that the we should use for it.
self._specials_map = np.zeros((256, 3))
for s in range(256):
self._specials_map[s] = self._bgcolors[get_special_background(s)]
def _render_char(self,
c: str,
color: Tuple[int, int, int],
background: Tuple[int, int, int]) -> np.ndarray:
"""Render a single character to a patch. Patches are cached for reuse."""
key = (c, tuple(color), tuple(background))
if key not in TILE_CACHE:
# Render this single character to a small image patch.
single_character = pg.surfarray.array3d(
self._font.render(c, True, color, background)).swapaxes(0, 1)
# Ensure that the patch is exactly 16x8.
single_character_fixed_size = single_character[:16, :8]
TILE_CACHE[key] = single_character_fixed_size
return TILE_CACHE[key]
def render(self,
obs: Mapping[str, np.ndarray],
foreground_colors: Optional[np.ndarray] = None,
background_colors: Optional[np.ndarray] = None) -> np.ndarray:
"""Render an image of the TTY, with colors potentially overridden.
Args:
obs: Standard NLE observation dict, or observation dict from the NAO
dataset. Must contain key `tty_chars`.
foreground_colors: Optional RGB array of color overrides for the chars. If
not specified, colors will be derived from `tty_colors` instead.
background_colors: Optional RGB array of color overrides for tile
backgrounds. If not specified, background colors will be derived from
`specials` or `tty_background` keys of the observation.
Returns:
Rendered image in the form of an RGB numpy array.
"""
# If colors are not specified, extract them from the observation.
if foreground_colors is None:
foreground_colors = self._colors_map[np.clip(obs['tty_colors'], 0, 15)]
if background_colors is None:
if 'specials' in obs:
padded_specials = np.pad(obs['specials'], [[1, 2], [0, 1]])
padded_specials = np.clip(padded_specials, 0, 255)
background_colors = self._specials_map[padded_specials]
elif 'tty_background' in obs:
background_colors = self._colors_map[
np.clip(obs['tty_background'], 0, 15)]
else:
background_colors = np.zeros((24, 80, 3), dtype=np.uint8)
if 'tty_cursor' in obs:
background_colors[obs['tty_cursor'][1],
obs['tty_cursor'][0]] = self._bgcolors['cursor']
tty_chars = np.clip(obs['tty_chars'], 0, 255)
def _render_pos(x, y):
return self._render_char(
chr(represent_char(tty_chars[y, x])),
foreground_colors[y, x],
background_colors[y, x])
return np.vstack([np.hstack([_render_pos(x, y) for x in range(80)])
for y in range(24)])
| nao_top10-main | renderer.py |
# Copyright 2022 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A simple tool to iterate through the dataset, printing the name and source.
Example usage:
print_names_and_sources /path/to/dataset/code_contests_train*
"""
import io
import sys
import riegeli
import contest_problem_pb2
def _all_problems(filenames):
"""Iterates through all ContestProblems in filenames."""
for filename in filenames:
reader = riegeli.RecordReader(io.FileIO(filename, mode='rb'),)
for problem in reader.read_messages(contest_problem_pb2.ContestProblem):
yield problem
def _print_names_and_sources(filenames):
"""Prints the names and sources of all ContestProblems in filenames."""
for problem in _all_problems(filenames):
print(
contest_problem_pb2.ContestProblem.Source.Name(problem.source),
problem.name)
if __name__ == '__main__':
_print_names_and_sources(sys.argv[1:])
| code_contests-main | print_names_and_sources.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Install script for setuptools."""
import distutils.sysconfig
import fnmatch
import os
import posixpath
import re
import shutil
import sys
import sysconfig
import setuptools
from setuptools.command import build_ext
__version__ = '1.0.6'
PROJECT_NAME = 'labmaze'
REQUIRED_PACKAGES = [
'absl-py',
'numpy>=1.8.0',
'setuptools!=50.0.0', # https://github.com/pypa/setuptools/issues/2350
]
WORKSPACE_PYTHON_HEADERS_PATTERN = re.compile(
r'(?<=path = ").*(?=", # May be overwritten by setup\.py\.)')
IS_WINDOWS = sys.platform.startswith('win')
class BazelExtension(setuptools.Extension):
"""A C/C++ extension that is defined as a Bazel BUILD target."""
def __init__(self, bazel_target):
self.bazel_target = bazel_target
self.relpath, self.target_name = (
posixpath.relpath(bazel_target, '//').split(':'))
ext_name = os.path.join(
self.relpath.replace(posixpath.sep, os.path.sep), self.target_name)
setuptools.Extension.__init__(self, ext_name, sources=[])
class BuildBazelExtension(build_ext.build_ext):
"""A command that runs Bazel to build a C/C++ extension."""
def run(self):
for ext in self.extensions:
self.bazel_build(ext)
build_ext.build_ext.run(self)
def bazel_build(self, ext):
with open('WORKSPACE', 'r') as f:
workspace_contents = f.read()
with open('WORKSPACE', 'w') as f:
f.write(WORKSPACE_PYTHON_HEADERS_PATTERN.sub(
distutils.sysconfig.get_python_inc().replace(os.path.sep,
posixpath.sep),
workspace_contents))
if not os.path.exists(self.build_temp):
os.makedirs(self.build_temp)
bazel_argv = [
'bazel',
'build',
ext.bazel_target,
'--symlink_prefix=' + os.path.join(self.build_temp, 'bazel-'),
'--compilation_mode=' + ('dbg' if self.debug else 'opt'),
]
if IS_WINDOWS:
for library_dir in self.library_dirs:
bazel_argv.append('--linkopt=/LIBPATH:' + library_dir)
# TODO(stunya): Figure out why we need this.
if sysconfig.get_python_version() == '3.7':
bazel_argv.append('--linkopt=/LIBPATH:C:\\Python37\\Libs')
self.spawn(bazel_argv)
shared_lib_suffix = '.dll' if IS_WINDOWS else '.so'
ext_bazel_bin_path = os.path.join(
self.build_temp, 'bazel-bin',
ext.relpath, ext.target_name + shared_lib_suffix)
ext_dest_path = self.get_ext_fullpath(ext.name)
ext_dest_dir = os.path.dirname(ext_dest_path)
if not os.path.exists(ext_dest_dir):
os.makedirs(ext_dest_dir)
shutil.copyfile(ext_bazel_bin_path, ext_dest_path)
def find_data_files(package_dir, patterns):
"""Recursively finds files whose names match the given shell patterns."""
paths = set()
for directory, _, filenames in os.walk(package_dir):
for pattern in patterns:
for filename in fnmatch.filter(filenames, pattern):
# NB: paths must be relative to the package directory.
relative_dirpath = os.path.relpath(directory, package_dir)
paths.add(os.path.join(relative_dirpath, filename))
return list(paths)
setuptools.setup(
name=PROJECT_NAME,
version=__version__,
description='LabMaze: DeepMind Lab\'s text maze generator.',
author='DeepMind',
license='Apache 2.0',
ext_modules=[
BazelExtension('//labmaze/cc/python:_defaults'),
BazelExtension('//labmaze/cc/python:_random_maze'),
],
cmdclass=dict(build_ext=BuildBazelExtension),
packages=setuptools.find_packages(),
package_data={'labmaze':
find_data_files(package_dir='labmaze', patterns=['*.png'])},
install_requires=REQUIRED_PACKAGES,
)
| labmaze-master | setup.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""An array-like object that represents a 2D text grid."""
import sys
import numpy as np
class TextGrid(np.ndarray):
"""An array-like object that represents a 2D text grid.
This object is constructed from a newline-delimited string (with a trailing
newline character) and exposes an 2D array-like interface for character-wise
access. The original string can be retrieved by performing a string-conversion
on this object.
"""
def __new__(cls, newline_delimited_string):
raw = newline_delimited_string
split = raw[:-1].split('\n')
height = len(split)
width = len(split[0]) if split else 0
dtype = 'U1' if sys.version_info[0] >= 3 else 'S1'
obj = super(TextGrid, cls).__new__(cls, shape=(height, width), dtype=dtype)
obj[:, :] = tuple(tuple(line) for line in split)
return obj
def __str__(self):
lines = [''.join(row) for row in self]
lines.append('')
return '\n'.join(lines)
| labmaze-master | labmaze/text_grid.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for labmaze.fixed_maze."""
from absl.testing import absltest
from absl.testing import parameterized
from labmaze import fixed_maze
import numpy as np
_WIDTH = 9
_HEIGHT = 7
_EMPTY_CELL = ' '
_WALL = '*'
_SPAWN_TOKEN = '%'
_OBJECT_TOKEN = '$'
_MAZE_1 = ('* * * * *\n'
' * * * * \n'
'* * * * *\n'
' * * * * \n'
'* * * * *\n'
' * * * * \n'
'* * * * *\n')
_MAZE_2 = ('* * * * *\n'
' *%* *$* \n'
'* *$* * *\n'
' *%* *%* \n'
'* * *$* *\n'
' *$* * * \n'
'* * *$* *\n')
_MAZE_2_SPAWNS = ((1, 2), (3, 2), (3, 6))
_MAZE_2_OBJECTS = ((1, 6), (2, 3), (4, 5), (5, 2), (6, 5))
class FixedMazeWithRandomGoalsTest(parameterized.TestCase):
def testCorrectSize(self):
maze = fixed_maze.FixedMazeWithRandomGoals(entity_layer=_MAZE_1)
self.assertEqual(maze.height, _HEIGHT)
self.assertEqual(maze.width, _WIDTH)
def testCorrectEntityLayer(self):
maze = fixed_maze.FixedMazeWithRandomGoals(
entity_layer=_MAZE_2,
num_spawns=0, spawn_token=_SPAWN_TOKEN,
num_objects=0, object_token=_OBJECT_TOKEN)
maze_chars = _MAZE_1.split('\n')
for y in range(maze.height):
for x in range(maze.width):
self.assertEqual(maze.entity_layer[y, x], maze_chars[y][x])
def assert_consistent_maze(self, maze, num_spawns, num_objects,
required_spawns=(), required_objects=()):
spawns_found = 0
objects_found = 0
for y in range(maze.height):
for x in range(maze.width):
if y % 2 == x % 2:
self.assertEqual(maze.entity_layer[y, x], _WALL)
else:
self.assertIn(maze.entity_layer[y, x],
(_EMPTY_CELL, _SPAWN_TOKEN, _OBJECT_TOKEN))
if maze.entity_layer[y, x] == _SPAWN_TOKEN:
spawns_found += 1
if num_spawns < len(required_spawns):
self.assertIn((y, x), required_spawns)
elif maze.entity_layer[y, x] == _OBJECT_TOKEN:
objects_found += 1
if num_objects < len(required_objects):
self.assertIn((y, x), required_objects)
if num_spawns >= len(required_spawns):
for required_spawn in required_spawns:
self.assertEqual(maze.entity_layer[required_spawn], _SPAWN_TOKEN)
if num_objects >= len(required_objects):
for required_object in required_objects:
self.assertEqual(maze.entity_layer[required_object], _OBJECT_TOKEN)
self.assertEqual(spawns_found, num_spawns)
self.assertEqual(objects_found, num_objects)
def testConsistentMazeUnconstrained(self):
num_spawns = 2
num_objects = 3
maze = fixed_maze.FixedMazeWithRandomGoals(
entity_layer=_MAZE_1,
num_spawns=num_spawns, spawn_token=_SPAWN_TOKEN,
num_objects=num_objects, object_token=_OBJECT_TOKEN,
random_state=np.random.RandomState(123))
self.assert_consistent_maze(maze, num_spawns, num_objects)
for _ in range(5):
old_entity_layer = maze.entity_layer.copy()
maze.regenerate()
self.assertFalse((maze.entity_layer == old_entity_layer).all())
self.assert_consistent_maze(maze, num_spawns, num_objects)
@parameterized.named_parameters(
('underconstrained', 1, 2),
('overconstrained', 4, 7))
def testConsistentMazeConstrained(self, num_spawns, num_objects):
maze = fixed_maze.FixedMazeWithRandomGoals(
entity_layer=_MAZE_2,
num_spawns=num_spawns, spawn_token=_SPAWN_TOKEN,
num_objects=num_objects, object_token=_OBJECT_TOKEN,
random_state=np.random.RandomState(234))
self.assert_consistent_maze(maze, num_spawns, num_objects,
required_spawns=_MAZE_2_SPAWNS,
required_objects=_MAZE_2_OBJECTS)
for _ in range(5):
old_entity_layer = maze.entity_layer.copy()
maze.regenerate()
self.assertFalse((maze.entity_layer == old_entity_layer).all())
self.assert_consistent_maze(maze, num_spawns, num_objects,
required_spawns=_MAZE_2_SPAWNS,
required_objects=_MAZE_2_OBJECTS)
if __name__ == '__main__':
absltest.main()
| labmaze-master | labmaze/fixed_maze_test.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Text mazes with a fixed, prespecified layout."""
import itertools
from labmaze import base
from labmaze import defaults
from labmaze import text_grid
import numpy as np
_EMPTY_CELL = ' '
class FixedMazeWithRandomGoals(base.BaseMaze):
"""A maze with fixed layout but randomized spawn points and object positions.
The maze's layout is prespecified through a newline-terminated string. At
each call to `regenerate`, the spawn points and object positions are randomly
drawn from the empty cells within the specified maze layout. The number of
spawn points and object positions generated is user-specifiable, but is fixed
across calls to `regenerate`.
Optionally, the user can also constrain the spawn points and object positions
to be drawn from a predetermined set. This is done by including the spawn
and/or object tokens directly into the maze layout string. If the requested
number of spawns or objects is greater than the number of the respective
tokens present in the layout string, then additional spawns/objects are
randomly generated into the remaining empty cells in the layout string.
"""
def __init__(self, entity_layer, variations_layer=None,
num_spawns=None,
spawn_token=defaults.SPAWN_TOKEN,
num_objects=None,
object_token=defaults.OBJECT_TOKEN,
random_state=None):
"""Initializes this maze object.
Args:
entity_layer: A string specifying the layout of this maze. The lines in
this string should be of equal length, and the string should terminate
with a newline character. Maze walls are represented by the '*'
character. Optionally, candidate positions for spawn points and object
locations can be specified by adding the appropriate tokens to the
desired locations in the string. See this class' docstring for details.
variations_layer: A string specifying the variations layer for this maze.
This is used to change the visual appearance across various parts of
the maze. See the docstring for `variations_layer` property for details.
num_spawns: The total number of spawn points to be generated within this
maze. If `None`, this maze will use all spawn tokens present in the
`entity_layer` string (i.e. no randomization).
spawn_token: The character that is used to represent spawn points in this
text maze.
num_objects: The total number of object positions to be generated within
this maze. If `None`, this maze will use all object tokens present in
the `entity_layer` string (i.e. no randomization).
object_token: The character that is used to represent object locations in
this text maze.
random_state: A `numpy.random.RandomState` object.
Raises:
ValueError: If `variations_layer` is not of the same shape as
`entity_layer`, or if `spawn_token` or `object_token` is not exactly
one character long.
"""
self._entity_layer = text_grid.TextGrid(entity_layer)
if variations_layer is not None:
self._variations_layer = text_grid.TextGrid(variations_layer)
if self._variations_layer.shape != self._entity_layer.shape:
raise ValueError(
'`variations_layer` is specified, but its shape is not the same as '
'`entity_layer`: got {} vs. {}'
.format(self._variations_layer.shape, self._entity_layer.shape))
else:
self._variations_layer = self._entity_layer.copy()
self._variations_layer[:] = '.'
self._max_variations = len(set(self._variations_layer.flatten())) - 1
spawn_token = str(spawn_token)
if len(spawn_token) != 1:
raise ValueError('`spawn_token` should be a single character: '
'got {!r}'.format(spawn_token))
else:
self._spawn_token = spawn_token
object_token = str(object_token)
if len(object_token) != 1:
raise ValueError('`object_token` should be a single character: '
'got {!r}'.format(object_token))
else:
self._object_token = object_token
self._height, self._width = self._entity_layer.shape
self._random_state = random_state or np.random
self._empty_cells = []
self._required_spawns = []
self._required_objects = []
for y in range(self._height):
for x in range(self._width):
if self._entity_layer[y, x] == _EMPTY_CELL:
self._empty_cells.append((y, x))
elif self._entity_layer[y, x] == self._spawn_token:
self._required_spawns.append((y, x))
elif self._entity_layer[y, x] == self._object_token:
self._required_objects.append((y, x))
if num_spawns is not None:
self._num_spawns = num_spawns
else:
self._num_spawns = len(self._required_spawns)
if num_objects is not None:
self._num_objects = num_objects
else:
self._num_objects = len(self._required_objects)
self.regenerate()
def regenerate(self):
for (y, x) in itertools.chain(
self._empty_cells, self._required_spawns, self._required_objects):
self._entity_layer[y, x] = _EMPTY_CELL
if self._required_spawns:
chosen_spawn_indices = self._random_state.choice(
len(self._required_spawns),
min(self._num_spawns, len(self._required_spawns)), replace=False)
spawns = [self._required_spawns[i] for i in chosen_spawn_indices]
else:
spawns = []
if self._required_objects:
chosen_object_indices = self._random_state.choice(
len(self._required_objects),
min(self._num_objects, len(self._required_objects)), replace=False)
objects = [self._required_objects[i] for i in chosen_object_indices]
else:
objects = []
extra_spawns = max(0, self._num_spawns - len(self._required_spawns))
extra_objects = max(0, self._num_objects - len(self._required_objects))
if extra_spawns + extra_objects > 0:
chosen_extra_indices = self._random_state.choice(
len(self._empty_cells), extra_spawns + extra_objects, replace=False)
extras = [self._empty_cells[i] for i in chosen_extra_indices]
spawns += extras[:extra_spawns]
objects += extras[extra_spawns:]
for (y, x) in spawns:
self._entity_layer[y, x] = self._spawn_token
for (y, x) in objects:
self._entity_layer[y, x] = self._object_token
@property
def entity_layer(self):
return self._entity_layer
@property
def variations_layer(self):
return self._variations_layer
@property
def height(self):
return self._height
@property
def width(self):
return self._width
@property
def max_variations(self):
return self._max_variations
@property
def max_rooms(self):
return 1
@property
def objects_per_room(self):
return self._num_objects
@property
def spawn_token(self):
return self._spawn_token
@property
def object_token(self):
return self._object_token
| labmaze-master | labmaze/fixed_maze.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""LabMaze: DeepMind Lab's text maze generator."""
from labmaze.base import BaseMaze
from labmaze.fixed_maze import FixedMazeWithRandomGoals
from labmaze.random_maze import RandomMaze
from labmaze.text_grid import TextGrid
| labmaze-master | labmaze/__init__.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for labmaze.RandomMaze."""
import copy
from absl.testing import absltest
import labmaze
import numpy as np
class RandomMazeTest(absltest.TestCase):
"""Tests for labmaze.RandomMaze.
Tests whose name contain the word 'golden' are brittle since the output
depends on the specific implementation of various random algorithms in the C++
standard library. Each test case contains two sets of golden output data,
generated by libstdc++ and libc++.
"""
def testGolden7x9Maze(self):
maze = labmaze.RandomMaze(height=7, width=9, random_seed=12345)
expected_mazes = {('*********\n'
'*********\n'
'*********\n'
'*** ***\n'
'*** ***\n'
'*** ***\n'
'*********\n'), # libstdc++
('*********\n'
'*********\n'
'*********\n'
'* ***\n'
'* ***\n'
'* ***\n'
'*********\n'), # libc++
}
actual_maze = str(maze.entity_layer)
self.assertIn(actual_maze, expected_mazes)
np.testing.assert_array_equal(maze.entity_layer,
labmaze.TextGrid(actual_maze))
expected_variations = actual_maze.replace('*', '.').replace(' ', 'A')
self.assertEqual(str(maze.variations_layer), expected_variations)
np.testing.assert_array_equal(maze.variations_layer,
labmaze.TextGrid(expected_variations))
def testGoldenTwoRoom9x11Maze(self):
maze = labmaze.RandomMaze(height=9, width=11,
max_rooms=2, room_min_size=4, room_max_size=6,
random_seed=12345)
expected_mazes = {('***********\n'
'*** ***\n'
'*** * ***\n'
'*** * *\n'
'*** * *** *\n'
'*** * * *\n'
'*** * * *\n'
'*** *\n'
'***********\n'), # libc++
('***********\n'
'* *****\n'
'* * *****\n'
'* *\n'
'* * *\n'
'* * *\n'
'* *** *****\n'
'* *****\n'
'***********\n'), # libstdc++
('***********\n'
'* ***\n'
'* * ***\n'
'* * ***\n'
'*** * * ***\n'
'*** *\n'
'***** *\n'
'***** *\n'
'***********\n'), # MSVC14
}
self.assertIn(str(maze.entity_layer), expected_mazes)
expected_variations = {('...........\n'
'.....AAA...\n'
'.....AAA...\n'
'.....AAA...\n'
'...........\n'
'.....BBB...\n'
'.....BBB...\n'
'.....BBB...\n'
'...........\n'), # libstdc++
('...........\n'
'.AAA.......\n'
'.AAA.......\n'
'.AAA.BBBBB.\n'
'.AAA.BBBBB.\n'
'.AAA.BBBBB.\n'
'...........\n'
'...........\n'
'...........\n'), # libc++
('...........\n'
'.AAAAA.....\n'
'.AAAAA.....\n'
'.AAAAA.....\n'
'...........\n'
'.....BBBBB.\n'
'.....BBBBB.\n'
'.....BBBBB.\n'
'...........\n'), # MSVC14
}
self.assertIn(str(maze.variations_layer), expected_variations)
def testRegenerate(self):
maze = labmaze.RandomMaze(height=51, width=31,
max_rooms=5, room_min_size=10, room_max_size=20,
random_seed=12345)
old_maze, old_variations = None, None
for _ in range(5):
maze.regenerate()
if old_maze is not None:
self.assertNotEqual(str(maze.entity_layer), str(old_maze))
self.assertTrue(np.any(maze.entity_layer != old_maze))
self.assertNotEqual(str(maze.variations_layer), str(old_variations))
self.assertTrue(np.any(maze.variations_layer != old_variations))
old_maze = copy.deepcopy(maze.entity_layer)
old_variations = copy.deepcopy(maze.variations_layer)
def testGoldenMazeRegeneration(self):
# This test makes sure that regeneration logic is not operating on an
# old, dirty maze object.
maze = labmaze.RandomMaze(height=17, width=17,
max_rooms=9, room_min_size=3, room_max_size=3,
random_seed=12345)
expected_mazes = {('*****************\n'
'* ***** ***\n'
'* ***** *** ***\n'
'* *** *\n'
'*** *** ***** *\n'
'* * * *\n'
'* * * * *** *\n'
'* * *\n'
'* * * * * * * ***\n'
'* * *\n'
'* * * * * *\n'
'* * * * *\n'
'* ***** *** * * *\n'
'* * * *\n'
'***** * * * *\n'
'***** * *\n'
'*****************\n'), # libstdc++
('*****************\n'
'*** *\n'
'*** *********** *\n'
'*** * * *\n'
'*** * * * * *\n'
'* * * * *\n'
'* ***** ***** *\n'
'* *** *\n'
'*** *** * ***** *\n'
'* * * * * *\n'
'* * * * * *\n'
'* * * *\n'
'*** *** * * * * *\n'
'* *** * *\n'
'* *** * * *\n'
'* * *\n'
'*****************\n'), # libc++
('*****************\n'
'********* *\n'
'********* ***** *\n'
'* ***** * *\n'
'* ***** * * *\n'
'* * * *\n'
'* ************* *\n'
'* * *\n'
'* * *** * ***\n'
'* * *\n'
'* ***** * *** *\n'
'* *** *\n'
'* * ***** *** *\n'
'* * *\n'
'* *** * * *\n'
'* * *\n'
'*****************\n'), # MSVC14
}
self.assertIn(str(maze.entity_layer), expected_mazes)
maze.regenerate()
expected_mazes_2 = {('*****************\n'
'*** * *\n'
'*** * * * *\n'
'* * * *\n'
'* * *** ******* *\n'
'* * * *** *\n'
'* * * *** *** *\n'
'* * * * *\n'
'* * * * * * * *\n'
'* * * * *\n'
'* * *** ***** *\n'
'* * *\n'
'*** * * ***** *\n'
'* * * *\n'
'* ***** * ***\n'
'* * ***\n'
'*****************\n'), # libstdc++
('*****************\n'
'********* *****\n'
'********* *****\n'
'* * *\n'
'* * * *** *** *\n'
'* * * * *\n'
'* ***** * * *\n'
'* * *\n'
'* *** ***** *** *\n'
'* * *\n'
'* * * * *\n'
'* * * *\n'
'* * * * * *** ***\n'
'* ***\n'
'*** ***********\n'
'*** ***********\n'
'*****************\n'), # libc++
('*****************\n'
'* *****\n'
'* * *** *****\n'
'* *\n'
'*** * * ***** *\n'
'* * * *\n'
'* ***** *** * *\n'
'* *\n'
'* * * *** * * *\n'
'* * * * *\n'
'* * * * * * *\n'
'* * * *\n'
'* * * * * *** *\n'
'* * * *\n'
'* * *** * *****\n'
'* * *****\n'
'*****************\n'), # MSVC14
}
self.assertIn(str(maze.entity_layer), expected_mazes_2)
def testInvalidArguments(self):
with self.assertRaisesRegexp(ValueError, 'height.*integer'):
labmaze.RandomMaze(height=2.5)
with self.assertRaisesRegexp(ValueError, 'height.*positive'):
labmaze.RandomMaze(height=-3)
with self.assertRaisesRegexp(ValueError, 'height.*odd'):
labmaze.RandomMaze(height=4)
with self.assertRaisesRegexp(ValueError, 'width.*integer'):
labmaze.RandomMaze(width=1.25)
with self.assertRaisesRegexp(ValueError, 'width.*positive'):
labmaze.RandomMaze(width=-5)
with self.assertRaisesRegexp(ValueError, 'width.*odd'):
labmaze.RandomMaze(width=2)
with self.assertRaisesRegexp(ValueError, 'room_min_size.*integer'):
labmaze.RandomMaze(room_min_size=3.3)
with self.assertRaisesRegexp(ValueError, 'room_min_size.*positive'):
labmaze.RandomMaze(room_min_size=-1)
with self.assertRaisesRegexp(ValueError, 'room_max_size.*integer'):
labmaze.RandomMaze(room_max_size=4.4)
with self.assertRaisesRegexp(ValueError, 'room_max_size.*positive'):
labmaze.RandomMaze(room_max_size=-2)
with self.assertRaisesRegexp(
ValueError, 'room_min_size.*less than or equal to.*room_max_size'):
labmaze.RandomMaze(room_min_size=4, room_max_size=3)
with self.assertRaisesRegexp(ValueError, 'retry_count.*integer'):
labmaze.RandomMaze(retry_count=5.4)
with self.assertRaisesRegexp(ValueError, 'retry_count.*positive'):
labmaze.RandomMaze(retry_count=-7)
with self.assertRaisesRegexp(
ValueError, 'extra_connection_probability.*between 0.0 and 1.0'):
labmaze.RandomMaze(extra_connection_probability=1.1)
with self.assertRaisesRegexp(ValueError, 'max_variations.*integer'):
labmaze.RandomMaze(max_variations=6.7)
with self.assertRaisesRegexp(
ValueError, 'max_variations.*between 0 and 26'):
labmaze.RandomMaze(max_variations=27)
with self.assertRaisesRegexp(ValueError, 'spawn_token.*single character'):
labmaze.RandomMaze(spawn_token='foo')
with self.assertRaisesRegexp(ValueError, 'object_token.*single character'):
labmaze.RandomMaze(object_token='bar')
if __name__ == '__main__':
absltest.main()
| labmaze-master | labmaze/random_maze_test.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Default constants for LabMaze."""
from labmaze.cc.python._defaults import * # pylint: disable=wildcard-import
| labmaze-master | labmaze/defaults.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Randomly generated text mazes."""
from labmaze import base
from labmaze import defaults
from labmaze import text_grid
from labmaze.cc.python import _random_maze
import numpy as np
class RandomMaze(base.BaseMaze):
"""A random text maze generated by DeepMind Lab's maze generator."""
def __init__(
self, height=11, width=11,
max_rooms=defaults.MAX_ROOMS,
room_min_size=defaults.ROOM_MIN_SIZE,
room_max_size=defaults.ROOM_MAX_SIZE,
retry_count=defaults.RETRY_COUNT,
extra_connection_probability=defaults.EXTRA_CONNECTION_PROBABILITY,
max_variations=defaults.MAX_VARIATIONS,
has_doors=defaults.HAS_DOORS,
simplify=defaults.SIMPLIFY,
spawns_per_room=defaults.SPAWN_COUNT,
spawn_token=defaults.SPAWN_TOKEN,
objects_per_room=defaults.OBJECT_COUNT,
object_token=defaults.OBJECT_TOKEN, random_seed=None):
if height != int(height) or height < 0 or height % 2 == 0:
raise ValueError(
'`height` should be a positive odd integer: got {!r}'.format(height))
if width != int(width) or width < 0 or width % 2 == 0:
raise ValueError(
'`width` should be a positive odd integer: got {!r}'.format(width))
if room_min_size != int(room_min_size) or room_min_size < 0:
raise ValueError('`room_min_size` should be a positive integer: '
'got {!r}'.format(room_min_size))
if room_max_size != int(room_max_size) or room_max_size < 0:
raise ValueError('`room_max_size` should be a positive integer: '
'got {!r}'.format(room_max_size))
if room_min_size > room_max_size:
raise ValueError(
'`room_min_size` should be less than or equal to `room_max_size`: '
'got room_min_size={!r} and room_max_size={!r}'
.format(room_min_size, room_max_size))
if retry_count != int(retry_count) or retry_count < 0:
raise ValueError('`retry_count` should be a positive integer: '
'got {!r}'.format(retry_count))
if extra_connection_probability < 0 or extra_connection_probability > 1:
raise ValueError(
'`extra_connection_probability` should be between 0.0 and 1.0: '
'got {!r}'.format(extra_connection_probability))
if (max_variations != int(max_variations)
or max_variations < 0 or max_variations > 26):
raise ValueError(
'`max_variations` should be an integer between 0 and 26: '
'got {!r}'.format(max_variations))
spawn_token = str(spawn_token)
if len(spawn_token) != 1:
raise ValueError('`spawn_token` should be a single character: '
'got {!r}'.format(spawn_token))
object_token = str(object_token)
if len(object_token) != 1:
raise ValueError('`object_token` should be a single character: '
'got {!r}'.format(object_token))
if random_seed is None:
random_seed = np.random.randint(2147483648) # 2**31
self._height = height
self._width = width
self._max_rooms = max_rooms
self._room_min_size = room_min_size
self._room_max_size = room_max_size
self._max_variations = max_variations
self._spawns_per_room = spawns_per_room
self._spawn_token = spawn_token
self._objects_per_room = objects_per_room
self._object_token = object_token
self._native_maze = _random_maze.RandomMaze(
height=height, width=width, max_rooms=max_rooms,
room_min_size=room_min_size, room_max_size=room_max_size,
retry_count=retry_count,
extra_connection_probability=extra_connection_probability,
max_variations=max_variations,
has_doors=has_doors, simplify=simplify,
spawns_per_room=spawns_per_room, spawn_token=spawn_token,
objects_per_room=objects_per_room, object_token=object_token,
random_seed=random_seed)
self._entity_layer = text_grid.TextGrid(self._native_maze.entity_layer)
self._variations_layer = (
text_grid.TextGrid(self._native_maze.variations_layer))
def regenerate(self):
self._native_maze.regenerate()
self._entity_layer = text_grid.TextGrid(self._native_maze.entity_layer)
self._variations_layer = (
text_grid.TextGrid(self._native_maze.variations_layer))
@property
def entity_layer(self):
return self._entity_layer
@property
def variations_layer(self):
return self._variations_layer
@property
def height(self):
return self._height
@property
def width(self):
return self._width
@property
def max_rooms(self):
return self._max_rooms
@property
def room_min_size(self):
return self._room_min_size
@property
def room_max_size(self):
return self._room_max_size
@property
def max_variations(self):
return self._max_variations
@property
def spawns_per_room(self):
return self._spawns_per_room
@property
def spawn_token(self):
return self._spawn_token
@property
def objects_per_room(self):
return self._objects_per_room
@property
def object_token(self):
return self._object_token
| labmaze-master | labmaze/random_maze.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Text mazes generated by DeepMind Lab's maze generator."""
import abc
from labmaze import defaults
class BaseMaze(metaclass=abc.ABCMeta):
"""A abstract base class for DeepMind Lab-style text mazes."""
def regenerate(self):
"""Regenerates the maze if required."""
pass
@abc.abstractproperty
def entity_layer(self):
"""The entity layer of the current maze.
The entity layer defines the actual structure of the maze, i.e. which cells
are vacant and which are occupied by walls. For further explanation, see:
https://github.com/deepmind/lab/blob/master/docs/developers/creating_levels/text_level.md#text-level-format
Returns:
A 2-dimensional NumPy array of printable characters.
"""
@abc.abstractproperty
def variations_layer(self):
"""The variations layer of the current maze.
The variations layer defines the variations in decorative aspects of each
cell in the maze. Each variation is assigned a different character (DeepMind
Lab uses '.' for default styling, and A-Z for variations) For further
explanation, see:
https://github.com/deepmind/lab/blob/master/docs/developers/creating_levels/text_level.md.md#text-level-format
Returns:
A 2-dimensional NumPy array of printable characters.
"""
@abc.abstractproperty
def height(self):
"""The number of cells along the y-direction of this maze."""
@abc.abstractproperty
def width(self):
"""The number of cells along the x-direction of this maze."""
@property
def max_variations(self):
"""The maximum number of variations in the variations layer of this maze."""
@property
def spawn_token(self):
return defaults.SPAWN_TOKEN
@property
def object_token(self):
return defaults.OBJECT_TOKEN
| labmaze-master | labmaze/base.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for labmaze.TextGrid."""
import copy
from absl.testing import absltest
import labmaze
import numpy as np
class TextGridTest(absltest.TestCase):
def testConstruction(self):
original_string = 'abcd\nefgh\nijkl\n'
maze = labmaze.TextGrid(original_string)
self.assertEqual(str(maze), original_string)
self.assertEqual(maze.shape, (3, 4))
expected_array = [['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h'],
['i', 'j', 'k', 'l']]
np.testing.assert_array_equal(maze, expected_array)
# Test that iteration works.
for actual_row, expected_row in zip(maze, expected_array):
for actual_col, expected_col in zip(actual_row, expected_row):
self.assertEqual(actual_col.strip(), expected_col.strip())
# Test that indexed access works.
height = len(expected_array)
width = len(expected_array[0])
for y in range(height):
for x in range(width):
self.assertEqual(maze[y, x].strip(), expected_array[y][x].strip())
def testAssignment(self):
original_string = 'abcd\nefgh\nijkl\n'
maze = labmaze.TextGrid(original_string)
maze[:2, :2] = '#'
expected_string = '##cd\n##gh\nijkl\n'
expected_array = [['#', '#', 'c', 'd'],
['#', '#', 'g', 'h'],
['i', 'j', 'k', 'l']]
self.assertEqual(str(maze), expected_string)
np.testing.assert_array_equal(maze, expected_array)
def testCopying(self):
original_string = '1234\n5678\n'
maze = labmaze.TextGrid(original_string)
copied = copy.copy(maze)
self.assertEqual(type(maze), type(copied))
self.assertEqual(str(maze), str(copied))
np.testing.assert_array_equal(maze, copied)
deepcopied = copy.deepcopy(maze)
self.assertEqual(type(maze), type(deepcopied))
self.assertEqual(str(maze), str(deepcopied))
np.testing.assert_array_equal(maze, deepcopied)
if __name__ == '__main__':
absltest.main()
| labmaze-master | labmaze/text_grid_test.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
| labmaze-master | labmaze/cc/__init__.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
| labmaze-master | labmaze/cc/python/__init__.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""LabMaze texture assets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import sys
ROOT_DIR = sys.modules[__name__].__path__[0]
SKY_STYLES = ('sky_01', 'sky_02', 'sky_03')
SkyBox = collections.namedtuple(
'SkyBox', ('left', 'right', 'up', 'down', 'front', 'back'))
def get_sky_texture_paths(style):
if style not in SKY_STYLES:
raise ValueError('`style` should be one of {}: got {!r}'.format(
SKY_STYLES, style))
return SkyBox(left=os.path.join(ROOT_DIR, style, 'lf.png'),
right=os.path.join(ROOT_DIR, style, 'rt.png'),
up=os.path.join(ROOT_DIR, style, 'up.png'),
down=os.path.join(ROOT_DIR, style, 'dn.png'),
front=os.path.join(ROOT_DIR, style, 'ft.png'),
back=os.path.join(ROOT_DIR, style, 'bk.png'))
MAZE_STYLES = ('style_01', 'style_02', 'style_03', 'style_04', 'style_05')
WALL_TEXTURES = {
'style_01': ('blue', 'cerise', 'green_bright', 'green', 'purple',
'red_bright', 'red', 'yellow'),
'style_02': ('blue_bright', 'blue', 'dblue', 'lgreen', 'purple',
'yellow_bright', 'yellow'),
'style_03': ('blue', 'cyan', 'gray_bright', 'gray',
'orange_bright', 'orange', 'purple'),
'style_04': ('cerise', 'green_bright', 'green', 'purple',
'red_bright', 'red'),
'style_05': ('red_bright', 'red', 'yellow_bright', 'yellow')
}
def get_wall_texture_paths(style):
if style not in MAZE_STYLES:
raise ValueError('`style` should be one of {}: got {!r}'.format(
MAZE_STYLES, style))
return {name: os.path.join(ROOT_DIR, style, 'wall_{:s}_d.png'.format(name))
for name in WALL_TEXTURES[style]}
FLOOR_TEXTURES = {
'style_01': ('blue_bright', 'blue', 'blue_team', 'orange_bright', 'orange',
'red_team'),
'style_02': ('blue_bright', 'blue', 'green_bright', 'green', 'orange'),
'style_03': ('blue_bright', 'blue', 'green_bright', 'green', 'orange',
'purple', 'red'),
'style_04': ('blue_bright', 'blue', 'cyan', 'dorange', 'orange_bright',
'orange'),
'style_05': ('blue_bright', 'blue', 'orange_bright', 'orange')
}
def get_floor_texture_paths(style):
if style not in MAZE_STYLES:
raise ValueError('`style` should be one of {}: got {!r}'.format(
MAZE_STYLES, style))
return {name: os.path.join(ROOT_DIR, style, 'floor_{:s}_d.png'.format(name))
for name in FLOOR_TEXTURES[style]}
| labmaze-master | labmaze/assets/__init__.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for labmaze.assets."""
from absl.testing import absltest
from labmaze import assets
# DO NOT REMOVE THIS LINE -- COPYBARA: from google_internal import resources
def get_file_contents(path):
with open(path, 'rb') as f:
return f.read()
class AssetsTest(absltest.TestCase):
def testHasSkyTextures(self):
for style in assets.SKY_STYLES:
texture_paths = assets.get_sky_texture_paths(style)
self.assertTrue(get_file_contents(texture_paths.left))
self.assertTrue(get_file_contents(texture_paths.right))
self.assertTrue(get_file_contents(texture_paths.up))
self.assertTrue(get_file_contents(texture_paths.down))
self.assertTrue(get_file_contents(texture_paths.front))
self.assertTrue(get_file_contents(texture_paths.back))
def testHasWallTextures(self):
for style in assets.MAZE_STYLES:
texture_paths = assets.get_wall_texture_paths(style)
for texture_name in assets.WALL_TEXTURES[style]:
self.assertTrue(get_file_contents(texture_paths[texture_name]))
def testHasFloorTextures(self):
for style in assets.MAZE_STYLES:
texture_paths = assets.get_floor_texture_paths(style)
for texture_name in assets.FLOOR_TEXTURES[style]:
self.assertTrue(get_file_contents(texture_paths[texture_name]))
if __name__ == '__main__':
absltest.main()
| labmaze-master | labmaze/assets/assets_test.py |
# Copyright 2021 DeepMind Technologies Limited and Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Class which gives gan grads with explicit regularization."""
import functools
import jax
import jax.numpy as jnp
from dd_two_player_games import drift_utils
from dd_two_player_games import gan
from dd_two_player_games import utils
def explicit_regularization_grads(
regularizer_fns, coeffs,
params, state, data_batch, rng, is_training, attr_name):
"""Accumulate explicit regularization gradients."""
player_regularizer_fns = getattr(regularizer_fns, attr_name)
player_coeffs = getattr(coeffs, attr_name)
assert isinstance(
player_regularizer_fns, drift_utils.PlayerRegularizationTerms)
assert isinstance(
player_coeffs, drift_utils.PlayerRegularizationTerms)
reg_args = (params, state, data_batch, rng, is_training)
accumulator = jax.tree_map(jnp.zeros_like, getattr(params, attr_name))
for grad_reg_fn, coeff in zip(player_regularizer_fns, player_coeffs):
accumulator = utils.add_trees_with_coeff(
acc=accumulator,
mul=grad_reg_fn(*reg_args),
coeff=coeff)
return accumulator, utils.any_non_zero(player_coeffs)
class GANGradsCalculator(object):
"""Utility class to compute GAN gradients with explicit regularization."""
def __init__(self, gan_model, estimator_fn, use_pmean=True):
super(GANGradsCalculator, self).__init__()
self._gan = gan_model
self._estimator_fn = estimator_fn
self._use_pmean = use_pmean
self._maybe_pmean = jax.lax.pmean if use_pmean else lambda x, axis_name: x
@property
def regularisation_grad_fns(self):
"""Create the regularisation functions."""
disc_reg_grad_fns = drift_utils.PlayerRegularizationTerms(
self_norm=self.disc_grads_disc_norm,
other_norm=self.disc_grads_gen_norm,
other_dot_prod=self.disc_grads_gen_dot_prod)
gen_reg_grad_fns = drift_utils.PlayerRegularizationTerms(
self_norm=self.gen_grads_gen_norm,
other_norm=self.gen_grads_disc_norm,
other_dot_prod=self.gen_grads_disc_dot_prod)
return gan.GANTuple(disc=disc_reg_grad_fns, gen=gen_reg_grad_fns)
@property
def disc_grads_disc_norm(self):
return self._estimator_fn(
self._gan.disc_loss_fn_disc_grads,
self._gan.disc_loss_fn_disc_grads,
'disc')
@property
def disc_grads_gen_norm(self):
return self._estimator_fn(
self._gan.gen_loss_fn_gen_grads,
self._gan.gen_loss_fn_gen_grads,
'disc')
@property
def disc_grads_gen_dot_prod(self):
# Note: order matters due to the stop grad.
return self._estimator_fn(
self._gan.disc_loss_fn_gen_grads,
self._gan.gen_loss_fn_gen_grads,
'disc')
@property
def gen_grads_gen_norm(self):
return self._estimator_fn(
self._gan.gen_loss_fn_gen_grads,
self._gan.gen_loss_fn_gen_grads,
'gen')
@property
def gen_grads_disc_norm(self):
return self._estimator_fn(
self._gan.disc_loss_fn_disc_grads,
self._gan.disc_loss_fn_disc_grads,
'gen')
@property
def gen_grads_disc_dot_prod(self):
# Note: order matters due to the stop grad.
return self._estimator_fn(
self._gan.gen_loss_fn_disc_grads,
self._gan.disc_loss_fn_disc_grads,
'gen')
@functools.partial(jax.jit, static_argnums=(0, 5, 6))
def disc_grads(
self, params, state, data_batch, rng_disc, is_training, coeffs):
"""Compute discriminator gradients."""
disc_loss_grads, disc_gan_loss_aux = jax.grad(
self._gan.disc_loss, has_aux=True)(
params, state, data_batch, rng_disc, is_training)
disc_loss_grads = disc_loss_grads.disc
disc_reg_grads, non_zero_coeff = self.disc_explicit_regularization_grads(
params, state, data_batch, rng_disc, is_training, coeffs)
disc_grads = utils.add_trees_with_coeff(
acc=disc_loss_grads,
mul=disc_reg_grads,
coeff=non_zero_coeff)
disc_grads = self._maybe_pmean(disc_grads, axis_name='i')
return disc_grads, disc_gan_loss_aux
@functools.partial(jax.jit, static_argnums=(0, 5, 6))
def gen_grads(
self, params, state, data_batch, rng_gen, is_training, coeffs):
"""Compute generator gradients."""
gen_loss_grads, gen_gan_loss_aux = jax.grad(
self._gan.gen_loss, has_aux=True)(
params, state, data_batch, rng_gen, is_training)
gen_loss_grads = gen_loss_grads.gen
gen_reg_grads, non_zero_coeff = self.gen_explicit_regularization_grads(
params, state, data_batch, rng_gen, is_training, coeffs)
gen_grads = utils.add_trees_with_coeff(
acc=gen_loss_grads,
mul=gen_reg_grads,
coeff=non_zero_coeff)
gen_grads = self._maybe_pmean(gen_grads, axis_name='i')
return gen_grads, gen_gan_loss_aux
def disc_explicit_regularization_grads(
self, params, state, data_batch, rng_disc, is_training, coeffs):
return explicit_regularization_grads(
self.regularisation_grad_fns, coeffs,
params, state, data_batch, rng_disc, is_training, 'disc')
def gen_explicit_regularization_grads(
self, params, state, data_batch, rng_gen, is_training, coeffs):
return explicit_regularization_grads(
self.regularisation_grad_fns, coeffs,
params, state, data_batch, rng_gen, is_training, 'gen')
def both_player_grads(
self, params, state, disc_data_batch, gen_data_batch,
rng_disc, rng_gen, is_training, exp_reg_coeffs):
"""Compute the gradients for both players and return them as a GANTuple."""
disc_grads, disc_aux = self.disc_grads(
params, state, disc_data_batch, rng_disc, is_training,
exp_reg_coeffs)
gen_grads, gen_aux = self.gen_grads(
params, state, gen_data_batch, rng_gen, is_training,
exp_reg_coeffs)
grads = gan.GANTuple(disc=disc_grads, gen=gen_grads)
aux = gan.GANTuple(disc=disc_aux, gen=gen_aux)
return grads, aux
| discretisation_drift-main | dd_two_player_games/gan_grads_calculator.py |
# Copyright 2021 DeepMind Technologies Limited and Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model utilities."""
import collections
import immutabledict
import jax
class Sampler(object):
"""Sampler used for obtaining evaluation metric."""
def __init__(self, model, params, state, pmap=True):
self.model = model
self.params = params
self.state = state
self.pmap = pmap
def sample_batch(self, batch_size, rng):
gen_kwargs = immutabledict.immutabledict(
collections.OrderedDict([('is_training', False),
('test_local_stats', False)]))
sample_fn = self.model.sample
if self.pmap:
sample_fn = jax.pmap(
sample_fn, axis_name='i', static_broadcasted_argnums=(3, 4))
return sample_fn(
self.params.gen, self.state.players.gen, rng, batch_size, gen_kwargs)[0]
| discretisation_drift-main | dd_two_player_games/model_utils.py |
# Copyright 2021 DeepMind Technologies Limited and Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Code to glue together the two GAN players."""
import collections
import functools
import haiku as hk
import immutabledict
import jax
import jax.numpy as jnp
GANTuple = collections.namedtuple('GANTuple', ['disc', 'gen'])
GANPenalty = collections.namedtuple('GANPenalty', ['fn', 'coeff'])
GANState = collections.namedtuple('GANState', ['players', 'param_transforms'])
GANLossAux = collections.namedtuple(
'GANLossAux', ['state', 'log_dict', 'loss_components'])
def get_player_fn(player, player_kwargs):
def player_fn(*args, **kwargs):
return player(**player_kwargs)(*args, **kwargs)
return player_fn
def filter_out_new_training_state(new_state, old_state):
"""Keeps only the training state from the old state.
The training state is defined as anything that will be used
during training time. All the state used at training time will be taken
from `old_state`, while states needed for evaluation (such as batch norm
statistics), will be kept from `new_state`.
Filtering states this way allows us to have the best evaluation statistics
while not leaking updates between the two players.
Args:
new_state: Dict composing of the new states (module_name to state).
old_state: Dict composing of the old states (module_name to state).
Returns:
The resulting state after choosing components from old_state and new_state
based on their interaction with training.
"""
assert new_state.keys() == old_state.keys()
out = collections.defaultdict(dict)
for module_name in new_state.keys():
if 'batch_norm' in module_name:
out[module_name] = new_state[module_name]
else:
out[module_name] = old_state[module_name]
return hk.data_structures.to_haiku_dict(out)
class GAN:
"""A module which applies the relevant losses to the disc and generator."""
def __init__(
self, players_hk, losses, penalties,
player_param_transformers, players_kwargs, num_latents):
"""Initialises the module.
Args:
players_hk: A GANTuple containing the haiku module constructors to be
passed to `hk.transform_with_state`. The discriminator is assumed to
produce the right output which can then be passed into the corresponding
losses.
losses: A GANTuple containing the losses used to train the model.
The current API assumes that losses both for the discriminator and
generator are of the form:
```def loss(discriminator_real_output, discriminator_sample_output):
...
return loss
```
where `discriminator_real_output`, `discriminator_sample_output` are
the discriminator output on real data and fake data respectively.
The loss returned is a jax scalar.
penalties: A GANTuple containing optional GANPenalty that can be used
for training. If no penalty should be used for one of the players, pass
None.
player_param_transformers: A GANTuple containing parameter transformers
that are applied before a forward pass of the players.
players_kwargs: A GANTuple containing the keyword args to build the two
players.
num_latents: Integer, the number of latents used.
"""
# Define the Haiku network transforms.
gen_transform = hk.without_apply_rng(
hk.transform_with_state(
get_player_fn(players_hk.gen, players_kwargs.gen)))
disc_transform = hk.without_apply_rng(
hk.transform_with_state(
get_player_fn(players_hk.disc, players_kwargs.disc)))
if player_param_transformers.disc:
self._disc_param_transform = hk.without_apply_rng(
hk.transform_with_state(
get_player_fn(player_param_transformers.disc, {})))
else:
self._disc_param_transform = None
self._transforms = GANTuple(disc=disc_transform, gen=gen_transform)
self._penalties = penalties
self._losses = losses
self._num_latents = num_latents
def initial_params(self, rng, batch):
"""Returns the initial parameters."""
# Generate dummy latents for the generator.
dummy_latents = jnp.zeros((batch.shape[0], self._num_latents))
# Get initial network parameters.
rng_gen, rng_disc, rng_disc_transform = jax.random.split(rng, 3)
gen_init_params, gen_init_state = self._transforms.gen.init(
rng_gen, dummy_latents)
disc_init_params, disc_init_state = self._transforms.disc.init(
rng_disc, batch)
init_params = GANTuple(gen=gen_init_params, disc=disc_init_params)
init_players_state = GANTuple(gen=gen_init_state, disc=disc_init_state)
if self._disc_param_transform:
_, init_disc_params_transform_state = self._disc_param_transform.init(
rng_disc_transform, init_params.disc)
else:
init_disc_params_transform_state = None
init_param_transforms_states = GANTuple(
disc=init_disc_params_transform_state, gen=None)
init_state = GANState(
players=init_players_state,
param_transforms=init_param_transforms_states)
return init_params, init_state
@functools.partial(jax.jit, static_argnums=(0, 4, 5))
def sample(self, gen_params, gen_state, rng, num_samples, gen_kwargs):
"""Generates images from noise latents."""
latents = jax.random.normal(rng, shape=(num_samples, self._num_latents))
return self._transforms.gen.apply(
gen_params, gen_state, latents, **gen_kwargs)
@functools.partial(jax.jit, static_argnums=(0, 4, 5))
def disc_forward(self, disc_params, state, disc_inputs, is_training,
update_stats):
"""Discriminator forward pass with optional parameter transform."""
if self._disc_param_transform:
disc_params, disc_params_transform_state = self._disc_param_transform.apply(
{}, state.param_transforms.disc, disc_params,
update_stats=update_stats)
else:
disc_params_transform_state = ()
disc_outputs, disc_state = self._transforms.disc.apply(
disc_params, state.players.disc, disc_inputs, is_training)
return disc_outputs, disc_state, disc_params, disc_params_transform_state
@functools.partial(jax.jit, static_argnums=(0, 5))
def disc_loss(self, params, state, data_batch, rng, is_training):
"""Compute discriminator loss. Only updates the discriminator state."""
num_data = data_batch.shape[0]
gen_kwargs = immutabledict.immutabledict(
collections.OrderedDict([('is_training', is_training)]))
samples, gen_state = self.sample(
params.gen, state.players.gen, rng, num_data, gen_kwargs)
# Update the part of the state which is used for evaluation, not training.
# During training we do not want to have the players update each others'
# state.
# For example, we can update BatchNorm state since this is not used in
# training, but we do not want to update SpectralNormalization state.
gen_state = filter_out_new_training_state(gen_state, state.players.gen)
# We merge the inputs to the discriminator and do it one pass in order
# to ensure that we update the discriminator state only once and that
# the real data and fake data obtain the same state.
disc_inputs = jnp.concatenate((data_batch, samples), axis=0)
(disc_outputs, disc_state,
new_disc_params, disc_params_transform_state) = self.disc_forward(
params.disc, state, disc_inputs, is_training, is_training)
data_disc_output, samples_disc_output = jnp.split(
disc_outputs, [data_batch.shape[0],], axis=0)
loss, loss_components = self._losses.disc(
data_disc_output, samples_disc_output)
if self._penalties.disc:
penalty_fn = self._penalties.disc.fn
penalty_coeff = self._penalties.disc.coeff
def disc_apply(x):
# Note: we do not update the state from the penalty run.
return self._transforms.disc.apply(
new_disc_params, disc_state, x, is_training)[0]
loss += penalty_coeff * penalty_fn(disc_apply, rng, data_batch, samples)
player_states = GANTuple(gen=gen_state, disc=disc_state)
param_transforms_states = state.param_transforms._replace(
disc=disc_params_transform_state)
state = GANState(players=player_states,
param_transforms=param_transforms_states)
logged_dict = {'disc_loss': loss}
aux = GANLossAux(
state=state, log_dict=logged_dict, loss_components=loss_components)
return loss, aux
@functools.partial(jax.jit, static_argnums=(0, 5))
def gen_loss(self, params, state, data_batch, rng, is_training):
"""Compute generator loss. Only updates generator state."""
num_data = data_batch.shape[0]
gen_kwargs = immutabledict.immutabledict(
collections.OrderedDict([('is_training', is_training)]))
samples, gen_state = self.sample(
params.gen, state.players.gen, rng, num_data, gen_kwargs)
# We merge the inputs to the discriminator and do it one pass in order
# to ensure that we update the discriminator state only once and that
# the real data and fake data obtain the same state.
disc_inputs = jnp.concatenate((data_batch, samples), axis=0)
# Set is_training to the given values for the discriminator in case it has
# state that changes during training. We pass update_stats to be False since
# we do not want to update the discriminator parameter transformers in
# the generator forward pass.
(disc_outputs, disc_state, _, _) = self.disc_forward(
params.disc, state, disc_inputs, is_training, False)
data_disc_output, samples_disc_output = jnp.split(
disc_outputs, [data_batch.shape[0],], axis=0)
# Update the part of the state which is used for evaluation, not training.
# During training we do not want to have the players update each others'
# state.
# For example, we can update BatchNorm state since this is not used in
# training, but we do not want to update SpectralNormalization state.
disc_state = filter_out_new_training_state(disc_state, state.players.disc)
player_states = GANTuple(gen=gen_state, disc=disc_state)
# No change to param transforms.
state = state._replace(players=player_states)
loss, loss_components = self._losses.gen(
data_disc_output, samples_disc_output)
logged_dict = {'gen_loss': loss}
aux = GANLossAux(
state=state, log_dict=logged_dict, loss_components=loss_components)
return loss, aux
@property
def disc_loss_grad_fn(self):
return jax.grad(lambda *args: self.disc_loss(*args)[0])
@property
def gen_loss_grad_fn(self):
return jax.grad(lambda *args: self.gen_loss(*args)[0])
def disc_loss_fn_disc_grads(self, *args):
"""Computes discriminator loss gradients wrt to discriminator params."""
return self.disc_loss_grad_fn(*args).disc
def disc_loss_fn_gen_grads(self, *args):
"""Computes discriminator loss gradients wrt to generator params."""
return self.disc_loss_grad_fn(*args).gen
def gen_loss_fn_disc_grads(self, *args):
"""Computes generator loss gradients wrt to discriminator params."""
return self.gen_loss_grad_fn(*args).disc
def gen_loss_fn_gen_grads(self, *args):
"""Computes loss loss gradients wrt to generator params."""
return self.gen_loss_grad_fn(*args).gen
@property
def disc_loss_components(self):
return lambda *args: self.disc_loss(*args)[1].loss_components
@property
def gen_loss_components(self):
return lambda *args: self.gen_loss(*args)[1].loss_components
| discretisation_drift-main | dd_two_player_games/gan.py |
# Copyright 2021 DeepMind Technologies Limited and Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Config for training GANs using Adam as a baseline."""
from jaxline import base_config
from ml_collections import config_dict
def get_config():
"""Return config object for training."""
config = base_config.get_base_config()
## Experiment config.
config.experiment_kwargs = config_dict.ConfigDict(
dict(
config=dict(
random_seed=0,
dataset='cifar10',
data_processor='ImageProcessor',
optimizers=dict(
discriminator=dict(
name='adam',
lr=1e-4,
kwargs=dict(
b1=0.5,
b2=0.999)),
generator=dict(
name='adam',
lr=1e-4,
kwargs=dict(
b1=0.5,
b2=0.999)),
),
nets=dict( # See `nets.py`
discriminator='CifarDiscriminator',
disc_kwargs=dict(),
generator='CifarGenerator',
gen_kwargs=dict(),
),
losses=dict( # See `losses.py`
discriminator='discriminator_goodfellow_loss',
generator='generator_saturating_loss',
),
penalties=dict( # See `losses.py`
discriminator=None,
generator=None,
),
param_transformers=dict( # See `nets.py`
# discriminator='spectral_norm',
discriminator='no_op',
generator=None,
),
training=dict(
simultaneous_updates=False,
runge_kutta_updates=False,
estimator_fn='unbiased_estimate_fn_lowest_variance',
# One of: disc_first, gen_first.
alternating_player_order='disc_first',
batch_size=128,
rk_disc_regularizer_weight_coeff=0.,
grad_regularizes=dict(
dd_coeffs_multiplier=dict(
disc=dict(
self_norm=0.0,
other_norm=0.0,
other_dot_prod=0.0,
),
gen=dict(
self_norm=0.0,
other_norm=0.0,
other_dot_prod=0.0,
)),
explicit_non_dd_coeffs=dict(
disc=dict(
self_norm=0.0,
other_norm=0.0,
other_dot_prod=0.0,
),
gen=dict(
self_norm=0.0,
other_norm=0.0,
other_dot_prod=0.0,
))),
num_gen_updates=1,
num_disc_updates=1,
num_latents=128),
eval=dict(
run_image_metrics=True,
batch_size=16,
# The number of data/sample splits to be used for evaluation.
num_eval_splits=5,
num_inception_images=10000),
)))
## Training loop config.
config.interval_type = 'steps'
config.training_steps = int(6e5)
config.log_tensors_interval = 100
config.save_checkpoint_interval = 100
config.train_checkpoint_all_hosts = False
# Debugging info
# Set the `init_ckpt_path` to a trained model for local training.
# config.init_ckpt_path = ''
# Change to evaluate a specific checkpoint
config.restore_path = ''
config.checkpoint_dir = '/tmp/dd_two_player_games'
config.eval_specific_checkpoint_dir = ''
# Change to False if you want to test checkpointing.
config.delete_existing_local_checkpoints = True
config.best_model_eval_metric = 'IS_mean'
return config
| discretisation_drift-main | dd_two_player_games/cifar_config.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.