python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
---|---|---|
# coding=utf-8
# 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.
"""Run verification for feedforward ReLU networks."""
import os
import time
from typing import Any, Callable, Mapping
from absl import app
from absl import flags
from absl import logging
import jax.numpy as jnp
from jax_verify.extensions.functional_lagrangian import attacks
from jax_verify.extensions.functional_lagrangian import bounding
from jax_verify.extensions.functional_lagrangian import data
from jax_verify.extensions.functional_lagrangian import dual_solve
from jax_verify.extensions.functional_lagrangian import model
from jax_verify.extensions.functional_lagrangian import verify_utils
from jax_verify.extensions.sdp_verify import utils as sdp_utils
import ml_collections
from ml_collections import config_flags
PROJECT_PATH = os.getcwd()
config_flags.DEFINE_config_file(
'config', f'{PROJECT_PATH}/configs/config_ood_stochastic_model.py',
'ConfigDict for the experiment.')
FLAGS = flags.FLAGS
def make_logger(log_message: str) -> Callable[[int, Mapping[str, Any]], None]:
"""Creates a logger.
Args:
log_message: description message for the logs.
Returns:
Function that accepts a step counter and measurements, and logs them.
"""
def log_fn(step, measures):
msg = f'[{log_message}] step={step}'
for k, v in measures.items():
msg += f', {k}={v}'
logging.info(msg)
return log_fn
def main(unused_argv):
config = FLAGS.config
logging.info('Config: \n %s', config)
data_spec = data.make_data_spec(config.problem, config.assets_dir)
spec_type = {e.value: e for e in verify_utils.SpecType}[config.spec_type]
if spec_type == verify_utils.SpecType.UNCERTAINTY:
if data_spec.true_label in config.labels_in_distribution:
return
else:
if data_spec.true_label == data_spec.target_label:
return
params = model.load_model(
root_dir=config.assets_dir,
model_name=config.problem.model_name,
num_std_for_bound=config.problem.get('num_std_for_bound'),
)
params_elided, bounds, bp_bound, bp_time = (
bounding.make_elided_params_and_bounds(config, data_spec, spec_type,
params))
dual_state = ml_collections.ConfigDict(type_safe=False)
def spec_fn(inputs):
# params_elided is a list of network parameters, with the final
# layer elided with the objective (output size is 1, and not num classes)
return jnp.squeeze(sdp_utils.predict_cnn(params_elided, inputs), axis=-1)
def run(mode: str):
logger = make_logger(log_message=mode.title())
start_time = time.time()
prng_key = dual_solve.solve_dual(
dual_state=dual_state,
config=config,
bounds=bounds,
spec_type=spec_type,
spec_fn=spec_fn,
params=params_elided,
mode=mode,
logger=logger)
elapsed_time = time.time() - start_time
adv_objective = attacks.adversarial_attack( # pytype: disable=wrong-arg-types # jax-devicearray
params, data_spec, spec_type, prng_key, config.attack.num_steps,
config.attack.learning_rate, config.attack.get('num_samples', 1))
output_dict = {
'dataset_idx': config.problem.dataset_idx,
'true_label': data_spec.true_label,
'target_label': data_spec.target_label,
'epsilon': config.problem.epsilon_unprocessed,
'verified_ub': dual_state.loss,
'verification_time': elapsed_time,
'adv_lb': adv_objective,
'adv_success': adv_objective > config.problem.feasibility_margin,
'bp_bound': bp_bound,
'bp_time': bp_time,
}
logger = make_logger(log_message=mode.title())
logger(0, output_dict)
run('train')
run('eval')
if __name__ == '__main__':
app.run(main)
| jax_verify-master | jax_verify/extensions/functional_lagrangian/run/run_functional_lagrangian.py |
# coding=utf-8
# 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.
"""Config for experiments on uncertainty spec with stochastic neural networks."""
import ml_collections
def get_uncertainty_config(num_layers):
"""Running mixed solver strategy."""
config = ml_collections.ConfigDict()
config.train = ml_collections.ConfigDict()
config.train.optim_type = 'mixed'
u_config_train = {
'optim_type': 'uncertainty',
'n_iter': 1_000,
'n_pieces': 0,
'solve_max': 'exp',
'learning_rate': 1.0,
}
solver_config = {'optim_type': 'lp'}
config.train.mixed_strat = [[solver_config]] * num_layers + [[u_config_train]]
config.train.solver_weights = [[1.0]] * (num_layers + 1)
u_config_eval = {
'optim_type': 'uncertainty',
'n_iter': 0,
'n_pieces': 100,
'solve_max': 'exp_bound',
}
config.eval = ml_collections.ConfigDict()
config.eval.optim_type = 'mixed'
config.eval.mixed_strat = [[solver_config]] * num_layers + [[u_config_eval]]
config.eval.solver_weights = [[1.0]] * (num_layers + 1)
return config
def get_attack_config():
"""Attack config."""
# Config to use for adversarial attak lower bound
config = ml_collections.ConfigDict()
config.num_steps = 200
config.learning_rate = 1.
config.num_samples = 50
return config
def get_dual_config():
"""Dual config."""
# type of lagrangian functional: e.g. dense_quad, mlp
config = ml_collections.ConfigDict()
config.lagrangian_form = ml_collections.ConfigDict({
'name': 'linear',
'kwargs': {},
})
config.affine_before_relu = False
return config
def get_config(model_name='mnist_mlp_2_128'):
"""Main configdict."""
config = ml_collections.ConfigDict()
config.assets_dir = '/tmp/jax_verify' # directory to download data and models
if model_name.startswith('mnist_mlp'):
dataset = 'emnist'
num_layers = 3
num_std_for_bound = 3.0
epsilon = 0.01
elif model_name.startswith('mnist_cnn'):
dataset = 'emnist'
num_layers = 5
num_std_for_bound = None
epsilon = 0.01
elif model_name.startswith('cifar_vgg'):
dataset = 'cifar100'
num_layers = 6
num_std_for_bound = None
epsilon = 0.001
config.seed = 23
config.use_gpu = False
config.spec_type = 'uncertainty'
config.labels_in_distribution = []
config.use_best = False # PGA may be overly optimistic
config.problem = ml_collections.ConfigDict()
config.problem.model_name = model_name
config.problem.dataset = dataset
config.problem.dataset_idx = 0 # which example from dataset to verify?
config.problem.target_label_idx = 0 # which class to target?
config.problem.epsilon_unprocessed = epsilon # radius before preprocessing
config.problem.scale_center = False
config.problem.num_std_for_bound = num_std_for_bound
# check adversary cannot bring loss below feasibility_margin
config.problem.feasibility_margin = 0.0
config.dual = get_dual_config()
config.attack = get_attack_config()
# whether to block asynchronous dispatch at each iteration for precise timing
config.block_to_time = False
# Choose boundprop method: e.g. 'nonconvex', 'ibp', 'crown_ibp'
config.boundprop_type = 'nonconvex'
# Choose boundprop method: e.g. 'ibp', 'crown'
config.bilinear_boundprop_type = 'nonconvex'
# nonconvex boundprop params, only used if config.boundprop_type = 'nonconvex'
config.nonconvex_boundprop_steps = 100
config.nonconvex_boundprop_nodes = 128
config.outer_opt = ml_collections.ConfigDict()
config.outer_opt.lr_init = 1e-3 # initial learning rate
config.outer_opt.steps_per_anneal = 250 # steps between each anneal
config.outer_opt.anneal_lengths = '' # steps per epoch
config.outer_opt.anneal_factor = 0.1 # learning rate anneal factor
config.outer_opt.num_anneals = 3 # # of times to anneal learning rate
config.outer_opt.opt_name = 'adam' # Optix class: "adam" "sgd", "rmsprop"
config.outer_opt.opt_kwargs = {} # Momentum for gradient descent'
config.inner_opt = get_uncertainty_config(num_layers)
return config
| jax_verify-master | jax_verify/extensions/functional_lagrangian/run/configs/config_ood_stochastic_model.py |
# coding=utf-8
# 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.
"""Verification configuration."""
import ml_collections
def get_input_uncertainty_config(num_layers=2):
"""Running mixed solver strategy."""
config = ml_collections.ConfigDict()
config.train = ml_collections.ConfigDict()
config.train.optim_type = 'mixed'
u_config = {
'optim_type': 'uncertainty',
'solve_max': 'exp',
'n_iter': 20,
'n_pieces': 30,
'learning_rate': 1.
}
solver_config_input_init = {
'optim_type': 'uncertainty_input',
'layer_type': 'input',
'sig_max': .1
}
solver_config_input_first = {
'optim_type': 'uncertainty_input',
'layer_type': 'first',
'sig_max': .1
}
solver_config = {'optim_type': 'lp'}
config.train.mixed_strat = (
[[solver_config_input_init], [solver_config_input_first]] +
[[solver_config]] * num_layers + [[u_config]])
config.train.solver_weights = [[1.0]] * (num_layers + 3)
u_config_eval = {
'optim_type': 'uncertainty',
'n_iter': 0,
'n_pieces': 100,
'solve_max': 'exp_bound',
}
config.eval = ml_collections.ConfigDict()
config.eval.optim_type = 'mixed'
config.eval.mixed_strat = (
[[solver_config_input_init], [solver_config_input_first]] +
[[solver_config]] * num_layers + [[u_config_eval]])
config.eval.solver_weights = [[1.0]] * (num_layers + 3)
return config
def get_dual_config():
"""Dual config."""
config = ml_collections.ConfigDict()
names = ['linear_exp', 'linear', 'linear', 'linear', 'linear']
config.lagrangian_form = []
for name in names:
config.lagrangian_form.append(
ml_collections.ConfigDict({
'name': name,
'kwargs': {},
}))
config.affine_before_relu = False
return config
def get_attack_config():
"""Attack config."""
# Config to use for adversarial attak lower bound
config = ml_collections.ConfigDict()
config.num_steps = 200
config.learning_rate = 1.
return config
def get_config():
"""Main configdict."""
config = ml_collections.ConfigDict()
config.assets_dir = '/tmp/jax_verify' # directory to download data and models
config.seed = 23
config.use_gpu = True
config.spec_type = 'uncertainty'
config.labels_in_distribution = []
config.use_best = True
config.problem = ml_collections.ConfigDict()
config.problem.dataset = 'emnist_CEDA'
config.problem.dataset_idx = 0 # which example from dataset to verify?
config.problem.target_label_idx = 4 # which class to target?
config.problem.epsilon_unprocessed = 0.04 # radius before preprocessing
config.problem.probability_threshold = .97
config.problem.input_shape = (28, 28, 1)
# Use inception_preprocessing i.e. [-1,1]-scaled inputs
config.problem.scale_center = False
config.problem.model_name = 'mnist_ceda'
# check adversary cannot bring loss below feasibility_margin
config.problem.feasibility_margin = 0.0
config.add_input_noise = True
config.dual = get_dual_config()
config.attack = get_attack_config()
# whether to block asynchronous dispatch at each iteration for precise timing
config.block_to_time = False
# Choose boundprop method: e.g. 'nonconvex', 'ibp', 'crown_ibp'
config.boundprop_type = 'nonconvex'
config.bilinear_boundprop_type = 'ibp'
# nonconvex boundprop params, only used if config.boundprop_type = 'nonconvex'
config.nonconvex_boundprop_steps = 100
config.nonconvex_boundprop_nodes = 128
config.outer_opt = ml_collections.ConfigDict()
config.outer_opt.lr_init = 1e-4 # initial learning rate
config.outer_opt.steps_per_anneal = 10 # steps between each anneal
config.outer_opt.anneal_lengths = '60000, 20000, 20000' # steps per epoch
config.outer_opt.anneal_factor = 0.1 # learning rate anneal factor
config.outer_opt.num_anneals = 2 # # of times to anneal learning rate
config.outer_opt.opt_name = 'adam' # Optix class: "adam" "sgd", "rmsprop"
config.outer_opt.opt_kwargs = {} # Momentum for gradient descent'
config.inner_opt = get_input_uncertainty_config()
return config
| jax_verify-master | jax_verify/extensions/functional_lagrangian/run/configs/config_ood_stochastic_input.py |
# coding=utf-8
# 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.
"""Verification configuration."""
import ml_collections
def get_pga_params_config_dict():
"""Create config dict with for running PGA."""
pga_config = ml_collections.ConfigDict()
pga_config.optim_type = 'pga'
pga_config.n_iter = 10000
pga_config.lr = 0.1
pga_config.n_restarts = 300
pga_config.method = 'square'
pga_config.finetune_n_iter = 50
pga_config.finetune_lr = 0.1
pga_config.finetune_method = 'pgd'
pga_config.normalize = False
return pga_config
def get_adv_softmax_config(num_layers):
"""Running mixed solver strategy."""
# Train config
config = ml_collections.ConfigDict()
config.train = ml_collections.ConfigDict()
config.train.optim_type = 'mixed'
u_config_train = get_pga_params_config_dict()
solver_config = {'optim_type': 'lp'}
config.train.mixed_strat = [[solver_config]] * num_layers + [[u_config_train]]
config.train.solver_weights = [[1.0]] * (num_layers + 1)
# Eval config
config.eval = ml_collections.ConfigDict()
u_config_eval = {
'optim_type': 'uncertainty',
'solve_max': 'exp_bound',
}
config.eval.optim_type = 'mixed'
config.eval.mixed_strat = [[solver_config]] * num_layers + [[u_config_eval]]
config.eval.solver_weights = [[1.0]] * (num_layers + 1)
return config
def get_attack_config():
"""Attack config."""
# Config to use for adversarial attak lower bound
config = ml_collections.ConfigDict()
config.num_steps = 200
config.learning_rate = 1.
config.num_samples = 50
return config
def get_dual_config():
"""Dual config."""
# type of lagrangian functional: e.g. dense_quad, mlp
config = ml_collections.ConfigDict()
config.lagrangian_form = ml_collections.ConfigDict({
'name': 'linear',
'kwargs': {},
})
config.affine_before_relu = False
return config
def get_config(model_name='mnist_mlp_1_128'):
"""Main configdict."""
if model_name.startswith('mnist_mlp_1'):
dataset = 'mnist'
num_layers = 2
num_std_for_bound = 3.0
elif model_name.startswith('mnist_mlp_2'):
dataset = 'mnist'
num_layers = 3
num_std_for_bound = 3.0
elif model_name.startswith('mnist_cnn'):
dataset = 'mnist'
num_layers = 5
num_std_for_bound = None
elif model_name.startswith('cifar_vgg'):
dataset = 'cifar10'
num_layers = 6
num_std_for_bound = None
config = ml_collections.ConfigDict()
config.assets_dir = '/tmp/jax_verify' # directory to download data and models
config.seed = 23
config.use_gpu = True
config.spec_type = 'adversarial_softmax'
config.labels_in_distribution = []
config.use_best = False # PGA may be overly optimistic
config.problem = ml_collections.ConfigDict()
config.problem.dataset = dataset
config.problem.dataset_idx = 0 # which example from dataset to verify?
config.problem.target_label_idx = 0 # which class to target?
config.problem.epsilon_unprocessed = 0.001 # radius before preprocessing
config.problem.scale_center = False
config.problem.num_std_for_bound = num_std_for_bound
# check adversary cannot bring loss below feasibility_margin
config.problem.feasibility_margin = 0.0
config.problem.model_name = model_name
config.dual = get_dual_config()
config.attack = get_attack_config()
# whether to block asynchronous dispatch at each iteration for precise timing
config.block_to_time = False
# Choose boundprop method: e.g. 'nonconvex', 'ibp', 'crown_ibp'
config.boundprop_type = 'nonconvex'
config.bilinear_boundprop_type = 'ibp'
# nonconvex boundprop params, only used if config.boundprop_type = 'nonconvex'
config.nonconvex_boundprop_steps = 0
config.nonconvex_boundprop_nodes = 128
config.outer_opt = ml_collections.ConfigDict()
config.outer_opt.lr_init = 1e-3 # initial learning rate
config.outer_opt.steps_per_anneal = 1000 # steps between each anneal
config.outer_opt.anneal_lengths = '' # steps per epoch
config.outer_opt.anneal_factor = 0.1 # learning rate anneal factor
config.outer_opt.num_anneals = 3 # # of times to anneal learning rate
config.outer_opt.opt_name = 'adam' # Optix class: "adam" "sgd", "rmsprop"
config.outer_opt.opt_kwargs = {} # Momentum for gradient descent'
config.inner_opt = get_adv_softmax_config(num_layers)
return config
| jax_verify-master | jax_verify/extensions/functional_lagrangian/run/configs/config_adv_stochastic_model.py |
# coding=utf-8
# 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 Interval Bound Propagation.
"""
import functools
from typing import Callable, Mapping, Tuple, Union
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import synthetic_primitives
from jax_verify.src import utils
from jax_verify.src.linear import linear_relaxations
from jax_verify.src.types import ArgsKwargsCallable, Primitive, Tensor # pylint: disable=g-multiple-import
IntervalBound = bound_propagation.IntervalBound
def _make_ibp_passthrough_primitive(
primitive: Primitive,
) -> ArgsKwargsCallable[
graph_traversal.LayerInput[IntervalBound], IntervalBound]:
"""Generate a function that simply apply the primitive to the bounds.
Args:
primitive: jax primitive
Returns:
ibp_primitive: Function applying transparently the primitive to both
upper and lower bounds.
"""
def ibp_primitive(
*args: bound_propagation.LayerInput, **kwargs) -> IntervalBound:
# We assume that one version should be called with all the 'lower' bound and
# one with the upper bound. If there is some argument that is not a bound,
# we assumed it's just simple parameters and pass them through.
lower_args = [arg.lower if isinstance(arg, bound_propagation.Bound) else arg
for arg in args]
upper_args = [arg.upper if isinstance(arg, bound_propagation.Bound) else arg
for arg in args]
out_lb = primitive.bind(*lower_args, **kwargs)
out_ub = primitive.bind(*upper_args, **kwargs)
return IntervalBound(out_lb, out_ub)
return ibp_primitive
def _decompose_affine_argument(
hs: bound_propagation.LayerInput) -> Tuple[Tensor, Tensor]:
"""Decompose an argument for a (bound, parameter) IBP propagation.
We do not need to know which argument is the bound and which one is the
parameter because we can simply decompose the operation.
To propagate W * x, we can simply do
out_diff = abs(W) * (x.upper - x.lower) / 2
out_mean = W * (x.upper + x.lower) / 2
out_ub = out_mean + out_diff
out_lb = out_mean - out_diff
This function will separate W and x in the two components we need so that we
do not have to worry about argument order.
Args:
hs: Either an IntervalBound or a jnp.array
Returns:
part1, part2: jnp.ndarrays
"""
if isinstance(hs, bound_propagation.Bound):
return (hs.upper - hs.lower) / 2, (hs.upper + hs.lower) / 2
else:
return jnp.abs(hs), hs
def _ibp_bilinear(
primitive: Primitive,
lhs: bound_propagation.LayerInput,
rhs: bound_propagation.LayerInput,
**kwargs) -> bound_propagation.LayerInput:
"""Propagation of IBP bounds through a bilinear primitive (product, conv).
We don't know if the bound is on the left or right hand side, but we expect
that one hand is a bound and the other is a constant/parameter.
Args:
primitive: Bilinear primitive.
lhs: First input to the primitive.
rhs: Second input to the primitive.
**kwargs: Parameters of the primitive.
Returns:
out_bounds: IntervalBound on the output of the primitive.
"""
if (isinstance(lhs, bound_propagation.Bound) !=
isinstance(rhs, bound_propagation.Bound)):
# This is the case where one is a Bound and the other is not.
lhses = _decompose_affine_argument(lhs)
rhses = _decompose_affine_argument(rhs)
forward_mean = primitive.bind(lhses[1], rhses[1], **kwargs)
forward_range = primitive.bind(lhses[0], rhses[0], **kwargs)
out_lb = forward_mean - forward_range
out_ub = forward_mean + forward_range
return IntervalBound(out_lb, out_ub)
elif ((not isinstance(lhs, bound_propagation.Bound)) and
(not isinstance(rhs, bound_propagation.Bound))):
# Both are arrays, so can simply go through
return primitive.bind(lhs, rhs, **kwargs)
elif primitive == lax.dot_general_p:
# If both inputs are bounds and this is a `dot_general_p` primitive, we have
# a special implementation for it with the tighter bounds of using the exact
# bounds instead of relying on McCormick based bounds.
return _ibp_dotgeneral_bilinear(lhs, rhs, **kwargs)
else:
# If both inputs are bounds but this is not the special case of the
# dotgeneral primitive, we can use McCormick inequalities for bilinear
# functions to compute the interval bounds.
# If x in [x_l, x_u] and y in [y_l, y_u], then the following hold:
# xy >= y_l*x + x_l*y - x_l*y_l
# xy >= y_u*x + x_u*y - x_u*y_u
# xy <= y_u*x + x_l*y - x_l*y_u
# xy <= y_l*x + x_u*y - x_u*y_l
# These bounds are also used in the fastlin approach proposed in
# https://arxiv.org/pdf/2002.06622.pdf
# TODO: Tighten the bounds further to min/max of
# x_l*y_l, x_l*y_u, x_u*y_l, and x_u*y_u for more primitives.
# Use the first McCormick lower bound
out_lb1 = _ibp_bilinear(primitive, lhs, rhs.lower, **kwargs).lower
out_lb1 += _ibp_bilinear(primitive, lhs.lower, rhs, **kwargs).lower
out_lb1 -= _ibp_bilinear(primitive, lhs.lower, rhs.lower, **kwargs)
# Use the second McCormick lower bound
out_lb2 = _ibp_bilinear(primitive, lhs, rhs.upper, **kwargs).lower
out_lb2 += _ibp_bilinear(primitive, lhs.upper, rhs, **kwargs).lower
out_lb2 -= _ibp_bilinear(primitive, lhs.upper, rhs.upper, **kwargs)
# Choose the best lower bound out of the two
out_lb = jnp.maximum(out_lb1, out_lb2)
# Use the first McCormick upper bound
out_ub1 = _ibp_bilinear(primitive, lhs, rhs.upper, **kwargs).upper
out_ub1 += _ibp_bilinear(primitive, lhs.lower, rhs, **kwargs).upper
out_ub1 -= _ibp_bilinear(primitive, lhs.lower, rhs.upper, **kwargs)
# Use the second McCormick upper bound
out_ub2 = _ibp_bilinear(primitive, lhs, rhs.lower, **kwargs).upper
out_ub2 += _ibp_bilinear(primitive, lhs.upper, rhs, **kwargs).upper
out_ub2 -= _ibp_bilinear(primitive, lhs.upper, rhs.lower, **kwargs)
# Choose the best upper bound out of the two
out_ub = jnp.minimum(out_ub1, out_ub2)
return IntervalBound(out_lb, out_ub)
def _move_axes(
bound: bound_propagation.Bound,
cdims: Tuple[int, ...],
bdims: Tuple[int, ...],
orig_axis: int,
new_axis: int,
) -> Tuple[IntervalBound, Tuple[int, ...], Tuple[int, ...]]:
"""Reorganise the axis of a bound, and the dimension_numbers indexing it.
The axis in position `orig_axis` gets moved to position `new_axis`.
Args:
bound: Bound whose axis needs to be re-organised.
cdims: Contracting dimensions, pointing at some axis of bound.
bdims: Batch dimensions, pointing at some axis of bound.
orig_axis: Index of the axis to move.
new_axis: New position for this axis.
Returns:
new_bound: Re-organised bound.
new_cdims: Re-organised cdims.
new_bdims: Re-organised bdims.
"""
def new_axis_fn(old_axis):
if old_axis == orig_axis:
# This is the axis being moved. Return its new position.
return new_axis
elif (old_axis < orig_axis) and (old_axis >= new_axis):
# The original axis being moved was after, but it has now moved to before
# (or at this space). This means that this axis gets shifted back
return old_axis + 1
elif (old_axis > orig_axis) and (old_axis <= new_axis):
# The original axis being moved was before this one, but it has now moved
# to after. This means that this axis gets shifted forward.
return old_axis - 1
else:
# Nothing should be changing.
return old_axis
mapping = {old_axis: new_axis_fn(old_axis)
for old_axis in range(len(bound.lower.shape))}
permutation = sorted(range(len(bound.lower.shape)), key=lambda x: mapping[x])
new_bound = IntervalBound(jax.lax.transpose(bound.lower, permutation),
jax.lax.transpose(bound.upper, permutation))
new_cdims = tuple(new_axis_fn(old_axis) for old_axis in cdims)
new_bdims = tuple(new_axis_fn(old_axis) for old_axis in bdims)
return new_bound, new_cdims, new_bdims
def _ibp_dotgeneral_bilinear(lhs: bound_propagation.Bound,
rhs: bound_propagation.Bound,
**kwargs
) -> IntervalBound:
"""IBP propagation through a dotgeneral primitive with two bound input.
Args:
lhs: First input to the dotgeneral
rhs: Second input to the primitive.
**kwargs: Parameters of the primitive.
Returns:
out_bounds: Bound on the output of the general dot product.
"""
(lhs_cdims, rhs_cdims), (lhs_bdims, rhs_bdims) = kwargs['dimension_numbers']
# Move the contracting dimensions to the front.
for cdim_index in range(len(lhs_cdims)):
lhs, lhs_cdims, lhs_bdims = _move_axes(lhs, lhs_cdims, lhs_bdims,
lhs_cdims[cdim_index], cdim_index)
rhs, rhs_cdims, rhs_bdims = _move_axes(rhs, rhs_cdims, rhs_bdims,
rhs_cdims[cdim_index], cdim_index)
# Because we're going to scan over the contracting dimensions, the
# batch dimensions are appearing len(cdims) earlier.
new_lhs_bdims = tuple(bdim - len(lhs_cdims) for bdim in lhs_bdims)
new_rhs_bdims = tuple(bdim - len(rhs_cdims) for bdim in rhs_bdims)
merge_cdims = lambda x: x.reshape((-1,) + x.shape[len(lhs_cdims):])
operands = ((merge_cdims(lhs.lower), merge_cdims(lhs.upper)),
(merge_cdims(rhs.lower), merge_cdims(rhs.upper)))
batch_shape = tuple(lhs.lower.shape[axis] for axis in lhs_bdims)
lhs_contr_shape = tuple(dim for axis, dim in enumerate(lhs.lower.shape)
if axis not in lhs_cdims + lhs_bdims)
rhs_contr_shape = tuple(dim for axis, dim in enumerate(rhs.lower.shape)
if axis not in rhs_cdims + rhs_bdims)
out_shape = batch_shape + lhs_contr_shape + rhs_contr_shape
init_carry = (jnp.zeros(out_shape), jnp.zeros(out_shape))
new_dim_numbers = (((), ()), (new_lhs_bdims, new_rhs_bdims))
unreduced_dotgeneral = functools.partial(jax.lax.dot_general,
dimension_numbers=new_dim_numbers)
def scan_fun(carry: Tuple[Tensor, Tensor],
inp: Tuple[Tuple[Tensor, Tensor], Tuple[Tensor, Tensor]]
) -> Tuple[Tuple[Tensor, Tensor], None]:
"""Accumulates the minimum and maximum as inp traverse the first dimension.
(The first dimension is where we have merged all contracting dimensions.)
Args:
carry: Current running sum of the lower bound and upper bound
inp: Slice of the input tensors.
Returns:
updated_carry: New version of the running sum including these elements.
None
"""
(lhs_low, lhs_up), (rhs_low, rhs_up) = inp
carry_min, carry_max = carry
opt_1 = unreduced_dotgeneral(lhs_low, rhs_low)
opt_2 = unreduced_dotgeneral(lhs_low, rhs_up)
opt_3 = unreduced_dotgeneral(lhs_up, rhs_low)
opt_4 = unreduced_dotgeneral(lhs_up, rhs_up)
elt_min = jnp.minimum(jnp.minimum(jnp.minimum(opt_1, opt_2), opt_3), opt_4)
elt_max = jnp.maximum(jnp.maximum(jnp.maximum(opt_1, opt_2), opt_3), opt_4)
return (carry_min + elt_min, carry_max + elt_max), None
(lower, upper), _ = jax.lax.scan(scan_fun, init_carry, operands)
return IntervalBound(lower, upper)
def _ibp_div(
lhs: bound_propagation.LayerInput,
rhs: Tensor,
) -> bound_propagation.LayerInput:
"""Propagation of IBP bounds through Elementwise division.
We don't support the propagation of bounds through the denominator.
Args:
lhs: Numerator of the division.
rhs: Denominator of the division.
Returns:
out_bounds: Bound on the output of the division.
"""
if isinstance(rhs, bound_propagation.Bound):
raise ValueError('Bound propagation through the denominator unsupported.')
return _ibp_bilinear(lax.mul_p, lhs, 1. / rhs)
def _ibp_add(
lhs: bound_propagation.LayerInput,
rhs: bound_propagation.LayerInput,
) -> IntervalBound:
"""Propagation of IBP bounds through an addition.
Args:
lhs: Lefthand side of addition.
rhs: Righthand side of addition.
Returns:
out_bounds: IntervalBound.
"""
if isinstance(lhs, bound_propagation.Bound):
if isinstance(rhs, bound_propagation.Bound):
new_lower = lhs.lower + rhs.lower
new_upper = lhs.upper + rhs.upper
else:
new_lower = lhs.lower + rhs
new_upper = lhs.upper + rhs
else:
# At least one of the inputs is a bound
new_lower = rhs.lower + lhs
new_upper = rhs.upper + lhs
return IntervalBound(new_lower, new_upper)
def _ibp_neg(inp: IntervalBound) -> IntervalBound:
"""Propagation of IBP bounds through a negation.
Args:
inp: Bounds that need to be negated.
Returns:
out_bounds: IntervalBound
"""
return IntervalBound(-inp.upper, -inp.lower)
def _ibp_sub(
lhs: bound_propagation.LayerInput,
rhs: bound_propagation.LayerInput,
) -> IntervalBound:
"""Propagation of IBP bounds through a substraction.
Args:
lhs: Lefthand side of substraction.
rhs: Righthand side of substraction.
Returns:
out_bounds: IntervalBound.
"""
if isinstance(lhs, bound_propagation.Bound):
if isinstance(rhs, bound_propagation.Bound):
return IntervalBound(lhs.lower - rhs.upper, lhs.upper - rhs.lower)
else:
return IntervalBound(lhs.lower - rhs, lhs.upper - rhs)
else:
# At least one of the inputs is a bound
return IntervalBound(lhs - rhs.upper, lhs - rhs.lower)
def _ibp_softmax(logits: bound_propagation.LayerInput, axis) -> IntervalBound:
"""Propagation of IBP bounds through softmax.
Args:
logits: logits, or their bounds
axis: the axis or axes along which the softmax should be computed
Returns:
out_bounds: softmax output or its bounds
"""
if isinstance(logits, bound_propagation.Bound):
# TODO: This bound of the softmax is not as tight as it could be
# because in the normalization term it uses all upper rather than all except
# 1 upper.
log_z_ub = jax.nn.logsumexp(logits.upper, keepdims=True, axis=axis)
out_lb = jnp.exp(logits.lower - log_z_ub)
log_z_lb = jax.nn.logsumexp(logits.lower, keepdims=True, axis=axis)
out_ub = jnp.exp(jnp.minimum(logits.upper - log_z_lb, 0))
return IntervalBound(out_lb, out_ub)
else:
# If the inputs are not bounds, return softmax of logits
return jax.nn.softmax(logits, axis=axis)
def _ibp_unimodal_0min(
fun: Callable[[Tensor], Tensor],
x: IntervalBound
) -> IntervalBound:
"""Propagation of IBP bounds through unimodal function whose min is 0.
Args:
fun: Elementwise function which is decreasing before 0 and increasing after,
achieving its minimum value is at 0.
x: Bounds on the inputs to the function.
Returns:
Bounds on the output of the function.
"""
lower_out = fun(x.lower)
upper_out = fun(x.upper)
out_lb = jnp.where(jnp.logical_and(x.upper >= 0., x.lower <= 0.),
fun(jnp.zeros_like(x.lower)),
jnp.minimum(lower_out, upper_out))
out_ub = jnp.maximum(lower_out, upper_out)
return IntervalBound(out_lb, out_ub)
def _ibp_unimodal_0max(
fun: Callable[[Tensor], Tensor],
x: IntervalBound
) -> IntervalBound:
"""Propagation of IBP bounds through unimodal function whose max is 0.
Args:
fun: Elementwise function which is increasing before 0 and decreasing after,
achieving its maximum value is at 0.
x: Bounds on the inputs to the function.
Returns:
Bounds on the output of the function.
"""
lower_out = fun(x.lower)
upper_out = fun(x.upper)
out_lb = jnp.minimum(lower_out, upper_out)
out_ub = jnp.where(jnp.logical_and(x.upper >= 0., x.lower <= 0.),
fun(jnp.zeros_like(x.lower)),
jnp.maximum(lower_out, upper_out))
return IntervalBound(out_lb, out_ub)
def _ibp_leaky_relu(x: IntervalBound,
negative_slope: Union[float, Tensor]) -> IntervalBound:
"""Propagation of IBP bounds through leaky Relu.
Considers the case where the negative slope is negative.
Args:
x: Bounds on the inputs to the leaky ReLU.
negative_slope: Slope for negative inputs.
Returns:
out_bounds: Bounds on the output of the leaky ReLU.
"""
sigma_l = jax.nn.leaky_relu(x.lower, negative_slope)
sigma_u = jax.nn.leaky_relu(x.upper, negative_slope)
l_sigma = jnp.where(
jnp.logical_and(x.lower < 0., x.upper > 0.),
jnp.minimum(jnp.minimum(sigma_l, sigma_u), 0.),
jnp.minimum(sigma_l, sigma_u))
u_sigma = jnp.maximum(sigma_l, sigma_u)
return IntervalBound(l_sigma, u_sigma)
def _ibp_integer_pow(x: bound_propagation.LayerInput, y: int) -> IntervalBound:
"""Propagation of IBP bounds through integer_pow.
Args:
x: Argument be raised to a power, element-wise
y: fixed integer exponent
Returns:
out_bounds: integer_pow output or its bounds.
"""
if y < 0:
raise NotImplementedError
l_pow = lax.integer_pow(x.lower, y)
u_pow = lax.integer_pow(x.upper, y)
if y % 2 == 0:
# Even powers
contains_zero = jnp.logical_and(
jnp.less_equal(x.lower, 0), jnp.greater_equal(x.upper, 0))
lower = jnp.where(contains_zero, jnp.zeros_like(x.lower),
jnp.minimum(l_pow, u_pow))
upper = jnp.maximum(l_pow, u_pow)
return IntervalBound(lower, upper)
else:
# Odd powers
return IntervalBound(l_pow, u_pow)
def _ibp_linear(*args, **kwargs) -> IntervalBound:
"""Propagation of IBP bounds through a linear primitive treated as a blackbox.
Args:
*args: All inputs to the linear operation, which can be either Tensor or
bounds.
**kwargs: Parameters of the primitive, which would include the subgraph that
explains how to implement them.
Returns:
Bound on the output of the linear primitive.
"""
primitive = synthetic_primitives.linear_p
apply_fun = utils.bind_nonbound_args(primitive.bind, *args, **kwargs)
bound_args = [arg for arg in args if isinstance(arg, bound_propagation.Bound)]
all_args = tuple(range(len(bound_args)))
jac_fn = jax.jacfwd(apply_fun, argnums=all_args)
zero_inp_args = [jnp.zeros(b_arg.shape) for b_arg in bound_args]
offset = apply_fun(*zero_inp_args)
jacobians = jac_fn(*zero_inp_args)
pos_jacs = jax.tree_map(lambda x: jnp.maximum(x, 0.), jacobians)
neg_jacs = jax.tree_map(lambda x: jnp.minimum(x, 0.), jacobians)
new_lower = offset
new_upper = offset
for p_jac, n_jac, b_arg in zip(pos_jacs, neg_jacs, bound_args):
sum_dims = tuple(range(-len(b_arg.shape), 0))
new_lower += (p_jac * b_arg.lower + n_jac * b_arg.upper).sum(sum_dims)
new_upper += (p_jac * b_arg.upper + n_jac * b_arg.lower).sum(sum_dims)
return IntervalBound(new_lower, new_upper)
def _ibp_reciprocal(x: bound_propagation.LayerInput) -> IntervalBound:
"""Propagation of IBP bounds through reciprocal, assuming positive input.
Args:
x: Argument to get the inverse of.
Returns:
out_bounds: Reciprocal of the bounds.
"""
return IntervalBound(1. / jax.nn.relu(x.upper), 1. / jax.nn.relu(x.lower))
_input_transform = lambda x: IntervalBound(x.lower, x.upper)
# Define the mapping from jaxpr primitive to the IBP version.
_primitives_to_pass_through = [
*bound_propagation.RESHAPE_PRIMITIVES,
lax.reduce_sum_p,
lax.max_p,
lax.scatter_add_p,
lax.exp_p,
lax.sinh_p,
lax.log_p,
lax.tanh_p,
synthetic_primitives.softplus_p,
synthetic_primitives.relu_p,
synthetic_primitives.sigmoid_p,
lax.sqrt_p,
lax.sign_p,
]
_primitive_transform: Mapping[
Primitive,
ArgsKwargsCallable[
graph_traversal.LayerInput[IntervalBound], IntervalBound],
] = {
**{primitive: _make_ibp_passthrough_primitive(primitive)
for primitive in _primitives_to_pass_through},
**{primitive: functools.partial(_ibp_bilinear, primitive)
for primitive in bound_propagation.BILINEAR_PRIMITIVES},
lax.abs_p: functools.partial(_ibp_unimodal_0min, lax.abs),
lax.add_p: _ibp_add,
lax.cosh_p: functools.partial(_ibp_unimodal_0min, lax.cosh),
lax.sub_p: _ibp_sub,
lax.neg_p: _ibp_neg,
lax.div_p: _ibp_div,
lax.integer_pow_p: _ibp_integer_pow,
synthetic_primitives.sech_p: functools.partial(
_ibp_unimodal_0max, synthetic_primitives.sech_p.bind),
synthetic_primitives.leaky_relu_p: _ibp_leaky_relu,
synthetic_primitives.parametric_leaky_relu_p: _ibp_leaky_relu,
synthetic_primitives.softmax_p: _ibp_softmax,
synthetic_primitives.posreciprocal_p: _ibp_reciprocal,
}
bound_transform = graph_traversal.OpwiseGraphTransform(
_input_transform, _primitive_transform)
fused_linear_ibp_transform = graph_traversal.OpwiseGraphTransform(
_input_transform,
_primitive_transform | {synthetic_primitives.linear_p: _ibp_linear})
def interval_bound_propagation(function, *bounds, fused_linear=False):
"""Performs IBP as described in https://arxiv.org/abs/1810.12715.
Args:
function: Function performing computation to obtain bounds for. Takes as
only argument the network inputs.
*bounds: jax_verify.IntervalBounds, bounds on the inputs of the function.
fused_linear: Boolean indicating whether to treat sequence of linear
operations as a single operation, by materializing the equivalent weights.
This has the potential to be tighter, but may be less efficient.
Returns:
output_bound: Bounds on the output of the function obtained by IBP
"""
transform = fused_linear_ibp_transform if fused_linear else bound_transform
output_bound, _ = bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(transform),
function, *bounds)
return output_bound
| jax_verify-master | jax_verify/src/ibp.py |
# coding=utf-8
# 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.
"""Traverses a network, applying a transformation to each node in the graph.
This is accomplished by traversing the JaxPR representation of the computation.
"""
import abc
import collections
import dataclasses
import functools
from typing import Any, Callable, Generic, List, Mapping, MutableMapping, Optional, Sequence, Tuple, TypeVar, Union
import jax
import jax.numpy as jnp
from jax_verify.src import synthetic_primitives
from jax_verify.src.types import ArgsKwargsCallable, Index, Nest, Primitive, Tensor # pylint: disable=g-multiple-import
import typing_extensions
class InputBound(metaclass=abc.ABCMeta):
"""Abstract input bound."""
@property
@abc.abstractmethod
def lower(self) -> Tensor:
"""Concrete lower bound."""
@property
@abc.abstractmethod
def upper(self) -> Tensor:
"""Concrete upper bound."""
@property
@abc.abstractmethod
def shape(self) -> Tuple[int, ...]:
"""Shape of the node."""
@property
@abc.abstractmethod
def dtype(self) -> jnp.dtype:
"""Dtype of the node."""
GraphInput = Union[InputBound, Tensor]
class TransformedNode(metaclass=abc.ABCMeta):
"""Abstract transformed node, e.g. a propagated bound."""
Repr = TypeVar('Repr')
FwdRepr = TypeVar('FwdRepr', bound=TransformedNode)
BackRepr = TypeVar('BackRepr')
LayerInput = Union[Repr, Tensor]
class SubgraphHandler(typing_extensions.Protocol, Generic[Repr]):
"""Function to recursively handle a sub-graph."""
def __call__(
self,
transform: Any,
subgraph: jax.core.Jaxpr,
*args: LayerInput[Repr],
) -> Sequence[Any]:
pass
@dataclasses.dataclass
class TransformContext(Generic[Repr]):
"""Transform context.
Attributes:
index: Integer path identifying the input node.
subgraph_handler: Function to recursively handle a sub-graph.
"""
index: Index
subgraph_handler: Optional[SubgraphHandler[Repr]]
class GraphTransform(Generic[FwdRepr], metaclass=abc.ABCMeta):
"""Abstract forward Node transformation method."""
@abc.abstractmethod
def input_transform(
self,
context: TransformContext[FwdRepr],
input_bound: InputBound,
) -> FwdRepr:
"""Constructs input representations from a concrete input bound.
Args:
context: Transform context containing node index.
input_bound: Original concrete bounds on the input.
Returns:
Method-specific representation for the inputs.
"""
@abc.abstractmethod
def primitive_transform(
self,
context: TransformContext[FwdRepr],
primitive: Primitive,
*args: LayerInput[FwdRepr],
**params,
) -> FwdRepr:
"""Applies the given primitive operation to its arguments' representations.
Args:
context: Transform context containing node index.
primitive: Primitive Jax operation to transform.
*args: Arguments of the primitive. Arguments are expressed as
method-specific representations if they have any dependence on the
network's original inputs, or tensors otherwise.
**params: Keyword arguments of the primitive.
Returns:
Method-specific representation for the operation's output.
"""
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
"""Returns whether the primitive should be handled via its sub-graph.
If not, it will be handled by treating it as a single primitive.
This function is intended to be overridden. The default implementation
specifies that all synthetic primitives are to be handled as primitives.
Args:
primitive: Primitive Jax operation to transform.
Returns:
Whether to handle as a single primitive, as opposed to recursively
processing the sub-graph's child nodes.
"""
return primitive in synthetic_primitives.SUBGRAPH_PRIMITIVES
def equation_transform(
self,
context: TransformContext[FwdRepr],
primitive: Primitive,
*args: LayerInput[FwdRepr],
**params,
) -> Sequence[FwdRepr]:
"""Applies the given primitive operation to its arguments' representations.
By default this invokes `primitive_transform()` which will be overridden
for primitive-specific behaviour. However, this function consults
`context.subgraph_handler` allowing primitive-specific customisation of
sub-graph handling.
Args:
context: Transform context containing node index.
primitive: Primitive Jax operation to transform.
*args: Arguments of the primitive. Arguments are expressed as
method-specific representations if they have any dependence on the
network's original inputs, or tensors otherwise.
**params: Keyword arguments of the primitive.
Returns:
Method-specific representation for the operation's outputs.
"""
if self.should_handle_as_subgraph(primitive):
subgraph = synthetic_primitives.jax_primitive_subgraph(
primitive, **params)
return context.subgraph_handler(self, subgraph, *args)
# `primitive_transform` is for "regular" single-output primitives.
return [self.primitive_transform(context, primitive, *args, **params)]
class BackwardGraphTransform(Generic[BackRepr], metaclass=abc.ABCMeta):
"""Abstract Backward graph propagation method."""
@abc.abstractmethod
def primitive_backtransform(
self,
context: TransformContext[BackRepr],
primitive: Primitive,
eqn_outval: BackRepr,
*args: LayerInput[TransformedNode],
**params,
) -> Sequence[Sequence[Optional[BackRepr]]]:
"""Propagate backward to the `*args` inputs of `primitive`.
Args:
context: Transform context containing node index.
primitive: Primitive Jax operation to transform.
eqn_outval: Method-specific representation of the output of the primitive.
*args: Arguments of the primitive, as determined by an earlier forward
pass. Arguments are expressed in a representation specific to the
forward method, NOT `BackRepr`.
**params: Keyword arguments of the primitive.
Returns:
Method-specific representation for the operation's inputs.
For each input of the primitive there will be a list of values according
to the fan-out of this network node; these will be reduced with the
`aggregate`function.
The inputs' value lists will each be singleton `[None]` in the case that
none of them have any dependence on the network's non-fixed inputs.
"""
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
"""Returns whether the primitive should be handled via its sub-graph.
If not, it will be handled by treating it as a single primitive.
This function is intended to be overridden. The default implementation
specifies that all synthetic primitives are to be handled as primitives.
Args:
primitive: Primitive Jax operation to transform.
Returns:
Whether to handle as a single primitive, as opposed to recursively
processing the sub-graph's child nodes.
"""
return primitive in synthetic_primitives.SUBGRAPH_PRIMITIVES
def equation_backtransform(
self,
context: TransformContext[BackRepr],
primitive: Primitive,
eqn_outval: BackRepr,
*args: LayerInput[BackRepr],
**params,
) -> Sequence[Sequence[Optional[BackRepr]]]:
"""Applies the given primitive operation to its arguments' representations.
Normally this invokes `primitive_backtransform()` which will be overridden
for primitive-specific behaviour. However, as can be customised in
`should_handle_as_subgraph`, this may decide instead to process the
subgraph's child nodes recursively.
Args:
context: Transform context containing node index.
primitive: Primitive Jax operation to transform.
eqn_outval: Backward representation of the output of the primitive.
*args: Arguments of the primitive. Arguments need to either be a bound
or a tensor if they do not depend on the input.
**params: Keyword arguments of the primitive.
Returns:
Method-specific representation for each of the operation's input, or None
if the input is a Tensor.
"""
if self.should_handle_as_subgraph(primitive):
subgraph = synthetic_primitives.jax_primitive_subgraph(
primitive, **params)
return context.subgraph_handler(self, subgraph, eqn_outval)
return self.primitive_backtransform(
context, primitive, eqn_outval, *args, **params)
@abc.abstractmethod
def aggregate(self, eqn_outvals: Sequence[BackRepr]) -> BackRepr:
"""Aggregate the representations coming from different branches."""
class PrimitiveBacktransformFn(typing_extensions.Protocol, Generic[BackRepr]):
def __call__(
self,
outval: BackRepr,
*args: LayerInput[TransformedNode],
**params,
) -> Sequence[Optional[BackRepr]]:
pass
class BackwardOpwiseTransform(BackwardGraphTransform[BackRepr]):
"""Backward Propagation method defined by functions for each primitive op."""
def __init__(
self,
primitive_backtransform: Mapping[Primitive, PrimitiveBacktransformFn],
aggregation_fun: Callable[[Sequence[BackRepr]], BackRepr]):
self._primitive_backtransform = primitive_backtransform
self._aggregation_fun = aggregation_fun
def primitive_backtransform(
self,
context: TransformContext[BackRepr],
primitive: Primitive,
eqn_outval: BackRepr,
*args: LayerInput[TransformedNode],
**params,
) -> Sequence[Sequence[Optional[BackRepr]]]:
if primitive not in self._primitive_backtransform:
raise NotImplementedError(f'Unknown Primitive: {primitive}.')
del context
params = synthetic_primitives.filter_jaxverify_kwargs(params)
# Promote each output to a single-length list.
# This is for consistency with the sub-graph handler, in which output is
# returned as a list according to the multiple paths through the graph.
return list(zip(self._primitive_backtransform[primitive](
eqn_outval, *args, **params)))
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
if (isinstance(primitive, synthetic_primitives.FakePrimitive) and
primitive not in self._primitive_backtransform):
return True
return super().should_handle_as_subgraph(primitive)
def aggregate(self, eqn_outvals: Sequence[BackRepr]) -> BackRepr:
"""Aggregate the representations coming from different branches."""
return self._aggregation_fun(eqn_outvals)
class OpwiseGraphTransform(GraphTransform[FwdRepr]):
"""Bound propagation method defined by functions for each primitive op."""
def __init__(
self,
input_transform: Callable[[InputBound], FwdRepr],
primitive_transform: Mapping[
Primitive, ArgsKwargsCallable[LayerInput[FwdRepr], FwdRepr]]):
self._input_transform = input_transform
self._primitive_transform = primitive_transform
def input_transform(
self,
context: TransformContext[FwdRepr],
input_bound: InputBound,
) -> FwdRepr:
del context
return self._input_transform(input_bound)
def primitive_transform(
self,
context: TransformContext[FwdRepr],
primitive: Primitive,
*args: LayerInput[FwdRepr],
**params,
) -> FwdRepr:
if primitive not in self._primitive_transform:
raise NotImplementedError(f'Unknown Primitive: {primitive}')
del context
params = synthetic_primitives.filter_jaxverify_kwargs(params)
return self._primitive_transform[primitive](*args, **params)
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
if (isinstance(primitive, synthetic_primitives.FakePrimitive) and
primitive not in self._primitive_transform):
return True
return super().should_handle_as_subgraph(primitive)
class UpdatedGraphTransform(GraphTransform[FwdRepr]):
"""Graph transform with a base transform and updated primitive transform."""
def __init__(
self,
base_transform: GraphTransform[FwdRepr],
updated_primitive_transform: Mapping[
Primitive, ArgsKwargsCallable[LayerInput[FwdRepr], FwdRepr]]):
self._base_transform = base_transform
self._updated_primitive_transform = updated_primitive_transform
def input_transform(
self,
context: TransformContext[FwdRepr],
input_bound: InputBound,
) -> FwdRepr:
return self._base_transform.input_transform(context, input_bound)
def primitive_transform(
self,
context: TransformContext[FwdRepr],
primitive: Primitive,
*args: LayerInput[FwdRepr],
**params,
) -> FwdRepr:
if primitive in self._updated_primitive_transform:
return self._updated_primitive_transform[primitive](
context.index, *args, **params)
return self._base_transform.equation_transform(
context, primitive, *args, **params)[0]
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
if (isinstance(primitive, synthetic_primitives.FakePrimitive) and
primitive not in self._updated_primitive_transform):
return True
return self._base_transform.should_handle_as_subgraph(primitive)
JaxVar = Union[jax.core.Var, jax.core.Literal]
class IndexCounter:
"""Maintains and navigates a path consisting of integers."""
def __init__(self, initial_index: Optional[Index] = None):
self._index = [0] if initial_index is None else list(initial_index)
def incr(self):
self._index[-1] += 1
def decr(self):
self._index[-1] -= 1
def begin_child(self, initial_index: int = 0):
self._index.append(initial_index)
def end_child(self):
del self._index[-1]
def child_index(self) -> int:
return self._index[-1]
def as_tuple(self) -> Index:
return tuple(self._index)
def read_env(
env: Mapping[jax.core.Var, LayerInput[Repr]],
var: JaxVar,
) -> LayerInput[Repr]:
"""Read the value from the environment."""
if isinstance(var, jax.core.Literal):
# Literals are values baked into the Jaxpr, e.g. ReLU's '0' arg to 'max'.
return var.val
else:
val = env[var]
if isinstance(val, list):
return [elt for elt in val if elt is not None]
else:
return val
class PropagationGraph:
"""Holds a computational graph and the environment holding the variables.
"""
def __init__(self, graph: jax.core.Jaxpr, literals: Sequence[Tensor]):
self._graph = graph
self._literals = literals
self._index_to_node: MutableMapping[Index, jax.core.Var] = {}
self._last_index = None
@property
def inputs(self) -> Sequence[jax.core.Var]:
return self._graph.invars
@property
def outputs(self) -> Sequence[jax.core.Var]:
return [outvar for outvar in self._graph.outvars
if isinstance(outvar, jax.core.Var)]
def jaxpr_node(self, index: Index) -> jax.core.Var:
return self._index_to_node[index]
@property
def indices(self) -> Sequence[Index]:
return list(self._index_to_node.keys())
def forward_propagation(
self,
transform: GraphTransform[FwdRepr],
bounds: Nest[GraphInput],
) -> Tuple[Nest[FwdRepr], Mapping[jax.core.Var, LayerInput[FwdRepr]]]:
"""Performs forward propagation on the parsed computation graph.
This is accomplished by traversing the JaxPR representation of the
computation and translating the computational graph, using the
`primitive_transform` replacement for each jax primitive.
Args:
transform: Basic Jax primitive ops' equivalents for operating on
the representation (e.g. bound propagation).
bounds: Nest of `InputBound` objects containing the bounds on all the
inputs, or `Tensor`s containing known inputs directly.
Returns:
outvals: Propagated values corresponding to the graph output.
env: Dictionary holding the computed bounds on nodes of the graph.
"""
# Initialize the environment based on the provided bounds.
env = {}
is_bound = lambda b: isinstance(b, InputBound)
flat_bounds, _ = jax.tree_util.tree_flatten(bounds, is_leaf=is_bound)
invals = []
index = IndexCounter()
for bound, invar in zip(flat_bounds, self._graph.invars):
if is_bound(bound):
input_val = transform.input_transform(
TransformContext(index.as_tuple(), None), bound)
self._index_to_node[index.as_tuple()] = invar
index.incr()
else:
# Input is a fixed tensor.
input_val = bound
invals.append(input_val)
env.update(zip(self._graph.invars, invals))
env.update(zip(self._graph.constvars, self._literals))
for eqn in self._graph.eqns:
self._forward_prop_eqn(transform, env, index, eqn)
self._last_index = index.as_tuple()
outvals = jax.tree_util.tree_map(
functools.partial(read_env, env), self._graph.outvars)
return outvals, env
def _forward_prop_eqn(
self, transform: GraphTransform[FwdRepr],
env: MutableMapping[jax.core.Var, LayerInput[FwdRepr]],
index: IndexCounter,
eqn: jax.core.JaxprEqn):
"""Recursive step of `forward_propagation`."""
def subgraph_handler(
sub_transform: GraphTransform[FwdRepr],
sub_graph: jax.core.Jaxpr,
*invals: LayerInput[FwdRepr],
) -> Sequence[LayerInput[FwdRepr]]:
assert len(invals) == len(sub_graph.invars) == len(eqn.invars)
if sub_transform is transform:
# We must use the same environment, so that transformed equations
# in the sub-graph are included in it.
assert all(read_env(env, invar) is inval
for invar, inval in zip(eqn.invars, invals))
invals = [read_env(env, invar) for invar in eqn.invars]
sub_env = env
else:
# We must leave the environment intact, because it contains
# equations transformed by a different transformer.
# Set up a new environment.
sub_env = {}
# Add the sub-graph's inputs to the environment.
sub_env.update({
sub_invar: inval for sub_invar, inval in zip(sub_graph.invars, invals)
if isinstance(sub_invar, jax.core.Var)})
# Recursively propagate through the sub-graph.
index.begin_child()
try:
for sub_eqn in sub_graph.eqns:
self._forward_prop_eqn(sub_transform, sub_env, index, sub_eqn)
finally:
index.end_child()
# Associate the sub-graph's outputs with the enclosing equation outputs.
return [read_env(sub_env, sub_outvar) for sub_outvar in sub_graph.outvars]
eqn_invars_vals = jax.tree_util.tree_map(
functools.partial(read_env, env), eqn.invars)
idx = index.as_tuple()
if (eqn.primitive in synthetic_primitives.SUBGRAPH_PRIMITIVES or
synthetic_primitives.always_make_node(eqn.primitive) or
any(isinstance(inval, TransformedNode) for inval in eqn_invars_vals)):
if len(eqn.outvars) == 1:
if (idx in self._index_to_node
and self._index_to_node[idx] != eqn.outvars[0]):
raise ValueError('A node with this index pointing to another Node'
'already exists.')
eqn_outvals = transform.equation_transform(
TransformContext(idx, subgraph_handler),
eqn.primitive, *eqn_invars_vals, **eqn.params)
if len(eqn.outvars) == 1:
self._index_to_node[idx] = eqn.outvars[0]
else:
# No dependence on the network's inputs.
eqn_outvals = eqn.primitive.bind(*eqn_invars_vals, **eqn.params)
# `bind` usually emits a tensor, but sometimes a list.
# This may even be of length one, for example in the case of `sort_p`.
if not isinstance(eqn_outvals, list):
assert len(eqn.outvars) == 1
eqn_outvals = [eqn_outvals]
index.incr()
env.update({
outvar: outval
for outvar, outval in zip(eqn.outvars, eqn_outvals)})
def _propagate_backward(
self,
transform: BackwardGraphTransform[BackRepr],
forward_env: Mapping[jax.core.Var, LayerInput[TransformedNode]],
backward_env: MutableMapping[jax.core.Var, List[BackRepr]],
target_indices: Sequence[Index],
) -> Tuple[
Sequence[Optional[BackRepr]],
Mapping[jax.core.Var, Sequence[BackRepr]]]:
"""Performs backward propagation on the parsed computational graph.
Args:
transform: Backward Transformation to implement reverse bound propagation.
forward_env: Environment providing bounds over the nodes of the network,
as obtained by a forward propagation.
backward_env: Backward environment to hold the bounds being propagated
backward.
target_indices: Indices of the nodes for which we want to obtain
backward bounds.
Returns:
targets: Propagated values corresponding to the required target_indices.
backward_env: Backward environment holding the bounds being propagated
backward.
"""
index = IndexCounter(self._last_index)
limit_index = sorted(target_indices)[0]
for eqn in reversed(self._graph.eqns):
self._backward_prop_eqn(transform, forward_env, backward_env, index, eqn)
if index.as_tuple() <= limit_index:
break
targets = []
for target_idx in target_indices:
node_ref = self._index_to_node[target_idx]
if node_ref in backward_env:
targets.append(transform.aggregate(read_env(backward_env, node_ref)))
else:
targets.append(None)
return targets, backward_env
def backward_propagation(
self,
transform: BackwardGraphTransform[BackRepr],
forward_env: Mapping[jax.core.Var, LayerInput[TransformedNode]],
backward_bounds: Mapping[jax.core.Var, BackRepr],
target_indices: Sequence[Index],
) -> Tuple[
Sequence[Optional[BackRepr]],
Mapping[jax.core.Var, Sequence[BackRepr]]]:
"""Performs backward prop from an intermediate node up to target nodes.
Args:
transform: Backward Transformation to implement reverse bound propagation.
forward_env: Environment providing bounds over the nodes of the network,
as obtained by a forward propagation.
backward_bounds: Dict mapping the initial bounds that we want to propagate
backward.
target_indices: Indices of the nodes in the graph that we want to reach.
It is the responsibility of the caller to ensure that valid bounds can
be derived with only these bounds.
Returns:
targets: Propagated values corresponding to the required target_indices.
"""
backward_env = collections.defaultdict(list)
for node_ref, node_out in backward_bounds.items():
backward_env[node_ref].append(node_out)
return self._propagate_backward(transform, forward_env, backward_env,
target_indices)
def _backward_prop_eqn(
self,
transform: BackwardGraphTransform[BackRepr],
forward_env: Mapping[jax.core.Var, LayerInput[TransformedNode]],
backward_env: MutableMapping[jax.core.Var, List[BackRepr]],
index: IndexCounter, eqn: jax.core.JaxprEqn):
"""Recursive step of `backward_propagation`."""
def subgraph_handler(
sub_transform, sub_graph, outval: BackRepr,
) -> Sequence[Sequence[BackRepr]]:
assert len(eqn.outvars) == 1
if outval is not None:
# If we are actually backpropagating something, update the backward
# environment correctly.
outvals = [outval]
if sub_transform is transform:
# We must use the same environment, so that transformed equations
# in the sub-graph are included in it.
outvals = [read_env(backward_env, outvar) for outvar in eqn.outvars]
else:
# We must leave the environment intact, because it contains
# equations transformed by a different transformer.
# Set up a new environment.
raise NotImplementedError(
'Upstream backward transform attempting to process a sub-graph '
'that was not processed by the principal backward transform.')
# Add the sub-graph's outputs to the environment.
backward_env.update({ # pytype: disable=container-type-mismatch # jax-ndarray
sub_outvar: outval
for sub_outvar, outval in zip(sub_graph.outvars, outvals)})
# Recursively back-propagate through the sub-graph.
index.begin_child(len(sub_graph.eqns))
try:
for sub_eqn in reversed(sub_graph.eqns):
self._backward_prop_eqn(transform, forward_env, backward_env,
index, sub_eqn)
if index.child_index() != 0:
raise ValueError('Forward/backward indexing mismatch')
finally:
index.end_child()
# Associate the sub-graph's inputs with the enclosing equation inputs.
# However, if it's a synthetic primitive, then its input variables _are_
# the sub-graph's input variables (no proxying with `_Ref`);
# in this case just return empty lists because the input vars have already
# received their back-propagated values during sub-graph traversal.
eqn_invals = [
[] if sub_invar is invar else read_env(backward_env, sub_invar)
for sub_invar, invar in zip(sub_graph.invars, eqn.invars)]
return eqn_invals
# Decrement the index to match the indexing in the forward propagation.
index.decr()
if all(not isinstance(read_env(forward_env, outvar), TransformedNode)
for outvar in eqn.outvars):
# None of the outputs are bounds, which means that there is no dependency
# on the network's bound inputs.
eqn_invals = [[None] for _ in eqn.invars]
elif len(eqn.outvars) == 1:
# If there is only a single output and it's a bound, perform backward
# transformation
if eqn.outvars[0] != self._index_to_node[index.as_tuple()]:
raise ValueError('Forward/backward indexing mismatch')
# Check if a repr is being propagated backward through this primitive.
repr_on_outvar = eqn.outvars[0] in backward_env
eqn_outval = None
if repr_on_outvar:
# Get the BackReprs on the outvar so that we can ensure that it's not
# just an empty list.
outvar_reprs = read_env(backward_env, eqn.outvars[0])
if outvar_reprs:
eqn_outval = transform.aggregate(outvar_reprs)
if (eqn_outval is not None
or transform.should_handle_as_subgraph(eqn.primitive)):
# The two cases where we want to recurse into the primitives are:
# - If we have something to propagate backward on the output of the
# primitive (so eqn_outval is not None)
# - If this primitive should be handled as a subgraph, because the
# backward_env might contain something to backpropagate on the
# intermediate nodes.
eqn_invars_vals = jax.tree_util.tree_map(
functools.partial(read_env, forward_env), eqn.invars)
eqn_invals = transform.equation_backtransform(
TransformContext(index.as_tuple(), subgraph_handler),
eqn.primitive, eqn_outval, *eqn_invars_vals, **eqn.params)
else:
# If we do not propagate backward through this primitive, we do not want
# to fill the backward_env with dummy None variables. This way the
# parents of this bound will also not be executed unless a backward
# bound was defined on them.
eqn_invals = []
else:
# This multi output primitive produces a bound, which is not
# supported yet.
raise NotImplementedError('Multiple outputs primitives are not '
'supported.')
for in_var, in_val in zip(eqn.invars, eqn_invals):
# If it's a literal, there are no updates to perform.
if not isinstance(in_var, jax.core.Literal):
backward_env[in_var].extend(in_val)
| jax_verify-master | jax_verify/src/graph_traversal.py |
# coding=utf-8
# 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.
"""Bound with L1 constraints."""
import jax
from jax import numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import opt_utils
from jax_verify.src.types import Tensor
class SimplexIntervalBound(bound_propagation.IntervalBound):
"""Represent a bound for which we have a constraint on the sum of coordinates.
Each coordinate is subject to interval constraints, and the sum of all
coordinates must be equal to a given value.
"""
def __init__(self, lower_bound: Tensor, upper_bound: Tensor,
simplex_sum: float):
super(SimplexIntervalBound, self).__init__(lower_bound, upper_bound)
self._simplex_sum = simplex_sum
@property
def simplex_sum(self) -> float:
return self._simplex_sum
@classmethod
def from_jittable(
cls,
jittable_simplexint_bound: bound_propagation.JittableInputBound
) -> 'SimplexIntervalBound':
return cls(jittable_simplexint_bound.lower,
jittable_simplexint_bound.upper,
jittable_simplexint_bound.kwargs['simplex_sum'])
def to_jittable(self) -> bound_propagation.JittableInputBound:
return bound_propagation.JittableInputBound(
self.lower, self.upper, {SimplexIntervalBound: None},
{'simplex_sum': self.simplex_sum})
def project_onto_bound(self, tensor: Tensor) -> Tensor:
return opt_utils.project_onto_interval_simplex(self.lower, self.upper,
self.simplex_sum, tensor)
def concretize_linear_function_simplexinterval_constraints(
linexp, input_bound: SimplexIntervalBound) -> Tensor:
"""Compute the lower bound of a linear function under Simplex constraints."""
solve_lin = jax.vmap(opt_utils.fractional_exact_knapsack,
in_axes=(0, None, None, None))
# We are maximizing -lin_coeffs*x in order to minimize lin_coeffs*x
neg_sum_lin_bound = solve_lin(-linexp.lin_coeffs, input_bound.simplex_sum,
input_bound.lower, input_bound.upper)
return linexp.offset - neg_sum_lin_bound
def concretizing_input_simplexinterval_constraints(
linexp, input_bound: SimplexIntervalBound) -> Tensor:
"""Compute the input that achieves the lower bound of a linear function."""
flat_lower = jnp.reshape(input_bound.lower, (-1,))
flat_upper = jnp.reshape(input_bound.upper, (-1,))
flat_lin_coeffs = jnp.reshape(linexp.lin_coeffs, (-1, flat_lower.size))
def single_linexpr_concretizing_inp(coeffs):
_, sorted_lower, sorted_upper, sorted_idx = jax.lax.sort(
(coeffs, flat_lower, flat_upper, jnp.arange(coeffs.size)), num_keys=1)
sorted_assignment = opt_utils.sorted_knapsack(sorted_lower, sorted_upper,
input_bound.simplex_sum,
backward=False)
# This is a cute trick to avoid using a jnp.take_along_axis, which is
# usually quite slow, particularly on TPU, when you do permutation.
# jax.lax.sort can take multiple arguments, and will sort them according
# to the ordering of the first tensor.
# When we did the sorting of the weights, we also sorted the index of each
# coordinate. By sorting by it, we will recover the initial ordering.
_, assignment = jax.lax.sort((sorted_idx, sorted_assignment), num_keys=1)
return assignment
flat_conc_input = jax.vmap(single_linexpr_concretizing_inp)(flat_lin_coeffs)
return jnp.reshape(flat_conc_input, linexp.lin_coeffs.shape)
| jax_verify-master | jax_verify/src/simplex_bound.py |
# coding=utf-8
# 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.
"""Define convex relaxations for primitives."""
import dataclasses
import functools
from typing import Callable, Mapping, Optional, Sequence, Tuple, Union
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import mccormick
from jax_verify.src import opt_utils
from jax_verify.src import simplex_bound
from jax_verify.src import synthetic_primitives
from jax_verify.src import utils
from jax_verify.src.types import Primitive, Tensor, TensorFun # pylint: disable=g-multiple-import
import typing_extensions
def posbilinear_piecewise_linear_relaxation(
inp_x: bound_propagation.Bound, inp_y: bound_propagation.Bound, **params):
"""Piecewise linear relaxation of a Positive Bilinear primitive.
This uses pairwise interpolations of the McCormick inequalities.
For x in [x_l, x_u] and y in [y_l, y_u], the bound imposed are:
x·y >= x·y_l + x_l·y - x_l·y_l
x·y >= x·y_u + x_h·y - x_h·y_u
x·y <= x·y_u + x_l·y - x_l·y_u
x·y <= x·y_l + x_u·y - x_l·y_u
Args:
inp_x: Bounds on the first input.
inp_y: Bounds on the second input.
**params: Keywords parameters, notably containing the `jax_verify_subgraph`
that defines the bilinear primitive.
Returns:
lb_funs: Pair of linear lower-bounding functions.
ub_funs: Pair of linear upper-bounding functions.
"""
lb_fun0, lb_fun1, ub_fun0, ub_fun1 = (
mccormick.posbilinear_mccormick_relaxations(
functools.partial(synthetic_primitives.posbilinear_p.bind, **params),
inp_x.lower, inp_x.upper, inp_y.lower, inp_y.upper))
return (lb_fun0, lb_fun1), (ub_fun0, ub_fun1)
def fused_relu_relaxation(linear_out: bound_propagation.Bound,
*linear_inps: bound_propagation.LayerInput,
**params):
"""Performs the relaxation of a Fused ReLU primitive.
Args:
linear_out: Output of a linear primitive, input to the ReLU.
*linear_inps: Inputs to the linear layer that produced linear_out.
**params: Params of the Fused Relu operation, mainly the jaxpr defining it.
Returns:
lb_fun, ub_fun
"""
del linear_out
# Check that we can handle the primitive that we have been given.
subgraph = params['jax_verify_subgraph']
lin_eqn = params['jax_verify_fusedlinear']
# Ensure that we have the expected structure.
assert len(subgraph.eqns) == 1
relu_eqn = subgraph.eqns[0]
assert relu_eqn.primitive is synthetic_primitives.relu_p
assert relu_eqn.invars[0] is lin_eqn.outvars[0]
# Get the linear part isolated
bound_args = [(i, arg) for i, arg in enumerate(linear_inps)
if isinstance(arg, bound_propagation.Bound)]
# Ensure that we have a single bound input.
assert len(bound_args) == 1
bound_arg_index, bound_arg = bound_args[0]
# The input to the ReLU is always going to be an intermediate value, by
# construction, so the inputs to the lin_eqn are the same as the input
# to the fused_relu.
bound_linear_fun = utils.bind_nonbound_args(lin_eqn.primitive.bind,
*linear_inps, **lin_eqn.params)
def flat_bound_linear_fun(flat_inp):
inp = jnp.reshape(flat_inp, bound_arg.shape)
out = bound_linear_fun(inp)
return jnp.ravel(out)
zero_bound_inp = jnp.zeros(bound_arg.shape)
flat_zero_bound_inp = jnp.ravel(zero_bound_inp)
flat_lbs = jnp.ravel(bound_arg.lower)
flat_ubs = jnp.ravel(bound_arg.upper)
flat_lin_weight = jax.jacrev(flat_bound_linear_fun)(flat_zero_bound_inp)
lin_bias = bound_linear_fun(zero_bound_inp)
flat_lin_bias = jnp.ravel(lin_bias)
lb_fun = functools.partial(synthetic_primitives.fused_relu_p.bind, **params)
if True:
# Define the relaxation of the Fused ReLU over a hypercube - interval bound.
single_neuron_ub_fun = alt_fused_relu_hypercube_upper_bound(
flat_lbs, flat_ubs
)
flat_param_ub_fun = jax.vmap(single_neuron_ub_fun, in_axes=(0, 0, None))
flat_ub_fun = functools.partial(flat_param_ub_fun, flat_lin_weight,
flat_lin_bias)
def ub_fun(linear_out, *linear_inps):
del linear_out
# Find the input corresponding to the bound input to the linear.
bound_inp = linear_inps[bound_arg_index]
flat_bound_inp = jnp.ravel(bound_inp)
flat_upper_bound = flat_ub_fun(flat_bound_inp)
return jnp.reshape(flat_upper_bound, lin_bias.shape)
return lb_fun, ub_fun
def fused_relu_ubfun(
bound: graph_traversal.InputBound
) -> Callable[[Tensor, Tensor, Tensor, Tensor], Tensor]:
"""Get the function upper bounding a ReLU still parameterized by z."""
if True:
_, solve_given_z = fused_relu_hypercube_upper_bound(
bound.lower.flatten(), bound.upper.flatten())
return solve_given_z
def alt_fused_relu_hypercube_upper_bound(
flat_lbs: Tensor, flat_ubs: Tensor
) -> Callable[[Tensor, Tensor, Tensor], Tensor]:
"""Performs the relaxation of the FusedReLU over an hypercube.
This is based on the algorithm described in:
" The Convex Relaxation Barrier, Revisited: Tightened Single-Neuron
Relaxations for Neural Network Verification "
Args:
flat_lbs: Tensor of flattened lower bounds.
flat_ubs: Tensor of flattened upper bounds.
Returns:
ub_fun: Function computing the concave upper bound of a fused relu when
given the coefficient of a linear function, the bias, and the point at
which to evaluate the upper bound.
"""
def ub_fun(coeffs: Tensor, bias: float, x: Tensor) -> float:
# Let's define l_cup and u_cup.
# l_cup contains the bound value that each neuron should be at when we want
# to achieve the lowest possible value after the linear layer.
# u_cup contains the value when we want to achieve the highest values.
l_cup = jnp.where(coeffs >= 0, flat_lbs, flat_ubs)
u_cup = flat_lbs + flat_ubs - l_cup
# We define the value L(I) to be
# sum_{i in I} w_i l_cup(i) + sum_{i not in I} w_i u_cup(i) + b
# This corresponds to the value at a specific vertex of the input domain to
# the fused relu.
# Computing an upper bound requires to find a set I such that:
# L(I) >= 0
# and L(I + {h}) < 0
# The corresponding bound is given by:
# (a) sum_{i in I} w_i (x_i - l_cup(i))
# (b) + L(I) * (x_h - l_cup(h)) / (u_cup(h) - l_cup(h))
# We compute scores that indicate to us in which order we are going to add
# elements to the set I. This is based on (x - l_cup) / (u_cup - l_cup), but
# we are also putting all the elements with weights = 0 at the end.
# We also need to be careful for the cases where u_cup is equal to l_cup, in
# which case the input has no impact on L(I), on score(h) or on the bound.
# Proposition 1-2 in the paper explain why this is the right order to get
# the tightest bound.
tied_bounds = jnp.abs(u_cup - l_cup) < 1e-6
safe_denom = jnp.where(tied_bounds, 1., u_cup - l_cup)
scores = (x - l_cup) / safe_denom
no_zw_scores = jnp.where((coeffs == 0.) | tied_bounds, jnp.inf, scores)
# We are going to compute the L(I) as a function of the number of elements
# that we have added into the I set so far, based on the order given by
# `score_order`.
# ini_li is equivalent to computing the upper bound with IBP. This
# corresponds to an empty set I.
ini_li = jnp.sum(u_cup * coeffs) + bias
# li_inc is how much you change l_i by adding a given variable to the I set.
# It is necessarily negative, (because we switch from a positive
# contribution to a negative contribution.)
li_inc = coeffs * (l_cup - u_cup)
# w_xml is the contribution of a given variable to the evaluated bound if it
# is in the I set.
w_xml = coeffs * (x - l_cup)
# Compute all the reorganized arrays together to avoid having to do costly
# take_along_axis operations.
scores_sorted, li_inc_sorted, wxml_sorted = jax.lax.sort(
[no_zw_scores, li_inc, w_xml], num_keys=1)
li_end = ini_li + jnp.cumsum(li_inc_sorted)
# This is L(I) from which we are progressively going to take. We need to
# remove the contribution so that index=0 actually corresponds to the set I
# with 0 elements.
li = li_end - li_inc_sorted
# iopt is the index just before h, the last index for which L(I) is > 0.
# As L(I) is strictly decreasing, this will be a one-hot vector.
i_opt_mask = jnp.diff(li <= 0., append=jnp.array([True]))
# Similarly as for the L(I) computation, we remove the increment from the
# cumsum so that we represent correctly the case where I is empty
acced_sorted_wxml = jnp.cumsum(wxml_sorted) - wxml_sorted
# Let's now compute the corresponding bound, as described above. We will
# use the i_opt_mask to select the correct values.
a_part = acced_sorted_wxml
b_part = li * scores_sorted
relaxation_upper_bound = ((a_part + b_part) * i_opt_mask).sum()
# The relaxation computed so far is only valid if the ReLU is ambiguous.
# In the other cases, we now exactly the values of the output bound.
ibp_ub = ini_li
ibp_lb = jnp.sum(l_cup * coeffs) + bias
pass_through = jnp.sum(x * coeffs) + bias
upper_bound = jnp.where(ibp_lb > 0., pass_through,
jnp.where(ibp_ub < 0., 0., relaxation_upper_bound))
return upper_bound
return ub_fun # pytype: disable=bad-return-type # jax-ndarray
def fused_relu_hypercube_upper_bound(
flat_lbs: Tensor, flat_ubs: Tensor
) -> Tuple[Callable[[Tensor, Tensor, Tensor], Tensor],
Callable[[Tensor, Tensor, Tensor, Tensor], Tensor]]:
"""Performs the relaxation of the FusedReLU over an hypercube.
This corresponds to the upper bound obtained based on the Sharp formulation,
as described in Equation (1) of the "Bounds for Verified Compressed Sensing"
document.
We return two upper bounds because there exists two different settings:
- If the fused ReLU is defined only over a hypercube, we can use the first
bound as we know how to efficiently maximize over z.
- If the fused ReLU is defined over a product of domains, the problem is
more complex. We need to optimize z based on the maximization produced by
*all* the domains, so we need to return the un-optimized (over z) bound,
so that we can construct the overall bound function.
Args:
flat_lbs: Tensor of flattened lower bounds.
flat_ubs: Tensor of flattened upper bounds.
Returns:
ub_fun: Concave upper bound operating on the flattened input to the
FusedReLU.
solve_given_z: Upper bound over the output of the ReLU which is still
dependent on z.
"""
bound_gap = flat_ubs - flat_lbs
def solve_given_z(coeffs: Tensor, bias: float, x: Tensor, z: float):
alpha_equal_w_case = (coeffs * x
+ (1 - z) * (jnp.maximum(-coeffs, 0) * bound_gap
- coeffs * flat_lbs))
alpha_equal_0_case = z * (jax.nn.relu(coeffs) * bound_gap
+ coeffs * flat_lbs)
return jnp.minimum(alpha_equal_w_case, alpha_equal_0_case).sum() + bias * z
eval_all_z = jax.vmap(solve_given_z, in_axes=(None, None, None, 0))
def single_neuron_ub_fun(coeffs, bias, x):
ibp_upper = (jnp.maximum(coeffs, 0) * flat_ubs
+ jnp.minimum(coeffs, 0) * flat_lbs)
ibp_lower = (jnp.maximum(coeffs, 0) * flat_lbs
+ jnp.minimum(coeffs, 0) * flat_ubs)
ibp_bound_gap = ibp_upper - ibp_lower
safe_gap = jnp.where(ibp_bound_gap != 0., ibp_bound_gap, 1.)
possible_z = (coeffs * x - ibp_lower) / safe_gap
possible_z = jnp.concatenate((possible_z, jnp.array([0., 1.])))
vals_all_z = eval_all_z(coeffs, bias, x, possible_z)
return jnp.max(vals_all_z)
return single_neuron_ub_fun, solve_given_z # pytype: disable=bad-return-type # jax-ndarray
def convex_fn_relaxation(
primitive: Primitive,
*args: Union[bound_propagation.Bound, Tensor],
**params) -> Tuple[TensorFun, TensorFun]:
"""Relaxation of an element-wise convex primitive.
Args:
primitive: Convex primitive to relax.
*args: Inputs to the convex function: bounds on the input, unnamed params.
**params: Params of the convex operation, mainly the jaxpr defining it.
Returns:
lb_fun, ub_fun
"""
prim_fun = utils.bind_nonbound_args(primitive.bind, *args, **params)
inp, = [arg for arg in args if isinstance(arg, bound_propagation.Bound)]
x_lb, x_ub = inp.lower, inp.upper
y_lb, y_ub = prim_fun(x_lb), prim_fun(x_ub)
has_interval = x_ub != x_lb
denom = jnp.where(has_interval, x_ub - x_lb, jnp.ones_like(x_lb))
chord_slope = jnp.where(
has_interval, (y_ub - y_lb) / denom, jnp.zeros_like(x_lb))
chord_intercept = jnp.where(
has_interval, (y_lb * x_ub - y_ub * x_lb) / denom, y_lb)
chord_fun = lambda x: chord_slope * x + chord_intercept
return prim_fun, chord_fun
def relu_piecewise_linear_relaxation(inp: bound_propagation.Bound) -> Tuple[
Tuple[TensorFun, TensorFun],
Tuple[TensorFun]]:
"""Piecewise linear relaxation of the ReLU function.
Args:
inp: Bound on the inputs to the ReLU.
Returns:
lb_funs: Pair of linear lower-bounding functions.
ub_funs: Linear upper-bounding function.
"""
lb_fun0 = jnp.zeros_like
lb_fun1 = lambda x: x
_, chord_fun = convex_fn_relaxation(synthetic_primitives.relu_p, inp)
return (lb_fun0, lb_fun1), (chord_fun,)
def leaky_relu_piecewise_linear_relaxation(
inp: bound_propagation.Bound, *, negative_slope: float,
) -> Tuple[Sequence[TensorFun], Sequence[TensorFun]]:
"""Piecewise linear relaxation of the leaky ReLU.
Depending on how negative_slope compares to 1.0, the leaky_relu function is
going to either be convex or concave. The other function is going to be given
by its chord.
Args:
inp: Bounds on the leaky ReLU input.
negative_slope: Slope for negative inputs.
Returns:
lb_funs: Pair of linear lower-bounding functions (or single function if
negative_slope > 1).
ub_funs: Linear upper-bounding function (or pair if negative_slope > 1).
"""
lr_fun0 = lambda x: negative_slope * x
lr_fun1 = lambda x: x
_, chord_fun = convex_fn_relaxation(
synthetic_primitives.leaky_relu_p, inp, negative_slope=negative_slope)
if negative_slope > 1.:
# The leaky ReLu is a concave function
return (chord_fun,), (lr_fun0, lr_fun1)
else:
# The leaky Relu is a convex function
return (lr_fun0, lr_fun1), (chord_fun,)
def cvx_parametric_leaky_relu_pl_relaxation(
inp: bound_propagation.Bound, negative_slope: Tensor,
) -> Tuple[Sequence[TensorFun], Sequence[TensorFun]]:
"""Piecewise linear relaxation of convex (slope < 1) parametric leaky ReLU.
NOTE: the relaxation is valid only if the function is convex:
jnp.all(negative_slope < 1.)
TODO: could be adapted to work for all prelus by returning two lower
and upper bounding functions in any case. This would require handling in other
places where piecewise_linear_relaxation_fn is employed
(e.g., mip_solver/relaxation.py)
Args:
inp: Bounds on the leaky ReLU input.
negative_slope: Slope for negative inputs.
Returns:
lb_funs: Pair of linear lower-bounding functions.
ub_funs: Linear upper-bounding function.
"""
# All returned functions accept two inputs to comply with the primitive.
# The second input (negative_slope) is not used as it's passed in this scope.
lr_fun0 = lambda x, y: negative_slope * x
lr_fun1 = lambda x, y: x
_, chord_fun = convex_fn_relaxation(
synthetic_primitives.parametric_leaky_relu_p, inp, negative_slope)
# NOTE: assumes the leaky Relu is a convex function (negative_slope < 1)
return (lr_fun0, lr_fun1), (lambda x, y: chord_fun(x),)
def clip_piecewise_linear_relaxation(
inp: bound_propagation.Bound,
a_min: float, a_max: float,
) -> Tuple[Sequence[TensorFun], Sequence[TensorFun]]:
"""Piecewise linear relaxation of the Clipping function.
Args:
inp: Bounds on the clipped input.
a_min: Minimum value imposed on the output.
a_max: Maximum value imposed on the output.
Returns:
lb_funs: Pair of linear lower-bounding functions.
ub_funs: Pair of linear upper-bounding functions.
"""
clip_fun = functools.partial(jnp.clip, a_min=a_min, a_max=a_max)
x_lb, x_ub = inp.lower, inp.upper
y_lb, y_ub = clip_fun(inp.lower), clip_fun(inp.upper)
passing_has_interval = y_ub != y_lb
passing_ub_denom = jnp.where(passing_has_interval,
y_ub - x_lb, jnp.ones_like(x_lb))
passing_ub_slope = jnp.where(passing_has_interval,
(y_ub - y_lb) / passing_ub_denom,
jnp.zeros_like(x_lb))
passing_ub_intercept = jnp.where(passing_has_interval,
y_lb - passing_ub_slope * x_lb, y_ub)
passing_ub = lambda x, *_: passing_ub_slope * x + passing_ub_intercept
clipped_ub = lambda x, *_: a_max * jnp.ones_like(x_lb)
passing_lb_denom = jnp.where(passing_has_interval,
x_ub - y_lb, jnp.ones_like(x_lb))
passing_lb_slope = jnp.where(passing_has_interval,
(y_ub - y_lb) / passing_lb_denom,
jnp.zeros_like(x_lb))
passing_lb_intercept = jnp.where(passing_has_interval,
y_lb * (1 - passing_lb_slope), y_lb)
passing_lb = lambda x, *_: passing_lb_slope * x + passing_lb_intercept
clipped_lb = lambda x, *_: a_min * jnp.ones_like(x_lb)
return (clipped_lb, passing_lb), (passing_ub, clipped_ub)
def abs_piecewise_linear_relaxation(inp: bound_propagation.Bound) -> Tuple[
Tuple[TensorFun, TensorFun],
Tuple[TensorFun]]:
"""Piecewise linear relaxation of the abs function.
Args:
inp: Bound on the inputs to the Abs.
Returns:
lb_funs: Pair of linear lower-bounding functions.
ub_funs: Linear upper-bounding function.
"""
lb_fun0 = lambda x: -x
lb_fun1 = lambda x: x
_, chord_fun = convex_fn_relaxation(lax.abs_p, inp)
return (lb_fun0, lb_fun1), (chord_fun,)
def _find_s_shape_upper_bound_tangent(
fun: TensorFun, dfun: TensorFun, approx_tang_pt: TensorFun,
range_lb: Tensor, range_ub: Tensor,
tol: float) -> Tensor:
"""Search the point where the concave hull of s-shape fun stops being linear.
The concave upper bound of an s-shape function can be several things:
- It can be the function itself (if the interval considered is in R+)
- It can be linear (If the upper bound is small enough. This is a bit more
general that just if the interval is in R-)
- It can start linear and at some tangent point become the function.
This functions searches for the tangent point.
For the other cases, another function would have narrowed the search range
such that range_lb = range_ub and we early exit from the loop.
This is a combination of a binary search and of the Newton method.
Args:
fun: Function for which we are trying to find the cutoff.
dfun: Derivative of the function for which we are trying to find the cutoff.
approx_tang_pt: Approximate solution of the cutoff when the lower bound is
large.
range_lb: Lower bound of the domain on which to define the convex hull.
range_ub: Upper bound of the domain on which to define the convex hull.
tol: Tolerance criterion for convergence
Returns:
final_t: Tangent point at which the concave upper bound of the sigmoid
should go from linear to sigmoid. If range_lb == range_ub, that number
should be returned.
"""
flat_range_lb = jnp.reshape(range_lb, (-1,))
flat_range_ub = jnp.reshape(range_ub, (-1,))
# The point that we are looking for is the point where:
# dfun(x) = (fun(x) - fun(lb)) / (x - lb)
to_root_fun = lambda x, lb: dfun(x) - (fun(x)-fun(lb))/jnp.maximum(x-lb, tol)
to_root_val_and_grad = jax.vmap(jax.value_and_grad(to_root_fun))
search_lb = jnp.maximum(flat_range_lb, 0.)
search_ub = jnp.maximum(flat_range_ub, 0.)
upper_bound_for_large_l = jnp.where(flat_range_lb < -1e3,
approx_tang_pt(flat_range_lb),
float('inf'))
search_ub = jnp.minimum(flat_range_ub, upper_bound_for_large_l)
t_k = 0.5 * (search_lb + search_ub)
it = jnp.array(0)
def body_fun(loop_args):
it, t, lb, ub = loop_args
new_it = it + 1
f, df = to_root_val_and_grad(t, flat_range_lb)
new_lb = jnp.where(f >= 0., jnp.maximum(lb, t), lb)
new_ub = jnp.where(f <= 0., jnp.minimum(ub, t), ub)
newton_t = t - f / df
out_of_bounds_t = (newton_t <= new_lb) | (newton_t >= new_ub)
new_t = jnp.where((jnp.abs(df) <= tol) | out_of_bounds_t,
0.5 * (new_lb + new_ub),
newton_t)
return new_it, new_t, new_lb, new_ub
def continue_search(loop_args):
it, t, lb, ub = loop_args
# Points that have not converged have both
# - high value on the difference between average slope and sig derivative
# - high value on the gap between upper bound and lower bound
# If any one of this criterion is not satisfied, the point has converged.
not_converged = ((jnp.abs(to_root_fun(t, flat_range_lb)) >= tol) &
((ub - lb) >= tol))
# We keep searching as long as:
# - we don't exceed 100 iterations
# - There is at least 1 point that has not converged.
return jnp.logical_and(it <= 100, jnp.any(not_converged))
_, final_t, _, _ = jax.lax.while_loop(
continue_search, body_fun, (it, t_k, search_lb, search_ub))
final_t = jax.lax.stop_gradient(final_t)
# The search that we implemented is only valid when we are looking for the
# tangent point in R^+. In case we have called the search function with
# negative values, we should recover those.
final_t = jnp.clip(final_t, flat_range_lb, flat_range_ub)
final_t = jnp.reshape(final_t, range_lb.shape)
return final_t
def _find_upperbound_s_shape_linear_cutoff(
fun: TensorFun, dfun: TensorFun, approx_tang_pt: TensorFun,
lbs: Tensor, ubs: Tensor, tol: float
) -> Tensor:
"""Find the point where the s-shape concave upper bound stops being linear.
This function restricts the search space to a single point for the cases where
the concave upper bound is simply the function or is fully linear. It then
calls the binary search function.
Args:
fun: Function for which we are trying to find the cutoff.
dfun: Derivative of the function for which we are trying to find the cutoff.
approx_tang_pt: Approximate solution of the cutoff when the lower bound is
lbs: Lower bound of the domain on which to define the convex hull.
ubs: Upper bound of the domain on which to define the convex hull.
tol: Tolerance for numerical operations
Returns:
linear_cutoff_pt: Tangent point at which the concave upper bound of the
s-shaped function should go from linear to s-shaped function.
"""
dfun_ub = dfun(ubs)
avg_slope = (fun(ubs) - fun(lbs)) / jnp.maximum(ubs - lbs, tol)
t_lb = jnp.where((lbs <= 0.) & (dfun_ub >= avg_slope), ubs, lbs)
t_ub = jnp.where(lbs >= 0, lbs, ubs)
binary_search_fun = functools.partial(_find_s_shape_upper_bound_tangent,
fun, dfun, approx_tang_pt, tol=tol)
short_circuit_fun = lambda l, u: l
linear_cutoff_pt = jax.lax.cond(jnp.all(t_lb == t_ub),
short_circuit_fun, binary_search_fun,
t_lb, t_ub)
return linear_cutoff_pt
def s_shape_relaxation(
fun: TensorFun,
dfun: TensorFun,
approx_tang_pt: TensorFun,
inp: bound_propagation.Bound,
tol: float = 1e-6,
) -> Tuple[TensorFun, TensorFun]:
"""Perform the relaxation of an S-shape function.
See the supplementary materials of https://arxiv.org/pdf/2002.10410.pdf for
the derivation.
The tricky part is to determine when does the function concave upper bound (
respectively convex lower bound) switch from being linear to being the
function itself. We solve the problem of finding where the cutoff point is
between those two parts.
Args:
fun: Function to get the convex hull of, assumed to be s-shape.
What this means is that the function is:
- Odd (f(-x) = - f(x))
- Monotonically increasing.
- The derivative is 0. at -inf and +inf.
- The function is convex over R^- and concave over R^+
dfun: Derivative of the function.
approx_tang_pt: Upper bound on the position of the tangent point when the
lower bound of the domain is very large.
inp: Bound on the inputs to the S-shape function.
tol: Tolerance criterion
Returns:
lb_fun, ub_fun
"""
lbs = inp.lower
ubs = inp.upper
# Derive the concave upper bound, find where the cutoff is between the linear
# part and the s-shaped part
up_tangent_point = _find_upperbound_s_shape_linear_cutoff(
fun, dfun, approx_tang_pt, lbs, ubs, tol)
up_lin_slope = (fun(up_tangent_point) - fun(lbs)) / (
jnp.maximum(up_tangent_point - lbs, tol))
up_lin_offset = fun(up_tangent_point) - up_lin_slope * up_tangent_point
def s_shape_upper_concave(x):
return jnp.where(jnp.greater_equal(x, up_tangent_point),
fun(x), up_lin_slope * x + up_lin_offset)
# Derive the convex lower bound, find there the cutoff is between the s-shaped
# part and the linear part. By symmetry, we can reuse the upper bound code.
neg_low_tangent_point = _find_upperbound_s_shape_linear_cutoff(
fun, dfun, approx_tang_pt, -ubs, -lbs, tol)
low_tang_point = -neg_low_tangent_point
low_lin_slope = (fun(ubs) - fun(low_tang_point)) / (
jnp.maximum(ubs - low_tang_point, tol))
low_lin_offset = fun(low_tang_point) - low_lin_slope * low_tang_point
def s_shape_lower_convex(x):
return jnp.where(jnp.less_equal(x, low_tang_point),
fun(x), low_lin_slope * x + low_lin_offset)
return s_shape_lower_convex, s_shape_upper_concave
def sigmoid_relaxation(inp: bound_propagation.Bound,
tol: float = 1e-6
)->Tuple[TensorFun, TensorFun]:
"""Perform the relaxation of the sigmoid.
See the supplementary materials of https://arxiv.org/pdf/2002.10410.pdf for
the derivation.
Args:
inp: Bound on the inputs to the Sigmoid
tol: Tolerance criterion
Returns:
lb_fun, ub_fun
"""
sigmoid = jax.nn.sigmoid
dsigmoid = lambda x: sigmoid(x) * (1 - sigmoid(x))
# In the case where l is very large (in the negative), we can have an
# approximate solution of the tangent point. We can use this to shrink the
# search space, making the binary search converge significantly faster.
# If lb<-1e3, fun(lb)=0, so we can just solve:
# dfun(x) = fun(x) / (x - lb).
# <=> fun(X) (1 - fun(x)) = fun(x) / (x - lb)
# <=> 1 - fun(x) = 1 / (x - lb)
# <=> exp(-x) / (1 + exp(-x)) = 1 / (x - lb)
# <=> exp(-x) * (x - lb - 1) = 1
# <=> exp(x) - x = -lb -1
# Given that we know x >=0 for a tangent point, we have exp(x) < - lb - 1
# Therefore the solution is upper bounded by log(-lb-1)
# We add some padding (+1) around that value to make sure we are not excluding
# a valid solution from the search space.
approx_sig_tang = lambda lb: jnp.log(jnp.maximum(-lb - 1., 1.)) + 1.
return s_shape_relaxation(sigmoid, dsigmoid, approx_sig_tang, inp, tol)
def tanh_relaxation(
inp: bound_propagation.Bound,
tol: float = 1e-6,
) -> Tuple[TensorFun, TensorFun]:
"""Perform the relaxation of the hyperbolic tangent.
This is an implementation modeled on the convex hull of the sigmoid.
Args:
inp: Bound on the inputs to the hyperbolic tangent.
tol: Tolerance criterion
Returns:
lb_fun, ub_fun
"""
tanh = jax.nn.tanh
dtanh = lambda x: 1 - tanh(x)**2
# In the case where l is very large, in the negative, we can have an
# approximate solution.
# If lb <-1e3, fun(lb) = -1
# dfun(x) = (fun(x) + 1) / (x - lb)
# <=> 1 - fun(x)**2 = (fun(x) + 1) / (x - lb)
# <=> (1 - fun(x)) * (1 + fun(x)) = (fun(x) + 1) / (x - lb)
# <=> (1 - fun(x)) = 1 / (x - lb)
# <=> 2 / (exp(2x) + 1) = 1 / (x - lb)
# <=> exp(2x) - 2x = -2*lb - 1
# We know that for the tangent point we are searching, x >= 0,
# so we know that for our solution exp(2x) <= -2 * lb - 1
# Therefore, we know that the solution is upperbounded by 0.5 * log(-2*lb -1.)
# We'll add some padding to ensure we are not excluding any valid solution.
approx_tanh_tang = lambda lb: 0.5*jnp.log(jnp.maximum(-2*lb-1., 1.)) + 1.
return s_shape_relaxation(tanh, dtanh, approx_tanh_tang, inp, tol)
def posreciprocal_relaxation(
inp: bound_propagation.Bound,
) -> Tuple[TensorFun, TensorFun]:
"""Relaxation of reciprocal, on strictly positive inputs.
The (unchecked) assumption is that inputs are always positive, and 1/x is
therefore convex.
Args:
inp: Bounds on the input.
Returns:
lb_fun, ub_fun
"""
safe_inp = bound_propagation.IntervalBound(
utils.safe_pos(inp.lower), utils.safe_pos(inp.upper))
return convex_fn_relaxation(synthetic_primitives.posreciprocal_p, safe_inp)
class RelaxationFn(typing_extensions.Protocol):
def __call__(
self,
*inputs: bound_propagation.Bound,
**params,
) -> Tuple[TensorFun, TensorFun]:
"""Convex relation.
Args:
*inputs: Bound on the inputs to the function.
**params: Keyword parameters of the primitive.
Returns:
Convex lower bound and concave upper bound.
"""
class PiecewiseLinearRelaxationFn(typing_extensions.Protocol):
def __call__(
self,
*inputs: bound_propagation.Bound,
**params,
) -> Tuple[Sequence[TensorFun], Sequence[TensorFun]]:
"""Piecewise linear convex relation.
Args:
*inputs: Bound on the inputs to the function.
**params: Keyword parameters of the primitive.
Returns:
Lists of lower and upper bounding linear functions.
"""
@dataclasses.dataclass
class ActivationRelaxation:
"""Activation function traits, including convex relaxation.
Attributes:
relaxation_fn: Accepts input bounds and params; returns convex lower bound
and concave upper bound.
piecewise_linear_relaxation_fn: Optional; accepts input bounds and params;
returns lists of lower and upper bounding linear functions.
pos_neg_linear: Whether this positive and negative parts of this
1D activation function are both affine, e.g. ReLU, sign.
convex: Whether the activation function is convex.
eltwise_increasing: Whether the activation function is known to be
element-wise monotonically increasing.
"""
relaxation_fn: RelaxationFn
piecewise_linear_relaxation_fn: Optional[PiecewiseLinearRelaxationFn] = None
pos_neg_linear: bool = False
convex: bool = False
eltwise_increasing: bool = False
def intersection_relaxation(
piecewise_linear_relaxation_fn: PiecewiseLinearRelaxationFn,
*inputs: Union[bound_propagation.Bound, Tensor],
**params,
) -> Tuple[TensorFun, TensorFun]:
"""Relaxation based on intersection of piecewise linear components.
Args:
piecewise_linear_relaxation_fn: Accepts input bounds and params;
returns lists of lower and upper bounding linear functions.
*inputs: Inputs to the convex function: bounds on the input, unnamed params.
**params: Keyword parameters of the primitive.
Returns:
lb_fun, ub_fun
"""
lb_funs, ub_funs = piecewise_linear_relaxation_fn(*inputs, **params)
def lower_bound(*x):
return functools.reduce(jnp.maximum, [lb_fun(*x) for lb_fun in lb_funs])
def upper_bound(*x):
return functools.reduce(jnp.minimum, [ub_fun(*x) for ub_fun in ub_funs])
return lower_bound, upper_bound
relaxation_fns: Mapping[Primitive, ActivationRelaxation] = {
synthetic_primitives.relu_p: ActivationRelaxation(
functools.partial(
intersection_relaxation, relu_piecewise_linear_relaxation),
piecewise_linear_relaxation_fn=relu_piecewise_linear_relaxation,
pos_neg_linear=True, convex=True, eltwise_increasing=True),
synthetic_primitives.leaky_relu_p: ActivationRelaxation(
functools.partial(
intersection_relaxation, leaky_relu_piecewise_linear_relaxation),
piecewise_linear_relaxation_fn=leaky_relu_piecewise_linear_relaxation,
pos_neg_linear=True),
# NOTE: only convex (negative_slope < 1.) parametric ReLUs are supported
synthetic_primitives.parametric_leaky_relu_p: ActivationRelaxation(
functools.partial(
intersection_relaxation,
cvx_parametric_leaky_relu_pl_relaxation),
piecewise_linear_relaxation_fn=cvx_parametric_leaky_relu_pl_relaxation,
pos_neg_linear=True),
synthetic_primitives.clip_p: ActivationRelaxation(
functools.partial(
intersection_relaxation, clip_piecewise_linear_relaxation),
piecewise_linear_relaxation_fn=clip_piecewise_linear_relaxation,
eltwise_increasing=True),
lax.abs_p: ActivationRelaxation(
functools.partial(
intersection_relaxation, abs_piecewise_linear_relaxation),
piecewise_linear_relaxation_fn=abs_piecewise_linear_relaxation,
pos_neg_linear=True, convex=True),
synthetic_primitives.softplus_p: ActivationRelaxation(
functools.partial(
convex_fn_relaxation, synthetic_primitives.softplus_p),
convex=True, eltwise_increasing=True),
lax.exp_p: ActivationRelaxation(
functools.partial(convex_fn_relaxation, lax.exp_p),
convex=True, eltwise_increasing=True),
synthetic_primitives.posreciprocal_p: ActivationRelaxation(
posreciprocal_relaxation, convex=True),
synthetic_primitives.sigmoid_p: ActivationRelaxation(
sigmoid_relaxation, eltwise_increasing=True),
lax.tanh_p: ActivationRelaxation(
tanh_relaxation, eltwise_increasing=True),
synthetic_primitives.posbilinear_p: ActivationRelaxation(
functools.partial(
intersection_relaxation, posbilinear_piecewise_linear_relaxation),
piecewise_linear_relaxation_fn=posbilinear_piecewise_linear_relaxation),
synthetic_primitives.fused_relu_p: ActivationRelaxation(
fused_relu_relaxation),
}
| jax_verify-master | jax_verify/src/activation_relaxation.py |
# coding=utf-8
# 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.
"""Propagate the bounds through the network.
This is accomplished by traversing the JaxPR representation of the computation
and translating the computational graph.
"""
import abc
import collections
from typing import Generic, Mapping, Sequence, Tuple, TypeVar, Union
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import graph_traversal
from jax_verify.src import synthetic_primitives
from jax_verify.src.types import Nest, Primitive, SpecFn, Tensor # pylint: disable=g-multiple-import
Repr = TypeVar('Repr', bound=graph_traversal.TransformedNode)
# (lower, upper) input bound represented as a Tensor nest so that it can
# be passed as a parameter to a Jax jitted function.
# `bound_type` should be a dictionary using the desired bound class as a key
# (the value that the key maps to is unimportant). This way, jax does not
# complain about it not being a jax type.
# Example: {jax_verify.IntervalBound: None}
# Additional arguments can be provided in `kwargs`,
# The Bound class should implement a `from_jittable` class method, to
# instantiate the object based on the jittable bound.
JittableInputBound = collections.namedtuple(
'JittableInputBound', ['lower', 'upper', 'bound_type', 'kwargs'])
JittableGraphInput = Union[JittableInputBound, Tensor]
class Bound(graph_traversal.TransformedNode, metaclass=abc.ABCMeta):
"""Abstract propagated bound."""
@property
@abc.abstractmethod
def lower(self) -> Tensor:
"""Concrete lower bound."""
@property
@abc.abstractmethod
def upper(self) -> Tensor:
"""Concrete upper bound."""
@property
def shape(self) -> Tuple[int, ...]:
"""Shape of the node."""
return self.lower.shape
@property
def dtype(self) -> jnp.dtype:
"""Data type of the node."""
return self.lower.dtype
def unwrap(self) -> 'Bound':
"""Underlying bound of method-specific type, without extra constraints.
Usually this returns `self`. However, subclasses that wrap the bound to
provide additional information (for example externally imposed interval
constraints) will return the wrapped bound.
Returns:
Underlying bound arising directly from bound propagation.
"""
return self
LayerInput = graph_traversal.LayerInput[Bound]
TransformContext = graph_traversal.TransformContext[Bound]
class IntervalBound(Bound, graph_traversal.InputBound):
"""Represent an interval where some activations might be valid."""
def __init__(self, lower_bound: Tensor, upper_bound: Tensor): # pylint: disable=super-init-not-called
# Pylint complains that the __init__ method of the base class Bound is not
# called, despite the fact that Bound does not have an __init__ method.
self._lower_bound = lower_bound
self._upper_bound = upper_bound
@property
def lower(self) -> Tensor:
return self._lower_bound
@property
def upper(self) -> Tensor:
return self._upper_bound
def update_bounds(self, lower, upper):
self._lower_bound = lower
self._upper_bound = upper
@classmethod
def from_jittable(cls, jittable_bound: JittableInputBound):
return cls(jittable_bound.lower, jittable_bound.upper)
def to_jittable(self) -> JittableInputBound:
return JittableInputBound(self.lower, self.upper, {IntervalBound: None}, {})
def project_onto_bound(self, tensor: Tensor) -> Tensor:
return jnp.clip(tensor, a_min=self._lower_bound, a_max=self._upper_bound)
def unwrapping(fn):
"""Create a wrapper function to unwrap the bound arguments.
Use as a decorator. If a propagation function has been defined assuming
its input bound arguments are of the method-specific type
(e.g. `fastlin.LinearBound`), then applying this decorator will allow the
function to accept wrapped bound arguments with extra constraints
(e.g. `intersection.ConstrainedBound`) which it will ignore.
Args:
fn: Function accepting possibly wrapped bound arguments.
Returns:
Function accepting bound arguments of the method-specific type.
"""
unwrap = lambda x: x.unwrap() if isinstance(x, Bound) else x
def fn_unwrapped(*args, **kwargs):
return fn(*[unwrap(arg) for arg in args], **kwargs)
return fn_unwrapped
BoundTransform = graph_traversal.GraphTransform[Bound]
class PropagationAlgorithm(Generic[Repr], metaclass=abc.ABCMeta):
@abc.abstractmethod
def propagate(
self,
graph: graph_traversal.PropagationGraph,
bounds: Nest[graph_traversal.GraphInput],
) -> Tuple[Nest[Repr], Mapping[jax.core.Var, Union[Repr, Tensor]]]:
"""Propagate the given input bounds on the given graph."""
class ForwardPropagationAlgorithm(PropagationAlgorithm[Repr]):
"""Forward graph propagation method."""
def __init__(self, graph_transform: graph_traversal.GraphTransform[Repr]):
self._graph_transform = graph_transform
def propagate(
self,
graph: graph_traversal.PropagationGraph,
bounds: Nest[graph_traversal.GraphInput],
) -> Tuple[Nest[Repr], Mapping[jax.core.Var, Union[Repr, Tensor]]]:
"""Propagate forward the given input bounds on the given graph."""
return graph.forward_propagation(self._graph_transform, bounds)
def jit_inputs(
*inputs: Nest[graph_traversal.GraphInput],
) -> Sequence[Nest[JittableGraphInput]]:
"""Replace all the bound objects by jittable bounds."""
is_bound = lambda b: isinstance(b, Bound)
jit_bound = lambda b: b.to_jittable()
return jax.tree_util.tree_map(
lambda b: jit_bound(b) if is_bound(b) else b,
inputs, is_leaf=is_bound)
def unjit_inputs(
*inputs: Nest[JittableGraphInput],
) -> Sequence[Nest[graph_traversal.GraphInput]]:
"""Replace all the jittable bounds by standard bound objects."""
is_jittable_bound = lambda b: isinstance(b, JittableInputBound)
unjit_bound = lambda b: next(iter(b.bound_type)).from_jittable(b)
return jax.tree_util.tree_map(
lambda b: unjit_bound(b) if is_jittable_bound(b) else b,
inputs, is_leaf=is_jittable_bound)
def bound_propagation(
prop_alg: PropagationAlgorithm[Repr],
function: SpecFn,
*bounds: Nest[graph_traversal.GraphInput],
graph_simplifier=synthetic_primitives.default_simplifier,
) -> Tuple[
Nest[Union[Repr, Tensor]],
Mapping[jax.core.Var, Union[Repr, Tensor, Bound]]]:
"""Performs Bound Propagation on the model implemented by `function`.
Args:
prop_alg: Algorithm specifying how to traverse the graph and how to
transform each node.
function: Pure function inputs -> outputs. If the function to propagate
through has a more complex signature, the use of `functools.partial` can
solve that problem.
*bounds: Nest of `IntervalBound` objects containing the lower and upper
bounds on all the inputs, or `Tensor`s containing known inputs directly.
graph_simplifier: Function transforming the JaxPR graph into a simpler
graph. Default value is a function identifying specific activation
functions, followed by grouping of linear sequences and quadratic forms.
Returns:
bounds: Bounds over all the outputs of the function, with the same structure
as the output of `function`
env: Mapping from the node of the computations to their representation.
"""
# Parse the computation graph.
placeholder_inputs = jax.tree_util.tree_map(
lambda b: b.lower if isinstance(b, graph_traversal.InputBound) else b,
bounds)
parsed = synthetic_primitives.make_jaxpr_nojit(function, *placeholder_inputs)
output_shapes = jax.eval_shape(function, *placeholder_inputs)
flat_is_bound, _ = jax.tree_util.tree_flatten(
jax.tree_util.tree_map(
lambda b: isinstance(b, graph_traversal.InputBound), bounds))
inp_is_bound = {var: is_bound
for var, is_bound in zip(parsed.jaxpr.invars, flat_is_bound)}
simplified_graph = synthetic_primitives.simplify_graph(
graph_simplifier, parsed.jaxpr, inp_is_bound)
graph = graph_traversal.PropagationGraph(simplified_graph, parsed.literals)
outvals, env = prop_alg.propagate(graph, bounds)
# Make outvals into the same tree structure than the output of the function.
tree_structure = jax.tree_util.tree_structure(output_shapes)
outvals = jax.tree_util.tree_unflatten(tree_structure, outvals)
return outvals, env
RESHAPE_PRIMITIVES: Sequence[Primitive] = [
lax.copy_p,
lax.reshape_p,
lax.slice_p,
lax.dynamic_slice_p,
lax.squeeze_p,
lax.transpose_p,
lax.broadcast_in_dim_p,
lax.concatenate_p,
lax.gather_p,
lax.scatter_p,
*([lax.select_p] if hasattr(lax, 'select_p') else []),
*([lax.select_n_p] if hasattr(lax, 'select_n_p') else []),
synthetic_primitives.convert_float32_p,
]
BILINEAR_PRIMITIVES: Sequence[Primitive] = [
lax.mul_p,
lax.dot_general_p,
lax.conv_general_dilated_p,
]
# Note that synthetic_primitives.posbilinear_p is not present in the list of
# BILINEAR_PRIMITIVES. This is because it's only created by the bilinear
# primitive simplifier and therefore will always be tagging specific bilinear
# operation (and not just bilinear primitive which will be affine because one
# argument is a weight tensor). This allows us to avoid including posbilinear
# into AFFINE_PRIMITIVES.
AFFINE_PRIMITIVES: Sequence[Primitive] = [
lax.scatter_add_p,
lax.add_p,
lax.sub_p,
lax.reduce_sum_p,
lax.neg_p,
synthetic_primitives.linear_p,
*BILINEAR_PRIMITIVES,
]
# lax.div_p can also be treated as an affine primitive, subject to checking
# that its second arg (the divisor) is a constant.
| jax_verify-master | jax_verify/src/bound_propagation.py |
# coding=utf-8
# 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.
"""Mccormick relaxations for bilinear terms.
Create mc-cormick relaxations of bilinear terms for boundprop and verification.
"""
from typing import Callable, Tuple
import jax.numpy as jnp
from jax_verify.src.types import Tensor
BilinearFun = Callable[[Tensor, Tensor], Tensor]
def mccormick_ibp(
lx: Tensor,
ux: Tensor,
ly: Tensor,
uy: Tensor,
matrix: Tensor,
) -> Tuple[Tensor, Tensor]:
"""Compute bounds in x.T * matrix * y s.t x in [lx, ux], y in [ly, uy].
Args:
lx: Lower bounds on x (d,)
ux: Upper bounds on x (d,)
ly: Lower bounds on y (d,)
uy: Upper bounds on y (d,)
matrix: (d, d) matrix
Returns:
Lower and upper bounds on x.T * matrix * y
"""
ll = matrix * jnp.outer(lx, ly)
lu = matrix * jnp.outer(lx, uy)
ul = matrix * jnp.outer(ux, ly)
uu = matrix * jnp.outer(ux, uy)
lb_elementwise = jnp.minimum(jnp.minimum(ll, lu), jnp.minimum(ul, uu))
ub_elementwise = jnp.maximum(jnp.maximum(ll, lu), jnp.maximum(ul, uu))
return jnp.sum(lb_elementwise), jnp.sum(ub_elementwise)
def posbilinear_mccormick_relaxations(
fn: BilinearFun,
x_lb: Tensor, x_ub: Tensor, y_lb: Tensor, y_ub: Tensor,
) -> Tuple[BilinearFun, BilinearFun, BilinearFun, BilinearFun]:
"""Constructs all four McCormick relaxation of a positive bilinear primitive.
For x in [x_l, x_u] and y in [y_l, y_u], the bound imposed are:
x·y >= x·y_l + x_l·y - x_l·y_l
x·y >= x·y_u + x_h·y - x_h·y_u
x·y <= x·y_u + x_l·y - x_l·y_u
x·y <= x·y_l + x_u·y - x_l·y_u
Args:
fn: Positive definite bilinear function.
x_lb: Lower bounds on x
x_ub: Upper bounds on x
y_lb: Lower bounds on y
y_ub: Upper bounds on y
Returns:
lb_fun0, lb_fun1, ub_fun0, ub_fun1
"""
def lb_fun0(x, y):
return fn(x, y_lb) + fn(x_lb, y) - fn(x_lb, y_lb)
def lb_fun1(x, y):
return fn(x, y_ub) + fn(x_ub, y) - fn(x_ub, y_ub)
def ub_fun0(x, y):
return fn(x, y_ub) + fn(x_lb, y) - fn(x_lb, y_ub)
def ub_fun1(x, y):
return fn(x, y_lb) + fn(x_ub, y) - fn(x_ub, y_lb)
return lb_fun0, lb_fun1, ub_fun0, ub_fun1
def mccormick_outer_product(x: Tensor,
y: Tensor,
x_lb: Tensor,
x_ub: Tensor,
y_lb: Tensor,
y_ub: Tensor,
) -> Tensor:
"""McCormick Upper Bound on bilinear term x @ y.T.
Args:
x: Input tensor
y: Input tensor
x_lb: Lower bounds on x
x_ub: Upper bounds on x
y_lb: Lower bounds on y
y_ub: Upper bounds on y
Returns:
bd: Nonconvex bound.
"""
def outer(x, y):
x = jnp.reshape(x, [-1, 1])
y = jnp.reshape(y, [-1, 1])
return jnp.dot(x, y.T)
output_lb_a, output_lb_b, output_ub_a, output_ub_b = [
relax_fn(x, y) for relax_fn in posbilinear_mccormick_relaxations(
outer, x_lb, x_ub, y_lb, y_ub)]
return (jnp.maximum(output_lb_a, output_lb_b), # pytype: disable=bad-return-type # jax-ndarray
jnp.minimum(output_ub_a, output_ub_b))
| jax_verify-master | jax_verify/src/mccormick.py |
# coding=utf-8
# 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.
"""Bound propagation utilities."""
from typing import Generic, Mapping, Tuple, TypeVar
import jax
import jax.numpy as jnp
import jax_verify
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import synthetic_primitives
from jax_verify.src.types import Index, Nest, Primitive, SpecFn, Tensor # pylint: disable=g-multiple-import
T = TypeVar('T', bound=graph_traversal.TransformedNode)
class FixedBoundApplier(bound_propagation.BoundTransform):
"""Fixed bound constraints.
Use with `IntersectionBoundTransform` to apply branching decisions
to existing bounds.
"""
def __init__(self, fixed_bounds: Mapping[Index, Tuple[Tensor, Tensor]]):
self._fixed_bounds = fixed_bounds
def input_transform(
self,
context: bound_propagation.TransformContext,
input_bound: graph_traversal.InputBound,
) -> bound_propagation.Bound:
return jax_verify.IntervalBound(*self._fixed_bounds[context.index])
def primitive_transform(
self,
context: bound_propagation.TransformContext,
primitive: Primitive,
*args: bound_propagation.LayerInput,
**kwargs,
) -> bound_propagation.Bound:
if (context.index not in self._fixed_bounds and
isinstance(primitive, synthetic_primitives.FakePrimitive)):
# Bound is missing at the synthetic primitive level.
# Try and infer the bound from its sub-graph.
subgraph = kwargs['jax_verify_subgraph']
bound, = context.subgraph_handler(self, subgraph, *args)
return bound
return jax_verify.IntervalBound(*self._fixed_bounds[context.index])
class BoundRetriever(Generic[T], graph_traversal.GraphTransform[T]):
"""Retrieves bounds' concrete values.
The concrete values of the bound is only obtained when the bounds are queried.
"""
def __init__(self, base_transform: graph_traversal.GraphTransform[T]):
self._base_transform = base_transform
self._base_bounds = {}
def input_transform(
self,
context: graph_traversal.TransformContext[T],
input_bound: graph_traversal.InputBound,
) -> T:
bound = self._base_transform.input_transform(context, input_bound)
self._base_bounds[context.index] = bound
return bound
def primitive_transform(
self,
context: graph_traversal.TransformContext[T],
primitive: Primitive,
*args: graph_traversal.LayerInput[T],
**kwargs,
) -> T:
bound, = self._base_transform.equation_transform(
context, primitive, *args, **kwargs)
self._base_bounds[context.index] = bound
return bound
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
return self._base_transform.should_handle_as_subgraph(primitive)
@property
def concrete_bounds(self) -> Mapping[Index, Tuple[Tensor, Tensor]]:
return {index: (bound.lower, bound.upper)
for index, bound in self._base_bounds.items()}
@property
def base_transform(self):
return self._base_transform
class BoundRetrieverAlgorithm(
bound_propagation.PropagationAlgorithm[bound_propagation.Bound]):
"""Algorithm to collect concrete bounds.
Compared to a BoundRetriever Transform, this allows to obtain the final bounds
in the environment, such as when bounds in the environment are modified
by different transforms.
"""
def __init__(
self,
base_algorithm: bound_propagation.PropagationAlgorithm[
bound_propagation.Bound]):
self._base_algorithm = base_algorithm
self._base_bounds = {}
def propagate(
self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
) -> Tuple[
Nest[bound_propagation.Bound],
Mapping[jax.core.Var, bound_propagation.LayerInput],
]:
outvals, env = self._base_algorithm.propagate(graph, inputs)
self._base_bounds = {
index: graph_traversal.read_env(env, graph.jaxpr_node(index))
for index in graph.indices}
return outvals, env
@property
def concrete_bounds(self) -> Mapping[Index, Tuple[Tensor, Tensor]]:
return {index: (bound.lower, bound.upper)
for index, bound in self._base_bounds.items()}
class VacuousBoundTransform(bound_propagation.BoundTransform):
"""Generates vacuously loose bounds."""
def input_transform(
self,
context: bound_propagation.TransformContext,
input_bound: graph_traversal.InputBound
) -> bound_propagation.Bound:
return _vacuous_bounds(input_bound.lower)
def primitive_transform(
self,
context: bound_propagation.TransformContext,
primitive: Primitive,
*args: bound_propagation.LayerInput,
**kwargs,
) -> bound_propagation.Bound:
template_args = [
jnp.zeros_like(arg.lower)
if isinstance(arg, bound_propagation.Bound) else arg
for arg in args]
return _vacuous_bounds(primitive.bind(*template_args, **kwargs))
def _vacuous_bounds(template: Tensor) -> bound_propagation.Bound:
ones = jnp.ones_like(template)
return jax_verify.IntervalBound(-float('inf') * ones, +float('inf') * ones)
class GraphNode(bound_propagation.Bound):
"""Node of a Jax computation graph."""
def __init__(self, index: Index, primitive, *args, **kwargs):
self.index = index
self.primitive = primitive
self.args = args
self.kwargs = kwargs
if self.is_input():
input_bound: graph_traversal.InputBound = args[0]
self._shape = input_bound.lower.shape
self._dtype = input_bound.lower.dtype
else:
kwarged_fun = lambda x: primitive.bind(*x, **kwargs)
shape_and_type = jax.eval_shape(kwarged_fun, args)
self._shape = shape_and_type.shape
self._dtype = shape_and_type.dtype
def is_input(self):
return self.primitive is None
@property
def shape(self):
return self._shape
@property
def dtype(self):
return self._dtype
@property
def lower(self):
return -float('inf') * jnp.ones(self._shape, self._dtype)
@property
def upper(self):
return float('inf') * jnp.ones(self._shape, self._dtype)
class GraphInspector(graph_traversal.GraphTransform[GraphNode]):
"""Graph traverser that exposes the nodes."""
def __init__(self, subgraph_decider=None):
self._nodes = {}
self._subgraph_decider = subgraph_decider
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
if self._subgraph_decider:
return self._subgraph_decider(primitive)
else:
return super().should_handle_as_subgraph(primitive)
def input_transform(
self,
context: graph_traversal.TransformContext[GraphNode],
input_bound: graph_traversal.InputBound,
) -> GraphNode:
self._nodes[context.index] = GraphNode(context.index, None, input_bound)
return self._nodes[context.index]
def primitive_transform(
self,
context: graph_traversal.TransformContext[GraphNode],
primitive: Primitive,
*args: graph_traversal.LayerInput[GraphNode],
**kwargs,
) -> GraphNode:
self._nodes[context.index] = GraphNode(
context.index, primitive, *args, **kwargs)
return self._nodes[context.index]
@property
def nodes(self) -> Mapping[Index, GraphNode]:
return self._nodes
def computation_graph_nodes(
spec_fn: SpecFn,
*init_bound: Nest[graph_traversal.GraphInput],
) -> Mapping[Index, GraphNode]:
"""Extract a mapping from index to primitives."""
inspector = GraphInspector()
bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(inspector),
spec_fn, *init_bound)
return inspector.nodes
| jax_verify-master | jax_verify/src/bound_utils.py |
# coding=utf-8
# 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.
"""Common type definitions used by jax_verify."""
from typing import Any, Generic, Mapping, Sequence, Tuple, TypeVar, Union
import jax
import jax.numpy as jnp
import typing_extensions
Primitive = jax.core.Primitive
Tensor = jnp.ndarray
T = TypeVar('T')
U = TypeVar('U')
Nest = Union[T, Sequence['Nest[T]'], Mapping[Any, 'Nest[T]']]
Index = Tuple[int, ...]
class TensorFun(typing_extensions.Protocol):
def __call__(self, *inputs: Tensor) -> Tensor:
pass
class SpecFn(typing_extensions.Protocol):
"""Specification, expressed as all outputs are <=0."""
def __call__(self, *inputs: Nest[Tensor]) -> Nest[Tensor]:
pass
class ArgsKwargsCallable(typing_extensions.Protocol, Generic[T, U]):
def __call__(self, *args: T, **kwargs) -> U:
pass
| jax_verify-master | jax_verify/src/types.py |
# coding=utf-8
# 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.
"""Generic Optimizers for optimization based bound computation."""
import abc
import functools
from typing import Callable, Optional, Sequence, Tuple
import jax
from jax import numpy as jnp
from jax_verify.src import utils
from jax_verify.src.types import Nest, Tensor # pylint: disable=g-multiple-import
import optax
ParamSet = Nest[Tensor]
ProgressStats = Nest[Tensor]
TensorFun = Callable[[ParamSet], Tensor]
ProjectFun = Callable[[ParamSet], ParamSet]
class Optimizer(metaclass=abc.ABCMeta):
"""Base class defining the interface of the optimizers for JaxVerify."""
def __init__(self, log_optimization: bool = False):
self._log_optimization = log_optimization
self._opt_vals = None
@abc.abstractmethod
def optimize_fn(self,
obj_fun: TensorFun,
project_params: ProjectFun
) -> Callable[[ParamSet], ParamSet]:
"""Return a function that minimizes obj_fun.
The parameters should be in the set onto which `project_params` project to.
Args:
obj_fun: Function to minimize.
project_params: Function to project parameters onto the feasible set of
parameters. Returns the feasible arguments as a tuple.
Returns:
opt_fun: Function taking initial parameters and returning optimized ones.
"""
def get_last_opt_run(self) -> Tensor:
if not self._log_optimization:
raise ValueError('Optimizer not configured to collect objective values.')
if self._opt_vals is None:
raise ValueError('Optimizer not called.')
return self._opt_vals
class OptaxOptimizer(Optimizer):
"""Optimizer relying on Optax GradientTransformation to minimize an objective.
Performs num_steps steps of updates, while keeping track of the lowest result
obtained so far.
"""
def __init__(
self,
opt_gt: optax.GradientTransformation,
*,
num_steps: int,
log_optimization: bool = False,
):
super().__init__(log_optimization)
self._opt_gt = opt_gt
self._num_steps = num_steps
def optimize_fn(
self,
obj_fun: TensorFun,
project_params: ProjectFun,
) -> Callable[[ParamSet], ParamSet]:
"""Returns a function that minimizes obj_fun."""
val_and_grad_fn = jax.value_and_grad(obj_fun)
def update_state(
state: Tuple[ParamSet, ParamSet, ParamSet, Tensor],
) -> Tuple[ParamSet, ParamSet, ParamSet, Tensor]:
"""Update the state of the optimization.
The loop state consists of:
- params: Current value of the parameters in the optimization.
- opt_state: State of the optax optimizer.
- best_params: Value of the parameters that gave the lowest results.
- best_val: Objective value achieved for the best params.
Args:
state: The loop state.
Returns:
next_state: The updated status of the loop after one more step of
optimization.
val: The value of the optimzation at this point.
"""
params, opt_state, best_params, best_val = state
val, params_grad = val_and_grad_fn(params)
# Compute the next step in the optimization process.
updates, next_opt_state = self._opt_gt.update(params_grad, opt_state)
next_params = optax.apply_updates(params, updates)
next_params = project_params(next_params)
# Update the best params seen.
where_improved = functools.partial(jnp.where, val < best_val)
next_best_params = jax.tree_util.tree_map(where_improved,
params, best_params)
next_best_val = where_improved(val, best_val)
next_state = (next_params, next_opt_state,
next_best_params, next_best_val)
return next_state, val
def opt_fun(init_params):
best_params = init_params
if self._num_steps:
# Perform the optimization if we do at least one step.
init_opt_state = self._opt_gt.init(init_params)
_, _, best_params, _ = self.opt_loop(
update_state,
(init_params, init_opt_state, best_params, jnp.inf))
return best_params
return opt_fun
def opt_loop(self, body_fun, init_vals):
"""Calls `body_fun` num_steps times to perform the optimization."""
if self._log_optimization:
step_fun = lambda carry, _: body_fun(carry)
final_carry, opt_vals = jax.lax.scan(step_fun, init_vals, None,
length=self._num_steps)
self._opt_vals = opt_vals
return final_carry
else:
# We drop the first value passed to the step function, because it
# correspond to the iteration number.
# We drop the second returned value, which is the current
# value of the optimization that we do not need to log.
step_fun = lambda _, carry: body_fun(carry)[0]
return utils.fori_loop_no_backprop(0, self._num_steps,
step_fun, init_vals)
def _sum_fn(fn, *args, **kwargs):
out = fn(*args, **kwargs)
summand = out[0] if isinstance(out, tuple) else out
return summand.sum(), out
def _quad_approx(x: ParamSet, y: ParamSet, grad_y: ParamSet, step_size: Tensor
) -> Tensor:
"""Compute the quadratic term used in the backtracking linesearch."""
def quad_approx_var(x_var: Tensor, y_var: Tensor, grady_var: Tensor):
diff = x_var - y_var
return ((diff * grady_var).sum()
+ 0.5 / step_size * (diff**2).sum())
per_var_quad_approx = jax.tree_util.tree_map(quad_approx_var, x, y, grad_y)
return sum(jax.tree_util.tree_leaves(per_var_quad_approx))
def _broadcast_back_like(to_brd: Tensor, target: Tensor) -> Tensor:
"""Broadcast matching dimensions from the front rather than the back.
By default, numpy/jax match dimensions from the back. In this case, we
want to have a different step-size for each batch-element (so the common
dimension is at the front). This function adds dummy dimensions so that
broadcasting can happen as we want it.
Args:
to_brd: Tensor that we want to broadcast.
target: Tensor that we want to be able to be broadcasted against.
Returns:
brd: Broadcasted tensor.
"""
nb_add_dims = target.ndim - to_brd.ndim
return jnp.reshape(to_brd, to_brd.shape + (1,) * nb_add_dims)
class LinesearchFistaOptimizer(Optimizer):
"""FISTA with line search.
As done in the "An efficient nonconvex reformulation of stagewise convex
optimization problems" NeurIPS2020 submission. This is a reimplementation
of the code at:
l/d/r/r_v/verification/ibp/verification/nonconvex_optimizable_bounds.py
"""
def __init__(self,
num_steps: int,
max_step_size: float = 100.0,
min_step_size: float = 1e-5,
beta_l: float = 0.5,
beta_h: float = 1.5,
check_convergence_every: int = 1,
log_optimization: bool = False):
super().__init__(log_optimization)
self._num_steps = num_steps
self._max_step_size = max_step_size
self._min_step_size = min_step_size
self._beta_l = beta_l
self._beta_h = beta_h
self._check_convergence_every = check_convergence_every
def optimize_fn(
self,
obj_fun: TensorFun,
project_params: ProjectFun,
not_converged_fun: Optional[Callable[[ParamSet], bool]] = None):
"""Returns a function that minimizes obj_fun.
Args:
obj_fun: Functions to minimize (If this is an array, we assume that all
outputs needs to be minimized.)
project_params: Function to project parameters onto the feasible set of
parameters.
not_converged_fun: Function to indicate whether the optimization can be
early stopped because it has converged.
Returns:
opt_fun: Function taking initial parameters and returning optimized ones.
"""
# If no function is provided to identify convergence, we assume
# that the optmization has not converged at all time.
not_converged_fun = not_converged_fun or (lambda *_: True)
to_grad_fun = functools.partial(_sum_fn, obj_fun)
val_and_grad_fn = jax.value_and_grad(to_grad_fun, has_aux=True)
## Define the functions for the backtracking line search
def pgd_step(current: ParamSet, grad: ParamSet, step_size: Tensor):
def step_per_var(curr, g):
brd_step_size = _broadcast_back_like(step_size, g)
return curr - brd_step_size * g
gd_step = jax.tree_util.tree_map(step_per_var, current, grad)
return project_params(gd_step)
def should_decrease(step_size: Tensor,
y_stats: Tuple[ParamSet, ParamSet, ParamSet]):
y, obj_y, grad_y = y_stats
new_x = pgd_step(y, grad_y, step_size)
val_newx = obj_fun(new_x)
val_qapprox = obj_y + _quad_approx(new_x, y, grad_y, step_size)
per_sp_insufficient_progress = val_newx >= val_qapprox
step_size_not_min = step_size > self._min_step_size
# Perform the updates
return jnp.logical_and(step_size_not_min, per_sp_insufficient_progress)
# This will be performed in jax.lax.while_loop, with the following arguments
# ls_loop_args:
# need_lower: Boolean array indicating for each step_size if we still
# needs to lower the step size.
# step_size: Array of step size being used.
# y_stats: Tuple with y, f(y) and grad(y), so that we don't have to keep
# recomputing it.
def lower_stepsize_if_needed(ls_loop_args):
"""Reduce the step size for all the optimization target that need it.
Update the check to see if it needs to be reduced further.
Args:
ls_loop_args: Line search loop arguments
Returns:
new_ls_loop_args: Updated line search loop arguments
"""
need_lower, step_size, y_stats = ls_loop_args
new_step_size = jnp.where(need_lower,
self._beta_l * step_size, step_size)
new_need_lower = should_decrease(new_step_size, y_stats)
return new_need_lower, new_step_size, y_stats
need_lower_stepsize = lambda ls_loop_args: ls_loop_args[0].any()
## Define the function for the optimization loop
# Perform the Fista with backtracking line search algorithm, as described
# in "A Fast Iterative Shrinkage-Thresholding Algorithm", Beck and Teboulle
# The only change is that we increase the step size by a factor of
# self._beta_h for step size that didn't need to be reduced at all during
# the linesearch.
# This is performed in a jax.lax.while_loop, with the following arguments:
# opt_loop_args:
# it: Iteration counter
# x, y: variable set
# gamma: float, coefficient used for the momentum (t_k in the paper)
# step_size: Array containing the current values of the step size.
# last_obj_value: Last value of obj(j)
# We stop either based on a maximum number of iterations, or based on the
# given convergence criterion, which is checked every
# self._check_convergence_every iterations.
def fista_with_linesearch_step(opt_loop_args):
it, x, y, gamma, step_size, _ = opt_loop_args
# Compute f_y and d(f_y)/d(y)
# We ignore the first returned value which correspond to the sum of the
# objectives rather than the individual objectives.
(_, obj_y), grad_y = val_and_grad_fn(y)
# Compute the step size to use with a line search
y_stats = y, obj_y, grad_y
ini_need_lower = should_decrease(step_size, y_stats)
_, new_step_size, _ = jax.lax.while_loop(
need_lower_stepsize,
lower_stepsize_if_needed,
(ini_need_lower, step_size, y_stats))
# Perform the updates
new_x = pgd_step(y, grad_y, new_step_size)
new_gamma = 1 + jnp.sqrt(1 + gamma ** 2) / 2
coeff = (gamma - 1) / new_gamma
new_y = jax.tree_util.tree_map(
lambda new, old: new + coeff * (new - old), new_x, x)
# Increase the step size of the samples that didn't need reducing.
new_step_size = jnp.where(ini_need_lower,
new_step_size, self._beta_h * new_step_size)
return it + 1, new_x, new_y, new_gamma, new_step_size, obj_y
def continue_criterion(opt_loop_args):
it, x, *_ = opt_loop_args
not_all_iterations = it < self._num_steps
opt_not_converged = jax.lax.cond(
(it % self._check_convergence_every) == 0.,
not_converged_fun,
lambda _: jnp.array(True),
operand=x)
return jnp.logical_and(opt_not_converged, not_all_iterations)
def optimize(ini_x: ParamSet) -> ParamSet:
ini_y = ini_x
gamma = jnp.array(0.)
nb_targets = jax.eval_shape(obj_fun, ini_x).shape
step_size = self._max_step_size * jnp.ones(nb_targets)
init_val = jnp.inf * jnp.ones(nb_targets)
it = jnp.array(0)
_, final_x, _, _, _, _ = self.opt_loop(
continue_criterion,
fista_with_linesearch_step,
(it, ini_x, ini_y, gamma, step_size, init_val))
return final_x
return optimize
def opt_loop(self, continue_fun, update_fun, init_vals):
"""Performs the optimzation.
The step is defined by the `update_fun` function, and the optimization is
run for a maximum of self._num_steps, unless `continue_fun` returns False
at any point.
Args:
continue_fun: Function indicating whether the optimization has converged.
update_fun: Function performing one step of optimization.
init_vals: Initial value of the optimizition variables.
Returns:
The final state of the optimzation variables.
"""
if self._log_optimization:
# We want to log the data throughout so we need the number of steps to
# remain the same whatever happens, but we also don't want the
# optimization (including the early stopping) to change just because we're
# logging it. We're wrapping the function to add a marker of whether or
# not the optimization has finished. If it has, we just stop updating the
# values.
# We also extract the value of the objective, which is the last element of
# the carry, so that we can extract it from the scan loop.
def step_fun(wrapped_loop_args, _):
stopped, *opt_loop_args = wrapped_loop_args
should_continue = continue_fun(opt_loop_args)
new_stopped = jnp.logical_or(stopped, jnp.logical_not(should_continue))
new_opt_loop_args = jax.lax.cond(new_stopped, tuple, update_fun,
operand=opt_loop_args)
val = new_opt_loop_args[-1]
return (new_stopped, *new_opt_loop_args), val
ini_stopped = jnp.array(True)
(_, *final_carry), opt_vals = jax.lax.scan(
step_fun, (ini_stopped, *init_vals), None, length=self._num_steps)
self._opt_vals = opt_vals
return final_carry
else:
return jax.lax.while_loop(continue_fun, update_fun, init_vals)
class PortfolioOptimizer(Optimizer):
"""Optimizer that combines several existing optimizers.
Runs all of them independently and give the best result.
"""
def __init__(self, optimizers: Sequence[Optimizer],
log_optimization: bool = False):
super().__init__(log_optimization)
self._optimizers = optimizers
if log_optimization:
self._best_optimizer = 0
def optimize_fn(self,
obj_fun: TensorFun,
project_params: ProjectFun
) -> Callable[[ParamSet], ParamSet]:
"""Returns a functions that minimizes obj_fun."""
base_opt_funs = [choice_opt.optimize_fn(obj_fun, project_params)
for choice_opt in self._optimizers]
def opt_fun(initial_params):
best_params = initial_params
best_score = jnp.inf
for opt_idx, base_opt_fun in enumerate(base_opt_funs):
opt_params = base_opt_fun(initial_params)
score = obj_fun(opt_params).sum()
where_improved = functools.partial(jnp.where, score < best_score)
best_params = jax.tree_util.tree_map(where_improved, opt_params,
best_params)
if self._log_optimization:
self._best_optimizer = where_improved(jnp.asarray(opt_idx),
self._best_optimizer)
best_score = where_improved(score, best_score)
return best_params
return opt_fun
def get_last_opt_run(self) -> Tensor:
if not self._log_optimization:
raise ValueError('Optimizer not configured to collect objective values.')
# TODO: Make this jit compliant if it becomes necessary by padding
# things to size.
return self._optimizers[int(self._best_optimizer)].get_last_opt_run()
| jax_verify-master | jax_verify/src/optimizers.py |
# coding=utf-8
# 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.
"""Routines to solve basic optimization problems."""
from typing import Callable, Tuple
import jax
from jax import numpy as jnp
from jax_verify.src import utils
from jax_verify.src.types import Tensor
def greedy_assign(upper: Tensor, total_sum: float):
"""Perform a greedy assignment respecting an upper bound constraint.
Args:
upper: Maximum value to assign to each coordinate.
total_sum: Total value to assign to the coordinates.
Returns:
A tensor of greedy assignment.
"""
return jnp.clip(total_sum - (jnp.cumsum(upper) - upper),
a_min=0., a_max=upper)
def sorted_knapsack(lower: Tensor, upper: Tensor, total_sum: float,
backward: bool = False):
"""Perform a fractional knapsack assuming coordinates sorted by weights.
Args:
lower: Smallest allowable value on each of the coordinates.
upper: Largest allowable value on each of the coordinates.
total_sum: Total sum that need to be achieved.
backward: Whether to perform the greedy assignment from the start of the
tensor or from the end of it.
Returns:
Assignment to the variable of the knapsack problem.
"""
assignment_budget = upper - lower
if backward:
# If we want to do the assignment backward, we will follow the strategy of
# initially putting all the values at their upper bound, and then greeedily
# removing from the beginning of the Tensor until the budget is met, which
# would give the same result as if we were assigning in order from the back.
return upper - greedy_assign(assignment_budget, upper.sum() - total_sum) # pytype: disable=wrong-arg-types # jax-ndarray
else:
return lower + greedy_assign(assignment_budget, total_sum - lower.sum()) # pytype: disable=wrong-arg-types # jax-ndarray
def fractional_exact_knapsack(weights: Tensor, simplex_sum: float,
lower_bound: Tensor, upper_bound: Tensor
) -> float:
"""Solve the fractional knapsack problem.
max sum_i w_i x_i
such that l_i <= x_i <= u_i forall i
sum_i x_i = simplex_sum
Note that this is not exactly the classic fractional knapsack problem which
would have had the constraint sum_i x_i <= simplex_sum. This causes a
difference in the case where negative weights might be present, in which case
the results would differ.
The problem is solved using a greedy algorithm based on sorting the weights
rather than using a weighted-median type algorithm.
@TODO Ensure some error checking. What if the simplex sum is too high
(greater than the sum of upper bounds) or too low (smaller than sum of lower
bounds?).
Args:
weights: w_i, the linear coefficients on the coordinates.
simplex_sum: The total value that the sum of all constraints need to sum to.
lower_bound: Lower bound on the coordinates.
upper_bound: Upper bound on the coordinates.
Returns:
val: the value of the optimum solution of the optimization problem.
"""
flat_lower = jnp.reshape(lower_bound, (-1,))
flat_upper = jnp.reshape(upper_bound, (-1,))
flat_weights = jnp.reshape(weights, (-1,))
sorted_weights, sorted_lower, sorted_upper = jax.lax.sort(
(flat_weights, flat_lower, flat_upper), num_keys=1)
sorted_assignment = sorted_knapsack(sorted_lower, sorted_upper, simplex_sum,
backward=True)
return (sorted_weights * sorted_assignment).sum() # pytype: disable=bad-return-type # jax-types
def concave_1d_max(
obj_fn: Callable[[Tensor], Tensor],
x_lb: Tensor,
x_ub: Tensor,
*,
num_steps: int = 30,
) -> Tuple[Tensor, Tensor]:
"""Maximises the given element-wise function using golden ratio search.
Args:
obj_fn: Function to be maximised. Its inputs and outputs must have the
same shape, and its computation is assumed to be independent across
its elements.
x_lb: Lower bounds on the inputs to `obj_fn`.
x_ub: Upper bounds on the inputs to `obj_fn`.
num_steps: Number of optimisation steps. Every five steps give approximately
one additional decimal digit of accuracy of `y`.
Returns:
x: Tensor of same shape as inputs to `obj_fn` containing the argmax.
y: Tensor of same shape as inputs/outputs of `obj_fn` containing its max.
"""
phi = 0.61803398875 # inverse golden ratio
def loop_init():
# Initialise with four abcissae spaced at intervals phi^2 : phi^3 : phi^2 .
xs = [
x_lb,
phi * x_lb + (1.-phi) * x_ub,
(1.-phi) * x_lb + phi * x_ub,
x_ub,
]
ys = [
None,
obj_fn(xs[1]),
obj_fn(xs[2]),
None,
]
return xs, ys
def loop_step(_, val):
xs, ys = val
# Insert two new abcissae, so we have
# xs[0] ... left_x ... xs[1] ... xs[2] ... right_x ... xs[3]
# spaced at intervals phi^3 : phi^4 : phi^3 : phi^4 : phi^3 .
left_x = phi * xs[0] + (1.-phi) * xs[2]
right_x = (1.-phi) * xs[1] + phi * xs[3]
# Select either leftmost or rightmost four abcissae, whichever contains
# the maximum.
select = ys[1] > ys[2]
xs = [
jnp.where(select, xs[0], xs[1]),
jnp.where(select, left_x, xs[2]),
jnp.where(select, xs[1], right_x),
jnp.where(select, xs[2], xs[3]),
]
ys = [
None,
jnp.where(select, obj_fn(left_x), ys[2]),
jnp.where(select, ys[1], obj_fn(right_x)),
None,
]
return xs, ys
xs, _ = utils.fori_loop_no_backprop(0, num_steps, loop_step, loop_init())
# Extract optimal (argmax) x without gradients.
x = jax.lax.stop_gradient((xs[1] + xs[2]) / 2.)
# Re-evaluate at max with gradients.
return x, obj_fn(x)
def project_onto_interval_simplex(lower: Tensor, upper: Tensor,
simplex_sum: float, point: Tensor) -> Tensor:
"""Solve the projection on the intersection of simplex and interval domains.
The problem being solved is:
x_opt = argmin_x 0.5 || x - x_0 ||^2
s.t sum(x) = s
l <= x <= u
By dualising the simplex constraint and looking at the lagrangian, we can show
that x_opt = clip(x_0 - mu, l, u)
where mu is the lagrangian variable associated with the simplex constraint.
We are looking for which mu results in the constraint sum(x) = s to be
satisfied.
sum(x_opt) is going to be a 1D piecewise linear function. We are going to find
its root by identifying which of the linear pieces cross zero, and then using
linear interpolation to find where the crossing happen.
Args:
lower: Lower bound on the admissible values. (l in equations)
upper: Upper bound on the admissible values. (u in equations)
simplex_sum: Value that all coordinates need to sum to (s in equations)
point: Point that we are trying to project (x_0 in equations)
Returns:
x_opt: Projection of `point` onto the set of constraints.
"""
flat_lb = jnp.reshape(lower, (-1,))
flat_ub = jnp.reshape(upper, (-1,))
flat_pt = jnp.reshape(point, (-1,))
# We're also considering fake breakpoints outside of the actual ones, to avoid
# some numerical errors in the case where the breakpoints would be exactly at
# some upper bounds / lower bounds.
out_lower = flat_pt.min() - flat_ub.max() - 1.0
out_upper = flat_pt.max() - flat_lb.min() + 1.0
all_breakpoints = jax.lax.concatenate(
(flat_pt - flat_lb,
flat_pt - flat_ub,
jnp.array([out_lower, out_upper])), dimension=0)
sorted_breakpoints = jax.lax.sort(all_breakpoints)
brd_break = jnp.expand_dims(sorted_breakpoints, 1)
brd_lb = jnp.expand_dims(flat_lb, 0)
brd_ub = jnp.expand_dims(flat_ub, 0)
brd_point = jnp.expand_dims(flat_pt, 0)
terms = jnp.clip(brd_point - brd_break, a_min=brd_lb, a_max=brd_ub)
fun_val = terms.sum(axis=1) - simplex_sum
dy = jnp.diff(fun_val)
dx = jnp.diff(sorted_breakpoints)
safe_dy = jnp.where(dy != 0, dy, 1.)
# We need to use a safe version of dy to avoid creating NaNs when dy==0.
# The replacement of the values by 1. does not cause any problems for the
# computation of the opt_mu coefficient later.
interp = sorted_breakpoints[:-1] - fun_val[:-1] * dx / safe_dy
# interp gets multiplied by a mask of jnp.diff(fun_val >= 0.), so for
# incorrect value of interp, if dy == 0, then it means that fun_val was
# unchanged, so the jnp.diff would be set to False and mask out the
# incorrect value.
opt_mu = (interp * jnp.diff(fun_val >= 0.)).sum()
flat_x_opt = jnp.clip(flat_pt - opt_mu, a_min=flat_lb, a_max=flat_ub)
return jnp.reshape(flat_x_opt, lower.shape)
| jax_verify-master | jax_verify/src/opt_utils.py |
# coding=utf-8
# 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.
"""Utils used for JAX neural network verification."""
import math
import os
from typing import Callable, Sequence, Tuple, TypeVar, Union
import jax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src.types import Nest, Tensor, TensorFun # pylint: disable=g-multiple-import
import numpy as np
import urllib.request
EPSILON = 1.e-12
def safe_pos(x: Tensor) -> Tensor:
"""Returns `x` forced to be strictly positive."""
return jnp.maximum(x, EPSILON)
def safe_neg(x: Tensor) -> Tensor:
"""Returns `x` forced to be strictly negitive."""
return jnp.minimum(x, -EPSILON)
######## File Loading ########
def open_file(name, *open_args, root_dir='/tmp/jax_verify', **open_kwargs):
"""Load file, downloading to /tmp/jax_verify first if necessary."""
local_path = os.path.join(root_dir, name)
if not os.path.exists(os.path.dirname(local_path)):
os.makedirs(os.path.dirname(local_path))
if not os.path.exists(local_path):
gcp_bucket_url = 'https://storage.googleapis.com/deepmind-jax-verify/'
download_url = gcp_bucket_url + name
urllib.request.urlretrieve(download_url, local_path)
return open(local_path, *open_args, **open_kwargs)
######### Miscellaneous #########
def bind_nonbound_args(
fun: TensorFun,
*all_in_args: bound_propagation.LayerInput,
**kwargs,
) -> TensorFun:
"""Take a function and bind all keyword arguments and non-bound arguments."""
def tensorbound_fun(*bound_args):
fun_inps = []
bound_arg_pos = 0
for arg in all_in_args:
if isinstance(arg, bound_propagation.Bound):
fun_inps.append(bound_args[bound_arg_pos])
bound_arg_pos += 1
else:
fun_inps.append(arg)
assert len(bound_args) == bound_arg_pos
return fun(*fun_inps, **kwargs)
return tensorbound_fun
def batch_value_and_grad(fun, batch_dims, *args, **kwargs):
"""Equivalent to jax `value_and_grad` function but allows batched function.
This is to go around the fact that jax.value_and_grad only supports scalar
outputs.
Args:
fun: Function, operating in batch, to obtain gradients for.
batch_dims: Dimensions to batch over.
*args: Positional arguments for jax.value_and_grad
**kwargs: Named arguments for jax.value_and_grad.
Returns:
batch_value_and_grad_fn: Function returning the value and gradients of the
batched function
"""
add_batch_dim = lambda x: jnp.expand_dims(x, batch_dims)
remove_batch_dim = lambda x: x.squeeze(batch_dims)
def nobatch_fun(*nobatch_inps):
batch_inps = jax.tree_util.tree_map(add_batch_dim, nobatch_inps)
batch_out = fun(*batch_inps)
nobatch_out = jax.tree_util.tree_map(remove_batch_dim, batch_out)
return nobatch_out
nobatch_value_and_grad = jax.value_and_grad(nobatch_fun, *args, **kwargs)
batch_value_and_grad_fn = nobatch_value_and_grad
for batch_dim in batch_dims:
batch_value_and_grad_fn = jax.vmap(batch_value_and_grad_fn,
in_axes=batch_dim, out_axes=batch_dim)
return batch_value_and_grad_fn
def objective_chunk(
obj_shape: Sequence[int],
chunk_index: int,
nb_parallel_nodes: int,
):
"""Returns a one-hot tensor to select a chunk of elements from an objective.
Args:
obj_shape: Shape of the objective tensor to be chunked.
chunk_index: Index of the optimization chunk to generate.
nb_parallel_nodes: How large should the optimization chunks be. If 0,
optimize all problems at once.
Returns:
One-hot tensor of shape (nb_parallel_nodes, *obj_shape) specifying,
for each index in the chunk, an element of the objective.
"""
total_nb_nodes_to_opt = int(np.prod(obj_shape))
start_node = chunk_index * nb_parallel_nodes
if (nb_parallel_nodes == 0) or (total_nb_nodes_to_opt <= nb_parallel_nodes):
nb_nodes_to_opt = total_nb_nodes_to_opt
else:
nb_nodes_to_opt = nb_parallel_nodes
# In order to be able to use the function in the while loop, we have to have
# all tensors remain the same size so we're going to always create a tensor
# of the same size, but will not necessarily fill all the rows.
flat_obj = jnp.zeros((nb_nodes_to_opt, total_nb_nodes_to_opt))
opt_idx = jnp.arange(nb_nodes_to_opt)
node_idx = jnp.minimum(start_node + opt_idx, total_nb_nodes_to_opt-1)
to_add = ((start_node + opt_idx) < total_nb_nodes_to_opt).astype(jnp.float32)
flat_obj = flat_obj.at[(opt_idx, node_idx)].add(
to_add, indices_are_sorted=True, unique_indices=False)
obj = jnp.reshape(flat_obj, (nb_nodes_to_opt, *obj_shape))
return obj
def chunked_bounds(
bound_shape: Tuple[int, ...],
max_parallel_nodes: int,
bound_fn: Callable[[Tensor], Tuple[Tensor, Tensor]],
) -> Tuple[Tensor, Tensor]:
"""Perform computation of the bounds in chunks.
Args:
bound_shape: Shape of the bounds to compute
max_parallel_nodes: How many activations' bounds to compute at once.
If zero, compute all the activations' bounds simultaneously.
bound_fn: Function to compute bounds for a chunk, given a one-hot tensor
of shape (nb_parallel_nodes, *obj_shape) specifying the activation
elements to compute.
Returns:
Computed lower and upper bounds.
"""
def bound_chunk(chunk_index: int) -> Tuple[Tensor, Tensor]:
# Create the objective matrix
obj = objective_chunk(bound_shape, chunk_index, max_parallel_nodes)
return bound_fn(obj)
nb_act = int(np.prod(bound_shape))
if (max_parallel_nodes == 0) or (nb_act <= max_parallel_nodes):
flat_lbs, flat_ubs = bound_chunk(0)
else:
nb_bound_chunk = math.ceil(nb_act / max_parallel_nodes)
chunk_indices = jnp.arange(nb_bound_chunk)
(map_lbs, map_ubs) = jax.lax.map(bound_chunk, chunk_indices)
# Remove the padding elements
flat_lbs = jnp.reshape(map_lbs, (-1,))[:nb_act]
flat_ubs = jnp.reshape(map_ubs, (-1,))[:nb_act]
lbs = jnp.reshape(flat_lbs, bound_shape)
ubs = jnp.reshape(flat_ubs, bound_shape)
return lbs, ubs
LoopVal = TypeVar('LoopVal')
def fori_loop_no_backprop(
lower: Union[int, Tensor],
upper: Union[int, Tensor],
body_fun: Callable[[int, LoopVal], LoopVal],
init_val: LoopVal):
"""Loop by reduction to `lax.while_loop`, saving memory by avoiding backprop.
`lax.fori_loop` will reduce to `lax.scan` if `lower` and `upper` are both
known at tracing time, so as to support back-propagation. In contrast, this
function will always reduce to `lax.while_loop`, which precludes back-prop
but avoids retaining the loop state for all iterations.
Args:
lower: Lower bound (inclusive) of the "for" loop index.
upper: Upper bound (exclusive) of the "for" loop index.
body_fun: Operation to perform in each iteration of the loop.
init_val: Input loop value for first iteration of the loop.
Returns:
final_val: Output loop value from the last iteration of the loop.
"""
_, final_val = jax.lax.while_loop(
lambda i_val: i_val[0] < upper,
lambda i_val: (i_val[0] + 1, body_fun(i_val[0], i_val[1])),
(lower, init_val))
return final_val
def maybe_interp(vals: Sequence[Tensor], interp_params: Nest[Tensor]) -> Tensor:
if len(vals) == 1:
# Interpolation is trivial.
val, = vals
return val
else:
# Assume two pieces, so we can interpolate with a single parameter.
assert len(vals) == 2
val0, val1 = vals
return (1. - interp_params) * val0 + interp_params * val1
| jax_verify-master | jax_verify/src/utils.py |
# coding=utf-8
# 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.
"""Mechanism to combine input bounds from multiple methods."""
from typing import Optional
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src.types import Primitive, Tensor # pylint: disable=g-multiple-import
class IntersectionBound(bound_propagation.Bound):
"""Concretises to intersection of constituent bounds."""
def __init__(self, *base_bounds: bound_propagation.Bound):
self.base_bounds = base_bounds
@property
def lower(self) -> Tensor:
return jnp.array([bound.lower for bound in self.base_bounds]).max(axis=0)
@property
def upper(self) -> Tensor:
return jnp.array([bound.upper for bound in self.base_bounds]).min(axis=0)
class ConstrainedBound(bound_propagation.Bound):
"""Wraps a Bound with additional concrete constraints."""
def __init__(
self,
base_bound: bound_propagation.Bound,
lower: Optional[Tensor],
upper: Optional[Tensor],
):
self._base_bound = base_bound
self._lower = lower
self._upper = upper
def unwrap(self) -> bound_propagation.Bound:
return self._base_bound.unwrap()
@property
def lower(self) -> Tensor:
if self._lower is None:
return self._base_bound.lower
else:
return jnp.maximum(self._base_bound.lower, self._lower)
@property
def upper(self) -> Tensor:
if self._upper is None:
return self._base_bound.upper
else:
return jnp.minimum(self._base_bound.upper, self._upper)
class IntersectionBoundTransform(bound_propagation.BoundTransform):
"""Aggregates several bound transforms, intersecting their concrete bounds."""
def __init__(self, *base_transforms: bound_propagation.BoundTransform):
self._base_transforms = base_transforms
def input_transform(
self,
context: bound_propagation.TransformContext,
input_bound: graph_traversal.InputBound,
) -> IntersectionBound:
"""Constructs initial input bounds for each constituent bound type.
Args:
context: Transform context containing node index.
input_bound: Original concrete bounds on the input.
Returns:
Intersection of the constituent input bounds.
"""
return IntersectionBound(*[
transform.input_transform(context, input_bound)
for transform in self._base_transforms])
def primitive_transform(
self,
context: bound_propagation.TransformContext,
primitive: Primitive,
*args: bound_propagation.LayerInput,
**kwargs,
) -> IntersectionBound:
"""Propagates bounds for each constituent bound type.
Args:
context: Transform context containing node index.
primitive: Primitive Jax operation to transform.
*args: Arguments of the primitive, wrapped as `IntersectionBound`s.
**kwargs: Keyword Arguments of the primitive.
Returns:
Intersection of the propagated constituent output bounds.
"""
def base_args_for_arg(arg):
if isinstance(arg, bound_propagation.Bound):
return [ConstrainedBound(bound, arg.lower, arg.upper)
for bound in arg.unwrap().base_bounds]
else:
# Broadcast over the intersection components.
return [arg for _ in self._base_transforms]
base_args = [base_args_for_arg(arg) for arg in args]
return IntersectionBound(*[
transform.equation_transform(context, primitive, *args, **kwargs)[0]
for transform, *args in zip(self._base_transforms, *base_args)])
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
# Handle as a sub-graph only if _all_ intersectands can.
# Otherwise handle at the higher (synthetic primitive) level.
return all(base_transform.should_handle_as_subgraph(primitive)
for base_transform in self._base_transforms)
| jax_verify-master | jax_verify/src/intersection.py |
# coding=utf-8
# 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.
"""Provides methods to simplify the JaxPR computation graph.
"""
import collections
import functools
from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, TypeVar, Union
import jax
from jax import lax
from jax.experimental import pjit
from jax.interpreters import mlir
import jax.numpy as jnp
from jax_verify.src.types import Primitive, Tensor, TensorFun # pylint: disable=g-multiple-import
import numpy as np
VarIsBoundDict = MutableMapping[jax.core.Var, bool]
T = TypeVar('T')
ListNest = Union[T, Sequence['ListNest[T]']]
GraphSimplifier = ListNest[
Callable[[jax.core.Jaxpr, VarIsBoundDict], jax.core.Jaxpr]]
SimpleSimplifier = Callable[[jax.core.Jaxpr], jax.core.Jaxpr]
SUBGRAPH_PRIMITIVES: Sequence[Primitive] = (
jax.custom_derivatives.custom_jvp_call_jaxpr_p,
jax.custom_derivatives.custom_jvp_call_p,
jax.interpreters.pxla.xla_pmap_p,
pjit.pjit_p,
)
def jax_primitive_subgraph(primitive: Primitive, **params) -> jax.core.Jaxpr:
"""Returns the sub-graph for the given equation."""
if primitive == pjit.pjit_p:
return params['jaxpr'].jaxpr
elif primitive == jax.custom_derivatives.custom_jvp_call_jaxpr_p:
return params['fun_jaxpr'].jaxpr
elif primitive in SUBGRAPH_PRIMITIVES:
if isinstance(params['call_jaxpr'], jax.core.ClosedJaxpr):
return params['call_jaxpr'].jaxpr
else:
assert isinstance(params['call_jaxpr'], jax.core.Jaxpr)
return params['call_jaxpr']
else:
return params['jax_verify_subgraph']
def _replace_jax_primitive_subgraph(
primitive: Primitive,
params: MutableMapping[str, Any],
subgraph: jax.core.Jaxpr,
):
"""Updates the sub-graph for the given equation."""
if primitive == jax.custom_derivatives.custom_jvp_call_jaxpr_p:
params['fun_jaxpr'] = params['fun_jaxpr'].replace(jaxpr=subgraph)
elif primitive in SUBGRAPH_PRIMITIVES:
if primitive == pjit.pjit_p:
params['jaxpr'] = params['jaxpr'].replace(jaxpr=subgraph)
elif isinstance(params['call_jaxpr'], jax.core.ClosedJaxpr):
params['call_jaxpr'] = params['call_jaxpr'].replace(jaxpr=subgraph)
else:
assert isinstance(params['call_jaxpr'], jax.core.Jaxpr)
params['call_jaxpr'] = subgraph
else:
params['jax_verify_subgraph'] = subgraph
def filter_jaxverify_kwargs(kwargs: Mapping[str, Any]) -> Mapping[str, Any]:
if 'jax_verify_keepjvargs' in kwargs and kwargs['jax_verify_keepjvargs']:
return kwargs
else:
return {k: v for k, v in kwargs.items() if not k.startswith('jax_verify')}
def make_jaxpr_nojit(fun, *inps, **kwargs):
kwarged_fun = functools.partial(fun, **kwargs)
with jax.disable_jit():
make_jaxpr = jax.make_jaxpr(kwarged_fun)
return make_jaxpr(*inps)
def simplify_graph(
graph_simplifier: GraphSimplifier,
graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict,
) -> jax.core.Jaxpr:
"""Recursively apply the graph simplifier to the graph and its subgraphs.
Starts by filling in var_is_bound with the results for all variables.
Args:
graph_simplifier: Function simplifying the eqns in a jaxpr but ignoring
the subgraphs
graph: Jaxpr to simplify
var_is_bound: Dict mapping whether a given variable is a bound or not.
Returns:
Simplified Jaxpr, where all the subgraphs are also simplified.
"""
_propagate_var_is_bound(graph, var_is_bound)
return _simplify_graph(var_is_bound, graph, graph_simplifier)
def _simplify_graph(
var_is_bound: VarIsBoundDict,
graph: jax.core.Jaxpr,
graph_simplifier: GraphSimplifier,
) -> jax.core.Jaxpr:
"""Recursively apply the graph simplifier to the graph and its subgraphs.
Args:
var_is_bound: Dict mapping whether a given variable is a bound or not.
graph: Jaxpr to simplify
graph_simplifier: Function simplifying the eqns in a jaxpr but ignoring
the subgraphs
Returns:
Simplified Jaxpr, where all the subgraphs are also simplified.
"""
if isinstance(graph_simplifier, list):
# Recursively apply each child simplifier to the entire graph.
return functools.reduce(
functools.partial(_simplify_graph, var_is_bound),
graph_simplifier,
graph)
else:
# Apply this 'leaf' simplifier to the graph.
simplified_graph = graph_simplifier(graph, var_is_bound)
# Also recursively apply it to all sub-graphs.
for eqn in simplified_graph.eqns:
if eqn.primitive in SUBGRAPH_PRIMITIVES:
subgraph = jax_primitive_subgraph(eqn.primitive, **eqn.params)
_replace_jax_primitive_subgraph(
eqn.primitive,
eqn.params,
_simplify_graph(var_is_bound, subgraph, graph_simplifier),
)
return simplified_graph
capture_float32 = object()
class SyntheticPrimitiveSpec:
"""Traced graph of a function used to specify a synthetic primitive.."""
def __init__(
self,
fn: TensorFun,
upstream_simplifier: Optional[SimpleSimplifier],
primitive: 'FakePrimitive',
*arg_shapes_dtypes: Union[tuple[Sequence[int], jnp.dtype],
Callable[[], Tensor]],
**params):
"""Constructs a specification from the given function.
Traces `fn` with placeholder inputs specified by `arg_shapes_dtypes`, and
records the resulting Jaxpr. This will subsequently be used a reference
graph for detecting occurrences of `fn` within other graphs, allowing them
to be replaced with `primitive`.
The `upstream_simplifier` is important if this synthetic primitive is to be
detected _after_ the upstream graph simplifier has already been applied to
the main graph. In that case, occurrences of the synthetic primitive will
already have received upstream simplifications. We must apply the same
simplifications to this reference graph so that they match.
Args:
fn: Traceable function defining the computation to detect.
upstream_simplifier: Optional simplifier to apply to the reference graph.
primitive: Synthetic primitive to denote occurrences of `fn`.
*arg_shapes_dtypes: Shapes and dtypes of placeholder inputs to `fn`, or a
function producing the placeholder.
**params: Keyword parameters qualifying `primitive`. Any parameter may
be `capture_float32`, in which case the parameter value will be
determined during the match by capturing the actual value passed as
keyword param to `fn`.
"""
# Replace `capture_float32` params with thunks that look up the actual
# captured values passed as keyword params to `fn`.
subscript = lambda key, captures: captures[key]
params = {key: functools.partial(subscript, key)
if param is capture_float32 else param
for key, param in params.items()}
capture_keys = [key for key, param in params.items() if callable(param)]
placeholder_inputs = []
for asd in arg_shapes_dtypes:
if isinstance(asd, tuple):
shape, dtype = asd
placeholder_inputs.append(jnp.zeros(shape, dtype))
else:
placeholder_inputs.append(asd())
placeholder_params = {key: 7. for key in capture_keys}
closed_jaxpr = make_jaxpr_nojit(fn, *placeholder_inputs,
**placeholder_params)
self._graph = closed_jaxpr.jaxpr
self._capture_literals = {}
for capture_key in capture_keys:
# Re-trace using a different placeholder value for this param only.
# The actual values are immaterial; we simply need them to be different
# so that we can detect which literals correspond to this keyword param.
alt_params = {key: 8. if key == capture_key else 7.
for key in capture_keys}
closed_jaxpr = make_jaxpr_nojit(fn, *placeholder_inputs, **alt_params)
alt_graph = closed_jaxpr.jaxpr
for literal in _differing_literal_indices(self._graph, alt_graph):
assert literal not in self._capture_literals
self._capture_literals[literal] = capture_key
if upstream_simplifier:
self._graph = upstream_simplifier(self._graph)
self._primitive = primitive
self._params = params
@property
def graph(self) -> jax.core.Jaxpr:
return self._graph
@property
def capture_literals(self) -> Mapping[tuple[int, int], str]:
"""Literals whose values are to be captured.
Returns:
Python ids of literals whose values are to be captured, mapping to the
name of the spec function's keyword param that supplies the value.
"""
return self._capture_literals
@property
def primitive(self) -> 'FakePrimitive':
return self._primitive
@property
def params(self) -> Mapping[str, Any]:
return self._params
def simplify(self, graph_simplifier: SimpleSimplifier):
"""Applies an upstream graph simplifier to this reference graph.
This is important if this synthetic primitive is to be detected _after_
the upstream graph simplifier has already been applied to the main graph.
In that case, occurrences of the synthetic primitive will already have
received upstream simplifications. We must apply the same simplifications
to this reference graph so that they match.
Args:
graph_simplifier: Upstream graph simplifier to apply.
"""
self._graph = graph_simplifier(self._graph)
def _mark_outputs_whether_bounds(eqn, var_is_bound):
non_literal_inps = [invar for invar in eqn.invars
if not isinstance(invar, jax.core.Literal)]
# If any of the input is a bound, the outputs are bounds too.
outputs_are_bounds = any(var_is_bound[invar] for invar in non_literal_inps)
for outvar in eqn.outvars:
var_is_bound[outvar] = outputs_are_bounds
def _propagate_var_is_bound(graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict):
"""Fill in the var_is_bound dictionary to indicate which variables are bounds.
Args:
graph: The graph to check the variables of.
var_is_bound: Dictionary to fill in.
"""
for cvar in graph.constvars:
var_is_bound[cvar] = False
for eqn in graph.eqns:
_mark_outputs_whether_bounds(eqn, var_is_bound)
if eqn.primitive in SUBGRAPH_PRIMITIVES:
eqn_subgraph = jax_primitive_subgraph(eqn.primitive, **eqn.params)
subgraph_var_is_bound = {}
for subgraph_invar, eqn_invar in zip(eqn_subgraph.invars, eqn.invars):
if isinstance(eqn_invar, jax.core.Var):
subgraph_var_is_bound[subgraph_invar] = var_is_bound[eqn_invar]
else:
subgraph_var_is_bound[subgraph_invar] = False
_propagate_var_is_bound(eqn_subgraph, subgraph_var_is_bound)
var_is_bound.update(subgraph_var_is_bound)
def detect(
synthetic_primitive_specs: Sequence[SyntheticPrimitiveSpec],
graph: jax.core.Jaxpr,
) -> jax.core.Jaxpr:
"""Attempts to simplify the graph by identifying specific activations.
This is done by recognizing part of the graph and fusing them into synthetic
primitives.
Args:
synthetic_primitive_specs: Specifies graph features to be detected
as synthetic primitives.
graph: Unprocessed JaxPR graph.
Returns:
Potentially modified JaxPR graph.
"""
new_eqns = []
eqn_idx = 0
while eqn_idx < len(graph.eqns):
eqn, eqn_idx = _next_equation(synthetic_primitive_specs, graph, eqn_idx)
new_eqns.append(eqn)
return jax.core.Jaxpr(graph.constvars, graph.invars, graph.outvars, new_eqns)
def _next_equation(
synthetic_primitive_specs: Sequence[SyntheticPrimitiveSpec],
graph: jax.core.Jaxpr,
eqn_idx: int,
) -> tuple[jax.core.JaxprEqn, int]:
"""Determines the next equation in the Jaxpr, possibly a substitution.
Args:
synthetic_primitive_specs: Specification of what graph patterns can be
replaced with fake primitives.
graph: Jaxpr graph.
eqn_idx: Index of the equation in the Jaxpr graph.
Returns:
eqn: Next equation in the Jaxpr, which may be a fake primitive.
eqn_idx: Index of the following equation in the Jaxpr.
"""
for spec in synthetic_primitive_specs:
(
spec_matches, match_len,
primitive_invars, primitive_outvars, captures
) = _matches(spec.graph, spec.capture_literals, graph, eqn_idx)
if spec_matches:
sub_jaxpr = jax.core.Jaxpr(
constvars=[], invars=primitive_invars, outvars=primitive_outvars,
eqns=graph.eqns[eqn_idx:(eqn_idx + match_len)])
# Replace deferred keyword params with captured literals.
spec_params = {
key: param(captures) if callable(param) else param
for key, param in spec.params.items()}
return jax.core.new_jaxpr_eqn(
primitive_invars, primitive_outvars, spec.primitive,
{'jax_verify_subgraph': sub_jaxpr, **spec_params},
jax.core.no_effects,
graph.eqns[eqn_idx].source_info), eqn_idx + match_len
return graph.eqns[eqn_idx], eqn_idx + 1
def _equal_literal_values(lhs, rhs) -> bool:
# Check that the literals have the same value, using the appropriate
# comparison method.
if isinstance(lhs, jnp.ndarray):
return np.all(lhs.item() == rhs.item())
else:
# literal.val might be an int / float
return lhs == rhs
def _matches(
spec: jax.core.Jaxpr,
capture_literals: Mapping[tuple[int, int], str],
graph: jax.core.Jaxpr,
eqn_idx: int,
) -> tuple[
bool,
int,
Sequence[jax.core.Var],
Sequence[Union[jax.core.Var, jax.core.Literal]],
Mapping[str, Any],
]:
"""Determines whether the graph continues with the given reference graph.
Args:
spec: Reference Jaxpr graph specifying the fake primitive to match.
capture_literals: Python ids of literals whose value is to be captured,
mapping to capture param name.
graph: Jaxpr graph.
eqn_idx: Index of the current equation in the Jaxpr graph,
at which to check for a match.
Returns:
spec_matches: Whether the graph matches the spec.
match_len: How many (top-level) equations constitute the match.
invars: Varables of `graph` that correspond to `spec.invars`.
outvars: Varables of `graph` that correspond to `spec.outvars`.
captures: Captured literal values, keyed by param name.
"""
no_match = False, 0, [], [], {}
eqn_idx_orig = eqn_idx
graph_vars_by_spec_var = {}
captures = {}
def inputs_correspond(spec_eqn_invars, graph_eqn_invars, eqn_pos) -> bool:
# Check that the equation's inputs correspond.
if len(spec_eqn_invars) != len(graph_eqn_invars):
return False
for invar_idx, (spec_eqn_invar, graph_eqn_invar) in enumerate(zip(
spec_eqn_invars, graph_eqn_invars)):
if isinstance(spec_eqn_invar, jax.core.Literal):
if not isinstance(graph_eqn_invar, jax.core.Literal):
return False
# Check that the literals hold values of the same type.
if not isinstance(spec_eqn_invar.val, type(graph_eqn_invar.val)):
return False
if (eqn_pos, invar_idx) in capture_literals:
# The value of this literal in the specification graph is just a
# placeholder. Instead of an equality comparison, we capture the
# corresponding value in the actual graph.
key = capture_literals[(eqn_pos, invar_idx)]
if key in captures and not _equal_literal_values(
graph_eqn_invar.val, captures[key]):
# Same keyword param has already captured a different value.
return False
captures[key] = graph_eqn_invar.val
elif not _equal_literal_values(spec_eqn_invar.val, graph_eqn_invar.val):
return False
else:
if ((spec_eqn_invar in spec.invars or spec_eqn_invar in spec.constvars)
and spec_eqn_invar not in graph_vars_by_spec_var):
# Encountering an input for the first time.
graph_vars_by_spec_var[spec_eqn_invar] = graph_eqn_invar
if graph_vars_by_spec_var[spec_eqn_invar] != graph_eqn_invar:
return False
return True
for spec_eqn in spec.eqns:
if eqn_idx >= len(graph.eqns):
return no_match
graph_eqn = graph.eqns[eqn_idx]
eqn_pos = eqn_idx - eqn_idx_orig
eqn_idx += 1
# Check that the primitives are the same.
if graph_eqn.primitive != spec_eqn.primitive:
return no_match
if spec_eqn.primitive in (jax.lax.add_p, jax.lax.mul_p):
backup_graph_vars_by_spec_var = {**graph_vars_by_spec_var}
backup_captures = {**captures}
if not inputs_correspond(spec_eqn.invars, graph_eqn.invars, eqn_pos):
# Jax will sometimes silently reverse the order of args of these
# commutative ops, for example if one arg is a literal.
graph_vars_by_spec_var = backup_graph_vars_by_spec_var
captures = backup_captures
if not inputs_correspond(spec_eqn.invars,
list(reversed(graph_eqn.invars)), eqn_pos):
return no_match
else:
if not inputs_correspond(spec_eqn.invars, graph_eqn.invars, eqn_pos):
return no_match
# Check that the equation's params are equal.
if set(spec_eqn.params) != set(graph_eqn.params):
return no_match
for key in set(spec_eqn.params):
spec_param = spec_eqn.params[key]
graph_param = graph_eqn.params[key]
if key in ('fun_jaxpr', 'call_jaxpr', 'jax_verify_subgraph', 'jaxpr'):
# Recursively check that the sub-graphs match.
if isinstance(spec_param, jax.core.ClosedJaxpr):
assert isinstance(graph_param, jax.core.ClosedJaxpr)
subspec = spec_param.jaxpr
subgraph = graph_param.jaxpr
else:
assert isinstance(spec_param, jax.core.Jaxpr)
assert isinstance(graph_param, jax.core.Jaxpr)
subspec = spec_param
subgraph = graph_param
(
subgraph_matches, _,
subgraph_invars, subgraph_outvars, subgraph_captures
) = _matches(subspec, capture_literals, subgraph, 0)
captures.update(subgraph_captures)
if not subgraph_matches:
return no_match
if subgraph.invars != subgraph_invars:
return no_match
if subgraph.outvars != subgraph_outvars:
return no_match
# Assimilate the captured literal values from the sub-graph.
if any(key in captures and
not _equal_literal_values(capture, captures[key])
for key, capture in subgraph_captures.items()):
# Same keyword param has already captured a different value.
return no_match
elif key in ('shape', 'new_sizes',
'start_indices', 'limit_indices', 'slice_sizes'):
# Don't check shape, but do check rank.
if len(spec_param) != len(graph_param):
return no_match
elif not callable(spec_param):
if spec_param != graph_param:
return no_match
# Record the correspondence between the equation's outputs.
graph_vars_by_spec_var.update({
spec_eqn_outvar: graph_eqn_outvar
for spec_eqn_outvar, graph_eqn_outvar in zip(
spec_eqn.outvars, graph_eqn.outvars)})
# It's a match.
# Look up the input and output variables in the graph.
graph_invars = [
graph_vars_by_spec_var[spec_invar] for spec_invar in spec.invars]
assert all(graph_invar is not None for graph_invar in graph_invars)
graph_outvars = [
graph_vars_by_spec_var[spec_outvar]
if isinstance(spec_outvar, jax.core.Var) else spec_outvar
for spec_outvar in spec.outvars]
assert all(graph_outvar is not None for graph_outvar in graph_outvars)
return True, eqn_idx - eqn_idx_orig, graph_invars, graph_outvars, captures
def _differing_literal_indices(
graph: jax.core.Jaxpr,
alt_graph: jax.core.Jaxpr,
) -> Sequence[tuple[int, int]]:
"""Returns indices of literals taking different values in the two graphs."""
literals = []
assert len(graph.eqns) == len(alt_graph.eqns), 'Different number of equations'
for eqn_idx, (eqn, alt_eqn) in enumerate(zip(graph.eqns, alt_graph.eqns)):
assert eqn.primitive == alt_eqn.primitive, 'Different primitives'
# Check that the equation's inputs correspond.
for invar_idx, (eqn_invar, alt_eqn_invar) in enumerate(zip(eqn.invars,
alt_eqn.invars,
strict=True)):
assert (
isinstance(eqn_invar, jax.core.Literal) ==
isinstance(alt_eqn_invar, jax.core.Literal)
), 'Different literal occurrences'
if (isinstance(eqn_invar, jax.core.Literal) and
not _equal_literal_values(eqn_invar.val, alt_eqn_invar.val)):
literals.append((eqn_idx, invar_idx))
assert set(eqn.params) == set(alt_eqn.params), 'Different param key sets'
for key in set(eqn.params):
param = eqn.params[key]
alt_param = alt_eqn.params[key]
if key in ('fun_jaxpr', 'call_jaxpr', 'jax_verify_subgraph', 'jaxpr'):
# Recursively match the sub-graphs.
subgraph = param.jaxpr if isinstance(
param, jax.core.ClosedJaxpr) else param
alt_subgraph = alt_param.jaxpr if isinstance(
alt_param, jax.core.ClosedJaxpr) else alt_param
literals.extend(_differing_literal_indices(subgraph, alt_subgraph))
return literals
def _is_linear_eqn(eqn: jax.core.JaxprEqn, var_is_bound: VarIsBoundDict):
"""Identify if an eqn is a linear transformation of inputs that are bounds.
Args:
eqn: The equation to check.
var_is_bound: Dictionary indicating whether each variable represent a bound
or a Tensor.
Returns:
is_linear: boolean indicating whether the equation is linear.
"""
# Handle the case where a subgraph primitive contains only linear operations.
# We will simplify the graph and see if it amounts to a single primitive.
if eqn.primitive in SUBGRAPH_PRIMITIVES:
subgraph = jax_primitive_subgraph(eqn.primitive, **eqn.params)
grouped_subgraph = group_linear_sequence(subgraph, var_is_bound)
return (len(grouped_subgraph.eqns) == 1
and grouped_subgraph.eqns[0].primitive is linear_p)
# Otherwise, check simply the primitive
prim = eqn.primitive
non_literal_inps = [invar for invar in eqn.invars
if not isinstance(invar, jax.core.Literal)]
nb_bound_input = sum(var_is_bound[invar] for invar in non_literal_inps)
if not any(var_is_bound[outvar] for outvar in eqn.outvars):
return False
# Make sure that if this produces bounds,there is only one output
assert len(eqn.outvars) == 1
return (prim in LINEAR_OP
or (prim in BILINEAR_OP and nb_bound_input == 1)
or (prim is jax.lax.div_p
and nb_bound_input == 1
and not isinstance(eqn.invars[0], jax.core.Literal)
and var_is_bound[eqn.invars[0]]))
def _is_posbilinear_eqn(eqn, var_is_bound):
"""Identify if an eqn is a Posbilinear transformation.
Note that a PosBilinear primitive with only one of the inputs being a bound is
considered a linear transformation, not a posbilinear one.
Args:
eqn: The equation to check.
var_is_bound: Dictionary indicating whether each variable represent a bound
or a Tensor.
Returns:
is_posbilinear: boolean indicating whether the equation is posbilinear.
"""
# Handle the case where a subgraph primitive contains only a quadratic
# operation. This is often how the results of einsum are generated.
if eqn.primitive in SUBGRAPH_PRIMITIVES:
subgraph = jax_primitive_subgraph(eqn.primitive, **eqn.params)
grouped_subgraph = group_posbilinear(subgraph, var_is_bound)
return (len(grouped_subgraph.eqns) == 1
and grouped_subgraph.eqns[0].primitive is posbilinear_p)
# Otherwise, simply check the primitive
prim = eqn.primitive
non_literal_inps = [invar for invar in eqn.invars
if not isinstance(invar, jax.core.Literal)]
nb_bound_input = sum(var_is_bound[invar] for invar in non_literal_inps)
return (prim in BILINEAR_OP) and (nb_bound_input == 2)
def _find_eqn(eqn_list: Sequence[jax.core.JaxprEqn], var: jax.core.Var) -> int:
"""Find the equation producing the var, and returns its index."""
eqn_idx = 0
for eqn_idx, eqn in enumerate(eqn_list):
if eqn.outvars[0] == var:
return eqn_idx
else:
assert False
def group_posbilinear(graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict,
) -> jax.core.Jaxpr:
"""Simplifier identifying the PosBilinear terms in the graph.
A PosBilinear equation can be written in the form of:
x^T M y
where x and y are variable for which we have bound and M is a matrix with
positive entries.
Args:
graph: Jaxpr to simplify
var_is_bound: Dict mapping whether a given variable is a bound or not.
Returns:
Simplified Jaxpr, where all the PosBilinear have been identified.
"""
new_eqns = []
for eqn in graph.eqns:
# Identify the posbilinear operations
if _is_posbilinear_eqn(eqn, var_is_bound):
non_literal_invars = [invar for invar in eqn.invars
if isinstance(invar, jax.core.Var)]
posbilinear_jaxpr = jax.core.Jaxpr(
constvars=[], invars=non_literal_invars,
outvars=eqn.outvars, eqns=[eqn])
new_eqns.append(jax.core.new_jaxpr_eqn(
posbilinear_jaxpr.invars, posbilinear_jaxpr.outvars, posbilinear_p,
{'jax_verify_subgraph': posbilinear_jaxpr,
'jax_verify_keepjvargs': True}, jax.core.no_effects))
else:
new_eqns.append(eqn)
return jax.core.Jaxpr(graph.constvars, graph.invars, graph.outvars, new_eqns)
def group_linear_sequence(graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict,
) -> jax.core.Jaxpr:
"""Attempt to fold linear sequences together into synthetic linear primitives.
Args:
graph: Unprocessed JaxPR graph.
var_is_bound: Dict mapping whether a given variable is a bound or not.
Returns:
Potentially modified JaxPR graph.
"""
consumed_by_linear = set()
consumed_by = collections.Counter()
is_linear_result = {}
# Do a first pass through the graph to identify the Linear sequences
for eqn in graph.eqns:
is_linear = _is_linear_eqn(eqn, var_is_bound)
outvar = eqn.outvars[0]
is_linear_result[outvar] = is_linear
for invar in eqn.invars:
if not isinstance(invar, jax.core.Literal) and var_is_bound[invar]:
consumed_by[invar] += 1
if is_linear:
consumed_by_linear.add(invar)
for outvar in graph.outvars:
if isinstance(outvar, jax.core.Var):
consumed_by[outvar] += 1
# Now collect the equations, merging the Linear sequences together
new_eqns = []
to_be_folded = {}
for eqn in graph.eqns:
outvar = eqn.outvars[0]
if is_linear_result[outvar]:
# This is a Linear operation. Let's construct it, possibly including
# previous linear operations that were waiting to be folded in.
lin_invars = []
linear_eqns = []
for invar in eqn.invars:
if isinstance(invar, jax.core.Var):
# Filter out the literals, which should not be registered as inputs to
# a subgraph.
if invar in to_be_folded:
subg = to_be_folded[invar]
for sub_invar in subg.invars:
lin_invars.append(sub_invar)
linear_eqns.extend(subg.eqns)
del to_be_folded[invar]
else:
lin_invars.append(invar)
# Remove duplicates, preserving order.
lin_invars = list(dict.fromkeys(lin_invars))
lin_outvars = [outvar]
if eqn.primitive is linear_p:
linear_eqns.extend(eqn.params['jax_verify_subgraph'].eqns)
else:
linear_eqns.append(eqn)
sub_jaxpr = jax.core.Jaxpr(constvars=[], invars=lin_invars,
outvars=lin_outvars, eqns=linear_eqns)
if (consumed_by[outvar] == 1) and (outvar in consumed_by_linear):
# If it's going to be consumed by only a linear operation, put it in the
# to_be_folded dictionary, it will be included with the following linear
# equation.
to_be_folded[outvar] = sub_jaxpr
else:
# If it's consumed by multiple things, or by a non-linear operation, or
# is a terminal output, it does not need folding and should be included
# now.
agg_lin_eqn = jax.core.new_jaxpr_eqn(
sub_jaxpr.invars, sub_jaxpr.outvars, linear_p,
{'jax_verify_subgraph': sub_jaxpr, 'jax_verify_keepjvargs': True},
jax.core.no_effects)
new_eqns.append(agg_lin_eqn)
else:
# Non linear operation just gets included directly
new_eqns.append(eqn)
assert not to_be_folded
simple_graph = jax.core.Jaxpr(graph.constvars, graph.invars,
graph.outvars, new_eqns)
# There are some cases where this analysis misses combining some linear
# operations that can be combined, because there is a branching factor that
# can be resolved.
# One example: Making the output of a linear layer mean 0 would be this:
# y=Linear(x) -------------------> u = y - t ---->
# \--->t = mean(y)---/
# It appears that y is consumed by two different operations, but in practice,
# those two operations can be part of the same operation.
# Re-applying the simplification will succeed in merging those, so we will
# recursively simplify, until we have reached a fixed point (counted as a
# number of eqns in the graph.)
# In this example, after the first pass we would have identified two linear
# blocks:
# y = Linear(x)
# and
# u = y - mean(y).
# While in the first pass, it looks like y is consumed by two operations, they
# get agglomerated together which means that y has now only one dependent.
if len(new_eqns) != len(graph.eqns):
return group_linear_sequence(simple_graph, var_is_bound)
else:
return simple_graph
def group_fused_relu(graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict
) -> jax.core.Jaxpr:
"""Simplifier identifying FusedRelus (Linear followed by a ReLU).
The ReLU primitive will be replaced by a FusedRelu primitive, which
is responsible for implementing the ReLU, but will in appearance
also take the inputs to the linear as input and have as a special
parameter the implementation of the linear layer.
From a graph like this,
o ----[linear]------> o -----[relu]----------> o
we will move to graph like this:
>------------------------------|
| v
o -----[linear]----> o -----[fused_relu]----> o
fused_linear:[linear]
The goal of this is that we can use the knowledge we have of the
preceding linear operation to get a tighter relaxation of the ReLU.
Args:
graph: Jaxpr to simplify.
var_is_bound: Dict mapping whether a given variable is a bound or not.
Returns:
Simplified Jaxpr, where all the fused ReLU have been identified.
"""
# Pass through the network to find what variables are eligible to be
# the intermediate variable of a fused ReLU.
# The conditions are:
# - produced by a linear.
# - consumed by a ReLU.
# - Not consumed by anything else.
is_linear_variable = {}
consumed_by = collections.Counter()
for eqn in graph.eqns:
for invar in eqn.invars:
if not isinstance(invar, jax.core.Literal) and var_is_bound[invar]:
consumed_by[invar] += 1
is_linear_variable[eqn.outvars[0]] = eqn.primitive is linear_p
# Increase consumed_by for graph_input so that we don't fuse a graph output.
for outvar in graph.outvars:
if isinstance(outvar, jax.core.Var):
consumed_by[outvar] += 1
# Identify exactly which variables are involved in FusedRelus, based on the
# information collected.
fused_relu_interm_to_output = {}
for eqn in graph.eqns:
if (eqn.primitive is relu_p and
is_linear_variable[eqn.invars[0]] and
consumed_by[eqn.invars[0]] == 1):
fused_relu_interm_to_output[eqn.invars[0]] = eqn.outvars[0]
# Let's now create the new list of eqns where we replace the eqns involved in
# the fused ReLU by the fused ReLU.
new_eqns = []
for eqn in graph.eqns:
if eqn.outvars[0] in fused_relu_interm_to_output:
# This is the linear part of the fused ReLU.
linear_eqn = eqn
# Get the corresponding ReLU.
relu_eqn_idx = _find_eqn(graph.eqns,
fused_relu_interm_to_output[eqn.outvars[0]])
relu_eqn = graph.eqns[relu_eqn_idx]
# Let's now build the fused ReLU primitive
non_literal_invars = [invar for invar in eqn.invars
if isinstance(invar, jax.core.Var)]
fused_relu_invars = [eqn.outvars[0], *non_literal_invars]
fused_relu_jaxpr = jax.core.Jaxpr(
constvars=[], invars=fused_relu_invars,
outvars=relu_eqn.outvars, eqns=[relu_eqn])
# Keep the linear eqn in the jaxpr, so that we can concretize it.
new_eqns.append(linear_eqn)
# Insert the relu at that level, with an addition of a copy of the
# linear operation preceding it so that we can use it for the
# relaxation.
new_eqns.append(jax.core.new_jaxpr_eqn(
fused_relu_jaxpr.invars, fused_relu_jaxpr.outvars, fused_relu_p,
{'jax_verify_subgraph': fused_relu_jaxpr,
'jax_verify_keepjvargs': True,
'jax_verify_fusedlinear': linear_eqn},
jax.core.no_effects))
elif (eqn.primitive is relu_p and
eqn.invars[0] in fused_relu_interm_to_output):
# This is the relu part of the fused relu. We already included it.
pass
else:
new_eqns.append(eqn)
return jax.core.Jaxpr(graph.constvars, graph.invars, graph.outvars, new_eqns)
def hoist_constant_computations(graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict
) -> jax.core.Jaxpr:
"""Rearrange the equations to make for easier to reason about JaxPr.
All constant computations should be done at the beginning.
Args:
graph: Jaxpr to simplify
var_is_bound: Dict mapping whether a given variable is a bound or not.
Returns:
Simplified Jaxpr, where all non-bound computation are at the beginning.
"""
new_eqns = []
# Do a pass, including all the constant computations.
for eqn in graph.eqns:
if not var_is_bound[eqn.outvars[0]]:
new_eqns.append(eqn)
# Do a pass, including all the bound computations
for eqn in graph.eqns:
if var_is_bound[eqn.outvars[0]]:
new_eqns.append(eqn)
return jax.core.Jaxpr(graph.constvars, graph.invars,
graph.outvars, new_eqns)
def _get_count_and_suffix(graph: jax.core.Jaxpr) -> tuple[int, str]:
# We are going to be creating new variables.
# Let's find out what level we need to start counting from.
max_count = 0
suffix = ''
for eqn in graph.eqns:
for outvar in eqn.outvars:
if outvar.count > max_count:
max_count = outvar.count
suffix = outvar.suffix
return max_count, suffix
def expand_softmax_simplifier(graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict
) -> jax.core.Jaxpr:
"""Replace the softmax synthetic primitives by its decomposition.
It might seem like what we would want to do is simply not detect the softmax,
but simplifying the softmax and then expanding it makes it more verification
friendly. For example, this allows to remove the primitives that are employed
for numerical stability (reduce_max, stop_gradient and sub), but don't affect
output and that we might not handle.
Note that we as we create new variables, we will modify `var_is_bound` to keep
it complete.
Args:
graph: Jaxpr to simplify
var_is_bound: Dict mapping whether a given variable is a bound or not.
Returns:
Simplified Jaxpr, where all softmax have been expanded into
Exponential -> sum -> Reciprocal -> multiplication
|----------------------------/
"""
max_count, suffix = _get_count_and_suffix(graph)
new_var_idx = max_count + 1
new_eqns = []
find_prim = lambda eqns, prim: [eqn.primitive for eqn in eqns].index(prim)
for eqn in graph.eqns:
if eqn.primitive == softmax_p:
# We will ignore the operations performed for numerical stability , (the
# removal of the constant) and keep only the operations we need to
# propagate bound through. We will also replace the division by a
# reciprocal, and a multiplication.
# In order to take away some of the guess work, we will spy what the aval
# are, and the configurations for some of the parameters.
softmax_subgraph = eqn.params['jax_verify_subgraph']
if (
len(softmax_subgraph.eqns) == 1
and softmax_subgraph.eqns[0].primitive
== jax.custom_derivatives.custom_jvp_call_p
):
# The softmax is wrapped inside of a custom_jvp. We'll use the custom
# jvp subgraph as the softmax subgraph.
softmax_subgraph = softmax_subgraph.eqns[0].params['call_jaxpr']
exp_index = find_prim(softmax_subgraph.eqns, lax.exp_p)
full_size_aval = softmax_subgraph.eqns[exp_index].outvars[0].aval
exp_var = jax.core.Var(new_var_idx, suffix, full_size_aval)
var_is_bound[exp_var] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
eqn.invars, [exp_var], lax.exp_p, {}, jax.core.no_effects))
# Let's find the parameters of the reduce_sum and of the broadcast
# operation in the original softmax implementation so that we don't have
# to do guesswork
# Add the reduce sum eqn
reduce_sum_index = find_prim(softmax_subgraph.eqns, lax.reduce_sum_p)
orig_reduce_sum = softmax_subgraph.eqns[reduce_sum_index]
reduced_size_aval = orig_reduce_sum.outvars[0].aval
exp_sum_var = jax.core.Var(new_var_idx, suffix, reduced_size_aval)
var_is_bound[exp_sum_var] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
[exp_var], [exp_sum_var], lax.reduce_sum_p, orig_reduce_sum.params,
jax.core.no_effects))
# Add the broadcasting of it.
broadcast_index = find_prim(softmax_subgraph.eqns, lax.broadcast_in_dim_p)
orig_broadcast = softmax_subgraph.eqns[broadcast_index]
broad_size_aval = orig_broadcast.outvars[0].aval
broad_expsum_var = jax.core.Var(new_var_idx, suffix, broad_size_aval)
var_is_bound[broad_expsum_var] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
[exp_sum_var], [broad_expsum_var], lax.broadcast_in_dim_p,
orig_broadcast.params, jax.core.no_effects))
# Take the inverse of the exp sum
inv_expsum_var = jax.core.Var(new_var_idx, suffix, broad_size_aval)
var_is_bound[inv_expsum_var] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
[broad_expsum_var], [inv_expsum_var], posreciprocal_p, {},
jax.core.no_effects))
# Multiply the exponential to the (inv exp sum)
softmax_var = eqn.outvars[0]
new_eqns.append(jax.core.new_jaxpr_eqn(
[exp_var, inv_expsum_var], [softmax_var], jax.lax.mul_p, {},
jax.core.no_effects))
else:
new_eqns.append(eqn)
return jax.core.Jaxpr(graph.constvars, graph.invars,
graph.outvars, new_eqns)
def replace_eltwise_minimum(graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict,
) -> jax.core.Jaxpr:
"""Replace the elementwise min primitive by an equivalent max formulation."""
max_count, suffix = _get_count_and_suffix(graph)
new_var_idx = max_count + 1
new_eqns = []
for eqn in graph.eqns:
if (eqn.primitive == lax.min_p) and var_is_bound[eqn.outvars[0]]:
# Create negation of the first argument.
neg_inp_0_var = jax.core.Var(new_var_idx, suffix, eqn.invars[0].aval)
var_is_bound[neg_inp_0_var] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
eqn.invars[0:1], [neg_inp_0_var], lax.neg_p, {}, jax.core.no_effects))
# Create negation of the second argument.
neg_inp_1_var = jax.core.Var(new_var_idx, suffix, eqn.invars[1].aval)
var_is_bound[neg_inp_1_var] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
eqn.invars[1:2], [neg_inp_1_var], lax.neg_p, {}, jax.core.no_effects))
# Create the elementwise maximum
neg_min = jax.core.Var(new_var_idx, suffix, eqn.outvars[0].aval)
var_is_bound[neg_min] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
[neg_inp_0_var, neg_inp_1_var], [neg_min], lax.max_p, {},
jax.core.no_effects))
# Negate to obtain the elementwise minimum
elt_min_outvar = eqn.outvars[0]
new_eqns.append(jax.core.new_jaxpr_eqn(
[neg_min], [elt_min_outvar], lax.neg_p, {}, jax.core.no_effects))
else:
new_eqns.append(eqn)
return jax.core.Jaxpr(graph.constvars, graph.invars, graph.outvars, new_eqns)
def replace_eltwise_maximum(graph: jax.core.Jaxpr,
var_is_bound: VarIsBoundDict,
) -> jax.core.Jaxpr:
"""Replace the elementwise max primitive by a ReLU and sum."""
max_count, suffix = _get_count_and_suffix(graph)
new_var_idx = max_count + 1
new_eqns = []
for eqn in graph.eqns:
# If this in an elementwise maximum, that is not a ReLU
if ((eqn.primitive == lax.max_p) and var_is_bound[eqn.outvars[0]] and
not (isinstance(eqn.invars[1], jax.core.Literal)
and eqn.invars[1] == 0.)):
# We know that this is a an elementwise maximum operation max(a, b).
# We are going to rewrite it as b + ReLU(a - b)
# Create the difference between the two arguments of the elementwise max.
diff_var = jax.core.Var(new_var_idx, suffix, eqn.invars[0].aval)
var_is_bound[diff_var] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
eqn.invars, [diff_var], lax.sub_p, {}, jax.core.no_effects))
# Create the ReLU of the difference
relued_diff_var = jax.core.Var(new_var_idx, suffix, eqn.outvars[0].aval)
var_is_bound[relued_diff_var] = True
new_var_idx += 1
new_eqns.append(jax.core.new_jaxpr_eqn(
[diff_var], [relued_diff_var], relu_p, {}, jax.core.no_effects))
# Add the second term back.
max_outvar = eqn.outvars[0]
new_eqns.append(jax.core.new_jaxpr_eqn(
[relued_diff_var, eqn.invars[1]], [max_outvar], lax.add_p, {},
jax.core.no_effects))
else:
new_eqns.append(eqn)
return jax.core.Jaxpr(graph.constvars, graph.invars, graph.outvars, new_eqns)
class FakePrimitive(jax.core.Primitive):
"""This wraps an implementation of a primitive we want to identify.
This way our code that assumes that it can go through the primitive by calling
`bind` will work transparently.
We don't want to define it properly as a primitive because otherwise
operations like the jit will assume that it's a real primitive and not have
definitions for it.
"""
def __init__(self, name, impl, always_make_node=False): # pylint: disable=redefined-outer-name
self._name = name
self._impl = impl
self._always_make_node = always_make_node
self._register_lowering()
def bind(self, *args, **kwargs):
params = {k: v for k, v in kwargs.items() if k != 'jax_verify_subgraph'}
return self._impl(*args, **params)
@property
def name(self):
return self._name
@property
def always_make_node(self):
return self._always_make_node
def __str__(self):
return self._name
def __repr__(self):
return f'SyntheticPrimitive[{self._name}]'
def _register_lowering(self):
"""Register the lowering of the primitive.
In order to be usable inside a pjit, any primitive need to have defined a
lowering rule. The FakePrimitive are all traceable, so we will use
lower_fun to produce their lowering rule.
"""
lowering_rule = mlir.lower_fun(self.bind, multiple_results=False)
mlir.register_lowering(self, lowering_rule)
def always_make_node(primitive: Primitive):
return isinstance(primitive, FakePrimitive) and primitive.always_make_node
def simplifier_composition(*graph_simplifiers: GraphSimplifier
) -> GraphSimplifier:
"""Apply each simplifier one after the other."""
# We leave it as a list of simplifiers, and let `_simplify_graph` handle
# the aggregation. This will allows the first simplifier to be applied to
# the entire graph including sub-graphs, before the next simplifier is
# applied.
return list(graph_simplifiers)
def _subgraph_bind(*args, **kwargs):
"""Implement the primitive by iterating through the subgraph."""
jax_verify_subgraph = kwargs['jax_verify_subgraph']
return jax.core.eval_jaxpr(jax_verify_subgraph, [], *args)[0]
class SubgraphPrimitive(FakePrimitive):
"""Fake primitive delegating to the implementation to jax_verify_subgraph."""
def __init__(self, name):
super().__init__(name, _subgraph_bind)
def bind(self, *args, **kwargs):
return self._impl(*args, **kwargs)
convert_float32_p = FakePrimitive(
'ConvertFloat32', functools.partial(lax.convert_element_type,
new_dtype=jnp.float32))
sigmoid_p = FakePrimitive('Sigmoid', jax.nn.sigmoid)
softplus_p = FakePrimitive('Softplus', jax.nn.softplus)
softmax_p = FakePrimitive('Softmax', jax.nn.softmax)
relu_p = FakePrimitive('ReLU', jax.nn.relu)
leaky_relu_p = FakePrimitive('LeakyRelu', jax.nn.leaky_relu)
parametric_leaky_relu_p = FakePrimitive(
'ParametricLeakyRelu', jax.nn.leaky_relu)
clip_p = FakePrimitive('Clip', jnp.clip)
posreciprocal_p = FakePrimitive('PosReciprocal', jax.lax.reciprocal)
sech_p = FakePrimitive('Sech', lambda x: 1. / jnp.cosh(x))
linear_p = SubgraphPrimitive('Linear')
posbilinear_p = SubgraphPrimitive('PosBilinear')
quadratic_p = SubgraphPrimitive('Quadratic')
fused_relu_p = SubgraphPrimitive('FusedRelu')
def _make_specs(
fn: TensorFun,
upstream_simplifier: Optional[SimpleSimplifier],
primitive: 'FakePrimitive',
*arg_shapes_dtypes: Union[tuple[Sequence[int], jnp.dtype],
Callable[[], Tensor]],
**params) -> Sequence[SyntheticPrimitiveSpec]:
"""Create specs for the variants of the function that we might encounter."""
specs = [SyntheticPrimitiveSpec(
fn, upstream_simplifier, primitive,
*arg_shapes_dtypes, **params)]
if hasattr(fn, '__wrapped__'):
specs.append(SyntheticPrimitiveSpec(
fn.__wrapped__, upstream_simplifier, primitive,
*arg_shapes_dtypes, **params))
return specs
def activation_specs() -> Sequence[SyntheticPrimitiveSpec]:
"""Returns specs of activations to be replaced with synthetic primitives."""
synthetic_primitive_specs = []
# # ReLU.
synthetic_primitive_specs.extend(_make_specs(
jax.nn.relu, None, relu_p, ([], jnp.float32)))
# ReLU may also occur as an explicit max with zero.
synthetic_primitive_specs.extend(_make_specs(
lambda x: jnp.maximum(x, 0.), None, relu_p, ([], jnp.float32)))
# Clipped
synthetic_primitive_specs.extend(_make_specs(
jnp.clip, None, clip_p, ([], jnp.float32),
a_min=capture_float32, a_max=capture_float32))
# Clipped, with tensors inputs.
synthetic_primitive_specs.extend(_make_specs(
jnp.clip, None, clip_p,
([], jnp.float32), ([], jnp.float32), ([], jnp.float32)))
# Softplus.
synthetic_primitive_specs.extend(_make_specs(
jax.nn.softplus, None, softplus_p, ([], jnp.float32)))
# Softmax (n-D).
for rank in range(1, 9):
synthetic_primitive_specs.extend(_make_specs(
jax.nn.softmax, None, softmax_p, ([2] * rank, jnp.float32),
axis=(rank - 1)))
# LeakyRelu
synthetic_primitive_specs.extend(_make_specs(
jax.nn.leaky_relu, None, leaky_relu_p, ([], jnp.float32),
negative_slope=capture_float32))
# LeakyRelu with a learnable negative_slope per neuron (input to the function)
synthetic_primitive_specs.extend(_make_specs(
jax.nn.leaky_relu, None, parametric_leaky_relu_p,
([], jnp.float32), ([], jnp.float32)))
# Sigmoid
synthetic_primitive_specs.extend(_make_specs(
jax.nn.sigmoid, None, sigmoid_p, ([], jnp.float32)))
# Hyperbolic Secant
synthetic_primitive_specs.extend(_make_specs(
lambda x: 1. / jnp.cosh(x), None, sech_p, ([], jnp.float32)))
# Convert to float32.
# We mostly assume that all of our bounds are float32 tensors. However, if
# they are only weakly typed, this will result in convert_element_type
# primitives. These are fine (and are identity from our point of view).
# We however want to avoid ignoring all of such primitives (in case for
# example there is a conversion to int in the network, which we definitely
# would like to error on.)
# The plan is to detect the primitive we accept and handle them correctly,
# while not detecting the ones we don't, and let the code error.
synthetic_primitive_specs.extend(_make_specs(
functools.partial(lax.convert_element_type, new_dtype=jnp.float32),
None, convert_float32_p, lambda: jnp.asarray(0.)))
return synthetic_primitive_specs
LINEAR_OP: Sequence[Primitive] = [
lax.neg_p,
lax.concatenate_p,
lax.reshape_p,
lax.squeeze_p,
lax.transpose_p,
lax.broadcast_in_dim_p,
lax.gather_p,
lax.reduce_sum_p,
lax.add_p,
lax.scatter_add_p,
lax.dynamic_slice_p,
lax.slice_p,
lax.sub_p,
linear_p,
convert_float32_p,
*([lax.select_p] if hasattr(lax, 'select_p') else []),
*([lax.select_n_p] if hasattr(lax, 'select_n_p') else []),
]
BILINEAR_OP: Sequence[Primitive] = [
lax.dot_general_p,
lax.conv_general_dilated_p,
lax.mul_p,
lax.scatter_mul_p,
posbilinear_p,
]
# Don't use `functools.partial` here. We need to defer the invocation of
# `activation_specs()`, because it relies on Jax having been initialised.
activation_detector = lambda graph: detect(activation_specs(), graph)
activation_simplifier = lambda graph, _: activation_detector(graph)
default_simplifier = simplifier_composition(
activation_simplifier,
replace_eltwise_minimum,
replace_eltwise_maximum,
hoist_constant_computations,
group_linear_sequence,
group_posbilinear,
)
fused_relu_simplifier = simplifier_composition(default_simplifier,
group_fused_relu)
| jax_verify-master | jax_verify/src/synthetic_primitives.py |
# coding=utf-8
# 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.
"""Bound propagation utilities."""
import abc
from typing import Any, Callable, Generic, Mapping, Tuple, TypeVar
import jax
import jax.numpy as jnp
import jax_verify
from jax_verify.src import bound_propagation
from jax_verify.src import bound_utils
from jax_verify.src import graph_traversal
from jax_verify.src import utils
from jax_verify.src.types import Index, Nest, Primitive, Tensor # pylint: disable=g-multiple-import
T = TypeVar('T', bound=graph_traversal.TransformedNode)
class BackwardConcretizingTransform(
graph_traversal.BackwardGraphTransform[T],
Generic[T], # Explicitly restate this, to aid PyType resolution.
metaclass=abc.ABCMeta):
"""Abstract class for a Backward Transformation that can concretize bounds."""
@abc.abstractmethod
def concretize_args(self, primitive: Primitive) -> bool:
"""Return whether the arguments needs to be concretized.
Args:
primitive: Primitive that we are encountering.
"""
@abc.abstractmethod
def concrete_bound_chunk(
self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
node: jax.core.Var,
obj: Tensor,
) -> Tensor:
"""Computes concrete bounds for a chunk of neurons in the given layer.
Args:
graph: Graph to perform Backward Propagation on.
inputs: Bounds on the inputs.
env: Environment containing intermediate bound and shape information.
node: Graph node to obtain a bound for.
obj: One-hot tensor of shape (chunk_size, *node_shape) specifying, for
each index in the chunk, an element of the objective. Non-zero entries
may be +1 or -1 to request lower or upper bounds respectively.
Returns:
Bound of shape (chunk_size,) on the activation at `node`.
"""
class BackwardConcretizer(metaclass=abc.ABCMeta):
"""Abstract producer of concretize bounds by back-propagation."""
@abc.abstractmethod
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
"""Returns whether the primitive should be handled via its sub-graph."""
@abc.abstractmethod
def concretize_args(self, primitive: Primitive) -> bool:
"""Return whether the arguments needs to be concretized.
Args:
primitive: Primitive that we are encountering.
"""
@abc.abstractmethod
def concrete_bound(
self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
node_ref: jax.core.Var,
) -> jax_verify.IntervalBound:
"""Perform backward linear bound computation for the node `index`.
Args:
graph: Graph to perform Backward Propagation on.
inputs: Bounds on the inputs.
env: Environment containing intermediate bound and shape information.
node_ref: Graph node to obtain a bound for.
Returns:
concrete_bound: IntervalBound on the activation at `node`.
"""
class ChunkedBackwardConcretizer(BackwardConcretizer):
"""Concretizer that invokes the given transform in chunks for each layer."""
def __init__(self,
concretizing_transform: BackwardConcretizingTransform[Any],
max_chunk_size: int = 0):
self._concretizing_transform = concretizing_transform
self._max_chunk_size = max_chunk_size
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
return self._concretizing_transform.should_handle_as_subgraph(primitive)
def concretize_args(self, primitive: Primitive) -> bool:
return self._concretizing_transform.concretize_args(primitive)
def concrete_bound(
self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
node_ref: jax.core.Var,
) -> jax_verify.IntervalBound:
"""Perform backward linear bound computation for the node `index`.
Args:
graph: Graph to perform Backward Propagation on.
inputs: Bounds on the inputs.
env: Environment containing intermediate bound and shape information.
node_ref: Reference of the node to obtain a bound for.
Returns:
concrete_bound: IntervalBound on the activation at `node_ref`.
"""
node = graph_traversal.read_env(env, node_ref)
def bound_fn(obj: Tensor) -> Tuple[Tensor, Tensor]:
# Handle lower bounds and upper bounds independently in the same chunk.
obj = jnp.concatenate([obj, -obj], axis=0)
all_bounds = self._concretizing_transform.concrete_bound_chunk(
graph, inputs, env, node_ref, obj)
# Separate out the lower and upper bounds.
lower_bound, neg_upper_bound = jnp.split(all_bounds, 2, axis=0)
upper_bound = -neg_upper_bound
return lower_bound, upper_bound
return jax_verify.IntervalBound(
*utils.chunked_bounds(node.shape, self._max_chunk_size, bound_fn))
def stop_gradient_postprocess(
index: Index,
concrete_bound: bound_propagation.Bound,
) -> bound_propagation.Bound:
del index # unused
return jax_verify.IntervalBound(
jax.lax.stop_gradient(concrete_bound.lower),
jax.lax.stop_gradient(concrete_bound.upper))
class BackwardConcretizingAlgorithm(
bound_propagation.PropagationAlgorithm[bound_propagation.Bound]):
"""Abstract Backward graph propagation method with forward concretization.
A trace through the network is first obtained, then backward bound
computations are performed for each of the node requiring to be concretized,
such as intermediate nodes that are inputs to non-linearity or output values.
Note that the resulting environment of intermediate bounds (returned by
`propagate` alongside the concrete output bound) is sparse, in the sense that
many nodes will only contain a placeholder `GraphNode` with vacuous bounds.
The only nodes guaranteed to contain genuine bounds are the args to
concretised nodes, and the final outputs. In addition, the graph inputs are
included in concrete form for convenience.
"""
def __init__(
self,
backward_concretizer: BackwardConcretizer,
bound_postprocess_fn: Callable[
[Index, bound_propagation.LayerInput],
bound_propagation.LayerInput] = lambda _, x: x):
self._backward_concretizer = backward_concretizer
self._bound_postprocess_fn = bound_postprocess_fn
def propagate(
self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
) -> Tuple[
Nest[bound_propagation.LayerInput],
Mapping[jax.core.Var, bound_propagation.LayerInput]]:
subgraph_decider = self._backward_concretizer.should_handle_as_subgraph
graph_inspector = bound_utils.GraphInspector(subgraph_decider)
inspector_algorithm = bound_propagation.ForwardPropagationAlgorithm(
graph_inspector)
gn_outvals, env = inspector_algorithm.propagate(graph, inputs)
env = dict(env) # take a modifiable copy
def lazily_concretize(index, *, is_output):
jaxpr_node = graph.jaxpr_node(index)
graph_node = env[jaxpr_node]
if isinstance(graph_node, bound_utils.GraphNode):
# This node has not yet been concretized. Perform concretization.
concrete_bound = self._backward_concretizer.concrete_bound(
graph, inputs, env, jaxpr_node)
if not is_output:
concrete_bound = self._bound_postprocess_fn(index, concrete_bound)
# Update the environment, replacing the graph node with the concretised
# bound. Note that the same graph node may occur multiple times, under
# separate variables as we step into or out of a subgraph.
for k, v in env.items():
if v is graph_node:
env[k] = concrete_bound
# Iterate over the nodes in order so that we get intermediate bounds in
# the order where we need them.
for node in graph_inspector.nodes.values():
if (not node.is_input() and
self._backward_concretizer.concretize_args(node.primitive)):
for node_arg in node.args:
if isinstance(node_arg, bound_propagation.Bound):
lazily_concretize(node_arg.index, is_output=False)
# Iterate over the outputs, making sure to concretize all of them.
outvals = []
for gn in gn_outvals:
lazily_concretize(gn.index, is_output=True)
outvals.append(env[graph.jaxpr_node(gn.index)])
# Fill in the bounds for the inputs.
# This is unnecessary for backward methods themselves, but may be useful
# if the resulting `env` is used as a set of base bounds for a forward
# method.
flat_inputs, _ = jax.tree_util.tree_flatten(inputs)
for in_jaxpr_node, in_bound in zip(graph.inputs, flat_inputs):
if isinstance(env[in_jaxpr_node], bound_utils.GraphNode):
env[in_jaxpr_node] = in_bound
return outvals, env
class BackwardAlgorithmForwardConcretization(
bound_propagation.PropagationAlgorithm[bound_propagation.Bound]):
"""Abstract Backward graph propagation with forward concretization."""
def __init__(self, forward_transform: bound_propagation.BoundTransform,
backward_concretizer: BackwardConcretizer):
self._forward_algorithm = bound_propagation.ForwardPropagationAlgorithm(
forward_transform)
self._backward_concretizer = backward_concretizer
def propagate(
self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
) -> Tuple[
Nest[bound_propagation.LayerInput],
Mapping[jax.core.Var, bound_propagation.LayerInput]]:
# Perform the forward propagation so that all intermediate bounds are
# concretized.
_, env = self._forward_algorithm.propagate(graph, inputs)
env = dict(env) # take a modifiable copy
# Iterate over the outputs, computing each one separately.
outvals = []
for out_var in graph.outputs:
concrete_outvar_bound = self._backward_concretizer.concrete_bound(
graph, inputs, env, out_var)
outvals.append(concrete_outvar_bound)
env[out_var] = concrete_outvar_bound
return outvals, env
| jax_verify-master | jax_verify/src/concretization.py |
# coding=utf-8
# 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.
"""Pre-canned non-convex methods."""
from typing import Callable
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import ibp
from jax_verify.src import synthetic_primitives
from jax_verify.src.nonconvex import duals
from jax_verify.src.nonconvex import nonconvex
from jax_verify.src.nonconvex import optimizers
from jax_verify.src.types import Nest, Tensor # pylint: disable=g-multiple-import
def nonconvex_ibp_bound_propagation(
function: Callable[..., Nest[Tensor]],
*bounds: Nest[graph_traversal.GraphInput],
graph_simplifier=synthetic_primitives.default_simplifier,
) -> Nest[nonconvex.NonConvexBound]:
"""Builds the non-convex objective using IBP.
Args:
function: Function performing computation to obtain bounds for. Takes as
only arguments the network inputs.
*bounds: Bounds on the inputs of the function.
graph_simplifier: What graph simplifier to use.
Returns:
output_bounds: NonConvex bounds that can be optimized with a solver.
"""
algorithm = nonconvex.nonconvex_algorithm(
duals.WolfeNonConvexBound,
nonconvex.BaseBoundConcretizer(),
base_boundprop=ibp.bound_transform)
output_bounds, _ = bound_propagation.bound_propagation(
algorithm, function, *bounds, graph_simplifier=graph_simplifier)
return output_bounds
def nonconvex_constopt_bound_propagation(
function: Callable[..., Nest[Tensor]],
*bounds: Nest[graph_traversal.GraphInput],
graph_simplifier=synthetic_primitives.default_simplifier,
) -> Nest[nonconvex.NonConvexBound]:
"""Builds the optimizable objective.
Args:
function: Function performing computation to obtain bounds for. Takes as
only arguments the network inputs.
*bounds: Bounds on the inputs of the function.
graph_simplifier: What graph simplifier to use.
Returns:
output_bounds: NonConvex bounds that can be optimized with a solver.
"""
nostep_optimizer = optimizers.OptimizingConcretizer(
optimizers.PGDOptimizer(0, 0., optimize_dual=False),
max_parallel_nodes=512)
algorithm = nonconvex.nonconvex_algorithm(
duals.WolfeNonConvexBound, nostep_optimizer)
output_bounds, _ = bound_propagation.bound_propagation(
algorithm, function, *bounds, graph_simplifier=graph_simplifier)
return output_bounds
| jax_verify-master | jax_verify/src/nonconvex/methods.py |
# coding=utf-8
# 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.
"""Provides optimizers to use with the NonConvexBound in `nonconvex.py`.
"""
import abc
import functools
from typing import Tuple, Callable, Mapping, Optional, Sequence, Union
import jax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import ibp
from jax_verify.src import optimizers
from jax_verify.src import utils
from jax_verify.src.branching import branch_selection
from jax_verify.src.nonconvex import nonconvex
from jax_verify.src.types import Index, Tensor # pylint: disable=g-multiple-import
import optax
ParamSet = nonconvex.ParamSet
class BoundOptimizer(metaclass=abc.ABCMeta):
"""Abstract Class to define the API of optimizer.
Each subclass defines an optimization algorithm to solve the optimization
problem defined by a NonConvexBound. This is done by overloading the
`optimize` function.
"""
@abc.abstractmethod
def optimize_fun(self, non_convex_bound: nonconvex.NonConvexBound
) -> Callable[[ParamSet, ParamSet], ParamSet]:
pass
class OptimizingConcretizer(nonconvex.Concretizer):
"""Concretizer based on optimizing the intermediate bounds.
This needs to be initialized with an optimizer, and concrete bounds will be
obtained by solving the relaxation for the intermediate activations.
"""
def __init__(
self, optimizer: BoundOptimizer,
max_parallel_nodes: int = 512,
branching_constraints: Optional[
branch_selection.BranchingDecisionList] = None,
branching_optimizer: Optional[optax.GradientTransformation] = None,
branching_opt_number_steps: int = 0):
self._optimizer = optimizer
self._max_parallel_nodes = max_parallel_nodes
self._branching_constraints = []
self._branching_optimizer = None
self._branching_opt_number_steps = branching_opt_number_steps
if branching_constraints is not None:
self._branching_constraints = branching_constraints
# Keep the optimizer for the branching constraints dual variables.
if (branching_optimizer is None) or (branching_opt_number_steps == 0):
raise ValueError('If branching constraints are imposed, an optimizer '
'and a number of optimization steps for the lagrangian'
' variables corresponding to them needs to be '
'provided.')
self._branching_optimizer = branching_optimizer
self._branching_opt_number_steps = branching_opt_number_steps
def concrete_bound(
self,
graph: graph_traversal.PropagationGraph,
env: Mapping[jax.core.Var, Union[bound_propagation.Bound, Tensor]],
nonconvex_bound: nonconvex.NonConvexBound) -> bound_propagation.Bound:
return self.get_bounds(nonconvex_bound)
def get_bounds(self, to_opt_bound: nonconvex.NonConvexBound
) -> bound_propagation.Bound:
optimize_fun = self._optimizer.optimize_fun(to_opt_bound)
def bound_fn(obj: Tensor) -> Tuple[Tensor, Tensor]:
var_shapes, chunk_objectives = _create_opt_problems(to_opt_bound, obj)
ini_var_set = {key: 0.5 * jnp.ones(shape)
for key, shape in var_shapes.items()}
def solve_problem(objectives: ParamSet) -> Tensor:
# Optimize the bound for primal variables.
opt_var_set = optimize_fun(objectives, ini_var_set)
# Compute the resulting bound
_, bound_vals = to_opt_bound.dual(jax.lax.stop_gradient(opt_var_set),
objectives)
return bound_vals
if any(node_idx <= to_opt_bound.index
for (node_idx, *_) in self._branching_constraints):
# There exists constraints that needs to be taken into account.
# The dual vars per constraint are scalars, but we need to apply them
# for each of the optimization objective.
nb_targets = chunk_objectives[to_opt_bound.index].shape[0]
# Create the dual variables for them.
active_branching_constraints = [
(node_idx, neuron_idx, val, side)
for (node_idx, neuron_idx, val, side) in self._branching_constraints
if node_idx <= to_opt_bound.index]
nb_constraints = len(active_branching_constraints)
dual_vars = [jnp.zeros([nb_targets])] * nb_constraints
# Define the objective function to optimize. The branching constraints
# are lifted into the objective function.
def unbranched_objective(dual_vars: ParamSet) -> Tuple[float, Tensor]:
objectives = dict(chunk_objectives)
base_term = jnp.zeros([nb_targets])
for ((node_idx, neuron_idx, val, side),
branch_dvar) in zip(active_branching_constraints, dual_vars):
# Adjust the objective function to incorporate the dual variables.
if node_idx not in objectives:
objectives[node_idx] = jnp.zeros(var_shapes[node_idx])
# The branching constraint is encoded as:
# side * neuron >= side * val
# (when side==1, this is neuron >= lb,
# and when side==-1, this is -neuron >= -ub )
# To put in a canonical form \lambda_b() <= 0, this is:
# \lambda_b() = side * val - side * neuron
# Lifting the branching constraints takes us from the problem:
# min_{z} f(z)
# s.t. \mu_i() <= z_i <= \eta_i() \forall i
# \lambda_b() <= 0 \forall b
#
# to
# max_{\rho_b} min_{z} f(z) + \rho_b \lambda_b()
# s.t \mu_i() <= z_i <= \eta_i() \forall i
# s.t rho_b >= 0
# Add the term corresponding to the dual variables to the linear
# objective function.
coeff_to_add = -side * branch_dvar
index_to_update = jnp.index_exp[:, neuron_idx]
flat_node_obj = jnp.reshape(objectives[node_idx], (nb_targets, -1))
flat_updated_node_obj = flat_node_obj.at[index_to_update].add(
coeff_to_add)
updated_node_obj = jnp.reshape(flat_updated_node_obj,
var_shapes[node_idx])
objectives[node_idx] = updated_node_obj
# Don't forget the terms based on the bound.
base_term = base_term + (side * val * branch_dvar)
network_term = solve_problem(objectives)
bound = network_term + base_term
return bound.sum(), bound # pytype: disable=bad-return-type # jax-ndarray
def evaluate_bound(ini_dual_vars: Sequence[Tensor]) -> Tensor:
ini_state = self._branching_optimizer.init(ini_dual_vars)
eval_and_grad_fun = jax.grad(unbranched_objective, argnums=0,
has_aux=True)
# The carry consists of:
# - The best set of dual variables seen so far.
# - The current set of dual variables.
# - The best bound obtained so far.
# - The state of the optimizer.
# For each of the step, we will:
# - Evaluate the bounds by the current set of dual variables.
# - Update the best set of dual variables if progress was achieved.
# - Do an optimization step on the current set of dual variables.
# This way, we are guaranteed that we keep track of the dual variables
# producing the best bound at the end.
def opt_step(
carry: Tuple[Sequence[Tensor], Sequence[Tensor],
Tensor, optax.OptState], _
) -> Tuple[Tuple[Sequence[Tensor], Sequence[Tensor],
Tensor, optax.OptState], None]:
best_lagdual, lagdual, best_bound, state = carry
# Compute the bound and their gradients.
lagdual_grads, new_bound = eval_and_grad_fun(lagdual)
# Update the lagrangian dual variables for the best bound seen.
improve_best = new_bound > best_bound
new_best_lagdual = []
for best_dvar, new_dvar in zip(best_lagdual, lagdual):
new_best_lagdual.append(jnp.where(improve_best,
new_dvar, best_dvar))
# Update the best bound seen
new_best_bound = jnp.maximum(best_bound, new_bound)
# Perform optimization step
updates, new_state = self._branching_optimizer.update(
lagdual_grads, state, lagdual)
unc_dual = optax.apply_updates(lagdual, updates)
new_lagdual = jax.tree_map(lambda x: jnp.maximum(x, 0.), unc_dual)
return ((new_best_lagdual, new_lagdual, new_best_bound, new_state),
None)
dummy_bound = -float('inf')*jnp.ones([nb_targets])
initial_carry = (ini_dual_vars, ini_dual_vars, dummy_bound, ini_state)
(best_lagdual, *_), _ = jax.lax.scan(
opt_step, initial_carry, None,
length=self._branching_opt_number_steps)
_, bound_vals = unbranched_objective(
jax.lax.stop_gradient(best_lagdual))
return bound_vals
bound_vals = evaluate_bound(dual_vars)
else:
bound_vals = solve_problem(chunk_objectives)
chunk_lbs, chunk_ubs = _unpack_opt_problem(bound_vals)
return chunk_lbs, chunk_ubs
return ibp.IntervalBound(*utils.chunked_bounds(
to_opt_bound.shape, self._max_parallel_nodes, bound_fn))
def _create_opt_problems(
non_convex_bound: nonconvex.NonConvexBound,
obj: Tensor,
) -> Tuple[Mapping[Index, Tuple[int, ...]], ParamSet]:
"""Define the objective function and the necessary variables shape.
Iteratively yields the objectives to minimize in order to limit memory usage.
Args:
non_convex_bound: Bound for which to create the optimization problems.
obj: One-hot tensor of shape (nb_parallel_nodes, *obj_shape) specifying
the elements of the objective to optimise.
Returns:
var_to_opt: shapes of the variables to optimize to compute the bounds.
objectives_by_layer: Objectives to minimize, in the form of a dictionary
mapping the position of activations to the linear coefficients of the
objective function.
"""
# Get the objective for the upper bounds.
lb_obj = obj
ub_obj = -obj
obj = jnp.concatenate([lb_obj, ub_obj], axis=0)
# Generate the shape of the variables necessary to solve the problem
var_to_opt = {}
for pos, var_shape in non_convex_bound.variables.items():
var_to_opt[pos] = (obj.shape[0],) + var_shape
objectives_by_layer = {non_convex_bound.index: obj}
return var_to_opt, objectives_by_layer
def _unpack_opt_problem(dual_vals: Tensor) -> Tuple[Tensor, Tensor]:
"""Extract the lower bounds and upper bounds from the result of optmization.
Args:
dual_vals: Value of the dual returned by the optimization process.
Returns:
lb: Tensor containing lower bounds were they were computed and 0 elsewhere.
ub: Tensor containing upper bounds were they were computed and 0 elsewhere.
"""
lb_duals, ub_duals = jnp.split(dual_vals, 2, axis=0)
return lb_duals, -ub_duals
class LinesearchFistaOptimizer(BoundOptimizer):
"""FISTA with line search."""
def __init__(self,
num_steps: int,
max_step_size: float = 100.0,
min_step_size: float = 1e-5,
beta_l: float = 0.5,
beta_h: float = 1.5,
check_convergence_every: int = 1,
check_relative_dual_gap: bool = False,
termination_dual_gap: float = 1e-2):
self._optimizer = optimizers.LinesearchFistaOptimizer(
num_steps, max_step_size, min_step_size,
beta_l, beta_h, check_convergence_every)
self._check_relative_dual_gap = check_relative_dual_gap
self._termination_dual_gap = termination_dual_gap
def optimize_fun(self, non_convex_bound: nonconvex.NonConvexBound
)->Callable[[ParamSet, ParamSet], ParamSet]:
"""Returns a function optimizing the primal variables.
Args:
non_convex_bound: NonConvex object to define the objective function over
Returns:
optimize: Optimization function.
"""
def fun_to_opt(objectives, opt_vars):
"""Target functions to minimize.
The functions to minimize are the primal objectives, given
by non_convex_bound.primal function. This function also returns the
intermediate activation as an auxiliary output, which we want to
ignore.
Args:
objectives: Linear coefficients of the objective function on the
activations.
opt_vars: Value of the parameters to evaluate.
Returns:
obj: sum of the objective functions.
"""
obj, _ = non_convex_bound.primal_fn(opt_vars, objectives)
return obj
proj_fun = lambda opt_var: jnp.clip(opt_var, 0., 1.)
project_all_params = lambda opt_vars: jax.tree_map(proj_fun, opt_vars)
def any_not_done(objectives, opt_vars):
primal, dual = non_convex_bound.dual(opt_vars, objectives)
dgap_value = primal - dual
if self._check_relative_dual_gap:
bound_scale = 0.5 * (jnp.abs(primal) + jnp.abs(dual))
termination_gap = (1 + bound_scale) * self._termination_dual_gap
else:
termination_gap = self._termination_dual_gap
return (dgap_value > termination_gap).any()
def optimize(objectives: ParamSet, var_set: ParamSet) -> ParamSet:
obj_fun = functools.partial(fun_to_opt, objectives)
not_conv_fun = functools.partial(any_not_done, objectives)
opt_fun = self._optimizer.optimize_fn(obj_fun, project_all_params,
not_conv_fun)
return opt_fun(var_set)
return optimize
class PGDOptimizer(BoundOptimizer):
"""Projected Gradient Optimizer.
Optimization can either by taking gradients with respect to the primal or the
dual objective.
Passing a number of steps equal to zero will result in the bound derived from
the initialization.
"""
def __init__(self, num_steps: int, step_size: float,
optimize_dual: bool = False):
# Define the optimizer. Because we are minimizing the objective function,
# we will scale the gradient by a negative step size.
gradient_transform = optax.scale(-step_size)
self._optimizer = optimizers.OptaxOptimizer(
gradient_transform, num_steps=num_steps)
self._optimize_dual = optimize_dual
def optimize_fun(self, non_convex_bound: nonconvex.NonConvexBound,
) -> Callable[[ParamSet, ParamSet], ParamSet]:
"""Returns a function optimizing the primal variables.
Args:
non_convex_bound: NonConvex object to define the objective function over
Returns:
optimize: Optimization function.
"""
# If we are going to actually perform optimization, define the function to
# minimize (either the primal, or the negative of the dual),
# its gradient and the projection function to use.
def fun_to_opt(opt_vars, objectives):
if self._optimize_dual:
_, dual_vals = non_convex_bound.dual(opt_vars, objectives)
obj = -jnp.sum(dual_vals)
else:
obj, _ = non_convex_bound.primal_sumfn(opt_vars, objectives)
return obj
proj_fun = lambda x: jnp.clip(x, 0., 1.)
project_all_params = lambda x: jax.tree_map(proj_fun, x)
# Define the function to optimize a chunk of the nodes of the activation.
def optimize(objectives: ParamSet, var_set: ParamSet) -> ParamSet:
obj_fun = lambda opt_vars: fun_to_opt(opt_vars, objectives)
opt_fun = self._optimizer.optimize_fn(obj_fun, project_all_params)
return opt_fun(var_set)
return optimize
| jax_verify-master | jax_verify/src/nonconvex/optimizers.py |
# coding=utf-8
# 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.
"""Implement the dual computations for the NonConvex Reformulation."""
import collections
import functools
from typing import Callable, DefaultDict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Union
import jax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import synthetic_primitives
from jax_verify.src.nonconvex import nonconvex
from jax_verify.src.types import Index, Primitive, Tensor # pylint: disable=g-multiple-import
ParamSet = nonconvex.ParamSet
EvalFunArgs = [ParamSet, ParamSet, ParamSet]
WolfeDualFn = Callable[[ParamSet, Tensor, ParamSet, Tensor, Tensor, ParamSet],
Tensor]
LagrangianLevelFn = Callable[[Tensor, ParamSet], Tensor]
LagrangianBoundingFn = Callable[[Tensor, ParamSet], Tensor]
LagrangianVarTerm = Tuple[Union[str, Primitive], Callable[..., Tensor]]
LagrangianDict = DefaultDict[Index, MutableSequence[LagrangianVarTerm]]
LagrangianVartermsFn = Callable[[Tensor, LagrangianDict], None]
def _sum_fn(fn, *args, **kwargs):
out = fn(*args, **kwargs)
summand = out[0] if isinstance(out, tuple) else out
return summand.sum(), out
def _sum_over_acts(var: Tensor) -> Tensor:
return var.sum(axis=tuple(range(1, var.ndim)))
CVX_HULL_PRIMITIVES = (synthetic_primitives.relu_p,
synthetic_primitives.softplus_p,
synthetic_primitives.posbilinear_p,
)
class WolfeNonConvexBound(nonconvex.ConstrainedNonConvexBound):
"""This subclass allows the computation of the WolfeDual.
This is done through the `wolfe_dual_fn`, which propagates the dual variables
backwards. The quantity propagated backwards (dvar) needs to
be split between pos_dvar (dual variable on [lb_fun() - z]) and
neg_dvar (dual variable on [z - ub_fun()]).
In the presence of imposed (concrete) constraints, those need to be specified
differently. We need:
(bound_posdvar - bound_negdvar) + (boundfun_posdvar - boundfun_negdvar)
= dvar_cte + sum_{j>i} (boundfun_posdvar_j * lb_fun()
- boundfun_negdvar_j * ub_fun())
which means that we have degrees of freedom.
Current implementation decides based on a greedy approach, ignoring the
downstream consequences. This could be improved.
"""
def __init__(
self,
wolfe_dual_fn: WolfeDualFn,
index: Index,
shape: Tuple[int, ...],
previous_bounds: MutableMapping[Index, 'WolfeNonConvexBound'],
eval_fn: Callable[EvalFunArgs, Tensor],
variables: Mapping[Index, Tuple[int, ...]],
concretized_bounds: Optional[bound_propagation.Bound] = None):
"""Create a NonConvexBound that can compute the WolfeDual.
Args:
wolfe_dual_fn: Function performing backward propagation of bounds for the
wolfe dual and computing the contribution of this layer to the dual.
index: Unique index representing the position of this activation in the
computation graph.
shape: Shape of the activations that this bound represent.
previous_bounds: Dict mapping index of activation to the bound
representing it. We need it to be able to obtain the contributions of
previous layers to the Lagrangian.
eval_fn: Function to evaluate the bound computation problem in the primal
variables: Dict mapping index of activation to the shape of variables
required to optimize them.
concretized_bounds: (Optional) Precomputed bounds for this NonConvexBound.
"""
super().__init__(index, shape, previous_bounds,
eval_fn, variables, concretized_bounds)
self.wolfe_dual_fn = wolfe_dual_fn
def dual(self, var_set: ParamSet, objectives: ParamSet
) -> Tuple[Tensor, Tensor]:
dual_vars, acts = self._compute_dualvars_convexgrad(var_set, objectives)
primal = self._objective_fn(acts, objectives)
dual_gap = 0
index_bound_list = list(self.previous_bounds.items())
for index, intermediate_bound in reversed(index_bound_list):
wolfe_dual_fn = intermediate_bound.wolfe_dual_fn
if intermediate_bound.is_constrained():
wolfe_dual_contrib = wolfe_dual_fn(
var_set, dual_vars[index], acts,
intermediate_bound.lower, intermediate_bound.upper, dual_vars)
else:
wolfe_dual_contrib = wolfe_dual_fn(
var_set, dual_vars[index], acts, None, None, dual_vars)
dual_gap = dual_gap + wolfe_dual_contrib
wolfe_dual = primal + dual_gap
return primal, wolfe_dual
@classmethod
def get_initial_bound_constructor(
cls: Callable[..., 'WolfeNonConvexBound'],
index: Index,
lb: Tensor,
ub: Tensor) -> Callable[..., 'WolfeNonConvexBound']:
def wolfe_dual_fn(
var_set: ParamSet,
dvar: Tensor,
acts: ParamSet,
bound_lb: Tensor, bound_ub: Tensor,
dual_vars: ParamSet,
) -> Tensor:
del var_set
del bound_lb
del bound_ub
del dual_vars
pos_dvar = jnp.maximum(dvar, 0.)
neg_dvar = jnp.maximum(-dvar, 0.)
x_0 = acts[index]
dual_contrib = _sum_over_acts(pos_dvar * (lb - x_0)
+ neg_dvar * (x_0 - ub))
return dual_contrib
return functools.partial(cls, wolfe_dual_fn)
@classmethod
def get_linear_activation_constructor(
cls: Callable[..., 'WolfeNonConvexBound'],
index: Index,
vlin_fun: Callable[..., Tensor],
in_vals: Sequence[Union['WolfeNonConvexBound', Tensor]],
) -> Callable[..., 'WolfeNonConvexBound']:
def wolfe_dual_fn(
var_set: ParamSet,
dvar: Tensor,
acts: ParamSet,
bound_lb: Tensor,
bound_ub: Tensor,
dual_vars: ParamSet,
) -> Tensor:
pos_dvar = jnp.maximum(dvar, 0.)
neg_dvar = jnp.maximum(-dvar, 0.)
all_inps = [nonconvex.eval_if_nonconvexbound(inp, var_set, None, acts)
for inp in in_vals]
if bound_lb is not None:
bound_fun_eval = vlin_fun(all_inps)
brd_bound_lb = jnp.expand_dims(bound_lb, 0)
brd_bound_ub = jnp.expand_dims(bound_ub, 0)
bound_posdvar = jnp.where(brd_bound_lb >= bound_fun_eval,
pos_dvar, jnp.zeros_like(pos_dvar))
pos_dvar = pos_dvar - bound_posdvar
bound_negdvar = jnp.where(brd_bound_ub <= bound_fun_eval,
neg_dvar, jnp.zeros_like(neg_dvar))
neg_dvar = neg_dvar - bound_negdvar
_, backprop = jax.vjp(vlin_fun, all_inps)
all_pp_dvars = backprop(pos_dvar)[0]
all_nq_dvars = backprop(neg_dvar)[0]
for i, inp_i in enumerate(in_vals):
if not isinstance(inp_i, nonconvex.NonConvexBound):
continue
prev_dvar = all_pp_dvars[i] - all_nq_dvars[i]
if inp_i.index in dual_vars:
prev_dvar = dual_vars[inp_i.index] + prev_dvar
dual_vars[inp_i.index] = prev_dvar
if bound_lb is not None:
act_out_eval = acts[index]
bound_fun_to_out = bound_fun_eval - act_out_eval
dual_contrib = _sum_over_acts(
jnp.where(bound_posdvar > 0,
bound_posdvar * (brd_bound_lb - act_out_eval),
jnp.zeros_like(bound_posdvar))
+ jnp.where(bound_negdvar > 0,
bound_negdvar * (act_out_eval - brd_bound_ub),
jnp.zeros_like(bound_negdvar))
+ (pos_dvar - neg_dvar) * bound_fun_to_out)
return dual_contrib
else:
# There shouldn't be a contrib term here; everything cancels out.
return 0
return functools.partial(cls, wolfe_dual_fn)
@classmethod
def get_nonlinearity_activation_constructor(
cls: Callable[..., 'WolfeNonConvexBound'],
index: Index,
act_type: Primitive,
lb_fun: Callable[[Tensor], Tensor],
ub_fun: Callable[[Tensor], Tensor],
*inp: 'WolfeNonConvexBound',
) -> Callable[..., 'WolfeNonConvexBound']:
def wolfe_dual_fn(
var_set: ParamSet,
dvar: Tensor,
acts: ParamSet,
bound_lb: Tensor,
bound_ub: Tensor,
dual_vars: ParamSet,
) -> Tensor:
pos_dvar = jnp.maximum(dvar, 0.)
neg_dvar = jnp.maximum(-dvar, 0.)
inp_val = [inp_i.evaluate(var_set, {}, acts) for inp_i in inp]
lb_val, lb_backprop = jax.vjp(lb_fun, *inp_val)
ub_val, ub_backprop = jax.vjp(ub_fun, *inp_val)
if bound_lb is not None:
brd_bound_lb = jnp.expand_dims(bound_lb, 0)
brd_bound_ub = jnp.expand_dims(bound_ub, 0)
bound_posdvar = jnp.where(brd_bound_lb >= lb_val,
pos_dvar, jnp.zeros_like(pos_dvar))
pos_dvar = pos_dvar - bound_posdvar
bound_negdvar = jnp.where(brd_bound_ub <= ub_val,
neg_dvar, jnp.zeros_like(neg_dvar))
neg_dvar = neg_dvar - bound_negdvar
backprop_pos = lb_backprop(pos_dvar)
backprop_neg = ub_backprop(neg_dvar)
for (i, inp_i) in enumerate(inp):
prev_dvar = backprop_pos[i] - backprop_neg[i]
if inp_i.index in dual_vars:
prev_dvar = dual_vars[inp_i.index] + prev_dvar
dual_vars[inp_i.index] = prev_dvar
out_val = acts[index]
dual_contrib = _sum_over_acts(neg_dvar * (out_val - ub_val)
+ pos_dvar * (lb_val - out_val))
if bound_lb is not None:
dual_contrib = dual_contrib + _sum_over_acts(
jnp.where(bound_posdvar > 0,
bound_posdvar * (brd_bound_lb - out_val),
jnp.zeros_like(bound_posdvar))
+ jnp.where(bound_negdvar > 0,
bound_negdvar * (out_val - brd_bound_ub),
jnp.zeros_like(bound_negdvar)))
return dual_contrib
return functools.partial(cls, wolfe_dual_fn)
def requires_concretizing(self, consuming_primitive):
needs_concretizing = (consuming_primitive is None
or consuming_primitive in CVX_HULL_PRIMITIVES)
return (self._concretized_bounds is None) and needs_concretizing
def _initial_lagrangian_term(dvar: Tensor, lb: Tensor, ub: Tensor, x: Tensor
) -> Tensor:
pos_dvar = jnp.maximum(dvar, 0.)
neg_dvar = jnp.maximum(-dvar, 0.)
dual_contrib = (neg_dvar * (x - ub) + pos_dvar * (lb - x))
return dual_contrib
class LinLagrangianNonConvexBound(nonconvex.NonConvexBound):
"""This subclass allows the computation of the Linearized Lagrangian dual.
The lagrangian and its linearization are obtained through the
`lagrangian_level_fn` which compute the contribution of this layer to the
lagrangian, based on precomputed activation.
The minimization of linear function (such as the linearized lagrangian) over
the feasible domain is done through the `bounding_fn` function.
"""
def __init__(
self,
lagrangian_level_fn: LagrangianLevelFn,
bounding_fn: LagrangianBoundingFn,
index: Index,
shape: Tuple[int, ...],
previous_bounds: MutableMapping[Index, 'LinLagrangianNonConvexBound'],
eval_fn: Callable[EvalFunArgs, Tensor],
variables: Mapping[Index, Tuple[int, ...]],
concretized_bounds: Optional[bound_propagation.Bound] = None):
"""Create a NonConvexBound that can compute the Linearized Lagrangian dual.
Args:
lagrangian_level_fn: Function returning the contribution of this layer to
the lagrangian, based on precomputed activations.
bounding_fn: Function to perform linear minimization over the domain of
an activation.
index: Unique index representing the position of this activation in the
computation graph.
shape: Shape of the activations that this bound represent.
previous_bounds: Dict mapping index of activation to the bound
representing it. We need it to be able to obtain the contributions of
previous layers to the Lagrangian.
eval_fn: Function to evaluate the bound computation problem in the primal
variables: Dict mapping index of activation to the shape of variables
required to optimize them.
concretized_bounds: (Optional) Precomputed bounds for this NonConvexBound.
"""
super(LinLagrangianNonConvexBound, self).__init__(
index, shape, previous_bounds, eval_fn,
variables, concretized_bounds)
self.lagrangian_level_fn = lagrangian_level_fn
self.bounding_fn = bounding_fn
def lagrangian(acts: ParamSet,
objectives: ParamSet,
dual_vars: Tensor,
) -> Tuple[Tensor, ParamSet]:
primals = self._objective_fn(acts, objectives)
lagrangian = primals
for index, intermediate_bound in self.previous_bounds.items():
lagrangian_level_fn = intermediate_bound.lagrangian_level_fn
dvar = dual_vars[index]
contrib = lagrangian_level_fn(dvar, acts)
lagrangian += contrib
return lagrangian, primals
self._lagrangian_fn = lagrangian
self._lagrangian_sumfn = functools.partial(_sum_fn, lagrangian)
def dual(self, var_set: ParamSet, objectives: ParamSet) -> Tensor:
dual_vars, acts = self._compute_dualvars_nonconvexgrad(var_set, objectives)
# Compute the gradients of all the lagrangians (done by taking their sum),
# with regards to the activations.
lag_grad_fun = jax.value_and_grad(self._lagrangian_sumfn, argnums=0,
has_aux=True)
((_, (lagrangians, primals)),
laggrad_wrt_acts) = lag_grad_fun(acts, objectives, dual_vars)
lin_duals = lagrangians
for index, intermediate_bound in self.previous_bounds.items():
bounding_fn = intermediate_bound.bounding_fn
lag_grad = laggrad_wrt_acts[index]
contrib = bounding_fn(lag_grad, acts)
lin_duals += contrib
return primals, lin_duals # pytype: disable=bad-return-type # jax-ndarray
@classmethod
def get_initial_bound_constructor(
cls: Callable[..., 'LinLagrangianNonConvexBound'],
index: Index,
lb: Tensor,
ub: Tensor) -> Callable[..., 'LinLagrangianNonConvexBound']:
def lagrangian_level_fn(dvar: Tensor, acts: ParamSet) -> Tensor:
x_0 = acts[index]
dual_contrib = _sum_over_acts(_initial_lagrangian_term(dvar, lb, ub, x_0))
return dual_contrib
def bounding_fn(lag_grad: Tensor, acts: ParamSet) -> Tensor:
x_0 = acts[index]
bound_contrib = _sum_over_acts(jnp.maximum(lag_grad, 0.) * (lb - x_0) +
jnp.minimum(lag_grad, 0.) * (ub - x_0))
return bound_contrib
return functools.partial(cls, lagrangian_level_fn, bounding_fn)
@classmethod
def get_linear_activation_constructor(
cls: Callable[..., 'LinLagrangianNonConvexBound'],
index: Index,
vlin_fun: Callable[..., Tensor],
in_vals: Tuple[Union['LinLagrangianNonConvexBound', Tensor], ...]
) -> Callable[..., 'LinLagrangianNonConvexBound']:
def lagrangian_level_fn(dvar: Tensor, acts: ParamSet) -> Tensor:
act_inp_eval = [
acts[inp.index] if isinstance(inp, nonconvex.NonConvexBound) else inp
for inp in in_vals]
# Because this is linear, the function is both the lower bound and the
# upper bound.
act_out_eval = acts[index]
f_inp_eval = vlin_fun(act_inp_eval)
dual_contrib = _sum_over_acts(dvar * (f_inp_eval - act_out_eval))
return dual_contrib
def bounding_fn(lag_grad: Tensor, acts: ParamSet) -> Tensor:
act_out_eval = acts[index]
# We need to minimize the dotproduct between the lagrangian and the output
# of that linear layer. Let's take the gradient (because everything is
# linear and then we can simply assign bounds based on sign of gradient
# coefficients.)
dot_lagrangian_output = lambda x: (lag_grad * vlin_fun(x)).sum()
act_inp_eval = [
acts[inp.index] if isinstance(inp, nonconvex.NonConvexBound) else inp
for inp in in_vals]
minimizing_inps = []
grads = jax.grad(dot_lagrangian_output)(act_inp_eval)
for inp, grad in zip(in_vals, grads):
if isinstance(inp, nonconvex.NonConvexBound):
broad_lb = jnp.expand_dims(inp.lower, 0)
broad_ub = jnp.expand_dims(inp.upper, 0)
minimizing_inps.append(jnp.where(grad >= 0, broad_lb, broad_ub))
else:
minimizing_inps.append(inp)
bound_contrib = _sum_over_acts((vlin_fun(minimizing_inps) - act_out_eval)
* lag_grad)
return bound_contrib
return functools.partial(cls, lagrangian_level_fn, bounding_fn)
@classmethod
def get_nonlinearity_activation_constructor(
cls: Callable[..., 'LinLagrangianNonConvexBound'],
index: Index,
act_type: Primitive,
lb_fun: Callable[[Tensor], Tensor],
ub_fun: Callable[[Tensor], Tensor],
*inp: 'LinLagrangianNonConvexBound',
) -> Callable[..., 'LinLagrangianNonConvexBound']:
assert len(inp) == 1
inp = inp[0]
def lagrangian_level_fn(dvar: Tensor, acts: ParamSet) -> Tensor:
pos_dvar = jnp.maximum(dvar, 0.)
neg_dvar = jnp.maximum(-dvar, 0.)
act_inp_eval = acts[inp.index]
act_out_eval = acts[index]
lb_val = lb_fun(act_inp_eval)
ub_val = ub_fun(act_inp_eval)
dual_contrib = _sum_over_acts(neg_dvar * (act_out_eval - ub_val)
+ pos_dvar * (lb_val - act_out_eval))
return dual_contrib
# We consider convex monotonous activation functions, so
# - The lower bound is exact.
# - The lower/upper bound on the output can be obtained by forwarding
# through the exact function the lower/upper bound on the input.
out_lb = lb_fun(jnp.expand_dims(inp.lower, 0))
out_ub = lb_fun(jnp.expand_dims(inp.upper, 0))
def bounding_fn(lag_grad: Tensor, acts: ParamSet) -> Tensor:
act_out_eval = acts[index]
lb_val = jnp.expand_dims(out_lb, 0)
ub_val = jnp.expand_dims(out_ub, 0)
bound_contrib = _sum_over_acts(
jnp.maximum(lag_grad, 0.) * (lb_val - act_out_eval)
+ jnp.minimum(lag_grad, 0.) * (ub_val - act_out_eval))
return bound_contrib
return functools.partial(cls, lagrangian_level_fn, bounding_fn)
def requires_concretizing(self, consuming_primitive):
return self._concretized_bounds is None
class MinLagrangianNonConvexBound(nonconvex.NonConvexBound):
"""This subclass allows the computation of the primal minimized lagrangian.
The contribution of each primal variables are collected by the
`lagrangian_varterms_fn`. It does not directly compute the lagrangian but
fills in a dictionary mapping variables to the terms that involve them.
This is done so that we can reorganize the lagrangian per variable, and then
minimize it one variable at a time.
"""
def __init__(
self,
lagrangian_varterms_fn: LagrangianVartermsFn,
index: Index,
shape: Tuple[int, ...],
previous_bounds: MutableMapping[Index, 'MinLagrangianNonConvexBound'],
eval_fn: Callable[EvalFunArgs, Tensor],
variables: Mapping[Index, Tuple[int, ...]],
concretized_bounds: Optional[bound_propagation.Bound] = None):
"""Create a NonConvexBound that can compute the primal minimized Lagrangian.
Args:
lagrangian_varterms_fn: Function filling in a dictionary mapping each
variable to the terms involving it in the lagrangian.
index: Unique index representing the position of this activation in the
computation graph.
shape: Shape of the activations that this bound represent.
previous_bounds: Dict mapping index of activation to the bound
representing it. We need it to be able to obtain the contributions of
previous layers to the Lagrangian.
eval_fn: Function to evaluate the bound computation problem in the primal
variables: Dict mapping index of activation to the shape of variables
required to optimize them.
concretized_bounds: (Optional) Precomputed bounds for this NonConvexBound.
"""
super(MinLagrangianNonConvexBound, self).__init__(
index, shape, previous_bounds, eval_fn, variables, concretized_bounds)
self.lagrangian_varterms_fn = lagrangian_varterms_fn
def collect_lagrangian_varterms(self,
objectives: ParamSet,
dual_vars: ParamSet) -> LagrangianDict:
lagrangian_dict = collections.defaultdict(list)
for index, intermediate_bound in self.previous_bounds.items():
lagrangian_varterms_fn = intermediate_bound.lagrangian_varterms_fn
dvar = dual_vars[index]
lagrangian_varterms_fn(dvar, lagrangian_dict)
return lagrangian_dict
def dual(self, var_set: ParamSet, objectives: ParamSet) -> Tensor:
dual_vars, acts = self._compute_dualvars_nonconvexgrad(var_set, objectives)
nb_targets = objectives[self.index].shape[0]
# Compute the primals. This is not based on the activation minimizing the
# lagrangian (because those are not necessarily primal feasible)
primals = self._objective_fn(acts, objectives)
lagrangian_terms = self.collect_lagrangian_varterms(objectives, dual_vars)
# For each item in the network, we have a list of all the terms it is
# involved in. Let's use this to minimize the lagrangian.
opt_acts = {}
for index, lag_terms in lagrangian_terms.items():
intermediate_bound = self.previous_bounds[index]
broad_lb = jnp.repeat(jnp.expand_dims(intermediate_bound.lower, axis=0),
nb_targets, axis=0)
broad_ub = jnp.repeat(jnp.expand_dims(intermediate_bound.upper, axis=0),
nb_targets, axis=0)
opt_acts[index] = _optimize_lagrangian_terms(lag_terms,
broad_lb, broad_ub)
minimized_lagrangian = self._objective_fn(opt_acts, objectives)
for index, lag_terms in lagrangian_terms.items():
for _, lag_term_fn in lag_terms:
out_term = lag_term_fn(opt_acts[index])
minimized_lagrangian = minimized_lagrangian + _sum_over_acts(out_term)
return primals, minimized_lagrangian # pytype: disable=bad-return-type # jax-ndarray
@classmethod
def get_initial_bound_constructor(
cls: Callable[..., 'MinLagrangianNonConvexBound'],
index: Index,
lb: Tensor,
ub: Tensor) -> Callable[..., 'MinLagrangianNonConvexBound']:
def lagrangian_varterms_fn(dvar: Tensor, lagrangian_dict: LagrangianDict):
lagrangian_dict[index].append(
('Linear', functools.partial(_initial_lagrangian_term, dvar, lb, ub)))
return functools.partial(cls, lagrangian_varterms_fn)
@classmethod
def get_linear_activation_constructor(
cls: Callable[..., 'MinLagrangianNonConvexBound'],
index: Index,
vlin_fun: Callable[..., Tensor],
in_vals: Sequence[Union['MinLagrangianNonConvexBound', Tensor]],
) -> Callable[..., 'MinLagrangianNonConvexBound']:
def lagrangian_varterms_fn(dvar: Tensor, lagrangian_dict: LagrangianDict):
# There is a linear term of dvar over the outputs.
lagrangian_dict[index].append(('Linear', lambda x: (-dvar*x)))
# If only one of the input is a variable, we can do things in a simple
# way. Special casing this pattern avoids a bunch of failures on TPUs.
inp_is_bound = list(isinstance(inp, nonconvex.NonConvexBound)
for inp in in_vals)
if sum(inp_is_bound) == 1:
bound_arg_pos = inp_is_bound.index(True)
# The linear function has only one input, so we can just use it
# directly.
def single_input_vlin_fun(x):
inps = [inp if not is_bound else x
for inp, is_bound in zip(in_vals, inp_is_bound)]
return dvar * vlin_fun(inps)
lagrangian_dict[in_vals[bound_arg_pos].index].append( # pytype: disable=attribute-error # jax-ndarray
('Linear', single_input_vlin_fun))
else:
# There is multiple inputs, so we need to separate the contribution of
# each one, and assign the bias to one of them.
inps = []
for inp in in_vals:
if isinstance(inp, nonconvex.NonConvexBound):
# Add the opt dimension, and put in all the examples to 0, so that
# we can identify the bias term.
shape = inp.shape
inp_shape = (dvar.shape[0],) + shape
example_inp = jnp.zeros(inp_shape)
inps.append(example_inp)
else:
inps.append(inp)
# Get the linear term over the inputs through auto-diff
def lag_inp_contrib(x):
contrib = dvar * vlin_fun(x)
contrib = _sum_over_acts(contrib)
return contrib.sum(), contrib
(_, bias), grads = jax.value_and_grad(lag_inp_contrib,
has_aux=True)(inps)
grad_dot_prod = lambda grad, bias, x: _sum_over_acts(grad * x) + bias
for inp, grad in zip(in_vals, grads):
if isinstance(inp, nonconvex.NonConvexBound):
lagrangian_dict[inp.index].append(
('Linear', functools.partial(grad_dot_prod, grad, bias)))
# Zero out the bias now that it has been included in one term.
bias = 0. * bias
return functools.partial(cls, lagrangian_varterms_fn)
@classmethod
def get_nonlinearity_activation_constructor(
cls: Callable[..., 'MinLagrangianNonConvexBound'],
index: Index,
act_type: Primitive,
lb_fun: Callable[[Tensor], Tensor],
ub_fun: Callable[[Tensor], Tensor],
*inp: 'MinLagrangianNonConvexBound',
) -> Callable[..., 'MinLagrangianNonConvexBound']:
assert len(inp) == 1
assert act_type in _lagrangian_opt_fns
inp = inp[0]
def lagrangian_varterms_fn(dvar: Tensor, lagrangian_dict: LagrangianDict):
# There is a linear term of dvar over the outputs.
lagrangian_dict[index].append(('Linear', lambda x: (-dvar*x)))
# For the inputs, there is a linear term through the upper bound:
pos_dvar = jnp.maximum(dvar, 0.)
neg_dvar = jnp.maximum(-dvar, 0.)
negdvar_dot_ub = lambda x: (-neg_dvar * ub_fun(x))
lagrangian_dict[inp.index].append(('Linear', negdvar_dot_ub))
# For the inputs, there is a ReLU term through the lower bound
lagrangian_dict[inp.index].append(
(act_type, lambda x: (pos_dvar * lb_fun(x))))
return functools.partial(cls, lagrangian_varterms_fn)
def requires_concretizing(self, consuming_primitive):
return self._concretized_bounds is None
def _optimize_lagrangian_terms(lagrangian_terms: Sequence[LagrangianVarTerm],
lower_bound: Tensor,
upper_bound: Tensor) -> Tensor:
"""Minimize the part of the lagrangian corresponding to a given variable.
Args:
lagrangian_terms: A list of the terms involving that variable.
lower_bound: A tensor with the lower bound on the variable to optimize.
upper_bound: A tensor with the upper bound on the variable to optimize.
Returns:
opt_act: A tensor with the inputs minimizing the lagrangian terms for each
optimization target.
"""
act_term = None
# Get the total linear term
def linear_term(x):
out = 0
for act_type, lag_term_fn in lagrangian_terms:
if act_type == 'Linear':
out += lag_term_fn(x).sum()
return out
# Identify the NonLinear term if there is one
for act_type, lag_term_fn in lagrangian_terms:
if act_type in _lagrangian_opt_fns:
if act_term is not None:
raise ValueError('Variable involved in several activations.')
act_term = act_type, lag_term_fn
elif act_type == 'Linear':
pass
else:
raise ValueError('Unexpected contribution: ' + act_type)
# Perform the minimization
lin_coeffs = jax.grad(linear_term)(lower_bound)
if act_term is None:
# This does not involve a non linearity; this is just a linear term.
return jnp.where(lin_coeffs >= 0, lower_bound, upper_bound)
else:
act_type, lag_term_fn = act_term
return _lagrangian_opt_fns[act_type](
lin_coeffs, lag_term_fn, lower_bound, upper_bound)
def _optimize_softplus_lagrangian(lin_coeffs: Tensor,
nonlin_term: Callable[[Tensor], Tensor],
lower_bound: Tensor,
upper_bound: Tensor) -> Tensor:
"""Compute the input minimizing a sum of a linear term and a softplus.
To minimize a * softplus(x) + b * x
Either cancel gradient is feasible:
a * (1 / (1 + exp(-x))) + b = 0
<=> a + b * (1 + exp(-x)) = 0
<=> - (a + b) / b = exp(-x)
<=> x = ln(- b / (a + b))
If b=0, this is just normal linear minimization.
If b / (a + b) > 0, that means there is no point where the gradient
cancels, which means that the minimum will be obtained at one of the
extremum. We can simply do linear minimization with the gradient.
Otherwise, the minimum is for x = ln(-b / (a+b)), clipped to valid bounds.
Args:
lin_coeffs: b in the previous equation.
nonlin_term: x -> a * softplus(x)
lower_bound: Lower bound on the input we're minimizing over.
upper_bound: Upper bound on the input we're minimizing over.
Returns:
opt_act: A tensor with the inputs minimizing the function specified.
"""
# Get the coefficients on the softplus
dummy_inp = jnp.ones_like(lower_bound)
softplus_coeffs = nonlin_term(dummy_inp) / jax.nn.softplus(dummy_inp)
grad_at_lb = lin_coeffs + softplus_coeffs * jax.nn.sigmoid(lower_bound)
# Check condition where we can disregard the 0-gradient solution
safe_denom = jnp.where(lin_coeffs + softplus_coeffs != 0,
lin_coeffs + softplus_coeffs, 1e-12)
inner_log = -lin_coeffs / safe_denom
safe_inner_log = jnp.where(inner_log > 0,
inner_log, jnp.ones_like(inner_log))
zero_grad_infeasible = jnp.any(
jnp.stack([(lin_coeffs + jnp.zeros_like(softplus_coeffs)) == 0,
lin_coeffs + softplus_coeffs == 0,
inner_log <= 0], axis=0), axis=0)
return jnp.where(zero_grad_infeasible,
jnp.where(grad_at_lb >= 0, lower_bound, upper_bound),
jnp.clip(jnp.log(safe_inner_log),
a_min=lower_bound, a_max=upper_bound))
def _optimize_relu_lagrangian(lin_coeffs: Tensor,
nonlin_term: Callable[[Tensor], Tensor],
lower_bound: Tensor,
upper_bound: Tensor) -> Tensor:
"""Compute the input minimizing a sum of a linear term and a ReLU.
To minimize a * relu(x) + b * x,
We know that the function is piecewise linear. We will stack the three
possible solutions along axis = 0 and then keep the minimum one.
Args:
lin_coeffs: b in the previous equation.
nonlin_term: x -> a * relu(x)
lower_bound: Lower bound on the input we're minimizing over.
upper_bound: Upper bound on the input we're minimizing over.
Returns:
opt_act: A tensor with the inputs minimizing the function specified.
"""
zero_inp = jnp.zeros_like(lower_bound)
possible_inps = jnp.stack([
lower_bound,
jnp.clip(zero_inp, a_min=lower_bound, a_max=upper_bound),
upper_bound], axis=0)
out_val = lin_coeffs * possible_inps + nonlin_term(possible_inps)
choice = out_val.argmin(axis=0)
return jnp.choose(choice, possible_inps, mode='clip')
_lagrangian_opt_fns = {
synthetic_primitives.relu_p: _optimize_relu_lagrangian,
synthetic_primitives.softplus_p: _optimize_softplus_lagrangian,
}
| jax_verify-master | jax_verify/src/nonconvex/duals.py |
# coding=utf-8
# 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.
"""Build the nonconvex reformulation of the convex approximation of the network.
This is accomplished by traversing the JaxPR representation of the computation
and translating the computational graph.
This is based on the paper "An efficient nonconvex reformulation of stagewise
convex optimization problems" and the implementation was inspired by the
tensorflow version at:
/l/d/r/robust_verified/verification/ibp/verification/
nonconvex_optimizable_bounds.py
"""
import abc
import functools
from typing import Callable, Generic, Mapping, MutableMapping, Optional, Sequence, Tuple, Type, TypeVar, Union
from absl import logging
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import activation_relaxation
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import intersection
from jax_verify.src import synthetic_primitives
from jax_verify.src import utils
from jax_verify.src.types import Index, Nest, Primitive, Tensor, TensorFun # pylint: disable=g-multiple-import
NnCvx = TypeVar('NnCvx', bound='NonConvexBound')
# Mapping of a position in the computation to a set of parameters.
# These can be variables, gradients, or coefficients.
ParamSet = MutableMapping[Index, Tensor]
def _sum_fn(fn, *args, **kwargs):
out = fn(*args, **kwargs)
summand = out[0] if isinstance(out, tuple) else out
return summand.sum(), out
def _sum_over_acts(var: Tensor) -> Tensor:
return var.sum(axis=tuple(range(1, var.ndim)))
class NonConvexBound(bound_propagation.Bound, metaclass=abc.ABCMeta):
"""Represent a bound that can be optimized.
This is the object that gets propagated through the network.
The important elements it exposes are the following:
- variables: Specifies what is the shape of the parameters that need to be
provided such that a bound can be computed.
- dual: A function that takes as input variables as specified by `variables`
and a set of linear function over the activations, in the form of a dict
mapping activation index to (batch_dim , nb_opt, *act_dims) tensor, and
that returns the value of the primal objectives when those variables are
used, as well as a dual bound on those linear objectives. Different
options for dual computation are available, each implemented in a separate
sub-class.
- primal_fn: Similar function, but does not compute the dual objective. It
also has an additional `dummy_inps` inputs. When gradients with regards
to the activation needs to be obtained, these can obtained by providing
"0 activations" through this parameters, which would be added to the
network activations. Differentiating with regards to these parameters will
allow to obtain derivatives with regards to activations.
Making use of these elements has already been implemented in the
`BoundOptimizer` classes.
Important bits of machinery shared by all subclasses:
- _eval_fn is a function that takes as inputs tensors as specified by
`variables` and evaluate the activations.
- concretizer is an instance of `Concretizer`, that exposes a `concrete_bound`
method. This is used during the bound propagation when concrete bounds are
required (such as when defining the convex hull relaxation of a ReLU.).
The choice of concretizer impacts of those intermediate concrete bounds are
computed. This can be done by relying on a fallback method such as IBP, or
by optimization.
In addition, the subclass are responsible for encoding some additional
mechanisms required for the computation of the dual they implement.
"""
def __init__(
self,
index: Index,
shape: Tuple[int, ...],
previous_bounds: MutableMapping[Index, 'NonConvexBound'],
eval_fn: Callable[[ParamSet, ParamSet, ParamSet], Tensor],
variables: Mapping[Index, Tuple[int, ...]],
concretized_bounds: Optional[bound_propagation.Bound] = None):
"""Shared computation for the creation of NonConvexBound.
Args:
index: Unique index representing the position of this activation in the
computation graph.
shape: Shape of the activations that this bound represent.
previous_bounds: Dict mapping index of activation to the bound
representing it. We need it to be able to obtain the contributions of
previous layers to the Lagrangian.
eval_fn: Function to evaluate the bound computation problem in the primal
variables: Dict mapping index of activation to the shape of variables
required to optimize them.
concretized_bounds: (Optional) Precomputed bounds for this NonConvexBound.
"""
self.index = index
self._shape = shape
self.previous_bounds = previous_bounds
self.previous_bounds[index] = self
self._eval_fn = eval_fn
self.variables = variables
self._concretized_bounds = concretized_bounds
def primal(var_set: ParamSet,
objectives: ParamSet,
dummy_inps: Optional[ParamSet] = None
) -> Tuple[Tensor, ParamSet]:
"""Evaluate the primal objective of the problem.
dummy_inps are inputs which are always zeros, and that we will add to
every intermediate activations of the network for which we need gradients.
This way, computing the gradients with regards to those "inputs" allows
us to compute gradients with regards to intermediate activations, as
required for the definition of the dual variables.
Args:
var_set: Dictionary mapping the position in network to a tensor
containing the primal variables.
objectives: Dict mapping the position in network to the coefficient of
the linear objective function over the activations.
dummy_inps: Dictionary mapping the position in network to a zero
tensor.
Returns:
primals: All primal objectives.
"""
acts = {}
self.evaluate(var_set, dummy_inps, acts)
primals = self._objective_fn(acts, objectives)
return primals, acts
self.primal_fn = primal
self.primal_sumfn = functools.partial(_sum_fn, primal)
def _objective_fn(self, acts, objectives):
"""Default objective function is a dot product with the activations."""
primal_objs = sum(_sum_over_acts(acts[index] * act_objectives)
for index, act_objectives in objectives.items())
return primal_objs
@property
def shape(self):
return self._shape
@property
def dtype(self):
return jnp.float32
@property
def lower(self) -> Tensor:
if self._concretized_bounds is None:
logging.warning('.lower called on a non-concretized bound.'
'Returning spurious bounds.')
return -float('inf') * jnp.ones(self.shape, self.dtype)
return self._concretized_bounds.lower
@property
def upper(self) -> Tensor:
if self._concretized_bounds is None:
logging.warning('.upper called on a non-concretized bound.'
'Returning spurious bounds.')
return float('inf') * jnp.ones(self.shape, self.dtype)
return self._concretized_bounds.upper
def evaluate(self,
var_set: ParamSet,
dummy_inps: Optional[ParamSet] = None,
acts: Optional[ParamSet] = None) -> Tensor:
if acts is None:
acts = {}
if dummy_inps is None:
dummy_inps = {}
if self.index in acts:
return acts[self.index]
else:
val = self._eval_fn(var_set, dummy_inps, acts)
if self.index in dummy_inps:
val = val + dummy_inps[self.index]
acts[self.index] = val
return val
@abc.abstractmethod
def dual(self, var_set: ParamSet, objectives: ParamSet) -> Tensor:
"""Compute the dual, using dual variables derived from primals in var_set.
Returns both primal and dual, so that this can be used to compute dual gap.
Args:
var_set: Relaxation variables to use to compute the primal activations and
derive the duals from.
objectives: Dict mapping the position in network to the coefficient of
the linear objective function over the activations.
"""
@classmethod
@abc.abstractmethod
def get_initial_bound_constructor(
cls: Type[NnCvx],
index: Index,
lb: Tensor,
ub: Tensor) -> Callable[..., NnCvx]:
"""Class specific initialization for the input bounds of the network."""
raise NotImplementedError('Initial bound constructor not implemented')
@classmethod
@abc.abstractmethod
def get_linear_activation_constructor(
cls: Type[NnCvx],
index: Index,
vlin_fun: Callable[..., Tensor],
in_vals: Tuple[Tensor, ...]) -> Callable[..., NnCvx]:
"""Class specific initialization for the output of a linear function."""
raise NotImplementedError('Linear activation constructor not implemented')
@classmethod
@abc.abstractmethod
def get_nonlinearity_activation_constructor(
cls: Type[NnCvx],
index: Index,
inp: NnCvx,
act_type: Primitive,
lb_fun: Callable[[Tensor], Tensor],
ub_fun: Callable[[Tensor], Tensor]) -> Callable[..., NnCvx]:
"""Class specific initialization for the output of a non-linearity."""
raise NotImplementedError('Nonlinearity activation constructor not'
'implemented')
@abc.abstractmethod
def requires_concretizing(self, primitive) -> bool:
"""Returns whether the bounds need to be concretized.
Args:
primitive: Primitive where this bound is going to be fed into.
None indicates it is an output of the network.
Returns:
requires_concretizing: Indicate whether concretizing is required.
"""
raise NotImplementedError('Specification of when concretization is required'
'is not implemented.')
def _compute_dualvars_nonconvexgrad(self,
var_set: ParamSet,
objectives: ParamSet
) -> Tuple[ParamSet, ParamSet]:
"""Obtain dual vars based on derivatives of the nonconvex reformulation.
Compute the gradients of all the primals objectives, (done by taking their
sum), with regards to the dummy inputs of each activation.
This differentiation is for the function as expressed in the nonconvex
formulation, where each activation is a function of the previous
activations.
Args:
var_set: Interpolation coefficients to derive the activations from.
objectives: Arguments for the objective function.
Returns:
dual_vars: Dual variables corresponding to the derivatives of the primals
wrt to the network activation, in the nonconvex reformulation.
acts: Activations of the network.
"""
grad_fun = jax.grad(self.primal_sumfn, argnums=2, has_aux=True)
dummy_acts = {key: 0*val for key, val in var_set.items()}
dual_vars, (_, acts) = grad_fun(var_set, objectives, dummy_acts)
return dual_vars, acts
def _compute_dualvars_convexgrad(self,
var_set: ParamSet,
objectives: ParamSet
) -> Tuple[ParamSet, ParamSet]:
"""Obtain dual vars based on derivatives of the objective function.
Compute the gradients of all the primal objectives with regards to each
activation.
This differentiation is for the objective function expressed in the convex
sense, where all the activation are considered variables rather than
functions.
Args:
var_set: Interpolation coefficients to derive the activations from.
objectives: Arguments for the objective function.
Returns:
dual_vars: Dual variables corresponding to the derivatives of the primals
wrt to the network activation, in the convex formulation.
acts: Activations of the network.
"""
acts = {}
self.evaluate(var_set, {}, acts)
primal_gradfun_wrt_act = utils.batch_value_and_grad(
self._objective_fn, (0,))
_, dual_vars = primal_gradfun_wrt_act(acts, objectives)
return dual_vars, acts
def concretize(self, concretizer: 'Concretizer', graph, env):
self._concretized_bounds = concretizer.concrete_bound(graph, env, self)
@classmethod
def initial_nonconvex_bound(
cls: Type[NnCvx],
index: Index,
lower_bound: Tensor,
upper_bound: Tensor) -> NnCvx:
shape = lower_bound.shape
variables = {index: lower_bound.shape}
lb = jnp.expand_dims(lower_bound, axis=0)
ub = jnp.expand_dims(upper_bound, axis=0)
previous_bounds = {}
def eval_fn(var_set, *_):
val = lb + (ub - lb) * var_set[index]
return val
bound_ctor = cls.get_initial_bound_constructor(index, lb, ub)
return bound_ctor(
index, shape, previous_bounds, eval_fn, variables,
bound_propagation.IntervalBound(lower_bound, upper_bound))
class ConstrainedNonConvexBound(NonConvexBound, metaclass=abc.ABCMeta):
"""This special case of NonConvexBound supports `imposed_bounds` constraints.
The assumption is that, before any evaluation of the primal or dual, the
`set_imposed_bounds` function is called. As a result, these should be
created through a `_ConstrainedNonConvexTransform`
* `lower` and `upper` return those by default before being concretized.
* Concretizing will result in the concretized bounds being the tightest
between the bounds obtained by concretizing and the imposed ones.
* Imposing bounds will also constrain any existing concretized bounds.
* Evaluating an activation represented by this bound will return the
evaluation projected into the admissible bounds.
"""
def __init__(
self,
index: Index,
shape: Tuple[int, ...],
previous_bounds: MutableMapping[Index, 'ConstrainedNonConvexBound'],
eval_fn: Callable[[ParamSet, ParamSet, ParamSet], Tensor],
variables: Mapping[Index, Tuple[int, ...]],
concretized_bounds: Optional[bound_propagation.Bound] = None):
super().__init__(index, shape, previous_bounds,
eval_fn, variables, concretized_bounds)
self._imposed_bounds = None
def is_constrained(self) -> bool:
return self._imposed_bounds is not None
def imposed_bounds(self) -> bound_propagation.Bound:
if self._imposed_bounds is None:
raise ValueError('No imposed bounds')
return self._imposed_bounds
def set_imposed_bounds(self, imposed_bounds: bound_propagation.Bound):
self._imposed_bounds = imposed_bounds
if self._concretized_bounds is not None:
self._concretized_bounds = intersection.IntersectionBound(
self._concretized_bounds, self._imposed_bounds)
def evaluate(self,
var_set: ParamSet,
dummy_inps: Optional[ParamSet] = None,
acts: Optional[ParamSet] = None) -> Tensor:
"""Activation implied by `var_set`, projected onto the bounds."""
unconstrained_eval = super().evaluate(var_set, dummy_inps, acts)
if not self.is_constrained():
return unconstrained_eval
brd_lower = jnp.expand_dims(self.lower, 0)
brd_upper = jnp.expand_dims(self.upper, 0)
if dummy_inps and (self.index in dummy_inps):
# The dummy inp was added to the unconstrained eval, but we need to make
# sure that it's present even in the constrained version.
dummy_inp = dummy_inps[self.index]
constrained_eval = jnp.clip(unconstrained_eval,
brd_lower + dummy_inp, brd_upper + dummy_inp)
else:
constrained_eval = jnp.clip(unconstrained_eval, brd_lower, brd_upper)
if acts:
acts[self.index] = constrained_eval
return constrained_eval
@property
def lower(self) -> Tensor:
if self._imposed_bounds is not None and self._concretized_bounds is None:
return self._imposed_bounds.lower
return super().lower
@property
def upper(self) -> Tensor:
if self._imposed_bounds is not None and self._concretized_bounds is None:
return self._imposed_bounds.upper
return super().upper
def concretize(self, concretizer: 'Concretizer', graph, env):
super().concretize(concretizer, graph, env)
if self._imposed_bounds is not None:
# Ensure that the concretized bounds respect the imposed bounds.
self._concretized_bound = intersection.IntersectionBound(
self._concretized_bounds, self._imposed_bounds)
class Concretizer(abc.ABC):
"""Abstract class to define the API of concretizer.
The role of Concretizer is to give access to concrete bounds to define
relaxation while propagating NonConvexBound which are solver based.
"""
@abc.abstractmethod
def concrete_bound(
self,
graph: graph_traversal.PropagationGraph,
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
nonconvex_bound: NonConvexBound) -> bound_propagation.Bound:
"""Returns a concretized bound."""
class BaseBoundConcretizer(Concretizer):
"""Concretizer based on performing a parallel propagation with another method.
This should be constructed with an environment resulting from forward
propagation of another bound propagation method.
"""
def concrete_bound(
self,
graph: graph_traversal.PropagationGraph,
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
nonconvex_bound: NonConvexBound) -> bound_propagation.Bound:
return env[graph.jaxpr_node(nonconvex_bound.index)]
def eval_if_nonconvexbound(
inp: graph_traversal.LayerInput[NonConvexBound],
var_set: ParamSet,
dummy_inps: Optional[ParamSet],
activations: Optional[ParamSet]) -> Tensor:
if isinstance(inp, NonConvexBound):
return inp.evaluate(var_set, dummy_inps, activations)
else:
return inp
def _nonconvex_linear_op(
primitive: Primitive,
bound_cls: Type[NnCvx],
index: Index,
*in_vals: graph_traversal.LayerInput[NonConvexBound],
**kwargs) -> NnCvx:
"""Propagation of NonConvex bounds through a linear operation.
Args:
primitive: Primitive that this linear operation implement.
bound_cls: Bound class to use.
index: Unique integer identifying position
*in_vals: Input of the bound propagation in the forward pass
**kwargs: Dict with the parameters of the linear operation
Returns:
out_bounds: nonconvex bounds on the operation's output
"""
in_axes_to_vmap = [0 if isinstance(inp, NonConvexBound) else None
for inp in in_vals]
kwarged_lin_fun = lambda args: primitive.bind(*args, **kwargs)
vlin_fun = jax.vmap(kwarged_lin_fun, [in_axes_to_vmap], 0)
bound_parents = [inp for inp in in_vals if isinstance(inp, NonConvexBound)]
# We first merge the requirements of the inputs
variables = {}
previous_bounds = {}
for parent in bound_parents:
variables.update(parent.variables)
previous_bounds.update(parent.previous_bounds)
# Compute the shape of the output
placeholder_invals = []
for inp in in_vals:
if isinstance(inp, NonConvexBound):
placeholder_invals.append(jax.core.ShapedArray(inp.shape, jnp.float32))
else:
placeholder_invals.append(inp)
output_shape = jax.eval_shape(kwarged_lin_fun, placeholder_invals).shape
def eval_fn(var_set: ParamSet,
dummy_inps: Optional[ParamSet],
activations: Optional[ParamSet]) -> Tensor:
"""Evaluate the value of the activation in the relaxation.
Note: This fills up `activations` by side-effect.
Args:
var_set: Variables for the relaxed problems.
dummy_inps: Variables to add so that we can obtain gradients with regards
to intermediate activations.
activations: Cache for already computed activations.
Returns:
out: Tensor with the value of the activation.
"""
inps = [eval_if_nonconvexbound(inp, var_set, dummy_inps, activations)
for inp in in_vals]
out = vlin_fun(inps)
return out
variables[index] = output_shape
new_bound_ctor = bound_cls.get_linear_activation_constructor(
index, vlin_fun, in_vals)
return new_bound_ctor(index, output_shape, previous_bounds,
eval_fn, variables)
def _nonconvex_div(
bound_cls: Type[NnCvx],
index: Index,
lhs: graph_traversal.LayerInput[NonConvexBound],
rhs: graph_traversal.LayerInput[NonConvexBound],
) -> NnCvx:
"""Propagation of NonConvex bounds bounds through Elementwise division.
We don't support the propagation of bounds through the denominator.
Args:
bound_cls: Bound class to use.
index: Unique integer identifying position in the computational graph.
lhs: Numerator of the division.
rhs: Denominator of the division.
Returns:
out_bounds: Bound on the output of the division.
"""
if isinstance(rhs, bound_propagation.Bound):
raise ValueError('Bound propagation through the denominator unsupported.')
return _nonconvex_linear_op(lax.mul_p, bound_cls, index, lhs, 1. / rhs)
def _activation_convex_relaxation(
bound_cls: Type[NnCvx],
index: Index,
inputs: Sequence[NnCvx],
act_type: Primitive,
lb_fun: Callable[..., Tensor],
ub_fun: Callable[..., Tensor],
precomputed_bound: Optional[bound_propagation.Bound]) -> NnCvx:
"""Builds the NonConvexBound object corresponding to after non-linearities.
Args:
bound_cls: Bound class to use.
index: Index of the computation.
inputs: Inputs of the non-linearity.
act_type: Type of activation
lb_fun: Function to evaluate the upper bound of the activation for an input.
ub_fun: Function to evaluate the upper bound of the activation for an input.
precomputed_bound: Bound on the NonConvexBound to generate.
Returns:
out_bounds: NonConvexBound for the output of the non-linearity
"""
bound_parents = [inp for inp in inputs if isinstance(inp, NonConvexBound)]
# We first merge the requirements of the inputs
variables = {}
previous_bounds = {}
for parent in bound_parents:
variables.update(parent.variables)
previous_bounds.update(parent.previous_bounds)
inputs_lb = [jnp.expand_dims(inp.lower, 0) for inp in inputs]
output_shape_with_target = jax.eval_shape(lb_fun, *inputs_lb).shape
output_shape = output_shape_with_target[1:]
variables[index] = output_shape
def eval_fn(var_set, dummy_inps, activations):
"""Evaluate the value of the primal."""
inp_eval = [inp.evaluate(var_set, dummy_inps, activations) for inp in
inputs]
lb_val = lb_fun(*inp_eval)
ub_val = ub_fun(*inp_eval)
theta = var_set[index]
out_val = lb_val + theta * (ub_val - lb_val)
return out_val
shape = output_shape
new_bound_ctor = bound_cls.get_nonlinearity_activation_constructor(
index, act_type, lb_fun, ub_fun, *inputs)
return new_bound_ctor(index, shape, previous_bounds,
eval_fn, variables, precomputed_bound)
def _nonconvex_activation(
act_type: Primitive,
relaxation: Callable[..., Tuple[TensorFun, TensorFun]],
bound_cls: Type[NnCvx],
index: Index,
*inps: Union[NnCvx, Tensor],
eltwise_increasing: bool = False,
**params) -> NnCvx:
"""Propagation of NonConvexBounds through a non-linear operation.
Args:
act_type: Activation type, e.g. 'Softplus' or 'ReLU'.
relaxation: Function accepting (*inps, **params) and returning
convex lower bound and concave upper bound functions.
bound_cls: Bound class to use.
index: Node index.
*inps: Nonconvex bounds on the inputs to the operation.
eltwise_increasing: Whether the operation is known to be element-wise
monotonic increasing, in which case we can pre-compute its bounds.
**params: Parameters of the operation.
Returns:
out_bounds: Nonconvex bounds on the operation's output.
"""
lb_fun, ub_fun = relaxation(*inps, **params)
if eltwise_increasing:
# The function is assumed to be monotonically increasing, so we
# can readily pre-compute interval bounds on its output.
# `lb_fun` will be the original function whenever this is reached.
precomputed_bound = bound_propagation.IntervalBound(
lb_fun(*[inp.lower for inp in inps]), # pytype: disable=attribute-error # jax-ndarray
lb_fun(*[inp.upper for inp in inps])) # pytype: disable=attribute-error # jax-ndarray
else:
precomputed_bound = None
lb_fun = jax.vmap(lb_fun, in_axes=0, out_axes=0)
ub_fun = jax.vmap(ub_fun, in_axes=0, out_axes=0)
return _activation_convex_relaxation(
bound_cls, index,
[inp for inp in inps if isinstance(inp, NonConvexBound)],
act_type, lb_fun, ub_fun, precomputed_bound)
def _make_activation_primitive_transform(
primitive: Primitive,
activation: activation_relaxation.ActivationRelaxation,
) -> Callable[..., NonConvexBound]:
return functools.partial(
_nonconvex_activation,
primitive, activation.relaxation_fn,
eltwise_increasing=activation.eltwise_increasing)
_linear_op_primitives: Sequence[Primitive] = [
*bound_propagation.AFFINE_PRIMITIVES,
*bound_propagation.RESHAPE_PRIMITIVES,
]
_nonconvex_primitive_transform: Mapping[
Primitive, Callable[..., NonConvexBound],
] = {
**{primitive: functools.partial(_nonconvex_linear_op, primitive)
for primitive in _linear_op_primitives},
lax.div_p: _nonconvex_div,
**{primitive: _make_activation_primitive_transform(primitive, act)
for primitive, act in activation_relaxation.relaxation_fns.items()},
}
class _NonConvexTransform(
Generic[NnCvx], graph_traversal.GraphTransform[NnCvx]):
"""Graph Transform to build a NonConvex Relaxation, which can be optimized."""
def __init__(
self,
bound_cls: Type[NnCvx],
concretizer: Concretizer,
graph: graph_traversal.PropagationGraph,
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
):
self._bound_cls = bound_cls
self._concretizer = concretizer
self._graph = graph
self._env = env
def input_transform(
self,
context: graph_traversal.TransformContext[NnCvx],
input_bound: graph_traversal.InputBound,
) -> NnCvx:
return self._bound_cls.initial_nonconvex_bound(
context.index, input_bound.lower, input_bound.upper)
def primitive_transform(
self,
context: graph_traversal.TransformContext[NnCvx],
primitive: Primitive,
*args: graph_traversal.LayerInput[NnCvx],
**params,
) -> NnCvx:
for arg in args:
if (isinstance(arg, NonConvexBound) and
arg.requires_concretizing(primitive)):
arg.concretize(self._concretizer, self._graph, self._env)
params = synthetic_primitives.filter_jaxverify_kwargs(params)
new_bound = _nonconvex_primitive_transform[primitive](
self._bound_cls, context.index, *args, **params)
return new_bound
class _ConstrainedNonConvexTransform(
_NonConvexTransform[ConstrainedNonConvexBound]):
"""Graph Transform performing parallel boundprop and imposing bounds."""
def __init__(
self,
bound_cls: Type[ConstrainedNonConvexBound],
imposed_boundprop: bound_propagation.BoundTransform,
concretizer: Concretizer,
graph: graph_traversal.PropagationGraph,
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
):
super().__init__(bound_cls, concretizer, graph, env)
self._imposed_boundprop = imposed_boundprop
def input_transform(
self,
context: graph_traversal.TransformContext[ConstrainedNonConvexBound],
input_bound: graph_traversal.InputBound,
) -> ConstrainedNonConvexBound:
bound = super().input_transform(context, input_bound)
bound.set_imposed_bounds(self._imposed_boundprop.input_transform(
context, input_bound))
return bound
def primitive_transform(
self,
context: graph_traversal.TransformContext[ConstrainedNonConvexBound],
primitive: Primitive,
*args: graph_traversal.LayerInput[ConstrainedNonConvexBound],
**params,
) -> ConstrainedNonConvexBound:
bound = super().primitive_transform(context, primitive, *args, **params)
imposed_bound_args = [
arg.imposed_bounds()
if isinstance(arg, bound_propagation.Bound) else arg
for arg in args]
bound.set_imposed_bounds(self._imposed_boundprop.equation_transform(
context, primitive, *imposed_bound_args, **params)[0])
return bound
class NonConvexAlgorithm(
Generic[NnCvx], bound_propagation.PropagationAlgorithm[NnCvx]):
"""Forward algorithm with an optional initial pass for 'base' bounds."""
def __init__(
self,
nonconvex_transform_ctor: Callable[..., bound_propagation.BoundTransform],
concretizer: Concretizer,
base_boundprop: Optional[bound_propagation.BoundTransform] = None):
super().__init__()
self._nonconvex_transform_ctor = nonconvex_transform_ctor
self._concretizer = concretizer
self._base_boundprop = base_boundprop
def propagate(
self,
graph: graph_traversal.PropagationGraph,
bounds: Nest[graph_traversal.GraphInput],
) -> Tuple[
Nest[bound_propagation.Bound],
Mapping[jax.core.Var, bound_propagation.LayerInput],
]:
if self._base_boundprop is not None:
# Propagate the 'base' bounds in advance, for subsequent use by
# the concretiser.
_, base_env = bound_propagation.ForwardPropagationAlgorithm(
self._base_boundprop).propagate(graph, bounds)
else:
# No 'base' boundprop method specified.
# This is fine as long as the concretiser does not rely on base bounds.
base_env = None
nonconvex_transform = self._nonconvex_transform_ctor(
self._concretizer, graph, base_env)
output_bounds, env = bound_propagation.ForwardPropagationAlgorithm(
nonconvex_transform).propagate(graph, bounds)
# Always concretize the returned bounds so that `lower` and `upper` are
# accessible
for out_bound in jax.tree_util.tree_leaves(output_bounds):
if out_bound.requires_concretizing(None):
out_bound.concretize(self._concretizer, graph, base_env)
return output_bounds, env
def nonconvex_algorithm(
bound_cls: Type[NnCvx],
concretizer: Concretizer,
*,
base_boundprop: Optional[bound_propagation.BoundTransform] = None,
imposed_boundprop: Optional[bound_propagation.BoundTransform] = None,
) -> bound_propagation.PropagationAlgorithm[NnCvx]:
"""Builds a bound propagation algorithm for the non-convex formulation.
Args:
bound_cls: Bound class to use. This determines what dual formulation will
be computed.
concretizer: Concretizer to use to obtain intermediate bounds.
base_boundprop: Underlying bound propagation method for obtaining concrete
bounds.
imposed_boundprop: Additional bounds to apply as constraints, e.g. from
a branching decision.
Returns:
Propagation algorithm.
"""
if imposed_boundprop is None:
bound_transform_ctor = functools.partial(_NonConvexTransform, bound_cls)
else:
bound_transform_ctor = functools.partial(
_ConstrainedNonConvexTransform, bound_cls, imposed_boundprop)
return NonConvexAlgorithm(bound_transform_ctor, concretizer, base_boundprop)
| jax_verify-master | jax_verify/src/nonconvex/nonconvex.py |
# coding=utf-8
# 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 Backward Crown / Fastlin.
"""
import abc
import functools
from typing import Mapping, Optional, Sequence, Tuple
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import bound_utils
from jax_verify.src import concretization
from jax_verify.src import graph_traversal
from jax_verify.src import ibp
from jax_verify.src import optimizers
from jax_verify.src import synthetic_primitives
from jax_verify.src import utils
from jax_verify.src.linear import linear_relaxations
from jax_verify.src.types import Index, Nest, Primitive, SpecFn, Tensor # pylint: disable=g-multiple-import
import optax
def _sum_linear_backward_bounds(
linbound_seq: Sequence[linear_relaxations.LinearExpression],
) -> linear_relaxations.LinearExpression:
if len(linbound_seq) == 1:
return linbound_seq[0]
else:
return linbound_seq[0] + _sum_linear_backward_bounds(linbound_seq[1:])
def _backpropagate_linear_functions(
linfun: linear_relaxations.LinFun,
outval: linear_relaxations.LinearExpression,
*invals: bound_propagation.LayerInput,
)-> Sequence[Optional[linear_relaxations.LinearExpression]]:
"""Propagate a linear function backward through the linfun function.
Args:
linfun: Linear function to propagate through.
outval: Coefficients of a linear functions over the output of linfun.
*invals: Tensor or Bounds that are inputs to linfun
Returns:
new_in_args: Coefficients of a linear functions over the input of linfun,
representing the same linear function as was represented by outval.
"""
# Figure out the bias of the linear transformation, which will need to be
# added to the offset.
zero_in_args = [jnp.zeros(arg.shape) for arg in invals
if isinstance(arg, bound_propagation.Bound)]
nb_bound_inputs = len(zero_in_args)
linfun_onlybound_input = utils.bind_nonbound_args(linfun, *invals)
linfun_bias, vjp_fun = jax.vjp(linfun_onlybound_input, *zero_in_args)
# Let's evaluate what offset this would correspond to, based on the what the
# outval is.
broad_bias = jnp.expand_dims(linfun_bias, 0)
dims_to_reduce = tuple(range(1, broad_bias.ndim))
# We're splitting the offset between all the bounds that we propagate
# backward. This contains both the offset that was already present on the
# bounds being propagated backward and the ones coming from this level
# of the relaxation.
total_offset = (outval.offset + jnp.sum(outval.lin_coeffs * broad_bias,
dims_to_reduce))
shared_offset = total_offset / nb_bound_inputs
# Let's vmap the target dimension, so as to backpropagate for all targets.
vjp_fun = jax.vmap(vjp_fun, in_axes=0, out_axes=0)
in_args_lin_coeffs = vjp_fun(outval.lin_coeffs)
new_in_args = []
bound_arg_pos = 0
for arg in invals:
if isinstance(arg, bound_propagation.Bound):
new_in_args.append(linear_relaxations.LinearExpression(
in_args_lin_coeffs[bound_arg_pos], shared_offset))
bound_arg_pos += 1
else:
new_in_args.append(None)
return new_in_args
def _handle_linear_relaxation(
lb_fun: linear_relaxations.LinFun,
ub_fun: linear_relaxations.LinFun,
outval: linear_relaxations.LinearExpression,
*invals: bound_propagation.LayerInput,
) -> Sequence[Optional[linear_relaxations.LinearExpression]]:
"""Propagate a linear function backward through a linear relaxation.
This is employed when we have a non-linear primitive, once we have obtained
its linear lower bounding and linear upper bounding function.
We backpropagate through this linear relaxation of a non-linear primitive.
Args:
lb_fun: Linear lower bound of the primitive to propagate backwards through.
ub_fun: Linear upper bound of the primitive to progagate backwards through.
outval: Coefficients of a linear function over the output of the primitive
relaxed by lb_fun and ub_fun.
*invals: Tensor or Bounds that are inputs to the primitive relaxed by lb_fun
and ub_fun.
Returns:
new_in_args: Coefficients of a linear function over the input of the
primitive, representing the same linear function as was represented by
outval.
"""
# We're going to split the linear function over the output into two parts,
# depending on the sign of the coefficients.
# The one with positive coefficients will be backpropagated through the
# lower bound, the one with the negative coefficients will be propagated
# through the upper bound.
# The offset can go on either as it is not actually backpropagated, we just
# need to make sure that it is not double-counted.
pos_outval = linear_relaxations.LinearExpression(
jnp.maximum(outval.lin_coeffs, 0.), outval.offset)
neg_outval = linear_relaxations.LinearExpression(
jnp.minimum(outval.lin_coeffs, 0.), jnp.zeros_like(outval.offset))
through_pos_inlinfuns = _backpropagate_linear_functions(
lb_fun, pos_outval, *invals)
through_neg_inlinfuns = _backpropagate_linear_functions(
ub_fun, neg_outval, *invals)
new_in_args = []
for pos_contrib, neg_contrib in zip(through_pos_inlinfuns,
through_neg_inlinfuns):
# The None should be in the same position, whether through the lower or
# upper bound.
assert (pos_contrib is None) == (neg_contrib is None)
if pos_contrib is None:
new_in_args.append(None)
else:
new_in_args.append(pos_contrib + neg_contrib)
return new_in_args
class LinearBoundBackwardConcretizingTransform(
concretization.BackwardConcretizingTransform[
linear_relaxations.LinearExpression],
metaclass=abc.ABCMeta):
"""Transformation to propagate linear bounds backwards and concretize them.
This transform propagates instances of the same `LinearExpression` type as
used in `forward_linear_bounds`, but note that it interprets them differently:
- `lin_coeffs` has shape [nb_outputs, *input_shape]
- `offset` has shape [nb_outputs]
"""
def __init__(
self, concretization_fn: linear_relaxations.ConcretizationFn =
linear_relaxations.concretize_linear_expression):
self._concretization_fn = concretization_fn
def aggregate(
self,
eqn_outvals: Sequence[linear_relaxations.LinearExpression],
) -> linear_relaxations.LinearExpression:
return _sum_linear_backward_bounds(eqn_outvals)
def concrete_bound_chunk(
self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
node_ref: jax.core.Var,
obj: Tensor,
) -> Tensor:
initial_linear_expression = identity(obj)
flat_inputs, _ = jax.tree_util.tree_flatten(inputs)
bound_inputs = [inp for inp in flat_inputs
if isinstance(inp, bound_propagation.Bound)]
input_nodes_indices = [(i,) for i in range(len(bound_inputs))]
inputs_linfuns, _ = graph.backward_propagation(
self, env, {node_ref: initial_linear_expression}, input_nodes_indices)
flat_bound = jnp.zeros(())
for input_linfun, inp_bound in zip(inputs_linfuns, bound_inputs):
if input_linfun is not None:
# Only concretize when the input_linfun is not None. It is possible,
# especially when computing intermediate bounds, that not all of the
# inputs will have an impact on each bound to compute.
# Example:
# a -> Linear -> Relu -> sum -> out
# b -------------------/
# When computing the bound on the input to the ReLU, the backward
# bound on b will be None, and can be safely ignored.
inp_contrib = self._concretization_fn(input_linfun, inp_bound)
flat_bound = flat_bound + inp_contrib
return flat_bound
class LinearBoundBackwardTransform(LinearBoundBackwardConcretizingTransform):
"""Transformation to propagate linear bounds backwards and concretize them."""
def __init__(
self,
relaxer: linear_relaxations.LinearBoundsRelaxer,
primitive_needs_concrete_bounds: Tuple[Primitive, ...],
concretization_fn: linear_relaxations.ConcretizationFn =
linear_relaxations.concretize_linear_expression
):
super().__init__(concretization_fn)
self.relaxer = relaxer
self._primitive_needs_concrete_bounds = primitive_needs_concrete_bounds
def concretize_args(self, primitive: Primitive) -> bool:
return primitive in self._primitive_needs_concrete_bounds
def primitive_backtransform(
self,
context: graph_traversal.TransformContext[
linear_relaxations.LinearExpression],
primitive: Primitive,
eqn_outval: linear_relaxations.LinearExpression,
*args: bound_propagation.LayerInput,
**params,
) -> Sequence[Sequence[Optional[linear_relaxations.LinearExpression]]]:
if (primitive in bound_propagation.AFFINE_PRIMITIVES
or primitive in bound_propagation.RESHAPE_PRIMITIVES):
lin_fun = functools.partial(primitive.bind, **params)
in_linfun = _backpropagate_linear_functions(lin_fun, eqn_outval, *args)
else:
# This is not an affine primitive. We need to go through a relaxation.
# Obtain the linear bounds.
index = context.index
lb_linrelaxfun, ub_linrelaxfun = self.relaxer.linearize_primitive(
index, primitive, *args, **params)
in_linfun = _handle_linear_relaxation(lb_linrelaxfun, ub_linrelaxfun,
eqn_outval, *args)
return list(zip(in_linfun))
class _RelaxationScanner(
graph_traversal.BackwardGraphTransform[bound_propagation.LayerInput]):
"""Identifies the node relaxations relevant to the graph."""
def __init__(
self,
relaxer: linear_relaxations.ParameterizedLinearBoundsRelaxer):
self._relaxer = relaxer
self._node_relaxations = {}
@property
def node_relaxations(self) -> Mapping[
Index, linear_relaxations.ParameterizedNodeRelaxation]:
return self._node_relaxations
def aggregate(
self,
eqn_outvals: Sequence[bound_propagation.LayerInput],
) -> bound_propagation.LayerInput:
# In the case of fan-out, the same forward value should have been
# encountered on every possible backward path.
assert all(eqn_outval is eqn_outvals[0] for eqn_outval in eqn_outvals)
return eqn_outvals[0]
def primitive_backtransform(
self,
context: graph_traversal.TransformContext[bound_propagation.LayerInput],
primitive: Primitive,
eqn_outval: bound_propagation.LayerInput,
*args: bound_propagation.LayerInput,
**params) -> Sequence[Sequence[Optional[bound_propagation.LayerInput]]]:
if not (primitive in bound_propagation.AFFINE_PRIMITIVES
or primitive in bound_propagation.RESHAPE_PRIMITIVES):
# This is not an affine primitive. We need to go through a relaxation.
# Obtain the linear bounds.
input_info = [(arg.shape, isinstance(arg, bound_propagation.Bound))
for arg in args]
self._node_relaxations[context.index] = (
self._relaxer.parameterized_linearizer(
context.index, primitive, *input_info, **params))
# We're using this back-transform to traverse the nodes, rather than to
# compute anything. Arbitrarily return the forward bounds associated with
# each node.
return [[arg if isinstance(arg, bound_propagation.Bound) else None]
for arg in args]
class OptimizingLinearBoundBackwardTransform(
concretization.BackwardConcretizingTransform[
linear_relaxations.LinearExpression]):
"""Transformation to propagate linear bounds backwards and concretize them.
This transform propagates instances of the same `LinearExpression` type as
used in `forward_linear_bounds`, but note that it interprets them differently:
- `lin_coeffs` has shape [nb_outputs, *input_shape]
- `offset` has shape [nb_outputs]
"""
def __init__(
self,
relaxer: linear_relaxations.ParameterizedLinearBoundsRelaxer,
primitive_needs_concrete_bounds: Tuple[Primitive, ...],
optimizer: optimizers.Optimizer,
concretization_fn: linear_relaxations.ConcretizationFn =
linear_relaxations.concretize_linear_expression,
):
"""Constructs a per-node concretizer that performs an inner optimisation.
Args:
relaxer: Specifies the parameterised linear relaxation to use for each
primitive operation.
primitive_needs_concrete_bounds: Which primitive operations need to be
concretised.
optimizer: Optimizer used to minimise the upper bounds (and the negative
lower bounds) with respect to the linear relaxation parameters.
concretization_fn: Function to concretize the linear bounds at the end.
"""
self._relaxer = relaxer
self._primitive_needs_concrete_bounds = primitive_needs_concrete_bounds
self._optimizer = optimizer
self._concretization_fn = concretization_fn
def concretize_args(self, primitive: Primitive) -> bool:
return primitive in self._primitive_needs_concrete_bounds
def aggregate(
self,
eqn_outvals: Sequence[linear_relaxations.LinearExpression],
) -> linear_relaxations.LinearExpression:
raise NotImplementedError()
def primitive_backtransform(
self,
context: graph_traversal.TransformContext[
linear_relaxations.LinearExpression],
primitive: Primitive,
eqn_outval: linear_relaxations.LinearExpression,
*args: bound_propagation.LayerInput,
**params,
) -> Sequence[Sequence[Optional[linear_relaxations.LinearExpression]]]:
raise NotImplementedError()
def concrete_bound_chunk(
self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
node_ref: jax.core.Var,
obj: Tensor,
) -> Tensor:
# Analyse the relevant parts of the graph.
flat_inputs, _ = jax.tree_util.tree_flatten(inputs)
bound_inputs = [
inp for inp in flat_inputs
if isinstance(inp, graph_traversal.InputBound)]
input_nodes_indices = [(i,) for i in range(len(bound_inputs))]
scanner = _RelaxationScanner(self._relaxer)
graph.backward_propagation(
scanner, env, {node_ref: graph_traversal.read_env(env, node_ref)},
input_nodes_indices)
# Allow lookup of any node's input bounds, for parameter initialisation.
graph_inspector = bound_utils.GraphInspector()
bound_propagation.ForwardPropagationAlgorithm(
graph_inspector).propagate(graph, inputs)
def input_bounds(index: Index) -> Sequence[bound_propagation.LayerInput]:
graph_node = graph_inspector.nodes[index]
return [env[graph.jaxpr_node(arg.index)]
if isinstance(arg, bound_utils.GraphNode) else arg
for arg in graph_node.args]
# Define optimisation for a single neuron's bound. (We'll vmap afterwards.)
# This ensures that each neuron uses independent relaxation parameters.
def optimized_concrete_bound(one_obj):
def concrete_bound(relax_params):
return self._bind(
scanner.node_relaxations, relax_params).concrete_bound_chunk(
graph, inputs, env, node_ref, jnp.expand_dims(one_obj, 0))
# Define function to optimise: summary tightness of guaranteed bounds.
def objective(relax_params):
# TODO: At the moment we are optimizing the sum of the bounds
# but some of the optimizers (Fista + Linesearch) support optimizing
# independently each objectives, which would work better.
lb_min = concrete_bound(relax_params)
return jnp.sum(-lb_min)
# Define function to project on feasible parameters.
project_params = functools.partial(self._project_params, scanner)
opt_fun = self._optimizer.optimize_fn(objective, project_params)
initial_params = self._initial_params(scanner, input_bounds)
best_relax_params = opt_fun(initial_params)
# Evaluate the relaxation at these parameters.
return concrete_bound(jax.lax.stop_gradient(best_relax_params))
return jax.vmap(optimized_concrete_bound)(obj)
def _initial_params(self, scanner, input_bounds):
return {index: node_relaxation.initial_params(*input_bounds(index))
for index, node_relaxation in scanner.node_relaxations.items()}
def _project_params(self, scanner, unc_params):
return {
index: node_relaxation.project_params(unc_params[index])
for index, node_relaxation in scanner.node_relaxations.items()}
def _bind(
self,
node_relaxations: Mapping[
Index, linear_relaxations.ParameterizedNodeRelaxation],
relax_params: Mapping[Index, Tensor],
) -> LinearBoundBackwardConcretizingTransform:
return LinearBoundBackwardTransform(
linear_relaxations.BindRelaxerParams(node_relaxations, relax_params),
self._primitive_needs_concrete_bounds,
self._concretization_fn)
def identity(obj: Tensor) -> linear_relaxations.LinearExpression:
"""Returns identity linear expression for lower bound of objective."""
initial_lin_coeffs = obj
initial_offsets = jnp.zeros(obj.shape[:1])
return linear_relaxations.LinearExpression(initial_lin_coeffs,
initial_offsets)
CONCRETIZE_ARGS_PRIMITIVE = (
synthetic_primitives.leaky_relu_p,
synthetic_primitives.parametric_leaky_relu_p,
synthetic_primitives.relu_p,
synthetic_primitives.clip_p,
synthetic_primitives.sigmoid_p,
synthetic_primitives.posbilinear_p,
synthetic_primitives.posreciprocal_p,
synthetic_primitives.fused_relu_p,
lax.abs_p,
lax.exp_p,
)
backward_crown_transform = LinearBoundBackwardTransform(
linear_relaxations.crown_rvt_relaxer, CONCRETIZE_ARGS_PRIMITIVE)
backward_fastlin_transform = LinearBoundBackwardTransform(
linear_relaxations.fastlin_rvt_relaxer, CONCRETIZE_ARGS_PRIMITIVE)
backward_crown_concretizer = concretization.ChunkedBackwardConcretizer(
backward_crown_transform)
backward_fastlin_concretizer = concretization.ChunkedBackwardConcretizer(
backward_fastlin_transform)
def crownibp_bound_propagation(
function: SpecFn,
*bounds: Nest[graph_traversal.GraphInput],
) -> Nest[bound_propagation.LayerInput]:
"""Performs Crown-IBP as described in https://arxiv.org/abs/1906.06316.
We first perform IBP to obtain intermediate bounds and then propagate linear
bounds backwards.
Args:
function: Function performing computation to obtain bounds for. Takes as
only argument the network inputs.
*bounds: jax_verify.IntervalBounds, bounds on the inputs of the function.
Returns:
output_bounds: Bounds on the outputs of the function obtained by Crown-IBP
"""
crown_ibp_algorithm = concretization.BackwardAlgorithmForwardConcretization(
ibp.bound_transform, backward_crown_concretizer)
output_bounds, _ = bound_propagation.bound_propagation(
crown_ibp_algorithm, function, *bounds)
return output_bounds
def backward_crown_bound_propagation(
function: SpecFn,
*bounds: Nest[graph_traversal.GraphInput],
) -> Nest[bound_propagation.LayerInput]:
"""Performs CROWN as described in https://arxiv.org/abs/1811.00866.
Args:
function: Function performing computation to obtain bounds for. Takes as
only argument the network inputs.
*bounds: jax_verify.IntervalBound, bounds on the inputs of the function.
Returns:
output_bound: Bounds on the output of the function obtained by FastLin
"""
backward_crown_algorithm = concretization.BackwardConcretizingAlgorithm(
backward_crown_concretizer)
output_bound, _ = bound_propagation.bound_propagation(
backward_crown_algorithm, function, *bounds)
return output_bound
def backward_rvt_bound_propagation(
function: SpecFn,
*bounds: Nest[graph_traversal.GraphInput],
) -> Nest[bound_propagation.LayerInput]:
"""Performs CROWN as described in https://arxiv.org/abs/1811.00866.
Args:
function: Function performing computation to obtain bounds for. Takes as
only argument the network inputs.
*bounds: jax_verify.IntervalBound, bounds on the inputs of the function.
Returns:
output_bound: Bounds on the output of the function obtained by FastLin
"""
backward_crown_algorithm = concretization.BackwardConcretizingAlgorithm(
backward_crown_concretizer)
expand_softmax_simplifier_chain = synthetic_primitives.simplifier_composition(
synthetic_primitives.activation_simplifier,
synthetic_primitives.hoist_constant_computations,
synthetic_primitives.expand_softmax_simplifier,
synthetic_primitives.group_linear_sequence,
synthetic_primitives.group_posbilinear)
output_bound, _ = bound_propagation.bound_propagation(
backward_crown_algorithm, function, *bounds,
graph_simplifier=expand_softmax_simplifier_chain)
return output_bound
def backward_fastlin_bound_propagation(
function: SpecFn,
*bounds: Nest[graph_traversal.GraphInput],
) -> Nest[bound_propagation.LayerInput]:
"""Performs FastLin as described in https://arxiv.org/abs/1804.09699.
Args:
function: Function performing computation to obtain bounds for. Takes as
only argument the network inputs.
*bounds: jax_verify.IntervalBound, bounds on the inputs of the function.
Returns:
output_bound: Bounds on the output of the function obtained by FastLin
"""
backward_fastlin_algorithm = concretization.BackwardConcretizingAlgorithm(
backward_fastlin_concretizer)
output_bound, _ = bound_propagation.bound_propagation(
backward_fastlin_algorithm, function, *bounds)
return output_bound
class JointOptimizationConcretizationAlgorithm(
bound_propagation.PropagationAlgorithm[bound_propagation.Bound]
):
"""Algorithm to jointly optimize all the bounds in the network."""
def __init__(self,
relaxer: linear_relaxations.ParameterizedLinearBoundsRelaxer,
opt: optax.GradientTransformation,
num_opt_steps: int,
max_chunk_size: int = 0):
self._relaxer = relaxer
self._opt = opt
self._num_opt_steps = num_opt_steps
self._max_chunk_size = max_chunk_size
def propagate(self,
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput]):
# Inspect the graph to figure out what are the nodes needing concretization.
graph_inspector = bound_utils.GraphInspector()
inspector_algorithm = bound_propagation.ForwardPropagationAlgorithm(
graph_inspector)
gn_outvals, env = inspector_algorithm.propagate(graph, inputs)
flat_inputs, _ = jax.tree_util.tree_flatten(inputs)
flat_bounds = [inp for inp in flat_inputs
if isinstance(inp, bound_propagation.Bound)]
input_nodes_indices = [(i,) for i in range(len(flat_bounds))]
# For every node that requires relaxations, we will use a RelaxationScanner
# to collect the node that it requires.
relaxations = {}
def collect_relaxations(graph_node):
if graph_node.index not in relaxations:
index_to_concretize = graph_node.index
jaxpr_node = graph.jaxpr_node(index_to_concretize)
scanner = _RelaxationScanner(self._relaxer)
graph.backward_propagation(
scanner, env, {jaxpr_node: graph_node},
input_nodes_indices)
relaxations[index_to_concretize] = scanner.node_relaxations
for node in graph_inspector.nodes.values():
node_primitive = node.primitive
if node_primitive and node_primitive in CONCRETIZE_ARGS_PRIMITIVE:
for node_arg in node.args:
collect_relaxations(node_arg)
# Iterate over the outputs, making notes of their index so that we can use
# them to specify the objective function, and collecting the relaxations we
# need to define to use them.
objective_nodes = []
for gn in gn_outvals:
collect_relaxations(gn)
jaxpr_node = graph.jaxpr_node(gn.index)
objective_nodes.append(jaxpr_node)
env_with_final_bounds = self.jointly_optimize_relaxations(
relaxations, graph, inputs, env, objective_nodes)
outvals = [env_with_final_bounds[jaxpr_node_opted]
for jaxpr_node_opted in objective_nodes]
return outvals, env_with_final_bounds
def jointly_optimize_relaxations(
self,
relaxations: Mapping[Index, Mapping[
Index, linear_relaxations.ParameterizedNodeRelaxation]],
graph: graph_traversal.PropagationGraph,
inputs: Nest[graph_traversal.GraphInput],
env: Mapping[jax.core.Var, bound_propagation.LayerInput],
objective_nodes: Sequence[jax.core.Var]):
"""Perform the joint optimization of all the bounds.
For a network that is (index in parentheses):
Inp -> Linear(1) -> Relu(2) -> Linear(3) -> Relu(4) -> Linear(5)
We would have relaxations be a dict of the form:
{
(1,): {}, # When we concretize 1, we don't need any relaxations
(3,): {(2,): relaxation} # Concretizing 3, we need to relax 2
(5,): {(2,): relaxation, (4,): relaxation}
}
Args:
relaxations: Dict mapping each index to a relaxation dict mapping the
preceding primitives to their parameterized relaxer.
graph: Graph to perform the backward propagation on to obtain bounds.
inputs: Bounds on the inputs
env: Environment containing shape information
objective_nodes: List of jaxpr_nodes indicating which bound to use as
objective functions.
Returns:
env_with_bounds: Environment with concretized bounds.
"""
# Initialize the parameters for the optimization
default_init = lambda relax: relax.initial_params(*((None,) * relax.arity))
initial_params = jax.tree_map(default_init, relaxations)
initial_state = self._opt.init(initial_params)
param_and_state = initial_params, initial_state
# Define a function that compute all bounds that we have parameterized.
# This will concretize each intermediate bounds using the parameters
# corresponding to that level of the relaxation.
def all_bounds(params: Mapping[Index, Mapping[Index, Nest[Tensor]]]):
specific_env = dict(env)
for inter_index, node_relaxations in relaxations.items():
relax_params = params[inter_index]
jaxpr_node = graph.jaxpr_node(inter_index)
backward_transform = LinearBoundBackwardTransform(
linear_relaxations.BindRelaxerParams(node_relaxations,
relax_params),
CONCRETIZE_ARGS_PRIMITIVE)
chunked_backward_transform = concretization.ChunkedBackwardConcretizer(
backward_transform, self._max_chunk_size)
concrete_bound = chunked_backward_transform.concrete_bound(
graph, inputs, specific_env, jaxpr_node)
specific_env[jaxpr_node] = concrete_bound
return specific_env
# Define the objective function of the optimization. This will be the
# range of the final bound, as indicated by the objective_nodes argument.
def objective_fun(params: Mapping[Index, Mapping[Index, Nest[Tensor]]]):
env_with_bounds = all_bounds(params)
obj = 0
for jaxpr_node_to_opt in objective_nodes:
bound_to_opt = env_with_bounds[jaxpr_node_to_opt]
obj = obj + jnp.sum(bound_to_opt.upper - bound_to_opt.lower)
return obj
grad_fn = jax.grad(objective_fun)
# Define the optimization step, and call it as a fori-loop
def update_fun(_, param_and_state):
params, opt_state = param_and_state
updates, next_opt_state = self._opt.update(grad_fn(params), opt_state)
next_params = optax.apply_updates(params, updates)
next_params = jax.tree_util.tree_map(
lambda relax, param: relax.project_params(param),
relaxations, next_params)
return next_params, next_opt_state
relax_params, _ = utils.fori_loop_no_backprop(
0, self._num_opt_steps, update_fun, param_and_state)
# Compute the bounds corresponding to the final set of optimized
# parameters, and extract the final bounds that we were optimizing.
env_with_final_bounds = all_bounds(relax_params)
return env_with_final_bounds
| jax_verify-master | jax_verify/src/linear/backward_crown.py |
# coding=utf-8
# 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.
"""Utils for Linear Bounds.
"""
import abc
import functools
from typing import Callable, Generic, Mapping, Optional, Sequence, Tuple, TypeVar
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import activation_relaxation
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import mccormick
from jax_verify.src import synthetic_primitives
from jax_verify.src import utils
from jax_verify.src.types import ArgsKwargsCallable, Index, Nest, Primitive, Tensor, TensorFun # pylint: disable=g-multiple-import
import numpy as np
LinFun = TensorFun
# Representation of a linear function used in a relaxation.
# Can be a linear jax function (LinFun), or can be a LinearExpression.
LinearRelax = TypeVar('LinearRelax')
class LinearExpression:
"""Describes a set of linear expressions."""
def __init__(self, lin_coeffs, offset):
"""Creates a LinearExpression object.
Args:
lin_coeffs: nb_coeffs x (array shape)
offset: (array shape)
"""
self.lin_coeffs = lin_coeffs
self.offset = offset
@property
def shape(self):
return self.offset.shape
@property
def dtype(self):
return self.offset.dtype
def __add__(self, other):
if isinstance(other, LinearExpression):
return LinearExpression(self.lin_coeffs + other.lin_coeffs,
self.offset + other.offset)
else:
return LinearExpression(self.lin_coeffs, self.offset + other)
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
if isinstance(other, LinearExpression):
return LinearExpression(self.lin_coeffs - other.lin_coeffs,
self.offset - other.offset)
else:
return LinearExpression(self.lin_coeffs, self.offset - other)
def __rsub__(self, other):
if isinstance(other, LinearExpression):
return LinearExpression(other.lin_coeffs - self.lin_coeffs,
other.offset - self.offset)
else:
return LinearExpression(-self.lin_coeffs, other - self.offset,)
def __neg__(self):
return LinearExpression(-self.lin_coeffs, -self.offset)
def __truediv__(self, other):
return LinearExpression(self.lin_coeffs / other, self.offset / other)
def transpose(self, in_shape: Tuple[int]) -> 'LinearExpression':
"""Transposes the LinearExpression.
Convert the linear expression that are in the format of:
[flattenned_in_shape, *out_shape]
to the alternative format, which is
[flattenned_out_shape, *unflattened_in_shape].
Args:
in_shape: Shape of the inputs to the linear functions. The product of the
dimension needs to match the leading dimension of the lincoeffs.
Returns:
Expression in the transposed format.
"""
out_shape = self.offset.shape
flattened_out_shape = np.prod(out_shape)
coeffs_all_flattened = jnp.reshape(self.lin_coeffs,
(-1, flattened_out_shape))
transposed_flattened_coeffs = jnp.transpose(coeffs_all_flattened, (1, 0))
new_lin_coeffs = jnp.reshape(transposed_flattened_coeffs,
(flattened_out_shape, *in_shape))
new_offset = jnp.reshape(self.offset, (flattened_out_shape,))
return LinearExpression(new_lin_coeffs, new_offset)
ConcretizationFn = Callable[[LinearExpression, graph_traversal.GraphInput],
Tensor]
def concretize_linear_expression(
linexp: LinearExpression,
input_bound: graph_traversal.InputBound) -> Tensor:
"""Compute the lower bound value of a linear expression.
Args:
linexp: Coefficients of linear functions. The leading batch dimension
corresponds to different output neurons that need to be concretized. Shape
is [nb_linfun, *input_bound.shape]
input_bound: Bound on the activations of that layer. Its shape should match
the coefficients of the linear functions to concretize. Shape is
[*input_bound.shape]
Returns:
bound: A concretized bound on the value of the functions represented by
linexp. Shape is [nb_linfun]
"""
return concretize_linear_function_interval_bounds(linexp, input_bound)
def concretize_linear_function_interval_bounds(
linexp: LinearExpression,
input_bound: graph_traversal.InputBound) -> Tensor:
"""Compute the lower bound of a linear function under interval constraints."""
act_lower = jnp.expand_dims(input_bound.lower, 0)
act_upper = jnp.expand_dims(input_bound.upper, 0)
dims_to_reduce = tuple(range(1, act_lower.ndim))
return linexp.offset + jnp.sum(
jnp.minimum(linexp.lin_coeffs, 0.) * act_upper +
jnp.maximum(linexp.lin_coeffs, 0.) * act_lower, dims_to_reduce)
class LinearBoundsRelaxer(metaclass=abc.ABCMeta):
@abc.abstractmethod
def linearize_primitive(
self,
index: Index,
primitive: Primitive,
*inps: bound_propagation.LayerInput,
**params) -> Tuple[LinFun, LinFun]:
"""Obtain the parameters of the linearized relaxation of a given primitive.
The relaxation holds when the inputs are within range of the bounds
described by `inps`.
Args:
index: Index of the node in the bound propagation.
primitive: Primitive to relax.
*inps: Bounds on the inputs of the primitive or Tensors.
**params: Parameters of the primitive.
Returns:
lb_linfun: Function evaluating the linear lower bound relaxing that
primitive.
ub_linfun: Function evaluating the linear upper bound relaxing that
primitive.
"""
class OpwiseLinearBoundsRelaxer(LinearBoundsRelaxer):
"""Relaxer mapping each primitive to a predefined linear relaxation.
This relaxation admits no additional parameters.
"""
def __init__(
self,
primitive_mapper: Mapping[
Primitive,
ArgsKwargsCallable[
bound_propagation.LayerInput, Tuple[LinFun, LinFun]]],
default_relaxer: Optional[LinearBoundsRelaxer] = None):
self._primitive_mapper = primitive_mapper
self._default_relaxer = default_relaxer
def linearize_primitive(
self,
index: Index,
primitive: Primitive,
*inps: bound_propagation.LayerInput,
**params) -> Tuple[LinFun, LinFun]:
if primitive in self._primitive_mapper:
params = synthetic_primitives.filter_jaxverify_kwargs(params)
return self._primitive_mapper[primitive](*inps, **params)
elif self._default_relaxer:
return self._default_relaxer.linearize_primitive(
index, primitive, *inps, **params)
else:
raise ValueError(f'Unsupported primitive to relax: {primitive}.')
class ParameterizedNodeRelaxation(Generic[LinearRelax], metaclass=abc.ABCMeta):
"""Computes upper/lower linearisations using optimisable parameters."""
@property
@abc.abstractmethod
def arity(self) -> int:
"""Returns the number of input arguments expected by this relaxation."""
@abc.abstractmethod
def linearize(
self,
relax_params: Nest[Tensor],
*inps: bound_propagation.LayerInput,
) -> Tuple[LinearRelax, LinearRelax]:
"""Returns linearised relaxation for given optimisable parameters."""
@abc.abstractmethod
def initial_params(
self,
*inps: Optional[bound_propagation.LayerInput],
) -> Nest[Tensor]:
"""Returns initial values of optimisable parameters."""
@abc.abstractmethod
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
"""Projects optimisable parameters to their valid domain."""
class ParameterizedLinearBoundsRelaxer(metaclass=abc.ABCMeta):
"""Relaxer mapping each primitive to an optimisable linear relaxation."""
@abc.abstractmethod
def parameterized_linearizer(
self,
index: Index,
primitive: Primitive,
*input_info: Tuple[Sequence[int], bool],
**params) -> ParameterizedNodeRelaxation[LinFun]:
"""Obtain a parameterised family of linear relaxations of a given primitive.
Args:
index: Index of the node in the bound propagation.
primitive: Primitive to relax.
*input_info: Tuples of (shape, is_bound) of the inputs of the primitive.
**params: Parameters of the primitive.
Returns:
Object producing linearised lower/upper bounds given relaxation
parameters.
"""
class OpwiseParameterizedLinearBoundsRelaxer(ParameterizedLinearBoundsRelaxer):
"""Relaxer mapping each primitive to a parameterized linear relaxation."""
def __init__(
self,
primitive_mapper: Mapping[
Primitive,
ArgsKwargsCallable[Sequence[int],
ParameterizedNodeRelaxation[LinFun]]],
default_param_relaxer: Optional[ParameterizedLinearBoundsRelaxer] = None):
self._primitive_mapper = primitive_mapper
self._default_parameterized_relaxer = default_param_relaxer
def parameterized_linearizer(
self,
index: Index,
primitive: Primitive,
*input_info: Tuple[Sequence[int], bool],
**params) -> ParameterizedNodeRelaxation[LinFun]:
if primitive in self._primitive_mapper:
params = synthetic_primitives.filter_jaxverify_kwargs(params)
return self._primitive_mapper[primitive](*input_info, **params)
elif self._default_parameterized_relaxer:
return self._default_parameterized_relaxer.parameterized_linearizer(
index, primitive, *input_info, **params)
else:
raise ValueError(f'Unsupported primitive to relax: {primitive}.')
class ParameterizedLinearBoundsGlobalRelaxer(metaclass=abc.ABCMeta):
"""Relaxer mapping each primitive to an optimisable linear propagator."""
@abc.abstractmethod
def parameterized_global_linearizer(
self,
index: Index,
primitive: Primitive,
network_input_spec: bound_propagation.Bound,
*input_shapes: Sequence[int],
**params) -> ParameterizedNodeRelaxation[LinearExpression]:
"""Obtain a parameterised family of linear bound propagator.
Compared to the non-global version, this requires the additional
network_input_spec parameters.
Args:
index: Index of the node in the bound propagation.
primitive: Primitive to relax.
network_input_spec: Bound over the input of the network.
*input_shapes: Shapes of the inputs of the primitive.
**params: Parameters of the primitive.
Returns:
Object producing linearised lower/upper bounds given relaxation
parameters.
"""
class OpwiseParameterizedLinearBoundsGlobalRelaxer(
ParameterizedLinearBoundsGlobalRelaxer):
"""Relaxer mapping each primitive to a parameterized linear relaxation."""
def __init__(
self,
primitive_mapper: Mapping[
Primitive,
Callable[..., ParameterizedNodeRelaxation[LinearExpression]]],
default_param_relaxer: Optional[ParameterizedLinearBoundsGlobalRelaxer
] = None):
self._primitive_mapper = primitive_mapper
self._default_parameterized_relaxer = default_param_relaxer
def parameterized_global_linearizer(
self,
index: Index,
primitive: Primitive,
network_input_spec: bound_propagation.Bound,
*input_shapes: Sequence[int],
**params) -> ParameterizedNodeRelaxation[LinearExpression]:
if primitive in self._primitive_mapper:
params = synthetic_primitives.filter_jaxverify_kwargs(params)
return self._primitive_mapper[primitive](network_input_spec,
*input_shapes, **params)
elif self._default_parameterized_relaxer:
return (
self._default_parameterized_relaxer.parameterized_global_linearizer(
index, primitive, network_input_spec, *input_shapes, **params))
else:
raise ValueError(f'Unsupported primitive to relax: {primitive}.')
class BindRelaxerParams(LinearBoundsRelaxer):
"""Relaxer formed from binding parameters into a parameterised relaxer."""
def __init__(
self,
node_relaxations: Mapping[Index, ParameterizedNodeRelaxation[LinFun]],
relax_params: Mapping[Index, Tensor],
):
self._node_relaxations = node_relaxations
self._relax_params = relax_params
def linearize_primitive(
self,
index: Index,
primitive: Primitive,
*inps: bound_propagation.LayerInput,
**params) -> Tuple[LinFun, LinFun]:
return self._node_relaxations[index].linearize(
self._relax_params[index], *inps)
class ParameterizedLinFun(Generic[LinearRelax], metaclass=abc.ABCMeta):
"""Linearisation of lower OR upper bound using optimisable parameters."""
@property
@abc.abstractmethod
def arity(self) -> int:
"""Returns the number of input arguments expected by the linear function."""
@abc.abstractmethod
def linearize(
self,
relax_params: Nest[Tensor],
*inps: bound_propagation.LayerInput,
) -> LinearRelax:
"""Returns linearised half-bound for given optimisable parameters."""
@abc.abstractmethod
def initial_params(
self,
*inps: Optional[bound_propagation.LayerInput],
) -> Nest[Tensor]:
"""Returns initial values of optimisable parameters."""
@abc.abstractmethod
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
"""Projects optimisable parameters to their valid domain."""
class LowerUpperRelaxation(ParameterizedNodeRelaxation[LinearRelax]):
"""Adapts two parameterised half-bounds into a parameterised relaxation."""
def __init__(self, lower: ParameterizedLinFun[LinearRelax],
upper: ParameterizedLinFun[LinearRelax]):
super().__init__()
self._lower = lower
self._upper = upper
@property
def arity(self) -> int:
return self._lower.arity
def linearize(
self,
relax_params: Nest[Tensor],
*inps: bound_propagation.LayerInput,
) -> Tuple[LinearRelax, LinearRelax]:
lower_relax_params, upper_relax_params = relax_params
return (
self._lower.linearize(lower_relax_params, *inps),
self._upper.linearize(upper_relax_params, *inps))
def initial_params(
self,
*inps: Optional[bound_propagation.LayerInput],
) -> Nest[Tensor]:
return (
self._lower.initial_params(*inps),
self._upper.initial_params(*inps))
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
lower_relax_params, upper_relax_params = relax_params
return (
self._lower.project_params(lower_relax_params),
self._upper.project_params(upper_relax_params))
class _NoParamRelaxation(ParameterizedNodeRelaxation[LinearRelax]):
"""Adapts a simple relaxer function into a zero-parameter relaxer function."""
def __init__(
self,
relaxer: ArgsKwargsCallable[
bound_propagation.LayerInput, Tuple[LinFun, LinFun]],
*input_info: Tuple[Sequence[int], bool],
**params):
self._relaxer = relaxer
self._input_info = input_info
self._params = params
@property
def arity(self):
return len(self._input_info)
def linearize(
self,
relax_params: Nest[Tensor],
*inps: bound_propagation.LayerInput,
) -> Tuple[LinearRelax, LinearRelax]:
return self._relaxer(*inps, **self._params)
def initial_params(
self,
*inps: Optional[bound_propagation.LayerInput],
) -> Nest[Tensor]:
return ()
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
return relax_params
no_params = lambda relaxer: functools.partial(_NoParamRelaxation, relaxer)
def linearized(fn: TensorFun, *primals: Tensor) -> LinFun:
"""Returns linear function that is tangent to `fn` at given primal point."""
val, deriv = jax.linearize(fn, *primals)
return lambda *xs: val + deriv(*[x - p for x, p in zip(xs, primals)])
class SupportingHyperplane(ParameterizedLinFun[LinFun]):
"""Linearisation of primitive, parameterised by primal point."""
def __init__(
self,
fn: TensorFun,
*input_info: Tuple[Sequence[int], bool]):
super().__init__()
self._fn = fn
self._input_info = input_info
@property
def arity(self) -> int:
return len(self._input_info)
def linearize(
self,
relax_params: Nest[Tensor],
*inps: bound_propagation.LayerInput,
) -> LinFun:
primals = [
alpha * inp.upper + (1.-alpha) * inp.lower
if isinstance(inp, bound_propagation.Bound) else inp
for inp, alpha in zip(inps, relax_params)]
return linearized(self._fn, *primals)
def initial_params(
self,
*inps: Optional[bound_propagation.LayerInput],
) -> Nest[Tensor]:
# If an input is [known to be] a fixed tensor, don't allocate a
# relaxation parameter for it.
return [ # pytype: disable=bad-return-type # jax-ndarray
.5 * jnp.ones(shape=inp_shape)
if inp is None or isinstance(inp, bound_propagation.Bound) else None
for inp, (inp_shape, _) in zip(inps, self._input_info)]
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
return jax.tree_map(lambda x: jnp.clip(x, 0., 1.), relax_params)
def eltwise_linfun_from_coeff(slope: Tensor, offset: Tensor) -> LinFun:
return lambda x: slope * x + offset
class ElementwiseChord(ParameterizedLinFun[LinFun]):
"""Chord between input bounds of an element-wise primitive."""
arity = 1
def __init__(
self,
fn: TensorFun,
input_info: Tuple[Sequence[int], bool]):
super().__init__()
self._fn = fn
self._input_info = input_info
def linearize(
self,
relax_params: Nest[Tensor],
inp: bound_propagation.LayerInput,
) -> LinFun:
inp_lower, inp_upper = inp.lower, inp.upper
outp_lower, outp_upper = self._fn(inp_lower), self._fn(inp_upper)
has_interval = inp_upper != inp_lower
denom = jnp.where(
has_interval, inp_upper - inp_lower,
jnp.ones_like(inp_lower))
slope = jnp.where(
has_interval, (outp_upper - outp_lower) / denom,
jnp.zeros_like(inp_lower))
offset = jnp.where(
has_interval, (outp_lower * inp_upper - outp_upper * inp_lower) / denom,
outp_lower)
return eltwise_linfun_from_coeff(slope, offset)
def initial_params(
self,
*inps: Optional[bound_propagation.LayerInput],
) -> Nest[Tensor]:
return ()
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
return relax_params
def elementwise_convex_fn_relaxer(
primitive: Primitive,
input_info: Tuple[Sequence[int], bool],
**params) -> ParameterizedNodeRelaxation[LinFun]:
fn = functools.partial(primitive.bind, **params)
lower = SupportingHyperplane(fn, input_info)
upper = ElementwiseChord(fn, input_info)
return LowerUpperRelaxation(lower, upper)
def elementwise_concave_fn_relaxer(
primitive: Primitive,
input_info: Tuple[Sequence[int], bool],
**params) -> ParameterizedNodeRelaxation[LinFun]:
fn = functools.partial(primitive.bind, **params)
lower = ElementwiseChord(fn, input_info)
upper = SupportingHyperplane(fn, input_info)
return LowerUpperRelaxation(lower, upper)
class _SmoothConvexRelaxation(LowerUpperRelaxation):
"""Linear relaxation from supporting hyperplanes of a convex relaxation."""
def __init__(
self,
convex_relaxer: activation_relaxation.RelaxationFn,
*input_info: Tuple[Sequence[int], bool],
**params):
# Create a skeleton `ParameterizedLinFun` for initialisation and projection
# relaxation parameters. This doesn't need the lower/upper bound functions.
skeleton = SupportingHyperplane((lambda *_: None), *input_info)
super().__init__(skeleton, skeleton)
self._convex_relaxer = convex_relaxer
self._input_info = input_info
self._params = params
def linearize(
self,
relax_params: Nest[Tensor],
*inps: bound_propagation.LayerInput,
) -> Tuple[LinFun, LinFun]:
# First obtain convex lower and concave upper bounds.
# Do so at this late stage because they depend on the current input bounds.
lb_fun, ub_fun = self._convex_relaxer(*inps, **self._params)
lower = SupportingHyperplane(lb_fun, *self._input_info)
upper = SupportingHyperplane(ub_fun, *self._input_info)
lower_relax_params, upper_relax_params = relax_params
return (
lower.linearize(lower_relax_params, *inps),
upper.linearize(upper_relax_params, *inps))
def linear_from_smooth_convex(
convex_relaxer: activation_relaxation.RelaxationFn,
) -> ArgsKwargsCallable[Sequence[int], ParameterizedNodeRelaxation]:
return functools.partial(_SmoothConvexRelaxation, convex_relaxer)
def midpoint_relaxer(
primitive: Primitive,
*inputs: bound_propagation.LayerInput,
convex: bool = False,
**params) -> Tuple[LinFun, LinFun]:
"""Obtains relaxation by linearising convex relaxation about the midpoint.
In the case of a ReLU, this relaxes the ReLU with the adaptive choice of
lower bounds as described for CROWN-ada in https://arxiv.org/abs/1811.00866.
Args:
primitive: Primitive to relax.
*inputs: All inputs to the primitive, bounds or Tensor.
convex: Whether the primitive is known to be convex.
**params: Parameters of the primitive.
Returns:
lb_linfun, ub_linfun: Linear lower and upper bound functions.
"""
activation = activation_relaxation.relaxation_fns[primitive]
lb_fun, ub_fun = activation.relaxation_fn(*inputs, **params)
mid_points = [
0.5 * (x.lower + x.upper)
if isinstance(x, bound_propagation.Bound) else x for x in inputs]
lb_lin_fun = linearized(lb_fun, *mid_points)
ub_lin_fun = ub_fun if convex else linearized(ub_fun, *mid_points)
return lb_lin_fun, ub_lin_fun
def _fastlin_relu_relaxer(
inp: bound_propagation.Bound) -> Tuple[LinFun, LinFun]:
"""Obtain the parameters of a linear ReLU relaxation as in FastLin.
This relaxes the ReLU with the parallel bounds of slope (ub) / (ub - lb)
Args:
inp: Input to the ReLU.
Returns:
lb_linfun, ub_linfun: Linear functions bounding the ReLU
"""
inp_lower, inp_upper = inp.lower, inp.upper
relu_on = (inp_lower >= 0.)
relu_amb = jnp.logical_and(inp_lower < 0., inp_upper >= 0.)
slope = relu_on.astype(jnp.float32)
slope += jnp.where(
relu_amb,
inp_upper / utils.safe_pos(inp_upper - inp_lower),
jnp.zeros_like(inp_lower))
ub_offset = jnp.where(
relu_amb,
-slope * inp_lower,
jnp.zeros_like(inp_lower))
lb_offset = jnp.zeros_like(inp_lower)
return (eltwise_linfun_from_coeff(slope, lb_offset),
eltwise_linfun_from_coeff(slope, ub_offset))
def _rvt_exp_relaxer(inp: bound_propagation.Bound) -> Tuple[LinFun, LinFun]:
"""Obtain the parameters of a linear exp relaxation as in RVT.
Lower bound is obtained based on tangent, due to convexity.
Choice of point where the tangent is computed is taken from
https://arxiv.org/pdf/2002.06622.pdf
Chord connecting two endpoints provides upper bound
for exp(x) due to convexity.
Args:
inp: Input to the exp.
Returns:
lb_linfun, ub_linfun: Linear functions bounding the Exponential
"""
lower, upper = inp.lower, inp.upper
thresh = 12.0
min_input = -30.
forced_zeros = upper < min_input
unsafe_to_relax = (upper - lower)**2 < utils.EPSILON
unsafe = jnp.logical_or(forced_zeros, unsafe_to_relax)
def stable_exp(x):
"""If x is greater than thresh, use first order Taylor's expansion."""
return jnp.where(
jnp.greater(x, thresh),
jnp.exp(thresh)*(1 + x - thresh),
jnp.exp(x))
point = jnp.minimum((lower+upper)/2, lower + 0.99)
lb_slope = stable_exp(point)
lb_offset = lb_slope * (1 - point)
# If the relaxation is over too narrow a domain, use the lower bound
# constant as linear lower bounding function.
lb_slope = jnp.where(unsafe, jnp.zeros_like(lower), lb_slope)
lb_offset = jnp.where(unsafe, stable_exp(lower), lb_offset)
ub_slope = (stable_exp(upper)-stable_exp(lower))/(upper - lower)
ub_offset = stable_exp(lower) - ub_slope*lower
# If the relaxation is over too narrow a domain, or if even the upper bound
# is extremely small, we replace the upper bound by a bound with slope of 0.
ub_slope = jnp.where(unsafe, jnp.zeros_like(lower), ub_slope)
ub_offset = jnp.where(unsafe, stable_exp(upper), ub_offset)
lb_fun = eltwise_linfun_from_coeff(lb_slope, lb_offset)
ub_fun = eltwise_linfun_from_coeff(ub_slope, ub_offset)
return lb_fun, ub_fun
def _rvt_posbilinear_relaxer(
x: bound_propagation.Bound,
y: bound_propagation.Bound,
**params) -> Tuple[LinFun, LinFun]:
"""Obtains the parameters of a linear relaxation of a bilinear function.
Rather than using all 4 of the McCormick inequalities,
https://arxiv.org/pdf/2002.06622.pdf use only two:
For x in [x_l, x_u] and y in [y_l, y_u], the bound imposed are:
x·y >= x·y_l + x_l·y - x_l·y_l
x·y <= x·y_u + x_l·y - x_l·y_u
Args:
x: First input to the positive bilinear primitive.
y: Second input to the positive bilinear primitive
**params:
Returns:
lb_linfun, ub_linfun
"""
lb_fun, _, ub_fun, _ = (
mccormick.posbilinear_mccormick_relaxations(
functools.partial(synthetic_primitives.posbilinear_p.bind, **params),
x.lower, x.upper, y.lower, y.upper))
# These functions are linear by construction.
return lb_fun, ub_fun
def _maybe_interp_funs(
funs: Sequence[TensorFun],
interp_params: Nest[Tensor],
*args: Tensor,
) -> Tensor:
"""Interpolates between `funs` according to the given interpolation params."""
vals = [fun(*args) for fun in funs]
return utils.maybe_interp(vals, interp_params)
class ParameterizedPiecewiseLinearSubgradient(
ParameterizedNodeRelaxation[LinFun]):
"""Relaxation of a piecewise-linear function.
This implementation currently assumes exactly two pieces.
"""
def __init__(
self,
primitive: Primitive,
piecewise_linear_relaxation_fn: (
activation_relaxation.PiecewiseLinearRelaxationFn),
*input_info: Tuple[Sequence[int], bool],
soft_init: bool = True,
**params):
super().__init__()
self._primitive = primitive
self._piecewise_linear_relaxation_fn = piecewise_linear_relaxation_fn
self._input_info = input_info
self._soft_init = soft_init
self._params = params
@property
def arity(self):
return len(self._input_info)
def linearize(
self,
relax_params: Nest[Tensor],
*inputs: bound_propagation.LayerInput,
) -> Tuple[LinFun, LinFun]:
lb_funs, ub_funs = self._piecewise_linear_relaxation_fn(*inputs,
**self._params)
lb_relax_params, ub_relax_params = relax_params
return (
functools.partial(_maybe_interp_funs, lb_funs, lb_relax_params),
functools.partial(_maybe_interp_funs, ub_funs, ub_relax_params))
def initial_params(
self,
*inps: Optional[bound_propagation.LayerInput],
) -> Nest[Tensor]:
if len(inps) == 1 and self._soft_init:
soft_init_inp, = inps
else:
soft_init_inp = None
if soft_init_inp is not None:
# When interpolating between linear bound pieces (xb_fun0, xb_fun1),
# initialise close to xb_fun1 if input interval has more positive mass
# than negative, and close to xb_fun0 otherwise.
# This assumes that xb_fun0 is the effective piece for lower inputs
# and xb_fun1 is the effective piece for upper inputs.
# This is the case for ReLU for example, where (lb_fun0, lb_fun1)
# is (x:->0, x:->x). This amounts to a softened version of CROWN.
params = jnp.clip(
soft_init_inp.upper
/ utils.safe_pos(soft_init_inp.upper - soft_init_inp.lower),
0., 1.)
else:
# Include an interpolation parameter for each output.
output_shape = jax.eval_shape(
self._primitive.bind,
*[jnp.zeros(shape) for shape, _ in self._input_info],
**self._params).shape
params = .5 * jnp.ones(shape=output_shape, dtype=jnp.float32)
# Determine the number of linear pieces of the lower and upper bounds.
lb_funs, ub_funs = self._piecewise_linear_relaxation_fn(
*[
bound_propagation.IntervalBound(jnp.zeros(shape), jnp.zeros(shape))
if is_bound else jnp.zeros(shape)
for shape, is_bound in self._input_info
], **self._params)
return (() if len(lb_funs) <= 1 else params,
() if len(ub_funs) <= 1 else params)
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
return jax.tree_map(lambda x: jnp.clip(x, 0., 1.), relax_params)
_crown_mapper: Mapping[
Primitive,
ArgsKwargsCallable[bound_propagation.LayerInput, Tuple[LinFun, LinFun]],
] = {
**{prim: functools.partial(midpoint_relaxer, prim, convex=activation.convex)
for prim, activation in activation_relaxation.relaxation_fns.items()},
lax.exp_p: _rvt_exp_relaxer,
synthetic_primitives.posbilinear_p: _rvt_posbilinear_relaxer,
}
crown_rvt_relaxer = OpwiseLinearBoundsRelaxer(_crown_mapper)
_fastlin_mapper: Mapping[
Primitive,
ArgsKwargsCallable[bound_propagation.LayerInput, Tuple[LinFun, LinFun]],
] = {
**{prim: functools.partial(midpoint_relaxer, prim, convex=activation.convex)
for prim, activation in activation_relaxation.relaxation_fns.items()},
synthetic_primitives.relu_p: _fastlin_relu_relaxer,
lax.exp_p: _rvt_exp_relaxer,
synthetic_primitives.posbilinear_p: _rvt_posbilinear_relaxer,
}
fastlin_rvt_relaxer = OpwiseLinearBoundsRelaxer(_fastlin_mapper)
def _make_parameterized_relaxer(
primitive: Primitive,
activation: activation_relaxation.ActivationRelaxation,
) -> ArgsKwargsCallable[Sequence[int], ParameterizedNodeRelaxation]:
"""Makes a linear relaxation based on the given convex relatation."""
if activation.piecewise_linear_relaxation_fn:
return functools.partial(
ParameterizedPiecewiseLinearSubgradient,
primitive,
activation.piecewise_linear_relaxation_fn,
soft_init=activation.pos_neg_linear)
elif activation.convex:
return functools.partial(elementwise_convex_fn_relaxer, primitive)
else:
return linear_from_smooth_convex(activation.relaxation_fn)
_parameterized_mapper: Mapping[
Primitive,
ArgsKwargsCallable[Sequence[int], ParameterizedNodeRelaxation],
] = {
primitive: _make_parameterized_relaxer(primitive, activation)
for primitive, activation in activation_relaxation.relaxation_fns.items()}
parameterized_relaxer = OpwiseParameterizedLinearBoundsRelaxer(
_parameterized_mapper)
| jax_verify-master | jax_verify/src/linear/linear_relaxations.py |
# coding=utf-8
# 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 Beta-Crown.
Branching decisions are given by a Tuple of fixed tensor.
LayIdx is an integer tensor with size (max_splits, MAX_JAXPR_DEPTH) indicating
which layer to split on. MAX_JAXPR_DEPTH corresponds to a maximum nesting of
indexes that we will specify.
All other tensors are 1D with length max_splits.
NeurIdx is a 1D integer tensor indicating the neuron in that layer.
BranchVal is a 1D floating point tensor indicating where the cut is.
IsUpperBranch is a boolean tensor indicating if the inequality is
neur > branch_val (True)
neur < branch_val (False)
"""
from typing import Mapping, Optional, Sequence, Tuple
from jax import numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import concretization
from jax_verify.src import graph_traversal
from jax_verify.src import optimizers
from jax_verify.src.branching import branch_selection
from jax_verify.src.linear import backward_crown
from jax_verify.src.linear import linear_relaxations
from jax_verify.src.types import Index, Nest, Primitive, SpecFn, Tensor # pylint: disable=g-multiple-import
import optax
def _update_lin_with_lagrangian(eqn_lincoeffs: Tensor,
eqn_offset: Tensor,
active_branch_mask: Tensor,
lagrangian_variables: Tensor,
neur_idxs: Tensor,
branch_val: Tensor,
is_upper: Tensor) -> Tuple[Tensor, Tensor]:
"""Include the contribution of the lagrangian to the linear bounds.
Args:
eqn_lincoeffs: (nb_targets, *act_shape)[float ]coefficients of the linear
function bounding the output as a function of this layer's activation.
eqn_offset: (nb_targets,)[float] constant term of the linear function
bounding the output.
active_branch_mask: (nb_splits,)[bool] Boolean array indicating which
branching constraints are active at this level.
lagrangian_variables: (nb_splits,)[float] Value of the lagrangian multiplier
associated with each branching constraint.
neur_idxs: (nb_splits,)[int] Indication of what neuron is branched on. The
integers represent the location in the flattened activation array.
branch_val: (nb_splits,)[float] Cut-off point of the split constraint.
is_upper: (nb_splits,)[bool] Whether the constraint enforce the activation
to be above branch_val or below.
Returns:
lagrangianed_lincoeffs: Coefficients of the linear function, including
the lagrangian contribution.
lagrangianed_offset: Constant term of the linear function, including the
lagrangian contribution.
"""
# masked_lagrangian is (nb_splits,)
masked_lagrangian = active_branch_mask * lagrangian_variables
signed_masked_lagrangian = jnp.where(is_upper, -masked_lagrangian,
masked_lagrangian)
# We obtain here a scalar term, this is the contribution to the constant
# term (not a function of the input) of the linear equation by the
# lagrangian.
# We sum over the splits (because we take into consideration all the
# lagrangians of that layer, and we have masked the irrelevant ones).
lagrangian_constant_term = (-signed_masked_lagrangian * branch_val).sum()
lagrangianed_offset = (eqn_offset +
jnp.expand_dims(lagrangian_constant_term, 0))
# We now compute the new linear function to be lower-bounded.
# We want to add the lagrangian contribution to the function, for each of
# the target.
# We start by converting the array into the flat array
flat_lincoeffs = jnp.reshape(eqn_lincoeffs, (eqn_lincoeffs.shape[0], -1))
# We now gather the lin coefficients to update.
to_update = flat_lincoeffs.at[:, neur_idxs]
# and add the lagrangian contribution to them.
flat_lagrangianed_lincoeffs = to_update.add(signed_masked_lagrangian,
mode='drop')
lagrangianed_lincoeffs = jnp.reshape(flat_lagrangianed_lincoeffs,
eqn_lincoeffs.shape)
return lagrangianed_lincoeffs, lagrangianed_offset
class ConstrainedLinearBoundBackwardTransform(
backward_crown.LinearBoundBackwardConcretizingTransform):
"""Backward transformation adding the linear contributions from branching.
Those contributions come from the defined branching decisions and the
lagrangian variables associated with them, which should have been bound.
"""
def __init__(
self,
base_backward_transform: (
backward_crown.LinearBoundBackwardConcretizingTransform),
branching_decisions: branch_selection.JittableBranchingDecisions,
lagrangian_variables: Tensor,
concretization_fn: linear_relaxations.ConcretizationFn = (
linear_relaxations.concretize_linear_expression),
):
super().__init__(concretization_fn)
self._base_backward_transform = base_backward_transform
self._branching_decisions = branching_decisions
self._lagrangian_variables = lagrangian_variables
def concretize_args(self, primitive: Primitive) -> bool:
return self._base_backward_transform.concretize_args(primitive)
def primitive_backtransform(
self,
context: graph_traversal.TransformContext[
linear_relaxations.LinearExpression],
primitive: Primitive,
eqn_outval: linear_relaxations.LinearExpression,
*args: bound_propagation.LayerInput,
**params,
) -> Sequence[Sequence[Optional[linear_relaxations.LinearExpression]]]:
lay_idxs, neur_idxs, branch_val, is_upper = self._branching_decisions
index = context.index
max_jaxpr_depth = lay_idxs.shape[1]
index_tensor = jnp.array(index + (0,) * (max_jaxpr_depth - len(index)))
branching_in_this_layer = (lay_idxs == index_tensor).all(axis=1)
active_branch_mask = branching_in_this_layer.astype(jnp.float32)
# Include the lagrangian terms into the linear bounds that we are
# propagating.
# Note: I had an attempt at gating this function which is still relatively
# expensive behind a jax.lax.cond, in case the active_branch_mask was all
# false but this resulted in the whole bounding process being almost twice
# as slow.
lagrangianed_lincoeffs, lagrangianed_offset = _update_lin_with_lagrangian(
eqn_outval.lin_coeffs, eqn_outval.offset,
active_branch_mask, self._lagrangian_variables,
neur_idxs, branch_val, is_upper)
# This new linear expression is equivalent to the initial linear expression
# except that it now also include the contribution of the lagrangian.
lagrangianed_eqn_outval = linear_relaxations.LinearExpression(
lagrangianed_lincoeffs, lagrangianed_offset)
# We can now pass it on to the underlying primitive, to propagate backward.
return self._base_backward_transform.primitive_backtransform(
context, primitive, lagrangianed_eqn_outval, *args, **params)
def slope_and_lagrangian_optimizer(
slope_opt: optax.GradientTransformation,
lag_opt: optax.GradientTransformation,
) -> optax.GradientTransformation:
"""Creates an optimizer that handles the slopes and dual parameters.
We want to optimize them differently.
Args:
slope_opt: Optax optimizer for the slope coefficients.
lag_opt: Optax optimizer for the Lagrangian variable coefficients.
Returns:
optimizer: Optax optimizer for the combined set of params.
"""
param_schema = ('slope_params', 'dual_params')
opt_for_param = {'slope_params': slope_opt, 'dual_params': lag_opt}
return optax.multi_transform(transforms=opt_for_param,
param_labels=param_schema)
class BranchedOptimizingLinearBoundBackwardTransform(
backward_crown.OptimizingLinearBoundBackwardTransform):
"""Backward transform that concretize bounds through optimization.
The optimization is done over both the relaxation parameters and the
lagrangian variables associated with the branching constraints.
"""
def __init__(
self,
branching_decisions: branch_selection.JittableBranchingDecisions,
relaxer: linear_relaxations.ParameterizedLinearBoundsRelaxer,
primitive_needs_concrete_bounds: Tuple[Primitive, ...],
optimizer: optimizers.Optimizer,
concretization_fn: linear_relaxations.ConcretizationFn = (
linear_relaxations.concretize_linear_expression),
):
"""Constructs a per-node concretizer that performs an inner optimisation.
This supports the addition of additional branching constraints.
Args:
branching_decisions: Branching decisions that needs to be enforced.
relaxer: Specifies the parameterised linear relaxation to use for each
primitive operation.
primitive_needs_concrete_bounds: Which primitive operations need to be
concretised.
optimizer: Optimizer to use to compute the bound.
concretization_fn: Function to use to concretize the linear bounds.
"""
super().__init__(relaxer, primitive_needs_concrete_bounds, optimizer,
concretization_fn)
self._branching_decisions = branching_decisions
def _initial_params(
self, scanner, input_bounds,
) -> Tuple[Mapping[Index, Tensor], Tensor]:
slope_params = super()._initial_params(scanner, input_bounds)
dual_vars = jnp.zeros(self._branching_decisions[0].shape[0])
return slope_params, dual_vars
def _project_params(self, scanner, unc_params):
unc_slope_params, unc_dual_vars = unc_params
slope_params = super()._project_params(scanner, unc_slope_params)
dual_vars = jnp.maximum(unc_dual_vars, 0.)
return slope_params, dual_vars
def _bind(
self,
node_relaxations: Mapping[
Index, linear_relaxations.ParameterizedNodeRelaxation],
all_params: Tuple[Mapping[Index, Tensor], Tensor],
) -> backward_crown.LinearBoundBackwardConcretizingTransform:
slope_params, dual_vars = all_params
base_backward_transform = super()._bind(node_relaxations, slope_params)
return ConstrainedLinearBoundBackwardTransform(
base_backward_transform, self._branching_decisions, dual_vars,
self._concretization_fn)
def lagrangian_backward_linear_compute_bounds(
slope_optimizer: optax.GradientTransformation,
lag_optimizer: optax.GradientTransformation,
num_opt_steps: int,
function: SpecFn,
branching_decisions: branch_selection.JittableBranchingDecisions,
*bounds: Nest[graph_traversal.GraphInput],
) -> Nest[bound_propagation.LayerInput]:
"""Performs bound computation in the style of Beta-Crown.
https://arxiv.org/abs/2103.06624
Args:
slope_optimizer: Optax gradient transformation to use for optimizing the
alpha (slope of the relaxation of non-linearities) parameters.
lag_optimizer: Optax gradient transformation to use for optimizing the beta
(lagrangian variables for the branching constraints) parameters.
num_opt_steps: How many optimization steps to take for each bound
computation.
function: Function performing computation to obtain bounds for. Takes as
only arguments the network inputs.
branching_decisions: 4-tuple of tensors describing the branching
constraints to impose. Detailed description at the top of the module.
*bounds: Bounds on the input to the network.
Returns:
output_bound: Bounds on the output of the function.
"""
parameterized_relaxer = linear_relaxations.parameterized_relaxer
concretize_args_primitive = backward_crown.CONCRETIZE_ARGS_PRIMITIVE
optimizer = optimizers.OptaxOptimizer(
slope_and_lagrangian_optimizer(slope_optimizer, lag_optimizer),
num_steps=num_opt_steps)
backward_concretizer = concretization.ChunkedBackwardConcretizer(
BranchedOptimizingLinearBoundBackwardTransform(
branching_decisions, parameterized_relaxer, concretize_args_primitive,
optimizer),
max_chunk_size=128)
backward_algorithm = concretization.BackwardConcretizingAlgorithm(
backward_concretizer)
output_bound, _ = bound_propagation.bound_propagation(
backward_algorithm, function, *bounds)
return output_bound
| jax_verify-master | jax_verify/src/linear/backward_linearbounds_with_branching.py |
# coding=utf-8
# 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.
"""Utils for Linear Bounds.
"""
import abc
import functools
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import activation_relaxation
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import synthetic_primitives
from jax_verify.src import utils
Bound = bound_propagation.Bound
Primitive = bound_propagation.Primitive
Tensor = bound_propagation.Tensor
Nest = bound_propagation.Nest
LinFun = Callable[..., Tensor]
TensorFun = activation_relaxation.TensorFunction
EPSILON = 1e-5
class LinearExpression:
"""Describes a set of linear expressions."""
def __init__(self, lin_coeffs, offset):
"""Creates a LinearExpression object.
Args:
lin_coeffs: nb_coeffs x (array shape)
offset: (array shape)
"""
self.lin_coeffs = lin_coeffs
self.offset = offset
@property
def shape(self):
return self.offset.shape
def __add__(self, other):
if isinstance(other, LinearExpression):
return LinearExpression(self.lin_coeffs + other.lin_coeffs,
self.offset + other.offset)
else:
return LinearExpression(self.lin_coeffs, self.offset + other)
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
if isinstance(other, LinearExpression):
return LinearExpression(self.lin_coeffs - other.lin_coeffs,
self.offset - other.offset)
else:
return LinearExpression(self.lin_coeffs, self.offset - other)
def __rsub__(self, other):
if isinstance(other, LinearExpression):
return LinearExpression(other.lin_coeffs - self.lin_coeffs,
other.offset - self.offset)
else:
return LinearExpression(-self.lin_coeffs, other - self.offset,)
def __truediv__(self, other):
return LinearExpression(self.lin_coeffs / other, self.offset / other)
class LinearBoundsRelaxer(metaclass=abc.ABCMeta):
@abc.abstractmethod
def linearize_primitive(
self,
index: graph_traversal.Index,
primitive: Primitive,
*inps: Union[Bound, Tensor],
**params) -> Tuple[LinFun, LinFun]:
"""Obtain the parameters of the linearized relaxation of a given primitive.
The relaxation holds when the inputs are within range of the bounds
described by `inps`.
Args:
index: Index of the node in the bound propagation.
primitive: Primitive to relax.
*inps: Bounds on the inputs of the primitive or Tensors.
**params: Parameters of the primitive.
Returns:
lb_linfun: Function evaluating the linear lower bound relaxing that
primitive.
ub_linfun: Function evaluating the linear upper bound relaxing that
primitive.
"""
class OpwiseLinearBoundsRelaxer(LinearBoundsRelaxer):
"""Relaxer mapping each primitive to a predefined linear relaxation.
This relaxation admits no additional parameters.
"""
def __init__(
self,
primitive_mapper: Dict[Primitive, Callable[..., Tuple[LinFun, LinFun]]],
default_relaxer: Optional[LinearBoundsRelaxer] = None):
self._primitive_mapper = primitive_mapper
self._default_relaxer = default_relaxer
def linearize_primitive(
self,
index: graph_traversal.Index,
primitive: Primitive,
*inps: Union[Bound, Tensor],
**params) -> Tuple[LinFun, LinFun]:
if primitive in self._primitive_mapper:
return self._primitive_mapper[primitive](index, *inps, **params)
elif self._default_relaxer:
return self._default_relaxer.linearize_primitive(
index, primitive, *inps, **params)
else:
raise ValueError(f'Unsupported primitive to relax: {primitive}.')
class ParameterizedNodeRelaxation(metaclass=abc.ABCMeta):
"""Computes upper/lower linearisations using optimisable parameters."""
@abc.abstractproperty
def arity(self) -> int:
"""Returns the number of input argument that this relaxation expects."""
@abc.abstractmethod
def linearize(
self,
relax_params: Nest[Tensor],
*inps: Union[Bound, Tensor],
) -> Tuple[LinFun, LinFun]:
"""Returns linearised relaxation for given optimisable parameters."""
@abc.abstractmethod
def initial_params(
self,
*inps: Optional[Union[Bound, Tensor]],
) -> Nest[Tensor]:
"""Returns initial values of optimisable parameters."""
@abc.abstractmethod
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
"""Projects optimisable parameters to their valid domain."""
class ParameterizedLinearBoundsRelaxer(metaclass=abc.ABCMeta):
"""Relaxer mapping each primitive to an optimisable linear relaxation."""
@abc.abstractmethod
def parameterized_linearizer(
self,
index: graph_traversal.Index,
primitive: Primitive,
*input_shapes: Sequence[int],
**params) -> ParameterizedNodeRelaxation:
"""Obtain a parameterised family of linear relaxations of a given primitive.
The relaxations hold when the inputs are within range of the bounds
described by `inps`.
Args:
index: Index of the node in the bound propagation.
primitive: Primitive to relax.
*input_shapes: Shapes of the inputs of the primitive.
**params: Parameters of the primitive.
Returns:
Object producing linearised lower/upper bounds given relaxation
parameters.
"""
class OpwiseParameterizedLinearBoundsRelaxer(ParameterizedLinearBoundsRelaxer):
"""Relaxer mapping each primitive to a parameterized linear relaxation."""
def __init__(
self,
primitive_mapper: Dict[
Primitive, Callable[..., ParameterizedNodeRelaxation]],
default_param_relaxer: Optional[ParameterizedLinearBoundsRelaxer] = None):
self._primitive_mapper = primitive_mapper
self._default_parameterized_relaxer = default_param_relaxer
def parameterized_linearizer(
self,
index: graph_traversal.Index,
primitive: Primitive,
*input_shapes: Sequence[int],
**params) -> ParameterizedNodeRelaxation:
if primitive in self._primitive_mapper:
return self._primitive_mapper[primitive](index, *input_shapes, **params)
elif self._default_parameterized_relaxer:
return self._default_parameterized_relaxer.parameterized_linearizer(
index, primitive, *input_shapes, **params)
else:
raise ValueError(f'Unsupported primitive to relax: {primitive}.')
class BindRelaxerParams(LinearBoundsRelaxer):
"""Relaxer formed from binding parameters into a parameterised relaxer."""
def __init__(
self,
node_relaxations: Dict[
graph_traversal.Index, ParameterizedNodeRelaxation],
relax_params: Dict[graph_traversal.Index, Tensor],
):
self._node_relaxations = node_relaxations
self._relax_params = relax_params
def linearize_primitive(
self,
index: graph_traversal.Index,
primitive: Primitive,
*inps: Union[Bound, Tensor],
**params) -> Tuple[LinFun, LinFun]:
return self._node_relaxations[index].linearize(
self._relax_params[index], *inps)
class ParameterizedLinFun(metaclass=abc.ABCMeta):
"""Linearisation of lower OR upper bound using optimisable parameters."""
@abc.abstractproperty
def arity(self) -> int:
"""Returns the number of input argument that the linear function expects."""
@abc.abstractmethod
def linearize(
self,
relax_params: Nest[Tensor],
*inps: Union[Bound, Tensor],
) -> LinFun:
"""Returns linearised half-bound for given optimisable parameters."""
@abc.abstractmethod
def initial_params(
self,
*inps: Optional[Union[Bound, Tensor]],
) -> Nest[Tensor]:
"""Returns initial values of optimisable parameters."""
@abc.abstractmethod
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
"""Projects optimisable parameters to their valid domain."""
class LowerUpperRelaxation(ParameterizedNodeRelaxation):
"""Adapts two parameterised half-bounds into a parameterised relaxation."""
def __init__(
self, lower: ParameterizedLinFun, upper: ParameterizedLinFun):
super().__init__()
self._lower = lower
self._upper = upper
@property
def arity(self) -> int:
return self._lower.arity
def linearize(
self,
relax_params: Nest[Tensor],
*inps: Union[Bound, Tensor],
) -> Tuple[LinFun, LinFun]:
lower_relax_params, upper_relax_params = relax_params
return (
self._lower.linearize(lower_relax_params, *inps),
self._upper.linearize(upper_relax_params, *inps))
def initial_params(
self,
*inps: Optional[Union[Bound, Tensor]],
) -> Nest[Tensor]:
return (
self._lower.initial_params(*inps),
self._upper.initial_params(*inps))
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
lower_relax_params, upper_relax_params = relax_params
return (
self._lower.project_params(lower_relax_params),
self._upper.project_params(upper_relax_params))
class _NoParamRelaxation(ParameterizedNodeRelaxation):
"""Adapts a simple relaxer function into a zero-parameter relaxer function."""
def __init__(
self,
relaxer: Callable[..., Tuple[LinFun, LinFun]],
*input_shapes: Sequence[int],
**params):
self._relaxer = relaxer
self._input_shapes = input_shapes
self._params = params
@property
def arity(self):
return len(self._input_shapes)
def linearize(
self,
relax_params: Nest[Tensor],
*inps: Union[Bound, Tensor],
) -> Tuple[LinFun, LinFun]:
return self._relaxer(*inps, **self._params)
def initial_params(
self,
*inps: Optional[Union[Bound, Tensor]],
) -> Nest[Tensor]:
return ()
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
return relax_params
no_params = lambda relaxer: functools.partial(_NoParamRelaxation, relaxer)
def linearized(fn: Callable[..., Tensor], *primals: Tensor) -> LinFun:
"""Returns linear function that is tangent to `fn` at given primal point."""
val, deriv = jax.linearize(fn, *primals)
return lambda *xs: val + deriv(*[x - p for x, p in zip(xs, primals)])
class SupportingHyperplane(ParameterizedLinFun):
"""Linearisation of primitive, parameterised by primal point."""
def __init__(
self,
fn: TensorFun,
*input_shapes: Sequence[int]):
super().__init__()
self._fn = fn
self._input_shapes = input_shapes
@property
def arity(self) -> int:
return len(self._input_shapes)
def linearize(
self,
relax_params: Nest[Tensor],
*inps: Union[Bound, Tensor],
) -> LinFun:
primals = [
alpha * inp.upper + (1.-alpha) * inp.lower
if isinstance(inp, Bound) else inp
for inp, alpha in zip(inps, relax_params)]
return linearized(self._fn, *primals)
def initial_params(
self,
*inps: Optional[Union[Bound, Tensor]],
) -> Nest[Tensor]:
# If an input is [known to be] a fixed tensor, don't allocate a
# relaxation parameter for it.
return [
.5 * jnp.ones(shape=inp_shape)
if inp is None or isinstance(inp, Bound) else None
for inp, inp_shape in zip(inps, self._input_shapes)]
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
return jax.tree_map(lambda x: jnp.clip(x, 0., 1.), relax_params)
def eltwise_linfun_from_coeff(slope: Tensor, offset: Tensor) -> LinFun:
return lambda x: slope * x + offset
class ElementwiseChord(ParameterizedLinFun):
"""Chord between input bounds of an element-wise primitive."""
arity = 1
def __init__(
self,
fn: TensorFun,
input_shape: Sequence[int]):
super().__init__()
self._fn = fn
self._input_shape = input_shape
def linearize(
self,
relax_params: Nest[Tensor],
inp: Union[Bound, Tensor],
) -> LinFun:
inp_lower, inp_upper = inp.lower, inp.upper
outp_lower, outp_upper = self._fn(inp_lower), self._fn(inp_upper)
has_interval = inp_upper != inp_lower
denom = jnp.where(
has_interval, inp_upper - inp_lower,
jnp.ones_like(inp_lower))
slope = jnp.where(
has_interval, (outp_upper - outp_lower) / denom,
jnp.zeros_like(inp_lower))
offset = jnp.where(
has_interval, (outp_lower * inp_upper - outp_upper * inp_lower) / denom,
outp_lower)
return eltwise_linfun_from_coeff(slope, offset)
def initial_params(
self,
*inps: Optional[Union[Bound, Tensor]],
) -> Nest[Tensor]:
return ()
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
return relax_params
def elementwise_convex_fn_relaxer(
primitive: Primitive,
input_shape: Sequence[int],
**params) -> ParameterizedNodeRelaxation:
fn = functools.partial(primitive.bind, **params)
lower = SupportingHyperplane(fn, input_shape)
upper = ElementwiseChord(fn, input_shape)
return LowerUpperRelaxation(lower, upper)
def elementwise_concave_fn_relaxer(
primitive: Primitive,
input_shape: Sequence[int],
**params) -> ParameterizedNodeRelaxation:
fn = functools.partial(primitive.bind, **params)
lower = ElementwiseChord(fn, input_shape)
upper = SupportingHyperplane(fn, input_shape)
return LowerUpperRelaxation(lower, upper)
class _SmoothConvexRelaxation(LowerUpperRelaxation):
"""Linear relaxation from supporting hyperplanes of a convex relaxation."""
def __init__(
self,
convex_relaxer: Callable[..., Tuple[TensorFun, TensorFun]],
*input_shapes: Sequence[int],
**params):
# Create a skeleton `ParameterizedLinFun` for initialisation and projection
# relaxation parameters. This doesn't need the lower/upper bound functions.
skeleton = SupportingHyperplane((lambda *_: None), *input_shapes)
super().__init__(skeleton, skeleton)
self._convex_relaxer = convex_relaxer
self._input_shapes = input_shapes
self._params = params
def linearize(
self,
relax_params: Nest[Tensor],
*inps: Union[Bound, Tensor],
) -> Tuple[LinFun, LinFun]:
# First obtain convex lower and concave upper bounds.
# Do so at this late stage because they depend on the current input bounds.
lb_fun, ub_fun = self._convex_relaxer(*inps, **self._params)
lower = SupportingHyperplane(lb_fun, *self._input_shapes)
upper = SupportingHyperplane(ub_fun, *self._input_shapes)
lower_relax_params, upper_relax_params = relax_params
return (
lower.linearize(lower_relax_params, *inps),
upper.linearize(upper_relax_params, *inps))
def linear_from_smooth_convex(
convex_relaxer: Callable[..., Tuple[TensorFun, TensorFun]],
) -> Callable[..., ParameterizedNodeRelaxation]:
return functools.partial(_SmoothConvexRelaxation, convex_relaxer)
def _crown_relu_relaxer(inp: Bound) -> Tuple[LinFun, LinFun]:
"""Obtain the parameters of a linear ReLU relaxation as in CROWN.
This relaxes the ReLU with the adaptive choice of lower bounds as described
for CROWN-ada in https://arxiv.org/abs/1811.00866.
Args:
inp: Input to the ReLU.
Returns:
lb_linfun, ub_linfun: Linear functions bounding the ReLU
"""
inp_lower, inp_upper = inp.lower, inp.upper
relu_on = (inp_lower >= 0.)
relu_amb = jnp.logical_and(inp_lower < 0., inp_upper >= 0.)
ub_slope = relu_on.astype(jnp.float32)
ub_slope += jnp.where(relu_amb,
inp_upper / jnp.maximum(inp_upper - inp_lower, 1e-12),
jnp.zeros_like(inp_lower))
ub_offset = jnp.where(relu_amb, - ub_slope * inp_lower,
jnp.zeros_like(inp_lower))
lb_slope = (ub_slope >= 0.5).astype(jnp.float32)
lb_offset = jnp.zeros_like(inp_lower)
return (eltwise_linfun_from_coeff(lb_slope, lb_offset),
eltwise_linfun_from_coeff(ub_slope, ub_offset))
def _fastlin_relu_relaxer(inp: Bound) -> Tuple[LinFun, LinFun]:
"""Obtain the parameters of a linear ReLU relaxation as in FastLin.
This relaxes the ReLU with the parallel bounds of slope (ub) / (ub - lb)
Args:
inp: Input to the ReLU.
Returns:
lb_linfun, ub_linfun: Linear functions bounding the ReLU
"""
inp_lower, inp_upper = inp.lower, inp.upper
relu_on = (inp_lower >= 0.)
relu_amb = jnp.logical_and(inp_lower < 0., inp_upper >= 0.)
slope = relu_on.astype(jnp.float32)
slope += jnp.where(relu_amb,
inp_upper / jnp.maximum(inp_upper - inp_lower, 1e-12),
jnp.zeros_like(inp_lower))
ub_offset = jnp.where(relu_amb, - slope * inp_lower,
jnp.zeros_like(inp_lower))
lb_offset = jnp.zeros_like(inp_lower)
return (eltwise_linfun_from_coeff(slope, lb_offset),
eltwise_linfun_from_coeff(slope, ub_offset))
class ReluSubgradient(ParameterizedLinFun):
"""Lower bound of a ReLU-like function.
This applies to any two-piece linear function passing through the origin.
"""
arity = 1
def __init__(
self,
input_shape: Sequence[int],
neg_slope: float = 0.,
pos_slope: float = 1.):
super().__init__()
self._input_shape = input_shape
self._neg_slope = neg_slope
self._pos_slope = pos_slope
def linearize(
self,
relax_params: Nest[Tensor],
inp: Union[Bound, Tensor],
) -> LinFun:
inp_lower, inp_upper = inp.lower, inp.upper
lower_slope = jnp.where(inp_lower < 0., self._neg_slope, self._pos_slope)
upper_slope = jnp.where(inp_upper > 0., self._pos_slope, self._neg_slope)
slope = relax_params * upper_slope + (1.-relax_params) * lower_slope
offset = jnp.zeros_like(inp_lower)
return eltwise_linfun_from_coeff(slope, offset)
def initial_params(
self,
inp: Optional[Union[Bound, Tensor]],
) -> Nest[Tensor]:
if inp is None:
return .5 * jnp.ones(shape=self._input_shape, dtype=jnp.float32)
else:
# Initialise close to pos_slope if input interval has more positive mass
# than negative, and vice versa.
# This is a softened version of CROWN.
return jax.nn.sigmoid(inp.lower + inp.upper)
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
return jnp.clip(relax_params, 0., 1.)
def _parameterized_relu_relaxer(
primitive: Primitive,
input_shape: Sequence[int],
neg_slope: float = 0.,
pos_slope: float = 1.,
**params) -> ParameterizedNodeRelaxation:
"""Parameterised relaxation for ReLU-like functions.
This applies to any two-piece linear function passing through the origin.
Args:
primitive: ReLU-like primitive to relax.
input_shape: Shapes of the input of the primitive.
neg_slope: Gradient of the primitive for negative inputs.
pos_slope: Gradient of the primitive for positive inputs.
**params: Parameters of the primitive.
Returns:
Object producing linearised lower/upper bounds given relaxation
parameters.
"""
fn = functools.partial(primitive.bind, **params)
subgradient = ReluSubgradient(input_shape, neg_slope, pos_slope)
chord = ElementwiseChord(fn, input_shape)
if neg_slope <= pos_slope:
return LowerUpperRelaxation(lower=subgradient, upper=chord)
else:
# E.g. leaky ReLU with negative slope >1. This is concave.
return LowerUpperRelaxation(lower=chord, upper=subgradient)
def _rvt_exp_relaxer(inp: Bound) -> Tuple[LinFun, LinFun]:
"""Obtain the parameters of a linear exp relaxation as in RVT.
Lower bound is obtained based on tangent, due to convexity.
Choice of point where the tangent is computed is taken from
https://arxiv.org/pdf/2002.06622.pdf
Chord connecting two endpoints provides upper bound
for exp(x) due to convexity.
Args:
inp: Input to the exp.
Returns:
lb_linfun, ub_linfun: Linear functions bounding the Exponential
"""
lower, upper = inp.lower, inp.upper
thresh = 12.0
min_input = -30.
forced_zeros = upper < min_input
unsafe_to_relax = (upper - lower) < EPSILON
unsafe = jnp.logical_or(forced_zeros, unsafe_to_relax)
def stable_exp(x):
"""If x is greater than thresh, use first order Taylor's expansion."""
return jnp.where(
jnp.greater(x, thresh),
jnp.exp(thresh)*(1 + x - thresh),
jnp.exp(x))
point = jnp.minimum((lower+upper)/2, lower + 0.99)
lb_slope = stable_exp(point)
lb_offset = lb_slope * (1 - point)
# If the relaxation is over too narrow a domain, use the lower bound
# constant as linear lower bounding function.
lb_slope = jnp.where(unsafe, jnp.zeros_like(lower), lb_slope)
lb_offset = jnp.where(unsafe, stable_exp(lower), lb_offset)
ub_slope = (stable_exp(upper)-stable_exp(lower))/(upper - lower)
ub_offset = stable_exp(lower) - ub_slope*lower
# If the relaxation is over too narrow a domain, or if even the upper bound
# is extremely small, we replace the upper bound by a bound with slope of 0.
ub_slope = jnp.where(unsafe, jnp.zeros_like(lower), ub_slope)
ub_offset = jnp.where(unsafe, stable_exp(upper), ub_offset)
lb_fun = eltwise_linfun_from_coeff(lb_slope, lb_offset)
ub_fun = eltwise_linfun_from_coeff(ub_slope, ub_offset)
return lb_fun, ub_fun
def _rvt_posreciprocal_relaxer(inp: Bound) -> Tuple[LinFun, LinFun]:
"""Obtain the parameters of a linear relaxation of reciprocal.
The (unchecked) assumption is that inputs are always positive, and 1/x is
therefore convex.
Tangent provides lower bound for 1/x due to convexity when x > 0.
We use the midpoint to compute the tangent following the suggestion in
https://arxiv.org/pdf/2002.06622.pdf
Chord connecting the two endpoints provides upper bound for 1/x due to
convexity.
Args:
inp: Linear bounds for input to reciprocate, assumed to always be positive.
Returns:
lb_linfun, ub_linfun: Linear functions bounding the 1/x function for x > 0.
"""
lower, upper = inp.lower, inp.upper
safe_lower = jnp.maximum(lower, 1e-6)
safe_upper = jnp.maximum(upper, 1e-6)
point = (safe_lower + safe_upper)/2
lb_slope = -1.0/(point*point)
lb_offset = 2./point
ub_slope = -1.0 / (safe_upper * safe_lower)
ub_offset = 1.0 / safe_upper + 1.0 / safe_lower
lb_fun = eltwise_linfun_from_coeff(lb_slope, lb_offset)
ub_fun = eltwise_linfun_from_coeff(ub_slope, ub_offset)
return lb_fun, ub_fun
def _fixed_abs_relaxer(inp: Bound) -> Tuple[LinFun, LinFun]:
"""Obtains the parameters of a linear relaxation of the abs function.
This is obtained by linearizing the function (as it is convex) for the lower
bound, and taking the chord for the upper bound.
Args:
inp: Bound on the inputs of the absolute value.
Returns:
lb_linfun, ub_linfun.
"""
lb_fun, ub_fun = activation_relaxation.convex_fn_relaxation(lax.abs_p, inp)
# Linearizing in the mid point of the lower bound means that we are going to
# pick either x or -x as the linear lower bound, depending on which one
# represents the larger region, which is a reasonably good default.
mid_point = 0.5 * (inp.lower + inp.upper)
lb_linfun = linearized(lb_fun, mid_point)
# We know that the upper bound is already linear, so we can simply use it.
return lb_linfun, ub_fun
_parameterized_abs_relaxer = functools.partial(
_parameterized_relu_relaxer, neg_slope=-1., pos_slope=1.)
def _fixed_leaky_relu_relaxer(
inp: Bound, *, negative_slope: float) -> Tuple[LinFun, LinFun]:
"""Obtains the parameters of a linear relaxation of the LeakyReLU function.
Args:
inp: Bound on the inputs of the leaky relu.
negative_slope: Slope for the negative inputs.
Returns:
lb_linfun, ub_linfun.
"""
lb_fun, ub_fun = activation_relaxation.leaky_relu_relaxation(
inp, negative_slope=negative_slope)
mid_point = 0.5 * (inp.lower + inp.upper)
return linearized(lb_fun, mid_point), linearized(ub_fun, mid_point)
def _parameterized_leaky_relu_relaxer(
primitive: Primitive,
input_shape: Sequence[int],
*,
negative_slope: float,
) -> ParameterizedNodeRelaxation:
return _parameterized_relu_relaxer(
primitive, input_shape, neg_slope=negative_slope,
negative_slope=negative_slope) # pass `negative_slope` again as **params
def _fixed_sigmoid_relaxer(inp: Bound) -> Tuple[LinFun, LinFun]:
"""Obtains the parameters of a linear relaxation of the sigmoid function.
Args:
inp: Bound on the inputs of the sigmoid.
Returns:
lb_linfun, ub_linfun.
"""
lb_fun, ub_fun = activation_relaxation.sigmoid_relaxation(inp)
mid_point = 0.5 * (inp.lower + inp.upper)
return linearized(lb_fun, mid_point), linearized(ub_fun, mid_point)
def _rvt_posbilinear_relaxer(
x: Bound,
y: Bound,
**params) -> Tuple[LinFun, LinFun]:
"""Obtains the parameters of a linear relaxation of a bilinear function.
Rather than using all 4 of the McCormick inequalities,
https://arxiv.org/pdf/2002.06622.pdf use only two:
For x in [x_l, x_u] and y in [y_l, y_u], the bound imposed are:
x·y >= x·y_l + x_l·y - x_l·y_l
x·y <= x·y_u + x_l·y - x_l·y_u
Args:
x: First input to the positive bilinear primitive.
y: Second input to the positive bilinear primitive
**params:
Returns:
lb_linfun, ub_linfun
"""
assert isinstance(x, Bound)
assert isinstance(y, Bound)
x_lower = x.lower
y_lower, y_upper = y.lower, y.upper
fn = functools.partial(synthetic_primitives.posbilinear_p.bind, **params)
def lb_fun(x: Tensor, y: Tensor):
return fn(x, y_lower) + fn(x_lower, y) - fn(x_lower, y_lower)
def ub_fun(x: Tensor, y: Tensor):
return fn(x, y_upper) + fn(x_lower, y) - fn(x_lower, y_upper)
# These functions are linear by construction.
return lb_fun, ub_fun
class ParameterizedPosbilinearRelaxer(ParameterizedNodeRelaxation):
"""Parameterized linear relaxation of a bilinear function.
This uses pairwise interpolations of the McCormick inequalities.
For x in [x_l, x_u] and y in [y_l, y_u], the bound imposed are:
x·y >= x·y_l + x_l·y - x_l·y_l
x·y >= x·y_u + x_h·y - x_h·y_u
x·y <= x·y_u + x_l·y - x_l·y_u
x·y <= x·y_l + x_u·y - x_l·y_u
"""
arity = 2
def __init__(
self,
x_shape: Sequence[int],
y_shape: Sequence[int],
**params):
super().__init__()
self._x_shape = x_shape
self._y_shape = y_shape
self._params = params
def linearize(
self,
relax_params: Nest[Tensor],
x: Union[Bound, Tensor],
y: Union[Bound, Tensor]) -> Tuple[LinFun, LinFun]:
assert isinstance(x, Bound)
assert isinstance(y, Bound)
x_lower, x_upper = x.lower, x.upper
y_lower, y_upper = y.lower, y.upper
fn = functools.partial(
synthetic_primitives.posbilinear_p.bind, **self._params)
lower_relax_params, upper_relax_params = relax_params
def lb_fun(x: Tensor, y: Tensor):
lb0 = fn(x, y_lower) + fn(x_lower, y) - fn(x_lower, y_lower)
lb1 = fn(x, y_upper) + fn(x_upper, y) - fn(x_upper, y_upper)
return lower_relax_params * lb0 + (1.-lower_relax_params) * lb1
def ub_fun(x: Tensor, y: Tensor):
ub0 = fn(x, y_upper) + fn(x_lower, y) - fn(x_lower, y_upper)
ub1 = fn(x, y_lower) + fn(x_upper, y) - fn(x_upper, y_lower)
return upper_relax_params * ub0 + (1.-upper_relax_params) * ub1
# These functions are linear by construction.
return lb_fun, ub_fun
def initial_params(
self,
*inps: Optional[Union[Bound, Tensor]],
) -> Nest[Tensor]:
fn = functools.partial(
synthetic_primitives.posbilinear_p.bind, **self._params)
# Include a lower and an upper interpolation parameter for each output.
output_shape = jax.eval_shape(
fn, jnp.zeros(self._x_shape), jnp.zeros(self._y_shape)).shape
return (
.5 * jnp.ones(shape=output_shape, dtype=jnp.float32),
.5 * jnp.ones(shape=output_shape, dtype=jnp.float32))
def project_params(self, relax_params: Nest[Tensor]) -> Nest[Tensor]:
lower_relax_params, upper_relax_params = relax_params
return (
jnp.clip(lower_relax_params, 0., 1.),
jnp.clip(upper_relax_params, 0., 1.))
_parameterized_posbilinear_relaxer = functools.partial(
ParameterizedPosbilinearRelaxer)
_crown_mapper = {
synthetic_primitives.leaky_relu_p: _fixed_leaky_relu_relaxer,
synthetic_primitives.relu_p: _crown_relu_relaxer,
synthetic_primitives.sigmoid_p: _fixed_sigmoid_relaxer,
lax.abs_p: _fixed_abs_relaxer,
lax.exp_p: _rvt_exp_relaxer,
synthetic_primitives.posbilinear_p: _rvt_posbilinear_relaxer,
synthetic_primitives.posreciprocal_p: _rvt_posreciprocal_relaxer,
}
_crown_mapper = {prim: utils.simple_propagation(relax)
for prim, relax in _crown_mapper.items()}
crown_rvt_relaxer = OpwiseLinearBoundsRelaxer(_crown_mapper)
_fastlin_mapper = {
synthetic_primitives.leaky_relu_p: _fixed_leaky_relu_relaxer,
synthetic_primitives.relu_p: _fastlin_relu_relaxer,
synthetic_primitives.sigmoid_p: _fixed_sigmoid_relaxer,
lax.abs_p: _fixed_abs_relaxer,
lax.exp_p: _rvt_exp_relaxer,
synthetic_primitives.posreciprocal_p: _rvt_posreciprocal_relaxer,
synthetic_primitives.posbilinear_p: _rvt_posbilinear_relaxer,
}
_fastlin_mapper = {prim: utils.simple_propagation(relax)
for prim, relax in _fastlin_mapper.items()}
fastlin_rvt_relaxer = OpwiseLinearBoundsRelaxer(_fastlin_mapper)
_parameterized_mapper = {
synthetic_primitives.leaky_relu_p: functools.partial(
_parameterized_leaky_relu_relaxer, synthetic_primitives.leaky_relu_p),
synthetic_primitives.relu_p: functools.partial(
_parameterized_relu_relaxer, synthetic_primitives.relu_p),
synthetic_primitives.sigmoid_p: linear_from_smooth_convex(
activation_relaxation.sigmoid_relaxation),
lax.abs_p: functools.partial(_parameterized_abs_relaxer, lax.abs_p),
synthetic_primitives.softplus_p: functools.partial(
elementwise_convex_fn_relaxer, synthetic_primitives.softplus_p),
lax.exp_p: functools.partial(elementwise_convex_fn_relaxer, lax.exp_p),
synthetic_primitives.posreciprocal_p: functools.partial(
elementwise_concave_fn_relaxer, synthetic_primitives.posreciprocal_p),
synthetic_primitives.posbilinear_p: _parameterized_posbilinear_relaxer,
}
_parameterized_mapper = {prim: utils.simple_propagation(relax)
for prim, relax in _parameterized_mapper.items()}
parameterized_relaxer = OpwiseParameterizedLinearBoundsRelaxer(
_parameterized_mapper)
| jax_verify-master | jax_verify/src/linear/linear_bound_utils.py |
# coding=utf-8
# 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 Forward propagation of linear bounds."""
import abc
import functools
from typing import Iterator, MutableMapping, Sequence, Tuple, Union
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import ibp
from jax_verify.src import intersection
from jax_verify.src import synthetic_primitives
from jax_verify.src import utils
from jax_verify.src.linear import linear_relaxations
from jax_verify.src.types import Index, Primitive, Tensor # pylint: disable=g-multiple-import
import numpy as np
class RefBound:
"""Wrapper around a bound so that we can use it as a key."""
def __init__(self, index: Index, bound: graph_traversal.InputBound):
self.index = index
self.bound = bound
self.nb_coeffs = np.prod(bound.shape)
def __hash__(self):
return hash(self.index)
def __eq__(self, other):
return self.index == other.index
class LinearFunction:
"""Represent a pair of linear functions that encompass feasible activations.
We store the linear functions as LinearExpressions objects in `lower_lin` and
`upper_lin`, and also maintain a reference to the initial bounds on the input
to be able to concretize the bounds when needed.
The LinearExpression that we use to represent the bounds are represented by
two tensors:
- lin_coeffs of shape [nb_elements_ref_bounds, *act_dim]
- offset of shape [*act_dim]
where nb_elements_ref_bounds is the number of entries in the reference bound
(essentially the size if it was flattened) and act_dim are the dimension of
the bounds that we are representing.
"""
def __init__(self,
lower_linexp: linear_relaxations.LinearExpression,
upper_linexp: linear_relaxations.LinearExpression,
reference_bound: RefBound,):
self.lower_lin = lower_linexp
self.upper_lin = upper_linexp
self.reference_bound = reference_bound
@property
def shape(self):
return self.lower_lin.shape
@property
def dtype(self):
return self.lower_lin.dtype
@property
def nb_coeffs(self):
return self.reference_bound.nb_coeffs
def concretize(self) -> Tuple[Tensor, Tensor]:
"""Concretize the linear functions to obtain scalar bounds."""
ref_bound = self.reference_bound.bound
inp_shape = ref_bound.shape
concrete_lb = jnp.reshape(
linear_relaxations.concretize_linear_expression(
self.lower_lin.transpose(inp_shape), ref_bound), self.shape)
concrete_ub = -jnp.reshape(
linear_relaxations.concretize_linear_expression(
-self.upper_lin.transpose(inp_shape), ref_bound), self.shape)
return concrete_lb, concrete_ub
def __add__(self, other: Union['LinearFunction', Tensor]) -> 'LinearFunction':
if isinstance(other, LinearFunction):
if self.reference_bound != other.reference_bound:
raise ValueError('Adding linear functions referring to '
'different inputs.')
return LinearFunction(self.lower_lin + other.lower_lin,
self.upper_lin + other.upper_lin,
self.reference_bound)
else:
return LinearFunction(self.lower_lin + other,
self.upper_lin + other,
self.reference_bound)
def __radd__(self, other: Union['LinearFunction', Tensor]
) -> 'LinearFunction':
return self.__add__(other)
def __sub__(self, other: Union['LinearFunction', Tensor]) -> 'LinearFunction':
if isinstance(other, LinearFunction):
if self.reference_bound != other.reference_bound:
raise ValueError('Substracting linear functions referring to '
'different inputs.')
return LinearFunction(self.lower_lin - other.upper_lin,
self.upper_lin - other.lower_lin,
self.reference_bound)
else:
return LinearFunction(self.lower_lin - other,
self.upper_lin - other,
self.reference_bound)
def __rsub__(self, other: Union['LinearFunction', Tensor]
) -> 'LinearFunction':
if isinstance(other, LinearFunction):
if self.reference_bound != other.reference_bound:
raise ValueError('Substracting linear functions referring to '
'different inputs.')
return LinearFunction(other.lower_lin - self.upper_lin,
other.upper_lin - self.lower_lin,
self.reference_bound)
else:
return LinearFunction(other - self.upper_lin,
other - self.lower_lin,
self.reference_bound)
def identity_lin_coeffs(bound: graph_traversal.InputBound) -> Tensor:
input_dim = np.prod(bound.shape)
return jnp.reshape(jnp.eye(input_dim), (input_dim, *bound.shape))
class LinearBound(bound_propagation.Bound):
"""Linear bound over activations.
This is composed of several linear functions because the networks might have
several inputs.
"""
def __init__(self, linear_functions: Sequence[LinearFunction]):
self._refbound_to_linfun: MutableMapping[RefBound, LinearFunction] = {}
for function in linear_functions:
ref_bound = function.reference_bound
if ref_bound in self._refbound_to_linfun:
self._refbound_to_linfun[ref_bound] += function
else:
self._refbound_to_linfun[ref_bound] = function
self._concretized = None
self._shape = next(iter(linear_functions)).shape
self._dtype = next(iter(linear_functions)).dtype
@property
def lower(self):
if self._concretized is None:
self.concretize()
return self._concretized.lower
@property
def upper(self):
if self._concretized is None:
self.concretize()
return self._concretized.upper
@property
def shape(self):
return self._shape
@property
def dtype(self):
return self._dtype
def concretize(self):
if self._concretized is not None:
return self._concretized
lb = jnp.zeros(())
ub = jnp.zeros(())
for lin_fun in self._refbound_to_linfun.values():
lin_fun_lb, lin_fun_ub = lin_fun.concretize()
lb = lb + lin_fun_lb
ub = ub + lin_fun_ub
self._concretized = ibp.IntervalBound(lb, ub)
return self._concretized
def set_concretized(self, interval_bound):
self._concretized = interval_bound
@staticmethod
def initial_linear_bound(index: Index,
input_bound: graph_traversal.InputBound):
lin_coeffs = identity_lin_coeffs(input_bound)
offsets = jnp.zeros_like(input_bound.lower)
identity_lin = linear_relaxations.LinearExpression(lin_coeffs, offsets)
lin_function = LinearFunction(identity_lin, identity_lin,
RefBound(index, input_bound))
lin_bound = LinearBound([lin_function])
lin_bound.set_concretized(
ibp.IntervalBound(input_bound.lower, input_bound.upper))
return lin_bound
def get_linfun(self, ref_bound: RefBound) -> LinearFunction:
"""Get the coefficients of this linear bound with regards to the RefBound."""
if ref_bound in self._refbound_to_linfun:
return self._refbound_to_linfun[ref_bound]
else:
# This LinearBound does not depend on the input requested. Equivalently,
# it depends on it with all-coefficients and offsets equal to 0.
lincoeffs_shape = (ref_bound.nb_coeffs, *self.shape)
zero_lincoeffs = jnp.zeros(lincoeffs_shape)
zero_offsets = jnp.zeros(self.shape)
zero_linexpr = linear_relaxations.LinearExpression(
zero_lincoeffs, zero_offsets)
return LinearFunction(zero_linexpr, zero_linexpr, ref_bound)
def linear_functions(self) -> Iterator[LinearFunction]:
for lin_fun in self._refbound_to_linfun.values():
yield lin_fun
def reference_bounds(self) -> Iterator[RefBound]:
for ref_bound in self._refbound_to_linfun:
yield ref_bound
def get_linop_parts(
lin_op: linear_relaxations.LinFun,
invals: Sequence[LinearBound],
lin_is_positive: bool = False,
lin_is_negative: bool = False,
) -> Tuple[
Tuple[linear_relaxations.LinFun, linear_relaxations.LinFun],
Tuple[linear_relaxations.LinFun, linear_relaxations.LinFun],
Tensor,
]:
"""Extract the functions that implement positive/negative parts of lin_op.
For convenience, we will also return their vmapped version.
Args:
lin_op: Linear function to decompose into a positive and negative part.
invals: Inputs to the function.
lin_is_positive: Optional argument to guarantee that the linear function
has only positive coefficients.
lin_is_negative: Optional argument to guarantee that the linear function
has only negative coefficients.
Returns:
pos_part_op, neg_part_op: Linear function implementing the positive/negative
part of lin_op
pos_part_vop, neg_part_vop: Vmapped version of those functions.
offset: Constant part of the lin_op
"""
zero_inps = [jnp.zeros(inval.shape, inval.dtype) for inval in invals]
offset = lin_op(*zero_inps)
# In case we are told that the linear function has only positive, or only
# negative coefficients, we do not need to do do parameter identification.
# We also set up a dummy function doing no computation in the part that does
# not exist.
# If we have no guarantees, we have to identify the positive and negative part
# of the linear function.
if lin_is_positive:
assert not lin_is_negative
pos_part_op = lambda *args: lin_op(*args) - offset
neg_part_op = lambda *_: jnp.zeros(())
pos_part_vop = jax.vmap(pos_part_op, in_axes=0, out_axes=0)
neg_part_vop = neg_part_op
elif lin_is_negative:
pos_part_op = lambda *_: jnp.zeros(())
neg_part_op = lambda *args: lin_op(*args) - offset
pos_part_vop = pos_part_op
neg_part_vop = jax.vmap(neg_part_op, in_axes=0, out_axes=0)
else:
jac_fun = jax.jacfwd(lin_op, argnums=tuple(range(len(zero_inps))))
jacobians = jac_fun(*zero_inps)
def pos_part_op(*args):
pospart = jnp.zeros(())
for arg, jac in zip(args, jacobians):
pos_jac = jnp.maximum(jac, 0.)
pospart += (arg * pos_jac).sum(axis=tuple(range(-arg.ndim, 0)))
return pospart
def neg_part_op(*args):
negpart = jnp.zeros(())
for arg, jac in zip(args, jacobians):
neg_jac = jnp.minimum(jac, 0.)
negpart += (arg * neg_jac).sum(axis=tuple(range(-arg.ndim, 0)))
return negpart
pos_part_vop = jax.vmap(pos_part_op, in_axes=0, out_axes=0)
neg_part_vop = jax.vmap(neg_part_op, in_axes=0, out_axes=0)
return (pos_part_op, neg_part_op), (pos_part_vop, neg_part_vop), offset
def _forward_propagate_linear_bounds(lb_lin_op: linear_relaxations.LinFun,
ub_lin_op: linear_relaxations.LinFun,
invals: Sequence[LinearBound],
lin_is_positive: bool = False,
lin_is_negative: bool = False
) -> LinearBound:
"""Propagate linear bounds through a primitive relaxed to its linear bounds.
We assume that we have linear bounds on the inputs of the function.
The lin_is_positive/lin_is_negative arguments are optional but will
help making the propagation more efficient if we have some information
about the linear function that we need to propagate through.
Args:
lb_lin_op: Linear function, with only bound arguments that is a lower bound
on the function we want to propagate through. All the constant inputs and
parameters should have been bound.
ub_lin_op: Linear function, with only bound arguments that is an upper bound
on the function we want to propagate through. All the constant inputs and
parameters should have been bound.
invals: List of bounds that are inputs to lb_lin_op / ub_lin_op
lin_is_positive: Optional argument, set to True if the linear functions
are guaranteed to have only positive coefficients.
lin_is_negative: Optional argument, set to True if the linear functions
are guaranteed to have only negative coefficients.
Returns:
out_lin_bound: LinearBound on the output of the linear function.
"""
((lb_pospart_op, lb_negpart_op),
(lb_pospart_vop, lb_negpart_vop),
lb_offset) = get_linop_parts(lb_lin_op, invals,
lin_is_positive, lin_is_negative)
((ub_pospart_op, ub_negpart_op),
(ub_pospart_vop, ub_negpart_vop),
ub_offset) = get_linop_parts(ub_lin_op, invals,
lin_is_positive, lin_is_negative)
all_ref_bound = set()
for arg in invals:
for ref_bound in arg.reference_bounds():
all_ref_bound.add(ref_bound)
out_linfuns = []
lb_offset_shared = lb_offset / len(all_ref_bound)
ub_offset_shared = ub_offset / len(all_ref_bound)
for ref_bound in all_ref_bound:
in_linfuns = []
for arg in invals:
in_linfuns.append(arg.get_linfun(ref_bound))
lower_lincoeffs = (lb_pospart_vop(*(linfun.lower_lin.lin_coeffs
for linfun in in_linfuns))
+ lb_negpart_vop(*(linfun.upper_lin.lin_coeffs
for linfun in in_linfuns)))
lower_offset = (lb_pospart_op(*(linfun.lower_lin.offset
for linfun in in_linfuns))
+ lb_negpart_op(*(linfun.upper_lin.offset
for linfun in in_linfuns))
+ lb_offset_shared)
lower_linexpr = linear_relaxations.LinearExpression(
lower_lincoeffs, lower_offset)
upper_lincoeffs = (ub_pospart_vop(*(linfun.upper_lin.lin_coeffs
for linfun in in_linfuns))
+ ub_negpart_vop(*(linfun.lower_lin.lin_coeffs
for linfun in in_linfuns)))
upper_offset = (ub_pospart_op(*(linfun.upper_lin.offset
for linfun in in_linfuns))
+ ub_negpart_op(*(linfun.lower_lin.offset
for linfun in in_linfuns))
+ ub_offset_shared)
upper_linexpr = linear_relaxations.LinearExpression(
upper_lincoeffs, upper_offset)
out_linfun = LinearFunction(lower_linexpr, upper_linexpr, ref_bound)
out_linfuns.append(out_linfun)
return LinearBound(out_linfuns)
def _fastlin_bilinearwithparam_op(primitive: Primitive,
lhs: Union[LinearBound, Tensor],
rhs: Union[LinearBound, Tensor],
**kwargs) -> LinearBound:
"""Propagation of Linear bounds through an affine operation.
This operation is implemented by one of the bilinear primitives so we know
exactly how to do the bound propagation without having to materialize the
jacobian to obtain weights.
Args:
primitive: Linear function to pass through.
lhs: Either parameters or LinearBound.
rhs: Either parameters or LinearBound.
**kwargs: Dict with the parameters of the linear operation.
Returns:
out_bounds: LinearBound
"""
# Detect which order things are in, so that we can do forward propagation
# simply by calling `fun_call(bound_arg, param_arg)`, whatever the ordering
# initially was.
if isinstance(lhs, bound_propagation.Bound):
assert not isinstance(rhs, bound_propagation.Bound)
bound_arg = lhs
param_arg = rhs
fun_call = functools.partial(primitive.bind, **kwargs)
else:
assert isinstance(rhs, bound_propagation.Bound)
bound_arg = rhs
param_arg = lhs
fun_call = lambda b_arg, p_arg: primitive.bind(p_arg, b_arg, **kwargs)
vmap_funcall = jax.vmap(fun_call, in_axes=(0, None), out_axes=0)
# Extract the parameters for the bound propagation.
abs_params = jnp.abs(param_arg)
# Get access to the LinearBound, in case it is wrapped in an
# IntersectionBound.
unwrapped_bound = bound_arg.unwrap()
# Iterate over the different linear functions that the bound is composed of.
out_linfuns = []
for lin_fun in unwrapped_bound.linear_functions():
range_lin = (lin_fun.upper_lin - lin_fun.lower_lin) / 2
mean_lin = (lin_fun.upper_lin + lin_fun.lower_lin) / 2
ref_bound = lin_fun.reference_bound
out_range_lin_coeffs = vmap_funcall(range_lin.lin_coeffs, abs_params)
out_range_offset = fun_call(range_lin.offset, abs_params)
out_mean_lin_coeffs = vmap_funcall(mean_lin.lin_coeffs, param_arg)
out_mean_offset = fun_call(mean_lin.offset, param_arg)
out_lowerlinexp = linear_relaxations.LinearExpression(
out_mean_lin_coeffs - out_range_lin_coeffs,
out_mean_offset - out_range_offset)
out_upperlinexp = linear_relaxations.LinearExpression(
out_mean_lin_coeffs + out_range_lin_coeffs,
out_mean_offset + out_range_offset)
out_linfun = LinearFunction(out_lowerlinexp, out_upperlinexp, ref_bound)
out_linfuns.append(out_linfun)
return LinearBound(out_linfuns)
@bound_propagation.unwrapping
def _fastlin_add(lhs, rhs):
return lhs + rhs
@bound_propagation.unwrapping
def _fastlin_sub(lhs, rhs):
return lhs - rhs
def _fastlin_div(lhs, rhs):
"""Propagation of Linear bounds through Elementwise division.
We don't support the propagation of bounds through the denominator.
Args:
lhs: Numerator of the division.
rhs: Denominator of the division.
Returns:
out_bounds: Bound on the output of the division.
"""
if isinstance(rhs, bound_propagation.Bound):
raise ValueError('Bound propagation through the denominator unsupported.')
return _fastlin_bilinearwithparam_op(lax.mul_p, lhs, 1./rhs)
def forward_fastlin_bound_propagation(function, *bounds):
"""Performs forward linear bound propagation.
This is using the relu relaxation of Fastlin.
(https://arxiv.org/abs/1804.09699)
Args:
function: Function performing computation to obtain bounds for. Takes as
only argument the network inputs.
*bounds: jax_verify.IntervalBound, bounds on the inputs of the function.
Returns:
output_bound: Bounds on the output of the function obtained by FastLin
"""
output_bound, _ = bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(forward_fastlin_transform),
function, *bounds)
return output_bound
def forward_crown_bound_propagation(function, *bounds):
"""Performs forward linear bound propagation.
This is using the relu relaxation of CROWN.
(https://arxiv.org/abs/1811.00866)
Args:
function: Function performing computation to obtain bounds for. Takes as
only argument the network inputs.
*bounds: jax_verify.IntervalBound, bounds on the inputs of the function.
Returns:
output_bound: Bounds on the output of the function obtained by FastLin
"""
forward_crown_transform = ConcretizingForwardLinearBoundTransform(
linear_relaxations.crown_rvt_relaxer)
output_bound, _ = bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(forward_crown_transform),
function, *bounds)
return output_bound
def ibpforwardfastlin_bound_propagation(function, *bounds):
"""Obtains the best of IBP and ForwardFastlin bounds.
Args:
function: Function performing computation to obtain bounds for. Takes as
only argument the network inputs.
*bounds: jax_verify.IntervalBound, bounds on the inputs of the function.
Returns:
output_bound: Bounds on the output of the function obtained by FastLin
"""
output_bound, _ = bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(
intersection.IntersectionBoundTransform(ibp.bound_transform,
forward_fastlin_transform)),
function, *bounds)
return output_bound
class ForwardLinearBoundTransform(
graph_traversal.GraphTransform[LinearBound],
metaclass=abc.ABCMeta):
"""Propagate Linear bounds forward through the network."""
def __init__(self, linear_elision: bool = False):
self._linear_elision = linear_elision
def should_handle_as_subgraph(self, primitive: Primitive) -> bool:
if primitive is synthetic_primitives.linear_p:
# If we do linear elision, we do not want to treat linear_p as a subgraph.
# (we want to treat it as a single layer.)
return not self._linear_elision
else:
return super().should_handle_as_subgraph(primitive)
def input_transform(
self,
context: graph_traversal.TransformContext[
linear_relaxations.LinearExpression],
input_bound: graph_traversal.InputBound,
) -> LinearBound:
return LinearBound.initial_linear_bound(context.index, input_bound)
def primitive_transform(
self,
context: graph_traversal.TransformContext[
linear_relaxations.LinearExpression],
primitive: Primitive,
*args: graph_traversal.LayerInput[LinearBound],
**params,
) -> LinearBound:
# We specialise bilinear and reshape operation because we can compute them
# in a more lightweight manner, without having to resort to identifying
# parameters.
if primitive in bound_propagation.BILINEAR_PRIMITIVES:
return _fastlin_bilinearwithparam_op(primitive, *args, **params)
elif (primitive in bound_propagation.AFFINE_PRIMITIVES
or primitive in bound_propagation.RESHAPE_PRIMITIVES
or (primitive is lax.div_p and isinstance(args[1], Tensor))):
is_positive = primitive in POSLINEAR_PRIMITIVES
safe_params = synthetic_primitives.filter_jaxverify_kwargs(params)
lin_fun = utils.bind_nonbound_args(primitive.bind, *args, **safe_params)
lin_bound_inputs = [arg.unwrap() for arg in args
if isinstance(arg, bound_propagation.Bound)]
return _forward_propagate_linear_bounds(lin_fun, lin_fun,
lin_bound_inputs,
lin_is_positive=is_positive)
else:
# This is not an affine primitive. We need to go through a relaxation.
return self.nonlinear_primitive_transform(context, primitive,
*args, **params)
@abc.abstractmethod
def nonlinear_primitive_transform(
self,
context: graph_traversal.TransformContext[
linear_relaxations.LinearExpression],
primitive: Primitive,
*args: graph_traversal.LayerInput[LinearBound],
**params,
) -> LinearBound:
pass
class ConcretizingForwardLinearBoundTransform(ForwardLinearBoundTransform):
"""Forward linear bound propagation with concretization at every node."""
def __init__(self,
relaxer: linear_relaxations.LinearBoundsRelaxer,
linear_elision: bool = False):
super().__init__(linear_elision)
self.relaxer = relaxer
def nonlinear_primitive_transform(
self,
context: graph_traversal.TransformContext[
linear_relaxations.LinearExpression],
primitive: Primitive,
*args: graph_traversal.LayerInput[LinearBound],
**params,
) -> LinearBound:
# This is not an affine primitive. We need to go through a relaxation.
# Obtain the linear bounds.
lb_linfun, ub_linfun = self.relaxer.linearize_primitive(
context.index, primitive, *args, **params)
# Translate to functions that only accept variable (linear bound) inputs.
lb_linfun = utils.bind_nonbound_args(lb_linfun, *args)
ub_linfun = utils.bind_nonbound_args(ub_linfun, *args)
lin_bound_inputs = [arg.unwrap() for arg in args
if isinstance(arg, bound_propagation.Bound)]
is_positive = primitive in POSITIVE_RELAXATION_PRIMITIVES
is_negative = primitive in NEGATIVE_RELAXATION_PRIMITIVES
return _forward_propagate_linear_bounds(
lb_linfun, ub_linfun, lin_bound_inputs,
lin_is_positive=is_positive, lin_is_negative=is_negative)
POSLINEAR_PRIMITIVES = [
lax.scatter_add_p,
lax.add_p,
lax.reduce_sum_p,
*bound_propagation.RESHAPE_PRIMITIVES,
]
POSITIVE_RELAXATION_PRIMITIVES = [
synthetic_primitives.relu_p,
lax.exp_p,
]
NEGATIVE_RELAXATION_PRIMITIVES = [
synthetic_primitives.posreciprocal_p,
]
forward_fastlin_transform = ConcretizingForwardLinearBoundTransform(
linear_relaxations.fastlin_rvt_relaxer)
| jax_verify-master | jax_verify/src/linear/forward_linear_bounds.py |
# coding=utf-8
# 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.
"""Algorithms for branch/bound minimisation by partitioning activation space.
Each of the algorithms provided here maintains the current partitioning,
i.e. the set of leaves of the branching decision tree. This is represented
as a priority queue, such that the leaf (partition) with the highest value
of the output bound to be minimised appears first.
The algorithms iteratively branch by splitting the highest priority partition.
On each new sub-partition, its output bound and next branching point are
recomputed.
"""
import functools
import heapq
from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, Union
from absl import logging
import jax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import bound_utils
from jax_verify.src import graph_traversal
from jax_verify.src import intersection
from jax_verify.src.branching import branch_selection
from jax_verify.src.types import Index, Nest, SpecFn, Tensor # pylint: disable=g-multiple-import
import numpy as np
BoundsOnMax = Tuple[Tensor, Tensor]
BranchEvaluationFn = Callable[[
branch_selection.BranchingDecisionList,
], Tuple[
BoundsOnMax,
Optional[branch_selection.BranchPlane], # Next branch plane.
]]
JittableBranchEvaluationFn = Callable[[
branch_selection.JittableBranchingDecisions,
], Tuple[
Tuple[Tensor, Tensor], # Bounds on the branch.
Tuple[
branch_selection.JittableBranchingDecisions, # Next lower branch.
branch_selection.JittableBranchingDecisions, # Next upper branch.
],
]]
BoundFn = Callable[[
branch_selection.BranchingDecisionList,
], Tuple[
Tensor, # Upper bound on output.
Mapping[Index, Tuple[Tensor, Tensor]], # All intermediate bounds.
]]
BranchScoringFn = Callable[[
Mapping[Index, Tuple[Tensor, Tensor]], # All intermediate bounds.
], Tuple[
Mapping[Index, Tensor], # Scores for each neuron.
Optional[Mapping[Index, Tensor]], # Branch values for each neuron (or 0).
]]
def upper_bound_with_branching(
transform: bound_propagation.BoundTransform,
branch_neuron_selector: branch_selection.BranchNeuronSelector,
spec_fn: SpecFn,
*input_bounds: Nest[graph_traversal.GraphInput],
num_branches: int,
stop_at_negative_ub: bool = False,
) -> Tensor:
"""Applies the given bound prop method repeatedly with branching.
Args:
transform: Forward bound propagation method to apply.
branch_neuron_selector: Strategy for selecting branch planes.
spec_fn: Function for which to find an upper bound.
*input_bounds: Bounds on inputs to `spec_fn`.
num_branches: Number of branches to perform. The number of leaves will be
one more than this.
stop_at_negative_ub: Early stop the branch and bound if the upper bound
becomes negative.
Returns:
Component-wise upper-bound on output of `spec_fn`.
"""
root_bounds = bound_utils.BoundRetriever(bound_utils.VacuousBoundTransform())
bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(root_bounds),
spec_fn, *input_bounds)
def bound_fn(branching_decisions: branch_selection.BranchingDecisionList):
branch_constraint = bound_utils.FixedBoundApplier(
branch_selection.concrete_branch_bounds(
root_bounds.concrete_bounds, branching_decisions))
branch_bounds = bound_utils.BoundRetriever(
intersection.IntersectionBoundTransform(transform, branch_constraint))
output_bound, _ = bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(branch_bounds),
spec_fn, *input_bounds)
return output_bound.upper, {
'intermediate_bounds': branch_bounds.concrete_bounds,
}
branch_scoring_fn = functools.partial(
branch_neuron_selector.score_neurons,
branch_neuron_selector.analyse_inputs(spec_fn, *input_bounds))
_, all_upper_bounds, _ = run_branching(
functools.partial(evaluate_branch, bound_fn, branch_scoring_fn),
num_branches, stop_at_negative_ub)
return all_upper_bounds[-1]
def run_branching(
branch_evaluation_fn: BranchEvaluationFn,
num_branches: int,
stop_at_negative_ub: bool = False,
) -> Tensor:
"""Use branch-and-bound to find a tight upper bound for the network.
Args:
branch_evaluation_fn: Callable computing an upper bound and determining the
next branch plane, given a branch specified by decision list.
num_branches: Number of branches to perform. The number of leaves will be
one more than this.
stop_at_negative_ub: Early stop the branch and bound if the upper bound
becomes negative.
Returns:
Tensor of shape [num_branches, batch_size, spec_size] containing, at each
branching iteration, upper bounds for each example in the batch, associated
with the worst leaf branch, Tensor with number of solved subproblems
"""
# Maintain branches (leaves of the branching tree) as a priority queue,
# enabling us to branch on the cases with highest Lagrangian first.
all_branches = BranchQueue()
upper_bounds = []
def push_branch(branching_decisions: branch_selection.BranchingDecisionList):
bounds, next_branch_plane = branch_evaluation_fn(
branching_decisions)
all_branches.push(bounds, next_branch_plane, args=(branching_decisions,))
push_branch([])
upper_bounds.append(all_branches.max_bounds())
for _ in range(num_branches):
if not all_branches.can_pop():
break # The worst-scoring branch cannot be split further.
if stop_at_negative_ub and (all_branches.max_bounds().max() < 0.
or np.amax(all_branches.empirical_max()) > 0.):
break # We are early stopping and can already prove/disprove robustness.
next_branch_plane, (branching_decisions,), _ = all_branches.pop()
# Replace this branching choice with two new ones.
push_branch(branching_decisions + [next_branch_plane.lower_branch])
push_branch(branching_decisions + [next_branch_plane.upper_branch])
upper_bounds.append(all_branches.max_bounds())
empirical_max = all_branches.empirical_max()
batch_size = empirical_max.shape[0]
return empirical_max, jnp.array( # pytype: disable=bad-return-type # jax-ndarray
upper_bounds), jnp.ones(batch_size) * all_branches.n_subproblems()
def run_batched_branching(
batch_size: int,
max_branching_depth: int,
max_index_depth: int,
batched_branch_evaluation_fn: JittableBranchEvaluationFn,
num_evals: int,
stop_at_negative_ub: bool = False,
) -> Tensor:
"""Use branch-and-bound to find a tight upper bound for the network.
This method evaluates several sub-domains at once in order to be quicker.
Args:
batch_size: How many subdomains to evaluate at the same time.
max_branching_depth: How many constraints can we impose on a single
subdomain.
max_index_depth: What is the maximum level of depth in the index.
batched_branch_evaluation_fn: Function to evaluate a batch of set of
branching decision. This takes as input the branching decision in jitted
form, and returns:
- (lower bound, upper bound) on the minimum over the subdomain.
- The next branching decision to perform on this subdomain, in jitted
form.
num_evals: How many branching evaluations to perform.
stop_at_negative_ub: Early stop the branch and bound if the upper bound
becomes negative or the lower bound becomes positive.
Returns:
Tensor of shape [num_branches, batch_size, spec_size] containing, at each
branching iteration, upper bounds for each example in the batch,
associated with the worst leaf branch,
Tensor with number of solved subproblems
"""
# Maintain branches (leaves of the branching tree) as a priority queue,
# enabling us to branch on the cases with highest Lagrangian first.
all_branches = BranchQueue()
upper_bounds = []
empty_branching_decisions = branch_selection.branching_decisions_tensors(
[], max_branching_depth, max_index_depth)
array_empty_bdecs = jax.tree_map(lambda x: jnp.expand_dims(x, 0),
empty_branching_decisions)
def push_branches(
bdec_list: Sequence[branch_selection.BranchingDecisionList]):
list_bdec_tensors = [branch_selection.branching_decisions_tensors(
bdecs, max_branching_depth, max_index_depth) for bdecs in bdec_list]
array_bdecs_tensors = jax.tree_map(
lambda *bdec_ten: jnp.stack([*bdec_ten], axis=0), *list_bdec_tensors)
nb_branches_to_eval = len(bdec_list)
nb_branches_to_pad = batch_size - nb_branches_to_eval
if nb_branches_to_pad:
array_padding_bdecs = jax.tree_map(
lambda x: jnp.repeat(x, nb_branches_to_pad, 0), array_empty_bdecs)
to_eval_branches = jax.tree_map(lambda x, y: jnp.concatenate([x, y]),
array_bdecs_tensors, array_padding_bdecs)
else:
to_eval_branches = array_bdecs_tensors
((lower_bounds, upper_bounds),
(next_lower_branches, next_upper_branches)) = batched_branch_evaluation_fn(
to_eval_branches)
# For each existing subdomain, find out which position to insert a new
# constraint.
lower_bounds = np.array(lower_bounds)
upper_bounds = np.array(upper_bounds)
next_node_indices = [tuple(idx)
for idx in next_lower_branches.node_indices.tolist()]
next_neuron_indices = next_lower_branches.neuron_indices.tolist()
next_lower_vals = next_lower_branches.branch_vals.tolist()
next_upper_vals = next_upper_branches.branch_vals.tolist()
for subprob_idx, parent_bdecs in enumerate(bdec_list):
bounds = (lower_bounds[subprob_idx], upper_bounds[subprob_idx])
lower_branch_dec = branch_selection.BranchDecision(
next_node_indices[subprob_idx], next_neuron_indices[subprob_idx],
next_lower_vals[subprob_idx], False)
upper_branch_dec = branch_selection.BranchDecision(
next_node_indices[subprob_idx], next_neuron_indices[subprob_idx],
next_upper_vals[subprob_idx], True)
next_branch_plane = branch_selection.BranchPlane(lower_branch_dec,
upper_branch_dec)
all_branches.push(bounds, next_branch_plane, args=(parent_bdecs,))
push_branches([[]])
for _ in range(num_evals):
subdomains = []
while len(subdomains) < batch_size:
if not all_branches.can_pop():
break # Queue empty / worst scoring branch cannot be split further.
next_branch_plane, (branching_decisions,), _ = all_branches.pop()
subdomains.append(branching_decisions + [next_branch_plane.lower_branch])
subdomains.append(branching_decisions + [next_branch_plane.upper_branch])
if subdomains:
push_branches(subdomains)
else:
# We don't have any subdomain to evaluate.
break
max_bound = all_branches.max_bounds()
upper_bounds.append(max_bound)
emp_max = np.amax(all_branches.empirical_max() > 0.)
if stop_at_negative_ub and (max_bound.max() < 0. or emp_max > 0.):
# We can disprove robustness, or we can prove robustness for all
# remaining subdomains.
break
empirical_max = all_branches.empirical_max()
batch_size = empirical_max.shape[0]
return empirical_max, jnp.array( # pytype: disable=bad-return-type # jax-ndarray
upper_bounds), jnp.ones(batch_size) * all_branches.n_subproblems()
def evaluate_branch(
bound_fn: BoundFn,
branch_scoring_fn: BranchScoringFn,
branching_decisions: branch_selection.BranchingDecisionList,
) -> Tuple[BoundsOnMax, Optional[branch_selection.BranchPlane]]:
"""Evaluates a branch by first computing its intermediate bounds.
Use `functools.partial` to bind the `bound_fn` and `branch_scoring_fn` args,
to make this conform to `BranchEvaluationFn`.
Args:
bound_fn: A function that takes as input branching decisions and input
bounds and will compute final and intermediate bounds.
branch_scoring_fn: A function that takes as input information produced by
the bounding function and will return a score for all neurons, indicating
which ones to branch on. This will typically be based on
`branch_selection.BranchNeuronSelector.score_neurons`.
branching_decisions: Specifies the branch in question.
Returns:
bounds_on_max: Lower and upper bounds on the max attainable for each example
in the batch.
next_branch_plane: The next branching decision to make.
"""
# Obtain the bound for this set of branching decisions, and get the next
# branches to investigate.
upper_bound, branch_heuristics = bound_fn(branching_decisions)
# Obtain the scores for all the branching decisions.
branching_scores, branch_vals = branch_scoring_fn(branch_heuristics)
next_branch_plane = branch_selection.highest_score_branch_plane(
branching_scores, branch_vals)
emp_max_est = branch_heuristics.get(
'emp_max_est', -jnp.inf * jnp.ones_like(upper_bound))
return (emp_max_est, upper_bound), next_branch_plane # pytype: disable=bad-return-type # jax-ndarray
def evaluate_branch_with_filtering(
full_bound_fn: BoundFn,
appx_bound_fn: BoundFn,
branch_scoring_fn: BranchScoringFn,
branching_decisions: branch_selection.BranchingDecisionList,
*,
num_filtered_neurons: int,
bound_agg: str,
) -> Tuple[BoundsOnMax, Optional[branch_selection.BranchPlane]]:
"""Evaluates a branch by filtering via approximate intermediate bounds.
Use `functools.partial` to bind the `full_bound_fn`, `appx_bound_fn`, and
`branch_scoring_fn` args, to make this conform to `BranchEvaluationFn`.
Args:
full_bound_fn: A function that takes as input branching decisions and input
bounds and will compute final and intermediate bounds.
appx_bound_fn: Efficient approximation of `full_bound_fn`, used to compute
final branching scores for filtered neurons.
branch_scoring_fn: A function that takes as input information produced by
the bounding function and will return a score for all neurons, indicating
which ones to branch on. This will typically be based on
`branch_selection.BranchNeuronSelector.score_neurons`.
branching_decisions: Specifies the branch in question.
num_filtered_neurons: number of filtered neurons per layer.
bound_agg: string indicating how to aggregate bounds for upper and lower
branches that are computed via `appx_bound_fn`.
Returns:
bounds_on_max: Lower and upper bounds on the max attainable for each example
in the batch.
next_branch_plane: The next branching decision to make.
"""
# Obtain the bound for this set of branching decisions, and get the next
# branches to investigate.
upper_bound, branch_heuristics = full_bound_fn(branching_decisions)
# Obtain the initial scores for all the branching decisions, which are
# used to filter promising ones.
init_branching_scores, branch_vals = branch_scoring_fn(branch_heuristics)
next_branch_plane = branch_selection.highest_score_branch_plane(
init_branching_scores, branch_vals)
# Compute scores for all filtered neurons and select the one for branching
best_branch_score = jnp.inf
for index in init_branching_scores:
flat_scores = jnp.reshape(init_branching_scores[index], [-1])
neuron_indices = jnp.argsort(-flat_scores)
for neuron_index in neuron_indices[:num_filtered_neurons]:
neuron_score = flat_scores[neuron_index]
if not jnp.isinf(neuron_score):
curr_branch_plane = branch_selection.make_branch_plane(
index, neuron_index, branch_vals)
lower_branch_bound, _ = appx_bound_fn(
[*branching_decisions, curr_branch_plane.lower_branch])
upper_branch_bound, _ = appx_bound_fn(
[*branching_decisions, curr_branch_plane.upper_branch])
curr_branch_score = branch_selection.aggregate_ambiguities(bound_agg)(
jnp.max(lower_branch_bound),
jnp.max(upper_branch_bound))
if curr_branch_score < best_branch_score:
best_branch_score = curr_branch_score
next_branch_plane = curr_branch_plane
else:
# This is an infeasible choice, so we do not need to waste time
# evaluating it.
# In addition, in case we have poor convergence, it's entirely possible
# that by bad luck, this would be the best results, in which case we
# would end up in an infinite loop.
# (This branch gets picked, nothing gets changed, the bound remain the
# same and we keep on landing in the same place).
pass
emp_max_est = branch_heuristics.get(
'emp_max_est', -jnp.inf * jnp.ones_like(upper_bound))
return (emp_max_est, upper_bound), next_branch_plane # pytype: disable=bad-return-type # jax-ndarray
class BranchQueue:
"""Set of branch leaves, organised as a priority queue."""
def __init__(self, log=True, drop_negative_ub=False):
self._all_branches = []
self._j = 0
self._log = log
self._empirical_max = -np.inf
self._highest_negative_ub = -np.inf
self._bound_shape = None
self._drop_negative_ub = drop_negative_ub
def push(
self,
bounds: BoundsOnMax,
next_branch_plane: Optional[Union[bool, branch_selection.BranchPlane]],
*,
args: Optional[Sequence[Any]] = None,
jax_args: Optional[Sequence[Any]] = None):
"""Pushes the branch to the priority queue.
Args:
bounds: Per-example upper bound for this branch.
next_branch_plane: Neuron to split for the next branching.
args: Auxiliary arguments to store with the branch.
jax_args: Auxiliary arguments to store with the branch that are jax
objects. We're separating them so that we can hold them off device.
"""
args = args or ()
jax_args = jax_args or ()
# Move tensors off the device.
# There may be many branches, and there would be a risk of running out of
# device memory if every entry in the queue held their tensors on-device.
(emp_max, upper_bound), next_branch_plane, jax_args = _device_pop(
(bounds, next_branch_plane, jax_args))
if self._log:
logging.info('Branch %d: %s', self._j, ''.join(
f'[Sample {idx}] Bound {np.amax(bd):.04f} '
for idx, bd in enumerate(upper_bound)))
if np.amax(emp_max) > np.amax(self._empirical_max):
logging.info('New Empirical max: %.04f', np.amax(emp_max))
self._bound_shape = bounds[1].shape
# Queue entries are tuples beginning with `(priority, j, ...)`,
# where `j` is a unique identifier in case priorities are equal.
priority = -np.max(upper_bound)
entry = priority, self._j, upper_bound, next_branch_plane, args, jax_args
if (priority < 0.):
# This is a bound that will have to be split.
heapq.heappush(self._all_branches, entry)
elif not self._drop_negative_ub:
# We are not trying to save memory and are keeping all the bounds.
heapq.heappush(self._all_branches, entry)
else:
# This is a bound that we want to drop, it's a negative upper bound.
# We'll just update our running tally of what would be the limiting bound
# when we cross zero.
self._highest_negative_ub = np.maximum(self._highest_negative_ub,
upper_bound)
self._j += 1
# Update the highest value seen.
self._empirical_max = np.maximum(self._empirical_max, emp_max)
def can_pop(self) -> bool:
"""Returns whether the branch with the highest Lagrangian can be split."""
if self._all_branches:
top_branch = self._all_branches[0]
next_branch_plane = top_branch[3]
return next_branch_plane is not None
else:
return False
def pop(self) -> Tuple[
branch_selection.BranchPlane,
Sequence[Any],
Sequence[Any]]:
"""Pops the branch with the highest upper bound (averaged over batch).
Returns:
next_branch_plane: Neuron to split for the next branching.
args: Auxiliary arguments passed to `push`.
jax_args: Auxiliary arguments passed to `push` that are jax objects.
"""
entry = heapq.heappop(self._all_branches)
_, j, bounds, next_branch_plane, args, jax_args = entry
if self._log:
logging.info('Splitting branch %d: %s', j, ''.join(
f'[Sample {idx}] Bound {np.amax(bd):.04f} '
for idx, bd in enumerate(bounds)))
return next_branch_plane, args, jax_args
def max_bounds(self) -> Tensor:
"""Returns the effective upper bound: the worst case over all leaves."""
if self._drop_negative_ub and not self._all_branches:
# We have dropped all the negative bounds, and have run out of new leaves
# to branch. The remaining bound will be the one that we kept in the
# running tally of highest negative upper bound.
return self._highest_negative_ub
if np.prod(self._bound_shape) == 1:
# If we have a single output being bounded, we know where it is in the
# priority queue.
worst_priority = self._all_branches[0][0]
return np.reshape(-worst_priority, self._bound_shape)
else:
# If there is multiple outputs, then we need to go through the whole queue
# because otherwise we don't know which is the worst bound for a given
# coordinate.
bounds = np.stack(tuple(branch[2] for branch in self._all_branches))
# Extract bounds from each (priority, j, bounds, ...) entry.
return np.amax(bounds, axis=0)
def empirical_max(self) -> Tensor:
return self._empirical_max
def n_subproblems(self) -> int:
return self._j
def _device_pop(x: Nest[jnp.ndarray]) -> Nest[np.ndarray]:
"""Moves a tensor (or nest thereof) off the device.
Any other references to the tensor will become invalid.
Args:
x: Nest of Jax tensors.
Returns:
Nest of numpy tensors corresponding to `x`.
"""
x_np = jax.device_get(x)
jax.tree_map(lambda x: x.delete() if isinstance(x, jnp.ndarray) else None, x)
return x_np
| jax_verify-master | jax_verify/src/branching/branch_algorithm.py |
# coding=utf-8
# 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 utils for Branch-and-Bound algorithms.
Contains for example algorithm to evaluate the inputs that concretize the
backward linear bounds.
"""
from typing import Mapping, Tuple
import jax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import bound_utils
from jax_verify.src import graph_traversal
from jax_verify.src import utils
from jax_verify.src.linear import backward_crown
from jax_verify.src.linear import linear_relaxations
from jax_verify.src.types import Index, Nest, Tensor # pylint: disable=g-multiple-import
class NominalEvaluateConcretizingInputAlgorithm(
bound_propagation.PropagationAlgorithm[Tensor]):
"""Find the input concretizing a backward linear transform and evaluate it.
"""
def __init__(self,
intermediate_bounds: Mapping[Index, Tuple[Tensor, Tensor]],
backward_transform: backward_crown.LinearBoundBackwardTransform):
self._forward_bnd_algorithm = bound_propagation.ForwardPropagationAlgorithm(
bound_utils.FixedBoundApplier(intermediate_bounds))
self._backward_transform = backward_transform
def propagate(self, graph: graph_traversal.PropagationGraph,
*bounds: Nest[graph_traversal.GraphInput]):
assert len(graph.outputs) == 1
(out,), bound_env = self._forward_bnd_algorithm.propagate(graph, *bounds)
max_output = (out.upper == out.upper.max()).astype(jnp.float32)
max_output = jnp.expand_dims(max_output, 0)
initial_linear_expression = backward_crown.identity(-max_output)
flat_inputs, _ = jax.tree_util.tree_flatten(*bounds)
bound_inputs = [inp for inp in flat_inputs
if isinstance(inp, bound_propagation.Bound)]
input_nodes_indices = [(i,) for i in range(len(bound_inputs))]
inputs_linfuns, back_env = graph.backward_propagation(
self._backward_transform, bound_env,
{graph.outputs[0]: initial_linear_expression},
input_nodes_indices)
concretizing_bound_inputs = []
for input_linfun, inp_bound in zip(inputs_linfuns, bound_inputs):
if input_linfun is not None:
conc_inp = minimizing_concretizing_input(input_linfun, inp_bound)
concretizing_bound_inputs.append(conc_inp[0])
def eval_model(*graph_inputs):
# We are going to only pass Tensor.
# Forward propagation simply evaluate the primitive when there is no
# bound inputs.
outvals, _ = graph.forward_propagation(None, graph_inputs) # pytype: disable=wrong-arg-types
return outvals
eval_model_boundinps = utils.bind_nonbound_args(eval_model,
*flat_inputs)
nominal_outs = eval_model_boundinps(*concretizing_bound_inputs)
return nominal_outs, back_env
def minimizing_concretizing_input(
backward_linexp: linear_relaxations.LinearExpression,
input_bound: bound_propagation.Bound) -> Tensor:
"""Get the input that concretize the backward bound to its lower bound.
Args:
backward_linexp: Coefficients of linear functions. The leading batch
dimension corresponds to different output neurons that need to be
concretized.
input_bound: Bound on the activations of that layer. Its shape should
match the coefficients of the linear functions to concretize.
Returns:
concretizing_inp: The input that correspond to the lower bound of the
linear function given by backward_linexp.
"""
return concretizing_input_interval_bounds(backward_linexp, input_bound)
def concretizing_input_interval_bounds(
backward_linexp: linear_relaxations.LinearExpression,
input_bound: bound_propagation.Bound) -> Tensor:
"""Compute the inputs that achieves the lower bound of a linear function."""
act_lower = jnp.expand_dims(input_bound.lower, 0)
act_upper = jnp.expand_dims(input_bound.upper, 0)
return jnp.where(backward_linexp.lin_coeffs > 0., act_lower, act_upper)
| jax_verify-master | jax_verify/src/branching/branch_utils.py |
# coding=utf-8
# 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.
"""Strategies for selecting the neuron on which to branch."""
import abc
import collections
import enum
import functools
import math
from typing import Any, Callable, Mapping, NamedTuple, Optional, Sequence, Tuple, Union
import jax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import bound_utils
from jax_verify.src import graph_traversal
from jax_verify.src import synthetic_primitives
from jax_verify.src.branching import backpropagation
from jax_verify.src.linear import linear_relaxations
from jax_verify.src.types import Index, Nest, Primitive, SpecFn, Tensor # pylint: disable=g-multiple-import
BranchDecision = NamedTuple('BranchDecision', [
('node_index', Index),
('neuron_index', int),
('branch_val', float),
('is_upper', int),
])
BranchPlane = NamedTuple('BranchPlane', [
('lower_branch', BranchDecision),
('upper_branch', BranchDecision)
])
BranchingDecisionList = Sequence[BranchDecision]
JittableBranchingDecisions = NamedTuple('JittableBranchingDecisions', [
('node_indices', Tensor),
('neuron_indices', Tensor),
('branch_vals', Tensor),
('is_upper_branch', Tensor)])
InputAnalysis = Any
ScoringInputs = Any
BranchHeuristicInputs = Mapping[str, Any]
BranchVal = Union[Tensor, Tuple[Tensor, Tensor]]
relaxation_area = lambda lb, ub: -ub * lb
mid_point = lambda lb, ub: (lb + ub) / 2.0
class AnalysisType(enum.Enum):
RELU_INDICES = 'relu_indices'
SENSITIVITY = 'sensitivity'
BOUND_INFO = 'bound_info'
GRAD_SENSITIVITY = 'grad_sensitivity'
class BranchNeuronSelector(metaclass=abc.ABCMeta):
"""Strategy for selecting the neuron on which to branch."""
@abc.abstractmethod
def analyse_inputs(
self,
spec_fn: SpecFn,
*init_bound: Nest[graph_traversal.GraphInput],
) -> InputAnalysis:
"""Performs pre-computation for an input.
The output of this will remain the same throughout the verification
procedure, and not be dependent on the current state of the branch and
bound algorithm.
Args:
spec_fn: Network under verification, including specification (objective).
*init_bound: Interval bounds on the input tensor(s).
Returns:
input_analysis: Pre-computed input-dependent data.
"""
@abc.abstractmethod
def score_neurons(
self,
input_analysis: InputAnalysis,
heuristic_inputs: BranchHeuristicInputs,
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
"""Compute branching scores for all neurons.
Args:
input_analysis: Result of the analysis of the inputs.
heuristic_inputs: Statistics depending on the current state of the branch
and bound tree, based on which the branching decision needs to be made.
This will for example contain the intermediate bounds of the networks,
but may contain additional information.
Returns:
scores: Score for each graph node.
branch_vals: Critical values of all neurons for each graph node. If `None`
then simply use zero for all critical values.
"""
def selector_scoring_fn(
spec_fn: SpecFn,
branch_neuron_selector: BranchNeuronSelector,
heuristic_inputs: BranchHeuristicInputs,
*jit_input_bounds: Nest[bound_propagation.JittableInputBound]
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
"""Score the neurons in a jittable fashion for a BranchNeuronSelector.
The best way to use this function is to bind the first two arguments at the
beginning, and then to jit it, so as to have the neuron scoring be jittable.
Args:
spec_fn: Function whose bounds we are trying to obtain.
branch_neuron_selector: Strategy that we use for branching.
heuristic_inputs: Statistics depending on the current state of the branch
and bound tree.
*jit_input_bounds: Bounds on the inputs.
Returns:
scores_and_branch_vals: Score and branching values for each possible
branching decision throughout the network.
"""
input_bounds = bound_propagation.unjit_inputs(*jit_input_bounds)
input_analysis = branch_neuron_selector.analyse_inputs(
spec_fn, *input_bounds)
return branch_neuron_selector.score_neurons(input_analysis, heuristic_inputs)
class NodeSelector(BranchNeuronSelector, metaclass=abc.ABCMeta):
"""Component capable of handling branching for a specific type of Nodes."""
@abc.abstractmethod
def analysis_type(self) -> AnalysisType:
"""Returns the type of analysis required by the Selector.
The value returned from this function will be used to determine what the
inputs to `score_handled_nodes` should be.
Every NodeSelector that returns the same value will receive the same inputs
to compute the scores with. This allows to share computation between
different NodeSelector that have similar requirements, rather than
recomputing the `preprocess_heurisitics` several times.
"""
def score_neurons(
self,
input_analysis: InputAnalysis,
heuristic_inputs: BranchHeuristicInputs,
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
score_inps = self.preprocess_heuristics(input_analysis, heuristic_inputs)
return self.score_handled_nodes(score_inps)
def preprocess_heuristics(
self,
input_analysis: InputAnalysis,
heuristic_inputs: BranchHeuristicInputs,
) -> ScoringInputs:
"""Performs preprocessing of the analysis.
This may be shared by several NodeSelector if they have the same type.
Through the intermediate bounds that are given, this will depend on the
current node in the branch and bound tree that is being branched on.
By default, if this function is not overloaded, it will return exactly its
arguments.
Args:
input_analysis: Result of the analysis of the inputs.
heuristic_inputs: Statistics depending on the current state of the branch
and bound tree, based on which the branching decision needs to be made.
This will for example contain the intermediate bounds of the networks,
but may contain additional information.
Returns:
scoring_inputs: Inputs that the score_handled_nodes function require.
"""
return input_analysis, heuristic_inputs
@abc.abstractmethod
def score_handled_nodes(
self,
scoring_inputs: ScoringInputs,
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
"""Returns the branching decisions as well as a score for each of them."""
class CompositeNodeSelector(BranchNeuronSelector):
"""Combine NodeSelectors that propose branches on different network parts."""
def __init__(self,
selectors: Sequence[NodeSelector],
coefficients: Sequence[float]):
super().__init__()
self._selectors = selectors
self._coefficients = coefficients
def analyse_inputs(self, spec_fn: SpecFn, *init_bounds) -> InputAnalysis:
input_analyses = {}
for selector in self._selectors:
if selector.analysis_type() not in input_analyses:
input_analyses[selector.analysis_type()] = selector.analyse_inputs(
spec_fn, *init_bounds)
return input_analyses
def score_neurons(
self,
input_analysis: InputAnalysis,
heuristic_inputs: BranchHeuristicInputs,
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
weigh_scores = lambda weight, x: weight * x
scoring_inputs = {}
scores = {}
branch_vals = {}
for selector, coeff in zip(self._selectors, self._coefficients):
analysis_type = selector.analysis_type()
if selector.analysis_type not in scoring_inputs:
scoring_inputs[analysis_type] = selector.preprocess_heuristics(
input_analysis[analysis_type], heuristic_inputs)
selector_scores, selector_branch_vals = selector.score_handled_nodes(
scoring_inputs[analysis_type])
mul_by_coeff = functools.partial(weigh_scores, coeff)
weighted_selector_scores = jax.tree_map(mul_by_coeff,
selector_scores)
if set(scores) & set(weighted_selector_scores):
raise ValueError('Several branching heuristics are operating on the'
'same nodes.')
scores.update(weighted_selector_scores)
branch_vals.update(selector_branch_vals)
return scores, branch_vals
class ReluSelector(NodeSelector):
"""Strategy for selecting the neuron on which to branch."""
def analysis_type(self) -> AnalysisType:
return AnalysisType.RELU_INDICES
def analyse_inputs(
self,
spec_fn: SpecFn,
*init_bound: Nest[graph_traversal.GraphInput],
) -> InputAnalysis:
"""Performs pre-computation for an input."""
graph_nodes = computation_graph_nodes(spec_fn, *init_bound)
relu_preact_indices = primitive_preact_indices(
graph_nodes, [synthetic_primitives.relu_p])
if not relu_preact_indices:
raise ValueError('Cannot branch because this network has no ReLUs.')
return relu_preact_indices
def score_handled_nodes(
self,
scoring_inputs: ScoringInputs
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
"""Compute ambiguity scores for ReLU pre-activation."""
preact_indices, heuristic_inputs = scoring_inputs
bounds = heuristic_inputs['intermediate_bounds']
def masked_ambiguity(lower: Tensor, upper: Tensor) -> Tensor:
ambiguous = (lower < 0.) & (upper > 0.)
return jnp.where(ambiguous, relaxation_area(lower, upper), -jnp.inf)
return (
{index: masked_ambiguity(*bounds[index]) for index in preact_indices},
{index: jnp.zeros_like(bounds[index][0]) for index in preact_indices},
)
class BoundInfoSelector(NodeSelector):
"""Branching strategies specialised depending on the type of Node."""
def analysis_type(self) -> AnalysisType:
return AnalysisType.BOUND_INFO
def analyse_inputs(
self,
spec_fn: SpecFn,
*init_bound: Nest[graph_traversal.GraphInput],
) -> InputAnalysis:
"""Performs pre-computation for an input."""
bound_info = {}
input_info = bound_input_info(*init_bound)
bound_info.update(input_info)
graph_nodes = computation_graph_nodes(spec_fn, *init_bound)
bound_info['relu_preact_indices'] = primitive_preact_indices(
graph_nodes, [synthetic_primitives.relu_p])
bound_info['sign_preact_indices'] = primitive_preact_indices(
graph_nodes, [jax.lax.sign_p])
return bound_info
class InputSelector(BoundInfoSelector):
"""Strategy for selecting the input dimension on which to branch."""
def __init__(
self,
ambiguity: Callable[[Tensor, Tensor], Tensor]):
super().__init__()
def unfixed_ambiguity(lower: Tensor, upper: Tensor) -> Tensor:
unfixed = upper != lower
return jnp.where(unfixed, ambiguity(lower, upper), -jnp.inf)
self._ambiguity = unfixed_ambiguity
def score_handled_nodes(
self,
scoring_inputs: ScoringInputs,
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, Tensor]]:
"""Compute ambiguity scores for inputs."""
input_analysis, heuristic_inputs = scoring_inputs
input_indices = input_analysis['input_indices']
bounds = heuristic_inputs['intermediate_bounds']
return (
{index: self._ambiguity(*bounds[index]) for index in input_indices},
{index: mid_point(*bounds[index]) for index in input_indices},
)
class SensitivitySelector(NodeSelector, metaclass=abc.ABCMeta):
"""Neuron selection strategy based on estimated influence on output objective.
"""
def __init__(
self,
ambiguity_agg: str = 'min',
sensitivity_of_max: bool = True):
"""Initialises the neuron selector for a given network.
Args:
ambiguity_agg: Method ('min', 'max', 'avg') for combining the two
possible ambiguity measures of a ReLU relaxation. The two possibilities
arise from the choice of triangle: its vertices are (lb,0), (ub,ub),
and _either_ (ub,0) _or_ (lb,lb).
sensitivity_of_max: Whether to compute the neuron sensitivity with respect
to the worst bound. By default, will compute the sensitivity with
respect to all outputs.
"""
super().__init__()
self._ambiguity_agg = ambiguity_agg
self._sensitivity_of_max = sensitivity_of_max
def analysis_type(self) -> AnalysisType:
return AnalysisType.SENSITIVITY
def analyse_inputs(
self,
spec_fn: SpecFn,
*init_bounds: Nest[graph_traversal.GraphInput],
) -> InputAnalysis:
"""Performs pre-computation for an input."""
graph_nodes = computation_graph_nodes(spec_fn, *init_bounds)
preact_indices = primitive_preact_indices(graph_nodes,
[synthetic_primitives.relu_p])
bound_info = bound_input_info(*init_bounds)
input_indices = bound_info['input_indices']
if (not preact_indices) and (not input_indices):
raise ValueError('Cannot branch because this network has no ReLUs'
' and no branchable inputs.')
# Extract the bias terms.
inspector = bound_utils.GraphInspector()
output_node, _ = bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(inspector),
spec_fn, *init_bounds)
biases = {}
for node in inspector.nodes.values():
# Forward-propagate the bias.
if node.is_input():
input_bound: graph_traversal.InputBound = node.args[0]
bias = jnp.zeros_like(input_bound.lower)
else:
is_bound = lambda b: isinstance(b, bound_propagation.Bound)
arg_biases = [
jnp.zeros_like(biases[arg.index]) if is_bound(arg) else arg
for arg in node.args]
bias = node.primitive.bind(*arg_biases, **node.kwargs)
# Network inputs and ReLU outputs have no bias.
if node.is_input() or node.primitive == synthetic_primitives.relu_p:
bias = jnp.zeros_like(bias)
biases[node.index] = bias
return (spec_fn, init_bounds, graph_nodes, bound_info,
output_node.index, biases)
def preprocess_heuristics(
self,
input_analysis: InputAnalysis,
heuristic_inputs: BranchHeuristicInputs,
) -> Tuple[InputAnalysis, BranchHeuristicInputs, Mapping[Index, Tensor]]:
"""Compute scores to determine the influential ReLUs on which to branch."""
(spec_fn, init_bounds, graph_nodes, bound_info,
output_node_index, _) = input_analysis
bounds = heuristic_inputs['intermediate_bounds']
preact_indices = primitive_preact_indices(graph_nodes,
[synthetic_primitives.relu_p,
jax.lax.sign_p])
input_indices = bound_info['input_indices']
output_sensitivity = None
if self._sensitivity_of_max:
output_upper = bounds[output_node_index][1]
worst_output = (output_upper == output_upper.max())
output_sensitivity = -worst_output.astype(jnp.float32)
sensitivity_targets = preact_indices + input_indices
sensitivity_algorithm = backpropagation.SensitivityAlgorithm(
bound_utils.FixedBoundApplier(bounds),
sensitivity_targets, output_sensitivity)
bound_propagation.bound_propagation(
sensitivity_algorithm, spec_fn, *init_bounds)
sensitivities = {index: sens for index, sens in zip(
sensitivity_targets, sensitivity_algorithm.target_sensitivities)}
return input_analysis, heuristic_inputs, sensitivities
class SmartReluSelector(SensitivitySelector):
"""Neuron selection strategy based on estimated influence on output objective.
"""
def score_handled_nodes(
self,
scoring_inputs: Tuple[InputAnalysis,
BranchHeuristicInputs,
Mapping[Index, Tensor]],
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
"""Compute neuron scores for a given node, given sensitivity and bounds.
This implements Equation (9) in "Branch and Bound for Piecewise Linear
Neural Network Verification", https://arxiv.org/pdf/1909.06588.pdf.
Args:
scoring_inputs: Tuple composed of the results of the input analysis, the
statistics at that point of the branch-and-bound tree, as well as the
computed sensitivities
Returns:
scores: Scores for branching on each ReLU of the network.
branch_vals: Branching values for the ReLUs (always 0).
"""
input_analysis, heuristic_inputs, sensitivities = scoring_inputs
_, _, graph_nodes, _, _, biases = input_analysis
bounds = heuristic_inputs['intermediate_bounds']
relu_preact_indices = primitive_preact_indices(
graph_nodes, [synthetic_primitives.relu_p])
scores = {}
branch_vals = {}
for index in relu_preact_indices:
lower_bound, upper_bound = bounds[index]
bias = biases.get(index, 0.)
sensitivity = sensitivities[index]
# Only consider 'ambiguous' ReLUs: those whose input bounds straddle zero.
ambiguous = jnp.logical_and(lower_bound < 0., upper_bound > 0.)
# For excluded ReLUs, adjust bounds to a safe non-zero value.
upper_bound = jnp.maximum(upper_bound, jnp.finfo(jnp.float32).eps)
bias_score = aggregate_ambiguities(self._ambiguity_agg)(
sensitivity * bias,
(sensitivity * lower_bound / upper_bound) * bias)
intercept_score = -lower_bound * jnp.maximum(sensitivity, 0.)
scores[index] = jnp.where(ambiguous,
jnp.abs(bias_score + intercept_score),
-jnp.inf)
branch_vals[index] = jnp.zeros_like(lower_bound)
return scores, branch_vals
class SmartSignSelector(SensitivitySelector):
"""Neuron selection strategy based on estimated influence on output objective.
"""
def score_handled_nodes(
self,
scoring_inputs: Tuple[InputAnalysis,
BranchHeuristicInputs,
Mapping[Index, Tensor]],
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
"""Compute neuron scores for a given node, given sensitivity and bounds.
This implements Equation (9) in "Branch and Bound for Piecewise Linear
Neural Network Verification", https://arxiv.org/pdf/1909.06588.pdf.
Args:
scoring_inputs: Tuple composed of the results of the input analysis, the
statistics at that point of the branch-and-bound tree, as well as the
computed sensitivities
Returns:
scores: Scores for branching on each ReLU of the network.
branch_vals: Branching values for the ReLUs (always 0).
"""
input_analysis, heuristic_inputs, sensitivities = scoring_inputs
_, _, graph_nodes, _, _, _ = input_analysis
bounds = heuristic_inputs['intermediate_bounds']
sign_preact_indices = primitive_preact_indices(
graph_nodes, [jax.lax.sign_p])
scores = {}
branch_vals = {}
for index in sign_preact_indices:
lower_bound, upper_bound = bounds[index]
sensitivity = sensitivities[index]
# Only consider 'ambiguous' sign: those whose input bounds straddle zero.
ambiguous = jnp.logical_and(lower_bound < 0., upper_bound > 0.)
scores[index] = jnp.where(ambiguous, 2*jnp.abs(sensitivity), -jnp.inf)
branch_vals[index] = jnp.zeros_like(lower_bound)
return scores, branch_vals
class SensitivityReluSelector(SensitivitySelector):
"""Neuron selection strategy based on estimated influence on output objective.
"""
def score_handled_nodes(
self,
scoring_inputs: Tuple[InputAnalysis,
BranchHeuristicInputs,
Mapping[Index, Tensor]],
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
"""Compute neuron scores for a given node, given sensitivity and bounds.
This uses the sensitivity to estimate the impact of a change in what the K&W
bound would be, based on a local approximation.
This does not take into account:
- The impact on subsequent bounds being tightened.
- The impact on sensitivities going further towards the beginnning of the
network.
It only consider the impact involving the sensitivity at node preact_index.
The formula for the K&W bound is:
bound = -sum_{k=1}^n nu_{k+1}b_k - u_0 [nuhat_1]+ + l_0 [nuhat_1]-
+ sum_{k=2}^n u_k * l_k/(u_k - l_k) * [nuhat_k]+
where nu / nuhat are the sensitivities.
for ambiguous relu, nu = u/(u-l) * nuhat
for positive relu, nu = nuhat
for negative relu, nu = 0
Args:
scoring_inputs: Tuple composed of the results of the input analysis, the
statistics at that point of the branch-and-bound tree, as well as the
computed sensitivities
Returns:
scores: Scores for branching on each ReLU of the network.
branch_vals: Tensor of zero values, as this is the value over which ReLU
branch.
"""
input_analysis, heuristic_inputs, sensitivities = scoring_inputs
bounds = heuristic_inputs['intermediate_bounds']
_, _, graph_nodes, _, _, biases = input_analysis
relu_preact_indices = primitive_preact_indices(
graph_nodes, [synthetic_primitives.relu_p])
scores = {}
branch_vals = {}
for index in relu_preact_indices:
lower_bound, upper_bound = bounds[index]
bias = biases.get(index, 0.)
sensitivity = sensitivities[index]
# Only consider 'ambiguous' ReLUs: those whose input bounds straddle zero.
ambiguous = jnp.logical_and(lower_bound < 0., upper_bound > 0.)
# For excluded ReLUs, adjust bounds to a safe non-zero value.
upper_bound = jnp.maximum(upper_bound, jnp.finfo(jnp.float32).eps)
nuhat = sensitivity * (upper_bound - lower_bound) / upper_bound
# In the case of an ambiguous ReLU, the contribution to the bound is:
# nu = sensitivity = u / (u-l) * nuhat
score_amb = (sensitivity * bias
+ jnp.maximum(sensitivity, 0.) * lower_bound)
# If we are blocking the ReLU to be on, the contribution to the bound is:
# (as nu = nuhat)
score_on = nuhat * bias + jnp.maximum(nuhat, 0.) * lower_bound
# If we are blocking the ReLU to be off, the contribution to the bound is:
# (as nu = 0)
score_off = jnp.maximum(nuhat, 0.) * lower_bound
# We're going to compare the estimated improvements in bounds that we
# would gain by splitting on the ReLU, aggregating them in the chosen way.
# score_amb is the contribution to the upper bound as the ReLU was
# ambiguous so its difference with score_on and score_off represent the
# expected improvement we would get by splitting.
improvements = aggregate_ambiguities(self._ambiguity_agg)(
jnp.maximum(score_amb - score_on, 0.),
jnp.maximum(score_amb - score_off, 0.))
scores[index] = jnp.where(ambiguous, improvements, -jnp.inf)
branch_vals[index] = jnp.zeros_like(lower_bound)
return scores, branch_vals
class SensitivityLinfSelector(SensitivitySelector):
"""Input selection strategy based on estimated influence on output objective.
"""
def score_handled_nodes(
self,
scoring_inputs: Tuple[InputAnalysis,
BranchHeuristicInputs,
Mapping[Index, Tensor]],
) -> Tuple[Mapping[Index, Tensor], Mapping[Index, BranchVal]]:
"""Compute Input branching scores given sensitivity and bounds.
This only relies on the sensitivity of the output node and ignores the
impact on intermediate bounds.
Args:
scoring_inputs: Tuple composed of the results of the input analysis, the
statistics at that point of the branch-and-bound tree, as well as the
computed sensitivities
Returns:
scores: Scores for branching on each L_inf bound input of the network.
branch_vals: Mid-point for the interval bounds
"""
input_analysis, heuristic_inputs, sensitivities = scoring_inputs
bounds = heuristic_inputs['intermediate_bounds']
_, _, _, bound_info, _, _ = input_analysis
scores = {}
branch_vals = {}
for index in bound_info['input_indices']:
if index in bound_info['index_to_nze']:
# Skip the L0 bounds
continue
lower_bound, upper_bound = bounds[index]
sensitivity = sensitivities[index]
unfixed = lower_bound != upper_bound
# Given that the sensitivity is based on propagating the same way
# through the upper and lower bound of activation, we only have
# one relaxation.
# The bound it corresponds to is sensitivity * inp.
# Assuming the sensitivity is constant, depending on the sign of the
# coordinate, it will either increase the final bound in the lower branch,
# or in the upper branch, based on the amount of movement.
improvement = jnp.abs(sensitivity) * (upper_bound - lower_bound) / 2
scores[index] = jnp.where(unfixed, improvement, -jnp.inf)
branch_vals[index] = 0.5 * (lower_bound + upper_bound)
return scores, branch_vals
def aggregate_ambiguities(
ambiguity_agg: str) -> Callable[[Tensor, Tensor], Tensor]:
if ambiguity_agg == 'min':
return jnp.minimum
elif ambiguity_agg == 'max':
return jnp.maximum
elif ambiguity_agg == 'avg':
return lambda x, y: (x+y)/2.
else:
raise ValueError('Unknown ambiguity aggregation method: {ambiguity_agg}')
def bound_input_info(
*init_bound: Nest[graph_traversal.GraphInput],
) -> Mapping[str, Any]:
"""Returns useful information on inputs suitable for branching."""
is_bound = lambda b: isinstance(b, graph_traversal.InputBound)
input_count = 0
index = graph_traversal.IndexCounter()
flat_bounds, _ = jax.tree_util.tree_flatten(init_bound, is_leaf=is_bound)
input_indices = []
index_to_input = {}
for bound in flat_bounds:
if is_bound(bound):
if isinstance(bound, bound_propagation.IntervalBound):
index_to_input[index.as_tuple()] = input_count
else:
raise ValueError('Unknown input bound type')
input_indices.append(index.as_tuple())
index.incr()
input_count = input_count + 1
return {
'input_indices': input_indices,
'index_to_input': index_to_input,
}
def computation_graph_nodes(
spec_fn: SpecFn,
*init_bound: Nest[graph_traversal.GraphInput],
) -> Mapping[Index, bound_utils.GraphNode]:
"""Extract a mapping from index to primitives."""
inspector = bound_utils.GraphInspector()
bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(inspector),
spec_fn, *init_bound)
return inspector.nodes
def primitive_preact_indices(
graph_nodes: Mapping[Index, bound_utils.GraphNode],
target_primitives: Sequence[Primitive],
) -> Sequence[Index]:
"""Extract the index of the input to the required primitives."""
preact_indices = []
for _, node in graph_nodes.items():
if node.primitive in target_primitives:
preact_indices.append(node.args[0].index)
return preact_indices
@jax.jit
def identify_highest_scoring_neuron(
all_scores: Sequence[Tensor]
)-> Tuple[float, int, int]:
"""Identifies the most fitting neuron on which to branch.
Args:
all_scores: Scores for neurons in candidate graph nodes, indicating
fitness for branching.
Returns:
max_score: score of the highest scoring neuron.
node_pos: Position of the node containing the highest scoring neuron.
neuron_idx: Location within the flattened tensor of the selected neuron.
"""
# Select the pre-activation neuron with the greatest ambiguity.
# First select the node.
all_max_scores = jnp.array([jnp.amax(score) for score in all_scores])
all_neuron_index = jnp.array([jnp.argmax(score) for score in all_scores])
max_score = jnp.amax(all_max_scores)
node_pos = jnp.argmax(all_max_scores)
# Next select the highest-scoring neuron within that node.
neuron_idx = all_neuron_index[node_pos]
return max_score, node_pos, neuron_idx
def highest_score_branch_plane(
scores: Mapping[Index, Tensor],
branch_vals: Mapping[Index, BranchVal],
) -> Optional[BranchPlane]:
"""Determines the neuron on which to branch.
Args:
scores: Score for each graph node.
branch_vals: Critical values of all neurons for each graph node.
Returns:
`None` if no suitable neuron found, otherwise:
node_index: Graph node containing the selected neuron.
neuron_index: Location within the flattened tensor of the selected neuron.
branch_val: Critical value of the selected neuron on which to branch.
"""
indices, flat_scores = zip(*scores.items())
max_score, max_index, neuron_idx = identify_highest_scoring_neuron(
flat_scores)
index = indices[max_index]
if max_score == -jnp.inf:
return None
return make_branch_plane(index, neuron_idx, branch_vals)
@jax.jit
def get_branch_vals(
neuron_idx: int,
branch_vals: BranchVal
) -> Tuple[float, float]:
"""Get the lower and upper branching values associated with a neuron index."""
neuron_branch_val = lambda bvals: jnp.reshape(bvals, (-1,))[neuron_idx]
if isinstance(branch_vals, tuple):
lower_branch_vals, upper_branch_vals = branch_vals
else:
lower_branch_vals = upper_branch_vals = branch_vals
lower_branch_val = neuron_branch_val(lower_branch_vals)
upper_branch_val = neuron_branch_val(upper_branch_vals)
return lower_branch_val, upper_branch_val
def make_branch_plane(
index: Index,
neuron_idx: int,
branch_vals: Mapping[Index, BranchVal],
) -> BranchPlane:
"""Returns branch plane with the specified content."""
index_branch_vals = branch_vals[index]
lower_branch_val, upper_branch_val = get_branch_vals(neuron_idx,
index_branch_vals)
return BranchPlane(
BranchDecision(index, neuron_idx, lower_branch_val, -1),
BranchDecision(index, neuron_idx, upper_branch_val, 1))
def concrete_branch_bounds(
root_bounds: Mapping[Index, Tuple[Tensor, Tensor]],
branching_decisions: BranchingDecisionList,
) -> Mapping[Index, Tuple[Tensor, Tensor]]:
"""Materialises a branch's decision path as concrete interval bounds.
Args:
root_bounds: Initial concrete bounds for each graph node; may be vacuous.
branching_decisions: Specifies a branch's decision path.
Returns:
Copy of root_bounds, refined according to the current branch constraints.
"""
branch_bounds = dict(root_bounds)
for node, neuron_idx, branch_val, side in branching_decisions:
lower, upper = branch_bounds[node]
if side > 0:
lower = _set_element(lower, neuron_idx, branch_val) # pytype: disable=wrong-arg-types # jax-ndarray
else:
upper = _set_element(upper, neuron_idx, branch_val) # pytype: disable=wrong-arg-types # jax-ndarray
branch_bounds[node] = lower, upper
return branch_bounds
def _set_element(x: Tensor, i: int, v: Tensor) -> Tensor:
"""Returns a copy of `x` with its `i`th element set to v."""
shape = x.shape
x = jnp.reshape(x, [-1])
y = x.at[i].set(v)
return jnp.reshape(y, shape)
def max_index_depth(
spec_fn: SpecFn,
*input_bounds: graph_traversal.GraphInput) -> int:
"""Geth the maximum number of integers to use to identify a node."""
inspector = bound_utils.GraphInspector()
bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(inspector),
spec_fn, *input_bounds)
return max(len(node.index) for node in inspector.nodes.values())
def split_branching_decisions(
branching_decisions: BranchingDecisionList,
index_to_input: Mapping[Index, int],
) -> Tuple[BranchingDecisionList, BranchingDecisionList]:
"""Split branching decisions into activation based and input based."""
activation_branching_decisions = []
input_branching_decisions = []
for branch_dec in branching_decisions:
if branch_dec.node_index in index_to_input:
input_branching_decisions.append(branch_dec)
else:
activation_branching_decisions.append(branch_dec)
return activation_branching_decisions, input_branching_decisions
def branching_decisions_tensors(
branching_decisions: BranchingDecisionList,
initial_max_branching_depth: int,
max_idx_depth: int
) -> JittableBranchingDecisions:
"""Create the tensor version of `branching_decisions`.
Args:
branching_decisions: List of branching decisions, where branching
decisions are a branching plane and an integer indicating whether it is
the upper or lower branch.
initial_max_branching_depth: Length of the tensors to use to represent the
branching decisions in jitted form. Padding will be added to the
`branching_decisions` elements to make it to that length. If the length
of `branching_decisions` is larger than this, we will instead pad to the
nearest power of two multiple of this.
max_idx_depth: Max number of coordinates that we will use to identify a
node in the computation graph.
Returns:
Tensorial representation of `branching_decisions`.
"""
node_indices = []
neuron_indices = []
branch_vals = []
is_upper_branch = []
for node_index, neuron_index, branch_val, side in branching_decisions:
node_indices.append(node_index + (0,)*(max_idx_depth - len(node_index)))
neuron_indices.append(neuron_index)
branch_vals.append(branch_val)
is_upper_branch.append(side > 0)
# Pad the tensors to one of the accepted lengths.
tensor_len = target_pad_length(len(branching_decisions),
initial_max_branching_depth)
while len(node_indices) < tensor_len:
node_indices.append((0,)*max_idx_depth)
neuron_indices.append(-1)
branch_vals.append(0.)
is_upper_branch.append(True)
return JittableBranchingDecisions(
jnp.array(node_indices, dtype=jnp.int32),
jnp.array(neuron_indices, dtype=jnp.int32),
jnp.array(branch_vals, dtype=jnp.float32),
jnp.array(is_upper_branch, dtype=jnp.bool_))
def target_pad_length(actual_length: int, pad_scale: int) -> int:
factor = actual_length / pad_scale
safe_factor = max(1, factor)
next_2pow = math.ceil(math.log2(safe_factor))
return int(pad_scale * (2 ** next_2pow))
def branch_inputs(
input_branching_decisions: BranchingDecisionList,
*input_bounds: Nest[graph_traversal.GraphInput],
) -> Nest[graph_traversal.GraphInput]:
"""Split input domain according to input branching decisions.
Args:
input_branching_decisions: Specifies a branch's decision path.
*input_bounds: Original input domain.
Returns:
Copy of input_bounds, refined according to the current branch constraints,
"""
is_bound = lambda b: isinstance(b, graph_traversal.InputBound)
input_bounds = bound_propagation.unjit_inputs(*input_bounds)
flat_bounds, _ = jax.tree_util.tree_flatten(input_bounds, is_leaf=is_bound)
per_input_lower_decisions = collections.defaultdict(list)
per_input_upper_decisions = collections.defaultdict(list)
for (node, neuron_idx, branch_val, side) in input_branching_decisions:
if side > 0:
# This decision modifies the lower bound.
per_input_lower_decisions[node].append((neuron_idx, branch_val))
else:
# This decision modifies the upper bound.
per_input_upper_decisions[node].append((neuron_idx, branch_val))
index = graph_traversal.IndexCounter()
new_flat_bounds = []
for bound in flat_bounds:
if is_bound(bound):
node_lower_decs = per_input_lower_decisions[index.as_tuple()]
if node_lower_decs:
lower_n_indices, lower_branch_vals = zip(*node_lower_decs)
lower_tensor_len = target_pad_length(len(lower_n_indices), 4)
lower_to_pad = lower_tensor_len - len(lower_n_indices)
lower_n_indices = lower_n_indices + (0,) * lower_to_pad
lower_branch_vals = lower_branch_vals + (-jnp.inf,) * lower_to_pad
new_lower = _impose_constraints('max', bound.lower,
jnp.array(lower_n_indices),
jnp.array(lower_branch_vals))
else:
new_lower = bound.lower
node_upper_decs = per_input_upper_decisions[index.as_tuple()]
if node_upper_decs:
upper_n_indices, upper_branch_vals = zip(*node_upper_decs)
upper_tensor_len = target_pad_length(len(upper_n_indices), 4)
upper_to_pad = upper_tensor_len - len(upper_n_indices)
upper_n_indices = upper_n_indices + (0,) * upper_to_pad
upper_branch_vals = upper_branch_vals + (jnp.inf,) * upper_to_pad
new_upper = _impose_constraints('min', bound.upper,
jnp.array(upper_n_indices),
jnp.array(upper_branch_vals))
else:
new_upper = bound.upper
if isinstance(bound, bound_propagation.IntervalBound):
new_flat_bounds.append(bound_propagation.IntervalBound(
new_lower, new_upper))
else:
raise ValueError('Unknown input bound type for branching.')
index.incr()
else:
new_flat_bounds.append(bound)
new_input_bounds = jax.tree_util.tree_unflatten(
jax.tree_util.tree_structure(input_bounds, is_leaf=is_bound),
new_flat_bounds)
return new_input_bounds
@jax.jit
def infeasible_bounds(*input_bounds: Nest[bound_propagation.JittableGraphInput]
) -> bool:
"""Return whether there is any infeasibility in a set of bounds."""
is_bound = lambda b: isinstance(b, bound_propagation.Bound)
input_bounds = bound_propagation.unjit_inputs(input_bounds)
flat_inputs, _ = jax.tree_util.tree_flatten(input_bounds, is_bound)
infeasible = False
for inp in flat_inputs:
if isinstance(inp, jnp.ndarray):
pass
elif is_bound(inp):
# Anything that is a bound should be checked for crossing between lower
# and upper bound.
infeasible = jnp.logical_or(infeasible, bounds_crossing(inp))
else:
raise ValueError('Unknown type of input.')
return infeasible # pytype: disable=bad-return-type # jax-types
def bounds_crossing(bound: bound_propagation.Bound, tol: float = 1e-6) -> bool:
"""Return a boolean tensor indicating whether any bounds are crossing."""
return (bound.upper - bound.lower < -tol).any()
@functools.partial(jax.jit, static_argnums=(0,))
def _impose_constraints(update_rule: str,
ini_tensor: Tensor,
indices: Tensor,
values: Tensor) -> Tensor:
"""Impose a set of constraints over various coordinates of a tensor.
Args:
update_rule: Either 'min' or 'max', indicate how to modify the given tensor.
ini_tensor: Tensor to update.
indices: Coordinates of the tensor that we are imposing constraints on.
values: Values of the constraint that we are imposing.
Returns:
updated_tensor
"""
shape = ini_tensor.shape
flat_tensor = jnp.reshape(ini_tensor, (-1,))
to_update = flat_tensor.at[indices]
if update_rule == 'max':
updated_flat_tensor = to_update.max(values)
elif update_rule == 'min':
updated_flat_tensor = to_update.min(values)
else:
raise ValueError('Unknown update rule.')
return jnp.reshape(updated_flat_tensor, shape)
def enforce_jittable_branching_decisions(
branching_decisions: JittableBranchingDecisions,
index: Index, bound: bound_propagation.Bound,
) -> bound_propagation.Bound:
"""Ensure that a bound is consistent with a list of branching decisions.
Args:
branching_decisions: List of constraints that need to be enforced.
index: Index of the node at which this bounds lives.
bound: Bound that need to be consistent with the constraints.
Returns:
enforced_bound: Modified version of `bound` guaranteed to respect the
constraints
"""
lay_idxs, neur_idxs, branch_vals, is_upper = branching_decisions
max_idx_depth = lay_idxs.shape[1]
index_tensor = jnp.array(index + (0,) * (max_idx_depth - len(index)))
layer_mask = (lay_idxs == index_tensor).all(axis=1)
update_lower = layer_mask & is_upper
update_upper = layer_mask & ~is_upper
update_low_val = jnp.where(update_lower, branch_vals, -jnp.inf)
update_upper_val = jnp.where(update_upper, branch_vals, jnp.inf)
flat_lower = jnp.reshape(bound.lower, [-1])
enforced_flat_lower = flat_lower.at[neur_idxs].max(update_low_val,
mode='drop')
enforced_lower = jnp.reshape(enforced_flat_lower, bound.lower.shape)
flat_upper = jnp.reshape(bound.upper, [-1])
enforced_flat_upper = flat_upper.at[neur_idxs].min(update_upper_val,
mode='drop')
enforced_upper = jnp.reshape(enforced_flat_upper, bound.upper.shape)
return bound_propagation.IntervalBound(enforced_lower, enforced_upper)
| jax_verify-master | jax_verify/src/branching/branch_selection.py |
# coding=utf-8
# 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.
"""Backpropagation of sensitivity values.
This computes a measure of dependence of the output objective upon each
intermediate value of a ReLU-based neural network. This sensitivity measure
is constructed by back-propagating through the network, and linearising
each ReLU.
This sensitivity measure is derived in "Provable Defenses via the Convex Outer
Adversarial Polytope", https://arxiv.org/pdf/1711.00851.pdf.
"""
import functools
from typing import Mapping, Optional, Sequence, Union
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import synthetic_primitives
from jax_verify.src.types import Index, Nest, Primitive, Tensor # pylint: disable=g-multiple-import
def _sensitivity_linear_op(
primitive: Primitive,
outval: Tensor,
*args: Union[bound_propagation.Bound, Tensor],
**kwargs) -> Sequence[Optional[Tensor]]:
"""Back-propagates sensitivity through a linear Jax operation.
For linear ops, sensitivity of the inputs is computed by applying the
transpose of the op to the sensitivity of the outputs.
Args:
primitive: Linear (or affine) primitive op through which to backprop.
outval: Sensitivity value for the op's output.
*args: Inputs to the linear op, in the form of interval bounds (for
variables) and primal values (for constants).
**kwargs: Additional parameters to the linear op.
Returns:
Sensitivitity values for the op's variable inputs. Entries will be `None`
for constant inputs.
"""
# Use auto-diff to perform the transpose-product.
primal_args = [
jnp.zeros_like(arg.lower)
if isinstance(arg, bound_propagation.Bound) else arg
for arg in args]
_, vjp = jax.vjp(functools.partial(primitive.bind, **kwargs), *primal_args)
return vjp(outval)
def _sensitivity_relu(
outval: Tensor,
inp: bound_propagation.Bound
) -> Tensor:
"""Back-propagates sensitivity through a ReLU.
For the purposes of back-propagating sensitivity,
the ReLU uses a linear approximation given by the chord
from (lower_bound, ReLU(lower_bound)) to (upper_bound, ReLU(upper_bound))
Args:
outval: Sensitivity values for the ReLU outputs.
inp: Interval bounds on the ReLU input
Returns:
Sensitivity values for the ReLU input.
"""
# Arrange for always-blocking and always-passing ReLUs to give a slope
# of zero and one respectively.
lower_bound = jnp.minimum(inp.lower, 0.)
upper_bound = jnp.maximum(inp.upper, 0.)
chord_slope = upper_bound / jnp.maximum(
upper_bound - lower_bound, jnp.finfo(jnp.float32).eps)
return chord_slope * outval, # pytype: disable=bad-return-type # jax-ndarray
_LINEAR_PRIMITIVES: Sequence[Primitive] = [
*bound_propagation.AFFINE_PRIMITIVES,
*bound_propagation.RESHAPE_PRIMITIVES,
lax.div_p,
]
def _build_sensitivity_ops() -> Mapping[
Primitive, graph_traversal.PrimitiveBacktransformFn]:
"""Builds functions to back-prop 'sensitivity' through individual primitives.
Returns:
Sensitivity computation functions, in the form suitable to be passed to
`PropagationGraph.backward_propagation()`.
"""
sensitivity_primitive_ops = {
primitive: functools.partial(_sensitivity_linear_op, primitive)
for primitive in _LINEAR_PRIMITIVES}
sensitivity_primitive_ops[synthetic_primitives.relu_p] = _sensitivity_relu
# Through the sign function, we don't really have a sensitivity.
sensitivity_sign = lambda outval, _: (jnp.zeros_like(outval),)
sensitivity_primitive_ops[jax.lax.sign_p] = sensitivity_sign
return sensitivity_primitive_ops
sensitivity_backward_transform = graph_traversal.BackwardOpwiseTransform(
_build_sensitivity_ops(), sum)
class SensitivityAlgorithm(bound_propagation.PropagationAlgorithm[Tensor]):
"""Propagation algorithm computing output sensitivity to intermediate nodes."""
def __init__(
self,
forward_bound_transform: bound_propagation.BoundTransform,
sensitivity_targets: Sequence[Index],
output_sensitivity: Optional[Tensor] = None):
"""Define the sensitivity that needs to be computed.
Args:
forward_bound_transform: Transformation to use to compute intermediate
bounds.
sensitivity_targets: Index of the nodes for which we want to obtain
sensitivities.
output_sensitivity: (Optional) Linear coefficients for which we want the
sensitivity, defined over the output.
"""
self._forward_bnd_algorithm = bound_propagation.ForwardPropagationAlgorithm(
forward_bound_transform)
self._output_sensitivity = output_sensitivity
self._sensitivity_targets = sensitivity_targets
self.target_sensitivities = []
def propagate(self, graph: graph_traversal.PropagationGraph,
*bounds: Nest[graph_traversal.GraphInput]):
assert len(graph.outputs) == 1
out, bound_env = self._forward_bnd_algorithm.propagate(graph, bounds)
if self._output_sensitivity is not None:
output_sensitivity = self._output_sensitivity
else:
output_sensitivity = -jnp.ones(out[0].shape)
sensitivities, backward_env = graph.backward_propagation(
sensitivity_backward_transform, bound_env,
{graph.outputs[0]: output_sensitivity},
self._sensitivity_targets)
self.target_sensitivities = sensitivities
return out, backward_env
| jax_verify-master | jax_verify/src/branching/backpropagation.py |
# coding=utf-8
# 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.
"""Routines to solve the subproblem during verification."""
from typing import Dict, List, Mapping, Optional, Tuple, Union
from absl import logging
import cvxpy as cp
from cvxpy.reductions.solvers.defines import INSTALLED_MI_SOLVERS as MIP_SOLVERS
import jax
import jax.numpy as jnp
from jax_verify.src import utils
from jax_verify.src.mip_solver import relaxation
import numpy as np
CvxpyConstraint = cp.constraints.constraint.Constraint
Tensor = np.ndarray
Variable = Union[relaxation.RelaxVariable,
relaxation.BinaryVariable]
Solution = Mapping[str, jnp.ndarray]
class CvxpySolver(relaxation.RelaxationSolver):
"""Holder class to represent problem being built."""
def __init__(self):
"""Build and solve the relaxation using CVXPY."""
self.solver_variables: Dict[str, cp.Variable] = {}
self.constraints: List[CvxpyConstraint] = []
self.problem_kwargs = {}
def _variable_already_created(self, var: Variable) -> bool:
return var.name in self.solver_variables
def _create_solver_relax_variable(
self,
relax_var: relaxation.RelaxVariable,
index: int):
"""Create a new bound-constrained CVXPY variable based on a RelaxVariable.
Args:
relax_var: Variable generated by the relaxation bound propagation.
index: Index in the batch for which to build the variable.
"""
lower = np.reshape(relax_var.lower[index, ...], [-1])
upper = np.reshape(relax_var.upper[index, ...], [-1])
var = cp.Variable(lower.shape)
self.constraints += [lower <= var]
self.constraints += [var <= upper]
self.solver_variables[relax_var.name] = var
def create_linear_solver_constraint(self,
constraint: relaxation.LinearConstraint,
index: int):
"""Create a new CVXPY linear constraint.
Args:
constraint: Constraint generated by the relaxation bound propagation.
index: Index in the batch for which to build the variable.
"""
rhs = cp.expressions.constants.Constant(constraint.bias(index))
for (constraint_variable,
(cpts, coeffs)) in constraint.vars_and_coeffs(index):
if isinstance(constraint_variable, relaxation.RelaxVariable):
current_variable = self.solver_variables[constraint_variable.name]
for component, coeff in zip(cpts, coeffs):
if np.abs(coeff) > utils.EPSILON:
rhs += current_variable[component] * coeff.item()
if constraint.sense == 0:
self.constraints += [rhs == 0]
if constraint.sense == 1:
self.constraints += [rhs <= 0]
if constraint.sense == -1:
self.constraints += [rhs >= 0]
def create_activation_solver_constraint(
self, constraint: relaxation.RelaxActivationConstraint, act_index: int,
slope: float, bias: float):
"""Create the linear constraint involved in the activation relaxation.
Args:
constraint: Constraint generated by the relaxation bound propagation.
act_index: Index of the activation to encode (in the variables involved
in constraint)
slope : Slope coefficients of the linear inequality.
bias: Bias of the linear inequality
"""
outvar = self.solver_variables[constraint.outvar.name]
invar = self.solver_variables[constraint.invar.name]
expression = invar[act_index] * slope + bias - outvar[act_index]
if constraint.sense == 0:
self.constraints += [expression == 0]
if constraint.sense == 1:
self.constraints += [expression <= 0]
if constraint.sense == -1:
self.constraints += [expression >= 0]
def minimize_objective(
self,
var_name: str,
objective: Tensor,
objective_bias: float,
time_limit: Optional[int] = None,
) -> Tuple[float, Solution, bool]:
"""Minimize a linear function.
Args:
var_name: Index of the variable to define a linear function over the
components.
objective: Coefficients of the linear function.
objective_bias: Bias of the linear function.
time_limit: Maximum solve time in ms. Use None for unbounded. CVXPY does
not support time_limit so any other value will raise a ValueError.
Returns:
val: Value of the minimum.
solution: solution of the problem
status: Status of the optimization function.
"""
if time_limit is not None:
raise ValueError('Cvxpy Solver does not support time limit.')
# Define the objective function
obj = cp.expressions.constants.Constant(0.)
for i, coeff in enumerate(objective):
if np.abs(coeff) > utils.EPSILON:
obj += self.solver_variables[var_name][i] * coeff.item()
objective = cp.Minimize(obj)
prob = cp.Problem(objective, self.constraints)
logging.info('Starting problem solve.')
prob.solve(solver=cp.ECOS, **self.problem_kwargs)
logging.info('Problem status is %s', prob.status)
val = obj.value
if val is not None:
val += objective_bias
solution = jax.tree_map(lambda x: jnp.array(x.value),
self.solver_variables)
return val, solution, prob.status in (cp.settings.OPTIMAL,
cp.settings.OPTIMAL_INACCURATE)
class CvxpyMIPSolver(CvxpySolver, relaxation.MIPSolver): # pytype: disable=signature-mismatch # maybe_create_solver_variable uses parameter contravariance
"""Holder class to represent problem being built."""
def __init__(self):
"""Build and solve the MIP encoding using CVXPY."""
super(CvxpyMIPSolver, self).__init__()
if not MIP_SOLVERS:
raise NotImplementedError('No MIP solver is available.')
self.problem_kwargs.update(solver=MIP_SOLVERS[0])
def _create_solver_bool_variable(
self,
bin_var: relaxation.BinaryVariable,
index: int):
"""Create a new bound-constrained CVXPY variable based on a BinaryVariable.
Args:
bin_var: Variable generated by the MIP formulation.
index: Index in the batch for which to build the variable.
"""
shape = np.prod(bin_var.shape[1:])
self.solver_variables[bin_var.name] = cp.Variable(shape, boolean=True)
def create_mip_activation_solver_constraint(
self,
constraint: relaxation.MIPActivationConstraint,
act_index: int,
binslope: float,
slope: float,
bias: float,
):
"""Create the mip constraint involved in the activation constraint.
Encodes outvar =(>)(<) slope * invar + binslope * binvar + bias.
Args:
constraint: Constraint generated by the relaxation bound propagation.
act_index: Index of the activation to encode (in the variables involved
in constraint)
binslope: Multiplicative coefficient for the binary variable.
slope : Slope coefficients of the linear inequality.
bias: Bias of the linear inequality
"""
binvar = self.solver_variables[constraint.binvar.name]
outvar = self.solver_variables[constraint.outvar.name]
invar = self.solver_variables[constraint.invar.name]
expression = (invar[act_index] * slope + binvar[act_index] * binslope
+ bias - outvar[act_index])
if constraint.sense == 0:
self.constraints += [expression == 0]
if constraint.sense == 1:
self.constraints += [expression <= 0]
if constraint.sense == -1:
self.constraints += [expression >= 0]
| jax_verify-master | jax_verify/src/mip_solver/cvxpy_relaxation_solver.py |
# coding=utf-8
# 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.
"""Propagate the relaxation through the network.
This is accomplished by traversing the JaxPR representation of the computation
and translating the computational graph.
"""
import abc
import functools
from typing import Callable, Tuple, List, Mapping, Optional, Union
import jax
from jax import lax
import jax.numpy as jnp
from jax_verify.src import activation_relaxation
from jax_verify.src import bound_propagation
from jax_verify.src import graph_traversal
from jax_verify.src import ibp
from jax_verify.src import synthetic_primitives
from jax_verify.src.types import Index, Primitive, Tensor # pylint: disable=g-multiple-import
import numpy as np
class RelaxVariable(bound_propagation.Bound):
"""Variable used to build relaxation."""
def __init__(self, idx: Index, base_bound):
self.base_bound = base_bound
self.name = 'rlxvar'
for idx_cpt in idx:
self.name += f'_{idx_cpt}'
self.idx = idx
self.constraints = None
def set_constraints(self, constraints):
self.constraints = constraints
@property
def lower(self):
return self.base_bound.lower
@property
def upper(self):
return self.base_bound.upper
class OptRelaxVariable(RelaxVariable):
"""Variant of RelaxVariable with lazy optimization tightening."""
def __init__(self, base_relax_variable, optimize_transform):
super(OptRelaxVariable, self).__init__(base_relax_variable.idx,
base_relax_variable.base_bound)
self._shape = base_relax_variable.shape
self._opted_bounds = None
self._optimize_transform = optimize_transform
@property
def shape(self):
# Need to specify a shape method, because otherwise, a call to `.shape`
# will attempt to read `.lower` and trigger optimization
return self._shape
@property
def dtype(self):
# Need to specify a type method, because otherwise, a call to `.dtype`
# will attempt to read `.lower` and trigger optimization
return self._dtype
@property
def lower(self):
return self._optimized_bounds.lower
@property
def upper(self):
return self._optimized_bounds.upper
@property
def _optimized_bounds(self):
if self._opted_bounds is None:
self._opted_bounds = self._optimize_transform.tight_bounds(self)
return self._opted_bounds
class BinaryVariable():
"""Binary variable."""
def __init__(self, idx, shape):
self.shape = shape
self.name = f'boolvar_{idx}'
self.idx = idx
class MIPActivationConstraint:
"""MIP constraint to encode activation."""
def __init__(self, outvar, invar, binvar, mask, binscale, scale, bias, sense):
"""Represents: outvar =(>)(<) scale * invar + binscale * binvar + bias."""
self.outvar = outvar
self.invar = invar
self.binvar = binvar
self.binscale = binscale
self.mask = mask
self.scale = scale
self.bias = bias
self.sense = sense
def encode_into_solver(self, solver: 'MIPSolver', index: int):
"""Encode the linear constraints into the provided solver.
Args:
solver: MIPSolver to create the exact constraint into.
index: Index in the batch for which to build the variable.
"""
biases = np.reshape(self.bias[index, ...], [-1])
slopes = np.reshape(self.scale[index, ...], [-1])
binslopes = np.reshape(self.binscale[index, ...], [-1])
mask = np.reshape(self.mask[index, ...], [-1])
for act_index, (binslope, slope, bias) in enumerate(
zip(binslopes, slopes, biases)):
if mask[act_index]:
solver.create_mip_activation_solver_constraint(
self, act_index, binslope=binslope.item(),
slope=slope.item(), bias=bias.item())
class LinearConstraint:
"""Linear constraint, to be encoded into a solver."""
def __init__(self, vars_and_coeffs, bias, sense):
self._vars_and_coeffs = vars_and_coeffs
self._bias = bias
self.sense = sense
self.sample_dependent = bool(self._bias.shape)
def bias(self, index: int):
"""Get the bias corresponding to the minibatch sample `index`.
If bias has a dimension, it means it is sample dependent. Otherwise,
the bias is the same for all samples.
Args:
index: Index in the batch for which to build the variable.
Returns:
bias: value of the bias.
"""
return self._bias[index] if self.sample_dependent else self._bias
def vars_and_coeffs(self, index: int):
"""Get the variable and coefficients corresponding to the sample `index`.
If coeffs has a dimension, the coefficients are sample dependent. Otherwise,
the coefficients are the same for all samples.
Args:
index: Index in the batch for which to build the variable.
Returns:
vars_and_coeffs: vars_and_coeffs list where the coefficients are the one
corresponding to the sample `index`
"""
if self.sample_dependent:
return [(var, (cpts, coeffs[index]))
for (var, (cpts, coeffs)) in self._vars_and_coeffs]
else:
return self._vars_and_coeffs
def encode_into_solver(self, solver: 'RelaxationSolver', index: int):
"""Encode the linear constraints into the provided solver.
Args:
solver: RelaxationSolver to create the linear constraint into.
index: Index in the batch for which to build the variable.
"""
solver.create_linear_solver_constraint(self, index)
class RelaxActivationConstraint:
"""Linear constraint involved in the relaxation of an activation."""
def __init__(self, outvar, invar, mask, scale, bias, sense):
"""Represents the constraint outvar =(>)(<) scale * invar + bias."""
self.outvar = outvar
self.invar = invar
self.mask = mask
self.scale = scale
self.bias = bias
self.sense = sense
def encode_into_solver(self, solver: 'RelaxationSolver', index: int):
"""Encode the linear constraints into the provided solver.
Args:
solver: RelaxationSolver to create the linear constraint into.
index: Index in the batch for which to build the variable.
"""
biases = np.reshape(self.bias[index, ...], [-1])
slopes = np.reshape(self.scale[index, ...], [-1])
mask = np.reshape(self.mask[index, ...], [-1])
for act_index, (slope, bias) in enumerate(zip(slopes, biases)):
if mask[act_index]:
solver.create_activation_solver_constraint(
self, act_index, slope.item(), bias.item())
class RelaxationSolver(metaclass=abc.ABCMeta):
"""Abstract solver for the relaxation."""
def maybe_create_solver_variable(
self,
var: RelaxVariable,
index: int):
"""Create a new solver variable for var if it has not been created yet.
Args:
var: Variable generated by the relaxation bound propagation.
index: Index in the batch for which to build the variable.
"""
if not self._variable_already_created(var):
self._create_solver_relax_variable(var, index)
@abc.abstractmethod
def _create_solver_relax_variable(
self,
var: RelaxVariable,
index: int):
"""Create a new bound-constrained variable based on a RelaxVariable.
Args:
var: Variable generated by the relaxation bound propagation.
index: Index in the batch for which to build the variable.
"""
@abc.abstractmethod
def _variable_already_created(
self,
var: Union[RelaxVariable, BinaryVariable],
) -> bool:
"""Check whether the solver has already created a variable for var.
Args:
var: Variable generated by the relaxation bound propagation.
"""
@abc.abstractmethod
def create_linear_solver_constraint(
self,
constraint: LinearConstraint,
index: int):
"""Create a new solver linear constraint.
Args:
constraint: Constraint generated by the relaxation bound propagation.
index: Index in the batch for which to build the variable.
"""
@abc.abstractmethod
def create_activation_solver_constraint(
self,
constraint: RelaxActivationConstraint,
act_index: int,
slope: float,
bias: float):
"""Create the linear constraint involved in the activation relaxation.
Args:
constraint: Constraint generated by the relaxation bound propagation.
act_index: Index of the activation to encode (in the variables involved
in constraint)
slope : Slope coefficients of the linear inequality.
bias: Bias of the linear inequality
"""
@abc.abstractmethod
def minimize_objective(
self,
var_name: str,
objective: Tensor,
objective_bias: float,
time_limit_millis: Optional[int],
) -> Tuple[float, Mapping[str, Tensor], bool]:
"""Minimize a linear function.
Args:
var_name: Index of the variable to define a linear function over the
components.
objective: Coefficients of the linear function.
objective_bias: Bias of the linear function.
time_limit_millis: Maximum solve time in ms. Use None for unbounded.
Returns:
val: Value of the minimum.
solution: Solution found.
status: Status of the optimization function.
"""
class MIPSolver(RelaxationSolver):
"""Abstract solver for the MIP encoding."""
def maybe_create_solver_variable(
self,
var: Union[RelaxVariable, BinaryVariable],
index: int):
"""Create a new solver variable for var if it has not been created yet.
Args:
var: Variable generated by the relaxation bound propagation.
index: Index in the batch for which to build the variable.
"""
if not self._variable_already_created(var):
if isinstance(var, BinaryVariable):
self._create_solver_bool_variable(var, index)
else:
self._create_solver_relax_variable(var, index)
@abc.abstractmethod
def _create_solver_bool_variable(
self,
var: BinaryVariable,
index: int):
"""Create a new bound-constrained variable based on a BinaryVariable.
Args:
var: Variable generated by the relaxation bound propagation.
index: Index in the batch for which to build the variable.
"""
@abc.abstractmethod
def create_mip_activation_solver_constraint(
self,
constraint: MIPActivationConstraint,
act_index: int,
binslope: float,
slope: float,
bias: float):
"""Create the linear constraint involved in the activation relaxation.
Args:
constraint: Constraint generated by the relaxation bound propagation.
act_index: Index of the activation to encode (in the variables involved
in constraint)
binslope: Slope coefficients for the binary variable.
slope : Slope coefficients for the input variable.
bias: Bias of the linear inequality
"""
def encode_relaxation(
solver_ctor: Callable[[], RelaxationSolver],
env: Mapping[jax.core.Var, Union[RelaxVariable, Tensor]],
index: int,
) -> RelaxationSolver:
"""Creates a solver and encodes the relaxation into it.
Args:
solver_ctor: Constructor for the solver.
env: Environment created by applying boundprop with relaxation.py
index: The index in the minibatch for which the relaxation should be
encoded.
Returns:
solver: Solver containing the relaxation of the network encoded.
"""
solver = solver_ctor()
for key in env.keys():
if isinstance(env[key], RelaxVariable):
variable = env[key]
# Create the variable in the solver.
solver.maybe_create_solver_variable(variable, index)
# Create the constraints in the solver.
if variable.constraints:
for constraint in variable.constraints:
if isinstance(constraint, MIPActivationConstraint):
# create manually the binary variable because it is not collected
# automatically by the graph propagation.
solver.maybe_create_solver_variable(constraint.binvar, index)
constraint.encode_into_solver(solver, index)
return solver
def solve_relaxation(
solver_ctor: Callable[[], RelaxationSolver],
objective: Tensor,
objective_bias: float,
variable_opt: RelaxVariable,
env: Mapping[jax.core.Var, Union[RelaxVariable, Tensor]],
index: int,
time_limit_millis: Optional[int] = None,
) -> Tuple[float, Mapping[str, Tensor], bool]:
"""Solves the relaxation using the provided LP solver.
Args:
solver_ctor: Constructor for the solver.
objective: Objective to optimize, given as an array of coefficients to be
applied to the variable to form a linear objective function
objective_bias: Bias to add to objective
variable_opt: RelaxVariable over which the linear function to optimize
is defined.
env: Environment created by applying boundprop with relaxation.py
index: The index in the minibatch for which the LP should be solved
time_limit_millis: Time limit on solver. None if unbounded.
Returns:
opt: Value of the solution found.
solution: Solution found by the solver.
status: Whether the optimal solution has been achieved.
"""
solver = encode_relaxation(solver_ctor, env, index)
return solver.minimize_objective(variable_opt.name,
objective, objective_bias, time_limit_millis)
def _get_linear(primitive, outval, *eqn_invars, **params):
"""Get linear expressions corresponding to an affine layer.
Args:
primitive: jax primitive
outval: dummy tensor shaped according to a single example's outputs
*eqn_invars: Arguments of the primitive, wrapped as RelaxVariables
**params: Keyword Arguments of the primitive.
Returns:
For each output component, a pair `(bias, coefficients)`, where
`coefficients` is a list of `(component, coefficient)` pairs.
"""
def funx(x):
if isinstance(x, RelaxVariable):
return jnp.zeros(x.shape)
else:
return x
def fungrad(i, args):
return jnp.reshape(primitive.bind(*args, **params)[0, ...], [-1])[i]
results = []
# Loop over output dimensions one at a time to avoid creating a large
# materialized tensor
# TODO: Replace with something more efficient
for i in range(outval.size):
fung = functools.partial(fungrad, i)
bias, current_grad = jax.value_and_grad(fung, allow_int=True)(
[funx(x) for x in eqn_invars])
coefficients = []
for res, in_var in zip(current_grad, eqn_invars):
if isinstance(in_var, RelaxVariable):
components = jnp.flatnonzero(res)
coefficients.append((components, res.ravel()[components]))
else:
coefficients.append(None)
results.append((bias, coefficients))
return results
def _relax_input(
index: Index, in_bounds: bound_propagation.Bound,
) -> RelaxVariable:
"""Generates the initial inputs for the relaxation.
Args:
index: Integer identifying the input node.
in_bounds: Concrete bounds on the input node.
Returns:
`RelaxVariable` for the initial inputs.
"""
# Wrap initial bound as RelaxVariable bound.
in_variable = RelaxVariable(index, in_bounds)
return in_variable
_order_preserving_reshapes = [lax.reshape_p, lax.squeeze_p]
_affine_primitives_list = [
*bound_propagation.AFFINE_PRIMITIVES,
*bound_propagation.RESHAPE_PRIMITIVES,
lax.div_p,
]
def _relax_primitive(
index: Index, out_bounds: bound_propagation.Bound,
primitive: Primitive,
*args, use_mip: bool = False, **kwargs
) -> RelaxVariable:
"""Generates the relaxation for a given primitive op.
Args:
index: Integer identifying the computation node.
out_bounds: Concrete bounds on the outputs of the primitive op.
primitive: jax primitive.
*args: Arguments of the primitive, wrapped as RelaxVariables
use_mip: whether to use mixed integer programming for the activation
constraints.
**kwargs: Keyword Arguments of the primitive.
Returns:
`RelaxVariable` that contains the output of this primitive for the
relaxation, with all the constraints linking the output to inputs.
"""
# Create variable for output of this primitive
out_variable = RelaxVariable(index, out_bounds)
# Create constraints linking output and input of primitive
constraints = []
if primitive in _order_preserving_reshapes:
invar = args[0]
constraints = [RelaxActivationConstraint(outvar=out_variable,
invar=invar,
mask=jnp.ones(invar.shape),
scale=jnp.ones(invar.shape),
bias=jnp.zeros(invar.shape),
sense=0)]
elif primitive in _affine_primitives_list:
if primitive == lax.div_p and isinstance(args[1], RelaxVariable):
raise NotImplementedError(
'Division with non-constant divisor is not supported')
results = _get_linear(primitive, out_bounds.lower[0, ...],
*args, **kwargs)
for i, (bias, coeffs) in enumerate(results):
# Coefficients of the input variable(s).
vars_and_coeffs = [
(arg, coeff) for arg, coeff in zip(args, coeffs)
if isinstance(arg, RelaxVariable)]
# Equate with the output variable, by using a coefficient of -1.
out_coeff = (np.array([i], dtype=np.int64), np.array([-1.]))
vars_and_coeffs.append((out_variable, out_coeff))
constraints.append(LinearConstraint(vars_and_coeffs, bias, 0))
elif primitive in activation_relaxation.relaxation_fns:
# Generate convex relaxation.
safe_kwargs = synthetic_primitives.filter_jaxverify_kwargs(kwargs)
activation = activation_relaxation.relaxation_fns[primitive]
lb_funs, ub_funs = activation.piecewise_linear_relaxation_fn(*args,
**safe_kwargs)
invar, = args
zeros = jnp.zeros_like(invar.lower)
ones = jnp.ones_like(invar.lower)
if activation.pos_neg_linear and (len(lb_funs) == 1 or len(ub_funs) == 1):
# Use equality constraints if linear over the entire interval.
ambiguous = (invar.lower < 0) & (invar.upper > 0)
chord, = lb_funs if len(lb_funs) == 1 else ub_funs
constraints.append(RelaxActivationConstraint(
outvar=out_variable,
invar=invar,
mask=(~ambiguous),
scale=(chord(ones) - chord(zeros)),
bias=chord(zeros),
sense=0))
else:
ambiguous = ones
for lb_fun in lb_funs:
# act(x) >= lb(x)
constraints.append(RelaxActivationConstraint(
outvar=out_variable,
invar=invar,
mask=ambiguous,
scale=(lb_fun(ones) - lb_fun(zeros)),
bias=lb_fun(zeros),
sense=1))
for ub_fun in ub_funs:
# act(x) <= ub(x)
constraints.append(RelaxActivationConstraint(
outvar=out_variable,
invar=invar,
mask=ambiguous,
scale=(ub_fun(ones) - ub_fun(zeros)),
bias=ub_fun(zeros),
sense=-1))
if use_mip:
if primitive is not synthetic_primitives.relu_p:
raise ValueError(
f'Only ReLU activations supported. Encountered {primitive}')
binvar = BinaryVariable(index, out_bounds.lower.shape)
constraints += [
# outvar <= upper_bound * binvar
MIPActivationConstraint(outvar=out_variable,
invar=invar,
binvar=binvar,
binscale=invar.upper,
mask=ambiguous,
scale=zeros,
bias=zeros,
sense=-1),
# outvar <= invar - lower_bound * (1. - binvar)
MIPActivationConstraint(outvar=out_variable,
invar=invar,
binvar=binvar,
binscale=invar.lower,
mask=ambiguous,
scale=ones,
bias=-invar.lower,
sense=-1),
]
else:
raise NotImplementedError(f'Unsupported primitive: {primitive}')
out_variable.set_constraints(constraints)
return out_variable
class RelaxationTransform(graph_traversal.GraphTransform[RelaxVariable]):
"""Transform to produce `RelaxVariable`s for each op."""
def __init__(
self,
boundprop_transform: bound_propagation.BoundTransform,
use_mip: bool = False,
):
"""Defines relaxation constraint propagation.
Args:
boundprop_transform: Basic Jax primitive ops' equivalents for
the underlying bound propagation method.
use_mip: whether to use mixed integer programming for the activation
constraints.
"""
self._boundprop_transform = boundprop_transform
self._use_mip = use_mip
def input_transform(self, context, input_bound):
in_bounds = self._boundprop_transform.input_transform(
context, input_bound)
return _relax_input(context.index, in_bounds)
def primitive_transform(self, context, primitive, *args, **params):
interval_args = [arg.base_bound if isinstance(arg, RelaxVariable) else arg
for arg in args]
out_bounds, = self._boundprop_transform.equation_transform(
context, primitive, *interval_args, **params)
return _relax_primitive(
context.index, out_bounds, primitive, *args,
use_mip=self._use_mip, **params)
class OptimizedRelaxationTransform(
graph_traversal.GraphTransform[OptRelaxVariable]):
"""Wraps a RelaxVariable-producing BoundTransform to add optimization."""
def __init__(
self,
transform: graph_traversal.GraphTransform[RelaxVariable],
solver_ctor: Callable[[], RelaxationSolver],
time_limit_millis: Optional[int] = None):
self._transform = transform
self.solver_ctor = solver_ctor
self.solvers: List[RelaxationSolver] = []
self._time_limit_millis = time_limit_millis
def tight_bounds(self, variable: RelaxVariable) -> ibp.IntervalBound:
"""Compute tighter bounds based on the LP relaxation.
Args:
variable: Variable as created by the base boundprop transform. This is a
RelaxVariable that has already been encoded into the solvers.
Returns:
tightened_base_bound: Bounds tightened by optimizing with the LP solver.
"""
lbs = []
ubs = []
for solver in self.solvers:
nb_targets = np.prod(variable.shape[1:])
sample_lbs = []
sample_ubs = []
for target_idx in range(nb_targets):
objective = (jnp.arange(nb_targets) == target_idx).astype(jnp.float32)
lb, _, optimal_lb = solver.minimize_objective(
variable.name, objective, 0., self._time_limit_millis)
assert optimal_lb
neg_ub, _, optimal_ub = solver.minimize_objective(
variable.name, -objective, 0., self._time_limit_millis)
assert optimal_ub
sample_lbs.append(lb)
sample_ubs.append(-neg_ub)
lbs.append(sample_lbs)
ubs.append(sample_ubs)
tightened_base_bound = ibp.IntervalBound(
jnp.reshape(jnp.array(lbs), variable.shape),
jnp.reshape(jnp.array(ubs), variable.shape))
return tightened_base_bound
def input_transform(
self,
context: graph_traversal.TransformContext[OptRelaxVariable],
input_bound: graph_traversal.InputBound,
) -> RelaxVariable:
in_bounds = self._transform.input_transform(
context, input_bound)
for minibatch_index in range(in_bounds.shape[0]):
# Create one solver instance for each problem in the batch because they
# will have different constraints.
if minibatch_index >= len(self.solvers):
self.solvers.append(self.solver_ctor())
solver = self.solvers[minibatch_index]
solver.maybe_create_solver_variable(in_bounds, minibatch_index)
return in_bounds
def primitive_transform(
self,
context: graph_traversal.TransformContext[OptRelaxVariable],
primitive: Primitive,
*args: Union[RelaxVariable, Tensor],
**params,
) -> RelaxVariable:
basic_relax_var, = self._transform.equation_transform(
context, primitive, *args, **params)
opt_relax_var = OptRelaxVariable(basic_relax_var, self)
for minibatch_index, solver in enumerate(self.solvers):
# Encode the new variable and the associated constraints. We encode the
# basic variable, not the optimized one. This way, the optimization is
# only performed if the lower / upper bounds are required and the bounds
# on that variable are accessed "from outside".
solver.maybe_create_solver_variable(basic_relax_var, minibatch_index)
if basic_relax_var.constraints:
for constraint in basic_relax_var.constraints:
if isinstance(constraint, MIPActivationConstraint):
# create manually the binary variable because it is not collected
# automatically by the graph propagation.
solver.maybe_create_solver_variable(
constraint.binvar, minibatch_index)
constraint.encode_into_solver(solver, minibatch_index)
return opt_relax_var
| jax_verify-master | jax_verify/src/mip_solver/relaxation.py |
# coding=utf-8
# 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.
"""Methods for solving relaxation generated by relaxation.py.
This file mainly calls out to relaxation.RelaxationSolvers defined in other
files, and provides a higher-level interface than using relaxation.py directly.
"""
from jax_verify.src import bound_propagation
from jax_verify.src.mip_solver import cvxpy_relaxation_solver
from jax_verify.src.mip_solver import relaxation
def solve_planet_relaxation(
logits_fn, initial_bounds, boundprop_transform,
objective, objective_bias, index,
solver=cvxpy_relaxation_solver.CvxpySolver):
"""Solves the "Planet" (Ehlers 17) or "triangle" relaxation.
The general approach is to use jax_verify to generate constraints, which can
then be passed to generic solvers. Note that using CVXPY will incur a large
overhead when defining the LP, because we define all constraints element-wise,
to avoid representing convolutional layers as a single matrix multiplication,
which would be inefficient. In CVXPY, defining large numbers of constraints is
slow.
Args:
logits_fn: Mapping from inputs (batch_size x input_size) -> (batch_size,
num_classes)
initial_bounds: `IntervalBound` with initial bounds on inputs,
with lower and upper bounds of dimension (batch_size x input_size).
boundprop_transform: bound_propagation.BoundTransform instance, such as
`jax_verify.ibp_transform`. Used to pre-compute interval bounds for
intermediate activations used in defining the Planet relaxation.
objective: Objective to optimize, given as an array of coefficients to be
applied to the output of logits_fn defining the objective to minimize
objective_bias: Bias to add to objective
index: Index in the batch for which to solve the relaxation
solver: A relaxation.RelaxationSolver, which specifies the backend to solve
the resulting LP.
Returns:
val: The optimal value from the relaxation
solution: The optimal solution found by the solver
status: The status of the relaxation solver
"""
relaxation_transform = relaxation.RelaxationTransform(boundprop_transform)
variable, env = bound_propagation.bound_propagation(
bound_propagation.ForwardPropagationAlgorithm(relaxation_transform),
logits_fn, initial_bounds)
value, solution, status = relaxation.solve_relaxation(
solver, objective, objective_bias, variable, env,
index=index, time_limit_millis=None)
return value, solution, status
| jax_verify-master | jax_verify/src/mip_solver/solve_relaxation.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.
# ==============================================================================
"""Slowfast Norm-Free Nets (https://arxiv.org/abs/2111.12124).
This class of network contains a fast and a slow branch, both based on the NFNet
backbone (https://arxiv.org/abs/2102.06171). The is also a fushion layer mixing
fast features to the slow branch.
The NFNet backbone follows the original implementation:
https://github.com/deepmind/deepmind-research/blob/master/nfnets/nfnet.py
with changes to allow for customized kernel and stride patterns.
"""
from typing import Text, Optional, Sequence, Any
import chex
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
from slowfast_nfnets import base
class NFNet(hk.Module):
"""Normalizer-Free networks, The Next Generation."""
variant_dict = base.slowfast_nfnet_params
def __init__(self,
variant: Text = 'F0',
width: float = 1.0,
se_ratio: float = 0.5,
alpha: float = 0.2,
stochdepth_rate: float = 0.1,
drop_rate: Optional[float] = None,
activation: Text = 'gelu',
# Multiplier for the final conv channel count
final_conv_mult: int = 2,
final_conv_ch: Optional[int] = None,
use_two_convs: bool = True,
name: Optional[Text] = 'NFNet'):
super().__init__(name=name)
self.variant = variant
self.width = width
self.se_ratio = se_ratio
# Get variant info
block_params = self.variant_dict[self.variant]
self.width_pattern = block_params['width']
self.depth_pattern = block_params['depth']
self.bneck_pattern = block_params['expansion']
self.group_pattern = block_params['group_width']
self.big_pattern = block_params['big_width']
stem_kernel_pattern = block_params['stem_kernel_pattern']
stem_stride_pattern = block_params['stem_stride_pattern']
kernel_pattern = block_params['kernel_pattern']
stride_pattern = block_params['stride_pattern']
self.activation = base.nonlinearities[activation]
if drop_rate is None:
self.drop_rate = block_params['drop_rate']
else:
self.drop_rate = drop_rate
self.which_conv = base.WSConv2D
# Stem
ch = self.width_pattern[0] // 2
self.stem = hk.Sequential([
self.which_conv(ch // 8, kernel_shape=stem_kernel_pattern[0],
stride=stem_stride_pattern[0], padding='SAME',
name='stem_conv0'),
self.activation,
self.which_conv(ch // 4, kernel_shape=stem_kernel_pattern[1],
stride=stem_stride_pattern[1], padding='SAME',
name='stem_conv1'),
self.activation,
self.which_conv(ch // 2, kernel_shape=stem_kernel_pattern[2],
stride=stem_stride_pattern[2], padding='SAME',
name='stem_conv2'),
self.activation,
self.which_conv(ch, kernel_shape=stem_kernel_pattern[3],
stride=stem_stride_pattern[3], padding='SAME',
name='stem_conv3'),
])
# Body
self.blocks = []
expected_std = 1.0
num_blocks = sum(self.depth_pattern)
index = 0 # Overall block index
block_args = zip(self.width_pattern, self.depth_pattern, self.bneck_pattern,
self.group_pattern, self.big_pattern, kernel_pattern,
stride_pattern)
for (block_width, stage_depth, expand_ratio,
group_size, big_width, kernel, stride) in block_args:
for block_index in range(stage_depth):
# Scalar pre-multiplier so each block sees an N(0,1) input at init
beta = 1./ expected_std
# Block stochastic depth drop-rate
block_stochdepth_rate = stochdepth_rate * index / num_blocks
out_ch = (int(block_width * self.width))
self.blocks += [NFBlock(ch,
out_ch,
expansion=expand_ratio,
se_ratio=se_ratio,
group_size=group_size,
kernel_shape=kernel,
stride=stride if block_index == 0 else (1, 1),
beta=beta,
alpha=alpha,
activation=self.activation,
which_conv=self.which_conv,
stochdepth_rate=block_stochdepth_rate,
big_width=big_width,
use_two_convs=use_two_convs,
)]
ch = out_ch
index += 1
# Reset expected std but still give it 1 block of growth
if block_index == 0:
expected_std = 1.0
expected_std = (expected_std **2 + alpha**2)**0.5
# Head
if final_conv_mult is None:
if final_conv_ch is None:
raise ValueError('Must provide one of final_conv_mult or final_conv_ch')
ch = final_conv_ch
else:
ch = int(final_conv_mult * ch)
self.final_conv = self.which_conv(ch, kernel_shape=1,
padding='SAME', name='final_conv')
def __call__(self, x: chex.Array, is_training: bool) -> chex.Array:
"""Return the output of the final layer without any [log-]softmax."""
# Stem
out = self.stem(x)
# Blocks
for block in self.blocks:
out, _ = block(out, is_training=is_training)
# Final-conv->activation, pool, dropout, classify
out = self.activation(self.final_conv(out))
out = jnp.mean(out, [1, 2])
return out
class NFBlock(hk.Module):
"""Normalizer-Free Net Block."""
def __init__(self,
in_ch: int,
out_ch: int,
expansion: float = 0.5,
se_ratio: float = 0.5,
kernel_shape: Sequence[int] = (3, 1),
second_conv_kernel_shape: Sequence[int] = (1, 3),
group_size: int = 128,
stride: Sequence[int] = (1, 1),
beta: float = 1.0,
alpha: float = 0.2,
which_conv: Any = base.WSConv2D,
activation: Any = jax.nn.gelu,
big_width: bool = True,
use_two_convs: bool = True,
stochdepth_rate: Optional[float] = None,
name: Optional[Text] = None):
super().__init__(name=name)
self.in_ch, self.out_ch = in_ch, out_ch
self.expansion = expansion
self.se_ratio = se_ratio
self.kernel_shape = kernel_shape
self.activation = activation
self.beta, self.alpha = beta, alpha
# Mimic resnet style bigwidth scaling?
width = int((self.out_ch if big_width else self.in_ch) * expansion)
# Round expanded with based on group count
self.groups = width // group_size
self.width = group_size * self.groups
self.stride = stride
self.use_two_convs = use_two_convs
# Conv 0 (typically expansion conv)
self.conv0 = which_conv(self.width, kernel_shape=1, padding='SAME',
name='conv0')
# Grouped NxN conv
self.conv1 = which_conv(self.width, kernel_shape=kernel_shape,
stride=stride, padding='SAME',
feature_group_count=self.groups, name='conv1')
if self.use_two_convs:
self.conv1b = which_conv(self.width,
kernel_shape=second_conv_kernel_shape,
stride=1, padding='SAME',
feature_group_count=self.groups, name='conv1b')
# Conv 2, typically projection conv
self.conv2 = which_conv(self.out_ch, kernel_shape=1, padding='SAME',
name='conv2')
# Use shortcut conv on channel change or downsample.
self.use_projection = np.prod(stride) > 1 or self.in_ch != self.out_ch
if self.use_projection:
self.conv_shortcut = which_conv(self.out_ch, kernel_shape=1,
padding='SAME', name='conv_shortcut')
# Squeeze + Excite Module
self.se = base.SqueezeExcite(self.out_ch, self.out_ch, self.se_ratio)
# Are we using stochastic depth?
self._has_stochdepth = (stochdepth_rate is not None and
stochdepth_rate > 0. and stochdepth_rate < 1.0)
if self._has_stochdepth:
self.stoch_depth = base.StochDepth(stochdepth_rate)
def __call__(self, x: chex.Array, is_training: bool) -> chex.Array:
out = self.activation(x) * self.beta
if np.prod(self.stride) > 1: # Average-pool downsample.
pool_size = [1] + list(self.stride) + [1]
shortcut = hk.avg_pool(out, window_shape=pool_size,
strides=pool_size, padding='SAME')
if self.use_projection:
shortcut = self.conv_shortcut(shortcut)
elif self.use_projection:
shortcut = self.conv_shortcut(out)
else:
shortcut = x
out = self.conv0(out)
out = self.conv1(self.activation(out))
if self.use_two_convs:
out = self.conv1b(self.activation(out))
out = self.conv2(self.activation(out))
out = (self.se(out) * 2) * out # Multiply by 2 for rescaling
# Get average residual standard deviation for reporting metrics.
res_avg_var = jnp.mean(jnp.var(out, axis=[0, 1, 2]))
# Apply stochdepth if applicable.
if self._has_stochdepth:
out = self.stoch_depth(out, is_training)
# SkipInit Gain
out = out * hk.get_parameter('skip_gain', (), out.dtype, init=jnp.zeros)
return out * self.alpha + shortcut, res_avg_var
class FuseFast2Slow(hk.Module):
"""Fuses the information from the Fast pathway to the Slow pathway."""
def __init__(self,
channels: int,
kernel_size: Sequence[int] = (7, 1),
stride: Sequence[int] = (4, 1),
which_conv: Any = base.WSConv2D,
activation: Any = jax.nn.gelu,
name: Optional[Text] = None):
super().__init__(name=name)
self._activation = activation
self._which_conv = which_conv
self._conv_f2s = which_conv(channels, kernel_shape=kernel_size,
stride=stride, padding='SAME',
with_bias=True, name='conv_f2s')
def __call__(self, x_f: chex.Array, x_s: chex.Array,
is_training: bool) -> chex.Array:
fuse = self._conv_f2s(x_f)
fuse = self._activation(fuse)
x_s_fuse = jnp.concatenate([x_s, fuse], axis=-1)
return x_s_fuse
class SlowFastNFNet(hk.Module):
"""Slow fast NFNet-F0."""
def __init__(self,
variant: Text = 'F0',
time_ratio: int = 4,
activation: Any = jax.nn.gelu,
fusion_conv_channel_ratio: int = 2,
name: Optional[Text] = None):
super().__init__(name=name)
self._time_ratio = time_ratio
self._activation = activation
self._fast_net = NFNet(variant=f'{variant}-fast')
self._slow_net = NFNet(variant=f'{variant}-slow')
self._depth_pattern = self._slow_net.depth_pattern
self._fast2slow = []
for channels in self._fast_net.width_pattern[0] * np.array([1, 4, 8, 16]):
self._fast2slow.append(
FuseFast2Slow(
channels=channels * fusion_conv_channel_ratio))
def __call__(self, x: chex.Array, is_training: bool) -> chex.Array:
h_s = hk.max_pool(
x, window_shape=(1, self._time_ratio, 1, 1),
strides=(1, self._time_ratio, 1, 1),
padding='SAME')
h_f = x
h_s = self._slow_net.stem(h_s)
h_f = self._fast_net.stem(h_f)
depth = 0
for block_group, num_blocks in enumerate(self._depth_pattern):
f2s_block = self._fast2slow[block_group]
h_s = f2s_block(h_f, h_s, is_training)
for _ in range(num_blocks):
fast_block = self._fast_net.blocks[depth]
slow_block = self._slow_net.blocks[depth]
h_f, _ = fast_block(h_f, is_training=is_training)
h_s, _ = slow_block(h_s, is_training=is_training)
depth += 1
assert depth == len(self._fast_net.blocks)
h_f = self._activation(self._fast_net.final_conv(h_f))
h_s = self._activation(self._slow_net.final_conv(h_s))
h_f = jnp.mean(h_f, [1, 2])
h_s = jnp.mean(h_s, [1, 2])
out = jnp.concatenate([h_f, h_s], axis=-1)
return out
| slowfast_nfnets-main | slowfast_nfnet.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 slowfast_nfnets.slowfast_nfnet."""
from absl.testing import absltest
from absl.testing import parameterized
import haiku as hk
import jax
import numpy as np
from slowfast_nfnets import slowfast_nfnet
rng = np.random.default_rng(12345)
_RAND_SPEC = rng.uniform(-1., 1., size=(2, 400, 128, 1)).astype(np.float32)
class SlowfastNfnetTest(parameterized.TestCase):
def test_slow_nfnet_f0_runs(self):
def forward(inputs):
model = slowfast_nfnet.NFNet(variant='F0-slow')
return model(inputs, is_training=True)
init_fn, apply_fn = hk.transform_with_state(forward)
key = jax.random.PRNGKey(42)
params, state = init_fn(key, _RAND_SPEC)
out, _ = jax.jit(apply_fn)(params, state, key, _RAND_SPEC)
self.assertListEqual(list(out.shape), [2, 3072])
def test_fast_nfnet_f0_runs(self):
def forward(inputs):
model = slowfast_nfnet.NFNet(variant='F0-fast')
return model(inputs, is_training=True)
init_fn, apply_fn = hk.transform_with_state(forward)
key = jax.random.PRNGKey(42)
params, state = init_fn(key, _RAND_SPEC)
out, _ = jax.jit(apply_fn)(params, state, key, _RAND_SPEC)
self.assertListEqual(list(out.shape), [2, 384])
def test_slowfast_nfnet_f0_runs(self):
def forward(inputs):
model = slowfast_nfnet.SlowFastNFNet()
return model(inputs, is_training=True)
init_fn, apply_fn = hk.transform_with_state(forward)
key = jax.random.PRNGKey(42)
params, state = init_fn(key, _RAND_SPEC)
out, _ = jax.jit(apply_fn)(params, state, key, _RAND_SPEC)
self.assertListEqual(list(out.shape), [2, 3456])
if __name__ == '__main__':
absltest.main()
| slowfast_nfnets-main | slowfast_nfnet_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.
# ==============================================================================
"""Architecture definitions for different models."""
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
slowfast_nfnet_params = {
'F0-slow': {
'width': [256, 512, 1536, 1536],
'depth': [1, 2, 6, 3],
'expansion': [0.5] * 4,
'group_width': [128] * 4,
'big_width': [True] * 4,
'drop_rate': 0.2,
'stem_kernel_pattern': [[1, 3], [1, 3], [1, 3], [3, 3]],
'stem_stride_pattern': [[2, 2], [1, 1], [1, 1], [2, 2]],
'kernel_pattern': [[1, 1], [1, 1], [3, 1], [3, 1]],
'stride_pattern': [[1, 1], [1, 2], [1, 2], [1, 2]],
},
'F0-fast': {
'width': [32, 64, 192, 192],
'depth': [1, 2, 6, 3],
'expansion': [0.5] * 4,
'group_width': [16] * 4,
'big_width': [True] * 4,
'drop_rate': 0.2,
'stem_kernel_pattern': [[3, 3], [1, 3], [1, 3], [3, 3]],
'stem_stride_pattern': [[2, 2], [1, 1], [1, 1], [2, 2]],
'kernel_pattern': [[3, 1], [3, 1], [3, 1], [3, 1]],
'stride_pattern': [[1, 1], [1, 2], [1, 2], [1, 2]],
},
}
# Nonlinearities with magic constants (gamma) baked in.
# Note that not all nonlinearities will be stable, especially if they are
# not perfectly monotonic. Good choices include relu, silu, and gelu.
nonlinearities = {
'identity': lambda x: x,
'celu': lambda x: jax.nn.celu(x) * 1.270926833152771,
'elu': lambda x: jax.nn.elu(x) * 1.2716004848480225,
'gelu': lambda x: jax.nn.gelu(x) * 1.7015043497085571,
'glu': lambda x: jax.nn.glu(x) * 1.8484294414520264,
'leaky_relu': lambda x: jax.nn.leaky_relu(x) * 1.70590341091156,
'log_sigmoid': lambda x: jax.nn.log_sigmoid(x) * 1.9193484783172607,
'log_softmax': lambda x: jax.nn.log_softmax(x) * 1.0002083778381348,
'relu': lambda x: jax.nn.relu(x) * 1.7139588594436646,
'relu6': lambda x: jax.nn.relu6(x) * 1.7131484746932983,
'selu': lambda x: jax.nn.selu(x) * 1.0008515119552612,
'sigmoid': lambda x: jax.nn.sigmoid(x) * 4.803835391998291,
'silu': lambda x: jax.nn.silu(x) * 1.7881293296813965,
'soft_sign': lambda x: jax.nn.soft_sign(x) * 2.338853120803833,
'softplus': lambda x: jax.nn.softplus(x) * 1.9203323125839233,
'tanh': lambda x: jnp.tanh(x) * 1.5939117670059204,
}
class WSConv2D(hk.Conv2D):
"""2D Convolution with Scaled Weight Standardization and affine gain+bias."""
@hk.transparent
def standardize_weight(self, weight, eps=1e-4):
"""Apply scaled WS with affine gain."""
mean = jnp.mean(weight, axis=(0, 1, 2), keepdims=True)
var = jnp.var(weight, axis=(0, 1, 2), keepdims=True)
fan_in = np.prod(weight.shape[:-1])
# Get gain
gain = hk.get_parameter('gain', shape=(weight.shape[-1],),
dtype=weight.dtype, init=jnp.ones)
# Manually fused normalization, eq. to (w - mean) * gain / sqrt(N * var)
scale = jax.lax.rsqrt(jnp.maximum(var * fan_in, eps)) * gain
shift = mean * scale
return weight * scale - shift
def __call__(self, inputs: jnp.ndarray, eps: float = 1e-4) -> jnp.ndarray:
w_shape = self.kernel_shape + (
inputs.shape[self.channel_index] // self.feature_group_count,
self.output_channels)
# Use fan-in scaled init, but WS is largely insensitive to this choice.
w_init = hk.initializers.VarianceScaling(1.0, 'fan_in', 'normal')
w = hk.get_parameter('w', w_shape, inputs.dtype, init=w_init)
weight = self.standardize_weight(w, eps)
out = jax.lax.conv_general_dilated(
inputs, weight, window_strides=self.stride, padding=self.padding,
lhs_dilation=self.lhs_dilation, rhs_dilation=self.kernel_dilation,
dimension_numbers=self.dimension_numbers,
feature_group_count=self.feature_group_count)
# Always add bias
bias_shape = (self.output_channels,)
bias = hk.get_parameter('bias', bias_shape, inputs.dtype, init=jnp.zeros)
return out + bias
class SqueezeExcite(hk.Module):
"""Simple Squeeze+Excite module."""
def __init__(self, in_ch, out_ch, se_ratio=0.5,
hidden_ch=None, activation=jax.nn.relu,
name=None):
super().__init__(name=name)
self.in_ch, self.out_ch = in_ch, out_ch
if se_ratio is None:
if hidden_ch is None:
raise ValueError('Must provide one of se_ratio or hidden_ch')
self.hidden_ch = hidden_ch
else:
self.hidden_ch = max(1, int(self.in_ch * se_ratio))
self.activation = activation
self.fc0 = hk.Linear(self.hidden_ch, with_bias=True)
self.fc1 = hk.Linear(self.out_ch, with_bias=True)
def __call__(self, x):
h = jnp.mean(x, axis=[1, 2]) # Mean pool over HW extent
h = self.fc1(self.activation(self.fc0(h)))
h = jax.nn.sigmoid(h)[:, None, None] # Broadcast along H, W
return h
class StochDepth(hk.Module):
"""Batchwise Dropout used in EfficientNet, optionally sans rescaling."""
def __init__(self, drop_rate, scale_by_keep=False, name=None):
super().__init__(name=name)
self.drop_rate = drop_rate
self.scale_by_keep = scale_by_keep
def __call__(self, x, is_training) -> jnp.ndarray:
if not is_training:
return x
batch_size = x.shape[0]
r = jax.random.uniform(hk.next_rng_key(), [batch_size, 1, 1, 1],
dtype=x.dtype)
keep_prob = 1. - self.drop_rate
binary_tensor = jnp.floor(keep_prob + r)
if self.scale_by_keep:
x = x / keep_prob
return x * binary_tensor
| slowfast_nfnets-main | base.py |
# Copyright 2022 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.
# ============================================================================
"""Configuration for `train_main.py`."""
from ml_collections import config_dict
def get_cifar10_config():
config = config_dict.ConfigDict()
config.crop_size = (32, 32, 3)
config.image_size = (32, 32, 3)
config.train_subset = 'train'
config.test_subset = 'test'
return config
def get_mnist_config():
config = config_dict.ConfigDict()
config.crop_size = (28, 28, 1)
config.image_size = (28, 28, 1)
config.train_subset = 'train'
config.test_subset = 'test'
return config
def get_wide_resnet_model_config():
config = config_dict.ConfigDict()
config.kwargs = config_dict.ConfigDict()
config.kwargs.depth = 28
config.kwargs.width = 8
config.kwargs.activation = 'softplus'
config.kwargs.activation_kwargs = {}
return config
def get_optimizer_config():
config = config_dict.ConfigDict()
config.learning_rate = 0.1
config.lr_decay_factor = 0.1
config.lr_boundaries = (int(80e3), int(88e3), int(96e3))
config.momentum = 0.9
return config
def get_llr_config():
"""Local linearity regularisation."""
config = config_dict.ConfigDict()
config.loss_weight = 4.
# Weight placed on |d^T grad L|.
config.smoothing_factor = .3
# PGD settings, for the search for point furthest from the linear approx.
config.num_steps = 10
config.epsilon = 8./255.
config.warm_start = 500
return config
def get_training_config():
"""Training configuration, including adversarial and regularisers."""
config = config_dict.ConfigDict()
config.l2_regularizer_weight = 0.0002
config.nominal_loss_weight = 2.
config.adversarial_loss_weight = 0.
config.epsilon = 8./255.
config.train_pgd_steps = 20
config.test_pgd_steps = 50
config.llr = get_llr_config()
return config
def get_config():
"""Full experimental configuration for CIFAR."""
config = config_dict.ConfigDict()
config.dataset = 'cifar10'
config.cifar10 = get_cifar10_config()
config.mnist = get_mnist_config()
config.model = get_wide_resnet_model_config()
config.optimizer = get_optimizer_config()
config.train = get_training_config()
return config
| local_linearity_regularizer-main | local_linearity_regularizer/config.py |
# Copyright 2022 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.
# ============================================================================
"""Batch normalisation."""
import sonnet as snt
import tensorflow.compat.v1 as tf
class BatchNorm(snt.AbstractModule):
"""Batch Normalisation layer that computes moving averages of statistics."""
def __init__(self, decay_rate=0.1,
scale=True, offset=True, eps=1e-5, name='BatchNorm'):
super(BatchNorm, self).__init__(name=name)
self.decay_rate = decay_rate
self.eps = eps
self.name = name
self.use_scale = scale
self.use_offset = offset
def _build(
self, inputs, is_training=True, test_local_stats=False,
get_stats=None, set_stats=None):
"""Applies batch normalisation to the inputs.
Args:
inputs: Tensor to which batch normalisation is to be applied.
is_training: Whether to update the exponential moving averages with
the input's batch statistics.
test_local_stats: If `True`, normalises the inputs using its own batch
statistics. If `False`, normalises using the current exponential
moving averages.
get_stats: Optional `dict` to populate with batch stats.
set_stats: Optional `dict` containing override values of batch stats.
Returns:
Normalised copy of `inputs`.
"""
# Compute the batch statistics.
axis = list(range(inputs.shape.ndims - 1))
mean = tf.reduce_mean(inputs, axis=axis)
mean_square = tf.reduce_mean(inputs ** 2, axis=axis)
var = mean_square - mean ** 2
if self.use_scale:
self.gamma = tf.get_variable(
'gamma',
shape=mean.shape.as_list(),
initializer=tf.ones_initializer(),
trainable=True)
else:
self.gamma = None
if self.use_offset:
self.beta = tf.get_variable(
'beta',
shape=mean.shape.as_list(),
initializer=tf.zeros_initializer(),
trainable=True)
else:
self.beta = None
# Exponential moving averages.
accum_counter = tf.get_variable(
'accumulation_counter',
shape=[], dtype=tf.float32,
initializer=tf.zeros_initializer(),
trainable=False)
accum_mean = tf.get_variable(
'accumulated_mean',
shape=mean.shape.as_list(),
initializer=tf.zeros_initializer(),
trainable=False)
accum_var = tf.get_variable(
'accumulated_var',
shape=mean.shape.as_list(),
initializer=tf.ones_initializer(),
trainable=False)
# Handle getting/setting batch statistics.
if get_stats is not None:
# Get the batch statistics.
# Save them into the `get_stats` dict. Use the `accum_xxx`
# variables as keys, because we can rely on them being reused.
get_stats[accum_mean] = mean
get_stats[accum_var] = var
elif set_stats is not None:
# Set the batch statistics.
# These are provided in the `set_stats` dict, populated by having
# been passed to an earlier connection as `get_stats`.
mean = set_stats[accum_mean]
var = set_stats[accum_var]
# Update the moving averages with the batch statistics, if in training mode.
if is_training:
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, tf.group([
tf.assign_add(accum_counter, 1.),
tf.assign_sub(accum_mean, self.decay_rate * (accum_mean - mean)),
tf.assign_sub(accum_var, self.decay_rate * (accum_var - var)),
]))
# Base the batch normalisation either on the moving averages,
# or on the batch statistics.
return tf.nn.batch_normalization(
inputs,
mean if test_local_stats else accum_mean,
var if test_local_stats else accum_var,
offset=self.beta, scale=self.gamma, variance_epsilon=self.eps)
| local_linearity_regularizer-main | local_linearity_regularizer/batchnorm.py |
# Copyright 2022 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.
# ============================================================================
"""Smoke tests for training the model, using mock data."""
import functools
from absl.testing import absltest
import ml_collections
import tensorflow.compat.v1 as tf
from local_linearity_regularizer import datasets
from local_linearity_regularizer import graph
from local_linearity_regularizer import training_loop
from local_linearity_regularizer import wide_resnet
class TrainTest(absltest.TestCase):
def test_training(self):
image_shape = (32, 32, 3)
num_classes = 10
train_batch_size = 5
test_batch_size = 3
# Train and test datasets.
dataset_config = ml_collections.config_dict.ConfigDict({
'image_size': image_shape,
'crop_size': image_shape,
'train_subset': 'train',
'test_subset': 'test',
})
dataset_ctor = functools.partial(MockDataset, image_shape, num_classes)
train_input_fn, test_input_fn = graph.dataset_input_fns(
dataset_config, dataset_ctor, train_batch_size, test_batch_size)
# Classification model.
model = wide_resnet.WideResNet(
num_classes=num_classes,
depth=28, width=8, activation='softplus', activation_kwargs={})
config = ml_collections.config_dict.ConfigDict({
'optimizer': {
'learning_rate': 1.e-2,
'lr_boundaries': [4, 7],
'lr_decay_factor': .5,
'momentum': .9,
},
'train': {
'nominal_loss_weight': 1.,
'adversarial_loss_weight': 0.,
'l2_regularizer_weight': 0.,
'llr': {
'loss_weight': .01,
'smoothing_factor': .3,
'num_steps': 2,
'epsilon': .04,
'warm_start': 2,
},
'epsilon': .03,
'train_pgd_steps': 2,
'test_pgd_steps': 3,
},
})
loss, train_measures, test_measures, init_step_fn = graph.build_graph(
config, train_input_fn, test_input_fn,
datasets.cifar10_model_preprocess, model)
checkpoint = MockCheckpoint()
training_loop.train(
loss, train_measures, test_measures, init_step_fn, checkpoint,
num_runs=10,
test_every=3, num_test_runs=2)
class MockCheckpoint(training_loop.Checkpoint):
"""Placeholder for checkpointing."""
def __init__(self):
super().__init__()
self._state = {}
def restore_or_save(self, session):
pass
def save(self, session, step):
pass
@property
def state(self):
return self._state
class MockDataset(object):
"""Dataset with random image pixels and labels."""
def __init__(
self, image_shape, num_classes, batch_size, *,
subset, shuffle, preprocess_fn=(lambda x: x)):
super().__init__()
self._image_shape = image_shape
self._num_classes = num_classes
self._batch_size = batch_size
self._subset = subset
self._shuffle = shuffle
self._preprocess_fn = preprocess_fn
def __call__(self):
return self._make_one_shot_iterator().get_next()
def _make_one_shot_iterator(self):
return self
def get_next(self):
data_batch = {
'image': tf.random.uniform(
minval=0., maxval=1.,
dtype=tf.float32, shape=[self._batch_size, *self._image_shape]),
'label': tf.random.uniform(
maxval=self._num_classes,
dtype=tf.int64, shape=[self._batch_size]),
}
if self._preprocess_fn is not None:
data_batch = self._preprocess_fn(data_batch)
return data_batch
if __name__ == '__main__':
absltest.main()
| local_linearity_regularizer-main | local_linearity_regularizer/train_test.py |
# Copyright 2022 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.
# ============================================================================
"""Builds the robust training graph."""
import collections
import functools
from interval_bound_propagation.src import attacks
import tensorflow.compat.v1 as tf
from local_linearity_regularizer import datasets
from local_linearity_regularizer import regularizers
DatasetInputFns = collections.namedtuple('DatasetInputFns', ['train', 'test'])
def dataset_input_fns(config, dataset_ctor, train_batch_size, test_batch_size):
"""Returns functions to create TensorFlow graph for loading from dataset.
Args:
config: Dataset configuration.
dataset_ctor: Dataset's constructor.
train_batch_size: Batch size for the training set.
test_batch_size: Batch size for the test set.
Returns:
train_input_fn: Callable returning the training data as a nest of tensors.
test_input_fn: Callable returning the test data as a nest of tensors.
"""
train_preprocess_fn = datasets.random_crop_preprocess_fn(
config.image_size, config.crop_size)
train_dataset = dataset_ctor(
train_batch_size,
subset=config.train_subset,
shuffle=True,
preprocess_fn=train_preprocess_fn)
train_input_fn = (
lambda: tf.data.make_one_shot_iterator(train_dataset).get_next())
test_dataset = dataset_ctor(
test_batch_size,
subset=config.test_subset,
shuffle=False)
test_input_fn = (
lambda: tf.data.make_one_shot_iterator(test_dataset).get_next())
return DatasetInputFns(train=train_input_fn, test=test_input_fn)
def _linear_schedule(step, init_step, final_step, init_value, final_value):
"""Returns a scalar interpolated between `init_value` and `final_value`."""
rate = tf.cast(step - init_step, tf.float32) / float(final_step - init_step)
linear_value = rate * (final_value - init_value) + init_value
return tf.clip_by_value(
linear_value, min(init_value, final_value), max(init_value, final_value))
def _top_k_accuracy(labels, logits, k=1):
"""Proportion of examples having true label amongst the top k predicted.
Args:
labels: 3D int64 tensor containing labels. Its shape is
(num_steps_per_run, num_replicas, batch_size_per_replica).
logits: 4D float32 tensor of shape (labels_shape..., num_classes)
containing predicted logits.
k: Positive integer.
Returns:
Float32 scalar containing proportion of examples whose true label is
amongst the top `k` logits.
"""
# Combine the leading dimensions into a single batch dimension.
labels = tf.reshape(labels, [-1])
logits = tf.reshape(logits, [-1, tf.shape(logits)[-1]])
in_top_k = tf.nn.in_top_k(predictions=logits, targets=labels, k=k)
return tf.reduce_mean(tf.cast(in_top_k, tf.float32))
def _optimizer(optimizer_config, global_step):
"""Returns the optimizer with the configured learning rate schedule."""
lr_values = [optimizer_config.learning_rate]
for _ in optimizer_config.lr_boundaries:
lr_values.append(lr_values[-1] * optimizer_config.lr_decay_factor)
learning_rate = tf.train.piecewise_constant(
global_step,
values=lr_values,
boundaries=optimizer_config.lr_boundaries)
return tf.train.MomentumOptimizer(learning_rate, optimizer_config.momentum)
def _margin_logit_loss(model_logits, true_class, clip_loss_value=-30.):
"""Computes difference between logit for true label and next highest."""
num_classes = model_logits.get_shape().as_list()[-1]
logit_mask = tf.one_hot(true_class, depth=num_classes, axis=-1)
label_logits = tf.reduce_sum(logit_mask * model_logits, axis=-1)
logits_with_true_label_neg_inf = model_logits - logit_mask * 10000
highest_nonlabel_logits = tf.reduce_max(
logits_with_true_label_neg_inf, axis=-1)
loss = -(highest_nonlabel_logits - label_logits)
loss = tf.maximum(loss, clip_loss_value)
return tf.reduce_mean(loss)
def carlini_wagner_attack(
model_fn, images, labels, image_bounds, epsilon,
num_steps, learning_rate=0.1):
"""PGD using loss from Carlini-Wagner https://arxiv.org/abs/1608.04644.
More specifically this implements:
* Projected Gradient Descent [Madry, Kurakin]
* on the margin loss described in [Carlini Wagner]
* using the Adam optimizer [Kingma and Ba]
These defaults are chosen as we find this attack to reliably converge to
slightly better solutions than vanilla iterative FGSM.
Note that while this method is named `carlini_wagner`, it does not implement
the original attack described in the Carlini-Wagner paper. The CW attack
treats the norm constraint as a Lagrangian penalty, and performs binary search
on the penalty weight to find the smallest possible perturbation. Here, we
use a fixed perturbation radius, and enforce this constraint with projection.
Args:
model_fn: Callable taking image tensor and returning logits tensor.
images: Tensor of minibatch of images.
labels: Integer 1D tensor containing true labels.
image_bounds: Range of each element of `images`.
epsilon: Admissible L-infinity perturbation radius for the attack.
num_steps: Number of PGD iterations to perform.
learning_rate: PGD learning rate.
Returns:
Tensor of adversarial images found by the attack.
"""
def loss_fn(image):
model_logits = model_fn(image)
return _margin_logit_loss(model_logits, labels)
return attacks.pgd_attack(
loss_fn, images, epsilon, num_steps,
optimizer=attacks.UnrolledAdam(learning_rate),
image_bounds=image_bounds)
def _model_with_preprocess_fn(model, model_preprocess_fn):
"""Combines the model with its preprocessing function.
Args:
model: Callable taking (preprocessed_images, is_training, test_local_stats)
and returning logits.
model_preprocess_fn: Image pre-processing to be combined with `model`.
Returns:
Callable taking (raw_images, is_training, test_local_stats) and returning
logits.
"""
def model_with_preprocess(images, **batchnorm_kwargs):
# Transform inputs from [0, 1] to roughly [-1, +1], which is the range used
# by ResNets. (This may entail slightly different transformations for each
# channel to reflect the dataset statistics.)
# Do so here (instead of during dataset loading) because
# adversarial attacks assume that the model inputs are [0, 1].
images = model_preprocess_fn(images)
return model(images, **batchnorm_kwargs)
return model_with_preprocess
def _train_step(config, model, global_step, optimizer, batch):
"""Creates TensorFlow graph for a single training step.
Args:
config: Experiment configuration.
model: Callable taking (images, is_training, test_local_stats) and
returning logits.
global_step: TensorFlow global step counter.
optimizer: Training optimiser.
batch: Dict of tensors for the minibatch, under keys 'image' and 'label'.
Returns:
loss: Training loss being minimised.
logits: Nominal logits, of shape [batch_size, num_classes].
adv_logits: Adversarial logits, of shape [batch_size, num_classes].
labels: True labels of the examples in the minibatch.
"""
images = batch['image']
labels = batch['label']
# Nominal.
logits = model(images, is_training=True, test_local_stats=True)
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
# Adversarial.
if config.adversarial_loss_weight > 0.:
adv_images = carlini_wagner_attack(
functools.partial(model, is_training=False, test_local_stats=False),
images, labels,
image_bounds=(0., 1.),
epsilon=config.epsilon,
num_steps=config.train_pgd_steps)
adv_logits = model(adv_images, is_training=False, test_local_stats=True)
adv_cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=adv_logits, labels=labels)
else:
adv_logits = tf.zeros_like(logits)
adv_cross_entropy = tf.zeros_like(cross_entropy)
# Local linearity regulariser.
if config.llr.loss_weight > 0.:
linear_epsilon = _linear_schedule(
global_step, 0, config.llr.warm_start, 0, config.llr.epsilon)
linearity_loss = regularizers.local_linearity(
model, images, labels,
epsilon=linear_epsilon,
num_steps=config.llr.num_steps,
smoothing_factor=config.llr.smoothing_factor)
else:
linearity_loss = 0.
# Combine the losses.
classification_loss = tf.reduce_mean(
config.nominal_loss_weight * cross_entropy +
config.adversarial_loss_weight * adv_cross_entropy)
regularization_loss = (
regularizers.l2_regularization_loss(config.l2_regularizer_weight) +
config.llr.loss_weight * linearity_loss)
loss = tf.add(classification_loss, regularization_loss, name='loss')
# Optimise.
train_op = optimizer.minimize(loss, global_step=global_step)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops + [train_op]):
loss = tf.identity(loss)
return loss, logits, adv_logits, labels
def _test_step(config, model, batch):
"""Creates TensorFlow graph for a model evaluation step.
Args:
config: Experiment configuration.
model: Callable taking (images, is_training, test_local_stats) and
returning logits.
batch: Dict of tensors for the minibatch, under keys 'image' and 'label'.
Returns:
logits: Nominal logits, of shape [batch_size, num_classes].
adv_logits: Adversarial logits, of shape [batch_size, num_classes].
labels: True labels of the examples in the minibatch.
"""
images = batch['image']
labels = batch['label']
# Nominal.
logits = model(images, is_training=False, test_local_stats=False)
# Adversarial.
adv_images = carlini_wagner_attack(
functools.partial(model, is_training=False, test_local_stats=False),
images, labels,
image_bounds=(0., 1.),
epsilon=config.epsilon,
num_steps=config.test_pgd_steps)
adv_logits = model(adv_images, is_training=False, test_local_stats=False)
return logits, adv_logits, labels
def build_graph(
config,
train_input_fn, test_input_fn, model_preprocess_fn, model):
"""Builds the training graph.
Args:
config: Training configuration.
train_input_fn: Callable returning the training data as a nest of tensors.
test_input_fn: Callable returning the test data as a nest of tensors.
model_preprocess_fn: Image pre-processing that should be combined with
the model for adversarial evaluation.
model: Callable taking (preprocessed_images, is_training, test_local_stats)
and returning logits.
Returns:
loss: 0D tensor containing the loss to be minimised.
train_measures: Dict (with string keys) of 0D tensors containing
training measurements.
test_measures: Dict (with string keys) of 0D tensors containing
test set evaluation measurements.
init_step_fn: Function taking (session, initial_step_val)
to be invoked to initialise the global training step.
"""
global_step = tf.train.get_or_create_global_step()
optimizer = _optimizer(config.optimizer, global_step)
model_with_preprocess = _model_with_preprocess_fn(
model, model_preprocess_fn)
# Training step.
loss, train_logits, train_adv_logits, train_labels = _train_step(
config.train, model_with_preprocess, global_step, optimizer,
train_input_fn())
train_measures = {
'acc': _top_k_accuracy(train_labels, train_logits),
}
if config.train.adversarial_loss_weight > 0.:
train_measures.update({
'adv_acc': _top_k_accuracy(train_labels, train_adv_logits),
})
# Test evaluation.
with tf.name_scope('test_accuracy'):
test_logits, test_adv_logits, test_labels = _test_step(
config.train, model_with_preprocess, test_input_fn())
test_measures = {
'acc': _top_k_accuracy(test_labels, test_logits),
'adv_acc': _top_k_accuracy(test_labels, test_adv_logits),
}
initial_step = tf.placeholder(shape=(), dtype=tf.int64)
init_global_step_op = tf.assign(global_step, initial_step)
def init_step_fn(session, initial_step_val):
session.run(init_global_step_op, feed_dict={initial_step: initial_step_val})
return loss, train_measures, test_measures, init_step_fn
| local_linearity_regularizer-main | local_linearity_regularizer/graph.py |
# Copyright 2022 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.
# ============================================================================
"""Dataset preprocessing utilities."""
import functools
import numpy as np
import tensorflow.compat.v1 as tf
CIFAR10_CLASSES = [
'airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck',
]
def random_crop(image, image_shape, crop_shape):
"""Data augmentation used in training.
Args:
image: 4D tensor of shape (batch_size, image_height, image_width, channels)
image_shape: A tuple of (image_height, image_width, channels)
crop_shape: A tuple of (crop_height, crop_width, channels)
Returns:
fn: A cropping function, which takes a Tensor for a single image and
returns a Tensor for a cropped version of the image.
"""
has_batch = len(image.shape) > len(image_shape)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.reshape(image, [-1] + list(image_shape))
image = tf.image.random_flip_left_right(image)
image = tf.pad(
image, paddings=[[0, 0], [4, 4], [4, 4], [0, 0]], mode='REFLECT')
image = tf.random_crop(image, [tf.shape(image)[0]] + list(crop_shape))
# Remove the batch dimension if it didn't originally have one.
if not has_batch:
image = tf.squeeze(image, axis=0)
return image
def random_crop_preprocess_fn(image_shape, crop_shape):
"""Pre-processing to occur as part of the training dataset.
Pre-processing for the training set entails random cropping. The test set
receives no pre-processing: it's just the identity function.
Args:
image_shape: A tuple of (image_height, image_width, channels)
crop_shape: A tuple of (crop_height, crop_width, channels)
Returns:
Data batch preprocessing function, accepting and returning a `dict` with
keys 'image' and 'label'.
"""
image_fn = functools.partial(
random_crop, image_shape=image_shape, crop_shape=crop_shape)
return lambda x: {'image': image_fn(x['image']), 'label': x['label']}
def cifar10_model_preprocess(image):
"""Processing which should be combined with model for adv eval.
Performs an affine transform on each element of the image tensor to map them
to a range that straddles zero. A slightly different transform is applied
to each channel to reflect the statistics of the Cifar-10 dataset.
Args:
image: 4D NHWC image tensor with float32 values in the range [0, 1].
Returns:
4D NHWC image tensor with float32 values in the approximate range [-1, +1].
"""
cifar_means = [125.3, 123.0, 113.9]
cifar_devs = [63.0, 62.1, 66.7]
rescaled_means = np.array([x / 255. for x in cifar_means])
rescaled_devs = np.array([x / 255. for x in cifar_devs])
return (image - rescaled_means) / rescaled_devs
def mnist_model_preprocess(image):
"""Processing which should be combined with model for adv eval."""
return 2. * image - 1.
| local_linearity_regularizer-main | local_linearity_regularizer/datasets.py |
# Copyright 2022 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.
# ============================================================================
"""Robust training and evaluation loop."""
import abc
from absl import logging
import numpy as np
import tensorflow.compat.v1 as tf
class Checkpoint(metaclass=abc.ABCMeta):
"""Interface for regularly saving progress, in case of interruption."""
@abc.abstractmethod
def restore_or_save(self, session):
"""Restores an existing checkpoint if any; otherwise saves an initial one.
If a checkpoint is already present from an earlier abortive run (as
determined by the implementation), it is loaded so that training can
resume from where it left off. Both the TensorFlow trainable variables and
the Python loop state are restored.
If no such checkpoint is present, so there have been no earlier partial
attempts at this training, an initial checkpoint is saved.
Args:
session: TensorFlow session.
"""
@abc.abstractmethod
def save(self, session, step):
"""Saves a new checkpoint.
Both the TensorFlow trainable variables and the Python loop state are saved,
in case the run is accidentally interrupted.
Args:
session: TensorFlow session.
step: Training step, so that the implementation can elect to save a
checkpoint only every n steps.
"""
@property
@abc.abstractmethod
def state(self):
"""String-keyed dictionary of Python loop state."""
def train(loss, train_measures, test_measures, init_step_fn, checkpoint,
num_runs,
test_every=0, num_test_runs=0,
master='', train_writer=None, test_writer=None):
"""Builds and trains model.
Args:
loss: 0D tensor containing the loss to be minimised.
train_measures: Dict (with string keys) of 0D tensors containing
training measurements.
test_measures: Dict (with string keys) of 0D tensors containing
test set evaluation measurements.
init_step_fn: Function taking (session, initial_step_val)
to be invoked to initialise the global training step.
checkpoint: Checkpoint to save progress for resilience against interruption.
num_runs: Number of training runs to perform. Each run consists of
several training steps, as specified by `num_steps_per_run`.
test_every: Frequency (expressed as 'every n training runs') with which to
perform a full test set evaluation. Zero means never.
num_test_runs: Number of test runs to perform in order to complete a full
test set evaluation.
master: Name of the TensorFlow master to use.
train_writer: Optional XData writer to record `train_measures`.
test_writer: Optional XData writer to record `test_measures`.
"""
checkpoint.state['completed_runs'] = 0
full_test_set_evaluation = _make_full_test_set_evaluation_fn(
test_measures, num_test_runs, test_writer=test_writer)
with tf.train.MonitoredTrainingSession(
master=master, is_chief=True, chief_only_hooks=[], hooks=[],
config=tf.ConfigProto(
allow_soft_placement=True)
) as session:
checkpoint.restore_or_save(session._tf_sess()) # pylint: disable=protected-access
# Initialise the global training step.
# This is necessary because it's not stored in the checkpoint.
initial_step_val = checkpoint.state['completed_runs']
init_step_fn(session, initial_step_val)
while checkpoint.state['completed_runs'] < num_runs:
# Training step.
loss_val, train_measure_vals = session.run([loss, train_measures])
run = checkpoint.state['completed_runs'] + 1
step = run
logging.info(
'[%d] loss = %f, training measurements: %s',
step, loss_val, train_measure_vals)
if train_writer is not None:
train_writer.write({
'step': step,
**{'train_' + key: val for key, val in train_measure_vals.items()},
})
if test_every > 0 and run % test_every == 0:
full_test_set_evaluation(session, step)
checkpoint.state['completed_runs'] = run
checkpoint.save(session._tf_sess(), run) # pylint: disable=protected-access
def evaluate(test_measures, num_test_runs=0, master='', test_writer=None):
"""Builds and trains model.
Args:
test_measures: Dict (with string keys) of 0D tensors containing
test set evaluation measurements.
num_test_runs: Number of test runs to perform in order to complete a full
test set evaluation.
master: Name of the TensorFlow master to use.
test_writer: Optional XData writer to record `test_measures`.
"""
full_test_set_evaluation = _make_full_test_set_evaluation_fn(
test_measures, num_test_runs, test_writer=test_writer)
with tf.train.MonitoredTrainingSession(
master=master, is_chief=True, chief_only_hooks=[],
hooks=[],
config=tf.ConfigProto(
allow_soft_placement=True)
) as session:
# Use step=0 because there is only a single evaluation run in this case.
full_test_set_evaluation(session, step=0)
def _make_full_test_set_evaluation_fn(
test_measures, num_test_runs, test_writer=None):
"""Returns a function to perform a full test set evaluation.
Args:
test_measures: Dict (with string keys) of 0D tensors containing
test set evaluation measurements.
num_test_runs: Number of test runs to perform in order to complete a full
test set evaluation.
test_writer: Optional XData writer to record `test_measures`.
Returns:
Callable accepting `(session, step)` to perform a full test set evaluation.
"""
def run(session, step):
test_measure_vals = tf.nest.map_structure(
lambda *x: np.mean(x),
*[session.run(test_measures) for _ in range(num_test_runs)])
logging.info(
'[%d] test set evaluation on %d batches: %s',
step, num_test_runs, test_measure_vals)
if test_writer is not None:
test_writer.write({
'step': step,
**{'test_' + key: val for key, val in test_measure_vals.items()},
})
return run
| local_linearity_regularizer-main | local_linearity_regularizer/training_loop.py |
# Copyright 2022 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.
# ============================================================================
"""Regularizers for robust training."""
from absl import logging
from interval_bound_propagation.src import attacks
import tensorflow.compat.v1 as tf
REGULARIZED_VARIABLES = 'REGULARIZED_VARIABLES'
def l2_regularization_loss(weight):
"""Returns L2 regularization loss on the trainable variables.
Args:
weight: Controls the size of the regularization loss. May be zero if no
regularization is required.
Returns:
L2 regularization loss.
"""
if not (tf.trainable_variables() and weight > 0):
return tf.constant(0.)
# Names of all variables that have already been regularized.
regularization_losses = tf.get_collection(REGULARIZED_VARIABLES)
reg_vars_names = {v.op.name for v in regularization_losses}
def should_be_regularized(var):
"""Checks if a variable is a valid one to be regularized.
A variable is valid if its name ends with '/w', 'w_dw' or '/w_pw' i.e.
is not a bias or a batch norm variable. This function makes sure that
a variable is not regularized twice.
Args:
var: A candidate tensorflow variable.
Returns:
A boolean to indicate whether the variable should be regularized.
"""
var_name = var.op.name
valid_name = var_name.endswith(('/w', '/w_dw', '/w_pw'))
already_regularized = var_name in reg_vars_names
return valid_name and not already_regularized
def l2(tensor):
with tf.name_scope(None, 'L2Regularizer', [tensor]):
l2_weight = tf.convert_to_tensor(
weight, dtype=tensor.dtype.base_dtype, name='weight')
return tf.multiply(l2_weight, tf.nn.l2_loss(tensor), name='value')
regularized_variables = []
reg_losses = []
for var in tf.trainable_variables():
if should_be_regularized(var):
reg_losses.append(l2(var))
tf.add_to_collection(REGULARIZED_VARIABLES, var)
regularized_variables.append(var.op.name)
logging.info('regularizing: %s', ', '.join(sorted(regularized_variables)))
return tf.add_n(reg_losses, name='regularization_loss')
def local_linearity(
model, inputs, labels, epsilon=8./255., num_steps=10, smoothing_factor=2.):
"""Finds the greatest violation of the linear surface in the epsilon-vicinity.
Args:
model: Callable taking (inputs, is_training, test_local_stats,
get_stats, set_stats) and returning logits.
inputs: Tensor containing nominal inputs to the model.
labels: 1D int64 Tensor containing ground truth labels of the inputs.
epsilon: Perturbation radius of the linearity attack.
num_steps: Number of steps of PGD optimization.
smoothing_factor: Weight placed on |d^T grad L|.
Returns:
0D Tensor containing the linearity attack loss.
"""
batch_stats = {}
logits = model(
inputs, is_training=False, test_local_stats=True,
get_stats=batch_stats)
# Use one-hot probs instead of sparse labels.
# This is necessary because tf.nn.sparse_softmax_cross_entropy_with_logits
# does not allow taking the gradient of its gradient.
probs = tf.one_hot(labels, logits.shape[-1].value)
loss = tf.nn.softmax_cross_entropy_with_logits_v2(
logits=logits, labels=probs)
loss_grad = tf.gradients(loss, [inputs])[0]
loss_grad_sg = tf.stop_gradient(loss_grad)
def loss_fn(new_inputs, stop_grad=True, add_extra=False):
"""Local linearity measure for inputs."""
new_logits = model(
new_inputs, is_training=False, test_local_stats=True,
set_stats=batch_stats)
new_loss = tf.nn.softmax_cross_entropy_with_logits_v2(
logits=new_logits, labels=probs)
perturbation = tf.stop_gradient(new_inputs - inputs)
delta_grad = tf.reduce_sum(
perturbation * (loss_grad_sg if stop_grad else loss_grad),
axis=list(range(1, inputs.shape.ndims)))
diff = new_loss - (loss + delta_grad)
attack_loss = tf.sign(diff) * diff
if add_extra:
attack_loss += smoothing_factor * tf.sign(delta_grad) * delta_grad
return -tf.reduce_mean(attack_loss)
adv_x = attacks.pgd_attack(
loss_fn,
inputs,
epsilon=epsilon,
num_steps=num_steps,
image_bounds=(0., 1.),
optimizer=attacks.UnrolledAdam(0.1))
return -loss_fn(adv_x, stop_grad=False, add_extra=True)
| local_linearity_regularizer-main | local_linearity_regularizer/regularizers.py |
# Copyright 2022 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 the training graph building."""
import functools
from absl.testing import absltest
import ml_collections
import sonnet as snt
import tensorflow.compat.v1 as tf
from local_linearity_regularizer import graph
class GraphTest(absltest.TestCase):
def test_dataset_input_fns(self):
train_batch_size = 5
test_batch_size = 7
image_height = 11
image_width = 13
image_channels = 3
dataset_config = ml_collections.config_dict.ConfigDict({
'image_size': (image_height, image_width, image_channels),
'crop_size': (image_height, image_width, image_channels),
'train_subset': '_train',
'test_subset': '_test',
})
# Keep track of calls to the dataset constructor.
dataset_instances = []
def dataset_ctor(*args, **kwargs):
dataset_instance = MockDataset(
(image_height, image_width, image_channels), *args, **kwargs)
dataset_instances.append(dataset_instance)
return dataset_instance
train_input_fn, test_input_fn = graph.dataset_input_fns(
dataset_config, dataset_ctor, train_batch_size, test_batch_size)
# The dataset constructor should have been called twice: once for the
# train subset shuffled, and once for the test subset unshuffled.
self.assertLen(dataset_instances, 2)
self.assertEqual(train_batch_size, dataset_instances[0].batch_size)
self.assertEqual('_train', dataset_instances[0].subset)
self.assertEqual(True, dataset_instances[0].shuffle)
self.assertEqual(test_batch_size, dataset_instances[1].batch_size)
self.assertEqual('_test', dataset_instances[1].subset)
self.assertEqual(False, dataset_instances[1].shuffle)
# Check that each dataset instance yields batches of the correct size.
train_batch = train_input_fn()
self.assertEqual(
[train_batch_size, image_height, image_width, image_channels],
train_batch.shape.as_list())
test_batch = test_input_fn()
self.assertEqual(
[test_batch_size, image_height, image_width, image_channels],
test_batch.shape.as_list())
def test_build_graph(self):
train_batch_size = 5
test_batch_size = 7
config = ml_collections.config_dict.ConfigDict({
'optimizer': self._optimizer_config(),
'train': {
'nominal_loss_weight': 1.,
'adversarial_loss_weight': 0.,
'l2_regularizer_weight': 0.,
'llr': {
'loss_weight': 0.,
},
'epsilon': .1,
'train_pgd_steps': 20,
'test_pgd_steps': 50,
},
})
model = MockModel(num_classes=11)
loss, train_measures, test_measures, _ = graph.build_graph(
config,
functools.partial(self._make_input, train_batch_size),
functools.partial(self._make_input, test_batch_size),
model_preprocess_fn=(lambda x: x),
model=model,
)
# The module should be connected several times - see below.
self.assertLen(model.connection_kwargs, 4)
# Nominal training.
self.assertEqual(True, model.connection_kwargs[0]['is_training'])
self.assertEqual(True, model.connection_kwargs[0]['test_local_stats'])
# Nominal testing.
self.assertEqual(False, model.connection_kwargs[1]['is_training'])
self.assertEqual(False, model.connection_kwargs[1]['test_local_stats'])
# Adversarial testing: attack loop.
self.assertEqual(False, model.connection_kwargs[2]['is_training'])
self.assertEqual(False, model.connection_kwargs[2]['test_local_stats'])
# Adversarial testing: evaluating adversarial example.
self.assertEqual(False, model.connection_kwargs[3]['is_training'])
self.assertEqual(False, model.connection_kwargs[3]['test_local_stats'])
self._assert_is_scalar(loss)
self._assert_is_scalar(train_measures['acc'])
self._assert_is_scalar(test_measures['acc'])
def test_model_preprocess(self):
train_batch_size = 5
test_batch_size = 7
config = ml_collections.config_dict.ConfigDict({
'optimizer': self._optimizer_config(),
'train': {
'nominal_loss_weight': 1.,
'adversarial_loss_weight': 0.,
'l2_regularizer_weight': 0.,
'llr': {
'loss_weight': 0.,
},
'epsilon': .1,
'train_pgd_steps': 20,
'test_pgd_steps': 50,
},
})
# Keep track of invocations of the preprocess function.
model_preprocess_calls = []
def model_preprocess_fn(x):
model_preprocess_calls.append(x)
return 1. - x
graph.build_graph(
config,
functools.partial(self._make_input, train_batch_size),
functools.partial(self._make_input, test_batch_size),
model_preprocess_fn=model_preprocess_fn,
model=MockModel(num_classes=11),
)
# Check that the preprocess function was called for train and test inputs.
self.assertLen(model_preprocess_calls, 4)
# Nominal training.
self.assertEqual(train_batch_size, model_preprocess_calls[0].shape[0].value)
# Nominal testing.
self.assertEqual(test_batch_size, model_preprocess_calls[1].shape[0].value)
# Adversarial testing: attack loop.
self.assertEqual(test_batch_size, model_preprocess_calls[2].shape[0].value)
# Adversarial testing: evaluating adversarial example.
self.assertEqual(test_batch_size, model_preprocess_calls[3].shape[0].value)
def _optimizer_config(self):
return {
'learning_rate': 1.e-2,
'lr_boundaries': [1000],
'lr_decay_factor': .5,
'momentum': .9,
}
def _make_input(
self, batch_size, image_height=17, image_width=19, image_channels=3):
return {
'image': tf.placeholder(dtype=tf.float32, shape=[
batch_size, image_height, image_width, image_channels]),
'label': tf.placeholder(dtype=tf.int64, shape=[batch_size]),
}
def _assert_is_scalar(self, x):
self.assertEqual(x.dtype, tf.float32)
self.assertEqual(x.shape.as_list(), [])
class MockDataset(object):
"""Trivial dataset that records its call arguments."""
def __init__(
self, image_shape, batch_size, subset, shuffle=True, preprocess_fn=None):
super().__init__()
self._image_shape = image_shape
self._batch_size = batch_size
self._subset = subset
self._shuffle = shuffle
self._preprocess_fn = preprocess_fn
@property
def batch_size(self):
return self._batch_size
@property
def subset(self):
return self._subset
@property
def shuffle(self):
return self._shuffle
def __call__(self):
return self._make_one_shot_iterator().get_next()
def _make_one_shot_iterator(self):
return self
def get_next(self):
return tf.placeholder(
dtype=tf.float32, shape=[self._batch_size, *self._image_shape])
class MockModel(snt.AbstractModule):
"""Trivial Sonnet module that records its call arguments."""
def __init__(self, num_classes):
super().__init__()
self._num_classes = num_classes
self._connection_kwargs = []
@property
def connection_kwargs(self):
return self._connection_kwargs
def _build(self, inputs, **kwargs):
# Log the arguments for this connection to the graph.
self._connection_kwargs.append(kwargs)
mean = tf.reduce_mean(inputs, axis=list(range(1, inputs.shape.ndims)))
b = tf.get_variable('b', dtype=tf.float32, shape=[self._num_classes])
return tf.expand_dims(mean, 1) + b
if __name__ == '__main__':
absltest.main()
| local_linearity_regularizer-main | local_linearity_regularizer/graph_test.py |
# Copyright 2022 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.
# ============================================================================
"""TensorFlow version of the Wide ResNet model from Zagoruyko et al 2016.
This implementation is modeled after the reference implementation at:
https://github.com/szagoruyko/wide-residual-networks/tree/master/pytorch
References:
"Wide Residual Networks". (Zagoruyko et al 2016).
https://arxiv.org/pdf/1605.07146.pdf
"Deep Residual Learning for Image Recognition" (He et al 2015a).
https://arxiv.org/pdf/1512.03385.pdf
"Identity Mappings in Deep Residual Networks" (He et al 2015b)
https://arxiv.org/pdf/1603.05027.pdf
"""
import sonnet as snt
import tensorflow.compat.v1 as tf
from local_linearity_regularizer import batchnorm
def he_normal_initializer(seed=None, dtype=tf.float32):
"""He initialization (also called MSR or MSRA initialization).
Args:
seed: A Python integer. Used to create random seeds.
dtype: The data type. Only floating point types are supported.
Returns:
An initializer.
Compared to Glorot initialization (TF default), He initialization uses double
the standard deviation (becaue of ReLUs), and typically uses Gaussians rather
than uniform distributions.
ResNet papers typically use He initialization, and it tends to result slightly
(~0.2%) higher accuracy, though sometimes with BatchNorm this doesn't matter
at all.
"""
return tf.variance_scaling_initializer(
scale=2.0, mode='fan_in', distribution='normal', seed=seed, dtype=dtype)
_DEFAULT_INITIALIZERS = {'w': he_normal_initializer()}
def _bn_activations(
inputs, activation='relu', activation_kwargs=None, decay_rate=0.1,
**batchnorm_kwargs):
"""Batch norm plus activation layer.
Args:
inputs: 4D NHWC tensor of pre-activations.
activation: Name of activation function within `tf.nn`.
activation_kwargs: Additional keyword arguments to `activation`.
decay_rate: Batch norm decay rate.
**batchnorm_kwargs: Keyword arguments to pass through to the batch
normalisation layer.
Returns:
4D NHWC tensor of activations.
"""
activation_kwargs = activation_kwargs or {}
batchnorm_layer = batchnorm.BatchNorm(
decay_rate=decay_rate, scale=True, offset=True)
pre_activations = batchnorm_layer(inputs, **batchnorm_kwargs)
return getattr(tf.nn, activation)(pre_activations, **activation_kwargs)
class WideResNetBlock(snt.AbstractModule):
"""Wide ResNet Block, as implemented in Zagoruyko 2016.
Specifically, this is a pre-activation ResNet block, described in He et al
2015b, where each block consists of repeated applications of
(BN - ReLU - Conv). See Fig. 2b from He et al 2015b for further explanation.
All filters use a 3x3 receptive field. When `num_bottleneck_layers=1`, this
corresponds to the "basic" block in Zagoruyko et al, which is the recommended
block. This also corresponds to the original block structure from He et al
2015a.
The last difference is that when projection shortcuts are used, the
convolutional shortcut layer is applied to the result of the activation,
rather than to the original input. I haven't noticed this documented in the
papers, but I suspect the idea is that there are never two consecutive
convolutional layers without a batch norm layer in between.
"""
def __init__(self,
num_filters,
num_bottleneck_layers=1,
stride=1,
projection_shortcut=False,
activation='relu',
activation_kwargs=None,
decay_rate=0.1,
initializers=None,
name='wide_res_net_block'):
"""A Wide ResNet block, as in Zagoruyko 2016.
Args:
num_filters: An integer, the output dimension of each convolutional layer
in the block.
num_bottleneck_layers: An integer. The number of convolutional layers
between residual connections is `num_bottleneck_layers + 1`. The Wide
ResNet paper recommends that this be fixed at 1, and that depth instead
by modified by changing the number of blocks per layer.
stride: An integer. Stride greater than 1 will spatially downsample the
input. Typically, this is 2 for the first block in every layer (except
the first), and 1 for every other block.
projection_shortcut: A boolean. If `False` (default), an identity
connection is used. Otherwise a convolutional layer is applied after
the first activation. This should be `True` whenever n_in != n_out or
stride > 1. See discussion in class documentation above.
activation: Name of activation function within `tf.nn`.
activation_kwargs: Additional keyword arguments to `activation`.
decay_rate: Batch norm decay rate.
initializers: Optional dict containing ops to initialize the filters (with
key 'w') or biases (with key 'b'). The default initializers are
the He or MSRA initializers. Use `initializers=None` for Glorot
initialization (TF default).
name: A string, the name of the Sonnet module.
"""
super(WideResNetBlock, self).__init__(name=name)
self._num_filters = num_filters
self._num_bottleneck_layers = num_bottleneck_layers
self._stride = stride
self._projection_shortcut = projection_shortcut
if stride > 1 and not projection_shortcut:
raise ValueError('need a projection shortcut with stride > 1')
self._initializers = initializers or _DEFAULT_INITIALIZERS
self._activation = activation
self._activation_kwargs = activation_kwargs
self._decay_rate = decay_rate
def _build(self, x, **batchnorm_kwargs):
orig_x = x
for i in range(self._num_bottleneck_layers + 1):
stride = self._stride if i == 0 else 1
x = _bn_activations(
x,
activation=self._activation,
activation_kwargs=self._activation_kwargs,
decay_rate=self._decay_rate,
**batchnorm_kwargs)
# When using a projection shortcut, the residual connection should
# be applied from after the first activation, rather than before.
if self._projection_shortcut and i == 0:
orig_x = x
x = snt.Conv2D(
self._num_filters, [3, 3], stride=stride, use_bias=False,
initializers=self._initializers, name='conv_{}'.format(i))(x)
if self._projection_shortcut:
shortcut_x = snt.Conv2D(
self._num_filters, [1, 1], stride=self._stride, use_bias=False,
initializers=self._initializers, name='shortcut_x')(orig_x)
x += shortcut_x
else:
x += orig_x
return x
class WideResNet(snt.AbstractModule):
"""Wide ResNet architecture used for experiments in Zagoruyko et al 2016.
For best results, training and evaluation should use the CIFAR-10 pre-
processing functions defined in `datasets.py`. This model achieves 96.0%
accuracy on the CIFAR10 test set.
A ResNet model consists of a single 3x3 convolutional layer, followed by three
ResNet "layers", followed by a non-linearity, spatial average pooling, and a
final linear layer.
Each ResNet "layer" (not to be confused with a single layer of a neural
network) consists of a number of ResNet Blocks, which is determined by the
`depth` parameter.
Within each layer, the first ResNet block should use a projection shortcut,
and all others should use identity shortcuts. Each layer also operates at a
different spatial resolution (32x32, 16x16, and 8x8), which means that the
first ResNet block in each ResNet layer, other than the first, should also
use a stride of 2.
"""
def __init__(self,
depth=28,
width=10,
num_classes=10,
activation='relu',
activation_kwargs=None,
decay_rate=0.1,
initializers=None,
name='wide_res_net'):
"""A Wide ResNet block, as in Zagoruyko 2016.
Args:
depth: Number of layers. Must be 6n+4 for some positive integer n.
width: Controls the number of channels per hidden layer. The number of
channels will be initially `16*num_width`, increasing to `64*num_width`.
num_classes: Number of output classes.
activation: Name of activation function within `tf.nn`.
activation_kwargs: Additional keyword arguments to `activation`.
decay_rate: Batch norm decay rate.
initializers: Optional dict containing ops to initialize the filters (with
key 'w') or biases (with key 'b'). The default initializers are
the He or MSRA initializers. Use `initializers=None` for Glorot
initialization (TF default).
name: A string, the name of the Sonnet module.
"""
super(WideResNet, self).__init__(name=name)
if (depth - 4) % 6 != 0 or depth < 10:
raise ValueError('depth is {}, but must be 6n+4'.format(depth))
self._depth = depth
self._width = width
self._num_classes = num_classes
self._initializers = initializers or _DEFAULT_INITIALIZERS
self._activation = activation
self._activation_kwargs = activation_kwargs
self._decay_rate = decay_rate
def _build(self, x, **batchnorm_kwargs):
blocks_per_layer = (self._depth - 4) // 6
filter_sizes = [self._width * n for n in [16, 32, 64]]
x = snt.Conv2D(
filter_sizes[0], [3, 3], stride=1, use_bias=False,
initializers=self._initializers, name='init_conv')(x)
for layer_num, filter_size in enumerate(filter_sizes):
for i in range(blocks_per_layer):
stride = 2 if (layer_num != 0 and i == 0) else 1
projection_shortcut = (i == 0)
block = WideResNetBlock(
filter_size,
num_bottleneck_layers=1,
stride=stride,
projection_shortcut=projection_shortcut,
activation=self._activation,
activation_kwargs=self._activation_kwargs,
decay_rate=self._decay_rate,
initializers=self._initializers,
name='resnet_lay_{}_block_{}'.format(layer_num, i))
x = block(x, **batchnorm_kwargs)
x = _bn_activations(
x,
activation=self._activation,
activation_kwargs=self._activation_kwargs,
decay_rate=self._decay_rate,
**batchnorm_kwargs)
x = tf.reduce_mean(x, axis=[1, 2], keepdims=False, name='avg_pool')
x = snt.Linear(self._num_classes, initializers=self._initializers)(x)
return x
| local_linearity_regularizer-main | local_linearity_regularizer/wide_resnet.py |
# Copyright 2022 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.
# ============================================================================
"""Training script using Wide ResNet.
To run locally:
python3 train_main.py --config=config.py
"""
import functools
from absl import app
from absl import flags
from ml_collections import config_flags
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
from local_linearity_regularizer import datasets
from local_linearity_regularizer import graph
from local_linearity_regularizer import training_loop
from local_linearity_regularizer import wide_resnet
flags.DEFINE_integer('train_batch_size', 64, 'Batch size for training.')
flags.DEFINE_integer('num_runs', 100000, 'Number of training steps to execute.')
flags.DEFINE_integer('test_every', 4000,
'Number of runs between accuracy tests (<=0 to disable).')
flags.DEFINE_integer('test_batch_size', 80,
'Batch size to use for accuracy tests.')
flags.DEFINE_integer('num_test_runs', 125,
'Number of test set batches for accuracy tests.')
config_flags.DEFINE_config_file(
'config', 'config.py', 'Configuration file for the experimental setup.')
FLAGS = flags.FLAGS
class NullCheckpoint(training_loop.Checkpoint):
"""Placeholder for checkpointing."""
def __init__(self):
super().__init__()
self._state = {}
def restore_or_save(self, session):
pass
def save(self, session, step):
pass
@property
def state(self):
return self._state
def tfds_preprocess(batch):
"""Map image pixel values from uint8 [0,255] to float32 [0,1]."""
return {
'image': tf.cast(batch['image'], tf.float32) / 255.,
'label': batch['label'],
}
def tfds_load(name, batch_size, subset, shuffle, preprocess_fn=None):
"""Loads a TFDS dataset, with shuffle/preprocess dictated by the training.
Args:
name: TFDS name, e.g. 'cifar10'.
batch_size: Batch size.
subset: Dataset split, e.g. 'train'.
shuffle: Whether to shuffle the dataset.
preprocess_fn: Preprocessing requested by the training algorithm, for
example random cropping.
Returns:
TF Dataset structured as {'image': batch of HWC images with values in [0,1],
'label': batch of integer labels}.
"""
ds = tfds.load(name, split=subset).cache().repeat()
if shuffle:
ds = ds.shuffle(10 * batch_size, seed=0)
ds = ds.batch(batch_size)
ds = ds.map(tfds_preprocess)
if preprocess_fn:
ds = ds.map(preprocess_fn)
return ds
def main(_):
config = FLAGS.config
# Train and test datasets.
if config.dataset == 'cifar10':
model_preprocess_fn = datasets.cifar10_model_preprocess
elif config.dataset == 'mnist':
model_preprocess_fn = datasets.mnist_model_preprocess
else:
raise ValueError('Unsupported dataset: ' + config.dataset)
_, dataset_info = tfds.load(config.dataset, split='train', with_info=True)
num_classes = dataset_info.features['label'].num_classes
train_input_fn, test_input_fn = graph.dataset_input_fns(
config[config.dataset],
functools.partial(tfds_load, config.dataset),
FLAGS.train_batch_size,
FLAGS.test_batch_size)
# Classification model.
model = wide_resnet.WideResNet(
num_classes=num_classes, **config.model.kwargs.to_dict())
loss, train_measures, test_measures, init_step_fn = graph.build_graph(
config, train_input_fn, test_input_fn, model_preprocess_fn, model)
checkpoint = NullCheckpoint()
training_loop.train(
loss, train_measures, test_measures, init_step_fn, checkpoint,
num_runs=FLAGS.num_runs,
test_every=FLAGS.test_every, num_test_runs=FLAGS.num_test_runs)
if __name__ == '__main__':
tf.enable_resource_variables()
app.run(main)
| local_linearity_regularizer-main | local_linearity_regularizer/train_main.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.
# ==============================================================================
"""Tests for zipfs_gridworld."""
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from zipfian_environments.gridworld import zipfs_gridworld as zipf_env
from zipfian_environments.gridworld import zipfs_gridworld_core as zipf_env_core
class ZipfFindEnvironmentTest(parameterized.TestCase):
def test_full_wrapper(self):
env = zipf_env.ZipfsGridworldEnvironment(
rng=np.random.default_rng(seed=0)
)
result = env.reset()
self.assertIsNone(result.reward)
scroll_crop_size = zipf_env.SCROLL_CROP_SIZE
upsample_size = zipf_env.UPSAMPLE_SIZE
self.assertEqual(result.observation[0].shape,
(scroll_crop_size * upsample_size,
scroll_crop_size * upsample_size,
3))
us = zipf_env.UPSAMPLE_SIZE
scs = zipf_env.SCROLL_CROP_SIZE
offset = us * (scs // 2)
for i in range(8): # check all actions work
result = env.step(i)
self.assertEqual(result.observation[0].shape,
(scroll_crop_size * upsample_size,
scroll_crop_size * upsample_size,
3))
if not result.step_type.last:
# check egocentric scrolling is working, by checking agent is in center
np.testing.assert_array_almost_equal(
result.observation[0][offset:offset + us, offset:offset + us, :],
zipf_env._CHAR_TO_TEMPLATE_BASE[zipf_env_core.AGENT_CHAR] / 255.)
# check goal object cue in the top left as intended
np.testing.assert_array_almost_equal(
result.observation[0][:us, :us, :],
env._cue_template / 255.)
@parameterized.parameters(
"uniform",
"uniform_rare",
"zipf_1",
"zipf_1.5",
"zipf_2",
)
def test_simple_builder(self, level_name):
env = zipf_env.simple_builder(level_name)
env.reset()
scroll_crop_size = zipf_env.SCROLL_CROP_SIZE
upsample_size = zipf_env.UPSAMPLE_SIZE
for i in range(8):
result = env.step(i) # check all 8 movements work
self.assertEqual(result.observation[0].shape,
(scroll_crop_size * upsample_size,
scroll_crop_size * upsample_size,
3))
if __name__ == "__main__":
absltest.main()
| zipfian_environments-main | gridworld/zipfs_gridworld_test.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.
# ==============================================================================
"""The pycolab core of the environment for Zipf's Gridworld."""
import curses
import enum
from absl import app
from absl import flags
from absl import logging
import numpy as np
from pycolab import ascii_art
from pycolab import human_ui
from pycolab import things as plab_things
from pycolab.prefab_parts import sprites as prefab_sprites
from zipfian_environments.gridworld import map_building
FLAGS = flags.FLAGS
DEFAULT_NUM_ROOMS = (3, 3)
DEFAULT_ROOM_SIZE = (3, 3) # note one square around each room will be wall.
DEFAULT_NUM_MAPS = 20
DEFAULT_NUM_OBJECTS = 20
DEFAULT_ZIPF_EXPONENT = 2
AGENT_CHAR = map_building.AGENT_CHAR
WALL_CHAR = map_building.WALL_CHAR
FLOOR_CHAR = map_building.FLOOR_CHAR
OBJECT_SHAPES = [
"triangle", "empty_square", "plus", "inverse_plus", "ex", "inverse_ex",
"circle", "empty_circle", "tee", "upside_down_tee",
"h", "u", "upside_down_u", "vertical_stripes", "horizontal_stripes"
]
COLORS = {
"red": np.array([255, 0, 0]),
"green": np.array([0, 255, 0]),
"blue": np.array([0, 0, 255]),
"purple": np.array([128, 0, 128]),
"orange": np.array([255, 165, 0]),
"yellow": np.array([255, 255, 0]),
"brown": np.array([128, 64, 0]),
"pink": np.array([255, 64, 255]),
"cyan": np.array([0, 255, 255]),
"dark_green": np.array([0, 100, 0]),
"dark_red": np.array([100, 0, 0]),
"dark_blue": np.array([0, 0, 100]),
"teal": np.array([0, 100, 100]),
"lavender": np.array([215, 200, 255]),
"rose": np.array([255, 205, 230]),
}
def zipf_dist(n, exponent=1.):
vals = 1./(np.arange(1, n + 1))**exponent
return vals / np.sum(vals)
def uniform_rare_dist(n):
vals = np.zeros([n], dtype=np.float32)
num_rare = n // 5
vals[-num_rare:] = 1. / num_rare
return vals
# movement directions / actions for agent
class DIRECTIONS(enum.IntEnum):
N = 0
NE = 1
E = 2
SE = 3
S = 4
SW = 5
W = 6
NW = 7
class ObjectDrape(plab_things.Drape):
"""A `Drape` for objects that are to be found."""
def __init__(self, curtain, character, color, shape, value=0.):
super(ObjectDrape, self).__init__(curtain, character)
self.color = color
self.shape = shape
self.value = value
def update(self, actions, board, layers, backdrop, things, the_plot):
if self.curtain[things[AGENT_CHAR].position]:
# Award the player the appropriate amount of reward.
the_plot.add_reward(self.value)
the_plot.terminate_episode()
class PlayerSprite(prefab_sprites.MazeWalker):
"""The player / agent character."""
def __init__(self, corner, position, character):
super(PlayerSprite, self).__init__(
corner, position, character, impassable="#")
def update(self, actions, board, layers, backdrop, things, the_plot):
# agent can move around to look for the target
if actions == DIRECTIONS.N:
self._north(board, the_plot)
elif actions == DIRECTIONS.NE:
self._northeast(board, the_plot)
elif actions == DIRECTIONS.E:
self._east(board, the_plot)
elif actions == DIRECTIONS.SE:
self._southeast(board, the_plot)
elif actions == DIRECTIONS.S:
self._south(board, the_plot)
elif actions == DIRECTIONS.SW:
self._southwest(board, the_plot)
elif actions == DIRECTIONS.W:
self._west(board, the_plot)
elif actions == DIRECTIONS.NW:
self._northwest(board, the_plot)
def make_game(house_map, objects_and_properties):
"""Uses pycolab to turn an ascii map into a game.
Args:
house_map: the ascii art map to use, from generate_map.
objects_and_properties: list of (character, color, shape, value), for
setting up object properties.
Returns:
this_game: Pycolab engine running the specified game.
"""
sprites = {AGENT_CHAR: PlayerSprite}
drape_creators = {}
char_to_color_shape = []
# add dancers to level
for obj, color, shape, value in objects_and_properties:
drape_creators[obj] = ascii_art.Partial(
ObjectDrape, color=color, shape=shape, value=value)
char_to_color_shape.append((obj, color + " " + shape))
if value > 0.:
target_color_shape = color + " " + shape
this_game = ascii_art.ascii_art_to_game(
art=house_map,
what_lies_beneath=" ",
sprites=sprites,
drapes=drape_creators,
update_schedule=[[AGENT_CHAR],
[x[0] for x in objects_and_properties]])
this_game.the_plot["target_color_shape"] = target_color_shape
this_game.the_plot["char_to_color_shape"] = char_to_color_shape
return this_game
def builder(
num_maps=DEFAULT_NUM_MAPS,
num_rooms=DEFAULT_NUM_ROOMS,
room_size=DEFAULT_ROOM_SIZE,
num_objects=DEFAULT_NUM_OBJECTS,
zipf_exponent=DEFAULT_ZIPF_EXPONENT,
override_dist_function=None,
rng=None):
"""Builds a game (a single episode) of Zipf's Gridworld.
Args:
num_maps: The number of maps to sample from.
num_rooms: (n, m) to create a n x m grid of rooms.
room_size: (k, l) to create a k x l room shape.
num_objects: The number of objects to include per map.
zipf_exponent: the exponent to use for the Zipfian distribution, or 0 for
uniform.
override_dist_function: A function that takes as input a number of items,
and outputs a vector giving distribution over that number of items. This
is used for custom evaluation, e.g. on only the rare items.
rng: Optional np rng for reproducible results, e.g.
rng=np.random.default_rng(seed=0).
Returns:
A pycolab game sampled according to the specified distributions.
"""
if override_dist_function is None:
dist_function = lambda n: zipf_dist(n, exponent=zipf_exponent)
else:
dist_function = override_dist_function
# set up distribution over and sample index
map_weighting = dist_function(num_maps)
if rng is None:
rng = np.random.default_rng(1234)
map_index = rng.choice(np.arange(num_maps), p=map_weighting)
# always same map for given index
map_rng = np.random.default_rng(seed=1234 + map_index)
current_map, objects_in_map = map_building.generate_map(
n_rooms=num_rooms, room_size=room_size, n_objs=num_objects,
rng=map_rng
)
# set up object weighting and sample target object
object_weighting = dist_function(num_objects)
target_index = rng.choice(np.arange(num_objects),
p=object_weighting)
values = [1. if i == target_index else 0. for i in range(num_objects)]
# generate set of colors and shapes such that all pairings are unique
these_colors = []
these_shapes = []
while len(these_colors) < num_objects or len(these_shapes) < num_objects:
these_colors = map_rng.choice(list(COLORS.keys()), num_objects + 10,
replace=True)
these_shapes = map_rng.choice(OBJECT_SHAPES[:], num_objects + 10,
replace=True)
# ensure unique pairings
these_colors_and_shapes = sorted(list(set(zip(these_colors, these_shapes))))
map_rng.shuffle(these_colors_and_shapes)
these_colors, these_shapes = zip(*these_colors_and_shapes)
objects_and_properties = list(zip(objects_in_map, these_colors,
these_shapes, values))
logging.info(
"Making game with map_index %i and objects %s",
map_index, str(objects_and_properties))
game = make_game(current_map, objects_and_properties)
return game
def main(argv):
del argv # unused
game = builder()
# Note that these colors are only for human UI
fg_colors = {
AGENT_CHAR: (999, 999, 999), # Agent is white
WALL_CHAR: (300, 300, 300), # Wall, dark grey
FLOOR_CHAR: (0, 0, 0), # Floor
}
obj_chars = map_building.POSSIBLE_OBJECT_CHARS[:20]
cols = [(999 * x / 255.).astype(np.int32)for x in COLORS.values()]
cols = [tuple(x.tolist()) for x in cols] * 2
obj_chars_and_colors = zip(
obj_chars, cols
)
fg_colors.update(dict(obj_chars_and_colors))
bg_colors = {
c: (0, 0, 0) for c in map_building.RESERVED_CHARS + obj_chars
}
ui = human_ui.CursesUi(
keys_to_actions={
# Basic movement.
curses.KEY_UP: DIRECTIONS.N,
curses.KEY_DOWN: DIRECTIONS.S,
curses.KEY_LEFT: DIRECTIONS.W,
curses.KEY_RIGHT: DIRECTIONS.E,
"w": DIRECTIONS.N,
"d": DIRECTIONS.E,
"x": DIRECTIONS.S,
"a": DIRECTIONS.W,
"q": DIRECTIONS.NW,
"e": DIRECTIONS.NE,
"z": DIRECTIONS.SW,
"c": DIRECTIONS.SE,
-1: 8, # Do nothing.
},
delay=500,
colour_fg=fg_colors,
colour_bg=bg_colors)
ui.play(game)
if __name__ == "__main__":
app.run(main)
| zipfian_environments-main | gridworld/zipfs_gridworld_core.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 pycolab environment for finding objects in skewed environments.
Both the maps and the objects to find in each map are zipfian distributed.
The room is upsampled at a size of 9 pixels per square to render a view for the
agent, which is cropped in egocentric perspective, i.e. the agent is always in
the center of its view (see https://arxiv.org/abs/1910.00571).
"""
from absl import flags
import dm_env
import numpy as np
from pycolab import cropping
from zipfian_environments.gridworld import zipfs_gridworld_core as env_core
FLAGS = flags.FLAGS
UPSAMPLE_SIZE = 9 # pixels per game square
SCROLL_CROP_SIZE = 7 # in game squares
OBJECT_SHAPES = env_core.OBJECT_SHAPES
COLORS = env_core.COLORS
def _generate_template(object_name):
"""Generates a template object image, given a name with color and shape."""
object_color, object_type = object_name.split()
template = np.zeros((UPSAMPLE_SIZE, UPSAMPLE_SIZE))
half = UPSAMPLE_SIZE // 2
if object_type == "triangle":
for i in range(UPSAMPLE_SIZE):
for j in range(UPSAMPLE_SIZE):
if (j <= half and i >= 2 * (half - j)) or (j > half and i >= 2 *
(j - half)):
template[i, j] = 1.
elif object_type == "square":
template[:, :] = 1.
elif object_type == "empty_square":
template[:2, :] = 1.
template[-2:, :] = 1.
template[:, :2] = 1.
template[:, -2:] = 1.
elif object_type == "plus":
template[:, half - 1:half + 2] = 1.
template[half - 1:half + 2, :] = 1.
elif object_type == "inverse_plus":
template[:, :] = 1.
template[:, half - 1:half + 2] = 0.
template[half - 1:half + 2, :] = 0.
elif object_type == "ex":
for i in range(UPSAMPLE_SIZE):
for j in range(UPSAMPLE_SIZE):
if abs(i - j) <= 1 or abs(UPSAMPLE_SIZE - 1 - j - i) <= 1:
template[i, j] = 1.
elif object_type == "inverse_ex":
for i in range(UPSAMPLE_SIZE):
for j in range(UPSAMPLE_SIZE):
if not (abs(i - j) <= 1 or abs(UPSAMPLE_SIZE - 1 - j - i) <= 1):
template[i, j] = 1.
elif object_type == "circle":
for i in range(UPSAMPLE_SIZE):
for j in range(UPSAMPLE_SIZE):
if (i - half)**2 + (j - half)**2 <= half**2:
template[i, j] = 1.
elif object_type == "empty_circle":
for i in range(UPSAMPLE_SIZE):
for j in range(UPSAMPLE_SIZE):
if abs((i - half)**2 + (j - half)**2 - half**2) < 6:
template[i, j] = 1.
elif object_type == "tee":
template[:, half - 1:half + 2] = 1.
template[:3, :] = 1.
elif object_type == "upside_down_tee":
template[:, half - 1:half + 2] = 1.
template[-3:, :] = 1.
elif object_type == "h":
template[:, :3] = 1.
template[:, -3:] = 1.
template[half - 1:half + 2, :] = 1.
elif object_type == "u":
template[:, :3] = 1.
template[:, -3:] = 1.
template[-3:, :] = 1.
elif object_type == "upside_down_u":
template[:, :3] = 1.
template[:, -3:] = 1.
template[:3, :] = 1.
elif object_type == "vertical_stripes":
for j in range(half + UPSAMPLE_SIZE % 2):
template[:, 2*j] = 1.
elif object_type == "horizontal_stripes":
for i in range(half + UPSAMPLE_SIZE % 2):
template[2*i, :] = 1.
else:
raise ValueError("Unknown object: {}".format(object_type))
if object_color not in COLORS:
raise ValueError("Unknown color: {}".format(object_color))
template = np.tensordot(template, COLORS[object_color], axes=0)
return template
# Agent and wall templates
_CHAR_TO_TEMPLATE_BASE = {
env_core.AGENT_CHAR:
np.tensordot(
np.ones([UPSAMPLE_SIZE, UPSAMPLE_SIZE]),
np.array([255, 255, 255]),
axes=0),
env_core.WALL_CHAR:
np.tensordot(
np.ones([UPSAMPLE_SIZE, UPSAMPLE_SIZE]),
np.array([40, 40, 40]),
axes=0),
}
# cue background color is light gray
CUE_BACKGROUND = np.array([180, 180, 180])
def add_background_color_to_image(image, background_color):
"""Replaces zeros in the image with background color."""
return np.where(
np.all(image == 0., axis=-1, keepdims=True),
background_color[None, None, :],
image
)
def get_scrolling_cropper(rows=SCROLL_CROP_SIZE, cols=SCROLL_CROP_SIZE,
crop_pad_char=env_core.FLOOR_CHAR):
"""Sets up cropper for egocentric agent view."""
return cropping.ScrollingCropper(rows=rows, cols=cols,
to_track=[env_core.AGENT_CHAR],
pad_char=crop_pad_char,
scroll_margins=(None, None))
class ZipfsGridworldEnvironment(dm_env.Environment):
"""A Python environment API for finding tasks."""
def __init__(
self,
num_maps=env_core.DEFAULT_NUM_MAPS,
num_rooms=env_core.DEFAULT_NUM_ROOMS,
room_size=env_core.DEFAULT_ROOM_SIZE,
num_objects=env_core.DEFAULT_NUM_OBJECTS,
zipf_exponent=env_core.DEFAULT_ZIPF_EXPONENT,
override_dist_function=None,
max_steps=100,
rng=None):
"""Construct a dm_env-compatible wrapper for pycolab games for agent use.
This class inherits from dm_env and has all the expected methods and specs.
It also renders the game from ascii art to pixel observations.
Args:
num_maps: The number of possible maps to sample from.
num_rooms: The number of rooms per map, as a tuple of
(num_rooms_x, num_rooms_y); rooms are layed out in a grid of this size.
room_size: Tuple of (size_x, size_y) for each room, measured in game
squares.
num_objects: The number of objects to place in each map.
zipf_exponent: The strength of the skew, use 0 for a uniform distribution.
override_dist_function: Function that generates a distribution, in lieu of
the zipf_distribution function.
max_steps: The maximum number of steps to allow in an episode, after which
it will terminate.
rng: An optional numpy Random Generator, to set a fixed seed use e.g.
`rng=np.random.default_rng(seed=...)`
"""
# args
self._builder_kwargs = dict(
num_maps=num_maps,
num_rooms=num_rooms,
room_size=room_size,
num_objects=num_objects,
zipf_exponent=zipf_exponent,
override_dist_function=override_dist_function
)
self._max_steps = max_steps
# internal state
if rng is None:
rng = np.random.default_rng(seed=1234)
self._rng = rng
self._current_game = None # Current pycolab game instance.
self._state = None # Current game step state.
self._game_over = None # Whether the game has ended.
self._char_to_template = None # Mapping of chars to images.
self._cue_template = None
# rendering tools
self._cropper = get_scrolling_cropper(SCROLL_CROP_SIZE, SCROLL_CROP_SIZE,
env_core.FLOOR_CHAR)
def _render_observation(self, observation):
"""Renders from raw pycolab image observation to agent-usable pixel ones."""
observation = self._cropper.crop(observation)
obs_rows, obs_cols = observation.board.shape
image = np.zeros([obs_rows * UPSAMPLE_SIZE, obs_cols * UPSAMPLE_SIZE, 3],
dtype=np.float32)
for i in range(obs_rows):
for j in range(obs_cols):
this_char = chr(observation.board[i, j])
if this_char != env_core.FLOOR_CHAR:
image[
i * UPSAMPLE_SIZE:(i + 1) * UPSAMPLE_SIZE, j *
UPSAMPLE_SIZE:(j + 1) * UPSAMPLE_SIZE] = self._char_to_template[
this_char]
# insert cue image, always in agent's top left corner
image[:UPSAMPLE_SIZE, :UPSAMPLE_SIZE] = self._cue_template
image /= 255.
return (image,)
def reset(self):
"""Start a new episode."""
# Build a new game and retrieve its first set of state/reward/discount.
self._current_game = env_core.builder(
rng=self._rng,
**self._builder_kwargs)
# set up rendering, cropping, and state for current game
self._char_to_template = {
k: _generate_template(v) for k, v in self._current_game.the_plot[
"char_to_color_shape"]}
self._char_to_template.update(_CHAR_TO_TEMPLATE_BASE)
self._cue_template = add_background_color_to_image(
_generate_template(
self._current_game.the_plot["target_color_shape"]),
CUE_BACKGROUND)
self._cropper.set_engine(self._current_game)
self._state = dm_env.StepType.FIRST
# let's go!
observation, _, _ = self._current_game.its_showtime()
observation = self._render_observation(observation)
return dm_env.TimeStep(
step_type=self._state,
reward=None,
discount=None,
observation=observation)
def step(self, action):
"""Apply action, step the world forward, and return observations."""
# If needed, reset and start new episode.
if self._state == dm_env.StepType.LAST:
self._clear_state()
if self._current_game is None:
return self.reset()
# Execute the action in pycolab.
observation, reward, discount = self._current_game.play(action)
self._game_over = self._is_game_over()
reward = reward if reward is not None else 0.
observation = self._render_observation(observation)
# Check the current status of the game.
if self._game_over:
self._state = dm_env.StepType.LAST
else:
self._state = dm_env.StepType.MID
return dm_env.TimeStep(
step_type=self._state,
reward=reward,
discount=discount,
observation=observation)
def observation_spec(self):
image_shape = (SCROLL_CROP_SIZE * UPSAMPLE_SIZE,
SCROLL_CROP_SIZE * UPSAMPLE_SIZE,
3)
return (
# vision
dm_env.specs.Array(
shape=image_shape, dtype=np.float32, name="image"),
)
def action_spec(self):
return dm_env.specs.BoundedArray(
shape=[], dtype="int32",
minimum=0, maximum=7,
name="grid_actions")
def _is_game_over(self):
"""Returns whether it is game over, either from the engine or timeout."""
return (self._current_game.game_over or
(self._current_game.the_plot.frame >= self._max_steps))
def _clear_state(self):
"""Clear all the internal information about the game."""
self._state = None
self._current_game = None
self._char_to_template = None
self._game_over = None
def simple_builder(level_name, level_kwargs_overrides=None):
"""Simplifies building from fixed defs.
Args:
level_name: one of 'uniform', 'uniform_rare', or 'zipf_{exponent}' for
{exponent} interpretable as a float.
level_kwargs_overrides: optional dict of overrides to default level
settings, e.g. to run on larger maps or with more objects.
Returns:
A ZipfsGridworldEnvironment with the requested settings.
"""
level_args = dict(
num_maps=env_core.DEFAULT_NUM_MAPS,
num_rooms=env_core.DEFAULT_NUM_ROOMS,
room_size=env_core.DEFAULT_ROOM_SIZE,
num_objects=env_core.DEFAULT_NUM_OBJECTS,
)
if level_kwargs_overrides is not None:
level_args.update(level_kwargs_overrides)
if level_name == "uniform":
level_args["zipf_exponent"] = 0
elif level_name == "uniform_rare":
level_args["zipf_exponent"] = 0
level_args["override_dist_function"] = env_core.uniform_rare_dist
elif level_name[:4] == "zipf":
level_args["zipf_exponent"] = float(level_name[5:])
else:
raise ValueError("Unrecognized level name: " + level_name)
return ZipfsGridworldEnvironment(**level_args)
| zipfian_environments-main | gridworld/zipfs_gridworld.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.
# ==============================================================================
"""Utilities for building ascii maps with multiple rooms."""
import itertools
import numpy as np
AGENT_CHAR = "A"
WALL_CHAR = "#"
FLOOR_CHAR = " "
RESERVED_CHARS = [AGENT_CHAR, WALL_CHAR, FLOOR_CHAR]
POSSIBLE_OBJECT_CHARS = [
chr(i) for i in range(65, 91) if chr(i) not in RESERVED_CHARS
]
def manhattan_dist(x, y):
return abs(x[0] - y[0]) + abs(x[1] - y[1])
def get_neighbors(room, rooms_list):
return [other for other in rooms_list if manhattan_dist(room, other) == 1]
def ensure_connected(rooms_list, room_doors, rng):
"""Adds doors until all rooms are connected to each other."""
connected = rooms_list[:1]
unconnected = []
uncertain = rooms_list[1:]
while uncertain or unconnected:
if uncertain:
connected_new = []
for room in uncertain:
for other in connected:
if room in room_doors[other]:
connected.append(room)
connected_new.append(room)
break
if connected_new: # remove from uncertain
uncertain = list(set(uncertain) - set(connected_new))
else: # nothing new, remaining are unconnected
unconnected = uncertain
uncertain = []
elif unconnected:
connected_new = []
rng.shuffle(unconnected)
for room in unconnected:
connected_neighbors = get_neighbors(room, connected)
if connected_neighbors:
rng.shuffle(connected_neighbors)
other = connected_neighbors[0]
room_doors[room].append(other)
room_doors[other].append(room)
connected_new.append(room)
connected.append(room)
break # otherwise we may overdo it on connections
assert connected_new # should be at least 1 adjacency
uncertain = list(set(unconnected) - set(connected_new))
unconnected = []
return room_doors
def generate_map(n_rooms=(3, 3), room_size=(3, 3), n_objs=20, rng=None):
"""Generates a map for Zipf's Gridworld."""
if rng is None:
rng = np.random.default_rng(seed=0)
rooms_list = list(itertools.product(range(n_rooms[0]), range(n_rooms[1])))
room_doors = {room: [] for room in rooms_list}
# start by adding a random door to each room
for room in rooms_list:
if not room_doors[room]: # if it doesn't already have a door
neighbors = get_neighbors(room, rooms_list)
other = neighbors[rng.integers(len(neighbors))]
room_doors[room].append(other)
room_doors[other].append(room)
# now make sure it's connected
room_doors = ensure_connected(rooms_list, room_doors, rng)
# generate level
row_skip = room_size[0] + 1 # extra for walls
col_skip = room_size[1] + 1
num_rows = n_rooms[0] * row_skip + 1
num_cols = n_rooms[1] * col_skip + 1
level_layout = np.array([[" "] * num_cols] * num_rows)
# insert walls
for i in range(n_rooms[0] + 1):
level_layout[i * row_skip, :] = WALL_CHAR
for i in range(n_rooms[1] + 1):
level_layout[:, i * col_skip] = WALL_CHAR
# add doors
alldoors = []
for room in rooms_list:
for other in set(room_doors[room]):
if other[0] < room[0]:
loc = (room[0] * row_skip,
room[1] * col_skip + rng.integers(1, col_skip))
level_layout[loc] = FLOOR_CHAR
alldoors.append(loc)
elif other[1] < room[1]:
loc = (room[0] * row_skip + rng.integers(1, row_skip),
room[1] * col_skip)
level_layout[loc] = FLOOR_CHAR
alldoors.append(loc)
# add objects (and agent start) where they will not block anything
valid_locations = []
for i in range(num_rows):
for j in range(num_cols):
this_loc = (i, j)
if (i % row_skip) == 0 or (j % col_skip) == 0:
continue # inside wall
if not (((i % row_skip) in (1, row_skip - 1))
or ((j % col_skip) in (1, col_skip - 1))):
continue # not against a wall
adjacencies = [(i, j - 1), (i, j + 1), (i - 1, j), (i + 1, j)]
if any(x in alldoors for x in adjacencies):
continue # blocking a door
valid_locations.append(this_loc)
objs = POSSIBLE_OBJECT_CHARS[:n_objs] + [AGENT_CHAR]
assert len(valid_locations) > len(objs)
rng.shuffle(valid_locations)
for obj, loc in zip(objs, valid_locations):
level_layout[loc] = obj
objs_to_drape = objs[:-1]
# convert to pycolab's ascii format
level_layout = ["".join(x) for x in level_layout.tolist()]
return level_layout, objs_to_drape
| zipfian_environments-main | gridworld/map_building.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.
# ==============================================================================
"""Tests for dm_zipf_playroom.load_from_disk."""
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
from dm_env import test_utils
import dm_zipf_playroom
FLAGS = flags.FLAGS
flags.DEFINE_string('path', '',
'Directory that contains dm_zipf_playroom environment.')
class LoadFromDiskTest(test_utils.EnvironmentTestMixin, absltest.TestCase):
def make_object_under_test(self):
return dm_zipf_playroom.load_from_disk(
FLAGS.path,
settings=dm_zipf_playroom.EnvironmentSettings(
seed=123, level_name='lift/lift_shape_zipf2'))
class FastMappingTaskTest(parameterized.TestCase):
@parameterized.parameters(
dm_zipf_playroom.ZIPFIAN_DISTRIBUTIONS_TASK_LEVEL_NAMES)
def test_load_level(self, level_name):
self.assertIsNotNone(
dm_zipf_playroom.load_from_disk(
FLAGS.path,
settings=dm_zipf_playroom.EnvironmentSettings(
seed=123, level_name=level_name)))
if __name__ == '__main__':
absltest.main()
| zipfian_environments-main | playroom/load_from_disk_test.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.
# ==============================================================================
"""Python utility functions for loading DeepMind Zipfian Distributions Tasks."""
import codecs
import collections
import json
import os
import re
import subprocess
import time
import typing
from absl import logging
import dm_env
import docker
import grpc
import numpy as np
import portpicker
from dm_env_rpc.v1 import connection as dm_env_rpc_connection
from dm_env_rpc.v1 import dm_env_adaptor
from dm_env_rpc.v1 import dm_env_rpc_pb2
from dm_env_rpc.v1 import error
from dm_env_rpc.v1 import tensor_utils
# Maximum number of times to attempt gRPC connection.
_MAX_CONNECTION_ATTEMPTS = 10
# Port to expect the docker environment to internally listen on.
_DOCKER_INTERNAL_GRPC_PORT = 10000
_DEFAULT_DOCKER_IMAGE_NAME = 'gcr.io/google.com/deepmind-environments-staging/dm_zipfian_distributions:dm_zipfian_distributions_staging_gcr_20220629_RC00'
_ZIPFIAN_DISTRIBUTIONS_TASK_OBSERVATIONS = ['RGB_INTERLEAVED', 'TEXT']
ZIPFIAN_DISTRIBUTIONS_TASK_LEVEL_NAMES = frozenset((
'lift/lift_shape_uniform_rare',
'lift/lift_shape_zipf2',
'lift/lift_shape_zipf3',
'lift/lift_shape_zipf4',
'lift/lift_shape_uniform',
'put/lift_shape_many_zipf1',
'put/lift_shape_zipf2',
'put/lift_shape_uniform',
'put/lift_shape_many_zipf4',
'put/put_on_bed_tray_frequent',
'put/put_near_bed_tray_frequent',
'put/put_on_bed_tray_all',
'put/lift_shape_uniform_rare',
'put/put_on_bed_tray_rare',
'supervised/find_shape_zipf3',
'supervised/find_shape_uniform_rare',
'supervised/find_shape_zipf2',
'supervised/find_shape_uniform',
))
_ConnectionDetails = collections.namedtuple('_ConnectionDetails',
['channel', 'connection', 'specs'])
class _ZipfianDistributionsTasksEnv(dm_env_adaptor.DmEnvAdaptor):
"""An implementation of dm_env_rpc.DmEnvAdaptor for Zipfian Distributions tasks."""
def __init__(self, connection_details, requested_observations,
num_action_repeats):
super(_ZipfianDistributionsTasksEnv,
self).__init__(connection_details.connection,
connection_details.specs, requested_observations)
self._channel = connection_details.channel
self._num_action_repeats = num_action_repeats
def close(self):
super(_ZipfianDistributionsTasksEnv, self).close()
self._channel.close()
def step(self, action):
"""Implementation of dm_env.step that supports repeated actions."""
timestep = None
discount = None
reward = None
for _ in range(self._num_action_repeats):
next_timestep = super(_ZipfianDistributionsTasksEnv, self).step(action)
# Accumulate reward per timestep.
if next_timestep.reward is not None:
reward = (reward or 0.) + next_timestep.reward
# Calculate the product for discount.
if next_timestep.discount is not None:
discount = discount if discount else []
discount.append(next_timestep.discount)
timestep = dm_env.TimeStep(next_timestep.step_type, reward,
# Note: np.product(None) returns None.
np.product(discount),
next_timestep.observation)
if timestep.last():
return timestep
return timestep
class _ZipfianDistributionsTasksContainerEnv(_ZipfianDistributionsTasksEnv):
"""An implementation of _ZipfianDistributionsTasksEnv.
Ensures that the provided Docker container is closed on exit.
"""
def __init__(self, connection_details, requested_observations,
num_action_repeats, container):
super(_ZipfianDistributionsTasksContainerEnv,
self).__init__(connection_details, requested_observations,
num_action_repeats)
self._container = container
def close(self):
super(_ZipfianDistributionsTasksContainerEnv, self).close()
try:
self._container.kill()
except docker.errors.NotFound:
pass # Ignore, container has already been closed.
class _ZipfianDistributionsTasksProcessEnv(_ZipfianDistributionsTasksEnv):
"""An implementation of _ZipfianDistributionsTasksEnv.
Ensure that the provided running process is closed on exit.
"""
def __init__(self, connection_details, requested_observations,
num_action_repeats, process):
super(_ZipfianDistributionsTasksProcessEnv,
self).__init__(connection_details, requested_observations,
num_action_repeats)
self._process = process
def close(self):
super(_ZipfianDistributionsTasksProcessEnv, self).close()
self._process.terminate()
self._process.wait()
def _check_grpc_channel_ready(channel):
"""Helper function to check the gRPC channel is ready N times."""
for _ in range(_MAX_CONNECTION_ATTEMPTS - 1):
try:
return grpc.channel_ready_future(channel).result(timeout=1)
except grpc.FutureTimeoutError:
pass
return grpc.channel_ready_future(channel).result(timeout=1)
def _can_send_message(connection):
"""Returns if `connection` is healthy and able to process requests."""
try:
# This should return a response with an error unless the server isn't yet
# receiving requests.
connection.send(dm_env_rpc_pb2.StepRequest())
except error.DmEnvRpcError:
return True
except grpc.RpcError:
return False
def _create_channel_and_connection(port):
"""Returns a tuple of `(channel, connection)`."""
for _ in range(_MAX_CONNECTION_ATTEMPTS):
channel = grpc.secure_channel('localhost:{}'.format(port),
grpc.local_channel_credentials())
_check_grpc_channel_ready(channel)
connection = dm_env_rpc_connection.Connection(channel)
if _can_send_message(connection):
break
else:
# A gRPC server running within Docker sometimes reports that the channel
# is ready but transitively returns an error (status code 14) on first
# use. Giving the server some time to breath and retrying often fixes the
# problem.
connection.close()
channel.close()
time.sleep(1.0)
return channel, connection
def _parse_exception_message(message):
"""Returns a human-readable version of a dm_env_rpc json error message."""
try:
match = re.match(r'^message\:\ \"(.*)\"$', message)
json_data = codecs.decode(match.group(1), 'unicode-escape')
parsed_json_data = json.loads(json_data)
return ValueError(json.dumps(parsed_json_data, indent=4))
except: # pylint: disable=bare-except
return message
def _wrap_send(send):
"""Wraps `send` in order to reformat exceptions."""
try:
return send()
except ValueError as e:
e.args = [_parse_exception_message(e.args[0])]
raise
def _connect_to_environment(port, settings):
"""Helper function for connecting to a running dm_zipfian_distributions environment."""
if settings.level_name not in ZIPFIAN_DISTRIBUTIONS_TASK_LEVEL_NAMES:
raise ValueError(
'Level named "{}" is not a valid dm_zipfian_distributions level.'
.format(settings.level_name))
channel, connection = _create_channel_and_connection(port)
original_send = connection.send
connection.send = lambda request: _wrap_send(lambda: original_send(request))
world_name = connection.send(
dm_env_rpc_pb2.CreateWorldRequest(
settings={
'seed': tensor_utils.pack_tensor(settings.seed),
'episodeId': tensor_utils.pack_tensor(0),
'levelName': tensor_utils.pack_tensor(settings.level_name),
})).world_name
join_world_settings = {
'width':
tensor_utils.pack_tensor(settings.width),
'height':
tensor_utils.pack_tensor(settings.height),
'EpisodeLengthSeconds':
tensor_utils.pack_tensor(settings.episode_length_seconds),
'ShowReachabilityHUD': tensor_utils.pack_tensor(False),
}
specs = connection.send(
dm_env_rpc_pb2.JoinWorldRequest(
world_name=world_name, settings=join_world_settings)).specs
return _ConnectionDetails(channel=channel, connection=connection, specs=specs)
class EnvironmentSettings(typing.NamedTuple):
"""Collection of settings used to start a specific Zipfian Distributions task.
Required attributes:
seed: Seed to initialize the environment's RNG.
level_name: Name of the level to load.
Optional attributes:
width: Width (in pixels) of the desired RGB observation; defaults to 96.
height: Height (in pixels) of the desired RGB observation; defaults to 72.
episode_length_seconds: Maximum episode length (in seconds); defaults to
120.
num_action_repeats: Number of times to step the environment with the
provided action in calls to `step()`.
"""
seed: int
level_name: str
width: int = 96
height: int = 72
episode_length_seconds: float = 120.0
num_action_repeats: int = 1
def _validate_environment_settings(settings):
"""Helper function to validate the provided environment settings."""
if settings.episode_length_seconds <= 0.0:
raise ValueError('episode_length_seconds must have a positive value.')
if settings.num_action_repeats <= 0:
raise ValueError('num_action_repeats must have a positive value.')
if settings.width <= 0 or settings.height <= 0:
raise ValueError('width and height must have a positive value.')
def load_from_disk(path, settings):
"""Loads Zipfian Distributions Tasks from disk.
Args:
path: Directory containing dm_zipfian_distributions environment.
settings: EnvironmentSettings required to start the environment.
Returns:
An implementation of dm_env.Environment.
Raises:
RuntimeError: If unable to start environment process.
"""
_validate_environment_settings(settings)
executable_path = os.path.join(path, 'Linux64Player')
libosmesa_path = os.path.join(path, 'external_libosmesa_llvmpipe.so')
if not os.path.exists(executable_path) or not os.path.exists(libosmesa_path):
raise RuntimeError(
'Cannot find dm_zipfian_distributions executable or dependent files at path: {}'
.format(path))
port = portpicker.pick_unused_port()
process_flags = [
executable_path,
# Unity command-line flags.
'-logfile',
'-batchmode',
'-noaudio',
# Other command-line flags.
'--logtostderr',
'--server_type=GRPC',
'--uri_address=[::]:{}'.format(port),
]
os.environ.update({
'UNITY_RENDERER': 'software',
'UNITY_OSMESA_PATH': libosmesa_path,
})
process = subprocess.Popen(
process_flags, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if process.poll() is not None:
raise RuntimeError(
'Failed to start dm_zipfian_distributions process correctly.')
return _ZipfianDistributionsTasksProcessEnv(
_connect_to_environment(port, settings),
_ZIPFIAN_DISTRIBUTIONS_TASK_OBSERVATIONS, settings.num_action_repeats,
process)
def load_from_docker(settings, name=None):
"""Load Zipfian Distributions Tasks from docker container.
Args:
settings: EnvironmentSettings required to start the environment.
name: Optional name of Docker image that contains the
dm_zipfian_distributions environment. If left unset, uses the
dm_zipfian_distributions default name.
Returns:
An implementation of dm_env.Environment
"""
_validate_environment_settings(settings)
name = name or _DEFAULT_DOCKER_IMAGE_NAME
client = docker.from_env()
port = portpicker.pick_unused_port()
try:
client.images.get(name)
except docker.errors.ImageNotFound:
logging.info('Downloading docker image "%s"...', name)
client.images.pull(name)
logging.info('Download finished.')
container = client.containers.run(
name,
auto_remove=True,
detach=True,
ports={_DOCKER_INTERNAL_GRPC_PORT: port})
return _ZipfianDistributionsTasksContainerEnv(
_connect_to_environment(port, settings),
_ZIPFIAN_DISTRIBUTIONS_TASK_OBSERVATIONS,
settings.num_action_repeats,
container)
| zipfian_environments-main | playroom/load_environment.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.
# ==============================================================================
"""Python utilities for running dm_zipfian_distributions."""
from zipfian_environments.playroom import load_environment
EnvironmentSettings = load_environment.EnvironmentSettings
ZIPFIAN_DISTRIBUTIONS_TASK_LEVEL_NAMES = load_environment.ZIPFIAN_DISTRIBUTIONS_TASK_LEVEL_NAMES
load_from_disk = load_environment.load_from_disk
load_from_docker = load_environment.load_from_docker
| zipfian_environments-main | playroom/__init__.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.
# ==============================================================================
"""Tests for dm_zipf_playroom.zipfs_playroom.load_from_docker."""
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
from dm_env import test_utils
from zipfian_environments import playroom as zipfs_playroom
DOCKER_IMAGE_NAME = flags.DEFINE_string(
'docker_image_name', None,
'Name of the Docker image that contains the Zipfian Distributions Tasks. '
'If None, uses the default dm_zipf_playroom name')
class LoadFromDockerTest(test_utils.EnvironmentTestMixin, absltest.TestCase):
def make_object_under_test(self):
return zipfs_playroom.load_from_docker(
name=DOCKER_IMAGE_NAME.value,
settings=zipfs_playroom.EnvironmentSettings(
seed=123, level_name='lift/lift_shape_zipf2'))
class ZipfianDistributionsTaskTest(parameterized.TestCase):
@parameterized.parameters(
zipfs_playroom.ZIPFIAN_DISTRIBUTIONS_TASK_LEVEL_NAMES)
def test_load_level(self, level_name):
self.assertIsNotNone(
zipfs_playroom.load_from_docker(
name=DOCKER_IMAGE_NAME.value,
settings=zipfs_playroom.EnvironmentSettings(
seed=123, level_name=level_name)))
if __name__ == '__main__':
absltest.main()
| zipfian_environments-main | playroom/load_from_docker_test.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.
# ==============================================================================
"""Example human agent for interacting with DeepMind Zipfian Distributions Tasks."""
from absl import app
from absl import flags
from absl import logging
from dm_zipf_playroom import EnvironmentSettings
from dm_zipf_playroom import load_from_docker
import numpy as np
import pygame
FLAGS = flags.FLAGS
_SCREEN_SIZE = flags.DEFINE_list(
'screen_size', [640, 480],
'Screen width/height in pixels. Scales the environment RGB observations to '
'fit the screen size.')
_DOCKER_IMAGE_NAME = flags.DEFINE_string(
'docker_image_name', None,
'Name of the Docker image that contains the Zipfian Distributions Tasks. '
'If None, uses the default dm_zipfian_distributions name')
_SEED = flags.DEFINE_integer('seed', 123, 'Environment seed.')
_LEVEL_NAME = flags.DEFINE_string('level_name', 'lift/lift_shape_zipf2',
'Name of task to run.')
_FRAMES_PER_SECOND = 30
_KEYS_TO_ACTION = {
pygame.K_w: {'MOVE_BACK_FORWARD': 1},
pygame.K_s: {'MOVE_BACK_FORWARD': -1},
pygame.K_a: {'STRAFE_LEFT_RIGHT': -1},
pygame.K_d: {'STRAFE_LEFT_RIGHT': 1},
pygame.K_UP: {'LOOK_DOWN_UP': -1},
pygame.K_DOWN: {'LOOK_DOWN_UP': 1},
pygame.K_LEFT: {'LOOK_LEFT_RIGHT': -1},
pygame.K_RIGHT: {'LOOK_LEFT_RIGHT': 1},
pygame.K_SPACE: {'HAND_GRIP': 1},
} # pyformat: disable
_NO_ACTION = {
'MOVE_BACK_FORWARD': 0,
'STRAFE_LEFT_RIGHT': 0,
'LOOK_LEFT_RIGHT': 0,
'LOOK_DOWN_UP': 0,
'HAND_GRIP': 0,
}
def main(_):
pygame.init()
try:
pygame.mixer.quit()
except NotImplementedError:
pass
pygame.display.set_caption('Zipfian Distributions Tasks Human Agent')
episode_length_seconds = 120.0
env_settings = EnvironmentSettings(
seed=_SEED.value, level_name=_LEVEL_NAME.value,
episode_length_seconds=episode_length_seconds)
with load_from_docker(
name=_DOCKER_IMAGE_NAME.value, settings=env_settings) as env:
screen = pygame.display.set_mode(
(int(_SCREEN_SIZE.value[0]), int(_SCREEN_SIZE.value[1])))
rgb_spec = env.observation_spec()['RGB_INTERLEAVED']
surface = pygame.Surface((rgb_spec.shape[1], rgb_spec.shape[0]))
actions = _NO_ACTION
score = 0
clock = pygame.time.Clock()
while True:
# Do not close with CTRL-C as otherwise the docker container may be left
# running on exit.
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return
key_actions = _KEYS_TO_ACTION.get(event.key, {})
for name, action in key_actions.items():
actions[name] += action
elif event.type == pygame.KEYUP:
key_actions = _KEYS_TO_ACTION.get(event.key, {})
for name, action in key_actions.items():
actions[name] -= action
timestep = env.step(actions)
frame = np.swapaxes(timestep.observation['RGB_INTERLEAVED'], 0, 1)
font = pygame.font.SysFont('Sans', 10)
pygame.surfarray.blit_array(surface, frame)
text = font.render(timestep.observation['TEXT'], True, (0, 0, 0))
surface.blit(text, (0, 0))
pygame.transform.smoothscale(surface, screen.get_size(), screen)
pygame.display.update()
if timestep.reward:
score += timestep.reward
logging.info('Total score: %1.1f, reward: %1.1f', score,
timestep.reward)
clock.tick(_FRAMES_PER_SECOND)
if __name__ == '__main__':
app.run(main)
| zipfian_environments-main | playroom/examples/human_agent.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 Zipfian distribution over DMLab-30 levels.
To use this environment, you will need to have DMLab installed. For
instructions, see:
https://github.com/deepmind/lab#getting-started-on-linux
For more information on the DMLab-30 levels, see the level definitions:
https://github.com/deepmind/lab/tree/master/game_scripts/levels/contributed/dmlab30
"""
from typing import Sequence
import dm_env
import numpy as np
import deepmind_lab
LEVELS_DMLAB30_FORWARD = [
'rooms_collect_good_objects_train', 'rooms_exploit_deferred_effects_train',
'rooms_select_nonmatching_object', 'rooms_watermaze',
'rooms_keys_doors_puzzle', 'language_select_described_object',
'language_select_located_object', 'language_execute_random_task',
'language_answer_quantitative_question', 'lasertag_one_opponent_small',
'lasertag_three_opponents_small', 'lasertag_one_opponent_large',
'lasertag_three_opponents_large', 'natlab_fixed_large_map',
'natlab_varying_map_regrowth', 'natlab_varying_map_randomized',
'skymaze_irreversible_path_hard', 'skymaze_irreversible_path_varied',
'psychlab_arbitrary_visuomotor_mapping', 'psychlab_continuous_recognition',
'psychlab_sequential_comparison', 'psychlab_visual_search',
'explore_object_locations_small', 'explore_object_locations_large',
'explore_obstructed_goals_small', 'explore_obstructed_goals_large',
'explore_goal_locations_small', 'explore_goal_locations_large',
'explore_object_rewards_few', 'explore_object_rewards_many'
]
# Reverse distribution
LEVELS_DMLAB30_REVERSED = list(reversed(LEVELS_DMLAB30_FORWARD))
DEFAULT_OBS = ('RGB_INTERLEAVED', 'INSTR') # default observations
def zipf_dist(n, exponent=1.):
vals = 1. / (np.arange(1, n + 1))**exponent
return vals / np.sum(vals)
def uniform_rare_dist(n):
vals = np.zeros([n], dtype=np.float32)
num_rare = n // 5
vals[-num_rare:] = 1. / num_rare
return vals
def process_action_spec(lab_action_spec):
"""Processes action specs into dm_env format + produces action map."""
action_spec = {}
action_map = {}
action_count = len(lab_action_spec)
for i, spec in enumerate(lab_action_spec):
name = spec['name']
action_map[name] = i
action_spec[name] = dm_env.specs.BoundedArray(
dtype=np.dtype('int32'),
shape=(),
name=name,
minimum=spec['min'],
maximum=spec['max'])
return action_spec, action_map, action_count
def process_observation_spec(lab_observation_spec, observation_names):
"""Filters observation specs and converts to dm_env format."""
observation_spec = {}
for spec in lab_observation_spec:
name = spec['name']
shape = spec['shape']
if name in observation_names:
observation_spec[name] = dm_env.specs.Array(
dtype=spec['dtype'], shape=shape, name=name)
return observation_spec
class ZipfsLabyrinth(dm_env.Environment):
"""Zipf's Labyrinth environment."""
def __init__(self,
distribution: str = 'zipf1',
reverse_order: bool = False,
observations_to_include: Sequence[str] = DEFAULT_OBS) -> None:
"""Create the environment.
Args:
distribution: name of probability distribution over levels; one of the
following items ['uniform', 'uniform_rare', 'zipf1'].
reverse_order: whether to reverse the order of the levels.
observations_to_include: observations to keep from the environment,
defaults to vision + instruction.
"""
# set up distribution
if distribution == 'uniform':
self._distribution = np.ones((30,), dtype=np.float32) / 30
elif distribution == 'uniform_rare':
self._distribution = uniform_rare_dist(30)
elif distribution[:4] == 'zipf':
self._distribution = zipf_dist(30, exponent=float(distribution[4:]))
# get level names
if reverse_order:
levels = LEVELS_DMLAB30_REVERSED
else:
levels = LEVELS_DMLAB30_FORWARD
self.levels = ['contributed/dmlab30/' + l for l in levels]
# build environments
self._observations_to_include = observations_to_include
self._environments = []
observation_specs = []
action_specs = []
action_maps = []
action_count = None
for level in self.levels:
env = deepmind_lab.Lab(level, ['RGB_INTERLEAVED', 'INSTR'])
self._environments.append(env)
# observation specs
observation_spec = env.observation_spec()
observation_spec = process_observation_spec(observation_spec,
observations_to_include)
observation_specs.append(observation_spec)
# action specs
action_spec = env.action_spec()
action_spec, action_map, action_count = process_action_spec(action_spec)
action_specs.append(action_spec)
action_maps.append(action_map)
self._action_count = action_count
assert all([spec == action_specs[0] for spec in action_specs[1:]])
self._action_spec = action_specs[0]
assert all([action_map == action_maps[0] for action_map in action_maps[1:]])
self._action_map = action_maps[0]
assert all([spec == observation_specs[0] for spec in observation_specs[1:]])
self._observation_spec = observation_specs[0]
self._current_env = None
self._needs_reset = True
def _sample_env(self):
self._current_env = np.random.choice(self._environments,
p=self._distribution)
return self._current_env
def _observation(self):
return {
name: np.asarray(data, dtype=self._observation_spec[name].dtype)
for name, data in self._current_env.observations().items()
}
def reset(self):
"""Start a new episode."""
# sample an environment
self._sample_env()
self._current_env.reset()
self._needs_reset = False
return dm_env.restart(self._observation())
def step(self, action):
if self._needs_reset:
return self.reset()
lab_action = np.empty(self._action_count, dtype=np.dtype('int32'))
for name, value in action.items():
lab_action[self._action_map[name]] = value
reward = self._current_env.step(lab_action)
if self._current_env.is_running():
return dm_env.transition(reward=reward, observation=self._observation())
else:
self._needs_reset = True
return dm_env.termination(reward=reward, observation=self._observation())
@property
def observation_spec(self):
return self._observation_spec
@property
def action_spec(self):
return self._action_spec
| zipfian_environments-main | labyrinth/zipfs_labyrinth.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.
# ==============================================================================
"""Tests for zipfs_gridworld."""
import os
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from zipfian_environments.labyrinth import zipfs_labyrinth as zipf_env
import deepmind_lab
class ZipfsLabyrinthTest(parameterized.TestCase):
@parameterized.named_parameters(
dict(testcase_name="uniform",
distribution="uniform", reverse_order=False),
dict(testcase_name="uniform_rare",
distribution="uniform_rare", reverse_order=False),
dict(testcase_name="zipf_reversed",
distribution="zipf1", reverse_order=True),
)
def test_labyrinth(self, distribution, reverse_order):
env = zipf_env.ZipfsLabyrinth(
distribution=distribution, reverse_order=reverse_order
)
for _ in range(3):
timestep = env.reset()
observation = timestep.observation
self.assertEqual(set(observation.keys()),
set(["RGB_INTERLEAVED", "INSTR"]))
# Instruction shuold be single string
self.assertEqual(observation["INSTR"].shape, tuple())
self.assertIsInstance(observation["INSTR"].item(), str)
# vision should be RGB ints
vision_shape = observation["RGB_INTERLEAVED"].shape
self.assertLen(vision_shape, 3)
self.assertEqual(vision_shape[-1], 3)
self.assertEqual(observation["RGB_INTERLEAVED"].dtype, np.uint8)
for i in [0, 1]:
dummy_action = {k: i for k in env.action_spec.keys()}
env.step(dummy_action)
if __name__ == "__main__":
dmlab_runfiles_path = None # set path here
if dmlab_runfiles_path is not None:
deepmind_lab.set_runfiles_path(dmlab_runfiles_path)
absltest.main()
| zipfian_environments-main | labyrinth/zipfs_labyrinth_test.py |
# Copyright 2018 Google Inc. 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.
"""Simple tests for surface metric computations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import google3
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
import surface_distance
from surface_distance.surface_distance import metrics
class SurfaceDistanceTest(parameterized.TestCase, absltest.TestCase):
def _assert_almost_equal(self, expected, actual, places):
"""Assertion wrapper correctly handling NaN equality."""
if np.isnan(expected) and np.isnan(actual):
return
self.assertAlmostEqual(expected, actual, places)
def _assert_metrics(self,
surface_distances, mask_gt, mask_pred,
expected_average_surface_distance,
expected_hausdorff_100,
expected_hausdorff_95,
expected_surface_overlap_at_1mm,
expected_surface_dice_at_1mm,
expected_volumetric_dice,
places=3):
actual_average_surface_distance = (
surface_distance.compute_average_surface_distance(surface_distances))
for i in range(2):
self._assert_almost_equal(
expected_average_surface_distance[i],
actual_average_surface_distance[i],
places=places)
self._assert_almost_equal(
expected_hausdorff_100,
surface_distance.compute_robust_hausdorff(surface_distances, 100),
places=places)
self._assert_almost_equal(
expected_hausdorff_95,
surface_distance.compute_robust_hausdorff(surface_distances, 95),
places=places)
actual_surface_overlap_at_1mm = (
surface_distance.compute_surface_overlap_at_tolerance(
surface_distances, tolerance_mm=1))
for i in range(2):
self._assert_almost_equal(
expected_surface_overlap_at_1mm[i],
actual_surface_overlap_at_1mm[i],
places=places)
self._assert_almost_equal(
expected_surface_dice_at_1mm,
surface_distance.compute_surface_dice_at_tolerance(
surface_distances, tolerance_mm=1),
places=places)
self._assert_almost_equal(
expected_volumetric_dice,
surface_distance.compute_dice_coefficient(mask_gt, mask_pred),
places=places)
@parameterized.parameters((
np.zeros([2, 2, 2], dtype=bool),
np.zeros([2, 2], dtype=bool),
[1, 1],
), (
np.zeros([2, 2], dtype=bool),
np.zeros([2, 2, 2], dtype=bool),
[1, 1],
), (
np.zeros([2, 2], dtype=bool),
np.zeros([2, 2], dtype=bool),
[1, 1, 1],
))
def test_compute_surface_distances_raises_on_incompatible_shapes(
self, mask_gt, mask_pred, spacing_mm):
with self.assertRaisesRegex(ValueError,
'The arguments must be of compatible shape'):
surface_distance.compute_surface_distances(mask_gt, mask_pred, spacing_mm)
@parameterized.parameters((
np.zeros([2], dtype=bool),
np.zeros([2], dtype=bool),
[1],
), (
np.zeros([2, 2, 2, 2], dtype=bool),
np.zeros([2, 2, 2, 2], dtype=bool),
[1, 1, 1, 1],
))
def test_compute_surface_distances_raises_on_invalid_shapes(
self, mask_gt, mask_pred, spacing_mm):
with self.assertRaisesRegex(ValueError,
'Only 2D and 3D masks are supported'):
surface_distance.compute_surface_distances(mask_gt, mask_pred, spacing_mm)
class SurfaceDistance2DTest(SurfaceDistanceTest, parameterized.TestCase):
def test_on_2_pixels_2mm_away(self):
mask_gt = np.zeros((128, 128), bool)
mask_pred = np.zeros((128, 128), bool)
mask_gt[50, 70] = 1
mask_pred[50, 72] = 1
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(2, 1))
diag = 0.5 * math.sqrt(2**2 + 1**2)
expected_distances = {
'surfel_areas_gt': np.asarray([diag, diag, diag, diag]),
'surfel_areas_pred': np.asarray([diag, diag, diag, diag]),
'distances_gt_to_pred': np.asarray([1., 1., 2., 2.]),
'distances_pred_to_gt': np.asarray([1., 1., 2., 2.]),
}
self.assertEqual(len(expected_distances), len(surface_distances))
for key, expected_value in expected_distances.items():
np.testing.assert_array_equal(expected_value, surface_distances[key])
self._assert_metrics(
surface_distances,
mask_gt,
mask_pred,
expected_average_surface_distance=(1.5, 1.5),
expected_hausdorff_100=2.0,
expected_hausdorff_95=2.0,
expected_surface_overlap_at_1mm=(0.5, 0.5),
expected_surface_dice_at_1mm=0.5,
expected_volumetric_dice=0.0)
def test_two_squares_shifted_by_one_pixel(self):
# We make sure we do not have active pixels on the border of the image,
# because this will add additional 2D surfaces on the border of the image
# because the image is padded with background.
mask_gt = np.asarray(
[
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
],
dtype=bool)
mask_pred = np.asarray(
[
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
],
dtype=bool)
vertical = 2
horizontal = 1
diag = 0.5 * math.sqrt(horizontal**2 + vertical**2)
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(vertical, horizontal))
# We go from top left corner, clockwise to describe the surfaces and
# distances. The 2 surfaces are:
#
# /-\ /-\
# | | | |
# \-/ | |
# \-/
expected_surfel_areas_gt = np.asarray(
[diag, horizontal, diag, vertical, diag, horizontal, diag, vertical])
expected_surfel_areas_pred = np.asarray([
diag, horizontal, diag, vertical, vertical, diag, horizontal, diag,
vertical, vertical
])
expected_distances_gt_to_pred = np.asarray([0] * 5 + [horizontal] + [0] * 2)
expected_distances_pred_to_gt = np.asarray([0] * 5 + [vertical] * 3 +
[0] * 2)
# We sort these using the same sorting algorithm
(expected_distances_gt_to_pred, expected_surfel_areas_gt) = (
metrics._sort_distances_surfels(expected_distances_gt_to_pred,
expected_surfel_areas_gt))
(expected_distances_pred_to_gt, expected_surfel_areas_pred) = (
metrics._sort_distances_surfels(expected_distances_pred_to_gt,
expected_surfel_areas_pred))
expected_distances = {
'surfel_areas_gt': expected_surfel_areas_gt,
'surfel_areas_pred': expected_surfel_areas_pred,
'distances_gt_to_pred': expected_distances_gt_to_pred,
'distances_pred_to_gt': expected_distances_pred_to_gt,
}
self.assertEqual(len(expected_distances), len(surface_distances))
for key, expected_value in expected_distances.items():
np.testing.assert_array_equal(expected_value, surface_distances[key])
self._assert_metrics(
surface_distances,
mask_gt,
mask_pred,
expected_average_surface_distance=(
surface_distance.compute_average_surface_distance(
expected_distances)),
expected_hausdorff_100=(surface_distance.compute_robust_hausdorff(
expected_distances, 100)),
expected_hausdorff_95=surface_distance.compute_robust_hausdorff(
expected_distances, 95),
expected_surface_overlap_at_1mm=(
surface_distance.compute_surface_overlap_at_tolerance(
expected_distances, tolerance_mm=1)),
expected_surface_dice_at_1mm=(
surface_distance.compute_surface_dice_at_tolerance(
surface_distances, tolerance_mm=1)),
expected_volumetric_dice=(surface_distance.compute_dice_coefficient(
mask_gt, mask_pred)))
def test_empty_prediction_mask(self):
mask_gt = np.zeros((128, 128), bool)
mask_pred = np.zeros((128, 128), bool)
mask_gt[50, 60] = 1
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(3, 2))
self._assert_metrics(
surface_distances,
mask_gt,
mask_pred,
expected_average_surface_distance=(np.inf, np.nan),
expected_hausdorff_100=np.inf,
expected_hausdorff_95=np.inf,
expected_surface_overlap_at_1mm=(0.0, np.nan),
expected_surface_dice_at_1mm=0.0,
expected_volumetric_dice=0.0)
def test_empty_ground_truth_mask(self):
mask_gt = np.zeros((128, 128), bool)
mask_pred = np.zeros((128, 128), bool)
mask_pred[50, 60] = 1
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(3, 2))
self._assert_metrics(
surface_distances,
mask_gt,
mask_pred,
expected_average_surface_distance=(np.nan, np.inf),
expected_hausdorff_100=np.inf,
expected_hausdorff_95=np.inf,
expected_surface_overlap_at_1mm=(np.nan, 0.0),
expected_surface_dice_at_1mm=0.0,
expected_volumetric_dice=0.0)
def test_both_empty_masks(self):
mask_gt = np.zeros((128, 128), bool)
mask_pred = np.zeros((128, 128), bool)
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(3, 2))
self._assert_metrics(
surface_distances,
mask_gt,
mask_pred,
expected_average_surface_distance=(np.nan, np.nan),
expected_hausdorff_100=np.inf,
expected_hausdorff_95=np.inf,
expected_surface_overlap_at_1mm=(np.nan, np.nan),
expected_surface_dice_at_1mm=np.nan,
expected_volumetric_dice=np.nan)
class SurfaceDistance3DTest(SurfaceDistanceTest):
def test_on_2_pixels_2mm_away(self):
mask_gt = np.zeros((128, 128, 128), bool)
mask_pred = np.zeros((128, 128, 128), bool)
mask_gt[50, 60, 70] = 1
mask_pred[50, 60, 72] = 1
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(3, 2, 1))
self._assert_metrics(surface_distances, mask_gt, mask_pred,
expected_average_surface_distance=(1.5, 1.5),
expected_hausdorff_100=2.0,
expected_hausdorff_95=2.0,
expected_surface_overlap_at_1mm=(0.5, 0.5),
expected_surface_dice_at_1mm=0.5,
expected_volumetric_dice=0.0)
def test_two_cubes_shifted_by_one_pixel(self):
mask_gt = np.zeros((100, 100, 100), bool)
mask_pred = np.zeros((100, 100, 100), bool)
mask_gt[0:50, :, :] = 1
mask_pred[0:51, :, :] = 1
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(2, 1, 1))
self._assert_metrics(
surface_distances, mask_gt, mask_pred,
expected_average_surface_distance=(0.322, 0.339),
expected_hausdorff_100=2.0,
expected_hausdorff_95=2.0,
expected_surface_overlap_at_1mm=(0.842, 0.830),
expected_surface_dice_at_1mm=0.836,
expected_volumetric_dice=0.990)
def test_empty_prediction_mask(self):
mask_gt = np.zeros((128, 128, 128), bool)
mask_pred = np.zeros((128, 128, 128), bool)
mask_gt[50, 60, 70] = 1
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(3, 2, 1))
self._assert_metrics(
surface_distances, mask_gt, mask_pred,
expected_average_surface_distance=(np.inf, np.nan),
expected_hausdorff_100=np.inf,
expected_hausdorff_95=np.inf,
expected_surface_overlap_at_1mm=(0.0, np.nan),
expected_surface_dice_at_1mm=0.0,
expected_volumetric_dice=0.0)
def test_empty_ground_truth_mask(self):
mask_gt = np.zeros((128, 128, 128), bool)
mask_pred = np.zeros((128, 128, 128), bool)
mask_pred[50, 60, 72] = 1
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(3, 2, 1))
self._assert_metrics(
surface_distances, mask_gt, mask_pred,
expected_average_surface_distance=(np.nan, np.inf),
expected_hausdorff_100=np.inf,
expected_hausdorff_95=np.inf,
expected_surface_overlap_at_1mm=(np.nan, 0.0),
expected_surface_dice_at_1mm=0.0,
expected_volumetric_dice=0.0)
def test_both_empty_masks(self):
mask_gt = np.zeros((128, 128, 128), bool)
mask_pred = np.zeros((128, 128, 128), bool)
surface_distances = surface_distance.compute_surface_distances(
mask_gt, mask_pred, spacing_mm=(3, 2, 1))
self._assert_metrics(
surface_distances, mask_gt, mask_pred,
expected_average_surface_distance=(np.nan, np.nan),
expected_hausdorff_100=np.inf,
expected_hausdorff_95=np.inf,
expected_surface_overlap_at_1mm=(np.nan, np.nan),
expected_surface_dice_at_1mm=np.nan,
expected_volumetric_dice=np.nan)
if __name__ == '__main__':
absltest.main()
| surface-distance-master | surface_distance_test.py |
# Copyright 2018 Google Inc. 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.
"""Surface distance module: https://github.com/deepmind/surface-distance ."""
from .surface_distance import * # pylint: disable=wildcard-import
| surface-distance-master | __init__.py |
# Copyright 2018 Google Inc. 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.
"""PyPI package definition."""
from setuptools import setup
setup(name="Surface Distance Based Measures",
version="0.1",
description=(
"Library containing utilities to compute performance metrics for "
"segmentation"),
url="https://github.com/deepmind/surface-distance",
author="DeepMind",
license="Apache License, Version 2.0",
packages=["surface_distance"],
install_requires=["numpy", "scipy", "absl-py"])
| surface-distance-master | setup.py |
# Copyright 2018 Google Inc. 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.
"""Module exposing surface distance based measures."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from . import lookup_tables # pylint: disable=relative-beyond-top-level
import numpy as np
from scipy import ndimage
def _assert_is_numpy_array(name, array):
"""Raises an exception if `array` is not a numpy array."""
if not isinstance(array, np.ndarray):
raise ValueError("The argument {!r} should be a numpy array, not a "
"{}".format(name, type(array)))
def _check_nd_numpy_array(name, array, num_dims):
"""Raises an exception if `array` is not a `num_dims`-D numpy array."""
if len(array.shape) != num_dims:
raise ValueError("The argument {!r} should be a {}D array, not of "
"shape {}".format(name, num_dims, array.shape))
def _check_2d_numpy_array(name, array):
_check_nd_numpy_array(name, array, num_dims=2)
def _check_3d_numpy_array(name, array):
_check_nd_numpy_array(name, array, num_dims=3)
def _assert_is_bool_numpy_array(name, array):
_assert_is_numpy_array(name, array)
if array.dtype != bool:
raise ValueError("The argument {!r} should be a numpy array of type bool, "
"not {}".format(name, array.dtype))
def _compute_bounding_box(mask):
"""Computes the bounding box of the masks.
This function generalizes to arbitrary number of dimensions great or equal
to 1.
Args:
mask: The 2D or 3D numpy mask, where '0' means background and non-zero means
foreground.
Returns:
A tuple:
- The coordinates of the first point of the bounding box (smallest on all
axes), or `None` if the mask contains only zeros.
- The coordinates of the second point of the bounding box (greatest on all
axes), or `None` if the mask contains only zeros.
"""
num_dims = len(mask.shape)
bbox_min = np.zeros(num_dims, np.int64)
bbox_max = np.zeros(num_dims, np.int64)
# max projection to the x0-axis
proj_0 = np.amax(mask, axis=tuple(range(num_dims))[1:])
idx_nonzero_0 = np.nonzero(proj_0)[0]
if len(idx_nonzero_0) == 0: # pylint: disable=g-explicit-length-test
return None, None
bbox_min[0] = np.min(idx_nonzero_0)
bbox_max[0] = np.max(idx_nonzero_0)
# max projection to the i-th-axis for i in {1, ..., num_dims - 1}
for axis in range(1, num_dims):
max_over_axes = list(range(num_dims)) # Python 3 compatible
max_over_axes.pop(axis) # Remove the i-th dimension from the max
max_over_axes = tuple(max_over_axes) # numpy expects a tuple of ints
proj = np.amax(mask, axis=max_over_axes)
idx_nonzero = np.nonzero(proj)[0]
bbox_min[axis] = np.min(idx_nonzero)
bbox_max[axis] = np.max(idx_nonzero)
return bbox_min, bbox_max
def _crop_to_bounding_box(mask, bbox_min, bbox_max):
"""Crops a 2D or 3D mask to the bounding box specified by `bbox_{min,max}`."""
# we need to zeropad the cropped region with 1 voxel at the lower,
# the right (and the back on 3D) sides. This is required to obtain the
# "full" convolution result with the 2x2 (or 2x2x2 in 3D) kernel.
# TODO: This is correct only if the object is interior to the
# bounding box.
cropmask = np.zeros((bbox_max - bbox_min) + 2, np.uint8)
num_dims = len(mask.shape)
# pyformat: disable
if num_dims == 2:
cropmask[0:-1, 0:-1] = mask[bbox_min[0]:bbox_max[0] + 1,
bbox_min[1]:bbox_max[1] + 1]
elif num_dims == 3:
cropmask[0:-1, 0:-1, 0:-1] = mask[bbox_min[0]:bbox_max[0] + 1,
bbox_min[1]:bbox_max[1] + 1,
bbox_min[2]:bbox_max[2] + 1]
# pyformat: enable
else:
assert False
return cropmask
def _sort_distances_surfels(distances, surfel_areas):
"""Sorts the two list with respect to the tuple of (distance, surfel_area).
Args:
distances: The distances from A to B (e.g. `distances_gt_to_pred`).
surfel_areas: The surfel areas for A (e.g. `surfel_areas_gt`).
Returns:
A tuple of the sorted (distances, surfel_areas).
"""
sorted_surfels = np.array(sorted(zip(distances, surfel_areas)))
return sorted_surfels[:, 0], sorted_surfels[:, 1]
def compute_surface_distances(mask_gt,
mask_pred,
spacing_mm):
"""Computes closest distances from all surface points to the other surface.
This function can be applied to 2D or 3D tensors. For 2D, both masks must be
2D and `spacing_mm` must be a 2-element list. For 3D, both masks must be 3D
and `spacing_mm` must be a 3-element list. The description is done for the 2D
case, and the formulation for the 3D case is present is parenthesis,
introduced by "resp.".
Finds all contour elements (resp surface elements "surfels" in 3D) in the
ground truth mask `mask_gt` and the predicted mask `mask_pred`, computes their
length in mm (resp. area in mm^2) and the distance to the closest point on the
other contour (resp. surface). It returns two sorted lists of distances
together with the corresponding contour lengths (resp. surfel areas). If one
of the masks is empty, the corresponding lists are empty and all distances in
the other list are `inf`.
Args:
mask_gt: 2-dim (resp. 3-dim) bool Numpy array. The ground truth mask.
mask_pred: 2-dim (resp. 3-dim) bool Numpy array. The predicted mask.
spacing_mm: 2-element (resp. 3-element) list-like structure. Voxel spacing
in x0 anx x1 (resp. x0, x1 and x2) directions.
Returns:
A dict with:
"distances_gt_to_pred": 1-dim numpy array of type float. The distances in mm
from all ground truth surface elements to the predicted surface,
sorted from smallest to largest.
"distances_pred_to_gt": 1-dim numpy array of type float. The distances in mm
from all predicted surface elements to the ground truth surface,
sorted from smallest to largest.
"surfel_areas_gt": 1-dim numpy array of type float. The length of the
of the ground truth contours in mm (resp. the surface elements area in
mm^2) in the same order as distances_gt_to_pred.
"surfel_areas_pred": 1-dim numpy array of type float. The length of the
of the predicted contours in mm (resp. the surface elements area in
mm^2) in the same order as distances_gt_to_pred.
Raises:
ValueError: If the masks and the `spacing_mm` arguments are of incompatible
shape or type. Or if the masks are not 2D or 3D.
"""
# The terms used in this function are for the 3D case. In particular, surface
# in 2D stands for contours in 3D. The surface elements in 3D correspond to
# the line elements in 2D.
_assert_is_bool_numpy_array("mask_gt", mask_gt)
_assert_is_bool_numpy_array("mask_pred", mask_pred)
if not len(mask_gt.shape) == len(mask_pred.shape) == len(spacing_mm):
raise ValueError("The arguments must be of compatible shape. Got mask_gt "
"with {} dimensions ({}) and mask_pred with {} dimensions "
"({}), while the spacing_mm was {} elements.".format(
len(mask_gt.shape),
mask_gt.shape, len(mask_pred.shape), mask_pred.shape,
len(spacing_mm)))
num_dims = len(spacing_mm)
if num_dims == 2:
_check_2d_numpy_array("mask_gt", mask_gt)
_check_2d_numpy_array("mask_pred", mask_pred)
# compute the area for all 16 possible surface elements
# (given a 2x2 neighbourhood) according to the spacing_mm
neighbour_code_to_surface_area = (
lookup_tables.create_table_neighbour_code_to_contour_length(spacing_mm))
kernel = lookup_tables.ENCODE_NEIGHBOURHOOD_2D_KERNEL
full_true_neighbours = 0b1111
elif num_dims == 3:
_check_3d_numpy_array("mask_gt", mask_gt)
_check_3d_numpy_array("mask_pred", mask_pred)
# compute the area for all 256 possible surface elements
# (given a 2x2x2 neighbourhood) according to the spacing_mm
neighbour_code_to_surface_area = (
lookup_tables.create_table_neighbour_code_to_surface_area(spacing_mm))
kernel = lookup_tables.ENCODE_NEIGHBOURHOOD_3D_KERNEL
full_true_neighbours = 0b11111111
else:
raise ValueError("Only 2D and 3D masks are supported, not "
"{}D.".format(num_dims))
# compute the bounding box of the masks to trim the volume to the smallest
# possible processing subvolume
bbox_min, bbox_max = _compute_bounding_box(mask_gt | mask_pred)
# Both the min/max bbox are None at the same time, so we only check one.
if bbox_min is None:
return {
"distances_gt_to_pred": np.array([]),
"distances_pred_to_gt": np.array([]),
"surfel_areas_gt": np.array([]),
"surfel_areas_pred": np.array([]),
}
# crop the processing subvolume.
cropmask_gt = _crop_to_bounding_box(mask_gt, bbox_min, bbox_max)
cropmask_pred = _crop_to_bounding_box(mask_pred, bbox_min, bbox_max)
# compute the neighbour code (local binary pattern) for each voxel
# the resulting arrays are spacially shifted by minus half a voxel in each
# axis.
# i.e. the points are located at the corners of the original voxels
neighbour_code_map_gt = ndimage.filters.correlate(
cropmask_gt.astype(np.uint8), kernel, mode="constant", cval=0)
neighbour_code_map_pred = ndimage.filters.correlate(
cropmask_pred.astype(np.uint8), kernel, mode="constant", cval=0)
# create masks with the surface voxels
borders_gt = ((neighbour_code_map_gt != 0) &
(neighbour_code_map_gt != full_true_neighbours))
borders_pred = ((neighbour_code_map_pred != 0) &
(neighbour_code_map_pred != full_true_neighbours))
# compute the distance transform (closest distance of each voxel to the
# surface voxels)
if borders_gt.any():
distmap_gt = ndimage.morphology.distance_transform_edt(
~borders_gt, sampling=spacing_mm)
else:
distmap_gt = np.Inf * np.ones(borders_gt.shape)
if borders_pred.any():
distmap_pred = ndimage.morphology.distance_transform_edt(
~borders_pred, sampling=spacing_mm)
else:
distmap_pred = np.Inf * np.ones(borders_pred.shape)
# compute the area of each surface element
surface_area_map_gt = neighbour_code_to_surface_area[neighbour_code_map_gt]
surface_area_map_pred = neighbour_code_to_surface_area[
neighbour_code_map_pred]
# create a list of all surface elements with distance and area
distances_gt_to_pred = distmap_pred[borders_gt]
distances_pred_to_gt = distmap_gt[borders_pred]
surfel_areas_gt = surface_area_map_gt[borders_gt]
surfel_areas_pred = surface_area_map_pred[borders_pred]
# sort them by distance
if distances_gt_to_pred.shape != (0,):
distances_gt_to_pred, surfel_areas_gt = _sort_distances_surfels(
distances_gt_to_pred, surfel_areas_gt)
if distances_pred_to_gt.shape != (0,):
distances_pred_to_gt, surfel_areas_pred = _sort_distances_surfels(
distances_pred_to_gt, surfel_areas_pred)
return {
"distances_gt_to_pred": distances_gt_to_pred,
"distances_pred_to_gt": distances_pred_to_gt,
"surfel_areas_gt": surfel_areas_gt,
"surfel_areas_pred": surfel_areas_pred,
}
def compute_average_surface_distance(surface_distances):
"""Returns the average surface distance.
Computes the average surface distances by correctly taking the area of each
surface element into account. Call compute_surface_distances(...) before, to
obtain the `surface_distances` dict.
Args:
surface_distances: dict with "distances_gt_to_pred", "distances_pred_to_gt"
"surfel_areas_gt", "surfel_areas_pred" created by
compute_surface_distances()
Returns:
A tuple with two float values:
- the average distance (in mm) from the ground truth surface to the
predicted surface
- the average distance from the predicted surface to the ground truth
surface.
"""
distances_gt_to_pred = surface_distances["distances_gt_to_pred"]
distances_pred_to_gt = surface_distances["distances_pred_to_gt"]
surfel_areas_gt = surface_distances["surfel_areas_gt"]
surfel_areas_pred = surface_distances["surfel_areas_pred"]
average_distance_gt_to_pred = (
np.sum(distances_gt_to_pred * surfel_areas_gt) / np.sum(surfel_areas_gt))
average_distance_pred_to_gt = (
np.sum(distances_pred_to_gt * surfel_areas_pred) /
np.sum(surfel_areas_pred))
return (average_distance_gt_to_pred, average_distance_pred_to_gt)
def compute_robust_hausdorff(surface_distances, percent):
"""Computes the robust Hausdorff distance.
Computes the robust Hausdorff distance. "Robust", because it uses the
`percent` percentile of the distances instead of the maximum distance. The
percentage is computed by correctly taking the area of each surface element
into account.
Args:
surface_distances: dict with "distances_gt_to_pred", "distances_pred_to_gt"
"surfel_areas_gt", "surfel_areas_pred" created by
compute_surface_distances()
percent: a float value between 0 and 100.
Returns:
a float value. The robust Hausdorff distance in mm.
"""
distances_gt_to_pred = surface_distances["distances_gt_to_pred"]
distances_pred_to_gt = surface_distances["distances_pred_to_gt"]
surfel_areas_gt = surface_distances["surfel_areas_gt"]
surfel_areas_pred = surface_distances["surfel_areas_pred"]
if len(distances_gt_to_pred) > 0: # pylint: disable=g-explicit-length-test
surfel_areas_cum_gt = np.cumsum(surfel_areas_gt) / np.sum(surfel_areas_gt)
idx = np.searchsorted(surfel_areas_cum_gt, percent/100.0)
perc_distance_gt_to_pred = distances_gt_to_pred[
min(idx, len(distances_gt_to_pred)-1)]
else:
perc_distance_gt_to_pred = np.Inf
if len(distances_pred_to_gt) > 0: # pylint: disable=g-explicit-length-test
surfel_areas_cum_pred = (np.cumsum(surfel_areas_pred) /
np.sum(surfel_areas_pred))
idx = np.searchsorted(surfel_areas_cum_pred, percent/100.0)
perc_distance_pred_to_gt = distances_pred_to_gt[
min(idx, len(distances_pred_to_gt)-1)]
else:
perc_distance_pred_to_gt = np.Inf
return max(perc_distance_gt_to_pred, perc_distance_pred_to_gt)
def compute_surface_overlap_at_tolerance(surface_distances, tolerance_mm):
"""Computes the overlap of the surfaces at a specified tolerance.
Computes the overlap of the ground truth surface with the predicted surface
and vice versa allowing a specified tolerance (maximum surface-to-surface
distance that is regarded as overlapping). The overlapping fraction is
computed by correctly taking the area of each surface element into account.
Args:
surface_distances: dict with "distances_gt_to_pred", "distances_pred_to_gt"
"surfel_areas_gt", "surfel_areas_pred" created by
compute_surface_distances()
tolerance_mm: a float value. The tolerance in mm
Returns:
A tuple of two float values. The overlap fraction in [0.0, 1.0] of the
ground truth surface with the predicted surface and vice versa.
"""
distances_gt_to_pred = surface_distances["distances_gt_to_pred"]
distances_pred_to_gt = surface_distances["distances_pred_to_gt"]
surfel_areas_gt = surface_distances["surfel_areas_gt"]
surfel_areas_pred = surface_distances["surfel_areas_pred"]
rel_overlap_gt = (
np.sum(surfel_areas_gt[distances_gt_to_pred <= tolerance_mm]) /
np.sum(surfel_areas_gt))
rel_overlap_pred = (
np.sum(surfel_areas_pred[distances_pred_to_gt <= tolerance_mm]) /
np.sum(surfel_areas_pred))
return (rel_overlap_gt, rel_overlap_pred)
def compute_surface_dice_at_tolerance(surface_distances, tolerance_mm):
"""Computes the _surface_ DICE coefficient at a specified tolerance.
Computes the _surface_ DICE coefficient at a specified tolerance. Not to be
confused with the standard _volumetric_ DICE coefficient. The surface DICE
measures the overlap of two surfaces instead of two volumes. A surface
element is counted as overlapping (or touching), when the closest distance to
the other surface is less or equal to the specified tolerance. The DICE
coefficient is in the range between 0.0 (no overlap) to 1.0 (perfect overlap).
Args:
surface_distances: dict with "distances_gt_to_pred", "distances_pred_to_gt"
"surfel_areas_gt", "surfel_areas_pred" created by
compute_surface_distances()
tolerance_mm: a float value. The tolerance in mm
Returns:
A float value. The surface DICE coefficient in [0.0, 1.0].
"""
distances_gt_to_pred = surface_distances["distances_gt_to_pred"]
distances_pred_to_gt = surface_distances["distances_pred_to_gt"]
surfel_areas_gt = surface_distances["surfel_areas_gt"]
surfel_areas_pred = surface_distances["surfel_areas_pred"]
overlap_gt = np.sum(surfel_areas_gt[distances_gt_to_pred <= tolerance_mm])
overlap_pred = np.sum(surfel_areas_pred[distances_pred_to_gt <= tolerance_mm])
surface_dice = (overlap_gt + overlap_pred) / (
np.sum(surfel_areas_gt) + np.sum(surfel_areas_pred))
return surface_dice
def compute_dice_coefficient(mask_gt, mask_pred):
"""Computes soerensen-dice coefficient.
compute the soerensen-dice coefficient between the ground truth mask `mask_gt`
and the predicted mask `mask_pred`.
Args:
mask_gt: 3-dim Numpy array of type bool. The ground truth mask.
mask_pred: 3-dim Numpy array of type bool. The predicted mask.
Returns:
the dice coeffcient as float. If both masks are empty, the result is NaN.
"""
volume_sum = mask_gt.sum() + mask_pred.sum()
if volume_sum == 0:
return np.NaN
volume_intersect = (mask_gt & mask_pred).sum()
return 2*volume_intersect / volume_sum
| surface-distance-master | surface_distance/metrics.py |
# Copyright 2018 Google Inc. 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.
"""Lookup tables used by surface distance metrics."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
ENCODE_NEIGHBOURHOOD_3D_KERNEL = np.array([[[128, 64], [32, 16]], [[8, 4],
[2, 1]]])
# _NEIGHBOUR_CODE_TO_NORMALS is a lookup table.
# For every binary neighbour code
# (2x2x2 neighbourhood = 8 neighbours = 8 bits = 256 codes)
# it contains the surface normals of the triangles (called "surfel" for
# "surface element" in the following). The length of the normal
# vector encodes the surfel area.
#
# created using the marching_cube algorithm
# see e.g. https://en.wikipedia.org/wiki/Marching_cubes
# pylint: disable=line-too-long
_NEIGHBOUR_CODE_TO_NORMALS = [
[[0, 0, 0]],
[[0.125, 0.125, 0.125]],
[[-0.125, -0.125, 0.125]],
[[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0]],
[[0.125, -0.125, 0.125]],
[[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25]],
[[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]],
[[-0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, 0.125, 0.125]],
[[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25]],
[[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125]],
[[0.25, -0.25, 0.0], [0.25, -0.25, 0.0]],
[[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125]],
[[-0.5, 0.0, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125]],
[[0.5, 0.0, 0.0], [0.5, 0.0, 0.0]],
[[0.125, -0.125, -0.125]],
[[0.0, -0.25, -0.25], [0.0, 0.25, 0.25]],
[[-0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.0, -0.5, 0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]],
[[0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.0, 0.0, -0.5], [0.25, 0.25, 0.25], [-0.125, -0.125, -0.125]],
[[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]],
[[-0.125, 0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [-0.125, 0.125, 0.125]],
[[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.125, -0.125, -0.125]],
[[0.125, 0.125, 0.125], [0.375, 0.375, 0.375], [0.0, -0.25, 0.25], [-0.25, 0.0, 0.25]],
[[0.125, -0.125, -0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0]],
[[0.375, 0.375, 0.375], [0.0, 0.25, -0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]],
[[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.125, 0.125, 0.125]],
[[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25]],
[[0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.0, -0.25, 0.25], [0.0, 0.25, -0.25]],
[[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25]],
[[0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.125, -0.125, 0.125], [-0.25, -0.0, -0.25], [0.25, 0.0, 0.25]],
[[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], [0.125, -0.125, 0.125]],
[[-0.375, -0.375, 0.375], [-0.0, 0.25, 0.25], [0.125, 0.125, -0.125], [-0.25, -0.0, -0.25]],
[[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, 0.125, 0.125]],
[[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125]],
[[0.25, 0.25, -0.25], [0.25, 0.25, -0.25], [0.125, 0.125, -0.125], [-0.125, -0.125, 0.125]],
[[0.125, -0.125, 0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0]],
[[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], [0.125, -0.125, 0.125]],
[[0.0, 0.25, -0.25], [0.375, -0.375, -0.375], [-0.125, 0.125, 0.125], [0.25, 0.25, 0.0]],
[[-0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125]],
[[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0]],
[[0.0, 0.5, 0.0], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125]],
[[0.0, 0.5, 0.0], [0.125, -0.125, 0.125], [-0.25, 0.25, -0.25]],
[[0.0, 0.5, 0.0], [0.0, -0.5, 0.0]],
[[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.125, -0.125, 0.125]],
[[-0.375, -0.375, -0.375], [-0.25, 0.0, 0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]],
[[0.125, 0.125, 0.125], [0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125]],
[[0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125]],
[[-0.125, 0.125, 0.125], [0.25, -0.25, 0.0], [-0.25, 0.25, 0.0]],
[[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.375, 0.375, -0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]],
[[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]],
[[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0]],
[[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]],
[[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]],
[[-0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.125, -0.125, 0.125], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0]],
[[0.0, -0.25, 0.25], [0.0, -0.25, 0.25]],
[[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125]],
[[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [-0.125, -0.125, 0.125]],
[[0.375, -0.375, 0.375], [0.0, -0.25, -0.25], [-0.125, 0.125, -0.125], [0.25, 0.25, 0.0]],
[[-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125]],
[[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25]],
[[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125]],
[[-0.25, 0.25, -0.25], [-0.25, 0.25, -0.25], [-0.125, 0.125, -0.125], [-0.125, 0.125, -0.125]],
[[-0.25, 0.0, -0.25], [0.375, -0.375, -0.375], [0.0, 0.25, -0.25], [-0.125, 0.125, 0.125]],
[[0.5, 0.0, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125]],
[[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25]],
[[-0.0, 0.0, 0.5], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125]],
[[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25]],
[[-0.25, -0.0, -0.25], [-0.375, 0.375, 0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, 0.125]],
[[0.0, 0.0, -0.5], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]],
[[-0.0, 0.0, 0.5], [0.0, 0.0, 0.5]],
[[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5]],
[[0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5]],
[[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], [-0.125, 0.125, 0.125]],
[[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25]],
[[0.125, -0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25]],
[[0.25, 0.0, 0.25], [-0.375, -0.375, 0.375], [-0.25, 0.25, 0.0], [-0.125, -0.125, 0.125]],
[[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25]],
[[0.25, 0.0, 0.25], [0.25, 0.0, 0.25]],
[[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[-0.125, -0.125, 0.125], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25]],
[[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]],
[[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.125, -0.125, 0.125]],
[[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25]],
[[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.125, -0.125, -0.125]],
[[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125]],
[[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.5, 0.0, -0.0], [0.25, -0.25, -0.25], [0.125, -0.125, -0.125]],
[[-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125]],
[[0.375, -0.375, 0.375], [0.0, 0.25, 0.25], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]],
[[0.0, -0.5, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125]],
[[-0.375, -0.375, 0.375], [0.25, -0.25, 0.0], [0.0, 0.25, 0.25], [-0.125, -0.125, 0.125]],
[[-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.0, 0.0, 0.5]],
[[0.125, 0.125, 0.125], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25]],
[[0.0, 0.25, 0.25], [0.0, 0.25, 0.25]],
[[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], [0.125, 0.125, 0.125]],
[[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125]],
[[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, 0.125]],
[[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], [0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], [0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, 0.125]],
[[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.125, 0.125, 0.125]],
[[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125]],
[[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], [0.125, 0.125, 0.125]],
[[0.0, 0.25, 0.25], [0.0, 0.25, 0.25]],
[[0.125, 0.125, 0.125], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25]],
[[-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.0, 0.0, 0.5]],
[[-0.375, -0.375, 0.375], [0.25, -0.25, 0.0], [0.0, 0.25, 0.25], [-0.125, -0.125, 0.125]],
[[0.0, -0.5, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125]],
[[0.375, -0.375, 0.375], [0.0, 0.25, 0.25], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]],
[[-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125]],
[[0.5, 0.0, -0.0], [0.25, -0.25, -0.25], [0.125, -0.125, -0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125]],
[[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.125, -0.125, -0.125]],
[[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25]],
[[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.125, -0.125, 0.125]],
[[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]],
[[-0.125, -0.125, 0.125], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.25, 0.0, 0.25], [0.25, 0.0, 0.25]],
[[0.125, 0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25]],
[[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125]],
[[0.25, 0.0, 0.25], [-0.375, -0.375, 0.375], [-0.25, 0.25, 0.0], [-0.125, -0.125, 0.125]],
[[0.125, -0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25]],
[[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25]],
[[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], [-0.125, 0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5]],
[[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5]],
[[-0.0, 0.0, 0.5], [0.0, 0.0, 0.5]],
[[0.0, 0.0, -0.5], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]],
[[-0.25, -0.0, -0.25], [-0.375, 0.375, 0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, 0.125]],
[[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25]],
[[-0.0, 0.0, 0.5], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125]],
[[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25]],
[[0.5, 0.0, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125]],
[[-0.25, 0.0, -0.25], [0.375, -0.375, -0.375], [0.0, 0.25, -0.25], [-0.125, 0.125, 0.125]],
[[-0.25, 0.25, -0.25], [-0.25, 0.25, -0.25], [-0.125, 0.125, -0.125], [-0.125, 0.125, -0.125]],
[[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125]],
[[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125]],
[[-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125]],
[[0.375, -0.375, 0.375], [0.0, -0.25, -0.25], [-0.125, 0.125, -0.125], [0.25, 0.25, 0.0]],
[[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [-0.125, -0.125, 0.125]],
[[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125]],
[[0.0, -0.25, 0.25], [0.0, -0.25, 0.25]],
[[-0.125, -0.125, 0.125], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0]],
[[-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.125, -0.125, 0.125]],
[[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]],
[[0.125, 0.125, 0.125], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]],
[[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.125, -0.125, 0.125]],
[[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0]],
[[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]],
[[-0.375, 0.375, -0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]],
[[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.125, 0.125, 0.125], [0.25, -0.25, 0.0], [-0.25, 0.25, 0.0]],
[[0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125]],
[[0.125, 0.125, 0.125], [0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125]],
[[-0.375, -0.375, -0.375], [-0.25, 0.0, 0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]],
[[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.125, -0.125, 0.125]],
[[0.0, 0.5, 0.0], [0.0, -0.5, 0.0]],
[[0.0, 0.5, 0.0], [0.125, -0.125, 0.125], [-0.25, 0.25, -0.25]],
[[0.0, 0.5, 0.0], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125]],
[[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0]],
[[-0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125]],
[[0.0, 0.25, -0.25], [0.375, -0.375, -0.375], [-0.125, 0.125, 0.125], [0.25, 0.25, 0.0]],
[[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], [0.125, -0.125, 0.125]],
[[0.125, -0.125, 0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0]],
[[0.25, 0.25, -0.25], [0.25, 0.25, -0.25], [0.125, 0.125, -0.125], [-0.125, -0.125, 0.125]],
[[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, 0.125, 0.125]],
[[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125]],
[[-0.375, -0.375, 0.375], [-0.0, 0.25, 0.25], [0.125, 0.125, -0.125], [-0.25, -0.0, -0.25]],
[[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], [0.125, -0.125, 0.125]],
[[0.125, -0.125, 0.125], [-0.25, -0.0, -0.25], [0.25, 0.0, 0.25]],
[[0.125, -0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25]],
[[0.0, -0.25, 0.25], [0.0, 0.25, -0.25]],
[[0.125, 0.125, 0.125], [0.125, -0.125, 0.125]],
[[0.125, -0.125, 0.125]],
[[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25]],
[[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.125, 0.125, 0.125]],
[[0.375, 0.375, 0.375], [0.0, 0.25, -0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]],
[[0.125, -0.125, -0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0]],
[[0.125, 0.125, 0.125], [0.375, 0.375, 0.375], [0.0, -0.25, 0.25], [-0.25, 0.0, 0.25]],
[[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.125, -0.125, -0.125]],
[[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [-0.125, 0.125, 0.125]],
[[-0.125, 0.125, 0.125], [0.125, -0.125, -0.125]],
[[-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]],
[[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.0, 0.0, -0.5], [0.25, 0.25, 0.25], [-0.125, -0.125, -0.125]],
[[0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.0, -0.5, 0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]],
[[-0.125, -0.125, 0.125], [0.125, -0.125, -0.125]],
[[0.0, -0.25, -0.25], [0.0, 0.25, 0.25]],
[[0.125, -0.125, -0.125]],
[[0.5, 0.0, 0.0], [0.5, 0.0, 0.0]],
[[-0.5, 0.0, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125]],
[[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125]],
[[0.25, -0.25, 0.0], [0.25, -0.25, 0.0]],
[[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125]],
[[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25]],
[[0.125, 0.125, 0.125], [-0.125, 0.125, 0.125]],
[[-0.125, 0.125, 0.125]],
[[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]],
[[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]],
[[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25]],
[[0.125, -0.125, 0.125]],
[[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0]],
[[-0.125, -0.125, 0.125]],
[[0.125, 0.125, 0.125]],
[[0, 0, 0]]]
# pylint: enable=line-too-long
def create_table_neighbour_code_to_surface_area(spacing_mm):
"""Returns an array mapping neighbourhood code to the surface elements area.
Note that the normals encode the initial surface area. This function computes
the area corresponding to the given `spacing_mm`.
Args:
spacing_mm: 3-element list-like structure. Voxel spacing in x0, x1 and x2
direction.
"""
# compute the area for all 256 possible surface elements
# (given a 2x2x2 neighbourhood) according to the spacing_mm
neighbour_code_to_surface_area = np.zeros([256])
for code in range(256):
normals = np.array(_NEIGHBOUR_CODE_TO_NORMALS[code])
sum_area = 0
for normal_idx in range(normals.shape[0]):
# normal vector
n = np.zeros([3])
n[0] = normals[normal_idx, 0] * spacing_mm[1] * spacing_mm[2]
n[1] = normals[normal_idx, 1] * spacing_mm[0] * spacing_mm[2]
n[2] = normals[normal_idx, 2] * spacing_mm[0] * spacing_mm[1]
area = np.linalg.norm(n)
sum_area += area
neighbour_code_to_surface_area[code] = sum_area
return neighbour_code_to_surface_area
# In the neighbourhood, points are ordered: top left, top right, bottom left,
# bottom right.
ENCODE_NEIGHBOURHOOD_2D_KERNEL = np.array([[8, 4], [2, 1]])
def create_table_neighbour_code_to_contour_length(spacing_mm):
"""Returns an array mapping neighbourhood code to the contour length.
For the list of possible cases and their figures, see page 38 from:
https://nccastaff.bournemouth.ac.uk/jmacey/MastersProjects/MSc14/06/thesis.pdf
In 2D, each point has 4 neighbors. Thus, are 16 configurations. A
configuration is encoded with '1' meaning "inside the object" and '0' "outside
the object". The points are ordered: top left, top right, bottom left, bottom
right.
The x0 axis is assumed vertical downward, and the x1 axis is horizontal to the
right:
(0, 0) --> (0, 1)
|
(1, 0)
Args:
spacing_mm: 2-element list-like structure. Voxel spacing in x0 and x1
directions.
"""
neighbour_code_to_contour_length = np.zeros([16])
vertical = spacing_mm[0]
horizontal = spacing_mm[1]
diag = 0.5 * math.sqrt(spacing_mm[0]**2 + spacing_mm[1]**2)
# pyformat: disable
neighbour_code_to_contour_length[int("00"
"01", 2)] = diag
neighbour_code_to_contour_length[int("00"
"10", 2)] = diag
neighbour_code_to_contour_length[int("00"
"11", 2)] = horizontal
neighbour_code_to_contour_length[int("01"
"00", 2)] = diag
neighbour_code_to_contour_length[int("01"
"01", 2)] = vertical
neighbour_code_to_contour_length[int("01"
"10", 2)] = 2*diag
neighbour_code_to_contour_length[int("01"
"11", 2)] = diag
neighbour_code_to_contour_length[int("10"
"00", 2)] = diag
neighbour_code_to_contour_length[int("10"
"01", 2)] = 2*diag
neighbour_code_to_contour_length[int("10"
"10", 2)] = vertical
neighbour_code_to_contour_length[int("10"
"11", 2)] = diag
neighbour_code_to_contour_length[int("11"
"00", 2)] = horizontal
neighbour_code_to_contour_length[int("11"
"01", 2)] = diag
neighbour_code_to_contour_length[int("11"
"10", 2)] = diag
# pyformat: enable
return neighbour_code_to_contour_length
| surface-distance-master | surface_distance/lookup_tables.py |
# Copyright 2018 Google Inc. 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.
"""Surface distance module: https://github.com/deepmind/surface-distance ."""
from .metrics import * # pylint: disable=wildcard-import
__version__ = "0.1"
| surface-distance-master | surface_distance/__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.
# ==============================================================================
"""TAP-Net model definition."""
import functools
from typing import Optional, Mapping, Tuple
import chex
from einshape import jax_einshape as einshape
import haiku as hk
import jax
import jax.numpy as jnp
from tapnet.models import tsm_resnet
from tapnet.utils import model_utils
from tapnet.utils import transforms
def create_batch_norm(
x: chex.Array, is_training: bool, cross_replica_axis: Optional[str]
) -> chex.Array:
"""Function to allow TSM-ResNet to create batch norm layers."""
return hk.BatchNorm(
create_scale=True,
create_offset=True,
decay_rate=0.9,
cross_replica_axis=cross_replica_axis,
)(x, is_training)
class TAPNet(hk.Module):
"""Joint model for performing flow-based tasks."""
def __init__(
self,
feature_grid_stride: int = 8,
num_heads: int = 1,
cross_replica_axis: Optional[str] = 'i',
num_frames: int = 24,
):
"""Initialize the model and provide kwargs for the various components.
Args:
feature_grid_stride: Stride to extract features. For TSM-ResNet,
supported values are 8 (default), 16, and 32.
num_heads: Number of heads in the cost volume.
cross_replica_axis: Which cross replica axis to use for the batch norm.
num_frames: Number of frames passed into TSM-ResNet.
"""
super().__init__()
self.feature_grid_stride = feature_grid_stride
self.num_heads = num_heads
self.softmax_temperature = 10.0
self.tsm_resnet = tsm_resnet.TSMResNetV2(
normalize_fn=functools.partial(
create_batch_norm, cross_replica_axis=cross_replica_axis
),
num_frames=num_frames,
channel_shift_fraction=[0.125, 0.125, 0.0, 0.0],
name='tsm_resnet_video',
)
self.cost_volume_track_mods = {
'hid1':
hk.Conv3D(
16,
[1, 3, 3],
name='cost_volume_regression_1',
stride=[1, 1, 1],
),
'hid2':
hk.Conv3D(
1,
[1, 3, 3],
name='cost_volume_regression_2',
stride=[1, 1, 1],
),
'hid3':
hk.Conv3D(
32,
[1, 3, 3],
name='cost_volume_occlusion_1',
stride=[1, 2, 2],
),
'hid4':
hk.Linear(16, name='cost_volume_occlusion_2'),
'occ_out':
hk.Linear(1, name='occlusion_out'),
'regression_hid':
hk.Linear(128, name='regression_hid'),
'regression_out':
hk.Linear(2, name='regression_out'),
}
def tracks_from_cost_volume(
self,
interp_feature_heads: chex.Array,
feature_grid_heads: chex.Array,
query_points: Optional[chex.Array],
im_shp: Optional[chex.Shape] = None,
) -> Tuple[chex.Array, chex.Array]:
"""Converts features into tracks by computing a cost volume.
The computed cost volume will have shape
[batch, num_queries, time, height, width, num_heads], which can be very
memory intensive.
Args:
interp_feature_heads: A tensor of features for each query point, of shape
[batch, num_queries, channels, heads].
feature_grid_heads: A tensor of features for the video, of shape [batch,
time, height, width, channels, heads].
query_points: When computing tracks, we assume these points are given as
ground truth and we reproduce them exactly. This is a set of points of
shape [batch, num_points, 3], where each entry is [t, y, x] in frame/
raster coordinates.
im_shp: The shape of the original image, i.e., [batch, num_frames, time,
height, width, 3].
Returns:
A 2-tuple of the inferred points (of shape
[batch, num_points, num_frames, 2] where each point is [x, y]) and
inferred occlusion (of shape [batch, num_points, num_frames], where
each is a logit where higher means occluded)
"""
mods = self.cost_volume_track_mods
# Note: time is first axis to prevent the TPU from padding
cost_volume = jnp.einsum(
'bncd,bthwcd->tbnhwd',
interp_feature_heads,
feature_grid_heads,
)
shape = cost_volume.shape
cost_volume = einshape('tbnhwd->t(bn)hwd', cost_volume)
occlusion = mods['hid1'](cost_volume)
occlusion = jax.nn.relu(occlusion)
pos = mods['hid2'](occlusion)
pos = jax.nn.softmax(pos * self.softmax_temperature, axis=(-2, -3))
pos = einshape('t(bn)hw1->bnthw', pos, n=shape[2])
points = model_utils.heatmaps_to_points(
pos, im_shp, query_points=query_points
)
occlusion = mods['hid3'](occlusion)
occlusion = jnp.mean(occlusion, axis=(-2, -3))
occlusion = mods['hid4'](occlusion)
occlusion = jax.nn.relu(occlusion)
occlusion = mods['occ_out'](occlusion)
occlusion = jnp.transpose(occlusion, (1, 0, 2))
assert occlusion.shape[1] == shape[0]
occlusion = jnp.reshape(occlusion, (shape[1], shape[2], shape[0]))
return points, occlusion
def __call__(
self,
video: chex.Array,
is_training: bool,
query_points: chex.Array,
compute_regression: bool = True,
query_chunk_size: Optional[int] = None,
get_query_feats: bool = False,
feature_grid: Optional[chex.Array] = None,
) -> Mapping[str, chex.Array]:
"""Runs a forward pass of the model.
Args:
video: A 4-D or 5-D tensor representing a batch of sequences of images. In
the 4-D case, we assume the entire batch has been concatenated along the
batch dimension, one sequence after the other. This can speed up
inference on the TPU and save memory.
is_training: Whether we are training.
query_points: The query points for which we compute tracks.
compute_regression: if True, compute tracks using cost volumes; otherwise
simply compute features (required for the baseline)
query_chunk_size: When computing cost volumes, break the queries into
chunks of this size to save memory.
get_query_feats: If True, also return the features for each query obtained
using bilinear interpolation from the feature grid
feature_grid: If specified, use this as the feature grid rather than
computing it from the pixels.
Returns:
A dict of outputs, including:
feature_grid: a TSM-ResNet feature grid of shape
[batch, num_frames, height//stride, width//stride, channels]
query_feats (optional): A feature for each query point, of size
[batch, num_queries, channels]
occlusion: Occlusion logits, of shape [batch, num_queries, num_frames]
where higher indicates more likely to be occluded.
tracks: predicted point locations, of shape
[batch, num_queries, num_frames, 2], where each point is [x, y]
in raster coordinates
"""
num_frames = None
if feature_grid is None:
latent = self.tsm_resnet(
video,
is_training=is_training,
output_stride=self.feature_grid_stride,
out_num_frames=num_frames,
final_endpoint='tsm_resnet_unit_2',
)
feature_grid = latent / jnp.sqrt(
jnp.maximum(
jnp.sum(jnp.square(latent), axis=-1, keepdims=True),
1e-12,
))
shape = video.shape
if num_frames is not None and len(shape) < 5:
shape = (shape[0] // num_frames, num_frames) + shape[1:]
# shape is [batch_size, time, height, width, channels]; conversion needs
# [time, width, height]
position_in_grid = transforms.convert_grid_coordinates(
query_points,
shape[1:4],
feature_grid.shape[1:4],
coordinate_format='tyx',
)
interp_features = jax.vmap(
jax.vmap(
model_utils.interp,
in_axes=(3, None),
out_axes=1,
)
)(feature_grid, position_in_grid)
feature_grid_heads = einshape(
'bthw(cd)->bthwcd', feature_grid, d=self.num_heads
)
interp_features_heads = einshape(
'bn(cd)->bncd',
interp_features,
d=self.num_heads,
)
out = {'feature_grid': feature_grid}
if get_query_feats:
out['query_feats'] = interp_features
if compute_regression:
assert query_chunk_size is not None
all_occ = []
all_pts = []
infer = functools.partial(self.tracks_from_cost_volume, im_shp=shape)
for i in range(0, query_points.shape[1], query_chunk_size):
points, occlusion = infer(
interp_features_heads[:, i:i + query_chunk_size],
feature_grid_heads,
query_points[:, i:i + query_chunk_size],
)
all_occ.append(occlusion)
all_pts.append(points)
occlusion = jnp.concatenate(all_occ, axis=1)
points = jnp.concatenate(all_pts, axis=1)
out['occlusion'] = occlusion
out['tracks'] = points
return out
| tapnet-main | tapnet_model.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.
# ==============================================================================
"""Abstract task interface with documentation.
"""
import abc
from typing import Mapping, Optional, Tuple
import chex
import typing_extensions
class SharedModule(typing_extensions.Protocol):
def __call__(
self,
video: chex.Array,
is_training: bool,
query_points: chex.Array,
query_chunk_size: Optional[int] = None,
get_query_feats: bool = False,
**kwargs,
) -> Mapping[str, chex.Array]:
"""Runs a forward pass of a module.
Args:
video: A 4-D or 5-D tensor representing a batch of sequences of images. In
the 4-D case, we assume the entire batch has been concatenated along the
batch dimension, one sequence after the other. This can speed up
inference on the TPU and save memory.
is_training: Whether we are training.
query_points: The query points for which we compute tracks.
query_chunk_size: When computing cost volumes, break the queries into
chunks of this size to save memory.
get_query_feats: If True, also return the features for each query obtained
using bilinear interpolation from the feature grid
**kwargs: Additional module-specific parameters.
Returns:
Module outputs.
"""
class WrappedForwardFn(typing_extensions.Protocol):
"""Forward function, wrapped by haiku.
This wrapped forward function will inject the shared_modules and allow them
to use shared params. It should be called inside a loss_fn using the same
signature as `Task.forward_fn` (minus the shared_modules).
"""
def __call__(
self,
params: chex.ArrayTree,
state: chex.ArrayTree,
rng: chex.PRNGKey,
inputs: chex.ArrayTree,
is_training: bool,
input_key: Optional[str] = None,
query_chunk_size: int = 16,
get_query_feats: bool = True,
) -> Mapping[str, chex.Array]:
"""Forward pass for predicting point tracks.
Args:
params: hk.Params with the model parameters
state: hk.State with the model state
rng: jax.random.PRNGKey for random number generation.
inputs: Input dict. Inference will be performed on will be performed on
inputs[input_key]['video'] (with fallback to the input_key specified in
the constructor). Input videos should be a standard video tensor
([batch, num_frames, height, width, 3]) normalize to [-1,1].
inputs[input_key]['query_points'] specifies the query point locations,
of shape [batch, num_queries, 3], where each query is [t,y,x]
coordinates normalized to between -1 and 1.
is_training: Whether the model is in training mode.
input_key: Run on inputs[input_key]['video']. If None, use the input_key
from the constructor.
query_chunk_size: Compute predictions on this many queries simultaneously.
This saves memory as the cost volumes can be very large.
get_query_feats: If True, also return features for each query.
Returns:
Result dict produced by calling the model.
"""
class Task(abc.ABC):
"""An abstract Task definition."""
@abc.abstractmethod
def forward_fn(
self,
inputs: chex.ArrayTree,
is_training: bool,
shared_modules: Optional[Mapping[str, SharedModule]] = None,
) -> chex.ArrayTree:
"""Run the model forward pass and construct all required Haiku modules.
Args:
inputs: model input tensors. This is a dict keyed by dataset name, where
the value for each key is an item from the specified dataset.
is_training: Is the forward pass in training mode or not.
shared_modules: A dict of Haiku modules, keyed by module name, which
can be used to construct the modules which are shared across different
tasks.
Returns:
Anything. The important part is that this must construct all modules that
Haiku needs to initialize.
"""
def get_gradients(
self,
params: chex.ArrayTree,
state: chex.ArrayTree,
inputs: chex.ArrayTree,
rng: chex.PRNGKey,
global_step: chex.Array,
wrapped_forward_fn: WrappedForwardFn,
is_training: bool = True,
) -> Tuple[chex.ArrayTree, chex.ArrayTree, Mapping[str, chex.Array]]:
"""Get gradients for this tasks's loss function.
Params, state, inputs, rng, and global_step are pmapped, i.e. a separate
copy on each device.
Args:
params: Haiku parameters
state: Haiku state
inputs: model input tensors. This is a dict keyed by dataset name, where
the value for each key is an item from the specified dataset.
rng: random number state
global_step: global step
wrapped_forward_fn: A wrapper for the forward function that will inject
the shared_modules and allow them to use shared params. It should be
called inside a loss_fn using the same signature as forward_fn
(minus the shared_modules).
is_training: Is the forward pass in training mode or not.
Returns:
grads: A set of gradients compatible with optax apply_gradients (these
will be summed across tasks).
state: An updated Haiku state. The returned state will be passed to the
next task in the list.
scalars: A dict of (pmapped) scalars to be logged for this task. All
dict keys will have the task name prepended before they are logged.
"""
raise NotImplementedError()
def evaluate(
self,
global_step: chex.Array,
params: chex.ArrayTree,
state: chex.ArrayTree,
rng: chex.PRNGKey,
wrapped_forward_fn: WrappedForwardFn,
mode: str,
) -> Mapping[str, chex.Array]:
"""Evaluate this task's performance on a downstream benchmark.
Args:
global_step: global step
params: Haiku parameters
state: Haiku state
rng: random number state
wrapped_forward_fn: A wrapper for the forward function that will inject
the shared_modules and allow them to use shared params.
mode: A string mode used to determine, e.g., which dataset or split to
evaluate on. This will be the same value as the 'mode' parameter
used to launch different eval jobs in Jaxline.
Returns:
scalars: A dict of scalars to be logged for this task. All
dict keys will have the task name prepended before they are logged.
"""
raise NotImplementedError()
| tapnet-main | task.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.
# ==============================================================================
"""Evaluation dataset creation functions."""
import csv
import functools
import io
import os
from os import path
import pickle
import random
from typing import Iterable, Mapping, Optional, Tuple, Union
from absl import logging
from kubric.challenges.point_tracking import dataset
import mediapy as media
import numpy as np
from PIL import Image
import scipy.io as sio
import tensorflow as tf
import tensorflow_datasets as tfds
from tapnet.utils import transforms
DatasetElement = Mapping[str, Mapping[str, Union[np.ndarray, str]]]
def resize_video(video: np.ndarray, output_size: Tuple[int, int]) -> np.ndarray:
"""Resize a video to output_size."""
# If you have a GPU, consider replacing this with a GPU-enabled resize op,
# such as a jitted jax.image.resize. It will make things faster.
return media.resize_video(video, output_size[1:3])
def compute_tapvid_metrics(
query_points: np.ndarray,
gt_occluded: np.ndarray,
gt_tracks: np.ndarray,
pred_occluded: np.ndarray,
pred_tracks: np.ndarray,
query_mode: str,
) -> Mapping[str, np.ndarray]:
"""Computes TAP-Vid metrics (Jaccard, Pts.
Within Thresh, Occ.
Acc.)
See the TAP-Vid paper for details on the metric computation. All inputs are
given in raster coordinates. The first three arguments should be the direct
outputs of the reader: the 'query_points', 'occluded', and 'target_points'.
The paper metrics assume these are scaled relative to 256x256 images.
pred_occluded and pred_tracks are your algorithm's predictions.
This function takes a batch of inputs, and computes metrics separately for
each video. The metrics for the full benchmark are a simple mean of the
metrics across the full set of videos. These numbers are between 0 and 1,
but the paper multiplies them by 100 to ease reading.
Args:
query_points: The query points, an in the format [t, y, x]. Its size is
[b, n, 3], where b is the batch size and n is the number of queries
gt_occluded: A boolean array of shape [b, n, t], where t is the number of
frames. True indicates that the point is occluded.
gt_tracks: The target points, of shape [b, n, t, 2]. Each point is in the
format [x, y]
pred_occluded: A boolean array of predicted occlusions, in the same format
as gt_occluded.
pred_tracks: An array of track predictions from your algorithm, in the same
format as gt_tracks.
query_mode: Either 'first' or 'strided', depending on how queries are
sampled. If 'first', we assume the prior knowledge that all points
before the query point are occluded, and these are removed from the
evaluation.
Returns:
A dict with the following keys:
occlusion_accuracy: Accuracy at predicting occlusion.
pts_within_{x} for x in [1, 2, 4, 8, 16]: Fraction of points
predicted to be within the given pixel threshold, ignoring occlusion
prediction.
jaccard_{x} for x in [1, 2, 4, 8, 16]: Jaccard metric for the given
threshold
average_pts_within_thresh: average across pts_within_{x}
average_jaccard: average across jaccard_{x}
"""
metrics = {}
eye = np.eye(gt_tracks.shape[2], dtype=np.int32)
if query_mode == 'first':
# evaluate frames after the query frame
query_frame_to_eval_frames = np.cumsum(eye, axis=1) - eye
elif query_mode == 'strided':
# evaluate all frames except the query frame
query_frame_to_eval_frames = 1 - eye
else:
raise ValueError('Unknown query mode ' + query_mode)
query_frame = query_points[..., 0]
query_frame = np.round(query_frame).astype(np.int32)
evaluation_points = query_frame_to_eval_frames[query_frame] > 0
# Occlusion accuracy is simply how often the predicted occlusion equals the
# ground truth.
occ_acc = np.sum(
np.equal(pred_occluded, gt_occluded) & evaluation_points,
axis=(1, 2),
) / np.sum(evaluation_points)
metrics['occlusion_accuracy'] = occ_acc
# Next, convert the predictions and ground truth positions into pixel
# coordinates.
visible = np.logical_not(gt_occluded)
pred_visible = np.logical_not(pred_occluded)
all_frac_within = []
all_jaccard = []
for thresh in [1, 2, 4, 8, 16]:
# True positives are points that are within the threshold and where both
# the prediction and the ground truth are listed as visible.
within_dist = np.sum(
np.square(pred_tracks - gt_tracks),
axis=-1,
) < np.square(thresh)
is_correct = np.logical_and(within_dist, visible)
# Compute the frac_within_threshold, which is the fraction of points
# within the threshold among points that are visible in the ground truth,
# ignoring whether they're predicted to be visible.
count_correct = np.sum(
is_correct & evaluation_points,
axis=(1, 2),
)
count_visible_points = np.sum(visible & evaluation_points, axis=(1, 2))
frac_correct = count_correct / count_visible_points
metrics['pts_within_' + str(thresh)] = frac_correct
all_frac_within.append(frac_correct)
true_positives = np.sum(
is_correct & pred_visible & evaluation_points, axis=(1, 2)
)
# The denominator of the jaccard metric is the true positives plus
# false positives plus false negatives. However, note that true positives
# plus false negatives is simply the number of points in the ground truth
# which is easier to compute than trying to compute all three quantities.
# Thus we just add the number of points in the ground truth to the number
# of false positives.
#
# False positives are simply points that are predicted to be visible,
# but the ground truth is not visible or too far from the prediction.
gt_positives = np.sum(visible & evaluation_points, axis=(1, 2))
false_positives = (~visible) & pred_visible
false_positives = false_positives | ((~within_dist) & pred_visible)
false_positives = np.sum(false_positives & evaluation_points, axis=(1, 2))
jaccard = true_positives / (gt_positives + false_positives)
metrics['jaccard_' + str(thresh)] = jaccard
all_jaccard.append(jaccard)
metrics['average_jaccard'] = np.mean(
np.stack(all_jaccard, axis=1),
axis=1,
)
metrics['average_pts_within_thresh'] = np.mean(
np.stack(all_frac_within, axis=1),
axis=1,
)
return metrics
def latex_table(mean_scalars: Mapping[str, float]) -> str:
"""Generate a latex table for displaying TAP-Vid and PCK metrics."""
if 'average_jaccard' in mean_scalars:
latex_fields = [
'average_jaccard',
'average_pts_within_thresh',
'occlusion_accuracy',
'jaccard_1',
'jaccard_2',
'jaccard_4',
'jaccard_8',
'jaccard_16',
'pts_within_1',
'pts_within_2',
'pts_within_4',
'pts_within_8',
'pts_within_16',
]
header = (
'AJ & $<\\delta^{x}_{avg}$ & OA & Jac. $\\delta^{0}$ & '
+ 'Jac. $\\delta^{1}$ & Jac. $\\delta^{2}$ & '
+ 'Jac. $\\delta^{3}$ & Jac. $\\delta^{4}$ & $<\\delta^{0}$ & '
+ '$<\\delta^{1}$ & $<\\delta^{2}$ & $<\\delta^{3}$ & '
+ '$<\\delta^{4}$'
)
else:
latex_fields = ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
header = ' & '.join(latex_fields)
body = ' & '.join(
[f'{float(np.array(mean_scalars[x]*100)):.3}' for x in latex_fields]
)
return '\n'.join([header, body])
def sample_queries_strided(
target_occluded: np.ndarray,
target_points: np.ndarray,
frames: np.ndarray,
query_stride: int = 5,
) -> Mapping[str, np.ndarray]:
"""Package a set of frames and tracks for use in TAPNet evaluations.
Given a set of frames and tracks with no query points, sample queries
strided every query_stride frames, ignoring points that are not visible
at the selected frames.
Args:
target_occluded: Boolean occlusion flag, of shape [n_tracks, n_frames],
where True indicates occluded.
target_points: Position, of shape [n_tracks, n_frames, 2], where each point
is [x,y] scaled between 0 and 1.
frames: Video tensor, of shape [n_frames, height, width, 3]. Scaled between
-1 and 1.
query_stride: When sampling query points, search for un-occluded points
every query_stride frames and convert each one into a query.
Returns:
A dict with the keys:
video: Video tensor of shape [1, n_frames, height, width, 3]. The video
has floats scaled to the range [-1, 1].
query_points: Query points of shape [1, n_queries, 3] where
each point is [t, y, x] scaled to the range [-1, 1].
target_points: Target points of shape [1, n_queries, n_frames, 2] where
each point is [x, y] scaled to the range [-1, 1].
trackgroup: Index of the original track that each query point was
sampled from. This is useful for visualization.
"""
tracks = []
occs = []
queries = []
trackgroups = []
total = 0
trackgroup = np.arange(target_occluded.shape[0])
for i in range(0, target_occluded.shape[1], query_stride):
mask = target_occluded[:, i] == 0
query = np.stack(
[
i * np.ones(target_occluded.shape[0:1]),
target_points[:, i, 1],
target_points[:, i, 0],
],
axis=-1,
)
queries.append(query[mask])
tracks.append(target_points[mask])
occs.append(target_occluded[mask])
trackgroups.append(trackgroup[mask])
total += np.array(np.sum(target_occluded[:, i] == 0))
return {
'video': frames[np.newaxis, ...],
'query_points': np.concatenate(queries, axis=0)[np.newaxis, ...],
'target_points': np.concatenate(tracks, axis=0)[np.newaxis, ...],
'occluded': np.concatenate(occs, axis=0)[np.newaxis, ...],
'trackgroup': np.concatenate(trackgroups, axis=0)[np.newaxis, ...],
}
def sample_queries_first(
target_occluded: np.ndarray,
target_points: np.ndarray,
frames: np.ndarray,
) -> Mapping[str, np.ndarray]:
"""Package a set of frames and tracks for use in TAPNet evaluations.
Given a set of frames and tracks with no query points, use the first
visible point in each track as the query.
Args:
target_occluded: Boolean occlusion flag, of shape [n_tracks, n_frames],
where True indicates occluded.
target_points: Position, of shape [n_tracks, n_frames, 2], where each point
is [x,y] scaled between 0 and 1.
frames: Video tensor, of shape [n_frames, height, width, 3]. Scaled between
-1 and 1.
Returns:
A dict with the keys:
video: Video tensor of shape [1, n_frames, height, width, 3]
query_points: Query points of shape [1, n_queries, 3] where
each point is [t, y, x] scaled to the range [-1, 1]
target_points: Target points of shape [1, n_queries, n_frames, 2] where
each point is [x, y] scaled to the range [-1, 1]
"""
valid = np.sum(~target_occluded, axis=1) > 0
target_points = target_points[valid, :]
target_occluded = target_occluded[valid, :]
query_points = []
for i in range(target_points.shape[0]):
index = np.where(target_occluded[i] == 0)[0][0]
x, y = target_points[i, index, 0], target_points[i, index, 1]
query_points.append(np.array([index, y, x])) # [t, y, x]
query_points = np.stack(query_points, axis=0)
return {
'video': frames[np.newaxis, ...],
'query_points': query_points[np.newaxis, ...],
'target_points': target_points[np.newaxis, ...],
'occluded': target_occluded[np.newaxis, ...],
}
def create_jhmdb_dataset(
jhmdb_path: str, resolution: Optional[Tuple[int, int]] = (256, 256)
) -> Iterable[DatasetElement]:
"""JHMDB dataset, including fields required for PCK evaluation."""
videos = []
for file in tf.io.gfile.listdir(path.join(gt_dir, 'splits')):
# JHMDB file containing the first split, which is standard for this type of
# evaluation.
if not file.endswith('split1.txt'):
continue
video_folder = '_'.join(file.split('_')[:-2])
for video in tf.io.gfile.GFile(path.join(gt_dir, 'splits', file), 'r'):
video, traintest = video.split()
video, _ = video.split('.')
traintest = int(traintest)
video_path = path.join(video_folder, video)
if traintest == 2:
videos.append(video_path)
if not videos:
raise ValueError('No JHMDB videos found in directory ' + str(jhmdb_path))
# Shuffle so numbers converge faster.
random.shuffle(videos)
for video in videos:
logging.info(video)
joints = path.join(gt_dir, 'joint_positions', video, 'joint_positions.mat')
if not tf.io.gfile.exists(joints):
logging.info('skip %s', video)
continue
gt_pose = sio.loadmat(tf.io.gfile.GFile(joints, 'rb'))['pos_img']
gt_pose = np.transpose(gt_pose, [1, 2, 0])
frames = path.join(gt_dir, 'Rename_Images', video, '*.png')
framefil = tf.io.gfile.glob(frames)
framefil.sort()
def read_frame(f):
im = Image.open(tf.io.gfile.GFile(f, 'rb'))
im = im.convert('RGB')
im_data = np.array(im.getdata(), np.uint8)
return im_data.reshape([im.size[1], im.size[0], 3])
frames = [read_frame(x) for x in framefil]
frames = np.stack(frames)
height = frames.shape[1]
width = frames.shape[2]
invalid_x = np.logical_or(
gt_pose[:, 0:1, 0] < 0,
gt_pose[:, 0:1, 0] >= width,
)
invalid_y = np.logical_or(
gt_pose[:, 0:1, 1] < 0,
gt_pose[:, 0:1, 1] >= height,
)
invalid = np.logical_or(invalid_x, invalid_y)
invalid = np.tile(invalid, [1, gt_pose.shape[1]])
invalid = invalid[:, :, np.newaxis].astype(np.float32)
gt_pose_orig = gt_pose
if resolution is not None and resolution != frames.shape[1:3]:
frames = resize_video(frames, resolution)
frames = frames / (255.0 / 2.0) - 1.0
queries = gt_pose[:, 0]
queries = np.concatenate(
[queries[..., 0:1] * 0, queries[..., ::-1]],
axis=-1,
)
gt_pose = transforms.convert_grid_coordinates(
gt_pose,
np.array([width, height]),
np.array([frames.shape[2], frames.shape[1]]),
)
# Set invalid poses to -1 (outside the frame)
gt_pose = (1.0 - invalid) * gt_pose + invalid * (-1.0)
if gt_pose.shape[1] < frames.shape[0]:
# Some videos have pose sequences that are shorter than the frame
# sequence (usually because the person disappears). In this case,
# truncate the video.
logging.warning('short video!!')
frames = frames[: gt_pose.shape[1]]
converted = {
'video': frames[np.newaxis, ...],
'query_points': queries[np.newaxis, ...],
'target_points': gt_pose[np.newaxis, ...],
'gt_pose': gt_pose[np.newaxis, ...],
'gt_pose_orig': gt_pose_orig[np.newaxis, ...],
'occluded': gt_pose[np.newaxis, ..., 0] * 0,
'fname': video,
'im_size': np.array([height, width]),
}
yield {'jhmdb': converted}
def create_kubric_eval_train_dataset(
mode: str,
train_size: Tuple[int, int] = (256, 256),
max_dataset_size: int = 100,
) -> Iterable[DatasetElement]:
"""Dataset for evaluating performance on Kubric training data."""
res = dataset.create_point_tracking_dataset(
split='train',
train_size=train_size,
batch_dims=[1],
shuffle_buffer_size=None,
repeat=False,
vflip='vflip' in mode,
random_crop=False,
)
np_ds = tfds.as_numpy(res)
num_returned = 0
for data in np_ds:
if num_returned >= max_dataset_size:
break
num_returned += 1
yield {'kubric': data}
def create_kubric_eval_dataset(
mode: str, train_size: Tuple[int, int] = (256, 256)
) -> Iterable[DatasetElement]:
"""Dataset for evaluating performance on Kubric val data."""
res = dataset.create_point_tracking_dataset(
split='validation',
train_size=train_size,
batch_dims=[1],
shuffle_buffer_size=None,
repeat=False,
vflip='vflip' in mode,
random_crop=False,
)
np_ds = tfds.as_numpy(res)
for data in np_ds:
yield {'kubric': data}
def create_davis_dataset(
davis_points_path: str,
query_mode: str = 'strided',
full_resolution=False,
resolution: Optional[Tuple[int, int]] = (256, 256),
) -> Iterable[DatasetElement]:
"""Dataset for evaluating performance on DAVIS data."""
pickle_path = davis_points_path
with tf.io.gfile.GFile(pickle_path, 'rb') as f:
davis_points_dataset = pickle.load(f)
if full_resolution:
ds, _ = tfds.load(
'davis/full_resolution', split='validation', with_info=True
)
to_iterate = tfds.as_numpy(ds)
else:
to_iterate = davis_points_dataset.keys()
for tmp in to_iterate:
if full_resolution:
frames = tmp['video']['frames']
video_name = tmp['metadata']['video_name'].decode()
else:
video_name = tmp
frames = davis_points_dataset[video_name]['video']
if resolution is not None and resolution != frames.shape[1:3]:
frames = resize_video(frames, resolution)
frames = frames.astype(np.float32) / 255.0 * 2.0 - 1.0
target_points = davis_points_dataset[video_name]['points']
target_occ = davis_points_dataset[video_name]['occluded']
target_points = target_points * np.array([frames.shape[2], frames.shape[1]])
if query_mode == 'strided':
converted = sample_queries_strided(target_occ, target_points, frames)
elif query_mode == 'first':
converted = sample_queries_first(target_occ, target_points, frames)
else:
raise ValueError(f'Unknown query mode {query_mode}.')
yield {'davis': converted}
def create_rgb_stacking_dataset(
robotics_points_path: str,
query_mode: str = 'strided',
resolution: Optional[Tuple[int, int]] = (256, 256),
) -> Iterable[DatasetElement]:
"""Dataset for evaluating performance on robotics data."""
pickle_path = robotics_points_path
with tf.io.gfile.GFile(pickle_path, 'rb') as f:
robotics_points_dataset = pickle.load(f)
for example in robotics_points_dataset:
frames = example['video']
if resolution is not None and resolution != frames.shape[1:3]:
frames = resize_video(frames, resolution)
frames = frames.astype(np.float32) / 255.0 * 2.0 - 1.0
target_points = example['points']
target_occ = example['occluded']
target_points = target_points * np.array([frames.shape[2], frames.shape[1]])
if query_mode == 'strided':
converted = sample_queries_strided(target_occ, target_points, frames)
elif query_mode == 'first':
converted = sample_queries_first(target_occ, target_points, frames)
else:
raise ValueError(f'Unknown query mode {query_mode}.')
yield {'robotics': converted}
def create_kinetics_dataset(
kinetics_path: str, query_mode: str = 'strided',
resolution: Optional[Tuple[int, int]] = (256, 256),
) -> Iterable[DatasetElement]:
"""Dataset for evaluating performance on Kinetics point tracking."""
all_paths = tf.io.gfile.glob(path.join(kinetics_path, '*_of_0010.pkl'))
for pickle_path in all_paths:
with open(pickle_path, 'rb') as f:
data = pickle.load(f)
if isinstance(data, dict):
data = list(data.values())
# idx = random.randint(0, len(data) - 1)
for idx in range(len(data)):
example = data[idx]
frames = example['video']
if isinstance(frames[0], bytes):
# TAP-Vid is stored and JPEG bytes rather than `np.ndarray`s.
def decode(frame):
byteio = io.BytesIO(frame)
img = Image.open(byteio)
return np.array(img)
frames = np.array([decode(frame) for frame in frames])
if resolution is not None and resolution != frames.shape[1:3]:
frames = resize_video(frames, resolution)
frames = frames.astype(np.float32) / 255.0 * 2.0 - 1.0
target_points = example['points']
target_occ = example['occluded']
target_points *= np.array([frames.shape[2], frames.shape[1]])
if query_mode == 'strided':
converted = sample_queries_strided(target_occ, target_points, frames)
elif query_mode == 'first':
converted = sample_queries_first(target_occ, target_points, frames)
else:
raise ValueError(f'Unknown query mode {query_mode}.')
yield {'kinetics': converted}
def create_csv_dataset(
dataset_name: str,
csv_path: str,
video_base_path: str,
query_mode: str = 'strided',
resolution: Optional[Tuple[int, int]] = (256, 256),
max_video_frames: Optional[int] = 1000,
) -> Iterable[DatasetElement]:
"""Create an evaluation iterator out of human annotations and videos.
Args:
dataset_name: Name to the dataset.
csv_path: Path to annotations csv.
video_base_path: Path to annotated videos.
query_mode: sample query points from first frame or strided.
resolution: The video resolution in (height, width).
max_video_frames: Max length of annotated video.
Yields:
Samples for evaluation.
"""
point_tracks_all = dict()
with tf.io.gfile.GFile(csv_path, 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
video_id = row[0]
point_tracks = np.array(row[1:]).reshape(-1, 3)
if video_id in point_tracks_all:
point_tracks_all[video_id].append(point_tracks)
else:
point_tracks_all[video_id] = [point_tracks]
for video_id in point_tracks_all:
if video_id.endswith('.mp4'):
video_path = path.join(video_base_path, video_id)
else:
video_path = path.join(video_base_path, video_id + '.mp4')
frames = media.read_video(video_path)
if resolution is not None and resolution != frames.shape[1:3]:
frames = media.resize_video(frames, resolution)
frames = frames.astype(np.float32) / 255.0 * 2.0 - 1.0
point_tracks = np.stack(point_tracks_all[video_id], axis=0)
point_tracks = point_tracks.astype(np.float32)
if frames.shape[0] < point_tracks.shape[1]:
logging.info('Warning: short video!')
point_tracks = point_tracks[:, : frames.shape[0]]
point_tracks, occluded = point_tracks[..., 0:2], point_tracks[..., 2]
occluded = occluded > 0
target_points = point_tracks * np.array([frames.shape[2], frames.shape[1]])
num_splits = int(np.ceil(frames.shape[0] / max_video_frames))
if num_splits > 1:
print(f'Going to split the video {video_id} into {num_splits}')
for i in range(num_splits):
start_index = i * frames.shape[0] // num_splits
end_index = (i + 1) * frames.shape[0] // num_splits
sub_occluded = occluded[:, start_index:end_index]
sub_target_points = target_points[:, start_index:end_index]
sub_frames = frames[start_index:end_index]
if query_mode == 'strided':
converted = sample_queries_strided(
sub_occluded, sub_target_points, sub_frames
)
elif query_mode == 'first':
converted = sample_queries_first(
sub_occluded, sub_target_points, sub_frames
)
else:
raise ValueError(f'Unknown query mode {query_mode}.')
yield {dataset_name: converted}
| tapnet-main | evaluation_datasets.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.
# ==============================================================================
"""Live Demo for Online TAPIR."""
import functools
import time
import cv2
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
from tapnet import tapir_model
NUM_POINTS = 8
def construct_initial_causal_state(num_points, num_resolutions):
"""Construct initial causal state."""
value_shapes = {
"tapir/~/pips_mlp_mixer/block_1_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_1_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_2_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_2_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_3_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_3_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_4_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_4_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_5_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_5_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_6_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_6_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_7_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_7_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_8_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_8_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_9_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_9_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_10_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_10_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_11_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_11_causal_2": (1, num_points, 2, 2048),
"tapir/~/pips_mlp_mixer/block_causal_1": (1, num_points, 2, 512),
"tapir/~/pips_mlp_mixer/block_causal_2": (1, num_points, 2, 2048),
}
fake_ret = {
k: jnp.zeros(v, dtype=jnp.float32) for k, v in value_shapes.items()
}
return [fake_ret] * num_resolutions * 4
def preprocess_frames(frames):
"""Preprocess frames to model inputs.
Args:
frames: [num_frames, height, width, 3], [0, 255], np.uint8
Returns:
frames: [num_frames, height, width, 3], [-1, 1], np.float32
"""
frames = frames.astype(np.float32)
frames = frames / 255 * 2 - 1
return frames
def postprocess_frames(frames):
"""Postprocess frames back to traditional image format.
Args:
frames: [num_frames, height, width, 3], [-1, 1], np.float32
Returns:
frames: [num_frames, height, width, 3], [0, 255], np.uint8
"""
frames = (frames + 1) / 2 * 255
frames = np.round(frames).astype(np.uint8)
return frames
def postprocess_occlusions(occlusions, exp_dist):
"""Postprocess occlusions to boolean visible flag.
Args:
occlusions: [num_points, num_frames], [-inf, inf], np.float32
exp_dist: [num_points, num_frames], [-inf, inf], np.float32
Returns:
visibles: [num_points, num_frames], bool
"""
# visibles = occlusions < 0
pred_occ = jax.nn.sigmoid(occlusions)
pred_occ = 1 - (1 - pred_occ) * (1 - jax.nn.sigmoid(exp_dist))
return pred_occ < 0.5
def load_checkpoint(checkpoint_path):
ckpt_state = np.load(checkpoint_path, allow_pickle=True).item()
return ckpt_state["params"], ckpt_state["state"]
def build_online_model_init(frames, points):
model = tapir_model.TAPIR(
use_causal_conv=True, bilinear_interp_with_depthwise_conv=False
)
feature_grids = model.get_feature_grids(frames, is_training=False)
features = model.get_query_features(
frames,
is_training=False,
query_points=points,
feature_grids=feature_grids,
)
return features
def build_online_model_predict(frames, features, causal_context):
"""Compute point tracks and occlusions given frames and query points."""
model = tapir_model.TAPIR(
use_causal_conv=True, bilinear_interp_with_depthwise_conv=False
)
feature_grids = model.get_feature_grids(frames, is_training=False)
trajectories = model.estimate_trajectories(
frames.shape[-3:-1],
is_training=False,
feature_grids=feature_grids,
query_features=features,
query_points_in_video=None,
query_chunk_size=64,
causal_context=causal_context,
get_causal_context=True,
)
causal_context = trajectories["causal_context"]
del trajectories["causal_context"]
return {k: v[-1] for k, v in trajectories.items()}, causal_context
def get_frame(video_capture):
r_val, image = video_capture.read()
trunc = np.abs(image.shape[1] - image.shape[0]) // 2
if image.shape[1] > image.shape[0]:
image = image[:, trunc:-trunc]
elif image.shape[1] < image.shape[0]:
image = image[trunc:-trunc]
return r_val, image
print("Welcome to the TAPIR live demo.")
print("Please note that if the framerate is low (<~12 fps), TAPIR performance")
print("may degrade and you may need a more powerful GPU.")
print("Loading checkpoint...")
# --------------------
# Load checkpoint and initialize
params, state = load_checkpoint(
"tapnet/checkpoints/causal_tapir_checkpoint.npy"
)
print("Creating model...")
online_init = hk.transform_with_state(build_online_model_init)
online_init_apply = jax.jit(online_init.apply)
online_predict = hk.transform_with_state(build_online_model_predict)
online_predict_apply = jax.jit(online_predict.apply)
rng = jax.random.PRNGKey(42)
online_init_apply = functools.partial(
online_init_apply, params=params, state=state, rng=rng
)
online_predict_apply = functools.partial(
online_predict_apply, params=params, state=state, rng=rng
)
print("Initializing camera...")
# --------------------
# Start point tracking
vc = cv2.VideoCapture(0)
vc.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
if vc.isOpened(): # try to get the first frame
rval, frame = get_frame(vc)
else:
raise ValueError("Unable to open camera.")
pos = tuple()
query_frame = True
have_point = [False] * NUM_POINTS
query_features = None
causal_state = None
next_query_idx = 0
print("Compiling jax functions (this may take a while...)")
# --------------------
# Call one time to compile
query_points = jnp.zeros([NUM_POINTS, 3], dtype=jnp.float32)
query_features, _ = online_init_apply(
frames=preprocess_frames(frame[None, None]),
points=query_points[None, 0:1],
)
jax.block_until_ready(query_features)
query_features, _ = online_init_apply(
frames=preprocess_frames(frame[None, None]),
points=query_points[None],
)
causal_state = construct_initial_causal_state(
NUM_POINTS, len(query_features.resolutions) - 1
)
(prediction, causal_state), _ = online_predict_apply(
frames=preprocess_frames(frame[None, None]),
features=query_features,
causal_context=causal_state,
)
jax.block_until_ready(prediction["tracks"])
last_click_time = 0
def mouse_click(event, x, y, flags, param):
del flags, param
global pos, query_frame, last_click_time
# event fires multiple times per click sometimes??
if (time.time() - last_click_time) < 0.5:
return
if event == cv2.EVENT_LBUTTONDOWN:
pos = (y, frame.shape[1] - x)
query_frame = True
last_click_time = time.time()
cv2.namedWindow("Point Tracking")
cv2.setMouseCallback("Point Tracking", mouse_click)
t = time.time()
step_counter = 0
while rval:
rval, frame = get_frame(vc)
if query_frame:
query_points = jnp.array((0,) + pos, dtype=jnp.float32)
init_query_features, _ = online_init_apply(
frames=preprocess_frames(frame[None, None]),
points=query_points[None, None],
)
init_causal_state = construct_initial_causal_state(
1, len(query_features.resolutions) - 1
)
# cv2.circle(frame, (pos[0], pos[1]), 5, (255,0,0), -1)
query_frame = False
def upd(s1, s2):
return s1.at[:, next_query_idx : next_query_idx + 1].set(s2)
causal_state = jax.tree_map(upd, causal_state, init_causal_state)
query_features = tapir_model.QueryFeatures(
lowres=jax.tree_map(
upd, query_features.lowres, init_query_features.lowres
),
hires=jax.tree_map(
upd, query_features.hires, init_query_features.hires
),
resolutions=query_features.resolutions,
)
have_point[next_query_idx] = True
next_query_idx = (next_query_idx + 1) % NUM_POINTS
if pos:
(prediction, causal_state), _ = online_predict_apply(
frames=preprocess_frames(frame[None, None]),
features=query_features,
causal_context=causal_state,
)
track = prediction["tracks"][0, :, 0]
occlusion = prediction["occlusion"][0, :, 0]
expected_dist = prediction["expected_dist"][0, :, 0]
visibles = postprocess_occlusions(occlusion, expected_dist)
track = np.round(track)
for i in range(len(have_point)):
if visibles[i] and have_point[i]:
cv2.circle(
frame, (int(track[i, 0]), int(track[i, 1])), 5, (255, 0, 0), -1
)
if track[i, 0] < 16 and track[i, 1] < 16:
print((i, next_query_idx))
cv2.imshow("Point Tracking", frame[:, ::-1])
if pos:
step_counter += 1
if time.time() - t > 5:
print(f"{step_counter/(time.time()-t)} frames per second")
t = time.time()
step_counter = 0
else:
t = time.time()
key = cv2.waitKey(1)
if key == 27: # exit on ESC
break
cv2.destroyWindow("Point Tracking")
vc.release()
| tapnet-main | live_demo.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.
# ==============================================================================
"""Optimizer utils."""
from typing import Callable, Sequence, NamedTuple, Optional, Text
import haiku as hk
import jax
import jax.numpy as jnp
import optax
NORM_NAMES = ["layer_norm", "batch_norm", "_bn", "linear_classifier"]
def _weight_decay_exclude(
exclude_names: Optional[Sequence[Text]] = None,
) -> Callable[[str, str, jnp.ndarray], bool]:
"""Logic for deciding which parameters to include for weight decay..
Args:
exclude_names: an optional list of names to include for weight_decay. ['w']
by default.
Returns:
A predicate that returns False for params that need to be excluded from
weight_decay.
"""
# By default weight_decay the weights but not the biases.
if exclude_names is None:
exclude_names = ["b"]
def include(module_name: Text, name: Text, value: jnp.ndarray):
del value
# Do not weight decay the parameters of normalization blocks.
if any([norm_name in module_name for norm_name in NORM_NAMES]):
return False
else:
return name not in exclude_names
return include
class AddWeightDecayState(NamedTuple):
"""Stateless transformation."""
def add_weight_decay(
weight_decay: float,
exclude_names: Optional[Sequence[Text]] = None,
) -> optax.GradientTransformation:
"""Add parameter scaled by `weight_decay` to the `updates`.
Same as optax.add_decayed_weights but can exclude some parameters.
Args:
weight_decay: weight_decay coefficient.
exclude_names: an optional list of names to exclude for weight_decay. ['b']
by default.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return AddWeightDecayState()
def update_fn(updates, state, params):
include = _weight_decay_exclude(exclude_names=exclude_names)
u_in, u_ex = hk.data_structures.partition(include, updates)
p_in, _ = hk.data_structures.partition(include, params)
u_in = jax.tree_map(lambda g, p: g + weight_decay * p, u_in, p_in)
updates = hk.data_structures.merge(u_ex, u_in)
return updates, state
return optax.GradientTransformation(init_fn, update_fn)
| tapnet-main | optimizers.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 Jaxline script for training and evaluating TAPNet."""
import sys
from typing import Callable, Dict, Iterable, Iterator, Mapping, Optional, Tuple
from absl import app
from absl import flags
from absl import logging
import chex
import haiku as hk
import jax
import jax.numpy as jnp
from jaxline import experiment
from jaxline import platform
from jaxline import utils
from kubric.challenges.point_tracking import dataset
from ml_collections import config_dict
import numpy as np
import optax
import tensorflow as tf
import tensorflow_datasets as tfds
from tapnet import supervised_point_prediction
from tapnet import tapir_model
from tapnet import tapnet_model
from tapnet import task
from tapnet.utils import experiment_utils as exputils
class Experiment(experiment.AbstractExperiment):
"""TAPNet experiment.
This constructs a set of tasks which are used to compute gradients, as well as
a set of datasets which are passed into every task. After the tasks compute
gradients using the data, this experiment will aggregate and apply those
gradients using an optimizer.
This experiment is organized around the needs of Haiku's multi transform:
each task specifies its own forward function, but different tasks need to
share parameters. Therefore, the design of this experiment is that each
task has a forward function, but the global Experiment class is responsible
for creating the multi transform out of these. The Experiment class keeps
track of the variables. Each task doesn't directly call its own forward
function. Instead receives a "wrapped" forward function which contains
the Haiku state, which injected (via closure) by the Experiment class.
To do its job, multi transform needs two things: a function
which initializes all variables, and the set of forward functions that need
to be called separately, one for each task. The latter is just the set of
forward functions for each task. The initialization function is
just a function that calls every forward function sequentially.
"""
# A map from object properties that will be checkpointed to their name
# in a checkpoint. Currently we assume that these are all sharded
# device arrays.
CHECKPOINT_ATTRS = {
'_params': 'params',
'_state': 'state',
'_opt_state': 'opt_state',
}
def __init__(
self,
mode: str,
init_rng: jnp.ndarray,
config: config_dict.ConfigDict,
):
"""Initializes the experiment.
This includes constructing all of the requested tasks, creating the Haiku
transforms, and pmapping the update function that will be used throughout
training. Currently the two supported training tasks are 'selfsup_tracks'
and 'kubric'.
Args:
mode: either 'train' (for training) or one of the recognized eval modes
(see Experiment.evaluate).
init_rng: jax.random.PRNGKey for random number generation.
config: config options. See configs/tapnet_config.py for an example.
"""
super().__init__(mode=mode, init_rng=init_rng)
self.mode = mode
self.init_rng = init_rng
self.config = config
# Checkpointed experiment state.
self._params = None
self._state = None
self._opt_state = None
self._optimizer = None
# Input pipelines.
self._train_input = None
self._eval_input = None
self.point_prediction = (
supervised_point_prediction.SupervisedPointPrediction(
config, **config.supervised_point_prediction_kwargs
)
)
def forward(*args, is_training=True, **kwargs):
shared_modules = self._construct_shared_modules()
return self.point_prediction.forward_fn(
*args,
shared_modules=shared_modules,
is_training=is_training,
**kwargs,
)
self._transform = hk.transform_with_state(forward)
# NOTE: We "donate" the `params, state, opt_state` arguments which allows
# JAX (on some backends) to reuse the device memory associated with these
# inputs to store the outputs of our function (which also start with
# `params, state, opt_state`).
self._update_func = jax.pmap(
self._update_func, axis_name='i', donate_argnums=(0, 1, 2))
def _construct_shared_modules(self) -> Mapping[str, task.SharedModule]:
"""Constructs the TAPNet module which is used for all tasks.
More generally, these are Haiku modules that are passed to all tasks so that
weights are shared across tasks.
Returns:
A dict with a single key 'tapnet_model' containing the tapnet model.
"""
shared_module_constructors = {
'tapnet_model': tapnet_model.TAPNet,
'tapir_model': tapir_model.TAPIR,
}
shared_modules = {}
for shared_mod_name in self.config.shared_modules.shared_module_names:
ctor = shared_module_constructors[shared_mod_name]
kwargs = self.config.shared_modules[shared_mod_name + '_kwargs']
shared_modules[shared_mod_name] = ctor(**kwargs)
return shared_modules
# _ _
# | |_ _ __ __ _(_)_ __
# | __| '__/ _` | | '_ \
# | |_| | | (_| | | | | |
# \__|_| \__,_|_|_| |_|
#
def step( # pytype: disable=signature-mismatch # numpy-scalars
self,
global_step: chex.Array,
rng: chex.PRNGKey,
*unused_args,
**unused_kwargs,
) -> Dict[str, chex.Array]:
"""See base class."""
if self._train_input is None:
self._initialize_train()
inputs = next(self._train_input)
self._params, self._state, self._opt_state, scalars = self._update_func(
self._params,
self._state,
self._opt_state,
inputs,
rng,
global_step,
)
scalars = utils.get_first(scalars)
if ((utils.get_first(global_step) + 1) % self.config.evaluate_every) == 0:
for mode in self.config.eval_modes:
eval_scalars = self.evaluate(global_step, rng=rng, mode=mode)
scalars.update(eval_scalars)
return scalars
def _initialize_train(self):
"""Initializes the training parameters using the first training input.
self._multi_transform.init will call the forward_fn, which allows
Haiku to identify the params that need to be initialized.
"""
self._train_input = utils.py_prefetch(self._build_train_input)
total_steps = self.config.training.n_training_steps
# Scale by the (negative) learning rate.
# Check we haven't already restored params
if self._params is None:
logging.info('Initializing parameters.')
inputs = next(self._train_input)
init_net = jax.pmap(
lambda *a: self._transform.init(*a, is_training=True),
axis_name='i',
)
# Init uses the same RNG key on all hosts+devices to ensure everyone
# computes the same initial state.
init_rng = utils.bcast_local_devices(self.init_rng)
self._params, self._state = init_net(init_rng, inputs)
self._lr_schedule = exputils.get_lr_schedule(
total_steps,
self.config.optimizer,
)
self._optimizer = exputils.make_optimizer(
self.config.optimizer,
self._lr_schedule,
)
init_opt = jax.pmap(self._optimizer.init, axis_name='i')
if self._opt_state is None:
self._opt_state = init_opt(self._params)
def _build_train_input(
self,
) -> Iterable[Mapping[str, Mapping[str, np.ndarray]]]:
"""Builds the training input.
For each dataset specified in the config, this will call the appropriate
constructor for the dataset and then yield elements from each dataset.
Currently supported datasets are 'selfsup_kinetics_tracks' and 'kubric'.
Yields:
Elements of a joint dataset, where each item is a dict. The keys are
the dataset names, and the associated values are items generated by
those dataset classes.
"""
# Note: a dataset constructor is a function which takes only kwargs from
# the experiment config, and returns a dataset.
#
# A dataset consists of a generator function (calling next() on it will
# produce a data value)
dataset_constructors = {
'kubric': dataset.create_point_tracking_dataset,
}
dataset_generators = {}
for dset_name in self.config.datasets.dataset_names:
ds_generator = self.create_dataset_generator(
dataset_constructors,
dset_name,
color_augmentation=True,
)
dataset_generators[dset_name] = ds_generator
while True:
combined_dset = {}
for dset_name in self.config.datasets.dataset_names:
next_data = next(dataset_generators[dset_name])
combined_dset[dset_name] = next_data
yield combined_dset
def create_dataset_generator(
self,
dataset_constructors: Mapping[str, Callable[..., tf.data.Dataset]],
dset_name: str,
color_augmentation: bool = False,
) -> Iterator[Mapping[str, np.ndarray]]:
# Batch data on available devices.
# Number of devices is unknown when an interpreter reads a config file.
# Here we re-define batch dims to guide jax for right batching.
batch_dims = [
jax.local_device_count(),
self.config.datasets[dset_name + '_kwargs'].batch_dims,
]
dset_kwargs = dict(self.config.datasets[dset_name + '_kwargs'])
dset_kwargs['batch_dims'] = []
ds = dataset_constructors[dset_name](**dset_kwargs)
if color_augmentation:
ds = exputils.add_default_data_augmentation(ds)
for dim in batch_dims[::-1]:
ds = ds.batch(dim)
np_ds = tfds.as_numpy(ds)
return iter(np_ds)
def _update_func(
self,
params: chex.ArrayTree,
state: chex.ArrayTree,
opt_state: chex.ArrayTree,
inputs: chex.ArrayTree,
rng: chex.PRNGKey,
global_step: chex.Array,
) -> Tuple[chex.Array, chex.Array, chex.Array, Mapping[str, chex.Numeric]]:
"""Applies an update to parameters and returns new state."""
updates = None
grads, state, scalars = self.point_prediction.get_gradients(
params,
state,
inputs,
rng,
global_step,
self._transform.apply,
is_training=True,
)
scalars = {**scalars} # Mutable copy.
if grads is not None:
grads = jax.lax.psum(grads, axis_name='i')
task_updates, opt_state = self._optimizer.update(
grads,
opt_state,
params,
)
# We accumulate task_updates across tasks; if this is the first task
# processed, then updates is None and we just initialize with the
# updates from the first task.
if updates is None:
updates = task_updates
else:
updates = jax.tree_map(jnp.add, updates, task_updates)
scalars['gradient_norm'] = optax.global_norm(grads)
# Grab the learning rate to log before performing the step.
learning_rate = self._lr_schedule(global_step)
# Make the BYOL predictor train faster than everything else.
def multiply_lr(variable_name, variable_update):
need_fast_lr = False
for substr in self.config.fast_variables:
need_fast_lr = need_fast_lr or any([substr in x for x in variable_name])
if need_fast_lr:
logging.info('Boosting learning rate for: %s', '/'.join(variable_name))
return variable_update * 10.
return variable_update
mapping_type = type(updates)
def map_fn(nested_dict, prefix=None):
prefix = prefix or []
result = {}
for k, v in nested_dict.items():
if isinstance(v, mapping_type):
result[k] = map_fn(v, prefix + [k])
else:
result[k] = multiply_lr(prefix + [k], v)
return mapping_type(**result)
updates = map_fn(updates)
params = optax.apply_updates(params, updates)
n_params = 0
for k in params.keys(): # pytype: disable=attribute-error # numpy-scalars
for l in params[k]:
n_params = n_params + np.prod(params[k][l].shape) # pytype: disable=attribute-error # numpy-scalars
# Scalars to log (note: we log the mean across all hosts/devices).
scalars.update({
'learning_rate': learning_rate,
'n_params (M)': float(n_params / 1e6),
})
scalars = jax.lax.pmean(scalars, axis_name='i')
return params, state, opt_state, scalars
# _
# _____ ____ _| |
# / _ \ \ / / _` | |
# | __/\ V / (_| | |
# \___| \_/ \__,_|_|
#
def evaluate( # pytype: disable=signature-mismatch # numpy-scalars
self,
global_step: chex.Array,
rng: chex.PRNGKey,
mode: Optional[str] = None,
**unused_args,
) -> Dict[str, chex.Array]:
mode = mode or self.mode
point_prediction_task = self.point_prediction
forward_fn = self._transform.apply
eval_scalars = point_prediction_task.evaluate(
global_step=global_step,
params=self._params,
state=self._state,
rng=rng,
wrapped_forward_fn=forward_fn,
mode=mode,
)
return {
f'eval/{mode}/{key}': value for key, value in eval_scalars.items()
}
def main(_):
flags.mark_flag_as_required('config')
# Keep TF off the GPU; otherwise it hogs all the memory and leaves none for
# JAX.
tf.config.experimental.set_visible_devices([], 'GPU')
tf.config.experimental.set_visible_devices([], 'TPU')
platform.main(
Experiment,
sys.argv[1:],
checkpointer_factory=exputils.NumpyFileCheckpointer.create,
)
if __name__ == '__main__':
app.run(main)
| tapnet-main | experiment.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.
# ==============================================================================
"""Perceiver task module."""
import functools
from os import path
from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple
from absl import logging
import chex
import jax
import jax.numpy as jnp
from jaxline import utils
import matplotlib
import mediapy as media
from ml_collections import config_dict
import numpy as np
import optax
import tensorflow_datasets as tfds
import tensorflow as tf
from tapnet import evaluation_datasets
from tapnet import task
from tapnet.utils import model_utils
from tapnet.utils import transforms
from tapnet.utils import viz_utils
matplotlib.use('Agg')
class SupervisedPointPrediction(task.Task):
"""A task for predicting point tracks and training on ground-truth.
This task has a simple forward pass which predicts points, which is
also used for running evaluators on datasets where ground-truth is
known.
"""
def __init__(
self,
config: config_dict.ConfigDict,
input_key: str = 'kubric',
model_key: str = 'tapnet_model',
prediction_algo: str = 'cost_volume_regressor',
softmax_temperature: float = 20.0,
contrastive_loss_weight: float = 0.05,
position_loss_weight: float = 0.05,
expected_dist_thresh: float = 6.0,
train_chunk_size: int = 32,
eval_chunk_size: int = 16,
eval_inference_resolution=(256, 256),
eval_metrics_resolution=(256, 256),
):
"""Constructs a task for supervised learning on Kubric.
Args:
config: a ConfigDict for configuring this experiment, notably including
the paths for checkpoints and datasets.
input_key: The forward pass takes an input dict. Inference or learning
will be performed on inputs[input_key]['video']
model_key: The model to use from shared_modules
prediction_algo: specifies the network architecture to use to make
predictions. Can be 'cost_volume_regressor' for the algorithm presented
in the TAPNet paper, or 'cost_volume_cycle_consistency' for the VFS-Like
algorithm presented in the earlier Kubric paper.
softmax_temperature: temperature applied to cost volume before softmax.
This is only used with cost_volume_cycle_consistency.
contrastive_loss_weight: Weight for the additional contrastive loss that's
applied alongside the trajectory prediction loss.
position_loss_weight: Weight for position loss.
expected_dist_thresh: threshold for expected distance. Will be ignored if
the model does not return expected_dist.
train_chunk_size: Compute predictions on this many queries simultaneously.
This saves memory as the cost volumes can be very large.
eval_chunk_size: Compute predictions on this many queries simultaneously.
This saves memory as the cost volumes can be very large.
eval_inference_resolution: The video resolution during model inference in
(height, width). It can be different from the training resolution.
eval_metrics_resolution: The video resolution during evaluation metric
computation in (height, width). Point tracks will be re-scaled to this
resolution.
"""
super().__init__()
self.config = config
self.input_key = input_key
self.model_key = model_key
self.prediction_algo = prediction_algo
self.contrastive_loss_weight = contrastive_loss_weight
self.softmax_temperature = softmax_temperature
self.position_loss_weight = position_loss_weight
self.expected_dist_thresh = expected_dist_thresh
self.train_chunk_size = train_chunk_size
self.eval_chunk_size = eval_chunk_size
self.eval_inference_resolution = eval_inference_resolution
self.eval_metrics_resolution = eval_metrics_resolution
def forward_fn(
self,
inputs: chex.ArrayTree,
is_training: bool,
shared_modules: Optional[Mapping[str, task.SharedModule]] = None,
input_key: Optional[str] = None,
query_chunk_size: int = 32,
get_query_feats: bool = False,
) -> Mapping[str, chex.Array]:
"""Forward pass for predicting point tracks.
Args:
inputs: Input dict. Inference will be performed on will be performed on
inputs[input_key]['video'] (with fallback to the input_key specified in
the constructor). Input videos should be a standard video tensor
([batch, num_frames, height, width, 3]) normalize to [-1,1].
inputs[input_key]['query_points'] specifies the query point locations,
of shape [batch, num_queries, 3], where each query is [t,y,x]
coordinates in frame/raster coordinates.
is_training: Is the model in training mode.
shared_modules: Haiku modules, injected by experiment.py.
shared_modules['tapnet_model'] should be a JointModel.
input_key: Run on inputs[input_key]['video']. If None, use the input_key
from the constructor.
query_chunk_size: Compute predictions on this many queries simultaneously.
This saves memory as the cost volumes can be very large.
get_query_feats: If True, also return features for each query.
Returns:
Result dict produced by calling the joint model. See tapnet_model.py.
"""
if input_key is None:
input_key = self.input_key
frames = inputs[input_key]['video']
if self.prediction_algo in [
'cost_volume_regressor',
'cost_volume_cycle_consistency',
]:
return shared_modules[self.model_key](
frames,
is_training=is_training,
query_points=inputs[input_key]['query_points'],
query_chunk_size=query_chunk_size,
get_query_feats=get_query_feats,
)
else:
raise ValueError('Unsupported prediction_algo:' + self.prediction_algo)
def _loss_fn(
self,
params: chex.ArrayTree,
state: chex.ArrayTree,
inputs: chex.ArrayTree,
rng: chex.PRNGKey,
wrapped_forward_fn: task.WrappedForwardFn,
is_training: bool = True,
input_key: Optional[str] = None,
):
"""Loss function, used for training, depending on the algorithm.
This includes the Huber and softmax cross entropy losses for cost volume
regression, plus the contrastive loss for cost volume regression and
the baseline cost volume cycle consistency.
Args:
params: hk.Params with the model parameters
state: hk.State with the model state
inputs: Input dict. Inference will be performed on will be performed on
inputs[input_key]['video'] (with fallback to the input_key specified in
the constructor). Input videos should be a standard video tensor
([batch, num_frames, height, width, 3]) normalize to [-1,1].
inputs[input_key]['query_points'] specifies the query point locations,
of shape [batch, num_queries, 3], where each query is [t,y,x]
coordinates in frame/raster coordinates.
inputs[input_key]['target_points'] is the ground-truth locations on each
frame, of shape [batch, num_queries, num_frames, 2], where each point is
[x,y] raster coordinates (in the range [0,width]/[0,height]).
inputs[input_key]['occluded'] is the ground-truth occlusion flag, a
boolean of shape [batch, num_queries, num_frames], where True indicates
occluded.
rng: jax.random.PRNGKey for random number generation.
wrapped_forward_fn: A wrapper around self.forward which can inject Haiku
parameters.
is_training: Is the model in training mode.
input_key: Run on inputs[input_key]['video']. If None, use the input_key
from the constructor.
Returns:
A 2-tuple consisting of the summed loss, and a 2-tuple containing scalar
outputs and the updated state. The loss scalars are broken down into
the position loss, occlusion loss, and contrastive loss.
"""
if input_key is None:
input_key = self.input_key
output, state = functools.partial(
wrapped_forward_fn,
input_key=input_key,
query_chunk_size=self.train_chunk_size,
)(params, state, rng, inputs, is_training=is_training)
def tapnet_loss(
points, occlusion, target_points, target_occ, shape, expected_dist=None
):
# Huber loss is by default measured under 256x256 resolution
points = transforms.convert_grid_coordinates(
points, shape[3:1:-1], (256, 256), coordinate_format='xy'
)
target_points = transforms.convert_grid_coordinates(
target_points, shape[3:1:-1], (256, 256), coordinate_format='xy'
)
loss_huber = model_utils.huber_loss(points, target_points, target_occ)
loss_huber = jnp.mean(loss_huber) * self.position_loss_weight
if expected_dist is None:
loss_prob = 0.0
else:
loss_prob = model_utils.prob_loss(
jax.lax.stop_gradient(points),
expected_dist,
target_points,
target_occ,
self.expected_dist_thresh,
)
loss_prob = jnp.mean(loss_prob)
target_occ = target_occ.astype(occlusion.dtype) # pytype: disable=attribute-error
loss_occ = optax.sigmoid_binary_cross_entropy(occlusion, target_occ)
loss_occ = jnp.mean(loss_occ)
return loss_huber, loss_occ, loss_prob
loss_scalars = {}
loss = 0.0
if self.prediction_algo in ['cost_volume_regressor']:
loss_huber, loss_occ, loss_prob = tapnet_loss(
output['tracks'],
output['occlusion'],
inputs[input_key]['target_points'],
inputs[input_key]['occluded'],
inputs[input_key]['video'].shape, # pytype: disable=attribute-error # numpy-scalars
output['expected_dist'] if 'expected_dist' in output else None,
)
loss = loss_huber + loss_occ + loss_prob
loss_scalars['position_loss'] = loss_huber
loss_scalars['occlusion_loss'] = loss_occ
if 'expected_dist' in output:
loss_scalars['prob_loss'] = loss_prob
if 'unrefined_tracks' in output:
for l in range(len(output['unrefined_tracks'])):
loss_huber, loss_occ, loss_prob = tapnet_loss(
output['unrefined_tracks'][l],
output['unrefined_occlusion'][l],
inputs[input_key]['target_points'],
inputs[input_key]['occluded'],
inputs[input_key]['video'].shape, # pytype: disable=attribute-error # numpy-scalars
output['unrefined_expected_dist'][l]
if 'unrefined_expected_dist' in output
else None,
)
loss += loss_huber + loss_occ + loss_prob
loss_scalars[f'position_loss_{l}'] = loss_huber
loss_scalars[f'occlusion_loss_{l}'] = loss_occ
if 'unrefined_expected_dist' in output:
loss_scalars[f'prob_loss_{l}'] = loss_prob
if self.prediction_algo in ['cost_volume_cycle_consistency']:
feature_grid = output['feature_grid']
query_feats = output['query_feats']
loss_contrast = []
# This computes the contrastive loss from the paper. We break the set of
# queries up into chunks in order to save memory.
for qchunk in range(0, query_feats.shape[1], self.train_chunk_size):
qchunk_low = qchunk
qchunk_high = qchunk + self.train_chunk_size
all_pairs_dots = jnp.einsum(
'bnc,bthwc->bnthw',
query_feats[:, qchunk_low:qchunk_high],
feature_grid,
)
all_pairs_softmax = jax.nn.log_softmax(
all_pairs_dots * self.softmax_temperature, axis=(2, 3, 4)
)
im_shp = inputs[input_key]['video'].shape # pytype: disable=attribute-error # numpy-scalars
target_points = inputs[input_key]['target_points']
position_in_grid2 = transforms.convert_grid_coordinates(
target_points[:, qchunk_low:qchunk_high],
im_shp[3:1:-1],
feature_grid.shape[3:1:-1],
)
# result is shape [batch, num_queries, time]
# Interp handles a single 2D slice. We need to vmap it across all
# batch, queries, and time to extract the softmax value associated with
# the entire trajectory.
#
# Note: grid positions are in [x, y] format, but interp needs
# coordinates in [y, x] format.
interp_softmax = jax.vmap(jax.vmap(jax.vmap(model_utils.interp)))(
all_pairs_softmax,
position_in_grid2[..., ::-1],
)
target_occ = inputs[input_key]['occluded']
target_occ = target_occ[:, qchunk_low:qchunk_high]
loss_contrast.append(
jnp.mean(interp_softmax * (1.0 - target_occ), axis=-1)
)
loss_contrast = -jnp.mean(jnp.concatenate(loss_contrast, 1))
loss += loss_contrast * self.contrastive_loss_weight
loss_scalars['loss_contrast'] = loss_contrast
loss_scalars['loss'] = loss
scaled_loss = loss / jax.device_count()
return scaled_loss, (loss_scalars, state)
def get_gradients(
self,
params: chex.ArrayTree,
state: chex.ArrayTree,
inputs: chex.ArrayTree,
rng: chex.PRNGKey,
global_step: chex.Array,
wrapped_forward_fn: task.WrappedForwardFn,
is_training: bool = True,
) -> Tuple[chex.ArrayTree, chex.ArrayTree, Mapping[str, chex.Array]]:
"""Gets the gradients for the loss function. See _loss_fn."""
# This function computes the gradient of the first output of loss_fn and
# passes through the other arguments unchanged.
grad_loss_fn = jax.grad(self._loss_fn, has_aux=True)
scaled_grads, (loss_scalars, state) = grad_loss_fn(
params,
state,
inputs,
rng,
wrapped_forward_fn,
is_training=is_training,
)
grads = jax.lax.psum(scaled_grads, axis_name='i')
scalars = {}
scalars.update(loss_scalars)
scalars = jax.lax.pmean(scalars, axis_name='i')
return grads, state, scalars
def evaluate(
self,
global_step: chex.Array,
params: chex.ArrayTree,
state: chex.ArrayTree,
rng: chex.PRNGKey,
wrapped_forward_fn: task.WrappedForwardFn,
mode: str,
) -> Mapping[str, chex.Array]:
"""Run an evaluation epoch. See base class."""
global_step = np.array(utils.get_first(global_step))
if mode == 'eval_inference':
scalars = jax.device_get(
self._eval_inference(
global_step,
utils.get_first(state),
utils.get_first(params),
utils.get_first(rng),
wrapped_forward_fn,
)
)
else:
scalars = jax.device_get(
self._eval_epoch(
global_step,
utils.get_first(state),
utils.get_first(params),
utils.get_first(rng),
wrapped_forward_fn,
mode,
)
)
logging.info('[Step %d] Eval scalars: %s', global_step, scalars)
return scalars
def _infer_batch(
self,
params: chex.ArrayTree,
state: chex.ArrayTree,
inputs: chex.ArrayTree,
rng: chex.PRNGKey,
wrapped_forward_fn: task.WrappedForwardFn,
input_key: Optional[str] = None,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""Runs inference on a single batch and compute metrics.
For cost_volume_regressor we return the outputs directly inferred from the
model. For cost_volume_cycle_consistency, we compute the tracks by
computing the soft argmax operation (which tapnet_model.py doesn't compute)
and then use cycle-consistency to infer occlusion.
Args:
params: hk.Params with the model parameters
state: hk.State with the model state
inputs: Input dict. Inference will be performed on will be performed on
inputs[input_key]['video'] (with fallback to the input_key specified in
the constructor). Input videos should be a standard video tensor
([batch, num_frames, height, width, 3]) normalize to [-1,1].
inputs[input_key]['query_points'] specifies the query point locations,
of shape [batch, num_queries, 3], where each query is [t,y,x]
coordinates in frame/raster coordinates.
inputs[input_key]['target_points'] is the ground-truth locations on each
frame, of shape [batch, num_queries, num_frames, 2], where each point is
[x,y] raster coordinates (in the range [0,width]/[0,height]).
inputs[input_key]['occluded'] is the ground-truth occlusion flag, a
boolean of shape [batch, num_queries, num_frames], where True indicates
occluded.
rng: jax.random.PRNGKey for random number generation.
wrapped_forward_fn: A wrapper around self.forward_fn which can inject
Haiku parameters. It expects the same inputs as self.forward, plus
Haiku parameters, state, and a jax.random.PRNGKey. It's the result of
applying hk.transform to self.forward_fn.
input_key: Run on inputs[input_key]['video']. If None, use the input_key
from the constructor.
Returns:
A 2-tuple consisting of the occlusion logits, of shape
[batch, num_queries, num_frames], the predicted position, of shape
[batch, num_queries, num_frames, 2], and a dict of loss scalars.
"""
# Features for each query point are required when using cycle consistency.
get_query_feats = self.prediction_algo in ['cost_volume_cycle_consistency']
output, _ = functools.partial(wrapped_forward_fn, input_key=input_key)(
params,
state,
rng,
inputs,
is_training=False,
query_chunk_size=self.eval_chunk_size,
get_query_feats=get_query_feats,
)
loss_scalars = {}
if self.prediction_algo in ['cost_volume_regressor']:
# Outputs are already in the correct format for cost_volume_regressor.
tracks = output['tracks']
loss_occ = optax.sigmoid_binary_cross_entropy(
output['occlusion'], inputs[input_key]['occluded']
)
loss_occ = jnp.mean(loss_occ, axis=(1, 2))
occlusion = output['occlusion']
loss_scalars['loss_occ'] = loss_occ
else:
# compute forward-backward cycle consistency to infer occlusions.
feature_grid = output['feature_grid']
query_feats = output['query_feats']
all_tracks = []
all_occlusion = []
# We again chunk the queries to save memory; these einsums are big.
for qchunk in range(0, query_feats.shape[1], self.eval_chunk_size):
# Compute pairwise dot products between queries and all other features
all_pairs_dots = jnp.einsum(
'bnc,bthwc->bnthw',
query_feats[:, qchunk : qchunk + self.eval_chunk_size],
feature_grid,
)
# Compute the soft argmax for each frame
query_point_chunk = inputs[input_key]['query_points'][
:, qchunk : qchunk + self.eval_chunk_size
]
im_shp = inputs[input_key]['video'].shape # pytype: disable=attribute-error # numpy-scalars
tracks = model_utils.heatmaps_to_points(
jax.nn.softmax(
all_pairs_dots * self.softmax_temperature, axis=(-1, -2)
),
im_shp,
query_points=query_point_chunk,
)
# Extract the argmax feature from each frame for each query using
# bilinear interpolation.
frame_id = jnp.broadcast_to(
jnp.arange(tracks.shape[-2])[..., jnp.newaxis],
tracks[..., :1].shape,
)
position_in_grid = jnp.concatenate(
[frame_id, tracks[..., ::-1]], axis=-1
)
position_in_grid = transforms.convert_grid_coordinates(
position_in_grid,
im_shp[1:4],
feature_grid.shape[1:4],
coordinate_format='tyx',
)
# vmap over channels, duplicating the coordinates
vmap_interp = jax.vmap(
model_utils.interp, in_axes=(3, None), out_axes=1
)
# vmap over frames, using the same queries for each frame
vmap_interp = jax.vmap(vmap_interp, in_axes=(None, 0), out_axes=0)
# vmap over the batch
vmap_interp = jax.vmap(vmap_interp)
# interp_features is [batch_size,num_queries,num_frames,channels]
interp_features = vmap_interp(feature_grid, position_in_grid)
# For each query point, extract the features for the frame which
# contains the query.
# query_frame is [batch_size, num_queries]
query_frame = transforms.convert_grid_coordinates(
inputs[input_key]['query_points'][
:, qchunk : qchunk + self.eval_chunk_size, ...
],
im_shp[1:4],
feature_grid.shape[1:4],
coordinate_format='tyx',
)[..., 0]
query_frame = jnp.array(jnp.round(query_frame), jnp.int32)
# target_features is [batch_size, chunk, height, width, num_channels]
target_features = jnp.take_along_axis(
feature_grid,
query_frame[:, :, np.newaxis, np.newaxis, np.newaxis],
axis=1,
)
# For each output point along the track, compare the features with all
# features in the frame that the query came from
all_pairs_dots = jnp.einsum(
'bntc,bnhwc->bnthw', interp_features, target_features
)
# Again, take the soft argmax to see if we come back to the place we
# started from.
# inverse_tracks is [batch_size, chunk, num_frames, 2]
inverse_tracks = model_utils.heatmaps_to_points(
jax.nn.softmax(
all_pairs_dots * self.softmax_temperature,
axis=(-2, -1),
),
im_shp,
)
query_points = inputs[input_key]['query_points']
query_points = query_points[:, qchunk : qchunk + self.eval_chunk_size]
dist = jnp.square(inverse_tracks - query_points[jnp.newaxis, 2:0:-1])
dist = jnp.sum(dist, axis=-1)
occlusion = dist > jnp.square(48.0)
# We need to return logits, but the cycle consistency rule is binary.
# So we just convert the binary values into large real values.
occlusion = occlusion * 20.0 - 10.0
all_occlusion.append(occlusion)
all_tracks.append(tracks)
tracks = jnp.concatenate(all_tracks, axis=1)
occlusion = jnp.concatenate(all_occlusion, axis=1)
outputs = {'tracks': tracks, 'occlusion': occlusion}
if 'expected_dist' in output:
outputs['expected_dist'] = output['expected_dist']
return outputs, loss_scalars
def _eval_batch(
self,
params: chex.Array,
state: chex.Array,
inputs: chex.Array,
rng: chex.PRNGKey,
wrapped_forward_fn: task.WrappedForwardFn,
mode: str = '',
input_key: Optional[str] = None,
) -> Tuple[Mapping[str, chex.Array], Mapping[str, chex.Array]]:
"""Evaluates the model on a single batch and compute metrics.
Args:
params: hk.Params with the model parameters
state: hk.State with the model state
inputs: Input dict. Inference will be performed on will be performed on
inputs[input_key]['video'] (with fallback to the input_key specified in
the constructor). Input videos should be a standard video tensor
([batch, num_frames, height, width, 3]) normalize to [-1,1].
inputs[input_key]['query_points'] specifies the query point locations,
of shape [batch, num_queries, 3], where each query is [t,y,x]
coordinates in frame/raster coordinates.
inputs[input_key]['target_points'] is the ground-truth locations on each
frame, of shape [batch, num_queries, num_frames, 2], where each point is
[x,y] raster coordinates (in the range [0,width]/[0,height]).
inputs[input_key]['occluded'] is the ground-truth occlusion flag, a
boolean of shape [batch, num_queries, num_frames], where True indicates
occluded.
rng: jax.random.PRNGKey for random number generation.
wrapped_forward_fn: A wrapper around self.forward_fn which can inject
Haiku parameters. It expects the same inputs as self.forward, plus
Haiku parameters, state, and a jax.random.PRNGKey. It's the result of
applying hk.transform to self.forward_fn.
mode: Which evaluation we're running. For most it will compute standard
occlusion accuracy, points within thresholds, and jaccard metrics. For
eval_jhmdb, however, we will compute standard PCK.
input_key: Run on inputs[input_key]['video']. If None, use the input_key
from the constructor.
Returns:
A 2-tuple consisting of a dict of loss scalars and a dict of outputs.
The latter consists of the occlusion logits, of shape
[batch, num_queries, num_frames] and the predicted position, of shape
[batch, num_queries, num_frames, 2].
"""
outputs, loss_scalars = self._infer_batch(
params, state, inputs, rng, wrapped_forward_fn, input_key
)
loss_scalars = {**loss_scalars} # Mutable copy.
gt_occluded = inputs[input_key]['occluded']
gt_target_points = inputs[input_key]['target_points']
query_points = inputs[input_key]['query_points']
tracks = outputs['tracks']
# Huber loss is by default measured under 256x256 resolution
shape = inputs[input_key]['video'].shape
target_points = transforms.convert_grid_coordinates(
gt_target_points, shape[3:1:-1], (256, 256), coordinate_format='xy'
)
points = transforms.convert_grid_coordinates(
tracks, shape[3:1:-1], (256, 256), coordinate_format='xy'
)
loss_huber = model_utils.huber_loss(points, target_points, gt_occluded)
loss_scalars['position_loss'] = loss_huber
occlusion_logits = outputs['occlusion']
pred_occ = jax.nn.sigmoid(occlusion_logits)
if 'expected_dist' in outputs:
expected_dist = outputs['expected_dist']
pred_occ = 1 - (1 - pred_occ) * (1 - jax.nn.sigmoid(expected_dist))
pred_occ = pred_occ > 0.5 # threshold
if self.eval_inference_resolution != self.eval_metrics_resolution:
# Resize prediction and groundtruth to standard evaluation resolution
query_points = transforms.convert_grid_coordinates(
query_points,
(1,) + inputs[input_key]['video'].shape[2:4], # (1, height, width)
(1,) + self.eval_metrics_resolution, # (1, height, width)
coordinate_format='tyx',
)
gt_target_points = transforms.convert_grid_coordinates(
gt_target_points,
inputs[input_key]['video'].shape[3:1:-1], # (width, height)
self.eval_metrics_resolution[::-1], # (width, height)
coordinate_format='xy',
)
tracks = transforms.convert_grid_coordinates(
tracks,
inputs[input_key]['video'].shape[3:1:-1], # (width, height)
self.eval_metrics_resolution[::-1], # (width, height)
coordinate_format='xy',
)
query_mode = 'first' if 'q_first' in mode else 'strided'
metrics = evaluation_datasets.compute_tapvid_metrics(
query_points=query_points,
gt_occluded=gt_occluded,
gt_tracks=gt_target_points,
pred_occluded=pred_occ,
pred_tracks=tracks,
query_mode=query_mode,
)
loss_scalars.update(metrics)
return loss_scalars, {'tracks': tracks, 'occlusion': occlusion_logits}
def _build_eval_input(
self,
mode: str,
) -> Iterable[evaluation_datasets.DatasetElement]:
"""Build evalutation data reader generator.
Args:
mode: evaluation mode. Can be one of 'eval_davis_points',
'eval_robotics_points', 'eval_kinetics_points',
'eval_davis_points_q_first', 'eval_robotics_points_q_first',
'eval_kinetics_points_q_first', 'eval_jhmdb', 'eval_kubric',
Yields:
A dict with one key (for the dataset), containing a dict with the keys:
video: Video tensor of shape [1, num_frames, height, width, 3]
query_points: Query points of shape [1, n_queries, 3] where
each point is [t, y, x] in pixel/raster coordinates
target_points: Target points of shape [1, n_queries, n_frames, 2] where
each point is [x, y] raster coordinates (in the range
[0,width]/[0,height])
trackgroup (optional): Index of the original track that each query
point was sampled from. This is useful for visualization.
pad_extra_frames (optional): the number of pad frames that were added
to reach num_frames.
"""
query_mode = 'first' if 'q_first' in mode else 'strided'
if 'eval_kubric_train' in mode:
yield from evaluation_datasets.create_kubric_eval_train_dataset(
mode, train_size=self.config.datasets.kubric_kwargs.train_size
)
elif 'eval_kubric' in mode:
yield from evaluation_datasets.create_kubric_eval_dataset(
mode, train_size=self.config.datasets.kubric_kwargs.train_size
)
elif 'eval_davis_points' in mode:
yield from evaluation_datasets.create_davis_dataset(
self.config.davis_points_path,
query_mode=query_mode,
resolution=self.eval_inference_resolution,
)
elif 'eval_jhmdb' in mode:
yield from evaluation_datasets.create_jhmdb_dataset(
self.config.jhmdb_path, resolution=self.eval_inference_resolution
)
elif 'eval_robotics_points' in mode:
yield from evaluation_datasets.create_rgb_stacking_dataset(
self.config.robotics_points_path,
query_mode=query_mode,
resolution=self.eval_inference_resolution,
)
elif 'eval_kinetics_points' in mode:
yield from evaluation_datasets.create_kinetics_dataset(
self.config.kinetics_points_path,
query_mode=query_mode,
resolution=self.eval_inference_resolution,
)
elif 'eval_robotap' in mode:
yield from evaluation_datasets.create_csv_dataset(
dataset_name='robotap',
csv_path=self.config.robotap_csv_path,
video_base_path=self.config.robotap_video_path,
query_mode=query_mode,
resolution=self.eval_inference_resolution,
)
elif 'eval_perception_test' in mode:
yield from evaluation_datasets.create_csv_dataset(
dataset_name='perception_test',
csv_path=self.config.perception_test_csv_path,
video_base_path=self.config.perception_test_video_path,
query_mode=query_mode,
resolution=self.eval_inference_resolution,
)
else:
raise ValueError(f'Unrecognized eval mode {mode}')
def compute_pck(
self,
dist_all: Sequence[np.ndarray],
dist_thresh: float,
) -> Sequence[float]:
pck_all = np.zeros((len(dist_all),))
for pidx in range(len(dist_all)):
idxs = np.argwhere(dist_all[pidx] <= dist_thresh)
pck = 100.0 * len(idxs) / max(1e-12, len(dist_all[pidx]))
pck_all[pidx] = pck
return pck_all
def pck_evaluate(
self,
results: Sequence[Mapping[str, np.ndarray]],
) -> Mapping[str, np.ndarray]:
num_keypoints = 15
dist_all = [np.zeros((0, 0)) for _ in range(num_keypoints)]
for vid_idx in range(len(results)):
sample = results[vid_idx]
# [2, 15, clip_len]
pred_poses = np.transpose(sample['pred_pose'][0], (2, 0, 1))
gt_poses = sample['gt_pose_orig'][0]
width = sample['im_size'][1]
height = sample['im_size'][0]
# input is shape [15, clip_len, 2]
invalid_x = np.logical_or(
gt_poses[:, 0:1, 0] < 0, gt_poses[:, 0:1, 0] >= width
)
invalid_y = np.logical_or(
gt_poses[:, 0:1, 1] < 0, gt_poses[:, 0:1, 1] >= height
)
invalid = np.logical_or(invalid_x, invalid_y)
joint_visible = np.logical_not(np.tile(invalid, [1, gt_poses.shape[1]]))
gt_poses = np.transpose(gt_poses, (2, 0, 1))
clip_len = pred_poses.shape[-1]
assert (
pred_poses.shape == gt_poses.shape
), f'{pred_poses.shape} vs {gt_poses.shape}'
# [15, clip_len]
valid_max_gt_poses = gt_poses.copy()
valid_max_gt_poses[:, ~joint_visible] = -1
valid_min_gt_poses = gt_poses.copy()
valid_min_gt_poses[:, ~joint_visible] = 1e6
boxes = np.stack(
(
valid_max_gt_poses[0].max(axis=0)
- valid_min_gt_poses[0].min(axis=0),
valid_max_gt_poses[1].max(axis=0)
- valid_min_gt_poses[1].min(axis=0),
),
axis=0,
)
# [clip_len]
boxes = 0.6 * np.linalg.norm(boxes, axis=0)
for img_idx in range(clip_len):
for t in range(num_keypoints):
if not joint_visible[t, img_idx]:
continue
predx = pred_poses[0, t, img_idx]
predy = pred_poses[1, t, img_idx]
gtx = gt_poses[0, t, img_idx]
gty = gt_poses[1, t, img_idx]
dist = np.linalg.norm(np.subtract([predx, predy], [gtx, gty]))
dist = dist / boxes[img_idx]
dist_all[t] = np.append(dist_all[t], [[dist]])
pck_ranges = (0.1, 0.2, 0.3, 0.4, 0.5)
pck_all = []
for pck_range in pck_ranges:
pck_all.append(self.compute_pck(dist_all, pck_range))
eval_results = {}
for alpha, pck in zip(pck_ranges, pck_all):
eval_results[f'PCK@{alpha}'] = np.mean(pck)
return eval_results
def _eval_jhmdb(
self,
pred_pose: chex.Array,
gt_pose: chex.Array,
gt_pose_orig: chex.Array,
im_size: chex.Array,
fname: str,
is_first: bool = False,
) -> Mapping[str, np.ndarray]:
if is_first:
self.all_results = []
self.all_results.append({
'pred_pose': np.array(pred_pose),
'gt_pose': np.array(gt_pose),
'gt_pose_orig': np.array(gt_pose_orig),
'im_size': np.array(im_size),
})
return self.pck_evaluate(self.all_results)
def _eval_epoch(
self,
global_step: chex.Array,
state: chex.ArrayTree,
params: chex.ArrayTree,
rng: chex.PRNGKey,
wrapped_forward_fn: task.WrappedForwardFn,
mode: str,
) -> Mapping[str, chex.Array]:
"""Evaluates an epoch."""
num_samples = 0.0
summed_scalars = None
batch_id = 0
outdir = path.join(self.config.checkpoint_dir, mode, str(global_step))
logging.info('Saving videos to %s', outdir)
try:
tf.io.gfile.makedirs(outdir)
except FileExistsError:
print(f'Path {outdir} exists. Skip creating a new dir.')
if 'eval_kinetics' in mode:
input_key = 'kinetics'
elif 'eval_davis_points' in mode:
input_key = 'davis'
elif 'eval_jhmdb' in mode:
input_key = 'jhmdb'
elif 'eval_robotics_points' in mode:
input_key = 'robotics'
elif 'eval_robotap' in mode:
input_key = 'robotap'
elif 'eval_perception_test' in mode:
input_key = 'perception_test'
else:
input_key = 'kubric'
eval_batch_fn = functools.partial(
self._eval_batch,
wrapped_forward_fn=wrapped_forward_fn,
mode=mode,
input_key=input_key,
)
for inputs in self._build_eval_input(mode):
batch_size = inputs[input_key]['video'].shape[0] # pytype: disable=attribute-error # 'video' entry is array-valued
num_samples += batch_size
scalars, viz = eval_batch_fn(params, state, inputs, rng)
write_viz = batch_id < 0
if 'eval_davis_points' in mode or 'eval_robotics_points' in mode:
# Only write videos sometimes for the small datasets; otherwise
# there will be a crazy number of videos dumped.
write_viz = write_viz and (global_step % 10 == 0)
if 'eval_jhmdb' in mode:
pix_pts = viz['tracks']
grid_size = np.array(
[inputs[input_key]['im_size'][1], inputs[input_key]['im_size'][0]]
)
pix_pts = transforms.convert_grid_coordinates(
pix_pts,
(
self.eval_inference_resolution[1],
self.eval_inference_resolution[0],
),
grid_size,
)
mean_scalars = self._eval_jhmdb(
pix_pts,
inputs[input_key]['gt_pose'],
inputs[input_key]['gt_pose_orig'],
inputs[input_key]['im_size'],
inputs[input_key]['fname'],
is_first=batch_id == 0,
)
scalars = {}
if write_viz:
pix_pts = viz['tracks']
targ_pts = None
if 'eval_kinetics' in mode:
targ_pts = inputs[input_key]['target_points']
outname = [
f'{outdir}/{x}.mp4'
for x in range(batch_size * batch_id, batch_size * (batch_id + 1))
]
viz_utils.write_visualization(
(inputs[input_key]['video'] + 1.0) * (255.0 / 2.0),
pix_pts,
jax.nn.sigmoid(viz['occlusion']),
outname,
gt_points=targ_pts,
gt_occluded=inputs[input_key]['occluded'],
trackgroup=inputs[input_key]['trackgroup']
if 'trackgroup' in inputs[input_key]
else None,
)
del viz
batch_id += 1
logging.info('eval batch: %d', batch_id)
# Accumulate the sum of scalars for each step.
scalars = jax.tree_map(lambda x: jnp.sum(x, axis=0), scalars)
if summed_scalars is None:
summed_scalars = scalars
else:
summed_scalars = jax.tree_map(jnp.add, summed_scalars, scalars)
if 'eval_jhmdb' not in mode:
mean_scalars = jax.tree_map(lambda x: x / num_samples, summed_scalars)
logging.info(mean_scalars)
logging.info(evaluation_datasets.latex_table(mean_scalars))
return mean_scalars
def _eval_inference(
self,
global_step: chex.Array,
state: chex.ArrayTree,
params: chex.ArrayTree,
rng: chex.PRNGKey,
wrapped_forward_fn: task.WrappedForwardFn,
) -> Mapping[str, chex.Array]:
"""Inferences a single video."""
def _sample_random_points(frame_max_idx, height, width, num_points):
"""Sample random points with (time, height, width) order."""
y = np.random.randint(0, height, (num_points, 1))
x = np.random.randint(0, width, (num_points, 1))
t = np.random.randint(0, frame_max_idx + 1, (num_points, 1))
points = np.concatenate((t, y, x), axis=-1).astype(np.int32)
return points
config = self.config.inference
input_video_path = config.input_video_path
output_video_path = config.output_video_path
resize_height, resize_width = config.resize_height, config.resize_width
num_points = config.num_points
logging.info('load video from %s', input_video_path)
video = media.read_video(input_video_path)
num_frames, fps = video.metadata.num_images, video.metadata.fps
logging.info('resize video to (%s, %s)', resize_height, resize_width)
video = media.resize_video(video, (resize_height, resize_width))
video = video.astype(np.float32) / 255 * 2 - 1
query_points = _sample_random_points(
num_frames, resize_height, resize_width, num_points
)
occluded = np.zeros((num_points, num_frames), dtype=np.float32)
inputs = {
self.input_key: {
'video': video[np.newaxis],
'query_points': query_points[np.newaxis],
'occluded': occluded[np.newaxis],
}
}
outputs, _ = self._infer_batch(
params,
state,
inputs,
rng,
wrapped_forward_fn,
self.input_key,
)
occluded = outputs['occlusion'] > 0
video = (video + 1) * 255 / 2
video = video.astype(np.uint8)
painted_frames = viz_utils.paint_point_track(
video,
outputs['tracks'][0],
~occluded[0],
)
media.write_video(output_video_path, painted_frames, fps=fps)
logging.info('Inference result saved to %s', output_video_path)
return {'': 0} # pytype: disable=bad-return-type # numpy-scalars
| tapnet-main | supervised_point_prediction.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.
# ==============================================================================
"""TAPIR model definition."""
import functools
from typing import Any, Dict, List, Mapping, NamedTuple, Optional, Sequence, Tuple
import chex
from einshape import jax_einshape as einshape
import haiku as hk
import jax
import jax.numpy as jnp
from tapnet.models import resnet
from tapnet.utils import model_utils
from tapnet.utils import transforms
def layernorm(x):
return hk.LayerNorm(axis=-1, create_scale=True, create_offset=False)(x)
def depthwise_conv_residual(
x: chex.Array,
kernel_shape: int = 3,
use_causal_conv: bool = False,
causal_context: Optional[Mapping[str, chex.Array]] = None,
get_causal_context: bool = False,
) -> Tuple[chex.Array, Dict[str, chex.Array]]:
"""First mlp in mixer."""
cur_name = hk.experimental.current_name()
name1 = cur_name + '_causal_1'
if causal_context is not None:
x = jnp.concatenate([causal_context[name1], x], axis=-2)
# Because we're adding extra frames, the output of this convolution will
# also have extra (invalid) frames that need to be removed afterward.
num_extra = causal_context[name1].shape[-2]
new_causal_context = {}
if get_causal_context:
# Keep only as many frames of x as needed for future frames. This may be up
# to (kernel_shape - 1) frames.
new_causal_context[name1] = x[..., -(kernel_shape - 1) :, :]
x = hk.DepthwiseConv1D(
channel_multiplier=4,
kernel_shape=kernel_shape,
data_format='NWC',
stride=1,
padding=[(kernel_shape - 1, 0)] if use_causal_conv else 'SAME',
name='mlp1_up',
)(x)
x = jax.nn.gelu(x)
name2 = cur_name + '_causal_2'
if causal_context is not None:
x = jnp.concatenate([causal_context[name2], x[..., num_extra:, :]], axis=-2)
num_extra = causal_context[name2].shape[-2]
if get_causal_context:
new_causal_context[name2] = x[..., -(kernel_shape - 1) :, :]
x = hk.DepthwiseConv1D(
channel_multiplier=1,
kernel_shape=kernel_shape,
data_format='NWC',
stride=1,
padding=[(kernel_shape - 1, 0)] if use_causal_conv else 'SAME',
name='mlp1_up',
)(x)
if causal_context is not None:
x = x[..., num_extra:, :]
return (
x[..., 0::4] + x[..., 1::4] + x[..., 2::4] + x[..., 3::4],
new_causal_context,
)
def conv_channels_mixer(x):
"""Second mlp in mixer."""
in_channels = x.shape[-1]
x = hk.Linear(in_channels * 4, name='mlp2_up')(x)
x = jax.nn.gelu(x)
x = hk.Linear(in_channels, name='mlp2_down')(x)
return x
class PIPsConvBlock(hk.Module):
"""Transformer block (mha and ffw)."""
def __init__(self, name='block', kernel_shape=3, use_causal_conv=False):
super().__init__(name=name)
self.kernel_shape = kernel_shape
self.use_causal_conv = use_causal_conv
def __call__(self, x, causal_context=None, get_causal_context=False):
to_skip = x
x = layernorm(x)
x, new_causal_context = depthwise_conv_residual(
x,
self.kernel_shape,
self.use_causal_conv,
causal_context,
get_causal_context,
)
x = x + to_skip
to_skip = x
x = layernorm(x)
x = conv_channels_mixer(x)
x = x + to_skip
return x, new_causal_context
class PIPSMLPMixer(hk.Module):
"""Depthwise-conv version of PIPs's MLP Mixer."""
def __init__(
self,
output_channels,
hidden_dim=512,
num_blocks=12,
kernel_shape=3,
use_causal_conv=False,
name='pips_mlp_mixer',
):
super().__init__(name=name)
self._output_channels = output_channels
self.hidden_dim = hidden_dim
self._num_blocks = num_blocks
self.kernel_shape = kernel_shape
self.use_causal_conv = use_causal_conv
def __call__(self, x, causal_context=None, get_causal_context=False):
x = hk.Linear(self.hidden_dim)(x)
all_causal_context = {}
for _ in range(self._num_blocks):
x, new_causal_context = PIPsConvBlock(
kernel_shape=self.kernel_shape, use_causal_conv=self.use_causal_conv
)(x, causal_context, get_causal_context)
if get_causal_context:
all_causal_context.update(new_causal_context)
x = layernorm(x)
return hk.Linear(self._output_channels)(x), all_causal_context
def construct_patch_kernel(pos, grid_size, patch_size=7):
"""A conv kernel that performs bilinear interpolation for a point."""
# pos is n-by-2, [y,x]
# grid_size is [heigh,width]
# result is [1,n,kernel_height,kernel_width]
pos = pos + (patch_size) / 2 - 1
def gen_bump(pos, num):
# pos is shape [n]
# result is shape [n,num]
res = jnp.arange(num)
return jnp.maximum(
0, 1 - jnp.abs(res[jnp.newaxis, :] - pos[:, jnp.newaxis])
)
x_bump = gen_bump(pos[:, 1], grid_size[1] - patch_size + 1)
y_bump = gen_bump(pos[:, 0], grid_size[0] - patch_size + 1)
kernel = (
x_bump[:, jnp.newaxis, jnp.newaxis, :]
* y_bump[:, jnp.newaxis, :, jnp.newaxis]
)
return kernel
def extract_patch_depthwise_conv(pos, corrs, patch_size=7):
"""Use a depthwise conv to extract a patch via bilinear interpolation."""
# pos is n-by-2, [y,x], raster coordinates
# arr is [num_points, height, width]
# result is [num_points, height, width]
# add an extra batch axis because conv needs it
corrs = jnp.pad(
corrs,
(
(0, 0),
(patch_size - 1, patch_size - 1),
(patch_size - 1, patch_size - 1),
),
)[jnp.newaxis, ...]
kernel = construct_patch_kernel(pos, corrs.shape[2:4], patch_size)
dim_nums = jax.lax.ConvDimensionNumbers(
lhs_spec=(0, 1, 2, 3), rhs_spec=(0, 1, 2, 3), out_spec=(0, 1, 2, 3)
)
# the [0] gets rid of the extra batch axis
res = jax.lax.conv_general_dilated(
corrs,
kernel,
(1, 1),
'VALID',
(1, 1),
(1, 1),
dim_nums,
feature_group_count=kernel.shape[0],
)[0]
return res
def is_same_res(r1, r2):
"""Test if two image resolutions are the same."""
return all([x == y for x, y in zip(r1, r2)])
class FeatureGrids(NamedTuple):
"""Feature grids for a video, used to compute trajectories.
These are per-frame outputs of the encoding resnet.
Attributes:
lowres: Low-resolution features, one for each resolution; 256 channels.
hires: High-resolution features, one for each resolution; 64 channels.
resolutions: Resolutions used for trajectory computation. There will be one
entry for the initialization, and then an entry for each PIPs refinement
resolution.
"""
lowres: Sequence[chex.Array]
hires: Sequence[chex.Array]
resolutions: Sequence[Tuple[int, int]]
class QueryFeatures(NamedTuple):
"""Query features used to compute trajectories.
These are sampled from the query frames and are a full descriptor of the
tracked points. They can be acquired from a query image and then reused in a
separate video.
Attributes:
lowres: Low-resolution features, one for each resolution; each has shape
[batch, num_query_points, 256]
hires: High-resolution features, one for each resolution; each has shape
[batch, num_query_points, 64]
resolutions: Resolutions used for trajectory computation. There will be one
entry for the initialization, and then an entry for each PIPs refinement
resolution.
"""
lowres: Sequence[chex.Array]
hires: Sequence[chex.Array]
resolutions: Sequence[Tuple[int, int]]
class TAPIR(hk.Module):
"""TAPIR model."""
def __init__(
self,
bilinear_interp_with_depthwise_conv: bool = False,
num_pips_iter: int = 4,
pyramid_level: int = 1,
mixer_hidden_dim: int = 512,
num_mixer_blocks: int = 12,
mixer_kernel_shape: int = 3,
patch_size: int = 7,
softmax_temperature: float = 20.0,
use_causal_conv: bool = False,
parallelize_query_extraction: bool = False,
initial_resolution: Tuple[int, int] = (256, 256),
name: str = 'tapir',
):
super().__init__(name=name)
self.highres_dim = 128
self.lowres_dim = 256
self.resnet = resnet.ResNet(
resnet_v2=True,
normalization='instancenorm',
strides=(1, 2, 2, 1),
blocks_per_group=(2, 2, 2, 2),
channels_per_group=(64, self.highres_dim, 256, self.lowres_dim),
use_projection=(True, True, True, True),
use_max_pool=False,
name='resnet',
)
self.cost_volume_track_mods = {
'hid1': hk.Conv2D(
16,
[3, 3],
name='cost_volume_regression_1',
stride=[1, 1],
),
'hid2': hk.Conv2D(
1,
[3, 3],
name='cost_volume_regression_2',
stride=[1, 1],
),
'hid3': hk.Conv2D(
32,
[3, 3],
name='cost_volume_occlusion_1',
stride=[2, 2],
),
'hid4': hk.Linear(16, name='cost_volume_occlusion_2'),
'occ_out': hk.Linear(2, name='occlusion_out'),
'regression_hid': hk.Linear(128, name='regression_hid'),
'regression_out': hk.Linear(2, name='regression_out'),
'conv_stats_conv1': hk.Conv2D(
256,
[5, 5],
name='conv_stats_conv1',
stride=[1, 1],
),
'conv_stats_conv2': hk.Conv2D(
256,
[3, 3],
name='conv_stats_conv2',
stride=[1, 1],
),
'conv_stats_linear': hk.Linear(32, name='conv_stats_linear'),
}
self.pips_mixer = PIPSMLPMixer(
4 + self.highres_dim + self.lowres_dim,
hidden_dim=mixer_hidden_dim,
num_blocks=num_mixer_blocks,
kernel_shape=mixer_kernel_shape,
use_causal_conv=use_causal_conv,
)
self.bilinear_interp_with_depthwise_conv = (
bilinear_interp_with_depthwise_conv
)
self.parallelize_query_extraction = parallelize_query_extraction
self.num_pips_iter = num_pips_iter
self.pyramid_level = pyramid_level
self.patch_size = patch_size
self.softmax_temperature = softmax_temperature
self.initial_resolution = tuple(initial_resolution)
def tracks_from_cost_volume(
self,
interp_feature: chex.Array,
feature_grid: chex.Array,
query_points: Optional[chex.Array],
im_shp: Optional[chex.Shape] = None,
) -> Tuple[chex.Array, chex.Array, chex.Array]:
"""Converts features into tracks by computing a cost volume.
The computed cost volume will have shape
[batch, num_queries, time, height, width], which can be very
memory intensive.
Args:
interp_feature: A tensor of features for each query point, of shape
[batch, num_queries, channels, heads].
feature_grid: A tensor of features for the video, of shape [batch, time,
height, width, channels, heads].
query_points: When computing tracks, we assume these points are given as
ground truth and we reproduce them exactly. This is a set of points of
shape [batch, num_points, 3], where each entry is [t, y, x] in frame/
raster coordinates.
im_shp: The shape of the original image, i.e., [batch, num_frames, time,
height, width, 3].
Returns:
A 2-tuple of the inferred points (of shape
[batch, num_points, num_frames, 2] where each point is [x, y]) and
inferred occlusion (of shape [batch, num_points, num_frames], where
each is a logit where higher means occluded)
"""
mods = self.cost_volume_track_mods
# Note: time is first axis to prevent the TPU from padding
cost_volume = jnp.einsum(
'bnc,bthwc->tbnhw',
interp_feature,
feature_grid,
)
shape = cost_volume.shape
batch_size, num_points = cost_volume.shape[1:3]
cost_volume = einshape('tbnhw->(tbn)hw1', cost_volume)
occlusion = mods['hid1'](cost_volume)
occlusion = jax.nn.relu(occlusion)
pos = mods['hid2'](occlusion)
pos_rshp = einshape('(tb)hw1->t(b)hw1', pos, t=shape[0])
pos = einshape('t(bn)hw1->bnthw', pos_rshp, b=batch_size, n=num_points)
pos = jax.nn.softmax(pos * self.softmax_temperature, axis=(-2, -1))
points = model_utils.heatmaps_to_points(
pos, im_shp, query_points=query_points
)
occlusion = mods['hid3'](occlusion)
occlusion = jax.nn.relu(occlusion)
occlusion = jnp.mean(occlusion, axis=(-2, -3))
occlusion = mods['hid4'](occlusion)
occlusion = jax.nn.relu(occlusion)
occlusion = mods['occ_out'](occlusion)
expected_dist = einshape(
'(tbn)1->bnt', occlusion[..., 1:2], n=shape[2], t=shape[0]
)
occlusion = einshape(
'(tbn)1->bnt', occlusion[..., 0:1], n=shape[2], t=shape[0]
)
return points, occlusion, expected_dist
def refine_pips(
self,
target_feature,
frame_features,
pyramid,
pos_guess,
occ_guess,
expd_guess,
orig_hw,
last_iter=None,
mixer_iter=0.0,
resize_hw=None,
causal_context=None,
get_causal_context=False,
):
# frame_features is batch, num_frames, height, width, channels
# target_features is batch, num_points, channels
# pos_guess is batch, num_points, num_frames,2
orig_h, orig_w = orig_hw
resized_h, resized_w = resize_hw
corrs_pyr = []
assert len(target_feature) == len(pyramid)
for pyridx, (query, grid) in enumerate(zip(target_feature, pyramid)):
# note: interp needs [y,x]
coords = transforms.convert_grid_coordinates(
pos_guess, (orig_w, orig_h), grid.shape[-2:-4:-1]
)[..., ::-1]
last_iter_query = None
if last_iter is not None:
if pyridx == 0:
last_iter_query = last_iter[..., : self.highres_dim]
else:
last_iter_query = last_iter[..., self.highres_dim :]
if not self.bilinear_interp_with_depthwise_conv:
# on CPU, gathers are cheap and matmuls are expensive
ctxx, ctxy = jnp.meshgrid(jnp.arange(-3, 4), jnp.arange(-3, 4))
ctx = jnp.stack([ctxy, ctxx], axis=-1)
ctx = jnp.reshape(ctx, [-1, 2])
coords2 = (
coords[:, :, :, jnp.newaxis, :]
+ ctx[jnp.newaxis, jnp.newaxis, jnp.newaxis, ...]
)
# grid is batch, frames, height, width, channels
# coords is batch, num_points, frames, spatial, x/y
# neighborhood = batch, num_points, frames, patch_height, patch_width,
# channels
neighborhood = jax.vmap( # across batch
jax.vmap( # across frames
jax.vmap( # across patch context size
jax.vmap( # across channels
functools.partial(model_utils.interp, mode='constant'),
in_axes=(-1, None),
out_axes=-1,
),
in_axes=(None, -2),
out_axes=-2,
),
in_axes=(0, 1),
out_axes=1,
)
)(grid, coords2)
# s is spatial context size
if last_iter_query is None:
patches = jnp.einsum('bnfsc,bnc->bnfs', neighborhood, query)
else:
patches = jnp.einsum(
'bnfsc,bnfc->bnfs', neighborhood, last_iter_query
)
else:
# on TPU, matmul is cheap and gather is expensive, so we rewrite
# the interpolation with a depthwise conv.
if last_iter_query is None:
corrs = jnp.einsum('bfhwc,bnc->bnfhw', grid, query)
else:
corrs = jnp.einsum('bfhwc,bnfc->bnfhw', grid, last_iter_query)
n = corrs.shape[1]
# coords is bnfs2
# patches is batch,n,frames,height,width
# vmap across batch dimension (because we have different points across
# the batch) and across the frame axis (this could potentially be rolled
# into the depthwise conv)
extract_patch_depthwise_conv_ = functools.partial(
extract_patch_depthwise_conv, patch_size=self.patch_size
)
patches = jax.vmap(extract_patch_depthwise_conv_)(
einshape('bnfc->b(nf)c', coords), einshape('bnfhw->b(nf)hw', corrs)
)
patches = einshape('b(nf)hw->bnf(hw)', patches, n=n)
corrs_pyr.append(patches)
corrs_pyr = jnp.concatenate(corrs_pyr, axis=-1)
corrs_chunked = corrs_pyr
pos_guess_input = pos_guess
occ_guess_input = occ_guess[..., jnp.newaxis]
expd_guess_input = expd_guess[..., jnp.newaxis]
# mlp_input is batch, num_points, num_chunks, frames_per_chunk, channels
if last_iter is None:
both_feature = jnp.concatenate(
[target_feature[0], target_feature[1]], axis=-1
)
mlp_input_features = jnp.tile(
both_feature[:, :, jnp.newaxis, :],
(1, 1) + corrs_chunked.shape[-2:-1] + (1,),
)
else:
mlp_input_features = last_iter
pos_guess_input = jnp.zeros_like(pos_guess_input)
mlp_input = jnp.concatenate(
[
pos_guess_input,
occ_guess_input,
expd_guess_input,
mlp_input_features,
corrs_chunked,
],
axis=-1,
)
x = einshape('bnfc->(bn)fc', mlp_input)
if causal_context is not None:
causal_context = jax.tree_map(
lambda x: einshape('bn...->(bn)...', x), causal_context
)
res, new_causal_context = self.pips_mixer(
x, causal_context, get_causal_context
)
res = einshape('(bn)fc->bnfc', res, b=mlp_input.shape[0])
if get_causal_context:
new_causal_context = jax.tree_map(
lambda x: einshape('(bn)...->bn...', x, b=mlp_input.shape[0]),
new_causal_context,
)
pos_update = transforms.convert_grid_coordinates(
res[..., :2],
(resized_w, resized_h),
(orig_w, orig_h),
)
return (
pos_update + pos_guess,
res[..., 2] + occ_guess,
res[..., 3] + expd_guess,
res[..., 4:] + (mlp_input_features if last_iter is None else last_iter),
new_causal_context,
)
def get_feature_grids(
self,
video: chex.Array,
is_training: bool,
refinement_resolutions: Optional[List[Tuple[int, int]]] = None,
) -> FeatureGrids:
"""Computes feature grids.
Args:
video: A 5-D tensor representing a batch of sequences of images.
is_training: Whether we are training.
refinement_resolutions: A list of (height, width) tuples. Refinement will
be repeated at each specified resolution, in order to achieve high
accuracy on resolutions higher than what TAPIR was trained on. If None,
reasonable refinement resolutions will be inferred from the input video
size.
Returns:
A FeatureGrids object which contains the required features for every
required resolution. Note that there will be one more feature grid
than there are refinement_resolutions, because there is always a
feature grid computed for TAP-Net initialization.
"""
if refinement_resolutions is None:
refinement_resolutions = model_utils.generate_default_resolutions(
video.shape[2:4], self.initial_resolution
)
all_required_resolutions = [self.initial_resolution]
all_required_resolutions.extend(refinement_resolutions)
feature_grid = []
hires_feats = []
resize_im_shape = []
curr_resolution = (-1, -1)
for resolution in all_required_resolutions:
if resolution[0] % 8 != 0 or resolution[1] % 8 != 0:
raise ValueError('Image resolution must be a multiple of 8.')
if not is_same_res(curr_resolution, resolution):
if is_same_res(curr_resolution, video.shape[-3:-1]):
video_resize = video
else:
video_resize = jax.image.resize(
video, video.shape[0:2] + resolution + (3,), method='bilinear'
)
curr_resolution = resolution
resnet_out = hk.BatchApply(self.resnet)(
video_resize, is_training=is_training
)
latent = resnet_out['resnet_unit_3']
hires = resnet_out['resnet_unit_1']
latent = latent / jnp.sqrt(
jnp.maximum(
jnp.sum(jnp.square(latent), axis=-1, keepdims=True),
1e-12,
)
)
hires = hires / jnp.sqrt(
jnp.maximum(
jnp.sum(jnp.square(hires), axis=-1, keepdims=True),
1e-12,
)
)
feature_grid.append(latent)
hires_feats.append(hires)
resize_im_shape.append(video_resize.shape[2:4])
return FeatureGrids(
tuple(feature_grid), tuple(hires_feats), tuple(resize_im_shape)
)
def get_query_features(
self,
video: chex.Array,
is_training: bool,
query_points: chex.Array,
feature_grids: Optional[FeatureGrids] = None,
refinement_resolutions: Optional[List[Tuple[int, int]]] = None,
) -> QueryFeatures:
"""Computes query features, which can be used for estimate_trajectories.
Args:
video: A 5-D tensor representing a batch of sequences of images.
is_training: Whether we are training.
query_points: The query points for which we compute tracks.
feature_grids: If passed, we'll use these feature grids rather than
computing new ones.
refinement_resolutions: A list of (height, width) tuples. Refinement will
be repeated at each specified resolution, in order to achieve high
accuracy on resolutions higher than what TAPIR was trained on. If None,
reasonable refinement resolutions will be inferred from the input video
size.
Returns:
A QueryFeatures object which contains the required features for every
required resolution.
"""
if feature_grids is None:
feature_grids = self.get_feature_grids(
video,
is_training=is_training,
refinement_resolutions=refinement_resolutions,
)
feature_grid = feature_grids.lowres
hires_feats = feature_grids.hires
resize_im_shape = feature_grids.resolutions
shape = video.shape
# shape is [batch_size, time, height, width, channels]; conversion needs
# [time, width, height]
curr_resolution = (-1, -1)
query_feats = []
hires_query_feats = []
for i, resolution in enumerate(resize_im_shape):
if is_same_res(curr_resolution, resolution):
query_feats.append(query_feats[-1])
hires_query_feats.append(hires_query_feats[-1])
continue
position_in_grid = transforms.convert_grid_coordinates(
query_points,
shape[1:4],
feature_grid[i].shape[1:4],
coordinate_format='tyx',
)
position_in_grid_hires = transforms.convert_grid_coordinates(
query_points,
shape[1:4],
hires_feats[i].shape[1:4],
coordinate_format='tyx',
)
if self.parallelize_query_extraction:
# Extracting query features involves gathering features across frames;
# a naive implementation will cause the model to do an all gather of
# the full video feature tensor, which consumes lots of memory.
# Therefore, we instead perform the x,y gather for every point on every
# single frame, and then mask out the gathers on the incorrect frames.
# This could be made more efficient by gathering exactly one query
# feature per device (rather than per frame).
#
# interp_features is now [batch, time, num_points, features]
interp_features = jax.vmap(
jax.vmap(
jax.vmap(
model_utils.interp,
in_axes=(2, None),
out_axes=-1,
),
in_axes=(0, None),
)
)(feature_grid[i], position_in_grid[..., 1:])
# is_correct_frame is [batch, time, num_points]
frame_id = jnp.array(
jnp.round(position_in_grid[:, jnp.newaxis, :, 0]), jnp.int32
)
is_correct_frame = jax.nn.one_hot(
frame_id, feature_grid[i].shape[1], axis=1
)
interp_features = jnp.sum(
interp_features * is_correct_frame[..., jnp.newaxis], axis=1
)
hires_interp = jax.vmap(
jax.vmap(
jax.vmap(
model_utils.interp,
in_axes=(2, None),
out_axes=-1,
),
in_axes=(0, None),
)
)(hires_feats[i], position_in_grid_hires[..., 1:])
hires_interp = jnp.sum(
hires_interp * is_correct_frame[..., jnp.newaxis], axis=1
)
else:
interp_features = jax.vmap(
jax.vmap(
model_utils.interp,
in_axes=(3, None),
out_axes=1,
)
)(feature_grid[i], position_in_grid)
hires_interp = jax.vmap(
jax.vmap(
model_utils.interp,
in_axes=(3, None),
out_axes=1,
)
)(hires_feats[i], position_in_grid_hires)
hires_query_feats.append(hires_interp)
query_feats.append(interp_features)
return QueryFeatures(
tuple(query_feats), tuple(hires_query_feats), tuple(resize_im_shape)
)
def estimate_trajectories(
self,
video_size: Tuple[int, int],
is_training: bool,
feature_grids: FeatureGrids,
query_features: QueryFeatures,
query_points_in_video: Optional[chex.Array],
query_chunk_size: Optional[int] = None,
causal_context: Optional[Sequence[Mapping[str, chex.Array]]] = None,
get_causal_context: bool = False,
) -> Mapping[str, Any]:
"""Estimates trajectories given features for a video and query features.
Args:
video_size: A 2-tuple containing the original [height, width] of the
video. Predictions will be scaled with respect to this resolution.
is_training: Whether we are training.
feature_grids: a FeatureGrids object computed for the given video.
query_features: a QueryFeatures object computed for the query points.
query_points_in_video: If provided, assume that the query points come from
the same video as feature_grids, and therefore constrain the resulting
trajectories to (approximately) pass through them.
query_chunk_size: When computing cost volumes, break the queries into
chunks of this size to save memory.
causal_context: if running online, this will be features computed for each
trajectory on earlier frames. If None, no context is assumed.
get_causal_context: if True, the output dict will also include features
that can be passed as causal_context to future frames when running
online.
Returns:
A dict of outputs, including:
occlusion: Occlusion logits, of shape [batch, num_queries, num_frames]
where higher indicates more likely to be occluded.
tracks: predicted point locations, of shape
[batch, num_queries, num_frames, 2], where each point is [x, y]
in raster coordinates
expected_dist: uncertainty estimate logits, of shape
[batch, num_queries, num_frames], where higher indicates more likely
to be far from the correct answer.
causal_context: (if get_causal_context is True) a pytree which can
be passed as causal_context to subsequent calls if running the model
online. In the current model, it is a list of dicts, one per
PIPs refinement iteration, where for each dict the values are hidden
units from the temporal depthwise conv layers, and the keys are names
derived from Haiku's layer names.
"""
def train2orig(x):
return transforms.convert_grid_coordinates(
x,
self.initial_resolution[::-1],
video_size[::-1],
coordinate_format='xy',
)
occ_iters = []
pts_iters = []
expd_iters = []
new_causal_context = []
num_iters = self.num_pips_iter * (len(feature_grids.lowres) - 1)
# This contains both middle step points and final step points.
for _ in range(num_iters + 1):
occ_iters.append([])
pts_iters.append([])
expd_iters.append([])
new_causal_context.append([])
del new_causal_context[-1]
infer = functools.partial(
self.tracks_from_cost_volume,
im_shp=feature_grids.lowres[0].shape[0:2]
+ self.initial_resolution
+ (3,),
)
num_queries = query_features.lowres[0].shape[1]
# Note: the permutation is required in order to randomize which tracks
# get the stop_gradient.
if causal_context is None:
perm = jax.random.permutation(hk.next_rng_key(), num_queries)
else:
if is_training:
# Need to handle permutation if we want to train with causal context.
raise ValueError('Training with causal context is not supported.')
perm = jnp.arange(num_queries, dtype=jnp.int32)
inv_perm = jnp.zeros_like(perm)
inv_perm = inv_perm.at[perm].set(jnp.arange(num_queries))
for ch in range(0, num_queries, query_chunk_size):
perm_chunk = perm[ch : ch + query_chunk_size]
chunk = query_features.lowres[0][:, perm_chunk]
if causal_context is not None:
cc_chunk = jax.tree_map(lambda x: x[:, perm_chunk], causal_context) # pylint: disable=cell-var-from-loop
if query_points_in_video is not None:
infer_query_points = query_points_in_video[
:, perm[ch : ch + query_chunk_size]
]
num_frames = feature_grids.lowres[0].shape[1]
infer_query_points = transforms.convert_grid_coordinates(
infer_query_points,
(num_frames,) + video_size,
(num_frames,) + self.initial_resolution,
coordinate_format='tyx',
)
else:
infer_query_points = None
points, occlusion, expected_dist = infer(
chunk,
feature_grids.lowres[0],
infer_query_points,
)
pts_iters[0].append(train2orig(points))
occ_iters[0].append(occlusion)
expd_iters[0].append(expected_dist)
mixer_feats = None
for i in range(num_iters):
feature_level = i // self.num_pips_iter + 1
queries = [
query_features.hires[feature_level][:, perm_chunk],
query_features.lowres[feature_level][:, perm_chunk],
]
for _ in range(self.pyramid_level):
queries.append(queries[-1])
pyramid = [
feature_grids.hires[feature_level],
feature_grids.lowres[feature_level],
]
for _ in range(self.pyramid_level):
pyramid.append(
hk.avg_pool(
pyramid[-1], [1, 1, 2, 2, 1], [1, 1, 2, 2, 1], 'VALID'
)
)
# Note: even when the pyramids are higher resolution, the points are
# all scaled according to the original resolution. This is because
# the raw points are input into the model, and need to be scaled that
# way.
#
# TODO(doersch): this should constrain the output to match the query
# points.
cc = cc_chunk[i] if causal_context is not None else None
refined = self.refine_pips(
queries,
None,
pyramid,
points,
occlusion,
expected_dist,
orig_hw=self.initial_resolution,
last_iter=mixer_feats,
mixer_iter=i,
resize_hw=feature_grids.resolutions[feature_level],
causal_context=cc,
get_causal_context=get_causal_context,
)
if ch > 0:
refined = jax.lax.stop_gradient(refined)
points = refined[0]
occlusion = refined[1]
expected_dist = refined[2]
mixer_feats = refined[3]
new_causal_context[i].append(refined[4])
pts_iters[i + 1].append(train2orig(points))
occ_iters[i + 1].append(occlusion)
expd_iters[i + 1].append(expected_dist)
if (i + 1) % self.num_pips_iter == 0:
mixer_feats = None
expected_dist = expd_iters[0][-1]
occlusion = occ_iters[0][-1]
occlusion = []
points = []
expd = []
for i in range(len(occ_iters)):
occlusion.append(jnp.concatenate(occ_iters[i], axis=1)[:, inv_perm])
points.append(jnp.concatenate(pts_iters[i], axis=1)[:, inv_perm])
expd.append(jnp.concatenate(expd_iters[i], axis=1)[:, inv_perm])
for i in range(len(new_causal_context)):
new_causal_context[i] = jax.tree_map(
lambda *x: jnp.concatenate(x, axis=1)[:, inv_perm],
*new_causal_context[i],
)
out = dict(
occlusion=occlusion,
tracks=points,
expected_dist=expd,
)
if get_causal_context:
out['causal_context'] = new_causal_context
return out
def __call__(
self,
video: chex.Array,
is_training: bool,
query_points: chex.Array,
query_chunk_size: Optional[int] = None,
get_query_feats: bool = False,
refinement_resolutions: Optional[List[Tuple[int, int]]] = None,
) -> Mapping[str, chex.Array]:
"""Runs a forward pass of the model.
Args:
video: A 5-D tensor representing a batch of sequences of images.
is_training: Whether we are training.
query_points: The query points for which we compute tracks.
query_chunk_size: When computing cost volumes, break the queries into
chunks of this size to save memory.
get_query_feats: Return query features for other losses like contrastive.
Not supported in the current version.
refinement_resolutions: A list of (height, width) tuples. Refinement will
be repeated at each specified resolution, in order to achieve high
accuracy on resolutions higher than what TAPIR was trained on. If None,
reasonable refinement resolutions will be inferred from the input video
size.
Returns:
A dict of outputs, including:
occlusion: Occlusion logits, of shape [batch, num_queries, num_frames]
where higher indicates more likely to be occluded.
tracks: predicted point locations, of shape
[batch, num_queries, num_frames, 2], where each point is [x, y]
in raster coordinates
expected_dist: uncertainty estimate logits, of shape
[batch, num_queries, num_frames], where higher indicates more likely
to be far from the correct answer.
"""
if get_query_feats:
raise ValueError('Get query feats not supported in TAPIR.')
feature_grids = self.get_feature_grids(
video,
is_training,
refinement_resolutions,
)
query_features = self.get_query_features(
video,
is_training,
query_points,
feature_grids,
refinement_resolutions,
)
trajectories = self.estimate_trajectories(
video.shape[-3:-1],
is_training,
feature_grids,
query_features,
query_points,
query_chunk_size,
)
# The prediction is the average of the iterative refinement output across
# every resolution. At training time there's only one iteration, so we'll
# just get the final refined output. At test time, however, there will be
# more. The lowest resolution is at index self.num_pips_iter;
# self.num_pips_iter iterations after that will be the next resolution,
# and so on.
p = self.num_pips_iter
out = dict(
occlusion=jnp.mean(jnp.stack(trajectories['occlusion'][p::p]), axis=0),
tracks=jnp.mean(jnp.stack(trajectories['tracks'][p::p]), axis=0),
expected_dist=jnp.mean(
jnp.stack(trajectories['expected_dist'][p::p]), axis=0
),
unrefined_occlusion=trajectories['occlusion'][:-1],
unrefined_tracks=trajectories['tracks'][:-1],
unrefined_expected_dist=trajectories['expected_dist'][:-1],
)
return out
| tapnet-main | tapir_model.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.
# ==============================================================================
"""Clustering TAPIR tracks based on independent motion."""
import functools
import time
from typing import NamedTuple
from einshape import jax_einshape as einshape
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
from tapnet import tapir_model
class TrainingState(NamedTuple):
"""Container for the training state."""
params: hk.Params
state: hk.State
opt_state: optax.OptState
rng: jax.Array
step: jax.Array
def make_projection_matrix(pred_mat):
"""Convert predicted projection matrix parameters to a projection matrix."""
pred_mat = einshape('n(coi)->ncoi', pred_mat, o=3, i=4)
@jax.custom_vjp
def f(x):
return x
def f_fwd(x):
return f(x), tuple()
def f_bwd(_, g):
return (jnp.clip(g, -100, 100),)
f.defvjp(f_fwd, f_bwd)
pred_mat = f(pred_mat)
orth1 = jnp.ones_like(pred_mat[..., 0:1, :-1]) * jnp.array([0.0, 0.0, 1.0])
orth2 = pred_mat[..., 1:2, :-1] * jnp.array([1.0, 1.0, 0.0])
orth2 = orth2 / jnp.sqrt(
jnp.maximum(jnp.sum(jnp.square(orth2), axis=-1, keepdims=True), 1e-12)
)
orth3 = pred_mat[..., 2:3, :-1] * jnp.array([1.0, 1.0, 0.0])
orth3 = orth3 - orth2 * jnp.sum(orth3 * orth2, axis=-1, keepdims=True)
orth3 = orth3 / jnp.sqrt(
jnp.maximum(jnp.sum(jnp.square(orth3), axis=-1, keepdims=True), 1e-12)
)
cross_prod = jnp.cross(orth1, orth2)
orth3 = orth3 * jnp.sign(jnp.sum(cross_prod * orth3, axis=-1, keepdims=True))
orth = jnp.concatenate([orth3, orth2, orth1], axis=-2)
pred_mat = jnp.concatenate([orth, pred_mat[..., -1:]], axis=-1)
return pred_mat
def project(pred_mat, pos_pred):
"""Project 3D points to 2D, with penalties for depth out-of-range."""
pos_pred = jnp.concatenate(
[pos_pred[..., :3], pos_pred[..., 0:1] * 0 + 1], axis=-1
)
pred_pos = jnp.einsum('fcoi,nci->nfco', pred_mat, pos_pred)
depth = jnp.minimum(2.0, jnp.maximum(pred_pos[..., 2:3] + 1.0, 0.5))
oob = jnp.maximum(pred_pos[..., 2:3] - 2.0, 0.0) + jnp.maximum(
0.5 - pred_pos[..., 2:3], 0.0
)
all_pred = pred_pos[..., 0:2] / depth
all_pred = (
all_pred
+ 0.1 * jax.random.normal(hk.next_rng_key(), shape=oob.shape) * oob
)
return all_pred, depth[..., 0]
def forward(
fr_idx,
pts_idx,
pts,
vis,
num_cats=4,
is_training=True,
sequence_boundaries=tuple(),
):
"""Model forward pass."""
def bn(x):
return hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.99)(
x, is_training=is_training
)
pts_shape = pts.shape
pts = jnp.reshape(pts * vis[..., jnp.newaxis], [pts.shape[0], -1])
pt_state = hk.get_parameter('point_state', [pts_shape[0], 64], init=jnp.zeros)
def centroid_init(shp, dtype):
del shp # unused
centroid_weights = jax.nn.one_hot(
jax.random.randint(hk.next_rng_key(), [384], 0, pts.shape[0]),
pts.shape[0],
axis=0,
)
centroids = jnp.transpose(centroid_weights) @ pts
centroid_vis = jnp.transpose(centroid_weights) @ vis
time_weight = centroid_vis
centroids = jnp.concatenate([centroids, time_weight * 100.0], axis=1)
centroids = jnp.transpose(centroids)
return jnp.array(centroids, dtype=dtype)
centroids = hk.get_parameter(
'centroids', [pts_shape[1] * 3, 384], init=centroid_init
)
time_weight = jnp.abs(centroids[pts_shape[1] * 2 :, :]) / 100.0
centroids = centroids[: pts_shape[1] * 2, :]
vis_tile = jnp.reshape(
jnp.tile(vis[:, :, jnp.newaxis], [1, 1, 2]), [pts.shape[0], -1]
)
tw_tile = jnp.reshape(
jnp.tile(time_weight[:, jnp.newaxis, :], [1, 2, 1]), [-1, 384]
)
dists = jnp.square(pts * vis_tile) @ jnp.square(tw_tile)
dists -= 2 * (pts * vis_tile) @ (centroids * tw_tile)
dists += jnp.square(vis_tile) @ jnp.square(centroids * tw_tile)
dists = jnp.exp(-dists * 10.0)
dists = dists / jnp.maximum(jnp.sum(dists, axis=-1, keepdims=True), 1e-8)
pt_state += hk.Linear(64)(dists)
frame_state_nosmooth = hk.get_parameter(
'frame_state',
[pts_shape[1], 64],
init=hk.initializers.TruncatedNormal(1.0),
)
conv = hk.Conv1D(64, 128, feature_group_count=64)
frame_state = []
for bnd in sequence_boundaries:
frame_state.append(conv(frame_state_nosmooth[bnd[0] : bnd[1]]))
frame_state = jnp.concatenate(frame_state, axis=0)
frame_state = bn(frame_state)
pt_state = bn(pt_state)
state = jax.nn.relu(hk.Linear(64)(pt_state))
state += hk.Linear(64)(jax.nn.relu(bn(hk.Linear(32)(state))))
state += hk.Linear(64)(jax.nn.relu(bn(hk.Linear(32)(state))))
truncated_normal = hk.initializers.TruncatedNormal
base_pred = hk.get_parameter(
'cat_pred_base',
[3 * 64 * pts_shape[0], num_cats],
init=truncated_normal(1.0),
)
fork1_pred = hk.get_parameter(
'cat_pred_fork1',
[3 * 64 * pts_shape[0], num_cats],
init=lambda *args: truncated_normal(1.0)(*args) * 0.0001 + base_pred,
)
fork2_pred = hk.get_parameter(
'cat_pred_fork2',
[3 * 64 * pts_shape[0], num_cats],
init=lambda *args: truncated_normal(1.0)(*args) * 0.0001 + base_pred,
)
def mul(mat):
mat = einshape('(pio)c->pcio', mat, i=64, o=3)
return jnp.einsum('pcio,pi->pco', mat, state) * 0.01
pos_pred_base = mul(base_pred)[pts_idx]
pos_pred_fork1 = mul(fork1_pred)[pts_idx]
pos_pred_fork2 = mul(fork2_pred)[pts_idx]
state = frame_state
state = jax.nn.relu(hk.Linear(128)(state))
state += hk.Linear(128)(bn(jax.nn.relu(hk.Linear(64)(state))))
state += hk.Linear(128)(bn(jax.nn.relu(hk.Linear(64)(state))))
state = state * 0.01
base = hk.get_parameter(
'mat_pred_base',
[state.shape[-1], num_cats * 12],
init=hk.initializers.TruncatedNormal(1.0),
)
fork1 = hk.get_parameter(
'mat_pred_fork1',
[state.shape[-1], num_cats * 12],
init=hk.initializers.TruncatedNormal(1.0),
)
fork2 = hk.get_parameter(
'mat_pred_fork2',
[state.shape[-1], num_cats * 12],
init=hk.initializers.TruncatedNormal(1.0),
)
pred_mat_base = state @ base
pred_mat_fork1 = state @ fork1
pred_mat_fork2 = state @ fork2
pred_mat_base = make_projection_matrix(pred_mat_base)[fr_idx]
pred_mat_fork1 = make_projection_matrix(pred_mat_fork1)[fr_idx]
pred_mat_fork2 = make_projection_matrix(pred_mat_fork2)[fr_idx]
if not is_training:
pred_pos_all, depth_all = project(pred_mat_base, pos_pred_base)
return pred_pos_all, depth_all
else:
return {
'pos_pred_base': pos_pred_base,
'pos_pred_fork1': pos_pred_fork1,
'pos_pred_fork2': pos_pred_fork2,
'pred_mat_base': pred_mat_base,
'pred_mat_fork1': pred_mat_fork1,
'pred_mat_fork2': pred_mat_fork2,
}
# Create the loss.
@hk.transform_with_state
def loss_fn(
data,
num_cats=4,
delete_mode=False,
sequence_boundaries=tuple(),
final_num_cats=28,
):
"""Computes the (scalar) LM loss on `data` w.r.t. params."""
pts, vis, _ = data
pts_idx = jax.random.permutation(hk.next_rng_key(), pts.shape[0])[:2048]
fr_idx = jax.random.permutation(hk.next_rng_key(), pts.shape[1])[:1024]
fwd = forward(
fr_idx,
pts_idx,
pts,
vis,
num_cats=num_cats,
sequence_boundaries=sequence_boundaries,
)
pts = pts[pts_idx][:, fr_idx]
print(pts.shape)
vis = vis[pts_idx][:, fr_idx]
def do_fork(base, fork1, fork2, i, chunk=1):
chunk1 = base[..., : i * chunk]
chunk2 = fork1[..., i * chunk : ((1 + i) * chunk)]
chunk3 = fork2[..., i * chunk : ((1 + i) * chunk)]
chunk4 = base[..., (1 + i) * chunk :]
return jnp.concatenate([chunk1, chunk2, chunk3, chunk4], axis=-1)
def do_delete(base, i, chunk=1):
chunk1 = base[..., : i * chunk]
chunk4 = base[..., (1 + i) * chunk :]
return jnp.concatenate([chunk1, chunk4], axis=-1)
losses = []
sum_vis = jnp.sum(vis)
if delete_mode:
all_pred, _ = project(fwd['pred_mat_base'], fwd['pos_pred_base'])
all_err = get_err(pts, vis, all_pred)
for i in range(fwd['pred_mat_base'].shape[-3]):
err_i = do_delete(all_err, i)
losses.append(loss_internal(err_i, sum_vis))
else:
all_pred_base, _ = project(fwd['pred_mat_base'], fwd['pos_pred_base'])
all_err_base = get_err(pts, vis, all_pred_base)
all_pred_fork1, _ = project(fwd['pred_mat_fork1'], fwd['pos_pred_fork1'])
all_err_fork1 = get_err(pts, vis, all_pred_fork1)
all_pred_fork2, _ = project(fwd['pred_mat_fork2'], fwd['pos_pred_fork2'])
all_err_fork2 = get_err(pts, vis, all_pred_fork2)
for i in range(fwd['pred_mat_base'].shape[-3]):
err_i = do_fork(all_err_base, all_err_fork1, all_err_fork2, i)
losses.append(loss_internal(err_i, sum_vis))
if delete_mode:
topk, _ = jax.lax.top_k(-jnp.array(losses), num_cats - final_num_cats + 3)
accum_loss = jnp.mean(-topk)
else:
accum_loss = jnp.min(jnp.array(losses))
return accum_loss, jnp.array(losses)
def huber(x):
sqrt_x = jnp.sqrt(jnp.maximum(x, 1e-12))
return jnp.where(x < 0.004, x, 0.004 * (2 * sqrt_x - 0.004)) * 100.0
def get_err(pts, vis, all_pred):
tmp = pts[:, :, jnp.newaxis, :] - all_pred
tmp = jnp.sum(jnp.square(tmp) * vis[:, :, jnp.newaxis, jnp.newaxis], axis=-1)
return jnp.sum(tmp, axis=1)
def loss_internal(err_summed, sum_vis):
min_loss = jnp.sum(jnp.min(err_summed, axis=1)) / sum_vis
return min_loss
def loss_fn_wrapper(*args, **kwargs):
(loss, aux), state = loss_fn.apply(*args, **kwargs)
return loss, (state, aux)
def update(
state,
data,
lr_mul=1.0,
num_cats=4,
delete_mode=False,
sequence_boundaries=tuple(),
optimiser=None,
final_num_cats=28,
):
"""Does an SGD step and returns metrics."""
rng, new_rng = jax.random.split(state.rng)
loss_and_grad_fn = jax.value_and_grad(
functools.partial(
loss_fn_wrapper,
num_cats=num_cats,
delete_mode=delete_mode,
sequence_boundaries=sequence_boundaries,
final_num_cats=final_num_cats,
),
has_aux=True,
)
(loss, (new_state, losses)), gradients = loss_and_grad_fn(
state.params, state.state, rng, data
)
updates, new_opt_state = optimiser.update(gradients, state.opt_state)
updates = jax.tree_map(lambda x: x * lr_mul, updates)
new_params = optax.apply_updates(state.params, updates)
new_state = TrainingState(
params=new_params,
state=new_state,
opt_state=new_opt_state,
rng=new_rng,
step=state.step + 1,
)
metrics = {
'step': state.step,
'loss': loss,
'losses': losses,
}
return new_state, metrics
@hk.transform_with_state
def forward_fn(pts_idx, pts, vis, num_cats=4, sequence_boundaries=tuple()):
"""Test-time forward function."""
preds_all, depth_all = forward(
jnp.arange(pts.shape[1], dtype=jnp.int32),
pts_idx,
pts,
vis,
num_cats=num_cats,
is_training=False,
sequence_boundaries=sequence_boundaries,
)
pts = pts[pts_idx]
vis = vis[pts_idx]
err = jnp.sum(jnp.square(pts[:, :, jnp.newaxis, :] - preds_all), axis=-1)
return err * vis[:, :, jnp.newaxis], preds_all, depth_all
def pts_eval(
state,
pts_idx,
pts,
vis,
num_cats=4,
sequence_boundaries=tuple(),
):
"""Evaluate the errors for some points."""
(err, pred_all, depth_all), _ = forward_fn.apply(
state.params,
state.state,
state.rng,
pts_idx,
pts,
vis,
num_cats=num_cats,
sequence_boundaries=sequence_boundaries,
)
return err, pred_all, depth_all
def init(rng, data, num_cats=1, sequence_boundaries=tuple(), optimiser=None):
rng, init_rng = jax.random.split(rng)
initial_params, initial_state = loss_fn.init(
init_rng, data, num_cats=num_cats, sequence_boundaries=sequence_boundaries
)
initial_opt_state = optimiser.init(initial_params)
return TrainingState(
params=initial_params,
state=initial_state,
opt_state=initial_opt_state,
rng=rng,
step=jnp.array(0),
)
def compute_clusters(
separation_tracks_dict,
separation_visibility_dict,
demo_episode_ids,
separation_video_shapes,
query_features=None,
final_num_cats=15,
max_num_cats=25,
low_visibility_threshold=0.1,
):
"""Compute clustering.
Args:
separation_tracks_dict: dict of tracks keyed by episode id, each of shape
[num_points, num frames, 2].
separation_visibility_dict: dict of visibility values keyed by episode id,
each of shape [num_points, num frames].
demo_episode_ids: demo episode ids
separation_video_shapes: dict of video sizes (i.e. num_frames, height,
width, channels), keyed by episode id. Currently assumes that they are all
the same height, width.
query_features: query features associated with each points (short ones will
be removed)
final_num_cats: the number of output clusters
max_num_cats: the maximum number of clusters after splitting, before
beginning to merge.
low_visibility_threshold: throw out tracks with less than this fraction of
visible frames.
Returns:
A dict, where low-visibility points have been removed. "classes" is
the class id's for remaining points, and "sum_error" is the sum of error
for visible points.
"""
iters_before_split = 500
num_iters = (
max_num_cats + (max_num_cats - final_num_cats) - 1
) * iters_before_split
separation_tracks = np.concatenate(
[separation_tracks_dict[x] for x in demo_episode_ids], axis=1
)
separation_visibility = np.concatenate(
[separation_visibility_dict[x] for x in demo_episode_ids], axis=1
)
enough_visible = (
np.mean(separation_visibility, axis=-1) > low_visibility_threshold
)
separation_tracks = separation_tracks[enough_visible]
separation_visibility = separation_visibility[enough_visible]
if query_features is not None:
query_features = jax.tree_map(
lambda x: x[:, enough_visible] if len(x.shape) > 1 else x,
query_features,
)
separation_tracks_dict = jax.tree_map(
lambda x: x[enough_visible], separation_tracks_dict
)
separation_visibility_dict = jax.tree_map(
lambda x: x[enough_visible], separation_visibility_dict
)
cur = 0
sequence_boundaries = []
for shp in [separation_video_shapes[x] for x in demo_episode_ids]:
sequence_boundaries.append((cur, cur + shp[0]))
cur += shp[0]
sequence_boundaries = tuple(sequence_boundaries)
# Create the optimiser.
optimiser = optax.chain(
optax.clip_by_global_norm(1e-3),
optax.adam(5e-2, b1=0.9, b2=0.99),
)
# Initialise the model parameters.
rng = jax.random.PRNGKey(42)
shp = separation_video_shapes[demo_episode_ids[0]]
data = (
jnp.array(separation_tracks / np.array([shp[2], shp[1]])),
jnp.array(separation_visibility),
)
state = init(
rng,
data + (1,),
num_cats=1,
sequence_boundaries=sequence_boundaries,
optimiser=optimiser,
) # +(np.zeros([100],dtype=np.int32),np.zeros([100],dtype=np.int32)))
# Start training (note we don't include any explicit eval in this example).
prev_time = time.time()
log_every = 10
num_cats = 1
loss_curve = []
loss_moving_average = 0
num_since_fork = 1000
delete_mode = False
need_compile = True
for step in range(num_iters):
if step % iters_before_split == iters_before_split - 1:
if delete_mode:
num_cats -= 1
to_delete = np.argmin(loss_moving_average)
print('deleting:' + str(to_delete) + '; new num_cats:' + str(num_cats))
def do_delete(val, chunk=1):
val = np.array(val)
lb = to_delete * chunk # pylint: disable=cell-var-from-loop
ub = (to_delete + 1) * chunk # pylint: disable=cell-var-from-loop
return np.concatenate([val[:, :lb], val[:, ub:]], axis=1)
def delete_dict(param_dict):
param_dict['cat_pred_base'] = do_delete(param_dict['cat_pred_base']) # pylint: disable=cell-var-from-loop
param_dict['cat_pred_fork1'] = do_delete(param_dict['cat_pred_fork1']) # pylint: disable=cell-var-from-loop
param_dict['cat_pred_fork2'] = do_delete(param_dict['cat_pred_fork2']) # pylint: disable=cell-var-from-loop
param_dict['mat_pred_base'] = do_delete( # pylint: disable=cell-var-from-loop
param_dict['mat_pred_base'], chunk=12
)
param_dict['mat_pred_fork1'] = do_delete( # pylint: disable=cell-var-from-loop
param_dict['mat_pred_fork1'], chunk=12
)
param_dict['mat_pred_fork2'] = do_delete( # pylint: disable=cell-var-from-loop
param_dict['mat_pred_fork2'], chunk=12
)
delete_dict(state.params['~'])
delete_dict(state.opt_state[1][0].mu['~'])
delete_dict(state.opt_state[1][0].nu['~'])
else:
num_cats += 1
to_split = jnp.argmin(loss_moving_average)
print('splitting:' + str(to_split) + '; new num_cats:' + str(num_cats))
def do_fork(base, fork1, fork2, chunk=1, noise=0.0, mul=1.0):
base = np.array(base)
fork1 = np.array(fork1)
fork2 = np.array(fork2)
lb = to_split * chunk # pylint: disable=cell-var-from-loop
ub = (to_split + 1) * chunk # pylint: disable=cell-var-from-loop
base[:, lb:ub] = fork1[:, lb:ub]
base = np.concatenate([base, fork2[:, lb:ub]], axis=-1)
def reinit(fork):
fork = np.concatenate(
[
fork,
(
fork[:, lb:ub]
+ np.random.normal(size=[fork.shape[0], chunk]) * noise
),
],
axis=-1,
)
fork[:, lb:ub] = (
fork[:, lb:ub]
+ np.random.normal(size=[fork.shape[0], chunk]) * noise
)
if noise > 0:
fork = np.copy(base) + np.random.normal(size=base.shape) * noise
fork = fork * mul
return fork
return base, reinit(fork1), reinit(fork2)
def fork_dict(param_dict, noise=0.0, mul=1.0):
new_cpb, new_cpf1, new_cpf2 = do_fork( # pylint: disable=cell-var-from-loop
param_dict['cat_pred_base'],
param_dict['cat_pred_fork1'],
param_dict['cat_pred_fork2'],
noise=noise,
mul=mul,
)
param_dict['cat_pred_base'] = new_cpb
param_dict['cat_pred_fork1'] = new_cpf1
param_dict['cat_pred_fork2'] = new_cpf2
new_mpb, new_mpf1, new_mpf2 = do_fork( # pylint: disable=cell-var-from-loop
param_dict['mat_pred_base'],
param_dict['mat_pred_fork1'],
param_dict['mat_pred_fork2'],
chunk=12,
noise=noise,
mul=mul,
)
param_dict['mat_pred_base'] = new_mpb
param_dict['mat_pred_fork1'] = new_mpf1
param_dict['mat_pred_fork2'] = new_mpf2
fork_dict(state.params['~'], noise=0.000001)
fork_dict(state.opt_state[1][0].mu['~'], mul=0.0)
fork_dict(state.opt_state[1][0].nu['~'], mul=1.0)
state = TrainingState(
params=state.params,
state=state.state,
opt_state=optimiser.init(state.params),
rng=state.rng,
step=state.step,
)
delete_mode = num_cats == max_num_cats
num_since_fork = 0
loss_moving_average = 0
need_compile = True
if need_compile:
update_jit = jax.jit(
functools.partial(
update,
num_cats=num_cats,
delete_mode=delete_mode,
sequence_boundaries=sequence_boundaries,
optimiser=optimiser,
final_num_cats=final_num_cats,
)
)
need_compile = False
lr_mul = min(1.0, (num_since_fork + 1) / 20.0)
# TODO(doersch): hardcoding the LR schedule isn't very smart
if state.step > num_iters * 0.25:
lr_mul = lr_mul / 2.0
if state.step > num_iters * 0.50:
lr_mul = lr_mul / 2.0
if state.step > num_iters * 0.75:
lr_mul = lr_mul / 2.0
state, metrics = update_jit(state, data + (state.step,), lr_mul)
loss_curve.append(metrics['loss'])
loss_moving_average = 0.9 * loss_moving_average + 0.1 * metrics['losses']
if step % log_every == 0:
steps_per_sec = log_every / (time.time() - prev_time)
prev_time = time.time()
metrics |= {'steps_per_sec': steps_per_sec}
print(
{
k: float(v) if k != 'losses' else list(np.array(v))
for k, v in metrics.items()
}
)
num_since_fork += 1
pts_eval_jit = jax.jit(
functools.partial(
pts_eval,
num_cats=num_cats,
sequence_boundaries=sequence_boundaries,
)
)
sum_error = []
for i in range(0, separation_tracks.shape[0], 128):
err, _, _ = pts_eval_jit(
state,
np.arange(i, min(separation_tracks.shape[0], i + 128)),
data[0],
data[1],
)
sum_error.append(np.sum(err, axis=1))
sum_error = np.concatenate(sum_error, axis=0)
return {
'classes': np.array(np.argmin(np.array(sum_error), axis=-1)),
'sum_error': sum_error,
'separation_visibility': separation_visibility_dict,
'separation_tracks': separation_tracks_dict,
'query_features': query_features,
'demo_episode_ids': demo_episode_ids,
}
def construct_fake_causal_state(
query_features, convert_to_jax=False, channel_multiplier=4
):
"""Constructs a fake TAPIR causal state which can be used to reduce jitting.
Please not this function is very fragile and only works for the current
version of tapir. It will likely need to be updated if TAPIR changes, but it
is helpful for quick iterations.
Args:
query_features: Query features which will be used to infer shapes.
convert_to_jax: Whether to convert it to a jax array (helps prevent
recompiles)
channel_multiplier: for compatibility with smaller models
Returns:
A causal state.
"""
num_points = query_features_count(query_features)
num_resolutions = len(query_features.resolutions)
dims = 512 * channel_multiplier
value_shapes = {
'tapir/~/pips_mlp_mixer/block_1_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_1_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_2_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_2_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_3_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_3_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_4_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_4_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_5_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_5_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_6_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_6_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_7_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_7_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_8_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_8_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_9_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_9_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_10_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_10_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_11_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_11_causal_2': (1, num_points, 2, dims),
'tapir/~/pips_mlp_mixer/block_causal_1': (1, num_points, 2, 512),
'tapir/~/pips_mlp_mixer/block_causal_2': (1, num_points, 2, dims),
}
fake_ret = {k: np.zeros(v) for k, v in value_shapes.items()}
fake_ret = [fake_ret] * num_resolutions * 4
if convert_to_jax:
fake_ret = jax.tree_map(jnp.array, fake_ret)
return fake_ret
def _build_online_model_init(frames, query_points, *, tapir_model_kwargs):
"""Build tapir model for initialisation and tracking.
Args:
frames:
query_points:
tapir_model_kwargs:
Returns:
Raises:
<Any>:
"""
if not tapir_model_kwargs['use_causal_conv']:
raise ValueError('Online model requires causal TAPIR training.')
model = tapir_model.TAPIR(**tapir_model_kwargs)
feature_grids = model.get_feature_grids(
frames,
is_training=False,
)
query_features = model.get_query_features(
frames,
is_training=True,
query_points=query_points,
feature_grids=feature_grids,
)
return query_features
def _build_online_model_predict(
frames,
query_features,
causal_context,
*,
tapir_model_kwargs,
query_chunk_size=256,
query_points_in_video=None,
):
"""Compute point tracks and occlusions given frames and query points."""
if not tapir_model_kwargs['use_causal_conv']:
raise ValueError('Online model requires causal TAPIR training.')
model = tapir_model.TAPIR(**tapir_model_kwargs)
feature_grids = model.get_feature_grids(
frames,
is_training=False,
)
trajectories = model.estimate_trajectories(
frames.shape[-3:-1],
is_training=False,
feature_grids=feature_grids,
query_features=query_features,
query_points_in_video=query_points_in_video,
query_chunk_size=query_chunk_size,
causal_context=causal_context,
get_causal_context=True,
)
trajectories = dict(trajectories)
causal_context = trajectories['causal_context']
del trajectories['causal_context']
return {k: v[-1] for k, v in trajectories.items()}, causal_context
def build_models(
checkpoint_path,
query_chunk_size=256,
):
"""Build tapir model for initialisation and tracking."""
ckpt_state = np.load(checkpoint_path, allow_pickle=True).item()
params, state = ckpt_state['params'], ckpt_state['state']
num_params = hk.data_structures.tree_size(params)
num_bytes = hk.data_structures.tree_bytes(params)
print('TAPIR model')
print(
f'Number of params: {num_params}',
)
print(f'Number of bytes: {num_bytes / 1e6:.2f} MB')
tapir_model_kwargs = dict(
use_causal_conv=True, bilinear_interp_with_depthwise_conv=False
)
online_model_init_fn = functools.partial(
_build_online_model_init,
tapir_model_kwargs=tapir_model_kwargs,
)
online_init = hk.transform_with_state(online_model_init_fn)
online_init_apply = jax.jit(online_init.apply, backend='cpu')
online_model_predict_fn = functools.partial(
_build_online_model_predict,
tapir_model_kwargs=tapir_model_kwargs,
query_chunk_size=query_chunk_size,
)
online_predict = hk.transform_with_state(online_model_predict_fn)
# Jit is broken here unfortunately.
online_predict_apply_cpu = online_predict.apply
online_predict_apply_gpu = jax.jit(online_predict.apply, backend='gpu')
# online_predict_apply = online_predict.apply
rng = jax.random.PRNGKey(42)
online_init_apply = functools.partial(
online_init_apply, params=params, state=state, rng=rng
)
online_predict_apply_cpu = functools.partial(
online_predict_apply_cpu, params=params, state=state, rng=rng
)
online_predict_apply_gpu = functools.partial(
online_predict_apply_gpu, params=params, state=state, rng=rng
)
return online_init_apply, online_predict_apply_cpu, online_predict_apply_gpu
def query_features_join(feature_list):
"""Merge a list of query features int a single query features structure."""
lowres = [x.lowres for x in feature_list]
hires = [x.hires for x in feature_list]
joined_features = tapir_model.QueryFeatures(
lowres=tuple(np.concatenate(x, axis=1) for x in zip(*lowres)),
hires=tuple(np.concatenate(x, axis=1) for x in zip(*hires)),
resolutions=feature_list[0].resolutions,
)
return joined_features
def query_features_count(features):
"""Number of points within a query features structure."""
return features.lowres[0].shape[1]
def predictions_to_tracks_visibility(predictions, single_step=True):
"""Extract tracks and visibility from TAPIR predictions.
Args:
predictions: Predictions output of TAPIR
single_step: Whether we are processing a single step or a whole episode.
Returns:
* Tracks of shape [num_points, (t), xy]
* Visibility of shape [num_points, (t)]. Float between 0 and 1.
"""
tracks = predictions['tracks'][0]
occlusion = predictions['occlusion'][0]
expected_dist = predictions['expected_dist'][0]
if single_step:
tracks = tracks[:, 0]
occlusion = occlusion[:, 0]
expected_dist = expected_dist[:, 0]
pred_occ = jax.nn.sigmoid(occlusion)
visibility = (1 - pred_occ) * (1 - jax.nn.sigmoid(expected_dist))
return tracks, visibility
def preprocess_frames(frames: np.ndarray) -> np.ndarray:
"""Preprocess frames to model inputs.
Args:
frames: [num_frames, height, width, 3], [0, 255], np.uint8
Returns:
frames: [num_frames, height, width, 3], [-1, 1], np.float32
"""
frames = frames.astype(np.float32)
frames = frames / 255 * 2 - 1
return frames
def track_many_points(
separation_videos,
demo_episode_ids,
checkpoint_path,
frame_stride=4,
points_per_frame=8,
point_batch_size=2048,
sample_box_corners=(0.1, 0.1, 0.9, 0.9),
):
"""Track random points sampled from the videos.
Args:
separation_videos: dict of uint8 tensors, keyed by demo_episode_ids.
demo_episode_ids: demo episode ids.
checkpoint_path: path to TAPIR checkpoint file
frame_stride: sample points from one out of every this number of frames
points_per_frame: from each selected frame, sample this many points
point_batch_size: how many points to run through tapir simultaneously.
sample_box_corners: sample within this box. Format is [x_lower, y_lower,
x_upper, y_upper], in normalized coordinates.
Returns:
a dict with tracked points
"""
tapir_init, _, tapir_predict = build_models(
checkpoint_path, query_chunk_size=512
)
np.random.seed(42)
query_features = []
query_features2 = []
query_points = []
tmp_query_points = []
def merge_struct(query_features, tmp_query_points):
query_features2.append(query_features_join(query_features))
query_points.append(
[
np.concatenate([x[i] for x in tmp_query_points], axis=0)
for i in range(3)
]
)
for sv_idx, sv in enumerate([separation_videos[x] for x in demo_episode_ids]):
print(f'extracting query features for video {sv_idx}')
for i in range(0, len(sv), frame_stride):
x_scl = sample_box_corners[2] - sample_box_corners[0]
y_scl = sample_box_corners[3] - sample_box_corners[1]
x_add = sample_box_corners[0]
y_add = sample_box_corners[1]
qp = (
np.random.uniform(0.0, 1.0, [points_per_frame, 3])
* np.array([0.0, sv.shape[1] * y_scl, sv.shape[2] * x_scl])[None, ...]
+ np.array([0.0, sv.shape[1] * y_add, sv.shape[2] * x_add])[None, ...]
)
tmp_query_points.append((
np.array([sv_idx] * points_per_frame),
np.array([i] * points_per_frame),
qp[..., 1:],
))
qf, _ = tapir_init(
frames=preprocess_frames(sv[None, None, i]),
query_points=qp[None],
)
query_features.append(qf)
if len(query_features) == point_batch_size // points_per_frame:
merge_struct(query_features, tmp_query_points)
query_features = []
tmp_query_points = []
print('Done extracting query features')
num_extra = 0
if query_features:
merge_struct(query_features, tmp_query_points)
out_query_features = query_features_join(query_features2)
out_query_points = [
np.concatenate([x[i] for x in query_points], axis=0) for i in range(3)
]
if query_features:
del query_features2[-1]
del query_points[-1]
while len(query_features) < point_batch_size // points_per_frame:
query_features.append(query_features[-1])
tmp_query_points.append(tmp_query_points[-1])
num_extra += points_per_frame
merge_struct(query_features, tmp_query_points)
all_separation_tracks = []
all_separation_visibility = []
print('Note that TAPIR compilation takes a while.')
print('You may not see GPU usage immediately.')
for qf_idx, query_features in enumerate(query_features2):
print(f'query feature batch {qf_idx}/{len(query_features2)}')
separation_tracks = []
separation_visibility = []
for sv_idx, sv in enumerate(
[separation_videos[x] for x in demo_episode_ids]
):
print(f'tracking in video {sv_idx}/{len(demo_episode_ids)}')
causal_state = construct_fake_causal_state(
query_features,
convert_to_jax=True,
channel_multiplier=4,
)
for i in range(len(sv)):
(prediction, causal_state), _ = tapir_predict(
frames=preprocess_frames(sv[None, None, i]),
query_features=query_features,
causal_context=causal_state,
)
prediction = jax.tree_map(np.array, prediction)
res = predictions_to_tracks_visibility(prediction)
separation_tracks.append(res[0])
separation_visibility.append(res[1] > 0.5) # Threshold
all_separation_visibility.append(np.stack(separation_visibility, axis=1))
all_separation_tracks.append(np.stack(separation_tracks, axis=1))
separation_visibility = np.concatenate(all_separation_visibility, axis=0)
separation_tracks = np.concatenate(all_separation_tracks, axis=0)
pad_start = separation_tracks.shape[0] - num_extra
separation_tracks = separation_tracks[:pad_start]
separation_visibility = separation_visibility[:pad_start]
separation_video_shapes = [
separation_videos[x].shape for x in demo_episode_ids
]
bnds = []
cur = 0
for shp in separation_video_shapes:
bnds.append((cur, cur + shp[0]))
cur += shp[0]
separation_visibility = {
k: separation_visibility[:, lb:ub]
for k, (lb, ub) in zip(demo_episode_ids, bnds)
}
separation_tracks = {
k: separation_tracks[:, lb:ub]
for k, (lb, ub) in zip(demo_episode_ids, bnds)
}
return {
'separation_visibility': separation_visibility,
'separation_tracks': separation_tracks,
'video_shape': {
x: separation_video_shapes[i] for i, x in enumerate(demo_episode_ids)
},
'query_features': jax.tree_map(np.array, out_query_features),
'demo_episode_ids': demo_episode_ids,
'query_points': out_query_points,
}
| tapnet-main | tapir_clustering.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 and losses for building and training TAP models."""
from typing import Optional
import chex
import jax
import jax.numpy as jnp
import numpy as np
import optax
from tapnet.utils import transforms
def huber_loss(
tracks: chex.Array, target_points: chex.Array, occluded: chex.Numeric
) -> chex.Array:
"""Huber loss for point trajectories."""
error = tracks - target_points
# Huber loss with a threshold of 4 pixels
distsqr = jnp.sum(jnp.square(error), axis=-1)
dist = jnp.sqrt(distsqr + 1e-12) # add eps to prevent nan
delta = 4.0
loss_huber = jnp.where(
dist < delta, distsqr / 2, delta * (jnp.abs(dist) - delta / 2)
)
loss_huber *= 1.0 - occluded
loss_huber = jnp.mean(loss_huber, axis=[1, 2])
return loss_huber
def prob_loss(
tracks: chex.Array,
expd: chex.Array,
target_points: chex.Array,
occluded: chex.Array,
expected_dist_thresh: float = 8.0,
):
"""Loss for classifying if a point is within pixel threshold of its target."""
# Points with an error larger than 8 pixels are likely to be useless; marking
# them as occluded will actually improve Jaccard metrics and give
# qualitatively better results.
err = jnp.sum(jnp.square(tracks - target_points), axis=-1)
invalid = (err > expected_dist_thresh**2).astype(expd.dtype)
logprob = optax.sigmoid_binary_cross_entropy(expd, invalid)
logprob *= 1.0 - occluded
logprob = jnp.mean(logprob, axis=[1, 2])
return logprob
def interp(x: chex.Array, y: chex.Array, mode: str = 'nearest') -> chex.Array:
"""Bilinear interpolation.
Args:
x: Grid of features to be interpolated, of shape [height, width]
y: Points to be interpolated, of shape [num_points, 2], where each point is
[y, x] in pixel coordinates, or [num_points, 3], where each point is [z,
y, x]. Note that x and y are assumed to be raster coordinates: i.e. (0,
0) refers to the upper-left corner of the upper-left pixel. z, however, is
assumed to be frame coordinates, so 0 is the first frame, and 0.5 is
halfway between the first and second frames.
mode: mode for dealing with samples outside the range, passed to
jax.scipy.ndimage.map_coordinates.
Returns:
The interpolated value, of shape [num_points].
"""
# If the coordinate format is [z,y,x], we need to handle the z coordinate
# differently per the docstring.
if y.shape[-1] == 3:
y = jnp.concatenate([y[..., 0:1], y[..., 1:] - 0.5], axis=-1)
else:
y = y - 0.5
return jax.scipy.ndimage.map_coordinates(
x,
jnp.transpose(y),
order=1,
mode=mode,
)
def soft_argmax_heatmap(
softmax_val: chex.Array,
threshold: chex.Numeric = 5,
) -> chex.Array:
"""Computes the soft argmax a heatmap.
Finds the argmax grid cell, and then returns the average coordinate of
surrounding grid cells, weighted by the softmax.
Args:
softmax_val: A heatmap of shape [height, width], containing all positive
values summing to 1 across the entire grid.
threshold: The radius of surrounding cells to consider when computing the
average.
Returns:
The soft argmax, which is a single point [x,y] in grid coordinates.
"""
x, y = jnp.meshgrid(
jnp.arange(softmax_val.shape[1]),
jnp.arange(softmax_val.shape[0]),
)
coords = jnp.stack([x + 0.5, y + 0.5], axis=-1)
argmax_pos = jnp.argmax(jnp.reshape(softmax_val, -1))
pos = jnp.reshape(coords, [-1, 2])[argmax_pos, jnp.newaxis, jnp.newaxis, :]
valid = jnp.sum(
jnp.square(coords - pos),
axis=-1,
keepdims=True,
) < jnp.square(threshold)
weighted_sum = jnp.sum(
coords * valid * softmax_val[:, :, jnp.newaxis],
axis=(0, 1),
)
sum_of_weights = jnp.maximum(
jnp.sum(valid * softmax_val[:, :, jnp.newaxis], axis=(0, 1)),
1e-12,
)
return weighted_sum / sum_of_weights
def heatmaps_to_points(
all_pairs_softmax: chex.Array,
image_shape: chex.Shape,
threshold: chex.Numeric = 5,
query_points: Optional[chex.Array] = None,
) -> chex.Array:
"""Given a batch of heatmaps, compute a soft argmax.
If query points are given, constrain that the query points are returned
verbatim.
Args:
all_pairs_softmax: A set of heatmaps, of shape [batch, num_points, time,
height, width].
image_shape: The shape of the original image that the feature grid was
extracted from. This is needed to properly normalize coordinates.
threshold: Threshold for the soft argmax operation.
query_points (optional): If specified, we assume these points are given as
ground truth and we reproduce them exactly. This is a set of points of
shape [batch, num_points, 3], where each entry is [t, y, x] in frame/
raster coordinates.
Returns:
predicted points, of shape [batch, num_points, time, 2], where each point is
[x, y] in raster coordinates. These are the result of a soft argmax ecept
where the query point is specified, in which case the query points are
returned verbatim.
"""
# soft_argmax_heatmap operates over a single heatmap. We vmap it across
# batch, num_points, and frames.
vmap_sah = soft_argmax_heatmap
for _ in range(3):
vmap_sah = jax.vmap(vmap_sah, (0, None))
out_points = vmap_sah(all_pairs_softmax, threshold)
feature_grid_shape = all_pairs_softmax.shape[1:]
# Note: out_points is now [x, y]; we need to divide by [width, height].
# image_shape[3] is width and image_shape[2] is height.
out_points = transforms.convert_grid_coordinates(
out_points,
feature_grid_shape[3:1:-1],
image_shape[3:1:-1],
)
assert feature_grid_shape[1] == image_shape[1]
if query_points is not None:
# The [..., 0:1] is because we only care about the frame index.
query_frame = transforms.convert_grid_coordinates(
query_points,
image_shape[1:4],
feature_grid_shape[1:4],
coordinate_format='tyx',
)[..., 0:1]
query_frame = jnp.array(jnp.round(query_frame), jnp.int32)
frame_indices = jnp.arange(image_shape[1], dtype=jnp.int32)[
jnp.newaxis, jnp.newaxis, :
]
is_query_point = query_frame == frame_indices
is_query_point = is_query_point[:, :, :, jnp.newaxis]
out_points = (
out_points * (1 - is_query_point)
+ query_points[:, :, jnp.newaxis, 2:0:-1] * is_query_point
)
return out_points
def generate_default_resolutions(full_size, train_size, num_levels=None):
"""Generate a list of logarithmically-spaced resolutions.
Generated resolutions are between train_size and full_size, inclusive, with
num_levels different resolutions total. Useful for generating the input to
refinement_resolutions in PIPs.
Args:
full_size: 2-tuple of ints. The full image size desired.
train_size: 2-tuple of ints. The smallest refinement level. Should
typically match the training resolution, which is (256, 256) for TAPIR.
num_levels: number of levels. Typically each resolution should be less than
twice the size of prior resolutions.
Returns:
A list of resolutions.
"""
if all([x == y for x, y in zip(train_size, full_size)]):
return [train_size]
if num_levels is None:
size_ratio = np.array(full_size) / np.array(train_size)
num_levels = int(np.ceil(np.max(np.log2(size_ratio))) + 1)
if num_levels <= 1:
return [train_size]
h, w = full_size[0], full_size[1]
if h % 8 != 0 or w % 8 != 0:
print(
'Warning: output size is not a multiple of 8. Final layer '
+ 'will round size down.'
)
ll_h, ll_w = train_size[0], train_size[1]
sizes = []
for i in range(num_levels):
size = (
int(round((ll_h * (h / ll_h) ** (i / (num_levels - 1))) // 8)) * 8,
int(round((ll_w * (w / ll_w) ** (i / (num_levels - 1))) // 8)) * 8,
)
sizes.append(size)
return sizes
| tapnet-main | utils/model_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.
# ==============================================================================
"""Logging and other experiment utilities."""
import os
from typing import Mapping, Optional
import jax
from jaxline import utils
from ml_collections import config_dict
import numpy as np
import optax
import tensorflow as tf
from tapnet import optimizers
def get_lr_schedule(
total_steps: int,
optimizer_config: config_dict.ConfigDict,
) -> optax.Schedule:
"""Build the LR schedule function."""
base_lr = optimizer_config.base_lr
schedule_type = optimizer_config.schedule_type
if schedule_type == 'cosine':
warmup_steps = (optimizer_config.cosine_decay_kwargs.warmup_steps)
# Batch scale the other lr values as well:
init_value = optimizer_config.cosine_decay_kwargs.init_value
end_value = optimizer_config.cosine_decay_kwargs.end_value
schedule_fn = optax.warmup_cosine_decay_schedule(
init_value=init_value,
peak_value=base_lr,
warmup_steps=warmup_steps,
decay_steps=total_steps,
end_value=end_value)
elif schedule_type == 'constant_cosine':
# Convert end_value to alpha, used by cosine_decay_schedule.
alpha = optimizer_config.constant_cosine_decay_kwargs.end_value / base_lr
# Number of steps spent in constant phase.
constant_steps = int(
optimizer_config.constant_cosine_decay_kwargs.constant_fraction *
total_steps)
decay_steps = total_steps - constant_steps
constant_phase = optax.constant_schedule(value=base_lr)
decay_phase = optax.cosine_decay_schedule(
init_value=base_lr, decay_steps=decay_steps, alpha=alpha)
schedule_fn = optax.join_schedules(
schedules=[constant_phase, decay_phase], boundaries=[constant_steps])
else:
raise ValueError(f'Unknown learning rate schedule: {schedule_type}')
return schedule_fn
def make_optimizer(
optimizer_config: config_dict.ConfigDict,
lr_schedule: optax.Schedule,
) -> optax.GradientTransformation:
"""Construct the optax optimizer with given LR schedule."""
# Decay learned position embeddings by default.
weight_decay_exclude_names = ['b']
optax_chain = []
if optimizer_config.max_norm > 0:
optax_chain.append(optax.clip_by_global_norm(optimizer_config.max_norm))
if optimizer_config.optimizer == 'sgd':
optax_chain.extend([
optax.trace(**optimizer_config.sgd_kwargs),
optimizers.add_weight_decay(
optimizer_config.weight_decay,
exclude_names=weight_decay_exclude_names)
])
elif optimizer_config.optimizer == 'adam':
optax_chain.extend([
optax.scale_by_adam(**optimizer_config.adam_kwargs),
optimizers.add_weight_decay(
optimizer_config.weight_decay,
exclude_names=weight_decay_exclude_names)
])
else:
raise ValueError(f'Undefined optimizer {optimizer_config.optimizer}')
optax_chain.extend([
optax.scale_by_schedule(lr_schedule),
optax.scale(-1),
])
optimizer = optax.chain(*optax_chain)
optimizer = optax.apply_if_finite(optimizer, max_consecutive_errors=5)
return optimizer
class NumpyFileCheckpointer(utils.Checkpointer):
"""A Jaxline checkpointer which saves to numpy files on disk."""
def __init__(self, config: config_dict.ConfigDict, mode: str):
self._checkpoint_file = os.path.join(config.checkpoint_dir,
'checkpoint.npy')
self._checkpoint_state = config_dict.ConfigDict()
del mode
def get_experiment_state(self, ckpt_series: str) -> config_dict.ConfigDict:
"""Returns the experiment state for a given checkpoint series."""
if ckpt_series != 'latest':
raise ValueError('multiple checkpoint series are not supported')
return self._checkpoint_state
def save(self, ckpt_series: str) -> None:
"""Saves the checkpoint."""
if ckpt_series != 'latest':
raise ValueError('multiple checkpoint series are not supported')
exp_mod = self._checkpoint_state.experiment_module
global_step = self._checkpoint_state.global_step
f_np = lambda x: np.array(jax.device_get(utils.get_first(x)))
to_save = {}
for attr, name in exp_mod.CHECKPOINT_ATTRS.items():
if name == 'global_step':
raise ValueError(
'global_step attribute would overwrite jaxline global step')
np_params = jax.tree_map(f_np, getattr(exp_mod, attr))
to_save[name] = np_params
to_save['global_step'] = global_step
with tf.io.gfile.GFile(self._checkpoint_file + '_tmp', 'wb') as fp:
np.save(fp, to_save)
tf.io.gfile.rename(
self._checkpoint_file + '_tmp',
self._checkpoint_file,
overwrite=True,
)
def can_be_restored(self, ckpt_series: str) -> bool:
"""Returns whether or not a given checkpoint series can be restored."""
if ckpt_series != 'latest':
raise ValueError('multiple checkpoint series are not supported')
return tf.io.gfile.exists(self._checkpoint_file)
def restore(self, ckpt_series: str) -> None:
"""Restores the checkpoint."""
experiment_state = self.get_experiment_state(ckpt_series)
with tf.io.gfile.GFile(self._checkpoint_file, 'rb') as fp:
ckpt_state = np.load(fp, allow_pickle=True).item()
experiment_state.global_step = int(ckpt_state['global_step'])
exp_mod = experiment_state.experiment_module
for attr, name in exp_mod.CHECKPOINT_ATTRS.items():
setattr(exp_mod, attr, utils.bcast_local_devices(ckpt_state[name]))
def restore_path(self, ckpt_series: str) -> Optional[str]:
"""Returns the restore path for the checkpoint, or None."""
if not self.can_be_restored(ckpt_series):
return None
return self._checkpoint_file
def wait_for_checkpointing_to_finish(self) -> None:
"""Waits for any async checkpointing to complete."""
@classmethod
def create(
cls,
config: config_dict.ConfigDict,
mode: str,
) -> utils.Checkpointer:
return cls(config, mode)
def default_color_augmentation_fn(
inputs: Mapping[str, tf.Tensor]) -> Mapping[str, tf.Tensor]:
"""Standard color augmentation for videos.
Args:
inputs: A DatasetElement containing the item 'video' which will have
augmentations applied to it.
Returns:
A DatasetElement with all the same data as the original, except that
the video has augmentations applied.
"""
zero_centering_image = True
prob_color_augment = 0.8
prob_color_drop = 0.2
frames = inputs['video']
if frames.dtype != tf.float32:
raise ValueError('`frames` should be in float32.')
def color_augment(video: tf.Tensor) -> tf.Tensor:
"""Do standard color augmentations."""
# Note the same augmentation will be applied to all frames of the video.
if zero_centering_image:
video = 0.5 * (video + 1.0)
video = tf.image.random_brightness(video, max_delta=32. / 255.)
video = tf.image.random_saturation(video, lower=0.6, upper=1.4)
video = tf.image.random_contrast(video, lower=0.6, upper=1.4)
video = tf.image.random_hue(video, max_delta=0.2)
video = tf.clip_by_value(video, 0.0, 1.0)
if zero_centering_image:
video = 2 * (video-0.5)
return video
def color_drop(video: tf.Tensor) -> tf.Tensor:
video = tf.image.rgb_to_grayscale(video)
video = tf.tile(video, [1, 1, 1, 3])
return video
# Eventually applies color augmentation.
coin_toss_color_augment = tf.random.uniform(
[], minval=0, maxval=1, dtype=tf.float32)
frames = tf.cond(
pred=tf.less(coin_toss_color_augment,
tf.cast(prob_color_augment, tf.float32)),
true_fn=lambda: color_augment(frames),
false_fn=lambda: frames)
# Eventually applies color drop.
coin_toss_color_drop = tf.random.uniform(
[], minval=0, maxval=1, dtype=tf.float32)
frames = tf.cond(
pred=tf.less(coin_toss_color_drop, tf.cast(prob_color_drop, tf.float32)),
true_fn=lambda: color_drop(frames),
false_fn=lambda: frames)
result = {**inputs}
result['video'] = frames
return result
def add_default_data_augmentation(ds: tf.data.Dataset) -> tf.data.Dataset:
return ds.map(
default_color_augmentation_fn, num_parallel_calls=tf.data.AUTOTUNE)
| tapnet-main | utils/experiment_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.
# ==============================================================================
"""Utilities for transforming image coordinates."""
from typing import Sequence
import chex
import numpy as np
def convert_grid_coordinates(
coords: chex.Array,
input_grid_size: Sequence[int],
output_grid_size: Sequence[int],
coordinate_format: str = 'xy',
) -> chex.Array:
"""Convert image coordinates between image grids of different sizes.
By default, it assumes that the image corners are aligned. Therefore,
it adds .5 (since (0,0) is assumed to be the center of the upper-left grid
cell), multiplies by the size ratio, and then subtracts .5.
Args:
coords: The coordinates to be converted. It is of shape [..., 2] if
coordinate_format is 'xy' or [..., 3] if coordinate_format is 'tyx'.
input_grid_size: The size of the image/grid that the coordinates currently
are with respect to. This is a 2-tuple of the format [width, height]
if coordinate_format is 'xy' or a 3-tuple of the format
[num_frames, height, width] if coordinate_format is 'tyx'.
output_grid_size: The size of the target image/grid that you want the
coordinates to be with respect to. This is a 2-tuple of the format
[width, height] if coordinate_format is 'xy' or a 3-tuple of the format
[num_frames, height, width] if coordinate_format is 'tyx'.
coordinate_format: Which format the coordinates are in. This can be one
of 'xy' (the default) or 'tyx', which are the only formats used in this
project.
Returns:
The transformed coordinates, of the same shape as coordinates.
Raises:
ValueError: if coordinates don't match the given format.
"""
if isinstance(input_grid_size, tuple):
input_grid_size = np.array(input_grid_size)
if isinstance(output_grid_size, tuple):
output_grid_size = np.array(output_grid_size)
if coordinate_format == 'xy':
if input_grid_size.shape[0] != 2 or output_grid_size.shape[0] != 2:
raise ValueError(
'If coordinate_format is xy, the shapes must be length 2.')
elif coordinate_format == 'tyx':
if input_grid_size.shape[0] != 3 or output_grid_size.shape[0] != 3:
raise ValueError(
'If coordinate_format is tyx, the shapes must be length 3.')
if input_grid_size[0] != output_grid_size[0]:
raise ValueError('converting frame count is not supported.')
else:
raise ValueError('Recognized coordinate formats are xy and tyx.')
position_in_grid = coords
position_in_grid = position_in_grid * output_grid_size / input_grid_size
return position_in_grid
| tapnet-main | utils/transforms.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.
# ==============================================================================
"""Visualization utility functions."""
import colorsys
import random
from typing import List, Optional, Sequence, Tuple
from absl import logging
import matplotlib.pyplot as plt
import mediapy as media
import numpy as np
# Generate random colormaps for visualizing different points.
def get_colors(num_colors: int) -> List[Tuple[int, int, int]]:
"""Gets colormap for points."""
colors = []
for i in np.arange(0.0, 360.0, 360.0 / num_colors):
hue = i / 360.0
lightness = (50 + np.random.rand() * 10) / 100.0
saturation = (90 + np.random.rand() * 10) / 100.0
color = colorsys.hls_to_rgb(hue, lightness, saturation)
colors.append(
(int(color[0] * 255), int(color[1] * 255), int(color[2] * 255))
)
random.shuffle(colors)
return colors
def paint_point_track(
frames: np.ndarray,
point_tracks: np.ndarray,
visibles: np.ndarray,
colormap: Optional[List[Tuple[int, int, int]]] = None,
) -> np.ndarray:
"""Converts a sequence of points to color code video.
Args:
frames: [num_frames, height, width, 3], np.uint8, [0, 255]
point_tracks: [num_points, num_frames, 2], np.float32, [0, width / height]
visibles: [num_points, num_frames], bool
colormap: colormap for points, each point has a different RGB color.
Returns:
video: [num_frames, height, width, 3], np.uint8, [0, 255]
"""
num_points, num_frames = point_tracks.shape[0:2]
if colormap is None:
colormap = get_colors(num_colors=num_points)
height, width = frames.shape[1:3]
dot_size_as_fraction_of_min_edge = 0.015
radius = int(round(min(height, width) * dot_size_as_fraction_of_min_edge))
diam = radius * 2 + 1
quadratic_y = np.square(np.arange(diam)[:, np.newaxis] - radius - 1)
quadratic_x = np.square(np.arange(diam)[np.newaxis, :] - radius - 1)
icon = (quadratic_y + quadratic_x) - (radius**2) / 2.0
sharpness = 0.15
icon = np.clip(icon / (radius * 2 * sharpness), 0, 1)
icon = 1 - icon[:, :, np.newaxis]
icon1 = np.pad(icon, [(0, 1), (0, 1), (0, 0)])
icon2 = np.pad(icon, [(1, 0), (0, 1), (0, 0)])
icon3 = np.pad(icon, [(0, 1), (1, 0), (0, 0)])
icon4 = np.pad(icon, [(1, 0), (1, 0), (0, 0)])
video = frames.copy()
for t in range(num_frames):
# Pad so that points that extend outside the image frame don't crash us
image = np.pad(
video[t],
[
(radius + 1, radius + 1),
(radius + 1, radius + 1),
(0, 0),
],
)
for i in range(num_points):
# The icon is centered at the center of a pixel, but the input coordinates
# are raster coordinates. Therefore, to render a point at (1,1) (which
# lies on the corner between four pixels), we need 1/4 of the icon placed
# centered on the 0'th row, 0'th column, etc. We need to subtract
# 0.5 to make the fractional position come out right.
x, y = point_tracks[i, t, :] + 0.5
x = min(max(x, 0.0), width)
y = min(max(y, 0.0), height)
if visibles[i, t]:
x1, y1 = np.floor(x).astype(np.int32), np.floor(y).astype(np.int32)
x2, y2 = x1 + 1, y1 + 1
# bilinear interpolation
patch = (
icon1 * (x2 - x) * (y2 - y)
+ icon2 * (x2 - x) * (y - y1)
+ icon3 * (x - x1) * (y2 - y)
+ icon4 * (x - x1) * (y - y1)
)
x_ub = x1 + 2 * radius + 2
y_ub = y1 + 2 * radius + 2
image[y1:y_ub, x1:x_ub, :] = (1 - patch) * image[
y1:y_ub, x1:x_ub, :
] + patch * np.array(colormap[i])[np.newaxis, np.newaxis, :]
# Remove the pad
video[t] = image[
radius + 1 : -radius - 1, radius + 1 : -radius - 1
].astype(np.uint8)
return video
def plot_tracks_v2(
rgb: np.ndarray,
points: np.ndarray,
occluded: np.ndarray,
gt_points: Optional[np.ndarray] = None,
gt_occluded: Optional[np.ndarray] = None,
trackgroup: Optional[np.ndarray] = None,
) -> np.ndarray:
"""Plot tracks with matplotlib."""
disp = []
cmap = plt.cm.hsv # pytype: disable=module-attr
z_list = (
np.arange(points.shape[0]) if trackgroup is None else np.array(trackgroup)
)
# random permutation of the colors so nearby points in the list can get
# different colors
z_list = np.random.permutation(np.max(z_list) + 1)[z_list]
colors = cmap(z_list / (np.max(z_list) + 1))
figure_dpi = 64
figs = []
for i in range(rgb.shape[0]):
fig = plt.figure(
figsize=(256 / figure_dpi, 256 / figure_dpi),
dpi=figure_dpi,
frameon=False,
facecolor='w',
)
figs.append(fig)
ax = fig.add_subplot()
ax.axis('off')
ax.imshow(rgb[i] / 255.0)
colalpha = np.concatenate(
[colors[:, :-1], 1 - occluded[:, i : i + 1]], axis=1
)
plt.scatter(points[:, i, 0], points[:, i, 1], s=9, c=colalpha)
occ2 = occluded[:, i : i + 1]
if gt_occluded is not None:
occ2 *= 1 - gt_occluded[:, i : i + 1]
colalpha = np.concatenate([colors[:, :-1], occ2], axis=1)
if gt_points is not None:
colalpha = np.concatenate(
[colors[:, :-1], 1 - gt_occluded[:, i : i + 1]], axis=1
)
plt.scatter(
gt_points[:, i, 0], gt_points[:, i, 1], s=15, c=colalpha, marker='D'
)
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
plt.margins(0, 0)
fig.canvas.draw()
width, height = fig.get_size_inches() * fig.get_dpi()
img = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8').reshape(
int(height), int(width), 3
)
disp.append(np.copy(img))
for fig in figs:
plt.close(fig)
return np.stack(disp, axis=0)
def plot_tracks_v3(
rgb: np.ndarray,
points: np.ndarray,
occluded: np.ndarray,
gt_points: np.ndarray,
gt_occluded: np.ndarray,
trackgroup: Optional[np.ndarray] = None,
) -> np.ndarray:
"""Plot tracks in a 2x2 grid."""
if trackgroup is None:
trackgroup = np.arange(points.shape[0])
else:
trackgroup = np.array(trackgroup)
utg = np.unique(trackgroup)
chunks = np.array_split(utg, 4)
plots = []
for ch in chunks:
valid = np.any(trackgroup[:, np.newaxis] == ch[np.newaxis, :], axis=1)
new_trackgroup = np.argmax(
trackgroup[valid][:, np.newaxis] == ch[np.newaxis, :], axis=1
)
plots.append(
plot_tracks_v2(
rgb,
points[valid],
occluded[valid],
None if gt_points is None else gt_points[valid],
None if gt_points is None else gt_occluded[valid],
new_trackgroup,
)
)
p1 = np.concatenate(plots[0:2], axis=2)
p2 = np.concatenate(plots[2:4], axis=2)
return np.concatenate([p1, p2], axis=1)
def write_visualization(
video: np.ndarray,
points: np.ndarray,
occluded: np.ndarray,
visualization_path: Sequence[str],
gt_points: Optional[np.ndarray] = None,
gt_occluded: Optional[np.ndarray] = None,
trackgroup: Optional[np.ndarray] = None,
):
"""Write a visualization."""
for i in range(video.shape[0]):
logging.info('rendering...')
video_frames = plot_tracks_v2(
video[i],
points[i],
occluded[i],
gt_points[i] if gt_points is not None else None,
gt_occluded[i] if gt_occluded is not None else None,
trackgroup[i] if trackgroup is not None else None,
)
logging.info('writing...')
with media.VideoWriter(
visualization_path[i],
shape=video_frames.shape[-3:-1],
fps=5,
codec='h264',
bps=600000,
) as video_writer:
for j in range(video_frames.shape[0]):
fr = video_frames[j]
video_writer.add_image(fr.astype(np.uint8))
| tapnet-main | utils/viz_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.
# ==============================================================================
"""Utils functions for TSM."""
from typing import Tuple
import chex
import jax
import jax.numpy as jnp
def prepare_inputs(inputs: chex.Array) -> Tuple[jnp.ndarray, str, int]:
"""Deduces input mode for TSM."""
# Deduce if we run on TPU based on input shape.
if len(inputs.shape) == 5:
# Input is given in the standard [B, T, H, W, 3] format.
tsm_mode = 'gpu'
num_frames = inputs.shape[1]
inputs = jnp.reshape(inputs, [-1] + list(inputs.shape[2:]))
else:
# Input is given in the [T * B, H, W, 3] format.
tsm_mode = 'tpu'
num_frames = None
return inputs, tsm_mode, num_frames
def prepare_outputs(
outputs: chex.Array,
tsm_mode: str,
num_frames: int,
reduce_mean: bool = True,
) -> jnp.ndarray:
"""Processes output of TSM to undo the merging of batch and time."""
# Get the shape without the batch/time dimension (for TSM batch and time are
# merged in the first dimension).
shape_no_bt = list(outputs.shape[1:])
if tsm_mode == 'tpu':
# Outputs are of the shape [num_frames * B, ..., n_channels]
outputs = jnp.reshape(outputs, [num_frames, -1] + shape_no_bt)
if reduce_mean:
# We average over time and space.
outputs = jnp.mean(
outputs, axis=[0] + list(range(2,
len(shape_no_bt) + 1)))
else:
outputs = jnp.transpose(
outputs, axes=[1, 0] + list(range(2,
len(shape_no_bt) + 2)))
elif tsm_mode == 'gpu':
# Outputs are of the shape [B * num_frames, ..., n_channels].
outputs = jnp.reshape(outputs, [-1, num_frames] + shape_no_bt)
if reduce_mean:
outputs = jnp.mean(
outputs, axis=[1] + list(range(2,
len(shape_no_bt) + 1)))
elif tsm_mode.startswith('deflated'):
# In deflated mode, outputs are already in the right format.
pass
else:
raise ValueError('`tsm_mode` should be \'tpu\' or \'gpu\' or '
f'\'deflated_0.x\' ({tsm_mode} given)')
return outputs # pytype: disable=bad-return-type # numpy-scalars
def apply_temporal_shift(
x: chex.Array,
tsm_mode: str,
num_frames: int,
channel_shift_fraction: float = 0.125,
) -> jnp.ndarray:
"""Performs a temporal shift: https://arxiv.org/abs/1811.08383 with mode."""
if tsm_mode == 'tpu':
outputs = temporal_shift_tpu(x, num_frames, channel_shift_fraction)
elif tsm_mode == 'gpu':
outputs = temporal_shift_gpu(x, num_frames, channel_shift_fraction)
elif tsm_mode.startswith('deflated'):
alpha = float(tsm_mode.split('_')[1])
outputs = temporal_shift_image_mode(x, channel_shift_fraction, alpha)
else:
raise ValueError('`tsm_mode` should be \'tpu\' or \'gpu\' or '
f'\'deflated_0.x\' ({tsm_mode} given)')
return outputs
def temporal_shift_image_mode(x, channel_shift_fraction=0.125, alpha=0.3):
"""Temporal shift applied on single image (to emulate a fixed video)."""
# B, H, W, C = batch_size, im_height, im_width, channels.
# Input is (B, H, W, C).
orig_shp = tuple(x.shape)
n_channels = orig_shp[-1]
n_shift = int(n_channels * channel_shift_fraction)
# Alpha emulates the effect of the padding when using a single frame.
shifted_backward = alpha * x[:, :, :, -n_shift:]
shifted_forward = alpha * x[:, :, :, :n_shift]
no_shift = x[:, :, :, n_shift:-n_shift]
shifted_x = jnp.concatenate([shifted_backward, no_shift, shifted_forward],
axis=3)
return shifted_x
def temporal_shift_gpu(
x: chex.Array,
num_frames: int,
channel_shift_fraction: float = 0.125,
) -> jnp.ndarray:
"""Performs a temporal shift: https://arxiv.org/abs/1811.08383."""
# B, T, H, W, C = batch_size, num_frames, im_height, im_width, channels.
# Input is (B * T, H, W, C).
orig_shp = tuple(x.shape)
reshaped_x = jnp.reshape(x, (-1, num_frames) + orig_shp[1:])
n_channels = orig_shp[-1]
n_shift = int(n_channels * channel_shift_fraction)
new_shp = tuple(reshaped_x.shape)
# shifted_backward = reshaped_x[:, 1:, :, :, -n_shift:].
shifted_backward = jax.lax.slice(
reshaped_x, (0, 1, 0, 0, new_shp[4] - n_shift),
(new_shp[0], new_shp[1], new_shp[2], new_shp[3], new_shp[4]))
shifted_backward_padding = ((0, 0), (0, 1), (0, 0), (0, 0), (0, 0))
shifted_backward = jnp.pad(shifted_backward, shifted_backward_padding)
# shifted_forward = reshaped_x[:, :-1, :, :, :n_shift].
shifted_forward = jax.lax.slice(
reshaped_x, (0, 0, 0, 0, 0),
(new_shp[0], new_shp[1] - 1, new_shp[2], new_shp[3], n_shift))
shifted_forward_padding = ((0, 0), (1, 0), (0, 0), (0, 0), (0, 0))
shifted_forward = jnp.pad(shifted_forward, shifted_forward_padding)
no_shift = reshaped_x[:, :, :, :, n_shift:-n_shift]
shifted_x = jnp.concatenate([shifted_backward, no_shift, shifted_forward],
axis=4)
return jnp.reshape(shifted_x, (-1,) + orig_shp[1:])
def temporal_shift_tpu(
x: chex.Array,
num_frames: int,
channel_shift_fraction: float = 0.125,
) -> jnp.ndarray:
"""Performs a temporal shift: https://arxiv.org/abs/1811.08383.
TPU optimized version of TSM. Reshape is avoided by having the images
reshaped in [T * B, :] so that frames corresponding to same time frame in
videos are contiguous in memory. Finally, to avoid concatenate that prevent
some fusion from happening we simply sum masked version of the features.
Args:
x: Input expected to be [T * B, H, W, C] (where the batch has been reshaped
from a time major version of the input).
num_frames: number of frames T per video.
channel_shift_fraction: fraction of the channel to shift forward and
backward.
Returns:
The temporal shifted version of x.
"""
# B, T, H, W, C = batch_size, num_frames, im_height, im_width, channels.
# Input is (T * B, H, W, C).
original_dtype = x.dtype
original_shape = list(x.shape)
batch_size = int(original_shape[0] / num_frames)
n_channels = int(original_shape[-1])
n_shift = int(n_channels * channel_shift_fraction)
# Cast to bfloat16.
x = x.astype(jnp.bfloat16)
# For the following, assume that x has 3 channels [x1, x2, x3] and n_shift=1.
# Shift backward, we first pad by zeros [x1, x2, x3, 0, 0].
orig_shp = list(x.shape)
shifted_backward_padding = ((0, batch_size, 0), (0, 0, 0), (0, 0, 0),
(0, n_channels - n_shift, 0))
x_backward_padding = jax.lax.pad(
x,
padding_value=jnp.bfloat16(0.),
padding_config=shifted_backward_padding)
# The following shift gets to [x3^+1, 0, 0] (where +1 means from the future).
shifted_backward = jax.lax.slice(x_backward_padding,
(batch_size, 0, 0, n_channels - n_shift),
(orig_shp[0] + batch_size, orig_shp[1],
orig_shp[2], 2 * n_channels - n_shift))
# Shift forward, we first pad by zeros [0, 0, x1, x2, x3].
shifted_forward_padding = ((batch_size, 0, 0), (0, 0, 0), (0, 0, 0),
(n_channels - n_shift, 0, 0))
x_forward_padding = jax.lax.pad(
x, padding_value=jnp.bfloat16(0.), padding_config=shifted_forward_padding)
# The following shift gets to [0, 0, x1^-1] (where -1 means from the past).
shifted_forward = jax.lax.slice(
x_forward_padding, (0, 0, 0, 0),
(orig_shp[0], orig_shp[1], orig_shp[2], n_channels))
# No shift is in the middle, this gets [0, x2, 0].
mask_noshift = (jnp.reshape((jnp.arange(n_channels) >= n_shift) &
(jnp.arange(n_channels) < n_channels - n_shift),
(1, 1, 1, -1))).astype(jnp.bfloat16)
no_shift = mask_noshift * x
# By summing everything together, we end up with [x3^+1, x2, x1^-1].
# Note: channels have been reordered but that doesn't matter for the model.
shifted_x = shifted_backward + shifted_forward + no_shift
return shifted_x.astype(original_dtype)
| tapnet-main | models/tsm_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.
# ==============================================================================
"""Temporal Shift Module w/ ResNet-50 and ResNet-101.
Based on:
TSM: Temporal Shift Module for Efficient Video Understanding
Ji Lin, Chuang Gan, Song Han
https://arxiv.org/pdf/1811.08383.pdf.
"""
from typing import Optional, Sequence, Union
from absl import logging
import chex
import haiku as hk
import jax
import jax.numpy as jnp
import typing_extensions
from tapnet.models import tsm_utils as tsmu
class NormalizeFn(typing_extensions.Protocol):
def __call__(self, x: chex.Array, is_training: bool) -> chex.Array:
pass
class TSMResNetBlock(hk.Module):
"""A ResNet subblock with Temporal Channel Shifting.
Combines a typical ResNetV2 block implementation
(see https://arxiv.org/abs/1512.03385) with a pre-convolution Temporal
Shift Module (see https://arxiv.org/pdf/1811.08383.pdf) in the residual.
"""
def __init__(
self,
output_channels: int,
stride: int,
use_projection: bool,
tsm_mode: str,
normalize_fn: Optional[NormalizeFn] = None,
channel_shift_fraction: float = 0.125,
num_frames: int = 8,
rate: int = 1,
use_bottleneck: bool = False,
name: str = 'TSMResNetBlock',
):
"""Initializes the TSMResNetBlock module.
Args:
output_channels: Number of output channels.
stride: Stride used in convolutions.
use_projection: Whether to use a projection for the shortcut.
tsm_mode: Mode for TSM ('gpu' or 'tpu' or 'deflated_0.x').
normalize_fn: Function used for normalization.
channel_shift_fraction: The fraction of temporally shifted channels. If
`channel_shift_fraction` is 0, the block is the same as a normal ResNet
block.
num_frames: Size of frame dimension in a single batch example.
rate: dilation rate.
use_bottleneck: use a bottleneck (resnet-50 and above),
name: The name of the module.
"""
super().__init__(name=name)
self._output_channels = (
output_channels if use_bottleneck else output_channels // 4)
self._bottleneck_channels = output_channels // 4
self._stride = stride
self._rate = rate
self._use_projection = use_projection
self._normalize_fn = normalize_fn
self._tsm_mode = tsm_mode
self._channel_shift_fraction = channel_shift_fraction
self._num_frames = num_frames
self._use_bottleneck = use_bottleneck
def __call__(
self,
inputs: chex.Array,
is_training: bool = True,
) -> chex.Array:
"""Connects the ResNetBlock module into the graph.
Args:
inputs: A 4-D float array of shape `[B, H, W, C]`.
is_training: Whether to use training mode.
Returns:
A 4-D float array of shape
`[B * num_frames, new_h, new_w, output_channels]`.
"""
# ResNet V2 uses pre-activation, where the batch norm and relu are before
# convolutions, rather than after as in ResNet V1.
preact = inputs
if self._normalize_fn is not None:
preact = self._normalize_fn(preact, is_training=is_training)
preact = jax.nn.relu(preact)
if self._use_projection:
shortcut = hk.Conv2D(
output_channels=self._output_channels,
kernel_shape=1,
stride=self._stride,
with_bias=False,
padding='SAME',
name='shortcut_conv',
)(preact)
else:
shortcut = inputs
# Eventually applies Temporal Shift Module.
if self._channel_shift_fraction != 0:
preact = tsmu.apply_temporal_shift(
preact,
tsm_mode=self._tsm_mode,
num_frames=self._num_frames,
channel_shift_fraction=self._channel_shift_fraction)
# First convolution.
residual = hk.Conv2D(
self._bottleneck_channels,
kernel_shape=1 if self._use_bottleneck else 3,
stride=1 if self._use_bottleneck else self._stride,
with_bias=False,
padding='SAME',
name='conv_0',
)(preact)
if self._use_bottleneck:
# Second convolution.
if self._normalize_fn is not None:
residual = self._normalize_fn(residual, is_training=is_training)
residual = jax.nn.relu(residual)
residual = hk.Conv2D(
output_channels=self._bottleneck_channels,
kernel_shape=3,
stride=self._stride,
rate=self._rate,
with_bias=False,
padding='SAME',
name='conv_1',
)(residual)
# Third convolution.
if self._normalize_fn is not None:
residual = self._normalize_fn(residual, is_training=is_training)
residual = jax.nn.relu(residual)
residual = hk.Conv2D(
output_channels=self._output_channels,
kernel_shape=1 if self._use_bottleneck else 3,
stride=1,
with_bias=False,
padding='SAME',
name='conv_2',
)(residual)
# NOTE: we do not use block multiplier.
output = shortcut + residual
return output
class TSMResNetUnit(hk.Module):
"""Block group for TSM ResNet."""
def __init__(
self,
output_channels: int,
num_blocks: int,
stride: int,
tsm_mode: str,
num_frames: int,
normalize_fn: Optional[NormalizeFn] = None,
channel_shift_fraction: float = 0.125,
rate: int = 1,
use_bottleneck: bool = False,
name: str = 'tsm_resnet_unit',
):
"""Creates a TSMResNet Unit.
Args:
output_channels: Number of output channels.
num_blocks: Number of ResNet blocks in the unit.
stride: Stride of the unit.
tsm_mode: Which temporal shift module to use.
num_frames: Size of frame dimension in a single batch example.
normalize_fn: Function used for normalization.
channel_shift_fraction: The fraction of temporally shifted channels. If
`channel_shift_fraction` is 0, the block is the same as a normal ResNet
block.
rate: dilation rate.
use_bottleneck: use a bottleneck (resnet-50 and above).
name: The name of the module.
"""
super().__init__(name=name)
self._output_channels = output_channels
self._num_blocks = num_blocks
self._normalize_fn = normalize_fn
self._stride = stride
self._tsm_mode = tsm_mode
self._channel_shift_fraction = channel_shift_fraction
self._num_frames = num_frames
self._rate = rate
self._use_bottleneck = use_bottleneck
def __call__(
self,
inputs: chex.Array,
is_training: bool,
) -> chex.Array:
"""Connects the module to inputs.
Args:
inputs: A 4-D float array of shape `[B * num_frames, H, W, C]`.
is_training: Whether to use training mode.
Returns:
A 4-D float array of shape
`[B * num_frames, H // stride, W // stride, output_channels]`.
"""
net = inputs
for idx_block in range(self._num_blocks):
net = TSMResNetBlock(
self._output_channels,
stride=(self._stride if idx_block == 0 else 1),
rate=(max(self._rate // 2, 1) if idx_block == 0 else self._rate),
use_projection=(idx_block == 0),
normalize_fn=self._normalize_fn,
tsm_mode=self._tsm_mode,
channel_shift_fraction=self._channel_shift_fraction,
num_frames=self._num_frames,
name=f'block_{idx_block}',
)(net, is_training=is_training)
return net
class TSMResNetV2(hk.Module):
"""TSM based on ResNet V2 as described in https://arxiv.org/abs/1603.05027."""
# Endpoints of the model in order.
VALID_ENDPOINTS = (
'tsm_resnet_stem',
'tsm_resnet_unit_0',
'tsm_resnet_unit_1',
'tsm_resnet_unit_2',
'tsm_resnet_unit_3',
'last_conv',
'Embeddings',
)
def __init__(
self,
normalize_fn: Optional[NormalizeFn] = None,
depth: int = 18,
num_frames: int = 16,
channel_shift_fraction: Union[float, Sequence[float]] = 0.125,
width_mult: int = 1,
name: str = 'TSMResNetV2',
):
"""Constructs a ResNet model.
Args:
normalize_fn: Function used for normalization.
depth: Depth of the desired ResNet.
num_frames: Number of frames (used in TPU mode).
channel_shift_fraction: Fraction of channels that are temporally shifted,
if `channel_shift_fraction` is 0, a regular ResNet is returned.
width_mult: Whether or not to use a width multiplier.
name: The name of the module.
Raises:
ValueError: If `channel_shift_fraction` or `depth` has invalid value.
"""
super().__init__(name=name)
if isinstance(channel_shift_fraction, float):
channel_shift_fraction = [channel_shift_fraction] * 4
if not all([0. <= x <= 1.0 for x in channel_shift_fraction]):
raise ValueError(f'channel_shift_fraction ({channel_shift_fraction})'
' all have to be in [0, 1].')
self._num_frames = num_frames
self._channels = (256, 512, 1024, 2048)
num_blocks = {
18: (2, 2, 2, 2),
34: (3, 4, 6, 3),
50: (3, 4, 6, 3),
101: (3, 4, 23, 3),
152: (3, 8, 36, 3),
200: (3, 24, 36, 3),
}
if depth not in num_blocks:
raise ValueError(
f'`depth` should be in {list(num_blocks.keys())} ({depth} given).')
self._num_blocks = num_blocks[depth]
self._width_mult = width_mult
self._channel_shift_fraction = channel_shift_fraction
self._normalize_fn = normalize_fn
self._use_bottleneck = (depth >= 50)
def __call__(
self,
inputs: chex.Array,
is_training: bool = True,
final_endpoint: str = 'Embeddings',
is_deflated: bool = False,
alpha_deflation: float = 0.3,
out_num_frames: Optional[int] = None,
output_stride: int = 8,
) -> chex.Array:
"""Connects the TSM ResNetV2 module into the graph.
Args:
inputs: The input may be in one of two shapes; if the shape is `[B, T, H,
W, C]`, this module assumes the backend is a GPU (setting
`tsm_mode='gpu'`) and `T` is treated the time dimension, with `B` being
the batch dimension. This mode cannot be used when `is_deflated` is
`true`. In this mode, the num_frames parameter passed to the constructor
is ignored. If the shape is `[B, H, W, C]`, then the batch dimension is
assumed to be of the form [B*T, H, W, C], where `T` is the number of
frames in each video. This value may be set by passing `num_frames=n` to
the constructor. The default value is `n=16` (beware this default is not
the same as the default for the `TSMResNetBlock`, which has a default of
8 frames). In this case, the module assumes it is being run on a TPU,
and emits instructions that are more efficient for that case,
using`tsm_mode`='tpu'` for the downstream blocks.
is_training: Whether to use training mode.
final_endpoint: Up to which endpoint to run / return.
is_deflated: Whether or not to use the deflated version of the network.
alpha_deflation: Deflation parameter to use for dealing with the padding
effect.
out_num_frames: Whether time is on first axis, for TPU performance
output_stride: Stride of the final feature grid; possible values are
4, 8, 16, or 32. 32 is the standard for TSM-ResNet. Others strides are
achieved by converting strided to un-strided convolutions later in the
network, while increasing the dilation rate for later layers.
Returns:
Network output at location `final_endpoint`. A float array which shape
depends on `final_endpoint`.
Raises:
ValueError: If `final_endpoint` is not recognized.
"""
# Prepare inputs for TSM.
if is_deflated:
if len(inputs.shape) != 4:
raise ValueError(
'In deflated mode inputs should be given as [B, H, W, 3]')
logging.warning(
'Deflation is an experimental feature and the API might change.')
tsm_mode = f'deflated_{alpha_deflation}'
num_frames = 1
else:
inputs, tsm_mode, num_frames = tsmu.prepare_inputs(inputs)
num_frames = num_frames or out_num_frames or self._num_frames
self._final_endpoint = final_endpoint
if self._final_endpoint not in self.VALID_ENDPOINTS:
raise ValueError(f'Unknown final endpoint {self._final_endpoint}')
# Stem convolution.
end_point = 'tsm_resnet_stem'
net = hk.Conv2D(
output_channels=64 * self._width_mult,
kernel_shape=7,
stride=2,
with_bias=False,
name=end_point,
padding='SAME',
)(inputs)
net = hk.MaxPool(
window_shape=(1, 3, 3, 1),
strides=(1, 2, 2, 1),
padding='SAME',
)(net)
if self._final_endpoint == end_point:
net = tsmu.prepare_outputs(net, tsm_mode, num_frames, reduce_mean=False)
return net
if output_stride == 4:
strides = (1, 1, 1, 1)
rates = (1, 2, 4, 8)
elif output_stride == 8:
strides = (1, 2, 1, 1)
rates = (1, 1, 2, 4)
elif output_stride == 16:
strides = (1, 2, 2, 1)
rates = (1, 1, 1, 2)
elif output_stride == 32:
strides = (1, 2, 2, 2)
rates = (1, 1, 1, 1)
else:
raise ValueError('unsupported output stride')
# Residual block.
for unit_id, (channels, num_blocks, stride, rate) in enumerate(
zip(self._channels, self._num_blocks, strides, rates)):
end_point = f'tsm_resnet_unit_{unit_id}'
net = TSMResNetUnit(
output_channels=channels * self._width_mult,
num_blocks=num_blocks,
stride=stride,
rate=rate,
normalize_fn=self._normalize_fn,
channel_shift_fraction=self._channel_shift_fraction[unit_id],
num_frames=num_frames,
tsm_mode=tsm_mode,
use_bottleneck=self._use_bottleneck,
name=end_point,
)(net, is_training=is_training)
if self._final_endpoint == end_point:
net = tsmu.prepare_outputs(net, tsm_mode, num_frames, reduce_mean=False)
return net
if self._normalize_fn is not None:
net = self._normalize_fn(net, is_training=is_training)
net = jax.nn.relu(net)
end_point = 'last_conv'
if self._final_endpoint == end_point:
net = tsmu.prepare_outputs(net, tsm_mode, num_frames, reduce_mean=False)
return net
net = jnp.mean(net, axis=(1, 2))
# Prepare embedding outputs for TSM (temporal average of features).
net = tsmu.prepare_outputs(net, tsm_mode, num_frames, reduce_mean=True)
assert self._final_endpoint == 'Embeddings'
return net
| tapnet-main | models/tsm_resnet.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.
# ==============================================================================
"""ResNet with BatchNorm, LayerNorm, InstanceNorm or None."""
from typing import Mapping, Optional, Sequence, Union
import haiku as hk
import jax
FloatStrOrBool = Union[str, float, bool]
class BlockV1(hk.Module):
"""ResNet V1 block with optional bottleneck."""
def __init__(
self,
channels: int,
stride: Union[int, Sequence[int]],
use_projection: bool,
bn_config: Mapping[str, FloatStrOrBool],
bottleneck: bool,
normalization: Optional[str] = None,
name: Optional[str] = None,
):
super().__init__(name=name)
self.use_projection = use_projection
self.normalization = normalization
if normalization == "batchnorm":
bn_config = dict(bn_config)
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
bn_config.setdefault("decay_rate", 0.9)
bn_config.setdefault("cross_replica_axis", "i")
elif normalization == "layernorm":
bn_config = dict(bn_config)
bn_config.setdefault("axis", [-1, -2, -3])
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
elif normalization == "instancenorm":
bn_config = dict(bn_config)
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
if self.use_projection:
self.proj_conv = hk.Conv2D(
output_channels=channels,
kernel_shape=1,
stride=stride,
with_bias=False,
padding="SAME",
name="shortcut_conv")
if normalization == "batchnorm":
self.proj_batchnorm = hk.BatchNorm(
name="shortcut_batchnorm", **bn_config
)
elif normalization == "layernorm":
self.proj_norm = hk.LayerNorm(name="shortcut_layernorm", **bn_config)
elif normalization == "instancenorm":
self.proj_norm = hk.InstanceNorm(
name="shortcut_instancenorm", **bn_config
)
channel_div = 4 if bottleneck else 1
conv_0 = hk.Conv2D(
output_channels=channels // channel_div,
kernel_shape=1 if bottleneck else 3,
stride=1 if bottleneck else stride,
with_bias=False,
padding="SAME",
name="conv_0")
if normalization == "batchnorm":
bn_0 = hk.BatchNorm(name="batchnorm_0", **bn_config)
elif normalization == "layernorm":
bn_0 = hk.LayerNorm(name="layernorm_0", **bn_config)
elif normalization == "instancenorm":
bn_0 = hk.InstanceNorm(name="instancenorm_0", **bn_config)
conv_1 = hk.Conv2D(
output_channels=channels // channel_div,
kernel_shape=3,
stride=stride if bottleneck else 1,
with_bias=False,
padding="SAME",
name="conv_1")
if normalization == "batchnorm":
bn_1 = hk.BatchNorm(name="batchnorm_1", **bn_config)
elif normalization == "layernorm":
bn_1 = hk.LayerNorm(name="layernorm_1", **bn_config)
elif normalization == "instancenorm":
bn_1 = hk.InstanceNorm(name="instancenorm_1", **bn_config)
layers = ((conv_0, bn_0), (conv_1, bn_1))
if bottleneck:
conv_2 = hk.Conv2D(
output_channels=channels,
kernel_shape=1,
stride=1,
with_bias=False,
padding="SAME",
name="conv_2")
if normalization == "batchnorm":
bn_2 = hk.BatchNorm(name="batchnorm_2", **bn_config)
elif normalization == "layernorm":
bn_2 = hk.LayerNorm(name="layernorm_2", **bn_config)
elif normalization == "instancenorm":
bn_2 = hk.InstanceNorm(name="instancenorm_2", **bn_config)
layers = layers + ((conv_2, bn_2),)
self.layers = layers
def __call__(self, inputs, is_training, test_local_stats):
out = shortcut = inputs
if self.use_projection:
shortcut = self.proj_conv(shortcut)
if self.normalization == "batchnorm":
shortcut = self.proj_batchnorm(shortcut, is_training, test_local_stats)
elif self.normalization in ["layernorm", "instancenorm"]:
shortcut = self.proj_norm(shortcut)
for i, (conv_i, bn_i) in enumerate(self.layers):
out = conv_i(out)
if self.normalization == "batchnorm":
out = bn_i(out, is_training, test_local_stats)
elif self.normalization in ["layernorm", "instancenorm"]:
out = bn_i(out)
if i < len(self.layers) - 1: # Don't apply relu on last layer
out = jax.nn.relu(out)
return jax.nn.relu(out + shortcut)
class BlockV2(hk.Module):
"""ResNet V2 block with optional bottleneck."""
def __init__(
self,
channels: int,
stride: Union[int, Sequence[int]],
use_projection: bool,
bn_config: Mapping[str, FloatStrOrBool],
bottleneck: bool,
normalization: Optional[str] = None,
name: Optional[str] = None,
):
super().__init__(name=name)
self.use_projection = use_projection
self.normalization = normalization
bn_config = dict(bn_config)
if normalization == "batchnorm":
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
bn_config.setdefault("decay_rate", 0.9)
bn_config.setdefault("cross_replica_axis", "i")
elif normalization == "layernorm":
bn_config.setdefault("axis", [-1, -2, -3])
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
elif normalization == "instancenorm":
bn_config = dict(bn_config)
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
if self.use_projection:
self.proj_conv = hk.Conv2D(
output_channels=channels,
kernel_shape=1,
stride=stride,
with_bias=False,
padding="SAME",
name="shortcut_conv")
channel_div = 4 if bottleneck else 1
conv_0 = hk.Conv2D(
output_channels=channels // channel_div,
kernel_shape=1 if bottleneck else 3,
stride=1 if bottleneck else stride,
with_bias=False,
padding="SAME",
name="conv_0")
if normalization == "batchnorm":
bn_0 = hk.BatchNorm(name="batchnorm_0", **bn_config)
elif normalization == "layernorm":
bn_0 = hk.LayerNorm(name="layernorm_0", **bn_config)
elif normalization == "instancenorm":
bn_0 = hk.InstanceNorm(name="instancenorm_0", **bn_config)
conv_1 = hk.Conv2D(
output_channels=channels // channel_div,
kernel_shape=3,
stride=stride if bottleneck else 1,
with_bias=False,
padding="SAME",
name="conv_1")
if normalization == "batchnorm":
bn_1 = hk.BatchNorm(name="batchnorm_1", **bn_config)
elif normalization == "layernorm":
bn_1 = hk.LayerNorm(name="layernorm_1", **bn_config)
elif normalization == "instancenorm":
bn_1 = hk.InstanceNorm(name="instancenorm_1", **bn_config)
layers = ((conv_0, bn_0), (conv_1, bn_1))
if bottleneck:
conv_2 = hk.Conv2D(
output_channels=channels,
kernel_shape=1,
stride=1,
with_bias=False,
padding="SAME",
name="conv_2")
if normalization == "batchnorm":
bn_2 = hk.BatchNorm(name="batchnorm_2", **bn_config)
elif normalization == "layernorm":
bn_2 = hk.LayerNorm(name="layernorm_2", **bn_config)
elif normalization == "instancenorm":
bn_2 = hk.InstanceNorm(name="instancenorm_2", **bn_config)
layers = layers + ((conv_2, bn_2),)
self.layers = layers
def __call__(self, inputs, is_training, test_local_stats):
x = shortcut = inputs
for i, (conv_i, bn_i) in enumerate(self.layers):
if self.normalization == "batchnorm":
x = bn_i(x, is_training, test_local_stats)
elif self.normalization in ["layernorm", "instancenorm"]:
x = bn_i(x)
x = jax.nn.relu(x)
if i == 0 and self.use_projection:
shortcut = self.proj_conv(x)
x = conv_i(x)
return x + shortcut
class BlockGroup(hk.Module):
"""Higher level block for ResNet implementation."""
def __init__(
self,
channels: int,
num_blocks: int,
stride: Union[int, Sequence[int]],
bn_config: Mapping[str, FloatStrOrBool],
resnet_v2: bool,
bottleneck: bool,
use_projection: bool,
normalization: Optional[str] = None,
name: Optional[str] = None,
):
super().__init__(name=name)
block_cls = BlockV2 if resnet_v2 else BlockV1
self.blocks = []
for i in range(num_blocks):
self.blocks.append(
block_cls(
channels=channels,
stride=(1 if i else stride),
use_projection=(i == 0 and use_projection),
bottleneck=bottleneck,
normalization=normalization,
bn_config=bn_config,
name="block_%d" % i,
)
)
def __call__(self, inputs, is_training, test_local_stats):
out = inputs
for block in self.blocks:
out = block(out, is_training, test_local_stats)
return out
def check_length(length, value, name):
if len(value) != length:
raise ValueError(f"`{name}` must be of length 4 not {len(value)}")
class ResNet(hk.Module):
"""ResNet model."""
CONFIGS = {
18: {
"blocks_per_group": (2, 2, 2, 2),
"bottleneck": False,
"channels_per_group": (64, 128, 256, 512),
"use_projection": (False, True, True, True),
},
34: {
"blocks_per_group": (3, 4, 6, 3),
"bottleneck": False,
"channels_per_group": (64, 128, 256, 512),
"use_projection": (False, True, True, True),
},
50: {
"blocks_per_group": (3, 4, 6, 3),
"bottleneck": True,
"channels_per_group": (256, 512, 1024, 2048),
"use_projection": (True, True, True, True),
},
101: {
"blocks_per_group": (3, 4, 23, 3),
"bottleneck": True,
"channels_per_group": (256, 512, 1024, 2048),
"use_projection": (True, True, True, True),
},
152: {
"blocks_per_group": (3, 8, 36, 3),
"bottleneck": True,
"channels_per_group": (256, 512, 1024, 2048),
"use_projection": (True, True, True, True),
},
200: {
"blocks_per_group": (3, 24, 36, 3),
"bottleneck": True,
"channels_per_group": (256, 512, 1024, 2048),
"use_projection": (True, True, True, True),
},
}
BlockGroup = BlockGroup # pylint: disable=invalid-name
BlockV1 = BlockV1 # pylint: disable=invalid-name
BlockV2 = BlockV2 # pylint: disable=invalid-name
def __init__(
self,
blocks_per_group: Sequence[int],
bn_config: Optional[Mapping[str, FloatStrOrBool]] = None,
resnet_v2: bool = False,
normalization: Optional[str] = "batchnorm",
bottleneck: bool = False,
channels_per_group: Sequence[int] = (64, 128, 256, 512),
use_projection: Sequence[bool] = (True, True, True, True),
name: Optional[str] = None,
initial_conv_config: Optional[Mapping[str, FloatStrOrBool]] = None,
strides: Sequence[int] = (1, 2, 2, 2),
use_max_pool: bool = True,
):
"""Constructs a ResNet model.
Args:
blocks_per_group: A sequence of length 4 that indicates the number of
blocks created in each group.
bn_config: A dictionary of two elements, ``decay_rate`` and ``eps`` to be
passed on to the :class:`~haiku.BatchNorm` layers. By default the
``decay_rate`` is ``0.9`` and ``eps`` is ``1e-5``.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
``False``.
normalization: Use `batchnorm`, `layernorm`, `instancenorm` or None.
bottleneck: Whether the block should bottleneck or not. Defaults to
``True``.
channels_per_group: A sequence of length 4 that indicates the number of
channels used for each block in each group.
use_projection: A sequence of length 4 that indicates whether each
residual block should use projection.
name: Name of the module.
initial_conv_config: Keyword arguments passed to the constructor of the
initial :class:`~haiku.Conv2D` module.
strides: A sequence of length 4 that indicates the size of stride of
convolutions for each block in each group.
use_max_pool: Whether use max pooling after first convolution layer.
"""
super().__init__(name=name)
self.resnet_v2 = resnet_v2
self.normalization = normalization
self.use_max_pool = use_max_pool
if normalization == "batchnorm":
bn_config = dict(bn_config or {})
bn_config.setdefault("decay_rate", 0.9)
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
bn_config.setdefault("cross_replica_axis", "i")
elif normalization == "layernorm":
bn_config = dict(bn_config or {})
bn_config.setdefault("axis", [-1, -2, -3])
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
elif normalization == "instancenorm":
bn_config = dict(bn_config or {})
bn_config.setdefault("create_scale", True)
bn_config.setdefault("create_offset", True)
# Number of blocks in each group for ResNet.
check_length(4, blocks_per_group, "blocks_per_group")
check_length(4, channels_per_group, "channels_per_group")
check_length(4, strides, "strides")
initial_conv_config = dict(initial_conv_config or {})
initial_conv_config.setdefault("output_channels", 64)
initial_conv_config.setdefault("kernel_shape", 7)
initial_conv_config.setdefault("stride", 2)
initial_conv_config.setdefault("with_bias", False)
initial_conv_config.setdefault("padding", "SAME")
initial_conv_config.setdefault("name", "initial_conv")
self.initial_conv = hk.Conv2D(**initial_conv_config)
if not self.resnet_v2 and normalization == "batchnorm":
self.initial_batchnorm = hk.BatchNorm(
name="initial_batchnorm", **bn_config)
elif not self.resnet_v2 and normalization == "layernorm":
self.initial_norm = hk.LayerNorm(name="initial_layernorm", **bn_config)
elif not self.resnet_v2 and normalization == "instancenorm":
self.initial_norm = hk.InstanceNorm(
name="initial_instancenorm", **bn_config
)
self.block_groups = []
for i, stride in enumerate(strides):
self.block_groups.append(
BlockGroup(
channels=channels_per_group[i],
num_blocks=blocks_per_group[i],
stride=stride,
bn_config=bn_config,
normalization=normalization,
resnet_v2=resnet_v2,
bottleneck=bottleneck,
use_projection=use_projection[i],
name="block_group_%d" % i,
)
)
def __call__(self, inputs, is_training, test_local_stats=False):
out = inputs
out = self.initial_conv(out)
if not self.resnet_v2:
if self.normalization == "batchnorm":
out = self.initial_batchnorm(out, is_training, test_local_stats)
elif self.normalization in ["layernorm", "instancenorm"]:
out = self.initial_norm(out)
out = jax.nn.relu(out)
if self.use_max_pool:
out = hk.max_pool(
out, window_shape=(1, 3, 3, 1), strides=(1, 2, 2, 1), padding="SAME"
)
result = {}
for block_id, block_group in enumerate(self.block_groups):
out = block_group(out, is_training, test_local_stats)
result[f"resnet_unit_{block_id}"] = out
return result
| tapnet-main | models/resnet.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.
# ==============================================================================
"""Default config to train the TapNet."""
from jaxline import base_config
from ml_collections import config_dict
# We define the experiment launch config in the same file as the experiment to
# keep things self-contained in a single file.
def get_config() -> config_dict.ConfigDict:
"""Return config object for training."""
config = base_config.get_base_config()
# Experiment config.
config.training_steps = 100000
# NOTE: duplicates not allowed.
config.shared_module_names = ('tapnet_model',)
config.dataset_names = ('kubric',)
# Note: eval modes must always start with 'eval_'.
config.eval_modes = (
'eval_davis_points',
'eval_jhmdb',
'eval_robotics_points',
'eval_kinetics_points',
)
config.checkpoint_dir = '/tmp/tapnet_training/'
config.evaluate_every = 10000
config.experiment_kwargs = config_dict.ConfigDict(
dict(
config=dict(
sweep_name='default_sweep',
save_final_checkpoint_as_npy=True,
# `enable_double_transpose` should always be false when using 1D.
# For other D It is also completely untested and very unlikely
# to work.
optimizer=dict(
base_lr=2e-3,
max_norm=-1, # < 0 to turn off.
weight_decay=1e-2,
schedule_type='cosine',
cosine_decay_kwargs=dict(
init_value=0.0,
warmup_steps=5000,
end_value=0.0,
),
optimizer='adam',
# Optimizer-specific kwargs.
adam_kwargs=dict(
b1=0.9,
b2=0.95,
eps=1e-8,
),
),
fast_variables=tuple(),
shared_modules=dict(
shared_module_names=config.get_oneway_ref(
'shared_module_names',
),
tapnet_model_kwargs=dict(),
),
datasets=dict(
dataset_names=config.get_oneway_ref('dataset_names'),
kubric_kwargs=dict(
batch_dims=8,
shuffle_buffer_size=128,
train_size=(256, 256),
),
),
supervised_point_prediction_kwargs=dict(
prediction_algo='cost_volume_regressor',
),
checkpoint_dir=config.get_oneway_ref('checkpoint_dir'),
evaluate_every=config.get_oneway_ref('evaluate_every'),
eval_modes=config.get_oneway_ref('eval_modes'),
# If true, run evaluate() on the experiment once before
# you load a checkpoint.
# This is useful for getting initial values of metrics
# at random weights, or when debugging locally if you
# do not have any train job running.
davis_points_path='',
jhmdb_path='',
robotics_points_path='',
training=dict(
# Note: to sweep n_training_steps, DO NOT sweep these
# fields directly. Instead sweep config.training_steps.
# Otherwise, decay/stopping logic
# is not guaranteed to be consistent.
n_training_steps=config.get_oneway_ref('training_steps'),
),
inference=dict(
input_video_path='',
output_video_path='',
resize_height=256, # video height resized to before inference
resize_width=256, # video width resized to before inference
num_points=20, # number of random points to sample
),
)
)
)
# Set up where to store the resulting model.
config.train_checkpoint_all_hosts = False
config.save_checkpoint_interval = 10
config.eval_initial_weights = True
# Prevents accidentally setting keys that aren't recognized (e.g. in tests).
config.lock()
return config
| tapnet-main | configs/tapnet_config.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.
# ==============================================================================
"""Default config to train the TAPIR."""
from jaxline import base_config
from ml_collections import config_dict
# We define the experiment launch config in the same file as the experiment to
# keep things self-contained in a single file.
def get_config() -> config_dict.ConfigDict:
"""Return config object for training."""
config = base_config.get_base_config()
# Experiment config.
config.training_steps = 100000
# NOTE: duplicates not allowed.
config.shared_module_names = ('tapir_model',)
config.dataset_names = ('kubric',)
# Note: eval modes must always start with 'eval_'.
config.eval_modes = (
'eval_davis_points',
'eval_jhmdb',
'eval_robotics_points',
'eval_kinetics_points',
)
config.checkpoint_dir = '/tmp/tapnet_training/'
config.evaluate_every = 10000
config.experiment_kwargs = config_dict.ConfigDict(
dict(
config=dict(
sweep_name='default_sweep',
save_final_checkpoint_as_npy=True,
# `enable_double_transpose` should always be false when using 1D.
# For other D It is also completely untested and very unlikely
# to work.
optimizer=dict(
base_lr=1e-3,
max_norm=-1, # < 0 to turn off.
weight_decay=1e-1,
schedule_type='cosine',
cosine_decay_kwargs=dict(
init_value=0.0,
warmup_steps=1000,
end_value=0.0,
),
optimizer='adam',
# Optimizer-specific kwargs.
adam_kwargs=dict(
b1=0.9,
b2=0.95,
eps=1e-8,
),
),
fast_variables=tuple(),
shared_modules=dict(
shared_module_names=config.get_oneway_ref(
'shared_module_names',
),
tapir_model_kwargs=dict(
bilinear_interp_with_depthwise_conv=True,
use_causal_conv=False,
initial_resolution=(256, 256),
),
),
datasets=dict(
dataset_names=config.get_oneway_ref('dataset_names'),
kubric_kwargs=dict(
batch_dims=8,
shuffle_buffer_size=128,
train_size=(256, 256),
),
),
supervised_point_prediction_kwargs=dict(
prediction_algo='cost_volume_regressor',
model_key='tapir_model',
),
checkpoint_dir=config.get_oneway_ref('checkpoint_dir'),
evaluate_every=config.get_oneway_ref('evaluate_every'),
eval_modes=config.get_oneway_ref('eval_modes'),
# If true, run evaluate() on the experiment once before
# you load a checkpoint.
# This is useful for getting initial values of metrics
# at random weights, or when debugging locally if you
# do not have any train job running.
davis_points_path='',
jhmdb_path='',
robotics_points_path='',
training=dict(
# Note: to sweep n_training_steps, DO NOT sweep these
# fields directly. Instead sweep config.training_steps.
# Otherwise, decay/stopping logic
# is not guaranteed to be consistent.
n_training_steps=config.get_oneway_ref('training_steps'),
),
inference=dict(
input_video_path='',
output_video_path='',
resize_height=256, # video height resized to before inference
resize_width=256, # video width resized to before inference
num_points=20, # number of random points to sample
),
)
)
)
# Set up where to store the resulting model.
config.train_checkpoint_all_hosts = False
config.save_checkpoint_interval = 10
config.eval_initial_weights = True
# Prevents accidentally setting keys that aren't recognized (e.g. in tests).
config.lock()
return config
| tapnet-main | configs/tapir_config.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.
# ==============================================================================
"""Python script to generate a pickle with annotations from raw videos."""
import csv
import dataclasses
import io
import math
import os
import pickle
from typing import Dict, Iterator, List, Sequence, Tuple
from absl import app
from absl import flags
from absl import logging
import ffmpeg
import numpy as np
from PIL import Image
FLAGS = flags.FLAGS
flags.DEFINE_string('input_csv_path', None, 'Path to the input csv.')
flags.DEFINE_string(
'output_base_path',
None,
'Path to the output folder where pickle files will be stored.',
)
flags.DEFINE_string(
'video_root_path',
None,
(
'Path to the root directory of the extracted Kinetics-700-2020 videos'
' from the validation set.'
),
)
flags.DEFINE_integer('num_shards', 10, 'Number of pickle shards to output.')
_JPEG_HEADER = b'\xff\xd8'
@dataclasses.dataclass(frozen=True)
class Point:
x: float
y: float
occluded: bool
@dataclasses.dataclass(frozen=True)
class Track:
points: Tuple[Point, ...]
@dataclasses.dataclass(frozen=True)
class Video:
youtube_id: str
start_time_sec: int
end_time_sec: int
video_path: str
tracks: Tuple[Track, ...]
def csv_to_dataset(
csv_path: str, videos_path: Dict[str, str]
) -> Tuple[Video, ...]:
"""Reads the input CSV and creates a list of `Video`s out of that."""
def points(row: Sequence[str]) -> Iterator[Point]:
for i in range(250):
x, y, occ = row[3 + 3 * i : 3 + 3 * i + 3]
x = float(x)
y = float(y)
assert occ in ('0', '1')
occ = occ == '1'
yield Point(x, y, occ)
logging.info('Reading CSV "%s".', csv_path)
with open(csv_path) as f:
reader = csv.reader(f, delimiter=',')
tracks_per_video: Dict[Tuple[str, int, int], List[Track]] = {}
for row in reader:
assert len(row) == 3 + 3 * 250
youtube_id, start_time_sec, end_time_sec = row[:3]
start_time_sec = int(start_time_sec)
end_time_sec = int(end_time_sec)
key = (youtube_id, start_time_sec, end_time_sec)
track = Track(tuple(points(row)))
if key not in tracks_per_video:
tracks_per_video[key] = []
tracks_per_video[key].append(track)
def videos() -> Iterator[Video]:
for key, tracks in tracks_per_video.items():
youtube_id, start_time_sec, end_time_sec = key
name = f'{youtube_id}_{start_time_sec:06}_{end_time_sec:06}'
if name not in videos_path:
logging.warning('Video "%s" not downloaded. Skipping it.', name)
continue
video_path = videos_path[name]
yield Video(
youtube_id, start_time_sec, end_time_sec, video_path, tuple(tracks)
)
return tuple(videos())
def get_paths_to_videos(video_root_path: str) -> Dict[str, str]:
"""Returns the relative path to each downloaded video."""
logging.info('Reading all videos in subfolders of "%s".', video_root_path)
video_to_path: Dict[str, str] = {}
for folder_or_video in os.listdir(video_root_path):
path = os.path.join(video_root_path, folder_or_video)
if os.path.isdir(path):
subfolder_paths = get_paths_to_videos(path)
for k, v in subfolder_paths.items():
assert k not in video_to_path
video_to_path[k] = v
elif folder_or_video.endswith('.mp4'):
name = folder_or_video[:-4] # Remove '.mp4'.
assert name not in video_to_path
video_to_path[name] = path
return video_to_path
def extract_frames(video_path: str, fps: float) -> Tuple[bytes, ...]:
"""Extracts list of jpeg bytes from the given video using ffmpeg."""
cmd = (
ffmpeg.input(video_path)
.filter('fps', fps=fps)
.output('pipe:', format='image2pipe')
)
jpeg_bytes, _ = cmd.run(capture_stdout=True, quiet=True)
jpeg_bytes = jpeg_bytes.split(_JPEG_HEADER)[1:]
jpeg_bytes = map(lambda x: _JPEG_HEADER + x, jpeg_bytes)
return tuple(jpeg_bytes)
def generate_example(video: Video) -> Dict[str, np.ndarray]:
"""Generates a dictionary with the info from a `Video`."""
example: Dict[str, np.ndarray] = {}
imgs_encoded = extract_frames(video.video_path, 25.0)
if len(imgs_encoded) > 250:
imgs_encoded = imgs_encoded[:250]
if len(imgs_encoded) < 250:
# Clip is shorter than 10s.
num_frames = len(imgs_encoded)
new_tracks = tuple(
Track(tuple(t.points[:num_frames])) for t in video.tracks
)
video = Video(
video.youtube_id,
video.start_time_sec,
video.end_time_sec,
video.video_path,
new_tracks,
)
example['video'] = np.array(imgs_encoded)
byteio = io.BytesIO(imgs_encoded[0])
img = Image.open(byteio)
height, width, _ = np.array(img).shape
points = []
occluded = []
for track in video.tracks:
points.append(
[
[(p.x * width - 0.5) / width, (p.y * height - 0.5) / height]
for p in track.points
]
)
occluded.append([p.occluded for p in track.points])
example['points'] = np.array(points, dtype=np.float64)
example['occluded'] = np.array(occluded, dtype=bool)
return example
def main(argv: Sequence[str]) -> None:
del argv
output_folder = FLAGS.output_base_path
if output_folder and not os.path.exists(output_folder):
os.makedirs(output_folder)
# Reads data.
videos_path = get_paths_to_videos(FLAGS.video_root_path)
videos = csv_to_dataset(FLAGS.input_csv_path, videos_path)
# Process the dataset and store pickles.
num_examples_per_shard = int(math.ceil(len(videos) / FLAGS.num_shards))
shard = 0
data = []
for i, video in enumerate(videos):
print(
'Processing example %d of %d (%d%%) \r'
% (i, len(videos), i * 100 / len(videos)),
end='',
)
data.append(generate_example(video))
if i == len(videos) - 1 or len(data) == num_examples_per_shard:
shard_path = os.path.join(
output_folder, f'{shard:04}_of_{FLAGS.num_shards:04}.pkl'
)
logging.info('Writing file "%s".', shard_path)
with open(shard_path, 'wb') as f:
pickle.dump(data, f)
data.clear()
shard += 1
if __name__ == '__main__':
app.run(main)
| tapnet-main | data/generate_tapvid.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.
# ==============================================================================
"""Visualize frames of a random video of the given dataset."""
import io
import pickle
import random
from typing import Sequence
from absl import app
from absl import flags
from absl import logging
import mediapy as media
import numpy as np
from PIL import Image
from tapnet.utils import viz_utils
FLAGS = flags.FLAGS
flags.DEFINE_string(
'input_path', None, 'Path to the pickle file.', required=True
)
flags.DEFINE_string(
'output_path', None, 'Path to the output mp4 video.', required=True
)
def main(argv: Sequence[str]) -> None:
del argv
logging.info('Loading data from %s. This takes time.', FLAGS.input_path)
with open(FLAGS.input_path, 'rb') as f:
data = pickle.load(f)
if isinstance(data, dict):
data = list(data.values())
idx = random.randint(0, len(data) - 1)
video = data[idx]
frames = video['video']
if isinstance(frames[0], bytes):
# Tapnet is stored and JPEG bytes rather than `np.ndarray`s.
def decode(frame):
byteio = io.BytesIO(frame)
img = Image.open(byteio)
return np.array(img)
frames = np.array([decode(frame) for frame in frames])
if frames.shape[1] > 360:
frames = media.resize_video(frames, (360, 640))
scale_factor = np.array(frames.shape[2:0:-1])[np.newaxis, np.newaxis, :]
painted_frames = viz_utils.paint_point_track(
frames,
video['points'] * scale_factor,
~video['occluded'],
)
media.write_video(FLAGS.output_path, painted_frames, fps=25)
logging.info('Examplar point visualization saved to %s', FLAGS.output_path)
if __name__ == '__main__':
app.run(main)
| tapnet-main | data/visualize.py |
# -*- coding:utf-8 -*-
import argparse
import glob
import os
import collections
import re
import cPickle as pickle
import logging
from collections import defaultdict
logging.basicConfig(level=logging.INFO)
class ConvertFunctionError(RuntimeError):
pass
def extractFunctions(functions, inputPath):
functionRegex = {}
totalFunctions = 0
totalArguments = 0
for function in functions:
typeRegex = "\w+"
funcNameRegex = function
functionRegex[function] = re.compile("""
^ # Start of line
(%s) # Type (group 1)
\ # Space
%s # Function name
\s* # Optional whitespace
\( # Open bracket
([^()]*) # All of the arguments
\) # Close bracket
\s* # Optional whitespace
$ # End of line
""" % (typeRegex, funcNameRegex)
, re.VERBOSE)
inFunctionDeclaration = None
argumentTypes = None
arguments = None
with open(inputPath, 'r') as inputFile:
for line in inputFile:
if inFunctionDeclaration:
if line.startswith("{"):
argumentsWithTypes = []
logging.debug(argumentTypes)
for arg in arguments:
if arg in argumentTypes:
argumentsWithTypes.append((arg, argumentTypes[arg]))
elif arg + "[]" in argumentTypes:
# If we can't find the argument directly, check whether it was stored as an array type
argumentsWithTypes.append((arg + "[]", argumentTypes[arg + "[]"]))
else:
raise RuntimeError("Cannot find type for argument %s" % (arg,))
functionDescription = {
'returnType' : returnType,
'functionName' : inFunctionDeclaration,
'arguments' : argumentsWithTypes,
'origin' : inputPath
}
yield functionDescription
inFunctionDeclaration = None
else:
lineBeforeSemicolon = line.split(";")[0]
lineWords = lineBeforeSemicolon.split()
typeName = None
if lineWords[0] == "register":
typeName = lineWords[1]
lineWords = lineWords[2:]
logging.debug("REGISTER :" + typeName + " " + str(lineWords))
else:
typeName = lineWords[0]
lineWords = lineWords[1:]
logging.debug("NORMAL :" + typeName + " " + str(lineWords))
for argumentName in "".join(lineWords).strip().split(","):
if argumentName.startswith("*"):
argumentTypes[argumentName[1:]] = typeName + " *"
else:
argumentTypes[argumentName] = typeName
else:
for function in functions:
match = functionRegex[function].match(line)
if match:
logging.debug("Found function %s:" % (function,))
logging.debug(line)
logging.debug(match.groups())
returnType = match.group(1)
arguments = [ x.strip(" ,") for x in match.group(2).split(",") ]
totalArguments += len(arguments)
totalFunctions += 1
logging.debug("return type: " + returnType)
logging.debug("arguments " + str(arguments))
inFunctionDeclaration = function
argumentTypes = {}
parser = argparse.ArgumentParser()
parser.add_argument("functionList")
parser.add_argument("outputPath")
parser.add_argument("--input", action='append')
parser.add_argument("--debug", action='store_true')
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
with open(args.functionList, 'r') as functionFile:
functions = functionFile.read().split()
allFunctions = defaultdict(lambda: [])
seenNames = set()
for inputDir in args.input:
sectionName = os.path.basename(inputDir)
logging.info("Processing directory %s" %(sectionName,))
for cFile in glob.glob(os.path.join(inputDir,"*.c")):
logging.info("Looking for functions in %s" %(cFile))
for function in extractFunctions(functions, cFile):
logging.info("Extracted function %s" % (function['functionName'],))
allFunctions[sectionName].append(function)
seenNames.add(function['functionName'])
logging.info("Writing function list to: " + str(args.outputPath))
with open(args.outputPath, 'w') as outputFile:
pickle.dump(dict(allFunctions), outputFile)
missingNames = set(functions) - seenNames
for name in missingNames:
logging.warn("Could not find %s" % (name,))
| torch-cephes-master | makewrap/extractFunctions.py |
import cPickle as pickle
import os
import argparse
import itertools
import logging
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument("functions")
parser.add_argument("--outputDir", default="tests")
parser.add_argument("--debug", action='store_true')
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
testValues = {
# 'double' : [0.0, 1.0, 10.0, "math.huge"],
'double' : [0.5],
'int' : [1],
'cmplx' : ["cephes.new_cmplx(1, 1);"],
'fract' : ["nil ; error('TODO: fract parameter needed!')"],
'cmplx *' : ["cephes.new_cmplx(1, 1) ; error(' TODO: check this pointer makes sense!')"],
'void *' : ["nil ; error(' TODO: void * parameter needed!')"],
'double *' : ['ffi.new("double[1]", {0}) ; error(" TODO: check this array is sensible!")'],
'int *' : ['ffi.new("int[1]", {0}) ; error(" TODO: check this array is sensible!")'],
'fract *' : ["nil ; error(' TODO: fract * parameter needed!')"]
}
def testsForFunction(function):
logging.debug("Generating tests for %s" % (function['functionName'],))
logging.debug("Return type: " + function['returnType'])
logging.debug("Args: " + str(function['arguments']))
functionCArgs = ", ".join(argType + " " + argName for argName, argType in function['arguments'])
for i, (argName, argType) in enumerate(function['arguments']):
if argName.endswith("[]"):
argType += " *"
argName = argName[0:-2]
function['arguments'][i] = (argName, argType)
valueGenerators = [ testValues[argType] for argName, argType in function['arguments'] ]
testString = """
-- Test simple calls for {functionName}
-- Signature: {returnType} {functionName}({functionCArgs})
function callTests.test_{functionName}()
""".format(
returnType = function['returnType'],
functionName = function['functionName'],
functionCArgs = functionCArgs
)
argNames = [ argName for argName, _ in function['arguments'] ]
for argValues in itertools.product(*valueGenerators):
testString += """ {argDeclarations}
tester:assert(cephes.{functionName}({functionArgs}))""".format(
functionName = function['functionName'],
functionArgs = ", ".join(str(x) for x in argNames),
argDeclarations = "\n ".join("local %s = %s" % (argNames[i], argValue) for i, argValue in enumerate(argValues))
)
testString += """
end
"""
return testString
with open(args.functions, 'r') as inputFile:
allFunctions = pickle.load(inputFile)
for sectionName, functions in allFunctions.iteritems():
testFilePath = os.path.join(args.outputDir, "test_%s.lua" % (sectionName,))
with open(testFilePath, 'w') as testFile:
testFile.write("""
require 'cephes'
local ffi = require 'ffi'
local callTests = {}
local tester = torch.Tester()
""")
for function in functions:
testFile.write(testsForFunction(function))
testFile.write("""
tester:add(callTests)
tester:run()
""")
| torch-cephes-master | makewrap/createTests.py |
import cPickle as pickle
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("functions")
args = parser.parse_args()
def ffiForFunction(function):
functionString = str(function['returnType']) + " " + str(function['functionName'])
argsWithTypes = [ typeName + " " + arg for (arg, typeName) in function['arguments'] ]
functionString += "(" + (", ".join(argsWithTypes)) + ");\n"
return " " + functionString
with open(args.functions, 'r') as inputFile:
allFunctions = pickle.load(inputFile)
seenFiles = set()
ffiFilePath = "ffi.lua"
with open(ffiFilePath, 'w') as ffiFile:
ffiFile.write(
"""
local ffi = require("ffi")
cephes = ffi.load(package.searchpath('libcephes', package.cpath))
-- Define cmplx struct
ffi.cdef[[
typedef struct
{
double r;
double i;
}cmplx;
]]
""")
for sectionName, functions in allFunctions.iteritems():
ffiFile.write(
"""
-- imports for folder %s
ffi.cdef[[
""" % (sectionName,))
for function in functions:
if not function['origin'] in seenFiles:
ffiFile.write(" // %s\n" %(function['origin'],))
seenFiles.add(function['origin'])
ffiFile.write(ffiForFunction(function))
ffiFile.write("]]\n")
ffiFile.write(
"""
return cephes
""")
| torch-cephes-master | makewrap/createFFI.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.
# ============================================================================
"""Install script for setuptools."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import imp
from setuptools import find_packages
from setuptools import setup
setup(
name='dm-memorytasks',
version=imp.load_source('_version',
'dm_memorytasks/_version.py').__version__,
description=('DeepMind Memory Tasks, a set of Unity-based machine-'
'learning research tasks.'),
author='DeepMind',
license='Apache License, Version 2.0',
keywords='reinforcement-learning python machine learning',
packages=find_packages(exclude=['examples']),
install_requires=[
'absl-py',
'dm-env',
'dm-env-rpc<1.1.0',
'docker',
'grpcio',
'numpy',
'portpicker',
],
tests_require=['nose'],
python_requires='>=3.7',
extras_require={'examples': ['pygame']},
test_suite='nose.collector',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3.7',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
| dm_memorytasks-master | setup.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.
# ============================================================================
"""Example random agent for interacting with DeepMind Memory Tasks."""
from absl import app
from absl import flags
from absl import logging
from dm_env import specs
import dm_memorytasks
import numpy as np
FLAGS = flags.FLAGS
flags.DEFINE_string(
'docker_image_name', None,
'Name of the Docker image that contains the Memory Tasks. '
'If None, uses the default dm_memorytask name')
flags.DEFINE_integer('seed', 123, 'Environment seed.')
flags.DEFINE_string('level_name', 'spot_diff_extrapolate',
'Name of memory task to run.')
class RandomAgent(object):
"""Basic random agent for DeepMind Memory Tasks."""
def __init__(self, action_spec):
self.action_spec = action_spec
def act(self):
action = {}
for name, spec in self.action_spec.items():
# Uniformly sample BoundedArray actions.
if isinstance(spec, specs.BoundedArray):
action[name] = np.random.uniform(spec.minimum, spec.maximum, spec.shape)
else:
action[name] = spec.generate_value()
return action
def main(_):
env_settings = dm_memorytasks.EnvironmentSettings(
seed=FLAGS.seed, level_name=FLAGS.level_name)
with dm_memorytasks.load_from_docker(
name=FLAGS.docker_image_name, settings=env_settings) as env:
agent = RandomAgent(env.action_spec())
timestep = env.reset()
score = 0
while not timestep.last():
action = agent.act()
timestep = env.step(action)
if timestep.reward:
score += timestep.reward
logging.info('Total score: %1.1f, reward: %1.1f', score,
timestep.reward)
if __name__ == '__main__':
app.run(main)
| dm_memorytasks-master | examples/random_agent.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.
# ============================================================================
"""Example human agent for interacting with DeepMind Memory Tasks."""
from absl import app
from absl import flags
from absl import logging
import dm_memorytasks
import numpy as np
import pygame
FLAGS = flags.FLAGS
flags.DEFINE_list(
'screen_size', [640, 480],
'Screen width/height in pixels. Scales the environment RGB observations to '
'fit the screen size.')
flags.DEFINE_string(
'docker_image_name', None,
'Name of the Docker image that contains the Memory Tasks. '
'If None, uses the default dm_memorytask name')
flags.DEFINE_integer('seed', 123, 'Environment seed.')
flags.DEFINE_string('level_name', 'spot_diff_extrapolate',
'Name of memory task to run.')
_FRAMES_PER_SECOND = 30
_KEYS_TO_ACTION = {
pygame.K_w: {'MOVE_BACK_FORWARD': 1},
pygame.K_s: {'MOVE_BACK_FORWARD': -1},
pygame.K_a: {'STRAFE_LEFT_RIGHT': -1},
pygame.K_d: {'STRAFE_LEFT_RIGHT': 1},
pygame.K_UP: {'LOOK_DOWN_UP': -1},
pygame.K_DOWN: {'LOOK_DOWN_UP': 1},
pygame.K_LEFT: {'LOOK_LEFT_RIGHT': -1},
pygame.K_RIGHT: {'LOOK_LEFT_RIGHT': 1},
} # pyformat: disable
_NO_ACTION = {
'MOVE_BACK_FORWARD': 0,
'STRAFE_LEFT_RIGHT': 0,
'LOOK_LEFT_RIGHT': 0,
'LOOK_DOWN_UP': 0,
}
def main(_):
pygame.init()
try:
pygame.mixer.quit()
except NotImplementedError:
pass
pygame.display.set_caption('Memory Tasks Human Agent')
env_settings = dm_memorytasks.EnvironmentSettings(
seed=FLAGS.seed, level_name=FLAGS.level_name)
with dm_memorytasks.load_from_docker(name=FLAGS.docker_image_name,
settings=env_settings) as env:
screen = pygame.display.set_mode(
(int(FLAGS.screen_size[0]), int(FLAGS.screen_size[1])))
rgb_spec = env.observation_spec()['RGB_INTERLEAVED']
surface = pygame.Surface((rgb_spec.shape[1], rgb_spec.shape[0]))
actions = _NO_ACTION
score = 0
clock = pygame.time.Clock()
while True:
# Do not close with CTRL-C as otherwise the docker container may be left
# running on exit.
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return
key_actions = _KEYS_TO_ACTION.get(event.key, {})
for name, action in key_actions.items():
actions[name] += action
elif event.type == pygame.KEYUP:
key_actions = _KEYS_TO_ACTION.get(event.key, {})
for name, action in key_actions.items():
actions[name] -= action
timestep = env.step(actions)
frame = np.swapaxes(timestep.observation['RGB_INTERLEAVED'], 0, 1)
pygame.surfarray.blit_array(surface, frame)
pygame.transform.smoothscale(surface, screen.get_size(), screen)
pygame.display.update()
if timestep.reward:
score += timestep.reward
logging.info('Total score: %1.1f, reward: %1.1f', score,
timestep.reward)
clock.tick(_FRAMES_PER_SECOND)
if __name__ == '__main__':
app.run(main)
| dm_memorytasks-master | examples/human_agent.py |
# Lint as: python3
# 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.
# ============================================================================
"""Python utility functions for loading DeepMind Memory Tasks."""
import codecs
import collections
import json
import os
import re
import subprocess
import time
import typing
from absl import logging
import dm_env
import docker
import grpc
import numpy as np
import portpicker
from dm_env_rpc.v1 import connection as dm_env_rpc_connection
from dm_env_rpc.v1 import dm_env_adaptor
from dm_env_rpc.v1 import dm_env_rpc_pb2
from dm_env_rpc.v1 import error
from dm_env_rpc.v1 import tensor_utils
# Maximum number of times to attempt gRPC connection.
_MAX_CONNECTION_ATTEMPTS = 10
# Port to expect the docker environment to internally listen on.
_DOCKER_INTERNAL_GRPC_PORT = 10000
_DEFAULT_DOCKER_IMAGE_NAME = 'gcr.io/deepmind-environments/dm_memorytasks:v1.0.1'
_MEMORY_TASK_OBSERVATIONS = ['RGB_INTERLEAVED', 'AvatarPosition', 'Score']
MEMORY_TASK_LEVEL_NAMES = frozenset((
'invisible_goal_empty_arena_extrapolate',
'invisible_goal_empty_arena_holdout_extrapolate',
'invisible_goal_empty_arena_holdout_interpolate',
'invisible_goal_empty_arena_holdout_large',
'invisible_goal_empty_arena_holdout_small',
'invisible_goal_empty_arena_interpolate',
'invisible_goal_empty_arena_train',
'invisible_goal_with_buildings_extrapolate',
'invisible_goal_with_buildings_holdout_extrapolate',
'invisible_goal_with_buildings_holdout_interpolate',
'invisible_goal_with_buildings_holdout_large',
'invisible_goal_with_buildings_holdout_small',
'invisible_goal_with_buildings_interpolate',
'invisible_goal_with_buildings_train',
'spot_diff_extrapolate',
'spot_diff_holdout_extrapolate',
'spot_diff_holdout_interpolate',
'spot_diff_holdout_large',
'spot_diff_holdout_small',
'spot_diff_interpolate',
'spot_diff_motion_extrapolate',
'spot_diff_motion_holdout_extrapolate',
'spot_diff_motion_holdout_interpolate',
'spot_diff_motion_holdout_large',
'spot_diff_motion_holdout_small',
'spot_diff_motion_interpolate',
'spot_diff_motion_train',
'spot_diff_multi_extrapolate',
'spot_diff_multi_holdout_extrapolate',
'spot_diff_multi_holdout_interpolate',
'spot_diff_multi_holdout_large',
'spot_diff_multi_holdout_small',
'spot_diff_multi_interpolate',
'spot_diff_multi_train',
'spot_diff_passive_extrapolate',
'spot_diff_passive_holdout_extrapolate',
'spot_diff_passive_holdout_interpolate',
'spot_diff_passive_holdout_large',
'spot_diff_passive_holdout_small',
'spot_diff_passive_interpolate',
'spot_diff_passive_train',
'spot_diff_train',
'transitive_inference_extrapolate',
'transitive_inference_holdout_extrapolate',
'transitive_inference_holdout_interpolate',
'transitive_inference_holdout_large',
'transitive_inference_holdout_small',
'transitive_inference_interpolate',
'transitive_inference_train_large',
'transitive_inference_train_small',
'visible_goal_with_buildings_extrapolate',
'visible_goal_with_buildings_holdout_extrapolate',
'visible_goal_with_buildings_holdout_interpolate',
'visible_goal_with_buildings_holdout_large',
'visible_goal_with_buildings_holdout_small',
'visible_goal_with_buildings_interpolate',
'visible_goal_with_buildings_train',
))
_ConnectionDetails = collections.namedtuple('_ConnectionDetails',
['channel', 'connection', 'specs'])
class _MemoryTasksEnv(dm_env_adaptor.DmEnvAdaptor):
"""An implementation of dm_env_rpc.DmEnvAdaptor for memory tasks."""
def __init__(self, connection_details, requested_observations,
num_action_repeats):
super(_MemoryTasksEnv,
self).__init__(connection_details.connection,
connection_details.specs, requested_observations)
self._channel = connection_details.channel
self._num_action_repeats = num_action_repeats
def close(self):
super(_MemoryTasksEnv, self).close()
self._channel.close()
def step(self, action):
"""Implementation of dm_env.step that supports repeated actions."""
timestep = None
discount = None
reward = None
for _ in range(self._num_action_repeats):
next_timestep = super(_MemoryTasksEnv, self).step(action)
# Accumulate reward per timestep.
if next_timestep.reward is not None:
reward = (reward or 0.) + next_timestep.reward
# Calculate the product for discount.
if next_timestep.discount is not None:
discount = discount if discount else []
discount.append(next_timestep.discount)
timestep = dm_env.TimeStep(next_timestep.step_type, reward,
# Note: np.product(None) returns None.
np.product(discount),
next_timestep.observation)
if timestep.last():
return timestep
return timestep
class _MemoryTasksContainerEnv(_MemoryTasksEnv):
"""An implementation of _MemoryTasksEnv.
Ensures that the provided Docker container is closed on exit.
"""
def __init__(self, connection_details, requested_observations,
num_action_repeats, container):
super(_MemoryTasksContainerEnv,
self).__init__(connection_details, requested_observations,
num_action_repeats)
self._container = container
def close(self):
super(_MemoryTasksContainerEnv, self).close()
try:
self._container.kill()
except docker.errors.NotFound:
pass # Ignore, container has already been closed.
class _MemoryTasksProcessEnv(_MemoryTasksEnv):
"""An implementation of _MemoryTasksEnv.
Ensure that the provided running process is closed on exit.
"""
def __init__(self, connection_details, requested_observations,
num_action_repeats, process):
super(_MemoryTasksProcessEnv,
self).__init__(connection_details, requested_observations,
num_action_repeats)
self._process = process
def close(self):
super(_MemoryTasksProcessEnv, self).close()
self._process.terminate()
self._process.wait()
def _check_grpc_channel_ready(channel):
"""Helper function to check the gRPC channel is ready N times."""
for _ in range(_MAX_CONNECTION_ATTEMPTS - 1):
try:
return grpc.channel_ready_future(channel).result(timeout=1)
except grpc.FutureTimeoutError:
pass
return grpc.channel_ready_future(channel).result(timeout=1)
def _can_send_message(connection):
"""Returns if `connection` is healthy and able to process requests."""
try:
# This should return a response with an error unless the server isn't yet
# receiving requests.
connection.send(dm_env_rpc_pb2.StepRequest())
except error.DmEnvRpcError:
return True
except grpc.RpcError:
return False
def _create_channel_and_connection(port):
"""Returns a tuple of `(channel, connection)`."""
for _ in range(_MAX_CONNECTION_ATTEMPTS):
channel = grpc.secure_channel('localhost:{}'.format(port),
grpc.local_channel_credentials())
_check_grpc_channel_ready(channel)
connection = dm_env_rpc_connection.Connection(channel)
if _can_send_message(connection):
break
else:
# A gRPC server running within Docker sometimes reports that the channel
# is ready but transitively returns an error (status code 14) on first
# use. Giving the server some time to breath and retrying often fixes the
# problem.
connection.close()
channel.close()
time.sleep(1.0)
return channel, connection
def _parse_exception_message(message):
"""Returns a human-readable version of a dm_env_rpc json error message."""
try:
match = re.match(r'^message\:\ \"(.*)\"$', message)
json_data = codecs.decode(match.group(1), 'unicode-escape')
parsed_json_data = json.loads(json_data)
return ValueError(json.dumps(parsed_json_data, indent=4))
except: # pylint: disable=bare-except
return message
def _wrap_send(send):
"""Wraps `send` in order to reformat exceptions."""
try:
return send()
except ValueError as e:
e.args = [_parse_exception_message(e.args[0])]
raise
def _connect_to_environment(port, settings):
"""Helper function for connecting to a running dm_memorytask environment."""
if settings.level_name not in MEMORY_TASK_LEVEL_NAMES:
raise ValueError(
'Level named "{}" is not a valid dm_memorytask level.'.format(
settings.level_name))
channel, connection = _create_channel_and_connection(port)
original_send = connection.send
connection.send = lambda request: _wrap_send(lambda: original_send(request))
world_name = connection.send(
dm_env_rpc_pb2.CreateWorldRequest(
settings={
'seed': tensor_utils.pack_tensor(settings.seed),
'episodeId': tensor_utils.pack_tensor(0),
'levelName': tensor_utils.pack_tensor(settings.level_name),
})).world_name
join_world_settings = {
'width':
tensor_utils.pack_tensor(settings.width),
'height':
tensor_utils.pack_tensor(settings.height),
'EpisodeLengthSeconds':
tensor_utils.pack_tensor(settings.episode_length_seconds),
}
specs = connection.send(
dm_env_rpc_pb2.JoinWorldRequest(
world_name=world_name, settings=join_world_settings)).specs
return _ConnectionDetails(channel=channel, connection=connection, specs=specs)
class EnvironmentSettings(typing.NamedTuple):
"""Collection of settings used to start a specific Memory task.
Required attributes:
seed: Seed to initialize the environment's RNG.
level_name: Name of the level to load.
Optional attributes:
width: Width (in pixels) of the desired RGB observation; defaults to 96.
height: Height (in pixels) of the desired RGB observation; defaults to 72.
episode_length_seconds: Maximum episode length (in seconds); defaults to
120.
num_action_repeats: Number of times to step the environment with the
provided action in calls to `step()`.
"""
seed: int
level_name: str
width: int = 96
height: int = 72
episode_length_seconds: float = 120.0
num_action_repeats: int = 1
def _validate_environment_settings(settings):
"""Helper function to validate the provided environment settings."""
if settings.episode_length_seconds <= 0.0:
raise ValueError('episode_length_seconds must have a positive value.')
if settings.num_action_repeats <= 0:
raise ValueError('num_action_repeats must have a positive value.')
if settings.width <= 0 or settings.height <= 0:
raise ValueError('width and height must have a positive value.')
def load_from_disk(path, settings):
"""Load Memory Tasks from disk.
Args:
path: Directory containing dm_memorytasks environment.
settings: EnvironmentSettings required to start the environment.
Returns:
An implementation of dm_env.Environment.
Raises:
RuntimeError: If unable to start environment process.
"""
_validate_environment_settings(settings)
executable_path = os.path.join(path, 'Linux64Player')
libosmesa_path = os.path.join(path, 'external_libosmesa_llvmpipe.so')
if not os.path.exists(executable_path) or not os.path.exists(libosmesa_path):
raise RuntimeError(
'Cannot find dm_memorytasks executable or dependent files at path: {}'
.format(path))
port = portpicker.pick_unused_port()
process_flags = [
executable_path,
# Unity command-line flags.
'-logfile',
'-batchmode',
'-noaudio',
# Other command-line flags.
'--logtostderr',
'--server_type=GRPC',
'--uri_address=[::]:{}'.format(port),
]
os.environ.update({
'UNITY_RENDERER': 'software',
'UNITY_OSMESA_PATH': libosmesa_path,
})
process = subprocess.Popen(
process_flags, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if process.poll() is not None:
raise RuntimeError('Failed to start dm_memorytasks process correctly.')
return _MemoryTasksProcessEnv(
_connect_to_environment(port, settings), _MEMORY_TASK_OBSERVATIONS,
settings.num_action_repeats, process)
def load_from_docker(settings, name=None):
"""Load Memory Tasks from docker container.
Args:
settings: EnvironmentSettings required to start the environment.
name: Optional name of Docker image that contains the dm_memorytasks
environment. If left unset, uses the dm_memorytasks default name.
Returns:
An implementation of dm_env.Environment
"""
_validate_environment_settings(settings)
name = name or _DEFAULT_DOCKER_IMAGE_NAME
client = docker.from_env()
port = portpicker.pick_unused_port()
try:
client.images.get(name)
except docker.errors.ImageNotFound:
logging.info('Downloading docker image "%s"...', name)
client.images.pull(name)
logging.info('Download finished.')
container = client.containers.run(
name,
auto_remove=True,
detach=True,
ports={_DOCKER_INTERNAL_GRPC_PORT: port})
return _MemoryTasksContainerEnv(
_connect_to_environment(port, settings), _MEMORY_TASK_OBSERVATIONS,
settings.num_action_repeats, container)
| dm_memorytasks-master | dm_memorytasks/_load_environment.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.
# ============================================================================
"""Package version for dm_memorytasks.
Kept in separate file so it can be used during installation.
"""
__version__ = '1.0.3' # https://www.python.org/dev/peps/pep-0440/
| dm_memorytasks-master | dm_memorytasks/_version.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 dm_memorytasks.load_from_disk."""
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
from dm_env import test_utils
import dm_memorytasks
FLAGS = flags.FLAGS
flags.DEFINE_string('path', '',
'Directory that contains dm_memorytasks environment.')
class LoadFromDiskTest(test_utils.EnvironmentTestMixin, absltest.TestCase):
def make_object_under_test(self):
return dm_memorytasks.load_from_disk(
FLAGS.path,
settings=dm_memorytasks.EnvironmentSettings(
seed=123, level_name='spot_diff_extrapolate'))
class MemoryTaskTest(parameterized.TestCase):
@parameterized.parameters(dm_memorytasks.MEMORY_TASK_LEVEL_NAMES)
def test_load_level(self, level_name):
self.assertIsNotNone(
dm_memorytasks.load_from_disk(
FLAGS.path,
settings=dm_memorytasks.EnvironmentSettings(
seed=123, level_name=level_name)))
if __name__ == '__main__':
absltest.main()
| dm_memorytasks-master | dm_memorytasks/load_from_disk_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.
# ============================================================================
"""Python utilities for running dm_memorytasks."""
from dm_memorytasks import _load_environment
from dm_memorytasks._version import __version__
EnvironmentSettings = _load_environment.EnvironmentSettings
MEMORY_TASK_LEVEL_NAMES = _load_environment.MEMORY_TASK_LEVEL_NAMES
load_from_disk = _load_environment.load_from_disk
load_from_docker = _load_environment.load_from_docker
| dm_memorytasks-master | dm_memorytasks/__init__.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 dm_memorytasks.load_from_docker."""
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
from dm_env import test_utils
import dm_memorytasks
FLAGS = flags.FLAGS
flags.DEFINE_string(
'docker_image_name', None,
'Name of the Docker image that contains the Memory Tasks. '
'If None, uses the default dm_memorytask name')
class LoadFromDockerTest(test_utils.EnvironmentTestMixin, absltest.TestCase):
def make_object_under_test(self):
return dm_memorytasks.load_from_docker(
name=FLAGS.docker_image_name,
settings=dm_memorytasks.EnvironmentSettings(
seed=123, level_name='spot_diff_extrapolate'))
class MemoryTaskTest(parameterized.TestCase):
@parameterized.parameters(dm_memorytasks.MEMORY_TASK_LEVEL_NAMES)
def test_load_level(self, level_name):
self.assertIsNotNone(
dm_memorytasks.load_from_docker(
name=FLAGS.docker_image_name,
settings=dm_memorytasks.EnvironmentSettings(
seed=123, level_name=level_name)))
if __name__ == '__main__':
absltest.main()
| dm_memorytasks-master | dm_memorytasks/load_from_docker_test.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.
# ==============================================================================
"""Tests for extraction."""
import base64
import dataclasses
import gzip
from typing import BinaryIO, Iterable
from absl.testing import absltest
import extraction
from fs import memoryfs
@dataclasses.dataclass(frozen=True)
class _WMTDocInput:
date: str
sentence_split: str
unsplit: str
@dataclasses.dataclass(frozen=True)
class _ArchiveFileInput:
docs: list[_WMTDocInput]
file_name: str
class ExtractionTest(absltest.TestCase):
def setUp(self):
super(ExtractionTest, self).setUp()
self.mfs = memoryfs.MemoryFS()
self.addCleanup(self.mfs.close)
def test_get_wmt_docs_from_archive_file_paths(self):
deduplicated_wmt_sorting_keys = [
('20190101000000000000\x00\x01'
'1d377af8d421d226f274f12d31d4'
'cc15e7c6f85e2e1eb2530e19b123d019d776\x00\x01'),
('20190102000000000000\x00\x01'
'e1587db7b0a1fd73546c5b475626'
'2c39f3309f8b8cc2b63a5034a80928eb533a\x00\x01'),
('20200103000000000000\x00\x01'
'f86e132442e069c17be5b53fa9f2'
'890b54007a4f12332e717e29f35d3b96accc\x00\x01'),
]
deduplicated_wmt_sorting_keys_file_name = 'wmt_ids.gz'
with self.mfs.openbin(deduplicated_wmt_sorting_keys_file_name, 'wb') as f:
_write_doc_lines_to_archive(
[k.encode() for k in deduplicated_wmt_sorting_keys], f)
archive_file_inputs = [
_ArchiveFileInput(
docs=[
_WMTDocInput('20190101', 'sentence_split_1', 'unsplit_1'),
_WMTDocInput('20190102', 'sentence_split_2', 'unsplit_2'),
],
file_name='news-docs.2019.en.filtered.gz',
),
_ArchiveFileInput(
docs=[
_WMTDocInput('20200103', 'sentence_split_3', 'unsplit_3'),
_WMTDocInput('20200103', 'duplicate', 'duplicate'),
],
file_name='news-docs.2020.en.filtered.gz',
),
]
_write_test_inputs(archive_file_inputs, self.mfs)
wmt_docs = []
for archive_file_input in archive_file_inputs:
with self.mfs.openbin(deduplicated_wmt_sorting_keys_file_name,
'rb') as keys_file:
with self.mfs.openbin(archive_file_input.file_name,
'rb') as archive_file:
wmt_docs_for_archive = extraction.get_deduplicated_wmt_docs(
wmt_archive_files=[archive_file],
deduplicated_sorting_keys_file=keys_file,
)
wmt_docs.extend(wmt_docs_for_archive)
wmt_docs.sort(key=lambda x: x.sorting_key)
self.assertEqual([
extraction.WMTDoc(
sorting_key=deduplicated_wmt_sorting_keys[0],
publication_ts=1546300800,
text=b'sentence_split_1',
),
extraction.WMTDoc(
sorting_key=deduplicated_wmt_sorting_keys[1],
publication_ts=1546387200,
text=b'sentence_split_2',
),
extraction.WMTDoc(
sorting_key=deduplicated_wmt_sorting_keys[2],
publication_ts=1578009600,
text=b'sentence_split_3',
)
], wmt_docs)
def test_get_wmt_passages_from_docs(self):
self.assertEqual([
extraction.WMTPassage(id='doc_0_0', text=b'1. 2. 3. 4. 5. 6.'),
extraction.WMTPassage(id='doc_0_1', text=b'7.'),
extraction.WMTPassage(id='doc_1_0', text=b'1. 2. 3. 4. 5.'),
extraction.WMTPassage(id='doc_2_0', text=b'1. 2. 3. 4. 5.'),
extraction.WMTPassage(id='doc_3_0', text=b'1. 2. 3. 4. 5.'),
extraction.WMTPassage(id='doc_4_0', text=b'1. 2. 3. 4. 5? 6. 7.'),
],
list(
extraction.get_wmt_passages_from_docs(
[
extraction.WMTDoc(
sorting_key='doc_0',
publication_ts=0,
text=b'1. 2. 3. 4. 5. 6. 7.'),
extraction.WMTDoc(
sorting_key='doc_1',
publication_ts=0,
text=b'1. 2. 3. 4. 5.'),
extraction.WMTDoc(
sorting_key='doc_2',
publication_ts=0,
text=b'1. 2. 3. 4.\n5.'),
extraction.WMTDoc(
sorting_key='doc_3',
publication_ts=0,
text=b'1. 2. 3. 4.\n 5.'),
extraction.WMTDoc(
sorting_key='doc_4',
publication_ts=0,
text=b'1. 2. 3. 4. 5? 6. 7.'),
],
prepend_date=False)))
self.assertEqual([
extraction.WMTPassage(
id='doc_0_0',
text=b'Thursday, January 1, 1970. 1. 2. 3. 4. 5. 6.',
),
extraction.WMTPassage(
id='doc_0_1',
text=b'Thursday, January 1, 1970. 7.',
),
],
list(
extraction.get_wmt_passages_from_docs([
extraction.WMTDoc(
sorting_key='doc_0',
publication_ts=0,
text=b'1. 2. 3. 4. 5. 6. 7.')
])))
def _write_test_inputs(archive_file_inputs: Iterable[_ArchiveFileInput],
memory_fs: memoryfs.MemoryFS):
for archive in archive_file_inputs:
doc_lines = [_get_doc_line(doc) for doc in archive.docs]
with memory_fs.openbin(archive.file_name, 'wb') as f:
_write_doc_lines_to_archive(doc_lines, f)
def _get_doc_line(wmt_doc: _WMTDocInput) -> bytes:
return b'\t'.join([
wmt_doc.date.encode(),
base64.b64encode(wmt_doc.sentence_split.encode()),
base64.b64encode(wmt_doc.unsplit.encode()),
])
def _write_doc_lines_to_archive(doc_lines: Iterable[bytes],
file_object: BinaryIO):
with gzip.open(file_object, 'wb') as gfb:
gfb.write(b'\n'.join(doc_lines))
if __name__ == '__main__':
absltest.main()
| streamingqa-main | extraction_test.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.
# ==============================================================================
"""WMT docs extraction.
The exported functions are:
`get_deduplicated_wmt_docs`
1) takes the `gz` document-split versions of the WMT News Crawl from
'https://data.statmt.org/news-crawl/README',
2) extracts the documents,
3) filters out duplicates,
4) and then yields the lines parsed into `WMTDoc` objects.
`get_wmt_passages_from_docs`
1) takes the `WMTDoc`s from the previous output
2) splits the articles into sentences
3) and yields them as `WMTPassage` chunks.
"""
import base64
import dataclasses
import datetime
import gzip
import hashlib
from typing import BinaryIO, Iterable, Iterator, Union
import pytz
_EXTRACTION_FIELD_SEPARATOR = b'\t'
_EXTRACTION_DATE_FORMAT = '%Y%m%d'
_SORTING_KEY_DATE_FORMAT = '%Y%m%d%H%M%S%f'
_SORTING_KEY_FIELD_SEPARATOR = '\x00\x01'
_PASSAGE_ID = '{sorting_key}_{passage_idx}'
_PASSAGE_SENTENCE_SEPARATOR = b'. '
_PASSAGE_NUM_SENTENCES = 6
_PASSAGE_DATE_PREFIX_FORMAT = '%A, %B %-d, %Y'
@dataclasses.dataclass(frozen=True)
class WMTDoc:
"""The input extracted from the WMT archive files.
Attributes:
sorting_key: The assigned sorting key to the document.
publication_ts: Publication date of the document as UTC timestamp seconds.
text: The processed document text / article.
"""
sorting_key: str
publication_ts: int
text: bytes
@dataclasses.dataclass(frozen=True)
class WMTPassage:
"""A passage from a sequence of `WMTDoc` article sentence chunks.
Attributes:
id: Assigned ID consisting of the original `WMTDoc` `sorting_key` and an
index for the passage position in the original article.
text: A chunk from a sequence of sentences extracted from the `WMTDoc`
article.
"""
id: str
text: bytes
def get_deduplicated_wmt_docs(
wmt_archive_files: Iterable[Union[str, BinaryIO]],
deduplicated_sorting_keys_file: Union[str, BinaryIO]) -> Iterator[WMTDoc]:
"""Reads and yields deduplicated `WMTDoc`s from the WMT News Crawl.
Args:
wmt_archive_files: List of file paths or file path objects of the WMT News
Crawl dataset `.gz` files.
deduplicated_sorting_keys_file: File path to the gzipped newline delimited
txt file of deduplicated WMT sorting key IDs.
Yields:
Extracted and filtered `WMTDoc` objects.
"""
with gzip.open(deduplicated_sorting_keys_file) as f:
sorting_keys = set(line.strip().decode() for line in f)
for file_path_or_object in wmt_archive_files:
with gzip.open(file_path_or_object) as f:
for line in f:
doc = _extract_doc(line)
if doc.sorting_key in sorting_keys:
yield doc
def get_wmt_passages_from_docs(
wmt_docs: Iterable[WMTDoc],
prepend_date: bool = True) -> Iterator[WMTPassage]:
"""Yields `WMTPassage`s based on sentence split and chunked `WMTDoc` articles.
Args:
wmt_docs: The articles to be sentence split and chunked into passages.
prepend_date: If True, will prepend the article publication date to each
extracted passage.
Yields:
WMT passages as ID and text which can be used for the retrieval search
space.
"""
for doc in wmt_docs:
article = doc.text + b' '
article = article.replace(b'.\n', _PASSAGE_SENTENCE_SEPARATOR)
sentences = [s.strip() for s in article.split(_PASSAGE_SENTENCE_SEPARATOR)]
sentences = [s for s in sentences if s]
for p_i, s_i in enumerate(range(0, len(sentences), _PASSAGE_NUM_SENTENCES)):
chunk = sentences[s_i:s_i + _PASSAGE_NUM_SENTENCES]
passage = _PASSAGE_SENTENCE_SEPARATOR.join(chunk) + b'.'
if prepend_date:
prefix = datetime.datetime.fromtimestamp(
doc.publication_ts).strftime(_PASSAGE_DATE_PREFIX_FORMAT).encode()
passage = _PASSAGE_SENTENCE_SEPARATOR.join([prefix, passage])
passage_id = _PASSAGE_ID.format(
sorting_key=doc.sorting_key, passage_idx=p_i)
yield WMTPassage(id=passage_id, text=passage)
def _extract_doc(doc_line: bytes) -> WMTDoc:
"""Processes a doc line (= one line per doc) from the WMT dataset file."""
try:
publication_date, sentence_split_doc_line, unsplit_doc_line = (
doc_line.strip().split(_EXTRACTION_FIELD_SEPARATOR))
except ValueError as e:
raise ValueError('Failed to parse doc line') from e
# pylint: disable=g-tzinfo-replace
publication_dt = datetime.datetime.strptime(
publication_date.decode(),
_EXTRACTION_DATE_FORMAT).replace(tzinfo=pytz.UTC)
line_hash = hashlib.sha256(unsplit_doc_line).hexdigest()
sorting_key = _SORTING_KEY_FIELD_SEPARATOR.join([
publication_dt.strftime(_SORTING_KEY_DATE_FORMAT),
line_hash,
'',
])
return WMTDoc(
sorting_key=sorting_key,
publication_ts=int(publication_dt.timestamp()),
text=base64.b64decode(sentence_split_doc_line),
)
| streamingqa-main | extraction.py |
# Copyright 2017-2018 The dm_control Authors.
#
# 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 fnmatch
import logging
import os
import platform
import subprocess
import sys
import mujoco
import setuptools
from setuptools import find_packages
from setuptools import setup
from setuptools.command import install
from setuptools.command import test
PLATFORM = platform.system()
# Relative paths to the binding generator script and the output directory.
AUTOWRAP_PATH = 'dm_control/autowrap/autowrap.py'
MJBINDINGS_DIR = 'dm_control/mujoco/wrapper/mjbindings'
# We specify the header filenames explicitly rather than listing the contents
# of the `HEADERS_DIR` at runtime, since it will probably contain other stuff
# (e.g. `glfw.h`).
HEADER_FILENAMES = [
'mjdata.h',
'mjmodel.h',
'mjrender.h',
'mjtnum.h',
'mjui.h',
'mjvisualize.h',
'mjxmacro.h',
'mujoco.h',
]
def _initialize_mjbindings_options(cmd_instance):
"""Set default values for options relating to `build_mjbindings`."""
# A default value must be assigned to each user option here.
cmd_instance.inplace = 0
cmd_instance.headers_dir = mujoco.HEADERS_DIR
def _finalize_mjbindings_options(cmd_instance):
"""Post-process options relating to `build_mjbindings`."""
headers_dir = os.path.expanduser(cmd_instance.headers_dir)
header_paths = []
for filename in HEADER_FILENAMES:
full_path = os.path.join(headers_dir, filename)
if not os.path.exists(full_path):
raise IOError('Header file {!r} does not exist.'.format(full_path))
header_paths.append(full_path)
cmd_instance.header_paths = ' '.join(header_paths)
class BuildMJBindingsCommand(setuptools.Command):
"""Runs `autowrap.py` to generate the low-level ctypes bindings for MuJoCo."""
description = __doc__
user_options = [
# The format is (long option, short option, description).
('headers-dir=', None,
'Path to directory containing MuJoCo headers.'),
('inplace=', None,
'Place generated files in source directory rather than `build-lib`.'),
]
boolean_options = ['inplace']
def initialize_options(self):
_initialize_mjbindings_options(self)
def finalize_options(self):
_finalize_mjbindings_options(self)
def run(self):
cwd = os.path.realpath(os.curdir)
if self.inplace:
dist_root = cwd
else:
build_cmd = self.get_finalized_command('build')
dist_root = os.path.realpath(build_cmd.build_lib)
output_dir = os.path.join(dist_root, MJBINDINGS_DIR)
command = [
sys.executable or 'python',
AUTOWRAP_PATH,
'--header_paths={}'.format(self.header_paths),
'--output_dir={}'.format(output_dir)
]
self.announce('Running command: {}'.format(command), level=logging.DEBUG)
try:
# Prepend the current directory to $PYTHONPATH so that internal imports
# in `autowrap` can succeed before we've installed anything.
old_environ = os.environ.copy()
new_pythonpath = [cwd]
if 'PYTHONPATH' in old_environ:
new_pythonpath.append(old_environ['PYTHONPATH'])
os.environ['PYTHONPATH'] = ':'.join(new_pythonpath)
subprocess.check_call(command)
finally:
os.environ = old_environ
class InstallCommand(install.install):
"""Runs 'build_mjbindings' before installation."""
user_options = (
install.install.user_options + BuildMJBindingsCommand.user_options)
boolean_options = (
install.install.boolean_options + BuildMJBindingsCommand.boolean_options)
def initialize_options(self):
install.install.initialize_options(self)
_initialize_mjbindings_options(self)
def finalize_options(self):
install.install.finalize_options(self)
_finalize_mjbindings_options(self)
def run(self):
self.reinitialize_command('build_mjbindings',
inplace=self.inplace,
headers_dir=self.headers_dir)
self.run_command('build_mjbindings')
install.install.run(self)
class TestCommand(test.test):
"""Prepends path to generated sources before running unit tests."""
def run(self):
# Generate ctypes bindings in-place so that they can be imported in tests.
self.reinitialize_command('build_mjbindings', inplace=1)
self.run_command('build_mjbindings')
test.test.run(self)
def find_data_files(package_dir, patterns, excludes=()):
"""Recursively finds files whose names match the given shell patterns."""
paths = set()
def is_excluded(s):
for exclude in excludes:
if fnmatch.fnmatch(s, exclude):
return True
return False
for directory, _, filenames in os.walk(package_dir):
if is_excluded(directory):
continue
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)
full_path = os.path.join(relative_dirpath, filename)
if not is_excluded(full_path):
paths.add(full_path)
return list(paths)
setup(
name='dm_control',
version='1.0.14',
description='Continuous control environments and MuJoCo Python bindings.',
long_description="""
# `dm_control`: DeepMind Infrastructure for Physics-Based Simulation.
DeepMind's software stack for physics-based simulation and Reinforcement
Learning environments, using MuJoCo physics.
An **introductory tutorial** for this package is available as a Colaboratory
notebook: [Open In Google Colab](https://colab.research.google.com/github/deepmind/dm_control/blob/main/tutorial.ipynb).
""",
long_description_content_type='text/markdown',
author='DeepMind',
author_email='[email protected]',
url='https://github.com/deepmind/dm_control',
license='Apache License 2.0',
classifiers=[
'License :: OSI Approved :: Apache Software License',
],
keywords='machine learning control physics MuJoCo AI',
python_requires='>=3.8',
install_requires=[
'absl-py>=0.7.0',
'dm-env',
'dm-tree != 0.1.2',
'glfw',
'labmaze',
'lxml',
'mujoco >= 2.3.7',
'numpy >= 1.9.0',
'protobuf >= 3.19.4', # TensorFlow requires protobuf<3.20 (b/182876485)
'pyopengl >= 3.1.4',
'pyparsing >= 3.0.0',
'requests',
'setuptools!=50.0.0', # https://github.com/pypa/setuptools/issues/2350
'scipy',
'tqdm',
],
extras_require={
'HDF5': ['h5py'],
},
tests_require=[
'mock',
'nose',
'pillow>=9.0.1', # https://github.com/advisories/GHSA-8vj2-vxx3-667w
],
test_suite='nose.collector',
packages=find_packages(),
package_data={
'dm_control':
find_data_files(
package_dir='dm_control',
patterns=[
'*.amc', '*.msh', '*.png', '*.skn', '*.stl', '*.xml',
'*.textproto', '*.h5'
],
excludes=[
'*/dog_assets/extras/*',
'*/kinova/meshes/*', # Exclude non-decimated meshes.
]),
},
cmdclass={
'build_mjbindings': BuildMJBindingsCommand,
'install': InstallCommand,
'test': TestCommand,
},
entry_points={},
)
| dm_control-main | setup.py |
# Copyright 2017 The dm_control Authors.
#
# 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.
# ============================================================================
| dm_control-main | dm_control/__init__.py |
# Copyright 2018 The dm_control Authors.
#
# 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 `mjcf.debugging`."""
import contextlib
import os
import re
import shutil
import sys
from absl.testing import absltest
from dm_control import mjcf
from dm_control.mjcf import code_for_debugging_test as test_code
from dm_control.mjcf import debugging
ORIGINAL_DEBUG_MODE = debugging.debug_mode()
class DebuggingTest(absltest.TestCase):
def tearDown(self):
super().tearDown()
if ORIGINAL_DEBUG_MODE:
debugging.enable_debug_mode()
else:
debugging.disable_debug_mode()
def setup_debug_mode(self, debug_mode_enabled, full_dump_enabled=False):
if debug_mode_enabled:
debugging.enable_debug_mode()
else:
debugging.disable_debug_mode()
if full_dump_enabled:
base_dir = absltest.get_default_test_tmpdir()
self.dump_dir = os.path.join(base_dir, 'mjcf_debugging_test')
shutil.rmtree(self.dump_dir, ignore_errors=True)
os.mkdir(self.dump_dir)
else:
self.dump_dir = ''
debugging.set_full_dump_dir(self.dump_dir)
def assertStackFromTestCode(self, stack, function_name, line_ref):
self.assertEqual(stack[-1].function_name, function_name)
self.assertStartsWith(test_code.__file__, stack[-1].filename)
line_info = test_code.LINE_REF['.'.join([function_name, line_ref])]
self.assertEqual(stack[-1].line_number, line_info.line_number)
self.assertEqual(stack[-1].text, line_info.text)
@contextlib.contextmanager
def assertRaisesTestCodeRef(self, line_ref):
filename, _ = os.path.splitext(test_code.__file__)
expected_message = (
filename + '.py:' + str(test_code.LINE_REF[line_ref].line_number))
print(expected_message)
with self.assertRaisesRegex(ValueError, expected_message):
yield
def test_get_current_stack_trace(self):
self.setup_debug_mode(debug_mode_enabled=True)
stack_trace = debugging.get_current_stack_trace()
self.assertStartsWith(
sys.modules[__name__].__file__, stack_trace[-1].filename)
self.assertEqual(stack_trace[-1].function_name,
'test_get_current_stack_trace')
self.assertEqual(stack_trace[-1].text,
'stack_trace = debugging.get_current_stack_trace()')
def test_disable_debug_mode(self):
self.setup_debug_mode(debug_mode_enabled=False)
mjcf_model = test_code.make_valid_model()
test_code.break_valid_model(mjcf_model)
self.assertFalse(mjcf_model.get_init_stack())
my_actuator = mjcf_model.find('actuator', 'my_actuator')
my_actuator_attrib_stacks = (
my_actuator.get_last_modified_stacks_for_all_attributes())
for stack in my_actuator_attrib_stacks.values():
self.assertFalse(stack)
def test_element_and_attribute_stacks(self):
self.setup_debug_mode(debug_mode_enabled=True)
mjcf_model = test_code.make_valid_model()
test_code.break_valid_model(mjcf_model)
self.assertStackFromTestCode(mjcf_model.get_init_stack(),
'make_valid_model', 'mjcf_model')
my_actuator = mjcf_model.find('actuator', 'my_actuator')
self.assertStackFromTestCode(my_actuator.get_init_stack(),
'make_valid_model', 'my_actuator')
my_actuator_attrib_stacks = (
my_actuator.get_last_modified_stacks_for_all_attributes())
# `name` attribute was assigned at the same time as the element was created.
self.assertEqual(my_actuator_attrib_stacks['name'],
my_actuator.get_init_stack())
# `joint` attribute was modified later on.
self.assertStackFromTestCode(my_actuator_attrib_stacks['joint'],
'break_valid_model', 'my_actuator.joint')
def test_valid_physics(self):
self.setup_debug_mode(debug_mode_enabled=True)
mjcf_model = test_code.make_valid_model()
mjcf.Physics.from_mjcf_model(mjcf_model) # Should not raise
def test_physics_error_message_outside_of_debug_mode(self):
self.setup_debug_mode(debug_mode_enabled=False)
mjcf_model = test_code.make_broken_model()
# Make sure that we advertise debug mode if it's currently disabled.
with self.assertRaisesRegex(ValueError, '--pymjcf_debug'):
mjcf.Physics.from_mjcf_model(mjcf_model)
def test_physics_error_message_in_debug_mode(self):
self.setup_debug_mode(debug_mode_enabled=True)
mjcf_model_1 = test_code.make_broken_model()
with self.assertRaisesTestCodeRef('make_broken_model.my_actuator'):
mjcf.Physics.from_mjcf_model(mjcf_model_1)
mjcf_model_2 = test_code.make_valid_model()
physics = mjcf.Physics.from_mjcf_model(mjcf_model_2) # Should not raise.
test_code.break_valid_model(mjcf_model_2)
with self.assertRaisesTestCodeRef('break_valid_model.my_actuator.joint'):
physics.reload_from_mjcf_model(mjcf_model_2)
def test_full_debug_dump(self):
self.setup_debug_mode(debug_mode_enabled=True, full_dump_enabled=False)
mjcf_model = test_code.make_valid_model()
test_code.break_valid_model(mjcf_model)
# Make sure that we advertise full dump mode if it's currently disabled.
with self.assertRaisesRegex(ValueError, '--pymjcf_debug_full_dump_dir'):
mjcf.Physics.from_mjcf_model(mjcf_model)
self.setup_debug_mode(debug_mode_enabled=True, full_dump_enabled=True)
with self.assertRaises(ValueError):
mjcf.Physics.from_mjcf_model(mjcf_model)
with open(os.path.join(self.dump_dir, 'model.xml')) as f:
dumped_xml = f.read()
dumped_xml = [line.strip() for line in dumped_xml.strip().split('\n')]
xml_line_pattern = re.compile(r'^(.*)<!--pymjcfdebug:(\d+)-->$')
uninstrumented_pattern = re.compile(r'({})'.format(
'|'.join([
r'<mujoco model=".*">',
r'</mujoco>',
r'<default class=".*/"/?>',
r'</default>'
])))
for xml_line in dumped_xml:
print(xml_line)
xml_line_match = xml_line_pattern.match(xml_line)
if not xml_line_match:
# Only uninstrumented lines are allowed to have no metadata.
self.assertIsNotNone(uninstrumented_pattern.match(xml_line))
else:
xml_element = xml_line_match.group(1)
debug_id = int(xml_line_match.group(2))
with open(os.path.join(self.dump_dir, str(debug_id) + '.dump')) as f:
element_dump = f.read()
self.assertIn(xml_element, element_dump)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/mjcf/debugging_test.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.