python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
---|---|---|
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Neural Fictitious Self-Play (NFSP) agent implemented in Jax.
The code is around 4x slower than the TF implementation at the moment. Future
PRs improving the runtime are welcome.
See the paper https://arxiv.org/abs/1603.01121 for more details.
"""
import collections
import contextlib
import enum
import os
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
from open_spiel.python import rl_agent
from open_spiel.python.jax import dqn
from open_spiel.python.utils.reservoir_buffer import ReservoirBuffer
Transition = collections.namedtuple(
"Transition", "info_state action_probs legal_actions_mask")
MODE = enum.Enum("mode", "best_response average_policy")
class NFSP(rl_agent.AbstractAgent):
"""NFSP Agent implementation in JAX.
See open_spiel/python/examples/kuhn_nfsp.py for an usage example.
"""
def __init__(self,
player_id,
state_representation_size,
num_actions,
hidden_layers_sizes,
reservoir_buffer_capacity,
anticipatory_param,
batch_size=128,
rl_learning_rate=0.01,
sl_learning_rate=0.01,
min_buffer_size_to_learn=1000,
learn_every=64,
optimizer_str="sgd",
**kwargs):
"""Initialize the `NFSP` agent."""
self.player_id = player_id
self._num_actions = num_actions
self._layer_sizes = hidden_layers_sizes
self._batch_size = batch_size
self._learn_every = learn_every
self._anticipatory_param = anticipatory_param
self._min_buffer_size_to_learn = min_buffer_size_to_learn
self._reservoir_buffer = ReservoirBuffer(reservoir_buffer_capacity)
self._prev_timestep = None
self._prev_action = None
# Step counter to keep track of learning.
self._step_counter = 0
# Inner RL agent
kwargs.update({
"batch_size": batch_size,
"learning_rate": rl_learning_rate,
"learn_every": learn_every,
"min_buffer_size_to_learn": min_buffer_size_to_learn,
"optimizer_str": optimizer_str,
})
self._rl_agent = dqn.DQN(player_id, state_representation_size,
num_actions, hidden_layers_sizes, **kwargs)
# Keep track of the last training loss achieved in an update step.
self._last_rl_loss_value = lambda: self._rl_agent.loss
self._last_sl_loss_value = None
# Average policy network.
def network(x):
mlp = hk.nets.MLP(self._layer_sizes + [num_actions])
return mlp(x)
self.hk_avg_network = hk.without_apply_rng(hk.transform(network))
def avg_network_policy(param, info_state):
action_values = self.hk_avg_network.apply(param, info_state)
action_probs = jax.nn.softmax(action_values, axis=1)
return action_values, action_probs
self._avg_network_policy = jax.jit(avg_network_policy)
rng = jax.random.PRNGKey(42)
x = jnp.ones([1, state_representation_size])
self.params_avg_network = self.hk_avg_network.init(rng, x)
self.params_avg_network = jax.device_put(self.params_avg_network)
self._savers = [
("q_network", self._rl_agent.params_q_network),
("avg_network", self.params_avg_network)
]
if optimizer_str == "adam":
opt_init, opt_update = optax.chain(
optax.scale_by_adam(b1=0.9, b2=0.999, eps=1e-8),
optax.scale(sl_learning_rate))
elif optimizer_str == "sgd":
opt_init, opt_update = optax.sgd(sl_learning_rate)
else:
raise ValueError("Not implemented. Choose from ['adam', 'sgd'].")
self._opt_update_fn = self._get_update_func(opt_update)
self._opt_state = opt_init(self.params_avg_network)
self._loss_and_grad = jax.value_and_grad(self._loss_avg, has_aux=False)
self._sample_episode_policy()
self._jit_update = jax.jit(self.get_update())
def _get_update_func(self, opt_update):
def update(params, opt_state, gradient):
"""Learning rule (stochastic gradient descent)."""
updates, opt_state = opt_update(gradient, opt_state)
new_params = optax.apply_updates(params, updates)
return new_params, opt_state
return update
def get_step_counter(self):
return self._step_counter
@contextlib.contextmanager
def temp_mode_as(self, mode):
"""Context manager to temporarily overwrite the mode."""
previous_mode = self._mode
self._mode = mode
yield
self._mode = previous_mode
def _sample_episode_policy(self):
if np.random.rand() < self._anticipatory_param:
self._mode = MODE.best_response
else:
self._mode = MODE.average_policy
def _act(self, info_state, legal_actions):
info_state = np.reshape(info_state, [1, -1])
action_values, action_probs = self._avg_network_policy(
self.params_avg_network, info_state
)
self._last_action_values = action_values[0]
# Remove illegal actions, normalize probs
probs = np.zeros(self._num_actions)
action_probs = np.asarray(action_probs)
probs[legal_actions] = action_probs[0][legal_actions]
probs /= sum(probs)
action = np.random.choice(len(probs), p=probs)
return action, probs
@property
def mode(self):
return self._mode
@property
def loss(self):
return (self._last_sl_loss_value, self._last_rl_loss_value())
def step(self, time_step, is_evaluation=False):
"""Returns the action to be taken and updates the Q-networks if needed.
Args:
time_step: an instance of rl_environment.TimeStep.
is_evaluation: bool, whether this is a training or evaluation call.
Returns:
A `rl_agent.StepOutput` containing the action probs and chosen action.
"""
if self._mode == MODE.best_response:
agent_output = self._rl_agent.step(time_step, is_evaluation)
if not is_evaluation and not time_step.last():
self._add_transition(time_step, agent_output)
elif self._mode == MODE.average_policy:
# Act step: don't act at terminal info states.
if not time_step.last():
info_state = time_step.observations["info_state"][self.player_id]
legal_actions = time_step.observations["legal_actions"][self.player_id]
action, probs = self._act(info_state, legal_actions)
agent_output = rl_agent.StepOutput(action=action, probs=probs)
if self._prev_timestep and not is_evaluation:
self._rl_agent.add_transition(self._prev_timestep, self._prev_action,
time_step)
else:
raise ValueError("Invalid mode ({})".format(self._mode))
if not is_evaluation:
self._step_counter += 1
if self._step_counter % self._learn_every == 0:
self._last_sl_loss_value = self._learn()
# If learn step not triggered by rl policy, learn.
if self._mode == MODE.average_policy:
self._rl_agent.learn()
# Prepare for the next episode.
if time_step.last():
self._sample_episode_policy()
self._prev_timestep = None
self._prev_action = None
return
else:
self._prev_timestep = time_step
self._prev_action = agent_output.action
return agent_output
def _add_transition(self, time_step, agent_output):
"""Adds the new transition using `time_step` to the reservoir buffer.
Transitions are in the form (time_step, agent_output.probs, legal_mask).
Args:
time_step: an instance of rl_environment.TimeStep.
agent_output: an instance of rl_agent.StepOutput.
"""
legal_actions = time_step.observations["legal_actions"][self.player_id]
legal_actions_mask = np.zeros(self._num_actions)
legal_actions_mask[legal_actions] = 1.0
transition = Transition(
info_state=(time_step.observations["info_state"][self.player_id][:]),
action_probs=agent_output.probs,
legal_actions_mask=legal_actions_mask)
self._reservoir_buffer.add(transition)
def _loss_avg(self, param_avg, info_states, action_probs):
avg_logit = self.hk_avg_network.apply(param_avg, info_states)
loss_value = -jnp.sum(
action_probs * jax.nn.log_softmax(avg_logit)) / avg_logit.shape[0]
return loss_value
def get_update(self):
def update(param_avg, opt_state_avg, info_states, action_probs):
loss_val, grad_val = self._loss_and_grad(param_avg, info_states,
action_probs)
new_param_avg, new_opt_state_avg = self._opt_update_fn(
param_avg, opt_state_avg, grad_val)
return new_param_avg, new_opt_state_avg, loss_val
return update
def _learn(self):
"""Compute the loss on sampled transitions and perform a avg-network update.
If there are not enough elements in the buffer, no loss is computed and
`None` is returned instead.
Returns:
The average loss obtained on this batch of transitions or `None`.
"""
if (len(self._reservoir_buffer) < self._batch_size or
len(self._reservoir_buffer) < self._min_buffer_size_to_learn):
return None
transitions = self._reservoir_buffer.sample(self._batch_size)
info_states = np.asarray([t.info_state for t in transitions])
action_probs = np.asarray([t.action_probs for t in transitions])
self.params_avg_network, self._opt_state, loss_val_avg = self._jit_update(
self.params_avg_network, self._opt_state, info_states, action_probs)
return loss_val_avg
def _full_checkpoint_name(self, checkpoint_dir, name):
checkpoint_filename = "_".join([name, "pid" + str(self.player_id)])
return os.path.join(checkpoint_dir, checkpoint_filename)
def _latest_checkpoint_filename(self, name):
checkpoint_filename = "_".join([name, "pid" + str(self.player_id)])
return checkpoint_filename + "_latest"
def save(self, checkpoint_dir):
"""Saves the average policy network and the inner RL agent's q-network.
Note that this does not save the experience replay buffers and should
only be used to restore the agent's policy, not resume training.
Args:
checkpoint_dir: directory where checkpoints will be saved.
"""
raise NotImplementedError
def has_checkpoint(self, checkpoint_dir):
for name, _ in self._savers:
path = self._full_checkpoint_name(checkpoint_dir, name)
if os.path.exists(path):
return True
return False
def restore(self, checkpoint_dir):
"""Restores the average policy network and the inner RL agent's q-network.
Note that this does not restore the experience replay buffers and should
only be used to restore the agent's policy, not resume training.
Args:
checkpoint_dir: directory from which checkpoints will be restored.
"""
raise NotImplementedError
| open_spiel-master | open_spiel/python/jax/nfsp.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.
"""Boltzmann DQN agent implemented in JAX.
This algorithm is a variation of DQN that uses a softmax policy directly with
the unregularized action-value function. See https://arxiv.org/abs/2102.01585.
"""
import jax
import jax.numpy as jnp
import numpy as np
from open_spiel.python.jax import dqn
class BoltzmannDQN(dqn.DQN):
"""Boltzmann DQN implementation in JAX."""
def __init__(self, *args, eta: float = 1.0, seed: int = 42, **kwargs):
"""Initializes the Boltzmann DQN agent.
Args:
*args: args passed to the underlying DQN agent.
eta: Temperature parameter used in the softmax function.
seed: Random seed used for action selection.
**kwargs: kwargs passed to the underlying DQN agent.
"""
self._eta = eta
self._rs = np.random.RandomState(seed) # Used to select actions.
super().__init__(*args, seed=seed, **kwargs)
def _create_networks(self, rng, state_representation_size):
"""Called to create the networks."""
# We use the DQN networks and an additional network for the fixed policy.
super()._create_networks(rng, state_representation_size)
self.params_prev_q_network = self.hk_network.init(
rng, jnp.ones([1, state_representation_size]))
def _softmax_action_probs(self,
params,
info_state,
legal_actions,
coeff=None):
"""Returns a valid soft-max action and action probabilities.
Args:
params: Parameters of the Q-network.
info_state: Observations from the environment.
legal_actions: List of legal actions.
coeff: If not None, then the terms in softmax function will be
element-wise multiplied with these coefficients.
Returns:
a valid soft-max action and action probabilities.
"""
info_state = np.reshape(info_state, [1, -1])
q_values = self.hk_network_apply(params, info_state)[0]
legal_one_hot = self._to_one_hot(legal_actions)
legal_q_values = (
q_values + (1 - legal_one_hot) * dqn.ILLEGAL_ACTION_LOGITS_PENALTY)
# Apply temperature and subtract the maximum value for numerical stability.
temp = legal_q_values / self._eta
unnormalized = np.exp(temp - np.amax(temp))
if coeff is not None:
unnormalized = np.multiply(coeff, unnormalized)
probs = unnormalized / unnormalized.sum()
action = self._rs.choice(legal_actions, p=probs[legal_actions])
return action, probs
def _get_action_probs(self, info_state, legal_actions, is_evaluation=False):
"""Returns a selected action and the probabilities of legal actions."""
if is_evaluation:
# Soft-max normalized by the action probabilities from the previous
# Q-network.
_, prev_probs = self._softmax_action_probs(self.params_prev_q_network,
info_state, legal_actions)
return self._softmax_action_probs(self.params_q_network, info_state,
legal_actions, prev_probs)
# During training, we use the DQN action selection, which will be
# epsilon-greedy.
return super()._get_action_probs(
info_state, legal_actions, is_evaluation=False)
def update_prev_q_network(self):
"""Updates the parameters of the previous Q-network."""
self.params_prev_q_network = jax.tree_map(lambda x: x.copy(),
self.params_q_network)
| open_spiel-master | open_spiel/python/jax/boltzmann_dqn.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for open_spiel.python.jax.policy_gradient."""
import itertools
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from open_spiel.python import rl_environment
from open_spiel.python.jax import policy_gradient
import pyspiel
SEED = 24984617
class PolicyGradientTest(parameterized.TestCase, absltest.TestCase):
@parameterized.parameters(
itertools.product(("rpg", "qpg", "rm", "a2c"),
("kuhn_poker", "leduc_poker")))
def test_run_game(self, loss_str, game_name):
env = rl_environment.Environment(game_name)
env.seed(SEED)
info_state_size = env.observation_spec()["info_state"][0]
num_actions = env.action_spec()["num_actions"]
agents = [
policy_gradient.PolicyGradient( # pylint: disable=g-complex-comprehension
player_id=player_id,
info_state_size=info_state_size,
num_actions=num_actions,
loss_str=loss_str,
hidden_layers_sizes=[32, 32],
lambda_=1.0,
entropy_cost=0.001,
critic_learning_rate=0.01,
pi_learning_rate=0.01,
num_critic_before_pi=4,
seed=SEED) for player_id in [0, 1]
]
for _ in range(2):
time_step = env.reset()
while not time_step.last():
current_player = time_step.observations["current_player"]
current_agent = agents[current_player]
agent_output = current_agent.step(time_step)
time_step = env.step([agent_output.action])
for agent in agents:
agent.step(time_step)
def test_run_hanabi(self):
# Hanabi is an optional game, so check we have it before running the test.
game = "hanabi"
if game not in pyspiel.registered_names():
return
num_players = 3
env_configs = {
"players": num_players,
"max_life_tokens": 1,
"colors": 2,
"ranks": 3,
"hand_size": 2,
"max_information_tokens": 3,
"discount": 0.99
}
env = rl_environment.Environment(game, **env_configs)
env.seed(SEED)
info_state_size = env.observation_spec()["info_state"][0]
num_actions = env.action_spec()["num_actions"]
agents = [
policy_gradient.PolicyGradient( # pylint: disable=g-complex-comprehension
player_id=player_id,
info_state_size=info_state_size,
num_actions=num_actions,
hidden_layers_sizes=[8, 8],
lambda_=1.0,
entropy_cost=0.001,
critic_learning_rate=0.001,
pi_learning_rate=0.001,
num_critic_before_pi=4,
seed=SEED) for player_id in range(num_players)
]
time_step = env.reset()
while not time_step.last():
current_player = time_step.observations["current_player"]
agent_output = [agent.step(time_step) for agent in agents]
time_step = env.step([agent_output[current_player].action])
for agent in agents:
agent.step(time_step)
if __name__ == "__main__":
np.random.seed(SEED)
absltest.main()
| open_spiel-master | open_spiel/python/jax/policy_gradient_jax_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DQN agent implemented in JAX."""
import collections
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
import rlax
from open_spiel.python import rl_agent
from open_spiel.python.utils.replay_buffer import ReplayBuffer
Transition = collections.namedtuple(
"Transition",
"info_state action reward next_info_state is_final_step legal_actions_mask")
# Penalty for illegal actions in action selection. In epsilon-greedy, this will
# prevent them from being selected.
ILLEGAL_ACTION_LOGITS_PENALTY = -1e9
class DQN(rl_agent.AbstractAgent):
"""DQN Agent implementation in JAX."""
def __init__(self,
player_id,
state_representation_size,
num_actions,
hidden_layers_sizes=128,
replay_buffer_capacity=10000,
batch_size=128,
replay_buffer_class=ReplayBuffer,
learning_rate=0.01,
update_target_network_every=1000,
learn_every=10,
discount_factor=1.0,
min_buffer_size_to_learn=1000,
epsilon_start=1.0,
epsilon_end=0.1,
epsilon_decay_duration=int(1e6),
optimizer_str="sgd",
loss_str="mse",
huber_loss_parameter=1.0,
seed=42,
gradient_clipping=None):
"""Initialize the DQN agent."""
# This call to locals() is used to store every argument used to initialize
# the class instance, so it can be copied with no hyperparameter change.
self._kwargs = locals()
self.player_id = player_id
self._num_actions = num_actions
if isinstance(hidden_layers_sizes, int):
hidden_layers_sizes = [hidden_layers_sizes]
self._layer_sizes = hidden_layers_sizes
self._batch_size = batch_size
self._update_target_network_every = update_target_network_every
self._learn_every = learn_every
self._min_buffer_size_to_learn = min_buffer_size_to_learn
self._discount_factor = discount_factor
self.huber_loss_parameter = huber_loss_parameter
self._epsilon_start = epsilon_start
self._epsilon_end = epsilon_end
self._epsilon_decay_duration = epsilon_decay_duration
# TODO(author6) Allow for optional replay buffer config.
if not isinstance(replay_buffer_capacity, int):
raise ValueError("Replay buffer capacity not an integer.")
self._replay_buffer = replay_buffer_class(replay_buffer_capacity)
self._prev_timestep = None
self._prev_action = None
# Step counter to keep track of learning, eps decay and target network.
self._step_counter = 0
# Keep track of the last training loss achieved in an update step.
self._last_loss_value = None
# Create the Q-network instances
def network(x):
mlp = hk.nets.MLP(self._layer_sizes + [num_actions])
return mlp(x)
self.hk_network = hk.without_apply_rng(hk.transform(network))
self.hk_network_apply = jax.jit(self.hk_network.apply)
rng = jax.random.PRNGKey(seed)
self._create_networks(rng, state_representation_size)
if loss_str == "mse":
self.loss_func = lambda x: jnp.mean(x**2)
elif loss_str == "huber":
# pylint: disable=g-long-lambda
self.loss_func = lambda x: jnp.mean(
rlax.huber_loss(x, self.huber_loss_parameter))
else:
raise ValueError("Not implemented, choose from 'mse', 'huber'.")
if optimizer_str == "adam":
optimizer = optax.adam(learning_rate)
elif optimizer_str == "sgd":
optimizer = optax.sgd(learning_rate)
else:
raise ValueError("Not implemented, choose from 'adam' and 'sgd'.")
# Clipping the gradients prevent divergence and allow more stable training.
if gradient_clipping:
optimizer = optax.chain(optimizer,
optax.clip_by_global_norm(gradient_clipping))
opt_init, opt_update = optimizer.init, optimizer.update
self._opt_update_fn = self._get_update_func(opt_update)
self._opt_state = opt_init(self.params_q_network)
self._loss_and_grad = jax.value_and_grad(self._loss, has_aux=False)
self._jit_update = jax.jit(self.get_update())
def _create_networks(self, rng, state_representation_size):
"""Called to create the networks."""
x = jnp.ones([1, state_representation_size])
self.params_q_network = self.hk_network.init(rng, x)
self.params_target_q_network = self.hk_network.init(rng, x)
def _get_update_func(self, opt_update):
def update(params, opt_state, gradient):
"""Learning rule (stochastic gradient descent)."""
updates, opt_state = opt_update(gradient, opt_state)
new_params = optax.apply_updates(params, updates)
return new_params, opt_state
return update
def _get_action_probs(self, info_state, legal_actions, is_evaluation=False):
"""Returns a selected action and the probabilities of legal actions."""
epsilon = self._get_epsilon(is_evaluation)
return self._epsilon_greedy(info_state, legal_actions, epsilon)
def step(self, time_step, is_evaluation=False, add_transition_record=True):
"""Returns the action to be taken and updates the Q-network if needed.
Args:
time_step: an instance of rl_environment.TimeStep.
is_evaluation: bool, whether this is a training or evaluation call.
add_transition_record: Whether to add to the replay buffer on this step.
Returns:
A `rl_agent.StepOutput` containing the action probs and chosen action.
"""
# Act step: don't act at terminal info states or if its not our turn.
if (not time_step.last()) and (time_step.is_simultaneous_move() or
self.player_id
== time_step.current_player()):
info_state = time_step.observations["info_state"][self.player_id]
legal_actions = time_step.observations["legal_actions"][self.player_id]
action, probs = self._get_action_probs(
info_state, legal_actions, is_evaluation=is_evaluation)
else:
action = None
probs = []
# Don't mess up with the state during evaluation.
if not is_evaluation:
self._step_counter += 1
if self._step_counter % self._learn_every == 0:
self._last_loss_value = self.learn()
if self._step_counter % self._update_target_network_every == 0:
# state_dict method returns a dictionary containing a whole state of the
# module.
self.params_target_q_network = jax.tree_map(
lambda x: x.copy(), self.params_q_network)
if self._prev_timestep and add_transition_record:
# We may omit record adding here if it's done elsewhere.
self.add_transition(self._prev_timestep, self._prev_action, time_step)
if time_step.last(): # prepare for the next episode.
self._prev_timestep = None
self._prev_action = None
return
else:
self._prev_timestep = time_step
self._prev_action = action
return rl_agent.StepOutput(action=action, probs=probs)
def add_transition(self, prev_time_step, prev_action, time_step):
"""Adds the new transition using `time_step` to the replay buffer.
Adds the transition from `self._prev_timestep` to `time_step` by
`self._prev_action`.
Args:
prev_time_step: prev ts, an instance of rl_environment.TimeStep.
prev_action: int, action taken at `prev_time_step`.
time_step: current ts, an instance of rl_environment.TimeStep.
"""
assert prev_time_step is not None
legal_actions = (time_step.observations["legal_actions"][self.player_id])
legal_actions_mask = np.zeros(self._num_actions)
legal_actions_mask[legal_actions] = 1.0
transition = Transition(
info_state=(
prev_time_step.observations["info_state"][self.player_id][:]),
action=prev_action,
reward=time_step.rewards[self.player_id],
next_info_state=time_step.observations["info_state"][self.player_id][:],
is_final_step=float(time_step.last()),
legal_actions_mask=legal_actions_mask)
self._replay_buffer.add(transition)
def _epsilon_greedy(self, info_state, legal_actions, epsilon):
"""Returns a valid epsilon-greedy action and valid action probs.
Action probabilities are given by a softmax over legal q-values.
Args:
info_state: hashable representation of the information state.
legal_actions: list of legal actions at `info_state`.
epsilon: float, probability of taking an exploratory action.
Returns:
A valid epsilon-greedy action and valid action probabilities.
"""
probs = np.zeros(self._num_actions)
legal_one_hot = np.zeros(self._num_actions)
legal_one_hot[legal_actions] = 1
if np.random.rand() < epsilon:
action = np.random.choice(legal_actions)
probs[legal_actions] = 1.0 / len(legal_actions)
else:
info_state = np.reshape(info_state, [1, -1])
q_values = self.hk_network_apply(self.params_q_network, info_state)
legal_q_values = q_values[0] + (
1 - legal_one_hot) * ILLEGAL_ACTION_LOGITS_PENALTY
action = int(np.argmax(legal_q_values))
probs[action] = 1.0
return action, probs
def _get_epsilon(self, is_evaluation, power=1.0):
"""Returns the evaluation or decayed epsilon value."""
if is_evaluation:
return 0.0
decay_steps = min(self._step_counter, self._epsilon_decay_duration)
decayed_epsilon = (
self._epsilon_end + (self._epsilon_start - self._epsilon_end) *
(1 - decay_steps / self._epsilon_decay_duration)**power)
return decayed_epsilon
def _loss(self, param, param_target, info_states, actions, rewards,
next_info_states, are_final_steps, legal_actions_mask):
q_values = self.hk_network.apply(param, info_states)
target_q_values = self.hk_network.apply(param_target, next_info_states)
# Sum a large negative constant to illegal action logits before taking the
# max. This prevents illegal action values from being considered as target.
max_next_q = jnp.max(
target_q_values +
(1 - legal_actions_mask) * ILLEGAL_ACTION_LOGITS_PENALTY,
axis=-1)
max_next_q = jax.numpy.where(
1 - are_final_steps, x=max_next_q, y=jnp.zeros_like(max_next_q))
target = (
rewards + (1 - are_final_steps) * self._discount_factor * max_next_q)
target = jax.lax.stop_gradient(target)
predictions = jnp.sum(q_values * actions, axis=-1)
loss_value = self.loss_func(predictions - target)
return loss_value
def get_update(self):
def update(param, param_target, opt_state, info_states, actions, rewards,
next_info_states, are_final_steps, legal_actions_mask):
loss_val, grad_val = self._loss_and_grad(param, param_target, info_states,
actions, rewards,
next_info_states,
are_final_steps,
legal_actions_mask)
new_param, new_opt_state = self._opt_update_fn(param, opt_state, grad_val)
return new_param, new_opt_state, loss_val
return update
def _to_one_hot(self, a):
a_one_hot = np.zeros(self._num_actions)
a_one_hot[a] = 1.0
return a_one_hot
def learn(self):
"""Compute the loss on sampled transitions and perform a Q-network update.
If there are not enough elements in the buffer, no loss is computed and
`None` is returned instead.
Returns:
The average loss obtained on this batch of transitions or `None`.
"""
if (len(self._replay_buffer) < self._batch_size or
len(self._replay_buffer) < self._min_buffer_size_to_learn):
return None
transitions = self._replay_buffer.sample(self._batch_size)
info_states = np.asarray([t.info_state for t in transitions])
actions = np.asarray([self._to_one_hot(t.action) for t in transitions])
rewards = np.asarray([t.reward for t in transitions])
next_info_states = np.asarray([t.next_info_state for t in transitions])
are_final_steps = np.asarray([t.is_final_step for t in transitions])
legal_actions_mask = np.asarray([t.legal_actions_mask for t in transitions])
self.params_q_network, self._opt_state, loss_val = self._jit_update(
self.params_q_network, self.params_target_q_network, self._opt_state,
info_states, actions, rewards, next_info_states, are_final_steps,
legal_actions_mask)
return loss_val
@property
def q_values(self):
return self._q_values
@property
def replay_buffer(self):
return self._replay_buffer
@property
def loss(self):
return self._last_loss_value
@property
def prev_timestep(self):
return self._prev_timestep
@property
def prev_action(self):
return self._prev_action
@property
def step_counter(self):
return self._step_counter
| open_spiel-master | open_spiel/python/jax/dqn.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for open_spiel.python.algorithms.nfsp."""
from absl.testing import absltest
from open_spiel.python import rl_environment
from open_spiel.python.jax import nfsp
class NFSPTest(absltest.TestCase):
def test_run_kuhn(self):
env = rl_environment.Environment("kuhn_poker")
state_size = env.observation_spec()["info_state"][0]
num_actions = env.action_spec()["num_actions"]
agents = [
nfsp.NFSP( # pylint: disable=g-complex-comprehension
player_id,
state_representation_size=state_size,
num_actions=num_actions,
hidden_layers_sizes=[16],
reservoir_buffer_capacity=10,
anticipatory_param=0.1) for player_id in [0, 1]
]
for unused_ep in range(10):
time_step = env.reset()
while not time_step.last():
current_player = time_step.observations["current_player"]
current_agent = agents[current_player]
agent_output = current_agent.step(time_step)
time_step = env.step([agent_output.action])
for agent in agents:
agent.step(time_step)
class ReservoirBufferTest(absltest.TestCase):
def test_reservoir_buffer_add(self):
# pylint: disable=g-generic-assert
reservoir_buffer = nfsp.ReservoirBuffer(reservoir_buffer_capacity=10)
self.assertEqual(len(reservoir_buffer), 0)
reservoir_buffer.add("entry1")
self.assertEqual(len(reservoir_buffer), 1)
reservoir_buffer.add("entry2")
self.assertEqual(len(reservoir_buffer), 2)
self.assertIn("entry1", reservoir_buffer)
self.assertIn("entry2", reservoir_buffer)
def test_reservoir_buffer_max_capacity(self):
# pylint: disable=g-generic-assert
reservoir_buffer = nfsp.ReservoirBuffer(reservoir_buffer_capacity=2)
reservoir_buffer.add("entry1")
reservoir_buffer.add("entry2")
reservoir_buffer.add("entry3")
self.assertEqual(len(reservoir_buffer), 2)
def test_reservoir_buffer_sample(self):
replay_buffer = nfsp.ReservoirBuffer(reservoir_buffer_capacity=3)
replay_buffer.add("entry1")
replay_buffer.add("entry2")
replay_buffer.add("entry3")
samples = replay_buffer.sample(3)
self.assertIn("entry1", samples)
self.assertIn("entry2", samples)
self.assertIn("entry3", samples)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/jax/nfsp_jax_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.
"""OpenSpiel support for the Atari Learning Environment (ALE).
Originally introduced in (Bellemare et al., 2013):
https://arxiv.org/abs/1207.4708.
Uses environment wrappers from OpenAI Gym (https://gym.openai.com/) and Stable
Baselines 3 (https://jmlr.org/papers/v22/20-1364.html) to convert observations
into a suitable format for training.
"""
# pylint: disable=g-importing-member
from math import prod
import gym
import numpy as np
from stable_baselines3.common.atari_wrappers import ClipRewardEnv
from stable_baselines3.common.atari_wrappers import EpisodicLifeEnv
from stable_baselines3.common.atari_wrappers import FireResetEnv
from stable_baselines3.common.atari_wrappers import MaxAndSkipEnv
import pyspiel
_NUM_PLAYERS = 1
_GAME_TYPE = pyspiel.GameType(
short_name='atari',
long_name='atari',
dynamics=pyspiel.GameType.Dynamics.SEQUENTIAL,
chance_mode=pyspiel.GameType.ChanceMode.SAMPLED_STOCHASTIC,
information=pyspiel.GameType.Information.PERFECT_INFORMATION,
utility=pyspiel.GameType.Utility.ZERO_SUM,
reward_model=pyspiel.GameType.RewardModel.REWARDS,
max_num_players=_NUM_PLAYERS,
min_num_players=_NUM_PLAYERS,
provides_information_state_string=False,
provides_information_state_tensor=False,
provides_observation_string=True,
provides_observation_tensor=True,
parameter_specification={
'gym_id': 'ALE/Breakout-v5',
'seed': 1,
'idx': 0,
'capture_video': False,
'run_name': 'default',
'use_episodic_life_env': True
})
_GAME_INFO = pyspiel.GameInfo(
num_distinct_actions=4,
max_chance_outcomes=0,
num_players=_NUM_PLAYERS,
min_utility=-1.0,
max_utility=1.0,
utility_sum=0.0,
max_game_length=2000)
# NOTE: We include this wrapper by hand because the default wrapper
# threw errors (see modified lines).
class NoopResetEnv(gym.Wrapper):
"""Sample initial states by taking random number of no-ops on reset.
No-op is assumed to be action 0. :param env: the environment to wrap :param
noop_max: the maximum value of no-ops to run
"""
def __init__(self, env: gym.Env, noop_max: int = 30):
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.override_num_noops = None
self.noop_action = 0
assert env.unwrapped.get_action_meanings()[0] == 'NOOP'
def reset(self, **kwargs) -> np.ndarray:
self.env.reset(**kwargs)
if self.override_num_noops is not None:
noops = self.override_num_noops
else:
#### MODIFIED LINES: note method is named integers now ###
noops = self.unwrapped.np_random.integers(1, self.noop_max + 1)
### END MODIFIED LINES ###
assert noops > 0
obs = np.zeros(0)
for _ in range(noops):
obs, _, done, _ = self.env.step(self.noop_action)
if done:
obs = self.env.reset(**kwargs)
return obs
class AtariGame(pyspiel.Game):
"""An OpenSpiel wrapper for the OpenAI Gym Atari games."""
def __init__(self, params=None):
super().__init__(_GAME_TYPE, _GAME_INFO, params or dict())
self.gym_id = params.get('gym_id', 'BreakoutNoFrameskip-v4')
self.seed = params.get('seed', 1)
self.idx = params.get('idx', 0)
self.capture_video = params.get('capture_video', False)
self.run_name = params.get('run_name', 'default')
self.use_episodic_life_env = params.get('use_episodic_life_env', True)
env = gym.make(self.gym_id)
env = gym.wrappers.RecordEpisodeStatistics(env)
if self.capture_video and self.idx == 0:
env = gym.wrappers.RecordVideo(env, f'videos/{self.run_name}')
# Apply the standard set of wrappers from CleanRL's PPO implementation.
# These wrappers have been tested on Breakout; different games may
# benefit from different wrappers (e.g., Space Invaders might benefit
# from frameskip=3 instead of 4; see https://arxiv.org/abs/1312.5602).
env = NoopResetEnv(env, noop_max=30)
env = MaxAndSkipEnv(env, skip=4)
if self.use_episodic_life_env:
env = EpisodicLifeEnv(env)
if 'FIRE' in env.unwrapped.get_action_meanings():
env = FireResetEnv(env)
env = ClipRewardEnv(env)
env = gym.wrappers.ResizeObservation(env, (84, 84))
env = gym.wrappers.GrayScaleObservation(env)
env = gym.wrappers.FrameStack(env, 4)
env.seed(self.seed)
env.action_space.seed(self.seed)
env.observation_space.seed(self.seed)
self.observation_shape = env.reset().shape
self.env = env
def observation_tensor_shape(self):
return self.observation_shape
def new_initial_state(self):
"""Returns a state corresponding to the start of a game."""
return AtariState(self)
def make_py_observer(self, iig_obs_type=None, params=None):
"""Returns an object used for observing game state."""
if params is None:
params = dict()
params['observation_shape'] = self.observation_shape
return AtariObserver(
iig_obs_type or pyspiel.IIGObservationType(perfect_recall=False),
params)
class AtariState(pyspiel.State):
"""A python version of the Atari Game state."""
def __init__(self, game):
"""Constructor; should only be called by Game.new_initial_state."""
super().__init__(game)
self._is_terminal = False
self.tracked_rewards = 0
self.env = game.env
self.observation = self.env.reset()
self.last_reward = None
self.last_info = dict()
def current_player(self):
"""Returns id of the next player to move, or TERMINAL if game is over."""
return pyspiel.PlayerId.TERMINAL if self._is_terminal else 0
def _legal_actions(self, player):
"""Returns a list of legal actions, sorted in ascending order."""
return list(range(self.env.action_space.n))
def _apply_action(self, action):
"""Applies the specified action to the state."""
observation, reward, done, info = self.env.step(action)
self.last_info = info
self.last_reward = reward
self.tracked_rewards += reward
if done:
self._is_terminal = True
self.observation = observation # Store this for later
def _action_to_string(self, player, action):
return self.env.get_action_meanings()[action]
def is_terminal(self):
"""Returns True if the game is over."""
return self._is_terminal
def rewards(self):
return [self.last_reward]
def returns(self):
"""Total reward for each player over the course of the game so far."""
return [self.tracked_rewards]
def __str__(self):
"""String for debug purposes. No particular semantics are required."""
return 'DEBUG'
class AtariObserver:
"""Observer, conforming to the PyObserver interface (see observation.py)."""
# pylint: disable=unused-argument
def __init__(self, iig_obs_type, params):
"""Initializes an empty observation tensor."""
# Determine which observation pieces we want to include.
pieces = []
pieces.append(('observation', prod(params['observation_shape']),
params['observation_shape']))
# Build the single flat tensor.
total_size = sum(size for name, size, shape in pieces)
self.tensor = np.zeros((total_size), np.float32)
# Build the named & reshaped views of the bits of the flat tensor.
self.dict = {}
index = 0
for name, size, shape in pieces:
self.dict[name] = self.tensor[index:index + size].reshape(shape)
index += size
def set_from(self, state, player):
"""Updates `tensor` and `dict` to reflect `state` from PoV of `player`."""
self.tensor.fill(0)
if 'observation' in self.dict:
self.dict['observation'][:] = state.observation
def string_from(self, state, player):
"""Observation of `state` from the PoV of `player`, as a string."""
pieces = []
return ' '.join(str(p) for p in pieces)
# Register the game with the OpenSpiel library
pyspiel.register_game(_GAME_TYPE, AtariGame)
| open_spiel-master | open_spiel/python/games/atari.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Kuhn Poker implemented in Python.
This is a simple demonstration of implementing a game in Python, featuring
chance and imperfect information.
Python games are significantly slower than C++, but it may still be suitable
for prototyping or for small games.
It is possible to run C++ algorithms on Python implemented games, This is likely
to have good performance if the algorithm simply extracts a game tree and then
works with that. It is likely to be poor if the algorithm relies on processing
and updating states as it goes, e.g. MCTS.
"""
import enum
import numpy as np
import pyspiel
class Action(enum.IntEnum):
PASS = 0
BET = 1
_NUM_PLAYERS = 2
_DECK = frozenset([0, 1, 2])
_GAME_TYPE = pyspiel.GameType(
short_name="python_kuhn_poker",
long_name="Python Kuhn Poker",
dynamics=pyspiel.GameType.Dynamics.SEQUENTIAL,
chance_mode=pyspiel.GameType.ChanceMode.EXPLICIT_STOCHASTIC,
information=pyspiel.GameType.Information.IMPERFECT_INFORMATION,
utility=pyspiel.GameType.Utility.ZERO_SUM,
reward_model=pyspiel.GameType.RewardModel.TERMINAL,
max_num_players=_NUM_PLAYERS,
min_num_players=_NUM_PLAYERS,
provides_information_state_string=True,
provides_information_state_tensor=True,
provides_observation_string=True,
provides_observation_tensor=True,
provides_factored_observation_string=True)
_GAME_INFO = pyspiel.GameInfo(
num_distinct_actions=len(Action),
max_chance_outcomes=len(_DECK),
num_players=_NUM_PLAYERS,
min_utility=-2.0,
max_utility=2.0,
utility_sum=0.0,
max_game_length=3) # e.g. Pass, Bet, Bet
class KuhnPokerGame(pyspiel.Game):
"""A Python version of Kuhn poker."""
def __init__(self, params=None):
super().__init__(_GAME_TYPE, _GAME_INFO, params or dict())
def new_initial_state(self):
"""Returns a state corresponding to the start of a game."""
return KuhnPokerState(self)
def make_py_observer(self, iig_obs_type=None, params=None):
"""Returns an object used for observing game state."""
return KuhnPokerObserver(
iig_obs_type or pyspiel.IIGObservationType(perfect_recall=False),
params)
class KuhnPokerState(pyspiel.State):
"""A python version of the Kuhn poker state."""
def __init__(self, game):
"""Constructor; should only be called by Game.new_initial_state."""
super().__init__(game)
self.cards = []
self.bets = []
self.pot = [1.0, 1.0]
self._game_over = False
self._next_player = 0
# OpenSpiel (PySpiel) API functions are below. This is the standard set that
# should be implemented by every sequential-move game with chance.
def current_player(self):
"""Returns id of the next player to move, or TERMINAL if game is over."""
if self._game_over:
return pyspiel.PlayerId.TERMINAL
elif len(self.cards) < _NUM_PLAYERS:
return pyspiel.PlayerId.CHANCE
else:
return self._next_player
def _legal_actions(self, player):
"""Returns a list of legal actions, sorted in ascending order."""
assert player >= 0
return [Action.PASS, Action.BET]
def chance_outcomes(self):
"""Returns the possible chance outcomes and their probabilities."""
assert self.is_chance_node()
outcomes = sorted(_DECK - set(self.cards))
p = 1.0 / len(outcomes)
return [(o, p) for o in outcomes]
def _apply_action(self, action):
"""Applies the specified action to the state."""
if self.is_chance_node():
self.cards.append(action)
else:
self.bets.append(action)
if action == Action.BET:
self.pot[self._next_player] += 1
self._next_player = 1 - self._next_player
if ((min(self.pot) == 2) or
(len(self.bets) == 2 and action == Action.PASS) or
(len(self.bets) == 3)):
self._game_over = True
def _action_to_string(self, player, action):
"""Action -> string."""
if player == pyspiel.PlayerId.CHANCE:
return f"Deal:{action}"
elif action == Action.PASS:
return "Pass"
else:
return "Bet"
def is_terminal(self):
"""Returns True if the game is over."""
return self._game_over
def returns(self):
"""Total reward for each player over the course of the game so far."""
pot = self.pot
winnings = float(min(pot))
if not self._game_over:
return [0., 0.]
elif pot[0] > pot[1]:
return [winnings, -winnings]
elif pot[0] < pot[1]:
return [-winnings, winnings]
elif self.cards[0] > self.cards[1]:
return [winnings, -winnings]
else:
return [-winnings, winnings]
def __str__(self):
"""String for debug purposes. No particular semantics are required."""
return "".join([str(c) for c in self.cards] + ["pb"[b] for b in self.bets])
class KuhnPokerObserver:
"""Observer, conforming to the PyObserver interface (see observation.py)."""
def __init__(self, iig_obs_type, params):
"""Initializes an empty observation tensor."""
if params:
raise ValueError(f"Observation parameters not supported; passed {params}")
# Determine which observation pieces we want to include.
pieces = [("player", 2, (2,))]
if iig_obs_type.private_info == pyspiel.PrivateInfoType.SINGLE_PLAYER:
pieces.append(("private_card", 3, (3,)))
if iig_obs_type.public_info:
if iig_obs_type.perfect_recall:
pieces.append(("betting", 6, (3, 2)))
else:
pieces.append(("pot_contribution", 2, (2,)))
# Build the single flat tensor.
total_size = sum(size for name, size, shape in pieces)
self.tensor = np.zeros(total_size, np.float32)
# Build the named & reshaped views of the bits of the flat tensor.
self.dict = {}
index = 0
for name, size, shape in pieces:
self.dict[name] = self.tensor[index:index + size].reshape(shape)
index += size
def set_from(self, state, player):
"""Updates `tensor` and `dict` to reflect `state` from PoV of `player`."""
self.tensor.fill(0)
if "player" in self.dict:
self.dict["player"][player] = 1
if "private_card" in self.dict and len(state.cards) > player:
self.dict["private_card"][state.cards[player]] = 1
if "pot_contribution" in self.dict:
self.dict["pot_contribution"][:] = state.pot
if "betting" in self.dict:
for turn, action in enumerate(state.bets):
self.dict["betting"][turn, action] = 1
def string_from(self, state, player):
"""Observation of `state` from the PoV of `player`, as a string."""
pieces = []
if "player" in self.dict:
pieces.append(f"p{player}")
if "private_card" in self.dict and len(state.cards) > player:
pieces.append(f"card:{state.cards[player]}")
if "pot_contribution" in self.dict:
pieces.append(f"pot[{int(state.pot[0])} {int(state.pot[1])}]")
if "betting" in self.dict and state.bets:
pieces.append("".join("pb"[b] for b in state.bets))
return " ".join(str(p) for p in pieces)
# Register the game with the OpenSpiel library
pyspiel.register_game(_GAME_TYPE, KuhnPokerGame)
| open_spiel-master | open_spiel/python/games/kuhn_poker.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Liar's Poker implemented in Python."""
import numpy as np
import pyspiel
CHALLENGE_ACTION = 0
BID_ACTION_OFFSET = 1
_MAX_NUM_PLAYERS = 10
_MIN_NUM_PLAYERS = 2
_HAND_LENGTH = 10
_NUM_DIGITS = 10 # Number of digits to include from the range 1, 2, ..., 9, 0
_FULL_DECK = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
_GAME_TYPE = pyspiel.GameType(
short_name="python_liars_poker",
long_name="Python Liars Poker",
dynamics=pyspiel.GameType.Dynamics.SEQUENTIAL,
chance_mode=pyspiel.GameType.ChanceMode.EXPLICIT_STOCHASTIC,
information=pyspiel.GameType.Information.IMPERFECT_INFORMATION,
utility=pyspiel.GameType.Utility.ZERO_SUM,
reward_model=pyspiel.GameType.RewardModel.TERMINAL,
max_num_players=_MAX_NUM_PLAYERS,
min_num_players=_MIN_NUM_PLAYERS,
provides_information_state_string=True,
provides_information_state_tensor=True,
provides_observation_string=False,
provides_observation_tensor=True,
parameter_specification={
"players": _MIN_NUM_PLAYERS,
"hand_length": _HAND_LENGTH,
"num_digits": _NUM_DIGITS,
},
)
_GAME_INFO = pyspiel.GameInfo(
# Num actions = total number of cards * number of digits + action enum
num_distinct_actions=_HAND_LENGTH * _NUM_DIGITS * _MIN_NUM_PLAYERS
+ BID_ACTION_OFFSET,
max_chance_outcomes=_HAND_LENGTH * _NUM_DIGITS,
num_players=_MIN_NUM_PLAYERS,
min_utility=-(
_MIN_NUM_PLAYERS - 1
), # Reward from being challenged and losing.
max_utility=_MIN_NUM_PLAYERS
- 1, # Reward for being challenged and winning.
utility_sum=0.0,
# Number of possible rounds: hand_length * num_digits * num_players
# Total moves per round: num_players for non-rebid, num_players-1 for rebid
# Max game length: number of possible rounds * total moves per round
max_game_length=_HAND_LENGTH * _NUM_DIGITS * _MIN_NUM_PLAYERS**2,
)
class LiarsPoker(pyspiel.Game):
"""A Python version of Liar's poker."""
def __init__(self, params=None):
super().__init__(_GAME_TYPE, _GAME_INFO, params or dict())
game_parameters = self.get_parameters()
self.hand_length = game_parameters.get("hand_length", _HAND_LENGTH)
self.num_digits = game_parameters.get("num_digits", _NUM_DIGITS)
self.deck = _FULL_DECK[: self.num_digits]
def new_initial_state(self):
"""Returns a state corresponding to the start of a game."""
return LiarsPokerState(self)
def make_py_observer(self, iig_obs_type=None, params=None):
"""Returns an object used for observing game state."""
return LiarsPokerObserver(
iig_obs_type or pyspiel.IIGObservationType(perfect_recall=False),
self.num_players(),
self.hand_length,
self.num_digits,
params,
)
class LiarsPokerState(pyspiel.State):
"""A python version of the Liars Poker state."""
def __init__(self, game):
"""Constructor; should only be called by Game.new_initial_state."""
super().__init__(game)
# Game attributes
self._num_players = game.num_players()
self._hand_length = game.hand_length
self._num_digits = game.num_digits
self._deck = game.deck
self.hands = [[] for _ in range(self._num_players)]
# Action dynamics
self.total_possible_bids = (
game.hand_length * game.num_digits * self._num_players
)
self.bid_history = np.zeros((self.total_possible_bids, self._num_players))
self.challenge_history = np.zeros(
(self.total_possible_bids, self._num_players)
)
# self._current_player is only the valid current_player when cards have
# been dealt. Otherwise it's chance.
self._current_player = 0
self._max_bid = self._hand_length * self._num_digits * self._num_players
self._bid_originator = -1
self._current_action = -1
self._num_challenges = 0
self.is_rebid = False
# Game over dynamics
self._winner = -1
self._loser = -1
def current_player(self):
"""Returns id of the current player to act.
The id is:
- TERMINAL if game is over.
- CHANCE if a player is drawing a number to fill out their hand.
- a number otherwise.
"""
if self.is_terminal():
return pyspiel.PlayerId.TERMINAL
elif len(self.hands[self._num_players - 1]) < self._hand_length:
return pyspiel.PlayerId.CHANCE
else:
return self._current_player
def winner(self):
"""Returns the id of the winner if the bid originator has won.
-1 otherwise.
"""
return self._winner
def loser(self):
"""Returns the id of the loser if the bid originator has lost.
-1 otherwise.
"""
return self._loser
def _is_challenge_possible(self):
"""A challenge is possible once the first bid is made."""
return self._current_action != -1
def _is_rebid_possible(self):
"""A rebid is only possible when all players have challenged the original bid."""
return not self.is_rebid and self._num_challenges == self._num_players - 1
def _legal_actions(self, player):
"""Returns a list of legal actions, sorted in ascending order."""
assert player >= 0
actions = []
if self._is_challenge_possible():
actions.append(CHALLENGE_ACTION)
if player != self._bid_originator or self._is_rebid_possible():
# Any move higher than the current bid is allowed.
# Bids start at BID_ACTION_OFFSET (1) as 0 represents the challenge
# action.
for bid in range(
max(BID_ACTION_OFFSET, self._current_action + 1), self._max_bid
):
actions.append(bid)
return actions
def chance_outcomes(self):
"""Returns the possible chance outcomes and their probabilities."""
assert self.is_chance_node()
probability = 1.0 / self._num_digits
return [(digit, probability) for digit in self._deck]
def _decode_bid(self, bid):
"""Turns a bid ID to a (count, number) tuple.
For example, take 2 players each with 2 numbers from the deck of 1, 2, and
3.
- A bid of two 1's would correspond to a bid id 1.
- Explanation: 1 is the lowest number, and the only lower bid would be
zero 1's.
- A bid of three 3's would correspond to a bid id 10.
- Explanation: 1-4 1's take bid ids 0-3. 1-4 2's take bid ids 4-7. 1 and
2 3's take bid ids 8 and 9.
Args:
bid: Bid ID in the range 0 to self._max_bid (non-inclusive).
Returns:
A tuple of (count, number). For example, (1, 2) represents one 2's.
"""
count = bid % (self._hand_length * self._num_players) + 1
number = self._deck[bid // (self._hand_length * self._num_players)]
return (count, number)
def encode_bid(self, count, number):
"""Turns a count and number into a bid ID.
Bid ID is in the range 0 to self._max_bid (non-inclusive).
For example, take 2 players each with 2 numbers from the deck of 1, 2, and
3.
- A count of 2 and number of 1 would be a bid of two one's and a bid id 1.
- Explanation: 1 is the lowest number, and the only lower bid would be
zero 1's
corresponding to bid id 0.
Args:
count: The count of the bid.
number: The number of the bid.
Returns:
A single bid ID.
"""
return ((number - 1) * self._hand_length * self._num_players) + count - 1
def _counts(self):
"""Determines if the bid originator wins or loses."""
bid_count, bid_number = self._decode_bid(
self._current_action - BID_ACTION_OFFSET
)
# Count the number of bid_numbers from all players.
matches = 0
for player_id in range(self._num_players):
for digit in self.hands[player_id]:
if digit == bid_number:
matches += 1
# If the number of matches are at least the bid_count bid, then the bidder
# wins. Otherwise everyone else wins.
if matches >= bid_count:
self._winner = self._bid_originator
else:
self._loser = self._bid_originator
def _update_bid_history(self, bid, player):
"""Writes a player's bid into memory."""
self.bid_history[bid][player] = 1
def _update_challenge_history(self, bid, player):
"""Write a player's challenge for a bid into memory."""
self.challenge_history[bid][player] = 1
def _apply_action(self, action):
"""Applies an action and updates the state."""
if self.is_chance_node():
# If we are still populating hands, draw a number for the current player.
self.hands[self._current_player].append(action)
elif action == CHALLENGE_ACTION:
assert self._is_challenge_possible()
self._update_challenge_history(
self._current_action - BID_ACTION_OFFSET, self._current_player
)
self._num_challenges += 1
# If there is no ongoing rebid, check if all players challenge before
# counting. If there is an ongoing rebid, count once all the players
# except the bidder challenges.
if (not self.is_rebid and self._num_challenges == self._num_players) or (
self.is_rebid and self._num_challenges == self._num_players - 1
):
self._counts()
else:
# Set the current bid to the action.
self._current_action = action
if self._current_player == self._bid_originator:
# If the bid originator is bidding again, we have a rebid.
self.is_rebid = True
else:
# Otherwise, we have a regular bid.
self.is_rebid = False
# Set the bid originator to the current player.
self._bid_originator = self._current_player
self._update_bid_history(
self._current_action - BID_ACTION_OFFSET, self._current_player
)
self._num_challenges = 0
self._current_player = (self._current_player + 1) % self._num_players
def _action_to_string(self, player, action):
"""Action -> string."""
if player == pyspiel.PlayerId.CHANCE:
return f"Deal: {action}"
elif action == CHALLENGE_ACTION:
return "Challenge"
else:
count, number = self._decode_bid(action - BID_ACTION_OFFSET)
return f"Bid: {count} of {number}"
def is_terminal(self):
"""Returns True if the game is over."""
return self._winner >= 0 or self._loser >= 0
def returns(self):
"""Total reward for each player over the course of the game so far."""
if self._winner != -1:
bidder_reward = self._num_players - 1
others_reward = -1.0
elif self._loser != -1:
bidder_reward = -1 * (self._num_players - 1)
others_reward = 1.0
else:
# Game is not over.
bidder_reward = 0.0
others_reward = 0.0
return [
others_reward if player_id != self._bid_originator else bidder_reward
for player_id in range(self._num_players)
]
def __str__(self):
"""String for debug purposes. No particular semantics are required."""
if self._current_action != -1:
count, number = self._decode_bid(self._current_action - BID_ACTION_OFFSET)
else:
count, number = "None", "None"
return (
"Hands: {}, Bidder: {}, Current Player: {}, Current Bid: {} of {},"
" Rebid: {}".format(
self.hands,
self._bid_originator,
self.current_player(),
count,
number,
self.is_rebid,
)
)
class LiarsPokerObserver:
"""Observer, conforming to the PyObserver interface (see observation.py).
An observation will consist of the following:
- One hot encoding of the current player number: [0 0 0 1 0 0 0]
- A vector of length hand_length containing the digits in a player's hand.
- Two matrices each of size (hand_length * num_digits * num_players,
num_players)
will store bids and challenges respectively. Each row in the matrix
corresponds
to a particular bid (e.g. one 1, two 5s, or eight 3s). 0 will represent no
action. 1 will represent a player's bid or a player's challenge.
- One bit for whether we are rebidding: [1] rebid occuring, [0] otherwise
- One bit for whether we are counting: [1] COUNTS called, [0] otherwise
"""
def __init__(
self, iig_obs_type, num_players, hand_length, num_digits, params=None
):
"""Initiliazes an empty observation tensor."""
del params
self.num_players = num_players
self.hand_length = hand_length
# Determine which observation pieces we want to include.
# Pieces is a list of tuples containing observation pieces.
# Pieces are described by their (name, number of elements, and shape).
pieces = [(
"player",
num_players,
(num_players,),
)] # One-hot encoding for the player id.
if iig_obs_type.private_info == pyspiel.PrivateInfoType.SINGLE_PLAYER:
# Vector containing the digits in a player's hand
pieces.append(("private_hand", hand_length, (hand_length,)))
if iig_obs_type.public_info:
pieces.append(("rebid_state", 1, (1,)))
pieces.append(("counts_state", 1, (1,)))
if iig_obs_type.perfect_recall:
# One-hot encodings for players' moves at every round.
total_possible_rounds = hand_length * num_digits * num_players
pieces.append((
"bid_history",
total_possible_rounds * num_players,
(total_possible_rounds, num_players),
))
pieces.append((
"challenge_history",
total_possible_rounds * num_players,
(total_possible_rounds, num_players),
))
# Build the single flat tensor.
total_size = sum(size for name, size, shape in pieces)
self.tensor = np.zeros(total_size, np.float32)
# Build the named & reshaped views of the bits of the flat tensor.
self.dict = {}
index = 0
for name, size, shape in pieces:
self.dict[name] = self.tensor[index : index + size].reshape(shape)
index += size
def set_from(self, state, player):
"""Updates `tensor` and `dict` to reflect `state` from PoV of `player`."""
self.tensor.fill(0)
if "player" in self.dict:
self.dict["player"][player] = 1
if (
"private_hand" in self.dict
and len(state.hands[player]) == self.hand_length
):
self.dict["private_hand"] = np.asarray(state.hands[player])
if "rebid_state" in self.dict:
self.dict["rebid_state"][0] = int(state.is_rebid)
if "counts_state" in self.dict:
self.dict["counts_state"][0] = int(state.is_terminal())
if "bid_history" in self.dict:
self.dict["bid_history"] = state.bid_history
if "challenge_history" in self.dict:
self.dict["challenge_history"] = state.challenge_history
def string_from(self, state, player):
"""Observation of `state` from the PoV of `player`, as a string."""
pieces = []
if "player" in self.dict:
pieces.append(f"p{player}")
if (
"private_hand" in self.dict
and len(state.hands[player]) == self.hand_length
):
pieces.append(f"hand:{state.hands[player]}")
if "rebid_state" in self.dict:
pieces.append(f"rebid:{[int(state.is_rebid)]}")
if "counts_state" in self.dict:
pieces.append(f"counts:{[int(state.is_terminal())]}")
if "bid_history" in self.dict:
for bid in range(len(state.bid_history)):
if np.any(state.bid_history[bid] == 1):
pieces.append("b:{}.".format(bid))
if "challenge_history" in self.dict:
for bid in range(len(state.challenge_history)):
if np.any(state.challenge_history[bid] == 1):
pieces.append("c:{}.".format(bid))
return " ".join(str(p) for p in pieces)
# Register the game with the OpenSpiel library
pyspiel.register_game(_GAME_TYPE, LiarsPoker)
| open_spiel-master | open_spiel/python/games/liars_poker.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Tests for Python dynamic routing game."""
from absl.testing import absltest
from open_spiel.python import games # pylint:disable=unused-import
from open_spiel.python import policy
from open_spiel.python import rl_environment
from open_spiel.python.algorithms import cfr
from open_spiel.python.algorithms import expected_game_score
from open_spiel.python.algorithms import exploitability
from open_spiel.python.algorithms import external_sampling_mccfr as external_mccfr
from open_spiel.python.algorithms import outcome_sampling_mccfr as outcome_mccfr
from open_spiel.python.games import dynamic_routing
from open_spiel.python.games import dynamic_routing_utils
import pyspiel
_NUM_ITERATION_CFR_TEST = 1
class DynamicRoutingGameTest(absltest.TestCase):
def test_random_game(self):
"""Tests basic API functions with the standard game tests."""
game = pyspiel.load_game("python_dynamic_routing")
pyspiel.random_sim_test(game, num_sims=10, serialize=False, verbose=True)
def test_game_as_turn_based(self):
"""Check the game can be converted to a turn-based game."""
game = pyspiel.load_game("python_dynamic_routing")
turn_based = pyspiel.convert_to_turn_based(game)
pyspiel.random_sim_test(
turn_based, num_sims=10, serialize=False, verbose=True)
def test_game_as_turn_based_via_string(self):
"""Check the game can be created as a turn-based game from a string."""
game = pyspiel.load_game(
"turn_based_simultaneous_game(game=python_dynamic_routing())")
pyspiel.random_sim_test(game, num_sims=10, serialize=False, verbose=True)
def test_non_default_param_from_string(self):
"""Check params can be given through string loading."""
game = pyspiel.load_game("python_dynamic_routing(max_num_time_step=5)")
self.assertEqual(game.max_game_length(), 5)
def test_non_default_param_from_dict(self):
"""Check params can be given through a dictionary."""
game = pyspiel.load_game("python_dynamic_routing", {"max_num_time_step": 5})
self.assertEqual(game.max_game_length(), 5)
def test_action_consistency_convert_to_turn_based(self):
"""Check if the sequential game is consistent with the game."""
game = pyspiel.load_game("python_dynamic_routing")
seq_game = pyspiel.convert_to_turn_based(game)
state = game.new_initial_state()
seq_state = seq_game.new_initial_state()
self.assertEqual(
state.legal_actions(seq_state.current_player()),
seq_state.legal_actions(),
msg="The sequential actions are not correct.")
def test_cfr_on_turn_based_game_with_exploitability(self):
"""Check if CFR can be applied to the sequential game."""
game = pyspiel.load_game(
"python_dynamic_routing(max_num_time_step=5,time_step_length=1.0)")
seq_game = pyspiel.convert_to_turn_based(game)
cfr_solver = cfr.CFRSolver(seq_game)
for _ in range(_NUM_ITERATION_CFR_TEST):
cfr_solver.evaluate_and_update_policy()
exploitability.nash_conv(seq_game, cfr_solver.average_policy())
def test_ext_mccfr_on_turn_based_game_with_exploitability(self):
"""Check if external sampling MCCFR can be applied."""
game = pyspiel.load_game(
"python_dynamic_routing(max_num_time_step=5,time_step_length=1.0)")
seq_game = pyspiel.convert_to_turn_based(game)
cfr_solver = external_mccfr.ExternalSamplingSolver(
seq_game, external_mccfr.AverageType.SIMPLE)
for _ in range(_NUM_ITERATION_CFR_TEST):
cfr_solver.iteration()
exploitability.nash_conv(seq_game, cfr_solver.average_policy())
def test_int_mccfr_on_turn_based_game_with_exploitability(self):
"""Check if outcome sampling MCCFR can be applied."""
game = pyspiel.load_game(
"python_dynamic_routing(max_num_time_step=5,time_step_length=1.0)")
seq_game = pyspiel.convert_to_turn_based(game)
cfr_solver = outcome_mccfr.OutcomeSamplingSolver(seq_game)
for _ in range(_NUM_ITERATION_CFR_TEST):
cfr_solver.iteration()
exploitability.nash_conv(seq_game, cfr_solver.average_policy())
def test_creation_of_rl_environment(self):
"""Check if RL environment can be created."""
game = pyspiel.load_game("python_dynamic_routing")
seq_game = pyspiel.convert_to_turn_based(game)
rl_environment.Environment(seq_game)
def test_vehicle_origin_outside_network(self):
"""Check raise assertion if vehicle's origin is outside the Network."""
vehicles = [dynamic_routing_utils.Vehicle("I->O", "D->E", 0)]
with self.assertRaises(ValueError):
dynamic_routing.DynamicRoutingGame(
{
"max_num_time_step": 10,
"time_step_length": 0.5,
"players": -1
},
vehicles=vehicles)
def test_vehicle_destination_outside_network(self):
"""Check raise assertion if vehicle's destination is outside the Network."""
vehicles = [dynamic_routing_utils.Vehicle("O->A", "E->F", 0)]
with self.assertRaises(ValueError):
dynamic_routing.DynamicRoutingGame(
{
"max_num_time_step": 10,
"time_step_length": 0.5,
"players": -1
},
vehicles=vehicles)
def test_multiple_departure_time_vehicle(self):
"""Check that departure time can be define."""
vehicles = [
dynamic_routing_utils.Vehicle("O->A", "D->E", 0),
dynamic_routing_utils.Vehicle("O->A", "D->E", 0.5),
dynamic_routing_utils.Vehicle("O->A", "D->E", 1.0)
]
game = dynamic_routing.DynamicRoutingGame(
{
"max_num_time_step": 10,
"time_step_length": 0.5,
"players": -1
},
vehicles=vehicles)
pyspiel.random_sim_test(game, num_sims=10, serialize=False, verbose=True)
def test_game_evolution_first_action_policy(self):
"""Check game deterministic evolution under first action policy."""
# Test evolution of the game as expected (test value of the state).
# test legal_actions().
def test_observer_correct(self):
"""Check that the observer is correclty updated."""
# Add test about observer and tensor being updated.
def test_apply_actions_error_no_movement_with_negative_waiting_time(self):
"""Check that a vehicle cannot choose to not move if it has to move."""
# Test apply_actions().
def test_apply_actions_error_wrong_movement_with_negative_waiting_time(self):
"""Check that a vehicle cannot choose to move to a not successor link."""
# Test apply_actions().
def test_apply_actions_error_movement_with_positive_waiting_time(self):
"""Check that a vehicle cannot choose to move if it cannot move yet."""
# Test apply_actions().
def test_braess_paradox(self):
"""Test that Braess paradox can be reproduced with the mean field game."""
num_player = 8
braess_network = dynamic_routing_utils.Network(
{
"O": "A",
"A": ["B", "C"],
"B": ["C", "D"],
"C": ["D"],
"D": ["E"],
"E": []
},
node_position={
"O": (0, 0),
"A": (1, 0),
"B": (2, 1),
"C": (2, -1),
"D": (3, 0),
"E": (4, 0)
},
bpr_a_coefficient={
"O->A": 0,
"A->B": 1.0,
"A->C": 0,
"B->C": 0,
"B->D": 0,
"C->D": 1.0,
"D->E": 0
},
bpr_b_coefficient={
"O->A": 1.0,
"A->B": 1.0,
"A->C": 1.0,
"B->C": 1.0,
"B->D": 1.0,
"C->D": 1.0,
"D->E": 1.0
},
capacity={
"O->A": num_player,
"A->B": num_player,
"A->C": num_player,
"B->C": num_player,
"B->D": num_player,
"C->D": num_player,
"D->E": num_player
},
free_flow_travel_time={
"O->A": 0,
"A->B": 1.0,
"A->C": 2.0,
"B->C": 0.25,
"B->D": 2.0,
"C->D": 1.0,
"D->E": 0
})
demand = [
dynamic_routing_utils.Vehicle("O->A", "D->E") for _ in range(num_player)
]
game = dynamic_routing.DynamicRoutingGame(
{
"time_step_length": 0.125,
"max_num_time_step": 40
},
network=braess_network,
vehicles=demand)
class TruePathPolicy(policy.Policy):
def __init__(self, game):
super().__init__(game, list(range(num_player)))
self._path = {}
def action_probabilities(self, state, player_id=None):
assert player_id is not None
legal_actions = state.legal_actions(player_id)
if not legal_actions:
return {dynamic_routing_utils.NO_POSSIBLE_ACTION: 1.0}
elif len(legal_actions) == 1:
return {legal_actions[0]: 1.0}
else:
if legal_actions[0] == 1:
if self._path[player_id] in ["top", "middle"]:
return {1: 1.0}
elif self._path[player_id] == "bottom":
return {2: 1.0}
else:
raise ValueError()
elif legal_actions[0] == 3:
if self._path[player_id] == "top":
return {4: 1.0}
elif self._path[player_id] == "middle":
return {3: 1.0}
else:
raise ValueError()
raise ValueError(f"{legal_actions} is not correct.")
class NashEquilibriumBraess(TruePathPolicy):
def __init__(self, game):
super().__init__(game)
for player_id in range(num_player):
if player_id % 2 == 0:
self._path[player_id] = "middle"
if player_id % 4 == 1:
self._path[player_id] = "top"
if player_id % 4 == 3:
self._path[player_id] = "bottom"
class SocialOptimumBraess(NashEquilibriumBraess):
def __init__(self, game):
super().__init__(game)
for player_id in range(num_player):
if player_id % 2 == 0:
self._path[player_id] = "top"
if player_id % 2 == 1:
self._path[player_id] = "bottom"
ne_policy = NashEquilibriumBraess(game)
# Debug issue with nash conv computation and uncomment yhe following line.
# self.assertEqual(exploitability.nash_conv(game, ne_policy), 0.0)
self.assertSequenceAlmostEqual(
-expected_game_score.policy_value(game.new_initial_state(), ne_policy),
[3.75] * num_player)
so_policy = SocialOptimumBraess(game)
# Debug issue with nash conv computation and uncomment the following line.
# self.assertEqual(exploitability.nash_conv(game, so_policy), 0.125)
self.assertSequenceAlmostEqual(
-expected_game_score.policy_value(game.new_initial_state(), so_policy),
[3.5] * num_player)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/dynamic_routing_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Utils module for dynamic routing game and mean field routing game.
This module has three main classes:
- Network
- Vehicle
- OriginDestinationDemand
"""
from __future__ import annotations
from collections.abc import Collection
from typing import Any, Optional
# In case one vehicle has reached a end node, then it cannot do anything. In
# this case its action is 0. Action 0 is reserved to encode no possible action
# as requested by Open Spiel.
NO_POSSIBLE_ACTION = 0
def _road_section_from_nodes(origin: str, destination: str) -> str:
"""Create a road section 'A->B' from two nodes 'A' and 'B'."""
return f"{origin}->{destination}"
def _nodes_from_road_section(movement: str) -> tuple[str, str]:
"""Split a road section 'A->B' to two nodes 'A' and 'B'."""
origin, destination = movement.split("->")
return origin, destination
def assign_dictionary_input_to_object(dict_object: dict[str, Any],
road_sections: Collection[str],
default_value: Any) -> dict[str, Any]:
"""Check dictionary has road sections has key or return default_value dict."""
if dict_object:
assert set(dict_object) == set(road_sections), (
"Objects are not defined for each road sections.")
return dict_object
dict_object_returned = {}
for road_section in road_sections:
dict_object_returned[road_section] = default_value
return dict_object_returned
class Network:
"""Network implementation.
A network is basically a directed graph with a volume delay function on each
of its edges. Each vertex is refered to as a string (for example "A") and each
edge as a string f"{node1}->{node2}" (for example "A->B"). The network is
created from a adjacency list. Each road section is mapped to an action index
(positive integer) in _action_by_road_section. The volume delay function on
each road section rs is given by
_free_flow_travel_time[rs]*(1+ _a[rs]*(v/_capacity[rs])**_b[rs])
where v is the volume on the road section rs, according to the U.S. Bureau of
Public Road (BPR). Such functions are called fundamental diagram of traffic
flow.
If one would like to plot the network then node position should be passed
in the constructor. Then return_list_for_matplotlib_quiver can be used with
Matplotlib:
```python3
fig, ax = plt.subplots()
o_xs, o_ys, d_xs, d_ys = g.return_list_for_matplotlib_quiver()
ax.quiver(o_xs, o_ys, np.subtract(d_xs, o_xs), np.subtract(d_ys, o_ys),
color="b", angles='xy', scale_units='xy', scale=1)
```
See the Network tests for an example.
Attributes: _a, _b, _capacity, _free_flow_travel_time: dictionary that maps
road section string representation to its a, b, relative capacity and free
flow travel time coefficient in its BPR function.
_action_by_road_section: dictionary that maps road section to action id.
_adjacency_list: adjacency list of the line graph of the road network.
_node_position: dictionary that maps node to couple of float encoding x and
y position of the node. None by default.
_road_section_by_action: dictionary that maps action id to road section.
"""
_a: dict[str, float]
_b: dict[str, float]
_action_by_road_section: dict[str, int]
_adjacency_list: dict[str, Collection[str]]
_capacity: dict[str, float]
_free_flow_travel_time: dict[str, float]
_node_position: dict[str, tuple[float, float]]
_road_section_by_action: dict[int, str]
def __init__(self,
adjacency_list: dict[str, Collection[str]],
node_position: Optional[dict[str, tuple[float, float]]] = None,
bpr_a_coefficient: Optional[dict[str, float]] = None,
bpr_b_coefficient: Optional[dict[str, float]] = None,
capacity: Optional[dict[str, float]] = None,
free_flow_travel_time: Optional[dict[str, float]] = None):
self._adjacency_list = adjacency_list
self._action_by_road_section = self._create_action_by_road_section()
self._road_section_by_action = {
v: k for k, v in self._action_by_road_section.items()
}
nodes = set(adjacency_list)
# pylint: disable=g-complex-comprehension
assert all(destination_node in nodes
for destination_nodes in self._adjacency_list.values()
for destination_node in destination_nodes), (
"Adjacency list is not correct.")
# pylint: enable=g-complex-comprehension
if node_position:
assert set(node_position) == nodes
self._node_position = node_position
else:
self._node_position = None
self._a = assign_dictionary_input_to_object(bpr_a_coefficient,
self._action_by_road_section, 0)
self._b = assign_dictionary_input_to_object(bpr_b_coefficient,
self._action_by_road_section, 1)
self._capacity = assign_dictionary_input_to_object(
capacity, self._action_by_road_section, 1)
self._free_flow_travel_time = assign_dictionary_input_to_object(
free_flow_travel_time, self._action_by_road_section, 1)
assert hasattr(self, "_adjacency_list")
assert hasattr(self, "_node_position")
assert hasattr(self, "_a")
assert hasattr(self, "_b")
assert hasattr(self, "_capacity")
assert hasattr(self, "_free_flow_travel_time")
def _create_action_by_road_section(self) -> tuple[set[str], dict[int, str]]:
"""Create dictionary that maps movement to action.
The dictionary that maps movement to action is used to define the action
from a movement that a vehicle would like to do.
Returns:
action_by_road_section: dictionary with key begin a movement for example
"O->A" and value the action numbers. Action numbers are succesive
integers indexed from 1.
"""
action_by_road_section = {}
action_number = NO_POSSIBLE_ACTION + 1
for origin, successors in sorted(self._adjacency_list.items()):
for destination in successors:
road_section = _road_section_from_nodes(origin, destination)
if road_section in action_by_road_section:
raise ValueError((
f"{road_section} exists twice in the adjacency list. The current "
"network implementation does not enable parallel links."))
action_by_road_section[road_section] = action_number
action_number += 1
return action_by_road_section
def num_links(self) -> int:
"""Returns the number of road sections."""
return len(self._action_by_road_section)
def num_actions(self) -> int:
"""Returns the number of possible actions.
Equal to the number of road section + 1. An action could either be moving to
a specific road section or not move.
"""
return 1 + self.num_links()
def links(self) -> list[str]:
"""Returns the road sections as a list."""
return list(self._action_by_road_section)
def get_successors(self, node: str) -> Collection[str]:
"""Returns the successor nodes of the node."""
return self._adjacency_list[node]
def get_action_id_from_movement(self, origin: str, destination: str) -> int:
"""Maps two connected nodes to an action."""
return self._action_by_road_section[_road_section_from_nodes(
origin, destination)]
def get_road_section_from_action_id(self, action_id: int) -> str:
"""Maps a action to the corresponding road section."""
return self._road_section_by_action[action_id]
def is_location_at_sink_node(self, road_section: str) -> bool:
"""Returns True if the road section has no successors."""
start_section, end_section_node = _nodes_from_road_section(road_section)
if start_section not in self._adjacency_list:
raise KeyError(f"{start_section} is not a network node.")
return not self.get_successors(end_section_node)
def check_list_of_vehicles_is_correct(self, vehicles: Collection["Vehicle"]):
"""Assert that vehicles have valid origin and destination."""
for vehicle in vehicles:
if (vehicle.origin not in self._action_by_road_section or
vehicle.destination not in self._action_by_road_section):
raise ValueError(f"Incorrect origin or destination for {vehicle}")
def check_list_of_od_demand_is_correct(
self, vehicles: Collection["OriginDestinationDemand"]):
"""Assert that OD demands have valid origin and destination."""
for vehicle in vehicles:
if (vehicle.origin not in self._action_by_road_section or
vehicle.destination not in self._action_by_road_section):
raise ValueError(f"Incorrect origin or destination for {vehicle}")
def __str__(self) -> str:
return str(self._adjacency_list)
def get_travel_time(self, road_section: str, volume: float) -> int:
"""Returns travel time on the road section given the volume on it.
Volume unit should be the same as the capacity unit.
Travel time unit is the free flow travel time unit.
Args:
road_section: the road section.
volume: the volume on the road section.
"""
return self._free_flow_travel_time[road_section] * (
1.0 + self._a[road_section] *
(volume / self._capacity[road_section])**self._b[road_section])
def assert_valid_action(self, action: int, road_section: str = None):
"""Assert that an action as a int is valid.
The action should be a int between 1 and num_actions. In case road_section
is not None then it is test if the action correspond to going on a road
section which is a successor of road_section.
Args:
action: the action,
road_section: the road section.
"""
assert isinstance(action, int), f"{action} is not a int."
assert 1 <= action < self.num_actions(), str(action)
if road_section is not None:
new_road_section = self.get_road_section_from_action_id(action)
origin_new_section, end_new_section = _nodes_from_road_section(
new_road_section)
_, end_section_node = _nodes_from_road_section(road_section)
assert end_section_node == origin_new_section, (
f"The action is not legal, trying to go to {new_road_section} "
f"from {road_section} without going through {end_section_node}"
".")
successors = self.get_successors(origin_new_section)
assert end_new_section in successors, (
f"Invalid action {new_road_section}. It is not a successors of"
f" {end_section_node}: {successors}.")
def return_position_of_road_section(self,
road_section: str) -> tuple[float, float]:
"""Returns position of the middle of theroad section as (x,y)."""
assert self._node_position is not None, (
"The network should have node positions in order to be plot.")
o_link, d_link = _nodes_from_road_section(road_section)
o_x, o_y = self._node_position[o_link]
d_x, d_y = self._node_position[d_link]
return (o_x + d_x) / 2, (o_y + d_y) / 2
def return_list_for_matplotlib_quiver(
self) -> tuple[list[float], list[float], list[float], list[float]]:
"""Returns 4 list of encoding the positions of the road sections.
```python3
fig, ax = plt.subplots()
o_xs, o_ys, d_xs, d_ys = g.return_list_for_matplotlib_quiver()
ax.quiver(o_xs, o_ys, np.subtract(d_xs, o_xs), np.subtract(d_ys, o_ys),
color="b", angles='xy', scale_units='xy', scale=1)
```
will show the network.
Returns:
o_xs, o_ys, d_xs, d_ys: list of the start x and y positions and of the end
x and y postions of each road section. Each element of each list
corresponds to one road section.
"""
assert self._node_position is not None, (
"The network should have node positions in order to be plot.")
o_xs = []
o_ys = []
d_xs = []
d_ys = []
for road_section in self._action_by_road_section:
o_link, d_link = _nodes_from_road_section(road_section)
o_x, o_y = self._node_position[o_link]
d_x, d_y = self._node_position[d_link]
o_xs.append(o_x)
o_ys.append(o_y)
d_xs.append(d_x)
d_ys.append(d_y)
return o_xs, o_ys, d_xs, d_ys
class Vehicle:
"""A Vehicle is one origin and one destination.
Both the origin and the destination of the vehicle are road section, therefore
they are string formatted as "{str}->{str}".
Attributes:
destination: destination of the vehicle.
origin: origin of the vehicle.
departure_time: departure time of the vehicle.
"""
_destination: str
_origin: str
_departure_time: float
def __init__(self,
origin: str,
destination: str,
departure_time: float = 0.0):
assert all("->" in node for node in [origin, destination])
self._origin = origin
self._destination = destination
self._departure_time = departure_time
@property
def origin(self) -> str:
"""Returns vehicle's origin."""
return self._origin
@property
def destination(self) -> str:
"""Returns vehicle's destination."""
return self._destination
@property
def departure_time(self) -> float:
"""Returns vehicle's departure time."""
return self._departure_time
def __str__(self):
return (f"Vehicle with origin {self.origin}, destination {self.destination}"
f" and departure time {self._departure_time}.")
class OriginDestinationDemand(Vehicle):
"""Number of trips from origin to destination for a specific departure time.
Both the origin and the destination of the vehicle are road section, therefore
they are string formatted as "{str}->{str}".
Attributes:
destination: destination of the vehicles.
origin: origin of the vehicles.
departure_time: departure time of the vehicles.
counts: the number of vehicles with the origin, destination and departure
time.
"""
_counts: float
def __init__(self, origin: str, destination: str, departure_time: float,
counts: float):
super().__init__(origin, destination, departure_time)
self._counts = counts
@property
def counts(self) -> float:
"""Returns the number of vehicles in the instance."""
return self._counts
def __str__(self):
return (f"{self._counts} with origin {self.origin}, destination "
f"{self.destination} and departure time {self._departure_time}.")
| open_spiel-master | open_spiel/python/games/dynamic_routing_utils.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Tests for Python Kuhn Poker."""
from absl.testing import absltest
import numpy as np
from open_spiel.python import policy
from open_spiel.python.algorithms import exploitability
from open_spiel.python.algorithms import sequence_form_lp
from open_spiel.python.algorithms.get_all_states import get_all_states
from open_spiel.python.games import kuhn_poker # pylint: disable=unused-import
from open_spiel.python.observation import make_observation
import pyspiel
class KuhnPokerTest(absltest.TestCase):
def test_game_from_cc(self):
"""Runs our standard game tests, checking API consistency."""
game = pyspiel.load_game("python_kuhn_poker")
pyspiel.random_sim_test(game, num_sims=10, serialize=False, verbose=True)
def test_consistent(self):
"""Checks the Python and C++ game implementations are the same."""
py_game = pyspiel.load_game("python_kuhn_poker")
cc_game = pyspiel.load_game("kuhn_poker")
obs_types = [None, pyspiel.IIGObservationType(perfect_recall=True)]
py_observations = [make_observation(py_game, o) for o in obs_types]
cc_observations = [make_observation(cc_game, o) for o in obs_types]
py_states = get_all_states(py_game)
cc_states = get_all_states(cc_game)
self.assertCountEqual(list(cc_states), list(py_states))
for key, cc_state in cc_states.items():
py_state = py_states[key]
np.testing.assert_array_equal(py_state.history(), cc_state.history())
np.testing.assert_array_equal(py_state.returns(), cc_state.returns())
for py_obs, cc_obs in zip(py_observations, cc_observations):
for player in (0, 1):
py_obs.set_from(py_state, player)
cc_obs.set_from(cc_state, player)
np.testing.assert_array_equal(py_obs.tensor, cc_obs.tensor)
def test_nash_value_sequence_form_lp(self):
"""Checks Nash value using a Python sequence form LP solver."""
game = pyspiel.load_game("python_kuhn_poker")
val1, val2, _, _ = sequence_form_lp.solve_zero_sum_game(game)
# value from Kuhn 1950 or https://en.wikipedia.org/wiki/Kuhn_poker
self.assertAlmostEqual(val1, -1 / 18)
self.assertAlmostEqual(val2, +1 / 18)
def test_exploitability_uniform_random_py(self):
"""Checks the exploitability of the uniform random policy using Python."""
# NashConv of uniform random test_policy from (found on Google books):
# https://link.springer.com/chapter/10.1007/978-3-319-75931-9_5
game = pyspiel.load_game("python_kuhn_poker")
test_policy = policy.UniformRandomPolicy(game)
expected_nash_conv = 11 / 12
self.assertAlmostEqual(
exploitability.exploitability(game, test_policy),
expected_nash_conv / 2)
def test_exploitability_uniform_random_cc(self):
"""Checks the exploitability of the uniform random policy using C++."""
game = pyspiel.load_game("python_kuhn_poker")
test_policy = pyspiel.UniformRandomPolicy(game)
expected_nash_conv = 11 / 12
self.assertAlmostEqual(
pyspiel.exploitability(game, test_policy), expected_nash_conv / 2)
def test_cfr_cc(self):
"""Runs a C++ CFR algorithm on the game."""
game = pyspiel.load_game("python_kuhn_poker")
unused_results = pyspiel.CFRSolver(game)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/kuhn_poker_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Games implemented in Python.
These games are registered as they are imported. It's perfectly possible to
import just a single game if you prefer. There is no need to add new games here,
so long as they register themselves and you import them when wanting to use
them. However, adding them here will make them available for playthroughs and
for automated API testing.
Registration looks like this:
```
pyspiel.register_game(_GAME_TYPE, KuhnPokerGame)
```
"""
from open_spiel.python.games import block_dominoes
from open_spiel.python.games import dynamic_routing
from open_spiel.python.games import iterated_prisoners_dilemma
from open_spiel.python.games import kuhn_poker
from open_spiel.python.games import liars_poker
from open_spiel.python.games import tic_tac_toe
| open_spiel-master | open_spiel/python/games/__init__.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Tests for Python dynamic routing game utils."""
from absl.testing import absltest
from open_spiel.python.games import dynamic_routing_utils as utils
class NetworkTest(absltest.TestCase):
"""Tests for Network class."""
def setUp(self):
"""Create a network O->A->D for testing."""
super().setUp()
self.network = utils.Network({"O": ["A"], "A": ["D"], "D": []})
def test_adjacency_list_init(self):
"""Test class instanciation with adjacency list."""
self.assertEqual(self.network.num_links(), 2)
self.assertEqual(self.network.get_successors("O"), ["A"])
self.assertEqual(self.network.get_successors("A"), ["D"])
self.assertEqual(self.network.get_successors("D"), [])
self.assertTrue(self.network.is_location_at_sink_node("A->D"))
self.assertFalse(self.network.is_location_at_sink_node("O->A"))
self.assertEqual(self.network.get_action_id_from_movement("A", "D"), 1)
self.assertEqual(self.network.get_action_id_from_movement("O", "A"), 2)
self.assertEqual(self.network.get_road_section_from_action_id(1), "A->D")
self.assertEqual(self.network.get_road_section_from_action_id(2), "O->A")
def test_get_successors_with_wrong_node(self):
"""Test get successors on non existing node."""
with self.assertRaises(KeyError):
self.network.get_successors("Z")
def test_get_action_id_without_connected_nodes(self):
"""Test get actions id on non connected nodes."""
with self.assertRaises(KeyError):
self.network.get_action_id_from_movement("O", "D")
def test_get_action_id_with_wrong_nodes(self):
"""Test get actions id on non existing node."""
with self.assertRaises(KeyError):
self.network.get_action_id_from_movement("Z", "D")
def test_is_location_at_sink_noded_with_wrong_road_section(self):
"""Test is_location_at_sink_node on non existing second node."""
with self.assertRaises(KeyError):
self.network.is_location_at_sink_node("A->Z")
def test_is_location_at_sink_noded_with_wrong_road_section_2(self):
"""Test is_location_at_sink_node on non existing first node."""
with self.assertRaises(KeyError):
self.network.is_location_at_sink_node("Z->D")
def test_is_location_at_sink_noded_with_wrong_arg(self):
"""Test is_location_at_sink_node on wrong link str representation."""
with self.assertRaises(ValueError):
self.network.is_location_at_sink_node("D")
def test_get_road_section_with_action_id(self):
"""Test get_road_section_from_action_id on non possible action."""
with self.assertRaises(KeyError):
self.network.get_road_section_from_action_id(0)
def test_num_links_method(self):
# Write.
pass
def test_num_actions_method(self):
# Write.
pass
def test_links(self):
# Write.
pass
def test_check_list_of_vehicles_is_correct_method(self):
# Write.
pass
def test_check_list_of_od_demand_is_correct_method(self):
# Write.
pass
def test_str_method(self):
# Write.
pass
def test_get_travel_time_methods(self):
# Write.
pass
def test_assert_valid_action_methods(self):
# Write.
pass
def test_default_travel_time_methods(self):
# Write.
pass
def test_customable_travel_time_methods(self):
# Write.
pass
class VehicleTest(absltest.TestCase):
"""Tests for Vehicle class."""
def test_vehicle_1(self):
"""Test instanciation of Vehicle."""
vehicle = utils.Vehicle("O->A", "B->D")
self.assertEqual(vehicle.destination, "B->D")
self.assertEqual(vehicle.origin, "O->A")
self.assertEqual(vehicle.departure_time, 0)
def test_vehicle_2(self):
"""Test instanciation of with departure time."""
vehicle = utils.Vehicle("O->A", "B->D", 10.5)
self.assertEqual(vehicle.origin, "O->A")
self.assertEqual(vehicle.destination, "B->D")
self.assertEqual(vehicle.departure_time, 10.5)
class OriginDestinationDemandTest(absltest.TestCase):
"""Tests for OriginDestinationDemand class."""
def test_od_demand_1(self):
"""Test instanciation of OD demand."""
od_demand = utils.OriginDestinationDemand("O->A", "B->D", 0, 30)
self.assertEqual(od_demand.destination, "B->D")
self.assertEqual(od_demand.origin, "O->A")
self.assertEqual(od_demand.departure_time, 0)
self.assertEqual(od_demand.counts, 30)
def test_od_demand_2(self):
"""Test instanciation of OD demand."""
od_demand = utils.OriginDestinationDemand("O->A", "B->D", 10.5, 43.2)
self.assertEqual(od_demand.origin, "O->A")
self.assertEqual(od_demand.destination, "B->D")
self.assertEqual(od_demand.departure_time, 10.5)
self.assertEqual(od_demand.counts, 43.2)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/dynamic_routing_utils_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Tests for Python Block Dominoes."""
from absl.testing import absltest
from open_spiel.python.games import block_dominoes
import pyspiel
class DominoesBlockTest(absltest.TestCase):
def test_game_from_cc(self):
"""Runs our standard game tests, checking API consistency."""
game = pyspiel.load_game("python_block_dominoes")
pyspiel.random_sim_test(game, num_sims=100, serialize=False, verbose=True)
def test_single_deterministic_game_1(self):
"""Runs a single game where tiles and actions chose deterministically."""
game = pyspiel.load_game("python_block_dominoes")
state = game.new_initial_state()
hand0 = [
(6.0, 6.0),
(0.0, 2.0),
(4.0, 4.0),
(3.0, 3.0),
(2.0, 2.0),
(1.0, 1.0),
(0.0, 0.0),
]
hand1 = [
(5.0, 6.0),
(4.0, 5.0),
(3.0, 4.0),
(2.0, 3.0),
(1.0, 2.0),
(0.0, 1.0),
(4.0, 6.0),
]
self.deal_hands(state, [hand0, hand1])
self.apply_action(state, block_dominoes.Action(0, (6.0, 6.0), None))
self.apply_action(state, block_dominoes.Action(1, (5.0, 6.0), 6.0))
# player 0 don't hold any tile with 6 or 5, player 1 turn again
self.apply_action(state, block_dominoes.Action(1, (4.0, 5.0), 5.0))
self.apply_action(state, block_dominoes.Action(0, (4.0, 4.0), 4.0))
self.apply_action(state, block_dominoes.Action(1, (3.0, 4.0), 4.0))
self.apply_action(state, block_dominoes.Action(0, (3.0, 3.0), 3.0))
self.apply_action(state, block_dominoes.Action(1, (2.0, 3.0), 3.0))
self.apply_action(state, block_dominoes.Action(0, (2.0, 2.0), 2.0))
self.apply_action(state, block_dominoes.Action(1, (1.0, 2.0), 2.0))
self.apply_action(state, block_dominoes.Action(0, (1.0, 1.0), 1.0))
self.apply_action(state, block_dominoes.Action(1, (0.0, 1.0), 1.0))
self.apply_action(state, block_dominoes.Action(0, (0.0, 0.0), 0.0))
self.apply_action(state, block_dominoes.Action(1, (4.0, 6.0), 6.0))
# player 1 played all is tile and player 0 hold the tile (0, 2)
self.assertTrue(state.is_terminal())
self.assertEqual(state.returns()[0], -2)
self.assertEqual(state.returns()[1], 2)
def test_single_deterministic_game_2(self):
"""Runs a single game where tiles and actions chose deterministically."""
game = pyspiel.load_game("python_block_dominoes")
state = game.new_initial_state()
hand0 = [
(6.0, 6.0),
(0.0, 5.0),
(1.0, 5.0),
(2.0, 5.0),
(3.0, 5.0),
(4.0, 5.0),
(5.0, 5.0),
]
hand1 = [
(0.0, 4.0),
(1.0, 4.0),
(2.0, 4.0),
(3.0, 4.0),
(4.0, 4.0),
(0.0, 3.0),
(1.0, 3.0),
]
self.deal_hands(state, [hand0, hand1])
self.apply_action(state, block_dominoes.Action(0, (6.0, 6.0), None))
# Both players don't hold tile with 6, therefore both blocked and the
# game end
self.assertTrue(state.is_terminal())
self.assertEqual(state.returns()[0], -45)
self.assertEqual(state.returns()[1], 45)
@staticmethod
def apply_action(state, action):
actions_str = block_dominoes._ACTIONS_STR
state.apply_action(actions_str.index(str(action)))
@staticmethod
def deal_hands(state, hands):
deck = block_dominoes._DECK
for hand in hands:
for t in hand:
state.apply_action(deck.index(t))
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/block_dominoes_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for open_spiel.python.games.data."""
from absl.testing import absltest
from absl.testing import parameterized
from open_spiel.python.algorithms import exploitability
from open_spiel.python.games import data
import pyspiel
class NashEquilibriumtest(parameterized.TestCase):
@parameterized.parameters((0.), (0.1), (1 / 3))
def test_exploitability_is_zero_on_nash(self, alpha):
# A similar test exists in:
# open_spiel/python/algorithms/exploitability_test.py
game = pyspiel.load_game("kuhn_poker")
policy = data.kuhn_nash_equilibrium(alpha=alpha)
expl = exploitability.exploitability(game, policy)
self.assertAlmostEqual(0, expl)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/data_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Tests for Python Tic-Tac-Toe."""
import difflib
import os
import pickle
from absl.testing import absltest
import numpy as np
from open_spiel.python.algorithms.get_all_states import get_all_states
from open_spiel.python.games import tic_tac_toe
from open_spiel.python.observation import make_observation
import pyspiel
_DATA_DIR = "open_spiel/integration_tests/playthroughs/"
class TicTacToeTest(absltest.TestCase):
def test_can_create_game_and_state(self):
"""Checks we can create the game and a state."""
game = tic_tac_toe.TicTacToeGame()
state = game.new_initial_state()
self.assertEqual(str(state), "...\n...\n...")
def test_random_game(self):
"""Tests basic API functions."""
# This is here mostly to show the API by example.
# More serious simulation tests are done in python/tests/games_sim_test.py
# and in test_game_from_cc (below), both of which test the conformance to
# the API thoroughly.
game = tic_tac_toe.TicTacToeGame()
state = game.new_initial_state()
while not state.is_terminal():
print(state)
cur_player = state.current_player()
legal_actions = state.legal_actions()
action = np.random.choice(legal_actions)
print("Player {} chooses action {}".format(cur_player, action))
state.apply_action(action)
print(state)
print("Returns: {}".format(state.returns()))
def test_game_from_cc(self):
"""Runs our standard game tests, checking API consistency."""
game = pyspiel.load_game("python_tic_tac_toe")
pyspiel.random_sim_test(game, num_sims=10, serialize=False, verbose=True)
def test_playthoughs_consistent(self):
"""Checks the saved C++ and Python playthroughs are the same."""
test_srcdir = os.environ.get("TEST_SRCDIR", "")
path = os.path.join(test_srcdir, _DATA_DIR)
cc_playthrough = os.path.join(path, "tic_tac_toe.txt")
py_playthrough = os.path.join(path, "python_tic_tac_toe.txt")
with open(cc_playthrough, encoding="utf-8") as cc:
with open(py_playthrough, encoding="utf-8") as py:
diffs = difflib.ndiff(list(cc), list(py))
diffs = {d for d in diffs if d and d[0] in {"+", "-"}}
self.assertEqual(
diffs, {
"- game: tic_tac_toe\n",
"+ game: python_tic_tac_toe\n",
'- GameType.long_name = "Tic Tac Toe"\n',
'+ GameType.long_name = "Python Tic-Tac-Toe"\n',
'- GameType.short_name = "tic_tac_toe"\n',
'+ GameType.short_name = "python_tic_tac_toe"\n',
'- ToString() = "tic_tac_toe()"\n',
'+ ToString() = "python_tic_tac_toe()"\n',
"- CurrentPlayer() = -4\n",
"+ CurrentPlayer() = PlayerId.TERMINAL\n",
"- Returns() = [0, 0]\n",
"+ Returns() = [0, -0]\n",
})
def test_observation_tensors_same(self):
"""Checks observation tensor is the same from C++ and from Python."""
game = pyspiel.load_game("python_tic_tac_toe")
state = game.new_initial_state()
for a in [4, 5, 2, 3]:
state.apply_action(a)
py_obs = make_observation(game)
py_obs.set_from(state, state.current_player())
cc_obs = state.observation_tensor()
np.testing.assert_array_equal(py_obs.tensor, cc_obs)
def test_pickle(self):
"""Checks pickling and unpickling of game and state."""
game = pyspiel.load_game("python_tic_tac_toe")
pickled_game = pickle.dumps(game)
unpickled_game = pickle.loads(pickled_game)
self.assertEqual(str(game), str(unpickled_game))
state = game.new_initial_state()
for a in [4, 2, 3, 7]:
state.apply_action(a)
ser_str = pyspiel.serialize_game_and_state(game, state)
new_game, new_state = pyspiel.deserialize_game_and_state(ser_str)
self.assertEqual(str(game), str(new_game))
self.assertEqual(str(state), str(new_state))
pickled_state = pickle.dumps(state)
unpickled_state = pickle.loads(pickled_state)
self.assertEqual(str(state), str(unpickled_state))
def test_cloned_state_matches_original_state(self):
"""Check we can clone states successfully."""
game = tic_tac_toe.TicTacToeGame()
state = game.new_initial_state()
state.apply_action(1)
state.apply_action(2)
clone = state.clone()
self.assertEqual(state.history(), clone.history())
self.assertEqual(state.num_players(), clone.num_players())
self.assertEqual(state.move_number(), clone.move_number())
self.assertEqual(state.num_distinct_actions(), clone.num_distinct_actions())
self.assertEqual(state._cur_player, clone._cur_player)
self.assertEqual(state._player0_score, clone._player0_score)
self.assertEqual(state._is_terminal, clone._is_terminal)
np.testing.assert_array_equal(state.board, clone.board)
def test_consistent(self):
"""Checks the Python and C++ game implementations are the same."""
py_game = pyspiel.load_game("python_tic_tac_toe")
cc_game = pyspiel.load_game("tic_tac_toe")
py_obs = make_observation(py_game)
cc_obs = make_observation(cc_game)
py_states = get_all_states(py_game, to_string=str)
cc_states = get_all_states(cc_game, to_string=str)
self.assertCountEqual(list(cc_states), list(py_states))
for key, cc_state in cc_states.items():
py_state = py_states[key]
np.testing.assert_array_equal(py_state.history(), cc_state.history())
np.testing.assert_array_equal(py_state.returns(), cc_state.returns())
py_obs.set_from(py_state, 0)
cc_obs.set_from(cc_state, 0)
np.testing.assert_array_equal(py_obs.tensor, cc_obs.tensor)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/tic_tac_toe_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Mean field routing game policy used in N-playerrouting game.
The policy class DerivedNPlayerPolicyFromMeanFieldPolicy convert a mean field
routing game policy to a N player routing game policy. It keep in memory the
mean field policy and convert a N player routing game state to a mean field
routing game state when calling action_probabilities. Therefore the mean field
policy can be used on a N player state. This makes the mean field equilibrium
policy (which is faster to compute) a policy that approximate well the
equilbrium N player policy (which is slower to compute) when N is large.
"""
from typing import Dict
from open_spiel.python import policy
from open_spiel.python.games import dynamic_routing
from open_spiel.python.games import dynamic_routing_utils
from open_spiel.python.mfg.games import dynamic_routing as mean_field_routing_game
import pyspiel
def _create_empty_mfg_state(game: dynamic_routing.DynamicRoutingGame):
"""Create an empty MFG state for the N player routing game.
Args:
game: the N player game.
Returns:
new_mfg_state: an empty MFG state corresponding to the N player game.
"""
od_demand_dict = {}
for vehicle in game._vehicles: # pylint:disable=protected-access
key = (vehicle.origin, vehicle.destination, vehicle.departure_time)
if key not in od_demand_dict:
od_demand_dict[key] = 0
od_demand_dict[key] += 1
od_demand = []
for (origin, destination, departure_time), counts in od_demand_dict.items():
od_demand.append(
dynamic_routing_utils.OriginDestinationDemand(origin, destination,
departure_time, counts))
return mean_field_routing_game.MeanFieldRoutingGame(
{
"max_num_time_step": game.max_game_length(),
"time_step_length": game.time_step_length
},
network=game.network,
od_demand=od_demand,
perform_sanity_checks=game.perform_sanity_checks).new_initial_state()
class DerivedNPlayerPolicyFromMeanFieldPolicy(policy.Policy):
"""Policy that apply mean field policy to N player game for dynamic routing.
Attributes:
_mfg_policy: the mean field game policy.
_mfg_empty_state: an empty mfg state to clone for the state conversion.
_state_memoization: dictionary to memoize conversion of N player game state
string representation to the corresponding MFG state.
"""
def __init__(self, game: dynamic_routing.DynamicRoutingGame,
mfg_policy: policy.Policy):
"""Initializes a uniform random policy for all players in the game."""
super().__init__(game, list(range(game.num_players())))
self._mfg_policy = mfg_policy
self._mfg_empty_state = _create_empty_mfg_state(game)
self._state_memoization = {}
def _convert_state_to_mean_field_state(
self, n_player_state: dynamic_routing.DynamicRoutingGameState,
player_id: int) -> mean_field_routing_game.MeanFieldRoutingGameState:
"""Convert a N player state to a mean field state."""
assert player_id >= 0, "player_id should be a positive integer."
# create a string key for N player game.
state_key = (str(n_player_state), player_id)
mfg_state = self._state_memoization.get(state_key)
if mfg_state is not None:
return mfg_state
mfg_state = self._mfg_empty_state.clone()
# pylint:disable=protected-access
mfg_state._is_chance_init = False
mfg_state._current_time_step = n_player_state._current_time_step
mfg_state._is_terminal = n_player_state._is_terminal
mfg_state._player_id = pyspiel.PlayerId.DEFAULT_PLAYER_ID
mfg_state._waiting_time = n_player_state._waiting_times[player_id]
mfg_state._vehicle_at_destination = (
player_id in n_player_state._vehicle_at_destination)
mfg_state._vehicle_destination = n_player_state._vehicle_destinations[
player_id]
mfg_state._vehicle_final_arrival_time = (
n_player_state._vehicle_final_arrival_times[player_id])
mfg_state._vehicle_location = n_player_state._vehicle_locations[player_id]
mfg_state._vehicle_without_legal_action = (
player_id in n_player_state._vehicle_without_legal_actions)
# pylint:enable=protected-access
self._state_memoization[state_key] = mfg_state
return mfg_state
def action_probabilities(self,
state: dynamic_routing.DynamicRoutingGameState,
player_id=None) -> Dict[int, float]:
"""Returns the mean field action to apply in the N player state.
Args:
state: An N player dynamic routing game state.
player_id: the player id for which we want an action. Should be given to
the function.
Returns:
A `dict` of `{action: probability}` for the specified player in the
supplied state.
"""
assert player_id is not None
mfg_state = self._convert_state_to_mean_field_state(state, player_id)
# Due to memoization, action_probabilities should not change mfg_state. In
# case action_probabilities changes mfg_state, then mfg_state.clone() should
# be passed to the function.
return self._mfg_policy.action_probabilities(mfg_state)
| open_spiel-master | open_spiel/python/games/dynamic_routing_to_mean_field_game.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Python implementation of iterated prisoner's dilemma.
This is primarily here to demonstrate simultaneous-move games in Python.
"""
import enum
import numpy as np
import pyspiel
_NUM_PLAYERS = 2
_DEFAULT_PARAMS = {"termination_probability": 0.125, "max_game_length": 9999}
_PAYOFF = [[5, 0], [10, 1]]
_GAME_TYPE = pyspiel.GameType(
short_name="python_iterated_prisoners_dilemma",
long_name="Python Iterated Prisoner's Dilemma",
dynamics=pyspiel.GameType.Dynamics.SIMULTANEOUS,
chance_mode=pyspiel.GameType.ChanceMode.EXPLICIT_STOCHASTIC,
information=pyspiel.GameType.Information.PERFECT_INFORMATION,
utility=pyspiel.GameType.Utility.GENERAL_SUM,
reward_model=pyspiel.GameType.RewardModel.REWARDS,
max_num_players=_NUM_PLAYERS,
min_num_players=_NUM_PLAYERS,
provides_information_state_string=False,
provides_information_state_tensor=False,
provides_observation_string=False,
provides_observation_tensor=False,
provides_factored_observation_string=False,
parameter_specification=_DEFAULT_PARAMS)
class Action(enum.IntEnum):
COOPERATE = 0
DEFECT = 1
class Chance(enum.IntEnum):
CONTINUE = 0
STOP = 1
class IteratedPrisonersDilemmaGame(pyspiel.Game):
"""The game, from which states and observers can be made."""
# pylint:disable=dangerous-default-value
def __init__(self, params=_DEFAULT_PARAMS):
max_game_length = params["max_game_length"]
super().__init__(
_GAME_TYPE,
pyspiel.GameInfo(
num_distinct_actions=2,
max_chance_outcomes=2,
num_players=2,
min_utility=np.min(_PAYOFF) * max_game_length,
max_utility=np.max(_PAYOFF) * max_game_length,
utility_sum=None,
max_game_length=max_game_length,
),
params,
)
self._termination_probability = params["termination_probability"]
def new_initial_state(self):
"""Returns a state corresponding to the start of a game."""
return IteratedPrisonersDilemmaState(self, self._termination_probability)
def make_py_observer(self, iig_obs_type=None, params=None):
"""Returns an object used for observing game state."""
return IteratedPrisonersDilemmaObserver(
iig_obs_type or pyspiel.IIGObservationType(perfect_recall=False),
params)
class IteratedPrisonersDilemmaState(pyspiel.State):
"""Current state of the game."""
def __init__(self, game, termination_probability):
"""Constructor; should only be called by Game.new_initial_state."""
super().__init__(game)
self._current_iteration = 1
self._termination_probability = termination_probability
self._is_chance = False
self._game_over = False
self._rewards = np.zeros(_NUM_PLAYERS)
self._returns = np.zeros(_NUM_PLAYERS)
# OpenSpiel (PySpiel) API functions are below. This is the standard set that
# should be implemented by every simultaneous-move game with chance.
def current_player(self):
"""Returns id of the next player to move, or TERMINAL if game is over."""
if self._game_over:
return pyspiel.PlayerId.TERMINAL
elif self._is_chance:
return pyspiel.PlayerId.CHANCE
else:
return pyspiel.PlayerId.SIMULTANEOUS
def _legal_actions(self, player):
"""Returns a list of legal actions, sorted in ascending order."""
assert player >= 0
return [Action.COOPERATE, Action.DEFECT]
def chance_outcomes(self):
"""Returns the possible chance outcomes and their probabilities."""
assert self._is_chance
return [(Chance.CONTINUE, 1 - self._termination_probability),
(Chance.STOP, self._termination_probability)]
def _apply_action(self, action):
"""Applies the specified action to the state."""
# This is not called at simultaneous-move states.
assert self._is_chance and not self._game_over
self._current_iteration += 1
self._is_chance = False
self._game_over = (action == Chance.STOP)
if self._current_iteration > self.get_game().max_game_length():
self._game_over = True
def _apply_actions(self, actions):
"""Applies the specified actions (per player) to the state."""
assert not self._is_chance and not self._game_over
self._is_chance = True
self._rewards[0] = _PAYOFF[actions[0]][actions[1]]
self._rewards[1] = _PAYOFF[actions[1]][actions[0]]
self._returns += self._rewards
def _action_to_string(self, player, action):
"""Action -> string."""
if player == pyspiel.PlayerId.CHANCE:
return Chance(action).name
else:
return Action(action).name
def is_terminal(self):
"""Returns True if the game is over."""
return self._game_over
def rewards(self):
"""Reward at the previous step."""
return self._rewards
def returns(self):
"""Total reward for each player over the course of the game so far."""
return self._returns
def __str__(self):
"""String for debug purposes. No particular semantics are required."""
return (f"p0:{self.action_history_string(0)} "
f"p1:{self.action_history_string(1)}")
def action_history_string(self, player):
return "".join(
self._action_to_string(pa.player, pa.action)[0]
for pa in self.full_history()
if pa.player == player)
class IteratedPrisonersDilemmaObserver:
"""Observer, conforming to the PyObserver interface (see observation.py)."""
def __init__(self, iig_obs_type, params):
"""Initializes an empty observation tensor."""
assert not bool(params)
self.iig_obs_type = iig_obs_type
self.tensor = None
self.dict = {}
def set_from(self, state, player):
pass
def string_from(self, state, player):
"""Observation of `state` from the PoV of `player`, as a string."""
if self.iig_obs_type.public_info:
return (f"us:{state.action_history_string(player)} "
f"op:{state.action_history_string(1 - player)}")
else:
return None
# Register the game with the OpenSpiel library
pyspiel.register_game(_GAME_TYPE, IteratedPrisonersDilemmaGame)
| open_spiel-master | open_spiel/python/games/iterated_prisoners_dilemma.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Implementation of dynamic routing game.
The game is derived from https://arxiv.org/abs/2110.11943.
This dynamic routing game models the evolution of N vehicles in a road network.
The vehicles are described by their current link location, the time they have to
spend on the link before exiting it, and their destination. The action of a
vehicle is the successor link they want to reach when exiting a given link.
Actions are encoded as integer from 0 to K. Action 0 encodes not being able to
move on a successor link because the waiting time of the player is still
positive. Actions 1 to K correspond to the indices of the network links. Legal
actions for a player on link l, with a negative waiting time are the indices of
the successors link of l. When arriving on a link, the waiting time of the
player is assign based on the number of players on the link at this time. Over
time steps, the waiting time linearly decrease until it is negative, the vehicle
moves to a successor link and the waiting time get reassigned.
The cost of the vehicle is its arrival time, it could be seen as a running cost
where +1 is added to the cost at any time step the vehicle is not on its
destination.
This dynamic routing game is a mesoscopic traffic model with explicit congestion
dynamics where vehicle minimizes their arrival time.
The game is defined by:
- a network given by the class Network.
- a list of vehicles given by the class Vehicle.
The current game is implementated as a N player game. However this game can also
be extended to a mean field game, implemented as python_mfg_dynamic_routing.
"""
from typing import Any, Iterable, List, Mapping, Optional, Set
import numpy as np
from open_spiel.python.games import dynamic_routing_data
from open_spiel.python.games import dynamic_routing_utils
from open_spiel.python.observation import IIGObserverForPublicInfoGame
import pyspiel
_DEFAULT_PARAMS = {
"max_num_time_step": 10,
"time_step_length": 0.5,
"players": -1
}
_GAME_TYPE = pyspiel.GameType(
short_name="python_dynamic_routing",
long_name="Python Dynamic Routing Game",
dynamics=pyspiel.GameType.Dynamics.SIMULTANEOUS,
chance_mode=pyspiel.GameType.ChanceMode.DETERMINISTIC,
information=pyspiel.GameType.Information.PERFECT_INFORMATION,
utility=pyspiel.GameType.Utility.GENERAL_SUM,
reward_model=pyspiel.GameType.RewardModel.REWARDS,
max_num_players=100,
min_num_players=0,
provides_information_state_string=True,
provides_information_state_tensor=True,
provides_observation_string=True,
provides_observation_tensor=True,
default_loadable=True,
provides_factored_observation_string=True,
parameter_specification=_DEFAULT_PARAMS)
class DynamicRoutingGame(pyspiel.Game):
"""Implementation of dynamic routing game.
At each simultaneous-move time, each vehicle/player with negative waiting time
chooses on which successor link they would like to go. When arriving on the
link, a waiting time is assigned to the player based on the count of players
on the link, after everyone has moved to their successors link. One vehicle
arrival time is equal to the time step when they first reach their
destination.
See module docstring for more information.
Attributes inherited from GameInfo:
max_chance_outcome: 0, the game is deterministic.
max_game_length: maximum number of time step played. Passed during
construction.
max_utility: maximum utility is the opposite of the minimum arrival time.
Set to 0.
min_utility: minimum utility is the opposite of the maximum arrival time.
Set to - max_game_length - 1.
num_distinct_actions: maximum number of possible actions. This is equal to
the number of links + 1 (corresponding to having no possible action
_NO_POSSIBLE_ACTION).
num_players: the number of vehicles. Choosen during by the constructor as
the number of vehicles.
Attributes:
network: the network of the game.
_vehicles: a list of the vehicle. Their origin and their destination should
be road sections of the game. The number of vehicles in the list sets the
num_players attribute.
time_step_length: size of the time step, used to convert travel times into
number of game time steps.
perform_sanity_checks: if true, sanity checks are done during the game,
should be set to false to speed up the game.
"""
network: dynamic_routing_utils.Network
_vehicles: List[dynamic_routing_utils.Vehicle]
perform_sanity_checks: bool
time_step_length: float
def __init__(
self,
params: Mapping[str, Any],
network: Optional[dynamic_routing_utils.Network] = None,
vehicles: Optional[List[dynamic_routing_utils.Vehicle]] = None,
perform_sanity_checks: bool = True,
):
"""Initiliaze the game.
Args:
params: game parameters. It should define max_num_time_step and
time_step_length.
network: the network of the game.
vehicles: a list of the vehicle. Their origin and their destination should
be road sections of the game. The number of vehicles in the list sets
the num_players attribute.
perform_sanity_checks: set the perform_sanity_checks attribute.
"""
max_num_time_step = params["max_num_time_step"]
time_step_length = params["time_step_length"]
self.network = network if network else dynamic_routing_data.BRAESS_NETWORK
self._vehicles = (
vehicles
if vehicles else dynamic_routing_data.BRAESS_NETWORK_VEHICLES_DEMAND)
self.network.check_list_of_vehicles_is_correct(self._vehicles)
self.perform_sanity_checks = perform_sanity_checks
self.time_step_length = time_step_length
game_info = pyspiel.GameInfo(
num_distinct_actions=self.network.num_actions(),
max_chance_outcomes=0,
num_players=len(self._vehicles),
min_utility=-max_num_time_step - 1,
max_utility=0,
max_game_length=max_num_time_step)
super().__init__(_GAME_TYPE, game_info, params if params else {})
def new_initial_state(self) -> "DynamicRoutingGameState":
"""Returns the state corresponding to the start of a game."""
return DynamicRoutingGameState(self, self._vehicles, self.time_step_length)
def make_py_observer(self, iig_obs_type=None, params=None):
"""Returns a NetworkObserver object used for observing game state."""
if ((iig_obs_type is None) or
(iig_obs_type.public_info and not iig_obs_type.perfect_recall)):
return NetworkObserver(self.num_players(), self.max_game_length())
return IIGObserverForPublicInfoGame(iig_obs_type, params)
class DynamicRoutingGameState(pyspiel.State):
"""State of the DynamicRoutingGame.
One player is equal to one vehicle.
See docstring of the game class and of the file for more information.
Attributes:
_current_time_step: current time step of the game.
_is_terminal: boolean that encodes weither the game is over.
_time_step_length: size of the time step, used to convert travel times into
number of game time steps.
_vehicle_at_destination: set of vehicles that have reached their
destinations. When a vehicle has reached its destination but the game is
not finished, it cannot do anything.
_vehicle_destinations: the destination of each vehicle.
_vehicle_final_arrival_times: the arrival times of each vehicle, the arrival
is either 0 if the vehicle is still in the network or its arrival time if
the vehicle has reached its destination.
_vehicle_locations: current location of the vehicles as a network road
section.
_vehicle_without_legal_actions: list of vehicles without legal actions at
next time step. This is required because if no vehicle has legal actions
for a simultaneous node then an error if raised.
_waiting_times: time that each vehicle should wait before being able to move
to the next road section.
"""
_current_time_step: int
_is_terminal: bool
_time_step_length: float
_vehicle_at_destination: Set[int]
_vehicle_destinations: List[str]
_vehicle_final_arrival_times: List[float]
_vehicle_locations: List[str]
_vehicle_without_legal_actions: Set[int]
_waiting_times: List[int]
def __init__(self, game: DynamicRoutingGame,
vehicles: Iterable[dynamic_routing_utils.Vehicle],
time_step_length: float):
"""Constructor; should only be called by Game.new_initial_state."""
super().__init__(game)
self._current_time_step = 0
self._is_terminal = False
self._time_step_length = time_step_length
self._vehicle_at_destination = set()
self._vehicle_destinations = [vehicle.destination for vehicle in vehicles]
self._vehicle_final_arrival_times = [0.0 for _ in vehicles]
self._vehicle_locations = [vehicle.origin for vehicle in vehicles]
self._vehicle_without_legal_actions = set()
self._waiting_times = [
int(veh._departure_time / self._time_step_length) for veh in vehicles
]
self.running_cost = [0 for vehicle in vehicles]
@property
def current_time_step(self) -> int:
"""Return current time step."""
return self._current_time_step
def current_player(self) -> pyspiel.PlayerId:
"""Returns the current player.
If the game is over, TERMINAL is returned. If the game is at a chance
node then CHANCE is returned. Otherwise SIMULTANEOUS is returned.
"""
if self._is_terminal:
return pyspiel.PlayerId.TERMINAL
return pyspiel.PlayerId.SIMULTANEOUS
def assert_valid_player(self, vehicle: int):
"""Assert that a vehicle as a int between 0 and num_players."""
assert isinstance(vehicle, int), f"{vehicle} is not a int."
assert vehicle >= 0, f"player: {vehicle}<0."
assert vehicle < self.get_game().num_players(), (
f"player: {vehicle} >= num_players: {self.get_game().num_players()}")
def _legal_actions(self, vehicle: int) -> List[int]:
"""Return the legal actions of the vehicle.
Legal actions are the succesor road section of the vehicle current road
section.
Args:
vehicle: the vehicle id.
Returns:
list_legal_actions: a list of legal actions. If the game is finished then
the list is empty. If the vehicle is at its destination, has a positive
waiting time or if it is on a node without successors then an empty list
is returned. Otherwise the list of successors nodes of the current
vehicle location is returned.
"""
if self._is_terminal:
return []
if self.get_game().perform_sanity_checks:
self.assert_valid_player(vehicle)
if vehicle in self._vehicle_without_legal_actions:
# If the vehicle is at destination it cannot do anything.
return [dynamic_routing_utils.NO_POSSIBLE_ACTION]
if self._waiting_times[vehicle] > 0:
return [dynamic_routing_utils.NO_POSSIBLE_ACTION]
_, end_section_node = dynamic_routing_utils._nodes_from_road_section( # pylint:disable=protected-access
self._vehicle_locations[vehicle])
successors = self.get_game().network.get_successors(end_section_node)
if successors:
assert isinstance(successors, Iterable)
actions = [
self.get_game().network.get_action_id_from_movement(
end_section_node, d) for d in successors
]
if self.get_game().perform_sanity_checks:
map(self.get_game().network.assert_valid_action, actions)
return sorted(actions)
return []
def _apply_actions(self, actions: List[int]):
"""Applies the specified action to the state.
For each vehicle's action, if the vehicle is not at a sink node, if the
action is valid and if the waiting time is negative, then the vehicle will
move to the successor link corresponding to its action.
The function then detects if the vehicle has reached its destination or
a sink node and updates _vehicle_at_destination,
_vehicle_without_legal_actions and _vehicle_final_arrival_times
accordingly.
The function then assigns waiting for each vehicle that have moved based on
the new volume of cars on the link they reach.
The function evolves the time and checks if the game is finished.
Args:
actions: the action chosen by each vehicle.
"""
if self.get_game().perform_sanity_checks:
assert not self._is_terminal
if self.get_game().perform_sanity_checks:
assert isinstance(actions, Iterable)
assert len(actions) == self.get_game().num_players(), (
f"Each player does not have an actions. Actions has {len(actions)} "
f"elements, it should have {self.get_game().num_players()}.")
for vehicle_id, action in enumerate(actions):
if vehicle_id not in self._vehicle_at_destination:
self.running_cost[vehicle_id] += self._time_step_length
# Has the vehicle already reached a sink node?
if vehicle_id in self._vehicle_without_legal_actions:
if self.get_game().perform_sanity_checks:
assert action == dynamic_routing_utils.NO_POSSIBLE_ACTION, (
f"{action} should be {dynamic_routing_utils.NO_POSSIBLE_ACTION}.")
continue
if self._waiting_times[vehicle_id] > 0:
continue
if self.get_game().perform_sanity_checks:
self.get_game().network.assert_valid_action(
action, self._vehicle_locations[vehicle_id])
self._vehicle_locations[vehicle_id] = (
self.get_game().network.get_road_section_from_action_id(action))
if (self._vehicle_locations[vehicle_id] ==
self._vehicle_destinations[vehicle_id]):
self._vehicle_final_arrival_times[vehicle_id] = self._current_time_step
self._vehicle_at_destination.add(vehicle_id)
self._vehicle_without_legal_actions.add(vehicle_id)
# Will the vehicle have a legal action for next time step?
elif self.get_game().network.is_location_at_sink_node(
self._vehicle_locations[vehicle_id]):
self._vehicle_without_legal_actions.add(vehicle_id)
self._current_time_step += 1
volumes = {}
for road_section in self._vehicle_locations:
if road_section not in volumes:
volumes[road_section] = 0
# Each vehicle has a weight a one.
volumes[road_section] += 1
for vehicle_id, _ in enumerate(actions):
# Has the vehicle already reached a sink node?
if vehicle_id in self._vehicle_without_legal_actions:
continue
if self._waiting_times[vehicle_id] > 0:
self._waiting_times[vehicle_id] -= 1
else:
self._waiting_times[vehicle_id] = int(self.get_game(
).network.get_travel_time(self._vehicle_locations[vehicle_id], volumes[
self._vehicle_locations[vehicle_id]]) / self._time_step_length -
1.0)
# Is the game finished?
if (self._current_time_step >= self.get_game().max_game_length() or len(
self._vehicle_without_legal_actions) == self.get_game().num_players()):
self._is_terminal = True
for vehicle_id in range(self.get_game().num_players()):
if vehicle_id not in self._vehicle_at_destination:
self._vehicle_final_arrival_times[vehicle_id] = (
self._current_time_step)
def _action_to_string(self, player, action) -> str:
"""Action -> string."""
if self.get_game().perform_sanity_checks:
self.assert_valid_player(player)
if action == dynamic_routing_utils.NO_POSSIBLE_ACTION:
return f"Vehicle {player} reach a sink node or its destination."
if self.get_game().perform_sanity_checks:
self.get_game().network.assert_valid_action(action)
return (f"Vehicle {player} would like to move to "
f"{self.get_game().network.get_road_section_from_action_id(action)}"
".")
def is_terminal(self) -> bool:
"""Returns True if the game is over."""
return self._is_terminal
def rewards(self):
"""Reward at the previous step."""
if self._is_terminal or self._current_time_step == 0:
return [0 for _ in self._vehicle_locations]
reward = [-self._time_step_length for _ in self._vehicle_locations]
for vehicle in self._vehicle_at_destination:
reward[vehicle] = 0
return reward
def returns(self) -> List[float]:
"""Total reward for each player over the course of the game so far."""
if not self._is_terminal:
returns = [
-self._time_step_length * self.current_time_step
for _ in self._vehicle_locations
]
for vehicle in self._vehicle_at_destination:
returns[vehicle] = -(
self._vehicle_final_arrival_times[vehicle] * self._time_step_length)
return returns
returns = [
-arrival_time * self._time_step_length
for arrival_time in self._vehicle_final_arrival_times
]
return returns
def get_current_vehicle_locations(self) -> List[str]:
"""Get vehicle locations for debug purposes."""
return self._vehicle_locations
def get_location_as_int(self, vehicle: int) -> int:
"""Get the vehicle location."""
origin, destination = dynamic_routing_utils._nodes_from_road_section( # pylint:disable=protected-access
self._vehicle_locations[vehicle])
return self.get_game().network.get_action_id_from_movement(
origin, destination)
def get_current_vehicle_locations_as_int(self) -> List[int]:
"""Get locations of all vehicles for the observation tensor."""
return [
self.get_location_as_int(x)
for x in range(self.get_game().num_players())
]
def __str__(self) -> str:
"""String for debug purposes. No particular semantics are required."""
if self._is_terminal:
time = f"{self._current_time_step}, game finished."
else:
time = f"{self._current_time_step}"
return (f"Vehicle locations: {self._vehicle_locations}, "
f"time: {time}, waiting_time={self._waiting_times}.")
class NetworkObserver:
"""Network observer used by the learning algorithm.
The state string is the state history string. The state tensor is an array
of size max_game_length, num_players where each element is the location of
the vehicle at this time.
Attributes:
dict: dictionary {"observation": tensor}.
tensor: list of location for each time step.
"""
def __init__(self, num_vehicles: int, num_time: int):
"""Initializes an empty observation tensor."""
shape = (num_time + 1, num_vehicles + 1)
self.tensor = np.zeros(np.prod(shape), np.float32)
self.dict = {"observation": np.reshape(self.tensor, shape)}
def set_from(self, state, player):
"""Update the state tensor.
Put the locations of each players in the tensor row corresponding to
the current time step. Insert the current player location at the
beginning of the row.
Args:
state: the state,
player: the player.
"""
vehicles = state.get_current_vehicle_locations_as_int()
vehicles.insert(0, state.get_location_as_int(player))
self.dict["observation"][state.current_time_step, :] = vehicles
def string_from(self, state, player):
"""Return the state history string."""
return f"{player}: {state.history_str()}"
# Register the game with the OpenSpiel library
pyspiel.register_game(_GAME_TYPE, DynamicRoutingGame)
| open_spiel-master | open_spiel/python/games/dynamic_routing.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Tests for Python Liar's Poker."""
import pickle
from absl.testing import absltest
import numpy as np
from open_spiel.python.games import liars_poker
import pyspiel
class LiarsPokerTest(absltest.TestCase):
def test_can_create_game_and_state(self):
"""Checks we can create the game and a state."""
game = liars_poker.LiarsPoker({"hand_length": 3, "num_digits": 3})
state = game.new_initial_state()
# Ensure no moves have been made.
expected_hands = [[] for _ in range(game.num_players())]
expected_bidder = -1
expected_current_player = pyspiel.PlayerId.CHANCE
expected_current_count = "None"
expected_current_number = "None"
expected_rebid = False
expected = (
"Hands: {}, Bidder: {}, Current Player: {}, Current Bid: {} of {},"
" Rebid: {}".format(
expected_hands,
expected_bidder,
expected_current_player,
expected_current_count,
expected_current_number,
expected_rebid,
)
)
self.assertEqual(str(state), expected)
def test_draw_hands(self):
"""Tests hand drawing functions."""
game = liars_poker.LiarsPoker({"hand_length": 3, "num_digits": 3})
state = game.new_initial_state()
expected_hands = [[] for _ in range(game.num_players())]
for i in range(game.num_players() * game.hand_length):
# Verify we have chance nodes until all player hands are filled.
self.assertEqual(state.current_player(), pyspiel.PlayerId.CHANCE)
# Draw a digit.
outcomes_with_probs = state.chance_outcomes()
action_list, prob_list = zip(*outcomes_with_probs)
action = np.random.choice(action_list, p=prob_list)
# Verify players' hands are filled correctly.
cur_player = i % game.num_players()
expected_hands[cur_player].append(action)
state.apply_action(action)
self.assertEqual(state.hands, expected_hands)
# Assert after all hands are filled, we have non-chance nodes.
cur_player = state.current_player()
self.assertNotEqual(cur_player, pyspiel.PlayerId.CHANCE)
self.assertEqual(cur_player, 0)
def _populate_game_hands(self, game, state):
"""Populates players hands for testing."""
for _ in range(game.num_players() * game.hand_length):
outcomes_with_probs = state.chance_outcomes()
action_list, prob_list = zip(*outcomes_with_probs)
action = np.random.choice(action_list, p=prob_list)
state.apply_action(action)
def test_basic_bid(self):
"""Tests a single bid."""
game = liars_poker.LiarsPoker({"hand_length": 3, "num_digits": 3})
state = game.new_initial_state()
expected_bid_history = np.zeros(
(state.total_possible_bids, state.num_players())
)
# Fill players hands.
self._populate_game_hands(game, state)
# After all hands are filled, have player 0 bid.
cur_player = state.current_player()
action = 2
state.apply_action(action)
# Verify bid history is updated correctly.
bid_offset = liars_poker.BID_ACTION_OFFSET
expected_bid_history[action - bid_offset][cur_player] = 1
self.assertTrue((state.bid_history == expected_bid_history).all())
# Verify next set of legal bids is greater than the current bid.
for next_action in state.legal_actions():
if next_action == liars_poker.CHALLENGE_ACTION:
continue
self.assertGreater(next_action, action)
def _verify_returns(self, game, state):
self.assertTrue(state.winner() != -1 or state.loser() != -1)
actual_returns = state.returns()
if state.winner() != -1:
expected_returns = [-1.0 for _ in range(game.num_players())]
expected_returns[state.winner()] = game.num_players() - 1
else:
expected_returns = [1.0 for _ in range(game.num_players())]
expected_returns[state.loser()] = -1.0 * (game.num_players() - 1)
self.assertEqual(actual_returns, expected_returns)
def test_single_random_round(self):
"""Runs a single round of bidding followed by a challenge."""
game = liars_poker.LiarsPoker({"hand_length": 3, "num_digits": 3})
state = game.new_initial_state()
expected_challenge_history = np.zeros(
(state.total_possible_bids, state.num_players())
)
# Fill players hands.
self._populate_game_hands(game, state)
# Have player 0 bid.
action = 2
state.apply_action(action)
# Verify challenge action is available to the next player.
challenge = liars_poker.CHALLENGE_ACTION
self.assertIn(challenge, state.legal_actions())
# Player 1 challenges.
cur_player = state.current_player()
state.apply_action(challenge)
bid_offset = liars_poker.BID_ACTION_OFFSET
expected_challenge_history[action - bid_offset][cur_player] = 1
# Verify challenge history is updated correctly.
self.assertTrue(
(state.challenge_history == expected_challenge_history).all()
)
# Original bidder challenges, thus agreeing to a count.
cur_player = state.current_player()
state.apply_action(challenge)
expected_challenge_history[action - bid_offset][cur_player] = 1
# Verify challenge history is updated correctly.
self.assertTrue(
(state.challenge_history == expected_challenge_history).all()
)
# Verify game is over.
self.assertTrue(state.is_terminal())
# Verify returns.
self._verify_returns(game, state)
def test_single_deterministic_round(self):
"""Runs a single round where cards are dealt deterministically."""
game = liars_poker.LiarsPoker({"hand_length": 3, "num_digits": 3})
state = game.new_initial_state()
# Deal player 0 all "1" cards and player 1 all "2" cards.
for i in range(game.num_players() * game.hand_length):
if i % 2 == 0:
# Deal card to player 0
state.apply_action(1)
else:
# Deal card to player 1
state._apply_action(2)
# Have player 0 bid that there are four 1's.
state.apply_action(state.encode_bid(4, 1) + liars_poker.BID_ACTION_OFFSET)
# Player 1 challenges.
state.apply_action(liars_poker.CHALLENGE_ACTION)
# Player 0 accepts the challenge.
state.apply_action(liars_poker.CHALLENGE_ACTION)
# Verify game ends with player 0 losing.
self.assertTrue(state.is_terminal())
self.assertEqual(state.loser(), 0)
expected_returns = [1.0 for _ in range(game.num_players())]
expected_returns[state.loser()] = -1.0 * (game.num_players() - 1)
self.assertEqual(state.returns(), expected_returns)
def test_single_rebid(self):
"""Runs a 2 player game where a rebid is enacted."""
game = liars_poker.LiarsPoker({"hand_length": 3, "num_digits": 3})
state = game.new_initial_state()
# Fill players hands.
self._populate_game_hands(game, state)
# Have player 0 bid.
state.apply_action(2)
# Player 1 challenges.
state.apply_action(liars_poker.CHALLENGE_ACTION)
# Original bidder rebids.
state.apply_action(3)
# Verify game is not over.
self.assertFalse(state.is_terminal())
self.assertEqual(state.returns(), [0.0 for _ in range(game.num_players())])
# Player 1 challenges again.
state.apply_action(liars_poker.CHALLENGE_ACTION)
# Verify game is now over.
self.assertTrue(state.is_terminal())
self._verify_returns(game, state)
def test_rebid_then_new_bid(self):
"""Runs a 2 player game where a rebid is enacted."""
game = liars_poker.LiarsPoker({"hand_length": 3, "num_digits": 3})
state = game.new_initial_state()
# Fill players hands.
self._populate_game_hands(game, state)
# Have player 0 bid.
state.apply_action(2)
# Player 1 challenges.
state.apply_action(liars_poker.CHALLENGE_ACTION)
# Original bidder rebids.
state.apply_action(3)
# Verify game is not over.
self.assertFalse(state.is_terminal())
self.assertEqual(state.returns(), [0.0 for _ in range(game.num_players())])
# Player 1 bids.
state.apply_action(4)
# Verify game is not over.
self.assertFalse(state.is_terminal())
# Player 0 challenges.
state.apply_action(liars_poker.CHALLENGE_ACTION)
# Verify we're not rebidding and counts is only called once both players
# challenge.
self.assertFalse(state.is_terminal())
# Player 1 challenges and ends the game with a counts.
state.apply_action(liars_poker.CHALLENGE_ACTION)
# Verify game is now over.
self.assertTrue(state.is_terminal())
self._verify_returns(game, state)
def test_game_from_cc(self):
"""Runs the standard game tests, checking API consistency."""
game = pyspiel.load_game("python_liars_poker", {"players": 2})
pyspiel.random_sim_test(game, num_sims=10, serialize=False, verbose=True)
def test_pickle(self):
"""Checks pickling and unpickling of game and state."""
game = pyspiel.load_game("python_liars_poker")
pickled_game = pickle.dumps(game)
unpickled_game = pickle.loads(pickled_game)
self.assertEqual(str(game), str(unpickled_game))
state = game.new_initial_state()
for a in [2, 3, 4, 5]:
state.apply_action(a)
ser_str = pyspiel.serialize_game_and_state(game, state)
new_game, new_state = pyspiel.deserialize_game_and_state(ser_str)
self.assertEqual(str(game), str(new_game))
self.assertEqual(str(state), str(new_state))
pickled_state = pickle.dumps(state)
unpickled_state = pickle.loads(pickled_state)
self.assertEqual(str(state), str(unpickled_state))
def test_cloned_state_matches_original_state(self):
"""Check we can clone states successfully."""
game = liars_poker.LiarsPoker({"hand_length": 3, "num_digits": 3})
state = game.new_initial_state()
state.apply_action(1)
state.apply_action(2)
clone = state.clone()
self.assertEqual(state.history(), clone.history())
self.assertEqual(state.num_players(), clone.num_players())
self.assertEqual(state.move_number(), clone.move_number())
self.assertEqual(state.num_distinct_actions(), clone.num_distinct_actions())
self.assertEqual(state._current_player, clone._current_player)
self.assertEqual(state._current_action, clone._current_action)
np.testing.assert_array_equal(state.bid_history, clone.bid_history)
np.testing.assert_array_equal(
state.challenge_history, clone.challenge_history
)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/liars_poker_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Block Dominoes implemented in Python.
https://en.wikipedia.org/wiki/Dominoes#Blocking_game
"""
import copy
import itertools
import numpy as np
import pyspiel
_NUM_PLAYERS = 2
_PIPS = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
_DECK = list(itertools.combinations_with_replacement(_PIPS, 2))
_EDGES = [None, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
class Action:
"""Represent player possible action."""
def __init__(self, player, tile, edge):
self.player = player
self.tile = tile
self.edge = edge
def __str__(self):
return f"p{self.player} tile:{self.tile} pip:{self.edge}"
def __repr__(self):
return self.__str__()
def create_possible_actions():
actions = []
for player in range(_NUM_PLAYERS):
for tile in _DECK:
for edge in _EDGES:
if edge in tile or edge is None: # can we play tile on edge?
actions.append(Action(player, tile, edge))
return actions
_ACTIONS = create_possible_actions()
_ACTIONS_STR = [str(action) for action in _ACTIONS]
_HAND_SIZE = 7
_MAX_GAME_LENGTH = 28
_GAME_TYPE = pyspiel.GameType(
short_name="python_block_dominoes",
long_name="Python block dominoes",
dynamics=pyspiel.GameType.Dynamics.SEQUENTIAL,
chance_mode=pyspiel.GameType.ChanceMode.EXPLICIT_STOCHASTIC,
information=pyspiel.GameType.Information.IMPERFECT_INFORMATION,
utility=pyspiel.GameType.Utility.ZERO_SUM,
reward_model=pyspiel.GameType.RewardModel.TERMINAL,
max_num_players=_NUM_PLAYERS,
min_num_players=_NUM_PLAYERS,
provides_information_state_string=True,
provides_information_state_tensor=True,
provides_observation_string=True,
provides_observation_tensor=True,
provides_factored_observation_string=True,
)
_GAME_INFO = pyspiel.GameInfo(
num_distinct_actions=len(_ACTIONS),
max_chance_outcomes=len(_DECK),
# first player hand: (6,6) (6,5) (5,5) (6,4) (4,5) (6,3) (4,4)
# second player hand is empty. can be reduced.
min_utility=-69,
max_utility=69,
num_players=_NUM_PLAYERS,
# deal: 14 chance nodes + play: 14 player nodes
max_game_length=_MAX_GAME_LENGTH,
utility_sum=0.0,
)
class BlockDominoesGame(pyspiel.Game):
"""A Python version of Block Dominoes."""
def __init__(self, params=None):
super().__init__(_GAME_TYPE, _GAME_INFO, params or dict())
def new_initial_state(self):
"""Returns a state corresponding to the start of a game."""
return BlockDominoesState(self)
def make_py_observer(self, iig_obs_type=None, params=None):
"""Returns an object used for observing game state."""
return BlockDominoesObserver(
iig_obs_type or pyspiel.IIGObservationType(perfect_recall=False), params
)
class BlockDominoesState(pyspiel.State):
"""A python version of the Block Dominoes state."""
def __init__(self, game):
"""Constructor; should only be called by Game.new_initial_state."""
super().__init__(game)
self.actions_history = []
self.open_edges = []
self.hands = [[], []]
self.deck = copy.deepcopy(_DECK)
self._game_over = False
self._next_player = pyspiel.PlayerId.CHANCE
# OpenSpiel (PySpiel) API functions are below. This is the standard set that
# should be implemented by every sequential-move game with chance.
def current_player(self):
"""Returns id of the next player to move, or TERMINAL if game is over."""
if self._game_over:
return pyspiel.PlayerId.TERMINAL
if len(self.deck) > 14:
return pyspiel.PlayerId.CHANCE
return self._next_player
def _legal_actions(self, player):
"""Returns a list of legal actions, sorted in ascending order."""
assert player >= 0
assert player == self._next_player
return self.get_legal_actions(player)
def get_legal_actions(self, player):
"""Returns a list of legal actions."""
assert player >= 0
actions = []
hand = self.hands[player]
# first move, no open edges
if not self.open_edges:
for tile in hand:
actions.append(Action(player, tile, None))
else:
for tile in hand:
if tile[0] in self.open_edges:
actions.append(Action(player, tile, tile[0]))
if tile[0] != tile[1] and tile[1] in self.open_edges:
actions.append(Action(player, tile, tile[1]))
actions_idx = [_ACTIONS_STR.index(str(action)) for action in actions]
actions_idx.sort()
return actions_idx
def chance_outcomes(self):
"""Returns the possible chance outcomes and their probabilities."""
assert self.is_chance_node()
p = 1.0 / len(self.deck)
return [(_DECK.index(i), p) for i in self.deck]
def _apply_action(self, action):
"""Applies the specified action to the state."""
if self.is_chance_node():
hand_to_add_tile = (
self.hands[0] if len(self.hands[0]) != _HAND_SIZE else self.hands[1]
)
tile = _DECK[action]
self.deck.remove(tile)
hand_to_add_tile.append(tile)
if not len(self.hands[0]) == len(self.hands[1]) == _HAND_SIZE:
return # another tiles to deal
for hand in self.hands:
hand.sort()
self._next_player = 0
else:
action = _ACTIONS[action]
self.actions_history.append(action)
my_idx = self.current_player()
my_hand = self.hands[my_idx]
my_hand.remove(action.tile)
self.update_open_edges(action)
if not my_hand:
self._game_over = True # player played his last tile
return
opp_idx = 1 - my_idx
opp_legal_actions = self.get_legal_actions(opp_idx)
if opp_legal_actions:
self._next_player = opp_idx
return
my_legal_actions = self.get_legal_actions(my_idx)
if my_legal_actions:
self._next_player = my_idx
return
self._game_over = True # both players are blocked
def update_open_edges(self, action):
if not self.open_edges:
self.open_edges = list(action.tile)
else:
self.open_edges.remove(action.edge)
new_edge = (
action.tile[0] if action.tile[0] != action.edge else action.tile[1]
)
self.open_edges.append(new_edge)
self.open_edges.sort()
def _action_to_string(self, player, action):
"""Action -> string."""
if player == pyspiel.PlayerId.CHANCE:
return f"Deal {_DECK[action]}"
return _ACTIONS_STR[action]
def is_terminal(self):
"""Returns True if the game is over."""
return self._game_over
def returns(self):
"""Total reward for each player over the course of the game so far."""
if not self.is_terminal():
return [0, 0]
sum_of_pips0 = sum(t[0] + t[1] for t in self.hands[0])
sum_of_pips1 = sum(t[0] + t[1] for t in self.hands[1])
if sum_of_pips1 == sum_of_pips0:
return [0, 0]
if sum_of_pips1 > sum_of_pips0:
return [sum_of_pips1, -sum_of_pips1]
return [-sum_of_pips0, sum_of_pips0]
def __str__(self):
"""String for debug purposes. No particular semantics are required."""
hand0 = [str(c) for c in self.hands[0]]
hand1 = [str(c) for c in self.hands[1]]
history = [str(a) for a in self.actions_history]
return f"hand0:{hand0} hand1:{hand1} history:{history}"
class BlockDominoesObserver:
"""Observer, conforming to the PyObserver interface (see observation.py)."""
def __init__(self, iig_obs_type, params):
"""Initializes an empty observation tensor."""
if params:
raise ValueError(f"Observation parameters not supported; passed {params}")
# Determine which observation pieces we want to include.
pieces = [("player", 2, (2,))]
if iig_obs_type.private_info == pyspiel.PrivateInfoType.SINGLE_PLAYER:
# each tile is represented using 3 integers:
# 2 for the pips, and 1 to distinguish between (0,0) to empty slot for
# a tile.
pieces.append(("hand", 21, (7, 3)))
if iig_obs_type.public_info:
if iig_obs_type.perfect_recall:
# list of all played actions, each action is represented using 5
# integers:
# 2 for the played tile (0-6), 1 for the covered edge (0-6),
# 1 for which player (0/1), 1 to distinguish between actual move and
# empty slot for a move (0/1).
# the None (play on an empty board) edge represented using 0.
pieces.append(("actions_history", 70, (14, 5)))
else:
# last action, represented in the same way as in "actions_history"
# but without the last integer.
pieces.append(("last_action", 4, (4,)))
pieces.append(("hand_sizes", 2, (2,)))
# Build the single flat tensor.
total_size = sum(size for name, size, shape in pieces)
self.tensor = np.zeros(total_size, np.float32)
# Build the named & reshaped views of the bits of the flat tensor.
self.dict = {}
index = 0
for name, size, shape in pieces:
self.dict[name] = self.tensor[index : index + size].reshape(shape)
index += size
def set_from(self, state, player):
"""Updates `tensor` and `dict` to reflect `state` from PoV of `player`."""
self.tensor.fill(0)
if "player" in self.dict:
self.dict["player"][player] = 1
self.dict["player"][1 - player] = 0
if "hand_sizes" in self.dict:
my_hand_size = len(state.hands[player])
opp_hand_size = len(state.hands[1 - player])
self.dict["hand_sizes"][0] = my_hand_size
self.dict["hand_sizes"][1] = opp_hand_size
if "edges" in self.dict:
if state.open_edges:
self.dict["edges"][0] = state.open_edges[0]
self.dict["edges"][1] = state.open_edges[1]
else:
self.dict["edges"][0] = 0.0
self.dict["edges"][1] = 0.0
if "hand" in self.dict:
for i, tile in enumerate(state.hands[player]):
self.dict["hand"][i][0] = tile[0]
self.dict["hand"][i][1] = tile[1]
self.dict["hand"][i][2] = 1.0
if "actions_history" in self.dict:
for i, action in enumerate(state.actions_history):
self.dict["actions_history"][i][0] = action.tile[0]
self.dict["actions_history"][i][1] = action.tile[1]
self.dict["actions_history"][i][2] = (
action.edge if action.edge is not None else 0.0
)
self.dict["actions_history"][i][3] = action.player
self.dict["actions_history"][i][4] = 1.0
if "last_action" in self.dict:
if state.actions_history:
action = state.actions_history[-1]
self.dict["last_action"][0] = action.tile[0]
self.dict["last_action"][1] = action.tile[1]
self.dict["last_action"][2] = (
action.edge if action.edge is not None else 0.0
)
self.dict["last_action"][3] = action.player
def string_from(self, state, player):
"""Observation of `state` from the PoV of `player`, as a string."""
pieces = []
if "player" in self.dict:
pieces.append(f"p{player}")
if "hand" in self.dict:
pieces.append(f"hand:{state.hands[player]}")
if "actions_history" in self.dict:
pieces.append(f"history:{str(state.actions_history)}")
if "last_action" in self.dict and state.actions_history:
pieces.append(f"last_action:{str(state.actions_history[-1])}")
return " ".join(str(p) for p in pieces)
# Register the game with the OpenSpiel library
pyspiel.register_game(_GAME_TYPE, BlockDominoesGame)
| open_spiel-master | open_spiel/python/games/block_dominoes.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for dynamic_routing_to_mean_field_game."""
from absl.testing import absltest
from open_spiel.python import games # pylint:disable=unused-import
from open_spiel.python import policy
from open_spiel.python.algorithms import expected_game_score
from open_spiel.python.games import dynamic_routing_to_mean_field_game
from open_spiel.python.mfg import games as mfg_games # pylint:disable=unused-import
from open_spiel.python.mfg.algorithms import mirror_descent
import pyspiel
class DerivedNPlayerPolicyFromMeanFieldPolicyTest(absltest.TestCase):
def test_state_conversion_method(self):
"""Test N player game state to mean field game state conversion."""
# Test state conversion.
def test_uniform_mfg_policy_conversion_to_n_player_uniform_policy(self):
"""Test conversion of uniform to uniform policy."""
mfg_game = pyspiel.load_game("python_mfg_dynamic_routing", {
"time_step_length": 0.05,
"max_num_time_step": 100
})
n_player_game = pyspiel.load_game("python_dynamic_routing", {
"time_step_length": 0.05,
"max_num_time_step": 100
})
mfg_derived_policy = (
dynamic_routing_to_mean_field_game
.DerivedNPlayerPolicyFromMeanFieldPolicy(
n_player_game, policy.UniformRandomPolicy(mfg_game)))
derived_policy_value = expected_game_score.policy_value(
n_player_game.new_initial_state(), mfg_derived_policy)
uniform_policy_value = expected_game_score.policy_value(
n_player_game.new_initial_state(),
policy.UniformRandomPolicy(n_player_game))
self.assertSequenceAlmostEqual(derived_policy_value, uniform_policy_value)
def test_pigou_network_game_outcome_optimal_mfg_policy_in_n_player_game(self):
"""Test MFG Nash equilibrium policy for the Pigou network."""
# Test policy.
# Test game outcome.
def test_learning_and_applying_mfg_policy_in_n_player_game(self):
"""Test converting learnt MFG policy default game."""
# learning the Braess MFG Nash equilibrium
mfg_game = pyspiel.load_game("python_mfg_dynamic_routing")
omd = mirror_descent.MirrorDescent(mfg_game, lr=1)
for _ in range(10):
omd.iteration()
mfg_policy = omd.get_policy()
n_player_game = pyspiel.load_game("python_dynamic_routing")
mfg_derived_policy = (
dynamic_routing_to_mean_field_game
.DerivedNPlayerPolicyFromMeanFieldPolicy(n_player_game, mfg_policy))
expected_game_score.policy_value(n_player_game.new_initial_state(),
mfg_derived_policy)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/dynamic_routing_to_mean_field_game_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for iterated_prisoners_dilemma.py."""
from absl.testing import absltest
from open_spiel.python.games import iterated_prisoners_dilemma # pylint: disable=unused-import
import pyspiel
class IteratedPrisonersDilemmaTest(absltest.TestCase):
def test_default_param(self):
"""Check the game can be converted to a turn-based game."""
game = pyspiel.load_game("python_iterated_prisoners_dilemma")
self.assertEqual(game._termination_probability, 0.125)
def test_non_default_param_from_string(self):
"""Check params can be given through the string loading."""
game = pyspiel.load_game(
"python_iterated_prisoners_dilemma(termination_probability=0.5)")
self.assertEqual(game._termination_probability, 0.5)
def test_non_default_param_from_dict(self):
"""Check params can be given through a dictionary."""
game = pyspiel.load_game("python_iterated_prisoners_dilemma",
{"termination_probability": 0.75})
self.assertEqual(game._termination_probability, 0.75)
def test_game_as_turn_based(self):
"""Check the game can be converted to a turn-based game."""
game = pyspiel.load_game("python_iterated_prisoners_dilemma")
turn_based = pyspiel.convert_to_turn_based(game)
pyspiel.random_sim_test(
turn_based, num_sims=10, serialize=False, verbose=True)
def test_game_as_turn_based_via_string(self):
"""Check the game can be created as a turn-based game from a string."""
game = pyspiel.load_game(
"turn_based_simultaneous_game(game=python_iterated_prisoners_dilemma())"
)
pyspiel.random_sim_test(game, num_sims=10, serialize=False, verbose=True)
def test_game_from_cc(self):
"""Runs our standard game tests, checking API consistency."""
game = pyspiel.load_game("python_iterated_prisoners_dilemma")
pyspiel.random_sim_test(game, num_sims=10, serialize=False, verbose=True)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/python/games/iterated_prisoners_dilemma_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Default data for dynamic routing game."""
from open_spiel.python.games import dynamic_routing_utils
# The line network is a very simple network (O -> A -> D) with the goal of
# testing the routing game. There is no possible action and all cars will go
# from node O (being at node O means being on the link bef_O->O) to node D
# (being at node D means being on the link D->aft_D).
LINE_NETWORK = dynamic_routing_utils.Network({
"bef_O": "O",
"O": ["A"],
"A": ["D"],
"D": ["aft_D"],
"aft_D": []
})
LINE_NETWORK_VEHICLES_DEMAND = [
dynamic_routing_utils.Vehicle("bef_O->O", "D->aft_D") for _ in range(2)
]
LINE_NETWORK_OD_DEMAND = [
dynamic_routing_utils.OriginDestinationDemand("bef_O->O", "D->aft_D", 0,
100)
]
# The Braess network comes from the Braess paradox: Braess, D., 1968. "Uber ein
# Paradoxon aus der Verkehrsplanung". Unternehmensforschung 12, 258-268.
BRAESS_NUM_PLAYER = 5
BRAESS_NETWORK = dynamic_routing_utils.Network(
{
"O": "A",
"A": ["B", "C"],
"B": ["C", "D"],
"C": ["D"],
"D": ["E"],
"E": []
},
node_position={
"O": (0, 0),
"A": (1, 0),
"B": (2, 1),
"C": (2, -1),
"D": (3, 0),
"E": (4, 0)
},
bpr_a_coefficient={
"O->A": 0,
"A->B": 1.0,
"A->C": 0,
"B->C": 0,
"B->D": 0,
"C->D": 1.0,
"D->E": 0
},
bpr_b_coefficient={
"O->A": 1.0,
"A->B": 1.0,
"A->C": 1.0,
"B->C": 1.0,
"B->D": 1.0,
"C->D": 1.0,
"D->E": 1.0
},
capacity={
"O->A": BRAESS_NUM_PLAYER,
"A->B": BRAESS_NUM_PLAYER,
"A->C": BRAESS_NUM_PLAYER,
"B->C": BRAESS_NUM_PLAYER,
"B->D": BRAESS_NUM_PLAYER,
"C->D": BRAESS_NUM_PLAYER,
"D->E": BRAESS_NUM_PLAYER
},
free_flow_travel_time={
"O->A": 0,
"A->B": 1.0,
"A->C": 2.0,
"B->C": 0.25,
"B->D": 2.0,
"C->D": 1.0,
"D->E": 0
})
BRAESS_NETWORK_VEHICLES_DEMAND = [
dynamic_routing_utils.Vehicle("O->A", "D->E")
for _ in range(BRAESS_NUM_PLAYER)
]
BRAESS_NETWORK_OD_DEMAND = [
dynamic_routing_utils.OriginDestinationDemand("O->A", "D->E", 0,
BRAESS_NUM_PLAYER)
]
# The Sioux Falls data comes from "An Efficient Approach to Solving the Road
# Network Equilibrium Traffic Assignment Problem" by L. J. LeBlanc and E. K.
# Morlok (http://doi.org/10.1016/0041-1647(75)90030-1). We scale uniformly the
# data to decrease the number of time steps needed to cross the network. The
# demand and congestion functions data has been copied and pasted from the
# paper. The node position has been created from the paper's figure with a
# simple scale.
__SIOUX_FALLS_ADJACENCY = {
"1": ["2", "3"],
"2": ["1", "6"],
"3": ["1", "4", "12"],
"4": ["3", "5", "11"],
"5": ["4", "6", "9"],
"6": ["2", "5", "8"],
"7": ["8", "18"],
"8": ["6", "7", "9", "16"],
"9": ["5", "8", "10"],
"10": ["9", "11", "15", "16", "17"],
"11": ["4", "10", "12", "14"],
"12": ["3", "11", "13"],
"13": ["12", "24"],
"14": ["11", "15", "23"],
"15": ["10", "14", "19", "22"],
"16": ["8", "10", "17", "18"],
"17": ["10", "16", "19"],
"18": ["7", "16", "20"],
"19": ["15", "17", "20"],
"20": ["18", "19", "21", "22"],
"21": ["20", "22", "24"],
"22": ["15", "20", "21", "23"],
"23": ["14", "22", "24"],
"24": ["13", "21", "23"]
}
__SIOUX_FALLS_FREE_FLOW_TRAVEL_TIME = {
"1->2": 6, "1->3": 4, "2->1": 6, "2->6": 5, "3->1": 4, "3->4": 4,
"3->12": 4, "4->3": 4, "4->5": 2, "4->11": 6, "5->4": 2, "5->6": 4,
"5->9": 5, "6->2": 5, "6->5": 4, "6->8": 2, "7->8": 3, "7->18": 2,
"8->6": 2, "8->7": 3, "8->9": 10, "8->16": 5, "9->5": 5, "9->8": 10,
"9->10": 3, "10->9": 3, "10->11": 5, "10->15": 6, "10->16": 4, "10->17": 8,
"11->4": 6, "11->10": 5, "11->12": 6, "11->14": 4, "12->3": 4, "12->11": 6,
"12->13": 3, "13->12": 3, "13->24": 4, "14->11": 4, "14->15": 5,
"14->23": 4, "15->10": 6, "15->14": 5, "15->19": 3, "15->22": 3, "16->8": 5,
"16->10": 4, "16->17": 2, "16->18": 3, "17->10": 8, "17->16": 2,
"17->19": 2, "18->7": 2, "18->16": 3, "18->20": 4, "19->15": 3, "19->17": 2,
"19->20": 4, "20->18": 4, "20->19": 4, "20->21": 6, "20->22": 5,
"21->20": 6, "21->22": 2, "21->24": 3, "22->15": 3, "22->20": 5,
"22->21": 2, "22->23": 4, "23->14": 4, "23->22": 4, "23->24": 2,
"24->13": 4, "24->21": 3, "24->23": 2
}
__SIOUX_FALLS_BPR_A_COEFF = {
"1->2": 2 * 1e-18,
"1->3": 2 * 1e-18,
"2->1": 2 * 1e-18,
"2->6": 1240 * 1e-18,
"3->1": 2 * 1e-18,
"3->4": 6 * 1e-18,
"3->12": 2 * 1e-18,
"4->3": 6 * 1e-18,
"4->5": 3 * 1e-18,
"4->11": 1550 * 1e-18,
"5->4": 3 * 1e-18,
"5->6": 1000 * 1e-18,
"5->9": 75 * 1e-18,
"6->2": 1240 * 1e-18,
"6->5": 1000 * 1e-18,
"6->8": 520 * 1e-18,
"7->8": 119 * 1e-18,
"7->18": 1 * 1e-18,
"8->6": 520 * 1e-18,
"8->7": 119 * 1e-18,
"8->9": 2306 * 1e-18,
"8->16": 1156 * 1e-18,
"9->5": 75 * 1e-18,
"9->8": 2306 * 1e-18,
"9->10": 11 * 1e-18,
"10->9": 11 * 1e-18,
"10->11": 75 * 1e-18,
"10->15": 26 * 1e-18,
"10->16": 1080 * 1e-18,
"10->17": 1929 * 1e-18,
"11->4": 1550 * 1e-18,
"11->10": 75 * 1e-18,
"11->12": 1550 * 1e-18,
"11->14": 1061 * 1e-18,
"12->3": 2 * 1e-18,
"12->11": 1550 * 1e-18,
"12->13": 1 * 1e-18,
"13->12": 1 * 1e-18,
"13->24": 893 * 1e-18,
"14->11": 1061 * 1e-18,
"14->15": 1085 * 1e-18,
"14->23": 1020 * 1e-18,
"15->10": 26 * 1e-18,
"15->14": 1085 * 1e-18,
"15->19": 10 * 1e-18,
"15->22": 53 * 1e-18,
"16->8": 1156 * 1e-18,
"16->10": 1080 * 1e-18,
"16->17": 401 * 1e-18,
"16->18": 3 * 1e-18,
"17->10": 1929 * 1e-18,
"17->16": 401 * 1e-18,
"17->19": 553 * 1e-18,
"18->7": 1 * 1e-18,
"18->16": 3 * 1e-18,
"18->20": 2 * 1e-18,
"19->15": 10 * 1e-18,
"19->17": 553 * 1e-18,
"19->20": 957 * 1e-18,
"20->18": 2 * 1e-18,
"20->19": 957 * 1e-18,
"20->21": 1373 * 1e-18,
"20->22": 1130 * 1e-18,
"21->20": 1373 * 1e-18,
"21->22": 401 * 1e-18,
"21->24": 789 * 1e-18,
"22->15": 53 * 1e-18,
"22->20": 1130 * 1e-18,
"22->21": 401 * 1e-18,
"22->23": 960 * 1e-18,
"23->14": 1020 * 1e-18,
"23->22": 960 * 1e-18,
"23->24": 451 * 1e-18,
"24->13": 893 * 1e-18,
"24->21": 789 * 1e-18,
"24->23": 451 * 1e-18,
}
__SIOUX_FALLS_NODES = {
"1": (0, 9), "2": (5, 9), "3": (0, 8), "4": (1, 8), "5": (3, 8),
"6": (5, 8), "7": (7, 6), "8": (5, 6), "9": (3, 6), "10": (3, 5),
"11": (1, 5), "12": (0, 5), "13": (0, 0), "14": (1, 2), "15": (3, 2),
"16": (5, 5), "17": (5, 4), "18": (7, 5), "19": (5, 2), "20": (5, 0),
"21": (3, 0), "22": (3, 1), "23": (1, 1), "24": (1, 0)
}
__SIOUX_FALLS_DEMAND_AUX = [
("2", "1", 1), ("3", "1", 1), ("4", "1", 5), ("5", "1", 2),
("6", "1", 3), ("7", "1", 5), ("8", "1", 8), ("9", "1", 5),
("10", "1", 13), ("11", "1", 5), ("12", "1", 2), ("13", "1", 5),
("14", "1", 3), ("15", "1", 5), ("16", "1", 5), ("17", "1", 4),
("18", "1", 1), ("19", "1", 3), ("20", "1", 3), ("21", "1", 1),
("22", "1", 4), ("23", "1", 3), ("24", "1", 1), ("1", "2", 1),
("3", "2", 1), ("4", "2", 2), ("5", "2", 1), ("6", "2", 4),
("7", "2", 2), ("8", "2", 4), ("9", "2", 2), ("10", "2", 6),
("11", "2", 2), ("12", "2", 1), ("13", "2", 3), ("14", "2", 1),
("15", "2", 1), ("16", "2", 4), ("17", "2", 2), ("19", "2", 1),
("20", "2", 1), ("22", "2", 1), ("1", "3", 1), ("2", "3", 1),
("4", "3", 2), ("5", "3", 1), ("6", "3", 3), ("7", "3", 1),
("8", "3", 2), ("9", "3", 1), ("10", "3", 3), ("11", "3", 3),
("12", "3", 2), ("13", "3", 1), ("14", "3", 1), ("15", "3", 1),
("16", "3", 2), ("17", "3", 1), ("22", "3", 1), ("23", "3", 1),
("1", "4", 5), ("2", "4", 2), ("3", "4", 2), ("5", "4", 5),
("6", "4", 4), ("7", "4", 4), ("8", "4", 7), ("9", "4", 7),
("10", "4", 12), ("11", "4", 14), ("12", "4", 6), ("13", "4", 6),
("14", "4", 5), ("15", "4", 5), ("16", "4", 8), ("17", "4", 5),
("18", "4", 1), ("19", "4", 2), ("20", "4", 3), ("21", "4", 2),
("22", "4", 4), ("23", "4", 5), ("24", "4", 2), ("1", "5", 2),
("2", "5", 1), ("3", "5", 1), ("4", "5", 5), ("6", "5", 2),
("7", "5", 2), ("8", "5", 5), ("9", "5", 8), ("10", "5", 10),
("11", "5", 5), ("12", "5", 2), ("13", "5", 2), ("14", "5", 1),
("15", "5", 2), ("16", "5", 5), ("17", "5", 2), ("19", "5", 1),
("20", "5", 1), ("21", "5", 1), ("22", "5", 2), ("23", "5", 1),
("1", "6", 3), ("2", "6", 4), ("3", "6", 3), ("4", "6", 4),
("5", "6", 2), ("7", "6", 4), ("8", "6", 8), ("9", "6", 4),
("10", "6", 8), ("11", "6", 4), ("12", "6", 2), ("13", "6", 2),
("14", "6", 1), ("15", "6", 2), ("16", "6", 9), ("17", "6", 5),
("18", "6", 1), ("19", "6", 2), ("20", "6", 3), ("21", "6", 1),
("22", "6", 2), ("23", "6", 1), ("24", "6", 1), ("1", "7", 5),
("2", "7", 2), ("3", "7", 1), ("4", "7", 4), ("5", "7", 2),
("6", "7", 4), ("8", "7", 10), ("9", "7", 6), ("10", "7", 19),
("11", "7", 5), ("12", "7", 7), ("13", "7", 4), ("14", "7", 2),
("15", "7", 5), ("16", "7", 14), ("17", "7", 10), ("18", "7", 2),
("19", "7", 4), ("20", "7", 5), ("21", "7", 2), ("22", "7", 5),
("23", "7", 2), ("24", "7", 1), ("1", "8", 8), ("2", "8", 4),
("3", "8", 2), ("4", "8", 7), ("5", "8", 5), ("6", "8", 8),
("7", "8", 10), ("9", "8", 8), ("10", "8", 16), ("11", "8", 8),
("12", "8", 6), ("13", "8", 6), ("14", "8", 4), ("15", "8", 6),
("16", "8", 22), ("17", "8", 14), ("18", "8", 3), ("19", "8", 7),
("20", "8", 9), ("21", "8", 4), ("22", "8", 5), ("23", "8", 3),
("24", "8", 2), ("1", "9", 5), ("2", "9", 2), ("3", "9", 1),
("4", "9", 7), ("5", "9", 8), ("6", "9", 4), ("7", "9", 6),
("8", "9", 8), ("10", "9", 28), ("11", "9", 14), ("12", "9", 6),
("13", "9", 6), ("14", "9", 6), ("15", "9", 9), ("16", "9", 14),
("17", "9", 9), ("18", "9", 2), ("19", "9", 4), ("20", "9", 6),
("21", "9", 3), ("22", "9", 7), ("23", "9", 5), ("24", "9", 2),
("1", "10", 13), ("2", "10", 6), ("3", "10", 3), ("4", "10", 12),
("5", "10", 10), ("6", "10", 8), ("7", "10", 19), ("8", "10", 16),
("9", "10", 28), ("11", "10", 40), ("12", "10", 20), ("13", "10", 19),
("14", "10", 21), ("15", "10", 40), ("16", "10", 44), ("17", "10", 39),
("18", "10", 7), ("19", "10", 18), ("20", "10", 25), ("21", "10", 12),
("22", "10", 26), ("23", "10", 18), ("24", "10", 8), ("1", "11", 5),
("2", "11", 2), ("3", "11", 3), ("4", "11", 15), ("5", "11", 5),
("6", "11", 4), ("7", "11", 5), ("8", "11", 8), ("9", "11", 14),
("10", "11", 39), ("12", "11", 14), ("13", "11", 10), ("14", "11", 16),
("15", "11", 14), ("16", "11", 14), ("17", "11", 10), ("18", "11", 1),
("19", "11", 4), ("20", "11", 6), ("21", "11", 4), ("22", "11", 11),
("23", "11", 13), ("24", "11", 6), ("1", "12", 2), ("2", "12", 1),
("3", "12", 2), ("4", "12", 6), ("5", "12", 2), ("6", "12", 2),
("7", "12", 7), ("8", "12", 6), ("9", "12", 6), ("10", "12", 20),
("11", "12", 14), ("13", "12", 13), ("14", "12", 7), ("15", "12", 7),
("16", "12", 7), ("17", "12", 6), ("18", "12", 2), ("19", "12", 3),
("20", "12", 4), ("21", "12", 3), ("22", "12", 7), ("23", "12", 7),
("24", "12", 5), ("1", "13", 5), ("2", "13", 3), ("3", "13", 1),
("4", "13", 6), ("5", "13", 2), ("6", "13", 2), ("7", "13", 4),
("8", "13", 6), ("9", "13", 6), ("10", "13", 19), ("11", "13", 10),
("12", "13", 13), ("14", "13", 6), ("15", "13", 7), ("16", "13", 6),
("17", "13", 5), ("18", "13", 1), ("19", "13", 3), ("20", "13", 6),
("21", "13", 6), ("22", "13", 13), ("23", "13", 8), ("24", "13", 8),
("1", "14", 3), ("2", "14", 1), ("3", "14", 1), ("4", "14", 5),
("5", "14", 1), ("6", "14", 1), ("7", "14", 2), ("8", "14", 4),
("9", "14", 6), ("10", "14", 21), ("11", "14", 16), ("12", "14", 7),
("13", "14", 6), ("15", "14", 13), ("16", "14", 7), ("17", "14", 7),
("18", "14", 1), ("19", "14", 3), ("20", "14", 5), ("21", "14", 4),
("22", "14", 12), ("23", "14", 11), ("24", "14", 4), ("1", "15", 5),
("2", "15", 1), ("3", "15", 1), ("4", "15", 5), ("5", "15", 2),
("6", "15", 2), ("7", "15", 5), ("8", "15", 6), ("9", "15", 10),
("10", "15", 40), ("11", "15", 14), ("12", "15", 7), ("13", "15", 7),
("14", "15", 13), ("16", "15", 12), ("17", "15", 15), ("18", "15", 2),
("19", "15", 8), ("20", "15", 11), ("21", "15", 8), ("22", "15", 26),
("23", "15", 10), ("24", "15", 4), ("1", "16", 5), ("2", "16", 4),
("3", "16", 2), ("4", "16", 8), ("5", "16", 5), ("6", "16", 9),
("7", "16", 14), ("8", "16", 22), ("9", "16", 14), ("10", "16", 44),
("11", "16", 14), ("12", "16", 7), ("13", "16", 6), ("14", "16", 7),
("15", "16", 12), ("17", "16", 28), ("18", "16", 5), ("19", "16", 13),
("20", "16", 16), ("21", "16", 6), ("22", "16", 12), ("23", "16", 5),
("24", "16", 3), ("1", "17", 4), ("2", "17", 2), ("3", "17", 1),
("4", "17", 5), ("5", "17", 2), ("6", "17", 5), ("7", "17", 10),
("8", "17", 14), ("9", "17", 9), ("10", "17", 39), ("11", "17", 10),
("12", "17", 6), ("13", "17", 5), ("14", "17", 7), ("15", "17", 15),
("16", "17", 28), ("18", "17", 6), ("19", "17", 17), ("20", "17", 17),
("21", "17", 6), ("22", "17", 17), ("23", "17", 6), ("24", "17", 3),
("1", "18", 1), ("4", "18", 1), ("6", "18", 1), ("7", "18", 2),
("8", "18", 3), ("9", "18", 2), ("10", "18", 7), ("11", "18", 2),
("12", "18", 2), ("13", "18", 1), ("14", "18", 1), ("15", "18", 2),
("16", "18", 5), ("17", "18", 6), ("19", "18", 3), ("20", "18", 4),
("21", "18", 1), ("22", "18", 3), ("23", "18", 1), ("1", "19", 3),
("2", "19", 1), ("4", "19", 2), ("5", "19", 1), ("6", "19", 2),
("7", "19", 4), ("8", "19", 7), ("9", "19", 4), ("10", "19", 18),
("11", "19", 4), ("12", "19", 3), ("13", "19", 3), ("14", "19", 3),
("15", "19", 8), ("16", "19", 13), ("17", "19", 17), ("18", "19", 3),
("20", "19", 12), ("21", "19", 4), ("22", "19", 12), ("23", "19", 3),
("24", "19", 1), ("1", "20", 3), ("2", "20", 1), ("4", "20", 3),
("5", "20", 1), ("6", "20", 3), ("7", "20", 5), ("8", "20", 9),
("9", "20", 6), ("10", "20", 25), ("11", "20", 6), ("12", "20", 5),
("13", "20", 6), ("14", "20", 5), ("15", "20", 11), ("16", "20", 16),
("17", "20", 17), ("18", "20", 4), ("19", "20", 12), ("21", "20", 12),
("22", "20", 24), ("23", "20", 7), ("24", "20", 4), ("1", "21", 1),
("4", "21", 2), ("5", "21", 1), ("6", "21", 1), ("7", "21", 2),
("8", "21", 4), ("9", "21", 3), ("10", "21", 12), ("11", "21", 4),
("12", "21", 3), ("13", "21", 6), ("14", "21", 4), ("15", "21", 8),
("16", "21", 6), ("17", "21", 6), ("18", "21", 1), ("19", "21", 4),
("20", "21", 12), ("22", "21", 18), ("23", "21", 7), ("24", "21", 5),
("1", "22", 4), ("2", "22", 1), ("3", "22", 1), ("4", "22", 4),
("5", "22", 2), ("6", "22", 2), ("7", "22", 5), ("8", "22", 5),
("9", "22", 7), ("10", "22", 26), ("11", "22", 11), ("12", "22", 7),
("13", "22", 13), ("14", "22", 12), ("15", "22", 26), ("16", "22", 12),
("17", "22", 17), ("18", "22", 3), ("19", "22", 12), ("20", "22", 24),
("21", "22", 18), ("23", "22", 21), ("24", "22", 11), ("1", "23", 3),
("3", "23", 1), ("4", "23", 5), ("5", "23", 1), ("6", "23", 1),
("7", "23", 2), ("8", "23", 3), ("9", "23", 5), ("10", "23", 18),
("11", "23", 13), ("12", "23", 7), ("13", "23", 8), ("14", "23", 11),
("15", "23", 10), ("16", "23", 5), ("17", "23", 6), ("18", "23", 1),
("19", "23", 3), ("20", "23", 7), ("21", "23", 7), ("22", "23", 21),
("24", "23", 7), ("1", "24", 1), ("4", "24", 2), ("6", "24", 1),
("7", "24", 1), ("8", "24", 2), ("9", "24", 2), ("10", "24", 8),
("11", "24", 6), ("12", "24", 5), ("13", "24", 7), ("14", "24", 4),
("15", "24", 4), ("16", "24", 3), ("17", "24", 3), ("19", "24", 1),
("20", "24", 4), ("21", "24", 5), ("22", "24", 11), ("23", "24", 7)
]
def create_sioux_falls_network():
"""Returns Sioux Falls network object (Network).
Adds the origin and destination link to the adjacency list
__SIOUX_FALLS_ADJACENCY, to the BPR coefficients
__SIOUX_FALLS_FREE_FLOW_TRAVEL_TIME and __SIOUX_FALLS_BPR_A_COEFF and to the
node positions __SIOUX_FALLS_NODES and returns the network.
The BPR (Burean of Public Roads) coefficients are the coefficients used to
compute the travel time as a function of the volume on each link.
"""
adjacency = {}
free_flow_travel_time = __SIOUX_FALLS_FREE_FLOW_TRAVEL_TIME.copy()
bpr_a_coeff = __SIOUX_FALLS_BPR_A_COEFF.copy()
node_position = {}
for k, nodes in __SIOUX_FALLS_ADJACENCY.items():
adjacency[k] = nodes + [f"aft_{k}"]
adjacency[f"bef_{k}"] = [k]
adjacency[f"aft_{k}"] = []
free_flow_travel_time[f"bef_{k}->{k}"] = 0
free_flow_travel_time[f"{k}->aft_{k}"] = 0
bpr_a_coeff[f"bef_{k}->{k}"] = 0
bpr_a_coeff[f"{k}->aft_{k}"] = 0
for node, coord in __SIOUX_FALLS_NODES.items():
node_position[node] = coord
node_position[f"bef_{node}"] = coord
node_position[f"aft_{node}"] = coord
return dynamic_routing_utils.Network(
adjacency,
node_position=node_position,
bpr_a_coefficient=bpr_a_coeff,
bpr_b_coefficient={k: 4 for k in bpr_a_coeff},
capacity={k: 1 for k in bpr_a_coeff},
free_flow_travel_time=free_flow_travel_time)
SIOUX_FALLS_NETWORK = create_sioux_falls_network()
SIOUX_FALLS_OD_DEMAND = [
dynamic_routing_utils.OriginDestinationDemand(
f"bef_{origin}->{origin}", f"{dest}->aft_{dest}", 0, count * 1e2)
for (origin, dest, count) in __SIOUX_FALLS_DEMAND_AUX]
SIOUX_FALLS_DUMMY_OD_DEMAND = [
dynamic_routing_utils.OriginDestinationDemand("bef_19->19", "1->aft_1", 0,
70 * 1e2),
dynamic_routing_utils.OriginDestinationDemand("bef_1->1", "19->aft_19", 0,
70 * 1e2)
]
| open_spiel-master | open_spiel/python/games/dynamic_routing_data.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Numerical information about some games or some specific settings of games.
TODO(author2): Ideally, this should also be available from C++.
"""
import pyspiel
def kuhn_nash_equilibrium(alpha):
"""Returns a Nash Equilibrium in Kuhn parameterized by alpha in [0, 1/3].
See https://en.wikipedia.org/wiki/Kuhn_poker#Optimal_strategy
Args:
alpha: The probability to bet on a Jack for Player 0.
Raises:
ValueError: If `alpha` is not within [0, 1/3].
"""
if not 0 <= alpha <= 1 / 3:
raise ValueError("alpha ({}) must be in [0, 1/3]".format(alpha))
return pyspiel.kuhn_poker.get_optimal_policy(alpha)
| open_spiel-master | open_spiel/python/games/data.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Tic tac toe (noughts and crosses), implemented in Python.
This is a demonstration of implementing a deterministic perfect-information
game in Python.
Python games are significantly slower than C++, but it may still be suitable
for prototyping or for small games.
It is possible to run C++ algorithms on Python-implemented games. This is likely
to have good performance if the algorithm simply extracts a game tree and then
works with that (e.g. CFR algorithms). It is likely to be poor if the algorithm
relies on processing and updating states as it goes, e.g., MCTS.
"""
import numpy as np
from open_spiel.python.observation import IIGObserverForPublicInfoGame
import pyspiel
_NUM_PLAYERS = 2
_NUM_ROWS = 3
_NUM_COLS = 3
_NUM_CELLS = _NUM_ROWS * _NUM_COLS
_GAME_TYPE = pyspiel.GameType(
short_name="python_tic_tac_toe",
long_name="Python Tic-Tac-Toe",
dynamics=pyspiel.GameType.Dynamics.SEQUENTIAL,
chance_mode=pyspiel.GameType.ChanceMode.DETERMINISTIC,
information=pyspiel.GameType.Information.PERFECT_INFORMATION,
utility=pyspiel.GameType.Utility.ZERO_SUM,
reward_model=pyspiel.GameType.RewardModel.TERMINAL,
max_num_players=_NUM_PLAYERS,
min_num_players=_NUM_PLAYERS,
provides_information_state_string=True,
provides_information_state_tensor=False,
provides_observation_string=True,
provides_observation_tensor=True,
parameter_specification={})
_GAME_INFO = pyspiel.GameInfo(
num_distinct_actions=_NUM_CELLS,
max_chance_outcomes=0,
num_players=2,
min_utility=-1.0,
max_utility=1.0,
utility_sum=0.0,
max_game_length=_NUM_CELLS)
class TicTacToeGame(pyspiel.Game):
"""A Python version of the Tic-Tac-Toe game."""
def __init__(self, params=None):
super().__init__(_GAME_TYPE, _GAME_INFO, params or dict())
def new_initial_state(self):
"""Returns a state corresponding to the start of a game."""
return TicTacToeState(self)
def make_py_observer(self, iig_obs_type=None, params=None):
"""Returns an object used for observing game state."""
if ((iig_obs_type is None) or
(iig_obs_type.public_info and not iig_obs_type.perfect_recall)):
return BoardObserver(params)
else:
return IIGObserverForPublicInfoGame(iig_obs_type, params)
class TicTacToeState(pyspiel.State):
"""A python version of the Tic-Tac-Toe state."""
def __init__(self, game):
"""Constructor; should only be called by Game.new_initial_state."""
super().__init__(game)
self._cur_player = 0
self._player0_score = 0.0
self._is_terminal = False
self.board = np.full((_NUM_ROWS, _NUM_COLS), ".")
# OpenSpiel (PySpiel) API functions are below. This is the standard set that
# should be implemented by every perfect-information sequential-move game.
def current_player(self):
"""Returns id of the next player to move, or TERMINAL if game is over."""
return pyspiel.PlayerId.TERMINAL if self._is_terminal else self._cur_player
def _legal_actions(self, player):
"""Returns a list of legal actions, sorted in ascending order."""
return [a for a in range(_NUM_CELLS) if self.board[_coord(a)] == "."]
def _apply_action(self, action):
"""Applies the specified action to the state."""
self.board[_coord(action)] = "x" if self._cur_player == 0 else "o"
if _line_exists(self.board):
self._is_terminal = True
self._player0_score = 1.0 if self._cur_player == 0 else -1.0
elif all(self.board.ravel() != "."):
self._is_terminal = True
else:
self._cur_player = 1 - self._cur_player
def _action_to_string(self, player, action):
"""Action -> string."""
row, col = _coord(action)
return "{}({},{})".format("x" if player == 0 else "o", row, col)
def is_terminal(self):
"""Returns True if the game is over."""
return self._is_terminal
def returns(self):
"""Total reward for each player over the course of the game so far."""
return [self._player0_score, -self._player0_score]
def __str__(self):
"""String for debug purposes. No particular semantics are required."""
return _board_to_string(self.board)
class BoardObserver:
"""Observer, conforming to the PyObserver interface (see observation.py)."""
def __init__(self, params):
"""Initializes an empty observation tensor."""
if params:
raise ValueError(f"Observation parameters not supported; passed {params}")
# The observation should contain a 1-D tensor in `self.tensor` and a
# dictionary of views onto the tensor, which may be of any shape.
# Here the observation is indexed `(cell state, row, column)`.
shape = (1 + _NUM_PLAYERS, _NUM_ROWS, _NUM_COLS)
self.tensor = np.zeros(np.prod(shape), np.float32)
self.dict = {"observation": np.reshape(self.tensor, shape)}
def set_from(self, state, player):
"""Updates `tensor` and `dict` to reflect `state` from PoV of `player`."""
del player
# We update the observation via the shaped tensor since indexing is more
# convenient than with the 1-D tensor. Both are views onto the same memory.
obs = self.dict["observation"]
obs.fill(0)
for row in range(_NUM_ROWS):
for col in range(_NUM_COLS):
cell_state = ".ox".index(state.board[row, col])
obs[cell_state, row, col] = 1
def string_from(self, state, player):
"""Observation of `state` from the PoV of `player`, as a string."""
del player
return _board_to_string(state.board)
# Helper functions for game details.
def _line_value(line):
"""Checks a possible line, returning the winning symbol if any."""
if all(line == "x") or all(line == "o"):
return line[0]
def _line_exists(board):
"""Checks if a line exists, returns "x" or "o" if so, and None otherwise."""
return (_line_value(board[0]) or _line_value(board[1]) or
_line_value(board[2]) or _line_value(board[:, 0]) or
_line_value(board[:, 1]) or _line_value(board[:, 2]) or
_line_value(board.diagonal()) or
_line_value(np.fliplr(board).diagonal()))
def _coord(move):
"""Returns (row, col) from an action id."""
return (move // _NUM_COLS, move % _NUM_COLS)
def _board_to_string(board):
"""Returns a string representation of the board."""
return "\n".join("".join(row) for row in board)
# Register the game with the OpenSpiel library
pyspiel.register_game(_GAME_TYPE, TicTacToeGame)
| open_spiel-master | open_spiel/python/games/tic_tac_toe.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Re-run playthroughs and check for differences."""
import os
import re
from absl import logging
from absl.testing import absltest
from open_spiel.python.algorithms import generate_playthrough
import pyspiel
_DATA_DIR = "open_spiel/integration_tests/playthroughs/"
_OPTIONAL_GAMES = frozenset(["hanabi", "universal_poker"])
_AVAILABLE_GAMES = set(pyspiel.registered_names())
# Games for which we do not have playthroughs. Please don't add new games
# here if you can avoid it. Adding a playthrough is easy and very useful!
# Run `generate_new_playthrough.sh $GAME` to add a playthrough.
_MISSING_GAMES = set(["nfg_game", "efg_game", "restricted_nash_response"])
# Regex to find the game name in a playthrough. This will return the name of the
# transform for wrapped games, e.g. goofspiel --> turn_based_simultaneous_game
_SHORTNAME = r'^GameType\.short_name = "(.*)"$'
def _is_optional_game(basename):
"""Returns (bool, game_name or None).
Args:
basename: The basename of the file. It is assumed it starts with the game
name.
"""
for game_name in _OPTIONAL_GAMES:
if basename.startswith(game_name):
return True, game_name
return False, None
def _playthrough_match(filename, regex):
"""Returns the specified value fromm the playthrough."""
with open(filename, "r", encoding="utf-8") as f:
data = f.read()
return re.search(regex, data, re.MULTILINE)
class PlaythroughTest(absltest.TestCase):
def run_test(self, path, basename):
"""Instantiated for each test case in main, below."""
# We check whether the game is optional, and if it is, whether we do
# have the game.
is_optional, game_name = _is_optional_game(basename)
if is_optional:
if game_name not in _AVAILABLE_GAMES:
logging.info("Skipping %s because %s is not built in.", basename,
game_name)
return
file_path = os.path.join(path, basename)
expected, actual = generate_playthrough.replay(file_path)
for line_num, (expected_line, actual_line) in enumerate(
zip(expected.split("\n"), actual.split("\n"))):
self.assertEqual(
expected_line,
actual_line,
msg="Wrong line {} in {}".format(line_num, basename))
self.assertMultiLineEqual(expected, actual)
def test_all_games_tested(self):
"""Verify that every game is present in the playthroughs."""
test_srcdir = os.environ.get("TEST_SRCDIR", "")
path = os.path.join(test_srcdir, _DATA_DIR)
basenames = set(os.listdir(path))
missing_games = set(_AVAILABLE_GAMES) - set(_MISSING_GAMES) - set(
_playthrough_match(os.path.join(path, basename), _SHORTNAME)[1]
for basename in basenames)
self.assertEmpty(
missing_games,
msg="These games do not have playthroughs."
"Create playthroughs using generate_new_playthrough.sh")
def _add_tests():
"""Adds a test for each playthrough to the test class (above)."""
test_srcdir = os.environ.get("TEST_SRCDIR", "")
path = os.path.join(test_srcdir, _DATA_DIR)
basenames = sorted(os.listdir(path))
if len(basenames) < 40:
raise ValueError(f"Playthroughs are missing from {path}")
for basename in basenames:
test_name = f"test_playthrough_{basename}"
test_func = lambda self, basename=basename: self.run_test(path, basename)
test_func.__name__ = test_name
setattr(PlaythroughTest, test_name, test_func)
if __name__ == "__main__":
_add_tests()
absltest.main()
| open_spiel-master | open_spiel/integration_tests/playthrough_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| open_spiel-master | open_spiel/integration_tests/__init__.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for open_spiel.integration_tests.api."""
import enum
import re
import unittest
from absl import app
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from open_spiel.python import games # pylint:disable=unused-import
from open_spiel.python.algorithms import get_all_states
from open_spiel.python.algorithms import sample_some_states
from open_spiel.python.mfg import games as mfg_games # pylint:disable=unused-import
from open_spiel.python.observation import make_observation
import pyspiel
FLAGS = flags.FLAGS
flags.DEFINE_string("test_only_games", ".*",
"Test only selected games (regex). Defaults to all.")
_ALL_GAMES = pyspiel.registered_games()
_GAMES_TO_TEST = set([g.short_name for g in _ALL_GAMES if g.default_loadable])
_GAMES_NOT_UNDER_TEST = [
g.short_name for g in _ALL_GAMES if not g.default_loadable
]
_GAMES_TO_OMIT_LEGAL_ACTIONS_CHECK = set(["bridge_uncontested_bidding"])
# The list of game instances to test on the full tree as tuples
# (name to display, string to pass to load_game).
_GAMES_FULL_TREE_TRAVERSAL_TESTS = [
("cliff_walking", "cliff_walking(horizon=7)"),
("kuhn_poker", "kuhn_poker"),
("leduc_poker", "leduc_poker"),
("iigoofspiel4", ("turn_based_simultaneous_game(game=goofspiel("
"imp_info=True,num_cards=4,points_order=descending))")),
("kuhn_poker3p", "kuhn_poker(players=3)"),
("first_sealed_auction", "first_sealed_auction(max_value=2)"),
("tiny_hanabi", "tiny_hanabi"),
("nf_auction", ("turn_based_simultaneous_game(game="
"normal_form_extensive_game(game="
"first_sealed_auction(max_value=3)))")),
# Disabled by default - big games, slow tests.
# Uncomment to check the games if you modify them.
# ("liars_dice", "liars_dice"),
# ("tiny_bridge_2p", "tiny_bridge_2p"),
]
_GAMES_FULL_TREE_TRAVERSAL_TESTS_NAMES = [
g[1] for g in _GAMES_FULL_TREE_TRAVERSAL_TESTS
]
TOTAL_NUM_STATES = {
# This maps the game name to (chance, playable, terminal)
"cliff_walking": (0, 2119, 6358),
"kuhn_poker": (4, 24, 30),
"leduc_poker": (157, 3780, 5520),
"liars_dice": (7, 147456, 147420),
"iigoofspiel4": (0, 501, 576),
"kuhn_poker3p": (17, 288, 312),
"first_sealed_auction": (12, 10, 14),
"tiny_bridge_2p": (29, 53760, 53340),
"tiny_hanabi": (3, 16, 36),
"nf_auction": (0, 7, 36),
}
# This is kept to ensure non-regression, but we would like to remove that
# when we can interpret what are these numbers.
PERFECT_RECALL_NUM_STATES = {
"cliff_walking": 2119,
"kuhn_poker": 12,
"leduc_poker": 936,
"liars_dice": 24576,
"iigoofspiel4": 162,
"kuhn_poker3p": 48,
"first_sealed_auction": 4,
"tiny_bridge_2p": 3584,
"tiny_hanabi": 8,
"nf_auction": 2,
}
class EnforceAPIOnFullTreeBase(parameterized.TestCase):
"""Test properties on the full game tree, instantiating the tree only once.
A new class, extensing this class will be dynamically created and added as
a unittest class for the games we want to test exhaustively.
"""
@classmethod
def setUpClass(cls):
super(EnforceAPIOnFullTreeBase, cls).setUpClass()
cls.all_states = set(
get_all_states.get_all_states(
cls.game,
depth_limit=-1,
include_terminals=True,
include_chance_states=True).values())
def test_legal_actions_empty(self):
# We check we have some non-terminal non-random states
self.assertTrue(
any(not s.is_terminal() and not s.is_chance_node()
for s in self.all_states))
for state in self.all_states:
if state.is_terminal():
# Empty on terminal
msg = ("The game %s does not return an empty list on "
"legal_actions() for state %s" % (self.game_name, str(state)))
self.assertEmpty(state.legal_actions(), msg=msg)
for player in range(self.game.num_players()):
msg = ("The game %s does not return an empty list on "
"legal_actions(%i) for state %s" %
(self.game_name, player, str(state)))
self.assertEmpty(state.legal_actions(player), msg=msg)
elif state.is_simultaneous_node():
# No requirement for legal_actions to be empty, since all players act.
pass
elif state.is_chance_node():
# Would be an error to request legal actions for a non-chance player.
pass
else:
# Empty for players other than the current player
current_player = state.current_player()
for player in range(self.game.num_players()):
if player != current_player:
msg = ("The game {!r} does not return an empty list on "
"legal_actions(<not current player>) in state {}".format(
self.game_name, state))
self.assertEmpty(state.legal_actions(player), msg=msg)
def test_number_of_nodes(self):
expected_numbers = TOTAL_NUM_STATES[self.game_name]
num_chance_nodes = 0
num_terminals = 0
num_playable = 0
for state in self.all_states:
if state.is_terminal():
num_terminals += 1
elif state.is_chance_node():
num_chance_nodes += 1
else:
num_playable += 1
self.assertEqual(expected_numbers,
(num_chance_nodes, num_playable, num_terminals))
def test_current_player_returns_terminal_player_on_terminal_nodes(self):
for state in self.all_states:
if state.is_terminal():
self.assertEqual(pyspiel.PlayerId.TERMINAL, state.current_player())
def test_information_state_no_argument_raises_on_terminal_nodes(self):
for state in self.all_states:
if state.is_terminal():
with self.assertRaises(RuntimeError):
state.information_state_string()
def test_game_is_perfect_recall(self):
# We do not count the terminal nodes here.
expected_number_states = PERFECT_RECALL_NUM_STATES[self.game_name]
all_states = []
for _ in range(3):
infostate_player_to_history = _assert_is_perfect_recall(self.game)
all_states.append(infostate_player_to_history)
# We compare the total number of (infostate, player) touched, to prevent
# any regression (we skip chance nodes).
# We use assertEqual and not assertLen to prevent the huge dict to be
# displayed
self.assertEqual(expected_number_states, len(infostate_player_to_history)) # pylint: disable=g-generic-assert
def test_constant_sum(self):
game_type = self.game.get_type()
terminal_values = {
tuple(state.returns())
for state in self.all_states
if state.is_terminal()
}
if game_type.utility in (pyspiel.GameType.Utility.ZERO_SUM,
pyspiel.GameType.Utility.CONSTANT_SUM):
expected_sum = self.game.utility_sum()
for returns in terminal_values:
self.assertEqual(sum(returns), expected_sum)
elif game_type.utility == pyspiel.GameType.Utility.GENERAL_SUM:
all_sums = {sum(returns) for returns in terminal_values}
self.assertNotEqual(len(all_sums), 1)
elif game_type.utility == pyspiel.GameType.Utility.IDENTICAL:
for returns in terminal_values:
self.assertLen(set(returns), 1)
else:
raise AssertionError("Invalid utility type {}".format(game_type.utility))
def test_information_state_functions_raises_on_chance_nodes(self):
def _assert_information_state_on_chance_nodes_raises(state):
if state.is_chance_node():
with self.assertRaises(RuntimeError):
state.information_state_string()
with self.assertRaises(RuntimeError):
state.information_state_tensor()
for state in self.all_states:
_assert_information_state_on_chance_nodes_raises(state)
def test_current_player_infosets_no_overlap_between_players(self):
# This is the stronger property we can currently verify. In particular,
# we can find some state h0 where player 0 plays such that:
# h0.information_state_string(0) == h0.information_state_string(0).
states_for_player = [set() for _ in range(self.game.num_players())]
for state in self.all_states:
if not state.is_chance_node() and not state.is_terminal():
states_for_player[state.current_player()].add(state)
elif state.is_chance_node():
self.assertEqual(state.get_type(), pyspiel.StateType.CHANCE)
else:
self.assertEqual(state.get_type(), pyspiel.StateType.TERMINAL)
infoset_functions = [lambda s, player: s.information_state_string(player)]
def _information_state_tensor(state, player):
return tuple(np.asarray(state.information_state_tensor(player)).flatten())
infoset_functions.append(_information_state_tensor)
for infoset_function in infoset_functions:
information_sets_per_player = []
for player in range(self.game.num_players()):
set_l = set(
infoset_function(s, player) for s in states_for_player[player])
information_sets_per_player.append(set_l)
union = set()
for information_set in information_sets_per_player:
union = union.union(information_set)
self.assertLen(union, sum([len(x) for x in information_sets_per_player]))
class Relation(enum.Enum):
SUBSET_OR_EQUALS = 1
EQUALS = 2
class EnforceAPIOnPartialTreeBase(parameterized.TestCase):
"""This only partially test some properties."""
@classmethod
def setUpClass(cls):
super(EnforceAPIOnPartialTreeBase, cls).setUpClass()
cls.some_states = sample_some_states.sample_some_states(
cls.game, max_states=400)
cls.game_type = cls.game.get_type()
def test_sequence_lengths(self):
try:
max_history_len = self.game.max_history_length()
max_move_number = self.game.max_move_number()
max_chance_nodes_in_history = self.game.max_chance_nodes_in_history()
except RuntimeError:
return # The function is likely not implemented, so skip the test.
self.assertGreater(max_history_len, 0)
self.assertGreater(max_move_number, 0)
if self.game_type.chance_mode == pyspiel.GameType.ChanceMode.DETERMINISTIC:
self.assertEqual(max_chance_nodes_in_history, 0)
else:
self.assertGreater(max_chance_nodes_in_history, 0)
for state in self.some_states:
self.assertLessEqual(len(state.full_history()), max_history_len)
self.assertLessEqual(state.move_number(), max_move_number)
chance_nodes_in_history = 0
for item in state.full_history():
if item.player == pyspiel.PlayerId.CHANCE:
chance_nodes_in_history += 1
self.assertLessEqual(chance_nodes_in_history, max_chance_nodes_in_history)
def test_observations_raises_error_on_invalid_player(self):
game = self.game
game_type = self.game_type
game_name = self.game_name
num_players = game.num_players()
for state in self.some_states:
if game_type.provides_information_state_string:
if not state.is_chance_node():
for p in range(num_players):
state.information_state_string(p)
msg = f"information_state_string did not raise an error for {game_name}"
with self.assertRaisesRegex(RuntimeError, "player >= 0", msg=msg):
state.information_state_string(-1)
with self.assertRaisesRegex(RuntimeError, "player <", msg=msg):
state.information_state_string(num_players + 1)
if game_type.provides_information_state_tensor:
if not state.is_chance_node():
for p in range(num_players):
v = state.information_state_tensor(p)
self.assertLen(v, game.information_state_tensor_size())
msg = f"information_state_tensor did not raise an error for {game_name}"
with self.assertRaisesRegex(RuntimeError, "player >= 0", msg=msg):
state.information_state_tensor(-1)
with self.assertRaisesRegex(RuntimeError, "player <", msg=msg):
state.information_state_tensor(num_players + 1)
if game_type.provides_observation_tensor:
if not state.is_chance_node():
for p in range(num_players):
v = state.observation_tensor(p)
self.assertLen(v, game.observation_tensor_size())
msg = f"observation_tensor did not raise an error for {game_name}"
with self.assertRaisesRegex(RuntimeError, "player >= 0", msg=msg):
state.observation_tensor(-1)
with self.assertRaisesRegex(RuntimeError, "player <", msg=msg):
state.observation_tensor(num_players + 1)
if game_type.provides_observation_string:
if not state.is_chance_node():
for p in range(num_players):
state.observation_string(p)
msg = f"observation_string did not raise an error for {game_name}"
with self.assertRaisesRegex(RuntimeError, "player >= 0", msg=msg):
state.observation_string(-1)
with self.assertRaisesRegex(RuntimeError, "player <", msg=msg):
state.observation_string(num_players + 1)
def test_legal_actions_returns_empty_list_on_opponent(self):
if self.game_name in _GAMES_TO_OMIT_LEGAL_ACTIONS_CHECK:
return
for state in self.some_states:
if state.is_terminal():
# Empty on terminal
msg = ("The game %s does not return an empty list on "
"legal_actions() for state %s" % (self.game_name, state))
self.assertEmpty(state.legal_actions(), msg=msg)
for player in range(self.game.num_players()):
msg = ("The game %s does not return an empty list on "
"legal_actions(%i) for state %s" %
(self.game_name, player, state))
self.assertEmpty(state.legal_actions(player), msg=msg)
elif state.is_simultaneous_node():
# No requirement for legal_actions to be empty, since all players act.
pass
elif state.is_chance_node():
# Would be an error to request legal actions for a non-chance player.
pass
else:
# Empty for players other than the current player
current_player = state.current_player()
for player in range(self.game.num_players()):
if player != current_player:
msg = ("The game {!r} does not return an empty list on "
"legal_actions(<not current player>) in state {}".format(
self.game_name, state))
self.assertEmpty(state.legal_actions(player), msg=msg)
def test_private_information_contents(self):
private_observation = make_observation(
self.game,
pyspiel.IIGObservationType(
public_info=False,
perfect_recall=False,
private_info=pyspiel.PrivateInfoType.SINGLE_PLAYER,
),
)
if (not private_observation
or private_observation.string_from(self.some_states[0], 0) is None):
return
player_has_private_info = [False] * self.game.num_players()
for state in self.some_states:
for i in range(self.game.num_players()):
if private_observation.string_from(state, i):
player_has_private_info[i] = True
if (self.game_type.information ==
pyspiel.GameType.Information.IMPERFECT_INFORMATION):
self.assertTrue(any(player_has_private_info))
if (self.game_type.information ==
pyspiel.GameType.Information.PERFECT_INFORMATION):
self.assertFalse(any(player_has_private_info))
def test_no_invalid_public_observations(self):
public_observation = make_observation(
self.game,
pyspiel.IIGObservationType(
public_info=True,
perfect_recall=False,
private_info=pyspiel.PrivateInfoType.NONE,
),
)
if not public_observation:
return
if public_observation.string_from(self.some_states[0], 0) is None:
return
for state in self.some_states:
self.assertIsNotNone(public_observation.string_from(state, 0))
def _assert_properties_recursive(state, assert_functions):
for assert_function in assert_functions:
assert_function(state)
# Recursion
# TODO(author2): We often use a `give me the next node` function and we
# probably want a utility method for that, which works for all games.
if state.is_terminal():
return
elif state.is_chance_node():
for action, unused_prob in state.chance_outcomes():
state_for_search = state.child(action)
_assert_properties_recursive(state_for_search, assert_functions)
else:
for action in state.legal_actions():
state_for_search = state.child(action)
_assert_properties_recursive(state_for_search, assert_functions)
def _assert_is_perfect_recall(game):
"""Raises an AssertionError if the game is not perfect recall.
We are willing to ensure the following property (perfect recall):
- define X_i(h) be the sequence of information states and actions from the
start of the game observed by player i (i.e. excluding the states and
actions taken by the opponents unless those actions are included in player
i's information state), along h but not including the state at h:
X_i(h) = (s_1, a_1), (s_2, a_2), ... , (s_{t-1}, a_{t-1})
then player i has perfect recall in this game iff: forall s in S_i,
forall h1, h2 in s X_i(h1) == X_i(h2). Here, we check that the game has
perfect recall if this is true for all players i (excluding chance).
For more detail and context, see page 11 of
http://mlanctot.info/files/papers/PhD_Thesis_MarcLanctot.pdf
In particular, note that:
- we want to check that holds both for
+ `std::string information_state_string(current_player)`
+ `information_state_tensor`.
- we check that currently only from the point of view of the current
player at the information state (i.e. we compare
`prev_state.information_state_string(current_player)` but not
`prev_state.information_state_string(opponent_player)`
The strategy is the following: we traverse the full tree (of states, not
infostates), and make sure for each node that the history we get for
the infostate associated to that node, that is is unique with respect to
the infostate.
Args:
game: A Spiel game to check.
Returns:
The internal cache mapping (infostate_str, player_id) to a list of one
history leading to this infostate.
"""
game_info = game.get_type()
if game_info.dynamics != pyspiel.GameType.Dynamics.SEQUENTIAL:
raise ValueError("The game is expected to be sequential")
infostate_player_to_history = {}
_assert_is_perfect_recall_recursive(
game.new_initial_state(),
current_history=[],
infostate_player_to_history=infostate_player_to_history)
return infostate_player_to_history
def _assert_is_perfect_recall_recursive(state, current_history,
infostate_player_to_history):
"""Raises an AssertionError if the game is not perfect recall.
The strategy is the following: we traverse the full tree (of states, not
infostates), and make sure for each node that the history we get for
the infostate associated to that node, that is is unique with respect to
the infostate.
Args:
state: The current state during the recursive tree traversal.
current_history: The current list of strictly preceding `SpielState` objects
that lead to the current `state` (excluded).
infostate_player_to_history: A dictionnary mapping (infostate string
representation, current_player) to the list of one instance of actual
predecessor nodes.
"""
if not state.is_chance_node() and not state.is_terminal():
current_player = state.current_player()
infostate_str = state.information_state_string(current_player)
key = (infostate_str, current_player)
if key not in infostate_player_to_history:
# First time we see the node.
infostate_player_to_history[key] = list(current_history)
else:
previous_history = infostate_player_to_history[key]
if len(previous_history) != len(current_history):
raise AssertionError("We found 2 history leading to the same state:\n"
"State: {!r}\n"
"InfoState str: {}\n"
"First history ({} states): {!r}\n"
"Second history ({} states): {!r}\n".format(
state.history(), infostate_str,
len(previous_history),
"|".join([str(sa) for sa in previous_history]),
len(current_history),
"|".join([str(sa) for sa in current_history])))
# Check for `information_state`
# pylint: disable=g-complex-comprehension
expected_infosets_history = [(s.information_state_string(current_player),
a)
for s, a in previous_history
if s.current_player() == current_player]
# pylint: disable=g-complex-comprehension
infosets_history = [(s.information_state_string(current_player), a)
for s, a in current_history
if s.current_player() == current_player]
if expected_infosets_history != infosets_history:
# pyformat: disable
raise AssertionError("We found 2 history leading to the same state:\n"
"history: {!r}\n"
"info_state str: {}\n"
"**First history ({} states)**\n"
"states: {!r}\n"
"info_sets: {!r}\n"
"**Second history ({} states)**\n"
"Second info_state history: {!r}\n"
"Second history: {!r}\n".format(
state.history(),
infostate_str,
len(previous_history),
"|".join([str(sa) for sa in previous_history]),
expected_infosets_history,
len(current_history), infosets_history,
"|".join([str(sa) for sa in current_history])))
# pyformat: enable
# Check for `information_state_tensor`
expected_infosets_history = [
(s.information_state_tensor(s.current_player()), a)
for s, a in previous_history
if s.current_player() == current_player
]
infosets_history = [(s.information_state_tensor(s.current_player()), a)
for s, a in current_history
if s.current_player() == current_player]
if infosets_history != expected_infosets_history:
raise ValueError("The history as tensor in the same infoset "
"are different:\n"
"History: {!r}\n".format(state.history()))
# Recursion
# TODO(author2): We often use a `give me the next node` function and we
# probably want a utility method for that, which works for all games.
if state.is_terminal():
return
else:
for action in state.legal_actions():
state_for_search = state.child(action)
_assert_is_perfect_recall_recursive(
state_for_search,
current_history=current_history + [(state, action)],
infostate_player_to_history=infostate_player_to_history)
def _create_test_case_classes():
"""Yields one Testing class per game to test."""
for game_name, game_string in _GAMES_FULL_TREE_TRAVERSAL_TESTS:
if not re.match(FLAGS.test_only_games, game_string):
continue
game = pyspiel.load_game(game_string)
new_class = type("EnforceAPIFullTree_{}_Test".format(game_name),
(EnforceAPIOnFullTreeBase,), {})
new_class.game_name = game_name
new_class.game = game
yield new_class
for game_name in _GAMES_TO_TEST:
if not re.match(FLAGS.test_only_games, game_name):
continue
game = pyspiel.load_game(game_name)
new_class = type("EnforceAPIPartialTree_{}_Test".format(game_name),
(EnforceAPIOnPartialTreeBase,), {})
new_class.game_name = game_name
new_class.game = game
yield new_class
def load_tests(loader, tests, pattern): # pylint: disable=invalid-name,g-doc-args
"""Returns Dynamically created TestSuite.
This creates one TestCase per game to test.
See https://docs.python.org/2/library/unittest.html#load-tests-protocol.
"""
del pattern
tests = tuple(
loader.loadTestsFromTestCase(test_case_class)
for test_case_class in _create_test_case_classes())
return unittest.TestSuite(tests=tests)
def main(_):
absltest.main()
if __name__ == "__main__":
# Necessary to run main via app.run for internal tests.
app.run(main)
| open_spiel-master | open_spiel/integration_tests/api_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A test file for run_python_test.py."""
import sys
from absl import app
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_string("print_value", "hello world", "String to print.")
flags.DEFINE_integer("return_value", 0, "Return value for the process.")
def main(argv):
print("Num args:", len(argv))
print("argv[0]:", argv[0])
print("print_value:", FLAGS.print_value)
print("return_value:", FLAGS.return_value)
sys.exit(FLAGS.return_value)
if __name__ == "__main__":
app.run(main)
| open_spiel-master | open_spiel/utils/run_python_test_file.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as python3
"""Test that Python numpy arrays can be passed to C++ Eigen library."""
import time
from absl.testing import absltest
import numpy as np
import pyspiel_eigen_test
class PyEigenTest(absltest.TestCase):
def test_square_matrix_elements(self):
x = np.array([[1, 2], [3, 4]]).astype(float)
expected = np.array([[1, 2], [3, 4]]) ** 2
actual = pyspiel_eigen_test.square(x)
np.testing.assert_array_equal(expected, actual)
def test_transpose_and_square_matrix_elements(self):
x = np.array([[1, 2], [3, 4]]).astype(float)
x = x.transpose()
expected = np.array(
[[1, 9],
[4, 16]])
actual = pyspiel_eigen_test.square(x)
np.testing.assert_array_equal(expected, actual)
def test_transpose_then_slice_and_square_matrix_elements(self):
x = np.array([[1, 2], [3, 4]]).astype(float)
x = x.transpose()
expected = np.array([[9], [16]])
actual = pyspiel_eigen_test.square(x[0:, 1:])
np.testing.assert_array_equal(expected, actual)
def test_square_vector_elements(self):
x = np.array([1, 2, 3]).astype(float)
expected = np.array([[1], [4], [9]])
actual = pyspiel_eigen_test.square(x)
np.testing.assert_array_equal(expected, actual)
def test_allocate_cxx(self):
actual = pyspiel_eigen_test.matrix()
expected = np.array([[1, 2], [3, 4]])
np.testing.assert_array_equal(expected, actual)
def test_flags_copy_or_reference(self):
# A test implementing
# https://pybind11.readthedocs.io/en/stable/advanced/cast/eigen.html#returning-values-to-python
start = time.time()
a = pyspiel_eigen_test.BigMatrix()
print("Alloc: ", time.time() - start)
start = time.time()
m = a.get_matrix()
print("Ref get: ", time.time() - start)
self.assertTrue(m.flags.writeable)
self.assertFalse(m.flags.owndata)
start = time.time()
v = a.view_matrix()
print("Ref view: ", time.time() - start)
self.assertFalse(v.flags.writeable)
self.assertFalse(v.flags.owndata)
start = time.time()
c = a.copy_matrix()
print("Copy: ", time.time() - start)
self.assertTrue(c.flags.writeable)
self.assertTrue(c.flags.owndata)
if __name__ == "__main__":
absltest.main()
| open_spiel-master | open_spiel/eigen/eigen_binding_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An example of building and exporting a Tensorflow graph.
Adapted from the Travis Ebesu's blog post:
https://tebesu.github.io/posts/Training-a-TensorFlow-graph-in-C++-API
"""
from absl import app
from absl import flags
import numpy as np
import tensorflow.compat.v1 as tf
import pyspiel
FLAGS = flags.FLAGS
flags.DEFINE_string("game", "breakthrough", "Name of the game")
flags.DEFINE_string("dir", "/tmp", "Directory to save graph")
flags.DEFINE_string("filename", "graph.pb", "Filename for the graph")
def main(_):
game = pyspiel.load_game(FLAGS.game)
# Information state length
info_state_shape = game.observation_tensor_shape()
flat_info_state_length = np.prod(info_state_shape)
# Output
num_actions = game.num_distinct_actions()
with tf.Session() as sess:
net_input = tf.placeholder(
tf.float32, [None, flat_info_state_length], name="input")
# pylint: disable=unused-variable
output = tf.placeholder(tf.float32, [None, num_actions], name="output")
legals_mask = tf.placeholder(
tf.float32, [None, num_actions], name="legals_mask")
policy_net = tf.layers.dense(net_input, 128, activation=tf.nn.relu)
policy_net = tf.layers.dense(policy_net, 128, activation=tf.nn.relu)
policy_net = tf.layers.dense(policy_net, num_actions)
# Note: subtracting the max here is to help with numerical stability.
# However, there can still be numerical problems. If you are doing a softmax
# here, it can return NaN when the max for the policy net is high on one of
# the illegal actions, because policy_net - max will be small for legal
# actions, giving all exp(small) == 0 in the denominator, returning NaN at
# the end. One fix is to set the logits to -inf and define a custom cross
# entropy op that ignores over the illegal actions.
policy_net = policy_net - tf.reduce_max(policy_net, axis=-1, keepdims=True)
masked_exp_logit = tf.multiply(tf.exp(policy_net), legals_mask)
renormalizing_factor = tf.reduce_sum(
masked_exp_logit, axis=-1, keepdims=True)
# pylint: disable=unused-variable
policy_softmax = tf.where(
tf.equal(legals_mask, 0.),
tf.zeros_like(masked_exp_logit),
tf.divide(masked_exp_logit, renormalizing_factor),
name="policy_softmax")
policy_targets = tf.placeholder(shape=[None, num_actions], dtype=tf.float32)
policy_cost = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits_v2(
logits=policy_net, labels=policy_targets),
axis=0)
# We make one sample.
sampled_actions = tf.random.categorical(
tf.log(policy_softmax), 1, name="sampled_actions")
# pylint: disable=unused-variable
optimizer = tf.train.AdamOptimizer(0.0001).minimize(
policy_cost, name="train")
# pylint: disable=unused-variable
init = tf.variables_initializer(tf.global_variables(),
name="init_all_vars_op")
print("Writing file: {}/{}".format(FLAGS.dir, FLAGS.filename))
tf.train.write_graph(
sess.graph_def, FLAGS.dir, FLAGS.filename, as_text=False)
if __name__ == "__main__":
app.run(main)
| open_spiel-master | open_spiel/contrib/python/export_graph.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A simple random bot."""
import base64
import sys
import numpy as np
from open_spiel.python.observation import make_observation
import pyspiel
# Example implementation of the random bot for the HIG competition.
# The bot must strictly follow the communication protocol via stdin/stdout,
# but it can print any message to stderr for debugging.
# Read the current setup.
game_name = input()
play_as = int(input())
print(game_name, play_as, file=sys.stderr) # For debugging purposes.
# Load the provided game.
game = pyspiel.load_game(game_name)
# Observations will be received later from the referee.
# The referee factors the observation into public (common knowledge across all
# players) and private parts.
public_observation = make_observation(
game,
pyspiel.IIGObservationType(
perfect_recall=False,
public_info=True,
private_info=pyspiel.PrivateInfoType.NONE))
private_observation = make_observation(
game,
pyspiel.IIGObservationType(
perfect_recall=False,
public_info=False,
private_info=pyspiel.PrivateInfoType.SINGLE_PLAYER))
# Now there is 5 secs warm-up time that could be used for loading relevant
# supplementary data. All data can be read/written from persistent /data
# directory mounted from an external storage.
print("ready")
# Loop per match. This loop will end when referee instructs the player to do so.
while True:
# Acknowledge the match started.
print("start")
# This is just a placeholder for other implementations -- we do not use
# state in random agent, as it receives list of actions it can pick from.
state = game.new_initial_state()
while True: # Loop per state in match.
message = input() # Read message from the referee.
print(message, file=sys.stderr) # For debugging purposes.
if message == "tournament over":
# The tournament is now over: there is 60 sec shutdown time
# available for processing tournament results by the agent,
# for example to update supplementary data.
print("tournament over")
sys.exit(0)
if message.startswith("match over"):
# The full message has format "game over 123"
# where 123 is the final float reward received by this bot.
#
# Note that this message does not necessarily mean the match
# reached a terminal state: if opponent crashed / violated
# rules, the match will be over as well.
print("match over")
break
# Regular message: a public and private observation followed by
# a list of legal actions (if the bot should be acting).
public_buf, private_buf, *legal_actions = message.split(" ")
public_observation.decompress(base64.b64decode(public_buf))
private_observation.decompress(base64.b64decode(private_buf))
if legal_actions:
# There is time limit of 5 secs.
print(np.random.choice(legal_actions))
else:
# Pondering phase, i.e. thinking when the bot is not acting.
# The time limit is always at least 0.2s, but can be longer,
# up to 5s, depending on how long the opponent thinks.
print("ponder") # This bot does not ponder.
assert message.startswith("match over")
score = int(message.split(" ")[-1])
print("score:", score, file=sys.stderr)
| open_spiel-master | open_spiel/higc/bots/random_bot.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A bot that picks the first action from the list. Used only for tests."""
import base64
import sys
from open_spiel.python.observation import make_observation
import pyspiel
game_name = input()
play_as = int(input())
game = pyspiel.load_game(game_name)
public_observation = make_observation(
game,
pyspiel.IIGObservationType(
perfect_recall=False,
public_info=True,
private_info=pyspiel.PrivateInfoType.NONE))
private_observation = make_observation(
game,
pyspiel.IIGObservationType(
perfect_recall=False,
public_info=False,
private_info=pyspiel.PrivateInfoType.SINGLE_PLAYER))
print("ready")
while True:
print("start")
while True:
message = input()
if message == "tournament over":
print("tournament over")
sys.exit(0)
if message.startswith("match over"):
print("match over")
break
public_buf, private_buf, *legal_actions = message.split(" ")
public_observation.decompress(base64.b64decode(public_buf))
private_observation.decompress(base64.b64decode(private_buf))
if legal_actions:
print(legal_actions[0])
else:
print("ponder")
| open_spiel-master | open_spiel/higc/bots/test_bot_first_action.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests if a bot fails after a few actions.
A bot that picks the first action from the list for the first two rounds,
and then exists with an exception.
Used only for tests.
"""
import sys
game_name = input()
play_as = int(input())
print("ready")
while True:
print("start")
num_actions = 0
while True:
message = input()
if message == "tournament over":
print("tournament over")
sys.exit(0)
if message.startswith("match over"):
print("match over")
break
public_buf, private_buf, *legal_actions = message.split(" ")
if legal_actions:
num_actions += 1
print(legal_actions[-1])
else:
print("ponder")
if num_actions > 2:
raise RuntimeError
| open_spiel-master | open_spiel/higc/bots/test_bot_fail_after_few_actions.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utils function for routing game experiment."""
# pylint:disable=too-many-lines,import-error,missing-function-docstring,protected-access,too-many-locals,invalid-name,too-many-arguments,too-many-branches,missing-class-docstring,too-few-public-methods
# pylint:disable=line-too-long
import random
import time
import matplotlib.pyplot as plt
import numpy as np
import tensorflow.compat.v1 as tf
from open_spiel.python import policy as policy_module
from open_spiel.python import rl_environment
from open_spiel.python.algorithms import cfr
from open_spiel.python.algorithms import expected_game_score
from open_spiel.python.algorithms import exploitability
from open_spiel.python.algorithms import external_sampling_mccfr as external_mccfr
from open_spiel.python.algorithms import fictitious_play
from open_spiel.python.algorithms import nfsp
from open_spiel.python.algorithms import noisy_policy
from open_spiel.python.games import dynamic_routing
from open_spiel.python.games import dynamic_routing_utils
from open_spiel.python.mfg.algorithms import distribution as distribution_module
from open_spiel.python.mfg.algorithms import fictitious_play as mean_field_fictitious_play_module
from open_spiel.python.mfg.algorithms import mirror_descent
from open_spiel.python.mfg.algorithms import nash_conv as nash_conv_module
from open_spiel.python.mfg.algorithms import policy_value
from open_spiel.python.mfg.games import dynamic_routing as mean_field_routing_game
import pyspiel
# pylint:enable=line-too-long
def create_games(origin,
destination,
num_vehicles,
graph,
max_time_step,
time_step_length=1.0,
departure_time=None):
if departure_time is not None:
raise NotImplementedError("To do.")
list_of_vehicles = [
dynamic_routing_utils.Vehicle(origin, destination)
for _ in range(num_vehicles)
]
game = dynamic_routing.DynamicRoutingGame(
{
"max_num_time_step": max_time_step,
"time_step_length": time_step_length
},
network=graph,
vehicles=list_of_vehicles)
seq_game = pyspiel.convert_to_turn_based(game)
od_demand = [
dynamic_routing_utils.OriginDestinationDemand(origin, destination, 0,
num_vehicles)
]
mfg_game = mean_field_routing_game.MeanFieldRoutingGame(
{
"max_num_time_step": max_time_step,
"time_step_length": time_step_length
},
network=graph,
od_demand=od_demand)
return game, seq_game, mfg_game
def create_braess_network(capacity):
graph_dict = {
"A": {
"connection": {
"B": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 0
}
},
"location": [0, 0]
},
"B": {
"connection": {
"C": {
"a": 1.0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 1.0
},
"D": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 2.0
}
},
"location": [1, 0]
},
"C": {
"connection": {
"D": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 0.25
},
"E": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 2.0
}
},
"location": [2, 1]
},
"D": {
"connection": {
"E": {
"a": 1,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 1.0
}
},
"location": [2, -1]
},
"E": {
"connection": {
"F": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 0.0
}
},
"location": [3, 0]
},
"F": {
"connection": {},
"location": [4, 0]
}
}
adjacency_list = {
key: list(value["connection"].keys())
for key, value in graph_dict.items()
}
bpr_a_coefficient = {}
bpr_b_coefficient = {}
capacity = {}
free_flow_travel_time = {}
for o_node, value_dict in graph_dict.items():
for d_node, section_dict in value_dict["connection"].items():
road_section = dynamic_routing_utils._road_section_from_nodes(
origin=o_node, destination=d_node)
bpr_a_coefficient[road_section] = section_dict["a"]
bpr_b_coefficient[road_section] = section_dict["b"]
capacity[road_section] = section_dict["capacity"]
free_flow_travel_time[road_section] = section_dict[
"free_flow_travel_time"]
node_position = {key: value["location"] for key, value in graph_dict.items()}
return dynamic_routing_utils.Network(
adjacency_list,
node_position=node_position,
bpr_a_coefficient=bpr_a_coefficient,
bpr_b_coefficient=bpr_b_coefficient,
capacity=capacity,
free_flow_travel_time=free_flow_travel_time)
def create_augmented_braess_network(capacity):
graph_dict = {
"A": {
"connection": {
"B": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 0
}
},
"location": [0, 0]
},
"B": {
"connection": {
"C": {
"a": 1.0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 1.0
},
"D": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 2.0
}
},
"location": [1, 0]
},
"C": {
"connection": {
"D": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 0.25
},
"E": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 2.0
}
},
"location": [2, 1]
},
"D": {
"connection": {
"E": {
"a": 1,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 1.0
},
"G": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 0.0
}
},
"location": [2, -1]
},
"E": {
"connection": {
"F": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": 0.0
}
},
"location": [3, 0]
},
"F": {
"connection": {},
"location": [4, 0]
},
"G": {
"connection": {},
"location": [3, -1]
}
}
adjacency_list = {
key: list(value["connection"].keys())
for key, value in graph_dict.items()
}
bpr_a_coefficient = {}
bpr_b_coefficient = {}
capacity = {}
free_flow_travel_time = {}
for o_node, value_dict in graph_dict.items():
for d_node, section_dict in value_dict["connection"].items():
road_section = dynamic_routing_utils._road_section_from_nodes(
origin=o_node, destination=d_node)
bpr_a_coefficient[road_section] = section_dict["a"]
bpr_b_coefficient[road_section] = section_dict["b"]
capacity[road_section] = section_dict["capacity"]
free_flow_travel_time[road_section] = section_dict[
"free_flow_travel_time"]
node_position = {key: value["location"] for key, value in graph_dict.items()}
return dynamic_routing_utils.Network(
adjacency_list,
node_position=node_position,
bpr_a_coefficient=bpr_a_coefficient,
bpr_b_coefficient=bpr_b_coefficient,
capacity=capacity,
free_flow_travel_time=free_flow_travel_time)
def create_series_parallel_network(num_network_in_series,
time_step_length=1,
capacity=1):
i = 0
origin = "A_0->B_0"
graph_dict = {}
while i < num_network_in_series:
tt_up = random.random() + time_step_length
tt_down = random.random() + time_step_length
graph_dict.update({
f"A_{i}": {
"connection": {
f"B_{i}": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": time_step_length
}
},
"location": [0 + 3 * i, 0]
},
f"B_{i}": {
"connection": {
f"C_{i}": {
"a": 1.0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": tt_up
},
f"D_{i}": {
"a": 1.0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": tt_down
}
},
"location": [1 + 3 * i, 0]
},
f"C_{i}": {
"connection": {
f"A_{i+1}": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": time_step_length
}
},
"location": [2 + 3 * i, 1]
},
f"D_{i}": {
"connection": {
f"A_{i+1}": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": time_step_length
}
},
"location": [2 + 3 * i, -1]
}
})
i += 1
graph_dict[f"A_{i}"] = {
"connection": {
"END": {
"a": 0,
"b": 1.0,
"capacity": capacity,
"free_flow_travel_time": time_step_length
}
},
"location": [0 + 3 * i, 0]
}
graph_dict["END"] = {"connection": {}, "location": [1 + 3 * i, 0]}
time_horizon = int(3.0 * (num_network_in_series + 1) / time_step_length)
destination = f"A_{i}->END"
adjacency_list = {
key: list(value["connection"].keys())
for key, value in graph_dict.items()
}
bpr_a_coefficient = {}
bpr_b_coefficient = {}
capacity = {}
free_flow_travel_time = {}
for o_node, value_dict in graph_dict.items():
for d_node, section_dict in value_dict["connection"].items():
road_section = dynamic_routing_utils._road_section_from_nodes(
origin=o_node, destination=d_node)
bpr_a_coefficient[road_section] = section_dict["a"]
bpr_b_coefficient[road_section] = section_dict["b"]
capacity[road_section] = section_dict["capacity"]
free_flow_travel_time[road_section] = section_dict[
"free_flow_travel_time"]
node_position = {key: value["location"] for key, value in graph_dict.items()}
return dynamic_routing_utils.Network(
adjacency_list,
node_position=node_position,
bpr_a_coefficient=bpr_a_coefficient,
bpr_b_coefficient=bpr_b_coefficient,
capacity=capacity,
free_flow_travel_time=free_flow_travel_time
), origin, destination, time_horizon
def plot_network_n_player_game(g: dynamic_routing_utils.Network,
vehicle_locations=None):
"""Plot the network.
Args:
g: network to plot
vehicle_locations: vehicle location
"""
_, ax = plt.subplots()
o_xs, o_ys, d_xs, d_ys = g.return_list_for_matplotlib_quiver()
ax.quiver(
o_xs,
o_ys,
np.subtract(d_xs, o_xs),
np.subtract(d_ys, o_ys),
color="b",
angles="xy",
scale_units="xy",
scale=1)
ax.set_xlim([
np.min(np.concatenate((o_xs, d_xs))) - 0.5,
np.max(np.concatenate((o_xs, d_xs))) + 0.5
])
ax.set_ylim([
np.min(np.concatenate((o_ys, d_ys))) - 0.5,
np.max(np.concatenate((o_ys, d_ys))) + 0.5
])
if vehicle_locations is not None:
num_vehicle = len(vehicle_locations)
dict_location = {}
for vehicle_location in vehicle_locations:
if vehicle_location not in dict_location:
dict_location[vehicle_location] = 0.0
dict_location[vehicle_location] += 0.3 / num_vehicle
for point, width in dict_location.items():
circle = plt.Circle(point, width, color="r")
ax.add_patch(circle)
def plot_network_mean_field_game(g: dynamic_routing_utils.Network,
distribution=None,
scaling=1):
"""Plot the network.
Args:
g: network to plot
distribution: the distribution.
scaling: scaling factor. for plot rendering.
"""
_, ax = plt.subplots()
o_xs, o_ys, d_xs, d_ys = g.return_list_for_matplotlib_quiver()
ax.quiver(
o_xs,
o_ys,
np.subtract(d_xs, o_xs),
np.subtract(d_ys, o_ys),
color="b",
angles="xy",
scale_units="xy",
scale=1)
ax.set_xlim([
np.min(np.concatenate((o_xs, d_xs))) - 0.5,
np.max(np.concatenate((o_xs, d_xs))) + 0.5
])
ax.set_ylim([
np.min(np.concatenate((o_ys, d_ys))) - 0.5,
np.max(np.concatenate((o_ys, d_ys))) + 0.5
])
if distribution is not None:
for x, prob_of_position in distribution.items():
point = g.return_position_of_road_section(x)
width = 0.3 * scaling * prob_of_position
circle = plt.Circle(point, width, color="r")
ax.add_patch(circle)
def evolve_n_player_simultaneous_game(game, policy, graph):
state = game.new_initial_state()
i = 0
while not state.is_terminal():
i += 1
if state.is_chance_node():
# Sample a chance event outcome.
outcomes_with_probs = state.chance_outcomes()
action_list, prob_list = zip(*outcomes_with_probs)
action = np.random.choice(action_list, p=prob_list)
state.apply_action(action)
elif state.is_simultaneous_node():
# Simultaneous node: sample actions for all players.
chosen_actions = []
for i in range(game.num_players()):
legal_actions = state.legal_actions(i)
state_policy = policy(state, i)
assert len(legal_actions) == len(state_policy), (
f"{legal_actions} not same length than {state_policy}")
chosen_actions.append(
random.choices(legal_actions,
[state_policy[a] for a in legal_actions])[0])
state.apply_actions(chosen_actions)
else:
raise ValueError(
"State should either be simultaneous node or change node.")
plot_network_n_player_game(graph, [
graph.return_position_of_road_section(x)
for x in state.get_current_vehicle_locations()
])
print(f"Travel times: {[-x for x in state.returns()]}")
def evolve_n_player_sequential_game(seq_game, policy, graph, debug=False):
state = seq_game.new_initial_state()
while not state.is_terminal():
legal_actions = state.legal_actions()
if state.is_chance_node():
# Sample a chance event outcome.
outcomes_with_probs = state.chance_outcomes()
action_list, prob_list = zip(*outcomes_with_probs)
action = np.random.choice(action_list, p=prob_list)
if debug:
print("------------ Change node ------------")
print(
(f"Possible chance actions: {outcomes_with_probs}, the one taken: "
f"{action}."))
state.apply_action(action)
else:
if debug:
print("------------ Sequential action node ------------")
print(state.information_state_tensor())
print(state.observation_tensor())
print(state.information_state_string())
if policy is not None:
state_policy = policy(state)
vehicle_location = [
s.replace("'", "")
for s in str(state).split("[")[1].split("]")[0].split(", ")
]
if debug:
print((f"Policy for player {state.current_player()} at location "
f"{vehicle_location[state.current_player()]}: ") +
str([(str(graph.get_road_section_from_action_id(k)) +
f"with probability {v}")
for k, v in state_policy.items()]))
assert set(state_policy) == set(legal_actions)
action = random.choices(legal_actions,
[state_policy[a] for a in legal_actions])
assert len(action) == 1
action = action[0]
else:
action = random.choice(legal_actions)
state.apply_action(action)
vehicle_location = [
s.replace("'", "")
for s in str(state).split("[")[1].split("]")[0].split(", ")
]
if debug:
print(vehicle_location)
plot_network_n_player_game(
graph,
[graph.return_position_of_road_section(x) for x in vehicle_location])
if debug:
print(f"Travel times: {[-x for x in state.returns()]}")
def evolve_mean_field_game(mfg_game,
policy,
graph,
scaling=1,
frequency_printing=1):
distribution_mfg = distribution_module.DistributionPolicy(mfg_game, policy)
root_state = mfg_game.new_initial_state()
listing_states = [root_state]
# plot_network_mean_field_game(graph, {origin: 1})
i = 0
while not listing_states[0].is_terminal() and not all(
state._vehicle_without_legal_action for state in listing_states): # pylint:disable=protected-access
assert abs(sum(map(distribution_mfg.value, listing_states)) - 1) < 1e-4, (
f"{list(map(distribution_mfg.value, listing_states))}")
new_listing_states = []
list_of_state_seen = set()
# In case chance node:
if listing_states[0].current_player() == pyspiel.PlayerId.CHANCE:
for mfg_state in listing_states:
for action, _ in mfg_state.chance_outcomes():
new_mfg_state = mfg_state.child(action)
# Do not append twice the same file.
if str(new_mfg_state) not in list_of_state_seen:
new_listing_states.append(new_mfg_state)
list_of_state_seen.add(str(new_mfg_state))
current_distribution = {}
for mfg_state in new_listing_states:
location = mfg_state._vehicle_location # pylint:disable=protected-access
if location not in current_distribution:
current_distribution[location] = 0
current_distribution[location] += distribution_mfg.value(mfg_state)
plot_network_mean_field_game(graph, current_distribution, scaling=scaling)
# In case mean field node:
elif listing_states[0].current_player() == pyspiel.PlayerId.MEAN_FIELD:
for mfg_state in listing_states:
dist_to_register = mfg_state.distribution_support()
def get_probability_for_state(str_state):
try:
return distribution_mfg.value_str(str_state)
except ValueError:
return 0
dist = [
get_probability_for_state(str_state)
for str_state in dist_to_register
]
new_mfg_state = mfg_state.clone()
new_mfg_state.update_distribution(dist)
# Do not append twice the same file.
if str(new_mfg_state) not in list_of_state_seen:
new_listing_states.append(new_mfg_state)
list_of_state_seen.add(str(new_mfg_state))
# In case action node:
else:
assert (listing_states[0].current_player() ==
pyspiel.PlayerId.DEFAULT_PLAYER_ID), "The player id should be 0"
for mfg_state in listing_states:
for action, _ in policy.action_probabilities(mfg_state).items():
new_mfg_state = mfg_state.child(action)
# Do not append twice the same file.
if str(new_mfg_state) not in list_of_state_seen:
new_listing_states.append(new_mfg_state)
list_of_state_seen.add(str(new_mfg_state))
current_distribution = {}
for mfg_state in new_listing_states:
location = mfg_state._vehicle_location # pylint:disable=protected-access
if location not in current_distribution:
current_distribution[location] = 0
current_distribution[location] += distribution_mfg.value(mfg_state)
assert abs(sum(current_distribution.values()) - 1) < 1e-4, (
f"{current_distribution}")
i += 1
if i % frequency_printing == 0:
plot_network_mean_field_game(
graph, current_distribution, scaling=scaling)
listing_states = new_listing_states
def uniform_policy_n_player(seq_game):
return policy_module.UniformRandomPolicy(seq_game)
def first_action_policy_n_player(seq_game):
return policy_module.FirstActionPolicy(seq_game)
def ficticious_play(seq_game, number_of_iterations, compute_metrics=False):
xfp_solver = fictitious_play.XFPSolver(seq_game)
tick_time = time.time()
for _ in range(number_of_iterations):
xfp_solver.iteration()
timing = time.time() - tick_time
# print('done')
# average_policies = xfp_solver.average_policy_tables()
tabular_policy = policy_module.TabularPolicy(seq_game)
if compute_metrics:
nash_conv = exploitability.nash_conv(seq_game, xfp_solver.average_policy())
average_policy_values = expected_game_score.policy_value(
seq_game.new_initial_state(), [tabular_policy])
return timing, tabular_policy, nash_conv, average_policy_values
return timing, tabular_policy
def counterfactual_regret_minimization(seq_game,
number_of_iterations,
compute_metrics=False):
# freq_iteration_printing = number_of_iterations // 10
cfr_solver = cfr.CFRSolver(seq_game)
tick_time = time.time()
# print("CFRSolver initialized.")
for _ in range(number_of_iterations):
cfr_solver.evaluate_and_update_policy()
# if i % freq_iteration_printing == 0:
# print(f"Iteration {i}")
timing = time.time() - tick_time
# print("Finish.")
if compute_metrics:
nash_conv = exploitability.nash_conv(seq_game, cfr_solver.average_policy())
return timing, cfr_solver.average_policy(), nash_conv
return timing, cfr_solver.average_policy()
def external_sampling_monte_carlo_counterfactual_regret_minimization(
seq_game, number_of_iterations, compute_metrics=False):
cfr_solver = external_mccfr.ExternalSamplingSolver(
seq_game, external_mccfr.AverageType.SIMPLE)
tick_time = time.time()
# print("CFRSolver initialized.")
for _ in range(number_of_iterations):
cfr_solver.iteration()
timing = time.time() - tick_time
# print("Finish.")
if compute_metrics:
nash_conv = exploitability.nash_conv(seq_game, cfr_solver.average_policy())
return timing, cfr_solver.average_policy(), nash_conv
return timing, cfr_solver.average_policy()
class NFSPPolicies(policy_module.Policy):
"""Joint policy to be evaluated."""
def __init__(self, env, nfsp_policies, mode):
game = env.game
num_players = env.num_players
player_ids = list(range(num_players))
super().__init__(game, player_ids)
self._policies = nfsp_policies
self._mode = mode
self._obs = {
"info_state": [None] * num_players,
"legal_actions": [None] * num_players
}
def action_probabilities(self, state, player_id=None):
del player_id
cur_player = state.current_player()
legal_actions = state.legal_actions(cur_player)
self._obs["current_player"] = cur_player
self._obs["info_state"][cur_player] = (
state.information_state_tensor(cur_player))
self._obs["legal_actions"][cur_player] = legal_actions
info_state = rl_environment.TimeStep(
observations=self._obs, rewards=None, discounts=None, step_type=None)
with self._policies[cur_player].temp_mode_as(self._mode):
p = self._policies[cur_player].step(info_state, is_evaluation=True).probs
prob_dict = {action: p[action] for action in legal_actions}
return prob_dict
def neural_ficticious_self_play(seq_game,
num_epoch,
sess,
compute_metrics=False):
env = rl_environment.Environment(seq_game)
# Parameters from the game.
num_players = env.num_players
num_actions = env.action_spec()["num_actions"]
info_state_size = env.observation_spec()["info_state"][0]
# Parameters for the algorithm.
hidden_layers_sizes = [int(l) for l in [128]]
kwargs = {
"replay_buffer_capacity": int(2e5),
"reservoir_buffer_capacity": int(2e6),
"min_buffer_size_to_learn": 1000,
"anticipatory_param": 0.1,
"batch_size": 128,
"learn_every": 64,
"rl_learning_rate": 0.01,
"sl_learning_rate": 0.01,
"optimizer_str": "sgd",
"loss_str": "mse",
"update_target_network_every": 19200,
"discount_factor": 1.0,
"epsilon_decay_duration": int(20e6),
"epsilon_start": 0.06,
"epsilon_end": 0.001,
}
# freq_epoch_printing = num_epoch // 10
agents = [
nfsp.NFSP(sess, idx, info_state_size, num_actions, hidden_layers_sizes,
**kwargs) for idx in range(num_players)
]
joint_avg_policy = NFSPPolicies(env, agents, nfsp.MODE.average_policy)
sess.run(tf.global_variables_initializer())
# print("TF initialized.")
tick_time = time.time()
for _ in range(num_epoch):
# if ep % freq_epoch_printing == 0:
# print(f"Iteration {ep}")
time_step = env.reset()
while not time_step.last():
player_id = time_step.observations["current_player"]
agent_output = agents[player_id].step(time_step)
action_list = [agent_output.action]
time_step = env.step(action_list)
# Episode is over, step all agents with final info state.
for agent in agents:
agent.step(time_step)
timing = time.time() - tick_time
# print("Finish.")
if compute_metrics:
tabular_policy = joint_avg_policy.TabularPolicy(seq_game)
average_policy_values = expected_game_score.policy_value(
seq_game.new_initial_state(), [tabular_policy])
nash_conv = exploitability.nash_conv(env.game, joint_avg_policy)
return timing, joint_avg_policy, average_policy_values, nash_conv
return timing, joint_avg_policy
def mean_field_uniform_policy(mfg_game,
number_of_iterations,
compute_metrics=False):
del number_of_iterations
uniform_policy = policy_module.UniformRandomPolicy(mfg_game)
if compute_metrics:
distribution_mfg = distribution_module.DistributionPolicy(
mfg_game, uniform_policy)
policy_value_ = policy_value.PolicyValue(mfg_game, distribution_mfg,
uniform_policy).value(
mfg_game.new_initial_state())
return uniform_policy, policy_value_
return uniform_policy
def mean_field_fictitious_play(mfg_game,
number_of_iterations,
compute_metrics=False):
fp = mean_field_fictitious_play_module.FictitiousPlay(mfg_game)
tick_time = time.time()
for _ in range(number_of_iterations):
fp.iteration()
timing = time.time() - tick_time
fp_policy = fp.get_policy()
# print('learning done')
if compute_metrics:
distribution_mfg = distribution_module.DistributionPolicy(
mfg_game, fp_policy)
# print('distribution done')
policy_value_ = policy_value.PolicyValue(mfg_game, distribution_mfg,
fp_policy).value(
mfg_game.new_initial_state())
nash_conv_fp = nash_conv_module.NashConv(mfg_game, fp_policy)
return timing, fp_policy, nash_conv_fp, policy_value_
return timing, fp_policy
def online_mirror_descent(mfg_game,
number_of_iterations,
compute_metrics=False,
return_policy=False,
md_p=None):
md = md_p if md_p else mirror_descent.MirrorDescent(mfg_game)
tick_time = time.time()
for _ in range(number_of_iterations):
md.iteration()
timing = time.time() - tick_time
md_policy = md.get_policy()
if compute_metrics:
distribution_mfg = distribution_module.DistributionPolicy(
mfg_game, md_policy)
# print('distribution done')
policy_value_ = policy_value.PolicyValue(mfg_game, distribution_mfg,
md_policy).value(
mfg_game.new_initial_state())
nash_conv_md = nash_conv_module.NashConv(mfg_game, md_policy)
if return_policy:
return timing, md_policy, nash_conv_md, policy_value_, md
return timing, md_policy, nash_conv_md, policy_value_
return timing, md_policy
class RandomPolicyDeviation:
def __init__(self):
self.policy_deviation = {}
def get_policy_deviation(self, state, player_id):
key = (str(state), player_id)
if key not in self.policy_deviation:
assert player_id == state.current_player()
action_probability = [random.random() for a in state.legal_actions()]
self.policy_deviation[key] = [
x / sum(action_probability) for x in action_probability
]
return self.policy_deviation[key]
def get_results_n_player_sequential_game(seq_game, policy):
state = seq_game.new_initial_state()
while not state.is_terminal():
legal_actions = state.legal_actions()
if state.is_chance_node():
outcomes_with_probs = state.chance_outcomes()
action_list, prob_list = zip(*outcomes_with_probs)
action = np.random.choice(action_list, p=prob_list)
else:
state_policy = policy(state)
assert set(state_policy) == set(legal_actions)
action = random.choices(legal_actions,
[state_policy[a] for a in legal_actions])
assert len(action) == 1
action = action[0]
state.apply_action(action)
return state.returns()
def get_list_results_n_player_game(seq_game, policy, num_sample=10):
return [
get_results_n_player_sequential_game(seq_game, policy)
for _ in range(num_sample)
]
def get_average_results_n_player_game(seq_game, policy, num_sample=10):
result_array = get_list_results_n_player_game(seq_game, policy, num_sample)
return sum([sum(i) / len(i) for i in zip(*result_array)]) / len(result_array)
def get_results_n_player_simultaneous_game(game, policy):
state = game.new_initial_state()
i = 0
while not state.is_terminal():
i += 1
if state.is_chance_node():
# Sample a chance event outcome.
outcomes_with_probs = state.chance_outcomes()
action_list, prob_list = zip(*outcomes_with_probs)
action = np.random.choice(action_list, p=prob_list)
state.apply_action(action)
elif state.is_simultaneous_node():
# Simultaneous node: sample actions for all players.
chosen_actions = []
for i in range(game.num_players()):
legal_actions = state.legal_actions(i)
state_policy = policy(state, player_id=i)
assert abs(sum([state_policy[a] for a in legal_actions]) - 1) < 1e-4
chosen_actions.append(
random.choices(legal_actions,
[state_policy[a] for a in legal_actions])[0])
state.apply_actions(chosen_actions)
else:
raise ValueError(
"State should either be simultaneous node or change node.")
return state.returns()
def get_list_results_n_player_simulataneous_game(game, policy, num_sample=10):
return [
get_results_n_player_simultaneous_game(game, policy)
for _ in range(num_sample)
]
def get_expected_value(seq_game, policy, num_sample, player=0):
results = get_list_results_n_player_game(
seq_game, policy, num_sample=num_sample)
expected_value = sum(x[player] for x in results) / num_sample
# num_vehicle = len(results[0])
# error_bar = abs(sum([x[1] for x in results]) - sum(
# [x[2] for x in results])) / num_sample_trajectories
# expected_value_policy = sum(sum(x[i] for x in results) for i in range(
# 1, BRAESS_NUM_VEHICLES)) / ((BRAESS_NUM_VEHICLES-1)*num_sample_trajectories)
return expected_value
def compute_regret_policy(game,
policy,
num_random_policy_tested=10,
num_sample=100):
time_tick = time.time()
expected_value_policy = get_expected_value(game, policy, num_sample)
worse_regret = 0
for _ in range(num_random_policy_tested):
noisy_n_policy = noisy_policy.NoisyPolicy(policy, player_id=0, alpha=1)
expected_value_noise = get_expected_value(
game, noisy_n_policy, num_sample, player=0)
approximate_regret = expected_value_noise - expected_value_policy
worse_regret = max(worse_regret, approximate_regret)
return worse_regret, time.time() - time_tick
def get_expected_value_sim_game(game, policy, num_sample, player=0):
results = get_list_results_n_player_simulataneous_game(
game, policy, num_sample=num_sample)
assert len(results) == num_sample
expected_value = sum(x[player] for x in results) / num_sample
# num_vehicle = len(results[0])
# error_bar = abs(sum([x[1] for x in results]) - sum(
# [x[2] for x in results])) / num_sample_trajectories
# expected_value_policy = sum(sum(x[i] for x in results) for i in range(
# 1, BRAESS_NUM_VEHICLES)) / ((BRAESS_NUM_VEHICLES-1)*num_sample_trajectories)
return expected_value
def compute_regret_policy_random_noise_sim_game(game,
policy,
num_random_policy_tested=10,
num_sample=100):
time_tick = time.time()
expected_value_policy = get_expected_value_sim_game(game, policy, num_sample)
worse_regret = 0
for _ in range(num_random_policy_tested):
noisy_n_policy = noisy_policy.NoisyPolicy(policy, player_id=0, alpha=1)
expected_value_noise = get_expected_value_sim_game(
game, noisy_n_policy, num_sample, player=0)
approximate_regret = expected_value_noise - expected_value_policy
worse_regret = max(worse_regret, approximate_regret)
return worse_regret, time.time() - time_tick
class PurePolicyResponse(policy_module.Policy):
def __init__(self, game, policy, player_id):
self.game = game
self.player_id = player_id
self.policy = policy
def pure_action(self, state):
raise NotImplementedError()
def action_probabilities(self, state, player_id=None):
assert player_id is not None
if player_id == self.player_id:
legal_actions = state.legal_actions(self.player_id)
if not legal_actions:
return {0: 1.0}
if len(legal_actions) == 1:
return {legal_actions[0]: 1.0}
answer = {action: 0.0 for action in legal_actions}
pure_a = self.pure_action(state)
assert pure_a in answer
answer[pure_a] = 1.0
return answer
return self.policy.action_probabilities(state, player_id)
class PathBCEResponse(PurePolicyResponse):
def pure_action(self, state):
location = state.get_current_vehicle_locations()[self.player_id].split(
"->")[1]
if location == "B":
return state.get_game().network.get_action_id_from_movement("B", "C")
if location == "C":
return state.get_game().network.get_action_id_from_movement("C", "E")
return 0
class PathBCDEResponse(PurePolicyResponse):
def pure_action(self, state):
location = state.get_current_vehicle_locations()[self.player_id].split(
"->")[1]
if location == "B":
return state.get_game().network.get_action_id_from_movement("B", "C")
if location == "C":
return state.get_game().network.get_action_id_from_movement("C", "D")
return 0
class PathBDEResponse(PurePolicyResponse):
def pure_action(self, state):
location = state.get_current_vehicle_locations()[self.player_id].split(
"->")[1]
if location == "B":
return state.get_game().network.get_action_id_from_movement("B", "D")
return 0
def compute_regret_policy_against_pure_policy_sim_game(game,
policy,
compute_true_value=False,
num_sample=100):
time_tick = time.time()
if compute_true_value:
expected_value_policy = expected_game_score.policy_value(
game.new_initial_state(), policy)[0]
else:
expected_value_policy = get_expected_value_sim_game(game, policy,
num_sample)
worse_regret = 0
policies = [
PathBCEResponse(game, policy, 0),
PathBCDEResponse(game, policy, 0),
PathBDEResponse(game, policy, 0)
]
for deviation_policy in policies:
if compute_true_value:
expected_value_noise = expected_game_score.policy_value(
game.new_initial_state(), deviation_policy)[0]
else:
expected_value_noise = get_expected_value_sim_game(
game, deviation_policy, num_sample, player=0)
approximate_regret = expected_value_noise - expected_value_policy
worse_regret = max(worse_regret, approximate_regret)
return worse_regret, time.time() - time_tick
def online_mirror_descent_sioux_falls(mfg_game,
number_of_iterations,
md_p=None):
nash_conv_dict = {}
md = md_p if md_p else mirror_descent.MirrorDescent(mfg_game)
tick_time = time.time()
for i in range(number_of_iterations):
md.iteration()
md_policy = md.get_policy()
nash_conv_md = nash_conv_module.NashConv(mfg_game, md_policy)
nash_conv_dict[i] = nash_conv_md.nash_conv()
print((f"Iteration {i}, Nash conv: {nash_conv_md.nash_conv()}, "
"time: {time.time() - tick_time}"))
timing = time.time() - tick_time
md_policy = md.get_policy()
distribution_mfg = distribution_module.DistributionPolicy(mfg_game, md_policy)
policy_value_ = policy_value.PolicyValue(
mfg_game, distribution_mfg, md_policy).value(mfg_game.new_initial_state())
nash_conv_md = nash_conv_module.NashConv(mfg_game, md_policy)
return timing, md_policy, nash_conv_md, policy_value_, md, nash_conv_dict
| open_spiel-master | open_spiel/data/paper_data/routing_game_experiments/utils.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit test for GamutGenerator."""
from absl import app
from absl.testing import absltest
from absl.testing import parameterized
from open_spiel.python.egt.utils import game_payoffs_array
import pyspiel
class GamutGeneratorTest(parameterized.TestCase):
def _gamut_generator(self):
return pyspiel.GamutGenerator(
"gamut.jar"
)
@parameterized.parameters(
"-g BertrandOligopoly -players 2 -actions 4 -random_params",
"-g UniformLEG-CG -players 2 -actions 4 -random_params",
"-g PolymatrixGame-SW -players 2 -actions 4 -random_params",
"-g GraphicalGame-SW -players 2 -actions 4 -random_params",
"-g BidirectionalLEG-CG -players 2 -actions 4 -random_params",
"-g CovariantGame -players 2 -actions 4 -random_params",
"-g DispersionGame -players 2 -actions 4 -random_params",
"-g MinimumEffortGame -players 2 -actions 4 -random_params",
"-g RandomGame -players 2 -actions 4 -random_params",
"-g TravelersDilemma -players 2 -actions 4 -random_params",
)
def test_generate_game(self, game_str):
generator = self._gamut_generator()
# Using a string of arguments.
game = generator.generate_game(game_str)
self.assertIsNotNone(game)
payoff_tensor = game_payoffs_array(game)
self.assertEqual(payoff_tensor.shape, (2, 4, 4))
def test_gamut_api(self):
generator = self._gamut_generator()
# See the documentation at http://gamut.stanford.edu/ for the commands
# needed to generate the various different games.
# Using a string of arguments.
game = generator.generate_game(
"-g RandomGame -players 4 -normalize -min_payoff 0 "
+ "-max_payoff 150 -actions 2 4 5 7"
)
self.assertIsNotNone(game)
# Using a list of arguments.
game = generator.generate_game([
"-g",
"RandomGame",
"-players",
"4",
"-normalize",
"-min_payoff",
"0",
"-max_payoff",
"150",
"-actions",
"2",
"4",
"5",
"7",
])
self.assertIsNotNone(game)
# Using a list of arguments.
matrix_game = generator.generate_matrix_game([
"-g",
"RandomGame",
"-players",
"2",
"-normalize",
"-min_payoff",
"0",
"-max_payoff",
"150",
"-actions",
"10",
"15",
])
self.assertIsNotNone(matrix_game)
print(matrix_game.new_initial_state())
payoff_matrix = game_payoffs_array(matrix_game)
print(payoff_matrix.shape)
print(payoff_matrix)
# Using a list of arguments.
tensor_game = generator.generate_game([
"-g",
"RandomGame",
"-players",
"4",
"-normalize",
"-min_payoff",
"0",
"-max_payoff",
"150",
"-actions",
"2",
"4",
"5",
"7",
])
self.assertIsNotNone(tensor_game)
payoff_tensor = game_payoffs_array(tensor_game)
print(payoff_tensor.shape)
def main(_):
absltest.main()
if __name__ == "__main__":
# Calling main via app.run here is necessary for internal uses.
app.run(main)
| open_spiel-master | open_spiel/games/gamut/gamut_test.py |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Configuration for Sphinx."""
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'OpenSpiel'
copyright = '2019, DeepMind Technologies Ltd' # pylint: disable=redefined-builtin
author = 'DeepMind Technologies Ltd'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = ''
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.imgmath',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'recommonmark',
'sphinx_markdown_tables',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = {
'.rst': 'restructuredtext',
'.txt': 'markdown',
'.md': 'markdown',
}
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = [
'_build', 'Thumbs.db', '.DS_Store', '*README.md',
'requirements.readthedocs.txt'
]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. The default is `alabaster`.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# See https://sphinx-rtd-theme.readthedocs.io/en/stable/configuring.html
html_theme_options = {
'collapse_navigation': False,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'open_spieldoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'open_spiel.tex', 'open\\_spiel Documentation',
'The open\\_spiel authors', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, 'open_spiel', 'open_spiel Documentation', [author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'open_spiel', 'open_spiel Documentation', author, 'open_spiel',
'One line description of project.', 'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# -- Extension configuration -------------------------------------------------
# -- Options for intersphinx extension ---------------------------------------
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
# -- Options for todo extension ----------------------------------------------
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
| open_spiel-master | docs/conf.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Setup for pip package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['six', 'absl-py', 'numpy']
EXTRA_PACKAGES = {
'tensorflow': ['tensorflow>=1.8.0'],
'tensorflow with gpu': ['tensorflow-gpu>=1.8.0'],
'sonnet': ['dm-sonnet>=1.26'],
'sonnet with gpu': ['dm-sonnet-gpu>=1.26'],
'interval_bound_propagation': ['interval_bound_propagation>=1.0'],
}
def deep_verify_test_suite():
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('deep_verify/tests',
pattern='*_test.py')
return test_suite
setup(
name='deep_verify',
version='1.0',
description='A library to verify robustness of deep neural networks.',
url='https://github.com/deepmind/deep_verify',
author='DeepMind',
author_email='[email protected]',
# Contained modules and scripts.
packages=find_packages(),
install_requires=REQUIRED_PACKAGES,
extras_require=EXTRA_PACKAGES,
platforms=['any'],
license='Apache 2.0',
test_suite='setup.deep_verify_test_suite',
)
| deep-verify-master | setup.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Verifies a pre-trained MNIST model.
Usage for pre-training and verifying:
python verify.py
Alternatively, the classifier may be pre-trained with IBP:
python interval_bound_propagation/examples/train.py
--output_dir=/tmp/ibp_model --num_steps=60001
and then verified:
python verify.py --pretrained_model_path=/tmp/ibp_model/model-60000
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from absl import flags
from absl import logging
import deep_verify
import interval_bound_propagation as ibp
import tensorflow as tf
FLAGS = flags.FLAGS
flags.DEFINE_string('dataset', 'mnist', 'Dataset (either "mnist" or "cifar10")')
flags.DEFINE_string('model', 'tiny', 'Model size')
flags.DEFINE_string('pretrained_model_path', '',
'Optional path from which to restore pre-trained model.')
flags.DEFINE_integer('pretrain_batch_size', 200, 'Batch size for pre-training.')
flags.DEFINE_integer('test_batch_size', 200, 'Batch size for nominal testing.')
flags.DEFINE_integer('pretrain_steps', 10001, 'Number of pre-training steps.')
flags.DEFINE_integer('test_every_n', 2000,
'Number of steps between testing iterations.')
flags.DEFINE_string('learning_rate', '1e-3,1e-4@5000,1e-5@7500',
'Learning rate schedule of the form: '
'initial_learning_rate[,learning:steps]*. E.g., "1e-3" or '
'"1e-3,1e-4@5000,1e-5@7500".')
flags.DEFINE_float('epsilon', .02, 'Perturbation radius.')
flags.DEFINE_integer('verification_batch_size', 100,
'Batch size for verification.')
flags.DEFINE_integer('verification_steps', 2001,
'Number of steps of dual variable optimization per batch.')
flags.DEFINE_float('dual_learning_rate', 1e-3,
'Learning rate for verification.')
def layers(model_size):
"""Returns the layer specification for a given model name."""
if model_size == 'tiny':
return (
('linear', 100),
('activation', 'relu'))
elif model_size == 'small':
return (
('conv2d', (4, 4), 16, 'VALID', 2),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 1),
('activation', 'relu'),
('linear', 100),
('activation', 'relu'))
elif model_size == 'medium':
return (
('conv2d', (3, 3), 32, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 2),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 64, 'VALID', 2),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
elif model_size == 'large':
return (
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 2),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('linear', 200),
('activation', 'relu'))
else:
raise ValueError('Unknown model: "{}"'.format(model_size))
def pretraining_graph(classifier,
data_train, train_batch_size, train_randomize_fn,
step, learning_rate):
"""Constructs the TensorFlow graph for pre-training the model."""
train_data = ibp.build_dataset(data_train, batch_size=train_batch_size,
sequential=False)
if train_randomize_fn is not None:
train_data = train_data._replace(image=train_randomize_fn(train_data.image))
train_logits = classifier(train_data.image, is_training=True)
train_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=train_data.label, logits=train_logits))
learning_rate = ibp.parse_learning_rate(step, learning_rate)
optimizer = tf.train.AdamOptimizer(learning_rate)
train_op = optimizer.minimize(train_loss, step)
return train_op, train_loss
def nominal_accuracy_graph(classifier, data_test, test_batch_size):
"""Constructs the TensorFlow graph for computing the model's accuracy."""
# Test using while loop.
test_set_size = len(data_test[0])
if test_set_size % test_batch_size != 0:
logging.warn('Test set (size %d) is not a whole number of batches '
'(size %d). Some examples at the end of the test set will be '
'skipped.', test_set_size, test_batch_size)
num_test_batches = test_set_size // test_batch_size
def cond(i, *unused_args):
return i < num_test_batches
def body(i, total_test_accuracy):
"""Compute the sum of all metrics."""
test_data = ibp.build_dataset(data_test,
batch_size=test_batch_size,
sequential=True)
test_logits = classifier(test_data.image, is_training=False)
test_correct = tf.equal(test_data.label, tf.argmax(test_logits, axis=1))
test_accuracy = tf.reduce_mean(tf.cast(test_correct, tf.float32))
return i + 1, total_test_accuracy + test_accuracy
i = tf.zeros(shape=(), dtype=tf.int32)
total_test_accuracy = tf.zeros(shape=(), dtype=tf.float32)
i, total_test_accuracy = tf.while_loop(
cond,
body,
loop_vars=[i, total_test_accuracy],
back_prop=False,
parallel_iterations=1)
total_count = tf.cast(i, tf.float32)
test_accuracy = total_test_accuracy / total_count
return test_accuracy
def verification_graph(classifier, epsilon,
data_test, test_batch_size,
learning_rate):
"""Constructs the TensorFlow graph for the verification computation."""
test_data_live = ibp.build_dataset(data_test,
batch_size=test_batch_size,
sequential=True)
tf.nest.map_structure(
lambda x: x.set_shape([test_batch_size] + x.shape[1:]), test_data_live)
test_data, get_next_batch_op = deep_verify.with_explicit_update(
test_data_live)
net_builder = ibp.VerifiableModelWrapper(classifier)
net_builder(test_data.image)
input_bounds = deep_verify.input_bounds(test_data.image, epsilon)
boundprop_method = deep_verify.NaiveBoundPropagation()
boundprop_method.propagate_bounds(net_builder, input_bounds)
verifiable_layers = deep_verify.VerifiableLayerBuilder(
net_builder).build_layers()
formulation = deep_verify.StandardDualFormulation()
grouped_layers = formulation.group_layers(verifiable_layers)
dual_verification = deep_verify.DualVerification(formulation, grouped_layers)
dual_obj = dual_verification(test_data.label,
num_batches=1, current_batch=0, margin=1.)
dual_loss = tf.reduce_mean(dual_obj)
verified_correct = tf.reduce_max(dual_obj, axis=0) < 0
verified_accuracy = tf.reduce_mean(tf.cast(verified_correct, tf.float32))
dual_optimizer = tf.train.AdamOptimizer(learning_rate)
dual_train_op = dual_optimizer.minimize(
dual_loss, var_list=dual_verification.get_variables())
get_next_batch_op = tf.group([
get_next_batch_op,
tf.variables_initializer(dual_verification.get_variables()),
tf.variables_initializer(dual_optimizer.variables())])
return get_next_batch_op, dual_train_op, verified_accuracy
def main(argv):
if len(argv) > 1:
raise app.UsageError('Too many command-line arguments.')
num_classes = 10
if FLAGS.dataset == 'mnist':
data_train, data_test = tf.keras.datasets.mnist.load_data()
else:
assert FLAGS.dataset == 'cifar10', (
'Unknown dataset "{}"'.format(FLAGS.dataset))
data_train, data_test = tf.keras.datasets.cifar10.load_data()
data_train = (data_train[0], data_train[1].flatten())
data_test = (data_test[0], data_test[1].flatten())
# Base classifier network.
original_classifier = ibp.DNN(num_classes, layers(FLAGS.model))
classifier = original_classifier
if FLAGS.dataset == 'cifar10':
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
classifier = ibp.add_image_normalization(original_classifier, mean, std)
if FLAGS.dataset == 'cifar10':
def train_randomize_fn(image):
return ibp.randomize(image, (32, 32, 3), expand_shape=(40, 40, 3),
crop_shape=(32, 32, 3), vertical_flip=True)
else:
train_randomize_fn = None
step = tf.train.get_or_create_global_step()
train_op, train_loss = pretraining_graph(
classifier,
data_train, FLAGS.pretrain_batch_size, train_randomize_fn,
step, FLAGS.learning_rate)
test_accuracy = nominal_accuracy_graph(
classifier,
data_test, FLAGS.test_batch_size)
if FLAGS.pretrained_model_path:
saver = tf.train.Saver(original_classifier.get_variables())
# Accompanying verification graph.
get_next_batch_op, dual_train_op, verified_accuracy = verification_graph(
classifier, FLAGS.epsilon,
data_test, FLAGS.verification_batch_size,
FLAGS.dual_learning_rate)
test_set_size = len(data_test[0])
if test_set_size % FLAGS.verification_batch_size != 0:
logging.warn('Test set (size %d) is not a whole number of batches '
'(size %d). Some examples at the end of the test set will be '
'skipped.', test_set_size, FLAGS.verification_batch_size)
num_batches = test_set_size // FLAGS.verification_batch_size
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
with tf.train.SingularMonitoredSession(config=tf_config) as sess:
if FLAGS.pretrained_model_path:
print('Loading pre-trained model')
saver.restore(sess._tf_sess(), # pylint: disable=protected-access,
FLAGS.pretrained_model_path)
test_accuracy_val = sess.run(test_accuracy)
print('Loaded model: Test accuracy {:.2f}%'.format(
test_accuracy_val*100))
else:
print('Pre-training')
for _ in range(FLAGS.pretrain_steps):
iteration, train_loss_val, _ = sess.run([step, train_loss, train_op])
if iteration % FLAGS.test_every_n == 0:
test_accuracy_val = sess.run(test_accuracy)
print('Step {}: Test accuracy {:.2f}% Train loss {:.4f}'.format(
iteration, test_accuracy_val*100, train_loss_val))
print('Verification')
verified_accuracy_total = 0.
for batch in range(num_batches):
sess.run(get_next_batch_op)
for iteration in range(FLAGS.verification_steps):
sess.run(dual_train_op)
if iteration % 200 == 0:
verified_accuracy_val = sess.run(verified_accuracy)
print('Batch {}: Verified accuracy {:.2f}%'.format(
batch, verified_accuracy_val*100))
verified_accuracy_total += verified_accuracy_val
print('Whole dataset: Verified accuracy {:.2f}%'.format(
(verified_accuracy_val/num_batches)*100))
if __name__ == '__main__':
app.run(main)
| deep-verify-master | examples/verify.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library to verify robustness of neural networks using dual methods.
For more details see paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src import common
from deep_verify.src.auto_verifier import NotVerifiableError
from deep_verify.src.auto_verifier import VerifiableLayerBuilder
from deep_verify.src.bounds import naive_bounds
from deep_verify.src.bounds.fastlin_bounds import FastlinBoundPropagation
from deep_verify.src.bounds.layer_bounds import BoundPropagation
from deep_verify.src.bounds.naive_bounds import input_bounds
from deep_verify.src.bounds.naive_bounds import NaiveBoundPropagation
from deep_verify.src.common import with_explicit_update
from deep_verify.src.formulations.semidefinite import gram_calcs
from deep_verify.src.formulations.semidefinite.verify_dual_semidefinite import SemidefiniteDualFormulation
from deep_verify.src.formulations.standard import standard_layer_calcs
from deep_verify.src.formulations.standard.verify_dual_standard import StandardDualFormulation
from deep_verify.src.formulations.verify_dual_base import build_dual_vars
from deep_verify.src.formulations.verify_dual_base import build_project_duals_op
from deep_verify.src.formulations.verify_dual_base import DualFormulation
from deep_verify.src.layers.layers import Activation
from deep_verify.src.layers.layers import AffineLayer
from deep_verify.src.layers.layers import AvgPool
from deep_verify.src.layers.layers import Conv
from deep_verify.src.layers.layers import CustomOp
from deep_verify.src.layers.layers import Linear
from deep_verify.src.layers.layers import MaxPool
from deep_verify.src.layers.layers import SingleVerifiableLayer
from deep_verify.src.layers.layers import VerifiableLayer
from deep_verify.src.layers.layers_combined import combine_trailing_linear_layers
from deep_verify.src.layers.layers_combined import CombinedLayer
from deep_verify.src.layers.layers_combined import CombinedLinearLayer
from deep_verify.src.specifications.target_objective_base import TargetObjective
from deep_verify.src.specifications.target_objective_standard import StandardTargetObjective
from deep_verify.src.verify_dual_direct import DualVerification
| deep-verify-master | deep_verify/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library to verify robustness of neural networks using dual methods.
For more details see paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.tests.formulations.verify_dual_base_test import add_layer
from deep_verify.tests.formulations.verify_dual_base_test import AvgPool
from deep_verify.tests.formulations.verify_dual_base_test import DualFormulationTest
| deep-verify-master | deep_verify/tests/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for `auto_verifier`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from deep_verify.src import auto_verifier
from deep_verify.src.layers import layers
import interval_bound_propagation as ibp
import sonnet as snt
import tensorflow as tf
class _BatchNorm(snt.BatchNorm):
def _build(self, input_batch):
return super(_BatchNorm, self)._build(input_batch,
is_training=False,
test_local_stats=False)
class AutoVerifierTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(AutoVerifierTest, self).setUp()
self._inputs = tf.placeholder(dtype=tf.float32, shape=(11, 28, 28, 3))
def test_empty_network(self):
module = snt.Sequential([])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertEmpty(v_layers)
def test_standalone_conv_module(self):
module = snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID')
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.Conv)
self.assertIs(module, v_layers[0].module)
self.assertIsInstance(v_layers[0].input_node, ibp.ModelInputWrapper)
self.assertIs(v_layers[0].output_node, network.output_module)
def test_flatten_and_linear(self):
linear = snt.Linear(23)
module = snt.Sequential([
snt.BatchFlatten(),
linear,
])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.Linear)
self.assertIs(linear, v_layers[0].module)
self.assertEqual([2352], v_layers[0].input_node.shape)
self.assertIs(v_layers[0].output_node, network.output_module)
def test_pointless_reshape(self):
linear = snt.Linear(23)
module = snt.Sequential([
snt.BatchFlatten(),
linear,
snt.BatchFlatten(),
])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.Linear)
self.assertIs(linear, v_layers[0].module)
self.assertEqual([2352], v_layers[0].input_node.shape)
self.assertIs(v_layers[0].output_node, network.output_module)
def test_unrecognised_calculation_rejected(self):
class InvalidModule(snt.AbstractModule):
def _build(self, inputs):
module = snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID')
return module(2 * inputs)
module = InvalidModule()
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
with self.assertRaises(auto_verifier.NotVerifiableError):
_ = auto_verifier.VerifiableLayerBuilder(network).build_layers()
def test_unrecognised_trailing_calculation_rejected(self):
class InvalidModule(snt.AbstractModule):
def _build(self, inputs):
module = snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID')
return 2 * module(inputs)
module = InvalidModule()
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
with self.assertRaises(auto_verifier.NotVerifiableError):
_ = auto_verifier.VerifiableLayerBuilder(network).build_layers()
@parameterized.named_parameters(('relu', tf.nn.relu),
('sig', tf.nn.sigmoid),
('tanh', tf.nn.tanh),
('elu', tf.nn.elu))
def test_stack_with_snt_activation(self, activation_fn):
conv = snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID')
linear = snt.Linear(23)
module = snt.Sequential([
conv,
snt.Module(activation_fn),
snt.BatchFlatten(),
linear,
])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 3)
self.assertIsInstance(v_layers[0], layers.Conv)
self.assertIs(conv, v_layers[0].module)
self.assertIsInstance(v_layers[0].input_node, ibp.ModelInputWrapper)
self.assertIsInstance(v_layers[1], layers.Activation)
self.assertEqual(activation_fn.__name__, v_layers[1].activation)
self.assertIs(v_layers[0].output_node, v_layers[1].input_node)
self.assertIsInstance(v_layers[2], layers.Linear)
self.assertIs(linear, v_layers[2].module)
self.assertIs(v_layers[2].output_node, network.output_module)
@parameterized.named_parameters(('relu', tf.nn.relu),
('sig', tf.nn.sigmoid),
('tanh', tf.nn.tanh),
('elu', tf.nn.elu),)
def test_stack_with_tf_activation(self, activation_fn):
conv = snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID')
linear = snt.Linear(23)
module = snt.Sequential([
conv,
activation_fn,
snt.BatchFlatten(),
linear
])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 3)
self.assertIsInstance(v_layers[0], layers.Conv)
self.assertIs(conv, v_layers[0].module)
self.assertIsInstance(v_layers[0].input_node, ibp.ModelInputWrapper)
self.assertIsInstance(v_layers[1], layers.Activation)
self.assertEqual(activation_fn.__name__, v_layers[1].activation)
self.assertIs(v_layers[0].output_node, v_layers[1].input_node)
self.assertIsInstance(v_layers[2], layers.Linear)
self.assertIs(linear, v_layers[2].module)
self.assertIs(v_layers[2].output_node, network.output_module)
def test_batchnorm(self):
conv = snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID')
batchnorm = _BatchNorm()
module = snt.Sequential([
conv,
batchnorm,
])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.Conv)
self.assertIs(conv, v_layers[0].module)
self.assertIs(batchnorm, v_layers[0].batch_norm)
self.assertIsInstance(v_layers[0].input_node, ibp.ModelInputWrapper)
self.assertIs(v_layers[0].output_node, network.output_module)
def test_consecutive_batchnorm_rejected(self):
module = snt.Sequential([
snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID'),
_BatchNorm(),
_BatchNorm(),
])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
with self.assertRaises(auto_verifier.NotVerifiableError):
_ = auto_verifier.VerifiableLayerBuilder(network).build_layers()
def test_leading_batchnorm_rejected(self):
module = snt.Sequential([
_BatchNorm(),
snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID'),
])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
with self.assertRaises(auto_verifier.NotVerifiableError):
_ = auto_verifier.VerifiableLayerBuilder(network).build_layers()
def test_tolerates_identity(self):
conv = snt.Conv2D(output_channels=5, kernel_shape=3, padding='VALID')
linear = snt.Linear(23)
module = snt.Sequential([
tf.identity,
conv,
tf.identity,
tf.nn.relu,
tf.identity,
snt.BatchFlatten(),
tf.identity,
linear,
tf.identity,
])
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 3)
self.assertIsInstance(v_layers[0], layers.Conv)
self.assertIs(conv, v_layers[0].module)
self.assertIsInstance(v_layers[1], layers.Activation)
self.assertEqual('relu', v_layers[1].activation)
self.assertIsInstance(v_layers[2], layers.Linear)
self.assertIs(linear, v_layers[2].module)
def test_leaky_relu(self):
module = lambda x: tf.nn.leaky_relu(x, alpha=0.3)
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.Activation)
self.assertEqual('leaky_relu', v_layers[0].activation)
self.assertLen(v_layers[0].parameters, 1)
self.assertAllClose(0.3, v_layers[0].parameters['alpha'])
def test_avgpool(self):
def module(inputs):
return tf.nn.avg_pool(inputs, ksize=(3, 3),
padding='VALID', strides=(2, 2))
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.AvgPool)
self.assertEqual([3, 3], v_layers[0].kernel_shape)
self.assertEqual([2, 2], v_layers[0].strides)
def test_avgpool_global(self):
def module(inputs):
return tf.reduce_mean(inputs, axis=(1, 2))
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.AvgPool)
self.assertIs(None, v_layers[0].kernel_shape)
@parameterized.named_parameters(('plain', False),
('relu', True))
def test_maxpool(self, with_relu):
def module(inputs):
outputs = tf.nn.max_pool(inputs, ksize=(3, 3),
padding='VALID', strides=(2, 2))
if with_relu:
outputs = tf.nn.relu(outputs)
return outputs
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.MaxPool)
self.assertEqual([3, 3], v_layers[0].kernel_shape)
self.assertEqual([2, 2], v_layers[0].strides)
self.assertEqual(with_relu, v_layers[0].with_relu)
@parameterized.named_parameters(('plain', False),
('relu', True))
def test_maxpool_global(self, with_relu):
def module(inputs):
outputs = tf.reduce_max(inputs, axis=(1, 2))
if with_relu:
outputs = tf.nn.relu(outputs)
return outputs
network = ibp.VerifiableModelWrapper(module)
network(self._inputs)
v_layers = auto_verifier.VerifiableLayerBuilder(network).build_layers()
self.assertLen(v_layers, 1)
self.assertIsInstance(v_layers[0], layers.MaxPool)
self.assertIs(None, v_layers[0].kernel_shape)
self.assertEqual(with_relu, v_layers[0].with_relu)
if __name__ == '__main__':
tf.test.main()
| deep-verify-master | deep_verify/tests/auto_verifier_test.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Base test class for different verification strategies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
from absl.testing import parameterized
from deep_verify.src import auto_verifier
from deep_verify.src.bounds import naive_bounds
import interval_bound_propagation as ibp
import sonnet as snt
import tensorflow as tf
ImageLabel = collections.namedtuple('ImageLabel', ('image', 'label'))
class _TestNet(snt.AbstractModule):
def __init__(self, num_classes, build_fn):
super(_TestNet, self).__init__()
self._num_classes = num_classes
self._build_fn = build_fn
@property
def output_size(self):
return self._num_classes
def _build(self, image_batch):
input_node = ibp.ModelInputWrapper(0)
self._nodes_list = [input_node]
self._nodes = {image_batch: input_node}
self._node_inputs = {}
self._fanouts = collections.Counter()
outputs = self._build_fn(self._num_classes, self, image_batch)
self._fanouts[self._nodes[outputs]] += 1
self._outputs = outputs
return outputs
def append(self, node, outputs, *inputs):
self._nodes_list.append(node)
self._node_inputs[node] = inputs
for x in inputs:
self._fanouts[self._nodes[x]] += 1
self._nodes[outputs] = node
@property
def output_module(self):
self._ensure_is_connected()
return self._nodes[self._outputs]
def dependencies(self, node):
return [self._nodes[inputs] for inputs in self._node_inputs[node]]
@property
def modules(self):
self._ensure_is_connected()
# Omit the (virtual) network input node.
return self._nodes_list[1:]
def fanout_of(self, node):
self._ensure_is_connected()
return self._fanouts[node]
def propagate_bounds(self, input_bounds):
self._nodes_list[0].output_bounds = input_bounds
for node in self._nodes_list[1:]:
node.propagate_bounds(*[self._nodes[inputs].output_bounds
for inputs in self._node_inputs[node]])
class AvgPool(snt.AbstractModule):
"""Wraps `tf.nn.avg_pool` as a callable object with properties."""
def __init__(self, kernel_shape, strides):
"""Constructor.
No padding is supported: `tf.nn.avg_pool` is invoked with `padding='VALID'`.
Args:
kernel_shape: Integer list of `[kernel_height, kernel_width]`.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
"""
super(AvgPool, self).__init__()
self._kernel_shape = list(kernel_shape)
self._strides = list(strides)
@property
def kernel_shape(self):
return self._kernel_shape
@property
def padding(self):
return 'VALID' # No padding is supported.
@property
def strides(self):
return self._strides
def _build(self, value):
return tf.nn.avg_pool(value,
ksize=([1] + self._kernel_shape + [1]),
padding=self.padding,
strides=([1] + self._strides + [1]))
def add_layer(net, module, inputs, flatten=False, batch_norm=None):
if flatten:
reshape_module = snt.BatchFlatten()
outputs = reshape_module(inputs)
net.append(ibp.BatchReshapeWrapper(reshape_module,
outputs.shape[1:].as_list()),
outputs, inputs)
inputs = outputs
outputs = module(inputs)
if isinstance(module, AvgPool):
module.__name__ = 'avg_pool'
parameters = {'ksize': [1] + module.kernel_shape + [1],
'padding': module.padding,
'strides': [1] + module.strides + [1]}
net.append(ibp.IncreasingMonotonicWrapper(module, **parameters),
outputs, inputs)
elif isinstance(module, snt.Conv2D):
net.append(ibp.LinearConv2dWrapper(module), outputs, inputs)
elif isinstance(module, snt.Conv1D):
net.append(ibp.LinearConv1dWrapper(module), outputs, inputs)
elif isinstance(module, snt.Linear):
net.append(ibp.LinearFCWrapper(module), outputs, inputs)
else:
net.append(ibp.IncreasingMonotonicWrapper(module), outputs, inputs)
if batch_norm is not None:
inputs = outputs
outputs = batch_norm(inputs,
is_training=False, test_local_stats=False)
net.append(ibp.BatchNormWrapper(batch_norm), outputs, inputs)
return outputs
_inits = {'initializers': {'b': tf.truncated_normal_initializer()}}
_bn_inits = {'initializers': {
'beta': tf.truncated_normal_initializer(),
'gamma': tf.constant_initializer(0.7)
}}
def _linear_script(num_classes, net, layer_values):
layer_values = add_layer(net, snt.Linear(13, **_inits), layer_values,
flatten=True)
layer_values = add_layer(net, tf.nn.relu, layer_values)
layer_values = add_layer(net, snt.Linear(num_classes,
**_inits), layer_values)
return layer_values
def _conv_script(num_classes, net, layer_values):
layer_values = add_layer(net, snt.Conv2D(3, kernel_shape=(2, 2),
padding='VALID',
**_inits), layer_values)
layer_values = add_layer(net, tf.nn.relu, layer_values)
layer_values = add_layer(net, snt.Linear(11, **_inits), layer_values,
flatten=True)
layer_values = add_layer(net, tf.nn.relu, layer_values)
layer_values = add_layer(net, snt.Linear(num_classes,
**_inits), layer_values)
return layer_values
def _conv_batchnorm_script(num_classes, net, layer_values):
layer_values = add_layer(net, snt.Conv2D(3, kernel_shape=(2, 2),
padding='VALID',
use_bias=False
), layer_values,
batch_norm=snt.BatchNorm(scale=True, **_bn_inits))
layer_values = add_layer(net, tf.nn.relu, layer_values)
layer_values = add_layer(net, snt.Linear(11, use_bias=False
), layer_values,
flatten=True,
batch_norm=snt.BatchNorm(scale=True, **_bn_inits))
layer_values = add_layer(net, tf.nn.relu, layer_values)
layer_values = add_layer(net, snt.Linear(num_classes,
**_inits), layer_values)
return layer_values
def _avgpool_script(num_classes, net, layer_values):
layer_values = add_layer(net, snt.Conv2D(3, kernel_shape=(2, 2),
**_inits), layer_values)
layer_values = add_layer(net, tf.nn.relu, layer_values)
layer_values = add_layer(net, AvgPool(
kernel_shape=(2, 2), strides=(1, 1)), layer_values)
layer_values = add_layer(net, tf.nn.relu, layer_values)
layer_values = add_layer(net, snt.Linear(num_classes,
**_inits), layer_values,
flatten=True)
return layer_values
def _avgpool_linear_script(num_classes, net, layer_values):
layer_values = add_layer(net, snt.Conv2D(3, kernel_shape=(2, 2),
**_inits), layer_values)
layer_values = add_layer(net, tf.nn.relu, layer_values)
layer_values = add_layer(net, AvgPool(
kernel_shape=(2, 2), strides=(1, 1)), layer_values)
layer_values = add_layer(net, snt.Linear(num_classes,
**_inits), layer_values,
flatten=True)
return layer_values
class DualFormulationTest(tf.test.TestCase, parameterized.TestCase):
@abc.abstractmethod
def _verification_strategy(self):
pass
def _num_classes(self):
return 3
def _batch_size(self):
return 3
def _image_data(self):
image = tf.random_uniform(shape=(self._batch_size(), 5, 3, 2),
dtype=tf.float32)
label = tf.random_uniform((self._batch_size(),),
maxval=self._num_classes(),
dtype=tf.int64)
return ImageLabel(image=image, label=label)
def _network(self, model):
return _TestNet(self._num_classes(), self._script_fn(model))
def _script_fn(self, model):
return globals()['_' + model + '_script']
def _verifiable_layer_builder(self, net):
return auto_verifier.VerifiableLayerBuilder(net)
def _apply_verification(self, model, objective_computation_config=None):
image_data = self._image_data()
net = self._network(model)
net(image_data.image)
# Bound propagation is performed on the graph representation.
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
boundprop_method = naive_bounds.NaiveBoundPropagation()
boundprop_method.propagate_bounds(net, input_bounds)
net_layers = self._verifiable_layer_builder(net).build_layers()
grouped_layers = self._verification_strategy().group_layers(net_layers)
dual_obj, _, project_duals_op, supporting_ops = (
self._verification_strategy().create_duals_and_build_objective(
grouped_layers,
image_data.label,
tf.get_variable,
objective_computation_config=objective_computation_config))
self.assertEqual((self._num_classes(), self._batch_size()),
tuple(dual_obj.shape.as_list()))
# Smoke test: ensure that the verification calculation can run.
init_op = tf.global_variables_initializer()
with self.test_session() as session:
session.run(init_op)
session.run(supporting_ops['init'])
session.run(project_duals_op)
session.run(dual_obj)
def _build_objective(self, net, input_bounds, labels,
boundprop_method=naive_bounds.NaiveBoundPropagation()):
"""Invokes the verification formulation for the given network.
Args:
net: `_TestNet` specifying network graph.
input_bounds: Bounds for the network inputs.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
boundprop_method: Specifies the method used to propagate bounds.
Returns:
dual_obj: 2D tensor of shape (num_classes, batch_size) containing
dual objective values for each (class, example).
dual_var_lists: Nested list of 3D tensors of shape
(num_classes, batch_size, layer_size) and 5D tensors of shape
(num_classes, batch_size, height, width, channels)
containing Lagrange multipliers for the layers' calculations.
This has the same length as `verifiable_layers`, and typically each
entry is a singleton list with the dual variable for that layer.
ResNet blocks' entries have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
"""
net(input_bounds.nominal) # Connect the network to the graph.
boundprop_method.propagate_bounds(net, input_bounds)
net_layers = self._verifiable_layer_builder(net).build_layers()
grouped_layers = self._verification_strategy().group_layers(net_layers)
dual_obj, dual_var_lists, _, _ = (
self._verification_strategy().create_duals_and_build_objective(
grouped_layers, labels, tf.get_variable, margin=1.))
return dual_obj, dual_var_lists
def _expected_input_bounds(self, input_data, delta):
return tf.maximum(input_data-delta, 0.), tf.minimum(input_data+delta, 1.)
def _assert_dual_objective_close(self, expected_objective,
dual_obj, image_data):
neq = tf.not_equal(
tf.expand_dims(tf.range(self._num_classes(), dtype=tf.int64), axis=1),
image_data.label)
expected_objective = tf.where(neq, expected_objective,
-tf.ones_like(expected_objective))
init_op = tf.global_variables_initializer()
with self.test_session() as session:
session.run(init_op)
expected_objective_val, dual_obj_val = session.run([expected_objective,
dual_obj])
tol = 1e-6
self.assertAllClose(expected_objective_val, dual_obj_val,
atol=tol, rtol=tol)
| deep-verify-master | deep_verify/tests/formulations/verify_dual_base_test.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test template for dual formulations.
`verify_dual_base_test.DualFormulationTest` provides a base test case, which
may be sub-classed to allow new formulations to be tested against standard
network architectures.
For more details see paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| deep-verify-master | deep_verify/tests/formulations/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for semidefinite formulation of dual verification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from deep_verify.src.formulations.semidefinite import verify_dual_semidefinite
from deep_verify.tests.formulations import verify_dual_base_test
import tensorflow as tf
class SemidefiniteDualFormulationTest(
verify_dual_base_test.DualFormulationTest):
def _verification_strategy(self):
return verify_dual_semidefinite.SemidefiniteDualFormulation()
@parameterized.named_parameters(('linear', 'linear'),
('conv', 'conv'))
def test_semidefinite(self, model):
self._apply_verification(model)
@parameterized.named_parameters(('linear', 'linear'),
('conv', 'conv'))
def test_semidefinite_weak(self, model):
self._apply_verification(model, {'verify_option': 'weak'})
@parameterized.named_parameters(('linear', 'linear'),
('conv', 'conv'))
def test_semidefinite_strong(self, model):
self._apply_verification(model, {'verify_option': 'strong'})
@parameterized.named_parameters(('linear', 'linear'),
('conv', 'conv'))
def test_semidefinite_strong_approx(self, model):
self._apply_verification(model, {'verify_option': 'strong_approx'})
if __name__ == '__main__':
tf.test.main()
| deep-verify-master | deep_verify/tests/formulations/semidefinite/verify_dual_semidefinite_test.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for Gram matrix computations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from deep_verify.src.formulations.semidefinite import gram_calcs
from interval_bound_propagation import layer_utils
import sonnet as snt
import tensorflow as tf
def conv_weighted_gram_abs_projection_slow(w, d, beta, padding, strides):
"""Calculates a projection of | W^T d W | for an N-D convolution W.
Computes beta_i^{-1} sum_j |Q_ij| beta_j where Q = W^T d W is the
weighted Gram matrix for the convolution.
The convolution exploits sparsity of the convolution, thereby managing
to run in O(K^2 M C^3 + K^3 M C^2) time per example, for C channels,
spatial size M, and kernel size K. By comparison, working with
a fully materialised MCxMC matrix would require O(M^3 C^3) time.
Args:
w: (N+2)D tensor of shape (kernel_height, kernel_width,
input_channels, output_channels) containing the convolutional kernel.
d: (N+3)D tensor of shape (num_targets, batch_size,
output_height, output_width, output_channels), interpreted as a
diagonal weight matrix.
beta: (N+3)D tensor of shape (num_targets, batch_size,
input_height, input_width, input_channels) specifying the projection.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
Returns:
(N+3)D tensor of shape (num_targets, batch_size,
input_height, input_width, input_channels) containing | W^T d W | beta.
"""
input_shape = beta.shape[2:].as_list()
flatten = snt.BatchFlatten(preserve_dims=2)
unflatten = snt.BatchReshape(input_shape, preserve_dims=2)
w_lin, _ = layer_utils.materialise_conv(w, None, input_shape,
padding, strides)
return unflatten(linear_weighted_gram_abs_projection_slow(w_lin,
flatten(d),
flatten(beta)))
def linear_weighted_gram_abs_projection_slow(w, d, beta):
"""Calculates a projection of | W^T d W | for a fully connected matrix W.
Computes beta_i^{-1} sum_j |Q_ij| beta_j where Q = W^T d W is the
weighted Gram matrix.
Args:
w: 2D tensor of shape (input_size, output_size) containing the matrix.
d: 3D tensor of shape (num_targets, batch_size, output_size),
interpreted as a diagonal weight matrix.
beta: 3D tensor of shape (num_targets, batch_size, input_size)
specifying the projection.
Returns:
3D tensor of shape (num_targets, batch_size, input_size)
containing | W^T d W | beta.
"""
q = tf.einsum('cnio,cnjo->cnij',
w * tf.expand_dims(d, axis=2),
w * tf.expand_dims(beta, axis=3))
return tf.reduce_sum(tf.abs(q), axis=3) / beta
class GramCalcsTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
('SAME_32', 11, 3, 11, 'SAME', [1], tf.float32, 1.e-5),
('SAME', 17, 3, 17, 'SAME', [1]),
('SAME_even', 17, 2, 17, 'SAME', [1]),
('SAME_strided', 17, 4, 9, 'SAME', [2]),
('SAME_blocked', 11, 3, 11, 'SAME', [1], tf.float32, 1.e-5, 4),
('VALID_32', 11, 3, 9, 'VALID', [1], tf.float32, 1.e-5),
('VALID', 17, 3, 15, 'VALID', [1]),
('VALID_even', 17, 2, 16, 'VALID', [1]),
('VALID_strided', 17, 4, 7, 'VALID', [2]))
def test_conv1d_weighted_gram(self, input_size, kernel_size, output_size,
padding, strides,
dtype=tf.float64, atol=1.e-9, block_size=0):
num_targets = 3
batch_size = 2
input_channels = 13
output_channels = 11
w = tf.random_normal(dtype=dtype,
shape=[kernel_size,
input_channels, output_channels])
d = tf.random_gamma(alpha=1, dtype=dtype,
shape=[num_targets, batch_size,
output_size, output_channels])
beta = tf.random_gamma(alpha=1, dtype=dtype,
shape=[num_targets, batch_size,
input_size, input_channels])
proj = gram_calcs.conv_weighted_gram_abs_projection(w, d, beta,
padding, strides,
block_size=block_size)
proj_slow = conv_weighted_gram_abs_projection_slow(w, d, beta,
padding, strides)
with tf.Session() as session:
proj_val, proj_slow_val = session.run((proj, proj_slow))
self.assertAllClose(proj_val, proj_slow_val, atol=atol)
@parameterized.named_parameters(
('SAME_32', (7, 11), (3, 3), (7, 11), 'SAME', [1, 1], tf.float32, 1.e-5),
('SAME', (7, 17), (3, 3), (7, 17), 'SAME', [1, 1]),
('SAME_even', (7, 17), (2, 2), (7, 17), 'SAME', [1, 1]),
('SAME_strided', (7, 17), (3, 4), (4, 9), 'SAME', [2, 2]),
('SAME_blocked', (7, 11), (3, 3), (7, 11), 'SAME', [1, 1],
tf.float32, 1.e-5, 4),
('VALID_32', (7, 11), (3, 3), (5, 9), 'VALID', [1, 1], tf.float32, 1.e-5),
('VALID', (7, 17), (3, 3), (5, 15), 'VALID', [1, 1]),
('VALID_even', (7, 17), (2, 2), (6, 16), 'VALID', [1, 1]),
('VALID_strided', (7, 17), (3, 4), (3, 7), 'VALID', [2, 2]))
def test_conv2d_weighted_gram(self, input_size, kernel_size, output_size,
padding, strides,
dtype=tf.float64, atol=1.e-9, block_size=0):
num_targets = 3
batch_size = 2
input_height, input_width = input_size
kernel_height, kernel_width = kernel_size
input_channels = 13
output_height, output_width = output_size
output_channels = 11
w = tf.random_normal(dtype=dtype,
shape=[kernel_height, kernel_width,
input_channels, output_channels])
d = tf.random_gamma(alpha=1, dtype=dtype,
shape=[num_targets, batch_size,
output_height, output_width, output_channels])
beta = tf.random_gamma(alpha=1, dtype=dtype,
shape=[num_targets, batch_size,
input_height, input_width, input_channels])
proj = gram_calcs.conv_weighted_gram_abs_projection(w, d, beta,
padding, strides,
block_size=block_size)
proj_slow = conv_weighted_gram_abs_projection_slow(w, d, beta,
padding, strides)
with tf.Session() as session:
proj_val, proj_slow_val = session.run((proj, proj_slow))
self.assertAllClose(proj_val, proj_slow_val, atol=atol)
@parameterized.named_parameters(
('small_32', 7, 4, tf.float32, 1.e-5),
('small', 7, 4),
('large', 11, 13),
('large_blocked', 11, 13, tf.float32, 1.e-5, 3))
def test_linear_weighted_gram(self, input_size, output_size,
dtype=tf.float64, atol=1.e-9, block_size=0):
num_targets = 5
batch_size = 3
w = tf.random_normal(dtype=dtype, shape=[input_size, output_size])
d = tf.random_gamma(alpha=1, dtype=dtype,
shape=[num_targets, batch_size, output_size])
beta = tf.random_gamma(alpha=1, dtype=dtype,
shape=[num_targets, batch_size, input_size])
proj = gram_calcs.linear_weighted_gram_abs_projection(w, d, beta,
block_size=block_size)
proj_slow = linear_weighted_gram_abs_projection_slow(w, d, beta)
with tf.Session() as session:
proj_val, proj_slow_val = session.run((proj, proj_slow))
self.assertAllClose(proj_val, proj_slow_val, atol=atol)
if __name__ == '__main__':
tf.test.main()
| deep-verify-master | deep_verify/tests/formulations/semidefinite/gram_calcs_test.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for reduced formulation of dual verification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from deep_verify.src import common
from deep_verify.src.bounds import naive_bounds
from deep_verify.src.formulations.standard import standard_layer_calcs
from deep_verify.src.formulations.standard import verify_dual_standard
from deep_verify.tests.formulations import verify_dual_base_test
import interval_bound_propagation as ibp
from interval_bound_propagation import layer_utils
import sonnet as snt
import tensorflow as tf
class VerifyDualReducedTest(verify_dual_base_test.DualFormulationTest):
def _verification_strategy(self):
return verify_dual_standard.StandardDualFormulation(use_reduced=True)
@parameterized.named_parameters(('linear', 'linear'),
('conv', 'conv'),
('conv_batchnorm', 'conv_batchnorm'),
('avgpool', 'avgpool'),
('avgpool_linear', 'avgpool_linear'))
def test_run(self, model):
self._apply_verification(model)
def test_calc_linear(self):
image_data = self._image_data()
net = self._network('linear')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(linear_0,
relu_1, # pylint:disable=unused-variable
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), _ = dual_var_lists
# Expected input bounds for each layer.
linear_0_lb, linear_0_ub = self._expected_input_bounds(image_data.image, .1)
linear_0_lb = snt.BatchFlatten()(linear_0_lb)
linear_0_ub = snt.BatchFlatten()(linear_0_ub)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
linear_0_lb, linear_0_ub).apply_linear(
None, linear_0.module.w, linear_0.module.b)
# Expected objective value.
objective = 0
act_coeffs_0 = -tf.tensordot(mu_0, tf.transpose(linear_0.module.w), axes=1)
obj_0 = -tf.tensordot(mu_0, linear_0.module.b, axes=1)
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, linear_0_lb, linear_0_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, -objective_w,
relu_1_lb, relu_1_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
def test_calc_conv(self):
image_data = self._image_data()
net = self._network('conv')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(conv2d_0,
relu_1,
linear_2,
relu_3, # pylint:disable=unused-variable
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), (mu_2,), _ = dual_var_lists
# Expected input bounds for each layer.
conv2d_0_lb, conv2d_0_ub = self._expected_input_bounds(image_data.image, .1)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
conv2d_0_lb, conv2d_0_ub).apply_conv2d(
None, conv2d_0.module.w, conv2d_0.module.b, 'VALID', (1, 1))
linear_2_lb = snt.BatchFlatten()(tf.nn.relu(relu_1_lb))
linear_2_ub = snt.BatchFlatten()(tf.nn.relu(relu_1_ub))
relu_3_lb, relu_3_ub = ibp.IntervalBounds(
linear_2_lb, linear_2_ub).apply_linear(
None, linear_2.module.w, linear_2.module.b)
# Expected objective value.
objective = 0
act_coeffs_0 = -common.conv_transpose(mu_0, conv2d_0.module.w,
conv2d_0.input_shape,
'VALID', (1, 1))
obj_0 = -tf.reduce_sum(mu_0 * conv2d_0.module.b, axis=(2, 3, 4))
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, conv2d_0_lb, conv2d_0_ub)
act_coeffs_2 = -tf.tensordot(mu_2, tf.transpose(linear_2.module.w), axes=1)
objective += -tf.tensordot(mu_2, linear_2.module.b, axes=1)
lam_1 = tf.reshape(-act_coeffs_2,
[self._num_classes(), self._batch_size()] +
relu_1.output_shape)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, lam_1,
relu_1_lb, relu_1_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_2, -objective_w,
relu_3_lb, relu_3_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
def test_calc_conv_batchnorm(self):
image_data = self._image_data()
net = self._network('conv_batchnorm')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(conv2d_0,
relu_1,
linear_2,
relu_3, # pylint:disable=unused-variable
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), (mu_2,), _ = dual_var_lists
# Expected input bounds for each layer.
conv2d_0_lb, conv2d_0_ub = self._expected_input_bounds(image_data.image, .1)
conv2d_0_w, conv2d_0_b = layer_utils.combine_with_batchnorm(
conv2d_0.module.w, None, conv2d_0.batch_norm)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
conv2d_0_lb, conv2d_0_ub).apply_conv2d(
None, conv2d_0_w, conv2d_0_b, 'VALID', (1, 1))
linear_2_lb = snt.BatchFlatten()(tf.nn.relu(relu_1_lb))
linear_2_ub = snt.BatchFlatten()(tf.nn.relu(relu_1_ub))
linear_2_w, linear_2_b = layer_utils.combine_with_batchnorm(
linear_2.module.w, None, linear_2.batch_norm)
relu_3_lb, relu_3_ub = ibp.IntervalBounds(
linear_2_lb, linear_2_ub).apply_linear(
None, linear_2_w, linear_2_b)
# Expected objective value.
objective = 0
act_coeffs_0 = -common.conv_transpose(mu_0, conv2d_0_w,
conv2d_0.input_shape,
'VALID', (1, 1))
obj_0 = -tf.reduce_sum(mu_0 * conv2d_0_b, axis=(2, 3, 4))
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, conv2d_0_lb, conv2d_0_ub)
act_coeffs_2 = -tf.tensordot(mu_2, tf.transpose(linear_2_w), axes=1)
objective += -tf.tensordot(mu_2, linear_2_b, axes=1)
lam_1 = tf.reshape(-act_coeffs_2,
[self._num_classes(), self._batch_size()] +
relu_1.output_shape)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, lam_1,
relu_1_lb, relu_1_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_2, -objective_w,
relu_3_lb, relu_3_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
def test_calc_avgpool(self):
image_data = self._image_data()
net = self._network('avgpool')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(conv2d_0,
relu_1,
avgpool_2,
relu_3, # pylint:disable=unused-variable
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), (mu_2,), _ = dual_var_lists
# Expected input bounds for each layer.
conv2d_0_lb, conv2d_0_ub = self._expected_input_bounds(image_data.image, .1)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
conv2d_0_lb, conv2d_0_ub).apply_conv2d(
None, conv2d_0.module.w, conv2d_0.module.b, 'SAME', (1, 1))
avgpool_2_lb = tf.nn.relu(relu_1_lb)
avgpool_2_ub = tf.nn.relu(relu_1_ub)
relu_3_lb = tf.nn.avg_pool(avgpool_2_lb, ksize=[2, 2],
padding='VALID', strides=(1, 1))
relu_3_ub = tf.nn.avg_pool(avgpool_2_ub, ksize=[2, 2],
padding='VALID', strides=(1, 1))
# Expected objective value.
objective = 0
act_coeffs_0 = -common.conv_transpose(mu_0, conv2d_0.module.w,
conv2d_0.input_shape,
'SAME', (1, 1))
obj_0 = -tf.reduce_sum(mu_0 * conv2d_0.module.b, axis=(2, 3, 4))
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, conv2d_0_lb, conv2d_0_ub)
act_coeffs_2 = -common.avgpool_transpose(
mu_2, result_shape=relu_1.output_shape,
kernel_shape=(2, 2), strides=(1, 1))
lam_1 = -act_coeffs_2
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, lam_1,
relu_1_lb, relu_1_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
shaped_objective_w = tf.reshape(objective_w,
[self._num_classes(), self._batch_size()] +
avgpool_2.output_shape)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_2, -shaped_objective_w,
relu_3_lb, relu_3_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
def test_calc_avgpool_linear(self):
image_data = self._image_data()
net = self._network('avgpool_linear')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(conv2d_0,
relu_1,
avgpool_2,
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), _ = dual_var_lists
# Expected input bounds for each layer.
conv2d_0_lb, conv2d_0_ub = self._expected_input_bounds(image_data.image, .1)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
conv2d_0_lb, conv2d_0_ub).apply_conv2d(
None, conv2d_0.module.w, conv2d_0.module.b, 'SAME', (1, 1))
# Expected objective value.
objective = 0
act_coeffs_0 = -common.conv_transpose(mu_0, conv2d_0.module.w,
conv2d_0.input_shape,
'SAME', (1, 1))
obj_0 = -tf.reduce_sum(mu_0 * conv2d_0.module.b, axis=(2, 3, 4))
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, conv2d_0_lb, conv2d_0_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
combined_objective_w = common.avgpool_transpose(
tf.reshape(objective_w,
[self._num_classes(), self._batch_size()] +
avgpool_2.output_shape),
relu_1.output_shape,
kernel_shape=(2, 2), strides=(1, 1))
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, -combined_objective_w,
relu_1_lb, relu_1_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
if __name__ == '__main__':
tf.test.main()
| deep-verify-master | deep_verify/tests/formulations/standard/verify_dual_reduced_test.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for dual verification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from deep_verify.src import common
from deep_verify.src.bounds import naive_bounds
from deep_verify.src.formulations.standard import standard_layer_calcs
from deep_verify.src.formulations.standard import verify_dual_standard
from deep_verify.tests.formulations import verify_dual_base_test
import interval_bound_propagation as ibp
from interval_bound_propagation import layer_utils
import sonnet as snt
import tensorflow as tf
class VerifyDualStandardTest(verify_dual_base_test.DualFormulationTest):
def _verification_strategy(self):
return verify_dual_standard.StandardDualFormulation(use_reduced=False)
@parameterized.named_parameters(('linear', 'linear'),
('conv', 'conv'),
('conv_batchnorm', 'conv_batchnorm'),
('avgpool', 'avgpool'),
('avgpool_linear', 'avgpool_linear'))
def test_run(self, model):
self._apply_verification(model)
def test_calc_linear(self):
image_data = self._image_data()
net = self._network('linear')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(linear_0,
relu_1, # pylint:disable=unused-variable
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), _ = dual_var_lists
# Expected input bounds for each layer.
linear_0_lb, linear_0_ub = self._expected_input_bounds(image_data.image, .1)
linear_0_lb = snt.BatchFlatten()(linear_0_lb)
linear_0_ub = snt.BatchFlatten()(linear_0_ub)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
linear_0_lb, linear_0_ub).apply_linear(
None, linear_0.module.w, linear_0.module.b)
# Expected objective value.
objective = 0
act_coeffs_0 = -tf.tensordot(mu_0, tf.transpose(linear_0.module.w), axes=1)
obj_0 = -tf.tensordot(mu_0, linear_0.module.b, axes=1)
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, linear_0_lb, linear_0_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, -objective_w,
relu_1_lb, relu_1_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
def test_calc_conv(self):
image_data = self._image_data()
net = self._network('conv')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(conv2d_0,
relu_1, # pylint:disable=unused-variable
linear_2,
relu_3, # pylint:disable=unused-variable
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), (lam_1,), (mu_2,), _ = dual_var_lists
# Expected input bounds for each layer.
conv2d_0_lb, conv2d_0_ub = self._expected_input_bounds(image_data.image, .1)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
conv2d_0_lb, conv2d_0_ub).apply_conv2d(
None, conv2d_0.module.w, conv2d_0.module.b, 'VALID', (1, 1))
linear_2_lb = snt.BatchFlatten()(tf.nn.relu(relu_1_lb))
linear_2_ub = snt.BatchFlatten()(tf.nn.relu(relu_1_ub))
relu_3_lb, relu_3_ub = ibp.IntervalBounds(
linear_2_lb, linear_2_ub).apply_linear(
None, linear_2.module.w, linear_2.module.b)
# Expected objective value.
objective = 0
act_coeffs_0 = -common.conv_transpose(mu_0, conv2d_0.module.w,
conv2d_0.input_shape,
'VALID', (1, 1))
obj_0 = -tf.reduce_sum(mu_0 * conv2d_0.module.b, axis=(2, 3, 4))
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, conv2d_0_lb, conv2d_0_ub)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, lam_1,
relu_1_lb, relu_1_ub)
act_coeffs_2 = -tf.tensordot(mu_2, tf.transpose(linear_2.module.w), axes=1)
obj_2 = -tf.tensordot(mu_2, linear_2.module.b, axes=1)
objective += standard_layer_calcs.linear_dual_objective(
snt.BatchFlatten(preserve_dims=2)(lam_1),
act_coeffs_2, obj_2, linear_2_lb, linear_2_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_2, -objective_w,
relu_3_lb, relu_3_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
def test_calc_conv_batchnorm(self):
image_data = self._image_data()
net = self._network('conv_batchnorm')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(conv2d_0,
relu_1, # pylint:disable=unused-variable
linear_2,
relu_3, # pylint:disable=unused-variable
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), (lam_1,), (mu_2,), _ = dual_var_lists
# Expected input bounds for each layer.
conv2d_0_lb, conv2d_0_ub = self._expected_input_bounds(image_data.image, .1)
conv2d_0_w, conv2d_0_b = layer_utils.combine_with_batchnorm(
conv2d_0.module.w, None, conv2d_0.batch_norm)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
conv2d_0_lb, conv2d_0_ub).apply_conv2d(
None, conv2d_0_w, conv2d_0_b, 'VALID', (1, 1))
linear_2_lb = snt.BatchFlatten()(tf.nn.relu(relu_1_lb))
linear_2_ub = snt.BatchFlatten()(tf.nn.relu(relu_1_ub))
linear_2_w, linear_2_b = layer_utils.combine_with_batchnorm(
linear_2.module.w, None, linear_2.batch_norm)
relu_3_lb, relu_3_ub = ibp.IntervalBounds(
linear_2_lb, linear_2_ub).apply_linear(
None, linear_2_w, linear_2_b)
# Expected objective value.
objective = 0
act_coeffs_0 = -common.conv_transpose(mu_0, conv2d_0_w,
conv2d_0.input_shape,
'VALID', (1, 1))
obj_0 = -tf.reduce_sum(mu_0 * conv2d_0_b, axis=(2, 3, 4))
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, conv2d_0_lb, conv2d_0_ub)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, lam_1,
relu_1_lb, relu_1_ub)
act_coeffs_2 = -tf.tensordot(mu_2, tf.transpose(linear_2_w), axes=1)
obj_2 = -tf.tensordot(mu_2, linear_2_b, axes=1)
objective += standard_layer_calcs.linear_dual_objective(
snt.BatchFlatten(preserve_dims=2)(lam_1),
act_coeffs_2, obj_2, linear_2_lb, linear_2_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_2, -objective_w,
relu_3_lb, relu_3_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
def test_calc_avgpool(self):
image_data = self._image_data()
net = self._network('avgpool')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(conv2d_0,
relu_1, # pylint:disable=unused-variable
avgpool_2,
relu_3, # pylint:disable=unused-variable
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), (lam_1,), (mu_2,), _ = dual_var_lists
# Expected input bounds for each layer.
conv2d_0_lb, conv2d_0_ub = self._expected_input_bounds(image_data.image, .1)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
conv2d_0_lb, conv2d_0_ub).apply_conv2d(
None, conv2d_0.module.w, conv2d_0.module.b, 'SAME', (1, 1))
avgpool_2_lb = tf.nn.relu(relu_1_lb)
avgpool_2_ub = tf.nn.relu(relu_1_ub)
relu_3_lb = tf.nn.avg_pool(avgpool_2_lb, ksize=[2, 2],
padding='VALID', strides=(1, 1))
relu_3_ub = tf.nn.avg_pool(avgpool_2_ub, ksize=[2, 2],
padding='VALID', strides=(1, 1))
# Expected objective value.
objective = 0
act_coeffs_0 = -common.conv_transpose(mu_0, conv2d_0.module.w,
conv2d_0.input_shape,
'SAME', (1, 1))
obj_0 = -tf.reduce_sum(mu_0 * conv2d_0.module.b, axis=(2, 3, 4))
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, conv2d_0_lb, conv2d_0_ub)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, lam_1,
relu_1_lb, relu_1_ub)
act_coeffs_2 = -common.avgpool_transpose(
mu_2, result_shape=relu_1.output_shape,
kernel_shape=(2, 2), strides=(1, 1))
objective += standard_layer_calcs.linear_dual_objective(
lam_1, act_coeffs_2, 0., avgpool_2_lb, avgpool_2_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
shaped_objective_w = tf.reshape(objective_w,
[self._num_classes(), self._batch_size()] +
avgpool_2.output_shape)
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_2, -shaped_objective_w,
relu_3_lb, relu_3_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
def test_calc_avgpool_linear(self):
image_data = self._image_data()
net = self._network('avgpool_linear')
input_bounds = naive_bounds.input_bounds(image_data.image, delta=.1)
dual_obj, dual_var_lists = self._build_objective(net, input_bounds,
image_data.label)
# Explicitly build the expected TensorFlow graph for calculating objective.
(conv2d_0,
relu_1,
avgpool_2,
linear_obj) = self._verifiable_layer_builder(net).build_layers()
(mu_0,), _ = dual_var_lists
# Expected input bounds for each layer.
conv2d_0_lb, conv2d_0_ub = self._expected_input_bounds(image_data.image, .1)
relu_1_lb, relu_1_ub = ibp.IntervalBounds(
conv2d_0_lb, conv2d_0_ub).apply_conv2d(
None, conv2d_0.module.w, conv2d_0.module.b, 'SAME', (1, 1))
# Expected objective value.
objective = 0
act_coeffs_0 = -common.conv_transpose(mu_0, conv2d_0.module.w,
conv2d_0.input_shape,
'SAME', (1, 1))
obj_0 = -tf.reduce_sum(mu_0 * conv2d_0.module.b, axis=(2, 3, 4))
objective += standard_layer_calcs.linear_dual_objective(
None, act_coeffs_0, obj_0, conv2d_0_lb, conv2d_0_ub)
objective_w, objective_b = common.targeted_objective(
linear_obj.module.w, linear_obj.module.b, image_data.label)
combined_objective_w = common.avgpool_transpose(
tf.reshape(objective_w,
[self._num_classes(), self._batch_size()] +
avgpool_2.output_shape),
relu_1.output_shape,
kernel_shape=(2, 2), strides=(1, 1))
objective += standard_layer_calcs.activation_layer_dual_objective(
tf.nn.relu,
mu_0, -combined_objective_w,
relu_1_lb, relu_1_ub)
objective += objective_b
self._assert_dual_objective_close(objective, dual_obj, image_data)
if __name__ == '__main__':
tf.test.main()
| deep-verify-master | deep_verify/tests/formulations/standard/verify_dual_standard_test.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for dual verification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from deep_verify.src import common
from deep_verify.src.formulations.standard import standard_layer_calcs
from interval_bound_propagation import layer_utils
import numpy as np
import sonnet as snt
import tensorflow as tf
class StandardLayerCalcsTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(('float32', tf.float32),
('float64', tf.float64))
def test_linear_layer_dual_objective_shape(self, dtype):
num_classes = 3
batch_size = 11
input_size = 7
output_size = 5
w = tf.placeholder(dtype=dtype, shape=(input_size, output_size))
b = tf.placeholder(dtype=dtype, shape=(output_size,))
lam_in = tf.placeholder(dtype=dtype, shape=(
num_classes, batch_size, input_size))
mu_out = tf.placeholder(dtype=dtype, shape=(
num_classes, batch_size, output_size))
lb = tf.placeholder(dtype=dtype, shape=(batch_size, input_size))
ub = tf.placeholder(dtype=dtype, shape=(batch_size, input_size))
activation_coeffs = -tf.tensordot(mu_out, tf.transpose(w), axes=1)
dual_obj_bias = -tf.tensordot(mu_out, b, axes=1)
dual_obj = standard_layer_calcs.linear_dual_objective(
lam_in, activation_coeffs, dual_obj_bias, lb, ub)
self.assertEqual(dtype, dual_obj.dtype)
self.assertEqual((num_classes, batch_size), dual_obj.shape)
@parameterized.named_parameters(('float32', tf.float32, 1.e-6),
('float64', tf.float64, 1.e-8))
def test_linear_layer_dual_objective(self, dtype, tol):
w = tf.constant([[1.0, 2.0, 3.0], [4.0, -5.0, -6.0]], dtype=dtype)
b = tf.constant([0.1, 0.2, 0.3], dtype=dtype)
lb = tf.constant([[-1.0, -1.0]], dtype=dtype)
ub = tf.constant([[1.0, 1.0]], dtype=dtype)
lam_in = tf.constant([[[-.01, -.02]]], dtype=dtype)
mu_out = tf.constant([[[30.0, 40.0, 50.0]]], dtype=dtype)
# Activation coefficients: -.01 - 260, and -.02 + 380
activation_coeffs = -tf.tensordot(mu_out, tf.transpose(w), axes=1)
dual_obj_bias = -tf.tensordot(mu_out, b, axes=1)
dual_obj = standard_layer_calcs.linear_dual_objective(
lam_in, activation_coeffs, dual_obj_bias, lb, ub)
dual_obj_exp = np.array([[(.01 + 260.0) + (-.02 + 380.0) - 26.0]])
with self.test_session() as session:
dual_obj_act = session.run(dual_obj)
self.assertAllClose(dual_obj_exp, dual_obj_act, atol=tol, rtol=tol)
@parameterized.named_parameters(('float32', tf.float32),
('float64', tf.float64))
def test_conv2d_layer_dual_objective_shape(self, dtype):
num_classes = 6
batch_size = 23
input_height = 17
input_width = 7
kernel_height = 3
kernel_width = 4
input_channels = 3
output_channels = 5
padding = 'VALID'
strides = (2, 1)
# Output dimensions, based on convolution settings.
output_height = 8
output_width = 4
w = tf.placeholder(dtype=dtype, shape=(
kernel_height, kernel_width, input_channels, output_channels))
b = tf.placeholder(dtype=dtype, shape=(output_channels,))
lam_in = tf.placeholder(dtype=dtype, shape=(
num_classes, batch_size, input_height, input_width, input_channels))
mu_out = tf.placeholder(dtype=dtype, shape=(
num_classes, batch_size, output_height, output_width, output_channels))
lb = tf.placeholder(dtype=dtype, shape=(
batch_size, input_height, input_width, input_channels))
ub = tf.placeholder(dtype=dtype, shape=(
batch_size, input_height, input_width, input_channels))
activation_coeffs = -common.conv_transpose(mu_out, w,
lb.shape[1:].as_list(),
padding, strides)
dual_obj_bias = -tf.reduce_sum(mu_out * b, axis=(2, 3, 4))
dual_obj = standard_layer_calcs.linear_dual_objective(
lam_in, activation_coeffs, dual_obj_bias, lb, ub)
self.assertEqual(dtype, dual_obj.dtype)
self.assertEqual((num_classes, batch_size), dual_obj.shape)
@parameterized.named_parameters(('float32', tf.float32, 1.e-6),
('float64', tf.float64, 1.e-8))
def test_conv2d_layer_dual_objective(self, dtype, tol):
num_classes = 5
batch_size = 53
input_height = 17
input_width = 7
kernel_height = 3
kernel_width = 4
input_channels = 3
output_channels = 2
padding = 'VALID'
strides = (2, 1)
# Output dimensions, based on convolution settings.
output_height = 8
output_width = 4
w = tf.random_normal(dtype=dtype, shape=(
kernel_height, kernel_width, input_channels, output_channels))
b = tf.random_normal(dtype=dtype, shape=(output_channels,))
lam_in = tf.random_normal(dtype=dtype, shape=(
num_classes, batch_size, input_height, input_width, input_channels))
mu_out = tf.random_normal(dtype=dtype, shape=(
num_classes, batch_size, output_height, output_width, output_channels))
lb = tf.random_normal(dtype=dtype, shape=(
batch_size, input_height, input_width, input_channels))
ub = tf.random_normal(dtype=dtype, shape=(
batch_size, input_height, input_width, input_channels))
lb, ub = tf.minimum(lb, ub), tf.maximum(lb, ub)
activation_coeffs = -common.conv_transpose(mu_out, w,
lb.shape[1:].as_list(),
padding, strides)
dual_obj_bias = -tf.reduce_sum(mu_out * b, axis=(2, 3, 4))
dual_obj = standard_layer_calcs.linear_dual_objective(
lam_in, activation_coeffs, dual_obj_bias, lb, ub)
# Compare against equivalent linear layer.
dual_obj_lin = _materialised_conv_layer_dual_objective(
w, b, padding, strides, lam_in, mu_out, lb, ub)
with self.test_session() as session:
dual_obj_val, dual_obj_lin_val = session.run((dual_obj, dual_obj_lin))
self.assertAllClose(dual_obj_val, dual_obj_lin_val, atol=tol, rtol=tol)
@parameterized.named_parameters(('float32', tf.float32),
('float64', tf.float64))
def test_conv1d_layer_dual_objective_shape(self, dtype):
num_classes = 6
batch_size = 23
input_length = 13
kernel_length = 3
input_channels = 3
output_channels = 5
padding = 'VALID'
strides = (2,)
# Output dimensions, based on convolution settings.
output_length = 6
w = tf.placeholder(dtype=dtype, shape=(
kernel_length, input_channels, output_channels))
b = tf.placeholder(dtype=dtype, shape=(output_channels,))
lam_in = tf.placeholder(dtype=dtype, shape=(
num_classes, batch_size, input_length, input_channels))
mu_out = tf.placeholder(dtype=dtype, shape=(
num_classes, batch_size, output_length, output_channels))
lb = tf.placeholder(dtype=dtype, shape=(
batch_size, input_length, input_channels))
ub = tf.placeholder(dtype=dtype, shape=(
batch_size, input_length, input_channels))
activation_coeffs = -common.conv_transpose(mu_out, w,
lb.shape[1:].as_list(),
padding, strides)
dual_obj_bias = -tf.reduce_sum(mu_out * b, axis=(2, 3))
dual_obj = standard_layer_calcs.linear_dual_objective(
lam_in, activation_coeffs, dual_obj_bias, lb, ub)
self.assertEqual(dtype, dual_obj.dtype)
self.assertEqual((num_classes, batch_size), dual_obj.shape)
@parameterized.named_parameters(('float32', tf.float32, 1.e-6),
('float64', tf.float64, 1.e-8))
def test_conv1d_layer_dual_objective(self, dtype, tol):
num_classes = 5
batch_size = 53
input_length = 13
kernel_length = 5
input_channels = 3
output_channels = 2
padding = 'VALID'
strides = (2,)
# Output dimensions, based on convolution settings.
output_length = 5
w = tf.random_normal(dtype=dtype, shape=(
kernel_length, input_channels, output_channels))
b = tf.random_normal(dtype=dtype, shape=(output_channels,))
lam_in = tf.random_normal(dtype=dtype, shape=(
num_classes, batch_size, input_length, input_channels))
mu_out = tf.random_normal(dtype=dtype, shape=(
num_classes, batch_size, output_length, output_channels))
lb = tf.random_normal(dtype=dtype, shape=(
batch_size, input_length, input_channels))
ub = tf.random_normal(dtype=dtype, shape=(
batch_size, input_length, input_channels))
lb, ub = tf.minimum(lb, ub), tf.maximum(lb, ub)
activation_coeffs = -common.conv_transpose(mu_out, w,
lb.shape[1:].as_list(),
padding, strides)
dual_obj_bias = -tf.reduce_sum(mu_out * b, axis=(2, 3))
dual_obj = standard_layer_calcs.linear_dual_objective(
lam_in, activation_coeffs, dual_obj_bias, lb, ub)
# Compare against equivalent linear layer.
dual_obj_lin = _materialised_conv_layer_dual_objective(
w, b, padding, strides, lam_in, mu_out, lb, ub)
with self.test_session() as session:
dual_obj_val, dual_obj_lin_val = session.run((dual_obj, dual_obj_lin))
self.assertAllClose(dual_obj_val, dual_obj_lin_val, atol=tol, rtol=tol)
@parameterized.named_parameters(('plain', False), ('relu', True))
def test_global_maxpool_layer_dual_objective_shape(self, with_relu):
num_classes = 11
batch_size = 6
input_height = 17
input_width = 7
layer_channels = 3
mu_in = tf.placeholder(dtype=tf.float32, shape=(
num_classes, batch_size, input_height, input_width, layer_channels))
lam_out = tf.placeholder(dtype=tf.float32, shape=(
num_classes, batch_size, 1, 1, layer_channels))
lb = tf.placeholder(dtype=tf.float32, shape=(
batch_size, input_height, input_width, layer_channels))
ub = tf.placeholder(dtype=tf.float32, shape=(
batch_size, input_height, input_width, layer_channels))
dual_obj = standard_layer_calcs.maxpool_layer_dual_objective(
None, None, with_relu, mu_in, lam_out, lb, ub)
self.assertEqual((num_classes, batch_size), dual_obj.shape)
@parameterized.named_parameters(('plain', False), ('relu', True))
def test_maxpool_layer_dual_objective_shape(self, with_relu):
num_classes = 6
batch_size = 7
input_height = 33
input_width = 20
layer_channels = 3
# Output dimensions, based on maxpool settings.
output_height = 11
output_width = 5
mu_in = tf.placeholder(dtype=tf.float32, shape=(
num_classes, batch_size, input_height, input_width, layer_channels))
lam_out = tf.placeholder(dtype=tf.float32, shape=(
num_classes, batch_size, output_height, output_width, layer_channels))
lb = tf.placeholder(dtype=tf.float32, shape=(
batch_size, input_height, input_width, layer_channels))
ub = tf.placeholder(dtype=tf.float32, shape=(
batch_size, input_height, input_width, layer_channels))
dual_obj = standard_layer_calcs.maxpool_layer_dual_objective(
[3, 4], (3, 4), with_relu, mu_in, lam_out, lb, ub)
self.assertEqual((num_classes, batch_size), dual_obj.shape)
@parameterized.named_parameters(('plain', False), ('relu', True))
def test_global_maxpool_layer_dual_objective(self, with_relu):
num_classes = 11
batch_size = 23
input_height = 5
input_width = 7
layer_channels = 3
mu_in = tf.random_normal(shape=(
num_classes, batch_size, input_height, input_width, layer_channels))
lam_out = tf.random_normal(shape=(
num_classes, batch_size, 1, 1, layer_channels))
lb = tf.random_normal(shape=(
batch_size, input_height, input_width, layer_channels))
ub = tf.random_normal(shape=(
batch_size, input_height, input_width, layer_channels))
lb, ub = tf.minimum(lb, ub), tf.maximum(lb, ub)
dual_obj = standard_layer_calcs.maxpool_layer_dual_objective(
None, None, with_relu, mu_in, lam_out, lb, ub)
# Calculate the maxpool dual objective a different way.
dual_obj_alt = self._max_layer_dual_objective(lb, ub, mu_in, lam_out,
with_relu)
init_op = tf.global_variables_initializer()
with self.test_session() as session:
session.run(init_op)
# Verify that both methods give the same result.
dual_obj_val, dual_obj_alt_val = session.run((dual_obj, dual_obj_alt))
tol = 1.e-6
self.assertAllClose(dual_obj_val, dual_obj_alt_val, atol=tol, rtol=tol)
@parameterized.named_parameters(('plain', False), ('relu', True))
def test_maxpool_layer_dual_objective(self, with_relu):
num_classes = 7
batch_size = 13
input_height = 14
input_width = 15
layer_channels = 3
kernel_height = 2
kernel_width = 3
stride_vertical = 2
stride_horizontal = 3
# Output dimensions, based on maxpool settings.
# This maxpool tiles perfectly.
output_height = 7
output_width = 5
mu_in = tf.random_normal(shape=(
num_classes, batch_size, input_height, input_width, layer_channels))
lam_out = tf.random_normal(shape=(
num_classes, batch_size, output_height, output_width, layer_channels))
lb = tf.random_normal(shape=(
batch_size, input_height, input_width, layer_channels))
ub = tf.random_normal(shape=(
batch_size, input_height, input_width, layer_channels))
lb, ub = tf.minimum(lb, ub), tf.maximum(lb, ub)
dual_obj = standard_layer_calcs.maxpool_layer_dual_objective(
[kernel_height, kernel_width], (stride_vertical, stride_horizontal),
with_relu, mu_in, lam_out, lb, ub)
# Calculate the maxpool dual objective a different way.
dual_obj_alt = 0.
# Loop over all kernel placements.
for output_row in range(output_height):
for output_col in range(output_width):
# Slice up the input tensors.
output_row_slice = slice(output_row, output_row + 1)
output_col_slice = slice(output_col, output_col + 1)
input_row = stride_vertical * output_row
input_row_slice = slice(input_row, input_row + kernel_height)
input_col = stride_horizontal * output_col
input_col_slice = slice(input_col, input_col + kernel_width)
# Calculate contribution for this kernel placement.
dual_obj_alt += self._max_layer_dual_objective(
lb[:, input_row_slice, input_col_slice, :],
ub[:, input_row_slice, input_col_slice, :],
mu_in[:, :, input_row_slice, input_col_slice, :],
lam_out[:, :, output_row_slice, output_col_slice, :],
with_relu)
init_op = tf.global_variables_initializer()
with self.test_session() as session:
session.run(init_op)
# Verify that both methods give the same result.
dual_obj_val, dual_obj_alt_val = session.run((dual_obj, dual_obj_alt))
tol = 1.e-6
self.assertAllClose(dual_obj_val, dual_obj_alt_val, atol=tol, rtol=tol)
@parameterized.named_parameters(('plain', False), ('relu', True))
def test_overlapping_maxpool_layer_dual_objective(self, with_relu):
num_classes = 11
batch_size = 13
input_height = 7
input_width = 14
layer_channels = 3
kernel_height = 3
kernel_width = 5
stride_vertical = 1
stride_horizontal = 3
# Output dimensions, based on maxpool settings.
# This maxpool has overlaps vertically and horizontally.
output_height = 5
output_width = 4
vertical_overlap = tf.reshape(
tf.constant([1, 2, 3, 3, 3, 2, 1],
dtype=tf.float32),
shape=(input_height, 1, 1))
horizontal_overlap = tf.reshape(
tf.constant([1, 1, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 1, 1],
dtype=tf.float32),
shape=(1, input_width, 1))
mu_in = tf.random_normal(shape=(
num_classes, batch_size, input_height, input_width, layer_channels))
lam_out = tf.random_normal(shape=(
num_classes, batch_size, output_height, output_width, layer_channels))
lb = tf.random_normal(shape=(
batch_size, input_height, input_width, layer_channels))
ub = tf.random_normal(shape=(
batch_size, input_height, input_width, layer_channels))
lb, ub = tf.minimum(lb, ub), tf.maximum(lb, ub)
dual_obj = standard_layer_calcs.maxpool_layer_dual_objective(
[kernel_height, kernel_width], (stride_vertical, stride_horizontal),
with_relu, mu_in, lam_out, lb, ub)
# Calculate the maxpool dual objective a different way.
# Share the inputs' dual variables equally amongst all pools they belong to.
mu_in_shared = mu_in / (vertical_overlap * horizontal_overlap)
dual_obj_alt = 0.
# Loop over all kernel placements.
for output_row in range(output_height):
for output_col in range(output_width):
# Slice up the input tensors.
output_row_slice = slice(output_row, output_row + 1)
output_col_slice = slice(output_col, output_col + 1)
input_row = stride_vertical * output_row
input_row_slice = slice(input_row, input_row + kernel_height)
input_col = stride_horizontal * output_col
input_col_slice = slice(input_col, input_col + kernel_width)
# Calculate contribution for this kernel placement.
dual_obj_alt += self._max_layer_dual_objective(
lb[:, input_row_slice, input_col_slice, :],
ub[:, input_row_slice, input_col_slice, :],
mu_in_shared[:, :, input_row_slice, input_col_slice, :],
lam_out[:, :, output_row_slice, output_col_slice, :],
with_relu)
init_op = tf.global_variables_initializer()
with self.test_session() as session:
session.run(init_op)
# Verify that both methods give the same result.
dual_obj_val, dual_obj_alt_val = session.run((dual_obj, dual_obj_alt))
tol = 1.e-6
self.assertAllClose(dual_obj_val, dual_obj_alt_val, atol=tol, rtol=tol)
def _max_layer_dual_objective(self, lb, ub, mu_in, lam_out, with_relu):
"""Calculates expected dual objective for a global 'max' layer.
This can also be called repeatedly to obtain the dual objective for a
maxpool with a moving kernel that tiles the input space without overlapping.
Maximises (over y in [lb, ub])::
mu^T y - lam max(y)
by conditioning on the max obtaining its maximum at y_i, and evaluating
separately at the vertices of the resulting piecewise-linear function
in y_i.
Args:
lb: 4D tensor of shape (batch_size, height, width, channels)
containing lower bounds on the inputs.
ub: 4D tensor of shape (batch_size, height, width, channels)
containing upper bounds on the inputs.
mu_in: 5D tensor of shape (num_classes, batch_size, height, width,
channels) dual variables for the inputs' preceding linear calculations.
lam_out: 5D tensor of shape (num_classes, batch_size, 1, 1, channels)
containing dual variables for the outputs' max-pool calculations.
with_relu: Boolean, whether to apply a relu to the maxpool.
Returns:
2D tensor of shape (num_classes, batch_size) containing the dual
objective for the 'max' layer for each example.
"""
# Recall the problem: maximise (over y in [lb, ub])::
# mu^T y - lam max(y)
#
# For each input (kernel element) i, we condition on the maxpool
# attaining its maximum at y_i.
# This leads us to maximise (over z_j in [lb_j, min{y_i, ub_j}]
# and constraining z_i=y_i)::
# mu^T z - lam y_i
#
# That maximum, as a function of y_i in the domain [lb_max, ub_i],
# is concave and piecewise linear with cusps at ub_k.
# Instead of bisection, we evaluate it at those values of ub_k that lie
# within the interval [lb_max, ub_i], and also at lb_max itself.
# The maximum over all such k and i is our dual objective.
lb_max = tf.reduce_max(lb, axis=[1, 2], keepdims=True)
if with_relu:
# Model ReLU as an additional fixed input to the max, with bounds [0, 0].
lb_max = tf.maximum(lb_max, 0.)
# We'll need to consider ub_i and ub_k together.
# Set up xx_i, xx_k tensors shaped as (class?, N, Hi, Wi, Hk, Wk, C)
# where Hi, Hk range over input rows and Wi, Wk range over input columns.
mu_i = tf.expand_dims(tf.expand_dims(mu_in, 4), 5)
lam = tf.expand_dims(tf.expand_dims(lam_out, 4), 5)
lb_i = tf.expand_dims(tf.expand_dims(lb, 3), 4)
ub_i = tf.expand_dims(tf.expand_dims(ub, 3), 4)
ub_k = tf.expand_dims(tf.expand_dims(ub, 1), 2)
lb_max = tf.expand_dims(tf.expand_dims(lb_max, 1), 2)
def dual_obj_given_max_at_yi(c_k):
# Evaluate max (mu^T z - lam y_i) at y_i = c_k.
bc = tf.zeros_like(mu_i + c_k) # tf.where doesn't broadcast
dual_obj = standard_layer_calcs.max_linear(
mu_i + bc, lb_i + bc,
tf.minimum(c_k, ub_i), axis=[2, 3], keepdims=True)
dual_obj -= tf.maximum(lb_i * mu_i, tf.minimum(c_k, ub_i) * mu_i)
dual_obj += (mu_i - lam) * c_k
# Only consider this y if it's in the permitted range for a maximal y_i.
feasible = tf.logical_and(lb_max <= c_k, c_k <= ub_i + bc)
dual_obj = tf.where(feasible, dual_obj, -1.e8 + bc)
# Take maximum over all i, k.
return tf.reduce_max(dual_obj, axis=[2, 3, 4, 5])
# Evaluate max (mu^T z - lam y_i) at y_i = max_j lb_j.
dual_obj_lb_max = dual_obj_given_max_at_yi(lb_max)
# Evaluate max (mu^T z - lam y_i) at y_i = ub_k.
dual_obj_ub_k = dual_obj_given_max_at_yi(ub_k)
dual_obj_max = tf.maximum(dual_obj_lb_max, dual_obj_ub_k)
if with_relu:
# Also consider the case in which all y_i are <= 0,
# so relu_maxpool is zero.
# This leads us to maximise (over z_j in [lb_j, min{0, ub_j}])::
# mu^T z - lam 0
bc = tf.zeros_like(mu_i) # tf.where doesn't broadcast
dual_obj_zero = standard_layer_calcs.max_linear(
mu_i + bc, lb_i + bc,
tf.minimum(0., ub_i), axis=[2, 3], keepdims=True)
# Only consider this case if the y_i can actually all be <= 0.
bc = tf.zeros_like(dual_obj_zero) # tf.where doesn't broadcast
feasible = lb_max <= bc
dual_obj_zero = tf.where(feasible, dual_obj_zero, -1.e8 + bc)
dual_obj_zero = tf.reduce_max(dual_obj_zero, axis=[2, 3, 4, 5])
dual_obj_max = tf.maximum(dual_obj_max, dual_obj_zero)
return tf.reduce_sum(dual_obj_max, axis=2)
def _materialised_conv_layer_dual_objective(w, b, padding, strides,
lam_in, mu_out, lb, ub):
"""Materialised version of `conv_layer_dual_objective`."""
# Flatten the inputs, as the materialised convolution will have no
# spatial structure.
mu_out_flat = snt.BatchFlatten(preserve_dims=2)(mu_out)
# Materialise the convolution as a (sparse) fully connected linear layer.
w_flat, b_flat = layer_utils.materialise_conv(
w, b, lb.shape[1:].as_list(), padding=padding, strides=strides)
activation_coeffs = -tf.tensordot(mu_out_flat, tf.transpose(w_flat), axes=1)
dual_obj_bias = -tf.tensordot(mu_out_flat, b_flat, axes=1)
# Flatten the inputs, as the materialised convolution will have no
# spatial structure.
if lam_in is not None:
lam_in = snt.FlattenTrailingDimensions(2)(lam_in)
lb = snt.BatchFlatten()(lb)
ub = snt.BatchFlatten()(ub)
return standard_layer_calcs.linear_dual_objective(
lam_in, activation_coeffs, dual_obj_bias, lb, ub)
if __name__ == '__main__':
tf.test.main()
| deep-verify-master | deep_verify/tests/formulations/standard/standard_layer_calcs_test.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Automatic construction of verifiable layers from a Sonnet module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src.layers import layers
import interval_bound_propagation as ibp
import sonnet as snt
class NotVerifiableError(Exception):
"""Module's graph contains features that do not map to verification layers."""
class VerifiableLayerBuilder(object):
"""Constructs verifiable layers from a Sonnet module."""
def __init__(self, network):
"""Constructor.
Args:
network: `NetworkBuilder` containing network with propagated bounds.
"""
super(VerifiableLayerBuilder, self).__init__()
self._network = network
def build_layers(self):
"""Builds the verifiable layers.
Returns:
List of `SingleVerifiableLayer` for the module.
Raises:
NotVerifiableError: on invalid layer arrangement.
"""
backstop_node, known_fanout, verifiable_layers, reshape = (
self._build_layers_rec(self._network.output_module))
if (not isinstance(backstop_node, ibp.ModelInputWrapper) or
self._network.fanout_of(backstop_node) != known_fanout):
raise NotVerifiableError('Invalid connectivity')
if reshape:
raise NotVerifiableError('Cannot end with a reshape operation')
return self._fuse(verifiable_layers)
def _build_layers_rec(self, node, known_fanout=1, batchnorm_node=None):
"""Builds verifiable layers leading up to the given layer output.
The list is constructed by navigating the layers in reverse order,
stopping either when the module's original inputs are reached,
or (for within a ResNet block) when a layer is encountered that has
outputs not processed by this navigation.
Args:
node: Layer output, up to which to build verifiable layers.
known_fanout: Number of immediate outputs of `layer_tensor` that have
already been processed by the caller.
This is typically 1, but sub-classes may invoke with 2 (or possibly
greater) where the network contains branches.
batchnorm_node: The BatchNorm's ConnectedSubgraph object if
`layer_tensor` is the input to a BatchNorm layer, otherwise None.
Returns:
backstop_node: Node, typically the `ibp.ModelInputWrapper`, at which we
stopped backtracking.
known_fanout: Number of immediate outputs of `input_tensor` that were
processed in this call.
This is typically 1, but overrides may return 2 (or possibly greater)
in the presence of branched architectures.
verifiable_layers: List of `SingleVerifiableLayer` whose final element's
output is `outputs`.
reshape: Whether the final element of `verifiable_layers` is followed by
a reshape operation.
Raises:
NotVerifiableError: on invalid layer arrangement.
"""
if (isinstance(node, ibp.ModelInputWrapper) or
self._network.fanout_of(node) != known_fanout):
# Reached the inputs (or start of the enclosing ResNet block).
# No more layers to construct.
if batchnorm_node:
raise NotVerifiableError('Cannot begin with batchnorm')
return node, known_fanout, [], False
elif (isinstance(node, ibp.IncreasingMonotonicWrapper) and
node.module.__name__ == 'identity'):
# Recursively build all preceding layers.
input_node, = self._network.dependencies(node)
return self._build_layers_rec(input_node, batchnorm_node=batchnorm_node)
elif (isinstance(node, ibp.IncreasingMonotonicWrapper) and
node.module.__name__ == 'avg_pool'):
# Recursively build all preceding layers.
input_node, = self._network.dependencies(node)
input_tensor, known_fanout, verifiable_layers, reshape = (
self._build_layers_rec(input_node))
# Construct the AvgPool layer.
if batchnorm_node:
raise NotVerifiableError('AvgPool cannot have batchnorm')
if node.parameters['padding'] == 'SAME':
raise ValueError('"SAME" padding is not supported.')
verifiable_layers.append(layers.AvgPool(
input_node,
node,
kernel_shape=node.parameters['ksize'][1:-1],
strides=node.parameters['strides'][1:-1],
reshape=reshape))
return input_tensor, known_fanout, verifiable_layers, False
elif (isinstance(node, ibp.IncreasingMonotonicWrapper) and
node.module.__name__ == 'reduce_mean'):
# Recursively build all preceding layers.
input_node, = self._network.dependencies(node)
input_tensor, known_fanout, verifiable_layers, reshape = (
self._build_layers_rec(input_node))
# Construct the AvgPool layer.
if batchnorm_node:
raise NotVerifiableError('AvgPool cannot have batchnorm')
verifiable_layers.append(layers.AvgPool(
input_node,
node,
kernel_shape=None,
strides=None,
reshape=reshape))
return input_tensor, known_fanout, verifiable_layers, False
elif (isinstance(node, ibp.IncreasingMonotonicWrapper) and
node.module.__name__ == 'max_pool'):
# Recursively build all preceding layers.
input_node, = self._network.dependencies(node)
input_tensor, known_fanout, verifiable_layers, reshape = (
self._build_layers_rec(input_node))
# Construct the MaxPool layer.
if batchnorm_node:
raise NotVerifiableError('MaxPool cannot have batchnorm')
if node.parameters['padding'] == 'SAME':
raise ValueError('"SAME" padding is not supported.')
verifiable_layers.append(layers.MaxPool(
input_node,
node,
kernel_shape=node.parameters['ksize'][1:-1],
strides=node.parameters['strides'][1:-1],
reshape=reshape))
return input_tensor, known_fanout, verifiable_layers, False
elif (isinstance(node, ibp.IncreasingMonotonicWrapper) and
node.module.__name__ == 'reduce_max'):
# Recursively build all preceding layers.
input_node, = self._network.dependencies(node)
input_tensor, known_fanout, verifiable_layers, reshape = (
self._build_layers_rec(input_node))
# Construct the MaxPool layer.
if batchnorm_node:
raise NotVerifiableError('MaxPool cannot have batchnorm')
verifiable_layers.append(layers.MaxPool(
input_node,
node,
kernel_shape=None,
strides=None,
reshape=reshape))
return input_tensor, known_fanout, verifiable_layers, False
elif isinstance(node.module, snt.BatchNorm):
# Construct the previous layer with batchnorm.
if batchnorm_node:
raise NotVerifiableError('Cannot have consecutive batchnorms')
input_node, = self._network.dependencies(node)
return self._build_layers_rec(input_node, batchnorm_node=node)
elif isinstance(node.module, snt.BatchReshape):
# Recursively build all preceding layers.
input_node, = self._network.dependencies(node)
backstop_node, known_fanout, verifiable_layers, reshape = (
self._build_layers_rec(input_node))
if batchnorm_node:
raise NotVerifiableError('Reshape cannot have batchnorm')
return backstop_node, known_fanout, verifiable_layers, True
else:
# Recursively build all preceding layers.
input_nodes = self._network.dependencies(node)
if len(input_nodes) != 1:
raise NotVerifiableError('Unary operation expected')
input_node, = input_nodes
backstop_node, known_fanout, verifiable_layers, reshape = (
self._build_layers_rec(input_node))
# Construct the layer.
verifiable_layers.append(layers.create_verifiable_layer(
input_node,
batchnorm_node or node,
node.module,
batch_norm=(batchnorm_node.module if batchnorm_node else None),
reshape=reshape,
parameters=(node.parameters
if isinstance(node, ibp.IncreasingMonotonicWrapper)
else None),
))
return backstop_node, known_fanout, verifiable_layers, False
def _fuse(self, verifiable_layers):
"""Performs fusion of certain layer pairs."""
fused_layers = []
idx = 0
while idx < len(verifiable_layers):
if (idx+2 <= len(verifiable_layers) and
isinstance(verifiable_layers[idx], layers.MaxPool) and
isinstance(verifiable_layers[idx+1], layers.Activation) and
verifiable_layers[idx+1].activation == 'relu'):
# Fuse maxpool with relu.
original = verifiable_layers[idx]
fused_layers.append(layers.MaxPool(original.input_node,
original.output_node,
kernel_shape=original.kernel_shape,
strides=original.strides,
with_relu=True,
reshape=original.reshape))
idx += 2
else:
fused_layers.append(verifiable_layers[idx])
idx += 1
return fused_layers
| deep-verify-master | deep_verify/src/auto_verifier.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library to verify robustness of neural networks using dual methods.
For more details see paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| deep-verify-master | deep_verify/src/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Graph construction for dual verification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import operator
import tensorflow as tf
def with_explicit_update(volatile_value):
"""Wraps the volatile value in a variable to cache a stationary copy of it.
Args:
volatile_value: Volatile tensor value to hold still; may be nested.
Returns:
materialised_value: Non-trainable variable (or nest thereof) to hold a
stationary copy of the tensor.
update_op: Operation to update the cache by reevaluating the tensor.
"""
def materialise(value):
"""Returns a non-trainable variable to shadow the given volatile tensor."""
return tf.get_variable(value.name.replace(':', '__') + '_materialised',
shape=value.shape,
dtype=value.dtype,
trainable=False)
materialised_value = tf.nest.map_structure(materialise, volatile_value)
update_op = tf.group(tf.nest.flatten(
tf.nest.map_structure(tf.assign, materialised_value, volatile_value)))
return materialised_value, update_op
def targeted_objective(final_w, final_b, labels):
"""Determines final layer weights for attacks targeting each class.
Args:
final_w: 2D tensor of shape (last_hidden_layer_size, num_classes)
containing the weights for the final linear layer.
final_b: 1D tensor of shape (num_classes) containing the biases for the
final hidden layer.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
Returns:
obj_w: Tensor of shape (num_classes, batch_size, last_hidden_layer_size)
containing weights (to use in place of final linear layer weights)
for targeted attacks.
obj_b: Tensor of shape (num_classes, batch_size) containing bias
(to use in place of final linear layer biases) for targeted attacks.
"""
# Elide objective with final linear layer.
final_wt = tf.transpose(final_w)
obj_w = tf.expand_dims(final_wt, axis=1) - tf.gather(final_wt, labels, axis=0)
obj_b = tf.expand_dims(final_b, axis=1) - tf.gather(final_b, labels, axis=0)
return obj_w, obj_b
def concave_max_binsearch(fn, lb, ub, num_iter=20):
"""Ternary search to find the maximum of the given concave function.
Although the branching factor is three, the search interval shrinks by a
factor of two each iteration. Therefore, 20 iterations (the default) give
an accuracy of around one part per million.
The returned tensor will be a tuple of `(argmax, max)`. `argmax` has no
gradients. `max` is the tensor returned by applying `fn` to argmax, and so
will have no gradients via `argmax` but may have gradients with respect to
other tensors captured by `fn`.
Args:
fn: Function accepting a tensor and returning a tensor of the same shape,
expressing concave functions applied element-wise. Each output element
should depend only upon the corresponding input element.
lb: Floating-point tensor containing lower-bounds on inputs to `fn`.
ub: Floating-point tensor containing upper-bounds on inputs to `fn`.
num_iter: Number of binary search iterations to perform.
Returns:
Pair of tensors (of same shape as lb and ub) containing:
argmax: inputs (in range lb...ub) that maximise `fn` element-wise.
max: the attained values of `fn`.
"""
mid = tf.stop_gradient(.5 * lb + .5 * ub)
f_mid = fn(mid)
for _ in range(num_iter):
# Calculate quartiles.
lq = tf.stop_gradient(.75 * lb + .25 * ub)
uq = tf.stop_gradient(.25 * lb + .75 * ub)
f_lq = fn(lq)
f_uq = fn(uq)
# Identify three cases, recalling that fn is concave.
# Case 1: f_lq > f_mid > f_uq
# The maximum occurs in the range [lb, mid].
# Case 2: f_lq > f_mid > f_uq
# The maximum occurs in the range [mid, ub].
# Case 3: f_lq < f_mid > f_uq
# The maximum occurs in the range [lq, uq].
case1 = f_lq > f_mid
case2 = f_uq > f_mid
lb, ub, mid, f_mid = (
tf.where(case1, lb, tf.where(case2, mid, lq)),
tf.where(case1, mid, tf.where(case2, ub, uq)),
tf.where(case1, lq, tf.where(case2, uq, mid)),
tf.where(case1, f_lq, tf.where(case2, f_uq, f_mid))
)
return mid, f_mid
def _prod(lst):
return functools.reduce(operator.mul, lst, 1)
def convolution(x, kernel, padding, strides):
"""Applies an N-D convolution, respecting two batch dimensions.
Args:
x: (N+3)D tensor of shape (num_classes, batch_size, input_height,
input_width, input_channels) containing the coefficients to which the
convolution is to be applied.
kernel: (N+2)D tensor of shape (kernel_height, kernel_width, input_channels,
output_channels) containing weights for the convolution.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
Returns:
(N+3)D tensor of shape (num_classes, batch_size, output_height,
output_width, output_channels) containing the convolution of `x`.
Raises:
ValueError: if an unsupported convolution dimensionality is encountered.
"""
# Temporarily combine the classes/batch dimensions while convolving.
num_classes = x.shape[0].value
batch_size = tf.shape(x)[1]
x_squeezed = tf.reshape(x, shape=([num_classes * batch_size] +
x.shape[2:].as_list()))
if len(kernel.shape) == 4:
y = tf.nn.convolution(x_squeezed, kernel, padding=padding, strides=strides)
elif len(kernel.shape) == 3:
y = tf.nn.conv1d(x_squeezed, kernel, padding=padding, stride=strides[0])
else:
raise ValueError()
return tf.reshape(y, shape=([num_classes, batch_size] +
y.shape[1:].as_list()))
def conv_transpose(y, kernel, result_shape, padding, strides):
"""Applies an N-D transpose-convolution, respecting two batch dimensions.
Args:
y: (N+3)D tensor of shape (num_classes, batch_size, output_height,
output_width, output_channels) containing the coefficients to which the
transpose-convolution is to be applied.
kernel: (N+2)D tensor of shape (kernel_height, kernel_width, input_channels,
output_channels) containing weights for the convolution.
result_shape: List of [input_height, input_width, input_channels] specifying
the N+1 trailing (non-batch) dimensions of the output.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
Returns:
(N+3)D tensor of shape (num_classes, batch_size, input_height,
input_width, input_channels) containing the transpose-convolution of `y`.
Raises:
ValueError: if an unsupported convolution dimensionality is encountered.
"""
# Temporarily combine the (num_classes, batch_size) dimensions
# while applying the transpose convolution.
batch_size = tf.shape(y)[1]
y_squeezed = tf.reshape(y,
shape=([y.shape[0].value * batch_size] +
y.shape[2:].as_list()))
if len(result_shape) == 3:
x = tf.nn.conv2d_transpose(
y_squeezed, kernel,
output_shape=([tf.shape(y_squeezed)[0]] + result_shape),
padding=padding, strides=([1] + list(strides) + [1]))
elif len(result_shape) == 2:
x = tf.nn.conv1d_transpose(
y_squeezed,
kernel,
output_shape=([tf.shape(y_squeezed)[0]] + result_shape),
padding=padding,
strides=strides[0])
else:
raise ValueError()
return tf.reshape(x, shape=(
[y.shape[0].value, batch_size] + x.shape[1:].as_list()))
def avgpool_transpose(y, result_shape, kernel_shape, strides):
"""Applies an N-D 'transposed average pool', respecting two batch dimensions.
Args:
y: (N+3)D tensor of shape (num_classes, batch_size, output_height,
output_width, channels) containing the coefficients to which the
transpose-convolution is to be applied.
result_shape: Integer list of length N+1 specifying the non-batch dimensions
of the result: [input_height, input_width, channels].
kernel_shape: Integer list of `[kernel_height, kernel_width]`,
or `None` to aggregate over the layer`s entire spatial extent.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
Returns:
(N+3)D tensor of shape (num_classes, batch_size, input_height,
input_width, channels) containing the transpose-avgpool of `y`.
"""
if kernel_shape is None:
# We know that output_height=1 and output_width=1.
return tf.tile(y, [1, 1] + list(result_shape[:-1]) + [1]) / (
_prod(result_shape[:-1]))
else:
# Treat the average pool as a convolution with uniform weights.
kernel = tf.ones(dtype=y.dtype, shape=(list(kernel_shape) + [1, 1]))
channels = result_shape[-1]
kernel *= tf.eye(channels, dtype=y.dtype)
kernel /= _prod(kernel_shape)
return conv_transpose(y, kernel, result_shape=result_shape,
padding='VALID', strides=strides)
def conv_broadcast(x, kernel_shape, padding, strides):
"""Performs an N-D convolutional broadcast.
Inserts dimensions into `x`, by duplicating elements with respect to the
specified convolution.
For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then
with respect to each spatial dimension of the convolution (and disregarding
batch and channel dimensions for the sake of illustration), input data
of the form [a, b, c, d, e, f] is mapped to::
[[ a, b, c ],
[ b, c, d ],
[ c, d, e ],
[ d, e, f ]]
The output size (height and width) is as determined by tf.nn.convolution
with the kernel size, stride, and padding specified.
Args:
x: (N+2)D tensor of shape (batch_size, input_height, input_width,
input_channels)
kernel_shape: Integer list of length N specifying the spatial shape of the
convolution kernel.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of length N: `[vertical_stride, horizontal_stride]`.
Returns:
(2N+3)D tensor of shape (batch_size,
output_height, output_width, 1,
kernel_height, kernel_width, input_channels).
Raises:
ValueError: if an unsupported convolution dimensionality is encountered.
"""
if len(kernel_shape) == 2:
return conv2d_broadcast(x, kernel_shape[0], kernel_shape[1],
padding, strides)
elif len(kernel_shape) == 1:
return conv1d_broadcast(x, kernel_shape[0], padding, strides[0])
else:
raise ValueError()
def conv2d_broadcast(x, kernel_height, kernel_width, padding, strides):
"""Performs a convolutional broadcast.
Inserts dimensions into `x`, by duplicating elements with respect to the
specified convolution.
For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then
with respect to each spatial dimension of the convolution (and disregarding
batch and channel dimensions for the sake of illustration), input data
of the form [a, b, c, d, e, f] is mapped to::
[[ a, b, c ],
[ b, c, d ],
[ c, d, e ],
[ d, e, f ]]
The output size (height and width) is as determined by tf.nn.convolution
with the kernel size, stride, and padding specified.
Args:
x: 4D tensor of shape (batch_size, input_height, input_width,
input_channels)
kernel_height: Height of the convolution kernel.
kernel_width: Width of the convolution kernel.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
Returns:
7D tensor of shape (batch_size,
output_height, output_width, 1,
kernel_height, kernel_width, input_channels).
"""
batch_size = tf.shape(x)[0]
input_channels = x.shape[3].value
# Temporarily combine the (batch_size, input_channels) dims while
# applying the convolution. Introduce a dummy channels dimension instead.
squeezed = tf.transpose(x, perm=[0, 3, 1, 2])
squeezed = tf.reshape(squeezed, shape=(
[batch_size * input_channels] +
x.shape[1:3].as_list() +
[1]))
# Convolve each elementary (i.e. one-hot) filter with x.
diagonal_kernel = tf.reshape(
tf.eye(kernel_height * kernel_width, dtype=x.dtype),
shape=[kernel_height, kernel_width, 1, kernel_height * kernel_width])
conv = tf.nn.convolution(
squeezed, diagonal_kernel,
padding=padding, strides=strides)
# The resulting convolution has shape (batch_size*input_channels,
# output_height, output_width, kernel_height*kernel_width).
# Move input_channels back to the last dimension.
result = tf.reshape(conv, shape=(
[batch_size, input_channels] +
conv.shape[1:3].as_list() +
[kernel_height, kernel_width]))
result = tf.transpose(result, perm=[0, 2, 3, 4, 5, 1])
# Insert output_channels dimension.
return tf.expand_dims(result, 3)
def conv1d_broadcast(x, kernel_length, padding, stride):
"""Performs a convolutional broadcast.
Inserts dimensions into `x`, by duplicating elements with respect to the
specified convolution.
For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then
with respect to the sequence dimension of the convolution (and disregarding
batch and channel dimensions for the sake of illustration), input data
of the form [a, b, c, d, e, f] is mapped to::
[[ a, b, c ],
[ b, c, d ],
[ c, d, e ],
[ d, e, f ]]
The output size (length) is as determined by tf.nn.convolution
with the kernel size, stride, and padding specified.
Args:
x: 3D tensor of shape (batch_size, input_length, input_channels)
kernel_length: Length of the convolution kernel.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
stride: Integer stride.
Returns:
5D tensor of shape (batch_size,
output_length, 1,
kernel_length, input_channels).
"""
batch_size = tf.shape(x)[0]
input_channels = x.shape[2].value
# Temporarily combine the (batch_size, input_channels) dims while
# applying the convolution. Introduce a dummy channels dimension instead.
squeezed = tf.transpose(x, perm=[0, 2, 1])
squeezed = tf.reshape(squeezed, shape=(
[batch_size * input_channels] +
x.shape[1:2].as_list() +
[1]))
# Convolve each elementary (i.e. one-hot) filter with x.
diagonal_kernel = tf.reshape(
tf.eye(kernel_length, dtype=x.dtype),
shape=[kernel_length, 1, kernel_length])
conv = tf.nn.conv1d(
squeezed, diagonal_kernel,
padding=padding, stride=stride)
# The resulting convolution has shape (batch_size*input_channels,
# output_length, kernel_length).
# Move input_channels back to the last dimension.
result = tf.reshape(conv, shape=(
[batch_size, input_channels] +
conv.shape[1:2].as_list() +
[kernel_length]))
result = tf.transpose(result, perm=[0, 2, 3, 1])
# Insert output_channels dimension.
return tf.expand_dims(result, 2)
def conv_reduce_sum(x, result_shape, padding, strides):
"""Sums along the output dimensions in line with an N-D convolution.
For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then
with respect to each spatial dimension of the convolution (and disregarding
class, batch and channel dimensions for the sake of illustration), input data
of the form::
[[ a, b, c ],
[ d, e, f ],
[ g, h, i ],
[ j, k, l ]]
is mapped to [a, b+d, c+e+g, f+h+j, i+k, l].
Args:
x: (2N+4)D tensor of shape (num_classes, batch_size,
output_height, output_width, output_channels,
kernel_height, kernel_width, input_channels).
result_shape: Integer list of length N+1 specifying the non-batch dimensions
of the result: [input_height, input_width, input_channels].
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of length N: `[vertical_stride, horizontal_stride]`.
Returns:
(N+3)D tensor of shape (num_classes, batch_size,
input_height, input_width, input_channels)
Raises:
ValueError: if an unsupported convolution dimensionality is encountered.
"""
if len(result_shape) == 3:
return conv2d_reduce_sum(x, result_shape[0], result_shape[1],
padding, strides)
elif len(result_shape) == 2:
return conv1d_reduce_sum(x, result_shape[0], padding, strides[0])
else:
raise ValueError()
def conv2d_reduce_sum(x, input_height, input_width, padding, strides):
"""Sums along the output dimensions in line with a convolution.
For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then
with respect to each spatial dimension of the convolution (and disregarding
class, batch and channel dimensions for the sake of illustration), input data
of the form::
[[ a, b, c ],
[ d, e, f ],
[ g, h, i ],
[ j, k, l ]]
is mapped to [a, b+d, c+e+g, f+h+j, i+k, l].
Args:
x: 8D tensor of shape (num_classes, batch_size,
output_height, output_width, output_channels,
kernel_height, kernel_width, input_channels).
input_height: height of the returned tensor.
input_width: width of the returned tensor.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
Returns:
5D tensor of shape (num_classes, batch_size,
input_height, input_width, input_channels)
"""
# Sum over the output channels.
lam_sum = tf.reduce_sum(x, axis=4)
num_classes = x.shape[0].value
batch_size = tf.shape(x)[1]
kernel_height = x.shape[5].value
kernel_width = x.shape[6].value
input_channels = x.shape[7].value
# Temporarily combine the (num_classes, batch_size, in_layer_channels) dims
# while applying a transpose convolution.
# Also combine (kernel_height, kernel_width), using them as the channels
# as we'll apply the transpose convolution to each kernel point separately.
lam_squeezed = tf.transpose(lam_sum, perm=[0, 1, 6, 2, 3, 4, 5])
lam_squeezed = tf.reshape(lam_squeezed, shape=(
[num_classes * batch_size * input_channels] +
x.shape[2:4].as_list() +
[kernel_height * kernel_width]))
# De-convolve each elementary (i.e. one-hot) filter with the corresponding
# slice of lambda.
diagonal_kernel = tf.reshape(
tf.eye(kernel_height * kernel_width, dtype=x.dtype),
shape=[kernel_height, kernel_width, 1, kernel_height * kernel_width])
lam_deconv = tf.nn.conv2d_transpose(
lam_squeezed, diagonal_kernel, output_shape=(
[num_classes * batch_size * input_channels] +
[input_height, input_width, 1]),
padding=padding, strides=([1] + list(strides) + [1]))
# The resulting de-convolution has shape
# (num_classes*batch_size*in_layer_channels,
# in_layer_height, in_layer_width, 1).
# Make it match mu_in.
result = tf.reshape(lam_deconv, shape=(
[num_classes, batch_size, input_channels] +
lam_deconv.shape[1:3].as_list()))
return tf.transpose(result, perm=[0, 1, 3, 4, 2])
def conv1d_reduce_sum(x, input_length, padding, stride):
"""Sums along the output dimensions in line with a convolution.
For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then
with respect to the spatial dimension of the convolution (and disregarding
class, batch and channel dimensions for the sake of illustration), input data
of the form::
[[ a, b, c ],
[ d, e, f ],
[ g, h, i ],
[ j, k, l ]]
is mapped to [a, b+d, c+e+g, f+h+j, i+k, l].
Args:
x: 6D tensor of shape (num_classes, batch_size,
output_length, output_channels,
kernel_length, input_channels).
input_length: length of the returned tensor.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
stride: Integer stride.
Returns:
4D tensor of shape (num_classes, batch_size,
input_length, input_channels)
"""
# Sum over the output channels.
lam_sum = tf.reduce_sum(x, axis=3)
num_classes = x.shape[0].value
batch_size = tf.shape(x)[1]
kernel_length = x.shape[4].value
input_channels = x.shape[5].value
# Temporarily combine the (num_classes, batch_size, in_layer_channels) dims
# while applying a transpose convolution.
# Also use (kernel_length) as the channels
# as we'll apply the transpose convolution to each kernel point separately.
lam_squeezed = tf.transpose(lam_sum, perm=[0, 1, 4, 2, 3])
lam_squeezed = tf.reshape(lam_squeezed, shape=(
[num_classes * batch_size * input_channels] +
x.shape[2:3].as_list() +
[kernel_length]))
# De-convolve each elementary (i.e. one-hot) filter with the corresponding
# slice of lambda.
diagonal_kernel = tf.reshape(
tf.eye(kernel_length, dtype=x.dtype),
shape=[kernel_length, 1, kernel_length])
lam_deconv = tf.nn.conv1d_transpose(
lam_squeezed,
diagonal_kernel,
output_shape=([num_classes * batch_size * input_channels] +
[input_length, 1]),
padding=padding,
strides=stride)
# The resulting de-convolution has shape
# (num_classes*batch_size*in_layer_channels,
# in_layer_length, 1).
# Make it match mu_in.
result = tf.reshape(lam_deconv, shape=(
[num_classes, batch_size, input_channels] +
lam_deconv.shape[1:2].as_list()))
return tf.transpose(result, perm=[0, 1, 3, 2])
| deep-verify-master | deep_verify/src/common.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Graph construction for dual verification: Lagrangian calculation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sonnet as snt
import tensorflow as tf
class DualVerification(snt.AbstractModule):
"""Module to represent a network's Lagrangian, in terms of dual variables."""
def __init__(self, verification_strategy,
verifiable_layers,
target_strategy=None,
get_dual_variable=tf.get_variable,
name='dual_verification'):
"""Initialises the dual verification module.
Args:
verification_strategy: strategy object defining the dual verification
formulation, including what dual variables exist for each layer.
verifiable_layers: List of `VerifiableLayer` objects specifying
linear layers and non-linear activation functions.
target_strategy: target_objective_strategy object defining the objective
to optimize for the Lagrangian, default set to None, in which case we
will use the standard verification objective.
get_dual_variable: Function(name, shape, dtype) returning a dual variable.
It will be invoked by keyword arguments, so its arguments must be named
as given here, but may occur in any order.
name: Optional name for the module, defaulting to 'dual_verification'.
"""
super(DualVerification, self).__init__(name=name)
self._verification_strategy = verification_strategy
self._verifiable_layers = verifiable_layers
self._target_strategy = target_strategy
self._get_dual_variable = get_dual_variable
def _build(self, labels, num_batches, current_batch,
margin=0.,
objective_computation_config=None,
dataset_size=None):
"""Sets the up dual objective for the given network.
Dual variables are allocated for the entire dataset, covering all batches
as specified by `num_batches`. The dual objective accesses a slice of the
the dual variables specified by `current_batch`.
Args:
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
num_batches: Total number of batches in the dataset.
current_batch: 0D integer tensor containing index of current batch.
margin: Dual objective values for correct class will be forced to
`-margin`, thus disregarding large negative bounds when maximising.
objective_computation_config: Additional parameters for dual obj.
dataset_size: Size of dataset across all batches. By default this is
inferred from `num_batches * labels.shape[0]`, but can be set explictly
if not known at graph build time.
Returns:
2D tensor of shape (num_targets, batch_size) containing dual objective
values for each (class, example).
"""
# Dual variable generation across all batches.
if dataset_size is None:
batch_size = labels.shape[0]
dataset_size = num_batches * batch_size
else:
batch_size = tf.shape(labels)[0]
batch_lo = current_batch * batch_size
batch_hi = batch_lo + batch_size
def dual_var_getter(name, shape, dtype):
"""Creates a trainable tf.Variable for each dual variables."""
dual_var = self._get_dual_variable(name=name,
dtype=dtype,
shape=(shape[:1] + [dataset_size] +
shape[2:]))
# Return directly the tf.Variable if possible.
if dataset_size == batch_size:
return dual_var
# Select correct slice of dual variables for current batch.
sliced = dual_var[:, batch_lo:batch_hi]
sliced.set_shape(shape)
return sliced
(dual_obj, self._dual_var_lists, self._project_duals_op,
self._supporting_ops) = (
self._verification_strategy.create_duals_and_build_objective(
self._verifiable_layers,
labels,
dual_var_getter,
margin=margin,
target_strategy=self._target_strategy,
objective_computation_config=objective_computation_config))
return dual_obj
@property
def dual_var_lists(self):
"""TensorFlow variables for all dual variables."""
self._ensure_is_connected()
return self._dual_var_lists
@property
def project_duals_op(self):
"""TensorFlow operation to project all dual variables to their bounds."""
self._ensure_is_connected()
return self._project_duals_op
@property
def init_duals_op(self):
"""TensorFlow operation to initialize dual variables."""
return self.supporting_ops['init']
@property
def supporting_ops(self):
"""Additional TF ops (e.g. initialization) for the dual variables."""
self._ensure_is_connected()
return self._supporting_ops
def dual_variables_by_name(self, names):
"""Get dual variables by name."""
return _dual_variables_by_name(names, self.dual_var_lists)
def _dual_variables_by_name(names, dual_var_lists):
dual_vars = []
for dual_var_list in dual_var_lists:
for child_dual_var_lists in dual_var_list[:-1]:
dual_vars.extend(_dual_variables_by_name(names, child_dual_var_lists))
dual = dual_var_list[-1]
if dual is not None:
dual_vars.extend([dual[name] for name in names if name in dual])
return dual_vars
| deep-verify-master | deep_verify/src/verify_dual_direct.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Naive bound calculation for common neural network layers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src.bounds import layer_bounds
import interval_bound_propagation as ibp
import tensorflow as tf
def input_bounds(inputs, delta, lower_bound=0., upper_bound=1.,
preprocess_fn=None):
"""Calculates interval bounds on the network inputs.
Args:
inputs: 2D tensor of shape (batch_size, input_size), or 4D tensor of
shape (batch_size, height, width, channels), of input examples.
delta: Permitted perturbation on each input.
lower_bound: Scalar - smallest permissible input (pixel) value.
upper_bound: Scalar - largest permissible input (pixel) value.
preprocess_fn: Optional function mapping tensor to tensor
performing pre-processing on the raw inputs.
Returns:
`IntervalBounds` for the inputs, relative to `inputs`.
"""
# Input range, according to permitted perturbation radius.
if preprocess_fn:
lb = preprocess_fn(tf.maximum(inputs - delta, lower_bound)) - inputs
ub = preprocess_fn(tf.minimum(inputs + delta, upper_bound)) - inputs
else:
lb = tf.maximum(-delta, lower_bound - inputs)
ub = tf.minimum(delta, upper_bound - inputs)
return ibp.RelativeIntervalBounds(lb, ub, inputs)
class NaiveBoundPropagation(layer_bounds.BoundPropagation):
"""Naive layer-wise bound propagation method."""
| deep-verify-master | deep_verify/src/bounds/naive_bounds.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Bound calculation interface."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class BoundPropagation(object):
"""Method for propagating bounds through the layers."""
def propagate_bounds(self, network, in_bounds):
"""Calculates bounds on each layer.
Args:
network: `auto_verifier.NetworkBuilder` specifying network graph.
in_bounds: Bounds for the network inputs.
"""
network.propagate_bounds(in_bounds)
| deep-verify-master | deep_verify/src/bounds/layer_bounds.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Fast-Lin bound calculation for common neural network layers.
The Fast-Lin algorithm expresses lower and upper bounds of each layer of
a neural network as a symbolic linear expression in the input neurons,
relaxing the ReLU layers to retain linearity at the expense of tightness.
Reference: "Towards Fast Computation of Certified Robustness for ReLU Networks",
https://arxiv.org/pdf/1804.09699.pdf.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src.bounds import layer_bounds
import interval_bound_propagation as ibp
class FastlinBoundPropagation(layer_bounds.BoundPropagation):
"""Method for propagating symbolic bounds in multiple passes."""
def __init__(self, num_rounds=1, best_with_naive=False):
super(FastlinBoundPropagation, self).__init__()
self._num_rounds = num_rounds
self._best_with_naive = best_with_naive
def propagate_bounds(self, network, in_bounds):
if self._best_with_naive:
# Initial round of interval bound propagation.
super(FastlinBoundPropagation, self).propagate_bounds(network, in_bounds)
for _ in range(self._num_rounds):
# Construct symbolic bounds and propagate them.
super(FastlinBoundPropagation, self).propagate_bounds(
network, ibp.RelativeSymbolicBounds.convert(in_bounds))
| deep-verify-master | deep_verify/src/bounds/fastlin_bounds.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""IBP (interval bound propagation) extensions for dual verification.
Although the IBP library already provides both interval and symbolic bound
implementations, some of the dual verification computations are sensitive to
loss of accuracy from subtracting similar quantities, especially when very
small intervals are involved.
This sub-module provides alternative bound implementations that represent
the lower and upper bounds of an interval relative to some nominal value
within the interval, avoiding catastrophic loss of precision.
See section 6.1 of the paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| deep-verify-master | deep_verify/src/bounds/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Defines standard 'correct class' target objective specification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src.specifications import target_objective_base
import tensorflow as tf
class StandardTargetObjective(target_objective_base.TargetObjective):
"""Specifies the target objective to be minimized."""
def __init__(self, num_classes):
super(StandardTargetObjective, self).__init__()
self._num_targets = num_classes
def target_objective(self, final_w, final_b, labels):
"""Computes the true objective which is being optimized.
Args:
final_w: 2D tensor of shape (last_hidden_layer_size, num_classes)
containing the weights for the final linear layer.
final_b: 1D tensor of shape (num_classes) containing the biases for the
final hidden layer.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
Returns:
obj_w: Tensor of shape (num_targets, batch_size, last_hidden_layer_size)
containing weights (to use in place of final linear layer weights)
for targeted attacks.
obj_b: Tensor of shape (num_targets, batch_size) containing bias
(to use in place of final linear layer biases) for targeted attacks.
"""
# Elide objective with final linear layer.
final_wt = tf.transpose(final_w)
obj_w = (tf.expand_dims(final_wt, axis=1)
- tf.gather(final_wt, labels, axis=0))
obj_b = tf.expand_dims(final_b, axis=1) - tf.gather(final_b, labels, axis=0)
return obj_w, obj_b
def filter_correct_class(self, dual_obj, labels, margin=0.):
"""Filters out the objective when the target class contains the true label.
Args:
dual_obj: 2D tensor of shape (num_targets, batch_size) containing
dual objectives.
labels: 1D tensor of shape (batch_size) containing the labels for each
example in the batch.
margin: Dual objective values for correct class will be forced to
`-margin`, thus disregarding large negative bounds when maximising. By
default this is set to 0.
Returns:
2D tensor of shape (num_classes, batch_size) containing the corrected dual
objective values for each (class, example).
"""
neq = self.neq(labels)
dual_obj = tf.where(neq, dual_obj, -margin * tf.ones_like(dual_obj))
return dual_obj
def neq(self, labels):
assert hasattr(labels, 'dtype')
targets_to_filter = tf.expand_dims(
tf.range(self._num_targets, dtype=labels.dtype), axis=1)
return tf.not_equal(targets_to_filter, labels)
@property
def num_targets(self):
return self._num_targets
| deep-verify-master | deep_verify/src/specifications/target_objective_standard.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Primal objective specifications.
This module defines the interface for specifying the property to be verified
on the outputs of the network. It also provides a standard implementation
for a classifier, in which the specification is that the largest logit output
is that of the true class.
See section 3.2 of the paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| deep-verify-master | deep_verify/src/specifications/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Defines a target objective specification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class TargetObjective(object):
"""Specifies the target objective to be minimized."""
@abc.abstractmethod
def target_objective(self, final_w, final_b, labels):
"""Computes the true objective which is being optimized.
Args:
final_w: 2D tensor of shape (last_hidden_layer_size, num_classes)
containing the weights for the final linear layer.
final_b: 1D tensor of shape (num_classes) containing the biases for the
final hidden layer.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
Returns:
obj_w: Tensor of shape (num_targets, batch_size, last_hidden_layer_size)
containing weights (to use in place of final linear layer weights)
for targeted attacks.
obj_b: Tensor of shape (num_targets, batch_size) containing bias
(to use in place of final linear layer biases) for targeted attacks.
"""
@abc.abstractmethod
def filter_correct_class(self, dual_obj, labels, margin):
"""Filters out the objective when the target class contains the true label.
Args:
dual_obj: 2D tensor of shape (num_targets, batch_size) containing
dual objectives.
labels: 1D tensor of shape (batch_size) containing the labels for each
example in the batch.
margin: Dual objective values for correct class will be forced to
`-margin`, thus disregarding large negative bounds when maximising.
Returns:
2D tensor of shape (num_classes, batch_size) containing the corrected dual
objective values for each (class, example).
"""
@abc.abstractproperty
def num_targets(self):
"""Returns the number of targets in the objective."""
| deep-verify-master | deep_verify/src/specifications/target_objective_base.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Defines composite layers with customised dual variables."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src.layers import layers
import sonnet as snt
import tensorflow as tf
class CombinedLayer(layers.VerifiableLayer):
"""Activation plus linear layer, treated together (used by reduced)."""
def __init__(self, activation_layer, linear_layer):
if linear_layer.is_activation:
raise ValueError('Second layer must not be an activation layer')
super(CombinedLayer, self).__init__()
self._activation_layer = activation_layer
self._linear_layer = linear_layer
@property
def activation_layer(self):
return self._activation_layer
@property
def linear_layer(self):
return self._linear_layer
@property
def branches(self):
return self._linear_layer.branches
@property
def input_node(self):
return self._activation_layer.input_node
@property
def output_node(self):
return self._linear_layer.output_node
@property
def reshape(self):
return self._activation_layer.reshape
def reshape_duals_backwards(self, dual_vars):
if self.linear_layer.reshape:
# There was a reshape prior to the linear layer.
dual_vars = snt.BatchReshape(self.activation_layer.output_shape,
preserve_dims=2)(dual_vars)
return dual_vars
class CombinedLinearLayer(layers.VerifiableLayer):
"""Wraps linear layers, treating them as a single linear layer."""
def __init__(self, first_layer, second_layer):
"""Constructor.
Args:
first_layer: `AffineLayer` or `CombinedLinearLayer`.
second_layer: `AffineLayer` or `CombinedLinearLayer`.
"""
super(CombinedLinearLayer, self).__init__()
self._first_layer = first_layer
self._second_layer = second_layer
@property
def first_layer(self):
return self._first_layer
@property
def second_layer(self):
return self._second_layer
@property
def branches(self):
return self._second_layer.branches
@property
def input_node(self):
return self._first_layer.input_node
@property
def output_node(self):
return self._second_layer.output_node
@property
def reshape(self):
return self._first_layer.reshape
@property
def is_activation(self):
return False
def reshape_duals_backwards(self, dual_vars):
if self._second_layer.reshape:
# There was a reshape prior to the second layer.
dual_vars = snt.BatchReshape(self._first_layer.output_shape,
preserve_dims=2)(dual_vars)
return dual_vars
def get_objective_weights(self, labels, target_strategy=None):
# Obtain the final objective according to the second layer.
next_obj_w, next_obj_b = self._second_layer.get_objective_weights(
labels, target_strategy=target_strategy)
# Un-flatten the final objective.
num_classes = next_obj_w.shape[0].value
batch_size = tf.shape(next_obj_w)[1]
next_obj_w = tf.reshape(
next_obj_w, [num_classes, batch_size] +
list(self._first_layer.output_shape))
# If this layer is w1_ij, b1_j
# and the second layer's objective is w2_knj, b2_kn
# then the overall objective is given by wr_kni, br_kn as follows:
# w1_ij w2_knj -> wr_kni
# b1_j w2_knj + b2_kn -> br_kn
obj_w, obj_b = self._first_layer.backward_prop_batchnorm_bias(next_obj_w,
next_obj_b)
obj_b = obj_b + self._first_layer.backward_prop_bias(obj_w)
obj_w = self._first_layer.backward_prop(obj_w)
return layers.ObjectiveWeights(obj_w, obj_b)
def forward_prop(self, x, apply_bias=False, w_fn=None):
if (self._first_layer.batch_norm is not None or
self._second_layer.batch_norm is not None):
raise ValueError('Batch norm not supported.')
x = self._first_layer.forward_prop(x, apply_bias=apply_bias, w_fn=w_fn)
x = self._first_layer.reshape_duals_forwards(x, self._second_layer)
x = self._second_layer.forward_prop(x, apply_bias=apply_bias, w_fn=w_fn)
return x
def backward_prop(self, y, w_fn=None):
y = self._second_layer.backward_prop_batchnorm(y)
y = self._second_layer.backward_prop(y, w_fn=w_fn)
y = self.reshape_duals_backwards(y)
y = self._first_layer.backward_prop_batchnorm(y)
y = self._first_layer.backward_prop(y, w_fn=w_fn)
return y
def backward_prop_bias(self, y):
bias = tf.zeros(tf.shape(y)[:2], dtype=y.dtype)
y, bias = self._second_layer.backward_prop_batchnorm_bias(y, bias)
bias = bias + self._second_layer.backward_prop_bias(y)
y = self._second_layer.backward_prop(y)
y = self.reshape_duals_backwards(y)
y, bias = self._first_layer.backward_prop_batchnorm_bias(y, bias)
bias = bias + self._first_layer.backward_prop_bias(y)
return bias
def flatten(self):
if (self._first_layer.batch_norm is not None or
self._second_layer.batch_norm is not None):
raise ValueError('Batch norm not supported.')
return tf.matmul(self._first_layer.flatten(),
self._second_layer.flatten())
def backward_prop_batchnorm(self, y):
return y
def backward_prop_batchnorm_bias(self, y, bias):
return y, bias
def combine_trailing_linear_layers(verifiable_layers):
"""If the network culminates in two or more linear layers, combines them.
Args:
verifiable_layers: List of `SingleVerifiableLayer`.
Returns:
List of `VerifiableLayer` in which trailing linear layers have been combined
into one.
Raises:
ValueError: if an unsupported layer type or arrangement is encountered.
"""
if not isinstance(verifiable_layers[-1], layers.Linear):
raise ValueError('Final layers other than linear are not supported.')
# Take a copy, to avoid mutating the input.
final_layer = verifiable_layers[-1]
verifiable_layers = verifiable_layers[:-1]
while len(verifiable_layers) and not verifiable_layers[-1].is_activation:
# Combine the last two layers.
linear_layer = verifiable_layers.pop()
final_layer = CombinedLinearLayer(linear_layer, final_layer)
verifiable_layers.append(final_layer)
return verifiable_layers
| deep-verify-master | deep_verify/src/layers/layers_combined.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Layer wrappers for verification, allowing dual variables to be defined.
Instances of `layers.VerifiableLayer` are created by the graph analyser
(`auto_verifier.VerifiableLayerBuilder`) to wrap a single layer of the network.
Individual dual formulations may choose to further combine these into coarser
blocks (e.g. activation+linear) that form meaningful units for the verification
method.
In general, any verifiable layer will declare some dual variables to be
associated with that layer. Optimising with respect to the duals (for each
input example) will give the greatest chance of finding a verifiability proof.
By default, a layer will have a single dual variable for each output neuron,
corresponding to the Lagrange multiplier for the constrant that the neuron's
value matches the corresponding input value on the next layer. Other
non-standard formulations can define custom layer groupings specifying
their own collections of dual variables.
For more details see paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| deep-verify-master | deep_verify/src/layers/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Defines wrappers to easily propagate bounds."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
from deep_verify.src import common
from interval_bound_propagation import layer_utils
import six
import sonnet as snt
import tensorflow as tf
# Holds objective weights.
# The last layer can be combined with the target vector `c`.
ObjectiveWeights = collections.namedtuple('ObjectiveWeights', ['w', 'b'])
@six.add_metaclass(abc.ABCMeta)
class VerifiableLayer(object):
"""Abstract class for dual layers."""
def __init__(self):
self._no_duals = False
@property
def branches(self):
"""Returns list of (name, sub-layers list) pairs, e.g. for ResNet block."""
return []
@abc.abstractproperty
def input_node(self):
"""Returns an `ibp.VerifiableWrapper` for the previous layer's outputs."""
@abc.abstractproperty
def output_node(self):
"""Returns an `ibp.VerifiableWrapper` for this layer's outputs."""
@property
def input_shape(self):
return self.input_bounds.shape[1:]
@property
def output_shape(self):
return self.output_bounds.shape[1:]
@property
def inputs(self):
return self.input_bounds.nominal
@property
def outputs(self):
return self.output_bounds.nominal
@property
def input_bounds(self):
return self.input_node.output_bounds.concretize()
@property
def output_bounds(self):
return self.output_node.output_bounds.concretize()
def dual_shape(self):
"""Returns shape of the dual variable, or possibly nested dict thereof."""
# By default, there is one dual variable for each output.
return None if self._no_duals else tuple(self.output_shape)
def set_no_duals(self):
"""Declares that this layer has no dual variables of its own."""
self._no_duals = True
def reshape_duals_forwards(self, next_layer, dual_vars):
if next_layer.reshape:
# There was a reshape prior to the next layer.
dual_vars = snt.BatchReshape(next_layer.input_shape,
preserve_dims=2)(dual_vars)
return dual_vars
def project_duals_op(self, dual_vars): # pylint:disable=unused-argument
"""Projects duals into their regional constraints.
Args:
dual_vars: Dual variable tensor.
Returns:
Assignment op to modify `dual_vars`, clamping the dual variable
values to their admissible ranges.
"""
# By default, do no projection.
return tf.no_op()
@six.add_metaclass(abc.ABCMeta)
class CustomOp(object):
"""Function or operation with a different implementation for each layer type.
Each `visit_xxx` method is a call-back invoked via
`SingleVerfiableLayer.custom_op`. They have implementation-specific *args and
**kwargs, passed through by `SingleVerifiableLayer.custom_op`, for convenience
so that the same visitor instance can be used multiple times with different
arguments.
"""
def visit_linear(self, layer, w, b, *args, **kwargs):
"""Callback for `Linear`."""
raise NotImplementedError()
def visit_conv(self, layer, w, b, padding, strides, *args, **kwargs):
"""Callback for `Conv`."""
raise NotImplementedError()
def visit_avgpool(self, layer, *args, **kwargs):
"""Callback for `AvgPool`."""
raise NotImplementedError('AvgPool layers are not supported')
def visit_maxpool(self, layer, *args, **kwargs):
"""Callback for `MaxPool`."""
raise NotImplementedError('MaxPool layers are not supported')
@abc.abstractmethod
def visit_activation(self, layer, *args, **kwargs):
"""Callback for `Activation`."""
@six.add_metaclass(abc.ABCMeta)
class SingleVerifiableLayer(VerifiableLayer):
"""Dual layer for a single layer of the underlying network."""
def __init__(self, input_node, output_node, module,
batch_norm=None, reshape=False):
super(SingleVerifiableLayer, self).__init__()
self._module = module
self._batch_norm = batch_norm
self._reshape = reshape
self._input_node = input_node
self._output_node = output_node
@property
def input_node(self):
return self._input_node
@property
def output_node(self):
return self._output_node
@abc.abstractproperty
def is_activation(self):
"""Returns whether an activation layer, as opposed to linear/conv."""
@property
def module(self):
return self._module
@property
def batch_norm(self):
return self._batch_norm
@property
def reshape(self):
return self._reshape
def backward_prop_batchnorm(self, y):
if self.batch_norm is not None:
w, _ = layer_utils.decode_batchnorm(self.batch_norm)
y = y * tf.cast(w, y.dtype)
return y
def backward_prop_batchnorm_bias(self, y, bias):
if self.batch_norm is not None:
w, b = layer_utils.decode_batchnorm(self.batch_norm)
bias = bias + tf.reduce_sum(y * tf.cast(b, y.dtype),
axis=list(range(2, y.shape.ndims)))
y = y * tf.cast(w, y.dtype)
return y, bias
@abc.abstractmethod
def custom_op(self, op, *args, **kwargs):
"""Double-dispatch: invokes a `visit_xxx` method on `op`."""
@six.add_metaclass(abc.ABCMeta)
class AffineLayer(SingleVerifiableLayer):
"""Layer that acts as an affine transform, e.g. linear or convolution."""
@property
def is_activation(self):
return False
@abc.abstractmethod
def forward_prop(self, x, apply_bias=False, w_fn=None):
"""Applies the affine transform to a tensor.
Args:
x: Tensor of shape (num_targets, batch_size, input_shape...).
apply_bias: whether to include the `b` contribution.
w_fn: Optional elementwise preprocessing function to apply to `w`,
for example `tf.abs`.
Returns:
Tensor of shape (num_targets, batch_size, output_shape...),
containing w x + b .
"""
@abc.abstractmethod
def backward_prop(self, y, w_fn=None):
"""Applies the transpose of the affine transform to a tensor.
Args:
y: Tensor of shape (num_targets, batch_size, output_shape...).
w_fn: Optional elementwise preprocessing function to apply to `w`,
for example `tf.abs`.
Returns:
Tensor of shape (num_targets, batch_size, input_shape...),
containing w^T y .
"""
@abc.abstractmethod
def backward_prop_bias(self, y):
"""Takes the scalar product of the bias with a tensor.
Args:
y: Tensor of shape (num_targets, batch_size, output_shape...).
Returns:
Tensor of shape (num_targets, batch_size),
containing b^T y .
"""
@abc.abstractmethod
def flatten(self):
"""Flattens the affine transform, materialising it as fully connected.
Returns:
w_flat:
2D tensor of shape (input_size, output_size).
b_flat:
1D tensor of shape (output_size).
"""
class Conv(AffineLayer):
"""Wraps a convolutional layer."""
def __init__(self, input_node, output_node, module, batch_norm=None,
reshape=False):
super(Conv, self).__init__(input_node, output_node, module,
batch_norm=batch_norm, reshape=reshape)
self._w = module.w
self._b = module.b if module.has_bias else None
self._padding = module.padding
self._strides = module.stride[1:-1]
def forward_prop(self, x, apply_bias=False, w_fn=None):
w = w_fn(self._w) if w_fn is not None else self._w
y = common.convolution(x, tf.cast(w, x.dtype),
padding=self._padding, strides=self._strides)
if apply_bias and self._b is not None:
y += tf.cast(self._b, x.dtype)
return y
def backward_prop(self, y, w_fn=None):
w = w_fn(self._w) if w_fn is not None else self._w
return common.conv_transpose(y, tf.cast(w, y.dtype),
result_shape=self.input_shape,
padding=self._padding, strides=self._strides)
def backward_prop_bias(self, y):
if self._b is not None:
return tf.reduce_sum(y * tf.cast(self._b, y.dtype),
axis=list(range(2, y.shape.ndims)))
else:
return tf.zeros(tf.shape(y)[:2], dtype=y.dtype)
def flatten(self):
return layer_utils.materialise_conv(
self._w, self._b, input_shape=self.input_shape,
padding=self._padding, strides=self._strides)
def custom_op(self, op, *args, **kwargs):
return op.visit_conv(self, self._w, self._b,
self._padding, self._strides, *args, **kwargs)
class Linear(AffineLayer):
"""Wraps a linear layer."""
def __init__(self, input_node, output_node, module, batch_norm=None,
reshape=False):
super(Linear, self).__init__(input_node, output_node, module,
batch_norm=batch_norm, reshape=reshape)
self._w = module.w
self._b = module.b if module.has_bias else None
def forward_prop(self, x, apply_bias=False, w_fn=None):
w = w_fn(self._w) if w_fn is not None else self._w
y = tf.tensordot(x, tf.cast(w, x.dtype), axes=1)
if apply_bias and self._b is not None:
y += tf.cast(self._b, x.dtype)
return y
def backward_prop(self, y, w_fn=None):
w = w_fn(self._w) if w_fn is not None else self._w
return tf.tensordot(y, tf.transpose(tf.cast(w, y.dtype)), axes=1)
def backward_prop_bias(self, y):
if self._b is not None:
return tf.tensordot(y, tf.cast(self._b, y.dtype), axes=1)
else:
return tf.zeros(tf.shape(y)[:2], dtype=y.dtype)
def flatten(self):
return self._w, self._b
def custom_op(self, op, *args, **kwargs):
return op.visit_linear(self, self._w, self._b, *args, **kwargs)
def get_objective_weights(self, labels, target_strategy=None):
"""Elides the objective with this (final) linear layer."""
assert self._b is not None, 'Last layer must have a bias.'
if target_strategy is None:
w, b = common.targeted_objective(self._w, self._b, labels)
else:
w, b = target_strategy.target_objective(self._w, self._b, labels)
return ObjectiveWeights(w, b)
class AvgPool(AffineLayer):
"""Wraps an average-pool layer."""
def __init__(self, input_node, output_node,
kernel_shape, strides, reshape=False):
super(AvgPool, self).__init__(input_node, output_node,
module=None,
reshape=reshape)
self._kernel_shape = list(kernel_shape) if kernel_shape else None
self._strides = list(strides) if strides else None
@property
def kernel_shape(self):
return self._kernel_shape
@property
def strides(self):
return self._strides
def forward_prop(self, x, apply_bias=False, w_fn=None):
return self._module(x)
def backward_prop(self, y, w_fn=None):
del w_fn
return common.avgpool_transpose(y, result_shape=self.input_shape,
kernel_shape=self.kernel_shape,
strides=self.strides)
def backward_prop_bias(self, y):
return tf.zeros(tf.shape(y)[:2], dtype=y.dtype)
def flatten(self):
raise NotImplementedError()
def custom_op(self, op, *args, **kwargs):
return op.visit_avgpool(self, *args, **kwargs)
class MaxPool(SingleVerifiableLayer):
"""Wraps a max-pool layer."""
def __init__(self, input_node, output_node,
kernel_shape, strides, with_relu=False, reshape=False):
super(MaxPool, self).__init__(input_node, output_node,
module=None,
reshape=reshape)
self._kernel_shape = list(kernel_shape) if kernel_shape else None
self._strides = list(strides) if strides else None
self._with_relu = with_relu
@property
def kernel_shape(self):
return self._kernel_shape
@property
def strides(self):
return self._strides
@property
def with_relu(self):
return self._with_relu
@property
def is_activation(self):
return True
def custom_op(self, op, *args, **kwargs):
return op.visit_maxpool(self, *args, **kwargs)
class Activation(SingleVerifiableLayer):
"""Wraps an activation."""
def __init__(self, input_node, output_node, module,
reshape=False, parameters=None):
super(Activation, self).__init__(input_node, output_node, module,
reshape=reshape)
self._activation = module.__name__ # Convert to string.
self._parameters = parameters
@property
def is_activation(self):
return True
@property
def activation(self):
return self._activation
@property
def parameters(self):
return self._parameters
def custom_op(self, op, *args, **kwargs):
return op.visit_activation(self, *args, **kwargs)
def create_verifiable_layer(input_node, output_node, module,
batch_norm=None, reshape=False,
parameters=None):
"""Returns an instance of `SingleVerifiableLayer` for the specified module."""
if isinstance(module, snt.Conv2D) or isinstance(module, snt.Conv1D):
return Conv(input_node, output_node, module, batch_norm, reshape)
elif isinstance(module, snt.Linear):
return Linear(input_node, output_node, module, batch_norm, reshape)
else:
if batch_norm is not None:
raise ValueError('Cannot add a batch normalization layer to an '
'activation.')
return Activation(input_node, output_node, module, reshape,
parameters=parameters)
| deep-verify-master | deep_verify/src/layers/layers.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Defines a strategy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
from absl import logging
from deep_verify.src.specifications import target_objective_standard
import six
import tensorflow as tf
@six.add_metaclass(abc.ABCMeta)
class DualFormulation(object):
"""Specifies which dual variables exist for which layers."""
@abc.abstractmethod
def group_layers(self, verifiable_layers):
"""Groups dual layers as required by the verification strategy.
Args:
verifiable_layers: List of `SingleVerifiableLayer` objects specifying
linear layers and non-linear activation functions.
Returns:
List of `VerifiableLayer` objects specifying layers that give rise to
dual variables.
Raises:
ValueError: if an unsupported layer type or arrangement is encountered.
"""
@abc.abstractmethod
def dual_objective(self, verifiable_layers, labels, dual_var_lists,
target_strategy=None, objective_computation_config=None):
"""Computes the Lagrangian (dual objective).
Args:
verifiable_layers: List of `VerifiableLayer` objects specifying layers
that give rise to dual variables.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
dual_var_lists: Nested list of 3D tensors of shape
(num_classes, batch_size, layer_size) and 5D tensors of shape
(num_classes, batch_size, height, width, channels)
containing Lagrange multipliers for the layers' calculations.
This has the same length as `verifiable_layers`, and typically each
entry is a singleton list with the dual variable for that layer.
ResNet blocks' entries have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
target_strategy: a `TargetObjective` object which gets the objective
weights of the final layer depending on the strategy of the final
objective. Default is set to None in which case it uses the default
target strategy.
objective_computation_config: `ConfigDict` of additional parameters.
Returns:
2D tensor of shape (num_classes, batch_size) containing dual objective
for each target class, for each example.
"""
def create_duals_and_build_objective(
self, verifiable_layers,
labels,
dual_var_getter,
margin=0.,
target_strategy=None,
objective_computation_config=None):
"""Sets the up dual objective.
Args:
verifiable_layers: List of `VerifiableLayer` objects specifying layers
that give rise to dual variables.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
dual_var_getter: Function(name, shape, dtype) returning a dual variable.
margin: Dual objective values for correct class will be forced to
`-margin`, thus disregarding large negative bounds when maximising.
target_strategy: target_objective_strategy object defining the objective
to optimize for the Lagrangian, default set to None, in which case we
will use the standard verification objective.
objective_computation_config: Additional params to dual obj calculation.
Returns:
dual_objective: 2D tensor of shape (num_classes, batch_size) containing
dual objective values for each (class, example).
dual_var_lists: Nested list of 3D tensors of shape
(num_classes, batch_size, layer_size) and 5D tensors of shape
(num_classes, batch_size, height, width, channels)
containing Lagrange multipliers for the layers' calculations.
This has the same length as `verifiable_layers`, and typically each
entry is a singleton list with the dual variable for that layer.
ResNet blocks' entries have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
init_duals_op: TensorFlow operation to initialise all dual variables.
project_duals_op: TensorFlow operation to project all dual variables
to their bounds.
supporting_ops: Dictionary of additional ops (e.g. 'init') for
manipulating the dual variables.
The set of keys is implementation-dependent, according to what the
particular formulation supports.
"""
target_strategy = target_strategy or (
target_objective_standard.StandardTargetObjective(
verifiable_layers[-1].output_shape[-1]))
batch_size = labels.shape[0]
dtype = verifiable_layers[-1].output_bounds.lower.dtype
# Obtain TensorFlow variables for all dual variables.
def dual_var_getter_full(unused_layer, name, dual_shape):
return dual_var_getter(name=name,
dtype=dtype,
shape=([target_strategy.num_targets, batch_size] +
list(dual_shape)))
dual_var_lists = build_dual_vars(verifiable_layers,
dual_var_getter_full)
# Create a 'project' TensorFlow op to clamp the dual vars to their bounds.
project_duals_op = build_project_duals_op(verifiable_layers, dual_var_lists)
# Calculate the dual objective.
dual_obj = self.dual_objective(
verifiable_layers, labels, dual_var_lists,
target_strategy=target_strategy,
objective_computation_config=objective_computation_config)
# Filter out cases in which the target class is the correct class.
dual_obj = target_strategy.filter_correct_class(
dual_obj, tf.cast(labels, tf.int32), margin=margin)
# Build additional ops to manipulate the variables (e.g. initialisation).
supporting_ops = self.create_supporting_ops(
verifiable_layers, labels, dual_var_lists,
target_strategy=target_strategy,
objective_computation_config=objective_computation_config)
return dual_obj, dual_var_lists, project_duals_op, supporting_ops
def create_supporting_ops(self, verifiable_layers, labels, dual_var_lists,
target_strategy=None,
objective_computation_config=None):
"""Creates additional ops (e.g. initialization) for the dual variables.
Args:
verifiable_layers: List of `VerifiableLayer` objects specifying layers
that give rise to dual variables.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
dual_var_lists: Nested list of 3D tensors of shape
(num_classes, batch_size, layer_size) and 5D tensors of shape
(num_classes, batch_size, height, width, channels)
containing Lagrange multipliers for the layers' calculations.
This has the same length as `verifiable_layers`, and typically each
entry is a singleton list with the dual variable for that layer.
ResNet blocks' entries have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
target_strategy: a `TargetObjective` object which gets the objective
weights of the final layer depending on the strategy of the final
objective. Default is set to None in which case it uses the default
target strategy.
objective_computation_config: `ConfigDict` of additional parameters.
Returns:
Dictionary containing additional ops.
The set of keys is implementation-dependent, according to what a
particular formulation supports.
"""
del verifiable_layers, labels, dual_var_lists, target_strategy
del objective_computation_config
return {'init': tf.no_op()}
def build_dual_vars(verifiable_layers, dual_var_getter):
"""Creates dual variable list for the given layers.
Args:
verifiable_layers: Layers for which dual variables should be generated.
dual_var_getter: Function(layer, name, shape) returning a dual variable.
Returns:
Nested list of dual variable tensors, one list for each layer.
Each layer typically has a singleton list with its dual variable.
ResNet blocks will have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
"""
return [_dual_var_list_for_layer(dual_var_getter, layer, 'dual_{}'.format(i))
for i, layer in enumerate(verifiable_layers)]
def _dual_var_for_layer(dual_var_getter, layer, name, shape):
"""Creates a dual variable for the given layer shape.
Args:
dual_var_getter: Function(name, shape) returning a dual variable.
layer: Layer for which dual variables should be generated.
name: Name to use for dual variable.
shape: Shape of the dual variable, or a possibly nested dict of shapes.
Returns:
Dual variable tensors of the given shape, or a possibly nested dict of
such tensors according to the structure of `shape`.
"""
if isinstance(shape, dict):
return {k: _dual_var_for_layer(dual_var_getter, layer, name + '_' + k, v)
for k, v in shape.items()}
else:
return dual_var_getter(layer, name, shape)
def _dual_var_list_for_layer(dual_var_getter, layer, name):
"""Creates dual variable list for the given layer.
Args:
dual_var_getter: Function(name, shape) returning a dual variable.
layer: Layer for which dual variables should be generated.
name: Name to use for dual variable.
Returns:
List of dual variable tensors. Entries may be `None`.
This is typically a singleton list with the dual variable for the layer.
ResNet blocks will have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
"""
# Dual variable may not be required.
if layer.dual_shape() is None:
dual_var = None
else:
dual_var = _dual_var_for_layer(dual_var_getter, layer, name,
layer.dual_shape())
dual_var_list = []
# Precede with dual vars for branches, if it's a ResNet block.
for branch_name, branch_layers in layer.branches:
child_dual_var_lists = [
_dual_var_list_for_layer(dual_var_getter, sublayer,
'{}_{}_{}'.format(name, branch_name, i))
for i, sublayer in enumerate(branch_layers)]
dual_var_list.append(child_dual_var_lists)
dual_var_list.append(dual_var)
return dual_var_list
def build_project_duals_op(verifiable_layers, dual_var_lists):
"""Projects duals into their regional constraints.
Args:
verifiable_layers: List of `VerifiableLayer` objects specifying layers
that give rise to dual variables.
dual_var_lists: Nested list of TensorFlow variables containing Lagrange
multipliers for the layers' calculations.
This has the same length as `verifiable_layers`, and typically each
entry is a singleton list with the dual variable for that layer.
ResNet blocks' entries have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
Returns:
TensorFlow operation that updates the variables in `dual_var_lists`,
clamping them to their admissible ranges (where relevant).
"""
return tf.group(
*[_project_duals_op_for_layer(layer, dual_var_list)
for layer, dual_var_list in zip(verifiable_layers, dual_var_lists)])
def _project_duals_op_for_layer(layer, dual_var_list):
"""Returns op that updates duals for a single layer."""
# Dual variable may not be required.
if layer.dual_shape() is None:
project_op = tf.no_op()
else:
try:
project_op = layer.project_duals_op(dual_var_list[-1])
except (ValueError, AttributeError):
logging.warn('Cannot create projection.')
# Use an un-fed placeholder to force an error at graph execution time.
with tf.control_dependencies([tf.placeholder(dtype=tf.float32,
shape=(),
name='cannot_project')]):
project_op = tf.no_op()
project_ops = []
# Precede with dual vars for branches, if it's a ResNet block.
for (_, branch_layers), child_dual_var_lists in zip(layer.branches,
dual_var_list[:-1]):
project_ops.append(
build_project_duals_op(branch_layers, child_dual_var_lists))
project_ops.append(project_op)
return tf.group(*project_ops)
| deep-verify-master | deep_verify/src/formulations/verify_dual_base.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dual formulations of verification.
This module defines the interface for layer-wise formulations of verifiable
robustness that involve optimising dual variables (such as Lagrange multipliers)
associated with the layers.
For more details see paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| deep-verify-master | deep_verify/src/formulations/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Calculations relating to the Gram matrix of a convolution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src import common
from interval_bound_propagation import layer_utils
import numpy as np
import tensorflow as tf
def conv_weighted_gram_matrix(w, d, input_shape, padding, strides,
w_s=None):
"""Calculates W^T d W for an N-D convolution W, exploiting sparsity.
Args:
w: (N+2)D tensor of shape (kernel_height, kernel_width,
input_channels, output_channels) containing the convolutional kernel.
d: (N+3)D tensor of shape (num_targets, batch_size,
output_height, output_width, output_channels), interpreted as a
diagonal weight matrix.
input_shape: List of length N+1 specifying
[input_height, input_width, input_channels].
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
w_s: Optional (N+2)D tensor of shape (kernel_height, kernel_width,
input_slice_channels, output_channels) containing a slice of `w`
(over input_channels) if it is desired to build the Gram matrix a few
columns at a time; defaults to `w` to build the Gram matrix in full.
Returns:
(2N+4)D tensor of shape (num_targets, batch_size,
input_height, input_width, input_slice_channels,
2*kernel_height-1, 2*kernel_width-1, input_channels)
expressing W^T d W in a sheared form to exploit sparsity.
"""
w_s = w_s if w_s is not None else w
num_targets = d.shape[0].value
batch_size = tf.shape(d)[1]
n = w.shape.ndims - 2
kernel_shape = w.shape[:-2].as_list()
input_channels = w.shape[-2].value
input_slice_channels = w_s.shape[-2].value
output_channels = w.shape[-1].value
enlarged_kernel_shape = [2*s-1 for s in kernel_shape]
# We wish to combine W with itself at different kernel offsets,
# from -kernel_size to +kernel_size (exclusive).
# Achieve this by considering W (kernel) as a new stride-1 deconvolution.
w_offset, _ = layer_utils.materialise_conv(
tf.reverse(w, axis=list(range(n))), None,
input_shape=(enlarged_kernel_shape + [-1]),
padding='VALID', strides=(n*[1]))
# The above materialises it as a 2D tensor with shape
# (enlarged_kernel_shape*input_channels,
# kernel_height*kernel_width*output_channels).
w_offset = tf.reshape(w_offset, shape=(
[1] + enlarged_kernel_shape + [input_channels] +
kernel_shape + [output_channels]))
w_offset = tf.transpose(tf.reverse(w_offset, axis=list(range(1, n+1))),
perm=(list(range(n+2, 2*n+2)) +
list(range(n+2)) + [2*n+2]))
# W_offset is now a (2N+3)D tensor with shape
# (kernel_height, kernel_width, 1,
# 2*kernel_height-1, 2*kernel_width-1, input_channels, output_channels).
# Take all relevant pair-wise products of W with W_offset.
wtw = w_offset * tf.reshape(w_s, shape=(
kernel_shape + [input_slice_channels] + (n*[1]) + [1, output_channels]))
# WTW is a (2N+3)D tensor with shape
# (kernel_height, kernel_width, input_slice_channels,
# 2*kernel_height-1, 2*kernel_width-1, input_channels, output_channels).
# Combine with d, by performing a deconvolution.
wtw = tf.reshape(wtw, shape=(
kernel_shape +
[input_slice_channels*np.prod(enlarged_kernel_shape)*input_channels,
output_channels]))
result = common.conv_transpose(d, wtw,
input_shape[:-1] + [wtw.shape[n].value],
padding, strides)
# Output from common.conv_transpose is of shape:
# (num_targets, batch_size, input_height, input_width,
# input_slice_channels*enlarged_kernel_shape*input_channels).
result = tf.reshape(result, shape=(
[num_targets, batch_size] + input_shape[:-1] + [input_slice_channels] +
enlarged_kernel_shape + [input_channels]))
# Return a (2N+4)D tensor of shape (num_targets, batch_size,
# input_height, input_width, input_slice_channels,
# 2*kernel_height-1, 2*kernel_width-1, input_channels).
return result
def _conv_projection_slice(w, d, w_s, beta, padding, strides,
abs_fn=tf.abs):
"""Calculates a partial projection of | W^T d W |.
Computes sum_j |Q_ij| beta_j where Q = W^T d W_s is a slice of the
weighted Gram matrix and j indexes the column channels included in the slice.
Args:
w: (N+2)D tensor of shape (kernel_height, kernel_width,
input_channels, output_channels) containing the convolutional kernel.
d: (N+3)D tensor of shape (num_targets, batch_size,
output_height, output_width, output_channels), interpreted as a
diagonal weight matrix.
w_s: (N+2)D tensor of shape (kernel_height, kernel_width,
input_slice_channels, output_channels) containing the
desired slice of `w`.
beta: (N+3)D tensor of shape (num_targets, batch_size, input_height,
input_width, input_slice_channels) specifying the projection.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
abs_fn: Absolute value function; defaults to `tf.abs`.
Returns:
(N+3)D tensor of shape (num_targets, batch_size,
input_height, input_width, input_slice_channels) containing
sum_j |Q_ij| beta_j.
"""
num_targets = d.shape[0].value
batch_size = tf.shape(d)[1]
n = w.shape.ndims - 2
input_shape = beta.shape[2:].as_list()
wt_d_w = conv_weighted_gram_matrix(w, d, input_shape, padding, strides,
w_s=w_s)
# wt_d_w is a (2N+4)D tensor of shape (num_targets, batch_size,
# input_height, input_width, input_slice_channels,
# 2*kernel_height-1, 2*kernel_width-1, input_channels).
a = abs_fn(wt_d_w) * tf.reshape(beta, shape=(
[num_targets, batch_size] + input_shape + (n*[1]) + [1]))
return common.conv_reduce_sum(a, input_shape,
padding='SAME', strides=(n*[1]))
def conv_weighted_gram_abs_projection(w, d, beta, padding, strides,
abs_fn=tf.abs,
block_size=0):
"""Calculates a projection of | W^T d W | for an N-D convolution W.
Computes beta_i^{-1} sum_j |Q_ij| beta_j where Q = W^T d W is the
weighted Gram matrix for the convolution.
The computation exploits sparsity of the convolution, thereby managing
to run in O(K^2 M C^3 + K^3 M C^2) time per example, for C channels,
spatial size M, and kernel size K. By comparison, working with
a fully materialised MCxMC matrix would require O(M^3 C^3) time.
Args:
w: (N+2)D tensor of shape (kernel_height, kernel_width,
input_channels, output_channels) containing the convolutional kernel.
d: (N+3)D tensor of shape (num_targets, batch_size,
output_height, output_width, output_channels), interpreted as a
diagonal weight matrix.
beta: (N+3)D tensor of shape (num_targets, batch_size,
input_height, input_width, input_channels) specifying the projection.
padding: `"VALID"` or `"SAME"`, the convolution's padding algorithm.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
abs_fn: Absolute value function; defaults to `tf.abs`.
block_size: Number of column channels of W^T d W to process at a time,
or zero (default) to process all at once.
Returns:
(N+3)D tensor of shape (num_targets, batch_size,
input_height, input_width, input_channels) containing
beta_i^{-1} sum_j |Q_ij| beta_j.
"""
if block_size == 0:
proj = _conv_projection_slice(w, d, w, beta,
padding, strides, abs_fn=abs_fn)
else:
# Accumulate over slices of the input channels dimension.
input_channels = w.shape[-2].value
proj = tf.zeros_like(beta)
for idx_min in range(0, input_channels, block_size):
idx_max = min(idx_min+block_size, input_channels)
if beta.shape.ndims == 5:
w_s = w[:, :, idx_min:idx_max]
beta_s = beta[:, :, :, :, idx_min:idx_max]
elif beta.shape.ndims == 4:
w_s = w[:, idx_min:idx_max]
beta_s = beta[:, :, :, idx_min:idx_max]
else:
raise ValueError('Invalid rank for beta: {}'.format(beta.shape.ndims))
proj += _conv_projection_slice(w, d, w_s, beta_s,
padding, strides, abs_fn=abs_fn)
return proj / beta
def _linear_projection_slice(w, d, w_s, beta, abs_fn=tf.abs):
"""Calculates a partial projection of | W^T d W |.
Computes sum_j |Q_ij| beta_j where Q = W^T d W_s is a slice of the
weighted Gram matrix and j indexes the columns included in the slice.
Args:
w: 2D tensor of shape (input_size, output_size) containing the matrix.
d: 3D tensor of shape (num_targets, batch_size, output_size),
interpreted as a diagonal weight matrix.
w_s: 2D tensor of shape (input_slice_size, output_size) containing the
desired slice of `w`.
beta: 3D tensor of shape (num_targets, batch_size, input_slice_size)
specifying the partial projection.
abs_fn: Absolute value function; defaults to `tf.abs`.
Returns:
3D tensor of shape (num_targets, batch_size, input_size)
containing sum_j |Q_ij| beta_j.
"""
dw = tf.expand_dims(d, axis=2) * w_s
wt_d_w = tf.matmul(w, dw, transpose_b=True)
# wt_d_w is a 4D tensor of shape (num_targets, batch_size,
# input_size, input_slice_size).
return tf.reduce_sum(abs_fn(wt_d_w) * tf.expand_dims(beta, axis=2), axis=3)
def linear_weighted_gram_abs_projection(w, d, beta,
abs_fn=tf.abs,
block_size=0):
"""Calculates a projection of | W^T d W | for a fully connected matrix W.
Computes beta_i^{-1} sum_j |Q_ij| beta_j where Q = W^T d W is the
weighted Gram matrix.
Args:
w: 2D tensor of shape (input_size, output_size) containing the matrix.
d: 3D tensor of shape (num_targets, batch_size, output_size),
interpreted as a diagonal weight matrix.
beta: 3D tensor of shape (num_targets, batch_size, input_size)
specifying the projection.
abs_fn: Absolute value function; defaults to `tf.abs`.
block_size: Number of columns of W^T d W to process at a time,
or zero (default) to process all at once.
Returns:
3D tensor of shape (num_targets, batch_size, input_size)
containing beta_i^{-1} sum_j |Q_ij| beta_j.
"""
# Normalise beta.
beta = beta / tf.reduce_sum(beta, axis=2, keepdims=True)
if block_size == 0:
proj = _linear_projection_slice(w, d, w, beta, abs_fn=abs_fn)
else:
# Accumulate over slices of the input dimension.
input_size = w.shape[0].value
proj = tf.zeros_like(beta)
for idx_min in range(0, input_size, block_size):
idx_max = min(idx_min+block_size, input_size)
w_s = w[idx_min:idx_max]
beta_s = beta[:, :, idx_min:idx_max]
proj += _linear_projection_slice(w, d, w_s, beta_s,
abs_fn=abs_fn)
return proj / beta
| deep-verify-master | deep_verify/src/formulations/semidefinite/gram_calcs.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Graph construction for semidefinite formulation of dual verification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src.formulations import verify_dual_base
from deep_verify.src.formulations.semidefinite import gram_calcs
from deep_verify.src.layers import layers
from deep_verify.src.layers import layers_combined
from enum import Enum
import sonnet as snt
import tensorflow as tf
# Margin to ensure that Hessian remains positive definite in the face of
# numerical accuracy issues.
_EPSILON = 1.e-12
class VerifyOption(str, Enum):
SVD = 'svd'
WEAK = 'weak'
STRONG = 'strong'
STRONG_APPROX = 'strong_approx'
class _InputLayer(layers.VerifiableLayer):
"""No-op layer allowing dual variables at the first layer inputs."""
def __init__(self, first_layer):
if first_layer.is_activation:
raise ValueError('First layer must not be an activation layer')
super(_InputLayer, self).__init__()
self._first_layer = first_layer
@property
def input_node(self):
return self._first_layer.input_node
@property
def output_node(self):
return self._first_layer.input_node
@property
def reshape(self):
return self._first_layer.reshape
def dual_shape(self):
output_shape = super(_InputLayer, self).dual_shape()
return {
'x': output_shape,
}
def reshape_duals_forwards(self, next_layer, dual_vars):
if next_layer.reshape:
# There was a reshape prior to the next layer.
reshape = snt.BatchReshape(next_layer.input_shape, preserve_dims=2)
dual_vars = {key: reshape(dual_var)
for key, dual_var in dual_vars.items()}
return dual_vars
def project_duals_op(self, dual_vars):
"""Projects duals into their regional constraints.
Args:
dual_vars: Dual variable tensor.
Returns:
Tensor of same type and shape as `dual_vars`, in which the dual variable
values are clamped to their admissible ranges (if relevant).
"""
assign_ops = [tf.no_op()]
return tf.group(*assign_ops)
class _CombinedLayer(layers.VerifiableLayer):
"""Linear layer followed by activation layer, treated together."""
def __init__(self, linear_layer, activation_layer):
if linear_layer.is_activation:
raise ValueError('First layer must not be an activation layer')
if not activation_layer.is_activation:
raise ValueError('Second layer must be an activation layer')
super(_CombinedLayer, self).__init__()
self._linear_layer = linear_layer
self._activation_layer = activation_layer
@property
def linear_layer(self):
return self._linear_layer
@property
def activation_layer(self):
return self._activation_layer
@property
def input_node(self):
return self._linear_layer.input_node
@property
def output_node(self):
return self._activation_layer.output_node
@property
def reshape(self):
return self._linear_layer.reshape
def dual_shape(self):
output_shape = super(_CombinedLayer, self).dual_shape()
input_shape = tuple(self.input_shape)
return {
'x': output_shape,
'delta': output_shape,
'beta': input_shape,
'lambda': output_shape,
'mup': output_shape,
'mum': output_shape,
'muc': output_shape
}
def reshape_duals_forwards(self, next_layer, dual_vars):
if next_layer.reshape:
# There was a reshape prior to the next layer.
reshape = snt.BatchReshape(next_layer.input_shape, preserve_dims=2)
dual_vars = {key: reshape(dual_var) if key != 'beta' else dual_var
for key, dual_var in dual_vars.items()}
return dual_vars
def project_duals_op(self, dual_vars):
"""Projects duals into their regional constraints.
Args:
dual_vars: Dual variable tensor.
Returns:
Tensor of same type and shape as `dual_vars`, in which the dual variable
values are clamped to their admissible ranges (if relevant).
"""
beta = dual_vars['beta']
mup, mum, muc = dual_vars['mup'], dual_vars['mum'], dual_vars['muc']
assign_ops = []
# mup, mum, muc must be non-negative
lb_pre = self._activation_layer.input_bounds.lower
ub_pre = self._activation_layer.input_bounds.upper
mu_shape = mup.get_shape().as_list()
tile_shape = [mu_shape[0]] + [1 for _ in mu_shape[1:]]
on = tf.tile(
tf.expand_dims(lb_pre > 0.0, 0),
tile_shape)
off = tf.tile(
tf.expand_dims(ub_pre < 0.0, 0),
tile_shape)
known = tf.logical_or(on, off)
assign_ops.append(tf.assign(mup,
tf.where(on, mup,
tf.where(off, tf.zeros_like(mup),
tf.maximum(mup, 0.)))))
assign_ops.append(tf.assign(
mum, tf.where(known, tf.zeros_like(mum), tf.maximum(mum, 0.))))
assign_ops.append(tf.assign(
muc, tf.where(known, tf.zeros_like(muc), tf.maximum(muc, 0.))))
# beta must be strictly positive.
assign_ops.append(tf.assign(beta, tf.maximum(beta, 1.)))
return tf.group(*assign_ops)
class SemidefiniteDualFormulation(verify_dual_base.DualFormulation):
"""Specifies layers' dual verification contributions."""
def group_layers(self, verifiable_layers):
"""Groups dual layers as required by the verification strategy.
Args:
verifiable_layers: List of `SingleVerifiableLayer` objects specifying
linear layers and non-linear activation functions.
Returns:
List of `VerifiableLayer` objects specifying layers that give rise to
dual variables.
Raises:
ValueError: if an unsupported layer type or arrangement is encountered.
"""
verifiable_layers = layers_combined.combine_trailing_linear_layers(
verifiable_layers)
if len(verifiable_layers) < 3:
raise ValueError('The last predictor layer must be a linear layer. The '
'predictor must also contain at least one '
'linear-like layer followed by a non-linearity.')
# Group the layers.
grouped_layers = []
# Start with a no-op shaped according to the first linear layer's inputs.
grouped_layers.append(_InputLayer(verifiable_layers[0]))
# Layers are grouped in (activation, linear) pairs.
l = 0
while l < len(verifiable_layers) - 1:
grouped_layers.append(_CombinedLayer(
verifiable_layers[l],
verifiable_layers[l+1]))
l += 2
# Final layer (linear). It has no duals.
if l >= len(verifiable_layers):
raise ValueError('This formulation requires the network to end '
'linear -> activation -> linear.')
grouped_layers.append(verifiable_layers[l])
grouped_layers[-1].set_no_duals()
return grouped_layers
def set_objective_computation_config(self, config):
if config is None:
config = {}
self._softplus_temperature = config.get('softplus_temperature', 1.)
self._verify_option = config.get('verify_option', VerifyOption.WEAK)
self._sqrt_eps = config.get('sqrt_eps', _EPSILON)
self._approx_k = config.get('approx_k', 100)
self._exact_k = config.get('exact_k', 1000)
self._soften_abs = config.get('soften_abs', False)
self._use_lam = config.get('use_lam', True)
def _get_dual_vars(self, dual_vars):
if dual_vars.get('lambda') is not None:
lam = dual_vars.get('lambda')
delta = dual_vars['delta']
alpha = tf.sqrt(tf.square(lam) + tf.square(delta) + self._sqrt_eps)
return ((alpha + delta)/2, (alpha-delta)/2, lam/2)
else:
return (None, tf.zeros_like(dual_vars['x']), None)
def expand_tensor(self, x, aug_size):
return tf.reshape(x, aug_size + [-1])
def dual_objective(self, verifiable_layers, labels, dual_var_lists,
target_strategy=None, objective_computation_config=None):
"""Computes the Lagrangian (dual objective).
Args:
verifiable_layers: List of `VerifiableLayer` objects specifying layers
that give rise to dual variables.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
dual_var_lists: Nested list of 3D tensors of shape
(num_classes, batch_size, layer_size) and 5D tensors of shape
(num_classes, batch_size, height, width, channels)
containing Lagrange multipliers for the layers' calculations.
This has the same length as `verifiable_layers`, and typically each
entry is a singleton list with the dual variable for that layer.
ResNet blocks' entries have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
target_strategy: a `TargetObjective` object which gets the objective
weights of the final layer depending on the strategy of the final
objective. Default is set to None in which case it uses the default
target strategy.
objective_computation_config: `ConfigDict` of additional parameters.
Returns:
2D tensor of shape (num_classes, batch_size) containing dual objective
for each target class, for each example.
"""
self.set_objective_computation_config(objective_computation_config)
batch_size = tf.shape(labels)[0]
aug_batch_size = dual_var_lists[0][-1]['x'].shape.as_list()[:2]
dtype = verifiable_layers[-1].output_bounds.lower.dtype
# create dummy variables, only used to get gradient of Lagrangian wrt x
dxs = []
for layer in verifiable_layers[:-1]:
dxs.append(tf.zeros(aug_batch_size + layer.output_shape))
objective = tf.zeros([1, batch_size], dtype=dtype)
# Contribution for the layers.
lb_x = []
ub_x = []
for l in range(1, len(verifiable_layers) - 1):
dual_vars_lm1 = verifiable_layers[l-1].reshape_duals_forwards(
verifiable_layers[l], dual_var_lists[l-1][-1])
dual_vars_l = dual_var_lists[l][-1]
obj, lb_l, ub_l = self._layer_contrib(
verifiable_layers[l], dual_vars_lm1, dual_vars_l,
dxs[l-1],
dxs[l])
lb_x += [lb_l]
ub_x += [ub_l]
objective += obj
last_layer = verifiable_layers[-1] # linear layer.
objective_weights = last_layer.get_objective_weights(
labels, target_strategy=target_strategy)
# Contribution for the final linear layer.
dual_vars_km1 = verifiable_layers[-2].reshape_duals_forwards(
last_layer, dual_var_lists[-2][-1])
obj, lb_fin, ub_fin = self._last_layer_contrib(
last_layer, dual_vars_km1,
dxs[-1],
objective_weights.w, objective_weights.b)
lb_x += [lb_fin]
ub_x += [ub_fin]
objective += obj
grad = tf.gradients(tf.reduce_sum(objective), dxs)
for l, g in enumerate(grad):
objective += tf.reduce_sum(
g * tf.reshape((lb_x[l] + ub_x[l])/2, g.shape) +
self._soft_abs(g * tf.reshape((ub_x[l] - lb_x[l])/2, g.shape)),
axis=list(range(2, g.shape.ndims)))
return objective
def _layer_contrib(self, layer, dual_vars_lm1, dual_vars_l,
dx_lm1, dx_l):
assert isinstance(layer, _CombinedLayer)
if layer.activation_layer.activation != 'relu':
raise NotImplementedError('Only ReLU nonlinearities are supported.')
if layer.linear_layer.batch_norm is not None:
raise NotImplementedError('BatchNorm is not yet implemented.')
if self._use_lam:
x_lm1 = dual_vars_lm1['x']
x_l = dual_vars_l['x']
else:
x_lm1 = tf.zeros_like(dual_vars_lm1['x'])
x_l = tf.zeros_like(dual_vars_l['x'])
x_lm1 = x_lm1 + tf.reshape(dx_lm1, x_lm1.shape)
x_l = x_l + tf.reshape(dx_l, x_l.shape)
if self._use_lam:
_, delta_lm1, lam_lm1 = self._get_dual_vars(dual_vars_lm1)
alpha_l, _, lam_l = self._get_dual_vars(dual_vars_l)
beta_l = dual_vars_l['beta']
mup_l, mum_l, muc_l = (
dual_vars_l['mup'], dual_vars_l['mum'], dual_vars_l['muc'])
lb_lm1 = layer.input_bounds.lower
ub_lm1 = layer.input_bounds.upper
rad_lm1 = (ub_lm1 - lb_lm1) / 2.
mid_lm1 = (ub_lm1 + lb_lm1) / 2.
lb_pre = layer.activation_layer.input_bounds.lower
ub_pre = layer.activation_layer.input_bounds.upper
# If upper bound and lower bound are the same, d_l can be zero.
same_pre = ub_pre - lb_pre < 1.e-8
d_l = (
tf.where(same_pre, tf.zeros_like(ub_pre), ub_pre) /
tf.where(same_pre, tf.ones_like(lb_pre), ub_pre - lb_pre))
d_l = tf.where(lb_pre > 0.0, tf.ones_like(lb_pre), d_l)
d_l = tf.where(ub_pre < 0.0, tf.zeros_like(lb_pre), d_l)
bias_l = (tf.where(same_pre, tf.zeros_like(ub_pre), ub_pre * lb_pre) /
tf.where(same_pre, tf.ones_like(lb_pre), ub_pre - lb_pre))
bias_l = tf.where(lb_pre > 0.0, tf.zeros_like(lb_pre), bias_l)
bias_l = tf.where(ub_pre < 0.0, tf.zeros_like(ub_pre), bias_l)
# Pre-activations.
y_l = layer.linear_layer.forward_prop(x_lm1, apply_bias=True)
# Layer-specific computation of norm(w).
if self._use_lam:
w_norm = self._calc_w_norm(layer.linear_layer, x_lm1, beta_l, alpha_l)
# Contribution for nu.
nu_lm1 = (
(delta_lm1 if lam_lm1 is None else delta_lm1 - lam_lm1) +
w_norm / 4.)
nu_lm1 = nu_lm1/2 + self._soft_abs(nu_lm1)/2
dual_obj = tf.reduce_sum(nu_lm1 * (rad_lm1 * rad_lm1 -
(x_lm1-mid_lm1) * (x_lm1-mid_lm1)),
axis=list(range(2, nu_lm1.shape.ndims)))
# Contribution for lambda.
dual_obj += tf.reduce_sum(lam_l * x_l * (y_l - x_l),
axis=list(range(2, lam_l.shape.ndims)))
else:
dual_obj = tf.zeros(mup_l.shape.as_list()[:2])
# Contribution for mu.
dual_obj += tf.reduce_sum(mup_l * (x_l - y_l),
axis=list(range(2, mup_l.shape.ndims)))
dual_obj += tf.reduce_sum(mum_l * x_l,
axis=list(range(2, mum_l.shape.ndims)))
dual_obj += tf.reduce_sum(muc_l * (d_l * y_l - bias_l - x_l),
axis=list(range(2, muc_l.shape.ndims)))
return dual_obj, lb_lm1-x_lm1, ub_lm1-x_lm1
def _last_layer_contrib(self, layer, dual_vars_lm1, dx_lm1, obj_w, obj_b):
if self._use_lam:
x_lm1 = dual_vars_lm1['x']
else:
x_lm1 = tf.zeros_like(dual_vars_lm1['x'])
x_lm1 = x_lm1 + tf.reshape(dx_lm1, x_lm1.shape)
lb_lm1 = layer.input_bounds.lower
ub_lm1 = layer.input_bounds.upper
if self._use_lam:
_, delta_lm1, lam_lm1 = self._get_dual_vars(dual_vars_lm1)
rad_lm1 = (ub_lm1 - lb_lm1) / 2.
mid_lm1 = (ub_lm1 + lb_lm1) / 2.
# Contribution for nu.
nu_lm1 = tf.nn.relu(
delta_lm1 if lam_lm1 is None else delta_lm1 - lam_lm1)
dual_obj = tf.reduce_sum(nu_lm1 * (rad_lm1 * rad_lm1 -
(x_lm1-mid_lm1) * (x_lm1-mid_lm1)),
axis=list(range(2, nu_lm1.shape.ndims)))
else:
dual_obj = tf.zeros(x_lm1.shape.as_list()[:2])
# Contribution for primal objective.
dual_obj += tf.reduce_sum(obj_w * x_lm1, axis=2)
dual_obj += obj_b
return dual_obj, lb_lm1-x_lm1, ub_lm1-x_lm1
def _calc_w_norm(self, layer, x_lm1, beta_l, alpha_l):
# Norm of w, used for computing nu_lm1.
if self._verify_option == VerifyOption.WEAK:
w_norm = layer.forward_prop(beta_l, w_fn=tf.abs) * (alpha_l)
w_norm = layer.backward_prop(w_norm, w_fn=tf.abs) / beta_l
elif self._verify_option == VerifyOption.STRONG:
w_norm = layer.custom_op(_ScaledGramComputation(self._soft_abs,
self._exact_k),
alpha_l, beta_l)
else:
# Linearise the convolution.
flatten = snt.BatchFlatten(preserve_dims=2)
unflatten = snt.BatchReshape(x_lm1.shape[2:].as_list(), preserve_dims=2)
# flatten(beta_l): KxNxI w_lin: IxO flatten(delta_l,gam_l): KxNxO
if self._verify_option == VerifyOption.SVD:
w_lin, _ = layer.flatten()
w_scaled = (tf.expand_dims(flatten(beta_l), -1) *
tf.expand_dims(tf.expand_dims(w_lin, 0), 0) *
tf.expand_dims(tf.sqrt(flatten(alpha_l) +
self._sqrt_eps), 2))
s = tf.svd(w_scaled, compute_uv=False)
w_norm = tf.expand_dims(tf.reduce_max(s, axis=-1), axis=-1)
w_norm = unflatten(w_norm*w_norm) / (beta_l * beta_l)
elif self._verify_option == VerifyOption.STRONG_APPROX:
# Get size of input to layer
size_list = beta_l[0, 0, ...].shape.as_list()
size_x = 1
for s in size_list:
size_x *= s
# Prepare data
shape_beta = beta_l.shape.as_list()[2:]
batch_shape = beta_l.shape.as_list()[:2]
shape_alpha = alpha_l.shape.as_list()[2:]
beta_reduce = flatten(beta_l)
beta_reduce = beta_reduce / tf.reduce_sum(beta_reduce, axis=2,
keepdims=True)
beta_l = tf.reshape(beta_reduce, beta_l.shape)
k_sample = min(self._approx_k, size_x)
def process_columns(x, beta_cur):
"""Compute |W^T[alpha]Wx|beta_cur."""
shape_x_batch = x.shape.as_list()[:3]
x = tf.reshape(x, [shape_x_batch[0], -1] + shape_beta)
x_prop = tf.reshape(layer.forward_prop(x),
shape_x_batch + shape_alpha)
x = layer.backward_prop(
tf.reshape(x_prop * tf.expand_dims(alpha_l, 2),
[shape_x_batch[0], -1] + shape_alpha)
)
x = tf.reshape(x, shape_x_batch + shape_beta)
# Flatten beta and pick out relevant entries
beta_reshape = beta_cur
for _ in range(len(shape_beta)):
beta_reshape = tf.expand_dims(beta_reshape, -1)
return tf.reduce_sum(self._soft_abs(x) * beta_reshape, axis=2)
# Accumulator for sum over columns
samples = tf.random.categorical(tf.log(tf.reshape(beta_reduce,
[-1, size_x])+
1e-10),
k_sample)
samples = tf.one_hot(tf.reshape(samples, [-1]), size_x, axis=-1)
samples = tf.reshape(samples, (batch_shape + [k_sample] +
shape_beta))
x_acc = process_columns(samples,
tf.ones(batch_shape + [k_sample])/k_sample)
w_norm = x_acc/beta_l
else:
raise ValueError('Unknown verification option: ' + self._verify_option)
return w_norm
def _soft_abs(self, x):
if self._soften_abs:
return tf.sqrt(tf.square(x) + self._sqrt_eps)
else:
return tf.abs(x)
def _softplus(self, x):
temperature = self._softplus_temperature
return temperature * tf.nn.softplus(x / temperature)
class _ScaledGramComputation(layers.CustomOp):
"""Layer-specific op to compute weighted Gram matrix projections."""
def __init__(self, abs_fn, block_size):
super(_ScaledGramComputation, self).__init__()
self._abs_fn = abs_fn
self._block_size = block_size
def visit_linear(self, layer, w, b, alpha, beta):
return gram_calcs.linear_weighted_gram_abs_projection(
w, alpha, beta,
abs_fn=self._abs_fn,
block_size=self._block_size)
def visit_conv(self, layer, w, b, padding, strides, alpha, beta):
# Specify a block size (in channels) of 1.
# For convolutions, this was found to be the most efficient.
return gram_calcs.conv_weighted_gram_abs_projection(
w, alpha, beta,
padding=padding, strides=strides,
abs_fn=self._abs_fn,
block_size=1)
def visit_activation(self, layer):
raise NotImplementedError()
| deep-verify-master | deep_verify/src/formulations/semidefinite/verify_dual_semidefinite.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Semidefinite verification formulation.
Going beyond the 'standard' formulation (`src.formulations.standard`), this
module implements a tighter Lagrangian relaxation based on semidefinite
programming.
For more details see paper: "Efficient Neural Network Verification with
Exactness Characterization.",
http://auai.org/uai2019/proceedings/papers/164.pdf.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| deep-verify-master | deep_verify/src/formulations/semidefinite/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standard dual formulation of verification.
This module implements the standard formulation of verifiable robustness as
a Lagrangian dual problem, by introducing Lagrange multipliers (dual variables)
for the calculation of each layer of the network.
See section 3.4 of the paper: "A Dual Approach to Scalable Verification
of Deep Networks.", https://arxiv.org/abs/1803.06567.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| deep-verify-master | deep_verify/src/formulations/standard/__init__.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Graph construction for dual verification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import operator
from deep_verify.src import common
import tensorflow as tf
def _reduce_softmax(v, axis, inverse_temperature=None):
if inverse_temperature is None:
return tf.reduce_max(v, axis=axis)
# Apply smoothing.
return tf.reduce_sum(v * tf.nn.softmax(inverse_temperature * v, axis=axis),
axis=axis)
def _conj(nl, mu, lam, nominal, lb, ub, parameters=None,
inverse_temperature=None):
"""Dual objective contribution of a pre-activation value.
Finds the maximum value of `mu*x - lam*h(x)` for `lb <= x <= ub`
where `h` is the activation function.
If `nominal` is not `None`, then inputs and activations are interpreted
relative to nominal inputs and outputs respectively, so we actually maximise
`mu*x - lam*(h(nominal+x) - h(nominal))`.
Args:
nl: Callable for the non-linear activation function, e.g. tf.nn.relu.
mu: (N+2)D tensor of shape (num_classes, batch_size, *layer_shape)
containing Lagrange multipliers for the neurons' linear calculations.
lam: (N+2)D tensor of shape (num_classes, batch_size, *layer_shape)
containing Lagrange multipliers for the neurons' non-linear activations.
nominal: (N+1)D tensor of shape (batch_size, *layer_shape) containing
nominal input values. Inputs bounds are interpreted relative to these
nominal values. Defaults to zero if `None`.
lb: (N+1)D tensor of shape (batch_size, *layer_shape) containing
lower bounds of the neurons' pre-activation values.
ub: (N+1)D tensor of shape (batch_size, *layer_shape) containing
upper bounds of the neurons' pre-activation values.
parameters: Optional parameter dict.
inverse_temperature: Optional parameter to use a soft maximum. When
set to zero maximum will become equivalent to an average (over the
candidate points). When set to infinity (or None), it is equivalent to
taking the maximum. Note that a temperature will not necessarily result
in a valid verification bound. It approaches a valid bound as the
inverse_temperature rises.
Returns:
(N+1)D tensor of shape (num_classes, batch_size, *layer_shape) containing
maximum attained value of mu*x - lam*h(x).
"""
# Endpoints of admissible x-range are candidates for the maximum.
broadcast = tf.zeros_like(lam + mu)
lam = lam + broadcast
mu = mu + broadcast
# Candidates (and bounds) are relative to nominal, if nominal is supplied.
candidates = [broadcast + lb, broadcast + ub]
if nominal is None:
clamp = lambda x: tf.maximum(lb, tf.minimum(ub, x))
else:
# x is absolute (e.g. zero for ReLU).
# Shift relative to nominal, before clamping to within relative bounds.
clamp = lambda x: tf.maximum(lb, tf.minimum(ub, x - nominal))
# Use calculus to determine candidates internal to the admissible x-range.
if nl.__name__ == 'sigmoid':
def siginv(y):
cond_y = tf.logical_and(y > 0, y < 1)
y = tf.minimum(1-1e-16, tf.maximum(1e-16, y))
return tf.where(cond_y, tf.log(y) - tf.log(1 - y),
tf.ones_like(y) / 0.)
ratio_cond = tf.abs(lam) > 1e-14
ratio = lam / tf.where(ratio_cond, mu, tf.ones_like(mu))
cond_lam = tf.logical_and(ratio_cond, ratio > 0)
cond_lam = tf.logical_and(cond_lam, ratio < .25)
sqrt = tf.sqrt(tf.where(cond_lam, 1 - 4 * ratio, tf.zeros_like(mu)))
candidates.append(tf.where(
cond_lam,
clamp(siginv((1 - sqrt) / 2.0)),
broadcast + lb))
candidates.append(tf.where(
cond_lam,
clamp(siginv((1 + sqrt) / 2.0)),
broadcast + ub))
elif nl.__name__ == 'tanh':
ratio_cond = tf.abs(mu) > 1e-14
ratio = lam / tf.where(ratio_cond, mu, tf.ones_like(mu))
cond_lam = tf.logical_and(ratio_cond, ratio > 1)
sqrt = tf.sqrt(tf.maximum(ratio, 1)) + 1e-6
candidates.append(tf.where(
cond_lam,
clamp(-tf.acosh(sqrt)),
broadcast + lb))
candidates.append(tf.where(
cond_lam,
clamp(tf.acosh(sqrt)),
broadcast + ub))
elif nl.__name__ == 'elu':
ratio_cond = tf.abs(mu) > 1e-6
ratio = lam / tf.where(ratio_cond, mu, tf.ones_like(mu))
cond_lam = tf.logical_and(ratio_cond, ratio > 1)
maximum = tf.maximum(ratio, 1.)
candidates.append(tf.where(
cond_lam,
clamp(-tf.log(maximum)),
broadcast + lb))
elif nl.__name__ in ('relu', 'leaky_relu'):
# Include zero in the candidates as potential max/min points.
candidates.append(broadcast + clamp(tf.zeros_like(lb)))
else:
# For identity activation, consider the endpoints only.
pass
x = tf.stack(candidates, axis=0)
if nominal is None:
fun_vals = nl(x)
elif nl == 'relu':
# ReLU(a+x) - ReLU(a) = max(min(a, 0) + x, min(-a, 0))
fun_vals = tf.maximum(tf.minimum(nominal, 0) + x,
tf.minimum(-nominal, 0))
elif nl == 'leaky_relu':
# LeakyReLU(a+x) - LeakyReLUReLU(a) =
# max(x + min(a, 0) * (1 - alpha), alpha * x + min(-a, 0) * (1 - alpha))
alpha = parameters['alpha']
fun_vals = tf.maximum(x + tf.minimum(nominal, 0.) * (1. - alpha),
alpha * x + tf.minimum(-nominal, 0.) * (1. - alpha))
else:
fun_vals = nl(nominal + x) - nl(nominal)
v = mu * x - lam * fun_vals
return _reduce_softmax(v, 0, inverse_temperature)
def max_linear(coefficients, lb, ub, axis=None, keepdims=False,
inverse_temperature=None):
"""Maximises linear combinations over inputs within a specified hypercube.
Args:
coefficients: 3D tensor of shape (num_classes, batch_size, layer_size) or
5D tensor of shape (num_classes, batch_size, input_height,
input_width, input_channels)
containing coefficients of the linear combinations.
lb: 2D tensor of shape (batch_size, layer_size) or 4D tensor of shape
(batch_size, input_height, input_width, input_channels) containing lower
bounds on inputs.
ub: 2D tensor of shape (batch_size, layer_size) or 4D tensor of shape
(batch_size, input_height, input_width, input_channels) containing upper
bounds on inputs.
axis: Axis/axes (after broadcasting lb,ub) over which to take the linear
combination, or `None` to default to 'all dims after the leading two'.
keepdims: Whether to retain the dimensions over which the linear
combination is taken.
inverse_temperature: Optional parameter to use a soft maximum. When
set to zero maximum will become equivalent to an average (over the
candidate points). When set to infinity (or None), it is equivalent to
taking the maximum. Note that a temperature will not necessarily result
in a valid verification bound. It approaches a valid bound as the
inverse_temperature rises.
Returns:
opt_val: 2D tensor of shape (num_classes, batch_size) containing the
maximum attained values of the linear combinations.
"""
if axis is None:
axis = list(range(2, coefficients.shape.ndims))
v = tf.stack([coefficients * lb, coefficients * ub], axis=0)
v = _reduce_softmax(v, 0, inverse_temperature)
return tf.reduce_sum(v, axis=axis, keepdims=keepdims)
def linear_dual_objective(lam_in, activation_coeffs, dual_obj_bias, lb, ub,
inverse_temperature=None):
"""Calculates contribution to dual objective for a linear/conv layer.
Maximises (over x in [lb, ub])::
lam_{l-1}^T x - mu_l^T w_l x - mu_l^T b_l
Args:
lam_in: 3D tensor of shape (num_classes, batch_size, input_size) or
5D tensor of shape (num_classes, batch_size, input_height,
input_width, input_channels)
containing Lagrange multipliers for the input neurons' activations,
or `None` if this is the first layer.
activation_coeffs: 3D tensor of shape (num_classes, batch_size, layer_size)
or 5D tensor of shape (num_classes, batch_size, input_height,
input_width, input_channels) containing mu_l^T w_l.
dual_obj_bias: 2D tensor of shape (num_classes, batch_size) containing
mu_l^T b_l.
lb: 2D tensor of shape (batch_size, layer_size) or 4D tensor of shape
(batch_size, input_height, input_width, input_channels) containing lower
bounds on inputs.
ub: 2D tensor of shape (batch_size, layer_size) or 4D tensor of shape
(batch_size, input_height, input_width, input_channels) containing upper
bounds on inputs.
inverse_temperature: Optional parameter to use a soft maximum. When
set to zero maximum will become equivalent to an average (over the
candidate points). When set to infinity (or None), it is equivalent to
taking the maximum. Note that a temperature will not necessarily result
in a valid verification bound. It approaches a valid bound as the
inverse_temperature rises.
Returns:
2D tensor of shape (num_classes, batch_size) containing dual objective
contribution for each example.
"""
if lam_in is not None:
activation_coeffs += lam_in
return dual_obj_bias + max_linear(activation_coeffs, lb, ub,
inverse_temperature=inverse_temperature)
def _prod(lst):
return functools.reduce(operator.mul, lst, 1)
def maxpool_layer_dual_objective(kernel_shape, strides, with_relu,
mu_in, lam_out, lb, ub, nominal=None):
"""Calculates the contribution to the dual objective of an N-D max pool layer.
Maximises (over y in [lb, ub])::
mu_l^T y - lam_l^T h_l(y)
where `h` is the specified max pool operation.
If `nominal` is not `None`, then inputs and maxima are interpreted
relative to nominal inputs and outputs respectively, so we actually maximise::
mu_l^T y - lam_l^T (h_l(nominal+y) - h_l(nominal))`.
This formulation only supports maxpools that cover the input space without
gaps. Overlaps are permitted, although they will give rise to an overestimate
of the dual objective rather than a tight value.
Args:
kernel_shape: Integer list of `[kernel_height, kernel_width]`,
or `None` to aggregate over the layer`s entire spatial extent.
strides: Integer list of `[vertical_stride, horizontal_stride]`.
with_relu: Whether to apply `tf.nn.relu` to the maxpool.
mu_in: (N+3)D tensor of shape (num_classes, batch_size,
input_height, input_width, layer_channels) containing
Lagrange multipliers for the neurons' linear calculations.
lam_out: (N+3)D tensor of shape (num_classes, batch_size,
output_height, output_width, layer_channels) containing
Lagrange multipliers for the neurons' maxpool calculations.
lb: (N+2)D tensor of shape (batch_size,
input_height, input_width, layer_channels) containing
lower bounds of the neurons' pre-maxpool values.
ub: (N+2)D tensor of shape (batch_size,
input_height, input_width, layer_channels) containing
upper bounds of the neurons' pre-maxpool values.
nominal: (N+2)D tensor of shape (batch_size, input_height, input_width,
layer_channels) containing nominal input values. Inputs bounds are
interpreted relative to these nominal values. Defaults to zero.
Returns:
2D tensor of shape (num_classes, batch_size) containing dual objective
contribution for each example.
Raises:
ValueError: if the pools overlap or have gaps.
"""
if nominal is not None:
# TODO(stanforth) investigate a more numerically stable implementation
res = maxpool_layer_dual_objective(kernel_shape, strides, with_relu,
mu_in, lam_out,
nominal + lb, nominal + ub)
# Infer the nominal outputs.
if kernel_shape is None:
nominal_out = tf.reduce_max(nominal,
axis=list(range(1, nominal.shape.ndims-1)))
else:
nominal_out = tf.nn.max_pool(nominal, ksize=kernel_shape, padding='VALID',
strides=([1] + strides + [1]))
if with_relu:
nominal_out = tf.relu(nominal_out)
res -= tf.reduce_sum(mu_in * nominal,
axis=list(range(2, mu_in.shape.ndims)))
res += tf.reduce_sum(lam_out * nominal_out,
axis=list(range(2, lam_out.shape.ndims)))
return res
# Search for maximum by branching over inputs (kernel elements).
# Broadcast the tensors to match what `fn` will operate with, i.e. shape
# (num_classes, batch_size, output_height, output_width,
# kernel_height * kernel_width, layer_channels).
num_classes = mu_in.shape[0].value
batch_size = tf.shape(mu_in)[1]
input_shape = mu_in.shape[2:].as_list()
layer_channels = mu_in.shape[-1].value
output_spatial_shape = lam_out.shape[2:-1].as_list()
nd = lam_out.shape.ndims - 3
if kernel_shape is None:
# Maxpool will be across the entire layer (in each channel).
kernel_size = _prod(input_shape[:-1])
lb_bc = lb
ub_bc = ub
mu_bc = mu_in
else:
for i in range(len(kernel_shape)):
if kernel_shape[i] < strides[i]:
raise ValueError(
'The pools must tile the entire input space without gaps.')
padding = 'VALID'
# Determine the fan-out of each input, where the pools overlap.
# Builds a tensor of shape (1, 1, input_height, input_width, 1) of the form
# [[1,1,2,1,1], [1,1,2,1,1], [2,2,4,2,2], [1,1,2,1,1], [1,1,2,1,1]]
# (illustrated here with 3x3 kernel with stride 2 on a 5x5 input).
overlap = common.conv_reduce_sum(
tf.ones(dtype=mu_in.dtype, shape=(
[1, 1] + output_spatial_shape + [1] + kernel_shape + [1])),
input_shape,
padding=padding, strides=strides)
# Share mu values equally amongst pools where they overlap.
mu_in /= overlap
# Broadcast the bounds and mu vars where the kernel applications overlap.
kernel_size = _prod(kernel_shape)
lb_bc = common.conv_broadcast(lb, kernel_shape,
padding=padding, strides=strides)
ub_bc = common.conv_broadcast(ub, kernel_shape,
padding=padding, strides=strides)
# Temporarily combine the (num_classes, batch_size) dimensions
# while applying the broadcast to mu.
mu_bc = tf.reshape(mu_in, shape=([num_classes * batch_size] +
mu_in.shape[2:].as_list()))
mu_bc = common.conv_broadcast(mu_bc, kernel_shape,
padding=padding, strides=strides)
# conv_broadcast has returned tensors of shape
# (N, output_height, output_width, 1, kernel_height, kernel_width, C).
lb_bc = tf.reshape(lb_bc, shape=([1, batch_size] +
output_spatial_shape +
[kernel_size, layer_channels]))
ub_bc = tf.reshape(ub_bc, shape=([1, batch_size] +
output_spatial_shape +
[kernel_size, layer_channels]))
mu_bc = tf.reshape(mu_bc, shape=([num_classes, batch_size] +
output_spatial_shape +
[kernel_size, layer_channels]))
lb_bc += tf.zeros_like(mu_bc)
ub_bc += tf.zeros_like(mu_bc)
# Use the same lambda for each input.
lam_bc = tf.expand_dims(lam_out, axis=(nd+2))
# All xx_bc tensors are shaped as (class, N, H, W, i, C)
# where i ranges over inputs (kernel elements).
# To calculate for input (kernel element) i, we need to sum over inputs j.
# Set up xx_i, xx_j tensors shaped as (class, N, H, W, i, j, C)
# where i,j both range over inputs (kernel elements).
# y_i = tf.expand_dims(y, nd+3) (will create inside `fn`)
mu_j = tf.expand_dims(mu_bc, nd+2)
lb_j = tf.expand_dims(lb_bc, nd+2)
ub_j = tf.expand_dims(ub_bc, nd+2)
# Only consider j != i.
mask = 1.0 - tf.expand_dims(tf.eye(kernel_size), -1)
def fn(y):
"""Optimal dual objective, conditional on the value of the maxpool.
For each input (kernel element) i, for the given y_i,
maximises (over z_j in [lb_j, min{y_i, ub_j}] and constraining z_i=y_i)::
mu^T z - lam y_i
This will be infeasible if y_i < lb_j for some j, (also if y_i < 0 in the
case of relu+maxpool), so maxpool cannot be attained at input i. The
returned tensor is unspecified for such elements.
Args:
y: (N+4)D tensor of shape (num_classes, batch_size,
output_height, output_width,
kernel_height * kernel_width, layer_channels) containing, for each
input (kernel element) i, a value of maxpool assumed to be attained
at input i.
Returns:
Tensor of same shape as `y` containing, for each input (kernel element) i,
the optimal value of the dual objective, conditional the maxpool being
equal to `y` with the maximum attained at input i.
"""
y_i = tf.expand_dims(y, nd+3)
# Maximise sum_{j!=i} mu_j y_j where y_j <= y_i for all j!=i.
obj = max_linear(mask * mu_j, lb_j, tf.minimum(ub_j, y_i), axis=(nd+3))
return obj + (mu_bc - lam_bc) * y
lb_max = tf.reduce_max(lb_bc, axis=(nd+2), keepdims=True)
if with_relu:
lb_max = tf.maximum(lb_max, 0.)
_, attained = common.concave_max_binsearch(
fn, tf.zeros_like(lb_bc) + lb_max, ub_bc)
# Filter out any infeasible choices of i.
attained = tf.where(lb_max <= ub_bc, attained, tf.zeros_like(attained) +
tf.reduce_min(attained, axis=(nd+2), keepdims=True))
# Maximise over which input (kernel element) maximises the maxpool.
per_neuron_objective = tf.reduce_max(attained, axis=(nd+2))
if with_relu:
# The relu+maxpool may additionally be 'maximised' by zero.
# Calculate optimal dual objective, conditional on all y_i <= 0.
# Maximise (over z_j in [lb_j, min{0, ub_j}])::
# mu^T z - lam 0
attained_zero = max_linear(mu_bc, lb_bc, tf.minimum(ub_bc, 0.), axis=(nd+2))
# Filter out any infeasible cases.
per_neuron_objective = tf.where(
tf.squeeze(lb_max, axis=(nd+2)) <= 0.,
tf.maximum(per_neuron_objective, attained_zero),
per_neuron_objective)
return tf.reduce_sum(per_neuron_objective,
axis=list(range(2, per_neuron_objective.shape.ndims)))
def activation_layer_dual_objective(nl, mu_in, lam_out, lb, ub, nominal=None,
parameters=None, inverse_temperature=None):
"""Calculates the contribution to the dual objective of an activation layer.
Maximises (over y in [lb, ub])::
mu_l^T y - lam_l^T h_l(y)
where `h` is the specified non-linearity.
If `nominal` is not `None`, then inputs and activations are interpreted
relative to nominal inputs and outputs respectively, so we actually maximise::
mu_l^T y - lam_l^T (h_l(nominal+y) - h_l(nominal))`.
Args:
nl: Callable for the non-linear activation function, e.g. tf.nn.relu.
mu_in: (N+3)D tensor of shape (num_classes, batch_size,
input_height, input_width, layer_channels) containing
Lagrange multipliers for the neurons' linear calculations.
lam_out: (N+3)D tensor of shape (num_classes, batch_size,
output_height, output_width, layer_channels) containing
Lagrange multipliers for the neurons' non-linear activations.
lb: (N+2)D tensor of shape (batch_size,
layer_height, layer_width, layer_channels)
containing lower bounds of the neurons' pre-activation values.
ub: (N+2)D tensor of shape (batch_size,
layer_height, layer_width, layer_channels)
containing upper bounds of the neurons' pre-activation values.
nominal: (N+2)D tensor of shape (batch_size, input_height, input_width,
layer_channels) containing nominal input values. Inputs bounds are
interpreted relative to these nominal values. Defaults to zero.
parameters: Optional parameter dict.
inverse_temperature: Optional parameter to use a soft maximum. When
set to zero maximum will become equivalent to an average (over the
candidate points). When set to infinity (or None), it is equivalent to
taking the maximum. Note that a temperature will not necessarily result
in a valid verification bound. It approaches a valid bound as the
inverse_temperature rises.
Returns:
2D tensor of shape (num_classes, batch_size) containing dual objective
contribution for each example.
"""
per_neuron_objective = _conj(nl, mu_in, lam_out, nominal, lb, ub,
parameters=parameters,
inverse_temperature=inverse_temperature)
return tf.reduce_sum(per_neuron_objective,
axis=list(range(2, per_neuron_objective.shape.ndims)))
| deep-verify-master | deep_verify/src/formulations/standard/standard_layer_calcs.py |
# coding=utf-8
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Graph construction for dual verification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from deep_verify.src.formulations import verify_dual_base
from deep_verify.src.formulations.standard import standard_layer_calcs
from deep_verify.src.layers import layers
from deep_verify.src.layers import layers_combined
import tensorflow as tf
class StandardDualFormulation(verify_dual_base.DualFormulation,
layers.CustomOp):
"""Simplified standard/reduced formulation, with no ResNet block support."""
def __init__(self, use_reduced=True):
super(StandardDualFormulation, self).__init__()
self._use_reduced = use_reduced
def group_layers(self, verifiable_layers):
"""Groups dual layers as required by the verification strategy.
Args:
verifiable_layers: List of `SingleVerifiableLayer` objects specifying
linear layers and non-linear activation functions.
Returns:
List of `VerifiableLayer` objects specifying layers that give rise to
dual variables.
Raises:
ValueError: if an unsupported layer type or arrangement is encountered.
"""
# Locate the last activation layer.
# It is usually at position len-2, but it's possible to be followed by
# more than one linear layer.
k = len(verifiable_layers) - 1
while k >= 0 and not verifiable_layers[k].is_activation:
k -= 1
if k <= 0 or k >= len(verifiable_layers) - 1:
raise ValueError('The last predictor layer must be a linear layer. The '
'predictor must also contain at least one '
'linear-like layer followed by a non-linearity.')
# Group the layers.
grouped_layers = []
# Initial linear layer.
initial_layer, l = self._get_single_layer(verifiable_layers, 0)
grouped_layers.append(initial_layer)
# Successive layers.
self._group_next_layers(grouped_layers, verifiable_layers[l:k])
# No duals for final layer (activation+linear).
final_layer = verifiable_layers[k]
for linear_layer in verifiable_layers[k+1:]:
final_layer = layers_combined.CombinedLayer(final_layer, linear_layer)
final_layer.set_no_duals()
grouped_layers.append(final_layer)
return grouped_layers
def _group_next_layers(self, grouped_layers, verifiable_layers):
"""Groups dual layers as required by the verification strategy.
Args:
grouped_layers: Populated on exit with list of `VerifiableLayer` objects
specifying layers that give rise to dual variables.
verifiable_layers: List of `SingleVerifiableLayer` objects specifying
linear layers and non-linear activation functions.
Raises:
ValueError: if an unsupported layer type or arrangement is encountered.
"""
l = 0
while l < len(verifiable_layers):
l = self._group_next_layer(grouped_layers, verifiable_layers, l)
def _group_next_layer(self, grouped_layers, verifiable_layers, l):
"""One step of dual layer grouping as required by the verification strategy.
Args:
grouped_layers: On exit, a new `VerifiableLayer` object will be appended,
specifying a grouped layer that give rise to dual variables.
verifiable_layers: List of `SingleVerifiableLayer` objects specifying
linear layers and non-linear activation functions.
l: Index within `verifiable_layers` at which to start grouping.
Returns:
Updated value of `l`: index within `verifiable_layers` up to which
grouping has completed.
"""
if self._use_reduced:
# Activation layer followed by linear layer.
activation_layer = verifiable_layers[l]
l += 1
if l == len(verifiable_layers):
raise ValueError('This formulation requires the network to end '
'linear -> activation -> linear.')
linear_layer, l = self._get_single_layer(verifiable_layers, l)
grouped_layers.append(layers_combined.CombinedLayer(
activation_layer,
linear_layer))
return l
else:
# Standard formulation. Linear and activation layers are kept single.
layer, l = self._get_single_layer(verifiable_layers, l)
grouped_layers.append(layer)
return l
def _get_single_layer(self, verifiable_layers, l):
"""Extracts a single layer, grouping consecutive linear layers.
Args:
verifiable_layers: List of `SingleVerifiableLayer` objects specifying
linear layers and non-linear activation functions.
l: Index within `verifiable_layers` at which to extract.
Returns:
layer: `layer`, with any grouping operations applied.
l: Updated value of `l`: index within `verifiable_layers` up to which
layers have been consumed.
"""
layer = verifiable_layers[l]
l += 1
if isinstance(layer, layers.AffineLayer):
while l < len(verifiable_layers) and isinstance(verifiable_layers[l],
layers.AffineLayer):
layer = layers_combined.CombinedLinearLayer(layer, verifiable_layers[l])
l += 1
return self._single_layer(layer), l
def _single_layer(self, layer):
"""Groups a single layer.
Args:
layer: layer to group.
Returns:
`layer`, with any grouping operations applied.
"""
# This implementation is a no-op, but sub-classes will override this
# to handle ResNet blocks (recursively grouping their child layers).
return layer
def _is_affine_next(self, layer):
return (isinstance(layer, layers.AffineLayer) or
isinstance(layer, layers_combined.CombinedLinearLayer))
def set_objective_computation_config(self, config):
self._inverse_temperature = None
if config is not None:
self._inverse_temperature = config.get(
'inverse_temperature', float('inf'))
if (isinstance(self._inverse_temperature, float) and
self._inverse_temperature == float('inf')):
self._inverse_temperature = None
def dual_objective(self, verifiable_layers, labels, dual_var_lists,
target_strategy=None, objective_computation_config=None):
"""Computes the Lagrangian (dual objective).
Args:
verifiable_layers: List of `VerifiableLayer` objects specifying layers
that give rise to dual variables.
labels: 1D integer tensor of shape (batch_size) of labels for each
input example.
dual_var_lists: Nested list of 3D tensors of shape
(num_classes, batch_size, layer_size) and 5D tensors of shape
(num_classes, batch_size, height, width, channels)
containing Lagrange multipliers for the layers' calculations.
This has the same length as `verifiable_layers`, and typically each
entry is a singleton list with the dual variable for that layer.
ResNet blocks' entries have instead the structure
[[left-sub-duals], [right-sub-duals], overall-dual].
target_strategy: a `TargetObjective` object which gets the objective
weights of the final layer depending on the strategy of the final
objective. Default is set to None in which case it uses the default
target strategy.
objective_computation_config: `ConfigDict` of additional parameters.
Returns:
2D tensor of shape (num_classes, batch_size) containing dual objective
for each target class, for each example.
"""
self.set_objective_computation_config(objective_computation_config)
batch_size = tf.shape(labels)[0]
dtype = verifiable_layers[-1].output_bounds.lower.dtype
# Use broadcasting. The last layer will force the objective shape to be
# `[num_classes, batch_size]`.
objective = tf.zeros([1, batch_size], dtype=dtype)
# The Lagrangian is L = sum_l max_x [lam_{l-1}^T x - lam_l^T h_l(x)]
# where h_l(x) is layer l applied to values x, lam_{-1}=0.
# For numerical stability, we actually calculate this as follows:
# rearranged (but algebraically equivalent) way:
# L = sum_l max_x [lam_{l-1}^T (x - a_l) - lam_l^T (h_l(x) - h_l(a_l))]
# - lam_{final-1} a_{final}
# where a_l are the nominal input values to layer l.
# This rearranged form is equivalent because a_{l+1} = h_l(a_l).
# Note: c = -lam_{final-1} are the objective weights.
for l in range(len(verifiable_layers) - 1):
if l == 0:
dual_vars_lm1 = None
else:
dual_vars_lm1 = verifiable_layers[l-1].reshape_duals_forwards(
verifiable_layers[l], dual_var_lists[l-1][-1])
objective += self.layer_contrib(verifiable_layers[l],
dual_vars_lm1, *dual_var_lists[l])
# The negated objective weights take the role of dual variable for the
# last layer.
last_layer = verifiable_layers[-1] # activation+linear combined.
objective_weights = last_layer.linear_layer.get_objective_weights(
labels, target_strategy=target_strategy)
last_dual_var = last_layer.reshape_duals_backwards(-objective_weights.w)
# Contribution for the final activation layer.
dual_vars_lm1 = verifiable_layers[-2].reshape_duals_forwards(
last_layer, dual_var_lists[len(verifiable_layers) - 2][-1])
objective += self.layer_contrib(last_layer.activation_layer,
dual_vars_lm1, last_dual_var)
# Constant term (objective layer bias).
objective += tf.reduce_sum(
objective_weights.w * last_layer.linear_layer.input_bounds.nominal,
axis=list(range(2, objective_weights.w.shape.ndims)))
objective += objective_weights.b
return objective
def layer_contrib(self, layer, dual_vars_lm1, *dual_vars):
"""Computes the contribution of a layer to the dual objective."""
if isinstance(layer, layers_combined.CombinedLayer):
# Activation+Affine combination for the 'reduced' formulation.
# Back-prop the duals through the affine layer.
act_coeffs, obj_linear = self.affine_layer_act_coeffs(layer.linear_layer,
*dual_vars)
lam_out = layer.reshape_duals_backwards(-act_coeffs)
# Contribution for the activation layer.
obj_activation = self.layer_contrib(layer.activation_layer,
dual_vars_lm1, lam_out)
return obj_linear + obj_activation
elif self._is_affine_next(layer):
activation_coeffs, dual_obj_bias = self.affine_layer_act_coeffs(
layer, *dual_vars)
# Compute:
# max_x (lam_{l-1}^T x - mu_l^T (W_l x + b_l))
# where mu_l^T W_l is activation_coeffs
# and mu_l^T b_l is dual_obj_bias.
return self.affine_layer_contrib(layer, dual_vars_lm1,
activation_coeffs, dual_obj_bias)
else:
# Compute the term
# max_y (mu_l^T y - lam_l^T h_l(y))
# where h_l is the non-linearity for layer l.
return self.nonlinear_layer_contrib(layer, dual_vars_lm1, *dual_vars)
def affine_layer_act_coeffs(self, layer, *dual_vars):
"""Computes the coefficients W_l^T mu_l and b_l^T mu_l.
These will later be used in the expression::
max_x (lam_{l-1}^T x - mu_l^T (W_l x + b_l))
where W_l, b_l is the affine mapping for layer l.
Args:
layer: affine layer, or ResNet block beginning/ending with affine layers.
*dual_vars: mu_l, preceded by branch dual vars if it's a ResNet block.
Returns:
activation_coeffs: W_l^T mu_l
dual_obj: b_l^T mu_l, the contribution to the dual objective
"""
mu_l, = dual_vars
mu_l = layer.backward_prop_batchnorm(mu_l)
activation_coeffs = -layer.backward_prop(mu_l)
# Objective contribution is zero, as we work relative to nominals.
dual_obj = tf.zeros(tf.shape(mu_l)[:2], dtype=mu_l.dtype)
return activation_coeffs, dual_obj
def affine_layer_contrib(self, layer, dual_vars_lm1,
activation_coeffs, dual_obj_bias):
"""Computes the contribution of an affine layer to the dual objective.
Compute the term::
max_x (lam_{l-1}^T x - mu_l^T (W_l x + b_l))
where W_l, b_l is the affine mapping for layer l.
Args:
layer: affine (linear/conv) layer.
dual_vars_lm1: lam_{l-1}, or None for the first layer.
activation_coeffs: mu_l^T W_l
dual_obj_bias: mu_l^T b_l
Returns:
Dual objective contribution.
"""
return standard_layer_calcs.linear_dual_objective(
dual_vars_lm1,
activation_coeffs, dual_obj_bias,
layer.input_bounds.lower_offset, layer.input_bounds.upper_offset,
inverse_temperature=self._inverse_temperature)
def nonlinear_layer_contrib(self, layer, dual_vars_lm1, *dual_vars):
"""Computes the contribution of a non-linear layer to the dual objective.
Compute the term
max_y (mu_l^T y - lam_l^T h_l(y))
where h_l is the non-linearity for layer l.
Args:
layer: non-linear layer, or ResNet block beginning with a non-linear
layer.
dual_vars_lm1: mu_{l-1}
*dual_vars: lam_l, preceded by branch dual vars if it's a ResNet block.
Returns:
Dual objective contribution.
"""
# Invoke visit_activation, visit_maxpool, or visit_resnet_block.
return layer.custom_op(self, dual_vars_lm1, *dual_vars)
def visit_activation(self, layer, mu_lm1, lam_l):
return standard_layer_calcs.activation_layer_dual_objective(
layer.module, mu_lm1, lam_l,
layer.input_bounds.lower_offset, layer.input_bounds.upper_offset,
nominal=layer.input_bounds.nominal, parameters=layer.parameters,
inverse_temperature=self._inverse_temperature)
def visit_maxpool(self, layer, mu_lm1, lam_l):
self._ensure_no_temperature()
return standard_layer_calcs.maxpool_layer_dual_objective(
layer.kernel_shape, layer.strides, layer.with_relu, mu_lm1, lam_l,
layer.input_bounds.lower_offset, layer.input_bounds.upper_offset,
nominal=layer.input_bounds.nominal)
def _ensure_no_temperature(self):
if self._inverse_temperature is not None:
raise ValueError('Smoothing of the dual objective is not supported.')
| deep-verify-master | deep_verify/src/formulations/standard/verify_dual_standard.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.
# ==============================================================================
"""Training and evaluation loops for an experiment.
The code in this file is adapted from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
import time
from typing import Any, Mapping, Text, Type
from absl import app
from absl import flags
from absl import logging
import jax
import numpy as np
from semppl import eval_experiment
from semppl.configs import eval as eval_config
_WORKER_MODE = flags.DEFINE_string('worker_mode', 'train',
'The mode, train or eval')
_WORKER_TPU_DRIVER = flags.DEFINE_string('worker_tpu_driver', '',
'The tpu driver to use')
_BATCH_SIZE = flags.DEFINE_integer('batch_size', 1024, 'Total batch size')
_NUM_EPOCHS = flags.DEFINE_integer('num_epochs', 100,
'Number of training epochs for evaluation.')
_CHECKPOINT_ROOT = flags.DEFINE_string('checkpoint_root', '',
'The directory to save checkpoints to.')
_LOG_TENSORS_INTERVAL = flags.DEFINE_integer('log_tensors_interval', 60,
'Log tensors every n seconds.')
FLAGS = flags.FLAGS
ExperimentType = Type[eval_experiment.EvalExperiment]
def train_loop(experiment_class: ExperimentType, config: Mapping[Text, Any]):
"""The main training loop.
This loop periodically saves a checkpoint to be evaluated in the eval_loop.
Args:
experiment_class: the constructor for the experiment.
config: the experiment config.
"""
experiment = experiment_class(**config)
rng = jax.random.PRNGKey(0)
step = 0
host_id = jax.host_id()
last_logging = time.time()
if config['checkpointing_config']['use_checkpointing']:
checkpoint_data = experiment.load_checkpoint()
if checkpoint_data is None:
step = 0
else:
step, rng = checkpoint_data
local_device_count = jax.local_device_count()
while step < config['max_steps']:
step_rng, rng = tuple(jax.random.split(rng))
# Broadcast the random seeds across the devices
step_rng_device = jax.random.split(step_rng, num=jax.device_count())
first_local_device_id = host_id * local_device_count
step_rng_device = step_rng_device[first_local_device_id:(
first_local_device_id + local_device_count)]
step_device = np.broadcast_to(step, [local_device_count])
# Perform a training step and get scalars to log.
scalars = experiment.step(global_step=step_device, rng=step_rng_device)
# Checkpointing and logging.
if config['checkpointing_config']['use_checkpointing']:
experiment.save_checkpoint(step, rng)
current_time = time.time()
if current_time - last_logging > _LOG_TENSORS_INTERVAL.value:
logging.info('Step %d: %s', step, scalars)
last_logging = current_time
step += 1
logging.info('Saving final checkpoint')
logging.info('Step %d: %s', step, scalars)
experiment.save_checkpoint(step, rng)
def eval_loop(experiment_class: ExperimentType, config: Mapping[Text, Any]):
"""The main evaluation loop.
This loop periodically loads a checkpoint and evaluates its performance on the
test set, by calling experiment.evaluate.
Args:
experiment_class: the constructor for the experiment.
config: the experiment config.
"""
experiment = experiment_class(**config)
last_evaluated_step = -1
while True:
checkpoint_data = experiment.load_checkpoint()
if checkpoint_data is None:
logging.info('No checkpoint found. Waiting for 10s.')
time.sleep(10)
continue
step, _ = checkpoint_data
if step <= last_evaluated_step:
logging.info('Checkpoint at step %d already evaluated, waiting.', step)
time.sleep(10)
continue
host_id = jax.host_id()
local_device_count = jax.local_device_count()
step_device = np.broadcast_to(step, [local_device_count])
scalars = experiment.evaluate(global_step=step_device)
if host_id == 0: # Only perform logging in one host.
logging.info('Evaluation at step %d: %s', step, scalars)
last_evaluated_step = step
if last_evaluated_step >= config['max_steps']:
return
def main(_):
if _WORKER_TPU_DRIVER.value:
jax.config.update('jax_xla_backend', 'tpu_driver')
jax.config.update('jax_backend_target', _WORKER_TPU_DRIVER.value)
logging.info('Backend: %s %r', _WORKER_TPU_DRIVER.value, jax.devices())
experiment_class = eval_experiment.EvalExperiment
config = eval_config.get_config(f'{_CHECKPOINT_ROOT.value}/pretrain.pkl',
_BATCH_SIZE.value, _NUM_EPOCHS.value)
config['checkpointing_config']['checkpoint_dir'] = _CHECKPOINT_ROOT.value # pytype: disable=unsupported-operands # dict-kwargs
if _WORKER_MODE.value == 'train':
train_loop(experiment_class, config)
elif _WORKER_MODE.value == 'eval':
eval_loop(experiment_class, config)
if __name__ == '__main__':
app.run(main)
| semppl-main | main_loop.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for SemPPL's main training loop.
The code in this file is adapted from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
from absl import flags
from absl.testing import absltest
import tensorflow_datasets as tfds
from semppl import eval_experiment
from semppl import main_loop
from semppl.configs import eval as eval_config
FLAGS = flags.FLAGS
class MainLoopTest(absltest.TestCase):
def test_linear_eval(self):
config = eval_config.get_config(
checkpoint_to_evaluate=None, batch_size=4, num_epochs=10)
temp_dir = self.create_tempdir().full_path
# Override some config fields to make test lighter.
config['network_config']['encoder_class'] = 'TinyResNet'
config['allow_train_from_scratch'] = True
config['checkpointing_config']['checkpoint_dir'] = temp_dir
config['evaluation_config']['batch_size'] = 16
config['max_steps'] = 16
with tfds.testing.mock_data(num_examples=64):
experiment_class = eval_experiment.EvalExperiment
main_loop.train_loop(experiment_class, config)
main_loop.eval_loop(experiment_class, config)
if __name__ == '__main__':
absltest.main()
| semppl-main | main_loop_test.py |
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Linear evaluation or fine-tuning pipeline.
Use this experiment to evaluate a checkpoint.
The code in this file is adapted from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
import functools
from typing import Any, Generator, Mapping, NamedTuple, Optional, Text, Tuple, Union
from absl import logging
from acme.jax import utils as acme_utils
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
from semppl.utils import checkpointing
from semppl.utils import dataset
from semppl.utils import helpers
from semppl.utils import networks
from semppl.utils import schedules
# Type declarations.
OptState = Tuple[optax.TraceState, optax.ScaleByScheduleState, optax.ScaleState]
LogsDict = Mapping[Text, jnp.ndarray]
class _EvalExperimentState(NamedTuple):
backbone_params: hk.Params
classif_params: hk.Params
backbone_state: hk.State
backbone_opt_state: Union[None, OptState]
classif_opt_state: OptState
class EvalExperiment:
"""Linear evaluation experiment."""
def __init__(self, random_seed: int, num_classes: int, batch_size: int,
max_steps: int, enable_double_transpose: bool,
checkpoint_to_evaluate: Optional[Text],
allow_train_from_scratch: bool, freeze_backbone: bool,
network_config: Mapping[Text, Any],
optimizer_config: Mapping[Text, Any],
lr_schedule_config: Mapping[Text, Any],
evaluation_config: Mapping[Text, Any],
checkpointing_config: Mapping[Text, Any]):
"""Constructs the experiment.
Args:
random_seed: the random seed to use when initializing network weights.
num_classes: the number of classes; used for the online evaluation.
batch_size: the total batch size; should be a multiple of the number of
available accelerators.
max_steps: the number of training steps; used for the lr/target network
ema schedules.
enable_double_transpose: see dataset.py; only has effect on TPU.
checkpoint_to_evaluate: the path to the checkpoint to evaluate.
allow_train_from_scratch: whether to allow training without specifying a
checkpoint to evaluate (training from scratch).
freeze_backbone: whether the backbone resnet should remain frozen (linear
evaluation) or be trainable (fine-tuning).
network_config: the configuration for the network.
optimizer_config: the configuration for the optimizer.
lr_schedule_config: the configuration for the learning rate schedule.
evaluation_config: the evaluation configuration.
checkpointing_config: the configuration for checkpointing.
"""
self._random_seed = random_seed
self._enable_double_transpose = enable_double_transpose
self._num_classes = num_classes
self._lr_schedule_config = lr_schedule_config
self._batch_size = batch_size
self._max_steps = max_steps
self._checkpoint_to_evaluate = checkpoint_to_evaluate
self._allow_train_from_scratch = allow_train_from_scratch
self._freeze_backbone = freeze_backbone
self._optimizer_config = optimizer_config
self._evaluation_config = evaluation_config
# Checkpointed experiment state.
self._experiment_state = None
# Input pipelines.
self._train_input = None
self._eval_input = None
backbone_fn = functools.partial(self._backbone_fn, **network_config)
self.forward_backbone = hk.without_apply_rng(
hk.transform_with_state(backbone_fn))
self.forward_classif = hk.without_apply_rng(hk.transform(self._classif_fn))
self.update_pmap = jax.pmap(self._update_func, axis_name='i')
self.eval_batch_jit = jax.jit(self._eval_batch)
self._is_backbone_training = not self._freeze_backbone
self._checkpointer = checkpointing.Checkpointer(**checkpointing_config)
def _should_transpose_images(self):
"""Should we transpose images (saves host-to-device time on TPUs)."""
return (self._enable_double_transpose and
jax.local_devices()[0].platform == 'tpu')
def _backbone_fn(
self,
inputs: dataset.Batch,
encoder_class: Text,
encoder_config: Mapping[Text, Any],
bn_decay_rate: float,
is_training: bool,
) -> jnp.ndarray:
"""Forward of the encoder (backbone)."""
bn_config = {'decay_rate': bn_decay_rate}
encoder = getattr(networks, encoder_class)
model = encoder(None, bn_config=bn_config, **encoder_config)
if self._should_transpose_images():
inputs = dataset.transpose_images(inputs)
images = dataset.normalize_images(inputs['images'])
return model(images, is_training=is_training)
def _classif_fn(
self,
embeddings: jnp.ndarray,
) -> jnp.ndarray:
classifier = hk.Linear(output_size=self._num_classes)
return classifier(embeddings)
# _ _
# | |_ _ __ __ _(_)_ __
# | __| '__/ _` | | '_ \
# | |_| | | (_| | | | | |
# \__|_| \__,_|_|_| |_|
#
def step(self, *, global_step: jnp.ndarray,
rng: jnp.ndarray) -> Mapping[Text, np.ndarray]:
"""Performs a single training step."""
if self._train_input is None:
self._initialize_train(rng)
inputs = next(self._train_input)
self._experiment_state, scalars = self.update_pmap(self._experiment_state,
global_step, inputs)
scalars = helpers.get_first(scalars)
return scalars
def save_checkpoint(self, step: int, rng: jnp.ndarray):
self._checkpointer.maybe_save_checkpoint(
self._experiment_state,
step=step,
rng=rng,
is_final=step >= self._max_steps)
def load_checkpoint(self) -> Union[Tuple[int, jnp.ndarray], None]:
checkpoint_data = self._checkpointer.maybe_load_checkpoint()
if checkpoint_data is None:
return None
self._experiment_state, step, rng = checkpoint_data
return step, rng
def _initialize_train(self, rng):
"""SemPPL's _ExperimentState initialization.
Args:
rng: random number generator used to initialize parameters. If working in
a multi device setup, this need to be a ShardedArray.
dummy_input: a dummy image, used to compute intermediate outputs shapes.
Returns:
Initial EvalExperiment state.
Raises:
RuntimeError: invalid or empty checkpoint.
"""
self._train_input = acme_utils.prefetch(self._build_train_input())
# Check we haven't already restored params
if self._experiment_state is None:
inputs = next(self._train_input)
if self._checkpoint_to_evaluate is not None:
# Load params from checkpoint
checkpoint_data = checkpointing.load_checkpoint(
self._checkpoint_to_evaluate)
if checkpoint_data is None:
raise RuntimeError('Invalid checkpoint.')
backbone_params = helpers.get_first(
checkpoint_data['experiment_state']['online_params'])
backbone_state = helpers.get_first(
checkpoint_data['experiment_state']['online_state'])
backbone_params = helpers.bcast_local_devices(backbone_params)
backbone_state = helpers.bcast_local_devices(backbone_state)
else:
if not self._allow_train_from_scratch:
raise ValueError(
'No checkpoint specified, but `allow_train_from_scratch` '
'set to False')
# Initialize with random parameters
logging.info(
'No checkpoint specified, initializing the networks from scratch '
'(dry run mode)')
backbone_params, backbone_state = jax.pmap(
functools.partial(self.forward_backbone.init, is_training=True),
axis_name='i')(
rng=rng, inputs=inputs)
init_experiment = jax.pmap(self._make_initial_state, axis_name='i')
# Init uses the same RNG key on all hosts+devices to ensure everyone
# computes the same initial state and parameters.
init_rng = jax.random.PRNGKey(self._random_seed)
init_rng = helpers.bcast_local_devices(init_rng)
self._experiment_state = init_experiment(
rng=init_rng,
dummy_input=inputs,
backbone_params=backbone_params,
backbone_state=backbone_state)
# Clear the backbone optimizer's state when the backbone is frozen.
if self._freeze_backbone:
self._experiment_state = _EvalExperimentState(
backbone_params=self._experiment_state.backbone_params,
classif_params=self._experiment_state.classif_params,
backbone_state=self._experiment_state.backbone_state,
backbone_opt_state=None,
classif_opt_state=self._experiment_state.classif_opt_state,
)
def _make_initial_state(
self,
rng: jnp.ndarray,
dummy_input: dataset.Batch,
backbone_params: hk.Params,
backbone_state: hk.Params,
) -> _EvalExperimentState:
"""_EvalExperimentState initialization."""
# Initialize the backbone params
# Always create the batchnorm weights (is_training=True), they will be
# overwritten when loading the checkpoint.
embeddings, _ = self.forward_backbone.apply(
backbone_params, backbone_state, dummy_input, is_training=True)
backbone_opt_state = self._optimizer(0.).init(backbone_params)
# Initialize the classifier params and optimizer_state
classif_params = self.forward_classif.init(rng, embeddings)
classif_opt_state = self._optimizer(0.).init(classif_params)
return _EvalExperimentState( # pytype: disable=wrong-arg-types # numpy-scalars
backbone_params=backbone_params,
classif_params=classif_params,
backbone_state=backbone_state,
backbone_opt_state=backbone_opt_state,
classif_opt_state=classif_opt_state,
)
def _build_train_input(self) -> Generator[dataset.Batch, None, None]:
"""See base class."""
num_devices = jax.device_count()
global_batch_size = self._batch_size
per_device_batch_size, ragged = divmod(global_batch_size, num_devices)
if ragged:
raise ValueError(
f'Global batch size {global_batch_size} must be divisible by '
f'num devices {num_devices}')
return dataset.load(
dataset.Split.TRAIN_AND_VALID,
preprocess_mode=dataset.PreprocessMode.LINEAR_TRAIN,
transpose=self._should_transpose_images(),
batch_dims=[jax.local_device_count(), per_device_batch_size])
def _optimizer(self, learning_rate: float):
"""Build optimizer from config."""
return optax.sgd(learning_rate, **self._optimizer_config)
def _loss_fn(
self,
backbone_params: hk.Params,
classif_params: hk.Params,
backbone_state: hk.State,
inputs: dataset.Batch,
) -> Tuple[jnp.ndarray, Tuple[jnp.ndarray, hk.State]]:
"""Compute the classification loss function.
Args:
backbone_params: parameters of the encoder network.
classif_params: parameters of the linear classifier.
backbone_state: internal state of encoder network.
inputs: inputs, containing `images` and `labels`.
Returns:
The classification loss and various logs.
"""
embeddings, backbone_state = self.forward_backbone.apply(
backbone_params,
backbone_state,
inputs,
is_training=not self._freeze_backbone)
logits = self.forward_classif.apply(classif_params, embeddings)
labels = hk.one_hot(inputs['labels'], self._num_classes)
loss = helpers.softmax_cross_entropy(logits, labels, reduction='mean')
scaled_loss = loss / jax.device_count()
return scaled_loss, (loss, backbone_state)
def _update_func(
self,
experiment_state: _EvalExperimentState,
global_step: jnp.ndarray,
inputs: dataset.Batch,
) -> Tuple[_EvalExperimentState, LogsDict]:
"""Applies an update to parameters and returns new state."""
# This function computes the gradient of the first output of loss_fn and
# passes through the other arguments unchanged.
# Gradient of the first output of _loss_fn wrt the backbone (arg 0) and the
# classifier parameters (arg 1). The auxiliary outputs are returned as-is.
grad_loss_fn = jax.grad(self._loss_fn, has_aux=True, argnums=(0, 1))
grads, aux_outputs = grad_loss_fn(
experiment_state.backbone_params,
experiment_state.classif_params,
experiment_state.backbone_state,
inputs,
)
backbone_grads, classifier_grads = grads
train_loss, new_backbone_state = aux_outputs
classifier_grads = jax.lax.psum(classifier_grads, axis_name='i')
# Compute the decayed learning rate
learning_rate = schedules.learning_schedule(
global_step,
batch_size=self._batch_size,
total_steps=self._max_steps,
**self._lr_schedule_config)
logging.info('Learning rate: %s', learning_rate)
# Compute and apply updates via our optimizer.
classif_updates, new_classif_opt_state = self._optimizer(
learning_rate).update(classifier_grads,
experiment_state.classif_opt_state)
new_classif_params = optax.apply_updates(experiment_state.classif_params,
classif_updates)
if self._freeze_backbone:
del backbone_grads, new_backbone_state # Unused
# The backbone is not updated.
new_backbone_params = experiment_state.backbone_params
new_backbone_opt_state = None
new_backbone_state = experiment_state.backbone_state
else:
backbone_grads = jax.lax.psum(backbone_grads, axis_name='i')
# Compute and apply updates via our optimizer.
backbone_updates, new_backbone_opt_state = self._optimizer(
learning_rate).update(backbone_grads,
experiment_state.backbone_opt_state)
new_backbone_params = optax.apply_updates(
experiment_state.backbone_params, backbone_updates)
experiment_state = _EvalExperimentState( # pytype: disable=wrong-arg-types # numpy-scalars
new_backbone_params,
new_classif_params,
new_backbone_state,
new_backbone_opt_state,
new_classif_opt_state,
)
# Scalars to log (note: we log the mean across all hosts/devices).
scalars = {'train_loss': train_loss}
scalars = jax.lax.pmean(scalars, axis_name='i')
return experiment_state, scalars
# _
# _____ ____ _| |
# / _ \ \ / / _` | |
# | __/\ V / (_| | |
# \___| \_/ \__,_|_|
#
def evaluate(self, global_step, **unused_args):
"""See base class."""
global_step = np.array(helpers.get_first(global_step))
scalars = jax.device_get(self._eval_epoch(**self._evaluation_config))
logging.info('[Step %d] Eval scalars: %s', global_step, scalars)
return scalars
def _eval_batch(
self,
backbone_params: hk.Params,
classif_params: hk.Params,
backbone_state: hk.State,
inputs: dataset.Batch,
) -> LogsDict:
"""Evaluates a batch."""
embeddings, backbone_state = self.forward_backbone.apply(
backbone_params, backbone_state, inputs, is_training=False)
logits = self.forward_classif.apply(classif_params, embeddings)
labels = hk.one_hot(inputs['labels'], self._num_classes)
loss = helpers.softmax_cross_entropy(logits, labels, reduction=None)
top1_correct = helpers.topk_accuracy(logits, inputs['labels'], topk=1) # pytype: disable=wrong-arg-types # jax-ndarray
top5_correct = helpers.topk_accuracy(logits, inputs['labels'], topk=5) # pytype: disable=wrong-arg-types # jax-ndarray
# NOTE: Returned values will be summed and finally divided by num_samples.
return {
'eval_loss': loss,
'top1_accuracy': top1_correct,
'top5_accuracy': top5_correct
}
def _eval_epoch(self, subset: Text, batch_size: int):
"""Evaluates an epoch."""
num_samples = 0.
summed_scalars = None
backbone_params = helpers.get_first(self._experiment_state.backbone_params)
classif_params = helpers.get_first(self._experiment_state.classif_params)
backbone_state = helpers.get_first(self._experiment_state.backbone_state)
split = dataset.Split.from_string(subset)
dataset_iterator = dataset.load(
split,
preprocess_mode=dataset.PreprocessMode.EVAL,
transpose=self._should_transpose_images(),
batch_dims=[batch_size])
for inputs in dataset_iterator:
num_samples += inputs['labels'].shape[0]
scalars = self.eval_batch_jit(
backbone_params,
classif_params,
backbone_state,
inputs,
)
# 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)
mean_scalars = jax.tree_map(lambda x: x / num_samples, summed_scalars)
return mean_scalars
| semppl-main | eval_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.
# ==============================================================================
"""Utils for eval experiment."""
| semppl-main | utils/__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.
# ==============================================================================
"""Implementation of LARS Optimizer with optax.
The code in this file is taken from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
from typing import Any, Callable, List, NamedTuple, Optional, Tuple
import jax
import jax.numpy as jnp
import optax
import tree as nest
# A filter function takes a path and a value as input and outputs True for
# variable to apply update and False not to apply the update
FilterFn = Callable[[Tuple[Any], jnp.ndarray], jnp.ndarray]
def exclude_bias_and_norm(path: Tuple[Any], val: jnp.ndarray) -> jnp.ndarray:
"""Filter to exclude biaises and normalizations weights."""
del val
if path[-1] == "b" or "norm" in path[-2]:
return False # pytype: disable=bad-return-type # jax-ndarray
return True # pytype: disable=bad-return-type # jax-ndarray
def _partial_update(updates: optax.Updates,
new_updates: optax.Updates,
params: optax.Params,
filter_fn: Optional[FilterFn] = None) -> optax.Updates:
"""Returns new_update for params which filter_fn is True else updates."""
if filter_fn is None:
return new_updates
wrapped_filter_fn = lambda x, y: jnp.array(filter_fn(x, y))
params_to_filter = nest.map_structure_with_path(wrapped_filter_fn, params)
def _update_fn(g: jnp.ndarray, t: jnp.ndarray, m: jnp.ndarray) -> jnp.ndarray:
m = m.astype(g.dtype)
return g * (1. - m) + t * m
return jax.tree_map(_update_fn, updates, new_updates, params_to_filter)
class ScaleByLarsState(NamedTuple):
mu: jnp.ndarray
def scale_by_lars(
momentum: float = 0.9,
eta: float = 0.001,
filter_fn: Optional[FilterFn] = None) -> optax.GradientTransformation:
"""Rescales updates according to the LARS algorithm.
Does not include weight decay.
References:
[You et al, 2017](https://arxiv.org/abs/1708.03888)
Args:
momentum: momentum coeficient.
eta: LARS coefficient.
filter_fn: an optional filter function.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(params: optax.Params) -> ScaleByLarsState:
mu = jax.tree_map(jnp.zeros_like, params) # momentum
return ScaleByLarsState(mu=mu)
def update_fn(updates: optax.Updates, state: ScaleByLarsState,
params: optax.Params) -> Tuple[optax.Updates, ScaleByLarsState]:
def lars_adaptation(
update: jnp.ndarray,
param: jnp.ndarray,
) -> jnp.ndarray:
param_norm = jnp.linalg.norm(param)
update_norm = jnp.linalg.norm(update)
return update * jnp.where(
param_norm > 0.,
jnp.where(update_norm > 0,
(eta * param_norm / update_norm), 1.0), 1.0)
adapted_updates = jax.tree_map(lars_adaptation, updates, params)
adapted_updates = _partial_update(updates, adapted_updates, params,
filter_fn)
mu = jax.tree_map(lambda g, t: momentum * g + t, state.mu, adapted_updates)
return mu, ScaleByLarsState(mu=mu)
return optax.GradientTransformation(init_fn, update_fn)
class AddWeightDecayState(optax.TransformInitFn):
"""Stateless transformation."""
def add_weight_decay(
weight_decay: float,
filter_fn: Optional[FilterFn] = None) -> optax.GradientTransformation:
"""Adds a weight decay to the update.
Args:
weight_decay: weight_decay coeficient.
filter_fn: an optional filter function.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_) -> AddWeightDecayState:
return AddWeightDecayState()
def update_fn(
updates: optax.Updates,
state: AddWeightDecayState,
params: optax.Params,
) -> Tuple[optax.Updates, AddWeightDecayState]:
new_updates = jax.tree_map(lambda g, p: g + weight_decay * p, updates,
params)
new_updates = _partial_update(updates, new_updates, params, filter_fn)
return new_updates, state
return optax.GradientTransformation(init_fn, update_fn) # pytype: disable=wrong-arg-types # numpy-scalars
LarsState = List # Type for the lars optimizer
def lars(
learning_rate: float,
weight_decay: float = 0.,
momentum: float = 0.9,
eta: float = 0.001,
weight_decay_filter: Optional[FilterFn] = None,
lars_adaptation_filter: Optional[FilterFn] = None,
) -> optax.GradientTransformation:
"""Creates lars optimizer with weight decay.
References:
[You et al, 2017](https://arxiv.org/abs/1708.03888)
Args:
learning_rate: learning rate coefficient.
weight_decay: weight decay coefficient.
momentum: momentum coefficient.
eta: LARS coefficient.
weight_decay_filter: optional filter function to only apply the weight decay
on a subset of parameters. The filter function takes as input the
parameter path (as a tuple) and its associated update, and return a True
for params to apply the weight decay and False for params to not apply the
weight decay. When weight_decay_filter is set to None, the weight decay is
not applied to the bias, i.e. when the variable name is 'b', and the
weight decay is not applied to nornalization params, i.e. the panultimate
path contains 'norm'.
lars_adaptation_filter: similar to weight decay filter but for lars
adaptation
Returns:
An optax.GradientTransformation, i.e. a (init_fn, update_fn) tuple.
"""
if weight_decay_filter is None:
weight_decay_filter = lambda *_: True
if lars_adaptation_filter is None:
lars_adaptation_filter = lambda *_: True
return optax.chain(
add_weight_decay(
weight_decay=weight_decay, filter_fn=weight_decay_filter),
scale_by_lars(
momentum=momentum, eta=eta, filter_fn=lars_adaptation_filter),
optax.scale(-learning_rate),
)
| semppl-main | utils/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.
# ==============================================================================
"""ImageNet dataset with typical pre-processing.
The code in this file is taken from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
import enum
from typing import Generator, Mapping, Optional, Sequence, Text, Tuple
import jax
import jax.numpy as jnp
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
Batch = Mapping[Text, np.ndarray]
class Split(enum.Enum):
"""Imagenet dataset split."""
TRAIN = 1
TRAIN_AND_VALID = 2
VALID = 3
TEST = 4
@classmethod
def from_string(cls, name: Text) -> 'Split':
return {
'TRAIN': Split.TRAIN,
'TRAIN_AND_VALID': Split.TRAIN_AND_VALID,
'VALID': Split.VALID,
'VALIDATION': Split.VALID,
'TEST': Split.TEST
}[name.upper()]
@property
def num_examples(self):
return {
Split.TRAIN_AND_VALID: 1281167,
Split.TRAIN: 1271167,
Split.VALID: 10000,
Split.TEST: 50000
}[self]
class PreprocessMode(enum.Enum):
"""Preprocessing modes for the dataset."""
PRETRAIN = 1 # Generates two augmented views (random crop + augmentations).
LINEAR_TRAIN = 2 # Generates a single random crop.
EVAL = 3 # Generates a single center crop.
def normalize_images(images: jnp.ndarray) -> jnp.ndarray:
"""Normalize the image using ImageNet statistics."""
mean_rgb = (0.485, 0.456, 0.406)
stddev_rgb = (0.229, 0.224, 0.225)
normed_images = images - jnp.array(mean_rgb).reshape((1, 1, 1, 3))
normed_images = normed_images / jnp.array(stddev_rgb).reshape((1, 1, 1, 3))
return normed_images
def load(split: Split,
*,
preprocess_mode: PreprocessMode,
batch_dims: Sequence[int],
transpose: bool = False,
allow_caching: bool = False) -> Generator[Batch, None, None]:
"""Loads the given split of the dataset."""
start, end = _shard(split, jax.host_id(), jax.host_count())
total_batch_size = np.prod(batch_dims)
tfds_split = tfds.core.ReadInstruction(
_to_tfds_split(split), from_=start, to=end, unit='abs')
ds = tfds.load(
'imagenet2012:5.*.*',
split=tfds_split,
decoders={'image': tfds.decode.SkipDecoding()})
options = tf.data.Options()
options.experimental_threading.private_threadpool_size = 48
options.experimental_threading.max_intra_op_parallelism = 1
if preprocess_mode is not PreprocessMode.EVAL:
options.experimental_deterministic = False
if jax.host_count() > 1 and allow_caching:
# Only cache if we are reading a subset of the dataset.
ds = ds.cache()
ds = ds.repeat()
ds = ds.shuffle(buffer_size=10 * total_batch_size, seed=0)
else:
if split.num_examples % total_batch_size != 0:
raise ValueError(f'Test/valid must be divisible by {total_batch_size}')
ds = ds.with_options(options)
def preprocess_pretrain(example):
view1 = _preprocess_image(example['image'], mode=preprocess_mode)
view2 = _preprocess_image(example['image'], mode=preprocess_mode)
label = tf.cast(example['label'], tf.int32)
return {'view1': view1, 'view2': view2, 'labels': label}
def preprocess_linear_train(example):
image = _preprocess_image(example['image'], mode=preprocess_mode)
label = tf.cast(example['label'], tf.int32)
return {'images': image, 'labels': label}
def preprocess_eval(example):
image = _preprocess_image(example['image'], mode=preprocess_mode)
label = tf.cast(example['label'], tf.int32)
return {'images': image, 'labels': label}
if preprocess_mode is PreprocessMode.PRETRAIN:
ds = ds.map(
preprocess_pretrain, num_parallel_calls=tf.data.experimental.AUTOTUNE)
elif preprocess_mode is PreprocessMode.LINEAR_TRAIN:
ds = ds.map(
preprocess_linear_train,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
else:
ds = ds.map(
preprocess_eval, num_parallel_calls=tf.data.experimental.AUTOTUNE)
def transpose_fn(batch):
# We use the double-transpose-trick to improve performance for TPUs. Note
# that this (typically) requires a matching HWCN->NHWC transpose in your
# model code. The compiler cannot make this optimization for us since our
# data pipeline and model are compiled separately.
batch = dict(**batch)
if preprocess_mode is PreprocessMode.PRETRAIN:
batch['view1'] = tf.transpose(batch['view1'], (1, 2, 3, 0))
batch['view2'] = tf.transpose(batch['view2'], (1, 2, 3, 0))
else:
batch['images'] = tf.transpose(batch['images'], (1, 2, 3, 0))
return batch
for i, batch_size in enumerate(reversed(batch_dims)):
ds = ds.batch(batch_size)
if i == 0 and transpose:
ds = ds.map(transpose_fn) # NHWC -> HWCN
ds = ds.prefetch(tf.data.experimental.AUTOTUNE)
yield from tfds.as_numpy(ds)
def _to_tfds_split(split: Split) -> tfds.Split:
"""Returns the TFDS split appropriately sharded."""
# NOTE: Imagenet did not release labels for the test split used in the
# competition, we consider the VALID split the TEST split and reserve
# 10k images from TRAIN for VALID.
if split in (Split.TRAIN, Split.TRAIN_AND_VALID, Split.VALID):
return tfds.Split.TRAIN
else:
assert split == Split.TEST
return tfds.Split.VALIDATION
def _shard(split: Split, shard_index: int, num_shards: int) -> Tuple[int, int]:
"""Returns [start, end) for the given shard index."""
assert shard_index < num_shards
arange = np.arange(split.num_examples)
shard_range = np.array_split(arange, num_shards)[shard_index]
start, end = shard_range[0], (shard_range[-1] + 1)
if split == Split.TRAIN:
# Note that our TRAIN=TFDS_TRAIN[10000:] and VALID=TFDS_TRAIN[:10000].
offset = Split.VALID.num_examples
start += offset
end += offset
return start, end
def _preprocess_image(
image_bytes: tf.Tensor,
mode: PreprocessMode,
) -> tf.Tensor:
"""Returns processed and resized images."""
if mode is PreprocessMode.PRETRAIN:
image = _decode_and_random_crop(image_bytes)
# Random horizontal flipping is optionally done in augmentations.preprocess.
elif mode is PreprocessMode.LINEAR_TRAIN:
image = _decode_and_random_crop(image_bytes)
image = tf.image.random_flip_left_right(image)
else:
image = _decode_and_center_crop(image_bytes)
# NOTE: Bicubic resize (1) casts uint8 to float32 and (2) resizes without
# clamping overshoots. This means values returned will be outside the range
# [0.0, 255.0] (e.g. we have observed outputs in the range [-51.1, 336.6]).
assert image.dtype == tf.uint8
image = tf.image.resize(image, [224, 224], tf.image.ResizeMethod.BICUBIC)
image = tf.clip_by_value(image / 255., 0., 1.)
return image
def _decode_and_random_crop(image_bytes: tf.Tensor) -> tf.Tensor:
"""Make a random crop of 224."""
img_size = tf.image.extract_jpeg_shape(image_bytes)
area = tf.cast(img_size[1] * img_size[0], tf.float32)
target_area = tf.random.uniform([], 0.08, 1.0, dtype=tf.float32) * area
log_ratio = (tf.math.log(3 / 4), tf.math.log(4 / 3))
aspect_ratio = tf.math.exp(
tf.random.uniform([], *log_ratio, dtype=tf.float32))
w = tf.cast(tf.round(tf.sqrt(target_area * aspect_ratio)), tf.int32)
h = tf.cast(tf.round(tf.sqrt(target_area / aspect_ratio)), tf.int32)
w = tf.minimum(w, img_size[1])
h = tf.minimum(h, img_size[0])
offset_w = tf.random.uniform((),
minval=0,
maxval=img_size[1] - w + 1,
dtype=tf.int32)
offset_h = tf.random.uniform((),
minval=0,
maxval=img_size[0] - h + 1,
dtype=tf.int32)
crop_window = tf.stack([offset_h, offset_w, h, w])
image = tf.io.decode_and_crop_jpeg(image_bytes, crop_window, channels=3)
return image
def transpose_images(batch: Batch):
"""Transpose images for TPU training.."""
new_batch = dict(batch) # Avoid mutating in place.
if 'images' in batch:
new_batch['images'] = jnp.transpose(batch['images'], (3, 0, 1, 2))
else:
new_batch['view1'] = jnp.transpose(batch['view1'], (3, 0, 1, 2))
new_batch['view2'] = jnp.transpose(batch['view2'], (3, 0, 1, 2))
return new_batch
def _decode_and_center_crop(
image_bytes: tf.Tensor,
jpeg_shape: Optional[tf.Tensor] = None,
) -> tf.Tensor:
"""Crops to center of image with padding then scales."""
if jpeg_shape is None:
jpeg_shape = tf.image.extract_jpeg_shape(image_bytes)
image_height = jpeg_shape[0]
image_width = jpeg_shape[1]
padded_center_crop_size = tf.cast(
((224 / (224 + 32)) *
tf.cast(tf.minimum(image_height, image_width), tf.float32)), tf.int32)
offset_height = ((image_height - padded_center_crop_size) + 1) // 2
offset_width = ((image_width - padded_center_crop_size) + 1) // 2
crop_window = tf.stack([
offset_height, offset_width, padded_center_crop_size,
padded_center_crop_size
])
image = tf.image.decode_and_crop_jpeg(image_bytes, crop_window, channels=3)
return image
| semppl-main | utils/dataset.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.
# ==============================================================================
"""Networks used in SemPPL.
The code in this file is taken from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
from typing import Any, Mapping, Optional, Sequence, Text
import haiku as hk
import jax
import jax.numpy as jnp
class MLP(hk.Module):
"""One hidden layer perceptron, with normalization."""
def __init__(
self,
name: Text,
hidden_size: int,
output_size: int,
bn_config: Mapping[Text, Any],
):
super().__init__(name=name)
self._hidden_size = hidden_size
self._output_size = output_size
self._bn_config = bn_config
def __call__(self, inputs: jnp.ndarray, is_training: bool) -> jnp.ndarray:
out = hk.Linear(output_size=self._hidden_size, with_bias=True)(inputs)
out = hk.BatchNorm(**self._bn_config)(out, is_training=is_training)
out = jax.nn.relu(out)
out = hk.Linear(output_size=self._output_size, with_bias=False)(out)
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 ResNetTorso(hk.Module):
"""ResNet model."""
def __init__(
self,
blocks_per_group: Sequence[int],
num_classes: Optional[int] = None,
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
bottleneck: bool = True,
channels_per_group: Sequence[int] = (256, 512, 1024, 2048),
use_projection: Sequence[bool] = (True, True, True, True),
width_multiplier: int = 1,
name: Optional[str] = None,
):
"""Constructs a ResNet model.
Args:
blocks_per_group: A sequence of length 4 that indicates the number of
blocks created in each group.
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of three elements, `decay_rate`, `eps`, and
`cross_replica_axis`, to be passed on to the `BatchNorm` layers. By
default the `decay_rate` is `0.9` and `eps` is `1e-5`, and the axis is
`None`.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
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.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(name=name)
self.resnet_v2 = resnet_v2
bn_config = dict(bn_config or {})
bn_config.setdefault('decay_rate', 0.9)
bn_config.setdefault('eps', 1e-5)
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')
self.initial_conv = hk.Conv2D(
output_channels=64 * width_multiplier,
kernel_shape=7,
stride=2,
with_bias=False,
padding='SAME',
name='initial_conv')
if not self.resnet_v2:
self.initial_batchnorm = hk.BatchNorm(
name='initial_batchnorm', **bn_config)
self.block_groups = []
strides = (1, 2, 2, 2)
for i in range(4):
self.block_groups.append(
hk.nets.ResNet.BlockGroup(
channels=width_multiplier * channels_per_group[i],
num_blocks=blocks_per_group[i],
stride=strides[i],
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=bottleneck,
use_projection=use_projection[i],
name='block_group_%d' % (i)))
if self.resnet_v2:
self.final_batchnorm = hk.BatchNorm(name='final_batchnorm', **bn_config)
self.logits = hk.Linear(num_classes, w_init=jnp.zeros, name='logits')
def __call__(self, inputs, is_training, test_local_stats=False):
out = inputs
out = self.initial_conv(out)
if not self.resnet_v2:
out = self.initial_batchnorm(out, is_training, test_local_stats)
out = jax.nn.relu(out)
out = hk.max_pool(
out, window_shape=(1, 3, 3, 1), strides=(1, 2, 2, 1), padding='SAME')
for block_group in self.block_groups:
out = block_group(out, is_training, test_local_stats)
if self.resnet_v2:
out = self.final_batchnorm(out, is_training, test_local_stats)
out = jax.nn.relu(out)
out = jnp.mean(out, axis=[1, 2])
return out
class TinyResNet(ResNetTorso):
"""Tiny resnet for local runs and tests."""
def __init__(self,
num_classes: Optional[int] = None,
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(
blocks_per_group=(1, 1, 1, 1),
channels_per_group=(8, 8, 8, 8),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=False,
width_multiplier=width_multiplier,
name=name)
class ResNet18(ResNetTorso):
"""ResNet18."""
def __init__(self,
num_classes: Optional[int] = None,
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(
blocks_per_group=(2, 2, 2, 2),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=False,
channels_per_group=(64, 128, 256, 512),
width_multiplier=width_multiplier,
name=name)
class ResNet34(ResNetTorso):
"""ResNet34."""
def __init__(self,
num_classes: Optional[int],
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(
blocks_per_group=(3, 4, 6, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=False,
channels_per_group=(64, 128, 256, 512),
width_multiplier=width_multiplier,
name=name)
class ResNet50(ResNetTorso):
"""ResNet50."""
def __init__(self,
num_classes: Optional[int] = None,
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(
blocks_per_group=(3, 4, 6, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=True,
width_multiplier=width_multiplier,
name=name)
class ResNet101(ResNetTorso):
"""ResNet101."""
def __init__(self,
num_classes: Optional[int],
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(
blocks_per_group=(3, 4, 23, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=True,
width_multiplier=width_multiplier,
name=name)
class ResNet152(ResNetTorso):
"""ResNet152."""
def __init__(self,
num_classes: Optional[int],
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(
blocks_per_group=(3, 8, 36, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=True,
width_multiplier=width_multiplier,
name=name)
class ResNet200(ResNetTorso):
"""ResNet200."""
def __init__(self,
num_classes: Optional[int],
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(
blocks_per_group=(3, 24, 36, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=True,
width_multiplier=width_multiplier,
name=name)
| semppl-main | utils/networks.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.
# ==============================================================================
"""Utility functions.
The code in this file is taken from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
from typing import Optional, Text
from absl import logging
import jax
import jax.numpy as jnp
def topk_accuracy(
logits: jnp.ndarray,
labels: jnp.ndarray,
topk: int,
ignore_label_above: Optional[int] = None,
) -> jnp.ndarray:
"""Top-num_codes accuracy."""
assert len(labels.shape) == 1, 'topk expects 1d int labels.'
assert len(logits.shape) == 2, 'topk expects 2d logits.'
if ignore_label_above is not None:
logits = logits[labels < ignore_label_above, :]
labels = labels[labels < ignore_label_above]
prds = jnp.argsort(logits, axis=1)[:, ::-1]
prds = prds[:, :topk]
total = jnp.any(prds == jnp.tile(labels[:, jnp.newaxis], [1, topk]), axis=1)
return total
def softmax_cross_entropy(
logits: jnp.ndarray,
labels: jnp.ndarray,
reduction: Optional[Text] = 'mean',
) -> jnp.ndarray:
"""Computes softmax cross entropy given logits and one-hot class labels.
Args:
logits: Logit output values.
labels: Ground truth one-hot-encoded labels.
reduction: Type of reduction to apply to loss.
Returns:
Loss value. If `reduction` is `none`, this has the same shape as `labels`;
otherwise, it is scalar.
Raises:
ValueError: If the type of `reduction` is unsupported.
"""
loss = -jnp.sum(labels * jax.nn.log_softmax(logits), axis=-1)
if reduction == 'sum':
return jnp.sum(loss)
elif reduction == 'mean':
return jnp.mean(loss)
elif reduction == 'none' or reduction is None:
return loss
else:
raise ValueError(f'Incorrect reduction mode {reduction}')
def l2_normalize(
x: jnp.ndarray,
axis: Optional[int] = None,
epsilon: float = 1e-12,
) -> jnp.ndarray:
"""l2 normalize a tensor on an axis with numerical stability."""
square_sum = jnp.sum(jnp.square(x), axis=axis, keepdims=True)
x_inv_norm = jax.lax.rsqrt(jnp.maximum(square_sum, epsilon))
return x * x_inv_norm
def l2_weight_regularizer(params):
"""Helper to do lasso on weights.
Args:
params: the entire param set.
Returns:
Scalar of the l2 norm of the weights.
"""
l2_norm = 0.
for mod_name, mod_params in params.items():
if 'norm' not in mod_name:
for param_k, param_v in mod_params.items():
if param_k != 'b' not in param_k: # Filter out biases
l2_norm += jnp.sum(jnp.square(param_v))
else:
logging.warning('Excluding %s/%s from optimizer weight decay!',
mod_name, param_k)
else:
logging.warning('Excluding %s from optimizer weight decay!', mod_name)
return 0.5 * l2_norm
def bcast_local_devices(value):
"""Broadcasts an object to all local devices."""
devices = jax.local_devices()
def _replicate(x):
"""Replicate an object on each device."""
x = jnp.array(x)
return jax.device_put_sharded(len(devices) * [x], devices)
return jax.tree_util.tree_map(_replicate, value)
def get_first(xs):
"""Gets values from the first device."""
return jax.tree_map(lambda x: x[0], xs)
| semppl-main | utils/helpers.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.
# ==============================================================================
"""Data preprocessing and augmentation.
The code in this file is taken from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
import functools
from typing import Any, Mapping, Text
import jax
import jax.numpy as jnp
# typing
JaxBatch = Mapping[Text, jnp.ndarray]
ConfigDict = Mapping[Text, Any]
augment_config = dict(
view1=dict(
random_flip=True, # Random left/right flip
color_transform=dict(
apply_prob=1.0,
# Range of jittering
brightness=0.4,
contrast=0.4,
saturation=0.2,
hue=0.1,
# Probability of applying color jittering
color_jitter_prob=0.8,
# Probability of converting to grayscale
to_grayscale_prob=0.2,
# Shuffle the order of color transforms
shuffle=True),
gaussian_blur=dict(
apply_prob=1.0,
# Kernel size ~ image_size / blur_divider
blur_divider=10.,
# Kernel distribution
sigma_min=0.1,
sigma_max=2.0),
solarize=dict(apply_prob=0.0, threshold=0.5),
),
view2=dict(
random_flip=True,
color_transform=dict(
apply_prob=1.0,
brightness=0.4,
contrast=0.4,
saturation=0.2,
hue=0.1,
color_jitter_prob=0.8,
to_grayscale_prob=0.2,
shuffle=True),
gaussian_blur=dict(
apply_prob=0.1, blur_divider=10., sigma_min=0.1, sigma_max=2.0),
solarize=dict(apply_prob=0.2, threshold=0.5),
))
def postprocess(inputs: JaxBatch, rng: jnp.ndarray):
"""Apply the image augmentations to crops in inputs (view1 and view2)."""
def _postprocess_image(
images: jnp.ndarray,
rng: jnp.ndarray,
presets: ConfigDict,
) -> JaxBatch:
"""Applies augmentations in post-processing.
Args:
images: an NHWC tensor (with C=3), with float values in [0, 1].
rng: a single PRNGKey.
presets: a dict of presets for the augmentations.
Returns:
A batch of augmented images with shape NHWC, with keys view1, view2
and labels.
"""
flip_rng, color_rng, blur_rng, solarize_rng = jax.random.split(rng, 4)
out = images
if presets['random_flip']:
out = random_flip(out, flip_rng)
if presets['color_transform']['apply_prob'] > 0:
out = color_transform(out, color_rng, **presets['color_transform'])
if presets['gaussian_blur']['apply_prob'] > 0:
out = gaussian_blur(out, blur_rng, **presets['gaussian_blur'])
if presets['solarize']['apply_prob'] > 0:
out = solarize(out, solarize_rng, **presets['solarize'])
out = jnp.clip(out, 0., 1.)
return jax.lax.stop_gradient(out)
rng1, rng2 = jax.random.split(rng, num=2)
view1 = _postprocess_image(inputs['view1'], rng1, augment_config['view1'])
view2 = _postprocess_image(inputs['view2'], rng2, augment_config['view2'])
return dict(view1=view1, view2=view2, labels=inputs['labels'])
def _maybe_apply(apply_fn, inputs, rng, apply_prob):
should_apply = jax.random.uniform(rng, shape=()) <= apply_prob
return jax.lax.cond(should_apply, inputs, apply_fn, inputs, lambda x: x)
def _depthwise_conv2d(inputs, kernel, strides, padding):
"""Computes a depthwise conv2d in Jax.
Args:
inputs: an NHWC tensor with N=1.
kernel: a [H", W", 1, C] tensor.
strides: a 2d tensor.
padding: "SAME" or "VALID".
Returns:
The depthwise convolution of inputs with kernel, as [H, W, C].
"""
return jax.lax.conv_general_dilated(
inputs,
kernel,
strides,
padding,
feature_group_count=inputs.shape[-1],
dimension_numbers=('NHWC', 'HWIO', 'NHWC'))
def _gaussian_blur_single_image(image, kernel_size, padding, sigma):
"""Applies gaussian blur to a single image, given as NHWC with N=1."""
radius = int(kernel_size / 2)
kernel_size_ = 2 * radius + 1
x = jnp.arange(-radius, radius + 1).astype(jnp.float32)
blur_filter = jnp.exp(-x**2 / (2. * sigma**2))
blur_filter = blur_filter / jnp.sum(blur_filter)
blur_v = jnp.reshape(blur_filter, [kernel_size_, 1, 1, 1])
blur_h = jnp.reshape(blur_filter, [1, kernel_size_, 1, 1])
num_channels = image.shape[-1]
blur_h = jnp.tile(blur_h, [1, 1, 1, num_channels])
blur_v = jnp.tile(blur_v, [1, 1, 1, num_channels])
expand_batch_dim = len(image.shape) == 3
if expand_batch_dim:
image = image[jnp.newaxis, ...]
blurred = _depthwise_conv2d(image, blur_h, strides=[1, 1], padding=padding)
blurred = _depthwise_conv2d(blurred, blur_v, strides=[1, 1], padding=padding)
blurred = jnp.squeeze(blurred, axis=0)
return blurred
def _random_gaussian_blur(image, rng, kernel_size, padding, sigma_min,
sigma_max, apply_prob):
"""Applies a random gaussian blur."""
apply_rng, transform_rng = jax.random.split(rng)
def _apply(image):
sigma_rng, = jax.random.split(transform_rng, 1)
sigma = jax.random.uniform(
sigma_rng,
shape=(),
minval=sigma_min,
maxval=sigma_max,
dtype=jnp.float32)
return _gaussian_blur_single_image(image, kernel_size, padding, sigma)
return _maybe_apply(_apply, image, apply_rng, apply_prob)
def rgb_to_hsv(r, g, b):
"""Converts R, G, B values to H, S, V values.
Reference TF implementation:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/adjust_saturation_op.cc
Only input values between 0 and 1 are guaranteed to work properly, but this
function complies with the TF implementation outside of this range.
Args:
r: A tensor representing the red color component as floats.
g: A tensor representing the green color component as floats.
b: A tensor representing the blue color component as floats.
Returns:
H, S, V values, each as tensors of shape [...] (same as the input without
the last dimension).
"""
vv = jnp.maximum(jnp.maximum(r, g), b)
range_ = vv - jnp.minimum(jnp.minimum(r, g), b)
sat = jnp.where(vv > 0, range_ / vv, 0.)
norm = jnp.where(range_ != 0, 1. / (6. * range_), 1e9)
hr = norm * (g - b)
hg = norm * (b - r) + 2. / 6.
hb = norm * (r - g) + 4. / 6.
hue = jnp.where(r == vv, hr, jnp.where(g == vv, hg, hb))
hue = hue * (range_ > 0)
hue = hue + (hue < 0)
return hue, sat, vv
def hsv_to_rgb(h, s, v):
"""Converts H, S, V values to an R, G, B tuple.
Reference TF implementation:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/adjust_saturation_op.cc
Only input values between 0 and 1 are guaranteed to work properly, but this
function complies with the TF implementation outside of this range.
Args:
h: A float tensor of arbitrary shape for the hue (0-1 values).
s: A float tensor of the same shape for the saturation (0-1 values).
v: A float tensor of the same shape for the value channel (0-1 values).
Returns:
An (r, g, b) tuple, each with the same dimension as the inputs.
"""
c = s * v
m = v - c
dh = (h % 1.) * 6.
fmodu = dh % 2.
x = c * (1 - jnp.abs(fmodu - 1))
hcat = jnp.floor(dh).astype(jnp.int32)
rr = jnp.where(
(hcat == 0) | (hcat == 5), c, jnp.where(
(hcat == 1) | (hcat == 4), x, 0)) + m
gg = jnp.where(
(hcat == 1) | (hcat == 2), c, jnp.where(
(hcat == 0) | (hcat == 3), x, 0)) + m
bb = jnp.where(
(hcat == 3) | (hcat == 4), c, jnp.where(
(hcat == 2) | (hcat == 5), x, 0)) + m
return rr, gg, bb
def adjust_brightness(rgb_tuple, delta):
return jax.tree_map(lambda x: x + delta, rgb_tuple)
def adjust_contrast(image, factor):
def _adjust_contrast_channel(channel):
mean = jnp.mean(channel, axis=(-2, -1), keepdims=True)
return factor * (channel - mean) + mean
return jax.tree_map(_adjust_contrast_channel, image)
def adjust_saturation(h, s, v, factor):
return h, jnp.clip(s * factor, 0., 1.), v
def adjust_hue(h, s, v, delta):
# Note: this method exactly matches TF"s adjust_hue (combined with the hsv/rgb
# conversions) when running on GPU. When running on CPU, the results will be
# different if all RGB values for a pixel are outside of the [0, 1] range.
return (h + delta) % 1.0, s, v
def _random_brightness(rgb_tuple, rng, max_delta):
delta = jax.random.uniform(rng, shape=(), minval=-max_delta, maxval=max_delta)
return adjust_brightness(rgb_tuple, delta)
def _random_contrast(rgb_tuple, rng, max_delta):
factor = jax.random.uniform(
rng, shape=(), minval=1 - max_delta, maxval=1 + max_delta)
return adjust_contrast(rgb_tuple, factor)
def _random_saturation(rgb_tuple, rng, max_delta):
h, s, v = rgb_to_hsv(*rgb_tuple)
factor = jax.random.uniform(
rng, shape=(), minval=1 - max_delta, maxval=1 + max_delta)
return hsv_to_rgb(*adjust_saturation(h, s, v, factor))
def _random_hue(rgb_tuple, rng, max_delta):
h, s, v = rgb_to_hsv(*rgb_tuple)
delta = jax.random.uniform(rng, shape=(), minval=-max_delta, maxval=max_delta)
return hsv_to_rgb(*adjust_hue(h, s, v, delta))
def _to_grayscale(image):
rgb_weights = jnp.array([0.2989, 0.5870, 0.1140])
grayscale = jnp.tensordot(image, rgb_weights, axes=(-1, -1))[..., jnp.newaxis]
return jnp.tile(grayscale, (1, 1, 3)) # Back to 3 channels.
def _color_transform_single_image(image, rng, brightness, contrast, saturation,
hue, to_grayscale_prob, color_jitter_prob,
apply_prob, shuffle):
"""Applies color jittering to a single image."""
apply_rng, transform_rng = jax.random.split(rng)
perm_rng, b_rng, c_rng, s_rng, h_rng, cj_rng, gs_rng = jax.random.split(
transform_rng, 7)
# Whether the transform should be applied at all.
should_apply = jax.random.uniform(apply_rng, shape=()) <= apply_prob
# Whether to apply grayscale transform.
should_apply_gs = jax.random.uniform(gs_rng, shape=()) <= to_grayscale_prob
# Whether to apply color jittering.
should_apply_color = jax.random.uniform(cj_rng, shape=()) <= color_jitter_prob
# Decorator to conditionally apply fn based on an index.
def _make_cond(fn, idx):
def identity_fn(x, unused_rng, unused_param):
return x
def cond_fn(args, i):
def clip(args):
return jax.tree_map(lambda arg: jnp.clip(arg, 0., 1.), args)
out = jax.lax.cond(should_apply & should_apply_color & (i == idx), args,
lambda a: clip(fn(*a)), args,
lambda a: identity_fn(*a))
return jax.lax.stop_gradient(out)
return cond_fn
random_brightness_cond = _make_cond(_random_brightness, idx=0)
random_contrast_cond = _make_cond(_random_contrast, idx=1)
random_saturation_cond = _make_cond(_random_saturation, idx=2)
random_hue_cond = _make_cond(_random_hue, idx=3)
def _color_jitter(x):
rgb_tuple = tuple(jax.tree_map(jnp.squeeze, jnp.split(x, 3, axis=-1)))
if shuffle:
order = jax.random.permutation(perm_rng, jnp.arange(4, dtype=jnp.int32))
else:
order = range(4)
for idx in order:
if brightness > 0:
rgb_tuple = random_brightness_cond((rgb_tuple, b_rng, brightness), idx)
if contrast > 0:
rgb_tuple = random_contrast_cond((rgb_tuple, c_rng, contrast), idx)
if saturation > 0:
rgb_tuple = random_saturation_cond((rgb_tuple, s_rng, saturation), idx)
if hue > 0:
rgb_tuple = random_hue_cond((rgb_tuple, h_rng, hue), idx)
return jnp.stack(rgb_tuple, axis=-1)
out_apply = _color_jitter(image)
out_apply = jax.lax.cond(should_apply & should_apply_gs, out_apply,
_to_grayscale, out_apply, lambda x: x)
return jnp.clip(out_apply, 0., 1.)
def _random_flip_single_image(image, rng):
_, flip_rng = jax.random.split(rng)
should_flip_lr = jax.random.uniform(flip_rng, shape=()) <= 0.5
image = jax.lax.cond(should_flip_lr, image, jnp.fliplr, image, lambda x: x)
return image
def random_flip(images, rng):
rngs = jax.random.split(rng, images.shape[0])
return jax.vmap(_random_flip_single_image)(images, rngs)
def color_transform(images,
rng,
brightness=0.8,
contrast=0.8,
saturation=0.8,
hue=0.2,
color_jitter_prob=0.8,
to_grayscale_prob=0.2,
apply_prob=1.0,
shuffle=True):
"""Applies color jittering and/or grayscaling to a batch of images.
Args:
images: an NHWC tensor, with C=3.
rng: a single PRNGKey.
brightness: the range of jitter on brightness.
contrast: the range of jitter on contrast.
saturation: the range of jitter on saturation.
hue: the range of jitter on hue.
color_jitter_prob: the probability of applying color jittering.
to_grayscale_prob: the probability of converting the image to grayscale.
apply_prob: the probability of applying the transform to a batch element.
shuffle: whether to apply the transforms in a random order.
Returns:
A NHWC tensor of the transformed images.
"""
rngs = jax.random.split(rng, images.shape[0])
jitter_fn = functools.partial(
_color_transform_single_image,
brightness=brightness,
contrast=contrast,
saturation=saturation,
hue=hue,
color_jitter_prob=color_jitter_prob,
to_grayscale_prob=to_grayscale_prob,
apply_prob=apply_prob,
shuffle=shuffle)
return jax.vmap(jitter_fn)(images, rngs)
def gaussian_blur(images,
rng,
blur_divider=10.,
sigma_min=0.1,
sigma_max=2.0,
apply_prob=1.0):
"""Applies gaussian blur to a batch of images.
Args:
images: an NHWC tensor, with C=3.
rng: a single PRNGKey.
blur_divider: the blurring kernel will have size H / blur_divider.
sigma_min: the minimum value for sigma in the blurring kernel.
sigma_max: the maximum value for sigma in the blurring kernel.
apply_prob: the probability of applying the transform to a batch element.
Returns:
A NHWC tensor of the blurred images.
"""
rngs = jax.random.split(rng, images.shape[0])
kernel_size = images.shape[1] / blur_divider
blur_fn = functools.partial(
_random_gaussian_blur,
kernel_size=kernel_size,
padding='SAME',
sigma_min=sigma_min,
sigma_max=sigma_max,
apply_prob=apply_prob)
return jax.vmap(blur_fn)(images, rngs)
def _solarize_single_image(image, rng, threshold, apply_prob):
def _apply(image):
return jnp.where(image < threshold, image, 1. - image)
return _maybe_apply(_apply, image, rng, apply_prob)
def solarize(images, rng, threshold=0.5, apply_prob=1.0):
"""Applies solarization.
Args:
images: an NHWC tensor (with C=3).
rng: a single PRNGKey.
threshold: the solarization threshold.
apply_prob: the probability of applying the transform to a batch element.
Returns:
A NHWC tensor of the transformed images.
"""
rngs = jax.random.split(rng, images.shape[0])
solarize_fn = functools.partial(
_solarize_single_image, threshold=threshold, apply_prob=apply_prob)
return jax.vmap(solarize_fn)(images, rngs)
| semppl-main | utils/augmentations.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.
# ==============================================================================
"""Learning rate schedules.
The code in this file is taken from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
import jax.numpy as jnp
def target_ema(global_step: jnp.ndarray, base_ema: float,
max_steps: int) -> jnp.ndarray:
decay = _cosine_decay(global_step, max_steps, 1.)
return 1. - (1. - base_ema) * decay
def learning_schedule(global_step: jnp.ndarray, batch_size: int,
base_learning_rate: float, total_steps: int,
warmup_steps: int) -> float:
"""Cosine learning rate scheduler."""
# Compute LR & Scaled LR
scaled_lr = base_learning_rate * batch_size / 256.
learning_rate = (
global_step.astype(jnp.float32) / int(warmup_steps) *
scaled_lr if warmup_steps > 0 else scaled_lr)
# Cosine schedule after warmup.
return jnp.where(
global_step < warmup_steps, learning_rate,
_cosine_decay(global_step - warmup_steps, total_steps - warmup_steps,
scaled_lr))
def _cosine_decay(global_step: jnp.ndarray, max_steps: int,
initial_value: float) -> jnp.ndarray:
"""Simple implementation of cosine decay from TF1."""
global_step = jnp.minimum(global_step, max_steps)
cosine_decay_value = 0.5 * (1 + jnp.cos(jnp.pi * global_step / max_steps))
decayed_learning_rate = initial_value * cosine_decay_value
return decayed_learning_rate
| semppl-main | utils/schedules.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.
# ==============================================================================
"""Checkpoint saving and restoring utilities.
The code in this file is taken from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
import os
import time
from typing import Mapping, Text, Tuple, Union
from absl import logging
import dill
import jax
import jax.numpy as jnp
from semppl.utils import helpers
class Checkpointer:
"""A checkpoint saving and loading class."""
def __init__(self, use_checkpointing: bool, checkpoint_dir: Text,
save_checkpoint_interval: int, filename: Text):
if (not use_checkpointing or checkpoint_dir is None or
save_checkpoint_interval <= 0):
self._checkpoint_enabled = False
return
self._checkpoint_enabled = True
self._checkpoint_dir = checkpoint_dir
os.makedirs(self._checkpoint_dir, exist_ok=True)
self._filename = filename
self._checkpoint_path = os.path.join(self._checkpoint_dir, filename)
self._last_checkpoint_time = 0
self._checkpoint_every = save_checkpoint_interval
def maybe_save_checkpoint(self, experiment_state: Mapping[Text, jnp.ndarray],
step: int, rng: jnp.ndarray, is_final: bool):
"""Saves a checkpoint if enough time has passed since the previous one."""
current_time = time.time()
if (not self._checkpoint_enabled or
jax.host_id() != 0 or # Only checkpoint the first worker.
(not is_final and
current_time - self._last_checkpoint_time < self._checkpoint_every)):
return
checkpoint_data = dict(
experiment_state=jax.tree_map(lambda x: jax.device_get(x[0]),
experiment_state),
step=step,
rng=rng)
with open(self._checkpoint_path + '_tmp', 'wb') as checkpoint_file:
dill.dump(checkpoint_data, checkpoint_file, protocol=2)
try:
os.rename(self._checkpoint_path, self._checkpoint_path + '_old')
remove_old = True
except FileNotFoundError:
remove_old = False # No previous checkpoint to remove
os.rename(self._checkpoint_path + '_tmp', self._checkpoint_path)
if remove_old:
os.remove(self._checkpoint_path + '_old')
self._last_checkpoint_time = current_time
def maybe_load_checkpoint(
self) -> Union[Tuple[Mapping[Text, jnp.ndarray], int, jnp.ndarray], None]:
"""Loads a checkpoint if any is found."""
checkpoint_data = load_checkpoint(self._checkpoint_path)
if checkpoint_data is None:
logging.info('No existing checkpoint found at %s', self._checkpoint_path)
return None
step = checkpoint_data['step']
rng = checkpoint_data['rng']
experiment_state = jax.tree_map(helpers.bcast_local_devices,
checkpoint_data['experiment_state'])
del checkpoint_data
return experiment_state, step, rng
def load_checkpoint(checkpoint_path):
"""Function for loading pre-trained encoder checkpoint."""
logging.info('Loading checkpoint from %s', checkpoint_path)
try:
with open(checkpoint_path, 'rb') as checkpoint_file:
checkpoint_data = dill.load(checkpoint_file)
logging.info('Loading checkpoint from %s, saved at step %d',
checkpoint_path, checkpoint_data['step'])
return checkpoint_data
except FileNotFoundError:
return None
| semppl-main | utils/checkpointing.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.
# ==============================================================================
"""Eval experiment configuration."""
| semppl-main | configs/__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.
# ==============================================================================
"""Config file for evaluation experiment.
The code in this file is adapted from the BYOL code
(https://github.com/deepmind/deepmind-research/tree/master/byol).
"""
from typing import Text
from semppl.utils import dataset
def get_config(checkpoint_to_evaluate: Text, batch_size: int, num_epochs: int):
"""Return config object for training."""
train_images_per_epoch = dataset.Split.TRAIN_AND_VALID.num_examples
config = dict(
random_seed=0,
enable_double_transpose=True,
max_steps=num_epochs * train_images_per_epoch // batch_size,
num_classes=1000,
batch_size=batch_size,
checkpoint_to_evaluate=checkpoint_to_evaluate,
# If True, allows training without loading a checkpoint.
allow_train_from_scratch=False,
# Whether the backbone should be frozen (linear evaluation) or
# trainable (fine-tuning).
freeze_backbone=True,
optimizer_config=dict(
momentum=0.9,
nesterov=True,
),
lr_schedule_config=dict(
base_learning_rate=0.3,
warmup_steps=0,
),
network_config=dict( # Should match the evaluated checkpoint
encoder_class='ResNet50', # Should match a class in utils/networks.
encoder_config=dict(resnet_v2=False, width_multiplier=1),
bn_decay_rate=0.9,
),
evaluation_config=dict(
subset='test',
batch_size=100,
),
checkpointing_config=dict(
use_checkpointing=True,
checkpoint_dir='/tmp/semppl',
save_checkpoint_interval=300,
filename='linear-eval.pkl'),
)
return config
| semppl-main | configs/eval.py |
# Copyright 2018 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.
# ============================================================================
"""Setup for pip package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['absl-py', 'numpy', 'dm-sonnet', 'six']
EXTRA_PACKAGES = {
'tensorflow': ['tensorflow>=1.15.0', 'tensorflow-probability>=0.4.0'],
'tensorflow with gpu': ['tensorflow-gpu>=1.8.0',
'tensorflow-probability-gpu>=0.4.0'],
}
setup(
name='lamb',
version='1.0',
description=('LAnguage Modelling Benchmarks is '
'to tune and test Tensorflow LM models.'),
long_description='',
url='http://github.com/deepmind/lamb/',
author='Gabor Melis',
author_email='[email protected]',
# Contained modules and scripts.
packages=find_packages(),
install_requires=REQUIRED_PACKAGES,
extras_require=EXTRA_PACKAGES,
zip_safe=False,
license='Apache 2.0',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: Unix',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Software Development :: Libraries',
],
keywords='lamb tensorflow language modelling machine learning',
)
| lamb-master | setup.py |
# Copyright 2018 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 and command-line flags.
The configuration is currently a flat namespace mapping options to values.
Typically the experiment shell scripts set these options and they are passed to
python as command-line arguments. See README.md for documentation of
configuration options.
"""
# pylint: disable=g-importing-member
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from copy import copy
import math
from absl import flags
from absl import logging
import six
import tensorflow.compat.v1 as tf
from google.protobuf import text_format
from tensorflow.contrib import training as contrib_training
from tensorflow.contrib.training.python.training import hparam_pb2
# Bump this on incompatible changes such as renaming an option and update
# maybe_upgrade_args_line below.
_config_version = 5
# The format of options is `(name, type, default_value, visibility)`.
# `visibility` is optional and can be `deprecated`, `external` or `internal`.
def option_visibility(option):
if len(option) == 4:
return option[3]
else:
return None
# There will be a command-line flag for every option except those with
# `internal` visibility. Conversely, in the Config object, `external` and
# `deprecated` are not going to be present. String like 'data' are turned into
# python comments when options are saved/printed.
_config_options = [
('config_version', 'integer', _config_version),
'data',
('training_file', 'string', ''),
('validation_file', 'string', ''),
('test_file', 'string', ''),
('conditioning_separator', 'string', ''),
('file_encoding', 'string', 'utf-8'),
('word_based', 'boolean', False),
('episodic', 'boolean', False),
'model',
('num_params', 'integer', -1),
('share_input_and_output_embeddings', 'boolean', False),
('input_embedding_size', 'integer', -1),
('output_embedding_size', 'integer', -1),
('input_embedding_ratio', 'float', 1.0),
('output_embedding_ratio', 'float', -1.0),
('mos_num_components', 'integer', 0),
('token_dropout', 'float', 0.0),
('embedding_dropout', 'float', 0.0),
('input_dropout', 'float', 0.0),
('output_dropout', 'float', 0.0),
('downprojected_output_dropout', 'float', -1.0),
('shared_mask_dropout', 'boolean', False),
# Whether to embed 'globally' or per time step. They are
# equivalent, but may differ in performance.
('embed_once', 'boolean', True),
('output_once', 'boolean', True),
'cell',
('model', 'string', 'lstm'),
('num_layers', 'integer', 1),
('residual_connections', 'boolean', False),
('lstm_skip_connection', 'boolean', True),
('feature_mask_rounds', 'integer', 0),
('feature_mask_rank', 'integer', 0),
# Deprecated. This is here to be able to load old configs. True sets
# feature_mask_rounds to 2 and feature_mask_rank to 0.
('feature_mask', 'boolean', False),
# If in [0,1) then within the recurrent cell in every dense
# connectivity matrix of N elements, randomly chosen elements
# are fixed to 0 such that the total number of trainable,
# non-fixed values is N*sparsity_ratio. Values outside [0,1) are
# treated as 1.0 (i.e. no sparsity),.
('sparsity_ratio', 'float', -1.0),
# TODO(melisgl): Document it once it's actually used.
('overlay_rank', 'integer', -1),
('hidden_size', 'list_of_ints', '-1'),
('hidden_size_multiplier', 'float', 1.0),
('layer_norm', 'boolean', False),
('activation_fn', 'string', 'tf.tanh'),
('tie_forget_and_input_gates', 'boolean', False),
('cap_input_gate', 'boolean', True),
('trainable_initial_state', 'boolean', True),
('inter_layer_dropout', 'float', 0.0),
('state_dropout', 'float', 0.0),
# This allows gradual change in the dropout mask. It's kind of in between
# shared and non-shared masks.
('state_dropout_flip_rate', 'float', 0.0),
('update_dropout', 'float', 0.0),
('cell_clip', 'float', -1.0),
'objective',
('model_average', 'string', 'arithmetic'),
('num_training_samples', 'integer', 1),
('l2_penalty', 'float', 0.0),
('l1_penalty', 'float', 0.0),
('activation_norm_penalty', 'float', 0.0),
('drop_state_probability', 'float', 0.0),
'initialization',
('embedding_init_factor', 'float', 1.0),
('scale_input_embeddings', 'boolean', False),
('cell_init_factor', 'float', 1.0),
('forget_bias', 'float', 1.0),
('output_init_factor', 'float', 1.0),
'schedule',
('steps_per_turn', 'integer', 1000),
('print_training_stats_every_num_steps', 'integer', 1000),
('turns', 'integer', -1),
'optimization',
('optimizer_type', 'string', 'rmsprop'),
('rmsprop_beta2', 'float', 0.999),
('rmsprop_epsilon', 'float', 1e-8),
('adam_beta1', 'float', 0.9),
('adam_beta2', 'float', 0.999),
('adam_epsilon', 'float', 1e-8),
('batch_size', 'integer', -1),
('accum_batch_size', 'integer', -1),
('max_grad_norm', 'float', 1.0),
('max_time_steps', 'integer', 100),
('trigger_averaging_turns', 'integer', -1),
('trigger_averaging_at_the_latest', 'integer', -1),
'learning rate',
('learning_rate', 'float', 0.001),
# TODO(melisgl): Learning rate decay is currently unimplemented.
#
# After each optimization step beyond learning_rate_decay_burn_in_steps the
# effective learning rate is multiplied by learning_rate_decay so that it's
# equal to learning_rate * pow(decay, max(0, global_step - burn_in_steps)).
# Also see drop_learning_rate_turns.
('learning_rate_decay', 'float', 1.0),
('learning_rate_decay_burn_in_steps', 'integer', 0),
('drop_learning_rate_turns', 'integer', -1),
('drop_learning_rate_multiplier', 'float', 1.0),
('drop_learning_rate_at_the_latest', 'integer', -1),
'early stopping',
('early_stopping_turns', 'integer', -1),
('early_stopping_rampup_turns', 'integer', 0),
('early_stopping_worst_xe_target', 'string', ''),
('early_stopping_slowest_rate', 'float', 0.0),
'cross-validation',
('crossvalidate', 'boolean', False),
('crossvalidation_folds', 'integer', 10),
('crossvalidation_rounds', 'integer', 1),
'evaluation',
('max_training_eval_batches', 'integer', 100),
('max_eval_eval_batches', 'integer', -1),
('max_test_eval_batches', 'integer', -1),
('min_non_episodic_eval_examples_per_stripe', 'integer', 100),
('eval_on_test', 'boolean', False),
('eval_method', 'string', 'deterministic'),
('num_eval_samples', 'integer', 0),
('eval_softmax_temperature', 'float', 1.0),
('eval_softmax_temperature_estimation_num_tokens', 'integer', 50000),
('eval_power_mean_power', 'float', 1.0),
('eval_dropout_multiplier', 'float', 1.0),
('validation_prediction_file', 'string', ''),
('dyneval', 'boolean', False),
('dyneval_learning_rate', 'float', 0.001),
('dyneval_decay_rate', 'float', 0.02),
('dyneval_epsilon', 'float', 1e-5),
'experiments',
('experiment_dir', 'string', '/tmp/lamb'),
('save_config', 'boolean', True, 'external'),
('config_file', 'string', '', 'external'),
# Some parameters used to be specified like
# `--hps=model=lstm,hidden_size=500`, a comma-separated list of assignments.
('hps', 'string', '', 'deprecated'),
# These used to be saved in a sepearate file.
('hps_proto_file', 'string', '', 'deprecated'),
# The old name for config_file.
('flags_as_dict', 'string', '', 'deprecated'),
'checkpoints',
('save_checkpoints', 'boolean', True),
('load_checkpoint', 'string', '', 'external'),
('load_optimizer_state', 'boolean', True, 'external'),
('load_averaged', 'boolean', False, 'external'),
('use_old_linear_names', 'boolean', False, 'external'),
'misc',
('seed', 'integer', 1),
('swap_memory', 'boolean', False),
('log_device_placement', 'boolean', False),
# currently unused
('summary_flush_secs', 'integer', 120)
]
FLAGS = flags.FLAGS
def _filter_options(options):
return [option for option in options
if not isinstance(option, six.string_types)]
def _define_flags(options):
for option in _filter_options(options):
name, type_, default_ = option[:3]
if type_ == 'boolean':
flags.DEFINE_boolean(name, default_, '')
elif type_ == 'integer':
flags.DEFINE_integer(name, default_, '')
elif type_ == 'float':
flags.DEFINE_float(name, default_, '')
elif type_ == 'string':
flags.DEFINE_string(name, default_, '')
elif type_ == 'list_of_ints':
flags.DEFINE_string(name, default_, '')
else:
assert 'Unexpected option type %s' % type_
# Define command-line flags for all options (unless `internal`).
_define_flags(_config_options)
_is_initialized = [False]
def initialize():
"""Override flags from FLAGS.config_file and handle old formats.
Unless they were explicitly provided on the command line.
"""
if not _is_initialized[0]:
assert not (FLAGS.config_file and FLAGS.flags_as_dict), (
'Both config_file and flags_as_dict were specified.')
# The deprecated --flags_as_dict used to save some command-line flags as a
# dict.
if FLAGS.flags_as_dict:
logging.info('Handling --flags_as_dict %s', FLAGS.flags_as_dict)
with tf.gfile.GFile(FLAGS.flags_as_dict, 'r') as f:
# This contains a single dict.
args_dict = eval(f.read()) # pylint: disable=eval-used
if FLAGS.config_file:
logging.info('Handling --config_file %s', FLAGS.config_file)
with tf.gfile.GFile(FLAGS.config_file, 'r') as f:
# This contains a list of bindings.
args_dict = dict(eval(f.read())) # pylint: disable=eval-used
if FLAGS.config_file or FLAGS.flags_as_dict:
args_dict = _maybe_upgrade_args(args_dict)
# Update FLAGS with the upgraded values.
for name, value in args_dict.items():
if (name not in ['flags_version', 'config_version'] and
FLAGS[name].using_default_value):
logging.info('override FLAGS.%s = %r', name, value)
FLAGS[name].value = value
_handle_hps()
_handle_hps_proto_file()
# Turn off trainable_initial_state for non-episodic mode.
if not FLAGS.episodic:
FLAGS.trainable_initial_state = False
_is_initialized[0] = True
# args_dict comes from either --flags_as_dict or --config_file, either of which
# may be saved using an old format.
def _maybe_upgrade_args(args_dict):
version = args_dict.get('config_version', 1)
if version < _config_version:
logging.info('config file version was %s. Upgrading to %s',
version, _config_version)
if version < 2:
args_dict['validation_file'] = args_dict.pop('eval_file')
args_dict['max_time_steps'] = args_dict.pop('max_steps')
args_dict['steps_per_turn'] = args_dict.pop('steps')
args_dict['early_stopping_turns'] = args_dict.pop(
'early_stopping_rounds')
args_dict['early_stopping_rampup_turns'] = args_dict.pop(
'early_stopping_rampup_rounds')
args_dict['print_training_stats_every_num_steps'] = args_dict.pop(
'print_every')
if 'averaged_trigger_turns' in args_dict:
args_dict['trigger_averaging_turns'] = args_dict.pop(
'averaged_trigger_turns')
if 'mixture_of_softmaxes_num_components' in args_dict:
mos_num = args_dict.pop('mixture_of_softmaxes_num_components')
if mos_num == 1:
mos_num = 0
args_dict['mos_num_components'] = mos_num
if version < 5 and 'hidden_size' in args_dict:
# FLAGS.hidden_size used to be an int, now it's a string.
args_dict['hidden_size'] = str(args_dict['hidden_size'])
else:
assert version == _config_version, (
'Unexpected config format version {}'.format(version))
return args_dict
# No more versions changes, since the corresponding --hps_proto_file is for
# backwards compatibility only.
_hparams_version = 2
_v2_hparam_renames = {
'intra_layer_dropout': 'inter_layer_dropout',
'softmax_test_time_temperature': 'eval_softmax_temperature',
'test_time_power_mean_power': 'eval_power_mean_power',
'test_time_dropout_multiplier': 'eval_dropout_multiplier',
'weight_decay': 'l2_penalty',
'weight_penalty': 'l1_penalty',
'outer_steps': 'turns',
'drop_learning_rate_rounds': 'drop_learning_rate_turns',
'vocab_size': None
}
# Some options used to be specified like `--hps=model=lstm,hidden_size=500`, a
# comma-separated list of assignments. Now, any option can be given via the
# deprecated --hps option.
#
# Error handling is weak, but this is for v1 compatibility only, so that's ok.
def _handle_hps():
assignments = FLAGS.hps.split(',')
for assignment in assignments:
if assignment:
name, value = assignment.split('=')
name = _v2_hparam_renames.get(name, name)
if name and value:
FLAGS[name].parse(value)
logging.info('hps: FLAGS.%s = %r', name, FLAGS[name].value)
# There used to be two files in which options were saved. Now there is only one,
# but we must support old saves.
def _handle_hps_proto_file():
if FLAGS.hps_proto_file:
hparams_proto = hparam_pb2.HParamDef()
with tf.gfile.GFile(FLAGS.hps_proto_file) as f:
text_format.Parse(f.read(), hparams_proto)
hparams = contrib_training.HParams.from_proto(hparams_proto)
hparams = _maybe_upgrade_hparams(hparams)
for name, value in hparams.values().items():
if FLAGS[name].using_default_value:
logging.info('hps_proto FLAGS.%s = %r', name, value)
FLAGS[name].value = value
def _maybe_upgrade_hparams(hparams):
version = hparams.get('hparams_version', 1)
if version < _hparams_version:
logging.info('hps_proto_file version was %s. Upgrading to %s.',
version, _hparams_version)
def rename(old, new):
# No assignment, delete and readd with new value.
old_value = hparams.get(old)
if new and old_value is not None:
hparams.add_hparam(new, old_value)
hparams.del_hparam(old)
if version == 1:
for old_name, new_name in _v2_hparam_renames.items():
rename(old_name, new_name)
if hparams.get('mixture_of_softmaxes_num_components', None):
rename('mixture_of_softmaxes_num_components', 'mos_num_components')
if hparams.mos_num_components == 1:
hparams.mos_num_components = 0
if hparams.get('hidden_size', None):
value = str(hparams.get('hidden_size'))
hparams.del_hparam('hidden_size')
hparams.add_hparam('hidden_size', value)
else:
assert version == _hparams_version, (
'Unknown hps_proto_file format version {}'.format(version))
return hparams
# At startup the command-line flags are packaged into a Config object. Some code
# has been refactored to work with Config objects, some code still uses the
# command line arguments directly (as FLAGS.*). In general, we want to minimize
# dependency on FLAGS, and also on Config. Thus relevant parts of Config should
# be extracted and passed as arguments as early as possible.
class Config(object):
"""Flat, mutable configuration with dot notation."""
def __init__(self, options=()):
self._options = options
self._values = {}
def _find_option(self, name):
for option in _filter_options(self._options):
if option[0] == name:
return option
def __getattr__(self, name):
if name in ['_options', '_values', '_find_option']:
return super(Config, self).__getattribute__(name)
elif name in self._values:
return self._values[name]
else:
# Lookup the default value.
option = self._find_option(name)
if option is None:
return super(Config, self).__getattribute__(name)
# raise AttributeError('No config option named {}.'.format(name))
else:
return option[2]
def __setattr__(self, name, value):
if name in ['_options', '_values', '_find_option']:
super(Config, self).__setattr__(name, value)
elif self._find_option(name):
self._values[name] = value
else:
# Add an internal value that doesn't get saved.
self._options.append((name, 'unknown_type', None, 'internal'))
self._values[name] = value
def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
setattr(self, name, value)
def __contains__(self, name):
return name in self._values
def get(self, name, default):
if name in self:
return self[name]
else:
return default
def __iter__(self):
for option in _filter_options(self._options):
yield option[0]
def __copy__(self):
config = self.__class__(copy(self._options))
config._values = copy(self._values) # pylint: disable=protected-access
return config
def __str__(self):
s = ''
for option in self._options:
if s:
indent = ' '
else:
indent = ' '
if isinstance(option, six.string_types):
s += indent + '# ' + option + '\n'
elif option_visibility(option) != 'internal':
name = option[0]
value = self.__getattr__(name)
s += indent + str((name, value)) + ',\n'
return '[' + s + ']'
def save(self, filename):
with tf.gfile.GFile(filename, 'w') as f:
f.write(str(self))
def get_config():
"""Return the config in effect.
Returns:
A Config containing all the config options (except deprecated or external,
see _config_options) with values set from command-line arguments.
"""
options = [option for option in _config_options
if (isinstance(option, six.string_types) or
option_visibility(option) not in ['deprecated', 'external'])]
config = Config(options)
# Update the config with the flag values.
for option in _filter_options(options):
if option_visibility(option) not in ['deprecated', 'external', 'internal']:
name = option[0]
if option[1] == 'list_of_ints':
if isinstance(FLAGS[name].value, list):
value = [int(x) for x in FLAGS[name].value]
else:
value = [int(x) for x in FLAGS[name].value.split(',')]
else:
value = FLAGS[name].value
config[name] = value
return config
def handle_config_defaults(config, num_params_fn):
"""Resolve dependencies within `config`.
In particular, set hidden_size (if -1) according to num_params and make the
embedding sizes default to the hidden size. Also, handle budgeting: if
hidden_size is not provided (it is -1), but num_params is, then compute the
largest possible hidden_size with which the total number of trainable
parameters does not exceed num_params.
Args:
config: The base config. Must have num_params set.
num_params_fn: A function of one argument a config object. The config passed
to it is constructed by setting the hidden_size and performing the usual
defaulting.
Returns:
The mutated config.
"""
# TODO(melisgl): Move this to the tuner code.
# For ease of specification, tuning ranges are weird. Let's fix them up here.
if config.sparsity_ratio >= 1.0:
config.sparsity_ratio = -1.0
if config.input_embedding_ratio >= 1.0:
config.input_embedding_ratio = 1.0
if config.output_embedding_ratio >= 1.0:
config.output_embedding_ratio = 1.0
if config.output_embedding_ratio < 0.0:
config.output_embedding_ratio = config.input_embedding_ratio
if config.learning_rate_decay > 1.0:
config.learning_rate_decay = 1.0
if config.feature_mask_rank < 0:
config.feature_mask_rank = 0
if config.inter_layer_dropout < 0.0:
config.inter_layer_dropout = config.input_dropout
if config.downprojected_output_dropout < 0.0:
config.downprojected_output_dropout = config.output_dropout
# Handle deprecated feature_mask flag.
if config.feature_mask:
config.feature_mask_rounds = 2
config.feature_mask_rank = 0
# Handle the num_param budget.
if config.hidden_size in [-1, [-1]]:
assert config.num_params > -1, (
'Neither hidden_size nor num_params is specified.')
config.hidden_size = [_budget_hidden_size(config, num_params_fn)]
config = _handle_hidden_size_defaults(config)
# Perform some sanity checks.
if config.output_embedding_size > config.hidden_size[-1]:
logging.warn('output_embedding_size %s is greater than '
'the hidden size %s', config.output_embedding_size,
config.hidden_size[-1])
if config.share_input_and_output_embeddings:
assert config.input_embedding_size == config.output_embedding_size
return config
def _budget_hidden_size(config, num_params_fn):
"""Finds the largest possible hidden size that respects config.num_params.
Args:
config: A Config. Must have num_params set.
num_params_fn: A function of one argument a config object. The config passed
to it is constructed by setting the hidden_size and performing the usual
defaulting.
Returns:
The largest possible hidden size with which the total number of
trainable parameters does not exceed config.num_params. Respects
defaulting rules such as input_embedding_ratio.
"""
logging.info(
'Searching for largest possible hidden_size subject to num_params<=%s',
config.num_params)
assert config.num_params > 0
def config_with_hidden_size(hidden_size):
updated_config = copy(config)
updated_config.hidden_size = [hidden_size]
return _handle_hidden_size_defaults(updated_config)
def is_good(hidden_size):
n = num_params_fn(config_with_hidden_size(hidden_size))
good = (n <= config.num_params)
if n is None:
logging.info('hidden_size=%s, num_params=OOM BAD', hidden_size)
elif good:
logging.info('hidden_size=%s, num_params=%s GOOD', hidden_size, n)
else:
logging.info('hidden_size=%s, num_params=%s BAD', hidden_size, n)
return good, n
# Double the size until it's too large.
previous_hidden_size = 1
hidden_size = 1
good, n = is_good(hidden_size)
while good:
previous_hidden_size = hidden_size
hidden_size = max(hidden_size+1,
int(hidden_size*math.sqrt(1.2*config.num_params / n)))
good, n = is_good(hidden_size)
# Bisect the [previous_hidden_size, hidden_size] range.
def bisect(lower, upper, fn): # pylint: disable=missing-docstring
while lower < upper-1:
# The number of parameters is likely to be at least quadratic in
# hidden_size. Find the middle point in log space.
middle = int(math.exp((math.log(upper) + math.log(lower)) / 2))
middle = min(max(middle, lower+1), upper-1)
if fn(middle)[0]:
lower = middle
else:
upper = middle
return lower
return bisect(previous_hidden_size, hidden_size, is_good)
def _handle_hidden_size_defaults(config):
"""Handle default that depend on hidden_size."""
last_hidden_size = config.hidden_size[-1]
for i in six.moves.range(config.num_layers-len(config.hidden_size)):
config.hidden_size.append(
max(1, int(last_hidden_size * pow(config.hidden_size_multiplier, i+1))))
# Now set the actual embedding size if necessary.
last_hidden_size = config.hidden_size[-1]
if config.input_embedding_size == -1:
config.input_embedding_size = max(1, round_to_int(
config.input_embedding_ratio*last_hidden_size))
if config.output_embedding_size == -1:
config.output_embedding_size = max(1, round_to_int(
config.output_embedding_ratio*last_hidden_size))
return config
def round_to_int(x):
return int(round(x))
def flags_as_dict():
"""Return flags that were explicitly provided."""
dict_ = {}
for option in _filter_options(_config_options):
name = option[0]
if not FLAGS[name].using_default_value:
dict_[name] = FLAGS[name].value
return dict_
| lamb-master | lamb/lamb_flags.py |
# Copyright 2018 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A RNN cell with skip connections."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tensorflow.contrib import framework as contrib_framework
nest = contrib_framework.nest
class SkipMultiRNNCell(tf.nn.rnn_cell.RNNCell):
"""RNN cell composed sequentially of multiple simple cells."""
def __init__(self, cells, state_is_tuple=True):
"""Create a RNN cell composed sequentially of a number of RNNCells.
Args:
cells: list of RNNCells that will be composed in this order.
state_is_tuple: If True, accepted and returned states are n-tuples, where
`n = len(cells)`. If False, the states are all
concatenated along the column axis. This latter behavior will soon be
deprecated.
Raises:
ValueError: if cells is empty (not allowed), or at least one of the cells
returns a state tuple but the flag `state_is_tuple` is `False`.
"""
if not cells:
raise ValueError("Must specify at least one cell for SkipMultiRNNCell.")
if not nest.is_sequence(cells):
raise TypeError(
"cells must be a list or tuple, but saw: %s." % cells)
self._cells = cells
self._state_is_tuple = state_is_tuple
if not state_is_tuple:
if any(nest.is_sequence(c.state_size) for c in self._cells):
raise ValueError("Some cells return tuples of states, but the flag "
"state_is_tuple is not set. State sizes are: %s"
% str([c.state_size for c in self._cells]))
@property
def state_size(self):
if self._state_is_tuple:
return tuple(cell.state_size for cell in self._cells)
else:
return sum([cell.state_size for cell in self._cells])
@property
def output_size(self):
return self._cells[-1].output_size
def __call__(self, inputs, state, scope=None):
"""Run this multi-layer cell on inputs, starting from state."""
output = None
with tf.variable_scope(scope or "skip_multi_rnn_cell"):
cur_state_pos = 0
cur_inp = inputs
new_states = []
for i, cell in enumerate(self._cells):
with tf.variable_scope("cell_%d" % i):
if self._state_is_tuple:
if not nest.is_sequence(state):
raise ValueError(
"Expected state to be a tuple of length %d, but received: %s"
% (len(self.state_size), state))
cur_state = state[i]
else:
cur_state = tf.slice(
state, [0, cur_state_pos], [-1, cell.state_size])
cur_state_pos += cell.state_size
cur_inp, new_state = cell(cur_inp, cur_state)
new_states.append(new_state)
if output is None:
output = cur_inp
else:
output += cur_inp
new_states = (tuple(new_states) if self._state_is_tuple else
tf.concat(new_states, 1))
return output, new_states
| lamb-master | lamb/skip_multi_rnn_cell.py |
# Copyright 2018 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.
# ============================================================================
"""Averaging of model weights."""
# pylint: disable=missing-docstring
# pylint: disable=g-complex-comprehension
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
class Averaged(object):
def __init__(self, tensors):
tensors = list(tensors)
with tf.variable_scope('averaged'):
self._num_samples = tf.Variable(0, name='num_samples', trainable=False)
with tf.variable_scope('avg'):
self._averages = [
tf.get_variable(
tensor.name.replace('/', '-').replace(':', '-'),
tensor.get_shape(), initializer=tf.zeros_initializer(),
trainable=False)
for tensor in tensors]
with tf.variable_scope('save'):
self._saves = [
tf.get_variable(
tensor.name.replace('/', '-').replace(':', '-'),
tensor.get_shape(), initializer=tf.zeros_initializer(),
trainable=False)
for tensor in tensors]
self._tensors = tensors
self._take_sample = self._make_take_sample()
self._switch = self._make_swith_to_average()
self._restore = self._make_restore()
self._reset = self._make_reset()
def take_sample(self):
tf.get_default_session().run(self._take_sample)
def switch_to_average(self):
tf.get_default_session().run(self._switch)
def restore(self):
tf.get_default_session().run(self._restore)
def reset(self):
tf.get_default_session().run(self._reset)
def __enter__(self):
self.switch_to_average()
def __exit__(self, type_, value, traceback):
self.restore()
def _make_take_sample(self):
assignments = []
n = tf.cast(self._num_samples, tf.float32)
mu = 1.0 / (1.0 + n)
for tensor, average in zip(self._tensors, self._averages):
assignments.append(tf.assign_add(average, (tensor-average)*mu))
add_to_averages = tf.group(assignments)
with tf.control_dependencies([add_to_averages]):
incr_num_samples = tf.assign(self._num_samples, self._num_samples + 1)
return incr_num_samples
def _make_swith_to_average(self):
assignments = []
for save, tensor, average in zip(
self._saves, self._tensors, self._averages):
with tf.control_dependencies([save.assign(tensor)]):
assignments.append(tensor.assign(average))
return tf.group(assignments)
def _make_restore(self):
assignments = []
for save, tensor in zip(self._saves, self._tensors):
assignments.append(tf.assign(tensor, save))
return tf.group(assignments)
def _make_reset(self):
return tf.assign(self._num_samples, 0)
# TODO(melisgl): I think this works with ResourceVariables but not with normal
# Variables. Deferred until TF2.0.
def _swap(x, y):
x_value = x.read_value()
y_value = y.read_value()
with tf.control_dependencies([x_value, y_value]):
swap = tf.group(y.assign(x_value), x.assign(y_value))
return swap
| lamb-master | lamb/averaged.py |
# Copyright 2018 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.
# ============================================================================
"""Vocabulary."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import range
class Vocab(object):
"""Immutable reversible mappings from strings to integers."""
def __init__(self, tokens, unk=u'<UNK>', eos=u'\u25bc'):
"""Create a Vocab object that maps `tokens` to dense indices."""
self._token_to_index = {}
self._token_to_frequency = {}
self._unk = unk
self._eos = eos
token_to_index = self._token_to_index
token_to_frequency = self._token_to_frequency
# Get the unique tokens from `tokens` that might be a generator.
for token in tokens:
token_to_index[token] = True
token_to_frequency[token] = token_to_frequency.get(token, 0) + 1
token_to_index[unk] = True
token_to_index[eos] = True
# Now that we have a smaller set of tokens, assign ids in sorted
# order for deterministic encoding.
self._index_to_token = [None] * len(token_to_index)
index_to_token = self._index_to_token
i = 0
for token in sorted(list(token_to_index)):
token_to_index[token] = i
index_to_token[i] = token
i += 1
def unk_index(self):
"""Returns the index of the unknown token."""
return self._token_to_index[self._unk]
def eos_index(self):
"""Returns the index of the end-of-sentence token."""
return self._token_to_index[self._eos]
def token(self, index_):
"""The string whose `index()` is `index_` or an IndexError."""
return self._index_to_token[index_]
def __iter__(self):
"""Iterates over tokens in order of indices."""
for i in range(self.size()):
yield self.token(i)
def index_or_unk(self, token):
"""Find the index assigned to `token`.
Args:
token: a string.
Returns:
The index of `token` or `unk_index()` if it is not in the vocabulary.
"""
if token in self._token_to_index:
return self._token_to_index[token]
else:
return self.unk_index()
def size(self):
"""Returns the number of different tokens in the vocabulary."""
return len(self._index_to_token)
def decode(self, ids):
"""Decode a sequence of `ids` with `token()`."""
assert all([0 <= x and x < len(self._index_to_token) for x in ids])
return [self.token(x) for x in ids]
def encode(self, tokens, add_eos=True):
"""Encodes a sentence into a list of token indices.
Args:
tokens: A list of tokens.
add_eos: Whether to add the end of sentence token.
Returns:
A list of integer token indices where `unk_index()` stands for
tokens not found in the vocabulary.
"""
ids = [self.index_or_unk(token) for token in tokens]
if add_eos:
ids += [self.eos_index()]
return ids
def index_frequency(self, index_):
return self._token_to_frequency.get(self.token(index_), 0)
| lamb-master | lamb/vocab.py |
# Copyright 2018 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A stacked RNN cell with residual connections."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tensorflow.contrib import framework as contrib_framework
nest = contrib_framework.nest
class ResMultiRNNCell(tf.nn.rnn_cell.RNNCell):
"""RNN cell composed sequentially of multiple simple cells."""
def __init__(self, cells, state_is_tuple=True):
"""Create a RNN cell composed sequentially of a number of RNNCells.
Args:
cells: list of RNNCells that will be composed in this order.
state_is_tuple: If True, accepted and returned states are n-tuples, where
`n = len(cells)`. If False, the states are all
concatenated along the column axis. This latter behavior will soon be
deprecated.
Raises:
ValueError: if cells is empty (not allowed), or at least one of the cells
returns a state tuple but the flag `state_is_tuple` is `False`.
"""
if not cells:
raise ValueError("Must specify at least one cell for ResMultiRNNCell.")
if not nest.is_sequence(cells):
raise TypeError(
"cells must be a list or tuple, but saw: %s." % cells)
self._cells = cells
self._state_is_tuple = state_is_tuple
if not state_is_tuple:
if any(nest.is_sequence(c.state_size) for c in self._cells):
raise ValueError("Some cells return tuples of states, but the flag "
"state_is_tuple is not set. State sizes are: %s"
% str([c.state_size for c in self._cells]))
@property
def state_size(self):
if self._state_is_tuple:
return tuple(cell.state_size for cell in self._cells)
else:
return sum([cell.state_size for cell in self._cells])
@property
def output_size(self):
return self._cells[-1].output_size
def __call__(self, inputs, state, scope=None):
"""Run this multi-layer cell on inputs, starting from state."""
with tf.variable_scope(scope or "res_multi_rnn_cell"):
cur_state_pos = 0
cur_inp = inputs
new_states = []
for i, cell in enumerate(self._cells):
with tf.variable_scope("cell_%d" % i):
if self._state_is_tuple:
if not nest.is_sequence(state):
raise ValueError(
"Expected state to be a tuple of length %d, but received: %s"
% (len(self.state_size), state))
cur_state = state[i]
else:
cur_state = tf.slice(
state, [0, cur_state_pos], [-1, cell.state_size])
cur_state_pos += cell.state_size
cur_inp2, new_state = cell(cur_inp, cur_state)
if i == 0:
cur_inp = cur_inp2
else:
cur_inp = cur_inp + cur_inp2
new_states.append(new_state)
new_states = (tuple(new_states) if self._state_is_tuple else
tf.concat(new_states, 1))
return cur_inp, new_states
| lamb-master | lamb/res_multi_rnn_cell.py |
# Copyright 2018 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""An RHN cell."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from lamb import tiled_linear
import six
import tensorflow.compat.v1 as tf
# The state of an RHN cell consists of:
#
# - `s`, the cell state (like TiledLSTMCellState.c)
_TiledRHNStateTuple = collections.namedtuple('TiledRHNStateTuple', ('s'))
class TiledRHNStateTuple(_TiledRHNStateTuple):
__slots__ = ()
@property
def dtype(self):
s, = self
return s.dtype
class TiledRHNCell(tf.nn.rnn_cell.RNNCell):
"""An RHN cell with tiled connections.
A RHN cell is like a simplified LSTM with multiple layers. See
'Recurrent Highway Networks' by Zilly et al.
(https://arxiv.org/abs/1607.03474). This implementation is based on
v3 of that paper.
Supports various connectivity patterns such as the vanilla, dense
TiledLinear, and also SparseTiledLinear, LayerNormedTiledLinear.
"""
def __init__(
self, num_units, depth=1,
use_peepholes=False, cell_clip=None,
initializer=None,
tie_gates=False,
activation=tf.tanh,
input_transform=None,
state_transform=None,
update_transform=None,
tiled_linear_class=None,
tiled_linear_var_init_params=None):
"""Initialize the parameters of a single RHN layer.
Args:
num_units: int, The number of hidden units in the layer.
depth: int, The number of layers.
use_peepholes: bool, set True to enable diagonal/peephole connections
(non implemented).
cell_clip: (optional) A float value, if provided the cell state
is clipped to be in the [-cell_clip, cell_clip] range prior to
the cell output activation.
initializer: (optional) The initializer to use for the weight and
projection matrices.
tie_gates: Whether to make the input gate one minus the forget gate.
activation: Activation function of the inner states.
input_transform: None, or a function of one argument that
massages the input in some way. For example, variational
dropout can be implemted by passing a Dropout object here.
state_transform: Similar to input_transform, this is
applied to the recurrent state.
update_transform: Similar to input_transform, this is
applied to the proposed update ('h').
tiled_linear_class: A class such as tiled_linear.TiledLinear
that's instantiated an unspecified number of times with the
same tiled_linear_var_init_params but with possibly different
inputs and outputs. Defaults to tiled_linear.TiledLinear.
tiled_linear_var_init_params: Passed right on to
`tiled_linear_class` as the `var_init_params` argument.
"""
assert not use_peepholes, 'Peepholes are not implemented in RHNCell.'
self._num_units = num_units
self._depth = depth
self._use_peepholes = use_peepholes
self._cell_clip = cell_clip
self._initializer = initializer
self._tie_gates = tie_gates
self._activation = activation
self._input_transform = input_transform
self._state_transform = state_transform
self._update_transform = update_transform
if tiled_linear_class is None:
tiled_linear_class = tiled_linear.TiledLinear
self._tiled_linear_class = tiled_linear_class
self._tiled_linear_var_init_params = tiled_linear_var_init_params
self._tiled_linear_mods = [None]*depth
self._output_size = num_units
self._state_size = TiledRHNStateTuple(num_units)
@property
def state_size(self):
return self._state_size
@property
def output_size(self):
return self._output_size
def __call__(self, input_, state, scope=None):
"""Run one step of RHN.
All tensor arguments are shaped [batch_size, *].
Args:
input_: A tensor.
state: An TiledRHNStateTuple.
scope: VariableScope for the created subgraph; defaults to
`TiledRHNCell`.
Returns:
A tuple containing:
- A `2-D, [batch, num_units]`, Tensor representing the output of
the RHN after one time step (which consists of `depth` number
of computational steps).
- An TiledRHNStateTuple tuple of Tensors representing the new state
of the RHN after one time step.
Raises:
ValueError: If input size cannot be inferred from `input_`
via static shape inference.
"""
num_units = self._num_units
def maybe_transform(transform, x):
if transform is None:
return x
else:
return transform(x)
# Apply transformations to the input and the recurrent state.
transformed_input = maybe_transform(self._input_transform, input_)
# Let's figure out what the outputs are.
output_name_and_sizes = [
# This is the proposed update (usually 'j' in an LSTM).
('h', num_units),
# Called 'carry' gate in the paper. This pretty much plays the
# part of the forget gate of an LSTM.
('c', num_units)]
if not self._tie_gates:
# Called 'transform' gate, this is like the input gate of an
# LSTM.
output_name_and_sizes.append(('t', num_units))
with tf.variable_scope(scope or type(self).__name__,
initializer=self._initializer):
s = state.s
for level in six.moves.range(self._depth):
with tf.variable_scope('layer{}'.format(level)):
transformed_s = maybe_transform(self._state_transform, s)
if level == 0:
inputs = [transformed_input, transformed_s]
input_name_and_sizes = [
('x', transformed_input.get_shape().with_rank(2)[1]),
# This is the raw cell state. Unlike in an LSTM this
# is not passed through any non-linearity.
('s', num_units)]
else:
inputs = [transformed_s]
input_name_and_sizes = [('s', num_units)]
if self._tiled_linear_mods[level] is None:
self._tiled_linear_mods[level] = self._tiled_linear_class(
input_name_and_sizes, output_name_and_sizes,
self._tiled_linear_var_init_params)
if self._tie_gates:
h_pre, c_pre = self._tiled_linear_mods[level](inputs)
else:
h_pre, c_pre, t_pre = self._tiled_linear_mods[level](inputs)
# Compute the cell state s.
c = tf.sigmoid(c_pre)
h = self._activation(h_pre)
h = maybe_transform(self._update_transform, h)
if self._tie_gates:
t = 1 - c
else:
t = tf.sigmoid(t_pre)
s = c * s + t * h
if self._cell_clip is not None:
# pylint: disable=invalid-unary-operand-type
s = tf.clip_by_value(s, -self._cell_clip, self._cell_clip)
# pylint: enable=invalid-unary-operand-type
return s, TiledRHNStateTuple(s)
| lamb-master | lamb/tiled_rhn.py |
# Copyright 2018 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.
# ============================================================================
"""RNN Cell builder."""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import math
from absl import logging
import six
import tensorflow.compat.v1 as tf
# pylint: disable=g-bad-import-order
from lamb import utils
from lamb import tiled_linear
from lamb.nascell import NASCell
from lamb.tiled_lstm import TiledLSTMCell
from lamb.tiled_rhn import TiledRHNCell
from lamb.res_multi_rnn_cell import ResMultiRNNCell
from lamb.skip_multi_rnn_cell import SkipMultiRNNCell
from lamb.dropout import DirichletDropout
from lamb.dropout import DriftingDropout
from lamb.dropout import Dropout
from lamb.dropout import GaussianDropout
from tensorflow.contrib import framework as contrib_framework
def build_cell(model, num_layers, hidden_size,
layer_norm, cell_init_factor,
shared_mask_dropout,
input_dropout, inter_layer_dropout, state_dropout,
update_dropout, state_dropout_flip_rate,
tie_forget_and_input_gates, cap_input_gate, forget_bias,
feature_mask_rounds, feature_mask_rank,
overlay_rank, sparsity_ratio,
cell_clip, activation_fn,
lstm_skip_connection, residual_connections):
cell_initializer = utils.variance_scaling_initializer(
scale=cell_init_factor, mode='fan_in', distribution='truncated_normal')
def hidden_size_for_layer(layer_index):
if isinstance(hidden_size, int):
return hidden_size
elif layer_index < len(hidden_size):
return hidden_size[layer_index]
else:
return hidden_size[-1]
def dropout(dropout_rate, share=shared_mask_dropout,
flip_prob=None, kind='bernoulli', scaler=1.0):
if dropout_rate is not None:
# The same graph is used for training and evaluation with different
# dropout rates. Passing the constant configured dropout rate here would
# be a subtle error.
assert contrib_framework.is_tensor(dropout_rate)
if flip_prob is not None:
assert kind == 'bernoulli'
return DriftingDropout(1-dropout_rate, flip_prob=flip_prob,
scaler=scaler)
elif kind == 'bernoulli':
return Dropout(1-dropout_rate, share_mask=share, scaler=scaler)
elif kind == 'dirichlet':
return DirichletDropout(1-dropout_rate, share_mask=share, scaler=scaler)
elif kind == 'gaussian':
return GaussianDropout(1-dropout_rate, share_mask=share, scaler=scaler)
else:
assert False
# We don't use DriftingDropout currently. Ignore it.
state_dropout_flip_rate = state_dropout_flip_rate
# Set up input_transforms for the layers based on
# {input,inter_layer}_dropout.
input_transforms = []
for layer_index in six.moves.range(num_layers):
if model in ['lstm', 'nas']:
if layer_index == 0:
transform = dropout(input_dropout)
elif layer_index > 0:
transform = dropout(inter_layer_dropout)
else:
transform = None
elif model == 'rhn':
if layer_index == 0:
transform = dropout(input_dropout)
else:
# The input is not fed to higher layers.
transform = None
else:
assert False
input_transforms.append(transform)
# Populate state_transforms to handle state_dropout. This is currently the
# same for LSTM and RHN: all layers have the same dropout mask, possibly
# with further sharing over time steps.
state_transforms = []
for layer_index in six.moves.range(num_layers):
transform = dropout(state_dropout, share=True)
state_transforms.append(transform)
# Populate update_transforms to handle update_dropout. This is currently the
# same for LSTM and RHN: all layers have their own dropout mask which may be
# shared between time steps.
update_transforms = []
if model == 'lstm' and (tie_forget_and_input_gates or cap_input_gate):
# The 1.5 is to reach a more non-linear part of the output tanh.
base_scale = 1.5
else:
base_scale = 1.0
for layer_index in six.moves.range(num_layers):
if update_dropout is None:
scaler = 1.0
else:
scaler = base_scale*(1-update_dropout)
update_transforms.append(dropout(
update_dropout,
# Dropout mask for the recurrent state needs to be the
# same for all time steps.
share=True,
# This makes update dropout do mask*x at training time and
# x*(1-r) at test time instead of usual mask*x/(1-r) and
# x, respectively.
scaler=scaler))
def make_lstm_column():
init_params = collections.OrderedDict([
('B_f', {'initializer': utils.variance_scaling_initializer(
scale=cell_init_factor, distribution='truncated_normal',
mean=forget_bias)})
])
if overlay_rank > 0:
assert sparsity_ratio < 0
# TODO(melisgl): Specify initializers for the shared matrices.
tiled_linear_class = tiled_linear.OverlayedTiledLinear
init_params.update(collections.OrderedDict([
('W_x_i', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': overlay_rank}),
('W_x_j', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': overlay_rank}),
('W_x_f', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': overlay_rank}),
('W_x_o', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': overlay_rank}),
('W_h_i', {'overlay_sharing_key': 'W_h_any',
'overlay_rank': overlay_rank}),
('W_h_j', {'overlay_sharing_key': 'W_h_any',
'overlay_rank': overlay_rank}),
('W_h_f', {'overlay_sharing_key': 'W_h_any',
'overlay_rank': overlay_rank}),
('W_h_o', {'overlay_sharing_key': 'W_h_any',
'overlay_rank': overlay_rank}),
]))
elif sparsity_ratio >= 0.0:
assert overlay_rank == -1
tiled_linear_class = tiled_linear.SparseTiledLinear
# This is equivalent to using cell_initializer scaled by
# 1/sparsity_ratio.
sparse_initializer = tf.truncated_normal_initializer(
stddev=math.sqrt(cell_init_factor /
sparsity_ratio /
# TODO(melisgl): This is off if the input
# embedding size is different from the hidden
# size.
hidden_size))
init_params.update(collections.OrderedDict([
('W_x_.*', {'sparse_indices_sharing_key': 'W_x'}),
('W_h_.*', {'sparse_indices_sharing_key': 'W_h'}),
('W_x', {'sparsity_ratio': sparsity_ratio,
'initializer': sparse_initializer}),
('W_h', {'sparsity_ratio': sparsity_ratio,
'initializer': sparse_initializer}),
]))
else:
if layer_norm:
tiled_linear_class = tiled_linear.LayerNormedTiledLinear
else:
tiled_linear_class = tiled_linear.TiledLinear
init_params.update(collections.OrderedDict([
('W_.*', {'initializer': cell_initializer}),
('B_.*', {'initializer': cell_initializer})
]))
def make_layer(layer_index):
cell = TiledLSTMCell(
hidden_size_for_layer(layer_index),
tie_gates=tie_forget_and_input_gates,
cap_input_gate=cap_input_gate,
feature_mask_rounds=feature_mask_rounds,
feature_mask_rank=feature_mask_rank,
input_transform=input_transforms[layer_index],
state_transform=state_transforms[layer_index],
update_transform=update_transforms[layer_index],
tiled_linear_class=tiled_linear_class,
tiled_linear_var_init_params=init_params,
initializer=cell_initializer,
cell_clip=cell_clip if cell_clip > 0 else None,
layer_norm=layer_norm,
activation=eval(activation_fn)) # pylint: disable=eval-used
return cell
layers = [make_layer(i) for i in six.moves.range(num_layers)]
if lstm_skip_connection:
assert not residual_connections
return SkipMultiRNNCell(layers)
elif residual_connections:
return ResMultiRNNCell(layers)
else:
return tf.nn.rnn_cell.MultiRNNCell(layers)
def make_rhn_column():
init_params = collections.OrderedDict([
('B_c', {'initializer': tf.constant_initializer(forget_bias)}),
])
if overlay_rank > 0:
assert sparsity_ratio < 0
# TODO(melisgl): Specify initializers for the shared matrices.
tiled_linear_class = tiled_linear.OverlayedTiledLinear
init_params.update(collections.OrderedDict([
('W_x_h', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': overlay_rank}),
('W_x_c', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': overlay_rank}),
('W_x_t', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': overlay_rank}),
('W_s_h', {'overlay_sharing_key': 'W_s_any',
'overlay_rank': overlay_rank}),
('W_s_c', {'overlay_sharing_key': 'W_s_any',
'overlay_rank': overlay_rank}),
('W_s_t', {'overlay_sharing_key': 'W_s_any',
'overlay_rank': overlay_rank}),
]))
elif sparsity_ratio >= 0.0:
assert overlay_rank == -1
tiled_linear_class = tiled_linear.SparseTiledLinear
sparse_initializer = tf.truncated_normal_initializer(
stddev=math.sqrt(cell_init_factor /
sparsity_ratio /
# TODO(melisgl): This is off if the input
# embedding size is different from the hidden
# size.
hidden_size))
init_params.update(collections.OrderedDict([
('W_x_.*', {'sparse_indices_sharing_key': 'W_x'}),
('W_s_.*', {'sparse_indices_sharing_key': 'W_s'}),
('W_x', {'sparsity_ratio': sparsity_ratio,
'initializer': sparse_initializer}),
('W_s', {'sparsity_ratio': sparsity_ratio,
'initializer': sparse_initializer}),
]))
else:
tiled_linear_class = tiled_linear.TiledLinear
init_params.update(collections.OrderedDict([
('W_.*', {'initializer': cell_initializer}),
]))
logging.info('Creating RHN of depth %s', num_layers)
if layer_norm:
logging.warn('RHN does not support layer normalization.')
cell = TiledRHNCell(
hidden_size,
depth=num_layers,
tie_gates=tie_forget_and_input_gates,
input_transform=input_transforms[layer_index],
state_transform=state_transforms[layer_index],
update_transform=update_transforms[layer_index],
tiled_linear_class=tiled_linear_class,
tiled_linear_var_init_params=init_params,
cell_clip=cell_clip if cell_clip > 0 else None,
activation=eval(activation_fn)) # pylint: disable=eval-used
return cell
def make_nas_column():
assert not layer_norm
def make_layer(layer_index):
logging.info('Creating layer %s', layer_index)
cell = NASCell(
hidden_size,
input_transform=input_transforms[layer_index],
state_transform=state_transforms[layer_index],
update_transform=update_transforms[layer_index],
initializer=cell_initializer)
return cell
layers = [make_layer(i) for i in six.moves.range(num_layers)]
if lstm_skip_connection:
assert not residual_connections
return SkipMultiRNNCell(layers)
elif residual_connections:
return ResMultiRNNCell(layers)
else:
return tf.nn.rnn_cell.MultiRNNCell(layers)
assert len(hidden_size) <= num_layers
if model == 'lstm':
return make_lstm_column()
elif model == 'rhn':
assert len(set(hidden_size)) == 1
hidden_size = hidden_size[0]
return make_rhn_column()
elif model == 'nas':
assert len(set(hidden_size)) == 1
hidden_size = hidden_size[0]
return make_nas_column()
else:
assert False
| lamb-master | lamb/cell.py |
# Copyright 2018 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.
# ============================================================================
"""Early stopping, checkpointing for training."""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
class TrainingMonitor(object):
def __init__(self, max_turns=None, tuner=None, new_best_fn=None,
es_turns=None, es_rampup_turns=0, es_ramp_up_from=1,
es_worst_target=None, es_slowest_rate=None):
# The max number of turns (evaluations) after which training is stopped.
self._max_turns = max_turns
#
self._tuner = tuner
# Called when there is an improvement in XE.
self._new_best_fn = new_best_fn
# Early stopping: if there is no improvement for this many turns then
# training is stopped early (i.e. earlier than max_turns).
self._es_turns = es_turns
# Gradually ramp up the effective es_turns from es_ramp_up_from during the
# course of es_rampup_turns so that we pick off unpromising runs quickly.
self._es_rampup_turns = es_rampup_turns
self._es_ramp_up_from = es_ramp_up_from
# If the extrapolated best expected xe is worse than this, then bail out
# early.
self._es_worst_target = es_worst_target
# If the rate of improvement (the decrease in best_xe in the last
# effective_es_turns()) is less than this, then stop early.
self._es_slowest_rate = es_slowest_rate
# These are packaged up as state() for ease of checkpointing.
self._turn = -1
self._previous_best_xes = []
self._best_xe = None
self._best_xe_turn = None
self._finished_reason = None
self._calling_best_fn = False
self._averaging_triggered = False
self._metrics = None
def next_turn(self, evaluator):
def call_evaluator():
xe, metrics = evaluator()
self._metrics = metrics
return xe
if self._calling_best_fn or self.finished_reason() is not None:
# If we loaded a 'best' checkpoint (see the call to self._new_best_fn()
# below), clear _calling_best_fn so that self._turn gets incremented after
# the initial evaluation.
self._calling_best_fn = False
# Let _finished_reason be recomputed, because early stopping parameters
# might have changed if we are loaded from a checkpoint.
self._finished_reason = None
# Although training may be finished, let's evaluate again for its side
# effects such as logging results.
xe = call_evaluator()
# If evaluation parameters changed, the result may be different now.
self._maybe_update_best(xe)
# Parameters (e.g. max_turns) might be different now, so check for
# termination, but don't report anything to the tuner, because that would
# lead to duplicated measurements.
self._update_finished_reason(xe)
else:
self._turn += 1
# Importantly, this is called after turn is sensible.
xe = call_evaluator()
# _best_expected_xe assumes that the new result is recorded.
is_new_best = self._maybe_update_best(xe)
self._record_best()
self._update_finished_reason(xe)
if is_new_best:
self._calling_best_fn = True
self._new_best_fn()
self._calling_best_fn = False
return self.finished_reason() is None
# This is -1 before the first next_turn() call, then 0, 1, etc.
def turn(self):
return self._turn
def best_xe(self):
return self._best_xe
def best_xe_turn(self):
return self._best_xe_turn
def finished_reason(self):
return self._finished_reason
def metrics(self):
# The user provided metrics plus the interesting bits from the state get
# reported to the tuner.
metrics = self._metrics.copy()
metrics['turn'] = self._turn
metrics['best_xe'] = self._best_xe
metrics['best_xe_turn'] = self._best_xe_turn
metrics['finished_reason'] = self._finished_reason
return metrics
def state(self):
return repr(self._state_to_dict())
def set_state(self, state):
self._state_from_dict(eval(state)) # pylint: disable=eval-used
def _state_to_dict(self):
return {'turn': self._turn,
'previous_best_xes': self._previous_best_xes,
'best_xe': self._best_xe,
'best_xe_turn': self._best_xe_turn,
'finished_reason': self._finished_reason,
'calling_best_fn': self._calling_best_fn,
'averaging_triggered': self._averaging_triggered}
def _state_from_dict(self, dict_):
self._turn = dict_['turn']
self._previous_best_xes = dict_['previous_best_xes']
self._best_xe = dict_['best_xe']
self._best_xe_turn = dict_['best_xe_turn']
self._finished_reason = dict_['finished_reason']
self._calling_best_fn = dict_['calling_best_fn']
# Later additions to state. Maintain backward compatibility.
self._averaging_triggered = dict_.get('averaging_triggered', False)
def averaging_triggered(self):
return self._averaging_triggered
def set_averaging_triggered(self, value):
self._averaging_triggered = value
def _maybe_update_best(self, xe):
if self._best_xe is None or xe < self._best_xe:
self._best_xe = xe
self._best_xe_turn = self._turn
is_new_best = True
else:
is_new_best = False
return is_new_best
def _record_best(self):
if self._es_turns:
self._previous_best_xes.append(self._best_xe)
max_history = self._es_turns + 2
if len(self._previous_best_xes) > max_history:
self._previous_best_xes = self._previous_best_xes[-max_history:]
def effective_es_turns(self):
t = self._turn
d = self._es_turns
s = self._es_ramp_up_from
r = self._es_rampup_turns
if d <= 0:
return 999999
elif r == 0:
return d
else:
# Start with s at turn=0 and increase to d at turn=r-d.
slope = (d - s) / r
return s + int(slope * min(r, t))
def _improvement(self):
es_turns = self.effective_es_turns()
previous_best_xes = self._previous_best_xes
if len(previous_best_xes) > es_turns:
# pylint: disable=invalid-unary-operand-type
best_xe = self.best_xe()
improvement = previous_best_xes[-es_turns-1] - best_xe
assert 0 <= improvement
return improvement
else:
return None
# Extrapolate from the recent validation results in previous_best_xes,
def best_expected_xe(self):
improvement = self._improvement()
if improvement is not None:
num_remaining_turns = self._max_turns - self.turn()
assert num_remaining_turns >= 0
es_turns = self.effective_es_turns()
best_xe = self.best_xe()
# The rate of improvement is decreasing, so this is likely a lower bound.
return best_xe - improvement*float(num_remaining_turns) / es_turns
else:
return -99999.9
def es_worst_target(self):
return self._es_worst_target
def set_es_worst_target(self, value):
self._es_worst_target = value
def es_slowest_rate(self):
return self._es_slowest_rate
def _rate_of_improvement(self):
improvement = self._improvement()
if improvement is not None:
return improvement / self.effective_es_turns()
else:
return None
def _is_improvement_too_slow(self):
rate = self._rate_of_improvement()
return rate is not None and rate < self.es_slowest_rate()
def _update_finished_reason(self, xe):
# The tuner only supports numeric values in metrics. Filter out stuff like
# finished_reason.
numeric_metrics = self.metrics().copy()
for key in self.metrics():
try:
float(numeric_metrics[key])
except: # pylint: disable=bare-except
numeric_metrics.pop(key)
if math.isnan(xe):
if self._tuner:
self._tuner.report_done(infeasible=True, infeasible_reason='nan')
self._finished_reason = 'nan'
elif self._tuner and self._tuner.report_measure(
xe, global_step=self.turn(), metrics=numeric_metrics):
# The tuner wants us dead.
self._finished_reason = 'The tuner said so.'
elif self._max_turns is not None and self._max_turns <= self.turn():
self._finished_reason = 'Max turns %d reached.' % (self._max_turns)
else:
es_turns = self.effective_es_turns()
best_expected_xe = self.best_expected_xe()
es_worst_target = self.es_worst_target()
# Early stop if there was no improvement in XE for a while.
if es_turns > 0 and self._best_xe_turn + es_turns < self._turn:
self._finished_reason = 'No improvement for %s turns.' % (es_turns)
elif self._is_improvement_too_slow():
self._finished_reason = 'Improvement too slow (%s<%s).' % (
self._rate_of_improvement(), self.es_slowest_rate())
# Extrapolate learning curve and compare to current target.
elif es_worst_target and es_worst_target < best_expected_xe:
self._finished_reason = (
'Best expected XE %f is worse than %f.' %
(best_expected_xe, es_worst_target))
class LearningRateScheduler(object):
# TODO(melisgl): Handle decay, decay_burn_in, cyclical learning rates, etc.
def __init__(self, base_learning_rate, monitor, drop_multiplier=1.0,
drop_turns=-1, drop_at_turn_at_the_latest=-1):
assert _read_learning_rate_multiplier() == 1.0, (
'Found that learning rate is overridden. This is likely unintended.')
self.base_learning_rate = base_learning_rate
self.monitor = monitor
self.drop_multiplier = drop_multiplier
self.drop_turns = drop_turns
self.drop_at_turn_at_the_latest = drop_at_turn_at_the_latest
# These are packaged up as state() for ease of checkpointing.
self._multiplier = 1.0
self._last_drop_turn = -1
self._num_drops = 0
def state(self):
return repr(self._state_to_dict())
def set_state(self, state):
self._state_from_dict(eval(state)) # pylint: disable=eval-used
def _state_to_dict(self):
return {'multiplier': self._multiplier,
'last_drop_turn': self._last_drop_turn,
'num_drops': self._num_drops}
def _state_from_dict(self, dict_):
self._multiplier = dict_['multiplier']
self._last_drop_turn = dict_['last_drop_turn']
self._num_drops = dict_['num_drops']
def num_drops(self):
return self._num_drops
def learning_rate(self):
turn = self.monitor.turn()
best_xe_turn = self.monitor.best_xe_turn()
if ((self.drop_turns > 0 and
max(best_xe_turn, self._last_drop_turn) + self.drop_turns < turn)
# Maybe the learning rate hasn't been dropped yet and the latest turn to
# do so is now:
or (self._last_drop_turn == -1 and
self.drop_at_turn_at_the_latest > -1 and
self.drop_at_turn_at_the_latest <= turn)):
self._multiplier *= self.drop_multiplier
self._last_drop_turn = turn
self._num_drops += 1
return (self.base_learning_rate *
self._multiplier *
_read_learning_rate_multiplier())
def _read_learning_rate_multiplier(filename='/tmp/lamb-override'):
"""Quick hack to allow overriding the learning rate by editing a file."""
try:
with open(filename, 'r', encoding='utf-8') as f:
multiplier = float(f.readline())
except: # pylint: disable=bare-except
multiplier = 1.0
return multiplier
| lamb-master | lamb/monitoring.py |
# Copyright 2018 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.
# ============================================================================
"""Deterministic and MC evaluation."""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from absl import logging
from lamb import corpus
import numpy as np
import six
import tensorflow.compat.v1 as tf
def _make_feed(model, cond, cond_len, source, source_len, target,
last_state, episodic, dropout_multiplier=1.0, temperature=1.0):
feed = {model.softmax_temperature: temperature}
model.add_input_to_feed(feed, cond, cond_len, source, source_len, target)
model.add_dropout_to_feed(feed, dropout_multiplier)
if not episodic and last_state is not None:
feed.update({model.initial_state: last_state})
return feed
def _sum_masked(source_len, xe):
mask = (np.arange(xe.shape[0]).reshape(1, -1) <
source_len.reshape(-1, 1)).astype(np.float32).transpose()
return np.sum(mask*xe), np.sum(mask)
def evaluate_deterministic(
model, make_data_iterator_fn, dataset_name, episodic,
num_batches_to_discard=0, temperature=1.0, print_level=2,
prediction_callback=None, extra_ops=()):
"""Evaluate with a single pass with dropout turned off."""
sum_xe = 0
sum_len = 0
num_batches = 0
last_state = None
for (cond, cond_len, source, source_len, target) in make_data_iterator_fn():
feed = _make_feed(model, cond, cond_len, source, source_len, target,
last_state, episodic, 0, temperature)
xe, last_state = tf.get_default_session().run(
[model.xe_losses, model.last_state]+list(extra_ops), feed)[0:2]
if num_batches >= num_batches_to_discard:
sum_xe1, sum_len1 = _sum_masked(source_len, xe)
sum_xe += sum_xe1
sum_len += sum_len1
if prediction_callback:
prediction_callback(target, source_len, xe)
num_batches += 1
average_xe = sum_xe / sum_len
if print_level >= 1:
logging.info('final %s xe: %6.5f (%s), batches: %s',
dataset_name, average_xe, sum_len,
num_batches-num_batches_to_discard)
return average_xe
def evaluate_mc_with_geometric_mean(
model, make_data_iterator_fn, dataset_name, episodic,
num_batches_to_discard=0, num_samples=0, dropout_multiplier=1.0,
temperature=1.0, print_level=2):
"""Evaluate with MC dropout, taking the geometric mean of predictions."""
assert num_samples > 0
# Loop over batches made of examples in the corpus and accumulate
# statistics. data_iterator is already set up properly for
# episodic or non-episodic mode, we just need to keep passing the
# network's last state back.
sum_xe = 0
sum_len = 0
num_batches = 0
last_state = None
for (cond, cond_len, source, source_len, target) in make_data_iterator_fn():
if num_batches >= num_batches_to_discard:
feed = _make_feed(model, cond, cond_len, source, source_len, target,
last_state, episodic, dropout_multiplier, 1.0)
sum_logits = None
for _ in six.moves.range(num_samples):
# TODO(melisgl): The transfer of the logits
# [output_embedding_size, vocab_size] is expensive. The
# summing should take place purely in the graph.
logits = tf.get_default_session().run(model.logits, feed)
if sum_logits is None:
sum_logits = logits
else:
sum_logits += logits
# Now we feed the average of per-sample logits through the
# softmax to normalize.
feed.update({model.logits: sum_logits/num_samples,
model.softmax_temperature: temperature})
xe = tf.get_default_session().run(model.xe_losses, feed)
sum_xe1, sum_len1 = _sum_masked(source_len, xe)
sum_xe += sum_xe1
sum_len += sum_len1
average_xe = sum_xe / sum_len
if print_level >= 2:
logging.info('%s xe: %6.5f (%s), batches: %s (ns=%s)',
dataset_name, average_xe, sum_len,
num_batches-num_batches_to_discard, num_samples)
# Do a deterministic pass. We need this even in MC mode to get a
# single last state to feed back for the next batch. This isn't
# strictly correct, we should actually sample the state to be
# fed back and the most obvious way to do that is to loop over
# the entire dataset instead of just the batch, but then we'd
# need to keep all those logits around.
feed = _make_feed(model, cond, cond_len, source, source_len, target,
last_state, episodic, 0, temperature)
last_state = tf.get_default_session().run(model.last_state, feed)
num_batches += 1
if print_level >= 1:
logging.info('final %s xe: %6.5f (%s), batches: %s (ns=%s)',
dataset_name, average_xe, sum_len,
num_batches-num_batches_to_discard, num_samples)
return average_xe
def evaluate_mc_with_power_mean(
model, make_data_iterator_fn, dataset_name, episodic,
num_batches_to_discard=0, num_samples=0, dropout_multiplier=1.0,
power=1.0, temperature=1.0, print_level=2):
# pylint: disable=g-doc-return-or-yield,g-doc-args
# pylint: disable=g-docstring-missing-newline
r"""Evaluate with MC dropout, taking the power mean of predictions.
M_p(x_1,...,x_n) = (1/n*\sum_{i=1}^n x_i^p)^{1/p}"""
assert num_samples > 0
# Loop over batches made of examples in the corpus and accumulate
# statistics. data_iterator is already set up properly for
# episodic or non-episodic mode, we just need to keep passing the
# network's last state back.
sum_xe = 0
sum_len = 0
num_batches = 0
last_state = None
for (cond, cond_len, source, source_len, target) in make_data_iterator_fn():
if num_batches >= num_batches_to_discard:
feed = _make_feed(model, cond, cond_len, source, source_len, target,
last_state, episodic, dropout_multiplier, 1.0)
log_sum_probs = None
for _ in six.moves.range(num_samples):
# TODO(melisgl): The transfer of the logits
# [output_embedding_size, vocab_size] is expensive. The
# summing should take place purely in the graph.
log_probs = tf.get_default_session().run(model.log_probs, feed)
if log_sum_probs is None:
log_sum_probs = log_probs
else:
log_sum_probs = np.logaddexp(log_sum_probs, power*log_probs)
# log_sum_probs is \ln \sum x_i^p. We need to divide by n
# (i.e. subtract math.log(num_samples)), and raise to the
# power 1/p (i.e. divide by power), then feed the results
# through the softmax to renormalize.
feed.update(
{model.logits: (log_sum_probs -
math.log(num_samples))/power*temperature})
xe = tf.get_default_session().run(model.xe_losses, feed)
sum_xe1, sum_len1 = _sum_masked(source_len, xe)
sum_xe += sum_xe1
sum_len += sum_len1
average_xe = sum_xe / sum_len
if print_level >= 2:
logging.info('%s xe: %6.5f (%s), batches: %s (ns=%s)',
dataset_name, average_xe, sum_len,
num_batches-num_batches_to_discard, num_samples)
# Do a deterministic pass. We need this even in MC mode to get a
# single last state to feed back for the next batch. This isn't
# strictly correct, we should actually sample the state to be
# fed back and the most obvious way to do that is to loop over
# the entire dataset instead of just the batch, but then we'd
# need to keep all those logits around.
feed = _make_feed(model, cond, cond_len, source, source_len, target,
last_state, episodic, 0, 1.0)
last_state = tf.get_default_session().run(model.last_state, feed)
num_batches += 1
if print_level >= 1:
logging.info('final %s xe: %6.5f (%s), batches: %s (ns=%s)',
dataset_name, average_xe, sum_len,
num_batches-num_batches_to_discard, num_samples)
return average_xe
def evaluate_mc_with_arithmetic_mean(
model, make_data_iterator_fn, dataset_name, episodic,
num_batches_to_discard=0, num_samples=0, dropout_multiplier=1.0,
temperature=1.0, deterministic_last_state=False, print_level=2,
dyneval=None, extra_ops=()):
"""Evaluate with MC dropout, taking the average of predictions."""
assert num_samples > 0
log_sum_prob = None
for sample_index in six.moves.range(num_samples):
num_batches = 0
start = 0
sum_xe = 0.0
sum_len = 0
last_state = None
if dyneval:
# Restore the original weights.
dyneval.restore()
for (cond, cond_len, source, source_len, target) in make_data_iterator_fn():
feed = _make_feed(model, cond, cond_len, source, source_len, target,
last_state, episodic, dropout_multiplier, temperature)
# [time, batch]
sample_xe, last_state = tf.get_default_session().run(
[model.xe_losses, model.last_state]+list(extra_ops), feed)[0:2]
if num_batches >= num_batches_to_discard:
# [batch, time]
log_probs = -np.transpose(sample_xe).astype(np.float64)
max_time_steps = log_probs.shape[1]
if log_sum_prob is None:
log_sum_prob = log_probs
elif sample_index == 0:
log_sum_prob = np.concatenate([log_sum_prob, log_probs], axis=1)
else:
log_sum_prob[:, start:start+max_time_steps] = np.logaddexp(
log_sum_prob[:, start:start+max_time_steps], log_probs)
# Compute the mean XE.
mask = (np.arange(max_time_steps).reshape(1, -1) <
source_len.reshape(-1, 1)).astype(np.float32)
sum_xe += -np.sum(mask*(log_sum_prob[:, start:start+max_time_steps] -
math.log(sample_index+1)))
sum_len += np.sum(mask)
start += max_time_steps
if deterministic_last_state:
feed = _make_feed(model, cond, cond_len, source, source_len, target,
last_state, episodic, 0.0, temperature)
last_state = tf.get_default_session().run(model.last_state, feed)
num_batches += 1
average_xe = sum_xe / sum_len
if print_level >= 2:
logging.info('%s xe: %6.5f (%s), batches: %s (ns=%s/%s)',
dataset_name, average_xe, sum_len,
num_batches-num_batches_to_discard, sample_index+1,
num_samples)
if print_level >= 1:
logging.info('final %s xe: %6.5f (%s), batches: %s (ns=%s)',
dataset_name, average_xe, sum_len,
num_batches-num_batches_to_discard, num_samples)
return average_xe
def evaluate(model, make_data_iterator_fn, vocab, dataset_name, episodic,
num_batches_to_discard=0, num_samples=0, dropout_multiplier=1.0,
eval_method=None, power=1.0, temperature=1.0, print_level=2,
prediction_file=None, dyneval=None, extra_ops=()):
"""Evaluate."""
vocab = vocab
name = dataset_name
assert eval_method in ['deterministic', 'geometric', 'power', 'arithmetic']
if eval_method == 'deterministic':
name += '_det'
else:
if eval_method == 'geometric':
name += '_mcg'
elif eval_method == 'power':
name += '_mcp' + str(power)
elif eval_method == 'arithmetic':
name += '_mca'
if dropout_multiplier != 1.0:
name += '_d' + str(dropout_multiplier)
if temperature != 1.0:
name += '_t' + str(temperature)
def dispatch0(callback, extra_ops):
if eval_method == 'deterministic':
return evaluate_deterministic(
model, make_data_iterator_fn, name, episodic, num_batches_to_discard,
temperature, print_level=print_level, prediction_callback=callback,
extra_ops=extra_ops)
elif eval_method == 'geometric':
assert not extra_ops, 'Not implemented.'
return evaluate_mc_with_geometric_mean(
model, make_data_iterator_fn, name, episodic, num_batches_to_discard,
num_samples, dropout_multiplier, temperature,
print_level=print_level)
elif eval_method == 'power':
assert not extra_ops, 'Not implemented.'
return evaluate_mc_with_power_mean(
model, make_data_iterator_fn, name, episodic, num_batches_to_discard,
num_samples, dropout_multiplier, power, temperature,
print_level=print_level)
elif eval_method == 'arithmetic':
return evaluate_mc_with_arithmetic_mean(
model, make_data_iterator_fn, name, episodic, num_batches_to_discard,
num_samples, dropout_multiplier, temperature,
print_level=print_level, dyneval=dyneval,
extra_ops=extra_ops)
else:
assert False
def dispatch(callback):
if dyneval is None:
return dispatch0(callback, list(extra_ops))
else:
with dyneval:
return dispatch0(callback, [dyneval.update_op()] + list(extra_ops))
if prediction_file:
with tf.gfile.GFile(prediction_file, 'w') as f:
def callback(target, length, xe):
for i in six.moves.range(length[0]):
token = vocab.decode([target[i][0]])[0]
log_prob = -xe[i][0]
print('{!r}'.format(token), file=f)
print('{}'.format(log_prob), file=f)
return dispatch(callback)
else:
return dispatch(None)
def evaluate_all(model, data, vocab, batch_size, max_time_steps,
min_non_episodic_eval_examples_per_stripe,
max_training_eval_batches,
max_eval_eval_batches,
max_test_eval_batches,
episodic,
eval_softmax_temperature,
eval_softmax_temperature_estimation_num_tokens,
eval_method,
num_eval_samples,
eval_power_mean_power,
eval_dropout_multiplier,
validation_prediction_file,
dyneval,
conditioning_separator=None):
"""Evaluate on training/validation and maybe on test."""
# Evaluate on training set.
def make_train_iterator():
return corpus.get_batches(
data['training'], vocab,
batch_size,
max_time_steps,
episodic=episodic,
deterministic=True,
max_epochs=1,
max_batches=max_training_eval_batches,
conditioning_separator=conditioning_separator)
if dyneval:
dyneval.zero_sum_squared_grads()
training_xe = evaluate(
model, make_train_iterator, vocab, 'train', episodic,
# Let's not waste time on samples on training evaluation.
num_samples=0, eval_method='deterministic',
extra_ops=[dyneval.add_squared_grads_op()])
else:
training_xe = evaluate(
model, make_train_iterator, vocab, 'train', episodic,
# Let's not waste time on samples on training evaluation.
num_samples=0, eval_method='deterministic')
# For expediency, we evaluate in batches even in non-episodic
# mode, but make sure that each stripe in the batch has at least
# min_non_episodic_eval_examples_per_stripe examples to limit
# the handicap.
def eval_batch_size(dataset):
if (not episodic and
min_non_episodic_eval_examples_per_stripe):
return max(1, min(batch_size, dataset.size() //
min_non_episodic_eval_examples_per_stripe))
else:
return batch_size
# Find the best softmax temperature on using a few batches of the
# validation set.
config_sttt = eval_softmax_temperature
if config_sttt > 0.0:
eval_softmax_temperature = config_sttt
else:
def make_quick_eval_iterator():
quick_eval_max_batches = max(
1,
eval_softmax_temperature_estimation_num_tokens //
batch_size // max_time_steps)
return corpus.get_batches(
data['valid'], vocab,
batch_size,
max_time_steps,
episodic=episodic,
deterministic=True,
max_epochs=1,
max_batches=quick_eval_max_batches,
conditioning_separator=conditioning_separator)
xe = 99999999.0
best_i = 0
for i in six.moves.range(50):
eval_softmax_temperature0 = 1.06-i*0.02
if eval_softmax_temperature0 < -config_sttt-0.0001:
break
xe0 = evaluate(
model, make_quick_eval_iterator, vocab, 'sttt_eval', episodic,
num_samples=num_eval_samples,
temperature=eval_softmax_temperature0,
power=eval_power_mean_power,
dropout_multiplier=eval_dropout_multiplier,
eval_method=eval_method,
print_level=1)
if xe0 < xe:
best_i = i
xe = xe0
eval_softmax_temperature = eval_softmax_temperature0
# Stop if there was no improvement for two rounds.
if best_i+1 < i:
break
# Use the best eval_softmax_temperature and do a longer
# run on the validation set.
def make_eval_iterator():
return corpus.get_batches(
data['valid'], vocab,
eval_batch_size(data['valid']) if not dyneval else 1,
max_time_steps,
episodic=episodic,
deterministic=True,
max_epochs=1,
max_batches=max_eval_eval_batches,
conditioning_separator=conditioning_separator)
xe = evaluate(
model, make_eval_iterator, vocab, 'valid', episodic,
num_samples=num_eval_samples,
temperature=eval_softmax_temperature,
power=eval_power_mean_power,
dropout_multiplier=eval_dropout_multiplier,
eval_method=eval_method,
prediction_file=validation_prediction_file,
dyneval=dyneval)
# evaluate on test
if data['test'].size():
def make_test_iterator():
return corpus.get_batches(
data['test'], vocab,
eval_batch_size(data['test']) if not dyneval else 1,
max_time_steps,
episodic=episodic,
deterministic=True,
max_epochs=1,
max_batches=max_test_eval_batches,
conditioning_separator=conditioning_separator)
test_xe = evaluate(
model, make_test_iterator, vocab, 'test', episodic,
num_samples=num_eval_samples,
temperature=eval_softmax_temperature,
power=eval_power_mean_power,
dropout_multiplier=eval_dropout_multiplier,
eval_method=eval_method,
dyneval=dyneval)
else:
test_xe = None
return training_xe, xe, test_xe
| lamb-master | lamb/evaluation.py |
# Copyright 2018 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.
# ============================================================================
| lamb-master | lamb/__init__.py |
# Copyright 2018 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.
# ============================================================================
"""rnn_cell.NASCell adapted to support transforms."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
class NASCell(tf.nn.rnn_cell.RNNCell):
"""Neural Architecture Search (NAS) recurrent network cell.
This implements the recurrent cell from the paper:
https://arxiv.org/abs/1611.01578
Barret Zoph and Quoc V. Le.
"Neural Architecture Search with Reinforcement Learning" Proc. ICLR 2017.
The class uses an optional projection layer.
"""
def __init__(self, num_units, num_proj=None,
use_biases=False, reuse=None,
initializer=None,
input_transform=None,
state_transform=None,
update_transform=None):
"""Initialize the parameters for a NAS cell.
Args:
num_units: int, The number of units in the NAS cell
num_proj: (optional) int, The output dimensionality for the projection
matrices. If None, no projection is performed.
use_biases: (optional) bool, If True then use biases within the cell. This
is False by default.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
initializer: Initializer for the variables.
input_transform: None, or a function of one argument that
massages the input in some way. For example, variational
dropout can be implemted by passing a Dropout object here.
state_transform: Similar to input_transform, this is
applied to the recurrent state.
update_transform: Similar to input_transform, this is
applied to the proposed update ('j').
"""
super(NASCell, self).__init__(_reuse=reuse)
self._num_units = num_units
self._num_proj = num_proj
self._use_biases = use_biases
self._reuse = reuse
if num_proj is not None:
self._state_size = tf.nn.rnn_cell.LSTMStateTuple(num_units, num_proj)
self._output_size = num_proj
else:
self._state_size = tf.nn.rnn_cell.LSTMStateTuple(num_units, num_units)
self._output_size = num_units
self._initializer = initializer
self._input_transform = input_transform
self._state_transform = state_transform
assert update_transform is None
@property
def state_size(self):
return self._state_size
@property
def output_size(self):
return self._output_size
def call(self, inputs, state):
"""Run one step of NAS Cell.
Args:
inputs: input Tensor, 2D, batch x num_units.
state: This must be a tuple of state Tensors, both `2-D`, with column
sizes `c_state` and `m_state`.
Returns:
A tuple containing:
- A `2-D, [batch x output_dim]`, Tensor representing the output of the
NAS Cell after reading `inputs` when previous state was `state`.
Here output_dim is:
num_proj if num_proj was set,
num_units otherwise.
- Tensor(s) representing the new state of NAS Cell after reading `inputs`
when the previous state was `state`. Same type and shape(s) as `state`.
Raises:
ValueError: If input size cannot be inferred from inputs via
static shape inference.
"""
sigmoid = tf.sigmoid
tanh = tf.tanh
relu = tf.nn.relu
num_proj = self._num_units if self._num_proj is None else self._num_proj
def maybe_transform(transform, x):
if transform is None:
return x
else:
return transform(x)
(c_prev, m_prev) = state
m_prev = maybe_transform(self._state_transform, m_prev)
dtype = inputs.dtype
input_size = inputs.get_shape().with_rank(2)[1]
inputs = maybe_transform(self._input_transform, inputs)
if input_size.value is None:
raise ValueError("Could not infer input size from inputs.get_shape()[-1]")
# Variables for the NAS cell. W_m is all matrices multiplying the
# hiddenstate and W_inputs is all matrices multiplying the inputs.
concat_w_m = tf.get_variable(
"recurrent_kernel", [num_proj, 8 * self._num_units],
initializer=self._initializer, dtype=dtype)
concat_w_inputs = tf.get_variable(
"kernel", [input_size.value, 8 * self._num_units],
initializer=self._initializer, dtype=dtype)
m_matrix = tf.matmul(m_prev, concat_w_m)
inputs_matrix = tf.matmul(inputs, concat_w_inputs)
if self._use_biases:
b = tf.get_variable(
"bias",
shape=[8 * self._num_units],
initializer=tf.zeros_initializer(),
dtype=dtype)
m_matrix = tf.nn.bias_add(m_matrix, b)
# The NAS cell branches into 8 different splits for both the hiddenstate
# and the input
m_matrix_splits = tf.split(axis=1, num_or_size_splits=8,
value=m_matrix)
inputs_matrix_splits = tf.split(axis=1, num_or_size_splits=8,
value=inputs_matrix)
# First layer
layer1_0 = sigmoid(inputs_matrix_splits[0] + m_matrix_splits[0])
layer1_1 = relu(inputs_matrix_splits[1] + m_matrix_splits[1])
layer1_2 = sigmoid(inputs_matrix_splits[2] + m_matrix_splits[2])
layer1_3 = relu(inputs_matrix_splits[3] * m_matrix_splits[3])
layer1_4 = tanh(inputs_matrix_splits[4] + m_matrix_splits[4])
layer1_5 = sigmoid(inputs_matrix_splits[5] + m_matrix_splits[5])
layer1_6 = tanh(inputs_matrix_splits[6] + m_matrix_splits[6])
layer1_7 = sigmoid(inputs_matrix_splits[7] + m_matrix_splits[7])
# Second layer
l2_0 = tanh(layer1_0 * layer1_1)
l2_1 = tanh(layer1_2 + layer1_3)
l2_2 = tanh(layer1_4 * layer1_5)
l2_3 = sigmoid(layer1_6 + layer1_7)
# Inject the cell
l2_0 = tanh(l2_0 + c_prev)
# Third layer
l3_0_pre = l2_0 * l2_1
new_c = l3_0_pre # create new cell
l3_0 = l3_0_pre
l3_1 = tanh(l2_2 + l2_3)
# Final layer
new_m = tanh(l3_0 * l3_1)
# Projection layer if specified
if self._num_proj is not None:
concat_w_proj = tf.get_variable(
"projection_weights", [self._num_units, self._num_proj],
dtype)
new_m = tf.matmul(new_m, concat_w_proj)
new_state = tf.nn.rnn_cell.LSTMStateTuple(new_c, new_m)
return new_m, new_state
| lamb-master | lamb/nascell.py |
# Copyright 2018 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.
# ============================================================================
"""Efficient linear mappings from a number of inputs to outputs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
from absl import logging
from lamb import utils
import six
from sonnet.python.modules import base as snt_base
import tensorflow.compat.v1 as tf
class AbstractTiledLinear(snt_base.AbstractModule):
"""Efficient linear mappings from a number of inputs to outputs."""
def __init__(self, input_name_and_sizes, output_name_and_sizes,
var_init_params=None, name='tiled_linear'):
"""Constructs a AbstractTiledLinear module.
Args:
input_name_and_sizes: A sequence of `(name, size)` tuples
listing the inputs are their sizes (a positive integer or None
to rely on shape inferencing at build() time). As a
convenience, `(name, None)` can be shortened to `(name,)` or
just `name`.
output_name_and_sizes: Similar to `input_name_and_sizes`, it
lists the names and sizes of outputs. Since there is no way of
inferring shapes for outputs, the full `(name, size)` form
must always be used.
var_init_params: A dict for specifying initialization parameters
for variables such as the initializer, partitioner and
regularizer. Subclasses may support more parameters.
name: Name of the module.
Raises:
ValueError: If ` contains any keys other than 'w' or 'b'.
KeyError: If `partitioners` contains any keys other than 'w' or 'b'.
KeyError: If `regularizers` contains any keys other than 'w' or 'b'.
TypeError: If any of the given initializers are not callable.
TypeError: If any of the given partitioners are not callable.
TypeError: If any of the given regularizers are not callable.
"""
super(AbstractTiledLinear, self).__init__(name=name)
self._input_name_and_sizes = self._canonicalize_input_name_and_sizes(
input_name_and_sizes)
self._output_name_and_sizes_ = self._check_output_name_and_sizes(
output_name_and_sizes)
self._var_init_params = self._check_var_init_params(var_init_params)
self._merged_input_sizes = None
self._name = name
self._dtype = None
def _canonicalize_input_name_and_sizes(self, name_and_sizes):
result = []
for e in name_and_sizes:
if isinstance(e, six.string_types):
result.append((e, None))
else:
assert isinstance(e, tuple)
if len(e) == 1:
result.append((e[0], None))
elif len(e) == 2:
result.append(e)
else:
assert False, 'Malformed name_and_sizes spec {}.'.format(e)
return result
def _check_output_name_and_sizes(self, name_and_sizes):
for e in name_and_sizes:
assert isinstance(e, tuple)
assert len(e) == 2
assert isinstance(e[0], six.string_types)
assert isinstance(e[1], int)
return name_and_sizes
def _check_var_init_params(self, var_init_params):
if var_init_params is None:
return {}
else:
valid_keys = self.valid_var_init_param_keys()
for pattern in var_init_params:
for key in var_init_params[pattern]:
assert key in valid_keys, (
'Unexpected key {} in var_init_params[{}].'.format(key, pattern))
return var_init_params
def _check_dtype(self, inputs, previous_dtype):
dtype = previous_dtype
for input_ in inputs:
if dtype is None:
dtype = input_.dtype
else:
assert input_.dtype == dtype
return dtype
def valid_var_init_param_keys(self):
return ['initializer', 'partitioner', 'regularizer']
def _find_var_init_param(self, var_name, key, default):
for pattern in self._var_init_params:
if re.match(pattern, var_name):
value = self._var_init_params[pattern].get(key, None)
if value is not None:
return value
return default
def _get_variable(self, name, shape,
initializer=None,
default_initializer=None, default_partitioner=None,
default_regularizer=None):
if initializer is None:
initializer = self._find_var_init_param(
name, 'initializer', default_initializer)
partitioner = self._find_var_init_param(
name, 'partitioner', default_partitioner)
regularizer = self._find_var_init_param(
name, 'regularizer', default_regularizer)
return tf.get_variable(name, shape=shape, dtype=self._dtype,
initializer=initializer, partitioner=partitioner,
regularizer=regularizer)
def _declared_input_sizes(self):
sizes = []
for _, input_size in self._input_name_and_sizes:
sizes.append(input_size)
return tf.TensorShape(sizes)
def _inferred_input_sizes(self, inputs):
return tf.TensorShape([input_.get_shape().as_list()[-1]
for input_ in inputs])
def _merge_input_sizes(self, inputs):
inferred_input_sizes = self._inferred_input_sizes(inputs)
if self._merged_input_sizes is None:
declared_input_sizes = self._declared_input_sizes()
# This is the first call to build(). Remember the input sizes
# (only the last dimension matters for matmul).
if not declared_input_sizes.is_compatible_with(inferred_input_sizes):
raise snt_base.IncompatibleShapeError(
'{}: Declared input sizes {} are incompatible '
'with inferred ones {}.'.format(
self.scope_name, declared_input_sizes.as_list(),
inferred_input_sizes.as_list()))
self._merged_input_sizes = declared_input_sizes.merge_with(
inferred_input_sizes)
if not self._merged_input_sizes.is_fully_defined():
raise snt_base.IncompatibleShapeError(
'{}: Last input dimensions must be known at module build time.'
' Got {}.'.format(self.name, self._merged_input_sizes.as_list()))
else:
# At subsequent calls check that input sizes are compatible.
if not self._merged_input_sizes.is_compatible_with(inferred_input_sizes):
raise snt_base.IncompatibleShapeError(
'{}: Current input sizes {} are different '
'from first build {}'.format(
self.name, inferred_input_sizes.as_list(),
self._merged_input_sizes.as_list()))
def _merged_input_name_and_sizes(self):
return zip([input_name for input_name, _ in self._input_name_and_sizes],
self._merged_input_sizes.as_list())
def _output_name_and_sizes(self):
return self._output_name_and_sizes_
def _build(self, inputs):
"""Connects the module into the graph, with `inputs`.
If this is not the first time the module has been connected to the
graph, the Tensors in `inputs` must have the same final dimension,
in order for the existing variables to be the correct size for the
multiplication. The leading dimensions of the input tensors may
differ for each call to `build()`.
Args:
inputs: A sequence of tensors. The last dimension of the tensor
at position I must be compatible with the declared size of the
corresponding input (if not None) and also with the last
dimension of the corresponding input tensor in all previous
calls to build() on the same object.
Returns:
A sequence of output tensors.
Raises:
base.IncompatibleShapeError: If the input sizes are not
compatible with the declared or with the sizes previous calls.
"""
self._merge_input_sizes(inputs)
self._dtype = self._check_dtype(inputs, self._dtype)
return self._build_tiled_linear(inputs,
self._merged_input_name_and_sizes(),
self._output_name_and_sizes(),
True)
class TiledLinear(AbstractTiledLinear):
"""Plain linear mapping without any bells or whistles."""
def __init__(self, input_name_and_sizes, output_name_and_sizes,
var_init_params=None, name='tiled_linear'):
"""Plain linear mapping without any bells or whistles."""
super(TiledLinear, self).__init__(
input_name_and_sizes, output_name_and_sizes,
var_init_params=var_init_params, name=name)
self._weights = None
self._biases = None
def _ensure_weights(self):
# pylint: disable=missing-docstring
if self._weights is None:
# Tile an initializer together from the initializers of the individual
# tiles. We used to assemble the weight matrix by tiling the individual
# matrices, but with that tensorflow wasted gobs of memory for the
# gradients.
default_initializer = utils.variance_scaling_initializer(scale=1.0)
columns = []
for output_name, output_size in self._output_name_and_sizes_:
# Collect the initializers for the tiles for weight matrices mapping
# _to_ the output being considered. These will be stacked in a column of
# the final tiled weight matrix.
initializers_to_output = []
for input_name, input_size in self._input_name_and_sizes:
name = 'W_{}_{}'.format(input_name, output_name)
initializer = self._find_var_init_param(
name, 'initializer', default_initializer)
shape = [int(input_size), int(output_size)]
# logging.info('Tile initializer for %r %r: %r',
# name, shape, initializer)
initializers_to_output.append((initializer, shape))
columns.append(initializers_to_output)
def tiled_initializer(shape, dtype=self._dtype, partition_info=None):
column_values = []
for column in columns:
values = [initializer(shape, dtype=dtype,
partition_info=partition_info)
for initializer, shape in column]
column_values.append(tf.concat(values, axis=0))
return tf.concat(column_values, axis=1)
# Finally, instantiate the weights.
total_input_size = sum([input_size for _, input_size
in self._input_name_and_sizes])
total_output_size = sum([output_size for _, output_size
in self._output_name_and_sizes_])
self._weights = self._get_variable(
'W', shape=[total_input_size, total_output_size],
initializer=tiled_initializer)
return self._weights
def _ensure_biases(self):
# pylint: disable=missing-docstring
if self._biases is None:
# Biases are much smaller than weights, so wasting memory with gradients
# is not an issue.
biases = []
for output_name, output_size in self._output_name_and_sizes_:
bias = self._get_variable(
'B_{}'.format(output_name), shape=[output_size],
default_initializer=tf.zeros_initializer())
biases.append(bias)
self._biases = tf.concat(biases, 0)
return self._biases
def _build_tiled_linear(self, inputs, input_name_and_sizes,
output_name_and_sizes, add_bias):
# pylint: disable=missing-docstring
def split_output(output):
if len(output_name_and_sizes) == 1:
return output
elif len(set([size for _, size in output_name_and_sizes])) == 1:
# This is a bit faster than several tf.slice calls.
return tf.split(output, len(output_name_and_sizes), axis=1)
else:
outputs = []
offset = 0
for _, output_size in output_name_and_sizes:
outputs.append(tf.slice(output, [0, offset], [-1, output_size]))
offset += output_size
return outputs
weights = self._ensure_weights()
if len(inputs) > 1:
inputs = tf.concat(inputs, 1)
if add_bias:
biases = self._ensure_biases()
return split_output(tf.nn.xw_plus_b(inputs, weights, biases))
else:
return split_output(tf.matmul(inputs, weights))
class LayerNormedTiledLinear(AbstractTiledLinear):
# pylint: disable=missing-docstring
def _build_tiled_linear(self, inputs, input_name_and_sizes,
output_name_and_sizes, add_bias):
# pylint: disable=missing-docstring
# Return a list of weight matrices that parallels
# input_name_and_sizes and maps one input tensor to the
# concatenation of all outputs.
def make_weights_for_inputs():
rows = []
for input_name, input_size in input_name_and_sizes:
# Collect the weight matrices mapping from the input being
# considered. These will be stacked in a row.
weights_from_input = []
for output_name, output_size in output_name_and_sizes:
name = 'W_{}_{}'.format(input_name, output_name)
weight = self._get_variable(name, shape=[input_size, output_size])
weights_from_input.append(weight)
rows.append(tf.concat(weights_from_input, 1))
return rows
def make_biases():
biases = []
for name, size in output_name_and_sizes:
bias = self._get_variable('B_{}'.format(name), shape=[size],
default_initializer=tf.zeros_initializer())
biases.append(bias)
return tf.concat(biases, 0)
def split_output(output):
outputs = []
offset = 0
for _, output_size in output_name_and_sizes:
outputs.append(tf.slice(output, [0, offset], [-1, output_size]))
offset += output_size
return outputs
weights_for_inputs = make_weights_for_inputs()
s = make_biases() if add_bias else 0.0
for input_, weights, (name, _) in zip(inputs, weights_for_inputs,
input_name_and_sizes):
s += utils.layer_norm(tf.matmul(input_, weights), [1], bias=0.0,
scope='ln_{}'.format(name))
return split_output(s)
class SparseTiledLinear(AbstractTiledLinear):
"""Tiled mapping with sparse but fixed connectivity.
There are two additional variable initialization parameters:
`sparse_indices_sharing_key` and `sparsity_ratio`.
`sparse_indices_sharing_key` controls which tiles have the same
connectivity pattern (in the sense of having the same
tf.SparseTensor.indices). Generally, tiles with the same sharing key
and `sparsity_ratio` share these indices. There are two special key
values: `':name:'` and `':shape:'` that get substituted with the
name and shape of the actual tile, respectively.
For example, if an LSTM cell maps inputs ('x', 'h') to ('f, 'i, 'j',
'o'), then the following makes all weight matrices from the input
'x' to any of the gates or the candidate update share connectivity
structure. Similarly, there is connectivity pattern sharing between
weight matrices mapping from the recurrent state 'h'.
var_init_params=OrderedDict([
('W_x_.*', {'sparse_indices_sharing_key': 'x'}),
('W_h_.*', {'sparse_indices_sharing_key': 'h'}),
('.*', {'sparsity_ratio': 0.5,
'initializer': tf.random_uniform_initializer(-1, 1)})
])
Note that only the sparse indices are shared, the values are
different (unless playing tricks with the 'initializer' param).
If `sparsity_ratio` is set (to a float number in [0,1]), then this
represents the proportion of entries non-missing entries in the
tile. The actual connectivity pattern is determined randomly.
In the future, there may be support for band and block diagonal
matrices.
"""
def __init__(self, input_name_and_sizes, output_name_and_sizes,
var_init_params=None, name='sparse_tiled_linear'):
super(SparseTiledLinear, self).__init__(
input_name_and_sizes, output_name_and_sizes,
var_init_params=var_init_params, name=name)
self._sparse_indices_cache = {}
# Cache the SparseTensor instances to avoid the considerable
# overhead of creating duplicates just to be optimized out.
self._sparse_variable_cache = {}
def _find_or_create_sparse_indices(self, name, shape):
ratio = self._find_var_init_param(name, 'sparsity_ratio', None)
assert ratio, 'sparsity_ratio must be specified.'
sharing_key = self._find_var_init_param(name, 'sparse_indices_sharing_key',
':name:')
if sharing_key == ':name:':
key = name
if sharing_key == ':shape:':
sharing_key = shape
key = (sharing_key, ratio)
if key not in self._sparse_indices_cache:
logging.info('Creating sparse indices for %s%r with key %r.',
name, shape, key)
self._sparse_indices_cache[key] = utils.sparse_random_indices(ratio,
shape)
return self._sparse_indices_cache[key]
def _find_or_create_sparse_variable(self, name, sparse_indices, shape,
initializer=None, partitioner=None,
regularizer=None):
if name not in self._sparse_variable_cache:
logging.info('Create sparse variable %s.', name)
self._sparse_variable_cache[name] = utils.get_sparse_variable(
name, sparse_indices, shape=shape, initializer=initializer,
partitioner=partitioner, regularizer=regularizer)
return self._sparse_variable_cache[name]
def valid_var_init_param_keys(self):
return (super(SparseTiledLinear, self).valid_var_init_param_keys() +
['sparse_indices_sharing_key', 'sparsity_ratio'])
def _get_variable(self, name, shape,
default_initializer=None, default_partitioner=None,
default_regularizer=None, sparse_indices=None):
initializer = self._find_var_init_param(
name, 'initializer', default_initializer)
partitioner = self._find_var_init_param(
name, 'partitioner', default_partitioner)
regularizer = self._find_var_init_param(
name, 'regularizer', default_regularizer)
sparse_indices = self._find_or_create_sparse_indices(name, shape)
return self._find_or_create_sparse_variable(
name, sparse_indices, shape=shape, initializer=initializer,
partitioner=partitioner, regularizer=regularizer)
def _build_tiled_linear(self, inputs, input_name_and_sizes,
output_name_and_sizes, add_bias):
results = []
for output_name, output_size in output_name_and_sizes:
r = 0.0
for input_, (input_name, input_size) in zip(inputs, input_name_and_sizes):
name = 'W_{}_{}'.format(input_name, output_name)
weight = self._get_variable(
name, shape=[output_size, input_size])
r += tf.sparse_tensor_dense_matmul(weight, input_, adjoint_b=True)
r = tf.transpose(r)
if add_bias:
# Biases are dense, hence we call _get_variable of the base
# class.
r += super(SparseTiledLinear, self)._get_variable(
'B_{}'.format(output_name), shape=[output_size],
default_initializer=tf.zeros_initializer())
results.append(r)
return results
# TODO(melisgl): Since computation is the same as in TiledLinear,
# perhaps this should be implemented as a custom getter (see
# tf.get_variable) instead of being tied to tiling.
class OverlaidTiledLinear(TiledLinear):
"""Tiled mapping with weight sharing and low-rank overlays.
To reduce the number of parameters, one may want to share weight
matrices. This class makes that sharing possible in the form of W_1
= s_1*W + a_1*b_1 and W_2 = s_2*W + a_2*b_2 where the s are scalars,
and a*b are low-rank matrices.
`overlay_sharing_key` controls which tiles share the same underlying
weight matrix. Generally, tiles with the same sharing key and 2D
shape. There are two special key values: `':name:'` and `':shape:'`
that get substituted with the name and shape of the actual tile,
respectively.
For example, if an LSTM cell maps inputs ('x', 'h') to ('f, 'i, 'j',
'o'), then the following makes all weight matrices from the input
'x' to any of the gates or the candidate update share the underlying
full rank weight matrix.
var_init_params=OrderedDict([
('W_x_i', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': 16}),
('W_x_j', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': 10}),
('W_x_f', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': 8}),
('W_x_o', {'overlay_sharing_key': 'W_x_any',
'overlay_rank': 11}),
])
That is, W_x_i = s_W_x_i * W_x_any + a_W_x_i * b_W_x_i where 's_' is
a scalar, and 'a_', 'b_' are of shape [N, 16], [16, N] respectively.
W_x_j and the other are computed similarly by adding a low-rank
overlay ('a_'*'b_') on top of a shared weight matrix ('W_x_any').
"""
def __init__(self, *args, **kwargs):
super(OverlaidTiledLinear, self).__init__(*args, **kwargs)
self._matrix_cache = {}
def _get_variable(self, name, shape,
default_initializer=None, default_partitioner=None,
default_regularizer=None):
if len(shape) != 2:
return super(OverlaidTiledLinear, self)._get_variable(
name, shape, default_initializer=default_initializer,
default_partitioner=default_partitioner,
default_regularizer=default_regularizer)
else:
rank = self._find_var_init_param(name, 'overlay_rank', 0)
sharing_key = self._find_var_init_param(name, 'overlay_sharing_key',
':name:')
if sharing_key == ':name:':
sharing_key = name
if sharing_key == ':shape:':
sharing_key = shape
if (sharing_key in self._matrix_cache and
not tf.get_variable_scope().reuse):
scaler = super(OverlaidTiledLinear, self)._get_variable(
's_'+name, [shape[1]], default_initializer=tf.ones_initializer())
base = scaler*self._matrix_cache[sharing_key]
else:
base = super(OverlaidTiledLinear, self)._get_variable(
sharing_key, shape, default_initializer=default_initializer,
default_partitioner=default_partitioner,
default_regularizer=default_regularizer)
self._matrix_cache[sharing_key] = base
if rank == 0:
return base
else:
overlay = self._low_rank_matrix(name, rank=rank, shape=shape)
return base+overlay
def _low_rank_matrix(self, name, rank=None, shape=None,
initializer=None, trainable=True):
assert len(shape) == 2
a = super(OverlaidTiledLinear, self)._get_variable(
'a_'+name, [shape[0], rank], default_initializer=initializer)
b = super(OverlaidTiledLinear, self)._get_variable(
'b_'+name, [rank, shape[1]], default_initializer=initializer)
return tf.matmul(a, b)
def valid_var_init_param_keys(self):
return (super(OverlaidTiledLinear, self).valid_var_init_param_keys() +
['overlay_sharing_key', 'overlay_rank'])
| lamb-master | lamb/tiled_linear.py |
# Copyright 2018 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.
# ============================================================================
"""Various utility functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import random
import re
from absl import logging
import numpy as np
import six
import tensorflow.compat.v1 as tf
from tensorflow.contrib import framework as contrib_framework
nest = contrib_framework.nest
def ensure_list(x):
return [x] if not isinstance(x, list) else x
def linear(args, output_size, bias, bias_start=0.0, initializer=None,
scope=None):
with tf.variable_scope(scope or 'linear', initializer=initializer):
return _linear(args, output_size, bias, bias_start)
_BIAS_VARIABLE_NAME = 'bias'
_WEIGHTS_VARIABLE_NAME = 'kernel'
def _linear(args, output_size, bias, bias_start=0.0):
"""Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.
Args:
args: a 2D Tensor or a list of 2D, batch x n, Tensors.
output_size: int, second dimension of W[i].
bias: boolean, whether to add a bias term or not.
bias_start: starting value to initialize the bias; 0 by default.
Returns:
A 2D Tensor with shape [batch x output_size] equal to
sum_i(args[i] * W[i]), where W[i]s are newly created matrices.
Raises:
ValueError: if some of the arguments has unspecified or wrong shape.
"""
if args is None or (nest.is_sequence(args) and not args):
raise ValueError('`args` must be specified')
if not nest.is_sequence(args):
args = [args]
# Calculate the total size of arguments on dimension 1.
total_arg_size = 0
shapes = [a.get_shape() for a in args]
for shape in shapes:
if shape.ndims != 2:
raise ValueError('linear is expecting 2D arguments: %s' % shapes)
if shape[1].value is None:
raise ValueError('linear expects shape[1] to be provided for shape %s, '
'but saw %s' % (shape, shape[1]))
else:
total_arg_size += shape[1].value
dtype = [a.dtype for a in args][0]
# Now the computation.
scope = tf.get_variable_scope()
with tf.variable_scope(scope) as outer_scope:
weights = tf.get_variable(
_WEIGHTS_VARIABLE_NAME, [total_arg_size, output_size], dtype=dtype)
if len(args) == 1:
res = tf.matmul(args[0], weights)
else:
res = tf.matmul(tf.concat(args, 1), weights)
if not bias:
return res
with tf.variable_scope(outer_scope) as inner_scope:
inner_scope.set_partitioner(None)
biases = tf.get_variable(
_BIAS_VARIABLE_NAME, [output_size],
dtype=dtype,
initializer=tf.constant_initializer(bias_start, dtype=dtype))
return tf.add(res, biases)
def _find_var_init_param(var_init_params, var_name, key, default):
if var_init_params is not None:
for pattern in var_init_params:
if re.match(pattern, var_name):
value = var_init_params[pattern].get(key, None)
if value is not None:
return value
return default
def find_initializer(var_init_params, name, default_initializer):
return _find_var_init_param(var_init_params, name, 'initializer',
default_initializer)
def linear_v2(args, output_size, bias, rank=None, scope=None, # pylint: disable=missing-docstring
weight_name=_WEIGHTS_VARIABLE_NAME,
bias_name=_BIAS_VARIABLE_NAME,
var_init_params=None):
with tf.variable_scope(scope or 'linear_v2'):
if args is None or (nest.is_sequence(args) and not args):
raise ValueError('`args` must be specified')
if not nest.is_sequence(args):
args = [args]
# Calculate the total size of arguments on dimension 1.
total_arg_size = 0
shapes = [a.get_shape() for a in args]
for shape in shapes:
if shape.ndims != 2:
raise ValueError('linear is expecting 2D arguments: %s' % shapes)
if shape[1].value is None:
raise ValueError('linear expects shape[1] to be provided for shape %s, '
'but saw %s' % (shape, shape[1]))
else:
total_arg_size += shape[1].value
dtype = [a.dtype for a in args][0]
# Now the computation.
scope = tf.get_variable_scope()
with tf.variable_scope(scope) as outer_scope:
if rank is not None:
if isinstance(rank, float):
rank = int(min(total_arg_size, output_size)*rank)
if rank == 0:
rank = 1
if rank >= min(total_arg_size, output_size):
rank = None
if rank is None:
weights_initializer = find_initializer(
var_init_params, weight_name, None)
weights = tf.get_variable(
weight_name, [total_arg_size, output_size], dtype=dtype,
initializer=weights_initializer)
if len(args) == 1:
res = tf.matmul(args[0], weights)
else:
res = tf.matmul(tf.concat(args, 1), weights)
else:
left, right = low_rank_factorization(
weight_name, [total_arg_size, output_size], rank)
if len(args) == 1:
res = tf.matmul(tf.matmul(args[0], left), right)
else:
res = tf.matmul(tf.matmul(tf.concat(args, 1), left), right)
if not bias:
return res
with tf.variable_scope(outer_scope) as inner_scope:
inner_scope.set_partitioner(None)
bias_initializer = find_initializer(var_init_params, bias_name, None)
biases = tf.get_variable(bias_name, [output_size], dtype=dtype,
initializer=bias_initializer)
return tf.add(res, biases)
def layer_norm(x, reduction_indices, epsilon=1e-9, gain=None, bias=None,
per_element=True, scope=None):
"""DOC."""
reduction_indices = ensure_list(reduction_indices)
mean = tf.reduce_mean(x, reduction_indices, keep_dims=True)
variance = tf.reduce_mean(tf.squared_difference(x, mean),
reduction_indices, keep_dims=True)
normalized = (x - mean) / tf.sqrt(variance + epsilon)
dtype = x.dtype
shape = x.get_shape().as_list()
for i in six.moves.range(len(shape)):
if i not in reduction_indices or not per_element:
shape[i] = 1
with tf.variable_scope(scope or 'layer_norm'):
if gain is None:
gain = tf.get_variable('gain', shape=shape, dtype=dtype,
initializer=tf.ones_initializer())
if bias is None:
bias = tf.get_variable('bias', shape=shape, dtype=dtype,
initializer=tf.zeros_initializer())
return gain*normalized+bias
def get_sparse_variable(name, indices, shape, dtype=None, trainable=True,
initializer=None, partitioner=None, regularizer=None):
n = len(indices)
values = tf.get_variable(name, [n], dtype=dtype,
initializer=initializer, partitioner=partitioner,
regularizer=regularizer, trainable=trainable)
return tf.sparse_reorder(
tf.SparseTensor(indices=indices, values=values, dense_shape=shape))
def _random_index(shape):
if len(shape) == 0: # pylint: disable=g-explicit-length-test
return ()
else:
return (random.randrange(shape[0]),) + _random_index(shape[1:])
def _all_indices(shape): # pylint: disable=missing-docstring
indices = []
n = len(shape)
def add_indices(shape, depth, index):
if depth == n:
indices.append(index)
else:
for i in six.moves.range(shape[depth]):
add_indices(shape, depth+1, index + [i])
add_indices(shape, 0, [])
return indices
def sparse_random_indices(ratio, shape):
"""DOC."""
assert 0 < ratio and ratio <= 1.0
n = round_to_int(tf.TensorShape(shape).num_elements()*ratio)
# There are two implementations. The first generates random indices
# and wastes computation due to collisions, and the second wastes
# memory.
if ratio < 0.25:
indices = {}
if isinstance(shape, tf.TensorShape):
shape = shape.as_list()
while len(indices) < n:
index = _random_index(shape)
indices[index] = True
return indices.keys()
else:
indices = _all_indices(shape)
random.shuffle(indices)
return indices[:n]
def get_optimizer(optimizer_type):
"""Returns an optimizer builder.
Args:
optimizer_type: Short-form name of optimizer. Must be one of adadelta,
adagrad, adam, rmsprop, sgd.
Returns:
A function of two arguments:
- learning rate (tensor-like)
- a tf.HParams object from which hyperparamters for optimization
are extracted. Adam for example, extracts values of
`adam_beta1`, `adam_beta2` and `adam_epsilon` from HParams.
HParams doesn't need to have all listed keys.
"""
fixed_args = {}
keys = []
prefix = optimizer_type
if optimizer_type == 'adadelta':
opt_func = tf.train.AdadeltaOptimizer
elif optimizer_type == 'adagrad':
opt_func = tf.train.AdagradOptimizer
elif optimizer_type == 'adam':
opt_func = tf.train.AdamOptimizer
keys = ('beta1', 'beta2', 'epsilon')
elif optimizer_type == 'rmsprop':
opt_func = tf.train.AdamOptimizer
fixed_args = {'beta1': 0.0}
keys = ('beta2', 'epsilon')
elif optimizer_type == 'sgd':
opt_func = tf.train.GradientDescentOptimizer
else:
assert False
logging.info('%s optimisation.', prefix)
def build(learning_rate, config):
args = _extract_dict_from_config(config, prefix + '_', keys)
logging.info('%s hyperparameters: %r', prefix, args)
return opt_func(learning_rate, **dict(args, **fixed_args))
return build
def _extract_dict_from_config(config, prefix, keys):
"""Return a subset of key/value pairs from `config` as a dict.
Args:
config: A Config object.
prefix: A string to which `keys` are added to form keys in `config`.
keys: The potential keys in the resulting dict.
Returns:
A dict with `key`/`value` pairs where `prefix + key` has value
`value` in `config`.
"""
subset = {}
for key in keys:
config_key = prefix + key
subset[key] = config[config_key]
return subset
def repeat(iterable, n):
"""Repeats each element in iterable n times.
Args:
iterable: an iterable with elements to repeat.
n: number of repetitions.
Yields:
Elements from `iterable` each repeated `n` times.
"""
for e in iterable:
for _ in range(n):
yield e
def is_var_in_scope(var, scopes):
for scope in ensure_list(scopes):
# pylint: disable=g-explicit-bool-comparison
if var.name.startswith(scope + '/') or var.name == scope or scope == '':
return True
return False
def trainable_vars_in_scope(name):
"""Return a list of variables in scope `name`.
Args:
name: The name of the scope without the trailing '/'.
Returns:
A list of tf.Variables in the scope.
"""
vars_ = []
for var in tf.trainable_variables():
if is_var_in_scope(var, name):
vars_.append(var)
return vars_
def find_var(name, vars_=None):
"""Find a variable by name or return None.
Args:
name: The name of the variable (full qualified with all
enclosing scopes).
vars_: The variables among which to search. Defaults to all
trainable variables.
Returns:
The [first] variable with `name` among `vars_` or None if there
is no match.
"""
if vars_ is None:
vars_ = tf.trainable_variables()
return next((var for var in vars_ if var.name == name),
None)
def group_vars_by_scope(scopes, vars_=None, log=False):
"""Return a scope to list of vars in that scope map as a dict.
Args:
scopes: A sequence of scope names without the trailing '/'.
vars_: The variables among which to search. Defaults to all
trainable variables.
log: Whether to log matching and ummatching variables
Returns:
A dictionary that maps a scope to variables among `vars_` in that
scope. As the second value return all variables that were in none
of `scopes`.
"""
if vars_ is None:
vars_ = tf.trainable_variables()
var_groups = {}
unmatched_vars = []
for var in vars_:
for scope in scopes:
if is_var_in_scope(var, scope):
if scope not in var_groups:
var_groups[scope] = []
var_groups[scope].append(var)
if log:
logging.info('%s -- %s', scope, var.name[len(scope):])
break
else:
logging.info('-- %s', var.name)
unmatched_vars.append(var)
return var_groups, unmatched_vars
def _order_grouped_vars(var_groups):
# pylint: disable=g-complex-comprehension
return [var for scope in sorted(var_groups.keys())
for var in var_groups[scope]]
def gradients_for_var_group(var_groups, gradients, name):
"""Returns a slice of `gradients` belonging to the var group `name`."""
start = 0
for group_name in sorted(var_groups.keys()):
n = len(var_groups[group_name])
if group_name == name:
return gradients[start:start+n]
start += n
return []
def trainable_initial_state(batch_size, state_size, initial_state_init=None):
"""Make trainable initial state for an RNN cell with `state_size`."""
def create_one(i, size):
if initial_state_init is not None:
initializer = initial_state_init
else:
initializer = tf.truncated_normal_initializer(mean=0.0, stddev=1)
return get_batched_variable(
'initial_state_t{}'.format(i), batch_size, size,
initializer=initializer)
flat_vars = [create_one(i, size)
for i, size in enumerate(nest.flatten(state_size))]
return nest.pack_sequence_as(state_size, flat_vars)
def map_nested(fn, x):
return nest.pack_sequence_as(x, list(map(fn, nest.flatten(x))))
def create_grads(optimizer, loss, scopes, num_expected_missing_gradients=0):
"""Compute, apply gradients and add summaries for norms."""
logging.info('Creating gradient updates for scopes %r', scopes)
grouped_vars, _ = group_vars_by_scope(scopes, log=True)
ordered_vars = _order_grouped_vars(grouped_vars)
grads_and_vars = optimizer.compute_gradients(
loss, ordered_vars,
aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)
grads, _ = zip(*grads_and_vars)
num_missing_grads = sum(grad is None for grad in grads)
# Check that the gradient flow is not broken inadvertently. All
# trainable variables should have gradients.
if num_missing_grads > 0:
for grad, var in grads_and_vars:
if grad is None:
logging.info('NO GRADIENT for var %s', var.name)
else:
logging.info('Gradients found for %s', var.name)
assert num_missing_grads <= num_expected_missing_gradients, (
'%s variables have no gradients. Expected at most %s.' %
(num_missing_grads, num_expected_missing_gradients))
summaries = []
for grad, var in grads_and_vars:
summaries.append(
tf.summary.scalar(escape_summary_name(var.name + '_grad_norm'),
tf.norm(grad)))
return grads_and_vars, summaries
def clip_gradients_in_scope(grads_and_vars, scope, max_grad_norm):
"""DOC."""
if max_grad_norm == 0:
return grads_and_vars
else:
grads_in_scope = []
vars_in_scope = []
for grad, var in grads_and_vars:
if is_var_in_scope(var, scope):
grads_in_scope.append(grad)
vars_in_scope.append(var)
clipped_grads_in_scope, _ = tf.clip_by_global_norm(
grads_in_scope, max_grad_norm)
new_grads_and_vars = []
for grad, var in grads_and_vars:
if vars_in_scope and var is vars_in_scope[0]:
new_grads_and_vars.append((clipped_grads_in_scope.pop(0),
vars_in_scope.pop(0)))
else:
new_grads_and_vars.append((grad, var))
return new_grads_and_vars
def cv_splits(seq, k=10):
"""Split `seq` into `k` folds for cross-validation.
Args:
seq: A sequence of arbitrary elements.
k: Positive integer. The number of folds.
Yields:
`k` (training, validation) elements. The validation component of
each tuple is a subset of `seq` of length len(seq)/k (modulo
rounding) while training has all remaining elements from `seq`.
The validation sequences together form a segmentation of `seq`.
Note that `seq` is shuffled before the splitting.
"""
seq = list(seq)
random.shuffle(seq)
n = len(seq)
m = float(n) / k
start = 0
for i in six.moves.range(k):
if i == k -1:
end = n
else:
end = int((i+1) * m)
yield seq[:start] + seq[end:], seq[start:end]
start = end
def escape_summary_name(name):
return name.replace(':', '_')
def summaries_for_trainables():
summaries = []
for var in tf.trainable_variables():
name = escape_summary_name(var.name)
mean = tf.reduce_mean([var])
summaries.append(tf.summary.scalar(name + '_mean', mean))
summaries.append(tf.summary.scalar(name + '_var',
tf.reduce_mean(tf.square([var-mean]))))
return summaries
def log_scalar_summaries(summary_proto):
summary = tf.Summary()
summary.ParseFromString(summary_proto)
for value in summary.value:
logging.info('%s: %s', value.tag, value.simple_value)
def count_trainables(scopes=('',)):
total = 0
for scope in scopes:
n = 0
for var in trainable_vars_in_scope(scope):
shape = var.get_shape()
n += shape.num_elements()
total += n
return total
def log_trainables(scopes=('',)):
""""Log number of trainable parameters for each scope in `scopes`.
Args:
scopes: A sequence of scope names.
Returns:
The total number of trainable parameters over all scopes in
`scopes`. Possibly counting some parameters multiple times if the
scopes are nested.
"""
total = 0
for scope in scopes:
logging.info('Trainables in scope "%s":', scope)
n = 0
for var in trainable_vars_in_scope(scope):
shape = var.get_shape()
logging.info('trainable: %s shape %r (%r)', var.name, shape.as_list(),
shape.num_elements())
n += shape.num_elements()
logging.info('Number of parameters in scope "%s": %r', scope, n)
total += n
return total
def round_to_int(x):
return int(round(x))
# tf.orthogonal_initializer is not stable numerically on some machines
# (gpus?).
def orthogonal_initializer(gain=1.0, dtype=tf.float32):
"""Generates orthonormal matrices with random values.
Orthonormal initialization is important for RNNs:
http://arxiv.org/abs/1312.6120
http://smerity.com/articles/2016/orthogonal_init.html
For non-square shapes the returned matrix will be semi-orthonormal: if the
number of columns exceeds the number of rows, then the rows are orthonormal
vectors; but if the number of rows exceeds the number of columns, then the
columns are orthonormal vectors.
We use SVD decomposition to generate an orthonormal matrix with random values.
The same way as it is done in the Lasagne library for Theano. Note that both
u and v returned by the svd are orthogonal and random. We just need to pick
one with the right shape.
Args:
gain: A scalar with which the orthonormal tensor will be
multiplied unless overridden at initialization time. The rule of
thumb is 1.0 for weights before sigmoid activations, and sqrt(2)
before RELUs, but tuning this might be required.
dtype: a dtype of the intialized tensor.
Returns:
An initializer that generates random orthogonal matrices.
"""
def initialize(shape, dtype=dtype, partition_info=None, gain=gain):
partition_info = partition_info
flat_shape = (shape[0], np.prod(shape[1:]))
w = np.random.randn(*flat_shape)
u, _, v = np.linalg.svd(w, full_matrices=False)
w = u if u.shape == flat_shape else v
return tf.constant(gain*w.reshape(shape), dtype=dtype)
return initialize
def random_mask(shape, k):
x = tf.random_normal(shape=shape)
kth_largest = tf.nn.top_k(x, k)[0][:, k-1]
return tf.to_float(tf.greater_equal(x, tf.expand_dims(kth_largest, 1)))
def random_mask2(shape, k):
x = tf.random_normal(shape=shape)
x = tf.transpose(x)
kth_largest = tf.nn.top_k(x, k)[0][:, k-1]
mask = tf.to_float(tf.greater_equal(x, tf.expand_dims(kth_largest, 1)))
return tf.transpose(mask)
def make_low_rank_factorization_initializer(shape, rank):
fan_in = int(shape[0])
# This is the variance we'd like to see if a matrix of 'shape' was
# initialized directly.
variance = 1.0 / fan_in
# Each element of a*b (the low rank matrices) is the sum of 'rank'
# terms, each of which is a product of an element from 'a' and
# 'b'.
stddev = np.sqrt(np.sqrt(variance / rank))
return tf.initializers.truncated_normal(stddev=stddev)
def low_rank_factorization(name, shape, rank, initializer=None,
trainable=True, collections=None):
# pylint: disable=missing-docstring
if initializer is None:
initializer = make_low_rank_factorization_initializer(shape, rank)
a = tf.get_variable(
name + '_a', [shape[0], rank],
initializer=initializer, trainable=trainable, collections=collections)
b = tf.get_variable(
name + '_b', [rank, shape[1]],
initializer=initializer, trainable=trainable, collections=collections)
return a, b
class TFSerializer(object):
"""Serialize python object into a tf string variable."""
def __init__(self, name='serialized', initializer='{}'):
self._string = tf.get_variable(
name, dtype=tf.string, trainable=False, initializer=initializer)
self._new_string = tf.placeholder(dtype=tf.string, shape=[])
self._assign_op = tf.assign(self._string, self._new_string)
def store(self, obj):
tf.get_default_session().run(self._assign_op,
feed_dict={self._new_string: str(obj)})
def retrieve(self):
# pylint: disable=eval-used
return eval(tf.get_default_session().run(self._string))
def variables(self):
return [self._string]
def mixture_of_softmaxes(x, k, e, to_logits):
"""A slower, but supposedly more flexible softmax.
See "Breaking the Softmax Bottleneck: A High-Rank RNN Language Model"
by Yang et al, 2017.
Args:
x: A 2d tensor of shape [b, *]. Typically the output of an RNN cell.
k: The number of mixture components.
e: The embedding size. Often the same as the second dimension of x.
to_logits: A function that takes a [b*k, e] tensor as its argument and
transforms it into shape [b*k, v] where v is the vocabulary size.
Returns:
A [b, v] tensor of log probabilities. Each element is computed from
the mixture of the k components. The components share most of the
parameters (i.e. those in to_logits), but they have a smaller number
of non-shared parameters (those in the projections).
"""
# TODO(melisgl): For training where the entire output distribution is not
# needed, maybe sparse_softmax_cross_entropy_with_logits would be more
# efficient.
if True: # pylint: disable=using-constant-test
# This log-domain implementation seems preferrable, but it uses much more
# memory for some reason.
b = tf.shape(x)[0]
p_b_ke = tf.tanh(linear(x, k*e, True, scope='projection'))
p_bk_e = tf.reshape(p_b_ke, [b*k, e])
log_mixture_weights_b_k = tf.nn.log_softmax(
linear(x, k, False, scope='mos_weights'))
log_mixture_weights_b_k_1 = tf.reshape(log_mixture_weights_b_k, [b, k, 1])
logits_bk_v = to_logits(p_bk_e)
logprobs_bk_v = tf.nn.log_softmax(logits_bk_v)
logprobs_b_k_v = tf.reshape(logprobs_bk_v, [b, k, -1])
logprobs_b_v = tf.reduce_logsumexp(
logprobs_b_k_v + log_mixture_weights_b_k_1,
axis=1)
return logprobs_b_v
else:
# Alternatively, calculate with probabilities directly.
b = tf.shape(x)[0]
p_b_ke = tf.tanh(linear(x, k*e, True, scope='projection'))
p_bk_e = tf.reshape(p_b_ke, [b*k, e])
mixture_weights_b_k = tf.nn.softmax(
linear(x, k, False, scope='mos_weights'))
mixture_weights_b_k_1 = tf.reshape(mixture_weights_b_k, [b, k, 1])
logits_bk_v = to_logits(p_bk_e)
probs_bk_v = tf.nn.softmax(logits_bk_v)
probs_b_k_v = tf.reshape(probs_bk_v, [b, k, -1])
probs_b_v = tf.reduce_sum(
probs_b_k_v * mixture_weights_b_k_1,
axis=1)
return tf.log(probs_b_v+1e-8)
def expand_tile(tensor, n, name=None):
"""Returns a tensor repeated n times along a newly added first dimension."""
with tf.name_scope(name, 'expand_tile'):
n_ = tf.reshape(n, [1])
num_dims = len(tensor.get_shape().as_list())
multiples = tf.concat([n_, tf.ones([num_dims], dtype=tf.int32)], axis=0)
# multiples = [n, 1, 1, ..., 1]
res = tf.tile(tf.expand_dims(tensor, 0), multiples)
first_dim = None
if isinstance(n, int):
first_dim = n
res.set_shape([first_dim] + tensor.get_shape().as_list())
return res
def get_batched_variable(name, runtime_batch_size, shape=None,
dtype=tf.float32, initializer=None,
trainable=True):
"""Returns a new variable tensor tiled runtime_batch_size number of times.
Args:
name: name for the new variable.
runtime_batch_size: number of times to repeat the new variable along the
first dimentsion.
shape: shape of the new variable (e.g. [size] for [runtime_batch_size, size]
output).
dtype: type of the new variable to repeat.
initializer: initializer for the variable.
trainable: whether the new variable is trainable.
Returns:
A Tensor with variable of shape `shape` repeated `runtime_batch_size` times
along added first dimension.
"""
if initializer is None:
initializer = tf.zeros_initializer(dtype=dtype)
# If we're initializing from a constant then get_variable want a None shape.
shape = None if isinstance(initializer, tf.Tensor) else shape
var = tf.get_variable(name, shape=shape, dtype=dtype,
initializer=initializer, trainable=trainable)
return expand_tile(var, runtime_batch_size)
# We should eventually merge mask_from_lengths and create_mask.
# mask_from_lengths is more robust since shapes only need to be known at runtime
# NB: create_mask is time major, whereas mask_from_lengths is batch major
def create_mask(lengths, max_length):
"""Created a mask of shape [time, batch_size] to mask out padding."""
return tf.less(tf.reshape(tf.range(max_length, dtype=lengths.dtype),
[-1, 1]),
tf.reshape(lengths, [1, -1]))
def mask_from_lengths(lengths, max_length=None, dtype=None, name=None):
"""Convert a length scalar to a vector of binary masks.
This function will convert a vector of lengths to a matrix of binary masks.
E.g. [2, 4, 3] will become [[1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 0]]
Args:
lengths: a d-dimensional vector of integers corresponding to lengths.
max_length: an optional (default: None) scalar-like or 0-dimensional tensor
indicating the maximum length of the masks. If not provided, the maximum
length will be inferred from the lengths vector.
dtype: the dtype of the returned mask, if specified. If None, the dtype of
the lengths will be used.
name: a name for the operation (optional).
Returns:
A d x max_length tensor of binary masks (int32).
"""
with tf.name_scope(name, 'mask_from_lengths'):
dtype = lengths.dtype if dtype is None else dtype
max_length = tf.reduce_max(lengths) if max_length is None else max_length
indexes = tf.range(max_length, dtype=lengths.dtype)
mask = tf.less(tf.expand_dims(indexes, 0), tf.expand_dims(lengths, 1))
cast_mask = tf.cast(mask, dtype)
return tf.stop_gradient(cast_mask)
def compute_lengths(symbols_list, eos_symbol, name=None,
dtype=tf.int64):
"""Computes sequence lengths given end-of-sequence symbol.
Args:
symbols_list: list of [batch_size] tensors of symbols (e.g. integers).
eos_symbol: end of sequence symbol (e.g. integer).
name: name for the name scope of this op.
dtype: type of symbols, default: tf.int64.
Returns:
Tensor [batch_size] of lengths of sequences.
"""
with tf.name_scope(name, 'compute_lengths'):
max_len = len(symbols_list)
eos_symbol_ = tf.constant(eos_symbol, dtype=dtype)
# Array with max_len-time where we have EOS, 0 otherwise. Maximum of this is
# the first EOS in that example.
ends = [tf.constant(max_len - i, dtype=tf.int64)
* tf.to_int64(tf.equal(s, eos_symbol_))
for i, s in enumerate(symbols_list)]
# Lengths of sequences, or max_len for sequences that didn't have EOS.
# Note: examples that don't have EOS will have max value of 0 and value of
# max_len+1 in lens_.
lens_ = max_len + 1 - tf.reduce_max(tf.stack(ends, 1), axis=1)
# For examples that didn't have EOS decrease max_len+1 to max_len as the
# length.
lens = tf.subtract(lens_, tf.to_int64(tf.equal(lens_, max_len + 1)))
return tf.stop_gradient(tf.reshape(lens, [-1]))
def seq_softmax_cross_entropy_with_logits(logits, labels, lengths,
max_length=None, reduce_sum=True,
name=None):
"""Softmax cross-entropy for a batch of sequences of varying lengths.
The logits and labels arguments are similar to those of
sparse_softmax_cross_entropy_with_logits with different shape
requirements.
Args:
logits: Unscaled log probabilites of shape [time, batch, num_classes].
labels: Indices of the true classes of shape [time, batch] and dtype
int32 or int64.
lengths: [batch], dtype int32 or int64
max_length: Scalar integer. The time dimension in the above.
Inferred if possible.
reduce_sum: Whether to sum the cross entropy terms.
name: name for the name scope of this op.
Returns:
The cross-entropy loss. If `reduce_sum`, then the shape is
[batch], else it's the same shape as `labels`.
"""
with tf.name_scope(name, 'seq_softmax_cross_entropy_with_logits',
[logits, labels, lengths, max_length]):
mask = create_mask(lengths, max_length)
# TODO(melisgl): Maybe call softmax_cross_entropy_with_logits
# if the dtype of labels is non-integer.
xe_terms = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
masked_xe_terms = xe_terms * tf.cast(mask, xe_terms.dtype)
if reduce_sum:
return tf.reduce_sum(masked_xe_terms, axis=0)
else:
return masked_xe_terms
def variance_scaling_initializer(scale=2.0, mode='fan_in',
distribution='truncated_normal',
mean=0.0, seed=None, dtype=tf.float32):
"""Like tf.variance_scaling_initializer but supports non-zero means."""
if not dtype.is_floating:
raise TypeError('Cannot create initializer for non-floating point type.')
if mode not in ['fan_in', 'fan_out', 'fan_avg']:
raise TypeError('Unknown mode %s [fan_in, fan_out, fan_avg]' % mode)
# pylint: disable=unused-argument
def _initializer(shape, dtype=dtype, partition_info=None):
"""Initializer function."""
if not dtype.is_floating:
raise TypeError('Cannot create initializer for non-floating point type.')
# Estimating fan_in and fan_out is not possible to do perfectly, but we try.
# This is the right thing for matrix multiply and convolutions.
if shape:
fan_in = float(shape[-2]) if len(shape) > 1 else float(shape[-1])
fan_out = float(shape[-1])
else:
fan_in = 1.0
fan_out = 1.0
for dim in shape[:-2]:
fan_in *= float(dim)
fan_out *= float(dim)
if mode == 'fan_in':
# Count only number of input connections.
n = fan_in
elif mode == 'fan_out':
# Count only number of output connections.
n = fan_out
elif mode == 'fan_avg':
# Average number of inputs and output connections.
n = (fan_in + fan_out) / 2.0
if distribution == 'truncated_normal':
# To get stddev = math.sqrt(scale / n) need to adjust for truncated.
trunc_stddev = math.sqrt(1.3 * scale / n)
return tf.truncated_normal(shape, mean, trunc_stddev, dtype, seed=seed)
elif distribution == 'uniform':
# To get stddev = math.sqrt(scale / n) need to adjust for uniform.
limit = math.sqrt(3.0 * scale / n)
return tf.random_uniform(shape, mean-limit, mean+limit, dtype, seed=seed)
else:
assert 'Unexpected distribution %s.' % distribution
# pylint: enable=unused-argument
return _initializer
class FNCell(tf.nn.rnn_cell.RNNCell):
"""Dummy cell with no state that transforms its input with a function."""
def __init__(self, fn, output_size, reuse=None):
super(FNCell, self).__init__(_reuse=reuse)
if output_size < 1:
raise ValueError('Parameter output_size must be > 0: %d.' % output_size)
self._fn = fn
self._output_size = output_size
@property
def state_size(self):
return 1
@property
def output_size(self):
return self._output_size
def zero_state(self, batch_size, dtype):
with tf.name_scope(type(self).__name__ + 'ZeroState', values=[batch_size]):
return tf.zeros([batch_size, 1], dtype)
def call(self, inputs, state):
return self._fn(inputs), state
| lamb-master | lamb/utils.py |
# Copyright 2018 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A simple language model."""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
from absl import logging
from lamb import utils
from lamb.cell import build_cell
from lamb.dropout import Dropout
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
class LM(object):
"""A language model."""
def __init__(self, config, _model_only=False):
"""A language model.
Args:
config: A dictionary with the configuration options (see README.md).
_model_only: For internal use only.
"""
if not _model_only:
logging.info('Finalized parameters to follow.')
logging.info('%s', str(config))
logging.info('Building model.')
self._build_model(config)
logging.info('Building loss.')
self._build_loss(config)
self._check_budget(config)
self.config = config
else:
self._build_model(config)
@staticmethod
def num_params(config):
g = tf.Graph()
with g.as_default() as g:
# Speed graph creation up by only expanding the RNN to one step. This
# graph will be discarded anyway.
config.max_time_steps = 1
try:
LM(config, _model_only=True)
except (tf.errors.ResourceExhaustedError,
# Some OOM conditions turn into internal errors.
tf.errors.InternalError):
return None
n = utils.count_trainables()
return n
def _build_model(self, config):
self.global_step_var = tf.Variable(
tf.zeros([], tf.int64), name='global_step', trainable=False)
self.learning_rate = tf.placeholder(
tf.float32, shape=[], name='learning_rate')
## Input variables
self.num_samples = tf.placeholder_with_default(
1, shape=[], name='num_samples')
# For MT, this is the source language text. For LM, this is not used.
if config.conditioning_separator:
assert config.episodic, 'conditioning and non-episodic do not mix.'
self.conditioning = tf.placeholder(
dtype=tf.int64, shape=[config.max_time_steps, None],
name='conditioning')
self.conditioning_len = tf.placeholder(dtype=tf.int64, shape=[None],
name='conditioning_len')
# For plain LM, this is the input text. For MT this is the target language
# text.
self.source = tf.placeholder(
dtype=tf.int64, shape=[config.max_time_steps, None], name='source')
self.source_len = tf.placeholder(dtype=tf.int64, shape=[None],
name='source_len')
# This is the ground truth text to be predicted. A shifted by one version
# version of self.source.
self.target = tf.placeholder(
dtype=tf.int64, shape=[config.max_time_steps, None], name='target')
def maybe_create_dropout_placeholder(configured_dropout_rate, name):
if configured_dropout_rate > 0.0:
return tf.placeholder(tf.float32, shape=[], name=name)
else:
return None
self.embedding_dropout = maybe_create_dropout_placeholder(
config.embedding_dropout, 'embedding_dropout')
self.token_dropout = maybe_create_dropout_placeholder(
config.token_dropout, 'token_dropout')
self.input_dropout = maybe_create_dropout_placeholder(
config.input_dropout, 'input_dropout')
self.inter_layer_dropout = maybe_create_dropout_placeholder(
config.inter_layer_dropout, 'inter_layer_dropout')
self.update_dropout = maybe_create_dropout_placeholder(
config.update_dropout, 'update_dropout')
self.state_dropout = maybe_create_dropout_placeholder(
config.state_dropout, 'state_dropout')
self.flip_prob = maybe_create_dropout_placeholder(
config.state_dropout_flip_rate, 'flip_prob')
self.output_dropout = maybe_create_dropout_placeholder(
config.output_dropout, 'output_dropout')
self.downprojected_output_dropout = maybe_create_dropout_placeholder(
config.downprojected_output_dropout, 'downprojected_output_dropout')
self.softmax_temperature = tf.placeholder_with_default(
1.0, shape=[], name='softmax_temperature')
## Training
embedding_initializer = tf.variance_scaling_initializer(
scale=config.embedding_init_factor, mode='fan_out',
distribution='truncated_normal')
output_initializer = tf.variance_scaling_initializer(
scale=config.output_init_factor, mode='fan_in',
distribution='truncated_normal')
batch_size = tf.shape(self.source)[1]
last_hidden_size = utils.ensure_list(config.hidden_size)[-1]
tb_h = tf.stack([config.max_time_steps*batch_size, last_hidden_size])
t_b_v = tf.stack([config.max_time_steps, batch_size, config.vocab_size])
t_bk_o = tf.stack([
config.max_time_steps,
batch_size*(config.mos_num_components or 1),
config.output_embedding_size])
tbk_o = tf.stack([
config.max_time_steps*
batch_size*(config.mos_num_components or 1),
config.output_embedding_size])
t_b0_s_v = tf.stack(
[config.max_time_steps, tf.div(batch_size, self.num_samples),
self.num_samples, config.vocab_size])
if config.embed_once:
with tf.variable_scope('im', initializer=embedding_initializer):
embedding = tf.get_variable(
'embedding', [config.vocab_size, config.input_embedding_size],
initializer=embedding_initializer, dtype=tf.float32)
if self.embedding_dropout is not None:
embedding = tf.nn.dropout(
embedding, 1-self.embedding_dropout,
noise_shape=tf.stack([config.vocab_size, 1]))
embedded_source = tf.nn.embedding_lookup(embedding, self.source)
if self.token_dropout is not None:
embedding = tf.nn.dropout(
embedding, 1-self.token_dropout,
noise_shape=tf.stack([config.max_time_steps, batch_size, 1]))
if config.scale_input_embeddings:
embedded_source *= tf.sqrt(tf.cast(config.input_embedding_size,
tf.float32))
sources = embedded_source
else:
assert self.embedding_dropout is None, 'Not implemented.'
assert self.token_dropout is None, 'Not implemented.'
sources = self.source
def lm_1(cell, initial_state, inputs, input_lens, scope=None):
# According to tests (2019-03-13) swap_memory carries only a very penalty
# so we use it to choose between dynamic_rnn and static_rnn. For some
# reason, static_rnn can be 2x faster ... sometimes. On the other hand,
# dynamic_rnn handles memory better even without swap_memory=True.
if FLAGS.swap_memory:
return tf.nn.dynamic_rnn(cell=cell, inputs=inputs,
time_major=True,
sequence_length=input_lens,
initial_state=initial_state,
swap_memory=FLAGS.swap_memory,
dtype=tf.float32, scope=scope)
else:
return tf.nn.static_rnn(cell=cell, inputs=tf.unstack(inputs),
sequence_length=input_lens,
initial_state=initial_state,
dtype=tf.float32, scope=scope)
# This is for the config.output_once=True case.
def output_module_1(outputs):
with tf.variable_scope('om', initializer=output_initializer):
# Create the matrix and bias for the final projection into the softmax.
if config.share_input_and_output_embeddings:
assert config.embed_once, 'Not implemented.'
softmax_weights = embedding
softmax_weights_transpose = True
else:
softmax_weights = tf.get_variable(
'weights', [config.output_embedding_size, config.vocab_size],
dtype=tf.float32)
softmax_weights_transpose = False
softmax_bias = tf.get_variable('bias', [1, config.vocab_size],
initializer=tf.zeros_initializer(),
dtype=tf.float32)
def to_softmax(x, dropout=self.downprojected_output_dropout):
if dropout is not None:
if not config.shared_mask_dropout:
x = tf.nn.dropout(x, 1.0-dropout)
else:
x = tf.reshape(x, t_bk_o)
x = tf.nn.dropout(
x, 1.0-dropout,
# same mask for all time steps
noise_shape=[
1, batch_size*(config.mos_num_components or 1),
config.output_embedding_size])
x = tf.reshape(x, tbk_o)
return (
self.softmax_temperature*
(tf.matmul(x, softmax_weights,
transpose_b=softmax_weights_transpose) + softmax_bias))
last_hidden_size = utils.ensure_list(config.hidden_size)[-1]
outputs_t_b_h = tf.convert_to_tensor(outputs)
if self.output_dropout is not None:
if not config.shared_mask_dropout:
outputs_t_b_h = tf.nn.dropout(
outputs_t_b_h, 1.0-self.output_dropout)
else:
outputs_t_b_h = tf.nn.dropout(
outputs_t_b_h, 1.0-self.output_dropout,
noise_shape=[1, batch_size, last_hidden_size])
outputs_tb_h = tf.reshape(outputs_t_b_h, tb_h)
if config.mos_num_components == 0:
if config.output_embedding_size == last_hidden_size:
return (tf.reshape(to_softmax(outputs_tb_h, None), t_b_v),
outputs_t_b_h)
else:
downprojected_outputs_tb_o = utils.linear(
outputs_tb_h, config.output_embedding_size, False,
initializer=utils.orthogonal_initializer(), scope='projection')
logits_tb_v = to_softmax(downprojected_outputs_tb_o)
return tf.reshape(logits_tb_v, t_b_v), outputs_t_b_h
else:
logits_tb_v = utils.mixture_of_softmaxes(
outputs_tb_h, config.mos_num_components,
config.output_embedding_size, to_softmax)
return tf.reshape(logits_tb_v, t_b_v), outputs_t_b_h
# This is for the config.output_once=False case.
def output_module_per_step_1(outputs_b_h):
with tf.variable_scope('om', initializer=output_initializer):
def to_softmax(x, dropout=self.downprojected_output_dropout):
# Create the matrix and bias for the final projection into the
# softmax.
if config.share_input_and_output_embeddings:
assert config.embed_once, 'Not implemented.'
softmax_weights = embedding
softmax_weights_transpose = True
else:
softmax_weights = tf.get_variable(
'weights', [config.output_embedding_size, config.vocab_size],
dtype=tf.float32)
softmax_weights_transpose = False
softmax_bias = tf.get_variable('bias', [1, config.vocab_size],
initializer=tf.zeros_initializer(),
dtype=tf.float32)
if dropout is not None:
x = Dropout(1.0-dropout, share_mask=config.shared_mask_dropout)(x)
return (self.softmax_temperature *
(tf.matmul(x, softmax_weights,
transpose_b=softmax_weights_transpose) +
softmax_bias))
last_hidden_size = utils.ensure_list(config.hidden_size)[-1]
outputs_b_h = Dropout(1.0-self.output_dropout,
share_mask=self.output_dropout)(outputs_b_h)
if config.mos_num_components == 0:
if config.output_embedding_size == last_hidden_size:
return to_softmax(outputs_b_h, None)
else:
downprojected_outputs_b_o = utils.linear(
outputs_b_h, config.output_embedding_size, False,
initializer=utils.orthogonal_initializer(), scope='projection')
logits_b_v = to_softmax(downprojected_outputs_b_o)
return logits_b_v
else:
logits_b_v = utils.mixture_of_softmaxes(
outputs_b_h, config.mos_num_components,
config.output_embedding_size, to_softmax)
return logits_b_v
lm = tf.make_template('lm', lm_1)
def make_cell():
return build_cell(
model=config.model,
num_layers=config.num_layers,
hidden_size=config.hidden_size,
layer_norm=config.layer_norm,
cell_init_factor=config.cell_init_factor,
shared_mask_dropout=config.shared_mask_dropout,
input_dropout=self.input_dropout,
inter_layer_dropout=self.inter_layer_dropout,
state_dropout=self.state_dropout,
update_dropout=self.update_dropout,
state_dropout_flip_rate=self.flip_prob,
tie_forget_and_input_gates=config.tie_forget_and_input_gates,
cap_input_gate=config.cap_input_gate,
forget_bias=config.forget_bias,
feature_mask_rounds=config.feature_mask_rounds,
feature_mask_rank=config.feature_mask_rank,
overlay_rank=config.overlay_rank,
sparsity_ratio=config.sparsity_ratio,
cell_clip=config.cell_clip,
activation_fn=config.activation_fn,
lstm_skip_connection=config.lstm_skip_connection,
residual_connections=config.residual_connections)
def make_conditioning():
if config.embed_once:
with tf.variable_scope('cond_im', initializer=embedding_initializer):
embedding = tf.get_variable(
'embedding', [config.conditioning_vocab_size,
config.input_embedding_size],
initializer=embedding_initializer, dtype=tf.float32)
if self.embedding_dropout is not None:
embedding = tf.nn.dropout(
embedding, 1-self.embedding_dropout,
noise_shape=tf.stack([config.conditioning_vocab_size, 1]))
embedded_source = tf.nn.embedding_lookup(embedding, self.conditioning)
if self.token_dropout is not None:
embedding = tf.nn.dropout(
embedding, 1-self.token_dropout,
noise_shape=tf.stack([config.max_time_steps, batch_size, 1]))
if config.scale_input_embeddings:
embedded_source *= tf.sqrt(tf.cast(config.input_embedding_size,
tf.float32))
conditioning_sources = embedded_source
else:
assert False, 'Not implemented.'
conditioning_cell = make_cell()
conditioning_lm = tf.make_template('cond_lm', lm_1)
initial_state = conditioning_cell.zero_state(batch_size, dtype=tf.float32)
_, conditioning_last_state = conditioning_lm(
conditioning_cell, initial_state,
conditioning_sources, self.conditioning_len)
return conditioning_last_state
cell = make_cell()
if not config.embed_once:
cell = tf.nn.rnn_cell.EmbeddingWrapper(
cell, config.vocab_size, config.input_embedding_size,
initializer=embedding_initializer)
if config.conditioning_separator:
self.initial_state = make_conditioning()
elif config.trainable_initial_state:
with tf.variable_scope('lm_init'):
self.initial_state = utils.trainable_initial_state(
batch_size, cell.state_size)
else:
self.initial_state = cell.zero_state(batch_size, dtype=tf.float32)
outputs, self.last_state = lm(
cell, self.initial_state, sources, self.source_len)
self.cell_outputs = tf.convert_to_tensor(outputs)
if config.output_once:
output_module = tf.make_template('om', output_module_1)
logits_, self.dropped_cell_outputs = output_module(outputs)
else:
assert config.activation_norm_penalty == 0.0, (
'activation_norm_penalty not implemented for output_once=False.')
output_module_per_step = tf.make_template('om', output_module_per_step_1)
# KLUDGE: calling output_module_per_step here gets rid of the
# 'rnn/FNCell/' prefix on the variables names so output_once=False and
# output_once=True checkpoints are compatible.
output_module_per_step(outputs[0])
output_cell = utils.FNCell(output_module_per_step, config.vocab_size)
logits_, _ = tf.nn.dynamic_rnn(cell=output_cell,
inputs=tf.convert_to_tensor(outputs),
time_major=True,
sequence_length=self.source_len,
swap_memory=FLAGS.swap_memory,
dtype=tf.float32)
def average_samples():
# logits has shape t_b_v, where b=b0*num_samples. Separate out
# the samples in a new dimension.
logits = tf.reshape(logits_, t_b0_s_v)
if config.model_average == 'geometric':
x = tf.reduce_sum(logits, axis=2, keepdims=True)
elif config.model_average == 'arithmetic':
log_probs = tf.nn.log_softmax(logits)
x = tf.reduce_logsumexp(log_probs, axis=2, keepdims=True)
else:
assert False, 'Not implemented.'
# x is t_b0_1_v, tile it to t_b0_s_v.
x = tf.ones_like(logits) * x
return tf.reshape(x, t_b_v)
self.logits = tf.cond(tf.equal(self.num_samples, 1),
lambda: logits_,
average_samples)
def _build_loss(self, config):
# Single sample loss (in terms of num_training_samples)
self.xe_losses = utils.seq_softmax_cross_entropy_with_logits(
self.logits, self.target, self.source_len,
config.max_time_steps, reduce_sum=False, name='lm_loss')
self.xe_loss = tf.reduce_sum(self.xe_losses, axis=0)
self.log_probs = tf.nn.log_softmax(self.logits)
if config.l2_penalty == 0.0:
self.l2_loss = 0.0
else:
self.l2_loss = tf.add_n(
[tf.nn.l2_loss(var) for var in tf.trainable_variables()])
if config.l1_penalty == 0.0:
self.l1_loss = 0.0
else:
self.l1_loss = tf.add_n(
[tf.reduce_sum(tf.abs(var)) for var in tf.trainable_variables()])
if config.activation_norm_penalty == 0.0:
self.activation_norm_loss = 0.0
else:
self.activation_norm_loss = tf.reduce_mean(
# Sum over time to make values compatible with AWD-LSTM by Merity.
tf.reduce_sum(tf.square(self.dropped_cell_outputs), axis=0))
self.unregularized_loss = tf.reduce_mean(self.xe_loss)
self.loss = (self.unregularized_loss +
config.l2_penalty * self.l2_loss +
config.l1_penalty * self.l1_loss +
config.activation_norm_penalty * self.activation_norm_loss)
def get_scopes_to_train():
scopes_to_train = ['lm', 'om']
if config.trainable_initial_state:
scopes_to_train = ['lm_init'] + scopes_to_train
if config.embed_once:
scopes_to_train = ['im'] + scopes_to_train
if config.conditioning_separator:
scopes_to_train = ['cond_im', 'cond_lm'] + scopes_to_train
return scopes_to_train
def maybe_clip_grads(grads_and_vars):
logging.info('adding grad norm clipping')
return utils.clip_gradients_in_scope(
grads_and_vars, [''], config.max_grad_norm)
optimizer_builder = utils.get_optimizer(config.optimizer_type)
optimizer = optimizer_builder(self.learning_rate, config)
scopes_to_train = get_scopes_to_train()
grads_and_vars, training_summaries = utils.create_grads(
optimizer, self.loss, scopes_to_train)
# For dyneval.
self.clipped_grads_and_vars = maybe_clip_grads(grads_and_vars)
# Single minibatch training update
self.training_update = optimizer.apply_gradients(
self.clipped_grads_and_vars, global_step=self.global_step_var)
self.training_summary = tf.summary.merge(
training_summaries + utils.summaries_for_trainables())
# Accumulation of gradients across minibatches
if config.accum_batch_size > -1:
trained_vars = [var for _, var in grads_and_vars]
grad_accumulators = [
tf.Variable(tf.zeros_like(trained_var.initialized_value()),
trainable=False)
for trained_var in trained_vars]
self.accumulate_grads = tf.group(*[
accumulator.assign_add(grads_and_vars[0])
for accumulator, grads_and_vars
in zip(grad_accumulators, grads_and_vars)])
accumulated_grads_and_vars = zip(grad_accumulators, trained_vars)
self.accumulated_training_update = optimizer.apply_gradients(
maybe_clip_grads(accumulated_grads_and_vars),
global_step=self.global_step_var)
# Zero the accumulators after the update.
with tf.control_dependencies([self.accumulated_training_update]):
self.accumulated_training_update = tf.group(
*[var.assign(tf.zeros_like(var)) for var in grad_accumulators])
logging.info('Model: adding loss gradients finished.')
def _check_budget(self, config):
num_trainables = utils.log_trainables()
if config.num_params > -1:
assert num_trainables <= config.num_params, (
'The number of trainable parameters ({}) exceeds the budget ({}). '
.format(num_trainables, config.num_params))
if num_trainables < 0.98*(config.num_params-500):
logging.warn('Number of parameters (%s) is way below the budget (%s)',
num_trainables, config.num_params)
def global_step(self, session=None):
if session is None:
session = tf.get_default_session()
return session.run(self.global_step_var)
def add_input_to_feed(self, feed, cond, cond_len, source, source_len, target):
if self.config.conditioning_separator:
feed.update({self.conditioning: cond,
self.conditioning_len: cond_len})
else:
assert cond is None
assert cond_len is None
feed.update({self.source: source,
self.source_len: source_len,
self.target: target})
return feed
def add_dropout_to_feed(self, feed, multiplier=1):
config = self.config
if self.embedding_dropout is not None:
feed.update({self.embedding_dropout: multiplier*config.embedding_dropout})
if self.token_dropout is not None:
feed.update({self.token_dropout: multiplier*config.token_dropout})
if self.input_dropout is not None:
feed.update({self.input_dropout: multiplier*config.input_dropout})
if self.inter_layer_dropout is not None:
feed.update({self.inter_layer_dropout:
multiplier*config.inter_layer_dropout})
if self.update_dropout is not None:
feed.update({self.update_dropout: multiplier*config.update_dropout})
if self.state_dropout is not None:
feed.update({self.state_dropout: multiplier*config.state_dropout})
if self.flip_prob is not None:
feed.update({self.flip_prob: multiplier*config.state_dropout_flip_rate})
if self.output_dropout is not None:
feed.update({self.output_dropout: multiplier*config.output_dropout})
if self.downprojected_output_dropout is not None:
feed.update({self.downprojected_output_dropout:
multiplier*config.downprojected_output_dropout})
return feed
def fit(self, feed, session=None):
"""Training step for observed source language example."""
if session is None:
session = tf.get_default_session()
run_options = tf.RunOptions(
report_tensor_allocations_upon_oom=True)
_, cost, summary, last_state = session.run(
[self.training_update, self.unregularized_loss, self.training_summary,
self.last_state],
feed_dict=feed, options=run_options)
return cost, summary, last_state
def accumulate_gradients(self, feed, session=None):
if session is None:
session = tf.get_default_session()
_, cost, summary, last_state = session.run(
[self.accumulate_grads, self.unregularized_loss,
self.training_summary, self.last_state],
feed_dict=feed)
return cost, summary, last_state
def fit_accumulated(self, feed, session=None):
"""Training step for observed source language example."""
if session is None:
session = tf.get_default_session()
session.run([self.accumulated_training_update], feed_dict=feed)
| lamb-master | lamb/lm.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.