python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Composable timestep processing, for DQN Atari preprocessing. Aims: * Be self-contained. * Easy to have the preprocessing on the agent side or on the environment side. * Easy to swap out and modify parts of the processing. Conventions: * The term "processor" is used to refer to any callable that could also have a `reset()` function to clear any internal state. E.g. a plain function. Or an instance of a class with `__call__` method, with or without a `reset()` method. * `None` means no output when subsampling inputs. """ import collections from typing import Any, Callable, List, Iterable, Optional, Sequence, Text, Tuple import dm_env from dm_env import specs import numpy as np from PIL import Image Processor = Callable # Actually a callable that may also have a reset() method. Nest = Any # Recursive types are not yet supported by pytype. NamedTuple = Any StepType = dm_env.StepType def reset(processor: Processor[[Any], Any]) -> None: """Calls `reset()` on a `Processor` or function if the method exists.""" if hasattr(processor, 'reset'): processor.reset() identity = lambda v: v def trailing_zero_pad( length: int) -> Processor[[List[np.ndarray]], List[np.ndarray]]: """Adds trailing zero padding to array lists to ensure a minimum length.""" def trailing_zero_pad_fn(arrays): padding_length = length - len(arrays) if padding_length <= 0: return arrays zero = np.zeros_like(arrays[0]) return arrays + [zero] * padding_length return trailing_zero_pad_fn def none_to_zero_pad(values: List[Optional[NamedTuple]]) -> List[NamedTuple]: """Replaces `None`s in a list of named tuples with zeros of same structure.""" actual_values = [n for n in values if n is not None] if not actual_values: raise ValueError('Must have at least one value which is not None.') if len(actual_values) == len(values): return values example = actual_values[0] zero = type(example)(*(np.zeros_like(x) for x in example)) return [zero if v is None else v for v in values] def named_tuple_sequence_stack(values: Sequence[NamedTuple]) -> NamedTuple: """Converts a sequence of named tuples into a named tuple of tuples.""" # [T(1, 2), T(3, 4), T(5, 6)]. transposed = zip(*values) # ((1, 3, 5), (2, 4, 6)). return type(values[0])(*transposed) # T((1, 3, 5), (2, 4, 6)). class Deque: """Double ended queue with a maximum length and initial values.""" def __init__(self, max_length: int, initial_values=None): self._deque = collections.deque(maxlen=max_length) self._initial_values = initial_values or [] def reset(self) -> None: self._deque.clear() self._deque.extend(self._initial_values) def __call__(self, value: Any) -> collections.deque: self._deque.append(value) return self._deque class FixedPaddedBuffer: """Fixed size `None`-padded buffer which is cleared after it is filled. E.g. with `length = 3`, `initial_index = 2` and values `[0, 1, 2, 3, 4, 5, 6]` this will return `~~0`, `1~~`, `12~`, `123`, `4~~`, `45~`, `456`, where `~` represents `None`. Used to concatenate timesteps for action repeats. Action repeat requirements are: * Fixed size buffer of timesteps. * The `FIRST` timestep should return immediately to get the first action of the episode, as there is no preceding action to repeat. Prefix with padding. * For `MID` timesteps, the timestep buffer is periodically returned when full. * When a `LAST` timestep is encountered, the current buffer of timesteps is returned, suffixed with padding, as buffers should not cross episode boundaries. The requirements can be fulfilled by conditionally subsampling the output of this processor. """ def __init__(self, length: int, initial_index: int): self._length = length self._initial_index = initial_index % length self._index = self._initial_index self._buffer = [None] * self._length def reset(self) -> None: self._index = self._initial_index self._buffer = [None] * self._length def __call__(self, value: Any) -> Sequence[Any]: if self._index >= self._length: assert self._index == self._length self._index = 0 self._buffer = [None] * self._length self._buffer[self._index] = value self._index += 1 return self._buffer class ConditionallySubsample: """Conditionally passes through input, returning `None` otherwise.""" def __init__(self, condition: Processor[[Any], bool]): self._condition = condition def reset(self) -> None: reset(self._condition) def __call__(self, value: Any) -> Optional[Any]: return value if self._condition(value) else None class TimestepBufferCondition: """Returns `True` when an iterable of timesteps should be passed on. Specifically returns `True`: * If timesteps contain a `FIRST`. * If timesteps contain a `LAST`. * If number of steps passed since `FIRST` timestep modulo `period` is `0`. Returns `False` otherwise. Used for action repeats in Atari preprocessing. """ def __init__(self, period: int): self._period = period self._steps_since_first_timestep = None self._should_reset = False def reset(self): self._should_reset = False self._steps_since_first_timestep = None def __call__(self, timesteps: Iterable[dm_env.TimeStep]) -> bool: if self._should_reset: raise RuntimeError('Should have reset.') # Find the main step type, FIRST and LAST take precedence over MID. main_step_type = StepType.MID precedent_step_types = (StepType.FIRST, StepType.LAST) for timestep in timesteps: if timestep is None: continue if timestep.step_type in precedent_step_types: if main_step_type in precedent_step_types: raise RuntimeError('Expected at most one FIRST or LAST.') main_step_type = timestep.step_type # Must have FIRST timestep after a reset. if self._steps_since_first_timestep is None: if main_step_type != StepType.FIRST: raise RuntimeError('After reset first timestep should be FIRST.') # pytype: disable=unsupported-operands if main_step_type == StepType.FIRST: self._steps_since_first_timestep = 0 return True elif main_step_type == StepType.LAST: self._steps_since_first_timestep = None self._should_reset = True return True elif (self._steps_since_first_timestep + 1) % self._period == 0: self._steps_since_first_timestep += 1 return True else: self._steps_since_first_timestep += 1 return False # pytype: enable=unsupported-operands class ApplyToNamedTupleField: """Runs processors on a particular field of a named tuple.""" def __init__(self, field: Text, *processors: Processor[[Any], Any]): self._field = field self._processors = processors def reset(self) -> None: for processor in self._processors: reset(processor) def __call__(self, value: NamedTuple) -> NamedTuple: attr_value = getattr(value, self._field) for processor in self._processors: attr_value = processor(attr_value) return value._replace(**{self._field: attr_value}) class Maybe: """Wraps another processor so that `None` is returned when `None` is input.""" def __init__(self, processor: Processor[[Any], Any]): self._processor = processor def reset(self) -> None: reset(self._processor) def __call__(self, value: Optional[Any]) -> Optional[Any]: if value is None: return None else: return self._processor(value) class Sequential: """Chains together multiple processors.""" def __init__(self, *processors: Processor[[Any], Any]): self._processors = processors def reset(self) -> None: for processor in self._processors: reset(processor) def __call__(self, value: Any) -> Any: for processor in self._processors: value = processor(value) return value class ZeroDiscountOnLifeLoss: """Sets discount to zero on timestep if number of lives has decreased. This processor assumes observations to be tuples whose second entry is a scalar indicating the remaining number of lives. """ def __init__(self): self._num_lives_on_prev_step = None def reset(self) -> None: self._num_lives_on_prev_step = None def __call__(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep: # We have a life loss when the timestep is a regular transition and lives # have decreased since the previous timestep. num_lives = timestep.observation[1] life_lost = timestep.mid() and (num_lives < self._num_lives_on_prev_step) self._num_lives_on_prev_step = num_lives return timestep._replace(discount=0.) if life_lost else timestep def reduce_step_type(step_types: Sequence[StepType], debug: bool = False) -> StepType: """Outputs a representative step type from an array of step types.""" # Zero padding will appear to be FIRST. Padding should only be seen before the # FIRST (e.g. 000F) or after LAST (e.g. ML00). if debug: np_step_types = np.array(step_types) output_step_type = StepType.MID for i, step_type in enumerate(step_types): if step_type == 0: # step_type not actually FIRST, but we do expect 000F. if debug and not (np_step_types == 0).all(): raise ValueError('Expected zero padding followed by FIRST.') output_step_type = StepType.FIRST break elif step_type == StepType.LAST: output_step_type = StepType.LAST if debug and not (np_step_types[i + 1:] == 0).all(): raise ValueError('Expected LAST to be followed by zero padding.') break else: if step_type != StepType.MID: raise ValueError('Expected MID if not FIRST or LAST.') return output_step_type def aggregate_rewards(rewards: Sequence[Optional[float]], debug: bool = False) -> Optional[float]: """Sums up rewards, assumes discount is 1.""" if None in rewards: if debug: np_rewards = np.array(rewards) if not (np_rewards[-1] is None and (np_rewards[:-1] == 0).all()): # Should only ever have [0, 0, 0, None] due to zero padding. raise ValueError('Should only have a None reward for FIRST.') return None else: # Faster than np.sum for a list of floats. return sum(rewards) def aggregate_discounts(discounts: Sequence[Optional[float]], debug: bool = False) -> Optional[float]: """Aggregates array of discounts into a scalar, expects `0`, `1` or `None`.""" if debug: np_discounts = np.array(discounts) if not np.isin(np_discounts, [0., 1., None]).all(): raise ValueError('All discounts should be 0 or 1, got: %s.' % np_discounts) if None in discounts: if debug: if not (np_discounts[-1] is None and (np_discounts[:-1] == 0).all()): # Should have [0, 0, 0, None] due to zero padding. raise ValueError('Should only have a None discount for FIRST.') return None else: # Faster than np.prod for a list of floats. result = 1 for d in discounts: result *= d return result def rgb2y(array: np.ndarray) -> np.ndarray: """Converts RGB image array into grayscale.""" if array.ndim != 3: raise ValueError('Input array should be 3D, got %s.' % array.ndim) output = np.tensordot(array, [0.299, 0.587, 1 - (0.299 + 0.587)], (-1, 0)) return output.astype(np.uint8) def resize(shape: Tuple[int, ...]) -> Processor[[np.ndarray], np.ndarray]: """Resizes array to the given shape.""" if len(shape) != 2: raise ValueError('Resize shape has to be 2D, given: %s.' % str(shape)) # Image.resize takes (width, height) as output_shape argument. image_shape = (shape[1], shape[0]) def resize_fn(array): image = Image.fromarray(array).resize(image_shape, Image.BILINEAR) return np.array(image, dtype=np.uint8) return resize_fn def select_rgb_observation(timestep: dm_env.TimeStep) -> dm_env.TimeStep: """Replaces an observation tuple by its first entry (the RGB observation).""" return timestep._replace(observation=timestep.observation[0]) def apply_additional_discount( additional_discount: float) -> Processor[[float], float]: """Returns a function that scales its non-`None` input by a constant.""" return lambda d: None if d is None else additional_discount * d def clip_reward(bound: float) -> Processor[[Optional[float]], Optional[float]]: """Returns a function that clips non-`None` inputs to (`-bound`, `bound`).""" def clip_reward_fn(reward): return None if reward is None else max(min(reward, bound), -bound) return clip_reward_fn def show(prefix: Text) -> Processor[[Any], Any]: """Prints value and passes through, for debugging.""" def show_fn(value): print('%s: %s' % (prefix, value)) return value return show_fn def atari( additional_discount: float = 0.99, max_abs_reward: Optional[float] = 1.0, resize_shape: Optional[Tuple[int, int]] = (84, 84), num_action_repeats: int = 4, num_pooled_frames: int = 2, zero_discount_on_life_loss: bool = True, num_stacked_frames: int = 4, grayscaling: bool = True, ) -> Processor[[dm_env.TimeStep], Optional[dm_env.TimeStep]]: """Standard DQN preprocessing on Atari.""" # This processor does the following to a sequence of timesteps. # # 1. Zeroes discount on loss of life. # 2. Repeats actions (previous action should be repeated if None is returned). # 3. Max pools action repeated observations. # 4. Grayscales observations. # 5. Resizes observations. # 6. Stacks observations. # 7. Clips rewards. # 8. Applies an additional discount. # # For more detail see the annotations in the processors below. # The FixedPaddedBuffer, ConditionallySubsample, none_to_zero_pad, stack and # max_pool on the observation collectively does this (step types: F = FIRST, # M = MID, L = LAST, ~ is None): # # Type: F | M M M M | M M L | F | # Frames: A | B C D E | F G H | I | # Output: max[0A]| ~ ~ ~ max[DE]| ~ ~ max[H0]|max[0I]| return Sequential( # When the number of lives decreases, set discount to 0. ZeroDiscountOnLifeLoss() if zero_discount_on_life_loss else identity, # Select the RGB observation as the main observation, dropping lives. select_rgb_observation, # obs: 1, 2, 3, 4, 5, 6, 7, 8, 9, ... # Write timesteps into a fixed-sized buffer padded with None. FixedPaddedBuffer(length=num_action_repeats, initial_index=-1), # obs: ~~~1, 2~~~, 23~~, 234~, 2345, 6~~~, 67~~, 678~, 6789, ... # Periodically return the deque of timesteps, when the current timestep is # FIRST, after that every 4 steps, and when the current timestep is LAST. ConditionallySubsample(TimestepBufferCondition(num_action_repeats)), # obs: ~~~1, ~, ~, ~, 2345, ~, ~, ~, 6789, ... # If None pass through, otherwise apply the processor. Maybe( Sequential( # Replace Nones with zero padding in each buffer. none_to_zero_pad, # obs: 0001, ~, ~, ~, 2345, ~, ~, ~, 6789, ... # Convert sequence of nests into a nest of sequences. named_tuple_sequence_stack, # Choose representative step type from an array of step types. ApplyToNamedTupleField('step_type', reduce_step_type), # Rewards: sum then clip. ApplyToNamedTupleField( 'reward', aggregate_rewards, clip_reward(max_abs_reward) if max_abs_reward else identity, ), # Discounts: take product and scale by an additional discount. ApplyToNamedTupleField( 'discount', aggregate_discounts, apply_additional_discount(additional_discount), ), # Observations: max pool, grayscale, resize, and stack. ApplyToNamedTupleField( 'observation', lambda obs: np.stack(obs[-num_pooled_frames:], axis=0), lambda obs: np.max(obs, axis=0), # obs: max[01], ~, ~, ~, max[45], ~, ~, ~, max[89], ... # obs: A, ~, ~, ~, B, ~, ~, ~, C, ... rgb2y if grayscaling else identity, resize(resize_shape) if resize_shape else identity, Deque(max_length=num_stacked_frames), # obs: A, ~, ~, ~, AB, ~, ~, ~, ABC, ~, ~, ~, ABCD, ~, ~, ~, # BCDE, ~, ~, ~, CDEF, ... list, trailing_zero_pad(length=num_stacked_frames), # obs: A000, ~, ~, ~, AB00, ~, ~, ~, ABC0, ~, ~, ~, ABCD, # ~, ~, ~, BCDE, ... lambda obs: np.stack(obs, axis=-1), ), )), ) class AtariEnvironmentWrapper(dm_env.Environment): """Python environment wrapper that provides DQN Atari preprocessing. This is a thin wrapper around the Atari processor. Expects underlying Atari environment to have interleaved pixels (HWC) and zero-indexed actions. """ def __init__( self, environment: dm_env.Environment, additional_discount: float = 0.99, max_abs_reward: Optional[float] = 1.0, resize_shape: Optional[Tuple[int, int]] = (84, 84), num_action_repeats: int = 4, num_pooled_frames: int = 2, zero_discount_on_life_loss: bool = True, num_stacked_frames: int = 4, grayscaling: bool = True, ): rgb_spec, unused_lives_spec = environment.observation_spec() if rgb_spec.shape[2] != 3: raise ValueError( 'This wrapper assumes interleaved pixel observations with shape ' '(height, width, channels).') if int(environment.action_spec().minimum) != 0: raise ValueError('This wrapper assumes zero-indexed actions.') self._environment = environment self._processor = atari( additional_discount=additional_discount, max_abs_reward=max_abs_reward, resize_shape=resize_shape, num_action_repeats=num_action_repeats, num_pooled_frames=num_pooled_frames, zero_discount_on_life_loss=zero_discount_on_life_loss, num_stacked_frames=num_stacked_frames, grayscaling=grayscaling, ) if grayscaling: self._observation_shape = resize_shape + (num_stacked_frames,) self._observation_spec_name = 'grayscale' else: self._observation_shape = resize_shape + (3, num_stacked_frames) self._observation_spec_name = 'RGB' self._reset_next_step = True def reset(self) -> dm_env.TimeStep: """Resets environment and provides the first processed timestep.""" reset(self._processor) timestep = self._environment.reset() processed_timestep = self._processor(timestep) assert processed_timestep is not None self._reset_next_step = False return processed_timestep def step(self, action: int) -> dm_env.TimeStep: """Steps up to `num_action_repeat` times, returns a processed timestep.""" # This implements the action repeat by repeatedly passing in the last action # until an actual timestep is returned by the processor. if self._reset_next_step: return self.reset() # Ignore action. processed_timestep = None while processed_timestep is None: timestep = self._environment.step(action) processed_timestep = self._processor(timestep) if timestep.last(): self._reset_next_step = True assert processed_timestep is not None return processed_timestep def action_spec(self) -> specs.DiscreteArray: return self._environment.action_spec() def observation_spec(self) -> specs.Array: return specs.Array( shape=self._observation_shape, dtype=np.uint8, name=self._observation_spec_name) class AtariSimpleActionEnvironmentWrapper(dm_env.Environment): """Python environment wrapper for Atari so it takes integer actions. Use this when processing is done on the agent side. """ def __init__(self, environment: dm_env.Environment): self._environment = environment if int(environment.action_spec()[0].minimum) != 0: raise ValueError( 'This wrapper assumes zero-indexed actions. Use the Atari setting ' 'zero_indexed_actions=\"true\" to get actions in this format.') def reset(self) -> dm_env.TimeStep: return self._environment.reset() def step(self, action: int) -> dm_env.TimeStep: return self._environment.step([np.array(action).reshape((1,))]) def action_spec(self) -> specs.DiscreteArray: action_spec = self._environment.action_spec()[0] return specs.DiscreteArray( num_values=action_spec.maximum.item() + 1, dtype=action_spec.dtype, name='action_spec') def observation_spec(self) -> specs.Array: return self._environment.observation_spec()
deepmind-research-master
tandem_dqn/processors.py
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for Tandem losses.""" from absl.testing import absltest from absl.testing import parameterized import chex import jax from jax.config import config import numpy as np from tandem_dqn import agent from tandem_dqn import losses from tandem_dqn import networks from tandem_dqn import replay def make_tandem_qvals(): return agent.TandemTuple( active=networks.QNetworkOutputs(3. * np.ones((3, 5), np.float32)), passive=networks.QNetworkOutputs(2. * np.ones((3, 5), np.float32)) ) def make_transition(): return replay.Transition( s_tm1=np.zeros(3), a_tm1=np.ones(3, np.int32), r_t=5. * np.ones(3), discount_t=0.9 * np.ones(3), s_t=np.zeros(3)) class DoubleQLossesTest(parameterized.TestCase): def setUp(self): super().setUp() self.qs = make_tandem_qvals() self.transition = make_transition() self.rng_key = jax.random.PRNGKey(42) @chex.all_variants() @parameterized.parameters( ('double_q',), ('double_q_v',), ('double_q_p',), ('double_q_pv',), ('q_regression',), ) def test_active_loss_gradients(self, loss_type): loss_fn = losses.make_loss_fn(loss_type, active=True) def fn(q_tm1, q_t, q_t_target, transition, rng_key): return loss_fn(q_tm1, q_t, q_t_target, transition, rng_key) grad_fn = self.variant(jax.grad(fn, argnums=(0, 1, 2))) dldq_tm1, dldq_t, dldq_t_target = grad_fn( self.qs, self.qs, self.qs, self.transition, self.rng_key) # Assert that only active net gets nonzero gradients. self.assertGreater(np.sum(np.abs(dldq_tm1.active.q_values)), 0.) self.assertTrue(np.all(dldq_t.active.q_values == 0.)) self.assertTrue(np.all(dldq_t_target.active.q_values == 0.)) self.assertTrue(np.all(dldq_t.passive.q_values == 0.)) self.assertTrue(np.all(dldq_tm1.passive.q_values == 0.)) self.assertTrue(np.all(dldq_t_target.passive.q_values == 0.)) @chex.all_variants() @parameterized.parameters( ('double_q',), ('double_q_v',), ('double_q_p',), ('double_q_pv',), ('q_regression',), ) def test_passive_loss_gradients(self, loss_type): loss_fn = losses.make_loss_fn(loss_type, active=False) def fn(q_tm1, q_t, q_t_target, transition, rng_key): return loss_fn(q_tm1, q_t, q_t_target, transition, rng_key) grad_fn = self.variant(jax.grad(fn, argnums=(0, 1, 2))) dldq_tm1, dldq_t, dldq_t_target = grad_fn( self.qs, self.qs, self.qs, self.transition, self.rng_key) # Assert that only passive net gets nonzero gradients. self.assertGreater(np.sum(np.abs(dldq_tm1.passive.q_values)), 0.) self.assertTrue(np.all(dldq_t.passive.q_values == 0.)) self.assertTrue(np.all(dldq_t_target.passive.q_values == 0.)) self.assertTrue(np.all(dldq_t.active.q_values == 0.)) self.assertTrue(np.all(dldq_tm1.active.q_values == 0.)) self.assertTrue(np.all(dldq_t_target.active.q_values == 0.)) if __name__ == '__main__': config.update('jax_numpy_rank_promotion', 'raise') absltest.main()
deepmind-research-master
tandem_dqn/losses_test.py
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A Tandem DQN agent implemented in JAX, training on Atari.""" import collections import itertools import sys import typing from absl import app from absl import flags from absl import logging import dm_env import jax from jax.config import config import numpy as np import optax from tandem_dqn import agent as agent_lib from tandem_dqn import atari_data from tandem_dqn import gym_atari from tandem_dqn import losses from tandem_dqn import networks from tandem_dqn import parts from tandem_dqn import processors from tandem_dqn import replay as replay_lib # Relevant flag values are expressed in terms of environment frames. FLAGS = flags.FLAGS flags.DEFINE_string('environment_name', 'pong', '') flags.DEFINE_boolean('use_sticky_actions', False, '') flags.DEFINE_integer('environment_height', 84, '') flags.DEFINE_integer('environment_width', 84, '') flags.DEFINE_integer('replay_capacity', int(1e6), '') flags.DEFINE_bool('compress_state', True, '') flags.DEFINE_float('min_replay_capacity_fraction', 0.05, '') flags.DEFINE_integer('batch_size', 32, '') flags.DEFINE_integer('max_frames_per_episode', 108000, '') # 30 mins. flags.DEFINE_integer('num_action_repeats', 4, '') flags.DEFINE_integer('num_stacked_frames', 4, '') flags.DEFINE_float('exploration_epsilon_begin_value', 1., '') flags.DEFINE_float('exploration_epsilon_end_value', 0.01, '') flags.DEFINE_float('exploration_epsilon_decay_frame_fraction', 0.02, '') flags.DEFINE_float('eval_exploration_epsilon', 0.01, '') flags.DEFINE_integer('target_network_update_period', int(1.2e5), '') flags.DEFINE_float('additional_discount', 0.99, '') flags.DEFINE_float('max_abs_reward', 1., '') flags.DEFINE_integer('seed', 1, '') # GPU may introduce nondeterminism. flags.DEFINE_integer('num_iterations', 200, '') flags.DEFINE_integer('num_train_frames', int(1e6), '') # Per iteration. flags.DEFINE_integer('num_eval_frames', int(5e5), '') # Per iteration. flags.DEFINE_integer('learn_period', 16, '') flags.DEFINE_string('results_csv_path', '/tmp/results.csv', '') # Tandem-specific parameters. # Using fixed configs for optimizers: # RMSProp: lr = 0.00025, eps=0.01 / (32 ** 2) # ADAM: lr = 0.00005, eps=0.01 / 32 _OPTIMIZERS = ['rmsprop', 'adam'] flags.DEFINE_enum('optimizer_active', 'rmsprop', _OPTIMIZERS, '') flags.DEFINE_enum('optimizer_passive', 'rmsprop', _OPTIMIZERS, '') _NETWORKS = ['double_q', 'qr'] flags.DEFINE_enum('network_active', 'double_q', _NETWORKS, '') flags.DEFINE_enum('network_passive', 'double_q', _NETWORKS, '') _LOSSES = ['double_q', 'double_q_v', 'double_q_p', 'double_q_pv', 'qr', 'q_regression'] flags.DEFINE_enum('loss_active', 'double_q', _LOSSES, '') flags.DEFINE_enum('loss_passive', 'double_q', _LOSSES, '') flags.DEFINE_integer('tied_layers', 0, '') TandemTuple = agent_lib.TandemTuple def make_optimizer(optimizer_type): """Constructs optimizer.""" if optimizer_type == 'rmsprop': learning_rate = 0.00025 epsilon = 0.01 / (32**2) optimizer = optax.rmsprop( learning_rate=learning_rate, decay=0.95, eps=epsilon, centered=True) elif optimizer_type == 'adam': learning_rate = 0.00005 epsilon = 0.01 / 32 optimizer = optax.adam( learning_rate=learning_rate, eps=epsilon) else: raise ValueError('Unknown optimizer "{}"'.format(optimizer_type)) return optimizer def main(argv): """Trains Tandem DQN agent on Atari.""" del argv logging.info('Tandem DQN on Atari on %s.', jax.lib.xla_bridge.get_backend().platform) random_state = np.random.RandomState(FLAGS.seed) rng_key = jax.random.PRNGKey( random_state.randint(-sys.maxsize - 1, sys.maxsize + 1, dtype=np.int64)) if FLAGS.results_csv_path: writer = parts.CsvWriter(FLAGS.results_csv_path) else: writer = parts.NullWriter() def environment_builder(): """Creates Atari environment.""" env = gym_atari.GymAtari( FLAGS.environment_name, sticky_actions=FLAGS.use_sticky_actions, seed=random_state.randint(1, 2**32)) return gym_atari.RandomNoopsEnvironmentWrapper( env, min_noop_steps=1, max_noop_steps=30, seed=random_state.randint(1, 2**32), ) env = environment_builder() logging.info('Environment: %s', FLAGS.environment_name) logging.info('Action spec: %s', env.action_spec()) logging.info('Observation spec: %s', env.observation_spec()) num_actions = env.action_spec().num_values # Check: qr network and qr losses can only be used together. if ('qr' in FLAGS.network_active) != ('qr' in FLAGS.loss_active): raise ValueError('Active loss/net must either both use QR, or neither.') if ('qr' in FLAGS.network_passive) != ('qr' in FLAGS.loss_passive): raise ValueError('Passive loss/net must either both use QR, or neither.') network = TandemTuple( active=networks.make_network(FLAGS.network_active, num_actions), passive=networks.make_network(FLAGS.network_passive, num_actions), ) loss = TandemTuple( active=losses.make_loss_fn(FLAGS.loss_active, active=True), passive=losses.make_loss_fn(FLAGS.loss_passive, active=False), ) # Tied layers. assert 0 <= FLAGS.tied_layers <= 4 if FLAGS.tied_layers > 0 and (FLAGS.network_passive != 'double_q' or FLAGS.network_active != 'double_q'): raise ValueError('Tied layers > 0 is only supported for double_q networks.') layers = [ 'sequential/sequential/conv1', 'sequential/sequential/conv2', 'sequential/sequential/conv3', 'sequential/sequential_1/linear1' ] tied_layers = set(layers[:FLAGS.tied_layers]) def preprocessor_builder(): return processors.atari( additional_discount=FLAGS.additional_discount, max_abs_reward=FLAGS.max_abs_reward, resize_shape=(FLAGS.environment_height, FLAGS.environment_width), num_action_repeats=FLAGS.num_action_repeats, num_pooled_frames=2, zero_discount_on_life_loss=True, num_stacked_frames=FLAGS.num_stacked_frames, grayscaling=True, ) # Create sample network input from sample preprocessor output. sample_processed_timestep = preprocessor_builder()(env.reset()) sample_processed_timestep = typing.cast(dm_env.TimeStep, sample_processed_timestep) sample_network_input = sample_processed_timestep.observation assert sample_network_input.shape == (FLAGS.environment_height, FLAGS.environment_width, FLAGS.num_stacked_frames) exploration_epsilon_schedule = parts.LinearSchedule( begin_t=int(FLAGS.min_replay_capacity_fraction * FLAGS.replay_capacity * FLAGS.num_action_repeats), decay_steps=int(FLAGS.exploration_epsilon_decay_frame_fraction * FLAGS.num_iterations * FLAGS.num_train_frames), begin_value=FLAGS.exploration_epsilon_begin_value, end_value=FLAGS.exploration_epsilon_end_value) if FLAGS.compress_state: def encoder(transition): return transition._replace( s_tm1=replay_lib.compress_array(transition.s_tm1), s_t=replay_lib.compress_array(transition.s_t)) def decoder(transition): return transition._replace( s_tm1=replay_lib.uncompress_array(transition.s_tm1), s_t=replay_lib.uncompress_array(transition.s_t)) else: encoder = None decoder = None replay_structure = replay_lib.Transition( s_tm1=None, a_tm1=None, r_t=None, discount_t=None, s_t=None, a_t=None, mc_return_tm1=None, ) replay = replay_lib.TransitionReplay(FLAGS.replay_capacity, replay_structure, random_state, encoder, decoder) optimizer = TandemTuple( active=make_optimizer(FLAGS.optimizer_active), passive=make_optimizer(FLAGS.optimizer_passive), ) train_rng_key, eval_rng_key = jax.random.split(rng_key) train_agent = agent_lib.TandemDqn( preprocessor=preprocessor_builder(), sample_network_input=sample_network_input, network=network, optimizer=optimizer, loss=loss, transition_accumulator=replay_lib.TransitionAccumulatorWithMCReturn(), replay=replay, batch_size=FLAGS.batch_size, exploration_epsilon=exploration_epsilon_schedule, min_replay_capacity_fraction=FLAGS.min_replay_capacity_fraction, learn_period=FLAGS.learn_period, target_network_update_period=FLAGS.target_network_update_period, tied_layers=tied_layers, rng_key=train_rng_key, ) eval_agent_active = parts.EpsilonGreedyActor( preprocessor=preprocessor_builder(), network=network.active, exploration_epsilon=FLAGS.eval_exploration_epsilon, rng_key=eval_rng_key) eval_agent_passive = parts.EpsilonGreedyActor( preprocessor=preprocessor_builder(), network=network.passive, exploration_epsilon=FLAGS.eval_exploration_epsilon, rng_key=eval_rng_key) # Set up checkpointing. checkpoint = parts.NullCheckpoint() state = checkpoint.state state.iteration = 0 state.train_agent = train_agent state.eval_agent_active = eval_agent_active state.eval_agent_passive = eval_agent_passive state.random_state = random_state state.writer = writer if checkpoint.can_be_restored(): checkpoint.restore() # Run single iteration of training or evaluation. def run_iteration(agent, env, num_frames): seq = parts.run_loop(agent, env, FLAGS.max_frames_per_episode) seq_truncated = itertools.islice(seq, num_frames) trackers = parts.make_default_trackers(agent) return parts.generate_statistics(trackers, seq_truncated) def eval_log_output(eval_stats, suffix): human_normalized_score = atari_data.get_human_normalized_score( FLAGS.environment_name, eval_stats['episode_return']) capped_human_normalized_score = np.amin([1., human_normalized_score]) return [ ('eval_episode_return_' + suffix, eval_stats['episode_return'], '% 2.2f'), ('eval_num_episodes_' + suffix, eval_stats['num_episodes'], '%3d'), ('eval_frame_rate_' + suffix, eval_stats['step_rate'], '%4.0f'), ('normalized_return_' + suffix, human_normalized_score, '%.3f'), ('capped_normalized_return_' + suffix, capped_human_normalized_score, '%.3f'), ('human_gap_' + suffix, 1. - capped_human_normalized_score, '%.3f'), ] while state.iteration <= FLAGS.num_iterations: # New environment for each iteration to allow for determinism if preempted. env = environment_builder() # Set agent to train active and passive nets on each learning step. train_agent.set_training_mode('active_passive') logging.info('Training iteration %d.', state.iteration) num_train_frames = 0 if state.iteration == 0 else FLAGS.num_train_frames train_stats = run_iteration(train_agent, env, num_train_frames) logging.info('Evaluation iteration %d - active agent.', state.iteration) eval_agent_active.network_params = train_agent.online_params.active eval_stats_active = run_iteration(eval_agent_active, env, FLAGS.num_eval_frames) logging.info('Evaluation iteration %d - passive agent.', state.iteration) eval_agent_passive.network_params = train_agent.online_params.passive eval_stats_passive = run_iteration(eval_agent_passive, env, FLAGS.num_eval_frames) # Logging and checkpointing. agent_logs = [ 'loss_active', 'loss_passive', 'frac_diff_argmax', 'mc_error_active', 'mc_error_passive', 'mc_error_abs_active', 'mc_error_abs_passive', ] log_output = ( eval_log_output(eval_stats_active, 'active') + eval_log_output(eval_stats_passive, 'passive') + [('iteration', state.iteration, '%3d'), ('frame', state.iteration * FLAGS.num_train_frames, '%5d'), ('train_episode_return', train_stats['episode_return'], '% 2.2f'), ('train_num_episodes', train_stats['num_episodes'], '%3d'), ('train_frame_rate', train_stats['step_rate'], '%4.0f'), ] + [(k, train_stats[k], '% 2.2f') for k in agent_logs] ) log_output_str = ', '.join(('%s: ' + f) % (n, v) for n, v, f in log_output) logging.info(log_output_str) writer.write(collections.OrderedDict((n, v) for n, v, _ in log_output)) state.iteration += 1 checkpoint.save() writer.close() if __name__ == '__main__': config.update('jax_platform_name', 'gpu') # Default to GPU. config.update('jax_numpy_rank_promotion', 'raise') config.config_with_absl() app.run(main)
deepmind-research-master
tandem_dqn/run_tandem.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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Plot results for different side effects penalties. Loads csv result files generated by `run_experiment' and outputs a summary data frame in a csv file to be used for plotting by plot_results.ipynb. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path from absl import app from absl import flags import pandas as pd from side_effects_penalties.file_loading import load_files FLAGS = flags.FLAGS if __name__ == '__main__': # Avoid defining flags when used as a library. flags.DEFINE_string('path', '', 'File path.') flags.DEFINE_string('input_suffix', '', 'Filename suffix to use when loading data files.') flags.DEFINE_string('output_suffix', '', 'Filename suffix to use when saving files.') flags.DEFINE_bool('bar_plot', True, 'Make a data frame for a bar plot (True) ' + 'or learning curves (False)') flags.DEFINE_string('env_name', 'box', 'Environment name.') flags.DEFINE_bool('noops', True, 'Whether the environment includes noops.') flags.DEFINE_list('beta_list', [0.1, 0.3, 1.0, 3.0, 10.0, 30.0, 100.0], 'List of beta values.') flags.DEFINE_list('seed_list', [1], 'List of random seeds.') flags.DEFINE_bool('compare_penalties', True, 'Compare different penalties using the best beta value ' + 'for each penalty (True), or compare different beta values ' + 'for the same penalty (False).') flags.DEFINE_enum('dev_measure', 'rel_reach', ['none', 'reach', 'rel_reach', 'att_util'], 'Deviation measure (used if compare_penalties=False).') flags.DEFINE_enum('dev_fun', 'truncation', ['truncation', 'absolute'], 'Summary function for the deviation measure ' + '(used if compare_penalties=False)') flags.DEFINE_float('value_discount', 0.99, 'Discount factor for deviation measure value function ' + '(used if compare_penalties=False)') def beta_choice(baseline, dev_measure, dev_fun, value_discount, env_name, beta_list, seed_list, noops=False, path='', suffix=''): """Choose beta value that gives the highest final performance.""" if dev_measure == 'none': return 0.1 perf_max = float('-inf') best_beta = 0.0 for beta in beta_list: df = load_files(baseline=baseline, dev_measure=dev_measure, dev_fun=dev_fun, value_discount=value_discount, beta=beta, env_name=env_name, noops=noops, path=path, suffix=suffix, seed_list=seed_list) if df.empty: perf = float('-inf') else: perf = df['performance_smooth'].mean() if perf > perf_max: perf_max = perf best_beta = beta return best_beta def penalty_label(dev_measure, dev_fun, value_discount): """Penalty label specifying design choices.""" dev_measure_labels = { 'none': 'None', 'rel_reach': 'RR', 'att_util': 'AU', 'reach': 'UR'} label = dev_measure_labels[dev_measure] disc_lab = 'u' if value_discount == 1.0 else 'd' dev_lab = '' if dev_measure in ['rel_reach', 'att_util']: dev_lab = 't' if dev_fun == 'truncation' else 'a' if dev_measure != 'none': label = label + '(' + disc_lab + dev_lab + ')' return label def make_summary_data_frame( env_name, beta_list, seed_list, final=True, baseline=None, dev_measure=None, dev_fun=None, value_discount=None, noops=False, compare_penalties=True, path='', input_suffix='', output_suffix=''): """Make summary dataframe from multiple csv result files and output to csv.""" # For each of the penalty parameters (baseline, dev_measure, dev_fun, and # value_discount), compare a list of multiple values if the parameter is None, # or use the provided parameter value if it is not None baseline_list = ['start', 'inaction', 'stepwise', 'step_noroll'] if dev_measure is not None: dev_measure_list = [dev_measure] else: dev_measure_list = ['none', 'reach', 'rel_reach', 'att_util'] dataframes = [] for dev_measure in dev_measure_list: # These deviation measures don't have a deviation function: if dev_measure in ['reach', 'none']: dev_fun_list = ['none'] elif dev_fun is not None: dev_fun_list = [dev_fun] else: dev_fun_list = ['truncation', 'absolute'] # These deviation measures must be discounted: if dev_measure in ['none', 'att_util']: value_discount_list = [0.99] elif value_discount is not None: value_discount_list = [value_discount] else: value_discount_list = [0.99, 1.0] for baseline in baseline_list: for vd in value_discount_list: for devf in dev_fun_list: # Choose the best beta for this set of penalty parameters if # compare_penalties=True, or compare all betas otherwise if compare_penalties: beta = beta_choice( baseline=baseline, dev_measure=dev_measure, dev_fun=devf, value_discount=vd, env_name=env_name, noops=noops, beta_list=beta_list, seed_list=seed_list, path=path, suffix=input_suffix) betas = [beta] else: betas = beta_list for beta in betas: label = penalty_label( dev_measure=dev_measure, dev_fun=devf, value_discount=vd) df_part = load_files( baseline=baseline, dev_measure=dev_measure, dev_fun=devf, value_discount=vd, beta=beta, env_name=env_name, noops=noops, path=path, suffix=input_suffix, final=final, seed_list=seed_list) df_part = df_part.assign( baseline=baseline, dev_measure=dev_measure, dev_fun=devf, value_discount=vd, beta=beta, env_name=env_name, label=label) dataframes.append(df_part) df = pd.concat(dataframes, sort=False) # Output summary data frame final_str = '_final' if final else '' if compare_penalties: filename = ('df_summary_penalties_' + env_name + final_str + output_suffix + '.csv') else: filename = ('df_summary_betas_' + env_name + '_' + dev_measure + '_' + dev_fun + '_' + str(value_discount) + final_str + output_suffix + '.csv') f = os.path.join(path, filename) df.to_csv(f) return df def main(unused_argv): compare_penalties = FLAGS.compare_penalties dev_measure = None if compare_penalties else FLAGS.dev_measure dev_fun = None if compare_penalties else FLAGS.dev_fun value_discount = None if compare_penalties else FLAGS.value_discount make_summary_data_frame( compare_penalties=compare_penalties, env_name=FLAGS.env_name, noops=FLAGS.noops, final=FLAGS.bar_plot, dev_measure=dev_measure, value_discount=value_discount, dev_fun=dev_fun, path=FLAGS.path, input_suffix=FLAGS.input_suffix, output_suffix=FLAGS.output_suffix, beta_list=FLAGS.beta_list, seed_list=FLAGS.seed_list) if __name__ == '__main__': app.run(main)
deepmind-research-master
side_effects_penalties/results_summary.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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Helper functions for loading files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import pandas as pd def filename(env_name, noops, dev_measure, dev_fun, baseline, beta, value_discount, seed, path='', suffix=''): """Generate filename for the given set of parameters.""" noop_str = 'noops' if noops else 'nonoops' seed_str = '_' + str(seed) if seed else '' filename_template = ('{env_name}_{noop_str}_{dev_measure}_{dev_fun}' + '_{baseline}_beta_{beta}_vd_{value_discount}' + '{suffix}{seed_str}.csv') full_path = os.path.join(path, filename_template.format( env_name=env_name, noop_str=noop_str, dev_measure=dev_measure, dev_fun=dev_fun, baseline=baseline, beta=beta, value_discount=value_discount, suffix=suffix, seed_str=seed_str)) return full_path def load_files(baseline, dev_measure, dev_fun, value_discount, beta, env_name, noops, path, suffix, seed_list, final=True): """Load result files generated by run_experiment with the given parameters.""" def try_loading(f, final): if os.path.isfile(f): df = pd.read_csv(f, index_col=0) if final: last_episode = max(df['episode']) return df[df.episode == last_episode] else: return df else: return pd.DataFrame() dataframes = [] for seed in seed_list: f = filename(baseline=baseline, dev_measure=dev_measure, dev_fun=dev_fun, value_discount=value_discount, beta=beta, env_name=env_name, noops=noops, path=path, suffix=suffix, seed=int(seed)) df_part = try_loading(f, final) dataframes.append(df_part) df = pd.concat(dataframes) return df
deepmind-research-master
side_effects_penalties/file_loading.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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Side Effects Penalties. Abstract class for implementing a side effects (impact measure) penalty, and various concrete penalties deriving from it. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import copy import enum import random import numpy as np import six from six.moves import range from six.moves import zip import sonnet as snt import tensorflow.compat.v1 as tf class Actions(enum.IntEnum): """Enum for actions the agent can take.""" UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 NOOP = 4 @six.add_metaclass(abc.ABCMeta) class Baseline(object): """Base class for baseline states.""" def __init__(self, start_timestep, exact=False, env=None, timestep_to_state=None): """Create a baseline. Args: start_timestep: starting state timestep exact: whether to use an exact or approximate baseline env: a copy of the environment (used to simulate exact baselines) timestep_to_state: a function that turns timesteps into states """ self._exact = exact self._env = env self._timestep_to_state = timestep_to_state self._start_timestep = start_timestep self._baseline_state = self._timestep_to_state(self._start_timestep) self._inaction_next = collections.defaultdict( lambda: collections.defaultdict(lambda: 0)) @abc.abstractmethod def calculate(self): """Update and return the baseline state.""" def sample(self, state): """Sample the outcome of a noop in `state`.""" d = self._inaction_next[state] counts = np.array(list(d.values())) index = np.random.choice(a=len(counts), p=counts/sum(counts)) return list(d.keys())[index] def reset(self): """Signal start of new episode.""" self._baseline_state = self._timestep_to_state(self._start_timestep) if self._exact: self._env.reset() @abc.abstractproperty def rollout_func(self): """Function to compute a rollout chain, or None if n/a.""" @property def baseline_state(self): return self._baseline_state class StartBaseline(Baseline): """Starting state baseline.""" def calculate(self, *unused_args): return self._baseline_state @property def rollout_func(self): return None class InactionBaseline(Baseline): """Inaction baseline: the state resulting from taking no-ops from start.""" def calculate(self, prev_state, action, current_state): if self._exact: self._baseline_state = self._timestep_to_state( self._env.step(Actions.NOOP)) else: if action == Actions.NOOP: self._inaction_next[prev_state][current_state] += 1 if self._baseline_state in self._inaction_next: self._baseline_state = self.sample(self._baseline_state) return self._baseline_state @property def rollout_func(self): return None class StepwiseBaseline(Baseline): """Stepwise baseline: the state one no-op after the previous state.""" def __init__(self, start_timestep, exact=False, env=None, timestep_to_state=None, use_rollouts=True): """Create a stepwise baseline. Args: start_timestep: starting state timestep exact: whether to use an exact or approximate baseline env: a copy of the environment (used to simulate exact baselines) timestep_to_state: a function that turns timesteps into states use_rollouts: whether to use inaction rollouts """ super(StepwiseBaseline, self).__init__( start_timestep, exact, env, timestep_to_state) self._rollouts = use_rollouts def calculate(self, prev_state, action, current_state): """Update and return the baseline state. Args: prev_state: the state in which `action` was taken action: the action just taken current_state: the state resulting from taking `action` Returns: the baseline state, for computing the penalty for this transition """ if self._exact: if prev_state in self._inaction_next: self._baseline_state = self.sample(prev_state) else: inaction_env = copy.deepcopy(self._env) timestep_inaction = inaction_env.step(Actions.NOOP) self._baseline_state = self._timestep_to_state(timestep_inaction) self._inaction_next[prev_state][self._baseline_state] += 1 timestep_action = self._env.step(action) assert current_state == self._timestep_to_state(timestep_action) else: if action == Actions.NOOP: self._inaction_next[prev_state][current_state] += 1 if prev_state in self._inaction_next: self._baseline_state = self.sample(prev_state) else: self._baseline_state = prev_state return self._baseline_state def _inaction_rollout(self, state): """Compute an (approximate) inaction rollout from a state.""" chain = [] st = state while st not in chain: chain.append(st) if st in self._inaction_next: st = self.sample(st) return chain def parallel_inaction_rollouts(self, s1, s2): """Compute (approximate) parallel inaction rollouts from two states.""" chain = [] states = (s1, s2) while states not in chain: chain.append(states) s1, s2 = states states = (self.sample(s1) if s1 in self._inaction_next else s1, self.sample(s2) if s2 in self._inaction_next else s2) return chain @property def rollout_func(self): return self._inaction_rollout if self._rollouts else None @six.add_metaclass(abc.ABCMeta) class DeviationMeasure(object): """Base class for deviation measures.""" @abc.abstractmethod def calculate(self): """Calculate the deviation between two states.""" @abc.abstractmethod def update(self): """Update any models after seeing a state transition.""" class ReachabilityMixin(object): """Class for computing reachability deviation measure. Computes the relative/un- reachability given a dictionary of reachability scores for pairs of states. Expects _reachability, _discount, and _dev_fun attributes to exist in the inheriting class. """ def calculate(self, current_state, baseline_state, rollout_func=None): """Calculate relative/un- reachability between particular states.""" # relative reachability case if self._dev_fun: if rollout_func: curr_values = self._rollout_values(rollout_func(current_state)) base_values = self._rollout_values(rollout_func(baseline_state)) else: curr_values = self._reachability[current_state] base_values = self._reachability[baseline_state] all_s = set(list(curr_values.keys()) + list(base_values.keys())) total = 0 for s in all_s: diff = base_values[s] - curr_values[s] total += self._dev_fun(diff) d = total / len(all_s) # unreachability case else: assert rollout_func is None d = 1 - self._reachability[current_state][baseline_state] return d def _rollout_values(self, chain): """Compute stepwise rollout values for the relative reachability penalty. Args: chain: chain of states in an inaction rollout starting with the state for which to compute the rollout values Returns: a dictionary of the form: { s : (1-discount) sum_{k=0}^inf discount^k R_s(S_k) } where S_k is the k-th state in the inaction rollout from 'state', s is a state, and R_s(S_k) is the reachability of s from S_k. """ rollout_values = collections.defaultdict(lambda: 0) coeff = 1 for st in chain: for s, rch in six.iteritems(self._reachability[st]): rollout_values[s] += coeff * rch * (1.0 - self._discount) coeff *= self._discount last_state = chain[-1] for s, rch in six.iteritems(self._reachability[last_state]): rollout_values[s] += coeff * rch return rollout_values class Reachability(ReachabilityMixin, DeviationMeasure): """Approximate (relative) (un)reachability deviation measure. Unreachability (the default, when `dev_fun=None`) uses the length (say, n) of the shortest path (sequence of actions) from the current state to the baseline state. The reachability score is value_discount ** n. Unreachability is then 1.0 - the reachability score. Relative reachability (when `dev_fun` is not `None`) considers instead the difference in reachability of all other states from the current state versus from the baseline state. We approximate reachability by only considering state transitions that have been observed. Add transitions using the `update` function. """ def __init__(self, value_discount=1.0, dev_fun=None, discount=None): self._value_discount = value_discount self._dev_fun = dev_fun self._discount = discount self._reachability = collections.defaultdict( lambda: collections.defaultdict(lambda: 0)) def update(self, prev_state, current_state, action=None): del action # Unused. self._reachability[prev_state][prev_state] = 1 self._reachability[current_state][current_state] = 1 if self._reachability[prev_state][current_state] < self._value_discount: for s1 in self._reachability.keys(): if self._reachability[s1][prev_state] > 0: for s2 in self._reachability[current_state].keys(): if self._reachability[current_state][s2] > 0: self._reachability[s1][s2] = max( self._reachability[s1][s2], self._reachability[s1][prev_state] * self._value_discount * self._reachability[current_state][s2]) @property def discount(self): return self._discount class UVFAReachability(ReachabilityMixin, DeviationMeasure): """Approximate relative reachability deviation measure using UVFA. We approximate reachability using a neural network only trained on state transitions that have been observed. For each (s0, action, s1) transition, we update the reachability estimate for (s0, action, s) towards the reachability estimate between s1 and s, for each s in a random sample of size update_sample_size. In particular, the loss for the neural network reachability estimate (NN) is sum_s(max_a(NN(s1, a, s)) * value_discount - NN(s0, action, s)), where the sum is over all sampled s, the max is taken over all actions a. At evaluation time, the reachability difference is calculated with respect to a randomly sampled set of states of size calc_sample_size. """ def __init__( self, value_discount=0.95, dev_fun=None, discount=0.95, state_size=36, # Sokoban default num_actions=5, update_sample_size=10, calc_sample_size=10, hidden_size=50, representation_size=5, num_layers=1, base_loss_coeff=0.1, num_stored=100): # Create networks to generate state representations. To get a reachability # estimate, take the dot product of the origin network output and the goal # network output, then pass it through a sigmoid function to constrain it to # between 0 and 1. output_sizes = [hidden_size] * num_layers + [representation_size] self._origin_network = snt.nets.MLP( output_sizes=output_sizes, activation=tf.nn.relu, activate_final=False, name='origin_network') self._goal_network = snt.nets.MLP( output_sizes=output_sizes, activation=tf.nn.relu, activate_final=False, name='goal_network') self._value_discount = value_discount self._dev_fun = dev_fun self._discount = discount self._state_size = state_size self._num_actions = num_actions self._update_sample_size = update_sample_size self._calc_sample_size = calc_sample_size self._num_stored = num_stored self._stored_states = set() self._state_0_placeholder = tf.placeholder(tf.float32, shape=(state_size)) self._state_1_placeholder = tf.placeholder(tf.float32, shape=(state_size)) self._action_placeholder = tf.placeholder(tf.float32, shape=(num_actions)) self._update_sample_placeholder = tf.placeholder( tf.float32, shape=(update_sample_size, state_size)) self._calc_sample_placeholder = tf.placeholder( tf.float32, shape=(calc_sample_size, state_size)) # Trained to estimate reachability = value_discount ^ distance. self._sample_loss = self._get_state_action_loss( self._state_0_placeholder, self._state_1_placeholder, self._action_placeholder, self._update_sample_placeholder) # Add additional loss to force observed transitions towards value_discount. self._base_reachability = self._get_state_sample_reachability( self._state_0_placeholder, tf.expand_dims(self._state_1_placeholder, axis=0), action=self._action_placeholder) self._base_case_loss = tf.keras.losses.MSE(self._value_discount, self._base_reachability) self._opt = tf.train.AdamOptimizer().minimize(self._sample_loss + base_loss_coeff * self._base_case_loss) current_state_reachability = self._get_state_sample_reachability( self._state_0_placeholder, self._calc_sample_placeholder) baseline_state_reachability = self._get_state_sample_reachability( self._state_1_placeholder, self._calc_sample_placeholder) self._reachability_calculation = [ tf.reshape(baseline_state_reachability, [-1]), tf.reshape(current_state_reachability, [-1]) ] init = tf.global_variables_initializer() self._sess = tf.Session() self._sess.run(init) def calculate(self, current_state, baseline_state, rollout_func=None): """Compute the reachability penalty between two states.""" current_state = np.array(current_state).flatten() baseline_state = np.array(baseline_state).flatten() sample = self._sample_n_states(self._calc_sample_size) # Run if there are enough states to draw a correctly-sized sample from. if sample: base, curr = self._sess.run( self._reachability_calculation, feed_dict={ self._state_0_placeholder: current_state, self._state_1_placeholder: baseline_state, self._calc_sample_placeholder: sample }) return sum(map(self._dev_fun, base - curr)) / self._calc_sample_size else: return 0 def _sample_n_states(self, n): try: return random.sample(self._stored_states, n) except ValueError: return None def update(self, prev_state, current_state, action): prev_state = np.array(prev_state).flatten() current_state = np.array(current_state).flatten() one_hot_action = np.zeros(self._num_actions) one_hot_action[action] = 1 sample = self._sample_n_states(self._update_sample_size) if self._num_stored is None or len(self._stored_states) < self._num_stored: self._stored_states.add(tuple(prev_state)) self._stored_states.add(tuple(current_state)) elif (np.random.random() < 0.01 and tuple(current_state) not in self._stored_states): self._stored_states.pop() self._stored_states.add(tuple(current_state)) # If there aren't enough states to get a full sample, do nothing. if sample: self._sess.run([self._opt], feed_dict={ self._state_0_placeholder: prev_state, self._state_1_placeholder: current_state, self._action_placeholder: one_hot_action, self._update_sample_placeholder: sample }) def _get_state_action_loss(self, prev_state, current_state, action, sample): """Get the loss from differences in state reachability estimates.""" # Calculate NN(s0, action, s) for all s in sample. prev_state_reachability = self._get_state_sample_reachability( prev_state, sample, action=action) # Calculate max_a(NN(s1, a, s)) for all s in sample and all actions a. current_state_reachability = tf.stop_gradient( self._get_state_sample_reachability(current_state, sample)) # Combine to return loss. return tf.keras.losses.MSE( current_state_reachability * self._value_discount, prev_state_reachability) def _get_state_sample_reachability(self, state, sample, action=None): """Calculate reachability from a state to each item in a sample.""" if action is None: state_options = self._tile_with_all_actions(state) else: state_options = tf.expand_dims(tf.concat([state, action], axis=0), axis=0) goal_representations = self._goal_network(sample) # Reachability of sampled states by taking actions reach_result = tf.sigmoid( tf.reduce_max( tf.matmul( goal_representations, self._origin_network(state_options), transpose_b=True), axis=1)) if action is None: # Return 1 if sampled state is already reached (equal to state) reach_no_action = tf.cast(tf.reduce_all(tf.equal(sample, state), axis=1), dtype=tf.float32) reach_result = tf.maximum(reach_result, reach_no_action) return reach_result def _tile_with_all_actions(self, state): """Returns tensor with all state/action combinations.""" state_tiled = tf.tile(tf.expand_dims(state, axis=0), [self._num_actions, 1]) all_actions_tiled = tf.one_hot( tf.range(self._num_actions), depth=self._num_actions) return tf.concat([state_tiled, all_actions_tiled], axis=1) class AttainableUtilityMixin(object): """Class for computing attainable utility measure. Computes attainable utility (averaged over a set of utility functions) given value functions for each utility function. Expects _u_values, _discount, _value_discount, and _dev_fun attributes to exist in the inheriting class. """ def calculate(self, current_state, baseline_state, rollout_func=None): if rollout_func: current_values = self._rollout_values(rollout_func(current_state)) baseline_values = self._rollout_values(rollout_func(baseline_state)) else: current_values = [u_val[current_state] for u_val in self._u_values] baseline_values = [u_val[baseline_state] for u_val in self._u_values] penalties = [self._dev_fun(base_val - cur_val) * (1. - self._value_discount) for base_val, cur_val in zip(baseline_values, current_values)] return sum(penalties) / len(penalties) def _rollout_values(self, chain): """Compute stepwise rollout values for the attainable utility penalty. Args: chain: chain of states in an inaction rollout starting with the state for which to compute the rollout values Returns: a list containing (1-discount) sum_{k=0}^inf discount^k V_u(S_k) for each utility function u, where S_k is the k-th state in the inaction rollout from 'state'. """ rollout_values = [0 for _ in self._u_values] coeff = 1 for st in chain: rollout_values = [rv + coeff * u_val[st] * (1.0 - self._discount) for rv, u_val in zip(rollout_values, self._u_values)] coeff *= self._discount last_state = chain[-1] rollout_values = [rv + coeff * u_val[last_state] for rv, u_val in zip(rollout_values, self._u_values)] return rollout_values def _set_util_funs(self, util_funs): """Set up this instance's utility functions. Args: util_funs: either a number of functions to generate or a list of pre-defined utility functions, represented as dictionaries over states: util_funs[i][s] = u_i(s), the utility of s according to u_i. """ if isinstance(util_funs, int): self._util_funs = [ collections.defaultdict(float) for _ in range(util_funs) ] else: self._util_funs = util_funs def _utility(self, u, state): """Apply a random utility function, generating its value if necessary.""" if state not in u: u[state] = np.random.random() return u[state] class AttainableUtility(AttainableUtilityMixin, DeviationMeasure): """Approximate attainable utility deviation measure.""" def __init__(self, value_discount=0.99, dev_fun=np.abs, util_funs=10, discount=None): assert value_discount < 1.0 # AU does not converge otherwise self._value_discount = value_discount self._dev_fun = dev_fun self._discount = discount self._set_util_funs(util_funs) # u_values[i][s] = V_{u_i}(s), the (approximate) value of s according to u_i self._u_values = [ collections.defaultdict(float) for _ in range(len(self._util_funs)) ] # predecessors[s] = set of states known to lead, by some action, to s self._predecessors = collections.defaultdict(set) def update(self, prev_state, current_state, action=None): """Update predecessors and attainable utility estimates.""" del action # Unused. self._predecessors[current_state].add(prev_state) seen = set() queue = [current_state] while queue: s_to = queue.pop(0) seen.add(s_to) for u, u_val in zip(self._util_funs, self._u_values): for s_from in self._predecessors[s_to]: v = self._utility(u, s_from) + self._value_discount * u_val[s_to] if u_val[s_from] < v: u_val[s_from] = v if s_from not in seen: queue.append(s_from) class NoDeviation(DeviationMeasure): """Dummy deviation measure corresponding to no impact penalty.""" def calculate(self, *unused_args): return 0 def update(self, *unused_args): pass class SideEffectPenalty(object): """Impact penalty.""" def __init__( self, baseline, dev_measure, beta=1.0, nonterminal_weight=0.01, use_inseparable_rollout=False): """Make an object to calculate the impact penalty. Args: baseline: object for calculating the baseline state dev_measure: object for calculating the deviation between states beta: weight (scaling factor) for the impact penalty nonterminal_weight: penalty weight on nonterminal states. use_inseparable_rollout: whether to compute the penalty as the average of deviations over parallel inaction rollouts from the current and baseline states (True) otherwise just between the current state and baseline state (or by whatever rollout value is provided in the baseline) (False) """ self._baseline = baseline self._dev_measure = dev_measure self._beta = beta self._nonterminal_weight = nonterminal_weight self._use_inseparable_rollout = use_inseparable_rollout def calculate(self, prev_state, action, current_state): """Calculate the penalty associated with a transition, and update models.""" def compute_penalty(current_state, baseline_state): """Compute penalty.""" if self._use_inseparable_rollout: penalty = self._rollout_value(current_state, baseline_state, self._dev_measure.discount, self._dev_measure.calculate) else: penalty = self._dev_measure.calculate(current_state, baseline_state, self._baseline.rollout_func) return self._beta * penalty if current_state: # not a terminal state self._dev_measure.update(prev_state, current_state, action) baseline_state =\ self._baseline.calculate(prev_state, action, current_state) penalty = compute_penalty(current_state, baseline_state) return self._nonterminal_weight * penalty else: # terminal state penalty = compute_penalty(prev_state, self._baseline.baseline_state) return penalty def reset(self): """Signal start of new episode.""" self._baseline.reset() def _rollout_value(self, cur_state, base_state, discount, func): """Compute stepwise rollout value for unreachability.""" # Returns (1-discount) sum_{k=0}^inf discount^k R(S_{t,t+k}, S'_{t,t+k}), # where S_{t,t+k} is k-th state in the inaction rollout from current state, # S'_{t,t+k} is k-th state in the inaction rollout from baseline state, # and R is the reachability function. chain = self._baseline.parallel_inaction_rollouts(cur_state, base_state) coeff = 1 rollout_value = 0 for states in chain: rollout_value += (coeff * func(states[0], states[1]) * (1.0 - discount)) coeff *= discount last_states = chain[-1] rollout_value += coeff * func(last_states[0], last_states[1]) return rollout_value @property def beta(self): return self._beta
deepmind-research-master
side_effects_penalties/side_effects_penalty.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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================
deepmind-research-master
side_effects_penalties/__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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for side_effects_penalty.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest from absl.testing import parameterized import numpy as np from six.moves import range from side_effects_penalties import side_effects_penalty from side_effects_penalties import training from side_effects_penalties.side_effects_penalty import Actions environments = ['box', 'vase', 'sushi_goal'] class SideEffectsTestCase(parameterized.TestCase): def _timestep_to_state(self, timestep): return tuple(map(tuple, np.copy(timestep.observation['board']))) def _env_to_action_range(self, env): action_spec = env.action_spec() action_range = list(range(action_spec.minimum, action_spec.maximum + 1)) return action_range class BaselineTestCase(SideEffectsTestCase): def _create_baseline(self, env_name): self._env, _ = training.get_env(env_name, True) self._baseline_env, _ = training.get_env(env_name, True) baseline_class = getattr(side_effects_penalty, self.__class__.__name__[:-4]) # remove 'Test' self._baseline = baseline_class( self._env.reset(), True, self._baseline_env, self._timestep_to_state) def _test_trajectory(self, actions, key): init_state = self._timestep_to_state(self._env.reset()) self._baseline.reset() current_state = init_state for action in actions: timestep = self._env.step(action) next_state = self._timestep_to_state(timestep) baseline_state = self._baseline.calculate(current_state, action, next_state) comparison_dict = { 'current_state': current_state, 'next_state': next_state, 'init_state': init_state } self.assertEqual(baseline_state, comparison_dict[key]) current_state = next_state if timestep.last(): return class StartBaselineTest(BaselineTestCase): @parameterized.parameters(*environments) def testInit(self, env_name): self._create_baseline(env_name) self._test_trajectory([Actions.NOOP], 'init_state') @parameterized.parameters(*environments) def testTenNoops(self, env_name): self._create_baseline(env_name) self._test_trajectory([Actions.NOOP for _ in range(10)], 'init_state') class InactionBaselineTest(BaselineTestCase): box_env, _ = training.get_env('box', True) box_action_spec = box_env.action_spec() @parameterized.parameters( *list(range(box_action_spec.minimum, box_action_spec.maximum + 1))) def testStaticEnvOneAction(self, action): self._create_baseline('box') self._test_trajectory([action], 'init_state') def testStaticEnvRandomActions(self): self._create_baseline('box') num_steps = np.random.randint(low=1, high=20) action_range = self._env_to_action_range(self._env) actions = [np.random.choice(action_range) for _ in range(num_steps)] self._test_trajectory(actions, 'init_state') @parameterized.parameters(*environments) def testInactionPolicy(self, env_name): self._create_baseline(env_name) num_steps = np.random.randint(low=1, high=20) self._test_trajectory([Actions.NOOP for _ in range(num_steps)], 'next_state') class StepwiseBaselineTest(BaselineTestCase): def testStaticEnvRandomActions(self): self._create_baseline('box') action_range = self._env_to_action_range(self._env) num_steps = np.random.randint(low=1, high=20) actions = [np.random.choice(action_range) for _ in range(num_steps)] self._test_trajectory(actions, 'current_state') @parameterized.parameters(*environments) def testInactionPolicy(self, env_name): self._create_baseline(env_name) num_steps = np.random.randint(low=1, high=20) self._test_trajectory([Actions.NOOP for _ in range(num_steps)], 'next_state') @parameterized.parameters(*environments) def testInactionRollout(self, env_name): self._create_baseline(env_name) init_state = self._timestep_to_state(self._env.reset()) self._baseline.reset() action = Actions.NOOP state1 = init_state trajectory = [init_state] for _ in range(10): trajectory.append(self._timestep_to_state(self._env.step(action))) state2 = trajectory[-1] self._baseline.calculate(state1, action, state2) state1 = state2 chain = self._baseline.rollout_func(init_state) self.assertEqual(chain, trajectory[:len(chain)]) if len(chain) < len(trajectory): self.assertEqual(trajectory[len(chain) - 1], trajectory[len(chain)]) def testStaticRollouts(self): self._create_baseline('box') action_range = self._env_to_action_range(self._env) num_steps = np.random.randint(low=1, high=20) actions = [np.random.choice(action_range) for _ in range(num_steps)] state1 = self._timestep_to_state(self._env.reset()) states = [state1] self._baseline.reset() for action in actions: state2 = self._timestep_to_state(self._env.step(action)) states.append(state2) self._baseline.calculate(state1, action, state2) state1 = state2 i1, i2 = np.random.choice(len(states), 2) chain = self._baseline.parallel_inaction_rollouts(states[i1], states[i2]) self.assertLen(chain, 1) chain1 = self._baseline.rollout_func(states[i1]) self.assertLen(chain1, 1) chain2 = self._baseline.rollout_func(states[i2]) self.assertLen(chain2, 1) @parameterized.parameters(('parallel', 'vase'), ('parallel', 'sushi'), ('inaction', 'vase'), ('inaction', 'sushi')) def testConveyorRollouts(self, which_rollout, env_name): self._create_baseline(env_name) init_state = self._timestep_to_state(self._env.reset()) self._baseline.reset() action = Actions.NOOP state1 = init_state init_state_next = self._timestep_to_state(self._env.step(action)) state2 = init_state_next self._baseline.calculate(state1, action, state2) state1 = state2 for _ in range(10): state2 = self._timestep_to_state(self._env.step(action)) self._baseline.calculate(state1, action, state2) state1 = state2 if which_rollout == 'parallel': chain = self._baseline.parallel_inaction_rollouts(init_state, init_state_next) else: chain = self._baseline.rollout_func(init_state) self.assertLen(chain, 5) class NoDeviationTest(SideEffectsTestCase): def _random_initial_transition(self): env_name = np.random.choice(environments) noops = np.random.choice([True, False]) env, _ = training.get_env(env_name, noops) action_range = self._env_to_action_range(env) action = np.random.choice(action_range) state1 = self._timestep_to_state(env.reset()) state2 = self._timestep_to_state(env.step(action)) return (state1, state2) def testNoDeviation(self): deviation = side_effects_penalty.NoDeviation() state1, state2 = self._random_initial_transition() self.assertEqual(deviation.calculate(state1, state2), 0) def testNoDeviationUpdate(self): deviation = side_effects_penalty.NoDeviation() state1, state2 = self._random_initial_transition() deviation.update(state1, state2) self.assertEqual(deviation.calculate(state1, state2), 0) class UnreachabilityTest(SideEffectsTestCase): @parameterized.named_parameters(('Discounted', 0.99), ('Undiscounted', 1.0)) def testUnreachabilityCycle(self, gamma): # Reachability with no dev_fun means unreachability deviation = side_effects_penalty.Reachability(value_discount=gamma) env, _ = training.get_env('box', False) state0 = self._timestep_to_state(env.reset()) state1 = self._timestep_to_state(env.step(Actions.LEFT)) # deviation should not be calculated before calling update deviation.update(state0, state1) self.assertEqual(deviation.calculate(state0, state0), 1.0 - 1.0) self.assertEqual(deviation.calculate(state0, state1), 1.0 - gamma) self.assertEqual(deviation.calculate(state1, state0), 1.0 - 0.0) state2 = self._timestep_to_state(env.step(Actions.RIGHT)) self.assertEqual(state0, state2) deviation.update(state1, state2) self.assertEqual(deviation.calculate(state0, state0), 1.0 - 1.0) self.assertEqual(deviation.calculate(state0, state1), 1.0 - gamma) self.assertEqual(deviation.calculate(state1, state0), 1.0 - gamma) self.assertEqual(deviation.calculate(state1, state1), 1.0 - 1.0) if __name__ == '__main__': absltest.main()
deepmind-research-master
side_effects_penalties/side_effects_penalty_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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Q-learning with side effects penalties.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from side_effects_penalties import agent from side_effects_penalties import side_effects_penalty as sep class QLearningSE(agent.QLearning): """Q-learning agent with side-effects penalties.""" def __init__( self, actions, alpha=0.1, epsilon=0.1, q_initialisation=0.0, baseline='start', dev_measure='none', dev_fun='truncation', discount=0.99, value_discount=1.0, beta=1.0, num_util_funs=10, exact_baseline=False, baseline_env=None, start_timestep=None, state_size=None, nonterminal_weight=0.01): """Create a Q-learning agent with a side effects penalty. Args: actions: full discrete action spec. alpha: agent learning rate. epsilon: agent exploration rate. q_initialisation: float, used to initialise the value function. baseline: which baseline state to use ('start', 'inaction', 'stepwise'). dev_measure: deviation measure: - "none" for no penalty, - "reach" for unreachability, - "rel_reach" for relative reachability, - "att_util" for attainable utility, dev_fun: what function to apply in the deviation measure ('truncation' or 'absolute' (for 'rel_reach' and 'att_util'), or 'none' (otherwise)). discount: discount factor for rewards. value_discount: discount factor for value functions in penalties. beta: side effects penalty weight. num_util_funs: number of random utility functions for attainable utility. exact_baseline: whether to use an exact or approximate baseline. baseline_env: copy of environment (with noops) for the exact baseline. start_timestep: copy of starting timestep for the baseline. state_size: the size of each state (flattened) for NN reachability. nonterminal_weight: penalty weight on nonterminal states. Raises: ValueError: for incorrect baseline, dev_measure, or dev_fun """ super(QLearningSE, self).__init__(actions, alpha, epsilon, q_initialisation, discount) # Impact penalty: set dev_fun (f) if 'rel_reach' in dev_measure or 'att_util' in dev_measure: if dev_fun == 'truncation': dev_fun = lambda diff: np.maximum(0, diff) elif dev_fun == 'absolute': dev_fun = np.abs else: raise ValueError('Deviation function not recognized') else: assert dev_fun == 'none' dev_fun = None # Impact penalty: create deviation measure if dev_measure in {'reach', 'rel_reach'}: deviation = sep.Reachability(value_discount, dev_fun, discount) elif dev_measure == 'uvfa_rel_reach': deviation = sep.UVFAReachability(value_discount, dev_fun, discount, state_size) elif dev_measure == 'att_util': deviation = sep.AttainableUtility(value_discount, dev_fun, num_util_funs, discount) elif dev_measure == 'none': deviation = sep.NoDeviation() else: raise ValueError('Deviation measure not recognized') use_inseparable_rollout = ( dev_measure == 'reach' and baseline == 'stepwise') # Impact penalty: create baseline if baseline in {'start', 'inaction', 'stepwise'}: baseline_class = getattr(sep, baseline.capitalize() + 'Baseline') baseline = baseline_class(start_timestep, exact_baseline, baseline_env, self._timestep_to_state) elif baseline == 'step_noroll': baseline_class = getattr(sep, 'StepwiseBaseline') baseline = baseline_class(start_timestep, exact_baseline, baseline_env, self._timestep_to_state, False) else: raise ValueError('Baseline not recognized') self._impact_penalty = sep.SideEffectPenalty( baseline, deviation, beta, nonterminal_weight, use_inseparable_rollout) def begin_episode(self): """Perform episode initialisation.""" super(QLearningSE, self).begin_episode() self._impact_penalty.reset() def _calculate_reward(self, timestep, state): reward = super(QLearningSE, self)._calculate_reward(timestep, state) return (reward - self._impact_penalty.calculate( self._current_state, self._current_action, state))
deepmind-research-master
side_effects_penalties/agent_with_penalties.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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Vanilla Q-Learning agent.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from collections import abc import numpy as np from six.moves import range class EpsilonGreedyPolicy(object): """Epsilon greedy policy for table value function lookup.""" def __init__(self, value_function, actions): """Construct an epsilon greedy policy object. Args: value_function: agent value function as a dict. actions: list of possible actions. Raises: ValueError: if `actions` agument is not an iterable. """ if not isinstance(actions, abc.Iterable): raise ValueError('`actions` argument must be an iterable.') self._value_function = value_function self._actions = actions def get_action(self, epsilon, state): """Get action following the e-greedy policy. Args: epsilon: probability of selecting a random action state: current state of the game as a state/action tuple. Returns: Chosen action. """ if np.random.random() < epsilon: return np.random.choice(self._actions) else: values = [self._value_function[(state, action)] for action in self._actions] max_value = max(values) max_indices = [i for i, value in enumerate(values) if value == max_value] return self._actions[np.random.choice(max_indices)] class QLearning(object): """Q-learning agent.""" def __init__(self, actions, alpha=0.1, epsilon=0.1, q_initialisation=0.0, discount=0.99): """Create a Q-learning agent. Args: actions: a BoundedArraySpec that specifes full discrete action spec. alpha: agent learning rate. epsilon: agent exploration rate. q_initialisation: float, used to initialise the value function. discount: discount factor for rewards. """ self._value_function = collections.defaultdict(lambda: q_initialisation) self._valid_actions = list(range(actions.minimum, actions.maximum + 1)) self._policy = EpsilonGreedyPolicy(self._value_function, self._valid_actions) # Hyperparameters. self.alpha = alpha self.epsilon = epsilon self.discount = discount # Episode internal variables. self._current_action = None self._current_state = None def begin_episode(self): """Perform episode initialisation.""" self._current_state = None self._current_action = None def _timestep_to_state(self, timestep): return tuple(map(tuple, np.copy(timestep.observation['board']))) def step(self, timestep): """Perform a single step in the environment.""" # Get state observations. state = self._timestep_to_state(timestep) # This is one of the follow up states (i.e. not the initial state). if self._current_state is not None: self._update(timestep, state) self._current_state = state # Determine action. self._current_action = self._policy.get_action(self.epsilon, state) # Emit action. return self._current_action def _calculate_reward(self, timestep, unused_state): """Calculate reward: to be extended when impact penalty is added.""" reward = timestep.reward return reward def _update(self, timestep, state): """Perform value function update.""" reward = self._calculate_reward(timestep, state) # Terminal state. if not state: delta = (reward - self._value_function[(self._current_state, self._current_action)]) # Non-terminal state. else: max_action = self._policy.get_action(0, state) delta = ( reward + self.discount * self._value_function[(state, max_action)] - self._value_function[(self._current_state, self._current_action)]) self._value_function[(self._current_state, self._current_action)] += self.alpha * delta def end_episode(self, timestep): """Performs episode cleanup.""" # Update for the terminal state. self._update(timestep, None) @property def value_function(self): return self._value_function
deepmind-research-master
side_effects_penalties/agent.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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Run a Q-learning agent with a side effects penalty.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags import pandas as pd from six.moves import range from six.moves import zip from side_effects_penalties import agent_with_penalties from side_effects_penalties import training from side_effects_penalties.file_loading import filename FLAGS = flags.FLAGS if __name__ == '__main__': # Avoid defining flags when used as a library. # Side effects penalty settings flags.DEFINE_enum('baseline', 'inaction', ['start', 'inaction', 'stepwise', 'step_noroll'], 'Baseline.') flags.DEFINE_enum('dev_measure', 'rel_reach', ['none', 'reach', 'rel_reach', 'uvfa_rel_reach', 'att_util'], 'Deviation measure.') flags.DEFINE_enum('dev_fun', 'truncation', ['truncation', 'absolute'], 'Summary function for the deviation measure.') flags.DEFINE_float('discount', 0.99, 'Discount factor for rewards.') flags.DEFINE_float('value_discount', 0.99, 'Discount factor for deviation measure value function.') flags.DEFINE_float('beta', 30.0, 'Weight for side effects penalty.') flags.DEFINE_string('nonterminal', 'disc', 'Penalty for nonterminal states relative to terminal' 'states: none (0), full (1), or disc (1-discount).') flags.DEFINE_bool('exact_baseline', False, 'Compute the exact baseline using an environment copy.') # Agent settings flags.DEFINE_bool('anneal', True, 'Whether to anneal the exploration rate from 1 to 0.') flags.DEFINE_integer('num_episodes', 10000, 'Number of episodes.') flags.DEFINE_integer('num_episodes_noexp', 0, 'Number of episodes with no exploration.') flags.DEFINE_integer('seed', 1, 'Random seed.') # Environment settings flags.DEFINE_string('env_name', 'box', 'Environment name.') flags.DEFINE_bool('noops', True, 'Whether the environment includes noops.') flags.DEFINE_integer('movement_reward', 0, 'Movement reward.') flags.DEFINE_integer('goal_reward', 1, 'Reward for reaching a goal state.') flags.DEFINE_integer('side_effect_reward', -1, 'Hidden reward for causing side effects.') # Settings for outputting results flags.DEFINE_enum('mode', 'save', ['print', 'save'], 'Print results or save to file.') flags.DEFINE_string('path', '', 'File path.') flags.DEFINE_string('suffix', '', 'Filename suffix.') def run_experiment( baseline, dev_measure, dev_fun, discount, value_discount, beta, nonterminal, exact_baseline, anneal, num_episodes, num_episodes_noexp, seed, env_name, noops, movement_reward, goal_reward, side_effect_reward, mode, path, suffix): """Run agent and save or print the results.""" performances = [] rewards = [] seeds = [] episodes = [] if 'rel_reach' not in dev_measure and 'att_util' not in dev_measure: dev_fun = 'none' nonterminal_weights = {'none': 0.0, 'disc': 1.0-discount, 'full': 1.0} nonterminal_weight = nonterminal_weights[nonterminal] reward, performance = training.run_agent( baseline=baseline, dev_measure=dev_measure, dev_fun=dev_fun, discount=discount, value_discount=value_discount, beta=beta, nonterminal_weight=nonterminal_weight, exact_baseline=exact_baseline, anneal=anneal, num_episodes=num_episodes, num_episodes_noexp=num_episodes_noexp, seed=seed, env_name=env_name, noops=noops, movement_reward=movement_reward, goal_reward=goal_reward, side_effect_reward=side_effect_reward, agent_class=agent_with_penalties.QLearningSE) rewards.extend(reward) performances.extend(performance) seeds.extend([seed] * (num_episodes + num_episodes_noexp)) episodes.extend(list(range(num_episodes + num_episodes_noexp))) if mode == 'save': d = {'reward': rewards, 'performance': performances, 'seed': seeds, 'episode': episodes} df = pd.DataFrame(d) df1 = add_smoothed_data(df) f = filename(env_name, noops, dev_measure, dev_fun, baseline, beta, value_discount, path=path, suffix=suffix, seed=seed) df1.to_csv(f) return reward, performance def _smooth(values, window=100): return values.rolling(window,).mean() def add_smoothed_data(df, groupby='seed', window=100): grouped = df.groupby(groupby)[['reward', 'performance']] grouped = grouped.apply(_smooth, window=window).rename(columns={ 'performance': 'performance_smooth', 'reward': 'reward_smooth'}) temp = pd.concat([df, grouped], axis=1) return temp def main(unused_argv): reward, performance = run_experiment( baseline=FLAGS.baseline, dev_measure=FLAGS.dev_measure, dev_fun=FLAGS.dev_fun, discount=FLAGS.discount, value_discount=FLAGS.value_discount, beta=FLAGS.beta, nonterminal=FLAGS.nonterminal, exact_baseline=FLAGS.exact_baseline, anneal=FLAGS.anneal, num_episodes=FLAGS.num_episodes, num_episodes_noexp=FLAGS.num_episodes_noexp, seed=FLAGS.seed, env_name=FLAGS.env_name, noops=FLAGS.noops, movement_reward=FLAGS.movement_reward, goal_reward=FLAGS.goal_reward, side_effect_reward=FLAGS.side_effect_reward, mode=FLAGS.mode, path=FLAGS.path, suffix=FLAGS.suffix) if FLAGS.mode == 'print': print('Performance and reward in the last 10 steps:') print(list(zip(performance, reward))[-10:-1]) if __name__ == '__main__': app.run(main)
deepmind-research-master
side_effects_penalties/run_experiment.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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Training loop.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from ai_safety_gridworlds.helpers import factory import numpy as np from six.moves import range def get_env(env_name, noops, movement_reward=-1, goal_reward=1, side_effect_reward=-1): """Get a copy of the environment for simulating the baseline.""" if env_name == 'box' or 'sokocoin' in env_name: levels = {'box': 0, 'sokocoin1': 1, 'sokocoin2': 2, 'sokocoin3': 3} sizes = {'box': 36, 'sokocoin1': 100, 'sokocoin2': 72, 'sokocoin3': 100} env = factory.get_environment_obj( 'side_effects_sokoban', noops=noops, movement_reward=movement_reward, goal_reward=goal_reward, wall_reward=side_effect_reward, corner_reward=side_effect_reward, level=levels[env_name]) size = sizes[env_name] elif 'sushi' in env_name or env_name == 'vase': env = factory.get_environment_obj( 'conveyor_belt', variant=env_name, noops=noops, goal_reward=goal_reward) size = 49 else: env = factory.get_environment_obj(env_name) size = None return env, size def run_loop(agent, env, number_episodes, anneal): """Training agent.""" episodic_returns = [] episodic_performances = [] if anneal: agent.epsilon = 1.0 eps_unit = 1.0 / number_episodes for episode in range(number_episodes): # Get the initial set of observations from the environment. timestep = env.reset() # Prepare agent for a new episode. agent.begin_episode() while True: action = agent.step(timestep) timestep = env.step(action) if timestep.last(): agent.end_episode(timestep) episodic_returns.append(env.episode_return) episodic_performances.append(env.get_last_performance()) break if anneal: agent.epsilon = max(0, agent.epsilon - eps_unit) if episode % 500 == 0: print('Episode', episode) return episodic_returns, episodic_performances def run_agent(baseline, dev_measure, dev_fun, discount, value_discount, beta, nonterminal_weight, exact_baseline, anneal, num_episodes, num_episodes_noexp, seed, env_name, noops, movement_reward, goal_reward, side_effect_reward, agent_class): """Run agent. Create an agent with the given parameters for the side effects penalty. Run the agent for `num_episodes' episodes with an exploration rate that is either annealed from 1 to 0 (`anneal=True') or constant (`anneal=False'). Then run the agent with no exploration for `num_episodes_noexp' episodes. Args: baseline: baseline state dev_measure: deviation measure dev_fun: summary function for the deviation measure discount: discount factor value_discount: discount factor for deviation measure value function. beta: weight for side effects penalty nonterminal_weight: penalty weight for nonterminal states. exact_baseline: whether to use an exact or approximate baseline anneal: whether to anneal the exploration rate from 1 to 0 or use a constant exploration rate num_episodes: number of episodes num_episodes_noexp: number of episodes with no exploration seed: random seed env_name: environment name noops: whether the environment has noop actions movement_reward: movement reward goal_reward: reward for reaching a goal state side_effect_reward: hidden reward for causing side effects agent_class: Q-learning agent class: QLearning (regular) or QLearningSE (with side effects penalty) Returns: returns: return for each episode performances: safety performance for each episode """ np.random.seed(seed) env, state_size = get_env(env_name=env_name, noops=noops, movement_reward=movement_reward, goal_reward=goal_reward, side_effect_reward=side_effect_reward) start_timestep = env.reset() if exact_baseline: baseline_env, _ = get_env(env_name=env_name, noops=True, movement_reward=movement_reward, goal_reward=goal_reward, side_effect_reward=side_effect_reward) else: baseline_env = None agent = agent_class( actions=env.action_spec(), baseline=baseline, dev_measure=dev_measure, dev_fun=dev_fun, discount=discount, value_discount=value_discount, beta=beta, exact_baseline=exact_baseline, baseline_env=baseline_env, start_timestep=start_timestep, state_size=state_size, nonterminal_weight=nonterminal_weight) returns, performances = run_loop( agent, env, number_episodes=num_episodes, anneal=anneal) if num_episodes_noexp > 0: agent.epsilon = 0 returns_noexp, performances_noexp = run_loop( agent, env, number_episodes=num_episodes_noexp, anneal=False) returns.extend(returns_noexp) performances.extend(performances_noexp) return returns, performances
deepmind-research-master
side_effects_penalties/training.py
# Copyright 2020 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. # ============================================================================ """Construct DAGs representing causal graphs, and perform inference on them.""" import collections import haiku as hk import jax import jax.numpy as jnp import pandas as pd from tensorflow_probability.substrates import jax as tfp import tree class Node: """A node in a graphical model. Conceptually, this represents a random variable in a causal probabilistic model. It knows about its 'parents', i.e. other Nodes upon which this Node causally depends. The user is responsible for ensuring that any graph built with this class is acyclic. A node knows how to represent its probability density, conditional on the values of its parents. The node needs to have a 'name', corresponding to the series within the dataframe that should be used to populate it. """ def __init__(self, distribution_module, parents=(), hidden=False): """Initialise a `Node` instance. Args: distribution_module: An instance of `DistributionModule`, a Haiku module that is suitable for modelling the conditional distribution of this node given any parents. parents: `Iterable`, optional. A (potentially nested) collection of nodes which are direct ancestors of `self`. hidden: `bool`, optional. Whether this node is hidden. Hidden nodes are permitted to not have corresponding observations. """ parents = tree.flatten(parents) self._distribution_module = distribution_module self._column = distribution_module.column self._index = distribution_module.index self._hidden = hidden self._observed_value = None # When implementing the path-specific counterfactual fairness algorithm, # we need the concept of a distribution conditional on the 'corrected' # values of the parents. This is achieved via the 'node_to_replacement' # argument of make_distribution. # However, in order to work with the `fix_categorical` and `fix_continuous` # functions, we need to assign counterfactual values for parents at # evaluation time. self._parent_to_value = collections.OrderedDict( (parent, None) for parent in parents) # This is the conditional distribution using no replacements, i.e. it is # conditioned on the observed values of parents. self._distribution = None def __repr__(self): return 'Node<{}>'.format(self.name) @property def dim(self): """The dimensionality of this node.""" return self._distribution_module.dim @property def name(self): return self._column @property def hidden(self): return self._hidden @property def observed_value(self): return self._observed_value def find_ancestor(self, name): """Returns an ancestor node with the given name.""" if self.name == name: return self for parent in self.parents: found = parent.find_ancestor(name) if found is not None: return found @property def parents(self): return tuple(self._parent_to_value) @property def distribution_module(self): return self._distribution_module @property def distribution(self): self._distribution = self.make_distribution() return self._distribution def make_distribution(self, node_to_replacement=None): """Make a conditional distribution for this node | parents. By default we use values (representing 'real data') from the parent nodes as inputs to the distribution, however we can alternatively swap out any of these for arbitrary arrays by specifying `node_to_replacement`. Args: node_to_replacement: `None`, `dict: Node -> DeviceArray`. If specified, use the indicated array. Returns: `tfp.distributions.Distribution` """ cur_parent_to_value = self._parent_to_value self._parent_to_value = collections.OrderedDict( (parent, parent.observed_value) for parent in cur_parent_to_value.keys() ) if node_to_replacement is None: parent_values = self._parent_to_value.values() return self._distribution_module(*parent_values) args = [] for node, value in self._parent_to_value.items(): if node in node_to_replacement: replacement = node_to_replacement[node] args.append(replacement) else: args.append(value) return self._distribution_module(*args) def populate(self, data, node_to_replacement=None): """Given a dataframe, populate node data. If the Node does not have data present, this is taken to be a sign of a) An error if the node is not hidden. b) Fine if the node is hidden. In case a) an exception will be raised, and in case b) observed)v will not be mutated. Args: data: tf.data.Dataset node_to_replacement: None | dict(Node -> array). If not None, use the given ndarray data rather than extracting data from the frame. This is only considered when looking at the inputs to a distribution. Raises: RuntimeError: If `data` doesn't contain the necessary feature, and the node is not hidden. """ column = self._column hidden = self._hidden replacement = None if node_to_replacement is not None and self in node_to_replacement: replacement = node_to_replacement[self] if replacement is not None: # If a replacement is present, this takes priority over any other # consideration. self._observed_value = replacement return if self._index < 0: if not hidden: raise RuntimeError( 'Node {} is not hidden, and column {} is not in the frame.'.format( self, column)) # Nothing to do - there is no data, and the node is hidden. return # Produce the observed value for this node. self._observed_value = self._distribution_module.prepare_data(data) class DistributionModule(hk.Module): """Common base class for a Haiku module representing a distribution. This provides some additional functionality common to all modules that would be used as arguments to the `Node` class above. """ def __init__(self, column, index, dim): """Initialise a `DistributionModule` instance. Args: column: `string`. The name of the random variable to which this distribution corresponds, and should match the name of the series in the pandas dataframe. index: `int`. The index of the corresponding feature in the dataset. dim: `int`. The output dimensionality of the distribution. """ super().__init__(name=column.replace('-', '_')) self._column = column self._index = index self._dim = dim @property def dim(self): """The output dimensionality of this distribution.""" return self._dim @property def column(self): return self._column @property def index(self): return self._index def prepare_data(self, data): """Given a general tensor, return an ndarray if required. This method implements the functionality delegated from `Node._prepare_data`, and it is expected that subclasses will override the implementation appropriately. Args: data: A tf.data.Dataset. Returns: `np.ndarray` of appropriately converted values for this series. """ return data[:, [self._index]] def _package_args(self, args): """Concatenate args into a single tensor. Args: args: `List[DeviceArray]`, length > 0. Each array is of shape (batch_size, ?) or (batch_size,). The former will occur if looking at e.g. a one-hot encoded categorical variable, and the latter in the case of a continuous variable. Returns: `DeviceArray`, (batch_size, num_values). """ return jnp.concatenate(args, axis=1) class Gaussian(DistributionModule): """A Haiku module that maps some inputs into a normal distribution.""" def __init__(self, column, index, dim=1, hidden_shape=(), hidden_activation=jnp.tanh, scale=None): """Initialise a `Gaussian` instance with some dimensionality.""" super(Gaussian, self).__init__(column, index, dim) self._hidden_shape = tuple(hidden_shape) self._hidden_activation = hidden_activation self._scale = scale self._loc_net = hk.nets.MLP(self._hidden_shape + (self._dim,), activation=self._hidden_activation) def __call__(self, *args): if args: # There are arguments - these represent the variables on which we are # conditioning. We set the mean of the output distribution to be a # function of these values, parameterised with an MLP. concatenated_inputs = self._package_args(args) loc = self._loc_net(concatenated_inputs) else: # There are no arguments, so instead have a learnable location parameter. loc = hk.get_parameter('loc', shape=[self._dim], init=jnp.zeros) if self._scale is None: # The scale has not been explicitly specified, in which case it is left # to be single value, i.e. not a function of the conditioning set. log_var = hk.get_parameter('log_var', shape=[self._dim], init=jnp.ones) scale = jnp.sqrt(jnp.exp(log_var)) else: scale = jnp.float32(self._scale) return tfp.distributions.Normal(loc=loc, scale=scale) def prepare_data(self, data): # For continuous data, we ensure the data is of dtype float32, and # additionally that the resulant shape is (num_examples, 1) # Note that this implementation only works for dim=1, however this is # currently also enforced by the fact that pandas series cannot be # multidimensional. result = data[:, [self.index]].astype(jnp.float32) if len(result.shape) == 1: result = jnp.expand_dims(result, axis=1) return result class GaussianMixture(DistributionModule): """A Haiku module that maps some inputs into a mixture of normals.""" def __init__(self, column, num_components, dim=1): """Initialise a `GaussianMixture` instance with some dimensionality. Args: column: `string`. The name of the column. num_components: `int`. The number of gaussians in this mixture. dim: `int`. The dimensionality of the variable. """ super().__init__(column, -1, dim) self._num_components = num_components self._loc_net = hk.nets.MLP([self._dim]) self._categorical_logits_module = hk.nets.MLP([self._num_components]) def __call__(self, *args): # Define component Gaussians to be independent functions of args. locs = [] scales = [] for _ in range(self._num_components): loc = hk.get_parameter('loc', shape=[self._dim], init=jnp.zeros) log_var = hk.get_parameter('log_var', shape=[self._dim], init=jnp.ones) scale = jnp.sqrt(jnp.exp(log_var)) locs.extend(loc) scales.extend(scale) # Define the Categorical distribution which switches between these categorical_logits = hk.get_parameter('categorical_logits', shape=[self._num_components], init=jnp.zeros) # Enforce positivity in the logits categorical_logits = jax.nn.sigmoid(categorical_logits) # If we have a multidimensional node, then the normal distributions above # have a batch shape of (dim,). We want to select between these using the # categorical distribution, so tile the logits to match this shape expanded_logits = jnp.repeat(categorical_logits, self._dim) categorical = tfp.distributions.Categorical(logits=expanded_logits) return tfp.distributions.MixtureSameFamily( mixture_distribution=categorical, components_distribution=tfp.distributions.Normal( loc=locs, scale=scales)) class MLPMultinomial(DistributionModule): """A Haiku module that consists of an MLP + multinomial distribution.""" def __init__(self, column, index, dim, hidden_shape=(), hidden_activation=jnp.tanh): """Initialise an MLPMultinomial instance. Args: column: `string`. Name of the corresponding dataframe column. index: `int`. The index of the input data for this feature. dim: `int`. Number of categories. hidden_shape: `Iterable`, optional. Shape of hidden layers. hidden_activation: `Callable`, optional. Non-linearity for hidden layers. """ super(MLPMultinomial, self).__init__(column, index, dim) self._hidden_shape = tuple(hidden_shape) self._hidden_activation = hidden_activation self._logit_net = hk.nets.MLP(self._hidden_shape + (self.dim,), activation=self._hidden_activation) @classmethod def from_frame(cls, data, column, hidden_shape=()): """Create an MLPMultinomial instance from a pandas dataframe and column.""" # Helper method that uses the dataframe to work out how many categories # are in the given column. The dataframe is not used for any other purpose. if not isinstance(data[column].dtype, pd.api.types.CategoricalDtype): raise ValueError('{} is not categorical.'.format(column)) index = list(data.columns).index(column) num_categories = len(data[column].cat.categories) return cls(column, index, num_categories, hidden_shape) def __call__(self, *args): if args: concatenated_inputs = self._package_args(args) logits = self._logit_net(concatenated_inputs) else: logits = hk.get_parameter('b', shape=[self.dim], init=jnp.zeros) return tfp.distributions.Multinomial(logits=logits, total_count=1.0) def prepare_data(self, data): # For categorical data, we convert to a one-hot representation using the # pandas category 'codes'. These are integers, and will have a definite # ordering that is identical between runs. codes = data[:, self.index] codes = codes.astype(jnp.int32) return jnp.eye(self.dim)[codes] def populate(nodes, dataframe, node_to_replacement=None): """Populate observed values for nodes.""" for node in nodes: node.populate(dataframe, node_to_replacement=node_to_replacement)
deepmind-research-master
counterfactual_fairness/causal_network.py
# Copyright 2020 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. # ============================================================================ """Adult dataset. See https://archive.ics.uci.edu/ml/datasets/adult. """ import os from absl import logging import pandas as pd _COLUMNS = ('age', 'workclass', 'final-weight', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income') _CATEGORICAL_COLUMNS = ('workclass', 'education', 'marital-status', 'occupation', 'race', 'relationship', 'sex', 'native-country', 'income') def _read_data( name, data_path=''): with os.path.join(data_path, name) as data_file: data = pd.read_csv(data_file, header=None, index_col=False, names=_COLUMNS, skipinitialspace=True, na_values='?') for categorical in _CATEGORICAL_COLUMNS: data[categorical] = data[categorical].astype('category') return data def _combine_category_coding(df_1, df_2): """Combines the categories between dataframes df_1 and df_2. This is used to ensure that training and test data use the same category coding, so that the one-hot vectors representing the values are compatible between training and test data. Args: df_1: Pandas DataFrame. df_2: Pandas DataFrame. Must have the same columns as df_1. """ for column in df_1.columns: if df_1[column].dtype.name == 'category': categories_1 = set(df_1[column].cat.categories) categories_2 = set(df_2[column].cat.categories) categories = sorted(categories_1 | categories_2) df_1[column].cat.set_categories(categories, inplace=True) df_2[column].cat.set_categories(categories, inplace=True) def read_all_data(root_dir, remove_missing=True): """Return (train, test) dataframes, optionally removing incomplete rows.""" train_data = _read_data('adult.data', root_dir) test_data = _read_data('adult.test', root_dir) _combine_category_coding(train_data, test_data) if remove_missing: train_data = train_data.dropna() test_data = test_data.dropna() logging.info('Training data dtypes: %s', train_data.dtypes) return train_data, test_data
deepmind-research-master
counterfactual_fairness/adult.py
# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Training script for causal model for Adult dataset, using PSCF.""" import functools import time from typing import Any, List, Mapping, NamedTuple, Sequence from absl import app from absl import flags from absl import logging import haiku as hk import jax import jax.numpy as jnp from ml_collections.config_flags import config_flags import numpy as np import optax import pandas as pd from sklearn import metrics import tensorflow as tf import tensorflow_datasets as tfds from tensorflow_probability.substrates import jax as tfp from counterfactual_fairness import adult from counterfactual_fairness import causal_network from counterfactual_fairness import utils from counterfactual_fairness import variational FLAGS = flags.FLAGS config_flags.DEFINE_config_file( 'config', 'adult_pscf_config.py', 'Training configuration.') LOG_EVERY = 100 # These are all aliases to callables which will return instances of # particular distribution modules, or a Node itself. This is used to make # subsequent code more legible. Node = causal_network.Node Gaussian = causal_network.Gaussian MLPMultinomial = causal_network.MLPMultinomial def build_input(train_data: pd.DataFrame, batch_size: int, training_steps: int, shuffle_size: int = 10000): """See base class.""" num_epochs = (training_steps // batch_size) + 1 ds = utils.get_dataset(train_data, batch_size, shuffle_size, num_epochs=num_epochs) ds = ds.prefetch(tf.data.AUTOTUNE) return iter(tfds.as_numpy(ds)) class CausalNetOutput(NamedTuple): q_hidden_obs: Sequence[tfp.distributions.Distribution] p_hidden: Sequence[tfp.distributions.Distribution] hidden_samples: Sequence[jnp.ndarray] log_p_obs_hidden: jnp.ndarray is_male: jnp.ndarray # indicates which elements of the batch correspond to # male individuals def build_causal_graph(train_data: pd.DataFrame, column_names: List[str], inputs: jnp.ndarray): """Build the causal graph of the model.""" make_multinomial = functools.partial( causal_network.MLPMultinomial.from_frame, hidden_shape=(100,)) make_gaussian = functools.partial( causal_network.Gaussian, hidden_shape=(100,)) # Construct the graphical model. Each random variable is represented by an # instance of the `Node` class, as discussed in that class's docstring. # The following nodes have no parents, and thus the distribution modules # will not be conditional on anything -- they simply represent priors. node_a = Node(MLPMultinomial.from_frame(train_data, 'sex')) node_c1 = Node(MLPMultinomial.from_frame(train_data, 'native-country')) node_c2 = Node(Gaussian('age', column_names.index('age'))) # These are all hidden nodes, that do not correspond to any actual data in # pandas dataframe loaded previously. We therefore are permitted to control # the dimensionality of these nodes as we wish (with the `dim` argument). # The distribution module here should be interpreted as saying that we are # imposing a multi-modal prior (a mixture of Gaussians) on each latent # variable. node_hm = Node(causal_network.GaussianMixture('hm', 10, dim=2), hidden=True) node_hl = Node(causal_network.GaussianMixture('hl', 10, dim=2), hidden=True) node_hr1 = Node( causal_network.GaussianMixture('hr1', 10, dim=2), hidden=True) node_hr2 = Node( causal_network.GaussianMixture('hr2', 10, dim=2), hidden=True) node_hr3 = Node( causal_network.GaussianMixture('hr3', 10, dim=2), hidden=True) # The rest of the graph is now constructed; the order of construction is # important, so we can inform each node of its parents. # Note that in the paper we simply have one node called "R", but here it is # separated into three separate `Node` instances. This is necessary since # each node can only represent a single quantity in the dataframe. node_m = Node( make_multinomial(train_data, 'marital-status'), [node_a, node_hm, node_c1, node_c2]) node_l = Node( make_gaussian('education-num', column_names.index('education-num')), [node_a, node_hl, node_c1, node_c2, node_m]) node_r1 = Node( make_multinomial(train_data, 'occupation'), [node_a, node_c1, node_c2, node_m, node_l]) node_r2 = Node( make_gaussian('hours-per-week', column_names.index('hours-per-week')), [node_a, node_c1, node_c2, node_m, node_l]) node_r3 = Node( make_multinomial(train_data, 'workclass'), [node_a, node_c1, node_c2, node_m, node_l]) node_y = Node( MLPMultinomial.from_frame(train_data, 'income'), [node_a, node_c1, node_c2, node_m, node_l, node_r1, node_r2, node_r3]) # We now construct several (self-explanatory) collections of nodes. These # will be used at various points later in the code, and serve to provide # greater semantic interpretability. observable_nodes = (node_a, node_c1, node_c2, node_l, node_m, node_r1, node_r2, node_r3, node_y) # The nodes on which each latent variable is conditionally dependent. # Note that Y is not in this list, since all of its dependencies are # included below, and further it does not depend directly on Hm. nodes_on_which_hm_depends = (node_a, node_c1, node_c2, node_m) nodes_on_which_hl_depends = (node_a, node_c1, node_c2, node_m, node_l) nodes_on_which_hr1_depends = (node_a, node_c1, node_c2, node_m, node_l, node_r1) nodes_on_which_hr2_depends = (node_a, node_c1, node_c2, node_m, node_l, node_r2) nodes_on_which_hr3_depends = (node_a, node_c1, node_c2, node_m, node_l, node_r3) hidden_nodes = (node_hm, node_hl, node_hr1, node_hr2, node_hr3) # Function to create the distribution needed for variational inference. This # is the same for each latent variable. def make_q_x_obs_module(node): """Make a Variational module for the given hidden variable.""" assert node.hidden return variational.Variational( common_layer_sizes=(20, 20), output_dim=node.dim) # For each latent variable, we first construct a Haiku module (using the # function above), and then connect it to the graph using the node's # value. As described in more detail in the documentation for `Node`, # these values represent actual observed data. Therefore we will later # be connecting these same modules to the graph in different ways in order # to perform fair inference. q_hm_obs_module = make_q_x_obs_module(node_hm) q_hl_obs_module = make_q_x_obs_module(node_hl) q_hr1_obs_module = make_q_x_obs_module(node_hr1) q_hr2_obs_module = make_q_x_obs_module(node_hr2) q_hr3_obs_module = make_q_x_obs_module(node_hr3) causal_network.populate(observable_nodes, inputs) q_hm_obs = q_hm_obs_module( *(node.observed_value for node in nodes_on_which_hm_depends)) q_hl_obs = q_hl_obs_module( *(node.observed_value for node in nodes_on_which_hl_depends)) q_hr1_obs = q_hr1_obs_module( *(node.observed_value for node in nodes_on_which_hr1_depends)) q_hr2_obs = q_hr2_obs_module( *(node.observed_value for node in nodes_on_which_hr2_depends)) q_hr3_obs = q_hr3_obs_module( *(node.observed_value for node in nodes_on_which_hr3_depends)) q_hidden_obs = (q_hm_obs, q_hl_obs, q_hr1_obs, q_hr2_obs, q_hr3_obs) return observable_nodes, hidden_nodes, q_hidden_obs def build_forward_fn(train_data: pd.DataFrame, column_names: List[str], likelihood_multiplier: float): """Create the model's forward pass.""" def forward_fn(inputs: jnp.ndarray) -> CausalNetOutput: """Forward pass.""" observable_nodes, hidden_nodes, q_hidden = build_causal_graph( train_data, column_names, inputs) (node_hm, node_hl, node_hr1, node_hr2, node_hr3) = hidden_nodes (node_a, _, _, _, _, _, _, _, node_y) = observable_nodes # Log-likelihood function. def log_p_obs_h(hm_value, hl_value, hr1_value, hr2_value, hr3_value): """Compute log P(A, C, M, L, R, Y | H).""" # In order to create distributions like P(M | H_m, A, C), we need # the value of H_m that we've been provided as an argument, rather than # the value stored on H_m (which, in fact, will never be populated # since H_m is unobserved). # For compactness, we first construct the complete list of replacements. node_to_replacement = { node_hm: hm_value, node_hl: hl_value, node_hr1: hr1_value, node_hr2: hr2_value, node_hr3: hr3_value, } def log_prob_for_node(node): """Given a node, compute it's log probability for the given latents.""" log_prob = jnp.squeeze( node.make_distribution(node_to_replacement).log_prob( node.observed_value)) return log_prob # We apply the likelihood multiplier to all likelihood terms except that # for Y, the target. This is then added on separately in the line below. sum_no_y = likelihood_multiplier * sum( log_prob_for_node(node) for node in observable_nodes if node is not node_y) return sum_no_y + log_prob_for_node(node_y) q_hidden_obs = tuple(q_hidden) p_hidden = tuple(node.distribution for node in hidden_nodes) rnd_key = hk.next_rng_key() hidden_samples = tuple( q_hidden.sample(seed=rnd_key) for q_hidden in q_hidden_obs) log_p_obs_hidden = log_p_obs_h(*hidden_samples) # We need to split our batch of data into male and female parts. is_male = jnp.equal(node_a.observed_value[:, 1], 1) return CausalNetOutput( q_hidden_obs=q_hidden_obs, p_hidden=p_hidden, hidden_samples=hidden_samples, log_p_obs_hidden=log_p_obs_hidden, is_male=is_male) def fair_inference_fn(inputs: jnp.ndarray, batch_size: int, num_prediction_samples: int): """Get the fair and unfair predictions for the given input.""" observable_nodes, hidden_nodes, q_hidden_obs = build_causal_graph( train_data, column_names, inputs) (node_hm, node_hl, node_hr1, node_hr2, node_hr3) = hidden_nodes (node_a, node_c1, node_c2, node_l, node_m, node_r1, node_r2, node_r3, node_y) = observable_nodes (q_hm_obs, q_hl_obs, q_hr1_obs, q_hr2_obs, q_hr3_obs) = q_hidden_obs rnd_key = hk.next_rng_key() # *** FAIR INFERENCE *** # To predict Y in a fair sense: # * Infer Hm given observations. # * Infer M using inferred Hm, baseline A, real C # * Infer L using inferred Hl, M, real A, C # * Infer Y using inferred M, baseline A, real C # This is done by numerical integration, i.e. draw samples from # p_fair(Y | A, C, M, L). a_all_male = jnp.concatenate( (jnp.zeros((batch_size, 1)), jnp.ones((batch_size, 1))), axis=1) # Here we take a num_samples per observation. This results to # an array of shape: # (num_samples, batch_size, hm_dim). # However, forward pass is easier by reshaping to: # (num_samples * batch_size, hm_dim). hm_dim = 2 def expanded_sample(distribution): return distribution.sample( num_prediction_samples, seed=rnd_key).reshape( (batch_size * num_prediction_samples, hm_dim)) hm_pred_sample = expanded_sample(q_hm_obs) hl_pred_sample = expanded_sample(q_hl_obs) hr1_pred_sample = expanded_sample(q_hr1_obs) hr2_pred_sample = expanded_sample(q_hr2_obs) hr3_pred_sample = expanded_sample(q_hr3_obs) # The values of the observed nodes need to be tiled to match the dims # of the above hidden samples. The `expand` function achieves this. def expand(observed_value): return jnp.tile(observed_value, (num_prediction_samples, 1)) expanded_a = expand(node_a.observed_value) expanded_a_baseline = expand(a_all_male) expanded_c1 = expand(node_c1.observed_value) expanded_c2 = expand(node_c2.observed_value) # For M, and all subsequent variables, we only generate one sample. This # is because we already have *many* samples from the latent variables, and # all we require is an independent sample from the distribution. m_pred_sample = node_m.make_distribution({ node_a: expanded_a_baseline, node_hm: hm_pred_sample, node_c1: expanded_c1, node_c2: expanded_c2}).sample(seed=rnd_key) l_pred_sample = node_l.make_distribution({ node_a: expanded_a, node_hl: hl_pred_sample, node_c1: expanded_c1, node_c2: expanded_c2, node_m: m_pred_sample}).sample(seed=rnd_key) r1_pred_sample = node_r1.make_distribution({ node_a: expanded_a, node_hr1: hr1_pred_sample, node_c1: expanded_c1, node_c2: expanded_c2, node_m: m_pred_sample, node_l: l_pred_sample}).sample(seed=rnd_key) r2_pred_sample = node_r2.make_distribution({ node_a: expanded_a, node_hr2: hr2_pred_sample, node_c1: expanded_c1, node_c2: expanded_c2, node_m: m_pred_sample, node_l: l_pred_sample}).sample(seed=rnd_key) r3_pred_sample = node_r3.make_distribution({ node_a: expanded_a, node_hr3: hr3_pred_sample, node_c1: expanded_c1, node_c2: expanded_c2, node_m: m_pred_sample, node_l: l_pred_sample}).sample(seed=rnd_key) # Finally, we sample from the distribution for Y. Like above, we only # draw one sample per element in the array. y_pred_sample = node_y.make_distribution({ node_a: expanded_a_baseline, # node_a: expanded_a, node_c1: expanded_c1, node_c2: expanded_c2, node_m: m_pred_sample, node_l: l_pred_sample, node_r1: r1_pred_sample, node_r2: r2_pred_sample, node_r3: r3_pred_sample}).sample(seed=rnd_key) # Reshape back to (num_samples, batch_size, y_dim), undoing the expanding # operation used for sampling. y_pred_sample = y_pred_sample.reshape( (num_prediction_samples, batch_size, -1)) # Now form an array of shape (batch_size, y_dim) by taking an expectation # over the sample dimension. This represents the probability that the # result is in each class. y_pred_expectation = jnp.mean(y_pred_sample, axis=0) # Find out the predicted y, for later use in a confusion matrix. predicted_class_y_fair = utils.multinomial_class(y_pred_expectation) # *** NAIVE INFERENCE *** predicted_class_y_unfair = utils.multinomial_class(node_y.distribution) return predicted_class_y_fair, predicted_class_y_unfair return forward_fn, fair_inference_fn def _loss_fn( forward_fn, beta: float, mmd_sample_size: int, constraint_multiplier: float, constraint_ratio: float, params: hk.Params, rng: jnp.ndarray, inputs: jnp.ndarray, ) -> jnp.ndarray: """Loss function definition.""" outputs = forward_fn(params, rng, inputs) loss = _loss_klqp(outputs, beta) # if (constraint_ratio * constraint_multiplier) > 0: constraint_loss = 0. # Create constraint penalty and add to overall loss term. for distribution in outputs.q_hidden_obs: constraint_loss += (constraint_ratio * constraint_multiplier * utils.mmd_loss(distribution, outputs.is_male, mmd_sample_size, rng)) # Optimisation - don't do the computation if the multiplier is set to zero. loss += constraint_loss return loss def _evaluate( fair_inference_fn, params: hk.Params, rng: jnp.ndarray, inputs: jnp.ndarray, batch_size: int, num_prediction_samples: int, ): """Perform evaluation of fair inference.""" output = fair_inference_fn(params, rng, inputs, batch_size, num_prediction_samples) return output def _loss_klqp(outputs: CausalNetOutput, beta: float) -> jnp.ndarray: """Compute the loss on data wrt params.""" expected_log_q_hidden_obs = sum( jnp.sum(q_hidden_obs.log_prob(hidden_sample), axis=1) for q_hidden_obs, hidden_sample in zip(outputs.q_hidden_obs, outputs.hidden_samples)) assert expected_log_q_hidden_obs.ndim == 1 # For log probabilities computed from distributions, we need to sum along # the last axis, which takes the product of distributions for # multi-dimensional hidden variables. log_p_hidden = sum( jnp.sum(p_hidden.log_prob(hidden_sample), axis=1) for p_hidden, hidden_sample in zip(outputs.p_hidden, outputs.hidden_samples)) assert outputs.log_p_obs_hidden.ndim == 1 kl_divergence = ( beta * (expected_log_q_hidden_obs - log_p_hidden) - outputs.log_p_obs_hidden) return jnp.mean(kl_divergence) class Updater: """A stateless abstraction around an init_fn/update_fn pair. This extracts some common boilerplate from the training loop. """ def __init__(self, net_init, loss_fn, eval_fn, optimizer: optax.GradientTransformation, constraint_turn_on_step): self._net_init = net_init self._loss_fn = loss_fn self._eval_fn = eval_fn self._opt = optimizer self._constraint_turn_on_step = constraint_turn_on_step @functools.partial(jax.jit, static_argnums=0) def init(self, init_rng, data): """Initializes state of the updater.""" params = self._net_init(init_rng, data) opt_state = self._opt.init(params) out = dict( step=np.array(0), rng=init_rng, opt_state=opt_state, params=params, ) return out @functools.partial(jax.jit, static_argnums=0) def update(self, state: Mapping[str, Any], data: jnp.ndarray): """Updates the state using some data and returns metrics.""" rng = state['rng'] params = state['params'] constraint_ratio = (state['step'] > self._constraint_turn_on_step).astype( float) loss, g = jax.value_and_grad(self._loss_fn, argnums=1)( constraint_ratio, params, rng, data) updates, opt_state = self._opt.update(g, state['opt_state']) params = optax.apply_updates(params, updates) new_state = { 'step': state['step'] + 1, 'rng': rng, 'opt_state': opt_state, 'params': params, } new_metrics = { 'step': state['step'], 'loss': loss, } return new_state, new_metrics @functools.partial(jax.jit, static_argnums=(0, 3, 4)) def evaluate(self, state: Mapping[str, Any], inputs: jnp.ndarray, batch_size: int, num_prediction_samples: int): """Evaluate fair inference.""" rng = state['rng'] params = state['params'] fair_pred, unfair_pred = self._eval_fn(params, rng, inputs, batch_size, num_prediction_samples) return fair_pred, unfair_pred def main(_): flags_config = FLAGS.config # Create the dataset. train_data, test_data = adult.read_all_data(FLAGS.dataset_dir) column_names = list(train_data.columns) train_input = build_input(train_data, flags_config.batch_size, flags_config.num_steps) # Set up the model, loss, and updater. forward_fn, fair_inference_fn = build_forward_fn( train_data, column_names, flags_config.likelihood_multiplier) forward_fn = hk.transform(forward_fn) fair_inference_fn = hk.transform(fair_inference_fn) loss_fn = functools.partial(_loss_fn, forward_fn.apply, flags_config.beta, flags_config.mmd_sample_size, flags_config.constraint_multiplier) eval_fn = functools.partial(_evaluate, fair_inference_fn.apply) optimizer = optax.adam(flags_config.learning_rate) updater = Updater(forward_fn.init, loss_fn, eval_fn, optimizer, flags_config.constraint_turn_on_step) # Initialize parameters. logging.info('Initializing parameters...') rng = jax.random.PRNGKey(42) train_data = next(train_input) state = updater.init(rng, train_data) # Training loop. logging.info('Starting train loop...') prev_time = time.time() for step in range(flags_config.num_steps): train_data = next(train_input) state, stats = updater.update(state, train_data) if step % LOG_EVERY == 0: steps_per_sec = LOG_EVERY / (time.time() - prev_time) prev_time = time.time() stats.update({'steps_per_sec': steps_per_sec}) logging.info({k: float(v) for k, v in stats.items()}) # Evaluate. logging.info('Starting evaluation...') test_input = build_input(test_data, flags_config.batch_size, training_steps=0, shuffle_size=0) predicted_test_y = [] corrected_test_y = [] while True: try: eval_data = next(test_input) # Now run the fair prediction; this projects the input to the latent space # and then performs sampling. predicted_class_y_fair, predicted_class_y_unfair = updater.evaluate( state, eval_data, flags_config.batch_size, flags_config.num_prediction_samples) predicted_test_y.append(predicted_class_y_unfair) corrected_test_y.append(predicted_class_y_fair) # logging.info('Completed evaluation step %d', step) except StopIteration: logging.info('Finished evaluation') break # Join together the predictions from each batch. test_y = np.concatenate(predicted_test_y, axis=0) tweaked_test_y = np.concatenate(corrected_test_y, axis=0) # Note the true values for computing accuracy and confusion matrices. y_true = test_data['income'].cat.codes # Make sure y_true is the same size y_true = y_true[:len(test_y)] test_accuracy = metrics.accuracy_score(y_true, test_y) tweaked_test_accuracy = metrics.accuracy_score( y_true, tweaked_test_y) # Print out accuracy and confusion matrices. logging.info('Accuracy (full model): %f', test_accuracy) logging.info('Confusion matrix:') logging.info(metrics.confusion_matrix(y_true, test_y)) logging.info('') logging.info('Accuracy (tweaked with baseline: Male): %f', tweaked_test_accuracy) logging.info('Confusion matrix:') logging.info(metrics.confusion_matrix(y_true, tweaked_test_y)) if __name__ == '__main__': app.run(main)
deepmind-research-master
counterfactual_fairness/adult_pscf.py
# Copyright 2020 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. # ============================================================================ """Common utilities.""" from typing import Optional, Union from jax import random import jax.numpy as jnp import pandas as pd import tensorflow as tf from tensorflow_probability.substrates import jax as tfp tfd = tfp.distributions def get_dataset(dataset: pd.DataFrame, batch_size: int, shuffle_size: int = 10000, num_epochs: Optional[int] = None) -> tf.data.Dataset: """Makes a tf.Dataset with correct preprocessing.""" dataset_copy = dataset.copy() for column in dataset.columns: if dataset[column].dtype.name == 'category': dataset_copy.loc[:, column] = dataset[column].cat.codes ds = tf.data.Dataset.from_tensor_slices(dataset_copy.values) if shuffle_size > 0: ds = ds.shuffle(shuffle_size, reshuffle_each_iteration=True) ds = ds.repeat(num_epochs) return ds.batch(batch_size, drop_remainder=True) def multinomial_mode( distribution_or_probs: Union[tfd.Distribution, jnp.DeviceArray] ) -> jnp.DeviceArray: """Calculates the (one-hot) mode of a multinomial distribution. Args: distribution_or_probs: `tfp.distributions.Distribution` | List[tensors]. If the former, it is assumed that it has a `probs` property, and represents a distribution over categories. If the latter, these are taken to be the probabilities of categories directly. In either case, it is assumed that `probs` will be shape (batch_size, dim). Returns: `DeviceArray`, float32, (batch_size, dim). The mode of the distribution - this will be in one-hot form, but contain multiple non-zero entries in the event that more than one probability is joint-highest. """ if isinstance(distribution_or_probs, tfd.Distribution): probs = distribution_or_probs.probs_parameter() else: probs = distribution_or_probs max_prob = jnp.max(probs, axis=1, keepdims=True) mode = jnp.int32(jnp.equal(probs, max_prob)) return jnp.float32(mode / jnp.sum(mode, axis=1, keepdims=True)) def multinomial_class( distribution_or_probs: Union[tfd.Distribution, jnp.DeviceArray] ) -> jnp.DeviceArray: """Computes the mode class of a multinomial distribution. Args: distribution_or_probs: `tfp.distributions.Distribution` | DeviceArray. As for `multinomial_mode`. Returns: `DeviceArray`, float32, (batch_size,). For each element in the batch, the index of the class with highest probability. """ if isinstance(distribution_or_probs, tfd.Distribution): return jnp.argmax(distribution_or_probs.logits_parameter(), axis=1) return jnp.argmax(distribution_or_probs, axis=1) def multinomial_mode_ndarray(probs: jnp.DeviceArray) -> jnp.DeviceArray: """Calculates the (one-hot) mode from an ndarray of class probabilities. Equivalent to `multinomial_mode` above, but implemented for numpy ndarrays rather than Tensors. Args: probs: `DeviceArray`, (batch_size, dim). Probabilities for each class, for each element in a batch. Returns: `DeviceArray`, (batch_size, dim). """ max_prob = jnp.amax(probs, axis=1, keepdims=True) mode = jnp.equal(probs, max_prob).astype(jnp.int32) return (mode / jnp.sum(mode, axis=1, keepdims=True)).astype(jnp.float32) def multinomial_accuracy(distribution_or_probs: tfd.Distribution, data: jnp.DeviceArray) -> jnp.DeviceArray: """Compute the accuracy, averaged over a batch of data. Args: distribution_or_probs: `tfp.distributions.Distribution` | List[tensors]. As for functions above. data: `DeviceArray`. Reference data, of shape (batch_size, dim). Returns: `DeviceArray`, float32, (). Overall scalar accuracy. """ return jnp.mean( jnp.sum(multinomial_mode(distribution_or_probs) * data, axis=1)) def softmax_ndarray(logits: jnp.DeviceArray) -> jnp.DeviceArray: """Softmax function, implemented for numpy ndarrays.""" assert len(logits.shape) == 2 # Normalise for better stability. s = jnp.max(logits, axis=1, keepdims=True) e_x = jnp.exp(logits - s) return e_x / jnp.sum(e_x, axis=1, keepdims=True) def get_samples(distribution, num_samples, seed=None): """Given a batched distribution, compute samples and reshape along batch. That is, we have a distribution of shape (batch_size, ...), where each element of the tensor is independent. We then draw num_samples from each component, to give a tensor of shape: (num_samples, batch_size, ...) Args: distribution: `tfp.distributions.Distribution`. The distribution from which to sample. num_samples: `Integral` | `DeviceArray`, int32, (). The number of samples. seed: `Integral` | `None`. The seed that will be forwarded to the call to distribution.sample. Defaults to `None`. Returns: `DeviceArray`, float32, (batch_size * num_samples, ...). Samples for each element of the batch. """ # Obtain the sample from the distribution, which will be of shape # [num_samples] + batch_shape + event_shape. sample = distribution.sample(num_samples, seed=seed) sample = sample.reshape((-1, sample.shape[-1])) # Combine the first two dimensions through a reshape, so the result will # be of shape (num_samples * batch_size,) + shape_tail. return sample def mmd_loss(distribution: tfd.Distribution, is_a: jnp.DeviceArray, num_samples: int, rng: jnp.ndarray, num_random_features: int = 50, gamma: float = 1.): """Given two distributions, compute the Maximum Mean Discrepancy (MMD). More exactly, this uses the 'FastMMD' approximation, a.k.a. 'Random Fourier Features'. See the description, for example, in sections 2.3.1 and 2.4 of https://arxiv.org/pdf/1511.00830.pdf. Args: distribution: Distribution whose `sample()` method will return a DeviceArray of shape (batch_size, dim). is_a: A boolean array indicating which elements of the batch correspond to class A (the remaining indices correspond to class B). num_samples: The number of samples to draw from `distribution`. rng: Random seed provided by the user. num_random_features: The number of random fourier features used in the expansion. gamma: The value of gamma in the Gaussian MMD kernel. Returns: `DeviceArray`, shape (). The scalar MMD value for samples taken from the given distributions. """ if distribution.event_shape == (): # pylint: disable=g-explicit-bool-comparison dim_x = distribution.batch_shape[1] else: dim_x, = distribution.event_shape # Obtain samples from the distribution, which will be of shape # [num_samples] + batch_shape + event_shape. samples = distribution.sample(num_samples, seed=rng) w = random.normal(rng, shape=((dim_x, num_random_features))) b = random.uniform(rng, shape=(num_random_features,), minval=0, maxval=2*jnp.pi) def features(x): """Compute the kitchen sink feature.""" # We need to contract last axis of x with first of W - do this with # tensordot. The result has shape: # (?, ?, num_random_features) return jnp.sqrt(2 / num_random_features) * jnp.cos( jnp.sqrt(2 / gamma) * jnp.tensordot(x, w, axes=1) + b) # Compute the expected values of the given features. # The first axis represents the samples from the distribution, # second axis represents the batch_size. # Each of these now has shape (num_random_features,) exp_features = features(samples) # Swap axes so that batch_size is the last dimension to be compatible # with is_a and is_b shape at the next step exp_features_reshaped = jnp.swapaxes(exp_features, 1, 2) # Current dimensions [num_samples, num_random_features, batch_size] exp_features_reshaped_a = jnp.where(is_a, exp_features_reshaped, 0) exp_features_reshaped_b = jnp.where(is_a, 0, exp_features_reshaped) exp_features_a = jnp.mean(exp_features_reshaped_a, axis=(0, 2)) exp_features_b = jnp.mean(exp_features_reshaped_b, axis=(0, 2)) assert exp_features_a.shape == (num_random_features,) difference = exp_features_a - exp_features_b # Compute the squared norm. Shape (). return jnp.tensordot(difference, difference, axes=1) def mmd_loss_exact(distribution_a, distribution_b, num_samples, gamma=1.): """Exact estimate of MMD.""" assert distribution_a.event_shape == distribution_b.event_shape assert distribution_a.batch_shape[1:] == distribution_b.batch_shape[1:] # shape (num_samples * batch_size_a, dim_x) samples_a = get_samples(distribution_a, num_samples) # shape (num_samples * batch_size_b, dim_x) samples_b = get_samples(distribution_b, num_samples) # Make matrices of shape # (size_b, size_a, dim_x) # where: # size_a = num_samples * batch_size_a # size_b = num_samples * batch_size_b size_a = samples_a.shape[0] size_b = samples_b.shape[0] x_a = jnp.expand_dims(samples_a, axis=0) x_a = jnp.tile(x_a, (size_b, 1, 1)) x_b = jnp.expand_dims(samples_b, axis=1) x_b = jnp.tile(x_b, (1, size_a, 1)) def kernel_mean(x, y): """Gaussian kernel mean.""" diff = x - y # Contract over dim_x. exponent = - jnp.einsum('ijk,ijk->ij', diff, diff) / gamma # This has shape (size_b, size_a). kernel_matrix = jnp.exp(exponent) # Shape (). return jnp.mean(kernel_matrix) # Equation 7 from arxiv 1511.00830 return ( kernel_mean(x_a, x_a) + kernel_mean(x_b, x_b) - 2 * kernel_mean(x_a, x_b)) def scalar_log_prob(distribution, val): """Compute the log_prob per batch entry. It is conceptually similar to: jnp.sum(distribution.log_prob(val), axis=1) However, classes like `tfp.distributions.Multinomial` have a log_prob which returns a tensor of shape (batch_size,), which will cause the above incantation to fail. In these cases we fall back to returning just: distribution.log_prob(val) Args: distribution: `tfp.distributions.Distribution` which implements log_prob. val: `DeviceArray`, (batch_size, dim). Returns: `DeviceArray`, (batch_size,). If the result of log_prob has a trailing dimension, we perform a reduce_sum over it. Raises: ValueError: If distribution.log_prob(val) has an unsupported shape. """ log_prob_val = distribution.log_prob(val) if len(log_prob_val.shape) == 1: return log_prob_val elif len(log_prob_val.shape) > 2: raise ValueError('log_prob_val has unexpected shape {}.'.format( log_prob_val.shape)) return jnp.sum(log_prob_val, axis=1)
deepmind-research-master
counterfactual_fairness/utils.py
# Copyright 2020 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. # ============================================================================ """Config for adult PSCF experiment.""" import ml_collections def get_config(): """Return the default configuration.""" config = ml_collections.ConfigDict() config.num_steps = 10000 # Number of training steps to perform. config.batch_size = 128 # Batch size. config.learning_rate = 0.01 # Learning rate # Number of samples to draw for prediction. config.num_prediction_samples = 500 # Batch size to use for prediction. Ideally as big as possible, but may need # to be reduced for memory reasons depending on the value of # `num_prediction_samples`. config.prediction_batch_size = 500 # Multiplier for the likelihood term in the loss config.likelihood_multiplier = 5. # Multiplier for the MMD constraint term in the loss config.constraint_multiplier = 0. # Scaling factor to use in KL term. config.beta = 1.0 # The number of samples we draw from each latent variable distribution. config.mmd_sample_size = 100 # Directory into which results should be placed. By default it is the empty # string, in which case no saving will occur. The directory specified will be # created if it does not exist. config.output_dir = '' # The index of the step at which to turn on the constraint multiplier. For # steps prior to this the multiplier will be zero. config.constraint_turn_on_step = 0 # The random seed for tensorflow that is applied to the graph iff the value is # non-negative. By default the seed is not constrained. config.seed = -1 # When doing fair inference, don't sample when given a sample for the baseline # gender. config.baseline_passthrough = False return config
deepmind-research-master
counterfactual_fairness/adult_pscf_config.py
# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Functions and classes for performing variational inference.""" from typing import Callable, Iterable, Optional import haiku as hk import jax.numpy as jnp from tensorflow_probability.substrates import jax as tfp tfd = tfp.distributions class Variational(hk.Module): """A module representing the variational distribution q(H | *O). H is assumed to be a continuous variable. """ def __init__(self, common_layer_sizes: Iterable[int], activation: Callable[[jnp.DeviceArray], jnp.DeviceArray] = jnp.tanh, output_dim: int = 1, name: Optional[str] = None): """Initialises a `Variational` instance. Args: common_layer_sizes: The number of hidden units in the shared dense network layers. activation: Nonlinearity function to apply to each of the common layers. output_dim: The dimensionality of `H`. name: A name to assign to the module instance. """ super().__init__(name=name) self._common_layer_sizes = common_layer_sizes self._activation = activation self._output_dim = output_dim self._linear_layers = [ hk.Linear(layer_size) for layer_size in self._common_layer_sizes ] self._mean_output = hk.Linear(self._output_dim) self._log_var_output = hk.Linear(self._output_dim) def __call__(self, *args) -> tfd.Distribution: """Create a distribution for q(H | *O). Args: *args: `List[DeviceArray]`. Corresponds to the values of whatever variables are in the conditional set *O. Returns: `tfp.distributions.NormalDistribution` instance. """ # Stack all inputs, ensuring that shapes are consistent and that they are # all of dtype float32. input_ = [hk.Flatten()(arg) for arg in args] input_ = jnp.concatenate(input_, axis=1) # Create a common set of layers, then final layer separates mean & log_var for layer in self._linear_layers: input_ = layer(input_) input_ = self._activation(input_) # input_ now represents a tensor of shape (batch_size, final_layer_size). # This is now put through two final layers, one for the computation of each # of the mean and standard deviation of the resultant distribution. mean = self._mean_output(input_) log_var = self._log_var_output(input_) std = jnp.sqrt(jnp.exp(log_var)) return tfd.Normal(mean, std)
deepmind-research-master
counterfactual_fairness/variational.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Ensemble k-fold predictions and generate final submission file.""" import collections import os from absl import app from absl import flags from absl import logging import dill import jax import numpy as np from ogb import lsc # pylint: disable=g-bad-import-order import data_utils import losses _NUM_KFOLD_SPLITS = 10 FLAGS = flags.FLAGS _DATA_ROOT = flags.DEFINE_string('data_root', None, 'Path to the data root') _SPLIT = flags.DEFINE_enum('split', None, ['valid', 'test'], 'Data split') _PREDICTIONS_PATH = flags.DEFINE_string( 'predictions_path', None, 'Path with the output of the k-fold models.') _OUTPUT_PATH = flags.DEFINE_string('output_path', None, 'Output path.') def _np_one_hot(targets: np.ndarray, nb_classes: int): res = np.zeros(targets.shape + (nb_classes,), dtype=np.float32) np.put_along_axis(res, targets.astype(np.int32)[..., None], 1.0, axis=-1) return res def ensemble_predictions( node_idx_to_logits_list, all_labels, node_indices, use_mode_break_tie_by_mean: bool = True, ): """Ensemble together predictions for each node and generate final predictions.""" # First, assert that each node has the same number of predictions to ensemble. num_predictions_per_node = [ len(x) for x in node_idx_to_logits_list.values() ] num_models = np.unique(num_predictions_per_node) assert num_models.shape[0] == 1 num_models = num_models[0] # Gather all logits, shape should be [num_nodes, num_models, num_classes]. all_logits = np.stack( [np.stack(node_idx_to_logits_list[idx]) for idx in node_indices]) assert all_logits.shape == (node_indices.shape[0], num_models, data_utils.NUM_CLASSES) # Softmax on the final axis. all_probs = jax.nn.softmax(all_logits, axis=-1) # Take average across models axis to get probabilities. mean_probs = np.mean(all_probs, axis=1) # Assert there are no 2 equal logits for different classes. max_logit_value = np.max(all_logits, axis=-1) num_classes_with_max_value = ( all_logits == max_logit_value[..., None]).sum(axis=-1) num_logit_ties = (num_classes_with_max_value > 1).sum() if num_logit_ties: logging.warn( 'Found %d models with the exact same logits for two of the classes. ' '`argmax` will choose the first.', num_logit_ties) # Each model votes on one class per type. all_votes = np.argmax(all_logits, axis=-1) assert all_votes.shape == (node_indices.shape[0], num_models) all_votes_one_hot = _np_one_hot(all_votes, data_utils.NUM_CLASSES) assert all_votes_one_hot.shape == (node_indices.shape[0], num_models, data_utils.NUM_CLASSES) num_votes_per_class = np.sum(all_votes_one_hot, axis=1) assert num_votes_per_class.shape == ( node_indices.shape[0], data_utils.NUM_CLASSES) if use_mode_break_tie_by_mean: # Slight hack, give high weight to votes (any number > 1 works really) # and add probabilities between [0, 1] per class to tie-break only within # classes with equal votes. total_score = 10 * num_votes_per_class + mean_probs else: # Just take mean. total_score = mean_probs ensembled_logits = np.log(total_score) return losses.Predictions( node_indices=node_indices, labels=all_labels, logits=ensembled_logits, predictions=np.argmax(ensembled_logits, axis=-1), ) def load_predictions(predictions_path, split): """Loads set of predictions made by given XID.""" # Generate list of predictions per node. # Note for validation each validation index is only present in exactly 1 # model of the k-fold, however for test it is present in all of them. node_idx_to_logits_list = collections.defaultdict(list) # For the 10 models in the ensemble. for i in range(_NUM_KFOLD_SPLITS): path = os.path.join(predictions_path, str(i)) # Find subdirectories. # Directories will be something like: # os.path.join(path, "step_104899_2021-06-14T18:20:05", "(test|valid).dill") # So we make sure there is only one. candidates = [] for date_str in os.listdir(path): candidate_path = os.path.join(path, date_str, f'{split}.dill') if os.path.exists(candidate_path): candidates.append(candidate_path) if not candidates: raise ValueError(f'No {split} predictions found at {path}') elif len(candidates) > 1: raise ValueError(f'Found more than one {split} predictions: {candidates}') path_for_kth_model_predictions = candidates[0] with open(path_for_kth_model_predictions, 'rb') as f: results = dill.load(f) logging.info('Loaded %s', path_for_kth_model_predictions) for (node_idx, logits) in zip(results.node_indices, results.logits): node_idx_to_logits_list[node_idx].append(logits) return node_idx_to_logits_list def generate_ensembled_predictions( data_root: str, predictions_path: str, split: str) -> losses.Predictions: """Ensemble checkpoints from all WIDs in XID and generates submission file.""" array_dict = data_utils.get_arrays( data_root=data_root, return_pca_embeddings=False, return_adjacencies=False) # Load all valid and test predictions. node_idx_to_logits_list = load_predictions(predictions_path, split) # Assert that the indices loaded are as expected. expected_idx = array_dict[f'{split}_indices'] idx_found = np.array(list(node_idx_to_logits_list.keys())) assert np.all(np.sort(idx_found) == expected_idx) if split == 'valid': true_labels = array_dict['paper_label'][expected_idx.astype(np.int32)] else: # Don't know the test labels. true_labels = np.full(expected_idx.shape, np.nan) # Ensemble together all predictions. return ensemble_predictions( node_idx_to_logits_list, true_labels, expected_idx) def evaluate_validation(valid_predictions): evaluator = lsc.MAG240MEvaluator() evaluator_ouput = evaluator.eval( dict(y_pred=valid_predictions.predictions.astype(np.float64), y_true=valid_predictions.labels)) logging.info( 'Validation accuracy as reported by MAG240MEvaluator: %s', evaluator_ouput) def save_test_submission_file(test_predictions, output_dir): evaluator = lsc.MAG240MEvaluator() evaluator.save_test_submission( dict(y_pred=test_predictions.predictions.astype(np.float64)), output_dir) logging.info('Test submission file generated at %s', output_dir) def main(argv): del argv split = _SPLIT.value ensembled_predictions = generate_ensembled_predictions( data_root=_DATA_ROOT.value, predictions_path=_PREDICTIONS_PATH.value, split=split) output_dir = _OUTPUT_PATH.value os.makedirs(output_dir, exist_ok=True) if split == 'valid': evaluate_validation(ensembled_predictions) elif split == 'test': save_test_submission_file(ensembled_predictions, output_dir) ensembled_predictions_path = os.path.join(output_dir, f'{split}.dill') assert not os.path.exists(ensembled_predictions_path) with open(ensembled_predictions_path, 'wb') as f: dill.dump(ensembled_predictions, f) logging.info( '%s predictions stored at %s', split, ensembled_predictions_path) if __name__ == '__main__': app.run(main)
deepmind-research-master
ogb_lsc/mag/ensemble_predictions.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generates the k-fold validation splits.""" import os from absl import app from absl import flags import data_utils _DATA_ROOT = flags.DEFINE_string( 'data_root', None, required=True, help='Path containing the downloaded data.') _OUTPUT_DIR = flags.DEFINE_string( 'output_dir', None, required=True, help='Output directory to write the splits to') def main(argv): del argv array_dict = data_utils.get_arrays( data_root=_DATA_ROOT.value, return_pca_embeddings=False, return_adjacencies=False) os.makedirs(_OUTPUT_DIR.value, exist_ok=True) data_utils.generate_k_fold_splits( train_idx=array_dict['train_indices'], valid_idx=array_dict['valid_indices'], output_path=_OUTPUT_DIR.value, num_splits=data_utils.NUM_K_FOLD_SPLITS) if __name__ == '__main__': app.run(main)
deepmind-research-master
ogb_lsc/mag/generate_validation_splits.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Split and save the train/valid/test indices. Usage: python3 split_and_save_indices.py --data_root="mag_data" """ import pathlib from absl import app from absl import flags import numpy as np import torch Path = pathlib.Path FLAGS = flags.FLAGS flags.DEFINE_string('data_root', None, 'Data root directory') def main(argv) -> None: if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') mag_directory = Path(FLAGS.data_root) / 'mag240m_kddcup2021' raw_directory = mag_directory / 'raw' raw_directory.parent.mkdir(parents=True, exist_ok=True) splits_dict = torch.load(str(mag_directory / 'split_dict.pt')) for key, indices in splits_dict.items(): np.save(str(raw_directory / f'{key}_idx.npy'), indices) if __name__ == '__main__': flags.mark_flag_as_required('root') app.run(main)
deepmind-research-master
ogb_lsc/mag/split_and_save_indices.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Apply PCA to the papers' BERT features. Compute papers' PCA features. Recompute author and institution features from the paper PCA features. """ import pathlib import time from absl import app from absl import flags from absl import logging import numpy as np # pylint: disable=g-bad-import-order import data_utils Path = pathlib.Path _NUMBER_OF_PAPERS_TO_ESTIMATE_PCA_ON = 1000000 # None indicates all. FLAGS = flags.FLAGS flags.DEFINE_string('data_root', None, 'Data root directory') def _sample_vectors(vectors, num_samples, seed=0): """Randomly sample some vectors.""" rand = np.random.RandomState(seed=seed) indices = rand.choice(vectors.shape[0], size=num_samples, replace=False) return vectors[indices] def _pca(feat): """Returns evals (variances), evecs (rows are principal components).""" cov = np.cov(feat.T) _, evals, evecs = np.linalg.svd(cov, full_matrices=True) return evals, evecs def _read_raw_paper_features(): """Load raw paper features.""" path = Path(FLAGS.data_root) / data_utils.RAW_NODE_FEATURES_FILENAME try: # Use mmap if possible. features = np.load(path, mmap_mode='r') except FileNotFoundError: with open(path, 'rb') as fid: features = np.load(fid) return features def _get_principal_components(features, num_principal_components=129, num_samples=10000, seed=2, dtype='f4'): """Estimate PCA features.""" sample = _sample_vectors( features[:_NUMBER_OF_PAPERS_TO_ESTIMATE_PCA_ON], num_samples, seed=seed) # Compute PCA basis. _, evecs = _pca(sample) return evecs[:num_principal_components].T.astype(dtype) def _project_features_onto_principal_components(features, principal_components, block_size=1000000): """Apply PCA iteratively.""" num_principal_components = principal_components.shape[1] dtype = principal_components.dtype num_vectors = features.shape[0] num_features = features.shape[0] num_blocks = (num_features - 1) // block_size + 1 pca_features = np.empty([num_vectors, num_principal_components], dtype=dtype) # Loop through in blocks. start_time = time.time() for i in range(num_blocks): i_start = i * block_size i_end = (i + 1) * block_size f = np.array(features[i_start:i_end].copy()) pca_features[i_start:i_end] = np.dot(f, principal_components).astype(dtype) del f elapsed_time = time.time() - start_time time_left = elapsed_time / (i + 1) * (num_blocks - i - 1) logging.info('Features %d / %d. Elapsed time %.1f. Time left: %.1f', i_end, num_vectors, elapsed_time, time_left) return pca_features def _read_adjacency_indices(): # Get adjacencies. return data_utils.get_arrays( data_root=FLAGS.data_root, use_fused_node_labels=False, use_fused_node_adjacencies=False, return_pca_embeddings=False, ) def _compute_author_pca_features(paper_pca_features, index_arrays): return data_utils.paper_features_to_author_features( index_arrays['author_paper_index'], paper_pca_features) def _compute_institution_pca_features(author_pca_features, index_arrays): return data_utils.author_features_to_institution_features( index_arrays['institution_author_index'], author_pca_features) def _write_array(path, array): path.parent.mkdir(parents=True, exist_ok=True) with open(path, 'wb') as fid: np.save(fid, array) def main(unused_argv): data_root = Path(FLAGS.data_root) raw_paper_features = _read_raw_paper_features() principal_components = _get_principal_components(raw_paper_features) paper_pca_features = _project_features_onto_principal_components( raw_paper_features, principal_components) del raw_paper_features del principal_components paper_pca_path = data_root / data_utils.PCA_PAPER_FEATURES_FILENAME author_pca_path = data_root / data_utils.PCA_AUTHOR_FEATURES_FILENAME institution_pca_path = ( data_root / data_utils.PCA_INSTITUTION_FEATURES_FILENAME) merged_pca_path = data_root / data_utils.PCA_MERGED_FEATURES_FILENAME _write_array(paper_pca_path, paper_pca_features) # Compute author and institution features from paper PCA features. index_arrays = _read_adjacency_indices() author_pca_features = _compute_author_pca_features(paper_pca_features, index_arrays) _write_array(author_pca_path, author_pca_features) institution_pca_features = _compute_institution_pca_features( author_pca_features, index_arrays) _write_array(institution_pca_path, institution_pca_features) merged_pca_features = np.concatenate( [paper_pca_features, author_pca_features, institution_pca_features], axis=0) del author_pca_features del institution_pca_features _write_array(merged_pca_path, merged_pca_features) if __name__ == '__main__': flags.mark_flag_as_required('data_root') app.run(main)
deepmind-research-master
ogb_lsc/mag/pca_builder.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Experiment config for MAG240M-LSC entry.""" from jaxline import base_config from ml_collections import config_dict def get_config(debug: bool = False) -> config_dict.ConfigDict: """Get Jaxline experiment config.""" config = base_config.get_base_config() config.random_seed = 42 # E.g. '/data/pretrained_models/k0_seed100' (and set k_fold_split_id=0, below) config.restore_path = config_dict.placeholder(str) config.experiment_kwargs = config_dict.ConfigDict( dict( config=dict( debug=debug, predictions_dir=config_dict.placeholder(str), # 5 for model selection and early stopping, 50 for final eval. num_eval_iterations_to_ensemble=5, dataset_kwargs=dict( data_root='/data/', online_subsampling_kwargs=dict( max_nb_neighbours_per_type=[ [[40, 20, 0, 40], [0, 0, 0, 0], [0, 0, 0, 0]], [[40, 20, 0, 40], [40, 0, 10, 0], [0, 0, 0, 0]], ], remove_future_nodes=True, deduplicate_nodes=True, ), ratio_unlabeled_data_to_labeled_data=10.0, k_fold_split_id=config_dict.placeholder(int), use_all_labels_when_not_training=False, use_dummy_adjacencies=debug, ), optimizer=dict( name='adamw', kwargs=dict(weight_decay=1e-5, b1=0.9, b2=0.999), learning_rate_schedule=dict( use_schedule=True, base_learning_rate=1e-2, warmup_steps=50000, total_steps=config.get_ref('training_steps'), ), ), model_config=dict( mlp_hidden_sizes=[32] if debug else [512], latent_size=32 if debug else 256, num_message_passing_steps=2 if debug else 4, activation='relu', dropout_rate=0.3, dropedge_rate=0.25, disable_edge_updates=True, use_sent_edges=True, normalization_type='layer_norm', aggregation_function='sum', ), training=dict( loss_config=dict( bgrl_loss_config=dict( stop_gradient_for_supervised_loss=False, bgrl_loss_scale=1.0, symmetrize=True, first_graph_corruption_config=dict( feature_drop_prob=0.4, edge_drop_prob=0.2, ), second_graph_corruption_config=dict( feature_drop_prob=0.4, edge_drop_prob=0.2, ), ), ), # GPU memory may require reducing the `256`s below to `48`. dynamic_batch_size_config=dict( n_node=256 if debug else 340 * 256, n_edge=512 if debug else 720 * 256, n_graph=4 if debug else 256, ), ), eval=dict( split='valid', ema_annealing_schedule=dict( use_schedule=True, base_rate=0.999, total_steps=config.get_ref('training_steps')), dynamic_batch_size_config=dict( n_node=256 if debug else 340 * 128, n_edge=512 if debug else 720 * 128, n_graph=4 if debug else 128, ), )))) ## Training loop config. config.training_steps = 500000 config.checkpoint_dir = '/tmp/checkpoint/mag/' config.train_checkpoint_all_hosts = False config.log_train_data_interval = 10 config.log_tensors_interval = 10 config.save_checkpoint_interval = 30 config.best_model_eval_metric = 'accuracy' config.best_model_eval_metric_higher_is_better = True return config
deepmind-research-master
ogb_lsc/mag/config.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Builds CSR matrices which store the MAG graphs.""" import pathlib from absl import app from absl import flags from absl import logging import numpy as np import scipy.sparse # pylint: disable=g-bad-import-order import data_utils Path = pathlib.Path FLAGS = flags.FLAGS _DATA_FILES_AND_PARAMETERS = { 'author_affiliated_with_institution_edges.npy': { 'content_names': ('author', 'institution'), 'use_boolean': False }, 'author_writes_paper_edges.npy': { 'content_names': ('author', 'paper'), 'use_boolean': False }, 'paper_cites_paper_edges.npy': { 'content_names': ('paper', 'paper'), 'use_boolean': True }, } flags.DEFINE_string('data_root', None, 'Data root directory') flags.DEFINE_boolean('skip_existing', True, 'Skips existing CSR files') flags.mark_flags_as_required(['data_root']) def _read_edge_data(path): try: return np.load(path, mmap_mode='r') except FileNotFoundError: # If the file path can't be found by np.load, use the file handle w/o mmap. with path.open('rb') as fid: return np.load(fid) def _build_coo(edges_data, use_boolean=False): if use_boolean: mat_coo = scipy.sparse.coo_matrix( (np.ones_like(edges_data[1, :], dtype=bool), (edges_data[0, :], edges_data[1, :]))) else: mat_coo = scipy.sparse.coo_matrix( (edges_data[1, :], (edges_data[0, :], edges_data[1, :]))) return mat_coo def _get_output_paths(directory, content_names, use_boolean): boolean_str = '_b' if use_boolean else '' transpose_str = '_t' if len(set(content_names)) == 1 else '' output_prefix = '_'.join(content_names) output_prefix_t = '_'.join(content_names[::-1]) output_filename = f'{output_prefix}{boolean_str}.npz' output_filename_t = f'{output_prefix_t}{boolean_str}{transpose_str}.npz' output_path = directory / output_filename output_path_t = directory / output_filename_t return output_path, output_path_t def _write_csr(path, csr): path.parent.mkdir(parents=True, exist_ok=True) with path.open('wb') as fid: scipy.sparse.save_npz(fid, csr) def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') raw_data_dir = Path(FLAGS.data_root) / data_utils.RAW_DIR preprocessed_dir = Path(FLAGS.data_root) / data_utils.PREPROCESSED_DIR for input_filename, parameters in _DATA_FILES_AND_PARAMETERS.items(): input_path = raw_data_dir / input_filename output_path, output_path_t = _get_output_paths(preprocessed_dir, **parameters) if FLAGS.skip_existing and output_path.exists() and output_path_t.exists(): # If both files exist, skip. When only one exists, that's handled below. logging.info( '%s and %s exist: skipping. Use flag `--skip_existing=False`' 'to force overwrite existing.', output_path, output_path_t) continue logging.info('Reading edge data from: %s', input_path) edge_data = _read_edge_data(input_path) logging.info('Building CSR matrices') mat_coo = _build_coo(edge_data, use_boolean=parameters['use_boolean']) # Convert matrices to CSR and write to disk. if not FLAGS.skip_existing or not output_path.exists(): logging.info('Writing CSR matrix to: %s', output_path) mat_csr = mat_coo.tocsr() _write_csr(output_path, mat_csr) del mat_csr # Free up memory asap. else: logging.info( '%s exists: skipping. Use flag `--skip_existing=False`' 'to force overwrite existing.', output_path) if not FLAGS.skip_existing or not output_path_t.exists(): logging.info('Writing (transposed) CSR matrix to: %s', output_path_t) mat_csr_t = mat_coo.transpose().tocsr() _write_csr(output_path_t, mat_csr_t) del mat_csr_t # Free up memory asap. else: logging.info( '%s exists: skipping. Use flag `--skip_existing=False`' 'to force overwrite existing.', output_path_t) del mat_coo # Free up memory asap. if __name__ == '__main__': app.run(main)
deepmind-research-master
ogb_lsc/mag/csr_builder.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MAG240M-LSC models.""" from typing import Callable, NamedTuple, Sequence import haiku as hk import jax import jax.numpy as jnp import jraph _REDUCER_NAMES = { 'sum': jax.ops.segment_sum, 'mean': jraph.segment_mean, 'softmax': jraph.segment_softmax, } class ModelOutput(NamedTuple): node_embeddings: jnp.ndarray node_embedding_projections: jnp.ndarray node_projection_predictions: jnp.ndarray node_logits: jnp.ndarray def build_update_fn( name: str, output_sizes: Sequence[int], activation: Callable[[jnp.ndarray], jnp.ndarray], normalization_type: str, is_training: bool, ): """Builds update function.""" def single_mlp(inner_name: str): """Creates a single MLP performing the update.""" mlp = hk.nets.MLP( output_sizes=output_sizes, name=inner_name, activation=activation) mlp = jraph.concatenated_args(mlp) if normalization_type == 'layer_norm': norm = hk.LayerNorm( axis=-1, create_scale=True, create_offset=True, name=name + '_layer_norm') elif normalization_type == 'batch_norm': batch_norm = hk.BatchNorm( create_scale=True, create_offset=True, decay_rate=0.9, name=f'{inner_name}_batch_norm', cross_replica_axis=None if hk.running_init() else 'i', ) norm = lambda x: batch_norm(x, is_training) elif normalization_type == 'none': return mlp else: raise ValueError(f'Unknown normalization type {normalization_type}') return jraph.concatenated_args(hk.Sequential([mlp, norm])) return single_mlp(f'{name}_homogeneous') def build_gn( output_sizes: Sequence[int], activation: Callable[[jnp.ndarray], jnp.ndarray], suffix: str, use_sent_edges: bool, is_training: bool, dropedge_rate: float, normalization_type: str, aggregation_function: str, ): """Builds an InteractionNetwork with MLP update functions.""" node_update_fn = build_update_fn( f'node_processor_{suffix}', output_sizes, activation=activation, normalization_type=normalization_type, is_training=is_training, ) edge_update_fn = build_update_fn( f'edge_processor_{suffix}', output_sizes, activation=activation, normalization_type=normalization_type, is_training=is_training, ) def maybe_dropedge(x): """Dropout on edge messages.""" if not is_training: return x return x * hk.dropout( hk.next_rng_key(), dropedge_rate, jnp.ones([x.shape[0], 1]), ) dropped_edge_update_fn = lambda *args: maybe_dropedge(edge_update_fn(*args)) return jraph.InteractionNetwork( update_edge_fn=dropped_edge_update_fn, update_node_fn=node_update_fn, aggregate_edges_for_nodes_fn=_REDUCER_NAMES[aggregation_function], include_sent_messages_in_node_update=use_sent_edges, ) def _get_activation_fn(name: str) -> Callable[[jnp.ndarray], jnp.ndarray]: if name == 'identity': return lambda x: x if hasattr(jax.nn, name): return getattr(jax.nn, name) raise ValueError('Unknown activation function %s specified. ' 'See https://jax.readthedocs.io/en/latest/jax.nn.html' 'for the list of supported function names.') class NodePropertyEncodeProcessDecode(hk.Module): """Node Property Prediction Encode Process Decode Model.""" def __init__( self, mlp_hidden_sizes: Sequence[int], latent_size: int, num_classes: int, num_message_passing_steps: int = 2, activation: str = 'relu', dropout_rate: float = 0.0, dropedge_rate: float = 0.0, use_sent_edges: bool = False, disable_edge_updates: bool = False, normalization_type: str = 'layer_norm', aggregation_function: str = 'sum', name='NodePropertyEncodeProcessDecode', ): super().__init__(name=name) self._num_classes = num_classes self._latent_size = latent_size self._output_sizes = list(mlp_hidden_sizes) + [latent_size] self._num_message_passing_steps = num_message_passing_steps self._activation = _get_activation_fn(activation) self._dropout_rate = dropout_rate self._dropedge_rate = dropedge_rate self._use_sent_edges = use_sent_edges self._disable_edge_updates = disable_edge_updates self._normalization_type = normalization_type self._aggregation_function = aggregation_function def _dropout_graph(self, graph: jraph.GraphsTuple) -> jraph.GraphsTuple: node_key, edge_key = hk.next_rng_keys(2) nodes = hk.dropout(node_key, self._dropout_rate, graph.nodes) edges = graph.edges if not self._disable_edge_updates: edges = hk.dropout(edge_key, self._dropout_rate, edges) return graph._replace(nodes=nodes, edges=edges) def _encode( self, graph: jraph.GraphsTuple, is_training: bool, ) -> jraph.GraphsTuple: node_embed_fn = build_update_fn( 'node_encoder', self._output_sizes, activation=self._activation, normalization_type=self._normalization_type, is_training=is_training, ) edge_embed_fn = build_update_fn( 'edge_encoder', self._output_sizes, activation=self._activation, normalization_type=self._normalization_type, is_training=is_training, ) gn = jraph.GraphMapFeatures(edge_embed_fn, node_embed_fn) graph = gn(graph) if is_training: graph = self._dropout_graph(graph) return graph def _process( self, graph: jraph.GraphsTuple, is_training: bool, ) -> jraph.GraphsTuple: for idx in range(self._num_message_passing_steps): net = build_gn( output_sizes=self._output_sizes, activation=self._activation, suffix=str(idx), use_sent_edges=self._use_sent_edges, is_training=is_training, dropedge_rate=self._dropedge_rate, normalization_type=self._normalization_type, aggregation_function=self._aggregation_function) residual_graph = net(graph) graph = graph._replace(nodes=graph.nodes + residual_graph.nodes) if not self._disable_edge_updates: graph = graph._replace(edges=graph.edges + residual_graph.edges) if is_training: graph = self._dropout_graph(graph) return graph def _node_mlp( self, graph: jraph.GraphsTuple, is_training: bool, output_size: int, name: str, ) -> jnp.ndarray: decoder_sizes = list(self._output_sizes[:-1]) + [output_size] net = build_update_fn( name, decoder_sizes, self._activation, normalization_type=self._normalization_type, is_training=is_training, ) return net(graph.nodes) def __call__( self, graph: jraph.GraphsTuple, is_training: bool, stop_gradient_embedding_to_logits: bool = False, ) -> ModelOutput: # Note that these update configs may need to change if # we switch back to GraphNetwork rather than InteractionNetwork. graph = self._encode(graph, is_training) graph = self._process(graph, is_training) node_embeddings = graph.nodes node_projections = self._node_mlp(graph, is_training, self._latent_size, 'projector') node_predictions = self._node_mlp( graph._replace(nodes=node_projections), is_training, self._latent_size, 'predictor', ) if stop_gradient_embedding_to_logits: graph = jax.tree_map(jax.lax.stop_gradient, graph) node_logits = self._node_mlp(graph, is_training, self._num_classes, 'logits_decoder') return ModelOutput( node_embeddings=node_embeddings, node_logits=node_logits, node_embedding_projections=node_projections, node_projection_predictions=node_predictions, )
deepmind-research-master
ogb_lsc/mag/models.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for subsampling the MAG dataset.""" import collections import jraph import numpy as np def get_or_sample_row(node_id: int, nb_neighbours: int, csr_matrix, remove_duplicates: bool): """Either obtain entire row or a subsampled set of neighbours.""" if node_id + 1 >= csr_matrix.indptr.shape[0]: lo = 0 hi = 0 else: lo = csr_matrix.indptr[node_id] hi = csr_matrix.indptr[node_id + 1] if lo == hi: # Skip empty neighbourhoods neighbours = None elif hi - lo <= nb_neighbours: neighbours = csr_matrix.indices[lo:hi] elif hi - lo < 5 * nb_neighbours: # For small surroundings, sample directly nb_neighbours = min(nb_neighbours, hi - lo) inds = lo + np.random.choice(hi - lo, size=(nb_neighbours,), replace=False) neighbours = csr_matrix.indices[inds] else: # Otherwise, do not slice -- sample indices instead # To extend GraphSAGE ("uniform w/ replacement"), modify this call inds = np.random.randint(lo, hi, size=(nb_neighbours,)) if remove_duplicates: inds = np.unique(inds) neighbours = csr_matrix.indices[inds] return neighbours def get_neighbours(node_id: int, node_type: int, neighbour_type: int, nb_neighbours: int, remove_duplicates: bool, author_institution_csr, institution_author_csr, author_paper_csr, paper_author_csr, paper_paper_csr, paper_paper_transpose_csr): """Fetch the edge indices from one node to corresponding neighbour type.""" if node_type == 0 and neighbour_type == 0: csr = paper_paper_transpose_csr # Citing elif node_type == 0 and neighbour_type == 1: csr = paper_author_csr elif node_type == 0 and neighbour_type == 3: csr = paper_paper_csr # Cited elif node_type == 1 and neighbour_type == 0: csr = author_paper_csr elif node_type == 1 and neighbour_type == 2: csr = author_institution_csr elif node_type == 2 and neighbour_type == 1: csr = institution_author_csr else: raise ValueError('Non-existent edge type requested') return get_or_sample_row(node_id, nb_neighbours, csr, remove_duplicates) def get_senders(neighbour_type: int, sender_index, paper_features): """Get the sender features from given neighbours.""" if neighbour_type == 0 or neighbour_type == 3: sender_features = paper_features[sender_index] elif neighbour_type == 1 or neighbour_type == 2: sender_features = np.zeros((sender_index.shape[0], paper_features.shape[1])) # Consider averages else: raise ValueError('Non-existent node type requested') return sender_features def make_edge_type_feature(node_type: int, neighbour_type: int): edge_feats = np.zeros(7) edge_feats[node_type] = 1.0 edge_feats[neighbour_type + 3] = 1.0 return edge_feats def subsample_graph(paper_id: int, author_institution_csr, institution_author_csr, author_paper_csr, paper_author_csr, paper_paper_csr, paper_paper_transpose_csr, max_nb_neighbours_per_type, max_nodes=None, max_edges=None, paper_years=None, remove_future_nodes=False, deduplicate_nodes=False) -> jraph.GraphsTuple: """Subsample a graph around given paper ID.""" if paper_years is not None: root_paper_year = paper_years[paper_id] else: root_paper_year = None # Add the center node as "node-zero" sub_nodes = [paper_id] num_nodes_in_subgraph = 1 num_edges_in_subgraph = 0 reached_node_budget = False reached_edge_budget = False node_and_type_to_index_in_subgraph = dict() node_and_type_to_index_in_subgraph[(paper_id, 0)] = 0 # Store all (integer) depths as an additional feature depths = [0] types = [0] sub_edges = [] sub_senders = [] sub_receivers = [] # Store all unprocessed neighbours # Each neighbour is stored as a 4-tuple (node_index in original graph, # node_index in subsampled graph, type, number of hops away from source). # TYPES: 0: paper, 1: author, 2: institution, 3: paper (for bidirectional) neighbour_deque = collections.deque([(paper_id, 0, 0, 0)]) max_depth = len(max_nb_neighbours_per_type) while neighbour_deque and not reached_edge_budget: left_entry = neighbour_deque.popleft() node_index, node_index_in_sampled_graph, node_type, node_depth = left_entry # Expand from this node, to a node of related type for neighbour_type in range(4): if reached_edge_budget: break # Budget may have been reached in previous type; break here. nb_neighbours = max_nb_neighbours_per_type[node_depth][node_type][neighbour_type] # pylint:disable=line-too-long # Only extend if we want to sample further in this edge type if nb_neighbours > 0: sampled_neighbors = get_neighbours( node_index, node_type, neighbour_type, nb_neighbours, deduplicate_nodes, author_institution_csr, institution_author_csr, author_paper_csr, paper_author_csr, paper_paper_csr, paper_paper_transpose_csr, ) if sampled_neighbors is not None: if remove_future_nodes and root_paper_year is not None: if neighbour_type in [0, 3]: sampled_neighbors = [ x for x in sampled_neighbors if paper_years[x] <= root_paper_year ] if not sampled_neighbors: continue nb_neighbours = len(sampled_neighbors) edge_feature = make_edge_type_feature(node_type, neighbour_type) for neighbor_original_idx in sampled_neighbors: # Key into dict of existing nodes using both node id and type. neighbor_key = (neighbor_original_idx, neighbour_type % 3) # Get existing idx in subgraph if it exists. neighbor_subgraph_idx = node_and_type_to_index_in_subgraph.get( neighbor_key, None) if (not reached_node_budget and (not deduplicate_nodes or neighbor_subgraph_idx is None)): # If it does not exist already, or we are not deduplicating, # just create a new node and update the dict. neighbor_subgraph_idx = num_nodes_in_subgraph node_and_type_to_index_in_subgraph[neighbor_key] = ( neighbor_subgraph_idx) num_nodes_in_subgraph += 1 sub_nodes.append(neighbor_original_idx) types.append(neighbour_type % 3) depths.append(node_depth + 1) if max_nodes is not None and num_nodes_in_subgraph >= max_nodes: reached_node_budget = True continue # Move to next neighbor which might already exist. if node_depth < max_depth - 1: # If the neighbours are to be further expanded, enqueue them. # Expand only if the nodes did not already exist. neighbour_deque.append( (neighbor_original_idx, neighbor_subgraph_idx, neighbour_type % 3, node_depth + 1)) # The neighbor id within graph is now fixed; just add edges. if neighbor_subgraph_idx is not None: # Either node existed before or was successfully added. sub_senders.append(neighbor_subgraph_idx) sub_receivers.append(node_index_in_sampled_graph) sub_edges.append(edge_feature) num_edges_in_subgraph += 1 if max_edges is not None and num_edges_in_subgraph >= max_edges: reached_edge_budget = True break # Break out of adding edges for this neighbor type # Stitch the graph together sub_nodes = np.array(sub_nodes, dtype=np.int32) if sub_senders: sub_senders = np.array(sub_senders, dtype=np.int32) sub_receivers = np.array(sub_receivers, dtype=np.int32) sub_edges = np.stack(sub_edges, axis=0) else: # Use empty arrays. sub_senders = np.zeros([0], dtype=np.int32) sub_receivers = np.zeros([0], dtype=np.int32) sub_edges = np.zeros([0, 7]) # Finally, derive the sizes sub_n_node = np.array([sub_nodes.shape[0]]) sub_n_edge = np.array([sub_senders.shape[0]]) assert sub_nodes.shape[0] == num_nodes_in_subgraph assert sub_edges.shape[0] == num_edges_in_subgraph if max_nodes is not None: assert num_nodes_in_subgraph <= max_nodes if max_edges is not None: assert num_edges_in_subgraph <= max_edges types = np.array(types) depths = np.array(depths) sub_nodes = { 'index': sub_nodes.astype(np.int32), 'type': types.astype(np.int16), 'depth': depths.astype(np.int16), } return jraph.GraphsTuple(nodes=sub_nodes, edges=sub_edges.astype(np.float16), senders=sub_senders.astype(np.int32), receivers=sub_receivers.astype(np.int32), globals=np.array([0], dtype=np.int16), n_node=sub_n_node.astype(dtype=np.int32), n_edge=sub_n_edge.astype(dtype=np.int32))
deepmind-research-master
ogb_lsc/mag/sub_sampler.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MAG240M-LSC datasets.""" import threading from typing import NamedTuple, Optional import jax import jraph from ml_collections import config_dict import numpy as np import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds # pylint: disable=g-bad-import-order # pytype: disable=import-error import batching_utils import data_utils # We only want to load these arrays once for all threads. # `get_arrays` uses an LRU cache which is not thread safe. LOADING_RAW_ARRAYS_LOCK = threading.Lock() NUM_CLASSES = data_utils.NUM_CLASSES _MAX_DEPTH_IN_SUBGRAPH = 3 class Batch(NamedTuple): """NamedTuple to represent batches of data.""" graph: jraph.GraphsTuple node_labels: np.ndarray label_mask: np.ndarray central_node_mask: np.ndarray node_indices: np.ndarray absolute_node_indices: np.ndarray def build_dataset_iterator( data_root: str, split: str, dynamic_batch_size_config: config_dict.ConfigDict, online_subsampling_kwargs: dict, # pylint: disable=g-bare-generic debug: bool = False, is_training: bool = True, k_fold_split_id: Optional[int] = None, ratio_unlabeled_data_to_labeled_data: float = 0.0, use_all_labels_when_not_training: bool = False, use_dummy_adjacencies: bool = False, ): """Returns an iterator over Batches from the dataset.""" if split == 'test': use_all_labels_when_not_training = True if not is_training: ratio_unlabeled_data_to_labeled_data = 0.0 # Load the master data arrays. with LOADING_RAW_ARRAYS_LOCK: array_dict = data_utils.get_arrays( data_root, k_fold_split_id=k_fold_split_id, use_dummy_adjacencies=use_dummy_adjacencies) node_labels = array_dict['paper_label'].reshape(-1) train_indices = array_dict['train_indices'].astype(np.int32) is_train_index = np.zeros(node_labels.shape[0], dtype=np.int32) is_train_index[train_indices] = 1 valid_indices = array_dict['valid_indices'].astype(np.int32) is_valid_index = np.zeros(node_labels.shape[0], dtype=np.int32) is_valid_index[valid_indices] = 1 is_train_or_valid_index = is_train_index + is_valid_index def sstable_to_intermediate_graph(graph): indices = tf.cast(graph.nodes['index'], tf.int32) first_index = indices[..., 0] # Add an additional absolute index, but adding offsets to authors, and # institution indices. absolute_index = graph.nodes['index'] is_author = graph.nodes['type'] == 1 absolute_index = tf.where( is_author, absolute_index + data_utils.NUM_PAPERS, absolute_index) is_institution = graph.nodes['type'] == 2 absolute_index = tf.where( is_institution, absolute_index + data_utils.NUM_PAPERS + data_utils.NUM_AUTHORS, absolute_index) is_same_as_central_node = tf.math.equal(indices, first_index) input_nodes = graph.nodes graph = graph._replace( nodes={ 'one_hot_type': tf.one_hot(tf.cast(input_nodes['type'], tf.int32), 3), 'one_hot_depth': tf.one_hot( tf.cast(input_nodes['depth'], tf.int32), _MAX_DEPTH_IN_SUBGRAPH), 'year': tf.expand_dims(input_nodes['year'], axis=-1), 'label': tf.one_hot( tf.cast(input_nodes['label'], tf.int32), NUM_CLASSES), 'is_same_as_central_node': is_same_as_central_node, # Only first node in graph has a valid label. 'is_central_node': tf.one_hot(0, tf.shape(input_nodes['label'])[0]), 'index': input_nodes['index'], 'absolute_index': absolute_index, }, globals=tf.expand_dims(graph.globals, axis=-1), ) return graph ds = data_utils.get_graph_subsampling_dataset( split, array_dict, shuffle_indices=is_training, ratio_unlabeled_data_to_labeled_data=ratio_unlabeled_data_to_labeled_data, max_nodes=dynamic_batch_size_config.n_node - 1, # Keep space for pads. max_edges=dynamic_batch_size_config.n_edge, **online_subsampling_kwargs) if debug: ds = ds.take(50) ds = ds.map( sstable_to_intermediate_graph, num_parallel_calls=tf.data.experimental.AUTOTUNE) if is_training: ds = ds.shard(jax.process_count(), jax.process_index()) ds = ds.shuffle(buffer_size=1 if debug else 128) ds = ds.repeat() ds = ds.prefetch(1 if debug else tf.data.experimental.AUTOTUNE) np_ds = iter(tfds.as_numpy(ds)) batched_np_ds = batching_utils.dynamically_batch( np_ds, **dynamic_batch_size_config, ) def intermediate_graph_to_batch(graph): central_node_mask = graph.nodes['is_central_node'] label = graph.nodes['label'] node_indices = graph.nodes['index'] absolute_indices = graph.nodes['absolute_index'] ### Construct label as a feature for non-central nodes. # First do a lookup with node indices, with a np.minimum to ensure we do not # index out of bounds due to num_authors being larger than num_papers. is_same_as_central_node = graph.nodes['is_same_as_central_node'] capped_indices = np.minimum(node_indices, node_labels.shape[0] - 1) label_as_feature = node_labels[capped_indices] # Nodes which are not in train set should get `num_classes` label. # Nodes in test set or non-arXiv nodes have -1 or nan labels. # Mask out invalid labels and non-papers. use_label_as_feature = np.logical_and(label_as_feature >= 0, graph.nodes['one_hot_type'][..., 0]) if split == 'train' or not use_all_labels_when_not_training: # Mask out validation papers and non-arxiv papers who # got labels from fusing with arxiv papers. use_label_as_feature = np.logical_and(is_train_index[capped_indices], use_label_as_feature) label_as_feature = np.where(use_label_as_feature, label_as_feature, NUM_CLASSES) # Mask out central node label in case it appears again. label_as_feature = np.where(is_same_as_central_node, NUM_CLASSES, label_as_feature) # Nodes which are not papers get `NUM_CLASSES+1` label. label_as_feature = np.where(graph.nodes['one_hot_type'][..., 0], label_as_feature, NUM_CLASSES+1) nodes = { 'label_as_feature': label_as_feature, 'year': graph.nodes['year'], 'bitstring_year': _get_bitstring_year_representation( graph.nodes['year']), 'one_hot_type': graph.nodes['one_hot_type'], 'one_hot_depth': graph.nodes['one_hot_depth'], } graph = graph._replace( nodes=nodes, globals={}, ) is_train_or_valid_node = np.logical_and( is_train_or_valid_index[capped_indices], graph.nodes['one_hot_type'][..., 0]) if is_training: label_mask = np.logical_and(central_node_mask, is_train_or_valid_node) else: # `label_mask` is used to index into valid central nodes by prediction # calculator. Since that computation is only done when not training, and # at that time we are guaranteed all central nodes have valid labels, # we just set label_mask = central_node_mask when not training. label_mask = central_node_mask batch = Batch( graph=graph, node_labels=label, central_node_mask=central_node_mask, label_mask=label_mask, node_indices=node_indices, absolute_node_indices=absolute_indices) # Transform integers into one-hots. batch = _add_one_hot_features_to_batch(batch) # Gather PCA features. return _add_embeddings_to_batch(batch, array_dict['bert_pca_129']) batch_list = [] for batch in batched_np_ds: with jax.profiler.StepTraceAnnotation('batch_postprocessing'): batch = intermediate_graph_to_batch(batch) if is_training: batch_list.append(batch) if len(batch_list) == jax.local_device_count(): yield jax.device_put_sharded(batch_list, jax.local_devices()) batch_list = [] else: yield batch def _get_bitstring_year_representation(year: np.ndarray): """Return year as bitstring.""" min_year = 1900 max_training_year = 2018 offseted_year = np.minimum(year, max_training_year) - min_year return np.unpackbits(offseted_year.astype(np.uint8), axis=-1) def _np_one_hot(targets: np.ndarray, nb_classes: int): res = np.zeros(targets.shape + (nb_classes,), dtype=np.float16) np.put_along_axis(res, targets.astype(np.int32)[..., None], 1.0, axis=-1) return res def _get_one_hot_year_representation( year: np.ndarray, one_hot_type: np.ndarray, ): """Returns good representation for year.""" # Bucket edges found based on quantiles to bucket into 20 equal sized buckets. bucket_edges = np.array([ 1964, 1975, 1983, 1989, 1994, 1998, 2001, 2004, 2006, 2008, 2009, 2011, 2012, 2013, 2014, 2016, 2017, # 2018, 2019, 2020 contain last-year-of-train, eval, test nodes ]) year = np.squeeze(year, axis=-1) year_id = np.searchsorted(bucket_edges, year) is_paper = one_hot_type[..., 0] bucket_id_for_non_paper = len(bucket_edges) + 1 bucket_id = np.where(is_paper, year_id, bucket_id_for_non_paper) one_hot_year = _np_one_hot(bucket_id, len(bucket_edges) + 2) return one_hot_year def _add_one_hot_features_to_batch(batch: Batch) -> Batch: """Transforms integer features into one-hot features.""" nodes = batch.graph.nodes.copy() nodes['one_hot_year'] = _get_one_hot_year_representation( nodes['year'], nodes['one_hot_type']) del nodes['year'] # NUM_CLASSES plus one category for papers for which a class is not provided # and another for nodes that are not papers. nodes['one_hot_label_as_feature'] = _np_one_hot( nodes['label_as_feature'], NUM_CLASSES + 2) del nodes['label_as_feature'] return batch._replace(graph=batch.graph._replace(nodes=nodes)) def _add_embeddings_to_batch(batch: Batch, embeddings: np.ndarray) -> Batch: nodes = batch.graph.nodes.copy() nodes['features'] = embeddings[batch.absolute_node_indices] graph = batch.graph._replace(nodes=nodes) return batch._replace(graph=graph)
deepmind-research-master
ogb_lsc/mag/datasets.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=line-too-long r"""MAG240M-LSC Jaxline experiment. Usage: ``` # A path pointing to the data root. DATA_ROOT=/tmp/mag/data # A path for checkpoints. CHECKPOINT_DIR=/tmp/checkpoint/ # A path for output predictions. OUTPUT_DIR=/tmp/predictions/ # Whether we are training a model of a k_fold of models (None for no k-fold) K_FOLD_INDEX=0 ``` Some reusable arguments: ``` SHARED_ARGUMENTS="--config=ogb_lsc/mag/config.py \ --config.experiment_kwargs.config.dataset_kwargs.data_root=${DATA_ROOT} \ --config.experiment_kwargs.config.dataset_kwargs.k_fold_split_id=${K_FOLD_INDEX} \ --config.checkpoint_dir=${CHECKPOINT_DIR}" ``` Train only: ``` python -m ogb_lsc.mag.experiment \ ${SHARED_ARGUMENTS} --jaxline_mode="train" RESTORE_PATH=${CHECKPOINT_DIR}/models/latest/step_${STEP}_${TIMESTAMP} ``` Train with early stopping on a separate eval thread: ``` python -m ogb_lsc.mag.experiment \ ${SHARED_ARGUMENTS} --jaxline_mode="train_eval_multithreaded" RESTORE_PATH=${CHECKPOINT_DIR}/models/best/step_${STEP}_${TIMESTAMP} ``` Produce predictions with a pretrained model: ``` SPLIT="valid" # Or "test" EPOCHS_TO_ENSEMBLE=50 # We used this in the submission. python -m ogb_lsc.mag.experiment \ ${SHARED_ARGUMENTS} --jaxline_mode="eval" \ --config.one_off_evaluate=True \ --config.experiment_kwargs.config.num_eval_iterations_to_ensemble=${EPOCHS_TO_ENSEMBLE} \ --config.restore_path=${RESTORE_PATH} \ --config.experiment_kwargs.config.predictions_dir=${OUTPUT_DIR} \ --config.experiment_kwargs.config.eval.split=${SPLIT} ``` Note it is also possible to pass a `restore_path` with `--jaxline_mode="train"` and training will continue where it left off. In the case of `--jaxline_mode="train_eval_multithreaded"` this will also work, but early stopping will not take into account any past best performance up to that restored model. Other useful options: To reduce the training batch size in case of OOM, for example for a batch size of approximately 48 on average. ``` SHARED_ARGUMENTS="${SHARED_ARGUMENTS} \ --config.experiment_kwargs.config.training.dynamic_batch_size_config.n_node=16320 \ --config.experiment_kwargs.config.training.dynamic_batch_size_config.n_edge=34560 \ --config.experiment_kwargs.config.training.dynamic_batch_size_config.n_graph=48" ``` To reduce lead time by using dummy adjacency matrices, instead of loading the the full ones into memory. ``` SHARED_ARGUMENTS="${SHARED_ARGUMENTS} \ --config.experiment_kwargs.config.dataset_kwargs.use_dummy_adjacencies=True" ``` """ # pylint: enable=line-too-long import datetime import functools import os import signal import threading from typing import Tuple from absl import app from absl import flags from absl import logging import chex import dill import haiku as hk import jax from jax.config import config as jax_config import jax.numpy as jnp from jaxline import experiment from jaxline import platform from jaxline import utils import jraph from ml_collections import config_dict import numpy as np import optax import tensorflow.compat.v2 as tf # pylint: disable=g-bad-import-order import datasets import losses import models import schedules FLAGS = flags.FLAGS class Experiment(experiment.AbstractExperiment): """MAG240M-LSC Jaxline experiment.""" CHECKPOINT_ATTRS = { '_params': 'params', '_opt_state': 'opt_state', '_network_state': 'network_state', '_ema_network_state': 'ema_network_state', '_ema_params': 'ema_params', } def __init__( self, mode: str, init_rng: jnp.ndarray, config: config_dict.ConfigDict, ): """Initializes experiment.""" super(Experiment, self).__init__(mode=mode, init_rng=init_rng) tf.config.experimental.set_visible_devices([], device_type='GPU') tf.config.experimental.set_visible_devices([], device_type='TPU') if mode not in ('train', 'eval', 'train_eval_multithreaded'): raise ValueError(f'Invalid mode {mode}.') self.mode = mode self.config = config self.init_rng = init_rng self.forward = hk.transform_with_state(self._forward_fn) self._predictions = None # Needed for checkpoint restore. self._params = None self._ema_params = None self._network_state = None self._ema_network_state = None self._opt_state = None # Track what has started. self._training = False self._evaluating = False def _train_init(self): iterator = self._build_numpy_dataset_iterator('train', is_training=True) self._train_input = utils.py_prefetch(lambda: iterator) dummy_batch = next(self._train_input) if self._params is None: self._initialize_experiment_state(self.init_rng, dummy_batch) self._update_func = jax.pmap( self._update_func, axis_name='i', donate_argnums=3, ) self._training = True def _eval_init(self): split = self.config.eval.split # Will build the iterator at each evaluation. self._make_eval_dataset_iterator = functools.partial( utils.py_prefetch, lambda: self._build_numpy_dataset_iterator(split, is_training=False)) self.eval_forward = jax.jit( functools.partial(self.forward.apply, is_training=False)) self._evaluating = True # _ _ # | |_ _ __ __ _(_)_ __ # | __| '__/ _` | | '_ \ # | |_| | | (_| | | | | | # \__|_| \__,_|_|_| |_| # def step( self, global_step: jnp.ndarray, rng: jnp.ndarray, **unused_args, ) -> losses.LogsDict: """See Jaxline base class.""" if not self._training: self._train_init() with jax.profiler.StepTraceAnnotation('next_train_input'): batch = next(self._train_input) with jax.profiler.StepTraceAnnotation('update_step'): (self._params, self._ema_params, self._network_state, self._ema_network_state, self._opt_state, stats) = self._update_func( self._params, self._ema_params, self._network_state, self._ema_network_state, self._opt_state, global_step, rng, batch, ) del batch # Buffers donated to _update_func. with jax.profiler.StepTraceAnnotation('get_stats'): stats = utils.get_first(stats) return stats def _build_numpy_dataset_iterator(self, split: str, is_training: bool): if is_training: dynamic_batch_size_config = self.config.training.dynamic_batch_size_config else: dynamic_batch_size_config = self.config.eval.dynamic_batch_size_config return datasets.build_dataset_iterator( split=split, dynamic_batch_size_config=dynamic_batch_size_config, debug=self.config.debug, is_training=is_training, **self.config.dataset_kwargs) def _initialize_experiment_state( self, init_rng: jnp.ndarray, dummy_batch: datasets.Batch, ): """Initialize parameters and opt state if not restoring from checkpoint.""" dummy_graph = dummy_batch.graph # Cast features to float32 so that parameters are as appropriate. dummy_graph = dummy_graph._replace( nodes=jax.tree_map(lambda x: x.astype(np.float32), dummy_graph.nodes), edges=jax.tree_map(lambda x: x.astype(np.float32), dummy_graph.edges), ) init_key = utils.bcast_local_devices(init_rng) p_init = jax.pmap(functools.partial(self.forward.init, is_training=True)) params, network_state = p_init(init_key, dummy_graph) opt_init, _ = self._optimizer( utils.bcast_local_devices(jnp.zeros([], jnp.int32))) opt_state = jax.pmap(opt_init)(params) # For EMA decay to work correctly, params/state must be floats. chex.assert_type(jax.tree_leaves(params), jnp.floating) chex.assert_type(jax.tree_leaves(network_state), jnp.floating) self._params = params self._ema_params = params self._network_state = network_state self._ema_network_state = network_state self._opt_state = opt_state def _get_learning_rate(self, global_step: jnp.ndarray) -> jnp.ndarray: return schedules.learning_schedule( global_step, **self.config.optimizer.learning_rate_schedule, ) def _optimizer( self, learning_rate: jnp.ndarray, ) -> optax.GradientTransformation: optimizer_fn = getattr(optax, self.config.optimizer.name) return optimizer_fn( learning_rate=learning_rate, **self.config.optimizer.kwargs, ) def _forward_fn( self, input_graph: jraph.GraphsTuple, is_training: bool, stop_gradient_embedding_to_logits: bool = False, ): model = models.NodePropertyEncodeProcessDecode( num_classes=datasets.NUM_CLASSES, **self.config.model_config, ) return model(input_graph, is_training, stop_gradient_embedding_to_logits) def _bgrl_loss( self, params: hk.Params, ema_params: hk.Params, network_state: hk.State, ema_network_state: hk.State, rng: jnp.ndarray, batch: datasets.Batch, ) -> Tuple[jnp.ndarray, Tuple[losses.LogsDict, hk.State]]: """Computes fully supervised loss.""" # First compute 2 graph corrupted views. first_corruption_key, second_corruption_key, rng = jax.random.split(rng, 3) (first_model_key, first_model_key_ema, second_model_key, second_model_key_ema, rng) = jax.random.split(rng, 5) first_corrupted_graph = losses.get_corrupted_view( batch.graph, rng_key=first_corruption_key, **self.config.training.loss_config.bgrl_loss_config.first_graph_corruption_config, # pylint:disable=line-too-long ) second_corrupted_graph = losses.get_corrupted_view( batch.graph, rng_key=second_corruption_key, **self.config.training.loss_config.bgrl_loss_config.second_graph_corruption_config, # pylint:disable=line-too-long ) # Then run the model on both. first_corrupted_output, _ = self.forward.apply( params, network_state, first_model_key, first_corrupted_graph, is_training=True, stop_gradient_embedding_to_logits=True, ) second_corrupted_output, _ = self.forward.apply( params, network_state, second_model_key, second_corrupted_graph, is_training=True, stop_gradient_embedding_to_logits=True, ) first_corrupted_output_ema, _ = self.forward.apply( ema_params, ema_network_state, first_model_key_ema, first_corrupted_graph, is_training=True, stop_gradient_embedding_to_logits=True, ) second_corrupted_output_ema, _ = self.forward.apply( ema_params, ema_network_state, second_model_key_ema, second_corrupted_graph, is_training=True, stop_gradient_embedding_to_logits=True, ) # These also contain projections for non-central nodes; remove them. num_nodes_per_graph = batch.graph.n_node node_central_indices = jnp.concatenate( [jnp.array([0]), jnp.cumsum(num_nodes_per_graph[:-1])]) bgrl_loss, bgrl_stats = losses.bgrl_loss( first_online_predictions=first_corrupted_output .node_projection_predictions[node_central_indices], second_target_projections=second_corrupted_output_ema .node_embedding_projections[node_central_indices], second_online_predictions=second_corrupted_output .node_projection_predictions[node_central_indices], first_target_projections=first_corrupted_output_ema .node_embedding_projections[node_central_indices], symmetrize=self.config.training.loss_config.bgrl_loss_config.symmetrize, valid_mask=batch.central_node_mask[node_central_indices], ) # Finally train decoder on original graph with optional stop gradient. stop_gradient = ( self.config.training.loss_config.bgrl_loss_config .stop_gradient_for_supervised_loss) model_output, new_network_state = self.forward.apply( params, network_state, rng, batch.graph, is_training=True, stop_gradient_embedding_to_logits=stop_gradient, ) supervised_loss, supervised_stats = losses.node_classification_loss( model_output.node_logits, batch, ) stats = dict(**supervised_stats, **bgrl_stats) total_loss = ( supervised_loss + self.config.training.loss_config.bgrl_loss_config.bgrl_loss_scale * bgrl_loss) return total_loss, (stats, new_network_state) def _loss( self, params: hk.Params, ema_params: hk.Params, network_state: hk.State, ema_network_state: hk.State, rng: jnp.ndarray, batch: datasets.Batch, ) -> Tuple[jnp.ndarray, Tuple[losses.LogsDict, hk.State]]: """Compute loss from params and batch.""" # Cast to float32 since some losses are unstable with float16. graph = batch.graph._replace( nodes=jax.tree_map(lambda x: x.astype(jnp.float32), batch.graph.nodes), edges=jax.tree_map(lambda x: x.astype(jnp.float32), batch.graph.edges), ) batch = batch._replace(graph=graph) return self._bgrl_loss(params, ema_params, network_state, ema_network_state, rng, batch) def _update_func( self, params: hk.Params, ema_params: hk.Params, network_state: hk.State, ema_network_state: hk.State, opt_state: optax.OptState, global_step: jnp.ndarray, rng: jnp.ndarray, batch: datasets.Batch, ) -> Tuple[hk.Params, hk.Params, hk.State, hk.State, optax.OptState, losses.LogsDict]: """Updates parameters.""" grad_fn = jax.value_and_grad(self._loss, has_aux=True) (_, (stats, new_network_state)), grads = grad_fn( params, ema_params, network_state, ema_network_state, rng, batch) learning_rate = self._get_learning_rate(global_step) _, opt_apply = self._optimizer(learning_rate) grad = jax.lax.pmean(grads, axis_name='i') updates, opt_state = opt_apply(grad, opt_state, params) params = optax.apply_updates(params, updates) # Stats and logging. param_norm = optax.global_norm(params) grad_norm = optax.global_norm(grad) ema_rate = schedules.ema_decay_schedule( step=global_step, **self.config.eval.ema_annealing_schedule) num_non_padded_nodes = ( batch.graph.n_node.sum() - jraph.get_number_of_padding_with_graphs_nodes(batch.graph)) num_non_padded_edges = ( batch.graph.n_edge.sum() - jraph.get_number_of_padding_with_graphs_edges(batch.graph)) num_non_padded_graphs = ( batch.graph.n_node.shape[0] - jraph.get_number_of_padding_with_graphs_graphs(batch.graph)) avg_num_nodes = num_non_padded_nodes / num_non_padded_graphs avg_num_edges = num_non_padded_edges / num_non_padded_graphs stats.update( dict( global_step=global_step, grad_norm=grad_norm, param_norm=param_norm, learning_rate=learning_rate, ema_rate=ema_rate, avg_num_nodes=avg_num_nodes, avg_num_edges=avg_num_edges, )) ema_fn = (lambda x, y: # pylint:disable=g-long-lambda schedules.apply_ema_decay(x, y, ema_rate)) ema_params = jax.tree_map(ema_fn, ema_params, params) ema_network_state = jax.tree_map( ema_fn, ema_network_state, network_state, ) return (params, ema_params, new_network_state, ema_network_state, opt_state, stats) # _ # _____ ____ _| | # / _ \ \ / / _` | | # | __/\ V / (_| | | # \___| \_/ \__,_|_| # def evaluate(self, global_step, rng, **unused_kwargs): """See base class.""" if not self._evaluating: self._eval_init() global_step = np.array(utils.get_first(global_step)) ema_params = utils.get_first(self._ema_params) ema_network_state = utils.get_first(self._ema_network_state) rng = utils.get_first(rng) # Evaluate using the ema params. results, predictions = self._evaluate_with_ensemble(ema_params, ema_network_state, rng) results['global_step'] = global_step # Store predictions if we got a path. self._maybe_save_predictions(predictions, global_step) return results def _evaluate_with_ensemble( self, params: hk.Params, state: hk.State, rng: jnp.ndarray, ): predictions_for_ensemble = [] num_iterations = self.config.num_eval_iterations_to_ensemble for iteration in range(num_iterations): results, predictions = self._evaluate_params(params, state, rng) self._log_results(f'Eval iteration {iteration}/{num_iterations}', results) predictions_for_ensemble.append(predictions) if len(predictions_for_ensemble) > 1: predictions = losses.ensemble_predictions_by_probability_average( predictions_for_ensemble) results = losses.get_accuracy_dict(predictions) self._log_results(f'Ensembled {num_iterations} iterations', results) return results, predictions def _maybe_save_predictions(self, predictions, global_step): if not self.config.predictions_dir: return split = self.config.eval.split output_dir = os.path.join( self.config.predictions_dir, _get_step_date_label(global_step)) os.makedirs(output_dir, exist_ok=True) output_path = os.path.join(output_dir, split + '.dill') with open(output_path, 'wb') as f: dill.dump(predictions, f) logging.info('Saved %s predictions at: %s', split, output_path) def _evaluate_params( self, params: hk.Params, state: hk.State, rng: jnp.ndarray, ): """Evaluate given set of parameters.""" num_valid = 0 predictions_list = [] labels_list = [] logits_list = [] indices_list = [] for i, batch in enumerate(self._make_eval_dataset_iterator()): model_output, _ = self.eval_forward( params, state, rng, batch.graph, ) (masked_indices, masked_predictions, masked_labels, masked_logits) = losses.get_predictions_labels_and_logits( model_output.node_logits, batch) predictions_list.append(masked_predictions) indices_list.append(masked_indices) labels_list.append(masked_labels) logits_list.append(masked_logits) num_valid += jnp.sum(batch.label_mask) if i % 10 == 0: logging.info('Generate predictons for %d batches so far', i + 1) predictions = losses.Predictions( np.concatenate(indices_list, axis=0), np.concatenate(labels_list, axis=0), np.concatenate(predictions_list, axis=0), np.concatenate(logits_list, axis=0)) if self.config.eval.split == 'test': results = dict(num_valid=num_valid, accuracy=np.nan) else: results = losses.get_accuracy_dict(predictions) return results, predictions def _log_results(self, prefix, results): logging_str = ', '.join( ['{}={:.4f}'.format(k, float(results[k])) for k in sorted(results.keys())]) logging.info('%s: %s', prefix, logging_str) def _restore_state_to_in_memory_checkpointer(restore_path): """Initializes experiment state from a checkpoint.""" # Load pretrained experiment state. python_state_path = os.path.join(restore_path, 'checkpoint.dill') with open(python_state_path, 'rb') as f: pretrained_state = dill.load(f) logging.info('Restored checkpoint from %s', python_state_path) # Assign state to a dummy experiment instance for the in-memory checkpointer, # broadcasting to devices. dummy_experiment = Experiment( mode='train', init_rng=0, config=FLAGS.config.experiment_kwargs.config) for attribute, key in Experiment.CHECKPOINT_ATTRS.items(): setattr(dummy_experiment, attribute, utils.bcast_local_devices(pretrained_state[key])) jaxline_state = dict( global_step=pretrained_state['global_step'], experiment_module=dummy_experiment) snapshot = utils.SnapshotNT(0, jaxline_state) # Finally, seed the jaxline `utils.InMemoryCheckpointer` global dict. utils.GLOBAL_CHECKPOINT_DICT['latest'] = utils.CheckpointNT( threading.local(), [snapshot]) def _get_step_date_label(global_step): # Date removing microseconds. date_str = datetime.datetime.now().isoformat().split('.')[0] return f'step_{global_step}_{date_str}' def _save_state_from_in_memory_checkpointer( save_path, experiment_class: experiment.AbstractExperiment): """Saves experiment state to a checkpoint.""" logging.info('Saving model.') for checkpoint_name, checkpoint in utils.GLOBAL_CHECKPOINT_DICT.items(): if not checkpoint.history: logging.info('Nothing to save in "%s"', checkpoint_name) continue pickle_nest = checkpoint.history[-1].pickle_nest global_step = pickle_nest['global_step'] state_dict = {'global_step': global_step} for attribute, key in experiment_class.CHECKPOINT_ATTRS.items(): state_dict[key] = utils.get_first( getattr(pickle_nest['experiment_module'], attribute)) save_dir = os.path.join( save_path, checkpoint_name, _get_step_date_label(global_step)) python_state_path = os.path.join(save_dir, 'checkpoint.dill') os.makedirs(save_dir, exist_ok=True) with open(python_state_path, 'wb') as f: dill.dump(state_dict, f) logging.info( 'Saved "%s" checkpoint to %s', checkpoint_name, python_state_path) def _setup_signals(save_model_fn): """Sets up a signal for model saving.""" # Save a model on Ctrl+C. def sigint_handler(unused_sig, unused_frame): # Ideally, rather than saving immediately, we would then "wait" for a good # time to save. In practice this reads from an in-memory checkpoint that # only saves every 30 seconds or so, so chances of race conditions are very # small. save_model_fn() logging.info(r'Use `Ctrl+\` to save and exit.') # Exit on `Ctrl+\`, saving a model. prev_sigquit_handler = signal.getsignal(signal.SIGQUIT) def sigquit_handler(unused_sig, unused_frame): # Restore previous handler early, just in case something goes wrong in the # next lines, so it is possible to press again and exit. signal.signal(signal.SIGQUIT, prev_sigquit_handler) save_model_fn() logging.info(r'Exiting on `Ctrl+\`') # Re-raise for clean exit. os.kill(os.getpid(), signal.SIGQUIT) signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGQUIT, sigquit_handler) def main(argv, experiment_class: experiment.AbstractExperiment): # Maybe restore a model. restore_path = FLAGS.config.restore_path if restore_path: _restore_state_to_in_memory_checkpointer(restore_path) # Maybe save a model. save_dir = os.path.join(FLAGS.config.checkpoint_dir, 'models') if FLAGS.config.one_off_evaluate: save_model_fn = lambda: None # No need to save checkpoint in this case. else: save_model_fn = functools.partial( _save_state_from_in_memory_checkpointer, save_dir, experiment_class) _setup_signals(save_model_fn) # Save on Ctrl+C (continue) or Ctrl+\ (exit). try: platform.main(experiment_class, argv) finally: save_model_fn() # Save at the end of training or in case of exception. if __name__ == '__main__': jax_config.update('jax_debug_nans', False) flags.mark_flag_as_required('config') app.run(lambda argv: main(argv, Experiment))
deepmind-research-master
ogb_lsc/mag/experiment.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset utilities.""" import functools import pathlib from typing import Dict, Tuple from absl import logging from graph_nets import graphs as tf_graphs from graph_nets import utils_tf import numpy as np import scipy.sparse as sp import tensorflow as tf import tqdm # pylint: disable=g-bad-import-order import sub_sampler Path = pathlib.Path NUM_PAPERS = 121751666 NUM_AUTHORS = 122383112 NUM_INSTITUTIONS = 25721 EMBEDDING_SIZE = 768 NUM_CLASSES = 153 NUM_NODES = NUM_PAPERS + NUM_AUTHORS + NUM_INSTITUTIONS NUM_EDGES = 1_728_364_232 assert NUM_NODES == 244_160_499 NUM_K_FOLD_SPLITS = 10 OFFSETS = { "paper": 0, "author": NUM_PAPERS, "institution": NUM_PAPERS + NUM_AUTHORS, } SIZES = { "paper": NUM_PAPERS, "author": NUM_AUTHORS, "institution": NUM_INSTITUTIONS } RAW_DIR = Path("raw") PREPROCESSED_DIR = Path("preprocessed") RAW_NODE_FEATURES_FILENAME = RAW_DIR / "node_feat.npy" RAW_NODE_LABELS_FILENAME = RAW_DIR / "node_label.npy" RAW_NODE_YEAR_FILENAME = RAW_DIR / "node_year.npy" TRAIN_INDEX_FILENAME = RAW_DIR / "train_idx.npy" VALID_INDEX_FILENAME = RAW_DIR / "train_idx.npy" TEST_INDEX_FILENAME = RAW_DIR / "train_idx.npy" EDGES_PAPER_PAPER_B = PREPROCESSED_DIR / "paper_paper_b.npz" EDGES_PAPER_PAPER_B_T = PREPROCESSED_DIR / "paper_paper_b_t.npz" EDGES_AUTHOR_INSTITUTION = PREPROCESSED_DIR / "author_institution.npz" EDGES_INSTITUTION_AUTHOR = PREPROCESSED_DIR / "institution_author.npz" EDGES_AUTHOR_PAPER = PREPROCESSED_DIR / "author_paper.npz" EDGES_PAPER_AUTHOR = PREPROCESSED_DIR / "paper_author.npz" PCA_PAPER_FEATURES_FILENAME = PREPROCESSED_DIR / "paper_feat_pca_129.npy" PCA_AUTHOR_FEATURES_FILENAME = ( PREPROCESSED_DIR / "author_feat_from_paper_feat_pca_129.npy") PCA_INSTITUTION_FEATURES_FILENAME = ( PREPROCESSED_DIR / "institution_feat_from_paper_feat_pca_129.npy") PCA_MERGED_FEATURES_FILENAME = ( PREPROCESSED_DIR / "merged_feat_from_paper_feat_pca_129.npy") NEIGHBOR_INDICES_FILENAME = PREPROCESSED_DIR / "neighbor_indices.npy" NEIGHBOR_DISTANCES_FILENAME = PREPROCESSED_DIR / "neighbor_distances.npy" FUSED_NODE_LABELS_FILENAME = PREPROCESSED_DIR / "fused_node_labels.npy" FUSED_PAPER_EDGES_FILENAME = PREPROCESSED_DIR / "fused_paper_edges.npz" FUSED_PAPER_EDGES_T_FILENAME = PREPROCESSED_DIR / "fused_paper_edges_t.npz" K_FOLD_SPLITS_DIR = Path("k_fold_splits") def get_raw_directory(data_root): return Path(data_root) / "raw" def get_preprocessed_directory(data_root): return Path(data_root) / "preprocessed" def _log_path_decorator(fn): def _decorated_fn(path, **kwargs): logging.info("Loading %s", path) output = fn(path, **kwargs) logging.info("Finish loading %s", path) return output return _decorated_fn @_log_path_decorator def load_csr(path, debug=False): if debug: # Dummy matrix for debugging. return sp.csr_matrix(np.zeros([10, 10])) return sp.load_npz(str(path)) @_log_path_decorator def load_npy(path): return np.load(str(path)) @functools.lru_cache() def get_arrays(data_root="/data/", use_fused_node_labels=True, use_fused_node_adjacencies=True, return_pca_embeddings=True, k_fold_split_id=None, return_adjacencies=True, use_dummy_adjacencies=False): """Returns all arrays needed for training.""" logging.info("Starting to get files") data_root = Path(data_root) array_dict = {} array_dict["paper_year"] = load_npy(data_root / RAW_NODE_YEAR_FILENAME) if k_fold_split_id is None: train_indices = load_npy(data_root / TRAIN_INDEX_FILENAME) valid_indices = load_npy(data_root / VALID_INDEX_FILENAME) else: train_indices, valid_indices = get_train_and_valid_idx_for_split( k_fold_split_id, num_splits=NUM_K_FOLD_SPLITS, root_path=data_root / K_FOLD_SPLITS_DIR) array_dict["train_indices"] = train_indices array_dict["valid_indices"] = valid_indices array_dict["test_indices"] = load_npy(data_root / TEST_INDEX_FILENAME) if use_fused_node_labels: array_dict["paper_label"] = load_npy(data_root / FUSED_NODE_LABELS_FILENAME) else: array_dict["paper_label"] = load_npy(data_root / RAW_NODE_LABELS_FILENAME) if return_adjacencies: logging.info("Starting to get adjacencies.") if use_fused_node_adjacencies: paper_paper_index = load_csr( data_root / FUSED_PAPER_EDGES_FILENAME, debug=use_dummy_adjacencies) paper_paper_index_t = load_csr( data_root / FUSED_PAPER_EDGES_T_FILENAME, debug=use_dummy_adjacencies) else: paper_paper_index = load_csr( data_root / EDGES_PAPER_PAPER_B, debug=use_dummy_adjacencies) paper_paper_index_t = load_csr( data_root / EDGES_PAPER_PAPER_B_T, debug=use_dummy_adjacencies) array_dict.update( dict( author_institution_index=load_csr( data_root / EDGES_AUTHOR_INSTITUTION, debug=use_dummy_adjacencies), institution_author_index=load_csr( data_root / EDGES_INSTITUTION_AUTHOR, debug=use_dummy_adjacencies), author_paper_index=load_csr( data_root / EDGES_AUTHOR_PAPER, debug=use_dummy_adjacencies), paper_author_index=load_csr( data_root / EDGES_PAPER_AUTHOR, debug=use_dummy_adjacencies), paper_paper_index=paper_paper_index, paper_paper_index_t=paper_paper_index_t, )) if return_pca_embeddings: array_dict["bert_pca_129"] = np.load( data_root / PCA_MERGED_FEATURES_FILENAME, mmap_mode="r") assert array_dict["bert_pca_129"].shape == (NUM_NODES, 129) logging.info("Finish getting files") # pytype: disable=attribute-error assert array_dict["paper_year"].shape[0] == NUM_PAPERS assert array_dict["paper_label"].shape[0] == NUM_PAPERS if return_adjacencies and not use_dummy_adjacencies: array_dict = _fix_adjacency_shapes(array_dict) assert array_dict["paper_author_index"].shape == (NUM_PAPERS, NUM_AUTHORS) assert array_dict["author_paper_index"].shape == (NUM_AUTHORS, NUM_PAPERS) assert array_dict["paper_paper_index"].shape == (NUM_PAPERS, NUM_PAPERS) assert array_dict["paper_paper_index_t"].shape == (NUM_PAPERS, NUM_PAPERS) assert array_dict["institution_author_index"].shape == ( NUM_INSTITUTIONS, NUM_AUTHORS) assert array_dict["author_institution_index"].shape == ( NUM_AUTHORS, NUM_INSTITUTIONS) # pytype: enable=attribute-error return array_dict def add_nodes_year(graph, paper_year): nodes = graph.nodes.copy() indices = nodes["index"] year = paper_year[np.minimum(indices, paper_year.shape[0] - 1)].copy() year[nodes["type"] != 0] = 1900 nodes["year"] = year return graph._replace(nodes=nodes) def add_nodes_label(graph, paper_label): nodes = graph.nodes.copy() indices = nodes["index"] label = paper_label[np.minimum(indices, paper_label.shape[0] - 1)] label[nodes["type"] != 0] = 0 nodes["label"] = label return graph._replace(nodes=nodes) def add_nodes_embedding_from_array(graph, array): """Adds embeddings from the sstable_service for the indices.""" nodes = graph.nodes.copy() indices = nodes["index"] embedding_indices = indices.copy() embedding_indices[nodes["type"] == 1] += NUM_PAPERS embedding_indices[nodes["type"] == 2] += NUM_PAPERS + NUM_AUTHORS # Gather the embeddings for the indices. nodes["features"] = array[embedding_indices] return graph._replace(nodes=nodes) def get_graph_subsampling_dataset( prefix, arrays, shuffle_indices, ratio_unlabeled_data_to_labeled_data, max_nodes, max_edges, **subsampler_kwargs): """Returns tf_dataset for online sampling.""" def generator(): labeled_indices = arrays[f"{prefix}_indices"] if ratio_unlabeled_data_to_labeled_data > 0: num_unlabeled_data_to_add = int(ratio_unlabeled_data_to_labeled_data * labeled_indices.shape[0]) unlabeled_indices = np.random.choice( NUM_PAPERS, size=num_unlabeled_data_to_add, replace=False) root_node_indices = np.concatenate([labeled_indices, unlabeled_indices]) else: root_node_indices = labeled_indices if shuffle_indices: root_node_indices = root_node_indices.copy() np.random.shuffle(root_node_indices) for index in root_node_indices: graph = sub_sampler.subsample_graph( index, arrays["author_institution_index"], arrays["institution_author_index"], arrays["author_paper_index"], arrays["paper_author_index"], arrays["paper_paper_index"], arrays["paper_paper_index_t"], paper_years=arrays["paper_year"], max_nodes=max_nodes, max_edges=max_edges, **subsampler_kwargs) graph = add_nodes_label(graph, arrays["paper_label"]) graph = add_nodes_year(graph, arrays["paper_year"]) graph = tf_graphs.GraphsTuple(*graph) yield graph sample_graph = next(generator()) return tf.data.Dataset.from_generator( generator, output_signature=utils_tf.specs_from_graphs_tuple(sample_graph)) def paper_features_to_author_features( author_paper_index, paper_features): """Averages paper features to authors.""" assert paper_features.shape[0] == NUM_PAPERS assert author_paper_index.shape[0] == NUM_AUTHORS author_features = np.zeros( [NUM_AUTHORS, paper_features.shape[1]], dtype=paper_features.dtype) for author_i in range(NUM_AUTHORS): paper_indices = author_paper_index[author_i].indices author_features[author_i] = paper_features[paper_indices].mean( axis=0, dtype=np.float32) if author_i % 10000 == 0: logging.info("%d/%d", author_i, NUM_AUTHORS) return author_features def author_features_to_institution_features( institution_author_index, author_features): """Averages author features to institutions.""" assert author_features.shape[0] == NUM_AUTHORS assert institution_author_index.shape[0] == NUM_INSTITUTIONS institution_features = np.zeros( [NUM_INSTITUTIONS, author_features.shape[1]], dtype=author_features.dtype) for institution_i in range(NUM_INSTITUTIONS): author_indices = institution_author_index[institution_i].indices institution_features[institution_i] = author_features[ author_indices].mean(axis=0, dtype=np.float32) if institution_i % 10000 == 0: logging.info("%d/%d", institution_i, NUM_INSTITUTIONS) return institution_features def generate_fused_paper_adjacency_matrix(neighbor_indices, neighbor_distances, paper_paper_csr): """Generates fused adjacency matrix for identical nodes.""" # First construct set of identical node indices. # NOTE: Since we take only top K=26 identical pairs for each node, this is not # actually exhaustive. Also, if A and B are equal, and B and C are equal, # this method would not necessarily detect A and C being equal. # However, this should capture almost all cases. logging.info("Generating fused paper adjacency matrix") eps = 0.0 mask = ((neighbor_indices != np.mgrid[:neighbor_indices.shape[0], :1]) & (neighbor_distances <= eps)) identical_pairs = list(map(tuple, np.nonzero(mask))) del mask # Have a csc version for fast column access. paper_paper_csc = paper_paper_csr.tocsc() # Construct new matrix as coo, starting off with original rows/cols. paper_paper_coo = paper_paper_csr.tocoo() new_rows = [paper_paper_coo.row] new_cols = [paper_paper_coo.col] for pair in tqdm.tqdm(identical_pairs): # STEP ONE: First merge papers being cited by the pair. # Add edges from second paper, to all papers cited by first paper. cited_by_first = paper_paper_csr.getrow(pair[0]).nonzero()[1] if cited_by_first.shape[0] > 0: new_rows.append(pair[1] * np.ones_like(cited_by_first)) new_cols.append(cited_by_first) # Add edges from first paper, to all papers cited by second paper. cited_by_second = paper_paper_csr.getrow(pair[1]).nonzero()[1] if cited_by_second.shape[0] > 0: new_rows.append(pair[0] * np.ones_like(cited_by_second)) new_cols.append(cited_by_second) # STEP TWO: Then merge papers that cite the pair. # Add edges to second paper, from all papers citing the first paper. citing_first = paper_paper_csc.getcol(pair[0]).nonzero()[0] if citing_first.shape[0] > 0: new_rows.append(citing_first) new_cols.append(pair[1] * np.ones_like(citing_first)) # Add edges to first paper, from all papers citing the second paper. citing_second = paper_paper_csc.getcol(pair[1]).nonzero()[0] if citing_second.shape[0] > 0: new_rows.append(citing_second) new_cols.append(pair[0] * np.ones_like(citing_second)) logging.info("Done with adjacency loop") paper_paper_coo_shape = paper_paper_coo.shape del paper_paper_csr del paper_paper_csc del paper_paper_coo # All done; now concatenate everything together and form new matrix. new_rows = np.concatenate(new_rows) new_cols = np.concatenate(new_cols) return sp.coo_matrix( (np.ones_like(new_rows, dtype=np.bool), (new_rows, new_cols)), shape=paper_paper_coo_shape).tocsr() def generate_k_fold_splits( train_idx, valid_idx, output_path, num_splits=NUM_K_FOLD_SPLITS): """Generates splits adding fractions of the validation split to training.""" output_path = Path(output_path) np.random.seed(42) valid_idx = np.random.permutation(valid_idx) # Split into `num_parts` (almost) identically sized arrays. valid_idx_parts = np.array_split(valid_idx, num_splits) for i in range(num_splits): # Add all but the i'th subpart to training set. new_train_idx = np.concatenate( [train_idx, *valid_idx_parts[:i], *valid_idx_parts[i+1:]]) # i'th subpart is validation set. new_valid_idx = valid_idx_parts[i] train_path = output_path / f"train_idx_{i}_{num_splits}.npy" valid_path = output_path / f"valid_idx_{i}_{num_splits}.npy" np.save(train_path, new_train_idx) np.save(valid_path, new_valid_idx) logging.info("Saved: %s", train_path) logging.info("Saved: %s", valid_path) def get_train_and_valid_idx_for_split( split_id: int, num_splits: int, root_path: str, ) -> Tuple[np.ndarray, np.ndarray]: """Returns train and valid indices for given split.""" new_train_idx = load_npy(f"{root_path}/train_idx_{split_id}_{num_splits}.npy") new_valid_idx = load_npy(f"{root_path}/valid_idx_{split_id}_{num_splits}.npy") return new_train_idx, new_valid_idx def generate_fused_node_labels(neighbor_indices, neighbor_distances, node_labels, train_indices, valid_indices, test_indices): """Generates fused adjacency matrix for identical nodes.""" logging.info("Generating fused node labels") valid_indices = set(valid_indices.tolist()) test_indices = set(test_indices.tolist()) valid_or_test_indices = valid_indices | test_indices train_indices = train_indices[train_indices < neighbor_indices.shape[0]] # Go through list of all pairs where one node is in training set, and for i in tqdm.tqdm(train_indices): for j in range(neighbor_indices.shape[1]): other_index = neighbor_indices[i][j] # if the other is not a validation or test node, if other_index in valid_or_test_indices: continue # and they are identical, if neighbor_distances[i][j] == 0: # assign the label of the training node to the other node node_labels[other_index] = node_labels[i] return node_labels def _pad_to_shape( sparse_csr_matrix: sp.csr_matrix, output_shape: Tuple[int, int]) -> sp.csr_matrix: """Pads a csr sparse matrix to the given shape.""" # We should not try to expand anything smaller. assert np.all(sparse_csr_matrix.shape <= output_shape) # Maybe it already has the right shape. if sparse_csr_matrix.shape == output_shape: return sparse_csr_matrix # Append as many indptr elements as we need to match the leading size, # This is achieved by just padding with copies of the last indptr element. required_padding = output_shape[0] - sparse_csr_matrix.shape[0] updated_indptr = np.concatenate( [sparse_csr_matrix.indptr] + [sparse_csr_matrix.indptr[-1:]] * required_padding, axis=0) # The change in trailing size does not have structural implications, it just # determines the highest possible value for the indices, so it is sufficient # to just pass the new output shape, with the correct trailing size. return sp.csr.csr_matrix( (sparse_csr_matrix.data, sparse_csr_matrix.indices, updated_indptr), shape=output_shape) def _fix_adjacency_shapes( arrays: Dict[str, sp.csr.csr_matrix], ) -> Dict[str, sp.csr.csr_matrix]: """Fixes the shapes of the adjacency matrices.""" arrays = arrays.copy() for key in ["author_institution_index", "author_paper_index", "paper_paper_index", "institution_author_index", "paper_author_index", "paper_paper_index_t"]: type_sender = key.split("_")[0] type_receiver = key.split("_")[1] arrays[key] = _pad_to_shape( arrays[key], output_shape=(SIZES[type_sender], SIZES[type_receiver])) return arrays
deepmind-research-master
ogb_lsc/mag/data_utils.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Losses and related utilities.""" from typing import Mapping, Tuple, Sequence, NamedTuple, Dict, Optional import jax import jax.numpy as jnp import jraph import numpy as np # pylint: disable=g-bad-import-order import datasets LogsDict = Mapping[str, jnp.ndarray] class Predictions(NamedTuple): node_indices: np.ndarray labels: np.ndarray predictions: np.ndarray logits: np.ndarray def node_classification_loss( logits: jnp.ndarray, batch: datasets.Batch, extra_stats: bool = False, ) -> Tuple[jnp.ndarray, LogsDict]: """Gets node-wise classification loss and statistics.""" log_probs = jax.nn.log_softmax(logits) loss = -jnp.sum(log_probs * batch.node_labels, axis=-1) num_valid = jnp.sum(batch.label_mask) labels = jnp.argmax(batch.node_labels, axis=-1) is_correct = (jnp.argmax(log_probs, axis=-1) == labels) num_correct = jnp.sum(is_correct * batch.label_mask) loss = jnp.sum(loss * batch.label_mask) / (num_valid + 1e-8) accuracy = num_correct / (num_valid + 1e-8) entropy = -jnp.mean(jnp.sum(jax.nn.softmax(logits) * log_probs, axis=-1)) stats = { 'classification_loss': loss, 'prediction_entropy': entropy, 'accuracy': accuracy, 'num_valid': num_valid, 'num_correct': num_correct, } if extra_stats: for k in range(1, 6): stats[f'top_{k}_correct'] = topk_correct(logits, labels, batch.label_mask, k) return loss, stats def get_predictions_labels_and_logits( logits: jnp.ndarray, batch: datasets.Batch, ) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray, jnp.ndarray]: """Gets prediction labels and logits.""" mask = batch.label_mask > 0. indices = batch.node_indices[mask] logits = logits[mask] predictions = jnp.argmax(logits, axis=-1) labels = jnp.argmax(batch.node_labels[mask], axis=-1) return indices, predictions, labels, logits def topk_correct( logits: jnp.ndarray, labels: jnp.ndarray, valid_mask: jnp.ndarray, topk: int, ) -> jnp.ndarray: """Calculates top-k accuracy.""" pred_ranking = jnp.argsort(logits, axis=1)[:, ::-1] pred_ranking = pred_ranking[:, :topk] is_correct = jnp.any(pred_ranking == labels[:, jnp.newaxis], axis=1) return (is_correct * valid_mask).sum() def ensemble_predictions_by_probability_average( predictions_list: Sequence[Predictions]) -> Predictions: """Ensemble predictions by ensembling the probabilities.""" _assert_consistent_predictions(predictions_list) all_probs = np.stack([ jax.nn.softmax(predictions.logits, axis=-1) for predictions in predictions_list ], axis=0) ensembled_logits = np.log(all_probs.mean(0)) return predictions_list[0]._replace( logits=ensembled_logits, predictions=np.argmax(ensembled_logits, axis=-1)) def get_accuracy_dict(predictions: Predictions) -> Dict[str, float]: """Returns the accuracy dict.""" output_dict = {} output_dict['num_valid'] = predictions.predictions.shape[0] matches = (predictions.labels == predictions.predictions) output_dict['accuracy'] = matches.mean() pred_ranking = jnp.argsort(predictions.logits, axis=1)[:, ::-1] for k in range(1, 6): matches = jnp.any( pred_ranking[:, :k] == predictions.labels[:, None], axis=1) output_dict[f'top_{k}_correct'] = matches.mean() return output_dict def bgrl_loss( first_online_predictions: jnp.ndarray, second_target_projections: jnp.ndarray, second_online_predictions: jnp.ndarray, first_target_projections: jnp.ndarray, symmetrize: bool, valid_mask: jnp.ndarray, ) -> Tuple[jnp.ndarray, LogsDict]: """Implements BGRL loss.""" first_side_node_loss = jnp.sum( jnp.square( _l2_normalize(first_online_predictions, axis=-1) - _l2_normalize(second_target_projections, axis=-1)), axis=-1) if symmetrize: second_side_node_loss = jnp.sum( jnp.square( _l2_normalize(second_online_predictions, axis=-1) - _l2_normalize(first_target_projections, axis=-1)), axis=-1) node_loss = first_side_node_loss + second_side_node_loss else: node_loss = first_side_node_loss loss = (node_loss * valid_mask).sum() / (valid_mask.sum() + 1e-6) return loss, dict(bgrl_loss=loss) def get_corrupted_view( graph: jraph.GraphsTuple, feature_drop_prob: float, edge_drop_prob: float, rng_key: jnp.ndarray, ) -> jraph.GraphsTuple: """Returns corrupted graph view.""" node_key, edge_key = jax.random.split(rng_key) def mask_feature(x): mask = jax.random.bernoulli(node_key, 1 - feature_drop_prob, x.shape) return x * mask # Randomly mask features with fixed probability. nodes = jax.tree_map(mask_feature, graph.nodes) # Simulate dropping of edges by changing genuine edges to self-loops on # the padded node. num_edges = graph.senders.shape[0] last_node_idx = graph.n_node.sum() - 1 edge_mask = jax.random.bernoulli(edge_key, 1 - edge_drop_prob, [num_edges]) senders = jnp.where(edge_mask, graph.senders, last_node_idx) receivers = jnp.where(edge_mask, graph.receivers, last_node_idx) # Note that n_edge will now be invalid since edges in the middle of the list # will correspond to the final graph. Set n_edge to None to ensure we do not # accidentally use this. return graph._replace( nodes=nodes, senders=senders, receivers=receivers, n_edge=None, ) def _assert_consistent_predictions(predictions_list: Sequence[Predictions]): first_predictions = predictions_list[0] for predictions in predictions_list: assert np.all(predictions.node_indices == first_predictions.node_indices) assert np.all(predictions.labels == first_predictions.labels) assert np.all( predictions.predictions == np.argmax(predictions.logits, axis=-1)) def _l2_normalize( x: jnp.ndarray, axis: Optional[int] = None, epsilon: float = 1e-6, ) -> jnp.ndarray: return x * jax.lax.rsqrt( jnp.sum(jnp.square(x), axis=axis, keepdims=True) + epsilon)
deepmind-research-master
ogb_lsc/mag/losses.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find neighborhoods around paper feature embeddings.""" import pathlib from absl import app from absl import flags from absl import logging import annoy import numpy as np import scipy.sparse as sp # pylint: disable=g-bad-import-order import data_utils Path = pathlib.Path _PAPER_PAPER_B_PATH = 'ogb_mag_adjacencies/paper_paper_b.npz' FLAGS = flags.FLAGS flags.DEFINE_string('data_root', None, 'Data root directory') def _read_paper_pca_features(): data_root = Path(FLAGS.data_root) path = data_root / data_utils.PCA_PAPER_FEATURES_FILENAME with open(path, 'rb') as fid: return np.load(fid) def _read_adjacency_indices(): # Get adjacencies. return data_utils.get_arrays( data_root=FLAGS.data_root, use_fused_node_labels=False, use_fused_node_adjacencies=False, return_pca_embeddings=False, ) def build_annoy_index(features): """Build the Annoy index.""" logging.info('Building annoy index') num_vectors, vector_size = features.shape annoy_index = annoy.AnnoyIndex(vector_size, 'euclidean') for i, x in enumerate(features): annoy_index.add_item(i, x) if i % 1000000 == 0: logging.info('Adding: %d / %d (%.3g %%)', i, num_vectors, 100 * i / num_vectors) n_trees = 10 _ = annoy_index.build(n_trees) return annoy_index def _get_annoy_index_path(): return Path(FLAGS.data_root) / data_utils.PREPROCESSED_DIR / 'annoy_index.ann' def save_annoy_index(annoy_index): logging.info('Saving annoy index') index_path = _get_annoy_index_path() index_path.parent.mkdir(parents=True, exist_ok=True) annoy_index.save(str(index_path)) def read_annoy_index(features): index_path = _get_annoy_index_path() vector_size = features.shape[1] annoy_index = annoy.AnnoyIndex(vector_size, 'euclidean') annoy_index.load(str(index_path)) return annoy_index def compute_neighbor_indices_and_distances(features): """Use the pre-built Annoy index to compute neighbor indices and distances.""" logging.info('Computing neighbors and distances') annoy_index = read_annoy_index(features) num_vectors = features.shape[0] k = 20 pad_k = 5 search_k = -1 neighbor_indices = np.zeros([num_vectors, k + pad_k + 1], dtype=np.int32) neighbor_distances = np.zeros([num_vectors, k + pad_k + 1], dtype=np.float32) for i in range(num_vectors): neighbor_indices[i], neighbor_distances[i] = annoy_index.get_nns_by_item( i, k + pad_k + 1, search_k=search_k, include_distances=True) if i % 10000 == 0: logging.info('Finding neighbors %d / %d', i, num_vectors) return neighbor_indices, neighbor_distances def _write_neighbors(neighbor_indices, neighbor_distances): """Write neighbor indices and distances.""" logging.info('Writing neighbors') indices_path = Path(FLAGS.data_root) / data_utils.NEIGHBOR_INDICES_FILENAME distances_path = ( Path(FLAGS.data_root) / data_utils.NEIGHBOR_DISTANCES_FILENAME) indices_path.parent.mkdir(parents=True, exist_ok=True) distances_path.parent.mkdir(parents=True, exist_ok=True) with open(indices_path, 'wb') as fid: np.save(fid, neighbor_indices) with open(distances_path, 'wb') as fid: np.save(fid, neighbor_distances) def _write_fused_edges(fused_paper_adjacency_matrix): """Write fused edges.""" data_root = Path(FLAGS.data_root) edges_path = data_root / data_utils.FUSED_PAPER_EDGES_FILENAME edges_t_path = data_root / data_utils.FUSED_PAPER_EDGES_T_FILENAME edges_path.parent.mkdir(parents=True, exist_ok=True) edges_t_path.parent.mkdir(parents=True, exist_ok=True) with open(edges_path, 'wb') as fid: sp.save_npz(fid, fused_paper_adjacency_matrix) with open(edges_t_path, 'wb') as fid: sp.save_npz(fid, fused_paper_adjacency_matrix.T) def _write_fused_nodes(fused_node_labels): """Write fused nodes.""" labels_path = Path(FLAGS.data_root) / data_utils.FUSED_NODE_LABELS_FILENAME labels_path.parent.mkdir(parents=True, exist_ok=True) with open(labels_path, 'wb') as fid: np.save(fid, fused_node_labels) def main(unused_argv): paper_pca_features = _read_paper_pca_features() # Find neighbors. annoy_index = build_annoy_index(paper_pca_features) save_annoy_index(annoy_index) neighbor_indices, neighbor_distances = compute_neighbor_indices_and_distances( paper_pca_features) del paper_pca_features _write_neighbors(neighbor_indices, neighbor_distances) data = _read_adjacency_indices() paper_paper_csr = data['paper_paper_index'] paper_label = data['paper_label'] train_indices = data['train_indices'] valid_indices = data['valid_indices'] test_indices = data['test_indices'] del data fused_paper_adjacency_matrix = data_utils.generate_fused_paper_adjacency_matrix( neighbor_indices, neighbor_distances, paper_paper_csr) _write_fused_edges(fused_paper_adjacency_matrix) del fused_paper_adjacency_matrix del paper_paper_csr fused_node_labels = data_utils.generate_fused_node_labels( neighbor_indices, neighbor_distances, paper_label, train_indices, valid_indices, test_indices) _write_fused_nodes(fused_node_labels) if __name__ == '__main__': flags.mark_flag_as_required('data_root') app.run(main)
deepmind-research-master
ogb_lsc/mag/neighbor_builder.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dynamic batching utilities.""" from typing import Generator, Iterable, Iterator, Sequence, Tuple import jax.tree_util as tree import jraph import numpy as np _NUMBER_FIELDS = ("n_node", "n_edge", "n_graph") def dynamically_batch(graphs_tuple_iterator: Iterator[jraph.GraphsTuple], n_node: int, n_edge: int, n_graph: int) -> Generator[jraph.GraphsTuple, None, None]: """Dynamically batches trees with `jraph.GraphsTuples` to `graph_batch_size`. Elements of the `graphs_tuple_iterator` will be incrementally added to a batch until the limits defined by `n_node`, `n_edge` and `n_graph` are reached. This means each element yielded by this generator For situations where you have variable sized data, it"s useful to be able to have variable sized batches. This is especially the case if you have a loss defined on the variable shaped element (for example, nodes in a graph). Args: graphs_tuple_iterator: An iterator of `jraph.GraphsTuples`. n_node: The maximum number of nodes in a batch. n_edge: The maximum number of edges in a batch. n_graph: The maximum number of graphs in a batch. Yields: A `jraph.GraphsTuple` batch of graphs. Raises: ValueError: if the number of graphs is < 2. RuntimeError: if the `graphs_tuple_iterator` contains elements which are not `jraph.GraphsTuple`s. RuntimeError: if a graph is found which is larger than the batch size. """ if n_graph < 2: raise ValueError("The number of graphs in a batch size must be greater or " f"equal to `2` for padding with graphs, got {n_graph}.") valid_batch_size = (n_node - 1, n_edge, n_graph - 1) accumulated_graphs = [] num_accumulated_nodes = 0 num_accumulated_edges = 0 num_accumulated_graphs = 0 for element in graphs_tuple_iterator: element_nodes, element_edges, element_graphs = _get_graph_size(element) if _is_over_batch_size(element, valid_batch_size): graph_size = element_nodes, element_edges, element_graphs graph_size = {k: v for k, v in zip(_NUMBER_FIELDS, graph_size)} batch_size = {k: v for k, v in zip(_NUMBER_FIELDS, valid_batch_size)} raise RuntimeError("Found graph bigger than batch size. Valid Batch " f"Size: {batch_size}, Graph Size: {graph_size}") if not accumulated_graphs: # If this is the first element of the batch, set it and continue. accumulated_graphs = [element] num_accumulated_nodes = element_nodes num_accumulated_edges = element_edges num_accumulated_graphs = element_graphs continue else: # Otherwise check if there is space for the graph in the batch: if ((num_accumulated_graphs + element_graphs > n_graph - 1) or (num_accumulated_nodes + element_nodes > n_node - 1) or (num_accumulated_edges + element_edges > n_edge)): # If there is, add it to the batch batched_graph = _batch_np(accumulated_graphs) yield jraph.pad_with_graphs(batched_graph, n_node, n_edge, n_graph) accumulated_graphs = [element] num_accumulated_nodes = element_nodes num_accumulated_edges = element_edges num_accumulated_graphs = element_graphs else: # Otherwise, return the old batch and start a new batch. accumulated_graphs.append(element) num_accumulated_nodes += element_nodes num_accumulated_edges += element_edges num_accumulated_graphs += element_graphs # We may still have data in batched graph. if accumulated_graphs: batched_graph = _batch_np(accumulated_graphs) yield jraph.pad_with_graphs(batched_graph, n_node, n_edge, n_graph) def _batch_np(graphs: Sequence[jraph.GraphsTuple]) -> jraph.GraphsTuple: # Calculates offsets for sender and receiver arrays, caused by concatenating # the nodes arrays. offsets = np.cumsum(np.array([0] + [np.sum(g.n_node) for g in graphs[:-1]])) def _map_concat(nests): concat = lambda *args: np.concatenate(args) return tree.tree_map(concat, *nests) return jraph.GraphsTuple( n_node=np.concatenate([g.n_node for g in graphs]), n_edge=np.concatenate([g.n_edge for g in graphs]), nodes=_map_concat([g.nodes for g in graphs]), edges=_map_concat([g.edges for g in graphs]), globals=_map_concat([g.globals for g in graphs]), senders=np.concatenate([g.senders + o for g, o in zip(graphs, offsets)]), receivers=np.concatenate( [g.receivers + o for g, o in zip(graphs, offsets)])) def _get_graph_size(graph: jraph.GraphsTuple) -> Tuple[int, int, int]: n_node = np.sum(graph.n_node) n_edge = len(graph.senders) n_graph = len(graph.n_node) return n_node, n_edge, n_graph def _is_over_batch_size( graph: jraph.GraphsTuple, graph_batch_size: Iterable[int], ) -> bool: graph_size = _get_graph_size(graph) return any([x > y for x, y in zip(graph_size, graph_batch_size)])
deepmind-research-master
ogb_lsc/mag/batching_utils.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Scheduling utilities.""" import jax.numpy as jnp def apply_ema_decay( ema_value: jnp.ndarray, current_value: jnp.ndarray, decay: jnp.ndarray, ) -> jnp.ndarray: """Implements EMA.""" return ema_value * decay + current_value * (1 - decay) def ema_decay_schedule( base_rate: jnp.ndarray, step: jnp.ndarray, total_steps: jnp.ndarray, use_schedule: bool, ) -> jnp.ndarray: """Anneals decay rate to 1 with cosine schedule.""" if not use_schedule: return base_rate multiplier = _cosine_decay(step, total_steps, 1.) return 1. - (1. - base_rate) * multiplier 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).astype(jnp.float32) 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 def learning_schedule( global_step: jnp.ndarray, base_learning_rate: float, total_steps: int, warmup_steps: int, use_schedule: bool, ) -> float: """Cosine learning rate scheduler.""" # Compute LR & Scaled LR if not use_schedule: return base_learning_rate warmup_learning_rate = ( global_step.astype(jnp.float32) / int(warmup_steps) * base_learning_rate if warmup_steps > 0 else base_learning_rate) # Cosine schedule after warmup. decay_learning_rate = _cosine_decay(global_step - warmup_steps, total_steps - warmup_steps, base_learning_rate) return jnp.where(global_step < warmup_steps, warmup_learning_rate, decay_learning_rate)
deepmind-research-master
ogb_lsc/mag/schedules.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Download data required for training and evaluating models.""" import pathlib from absl import app from absl import flags from absl import logging from google.cloud import storage # pylint: disable=g-bad-import-order import data_utils Path = pathlib.Path _BUCKET_NAME = 'deepmind-ogb-lsc' _MAX_DOWNLOAD_ATTEMPTS = 5 FLAGS = flags.FLAGS flags.DEFINE_enum('payload', None, ['data', 'models'], 'Download "data" or "models"?') flags.DEFINE_string('task_root', None, 'Local task root directory') DATA_RELATIVE_PATHS = ( data_utils.RAW_NODE_YEAR_FILENAME, data_utils.TRAIN_INDEX_FILENAME, data_utils.VALID_INDEX_FILENAME, data_utils.TEST_INDEX_FILENAME, data_utils.K_FOLD_SPLITS_DIR, data_utils.FUSED_NODE_LABELS_FILENAME, data_utils.FUSED_PAPER_EDGES_FILENAME, data_utils.FUSED_PAPER_EDGES_T_FILENAME, data_utils.EDGES_AUTHOR_INSTITUTION, data_utils.EDGES_INSTITUTION_AUTHOR, data_utils.EDGES_AUTHOR_PAPER, data_utils.EDGES_PAPER_AUTHOR, data_utils.PCA_MERGED_FEATURES_FILENAME, ) class DataCorruptionError(Exception): pass def _get_gcs_root(): return Path('mag') / FLAGS.payload def _get_gcs_bucket(): storage_client = storage.Client.create_anonymous_client() return storage_client.bucket(_BUCKET_NAME) def _write_blob_to_destination(blob, task_root, ignore_existing=True): """Write the blob.""" logging.info("Copying blob: '%s'", blob.name) destination_path = Path(task_root) / Path(*Path(blob.name).parts[1:]) logging.info(" ... to: '%s'", str(destination_path)) if ignore_existing and destination_path.exists(): return destination_path.parent.mkdir(parents=True, exist_ok=True) checksum = 'crc32c' for attempt in range(_MAX_DOWNLOAD_ATTEMPTS): try: blob.download_to_filename(destination_path.as_posix(), checksum=checksum) except storage.client.resumable_media.common.DataCorruption: pass else: break else: raise DataCorruptionError(f"Checksum ('{checksum}') for {blob.name} failed " f'after {attempt + 1} attempts') def main(unused_argv): bucket = _get_gcs_bucket() if FLAGS.payload == 'data': relative_paths = DATA_RELATIVE_PATHS else: relative_paths = (None,) for relative_path in relative_paths: if relative_path is None: relative_path = str(_get_gcs_root()) else: relative_path = str(_get_gcs_root() / relative_path) logging.info("Copying relative path: '%s'", relative_path) blobs = bucket.list_blobs(prefix=relative_path) for blob in blobs: _write_blob_to_destination(blob, FLAGS.task_root) if __name__ == '__main__': flags.mark_flag_as_required('payload') flags.mark_flag_as_required('task_root') app.run(main)
deepmind-research-master
ogb_lsc/mag/download_mag.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Script to generate ensembled PCQ test predictions.""" import collections import os import pathlib from typing import List, NamedTuple from absl import app from absl import flags from absl import logging import dill import numpy as np from ogb import lsc # pylint: disable=g-bad-import-order # pytype: disable=import-error import datasets _NUM_SEEDS = 2 _CLIP_VALUE = 20. _NUM_KFOLD_SPLITS = 10 _SEED_START = flags.DEFINE_integer( 'seed_start', 42, 'Initial seed for the list of ensemble models.') _CONFORMER_PATH = flags.DEFINE_string( 'conformer_path', None, 'Path to conformer predictions.', required=True) _NON_CONFORMER_PATH = flags.DEFINE_string( 'non_conformer_path', None, 'Path to non-conformer predictions.', required=True) _OUTPUT_PATH = flags.DEFINE_string('output_path', None, 'Output path.') _SPLIT = flags.DEFINE_enum('split', 'test', ['test', 'valid'], 'Split: valid or test.') class _Predictions(NamedTuple): predictions: np.ndarray indices: np.ndarray def _load_dill(fname) -> bytes: with open(fname, 'rb') as f: return dill.load(f) def _sort_by_indices(predictions: _Predictions) -> _Predictions: order = np.argsort(predictions.indices) return _Predictions( predictions=predictions.predictions[order], indices=predictions.indices[order]) def load_predictions(path: str, split: str) -> _Predictions: """Load written prediction file.""" if len(os.listdir(path)) != 1: raise ValueError('Prediction directory must have exactly ' 'one prediction sub-directory: %s' % path) prediction_subdir = os.listdir(path)[0] return _Predictions(*_load_dill(f'{path}/{prediction_subdir}/{split}.dill')) def mean_mae_distance(x, y): return np.abs(x - y).mean() def _load_valid_labels() -> np.ndarray: labels = [label for _, label in datasets.load_smile_strings(with_labels=True)] return np.array([labels[i] for i in datasets.load_splits()['valid']]) def evaluate_valid_predictions(ensembled_predictions: _Predictions): """Evaluates the predictions on the validation set.""" ensembled_predictions = _sort_by_indices(ensembled_predictions) evaluator = lsc.PCQM4MEvaluator() results = evaluator.eval( dict( y_pred=ensembled_predictions.predictions, y_true=_load_valid_labels())) logging.info('MAE on validation dataset: %f', results['mae']) def clip_predictions(predictions: _Predictions) -> _Predictions: return predictions._replace( predictions=np.clip(predictions.predictions, 0., _CLIP_VALUE)) def _generate_test_prediction_file(test_predictions: np.ndarray, output_path: pathlib.Path) -> pathlib.Path: """Generates the final file for submission.""" # Check that predictions are not nuts. assert test_predictions.dtype in [np.float64, np.float32] assert not np.any(np.isnan(test_predictions)) assert np.all(np.isfinite(test_predictions)) assert test_predictions.min() >= 0. assert test_predictions.max() <= 40. # Too risky to overwrite. if output_path.exists(): raise ValueError(f'{output_path} already exists') # Write to a local directory, and copy to final path (possibly cns). # It is not possible to write directlt on CNS. evaluator = lsc.PCQM4MEvaluator() evaluator.save_test_submission(dict(y_pred=test_predictions), output_path) return output_path def merge_complementary_results(split: str, results_a: _Predictions, results_b: _Predictions) -> _Predictions: """Merges two prediction results with no overlap.""" indices_a = set(results_a.indices) indices_b = set(results_b.indices) assert not indices_a.intersection(indices_b) if split == 'test': merged_indices = list(sorted(indices_a | indices_b)) expected_indices = datasets.load_splits()[split] assert np.all(expected_indices == merged_indices) predictions = np.concatenate([results_a.predictions, results_b.predictions]) indices = np.concatenate([results_a.indices, results_b.indices]) predictions = _sort_by_indices( _Predictions(indices=indices, predictions=predictions)) return predictions def ensemble_valid_predictions( predictions_list: List[_Predictions]) -> _Predictions: """Ensembles a list of predictions.""" index_to_predictions = collections.defaultdict(list) for predictions in predictions_list: for idx, pred in zip(predictions.indices, predictions.predictions): index_to_predictions[idx].append(pred) for idx, ensemble_list in index_to_predictions.items(): if len(ensemble_list) != _NUM_SEEDS: raise RuntimeError( 'Graph index in the validation set received wrong number of ' 'predictions to ensemble.') index_to_predictions = { k: np.median(pred_list, axis=0) for k, pred_list in index_to_predictions.items() } return _sort_by_indices( _Predictions( indices=np.array(list(index_to_predictions.keys())), predictions=np.array(list(index_to_predictions.values())))) def ensemble_test_predictions( predictions_list: List[_Predictions]) -> _Predictions: """Ensembles a list of predictions.""" predictions = np.median([pred.predictions for pred in predictions_list], axis=0) common_indices = predictions_list[0].indices for preds in predictions_list[1:]: assert np.all(preds.indices == common_indices) return _Predictions(predictions=predictions, indices=common_indices) def create_submission_from_predictions( output_path: pathlib.Path, test_predictions: _Predictions) -> pathlib.Path: """Creates a submission for predictions on a path.""" assert _SPLIT.value == 'test' output_path = _generate_test_prediction_file( test_predictions.predictions, output_path=output_path / 'submission_files') return output_path / 'y_pred_pcqm4m.npz' def merge_predictions(split: str) -> List[_Predictions]: """Generates features merged from conformer and non-conformer predictions.""" merged_predictions: List[_Predictions] = [] seed = _SEED_START.value # Load conformer and non-conformer predictions. for unused_seed_group in (0, 1): for k in range(_NUM_KFOLD_SPLITS): conformer_predictions: _Predictions = load_predictions( f'{_CONFORMER_PATH.value}/k{k}_seed{seed}', split) non_conformer_predictions: _Predictions = load_predictions( f'{_NON_CONFORMER_PATH.value}/k{k}_seed{seed}', split) merged_predictions.append( merge_complementary_results(_SPLIT.value, conformer_predictions, non_conformer_predictions)) seed += 1 return merged_predictions def main(_): split: str = _SPLIT.value # Merge conformer and non-conformer predictions. merged_predictions = merge_predictions(split) # Clip before ensembling. clipped_predictions = list(map(clip_predictions, merged_predictions)) # Ensemble predictions. if split == 'valid': ensembled_predictions = ensemble_valid_predictions(clipped_predictions) else: assert split == 'test' ensembled_predictions = ensemble_test_predictions(clipped_predictions) # Clip after ensembling. ensembled_predictions = clip_predictions(ensembled_predictions) ensembled_predictions_path = pathlib.Path(_OUTPUT_PATH.value) ensembled_predictions_path.mkdir(parents=True, exist_ok=True) with open(ensembled_predictions_path / f'{split}_predictions.dill', 'wb') as f: dill.dump(ensembled_predictions, f) if split == 'valid': evaluate_valid_predictions(ensembled_predictions) else: assert split == 'test' output_path = create_submission_from_predictions(ensembled_predictions_path, ensembled_predictions) logging.info('Submission files written to %s', output_path) if __name__ == '__main__': app.run(main)
deepmind-research-master
ogb_lsc/pcq/ensemble_predictions.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generates the k-fold validation splits.""" import os import pickle from absl import app from absl import flags from absl import logging import numpy as np # pylint: disable=g-bad-import-order import datasets _OUTPUT_DIR = flags.DEFINE_string( 'output_dir', None, required=True, help='Output directory to write the splits to') K = 10 def main(argv): del argv valid_indices = datasets.load_splits()['valid'] k_splits = np.split(valid_indices, K) os.makedirs(_OUTPUT_DIR.value, exist_ok=True) for k_i, split in enumerate(k_splits): fname = os.path.join(_OUTPUT_DIR.value, f'{k_i}.pkl') with open(fname, 'wb') as f: pickle.dump(split, f) logging.info('Saved: %s', fname) if __name__ == '__main__': app.run(main)
deepmind-research-master
ogb_lsc/pcq/generate_validation_splits.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Experiment config for PCQM4M-LSC entry.""" from jaxline import base_config from ml_collections import config_dict def get_config(debug: bool = False) -> config_dict.ConfigDict: """Get Jaxline experiment config.""" config = base_config.get_base_config() # E.g. '/data/pretrained_models/k0_seed100' (and set k_fold_split_id=0, below) config.restore_path = config_dict.placeholder(str) training_batch_size = 64 eval_batch_size = 64 ## Experiment config. loss_config_name = 'RegressionLossConfig' loss_kwargs = dict( exponent=1., # 2 for l2 loss, 1 for l1 loss, etc... ) dataset_config = dict( data_root=config_dict.placeholder(str), augment_with_random_mirror_symmetry=True, k_fold_split_id=config_dict.placeholder(int), num_k_fold_splits=config_dict.placeholder(int), # Options: "in" or "out". # Filter=in would keep the samples with nans in the conformer features. # Filter=out would keep the samples with no NaNs anywhere in the conformer # features. filter_in_or_out_samples_with_nans_in_conformers=( config_dict.placeholder(str)), cached_conformers_file=config_dict.placeholder(str)) model_config = dict( mlp_hidden_size=512, mlp_layers=2, latent_size=512, use_layer_norm=False, num_message_passing_steps=32, shared_message_passing_weights=False, mask_padding_graph_at_every_step=True, loss_config_name=loss_config_name, loss_kwargs=loss_kwargs, processor_mode='resnet', global_reducer='sum', node_reducer='sum', dropedge_rate=0.1, dropnode_rate=0.1, aux_multiplier=0.1, add_relative_distance=True, add_relative_displacement=True, add_absolute_positions=False, position_normalization=2., relative_displacement_normalization=1., ignore_globals=False, ignore_globals_from_final_layer_for_predictions=True, ) if debug: # Make network smaller. model_config.update(dict( mlp_hidden_size=32, mlp_layers=1, latent_size=32, num_message_passing_steps=1)) config.experiment_kwargs = config_dict.ConfigDict( dict( config=dict( debug=debug, predictions_dir=config_dict.placeholder(str), ema=True, ema_decay=0.9999, sample_random=0.05, optimizer=dict( name='adam', optimizer_kwargs=dict(b1=.9, b2=.95), lr_schedule=dict( warmup_steps=int(5e4), decay_steps=int(5e5), init_value=1e-5, peak_value=1e-4, end_value=0., ), ), model=model_config, dataset_config=dataset_config, # As a rule of thumb, use the following statistics: # Avg. # nodes in graph: 16. # Avg. # edges in graph: 40. training=dict( dynamic_batch_size={ 'n_node': 256 if debug else 16 * training_batch_size, 'n_edge': 512 if debug else 40 * training_batch_size, 'n_graph': 2 if debug else training_batch_size, },), evaluation=dict( split='valid', dynamic_batch_size=dict( n_node=256 if debug else 16 * eval_batch_size, n_edge=512 if debug else 40 * eval_batch_size, n_graph=2 if debug else eval_batch_size, ))))) ## Training loop config. config.training_steps = int(5e6) config.checkpoint_dir = '/tmp/checkpoint/pcq/' config.train_checkpoint_all_hosts = False config.save_checkpoint_interval = 300 config.log_train_data_interval = 60 config.log_tensors_interval = 60 config.best_model_eval_metric = 'mae' config.best_model_eval_metric_higher_is_better = False return config
deepmind-research-master
ogb_lsc/pcq/config.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Download data required for training and evaluating models.""" import pathlib from absl import app from absl import flags from absl import logging from google.cloud import storage Path = pathlib.Path _BUCKET_NAME = 'deepmind-ogb-lsc' _MAX_DOWNLOAD_ATTEMPTS = 5 FLAGS = flags.FLAGS flags.DEFINE_enum('payload', None, ['data', 'models'], 'Download "data" or "models"?') flags.DEFINE_string('task_root', None, 'Local task root directory') # GCS_DATA_ROOT = Path('pcq/data') # GCS_MODEL_ROOT = Path('pcq/models') DATA_RELATIVE_PATHS = [ 'raw/data.csv.gz', 'preprocessed/smile_to_conformer.pkl', 'k_fold_splits' ] class DataCorruptionError(Exception): pass def _get_gcs_root(): return Path('pcq') / FLAGS.payload def _get_gcs_bucket(): storage_client = storage.Client.create_anonymous_client() return storage_client.bucket(_BUCKET_NAME) def _write_blob_to_destination(blob, task_root, ignore_existing=True): """Write the blob.""" logging.info("Copying blob: '%s'", blob.name) destination_path = Path(task_root) / Path(*Path(blob.name).parts[1:]) logging.info(" ... to: '%s'", str(destination_path)) if ignore_existing and destination_path.exists(): return destination_path.parent.mkdir(parents=True, exist_ok=True) checksum = 'crc32c' for attempt in range(_MAX_DOWNLOAD_ATTEMPTS): try: blob.download_to_filename(destination_path.as_posix(), checksum=checksum) except storage.client.resumable_media.common.DataCorruption: pass else: break else: raise DataCorruptionError(f"Checksum ('{checksum}') for {blob.name} failed " f'after {attempt + 1} attempts') def main(unused_argv): bucket = _get_gcs_bucket() if FLAGS.payload == 'data': relative_paths = DATA_RELATIVE_PATHS else: relative_paths = (None,) for relative_path in relative_paths: if relative_path is None: relative_path = str(_get_gcs_root()) else: relative_path = str(_get_gcs_root() / relative_path) logging.info("Copying relative path: '%s'", relative_path) blobs = bucket.list_blobs(prefix=relative_path) for blob in blobs: _write_blob_to_destination(blob, FLAGS.task_root) if __name__ == '__main__': flags.mark_flag_as_required('payload') flags.mark_flag_as_required('task_root') app.run(main)
deepmind-research-master
ogb_lsc/pcq/download_pcq.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PCQM4M-LSC datasets.""" import functools import pickle from typing import Dict, List, Tuple, Union import numpy as np from ogb import lsc NUM_VALID_SAMPLES = 380_670 NUM_TEST_SAMPLES = 377_423 NORMALIZE_TARGET_MEAN = 5.690944545356371 NORMALIZE_TARGET_STD = 1.1561347795107815 def load_splits() -> Dict[str, List[int]]: """Loads dataset splits.""" dataset = _get_pcq_dataset(only_smiles=True) return dataset.get_idx_split() def load_kth_fold_indices(data_root: str, k_fold_split_id: int) -> List[int]: """Loads k-th fold indices.""" fname = f"{data_root}/k_fold_splits/{k_fold_split_id}.pkl" return list(map(int, _load_pickle(fname))) def load_all_except_kth_fold_indices(data_root: str, k_fold_split_id: int, num_k_fold_splits: int) -> List[int]: """Loads indices except for the kth fold.""" if k_fold_split_id is None: raise ValueError("Expected integer value for `k_fold_split_id`.") indices = [] for index in range(num_k_fold_splits): if index != k_fold_split_id: indices += load_kth_fold_indices(data_root, index) return indices def load_smile_strings( with_labels=False) -> List[Union[str, Tuple[str, np.ndarray]]]: """Loads the smile strings in the PCQ dataset.""" dataset = _get_pcq_dataset(only_smiles=True) smiles = [] for i in range(len(dataset)): smile, label = dataset[i] if with_labels: smiles.append((smile, label)) else: smiles.append(smile) return smiles @functools.lru_cache() def load_cached_conformers(cached_fname: str) -> Dict[str, np.ndarray]: """Returns cached dict mapping smile strings to conformer features.""" return _load_pickle(cached_fname) @functools.lru_cache() def _get_pcq_dataset(only_smiles: bool): return lsc.PCQM4MDataset(only_smiles=only_smiles) def _load_pickle(fname: str): with open(fname, "rb") as f: return pickle.load(f)
deepmind-research-master
ogb_lsc/pcq/datasets.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset utilities.""" from typing import List, Optional import jax import jraph from ml_collections import config_dict import numpy as np from ogb import utils from ogb.utils import features import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds import tree # pylint: disable=g-bad-import-order # pytype: disable=import-error import batching_utils import conformer_utils import datasets def build_dataset_iterator( data_root: str, split: str, dynamic_batch_size_config: config_dict.ConfigDict, sample_random: float, cached_conformers_file: str, debug: bool = False, is_training: bool = True, augment_with_random_mirror_symmetry: bool = False, positions_noise_std: Optional[float] = None, k_fold_split_id: Optional[int] = None, num_k_fold_splits: Optional[int] = None, filter_in_or_out_samples_with_nans_in_conformers: Optional[str] = None, ): """Returns an iterator over Batches from the dataset.""" if debug: max_items_to_read_from_dataset = 10 prefetch_buffer_size = 1 shuffle_buffer_size = 1 else: max_items_to_read_from_dataset = -1 # < 0 means no limit. prefetch_buffer_size = 64 # It can take a while to fill the shuffle buffer with k fold splits. shuffle_buffer_size = 128 if k_fold_split_id is None else int(1e6) num_local_devices = jax.local_device_count() # Load all smile strings. indices, smiles, labels = _load_smiles( data_root, split, k_fold_split_id=k_fold_split_id, num_k_fold_splits=num_k_fold_splits) if debug: indices = indices[:100] smiles = smiles[:100] labels = labels[:100] # Generate all conformer features from smile strings ahead of time. # This gives us a boost from multi-parallelism as opposed to doing it # online. conformers = _load_conformers(indices, smiles, cached_conformers_file) data_generator = ( lambda: _get_pcq_graph_generator(indices, smiles, labels, conformers)) # Create a dataset yielding graphs from smile strings. example = next(data_generator()) signature_from_example = tree.map_structure(_numpy_to_tensor_spec, example) ds = tf.data.Dataset.from_generator( data_generator, output_signature=signature_from_example) ds = ds.take(max_items_to_read_from_dataset) ds = ds.cache() if is_training: ds = ds.shuffle(shuffle_buffer_size) # Apply transformations. def map_fn(graph, conformer_positions): graph = _maybe_one_hot_atoms_with_noise( graph, is_training=is_training, sample_random=sample_random) # Add conformer features. graph = _add_conformer_features( graph, conformer_positions, augment_with_random_mirror_symmetry=augment_with_random_mirror_symmetry, noise_std=positions_noise_std, is_training=is_training, ) return _downcast_ints(graph) ds = ds.map(map_fn, num_parallel_calls=tf.data.AUTOTUNE) if filter_in_or_out_samples_with_nans_in_conformers: if filter_in_or_out_samples_with_nans_in_conformers not in ("in", "out"): raise ValueError( "Unknown value specified for the argument " "`filter_in_or_out_samples_with_nans_in_conformers`: %s" % filter_in_or_out_samples_with_nans_in_conformers) filter_fn = _get_conformer_filter( with_nans=(filter_in_or_out_samples_with_nans_in_conformers == "in")) ds = ds.filter(filter_fn) if is_training: ds = ds.shard(jax.process_count(), jax.process_index()) ds = ds.repeat() ds = ds.prefetch(prefetch_buffer_size) it = tfds.as_numpy(ds) # Dynamic batching. batched_gen = batching_utils.dynamically_batch( it, n_node=dynamic_batch_size_config.n_node + 1, n_edge=dynamic_batch_size_config.n_edge, n_graph=dynamic_batch_size_config.n_graph + 1, ) if is_training: # Stack `num_local_devices` of batches together for pmap updates. batch_size = num_local_devices def _batch(l): assert l return tree.map_structure(lambda *l: np.stack(l, axis=0), *l) def batcher_fn(): batch = [] for sample in batched_gen: batch.append(sample) if len(batch) == batch_size: yield _batch(batch) batch = [] if batch: yield _batch(batch) for sample in batcher_fn(): yield sample else: for sample in batched_gen: yield sample def _get_conformer_filter(with_nans: bool): """Selects a conformer filter to apply. Args: with_nans: Filter only selects samples with NaNs in conformer features. Else, selects samples without any NaNs in conformer features. Returns: A function that can be used with tf.data.Dataset.filter(). Raises: ValueError: If the input graph to the filter has no conformer features to filter. """ def _filter(graph: jraph.GraphsTuple) -> tf.Tensor: if ("positions" not in graph.nodes) or ( "positions_targets" not in graph.nodes) or ( "positions_nan_mask" not in graph.globals): raise ValueError("Conformer features not available to filter.") any_nan = tf.logical_not(tf.squeeze(graph.globals["positions_nan_mask"])) return any_nan if with_nans else tf.logical_not(any_nan) return _filter def _numpy_to_tensor_spec(arr: np.ndarray) -> tf.TensorSpec: if not isinstance(arr, np.ndarray): return tf.TensorSpec([], dtype=tf.int32 if isinstance(arr, int) else tf.float32) elif arr.shape: return tf.TensorSpec((None,) + arr.shape[1:], arr.dtype) else: return tf.TensorSpec([], arr.dtype) def _sample_uniform_categorical(num: int, size: int) -> tf.Tensor: return tf.random.categorical(tf.math.log([[1 / size] * size]), num)[0] @jax.curry(jax.tree_map) def _downcast_ints(x): if x.dtype == tf.int64: return tf.cast(x, tf.int32) return x def _one_hot_atoms(atoms: tf.Tensor) -> tf.Tensor: vocab_sizes = features.get_atom_feature_dims() one_hots = [] for i in range(atoms.shape[1]): one_hots.append(tf.one_hot(atoms[:, i], vocab_sizes[i], dtype=tf.float32)) return tf.concat(one_hots, axis=-1) def _sample_one_hot_atoms(atoms: tf.Tensor) -> tf.Tensor: vocab_sizes = features.get_atom_feature_dims() one_hots = [] num_atoms = tf.shape(atoms)[0] for i in range(atoms.shape[1]): sampled_category = _sample_uniform_categorical(num_atoms, vocab_sizes[i]) one_hots.append( tf.one_hot(sampled_category, vocab_sizes[i], dtype=tf.float32)) return tf.concat(one_hots, axis=-1) def _one_hot_bonds(bonds: tf.Tensor) -> tf.Tensor: vocab_sizes = features.get_bond_feature_dims() one_hots = [] for i in range(bonds.shape[1]): one_hots.append(tf.one_hot(bonds[:, i], vocab_sizes[i], dtype=tf.float32)) return tf.concat(one_hots, axis=-1) def _sample_one_hot_bonds(bonds: tf.Tensor) -> tf.Tensor: vocab_sizes = features.get_bond_feature_dims() one_hots = [] num_bonds = tf.shape(bonds)[0] for i in range(bonds.shape[1]): sampled_category = _sample_uniform_categorical(num_bonds, vocab_sizes[i]) one_hots.append( tf.one_hot(sampled_category, vocab_sizes[i], dtype=tf.float32)) return tf.concat(one_hots, axis=-1) def _maybe_one_hot_atoms_with_noise( x, is_training: bool, sample_random: float, ): """One hot atoms with noise.""" gt_nodes = _one_hot_atoms(x.nodes) gt_edges = _one_hot_bonds(x.edges) if is_training: num_nodes = tf.shape(x.nodes)[0] sample_node_or_not = tf.random.uniform([num_nodes], maxval=1) < sample_random nodes = tf.where( tf.expand_dims(sample_node_or_not, axis=-1), _sample_one_hot_atoms(x.nodes), gt_nodes) num_edges = tf.shape(x.edges)[0] sample_edges_or_not = tf.random.uniform([num_edges], maxval=1) < sample_random edges = tf.where( tf.expand_dims(sample_edges_or_not, axis=-1), _sample_one_hot_bonds(x.edges), gt_edges) else: nodes = gt_nodes edges = gt_edges return x._replace( nodes={ "atom_one_hots_targets": gt_nodes, "atom_one_hots": nodes, }, edges={ "bond_one_hots_targets": gt_edges, "bond_one_hots": edges }) def _load_smiles( data_root: str, split: str, k_fold_split_id: int, num_k_fold_splits: int, ): """Loads smiles trings for the input split.""" if split == "test" or k_fold_split_id is None: indices = datasets.load_splits()[split] elif split == "train": indices = datasets.load_all_except_kth_fold_indices( data_root, k_fold_split_id, num_k_fold_splits) indices += datasets.load_splits()["train"] else: assert split == "valid" indices = datasets.load_kth_fold_indices(data_root, k_fold_split_id) smiles_and_labels = datasets.load_smile_strings(with_labels=True) smiles, labels = list(zip(*smiles_and_labels)) return indices, [smiles[i] for i in indices], [labels[i] for i in indices] def _convert_ogb_graph_to_graphs_tuple(ogb_graph): """Converts an OGB Graph to a GraphsTuple.""" senders = ogb_graph["edge_index"][0] receivers = ogb_graph["edge_index"][1] edges = ogb_graph["edge_feat"] nodes = ogb_graph["node_feat"] n_node = np.array([ogb_graph["num_nodes"]]) n_edge = np.array([len(senders)]) graph = jraph.GraphsTuple( nodes=nodes, edges=edges, senders=senders, receivers=receivers, n_node=n_node, n_edge=n_edge, globals=None) return tree.map_structure(lambda x: x if x is not None else np.array(0.), graph) def _load_conformers(indices: List[int], smiles: List[str], cached_conformers_file: str): """Loads conformers.""" smile_to_conformer = datasets.load_cached_conformers(cached_conformers_file) conformers = [] for graph_idx, smile in zip(indices, smiles): del graph_idx # Unused. if smile not in smile_to_conformer: raise KeyError("Cache did not have conformer entry for the smile %s" % str(smile)) conformers.append(dict(conformer=smile_to_conformer[smile])) return conformers def _add_conformer_features( graph, conformer_features, augment_with_random_mirror_symmetry: bool, noise_std: float, is_training: bool, ): """Adds conformer features.""" if not isinstance(graph.nodes, dict): raise ValueError("Expected a dict type for `graph.nodes`.") # Remove mean position to center around a canonical origin. positions = conformer_features["conformer"] # NaN's appear in ~0.13% of training, 0.104% of validation and 0.16% of test # nodes. # See this colab: http://shortn/_6UcuosxY7x. nan_mask = tf.reduce_any(tf.math.is_nan(positions)) positions = tf.where(nan_mask, tf.constant(0., positions.dtype), positions) positions -= tf.reduce_mean(positions, axis=0, keepdims=True) # Optionally augment with a random rotation. if is_training: rot_mat = conformer_utils.get_random_rotation_matrix( augment_with_random_mirror_symmetry) positions = conformer_utils.rotate(positions, rot_mat) positions_targets = positions # Optionally add noise to the positions. if noise_std and is_training: positions = tf.random.normal(tf.shape(positions), positions, noise_std) return graph._replace( nodes=dict( positions=positions, positions_targets=positions_targets, **graph.nodes), globals={ "positions_nan_mask": tf.expand_dims(tf.logical_not(nan_mask), axis=0), **(graph.globals if isinstance(graph.globals, dict) else {}) }) def _get_pcq_graph_generator(indices, smiles, labels, conformers): """Returns a generator to yield graph.""" for idx, smile, conformer_positions, label in zip(indices, smiles, conformers, labels): graph = utils.smiles2graph(smile) graph = _convert_ogb_graph_to_graphs_tuple(graph) graph = graph._replace( globals={ "target": np.array([label], dtype=np.float32), "graph_index": np.array([idx], dtype=np.int32), **(graph.globals if isinstance(graph.globals, dict) else {}) }) yield graph, conformer_positions
deepmind-research-master
ogb_lsc/pcq/dataset_utils.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PCQM4M-LSC models.""" import copy import functools from typing import Any, Dict, Mapping, Sequence, Tuple import chex import haiku as hk import jax import jax.numpy as jnp import jraph from ml_collections import config_dict _REDUCER_NAMES = { "sum": jax.ops.segment_sum, "mean": jraph.segment_mean, } _NUM_EDGE_FEATURES = 13 _NUM_NODE_FEATURES = 173 @chex.dataclass class RegressionLossConfig: """Regression Loss Config.""" # For normalization and denormalization. std: float mean: float kwargs: Mapping[str, Any] out_size: int = 1 def _sigmoid_cross_entropy( logits: jnp.DeviceArray, labels: jnp.DeviceArray, ) -> jnp.DeviceArray: log_p = jax.nn.log_sigmoid(logits) log_not_p = jax.nn.log_sigmoid(-logits) return -labels * log_p - (1. - labels) * log_not_p def _softmax_cross_entropy( logits: jnp.DeviceArray, targets: jnp.DeviceArray, ) -> jnp.DeviceArray: logits = jax.nn.log_softmax(logits) return -jnp.sum(targets * logits, axis=-1) def _regression_loss( pred: jnp.ndarray, targets: jnp.ndarray, exponent: int, ) -> jnp.ndarray: """Regression loss.""" error = pred - targets if exponent == 2: return error ** 2 elif exponent == 1: return jnp.abs(error) else: raise ValueError(f"Unsupported exponent value {exponent}.") def _build_mlp( name: str, output_sizes: Sequence[int], use_layer_norm=False, activation=jax.nn.relu, ): """Builds an MLP, optionally with layernorm.""" net = hk.nets.MLP( output_sizes=output_sizes, name=name + "_mlp", activation=activation) if use_layer_norm: layer_norm = hk.LayerNorm( axis=-1, create_scale=True, create_offset=True, name=name + "_layer_norm") net = hk.Sequential([net, layer_norm]) return jraph.concatenated_args(net) def _compute_relative_displacement_and_distance( graph: jraph.GraphsTuple, normalization_factor: float, use_target: bool, ) -> Tuple[jnp.ndarray, jnp.ndarray]: """Computes relative displacements and distances.""" if use_target: node_positions = graph.nodes["positions_targets"] else: node_positions = graph.nodes["positions"] relative_displacement = node_positions[ graph.receivers] - node_positions[graph.senders] # Note due to the random rotations in space, mean across all nodes across # all batches is guaranteed to be zero, and the standard deviation is # guaranteed to be the same for all 3 coordinates, so we only need to scale # by a single value. relative_displacement /= normalization_factor relative_distance = jnp.linalg.norm( relative_displacement, axis=-1, keepdims=True) return relative_displacement, relative_distance def _broadcast_global_to_nodes( global_feature: jnp.ndarray, graph: jraph.GraphsTuple, ) -> jnp.ndarray: graph_idx = jnp.arange(graph.n_node.shape[0]) sum_n_node = jax.tree_leaves(graph.nodes)[0].shape[0] node_graph_idx = jnp.repeat( graph_idx, graph.n_node, axis=0, total_repeat_length=sum_n_node) return global_feature[node_graph_idx] def _broadcast_global_to_edges( global_feature: jnp.ndarray, graph: jraph.GraphsTuple, ) -> jnp.ndarray: graph_idx = jnp.arange(graph.n_edge.shape[0]) sum_n_edge = graph.senders.shape[0] edge_graph_idx = jnp.repeat( graph_idx, graph.n_edge, axis=0, total_repeat_length=sum_n_edge) return global_feature[edge_graph_idx] class GraphPropertyEncodeProcessDecode(hk.Module): """Encode-process-decode model for graph property prediction.""" def __init__( self, loss_config: config_dict.ConfigDict, mlp_hidden_size: int, mlp_layers: int, latent_size: int, use_layer_norm: bool, num_message_passing_steps: int, shared_message_passing_weights: bool, mask_padding_graph_at_every_step: bool, loss_config_name: str, loss_kwargs: config_dict.ConfigDict, processor_mode: str, global_reducer: str, node_reducer: str, dropedge_rate: float, dropnode_rate: float, aux_multiplier: float, ignore_globals: bool, ignore_globals_from_final_layer_for_predictions: bool, add_relative_distance: bool = False, add_relative_displacement: bool = False, add_absolute_positions: bool = False, position_normalization: float = 1., relative_displacement_normalization: float = 1., add_misc_node_features: bool = None, name="GraphPropertyEncodeProcessDecode", ): super(GraphPropertyEncodeProcessDecode, self).__init__() self._loss_config = loss_config self._config = config_dict.ConfigDict(dict( loss_config=loss_config, mlp_hidden_size=mlp_hidden_size, mlp_layers=mlp_layers, latent_size=latent_size, use_layer_norm=use_layer_norm, num_message_passing_steps=num_message_passing_steps, shared_message_passing_weights=shared_message_passing_weights, mask_padding_graph_at_every_step=mask_padding_graph_at_every_step, loss_config_name=loss_config_name, loss_kwargs=loss_kwargs, processor_mode=processor_mode, global_reducer=global_reducer, node_reducer=node_reducer, dropedge_rate=dropedge_rate, dropnode_rate=dropnode_rate, aux_multiplier=aux_multiplier, ignore_globals=ignore_globals, ignore_globals_from_final_layer_for_predictions=ignore_globals_from_final_layer_for_predictions, add_relative_distance=add_relative_distance, add_relative_displacement=add_relative_displacement, add_absolute_positions=add_absolute_positions, position_normalization=position_normalization, relative_displacement_normalization=relative_displacement_normalization, add_misc_node_features=add_misc_node_features, )) def __call__(self, graph: jraph.GraphsTuple) -> chex.ArrayTree: """Model inference step.""" out = self._forward(graph, is_training=False) if isinstance(self._loss_config, RegressionLossConfig): out["globals"] = out[ "globals"]*self._loss_config.std + self._loss_config.mean return out @hk.experimental.name_like("__call__") def get_loss( self, graph: jraph.GraphsTuple, is_training: bool = True, ) -> Tuple[jnp.ndarray, chex.ArrayTree]: """Model loss.""" scalars = get_utilization_scalars(graph) targets = copy.deepcopy(graph.globals["target"]) if len(targets.shape) == 1: targets = targets[:, None] del graph.globals["target"] target_mask = None if "target_mask" in graph.globals: target_mask = copy.deepcopy(graph.globals["target_mask"]) del graph.globals["target_mask"] out = self._forward(graph, is_training) if isinstance(self._loss_config, RegressionLossConfig): normalized_targets = ( (targets - self._loss_config.mean) / self._loss_config.std) per_graph_and_head_loss = _regression_loss( out["globals"], normalized_targets, **self._loss_config.kwargs) else: raise TypeError(type(self._loss_config)) # Mask out nans if target_mask is None: per_graph_and_head_loss = jnp.mean(per_graph_and_head_loss, axis=1) else: per_graph_and_head_loss = jnp.sum( per_graph_and_head_loss * target_mask, axis=1) per_graph_and_head_loss /= jnp.sum(target_mask + 1e-8, axis=1) g_mask = jraph.get_graph_padding_mask(graph) loss = _mean_with_mask(per_graph_and_head_loss, g_mask) scalars.update({"loss": loss}) if self._config.aux_multiplier > 0: atom_loss = self._get_node_auxiliary_loss( graph, out["atom_one_hots"], graph.nodes["atom_one_hots_targets"], is_regression=False) bond_loss = self._get_edge_auxiliary_loss( graph, out["bond_one_hots"], graph.edges["bond_one_hots_targets"], is_regression=False) loss += (atom_loss + bond_loss)*self._config.aux_multiplier scalars.update({"atom_loss": atom_loss, "bond_loss": bond_loss}) scaled_loss = loss / jax.device_count() scalars.update({"total_loss": loss}) return scaled_loss, scalars @hk.transparent def _prepare_features(self, graph: jraph.GraphsTuple) -> jraph.GraphsTuple: """Prepares features keys into flat node, edge and global features.""" # Collect edge features. edge_features_list = [graph.edges["bond_one_hots"]] if (self._config.add_relative_displacement or self._config.add_relative_distance): (relative_displacement, relative_distance ) = _compute_relative_displacement_and_distance( graph, self._config.relative_displacement_normalization, use_target=False) if self._config.add_relative_displacement: edge_features_list.append(relative_displacement) if self._config.add_relative_distance: edge_features_list.append(relative_distance) mask_at_edges = _broadcast_global_to_edges( graph.globals["positions_nan_mask"], graph) edge_features_list.append(mask_at_edges[:, None].astype(jnp.float32)) edge_features = jnp.concatenate(edge_features_list, axis=-1) # Collect node features node_features_list = [graph.nodes["atom_one_hots"]] if self._config.add_absolute_positions: node_features_list.append( graph.nodes["positions"] / self._config.position_normalization) mask_at_nodes = _broadcast_global_to_nodes( graph.globals["positions_nan_mask"], graph) node_features_list.append(mask_at_nodes[:, None].astype(jnp.float32)) node_features = jnp.concatenate(node_features_list, axis=-1) global_features = jnp.zeros((len(graph.n_node), self._config.latent_size)) chex.assert_tree_shape_prefix(global_features, (len(graph.n_node),)) return graph._replace( nodes=node_features, edges=edge_features, globals=global_features) @hk.transparent def _encoder( self, graph: jraph.GraphsTuple, is_training: bool, ) -> jraph.GraphsTuple: """Builds the encoder.""" del is_training # unused graph = self._prepare_features(graph) # Run encoders in all of the node, edge and global features. output_sizes = [self._config.mlp_hidden_size] * self._config.mlp_layers output_sizes += [self._config.latent_size] build_mlp = functools.partial( _build_mlp, output_sizes=output_sizes, use_layer_norm=self._config.use_layer_norm, ) gmf = jraph.GraphMapFeatures( embed_edge_fn=build_mlp("edge_encoder"), embed_node_fn=build_mlp("node_encoder"), embed_global_fn=None if self._config.ignore_globals else build_mlp("global_encoder"), ) return gmf(graph) @hk.transparent def _processor( self, graph: jraph.GraphsTuple, is_training: bool, ) -> jraph.GraphsTuple: """Builds the processor.""" output_sizes = [self._config.mlp_hidden_size] * self._config.mlp_layers output_sizes += [self._config.latent_size] build_mlp = functools.partial( _build_mlp, output_sizes=output_sizes, use_layer_norm=self._config.use_layer_norm, ) shared_weights = self._config.shared_message_passing_weights node_reducer = _REDUCER_NAMES[self._config.node_reducer] global_reducer = _REDUCER_NAMES[self._config.global_reducer] def dropout_if_training(fn, dropout_rate: float): def wrapped(*args): out = fn(*args) if is_training: mask = hk.dropout(hk.next_rng_key(), dropout_rate, jnp.ones([out.shape[0], 1])) out = out * mask return out return wrapped num_mps = self._config.num_message_passing_steps for step in range(num_mps): if step == 0 or not shared_weights: suffix = "shared" if shared_weights else step update_edge_fn = dropout_if_training( build_mlp(f"edge_processor_{suffix}"), dropout_rate=self._config.dropedge_rate) update_node_fn = dropout_if_training( build_mlp(f"node_processor_{suffix}"), dropout_rate=self._config.dropnode_rate) if self._config.ignore_globals: gnn = jraph.InteractionNetwork( update_edge_fn=update_edge_fn, update_node_fn=update_node_fn, aggregate_edges_for_nodes_fn=node_reducer) else: gnn = jraph.GraphNetwork( update_edge_fn=update_edge_fn, update_node_fn=update_node_fn, update_global_fn=build_mlp(f"global_processor_{suffix}"), aggregate_edges_for_nodes_fn=node_reducer, aggregate_nodes_for_globals_fn=global_reducer, aggregate_edges_for_globals_fn=global_reducer, ) mode = self._config.processor_mode if mode == "mlp": graph = gnn(graph) elif mode == "resnet": new_graph = gnn(graph) graph = graph._replace( nodes=graph.nodes + new_graph.nodes, edges=graph.edges + new_graph.edges, globals=graph.globals + new_graph.globals, ) else: raise ValueError(f"Unknown processor_mode `{mode}`") if self._config.mask_padding_graph_at_every_step: graph = _mask_out_padding_graph(graph) return graph @hk.transparent def _decoder( self, graph: jraph.GraphsTuple, input_graph: jraph.GraphsTuple, is_training: bool, ) -> chex.ArrayTree: """Builds the decoder.""" del is_training # unused. output_sizes = [self._config.mlp_hidden_size] * self._config.mlp_layers output_sizes += [self._loss_config.out_size] net = _build_mlp("regress_out", output_sizes, use_layer_norm=False) summed_nodes = _aggregate_nodes_to_globals(graph, graph.nodes) inputs_to_global_decoder = [summed_nodes] if not self._config.ignore_globals_from_final_layer_for_predictions: inputs_to_global_decoder.append(graph.globals) out = net(jnp.concatenate(inputs_to_global_decoder, axis=-1)) out_dict = {} out_dict["globals"] = out # Note "linear" names are for compatibility with pre-trained model names. out_dict["bond_one_hots"] = hk.Linear( _NUM_EDGE_FEATURES, name="linear")(graph.edges) out_dict["atom_one_hots"] = hk.Linear( _NUM_NODE_FEATURES, name="linear_1")(graph.nodes) return out_dict @hk.transparent def _forward(self, graph: jraph.GraphsTuple, is_training: bool): input_graph = jraph.GraphsTuple(*graph) with hk.experimental.name_scope("encoder_scope"): graph = self._encoder(graph, is_training) with hk.experimental.name_scope("processor_scope"): graph = self._processor(graph, is_training) with hk.experimental.name_scope("decoder_scope"): out = self._decoder(graph, input_graph, is_training) return out def _get_node_auxiliary_loss( self, graph, pred, targets, is_regression, additional_mask=None): loss = self._get_loss(pred, targets, is_regression) target_mask = jraph.get_node_padding_mask(graph) if additional_mask is not None: loss *= additional_mask target_mask = jnp.logical_and(target_mask, additional_mask) return _mean_with_mask(loss, target_mask) def _get_edge_auxiliary_loss( self, graph, pred, targets, is_regression, additional_mask=None): loss = self._get_loss(pred, targets, is_regression) target_mask = jraph.get_edge_padding_mask(graph) if additional_mask is not None: loss *= additional_mask target_mask = jnp.logical_and(target_mask, additional_mask) return _mean_with_mask(loss, target_mask) def _get_loss(self, pred, targets, is_regression): if is_regression: loss = ((pred - targets)**2).mean(axis=-1) else: targets /= jnp.maximum(1., jnp.sum(targets, axis=-1, keepdims=True)) loss = _softmax_cross_entropy(pred, targets) return loss def get_utilization_scalars( padded_graph: jraph.GraphsTuple) -> Dict[str, float]: padding_nodes = jraph.get_number_of_padding_with_graphs_nodes(padded_graph) all_nodes = len(jax.tree_leaves(padded_graph.nodes)[0]) padding_edges = jraph.get_number_of_padding_with_graphs_edges(padded_graph) all_edges = len(jax.tree_leaves(padded_graph.edges)[0]) padding_graphs = jraph.get_number_of_padding_with_graphs_graphs(padded_graph) all_graphs = len(padded_graph.n_node) return {"node_utilization": 1 - (padding_nodes / all_nodes), "edge_utilization": 1 - (padding_edges / all_edges), "graph_utilization": 1 - (padding_graphs / all_graphs)} def sum_with_mask(array: jnp.ndarray, mask: jnp.ndarray) -> jnp.ndarray: return (mask * array).sum(0) def _mean_with_mask(array: jnp.ndarray, mask: jnp.ndarray) -> jnp.ndarray: num_valid_rows = mask.sum(0) return sum_with_mask(array, mask) / num_valid_rows def _mask_out_padding_graph( padded_graph: jraph.GraphsTuple) -> jraph.GraphsTuple: return padded_graph._replace( nodes=jnp.where( jraph.get_node_padding_mask( padded_graph)[:, None], padded_graph.nodes, 0.), edges=jnp.where( jraph.get_edge_padding_mask( padded_graph)[:, None], padded_graph.edges, 0.), globals=jnp.where( jraph.get_graph_padding_mask( padded_graph)[:, None], padded_graph.globals, 0.), ) def _aggregate_nodes_to_globals(graph, node_features): n_graph = graph.n_node.shape[0] sum_n_node = jax.tree_leaves(graph.nodes)[0].shape[0] graph_idx = jnp.arange(n_graph) node_gr_idx = jnp.repeat( graph_idx, graph.n_node, axis=0, total_repeat_length=sum_n_node) return jax.ops.segment_sum(node_features, node_gr_idx, num_segments=n_graph)
deepmind-research-master
ogb_lsc/pcq/model.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PCQM4M-LSC Jaxline experiment.""" import datetime import functools import os import signal import threading from typing import Iterable, Mapping, NamedTuple, Tuple from absl import app from absl import flags from absl import logging import chex import dill import haiku as hk import jax from jax.config import config as jax_config import jax.numpy as jnp from jaxline import experiment from jaxline import platform from jaxline import utils import jraph import numpy as np import optax import tensorflow as tf import tree # pylint: disable=g-bad-import-order import dataset_utils import datasets import model FLAGS = flags.FLAGS def _get_step_date_label(global_step: int): # Date removing microseconds. date_str = datetime.datetime.now().isoformat().split('.')[0] return f'step_{global_step}_{date_str}' class _Predictions(NamedTuple): predictions: np.ndarray indices: np.ndarray def tf1_ema(ema_value, current_value, decay, step): """Implements EMA with TF1-style decay warmup.""" decay = jnp.minimum(decay, (1.0 + step) / (10.0 + step)) return ema_value * decay + current_value * (1 - decay) def _sort_predictions_by_indices(predictions: _Predictions): sorted_order = np.argsort(predictions.indices) return _Predictions( predictions=predictions.predictions[sorted_order], indices=predictions.indices[sorted_order]) class Experiment(experiment.AbstractExperiment): """OGB Graph Property Prediction GraphNet experiment.""" CHECKPOINT_ATTRS = { '_params': 'params', '_opt_state': 'opt_state', '_network_state': 'network_state', '_ema_network_state': 'ema_network_state', '_ema_params': 'ema_params', } def __init__(self, mode, init_rng, config): """Initializes experiment.""" super(Experiment, self).__init__(mode=mode, init_rng=init_rng) if mode not in ('train', 'eval', 'train_eval_multithreaded'): raise ValueError(f'Invalid mode {mode}.') # Do not use accelerators in data pipeline. tf.config.experimental.set_visible_devices([], device_type='GPU') tf.config.experimental.set_visible_devices([], device_type='TPU') self.mode = mode self.init_rng = init_rng self.config = config self.loss = None self.forward = None # Needed for checkpoint restore. self._params = None self._network_state = None self._opt_state = None self._ema_network_state = None self._ema_params = None # _ _ # | |_ _ __ __ _(_)_ __ # | __| "__/ _` | | "_ \ # | |_| | | (_| | | | | | # \__|_| \__,_|_|_| |_| # def step(self, global_step: jnp.ndarray, rng: jnp.ndarray, **unused_args): """See Jaxline base class.""" if self.loss is None: self._train_init() graph = next(self._train_input) out = self.update_parameters( self._params, self._ema_params, self._network_state, self._ema_network_state, self._opt_state, global_step, rng, graph._asdict()) (self._params, self._ema_params, self._network_state, self._ema_network_state, self._opt_state, scalars) = out return utils.get_first(scalars) def _construct_loss_config(self): loss_config = getattr(model, self.config.model.loss_config_name) if self.config.model.loss_config_name == 'RegressionLossConfig': return loss_config( mean=datasets.NORMALIZE_TARGET_MEAN, std=datasets.NORMALIZE_TARGET_STD, kwargs=self.config.model.loss_kwargs) else: raise ValueError('Unknown Loss Config') def _train_init(self): self.loss = hk.transform_with_state(self._loss) self._train_input = utils.py_prefetch( lambda: self._build_numpy_dataset_iterator('train', is_training=True)) init_stacked_graphs = next(self._train_input) init_key = utils.bcast_local_devices(self.init_rng) p_init = jax.pmap(self.loss.init) self._params, self._network_state = p_init(init_key, **init_stacked_graphs._asdict()) # Learning rate scheduling. lr_schedule = optax.warmup_cosine_decay_schedule( **self.config.optimizer.lr_schedule) self.optimizer = getattr(optax, self.config.optimizer.name)( learning_rate=lr_schedule, **self.config.optimizer.optimizer_kwargs) self._opt_state = jax.pmap(self.optimizer.init)(self._params) self.update_parameters = jax.pmap(self._update_parameters, axis_name='i') if self.config.ema: self._ema_params = self._params self._ema_network_state = self._network_state def _loss( self, **graph: Mapping[str, chex.ArrayTree]) -> chex.ArrayTree: graph = jraph.GraphsTuple(**graph) model_instance = model.GraphPropertyEncodeProcessDecode( loss_config=self._construct_loss_config(), **self.config.model) loss, scalars = model_instance.get_loss(graph) return loss, scalars def _maybe_save_predictions( self, predictions: jnp.ndarray, split: str, global_step: jnp.ndarray, ): if not self.config.predictions_dir: return output_dir = os.path.join(self.config.predictions_dir, _get_step_date_label(global_step)) os.makedirs(output_dir, exist_ok=True) output_path = os.path.join(output_dir, split + '.dill') with open(output_path, 'wb') as f: dill.dump(predictions, f) logging.info('Saved %s predictions at: %s', split, output_path) def _build_numpy_dataset_iterator(self, split: str, is_training: bool): dynamic_batch_size_config = ( self.config.training.dynamic_batch_size if is_training else self.config.evaluation.dynamic_batch_size) return dataset_utils.build_dataset_iterator( split=split, dynamic_batch_size_config=dynamic_batch_size_config, sample_random=self.config.sample_random, debug=self.config.debug, is_training=is_training, **self.config.dataset_config) def _update_parameters( self, params: hk.Params, ema_params: hk.Params, network_state: hk.State, ema_network_state: hk.State, opt_state: optax.OptState, global_step: jnp.ndarray, rng: jnp.ndarray, graph: jraph.GraphsTuple, ) -> Tuple[hk.Params, hk.Params, hk.State, hk.State, optax.OptState, chex.ArrayTree]: """Updates parameters.""" def get_loss(*x, **graph): (loss, scalars), network_state = self.loss.apply(*x, **graph) return loss, (scalars, network_state) grad_loss_fn = jax.grad(get_loss, has_aux=True) scaled_grads, (scalars, network_state) = grad_loss_fn( params, network_state, rng, **graph) grads = jax.lax.psum(scaled_grads, axis_name='i') updates, opt_state = self.optimizer.update(grads, opt_state, params) params = optax.apply_updates(params, updates) if ema_params is not None: ema = lambda x, y: tf1_ema(x, y, self.config.ema_decay, global_step) ema_params = jax.tree_map(ema, ema_params, params) ema_network_state = jax.tree_map(ema, ema_network_state, network_state) return params, ema_params, network_state, ema_network_state, opt_state, scalars # _ # _____ ____ _| | # / _ \ \ / / _` | | # | __/\ V / (_| | | # \___| \_/ \__,_|_| # def evaluate(self, global_step: jnp.ndarray, rng: jnp.ndarray, **unused_kwargs) -> chex.ArrayTree: """See Jaxline base class.""" if self.forward is None: self._eval_init() if self.config.ema: params = utils.get_first(self._ema_params) state = utils.get_first(self._ema_network_state) else: params = utils.get_first(self._params) state = utils.get_first(self._network_state) rng = utils.get_first(rng) split = self.config.evaluation.split predictions, scalars = self._get_predictions( params, state, rng, utils.py_prefetch( functools.partial( self._build_numpy_dataset_iterator, split, is_training=False))) self._maybe_save_predictions(predictions, split, global_step[0]) return scalars def _sum_regression_scalars(self, preds: jnp.ndarray, graph: jraph.GraphsTuple) -> chex.ArrayTree: """Creates unnormalised values for accumulation.""" targets = graph.globals['target'] graph_mask = jraph.get_graph_padding_mask(graph) # Sum for accumulation, normalise later since there are a # variable number of graphs per batch. mae = model.sum_with_mask(jnp.abs(targets - preds), graph_mask) mse = model.sum_with_mask((targets - preds)**2, graph_mask) count = jnp.sum(graph_mask) return {'values': {'mae': mae.item(), 'mse': mse.item()}, 'counts': {'mae': count.item(), 'mse': count.item()}} def _get_prediction( self, params: hk.Params, state: hk.State, rng: jnp.ndarray, graph: jraph.GraphsTuple, ) -> np.ndarray: """Returns predictions for all the graphs in the dataset split.""" model_out, _ = self.eval_apply(params, state, rng, **graph._asdict()) prediction = np.squeeze(model_out['globals'], axis=1) return prediction def _get_predictions( self, params: hk.Params, state: hk.State, rng: jnp.ndarray, graph_iterator: Iterable[jraph.GraphsTuple], ) -> Tuple[_Predictions, chex.ArrayTree]: all_scalars = [] predictions = [] graph_indices = [] for i, graph in enumerate(graph_iterator): prediction = self._get_prediction(params, state, rng, graph) if 'target' in graph.globals and not jnp.isnan( graph.globals['target']).any(): scalars = self._sum_regression_scalars(prediction, graph) all_scalars.append(scalars) num_padding_graphs = jraph.get_number_of_padding_with_graphs_graphs(graph) num_valid_graphs = len(graph.n_node) - num_padding_graphs depadded_prediction = prediction[:num_valid_graphs] predictions.append(depadded_prediction) graph_indices.append(graph.globals['graph_index'][:num_valid_graphs]) if i % 1000 == 0: logging.info('Generated predictions for %d batches so far', i + 1) predictions = _sort_predictions_by_indices( _Predictions( predictions=np.concatenate(predictions), indices=np.concatenate(graph_indices))) if all_scalars: sum_all_args = lambda *l: sum(l) # Sum over graphs in the dataset. accum_scalars = tree.map_structure(sum_all_args, *all_scalars) scalars = tree.map_structure(lambda x, y: x / y, accum_scalars['values'], accum_scalars['counts']) else: scalars = {} return predictions, scalars def _eval_init(self): self.forward = hk.transform_with_state(self._forward) self.eval_apply = jax.jit(self.forward.apply) def _forward(self, **graph: Mapping[str, chex.ArrayTree]) -> chex.ArrayTree: graph = jraph.GraphsTuple(**graph) model_instance = model.GraphPropertyEncodeProcessDecode( loss_config=self._construct_loss_config(), **self.config.model) return model_instance(graph) def _restore_state_to_in_memory_checkpointer(restore_path): """Initializes experiment state from a checkpoint.""" # Load pretrained experiment state. python_state_path = os.path.join(restore_path, 'checkpoint.dill') with open(python_state_path, 'rb') as f: pretrained_state = dill.load(f) logging.info('Restored checkpoint from %s', python_state_path) # Assign state to a dummy experiment instance for the in-memory checkpointer, # broadcasting to devices. dummy_experiment = Experiment( mode='train', init_rng=0, config=FLAGS.config.experiment_kwargs.config) for attribute, key in Experiment.CHECKPOINT_ATTRS.items(): setattr(dummy_experiment, attribute, utils.bcast_local_devices(pretrained_state[key])) jaxline_state = dict( global_step=pretrained_state['global_step'], experiment_module=dummy_experiment) snapshot = utils.SnapshotNT(0, jaxline_state) # Finally, seed the jaxline `utils.InMemoryCheckpointer` global dict. utils.GLOBAL_CHECKPOINT_DICT['latest'] = utils.CheckpointNT( threading.local(), [snapshot]) def _save_state_from_in_memory_checkpointer( save_path, experiment_class: experiment.AbstractExperiment): """Saves experiment state to a checkpoint.""" logging.info('Saving model.') for checkpoint_name, checkpoint in utils.GLOBAL_CHECKPOINT_DICT.items(): if not checkpoint.history: logging.info('Nothing to save in "%s"', checkpoint_name) continue pickle_nest = checkpoint.history[-1].pickle_nest global_step = pickle_nest['global_step'] state_dict = {'global_step': global_step} for attribute, key in experiment_class.CHECKPOINT_ATTRS.items(): state_dict[key] = utils.get_first( getattr(pickle_nest['experiment_module'], attribute)) save_dir = os.path.join( save_path, checkpoint_name, _get_step_date_label(global_step)) python_state_path = os.path.join(save_dir, 'checkpoint.dill') os.makedirs(save_dir, exist_ok=True) with open(python_state_path, 'wb') as f: dill.dump(state_dict, f) logging.info( 'Saved "%s" checkpoint to %s', checkpoint_name, python_state_path) def _setup_signals(save_model_fn): """Sets up a signal for model saving.""" # Save a model on Ctrl+C. def sigint_handler(unused_sig, unused_frame): # Ideally, rather than saving immediately, we would then "wait" for a good # time to save. In practice this reads from an in-memory checkpoint that # only saves every 30 seconds or so, so chances of race conditions are very # small. save_model_fn() logging.info(r'Use `Ctrl+\` to save and exit.') # Exit on `Ctrl+\`, saving a model. prev_sigquit_handler = signal.getsignal(signal.SIGQUIT) def sigquit_handler(unused_sig, unused_frame): # Restore previous handler early, just in case something goes wrong in the # next lines, so it is possible to press again and exit. signal.signal(signal.SIGQUIT, prev_sigquit_handler) save_model_fn() logging.info(r'Exiting on `Ctrl+\`') # Re-raise for clean exit. os.kill(os.getpid(), signal.SIGQUIT) signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGQUIT, sigquit_handler) def main(argv, experiment_class: experiment.AbstractExperiment): # Maybe restore a model. restore_path = FLAGS.config.restore_path if restore_path: _restore_state_to_in_memory_checkpointer(restore_path) # Maybe save a model. save_dir = os.path.join(FLAGS.config.checkpoint_dir, 'models') if FLAGS.config.one_off_evaluate: save_model_fn = lambda: None # No need to save checkpoint in this case. else: save_model_fn = functools.partial( _save_state_from_in_memory_checkpointer, save_dir, experiment_class) _setup_signals(save_model_fn) # Save on Ctrl+C (continue) or Ctrl+\ (exit). try: platform.main(experiment_class, argv) finally: save_model_fn() # Save at the end of training or in case of exception. if __name__ == '__main__': jax_config.update('jax_debug_nans', False) flags.mark_flag_as_required('config') app.run(lambda argv: main(argv, Experiment))
deepmind-research-master
ogb_lsc/pcq/experiment.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dynamic batching utilities.""" from typing import Generator, Iterator, Sequence, Tuple import jax.tree_util as tree import jraph import numpy as np _NUMBER_FIELDS = ("n_node", "n_edge", "n_graph") def dynamically_batch(graphs_tuple_iterator: Iterator[jraph.GraphsTuple], n_node: int, n_edge: int, n_graph: int) -> Generator[jraph.GraphsTuple, None, None]: """Dynamically batches trees with `jraph.GraphsTuples` to `graph_batch_size`. Elements of the `graphs_tuple_iterator` will be incrementally added to a batch until the limits defined by `n_node`, `n_edge` and `n_graph` are reached. This means each element yielded by this generator For situations where you have variable sized data, it"s useful to be able to have variable sized batches. This is especially the case if you have a loss defined on the variable shaped element (for example, nodes in a graph). Args: graphs_tuple_iterator: An iterator of `jraph.GraphsTuples`. n_node: The maximum number of nodes in a batch. n_edge: The maximum number of edges in a batch. n_graph: The maximum number of graphs in a batch. Yields: A `jraph.GraphsTuple` batch of graphs. Raises: ValueError: if the number of graphs is < 2. RuntimeError: if the `graphs_tuple_iterator` contains elements which are not `jraph.GraphsTuple`s. RuntimeError: if a graph is found which is larger than the batch size. """ if n_graph < 2: raise ValueError("The number of graphs in a batch size must be greater or " f"equal to `2` for padding with graphs, got {n_graph}.") valid_batch_size = (n_node - 1, n_edge, n_graph - 1) accumulated_graphs = [] num_accumulated_nodes = 0 num_accumulated_edges = 0 num_accumulated_graphs = 0 for element in graphs_tuple_iterator: element_nodes, element_edges, element_graphs = _get_graph_size(element) if _is_over_batch_size(element, valid_batch_size): graph_size = element_nodes, element_edges, element_graphs graph_size = {k: v for k, v in zip(_NUMBER_FIELDS, graph_size)} batch_size = {k: v for k, v in zip(_NUMBER_FIELDS, valid_batch_size)} raise RuntimeError("Found graph bigger than batch size. Valid Batch " f"Size: {batch_size}, Graph Size: {graph_size}") if not accumulated_graphs: # If this is the first element of the batch, set it and continue. accumulated_graphs = [element] num_accumulated_nodes = element_nodes num_accumulated_edges = element_edges num_accumulated_graphs = element_graphs continue else: # Otherwise check if there is space for the graph in the batch: if ((num_accumulated_graphs + element_graphs > n_graph - 1) or (num_accumulated_nodes + element_nodes > n_node - 1) or (num_accumulated_edges + element_edges > n_edge)): # If there is, add it to the batch batched_graph = _batch_np(accumulated_graphs) yield jraph.pad_with_graphs(batched_graph, n_node, n_edge, n_graph) accumulated_graphs = [element] num_accumulated_nodes = element_nodes num_accumulated_edges = element_edges num_accumulated_graphs = element_graphs else: # Otherwise, return the old batch and start a new batch. accumulated_graphs.append(element) num_accumulated_nodes += element_nodes num_accumulated_edges += element_edges num_accumulated_graphs += element_graphs # We may still have data in batched graph. if accumulated_graphs: batched_graph = _batch_np(accumulated_graphs) yield jraph.pad_with_graphs(batched_graph, n_node, n_edge, n_graph) def _batch_np(graphs: Sequence[jraph.GraphsTuple]) -> jraph.GraphsTuple: # Calculates offsets for sender and receiver arrays, caused by concatenating # the nodes arrays. offsets = np.cumsum(np.array([0] + [np.sum(g.n_node) for g in graphs[:-1]])) def _map_concat(nests): concat = lambda *args: np.concatenate(args) return tree.tree_map(concat, *nests) return jraph.GraphsTuple( n_node=np.concatenate([g.n_node for g in graphs]), n_edge=np.concatenate([g.n_edge for g in graphs]), nodes=_map_concat([g.nodes for g in graphs]), edges=_map_concat([g.edges for g in graphs]), globals=_map_concat([g.globals for g in graphs]), senders=np.concatenate([g.senders + o for g, o in zip(graphs, offsets)]), receivers=np.concatenate( [g.receivers + o for g, o in zip(graphs, offsets)])) def _get_graph_size(graph: jraph.GraphsTuple) -> Tuple[int, int, int]: n_node = np.sum(graph.n_node) n_edge = len(graph.senders) n_graph = len(graph.n_node) return n_node, n_edge, n_graph def _is_over_batch_size( graph: jraph.GraphsTuple, graph_batch_size: Tuple[int, int, int], ) -> bool: graph_size = _get_graph_size(graph) return any([x > y for x, y in zip(graph_size, graph_batch_size)])
deepmind-research-master
ogb_lsc/pcq/batching_utils.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generate conformer features to be used for training/predictions.""" import multiprocessing as mp import pickle from typing import List from absl import app from absl import flags import numpy as np # pylint: disable=g-bad-import-order import conformer_utils import datasets _SPLITS = flags.DEFINE_spaceseplist( 'splits', ['test'], 'Splits to compute conformer features for.') _OUTPUT_FILE = flags.DEFINE_string( 'output_file', None, required=True, help='Output file name to write the generated conformer features to.') _NUM_PROCS = flags.DEFINE_integer( 'num_parallel_procs', 64, 'Number of parallel processes to use for conformer generation.') def generate_conformer_features(smiles: List[str]) -> List[np.ndarray]: # Conformer generation is a CPU-bound task and hence can get a boost from # parallel processing. # To avoid GIL, we choose multiprocessing instead of the # simpler multi-threading option here for parallel computing. with mp.Pool(_NUM_PROCS.value) as pool: return list(pool.map(conformer_utils.compute_conformer, smiles)) def main(_): smiles = datasets.load_smile_strings(with_labels=False) indices = set() for split in _SPLITS.value: indices.update(datasets.load_splits()[split]) smiles = [smiles[i] for i in sorted(indices)] conformers = generate_conformer_features(smiles) smiles_to_conformers = dict(zip(smiles, conformers)) with open(_OUTPUT_FILE.value, 'wb') as f: pickle.dump(smiles_to_conformers, f) if __name__ == '__main__': app.run(main)
deepmind-research-master
ogb_lsc/pcq/generate_conformer_features.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Conformer utilities.""" import copy from typing import List, Optional from absl import logging import numpy as np import rdkit from rdkit import Chem from rdkit.Chem import AllChem import tensorflow.compat.v2 as tf def generate_conformers( molecule: Chem.rdchem.Mol, max_num_conformers: int, *, random_seed: int = -1, prune_rms_thresh: float = -1.0, max_iter: int = -1, fallback_to_random: bool = False, ) -> Chem.rdchem.Mol: """Generates conformers for a given molecule. Args: molecule: molecular representation of the compound. max_num_conformers: maximum number of conformers to generate. If pruning is done, the returned number of conformers is not guaranteed to match max_num_conformers. random_seed: random seed to use for conformer generation. prune_rms_thresh: RMSD threshold which allows to prune conformers that are too similar. max_iter: Maximum number of iterations to perform when optimising MMFF force field. If set to <= 0, energy optimisation is not performed. fallback_to_random: if conformers cannot be obtained, use random coordinates to initialise. Returns: Copy of a `molecule` with added hydrogens. The returned molecule contains force field-optimised conformers. The number of conformers is guaranteed to be <= max_num_conformers. """ mol = copy.deepcopy(molecule) mol = Chem.AddHs(mol) mol = _embed_conformers( mol, max_num_conformers, random_seed, prune_rms_thresh, fallback_to_random, use_random=False) if max_iter > 0: mol_with_conformers = _minimize_by_mmff(mol, max_iter) if mol_with_conformers is None: mol_with_conformers = _minimize_by_uff(mol, max_iter) else: mol_with_conformers = mol # Aligns conformations in a molecule to each other using the first # conformation as the reference. AllChem.AlignMolConformers(mol_with_conformers) # We remove hydrogens to keep the number of atoms consistent with the graph # nodes. mol_with_conformers = Chem.RemoveHs(mol_with_conformers) return mol_with_conformers def atom_to_feature_vector( atom: rdkit.Chem.rdchem.Atom, conformer: Optional[np.ndarray] = None, ) -> List[float]: """Converts rdkit atom object to feature list of indices. Args: atom: rdkit atom object. conformer: Generated conformers. Returns -1 values if set to None. Returns: List containing positions (x, y, z) of each atom from the conformer. """ if conformer: pos = conformer.GetAtomPosition(atom.GetIdx()) return [pos.x, pos.y, pos.z] return [np.nan, np.nan, np.nan] def compute_conformer(smile: str, max_iter: int = -1) -> np.ndarray: """Computes conformer. Args: smile: Smile string. max_iter: Maximum number of iterations to perform when optimising MMFF force field. If set to <= 0, energy optimisation is not performed. Returns: A tuple containing index, fingerprint and conformer. Raises: RuntimeError: If unable to convert smile string to RDKit mol. """ mol = rdkit.Chem.MolFromSmiles(smile) if not mol: raise RuntimeError('Unable to convert smile to molecule: %s' % smile) conformer_failed = False try: mol = generate_conformers( mol, max_num_conformers=1, random_seed=45, prune_rms_thresh=0.01, max_iter=max_iter) except IOError as e: logging.exception('Failed to generate conformers for %s . IOError %s.', smile, e) conformer_failed = True except ValueError: logging.error('Failed to generate conformers for %s . ValueError', smile) conformer_failed = True except: # pylint: disable=bare-except logging.error('Failed to generate conformers for %s.', smile) conformer_failed = True atom_features_list = [] conformer = None if conformer_failed else list(mol.GetConformers())[0] for atom in mol.GetAtoms(): atom_features_list.append(atom_to_feature_vector(atom, conformer)) conformer_features = np.array(atom_features_list, dtype=np.float32) return conformer_features def get_random_rotation_matrix(include_mirror_symmetry: bool) -> tf.Tensor: """Returns a single random rotation matrix.""" rotation_matrix = _get_random_rotation_3d() if include_mirror_symmetry: random_mirror_symmetry = _get_random_mirror_symmetry() rotation_matrix = tf.matmul(rotation_matrix, random_mirror_symmetry) return rotation_matrix def rotate(vectors: tf.Tensor, rotation_matrix: tf.Tensor) -> tf.Tensor: """Batch of vectors on a single rotation matrix.""" return tf.matmul(vectors, rotation_matrix) def _embed_conformers( molecule: Chem.rdchem.Mol, max_num_conformers: int, random_seed: int, prune_rms_thresh: float, fallback_to_random: bool, *, use_random: bool = False, ) -> Chem.rdchem.Mol: """Embeds conformers into a copy of a molecule. If random coordinates allowed, tries not to use random coordinates at first, and uses random only if fails. Args: molecule: molecular representation of the compound. max_num_conformers: maximum number of conformers to generate. If pruning is done, the returned number of conformers is not guaranteed to match max_num_conformers. random_seed: random seed to use for conformer generation. prune_rms_thresh: RMSD threshold which allows to prune conformers that are too similar. fallback_to_random: if conformers cannot be obtained, use random coordinates to initialise. *: use_random: Use random coordinates. Shouldn't be set by any caller except this function itself. Returns: A copy of a molecule with embedded conformers. Raises: ValueError: if conformers cannot be obtained for a given molecule. """ mol = copy.deepcopy(molecule) # Obtains parameters for conformer generation. # In particular, ETKDG is experimental-torsion basic knowledge distance # geometry, which allows to randomly generate an initial conformation that # satisfies various geometric constraints such as lower and upper bounds on # the distances between atoms. params = AllChem.ETKDGv3() params.randomSeed = random_seed params.pruneRmsThresh = prune_rms_thresh params.numThreads = -1 params.useRandomCoords = use_random conf_ids = AllChem.EmbedMultipleConfs(mol, max_num_conformers, params) if not conf_ids: if not fallback_to_random or use_random: raise ValueError('Cant get conformers') return _embed_conformers( mol, max_num_conformers, random_seed, prune_rms_thresh, fallback_to_random, use_random=True) return mol def _minimize_by_mmff( molecule: Chem.rdchem.Mol, max_iter: int, ) -> Optional[Chem.rdchem.Mol]: """Minimizes forcefield for conformers using MMFF algorithm. Args: molecule: a datastructure containing conformers. max_iter: number of maximum iterations to use when optimising force field. Returns: A copy of a `molecule` containing optimised conformers; or None if MMFF cannot be performed. """ molecule_props = AllChem.MMFFGetMoleculeProperties(molecule) if molecule_props is None: return None mol = copy.deepcopy(molecule) for conf_id in range(mol.GetNumConformers()): ff = AllChem.MMFFGetMoleculeForceField( mol, molecule_props, confId=conf_id, ignoreInterfragInteractions=False) ff.Initialize() # minimises a conformer within a mol in place. ff.Minimize(max_iter) return mol def _minimize_by_uff( molecule: Chem.rdchem.Mol, max_iter: int, ) -> Chem.rdchem.Mol: """Minimizes forcefield for conformers using UFF algorithm. Args: molecule: a datastructure containing conformers. max_iter: number of maximum iterations to use when optimising force field. Returns: A copy of a `molecule` containing optimised conformers. """ mol = copy.deepcopy(molecule) conf_ids = range(mol.GetNumConformers()) for conf_id in conf_ids: ff = AllChem.UFFGetMoleculeForceField(mol, confId=conf_id) ff.Initialize() # minimises a conformer within a mol in place. ff.Minimize(max_iter) return mol def _get_symmetry_rotation_matrix(sign: tf.Tensor) -> tf.Tensor: """Returns the 2d/3d matrix for mirror symmetry.""" zero = tf.zeros_like(sign) one = tf.ones_like(sign) # pylint: disable=bad-whitespace,bad-continuation rot = [sign, zero, zero, zero, one, zero, zero, zero, one] # pylint: enable=bad-whitespace,bad-continuation shape = (3, 3) rot = tf.stack(rot, axis=-1) rot = tf.reshape(rot, shape) return rot def _quaternion_to_rotation_matrix(quaternion: tf.Tensor) -> tf.Tensor: """Converts a batch of quaternions to a batch of rotation matrices.""" q0 = quaternion[0] q1 = quaternion[1] q2 = quaternion[2] q3 = quaternion[3] r00 = 2 * (q0 * q0 + q1 * q1) - 1 r01 = 2 * (q1 * q2 - q0 * q3) r02 = 2 * (q1 * q3 + q0 * q2) r10 = 2 * (q1 * q2 + q0 * q3) r11 = 2 * (q0 * q0 + q2 * q2) - 1 r12 = 2 * (q2 * q3 - q0 * q1) r20 = 2 * (q1 * q3 - q0 * q2) r21 = 2 * (q2 * q3 + q0 * q1) r22 = 2 * (q0 * q0 + q3 * q3) - 1 matrix = tf.stack([r00, r01, r02, r10, r11, r12, r20, r21, r22], axis=-1) return tf.reshape(matrix, [3, 3]) def _get_random_rotation_3d() -> tf.Tensor: random_quaternions = tf.random.normal( shape=[4], dtype=tf.float32) random_quaternions /= tf.linalg.norm( random_quaternions, axis=-1, keepdims=True) return _quaternion_to_rotation_matrix(random_quaternions) def _get_random_mirror_symmetry() -> tf.Tensor: random_0_1 = tf.random.uniform( shape=(), minval=0, maxval=2, dtype=tf.int32) random_signs = tf.cast((2 * random_0_1) - 1, tf.float32) return _get_symmetry_rotation_matrix(random_signs)
deepmind-research-master
ogb_lsc/pcq/conformer_utils.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A nice python representation of the underlying FGE state.""" from typing import List, Tuple import numpy as np from fusion_tcv import shape from fusion_tcv import shapes_known from fusion_tcv import tcv_common class StopSignalException(Exception): # pylint: disable=g-bad-exception-name """This is raised if the FGE environment raises the Stop/Alarm signal.""" pass class InvalidSolutionError(RuntimeError): """This is raised if returned solution is invalid.""" pass class UnhandledOctaveError(Exception): """This is raised if some Octave code raises an unhandled error.""" pass class FGEState: """A nice python representation of the underlying FGE State. Given that FGE isn't open source, all of these numbers are made up, and only a sketch of what it could look like. """ def __init__(self, num_plasmas): self._num_plasmas = num_plasmas @property def num_plasmas(self) -> int: return self._num_plasmas # Return 1 for singlet, 2 for droplets. @property def rzip_d(self) -> Tuple[List[float], List[float], List[float]]: """Returns the R, Z, and Ip for each plasma domain.""" if self.num_plasmas == 1: return [0.9], [0], [-120000] else: return [0.9, 0.88], [0.4, -0.4], [-60000, -65000] def get_coil_currents_by_type(self, coil_type) -> np.ndarray: currents = tcv_common.TCV_ACTION_RANGES.new_random_named_array() return currents[coil_type] * tcv_common.ENV_COIL_MAX_CURRENTS[coil_type] / 5 def get_lcfs_points(self, domain: int) -> shape.ShapePoints: del domain # Should be plasma domain specific return shapes_known.SHAPE_70166_0872.canonical().points def get_observation_vector(self) -> np.ndarray: return tcv_common.TCV_MEASUREMENT_RANGES.new_random_named_array().array @property def elongation(self) -> List[float]: return [1.4] * self.num_plasmas @property def triangularity(self) -> List[float]: return [0.25] * self.num_plasmas @property def radius(self) -> List[float]: return [0.23] * self.num_plasmas @property def limit_point_d(self) -> List[shape.Point]: return [shape.Point(tcv_common.INNER_LIMITER_R, 0.2)] * self.num_plasmas @property def is_diverted_d(self) -> List[bool]: return [False] * self.num_plasmas @property def x_points(self) -> shape.ShapePoints: return [] @property def flux(self) -> np.ndarray: """Return the flux at the grid coordinates.""" return np.random.random((len(self.z_coordinates), len(self.r_coordinates))) @property def magnetic_axis_flux_strength(self) -> float: """The magnetic flux at the center of the plasma.""" return 2 @property def lcfs_flux_strength(self) -> float: """The flux at the LCFS.""" return 1 @property def r_coordinates(self) -> np.ndarray: """The radial coordinates of the simulation.""" return np.arange(tcv_common.INNER_LIMITER_R, tcv_common.OUTER_LIMITER_R, tcv_common.LIMITER_WIDTH / 10) # Made up grid resolution. @property def z_coordinates(self): """The vertical coordinates of the simulation.""" return np.arange(-0.75, 0.75, 1.5 / 30) # Made up numbers.
deepmind-research-master
fusion_tcv/fge_state.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transforms from actual/target to rewards.""" import abc import math from typing import List, Optional import dataclasses # Comparison of some of the transforms: # Order is NegExp, SoftPlus, Sigmoid. # Over range of good to bad: # https://www.wolframalpha.com/input/?i=plot+e%5E%28x*ln%280.1%29%29%2C2%2F%281%2Be%5E%28x*ln%2819%29%29%29%2C1%2F%281%2Be%5E%28-+%28-ln%2819%29+-+%28x-1%29*%282*ln%2819%29%29%29%29%29+from+x%3D0+to+2 # When close to good: # https://www.wolframalpha.com/input/?i=plot+e%5E%28x*ln%280.1%29%29%2C2%2F%281%2Be%5E%28x*ln%2819%29%29%29%2C1%2F%281%2Be%5E%28-+%28-ln%2819%29+-+%28x-1%29*%282*ln%2819%29%29%29%29%29+from+x%3D0+to+0.2 class AbstractTransform(abc.ABC): @abc.abstractmethod def __call__(self, errors: List[float]) -> List[float]: """Transforms target errors into rewards.""" @property def outputs(self) -> Optional[int]: return None def clip(value: float, low: float, high: float) -> float: """Clip a value to the range of low - high.""" if math.isnan(value): return value assert low <= high return max(low, min(high, value)) def scale(v: float, a: float, b: float, c: float, d: float) -> float: """Scale a value, v on a line with anchor points a,b to new anchors c,d.""" v01 = (v - a) / (b - a) return c - v01 * (c - d) def logistic(v: float) -> float: """Standard logistic, asymptoting to 0 and 1.""" v = clip(v, -50, 50) # Improve numerical stability. return 1 / (1 + math.exp(-v)) @dataclasses.dataclass(frozen=True) class Equal(AbstractTransform): """Returns 1 if the error is 0 and not_equal_val otherwise.""" not_equal_val: float = 0 def __call__(self, errors: List[float]) -> List[float]: out = [] for err in errors: if math.isnan(err): out.append(err) elif err == 0: out.append(1) else: out.append(self.not_equal_val) return out class Abs(AbstractTransform): """Take the absolue value of the error. Does not guarantee 0-1.""" @staticmethod def __call__(errors: List[float]) -> List[float]: return [abs(err) for err in errors] class Neg(AbstractTransform): """Negate the error. Does not guarantee 0-1.""" @staticmethod def __call__(errors: List[float]) -> List[float]: return [-err for err in errors] @dataclasses.dataclass(frozen=True) class Pow(AbstractTransform): """Return a power of the error. Does not guarantee 0-1.""" pow: float def __call__(self, errors: List[float]) -> List[float]: return [err**self.pow for err in errors] @dataclasses.dataclass(frozen=True) class Log(AbstractTransform): """Return a log of the error. Does not guarantee 0-1.""" eps: float = 1e-4 def __call__(self, errors: List[float]) -> List[float]: return [math.log(err + self.eps) for err in errors] @dataclasses.dataclass(frozen=True) class ClippedLinear(AbstractTransform): """Scales and clips errors, bad to 0, good to 1. If good=0, this is a relu.""" bad: float good: float = 0 def __call__(self, errors: List[float]) -> List[float]: return [clip(scale(err, self.bad, self.good, 0, 1), 0, 1) for err in errors] @dataclasses.dataclass(frozen=True) class SoftPlus(AbstractTransform): """Scales and clips errors, bad to 0.1, good to 1, asymptoting to 0. Based on the lower half of the logistic instead of the standard softplus as we want it to be bounded from 0 to 1, with the good value being exactly 1. Various constants can be chosen to get the softplus to give the desired properties, but this is much simpler. """ bad: float good: float = 0 # Constant to set the sharpness/slope of the softplus. # Default was chosen such that the good/bad have 1 and 0.1 reward: # https://www.wolframalpha.com/input/?i=plot+2%2F%281%2Be%5E%28x*ln%2819%29%29%29+from+x%3D0+to+2 low: float = -math.log(19) # -2.9444389791664403 def __call__(self, errors: List[float]) -> List[float]: return [clip(2 * logistic(scale(e, self.bad, self.good, self.low, 0)), 0, 1) for e in errors] @dataclasses.dataclass(frozen=True) class NegExp(AbstractTransform): """Scales and clips errors, bad to 0.1, good to 1, asymptoting to 0. This scales the reward in an exponential space. This means there is a sharp gradient toward reaching the value of good, flattening out at the value of bad. This can be useful for a reward that gives meaningful signal far away, but still have a sharp gradient near the true target. """ bad: float good: float = 0 # Constant to set the sharpness/slope of the exponential. # Default was chosen such that the good/bad have 1 and 0.1 reward: # https://www.wolframalpha.com/input/?i=plot+e%5E%28x*ln%280.1%29%29+from+x%3D0+to+2 low: float = -math.log(0.1) def __call__(self, errors: List[float]) -> List[float]: return [clip(math.exp(-scale(e, self.bad, self.good, self.low, 0)), 0, 1) for e in errors] @dataclasses.dataclass(frozen=True) class Sigmoid(AbstractTransform): """Scales and clips errors, bad to 0.05, good to 0.95, asymptoting to 0-1.""" good: float bad: float # Constants to set the sharpness/slope of the sigmoid. # Defaults were chosen such that the good/bad have 0.95 and 0.05 reward: # https://www.wolframalpha.com/input/?i=plot+1%2F%281%2Be%5E%28-+%28-ln%2819%29+-+%28x-1%29*%282*ln%2819%29%29%29%29%29+from+x%3D0+to+2 high: float = math.log(19) # +2.9444389791664403 low: float = -math.log(19) # -2.9444389791664403 def __call__(self, errors: List[float]) -> List[float]: return [logistic(scale(err, self.bad, self.good, self.low, self.high)) for err in errors]
deepmind-research-master
fusion_tcv/transforms.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for experiments.""" from absl.testing import absltest from absl.testing import parameterized from dm_env import test_utils from fusion_tcv import agent from fusion_tcv import experiments from fusion_tcv import run_loop class FundamentalCapabilityTest(test_utils.EnvironmentTestMixin, absltest.TestCase): def make_object_under_test(self): return experiments.fundamental_capability() class ElongationTest(test_utils.EnvironmentTestMixin, absltest.TestCase): def make_object_under_test(self): return experiments.elongation() class IterTest(test_utils.EnvironmentTestMixin, absltest.TestCase): def make_object_under_test(self): return experiments.iter() class NegativeTriangularityTest(test_utils.EnvironmentTestMixin, absltest.TestCase): def make_object_under_test(self): return experiments.negative_triangularity() class SnowflakeTest(test_utils.EnvironmentTestMixin, absltest.TestCase): def make_object_under_test(self): return experiments.snowflake() class DropletTest(test_utils.EnvironmentTestMixin, absltest.TestCase): def make_object_under_test(self): return experiments.droplet() class ExperimentsTest(parameterized.TestCase): @parameterized.named_parameters( ("fundamental_capability", experiments.fundamental_capability), ("elongation", experiments.elongation), ("iter", experiments.iter), ("negative_triangularity", experiments.negative_triangularity), ("snowflake", experiments.snowflake), ("droplet", experiments.droplet), ) def test_env(self, env_fn): traj = run_loop.run_loop(env_fn(), agent.ZeroAgent(), max_steps=10) self.assertGreaterEqual(len(traj.reward), 1) if __name__ == "__main__": absltest.main()
deepmind-research-master
fusion_tcv/experiments_test.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Constants and general tooling for TCV plant.""" import collections from typing import Sequence, Text from dm_env import specs import numpy as np from fusion_tcv import named_array DT = 1e-4 # ie 10kHz # Below are general input/output specifications used for controllers that are # run on hardware. This interface corresponds to the so called "KH hybrid" # controller specification that is used in various experiments by EPFL. Hence, # this interface definition contains measurements and actions not used in our # tasks. # Number of actions the environment is exposing. Includes dummy (FAST) action. NUM_ACTIONS = 20 # Number of actuated coils in sim (without the dummy action coil). NUM_COILS_ACTUATED = 19 # Current and voltage limits by coil type # Note this are the limits used in the environments and are different # from the 'machine engineering limits' (as used/exposed by FGE). # We apply a safety factor (=< 1.0) to the engineering limits. CURRENT_SAFETY_FACTOR = 0.8 ENV_COIL_MAX_CURRENTS = collections.OrderedDict( E=7500*CURRENT_SAFETY_FACTOR, F=7500*CURRENT_SAFETY_FACTOR, OH=26000*CURRENT_SAFETY_FACTOR, DUMMY=2000*CURRENT_SAFETY_FACTOR, G=2000*CURRENT_SAFETY_FACTOR) # The g-coil has a saturation voltage that is tunable on a shot-by-shot basis. # There is a deadband, where an action with absolute value of less than 8% of # the saturation voltage is treated as zero. ENV_G_COIL_SATURATION_VOLTAGE = 300 ENV_G_COIL_DEADBAND = ENV_G_COIL_SATURATION_VOLTAGE * 0.08 VOLTAGE_SAFETY_FACTOR = 1.0 ENV_COIL_MAX_VOLTAGE = collections.OrderedDict( E=1400*VOLTAGE_SAFETY_FACTOR, F=2200*VOLTAGE_SAFETY_FACTOR, OH=1400*VOLTAGE_SAFETY_FACTOR, DUMMY=400*VOLTAGE_SAFETY_FACTOR, # This value is also used to clip values for the internal controller, # and also to set the deadband voltage. G=ENV_G_COIL_SATURATION_VOLTAGE) # Ordered actions send by a controller to the TCV. TCV_ACTIONS = ( 'E_001', 'E_002', 'E_003', 'E_004', 'E_005', 'E_006', 'E_007', 'E_008', 'F_001', 'F_002', 'F_003', 'F_004', 'F_005', 'F_006', 'F_007', 'F_008', 'OH_001', 'OH_002', 'DUMMY_001', # GAS, ignored by TCV. 'G_001' # FAST ) TCV_ACTION_INDICES = {n: i for i, n in enumerate(TCV_ACTIONS)} TCV_ACTION_TYPES = collections.OrderedDict( E=8, F=8, OH=2, DUMMY=1, G=1, ) # Map the TCV actions to ranges of indices in the array. TCV_ACTION_RANGES = named_array.NamedRanges(TCV_ACTION_TYPES) # The voltages seem not to be centered at 0, but instead near these values: TCV_ACTION_OFFSETS = { 'E_001': 6.79, 'E_002': -10.40, 'E_003': -1.45, 'E_004': 0.18, 'E_005': 11.36, 'E_006': -0.95, 'E_007': -4.28, 'E_008': 44.22, 'F_001': 38.49, 'F_002': -2.94, 'F_003': 5.58, 'F_004': 1.09, 'F_005': -36.63, 'F_006': -9.18, 'F_007': 5.34, 'F_008': 10.53, 'OH_001': -53.63, 'OH_002': -14.76, } TCV_ACTION_DELAYS = { 'E': [0.0005] * 8, 'F': [0.0005] * 8, 'OH': [0.0005] * 2, 'G': [0.0001], } # Ordered measurements and their dimensions from to the TCV controller specs. TCV_MEASUREMENTS = collections.OrderedDict( clint_vloop=1, # Flux loop 1 clint_rvloop=37, # Difference of flux between loops 2-38 and flux loop 1 bm=38, # Magnetic field probes IE=8, # E-coil currents IF=8, # F-coil currents IOH=2, # OH-coil currents Bdot=20, # Selection of 20 time-derivatives of magnetic field probes (bm). DIOH=1, # OH-coil currents difference: OH(0) - OH(1). FIR_FRINGE=1, # Not used, ignore. IG=1, # G-coil current ONEMM=1, # Not used, ignore vloop=1, # Flux loop 1 derivative IPHI=1, # Current through the Toroidal Field coils. Constant. Ignore. ) NUM_MEASUREMENTS = sum(TCV_MEASUREMENTS.values()) # map the TCV measurements to ranges of indices in the array TCV_MEASUREMENT_RANGES = named_array.NamedRanges(TCV_MEASUREMENTS) # Several of the measurement probes for the rvloops are broken. Add an extra key # that allows us to only grab the usable ones BROKEN_RVLOOP_IDXS = [9, 10, 11] TCV_MEASUREMENT_RANGES.set_range('clint_rvloop_usable', [ idx for i, idx in enumerate(TCV_MEASUREMENT_RANGES['clint_rvloop']) if i not in BROKEN_RVLOOP_IDXS]) TCV_COIL_CURRENTS_INDEX = [ *TCV_MEASUREMENT_RANGES['IE'], *TCV_MEASUREMENT_RANGES['IF'], *TCV_MEASUREMENT_RANGES['IOH'], *TCV_MEASUREMENT_RANGES['IPHI'], # In place of DUMMY. *TCV_MEASUREMENT_RANGES['IG'], ] # References for what we want the agent to accomplish. REF_RANGES = named_array.NamedRanges({ 'R': 2, 'Z': 2, 'Ip': 2, 'kappa': 2, 'delta': 2, 'radius': 2, 'lambda': 2, 'diverted': 2, # bool, must be diverted 'limited': 2, # bool, must be limited 'shape_r': 32, 'shape_z': 32, 'x_points_r': 8, 'x_points_z': 8, 'legs_r': 16, # Use for diverted/snowflake 'legs_z': 16, 'limit_point_r': 2, 'limit_point_z': 2, }) # Environments should use a consistent datatype for interacting with agents. ENVIRONMENT_DATA_TYPE = np.float64 def observation_spec(): """Observation spec for all TCV environments.""" return { 'references': specs.Array( shape=(REF_RANGES.size,), dtype=ENVIRONMENT_DATA_TYPE, name='references'), 'measurements': specs.Array( shape=(TCV_MEASUREMENT_RANGES.size,), dtype=ENVIRONMENT_DATA_TYPE, name='measurements'), 'last_action': specs.Array( shape=(TCV_ACTION_RANGES.size,), dtype=ENVIRONMENT_DATA_TYPE, name='last_action'), } def measurements_to_dict(measurements): """Converts a single measurement vector or a time series to a dict. Args: measurements: A single measurement of size `NUM_MEASUREMENTS` or a time series, where the batch dimension is last, shape: (NUM_MEASUREMENTS, t). Returns: A dict mapping keys `TCV_MEASUREMENTS` to the corresponding measurements. """ assert measurements.shape[0] == NUM_MEASUREMENTS measurements_dict = collections.OrderedDict() index = 0 for key, dim in TCV_MEASUREMENTS.items(): measurements_dict[key] = measurements[index:index + dim, ...] index += dim return measurements_dict def dict_to_measurement(measurement_dict): """Converts a single measurement dict to a vector or time series. Args: measurement_dict: A dict with the measurement keys containing np arrays of size (meas_size, ...). The inner sizes all have to be the same. Returns: An array of size (num_measurements, ...) """ assert len(measurement_dict) == len(TCV_MEASUREMENTS) # Grab the shape of the first array. shape = measurement_dict['clint_vloop'].shape out_shape = list(shape) out_shape[0] = NUM_MEASUREMENTS out_shape = tuple(out_shape) measurements = np.zeros((out_shape)) index = 0 for key, dim in TCV_MEASUREMENTS.items(): dim = TCV_MEASUREMENTS[key] measurements[index:index + dim, ...] = measurement_dict[key] index += dim return measurements def action_spec(): return get_coil_spec(TCV_ACTIONS, ENV_COIL_MAX_VOLTAGE, ENVIRONMENT_DATA_TYPE) def get_coil_spec(coil_names: Sequence[Text], spec_mapping, dtype=ENVIRONMENT_DATA_TYPE) -> specs.BoundedArray: """Maps specs indexed by coil type to coils given their type.""" coil_max, coil_min = [], [] for name in coil_names: # Coils names are <coil_type>_<coil_number> coil_type, _ = name.split('_') coil_max.append(spec_mapping[coil_type]) coil_min.append(-spec_mapping[coil_type]) return specs.BoundedArray( shape=(len(coil_names),), dtype=dtype, minimum=coil_min, maximum=coil_max) INNER_LIMITER_R = 0.62400001 OUTER_LIMITER_R = 1.14179182 LIMITER_WIDTH = OUTER_LIMITER_R - INNER_LIMITER_R LIMITER_RADIUS = LIMITER_WIDTH / 2 VESSEL_CENTER_R = INNER_LIMITER_R + LIMITER_RADIUS
deepmind-research-master
fusion_tcv/tcv_common.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generators for References vector.""" import abc import copy from typing import List, Optional import dataclasses from fusion_tcv import named_array from fusion_tcv import shape as shape_lib from fusion_tcv import tcv_common class AbstractReferenceGenerator(abc.ABC): """Abstract class for generating the reference signal.""" @abc.abstractmethod def reset(self) -> named_array.NamedArray: """Resets the class for a new episode and returns the first reference.""" @abc.abstractmethod def step(self) -> named_array.NamedArray: """Returns the reference signal.""" @dataclasses.dataclass class LinearTransition: reference: named_array.NamedArray # Reference at which to end the transition. transition_steps: int # Number of intermediate steps between the shapes. steady_steps: int # Number of steps in the steady state. class LinearTransitionReferenceGenerator(AbstractReferenceGenerator): """A base class for generating references that are a series of transitions.""" def __init__(self, start_offset: int = 0): self._last_ref = None self._reset_counters() self._start_offset = start_offset @abc.abstractmethod def _next_transition(self) -> LinearTransition: """Override this in the subclass.""" def reset(self) -> named_array.NamedArray: self._last_ref = None self._reset_counters() for _ in range(self._start_offset): self.step() return self.step() def _reset_counters(self): self._steady_step = 0 self._transition_step = 0 self._transition = None def step(self) -> named_array.NamedArray: if (self._transition is None or self._steady_step == self._transition.steady_steps): if self._transition is not None: self._last_ref = self._transition.reference self._reset_counters() self._transition = self._next_transition() # Ensure at least one steady step in middle transitions. # If we would like this to not have to be true, we need to change the # logic below which assumes there is at least one step in the steady # phase. assert self._transition.steady_steps > 0 assert self._transition is not None # to make pytype happy transition_steps = self._transition.transition_steps if self._last_ref is None: # No transition at beginning of episode. transition_steps = 0 if self._transition_step < transition_steps: # In transition phase. self._transition_step += 1 a = self._transition_step / (self._transition.transition_steps + 1) # pytype: disable=attribute-error return self._last_ref.names.named_array( self._last_ref.array * (1 - a) + self._transition.reference.array * a) # pytype: disable=attribute-error else: # In steady phase. self._steady_step += 1 return copy.deepcopy(self._transition.reference) class FixedReferenceGenerator(LinearTransitionReferenceGenerator): """Generates linear transitions from a fixed set of references.""" def __init__(self, transitions: List[LinearTransition], start_offset: int = 0): self._transitions = transitions self._current_transition = 0 super().__init__(start_offset=start_offset) def reset(self) -> named_array.NamedArray: self._current_transition = 0 return super().reset() def _next_transition(self) -> LinearTransition: if self._current_transition == len(self._transitions): # Have gone through all of the transitions. Return the final reference # for a very long time. return LinearTransition(steady_steps=50000, transition_steps=0, reference=self._transitions[-1].reference) self._current_transition += 1 return copy.deepcopy(self._transitions[self._current_transition - 1]) @dataclasses.dataclass class TimedTransition: steady_steps: int # Number of steps to hold the shape. transition_steps: int # Number of steps to transition. @dataclasses.dataclass class ParametrizedShapeTimedTarget: """RZIP condition with a timestep attached.""" shape: shape_lib.Shape timing: TimedTransition class PresetShapePointsReferenceGenerator(FixedReferenceGenerator): """Generates a fixed set of shape points.""" def __init__( self, targets: List[ParametrizedShapeTimedTarget], start_offset: int = 0): if targets[0].timing.transition_steps != 0: raise ValueError("Invalid first timing, transition must be 0, not " f"{targets[0].timing.transition_steps}") transitions = [] for target in targets: transitions.append(LinearTransition( steady_steps=target.timing.steady_steps, transition_steps=target.timing.transition_steps, reference=target.shape.canonical().gen_references())) super().__init__(transitions, start_offset=start_offset) class ShapeFromShot(PresetShapePointsReferenceGenerator): """Generate shapes from EPFL references.""" def __init__( self, time_slices: List[shape_lib.ReferenceTimeSlice], start: Optional[float] = None): """Given a series of time slices, start from time_slice.time==start.""" if start is None: start = time_slices[0].time dt = 1e-4 targets = [] time_slices = shape_lib.canonicalize_reference_series(time_slices) prev = None for i, ref in enumerate(time_slices): assert prev is None or prev.hold < ref.time if ref.time < start: continue if prev is None and start != ref.time: raise ValueError("start must be one of the time slice times.") steady = (max(1, int((ref.hold - ref.time) / dt)) if i < len(time_slices) - 1 else 100000) transition = (0 if prev is None else (int((ref.time - prev.time) / dt) - max(1, int((prev.hold - prev.time) / dt)))) targets.append(ParametrizedShapeTimedTarget( shape=ref.shape, timing=TimedTransition( steady_steps=steady, transition_steps=transition))) prev = ref assert targets super().__init__(targets) @dataclasses.dataclass class RZIpTarget: r: float z: float ip: float def make_symmetric_multidomain_rzip_reference( target: RZIpTarget) -> named_array.NamedArray: """Generate multi-domain rzip references.""" refs = tcv_common.REF_RANGES.new_named_array() refs["R"] = (target.r, target.r) refs["Z"] = (target.z, -target.z) refs["Ip"] = (target.ip, target.ip) return refs
deepmind-research-master
fusion_tcv/ref_gen.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reward targets that return target+actual.""" import abc import math from typing import List, Optional, Sequence, Tuple import dataclasses import numpy as np import scipy from fusion_tcv import fge_state from fusion_tcv import named_array from fusion_tcv import shape from fusion_tcv import tcv_common class TargetError(Exception): """For when a target can't be computed.""" @dataclasses.dataclass(frozen=True) class Target: actual: float target: float @classmethod def invalid(cls): """This target is invalid and should be ignored. Equivalent to weight=0.""" return cls(float("nan"), float("nan")) class AbstractTarget(abc.ABC): """Measure something about the simulation, with a target and actual value.""" @property def name(self) -> str: """Returns a name for the target.""" return self.__class__.__name__ @abc.abstractproperty def outputs(self) -> int: """Return the number of outputs this produces.""" @abc.abstractmethod def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: """Returns a list of targets.""" @dataclasses.dataclass(frozen=True) class AbstractSingleValuePerDomainTarget(AbstractTarget): """Base class for single value per plasma domain targets.""" target: Optional[Sequence[float]] = None indices: List[int] = dataclasses.field(default_factory=lambda: [0]) def __post_init__(self): if self.indices not in ([0], [1], [0, 1]): raise ValueError( f"Invalid indices: {self.indices}, must be [0], [1] or [0, 1].") if self.target and len(self.target) != len(self.indices): raise ValueError("Wrong number of targets.") @property def outputs(self) -> int: return len(self.indices) @property def name(self) -> str: return f"{super().name}: " + ",".join(str(i) for i in self.indices) @dataclasses.dataclass(frozen=True) class R(AbstractSingleValuePerDomainTarget): """Target for R.""" def __call__(self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: r_d, _, _ = state.rzip_d if self.target is None: return [Target(r_d[idx], references["R"][idx]) for idx in self.indices] else: return [Target(r_d[idx], target) for idx, target in zip(self.indices, self.target)] @dataclasses.dataclass(frozen=True) class Z(AbstractSingleValuePerDomainTarget): """Target for Z.""" def __call__(self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: _, z_d, _ = state.rzip_d if self.target is None: return [Target(z_d[idx], references["Z"][idx]) for idx in self.indices] else: return [Target(z_d[idx], target) for idx, target in zip(self.indices, self.target)] @dataclasses.dataclass(frozen=True) class Ip(AbstractSingleValuePerDomainTarget): """Target for Ip.""" def __call__(self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: _, _, ip_d = state.rzip_d if self.target is None: return [Target(ip_d[idx], references["Ip"][idx]) for idx in self.indices] else: return [Target(ip_d[idx], target) for idx, target in zip(self.indices, self.target)] class OHCurrentsClose(AbstractTarget): """Target for keeping OH currents close.""" @property def outputs(self) -> int: return 1 def __call__(self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: oh_coil_currents = state.get_coil_currents_by_type("OH") diff = abs(oh_coil_currents[0] - oh_coil_currents[1]) return [Target(diff, 0)] class EFCurrents(AbstractTarget): """EFCurrents, useful for avoiding stuck coils.""" @property def outputs(self) -> int: return 16 def __call__(self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: currents = np.concatenate([state.get_coil_currents_by_type("E"), state.get_coil_currents_by_type("F")]) return [Target(c, 0) for c in currents] @dataclasses.dataclass(frozen=True) class VoltageOOB(AbstractTarget): """Target for how much the voltages exceed the bounds.""" relative: bool = True @property def outputs(self) -> int: return tcv_common.NUM_ACTIONS def __call__(self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: bounds = tcv_common.action_spec() excess = (np.maximum(bounds.minimum - voltages, 0) + np.maximum(voltages - bounds.maximum, 0)) if self.relative: excess /= (bounds.maximum - bounds.minimum) return [Target(v, 0) for v in excess] @dataclasses.dataclass(frozen=True) class ShapeElongation(AbstractSingleValuePerDomainTarget): """Try to keep the elongation close to the references.""" def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: if self.target is not None: targets = self.target else: targets = references["kappa"][self.indices] return [Target(state.elongation[i], target) for i, target in zip(self.indices, targets)] @dataclasses.dataclass(frozen=True) class ShapeTriangularity(AbstractSingleValuePerDomainTarget): """Try to keep the triangularity close to the references.""" def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: if self.target is not None: targets = self.target else: targets = references["delta"][self.indices] return [Target(state.triangularity[i], target) for i, target in zip(self.indices, targets)] @dataclasses.dataclass(frozen=True) class ShapeRadius(AbstractSingleValuePerDomainTarget): """Try to keep the shape radius close to the references.""" def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: if self.target is not None: targets = self.target else: targets = references["radius"][self.indices] return [Target(state.radius[i], target) for i, target in zip(self.indices, targets)] @dataclasses.dataclass(frozen=True) class AbstractPointsTarget(AbstractTarget): """Base class for shape point targets.""" points: Optional[shape.ShapePoints] = None ref_name: Optional[str] = None num_points: Optional[int] = None def __post_init__(self): if self.points is not None: return elif self.ref_name is None: raise ValueError("Must specify points or ref_name") else: ref_name = f"{self.ref_name}_r" if ref_name not in tcv_common.REF_RANGES: raise ValueError(f"{self.ref_name} is invalid.") elif (self.num_points is not None and self.num_points > tcv_common.REF_RANGES.count(ref_name)): raise ValueError( (f"Requesting more points ({self.num_points}) than {self.ref_name} " "provides.")) @property def outputs(self) -> int: return len(self.points) if self.points is not None else self.num_points def _target_points( self, references: named_array.NamedArray) -> shape.ShapePoints: if self.points is not None: return self.points else: return shape.points_from_references( references, self.ref_name, self.num_points) def splined_lcfs_points( state: fge_state.FGEState, num_points: int, domain: int = 0) -> shape.ShapePoints: """Return a smooth lcfs, cleaning FGE x-point artifacts.""" points = state.get_lcfs_points(domain) x_point = (shape.Point(*state.limit_point_d[domain]) if state.is_diverted_d[domain] else None) if x_point is not None: x_points = [x_point] # Drop points near the x-point due to noise in the shape projection near # the x-point. points = [p for p in points if shape.dist(p, x_point) > 0.1] points.append(x_point) points = shape.sort_by_angle(points) else: x_points = [] return shape.spline_interpolate_points(points, num_points, x_points) @dataclasses.dataclass(frozen=True) class ShapeLCFSDistance(AbstractPointsTarget): """Try to keep the shape close to the references. Check the distance from the target shape points to the smooth LCFS. """ ref_name: str = dataclasses.field(default="shape", init=False) domain: int = dataclasses.field(default=0, init=False) def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: lcfs = splined_lcfs_points(state, 90, self.domain) outputs = [] for p in self._target_points(references): if p.r == 0: # For invalid/changing number of points. outputs.append(Target.invalid()) continue dist = shape.dist_point_to_surface(np.array(lcfs), np.array(p)) outputs.append(Target(dist, 0)) return outputs def flux_at_points(state: fge_state.FGEState, points: np.ndarray) -> np.ndarray: """Return the normalized interpolated flux values at a set of points.""" # Normalized flux such that the LCFS has a value of 1, 0 in the middle, # and bigger than 1 farther out. normalized_flux = ( # (LY.Fx - LY.FA) / (LY.FB - LY.FA) (state.flux - state.magnetic_axis_flux_strength) / (state.lcfs_flux_strength - state.magnetic_axis_flux_strength)).T smooth_flux = scipy.interpolate.RectBivariateSpline( np.squeeze(state.r_coordinates), np.squeeze(state.z_coordinates), normalized_flux) return smooth_flux(points[:, 0], points[:, 1], grid=False) @dataclasses.dataclass(frozen=True) class ShapeNormalizedLCFSFlux(AbstractPointsTarget): """Try to keep the shape close to the references using flux. Check the normalized flux values at points along the target shape. This works in flux space, not linear distance, so may encourage smaller plasmas than the distance based shape rewards. """ ref_name: str = dataclasses.field(default="shape1", init=False) def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: outputs = [] for p in self._target_points(references): if p.r == 0: # For invalid/changing number of points. outputs.append(Target.invalid()) else: outputs.append(Target( flux_at_points(state, np.array([p]))[0], 1)) return outputs @dataclasses.dataclass(frozen=True) class LegsNormalizedFlux(ShapeNormalizedLCFSFlux): """Try to keep the legs references close to the LCFS.""" ref_name: str = dataclasses.field(default="legs", init=False) @dataclasses.dataclass(frozen=True) class AbstractXPointTarget(AbstractPointsTarget): """Base class for x-point targets.""" ref_name: str = dataclasses.field(default="x_points", init=False) @dataclasses.dataclass(frozen=True) class XPointFluxGradient(AbstractXPointTarget): """Keep target points as an X point by attempting 0 flux gradient.""" def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: eps = 0.01 targets = [] for point in self._target_points(references): if point.r == 0: # For invalid/changing number of points. targets.append(Target.invalid()) continue diff_points = np.array([ [point.r - eps, point.z], [point.r + eps, point.z], [point.r, point.z - eps], [point.r, point.z + eps], ]) flux_values = flux_at_points(state, diff_points) diff = ((np.abs(flux_values[0] - flux_values[1]) / (2 * eps)) + (np.abs(flux_values[2] - flux_values[3]) / (2 * eps))) targets.append(Target(diff, 0)) return targets def _dist(p1: shape.Point, p2: shape.Point): return math.hypot(p1.r - p2.r, p1.z - p2.z) def _min_dist(pt: shape.Point, points: shape.ShapePoints, min_dist: float) -> Tuple[Optional[int], float]: index = None for i, point in enumerate(points): dist = _dist(pt, point) if dist < min_dist: index = i min_dist = dist return index, min_dist @dataclasses.dataclass(frozen=True) class XPointDistance(AbstractXPointTarget): """Keep target points as an X point by attempting to minimize distance. This assigns the x-points to targets without replacement. The first target will get the distance to the nearest x-point. The second target will get the closest, but ignoring the one assigned to the first target point. If none are within `max_dist`, then no x-point is assigned and that distance will be returned. It may be worth switching to a fancier algorithm that tries to minimize the total distance between targets and x-points, but that's slower, and we may actually care about some x-points more (eg a diverted point is more important than one farther away). """ max_dist: float = 0.2 def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: x_points = state.x_points targets = [] for target_point in self._target_points(references): if target_point.r == 0: # For invalid/changing number of points. targets.append(Target.invalid()) continue index, min_dist = _min_dist(target_point, x_points, self.max_dist) if index is not None: x_points.pop(index) targets.append(Target(min_dist, 0)) return targets @dataclasses.dataclass(frozen=True) class XPointFar(AbstractXPointTarget): """Keep extraneous x-points far away from the LCFS. Returns the distance from the LCFS to any true x-point that is far from a target x-point. This assigns the x-points to targets without replacement. The first target will get the distance to the nearest x-point. The second target will get the closest, but ignoring the one assigned to the first target point. If none are within `max_dist`, then no x-point is assigned and that distance will be returned. It may be worth switching to a fancier algorithm that tries to minimize the total distance between targets and x-points, but that's slower, and we may actually care about some x-points more (eg a diverted point is more important than one farther away). """ max_dist: float = 0.2 domain: int = 0 diverted: Optional[shape.Diverted] = None def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: if self.diverted is not None: target = self.diverted else: target = shape.Diverted.from_refs(references) if target == shape.Diverted.ANY: return [] # Don't care. x_points = state.x_points # Filter out x-points that are near target x-points. for target_point in self._target_points(references): if target_point.r == 0: # For invalid/changing number of points. continue index, _ = _min_dist(target_point, x_points, self.max_dist) if index is not None: x_points.pop(index) if not x_points: return [Target(100, 0)] # No x-point gives full reward, not weight=0. lcfs = state.get_lcfs_points(self.domain) return [Target(shape.dist_point_to_surface(np.array(lcfs), np.array(p)), 0) for p in x_points] @dataclasses.dataclass(frozen=True) class XPointNormalizedFlux(AbstractXPointTarget): """Keep the actual X points close to the LCFS. Choose the x-points based on their distance to the target x-points. """ max_dist: float = 0.2 diverted: Optional[shape.Diverted] = None def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: if self.diverted is not None: diverted = self.diverted else: diverted = shape.Diverted.from_refs(references) x_points = state.x_points fluxes = list(flux_at_points(state, np.array(x_points).reshape((-1, 2)))) targets = [] # We should probably minimize the overall distance between targets and # x-points, but the algorithm is complicated, so instead be greedy and # assume they're given in priority order, or farther apart than max_dist. for target_point in self._target_points(references): if target_point.r == 0 or diverted != shape.Diverted.DIVERTED: # For invalid/changing number of points. targets.append(Target.invalid()) continue index, _ = _min_dist(target_point, x_points, self.max_dist) if index is not None: targets.append(Target(fluxes[index], 1)) x_points.pop(index) fluxes.pop(index) else: targets.append(Target(0, 1)) return targets @dataclasses.dataclass(frozen=True) class XPointCount(AbstractTarget): """Target for number of x-points. Useful to avoid more than you want.""" target: Optional[int] = None @property def outputs(self) -> int: return 1 def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: if self.target is not None: target = self.target else: target_points = shape.points_from_references( references, "x_points", tcv_common.REF_RANGES.count("x_points_r")) target = sum(1 for p in target_points if p.r != 0) return [Target(len(state.x_points), target)] @dataclasses.dataclass(frozen=True) class Diverted(AbstractTarget): """Target for whether the plasma is diverted by an x-point.""" diverted: Optional[shape.Diverted] = None @property def outputs(self) -> int: return 1 def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: if self.diverted is not None: target = self.diverted else: target = shape.Diverted.from_refs(references) actual = 1 if state.is_diverted_d[0] else 0 if target == shape.Diverted.ANY: return [Target.invalid()] # Don't care. elif target == shape.Diverted.DIVERTED: return [Target(actual, 1)] return [Target(actual, 0)] @dataclasses.dataclass(frozen=True) class LimitPoint(AbstractPointsTarget): """Target for where the plasma is limited, either on the wall or x-point.""" ref_name: str = dataclasses.field(default="limit_point", init=False) num_points: int = dataclasses.field(default=1, init=False) diverted: Optional[shape.Diverted] = None max_dist: float = 1 def __call__( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray) -> List[Target]: if self.diverted is not None: diverted_target = self.diverted else: diverted_target = shape.Diverted.from_refs(references) if diverted_target == shape.Diverted.ANY: return [Target.invalid()] target_point = self._target_points(references)[0] if target_point.r == 0: return [Target.invalid()] limit_point = shape.Point(*state.limit_point_d[0]) dist = np.hypot(*(target_point - limit_point)) is_diverted = state.is_diverted_d[0] if diverted_target == shape.Diverted.DIVERTED: return [Target((dist if is_diverted else self.max_dist), 0)] return [Target((dist if not is_diverted else self.max_dist), 0)]
deepmind-research-master
fusion_tcv/targets.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reward combiners.""" import abc import math from typing import List, Optional, Tuple import dataclasses import numpy as np from scipy import special from fusion_tcv import targets class AbstractCombiner(targets.AbstractTarget): """Combines a set of rewards, possibly weighted.""" @abc.abstractmethod def __call__(self, values: List[float], weights: Optional[List[float]] = None) -> List[float]: """Combines a set of rewards, possibly weighted.""" @property def outputs(self) -> int: """All combiners return exactly one value, even if it's NaN.""" return 1 @staticmethod def _clean_values_weights( values: List[float], weights: Optional[List[float]] = None) -> Tuple[List[float], List[float]]: """Validate the values and weights, and if no weights, return equal.""" if weights is None: weights = [1] * len(values) else: if len(values) != len(weights): raise ValueError("Number of weights don't match values. " f"values: {len(values)}, weights: {len(weights)}") for w in weights: if w < 0: raise ValueError(f"Weights must be >=0: {w}") new_values_weights = [(v, w) for v, w in zip(values, weights) if not np.isnan(v) and w > 0] return tuple(zip(*new_values_weights)) if new_values_weights else ([], []) class Mean(AbstractCombiner): """Take the weighted mean of the values. Ignores NaNs and values with weight 0. """ def __call__(self, values: List[float], weights: Optional[List[float]] = None) -> List[float]: values, weights = self._clean_values_weights(values, weights) if not values: return [float("nan")] return [sum(r * w for r, w in zip(values, weights)) / sum(weights)] def _multiply(values, weights, mean): """Multiplies the values taking care to validate the weights. Defines 0^0 = 1 so a reward with no weight is "off" even if the value is 0. Args: values: The reward values. weights: The reward weights. mean: If true, divides by the sum of the weights (computes the geometric mean). Returns: Product of v^w across the components. """ # If weight and value are both zero, set the value to 1 so that 0^0 = 1. values = [1 if (v == 0 and w == 0) else v for (v, w) in zip(values, weights)] if any(v == 0 for v in values): return [0] den = sum(weights) if mean else 1 return [math.exp(sum(np.log(values) * weights) / den)] class Multiply(AbstractCombiner): """Combine by multiplying the (weighted) values together. This is the same as Geometric mean, but without the n^th root taken at the end. This means doing poorly on several rewards compounds, rather than averages. As such it likely only makes sense after the non-linearities, ie where the values are in the 0-1 range, otherwise it'll cause them to increase. This is even harsher than Min or SmoothMax(-inf). Ignores NaNs and values with weight 0. """ def __call__(self, values: List[float], weights: Optional[List[float]] = None) -> List[float]: values, weights = self._clean_values_weights(values, weights) if not values: return [float("nan")] return _multiply(values, weights, mean=False) class GeometricMean(AbstractCombiner): """Take the weighted geometric mean of the values. Pushes values towards 0, so likely only makes sense after the non-linear transforms. Ignores NaNs and values with weight 0. """ def __call__(self, values: List[float], weights: Optional[List[float]] = None) -> List[float]: values, weights = self._clean_values_weights(values, weights) if not values: return [float("nan")] return _multiply(values, weights, mean=True) class Min(AbstractCombiner): """Take the min of the values. Ignores NaNs and values with weight 0.""" def __call__(self, values: List[float], weights: Optional[List[float]] = None) -> List[float]: values, _ = self._clean_values_weights(values, weights) if not values: return [float("nan")] return [min(values)] class Max(AbstractCombiner): """Take the max of the values. Ignores NaNs and values with weight 0.""" def __call__(self, values: List[float], weights: Optional[List[float]] = None) -> List[float]: values, _ = self._clean_values_weights(values, weights) if not values: return [float("nan")] return [max(values)] @dataclasses.dataclass(frozen=True) class LNorm(AbstractCombiner): """Take the l-norm of the values. Reasonable norm values (assuming normalized): - 1: avg of the values - 2: euclidean distance metric - inf: max value Values in between go between the average and max. As the l-norm goes up, the result gets closer to the max. Normalized means dividing by the max possible distance, such that the units still make sense. This likely only makes sense before the non-linear transforms. SmoothMax is similar but more flexible and understandable. Ignores NaNs and values with weight 0. """ norm: float normalized: bool = True def __call__(self, values: List[float], weights: Optional[List[float]] = None) -> List[float]: values, _ = self._clean_values_weights(values, weights) if not values: return [float("nan")] lnorm = np.linalg.norm(values, ord=self.norm) if self.normalized: lnorm /= np.linalg.norm(np.ones(len(values)), ord=self.norm) return [float(lnorm)] @dataclasses.dataclass(frozen=True) class SmoothMax(AbstractCombiner): """Combines component rewards using a smooth maximum. https://en.wikipedia.org/wiki/Smooth_maximum alpha is the exponent for the smooth max. - alpha -> inf: returns the maximum - alpha == 0: returns the weighted average - alpha -> -inf: returns the minimum alpha in between returns values in between. Since this varies between min, mean and max, it keeps the existing scale. Alpha >= 0 make sense before converting to 0-1, alpha <= 0 make sense after. Ignores NaNs and values with weight 0. """ alpha: float def __call__(self, values: List[float], weights: Optional[List[float]] = None) -> List[float]: values, weights = self._clean_values_weights(values, weights) if not values: return [float("nan")] if math.isinf(self.alpha): return [max(values) if self.alpha > 0 else min(values)] # Compute weights in a numerically-friendly way. log_soft_weights = [np.log(w) + c * self.alpha for w, c in zip(weights, values)] log_soft_weights -= special.logsumexp(log_soft_weights) soft_weights = np.exp(log_soft_weights) return Mean()(values, soft_weights) # weighted mean
deepmind-research-master
fusion_tcv/combiners.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Terminations for the fusion environment.""" import abc from typing import List, Optional import numpy as np from fusion_tcv import fge_state from fusion_tcv import tcv_common class Abstract(abc.ABC): """Abstract reward class.""" @abc.abstractmethod def terminate(self, state: fge_state.FGEState) -> Optional[str]: """Returns a reason if the situation should be considered a termination.""" class CoilCurrentSaturation(Abstract): """Terminates if the coils have saturated their current.""" def terminate(self, state: fge_state.FGEState) -> Optional[str]: # Coil currents are checked by type, independent of the order. for coil_type, max_current in tcv_common.ENV_COIL_MAX_CURRENTS.items(): if coil_type == "DUMMY": continue currents = state.get_coil_currents_by_type(coil_type) if (np.abs(currents) > max_current).any(): return (f"CoilCurrentSaturation: {coil_type}, max: {max_current}, " "real: " + ", ".join(f"{c:.1f}" for c in currents)) return None class OHTooDifferent(Abstract): """Terminates if the coil currents are too far apart from one another.""" def __init__(self, max_diff: float): self._max_diff = max_diff def terminate(self, state: fge_state.FGEState) -> Optional[str]: oh_coil_currents = state.get_coil_currents_by_type("OH") assert len(oh_coil_currents) == 2 oh_current_abs = abs(oh_coil_currents[0] - oh_coil_currents[1]) if oh_current_abs > self._max_diff: return ("OHTooDifferent: currents: " f"({oh_coil_currents[0]:.0f}, {oh_coil_currents[1]:.0f}), " f"diff: {oh_current_abs:.0f}, max: {self._max_diff}") return None class IPTooLow(Abstract): """Terminates if the magnitude of Ip in any component is too low.""" def __init__(self, singlet_threshold: float, droplet_threshold: float): self._singlet_threshold = singlet_threshold self._droplet_threshold = droplet_threshold def terminate(self, state: fge_state.FGEState) -> Optional[str]: _, _, ip_d = state.rzip_d if len(ip_d) == 1: if ip_d[0] > self._singlet_threshold: # Sign due to negative Ip. return f"IPTooLow: Singlet, {ip_d[0]:.0f}" return None else: if max(ip_d) > self._droplet_threshold: # Sign due to negative Ip. return f"IPTooLow: Components: {ip_d[0]:.0f}, {ip_d[1]:.0f}" return None class AnyTermination(Abstract): """Terminates if any of conditions are met.""" def __init__(self, terminators: List[Abstract]): self._terminators = terminators def terminate(self, state: fge_state.FGEState) -> Optional[str]: for terminator in self._terminators: term = terminator.terminate(state) if term: return term return None CURRENT_OH_IP = AnyTermination([ CoilCurrentSaturation(), OHTooDifferent(max_diff=4000), IPTooLow(singlet_threshold=-60000, droplet_threshold=-25000), ])
deepmind-research-master
fusion_tcv/terminations.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """References used in the experiments.""" from fusion_tcv import ref_gen from fusion_tcv import shape from fusion_tcv import shapes_known from fusion_tcv import tcv_common # pylint: disable=bad-whitespace # Used in TCV#70915 def fundamental_capability() -> ref_gen.AbstractReferenceGenerator: return ref_gen.ShapeFromShot([ # Start at the handover state and hold for ~50ms. shape.ReferenceTimeSlice( time=0.0872, hold=0.15, shape=shape.Shape( ip=-110000, params=shapes_known.SHAPE_70166_0872.params, points=shapes_known.SHAPE_70166_0872.points, limit_point=shapes_known.SHAPE_70166_0872.limit_point, diverted=shape.Diverted.LIMITED, ), ), # Ramp the Ip over 50ms then hold for 50ms. shape.ReferenceTimeSlice( time=0.2, hold=0.25, shape=shape.Shape( ip=-150000, params=shape.ParametrizedShape( r0=0.8796, z0=0.2339, kappa=1.2441, delta=0.2567, radius=0.2390, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6299, 0.1413), shape.Point( 0.6481, 0.0577), shape.Point( 0.6804, -0.0087), shape.Point( 0.7286, -0.0513), shape.Point( 0.7931, -0.0660), shape.Point( 0.8709, -0.0513), shape.Point( 0.9543, -0.0087), shape.Point( 1.0304, 0.0577), shape.Point( 1.0844, 0.1413), shape.Point( 1.1040, 0.2340), shape.Point( 1.0844, 0.3267), shape.Point( 1.0304, 0.4103), shape.Point( 0.9543, 0.4767), shape.Point( 0.8709, 0.5193), shape.Point( 0.7931, 0.5340), shape.Point( 0.7286, 0.5193), shape.Point( 0.6804, 0.4767), shape.Point( 0.6481, 0.4103), shape.Point( 0.6299, 0.3267), shape.Point( 0.6240, 0.2340), ], limit_point=shape.Point( 0.6240, 0.2340), diverted=shape.Diverted.LIMITED, ), ), # Transform the shape to the DM handover shape and hold for 50ms. shape.ReferenceTimeSlice( time=0.3, hold=0.35, shape=shape.Shape( ip=-150000, params=shape.ParametrizedShape( r0=0.8822, z0=0.2340, kappa=1.4396, delta=0.2760, radius=0.2388, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6299, 0.1265), shape.Point( 0.6481, 0.0295), shape.Point( 0.6804, -0.0475), shape.Point( 0.7286, -0.0970), shape.Point( 0.7931, -0.1140), shape.Point( 0.8709, -0.0970), shape.Point( 0.9543, -0.0475), shape.Point( 1.0304, 0.0295), shape.Point( 1.0844, 0.1265), shape.Point( 1.1040, 0.2340), shape.Point( 1.0844, 0.3415), shape.Point( 1.0304, 0.4385), shape.Point( 0.9543, 0.5155), shape.Point( 0.8709, 0.5650), shape.Point( 0.7931, 0.5820), shape.Point( 0.7286, 0.5650), shape.Point( 0.6804, 0.5155), shape.Point( 0.6481, 0.4385), shape.Point( 0.6299, 0.3415), shape.Point( 0.6240, 0.2340), ], limit_point=shape.Point( 0.6240, 0.2340), diverted=shape.Diverted.LIMITED, ), ), # Shift down by 20cm and hold for 50ms. shape.ReferenceTimeSlice( time=0.4, hold=0.45, shape=shape.Shape( ip=-150000, params=shape.ParametrizedShape( r0=0.8822, z0=0.0340, kappa=1.4396, delta=0.2760, radius=0.2388, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6299, -0.0735), shape.Point( 0.6481, -0.1705), shape.Point( 0.6804, -0.2475), shape.Point( 0.7286, -0.2970), shape.Point( 0.7931, -0.3140), shape.Point( 0.8709, -0.2970), shape.Point( 0.9543, -0.2475), shape.Point( 1.0304, -0.1705), shape.Point( 1.0844, -0.0735), shape.Point( 1.1040, 0.0340), shape.Point( 1.0844, 0.1415), shape.Point( 1.0304, 0.2385), shape.Point( 0.9543, 0.3155), shape.Point( 0.8709, 0.3650), shape.Point( 0.7931, 0.3820), shape.Point( 0.7286, 0.3650), shape.Point( 0.6804, 0.3155), shape.Point( 0.6481, 0.2385), shape.Point( 0.6299, 0.1415), shape.Point( 0.6240, 0.0340), ], limit_point=shape.Point( 0.6240, 0.0340), diverted=shape.Diverted.LIMITED, ), ), # Add an X-point and allow to be ANY. shape.ReferenceTimeSlice( time=0.451, shape=shape.Shape( ip=-150000, params=shape.ParametrizedShape( r0=0.8822, z0=0.0340, kappa=1.4396, delta=0.2760, radius=0.2388, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6299, -0.0735), shape.Point( 0.6481, -0.1705), shape.Point( 0.6804, -0.2475), shape.Point( 0.7286, -0.2970), shape.Point( 0.7931, -0.3140), shape.Point( 0.8709, -0.2970), shape.Point( 0.9543, -0.2475), shape.Point( 1.0304, -0.1705), shape.Point( 1.0844, -0.0735), shape.Point( 1.1040, 0.0340), shape.Point( 1.0844, 0.1415), shape.Point( 1.0304, 0.2385), shape.Point( 0.9543, 0.3155), shape.Point( 0.8709, 0.3650), shape.Point( 0.7931, 0.3820), shape.Point( 0.7286, 0.3650), shape.Point( 0.6804, 0.3155), shape.Point( 0.6481, 0.2385), shape.Point( 0.6299, 0.1415), shape.Point( 0.6240, 0.0340), ], x_points=[shape.Point( 0.6240, -0.7)], diverted=shape.Diverted.ANY, ), ), # Make diverted and hold for 350ms. shape.ReferenceTimeSlice( time=0.50, hold=0.85, shape=shape.Shape( # based on 70519 @ 0.840 ip=-150000, params=shape.ParametrizedShape( r0=0.8618, z0=0.0130, kappa=1.5585, delta=0.3175, radius=0.232, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ shape.Point(0.8286, -0.3612), shape.Point(0.7722, -0.3807), shape.Point(0.7512, -0.3375), shape.Point(0.7246, -0.2900), shape.Point(0.6995, -0.2425), shape.Point(0.6783, -0.1950), shape.Point(0.6627, -0.1475), shape.Point(0.6531, -0.1000), shape.Point(0.6469, -0.0288), shape.Point(0.6461, 0.0425), shape.Point(0.6509, 0.1137), shape.Point(0.6594, 0.1612), shape.Point(0.6738, 0.2087), shape.Point(0.6970, 0.2562), shape.Point(0.7327, 0.2991), shape.Point(0.7722, 0.3243), shape.Point(0.8117, 0.3348), shape.Point(0.8709, 0.3290), shape.Point(0.9104, 0.3143), shape.Point(0.9499, 0.2912), shape.Point(0.9893, 0.2597), shape.Point(1.0164, 0.2325), shape.Point(1.0486, 0.1932), shape.Point(1.0696, 0.1612), shape.Point(1.0938, 0.1137), shape.Point(1.1084, 0.0662), shape.Point(1.1078, -0.0050), shape.Point(1.0937, -0.0525), shape.Point(1.0721, -0.1000), shape.Point(1.0486, -0.1416), shape.Point(1.0288, -0.1720), shape.Point(0.9935, -0.2187), shape.Point(0.9696, -0.2464), shape.Point(0.9301, -0.2856), shape.Point(0.8961, -0.3137), shape.Point(0.8641, -0.3375), ], x_points=[shape.Point(0.7722, -0.3807)], limit_point=shape.Point(0.7722, -0.3807), diverted=shape.Diverted.DIVERTED, ), ), # Remove the X-point and let be ANY. shape.ReferenceTimeSlice( # based on 70519 @ 0.840 time=0.851, shape=shape.Shape( ip=-150000, params=shape.ParametrizedShape( r0=0.8618, z0=0.0130, kappa=1.5585, delta=0.3175, radius=0.232, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ shape.Point(0.8286, -0.3612), shape.Point(0.7722, -0.3807), shape.Point(0.7512, -0.3375), shape.Point(0.7246, -0.2900), shape.Point(0.6995, -0.2425), shape.Point(0.6783, -0.1950), shape.Point(0.6627, -0.1475), shape.Point(0.6531, -0.1000), shape.Point(0.6469, -0.0288), shape.Point(0.6461, 0.0425), shape.Point(0.6509, 0.1137), shape.Point(0.6594, 0.1612), shape.Point(0.6738, 0.2087), shape.Point(0.6970, 0.2562), shape.Point(0.7327, 0.2991), shape.Point(0.7722, 0.3243), shape.Point(0.8117, 0.3348), shape.Point(0.8709, 0.3290), shape.Point(0.9104, 0.3143), shape.Point(0.9499, 0.2912), shape.Point(0.9893, 0.2597), shape.Point(1.0164, 0.2325), shape.Point(1.0486, 0.1932), shape.Point(1.0696, 0.1612), shape.Point(1.0938, 0.1137), shape.Point(1.1084, 0.0662), shape.Point(1.1078, -0.0050), shape.Point(1.0937, -0.0525), shape.Point(1.0721, -0.1000), shape.Point(1.0486, -0.1416), shape.Point(1.0288, -0.1720), shape.Point(0.9935, -0.2187), shape.Point(0.9696, -0.2464), shape.Point(0.9301, -0.2856), shape.Point(0.8961, -0.3137), shape.Point(0.8641, -0.3375), ], diverted=shape.Diverted.ANY, ), ), # Shift back to round shape. shape.ReferenceTimeSlice( time=0.90, shape=shape.Shape( ip=-150000, params=shapes_known.SHAPE_70166_0872.params, points=shapes_known.SHAPE_70166_0872.points, limit_point=shapes_known.SHAPE_70166_0872.limit_point, diverted=shape.Diverted.LIMITED, ), ), # Ramp the Ip down. shape.ReferenceTimeSlice( time=1.00, shape=shape.Shape( ip=-70000, params=shapes_known.SHAPE_70166_0872.params, points=shapes_known.SHAPE_70166_0872.points, limit_point=shapes_known.SHAPE_70166_0872.limit_point, diverted=shape.Diverted.LIMITED, ), ), ]) # Used in TCV#70920 def elongation() -> ref_gen.AbstractReferenceGenerator: return ref_gen.ShapeFromShot([ shape.ReferenceTimeSlice( time=0.45, hold=0.475, shape=shape.Shape( params=shapes_known.SHAPE_70166_0450.params, diverted=shapes_known.SHAPE_70166_0450.diverted, limit_point=shape.Point(tcv_common.INNER_LIMITER_R, 0.25), ip=shapes_known.SHAPE_70166_0450.ip) ), shape.ReferenceTimeSlice( time=0.55, shape=shape.Shape( params=shape.ParametrizedShape( r0=0.875, z0=0.2, kappa=1.9, delta=0.3, radius=0.235, lambda_=0, side=shape.ShapeSide.LEFT), ip=-190000, limit_point=shape.Point(tcv_common.INNER_LIMITER_R, 0.2), diverted=shape.Diverted.LIMITED) ), ]) # Used in TCV#70457 def negative_triangularity() -> ref_gen.AbstractReferenceGenerator: return ref_gen.ShapeFromShot([ shape.ReferenceTimeSlice( time=0.45, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.89, z0=0.15, kappa=1.4, delta=-0.8, radius=0.25, lambda_=0, side=shape.ShapeSide.LEFT), x_points=[ shape.Point(tcv_common.OUTER_LIMITER_R - 0.03, 0.50), shape.Point(tcv_common.OUTER_LIMITER_R - 0.03, -0.2), ], diverted=shape.Diverted.DIVERTED, ), ), ]) # Used in TCV#70755 def snowflake() -> ref_gen.AbstractReferenceGenerator: return ref_gen.ShapeFromShot([ shape.ReferenceTimeSlice( time=0.0872, shape=shape.Shape( ip=-110000, params=shapes_known.SHAPE_70166_0872.params, points=shapes_known.SHAPE_70166_0872.points, limit_point=shapes_known.SHAPE_70166_0872.limit_point, diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=0.15, # 0.2680, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.8713, z0=0.0662, kappa=1.6059, delta=0.3814, radius=0.2378, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6270, 0.0660), shape.Point( 0.6290, -0.0840), shape.Point( 0.6530, -0.2170), shape.Point( 0.7500, -0.3114), shape.Point( 0.9260, -0.2270), shape.Point( 1.0530, -0.0930), shape.Point( 1.1020, 0.0660), shape.Point( 1.0530, 0.2250), shape.Point( 0.9460, 0.3590), shape.Point( 0.8100, 0.4340), shape.Point( 0.7000, 0.4240), shape.Point( 0.6500, 0.3490), shape.Point( 0.6290, 0.2160), ], x_points=[ shape.Point( 0.7000, -0.4700), ], diverted=shape.Diverted.ANY, ), ), shape.ReferenceTimeSlice( time=0.2, # 0.4280, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.8884, z0=0.0319, kappa=1.6229, delta=0.3875, radius=0.2261, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6550, 0.0080), shape.Point( 0.6650, -0.1260), shape.Point( 0.6840, -0.2600), shape.Point( 0.7600, -0.3750), shape.Point( 0.9400, -0.2790), shape.Point( 1.0500, -0.1450), shape.Point( 1.1060, 0.0080), shape.Point( 1.0760, 0.1620), shape.Point( 0.9780, 0.2960), shape.Point( 0.8410, 0.3530), shape.Point( 0.7300, 0.3380), shape.Point( 0.6750, 0.2670), shape.Point( 0.6550, 0.1430), ], x_points=[ shape.Point( 0.7600, -0.3750), ], limit_point=shape.Point( 0.7600, -0.3750), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=0.25, # 0.5000, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.8886, z0=0.0044, kappa=1.5419, delta=0.2430, radius=0.2137, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 14 points shape.Point( 0.6780, -0.1200), shape.Point( 0.7200, -0.2360), shape.Point( 0.7840, -0.3754), shape.Point( 0.9090, -0.3040), shape.Point( 1.0040, -0.2110), shape.Point( 1.0660, -0.1110), shape.Point( 1.0950, -0.0030), shape.Point( 1.0800, 0.1070), shape.Point( 1.0210, 0.2070), shape.Point( 0.9250, 0.2740), shape.Point( 0.8090, 0.2730), shape.Point( 0.7170, 0.2040), shape.Point( 0.6660, 0.1010), shape.Point( 0.6570, -0.0100), ], x_points=[ shape.Point( 0.7840, -0.3754), shape.Point( 0.8600, -0.7500), ], legs=[ shape.Point( 0.8220, -0.5627), ], limit_point=shape.Point( 0.7840, -0.3754), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=0.4, # 0.6000, hold=0.8, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.8886, z0=0.0044, kappa=1.5419, delta=0.2430, radius=0.2137, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 14 points shape.Point( 0.6780, -0.1200), shape.Point( 0.7200, -0.2360), shape.Point( 0.7840, -0.3754), shape.Point( 0.9090, -0.3040), shape.Point( 1.0040, -0.2110), shape.Point( 1.0660, -0.1110), shape.Point( 1.0950, -0.0030), shape.Point( 1.0800, 0.1070), shape.Point( 1.0210, 0.2070), shape.Point( 0.9250, 0.2740), shape.Point( 0.8090, 0.2730), shape.Point( 0.7170, 0.2040), shape.Point( 0.6660, 0.1010), shape.Point( 0.6570, -0.0100), ], x_points=[ shape.Point( 0.7840, -0.3754), shape.Point( 0.8028, -0.4153), ], legs=[ shape.Point( 0.7934, -0.3953), ], limit_point=shape.Point( 0.7840, -0.3754), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=0.9, # 0.5000, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.8886, z0=0.0044, kappa=1.5419, delta=0.2430, radius=0.2137, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 14 points shape.Point( 0.6780, -0.1200), shape.Point( 0.7200, -0.2360), shape.Point( 0.7840, -0.3754), shape.Point( 0.9090, -0.3040), shape.Point( 1.0040, -0.2110), shape.Point( 1.0660, -0.1110), shape.Point( 1.0950, -0.0030), shape.Point( 1.0800, 0.1070), shape.Point( 1.0210, 0.2070), shape.Point( 0.9250, 0.2740), shape.Point( 0.8090, 0.2730), shape.Point( 0.7170, 0.2040), shape.Point( 0.6660, 0.1010), shape.Point( 0.6570, -0.0100), ], x_points=[ shape.Point( 0.7840, -0.3754), shape.Point( 0.8600, -0.7500), ], legs=[ shape.Point( 0.8220, -0.5627), ], limit_point=shape.Point( 0.7840, -0.3754), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=0.95, # 0.4280, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.8884, z0=0.0319, kappa=1.6229, delta=0.3875, radius=0.2261, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6550, 0.0080), shape.Point( 0.6650, -0.1260), shape.Point( 0.6840, -0.2600), shape.Point( 0.7600, -0.3750), shape.Point( 0.9400, -0.2790), shape.Point( 1.0500, -0.1450), shape.Point( 1.1060, 0.0080), shape.Point( 1.0760, 0.1620), shape.Point( 0.9780, 0.2960), shape.Point( 0.8410, 0.3530), shape.Point( 0.7300, 0.3380), shape.Point( 0.6750, 0.2670), shape.Point( 0.6550, 0.1430), ], x_points=[ shape.Point( 0.7600, -0.3750), ], diverted=shape.Diverted.ANY, ), ), shape.ReferenceTimeSlice( time=1.0, # 0.2680, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.8713, z0=0.0662, kappa=1.6059, delta=0.3814, radius=0.2378, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6270, 0.0660), shape.Point( 0.6290, -0.0840), shape.Point( 0.6530, -0.2170), shape.Point( 0.7500, -0.3114), shape.Point( 0.9260, -0.2270), shape.Point( 1.0530, -0.0930), shape.Point( 1.1020, 0.0660), shape.Point( 1.0530, 0.2250), shape.Point( 0.9460, 0.3590), shape.Point( 0.8100, 0.4340), shape.Point( 0.7000, 0.4240), shape.Point( 0.6500, 0.3490), shape.Point( 0.6290, 0.2160), ], x_points=[ shape.Point( 0.7000, -0.4700), ], limit_point=shape.Point( 0.6240, 0.0660), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=1.05, # 0.0872, shape=shape.Shape( ip=-70000, params=shape.ParametrizedShape( r0=0.8703, z0=0.0547, kappa=1.2459, delta=0.2431, radius=0.2395, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6299, -0.0377), shape.Point( 0.6481, -0.1213), shape.Point( 0.6804, -0.1877), shape.Point( 0.7286, -0.2303), shape.Point( 0.7931, -0.2450), shape.Point( 0.8709, -0.2303), shape.Point( 0.9543, -0.1877), shape.Point( 1.0304, -0.1213), shape.Point( 1.0844, -0.0377), shape.Point( 1.1040, 0.0550), shape.Point( 1.0844, 0.1477), shape.Point( 1.0304, 0.2313), shape.Point( 0.9543, 0.2977), shape.Point( 0.8709, 0.3403), shape.Point( 0.7931, 0.3550), shape.Point( 0.7286, 0.3403), shape.Point( 0.6804, 0.2977), shape.Point( 0.6481, 0.2313), shape.Point( 0.6299, 0.1477), shape.Point( 0.6240, 0.0550), ], limit_point=shape.Point( 0.6240, 0.0550), diverted=shape.Diverted.LIMITED, ), ), ]) # Used in TCV#70600 def iter() -> ref_gen.AbstractReferenceGenerator: # pylint: disable=redefined-builtin return ref_gen.ShapeFromShot([ # Taken from TCV#70392. shape.ReferenceTimeSlice( time=0.0872, shape=shape.Shape( ip=-135000, params=shape.ParametrizedShape( r0=0.8831, z0=0.0501, kappa=1.2500, delta=0.1083, radius=0.2400, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6330, -0.0427), shape.Point( 0.6596, -0.1263), shape.Point( 0.7033, -0.1927), shape.Point( 0.7623, -0.2353), shape.Point( 0.8329, -0.2500), shape.Point( 0.9094, -0.2353), shape.Point( 0.9839, -0.1927), shape.Point( 1.0468, -0.1263), shape.Point( 1.0891, -0.0427), shape.Point( 1.1040, 0.0500), shape.Point( 1.0891, 0.1427), shape.Point( 1.0468, 0.2263), shape.Point( 0.9839, 0.2927), shape.Point( 0.9094, 0.3353), shape.Point( 0.8329, 0.3500), shape.Point( 0.7623, 0.3353), shape.Point( 0.7033, 0.2927), shape.Point( 0.6596, 0.2263), shape.Point( 0.6330, 0.1427), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=0.1328, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8885, z0=0.0503, kappa=1.4887, delta=0.2421, radius=0.2448, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6305, -0.0636), shape.Point( 0.6505, -0.1660), shape.Point( 0.6855, -0.2473), shape.Point( 0.7366, -0.2995), shape.Point( 0.8037, -0.3175), shape.Point( 0.8830, -0.2995), shape.Point( 0.9666, -0.2473), shape.Point( 1.0420, -0.1660), shape.Point( 1.0949, -0.0636), shape.Point( 1.1140, 0.0500), shape.Point( 1.0949, 0.1636), shape.Point( 1.0420, 0.2660), shape.Point( 0.9666, 0.3473), shape.Point( 0.8830, 0.3995), shape.Point( 0.8037, 0.4175), shape.Point( 0.7366, 0.3995), shape.Point( 0.6855, 0.3473), shape.Point( 0.6505, 0.2660), shape.Point( 0.6305, 0.1636), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=0.1880, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8858, z0=0.0502, kappa=1.4899, delta=0.3813, radius=0.2443, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6284, -0.0636), shape.Point( 0.6427, -0.1660), shape.Point( 0.6694, -0.2473), shape.Point( 0.7122, -0.2995), shape.Point( 0.7736, -0.3175), shape.Point( 0.8528, -0.2995), shape.Point( 0.9425, -0.2473), shape.Point( 1.0282, -0.1660), shape.Point( 1.0909, -0.0636), shape.Point( 1.1140, 0.0500), shape.Point( 1.0909, 0.1636), shape.Point( 1.0282, 0.2660), shape.Point( 0.9425, 0.3473), shape.Point( 0.8528, 0.3995), shape.Point( 0.7736, 0.4175), shape.Point( 0.7122, 0.3995), shape.Point( 0.6694, 0.3473), shape.Point( 0.6427, 0.2660), shape.Point( 0.6284, 0.1636), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=0.2280, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8820, z0=0.0501, kappa=1.4817, delta=0.4028, radius=0.2386, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 14 points shape.Point( 0.6317, -0.1062), shape.Point( 0.6589, -0.2315), shape.Point( 0.7163, -0.3010), shape.Point( 0.8130, -0.3010), shape.Point( 0.9398, -0.2315), shape.Point( 1.0559, -0.1062), shape.Point( 1.1040, 0.0500), shape.Point( 1.0559, 0.2062), shape.Point( 0.9398, 0.3315), shape.Point( 0.8130, 0.4010), shape.Point( 0.7163, 0.4010), shape.Point( 0.6589, 0.3315), shape.Point( 0.6317, 0.2062), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=0.2680, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8780, z0=0.0664, kappa=1.6140, delta=0.3943, radius=0.2376, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6270, 0.0660), shape.Point( 0.6290, -0.0840), shape.Point( 0.6530, -0.2170), shape.Point( 0.7500, -0.3114), shape.Point( 0.9260, -0.2270), shape.Point( 1.0530, -0.0930), shape.Point( 1.1020, 0.0660), shape.Point( 1.0530, 0.2250), shape.Point( 0.9460, 0.3590), shape.Point( 0.8100, 0.4340), shape.Point( 0.7000, 0.4240), shape.Point( 0.6500, 0.3490), shape.Point( 0.6290, 0.2160), ], x_points=[ shape.Point( 0.7000, -0.4700), ], limit_point=shape.Point( 0.6240, 0.0660), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=0.3080, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8670, z0=0.0394, kappa=1.5594, delta=0.2588, radius=0.2252, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6250, 0.0404), shape.Point( 0.6250, -0.0868), shape.Point( 0.6550, -0.2151), shape.Point( 0.7500, -0.3244), shape.Point( 0.9290, -0.2331), shape.Point( 1.0460, -0.1058), shape.Point( 1.0760, 0.0404), shape.Point( 1.0460, 0.1867), shape.Point( 0.9480, 0.3141), shape.Point( 0.8110, 0.3777), shape.Point( 0.7000, 0.3692), shape.Point( 0.6450, 0.2960), shape.Point( 0.6250, 0.1677), ], x_points=[ shape.Point( 0.7200, -0.4355), ], limit_point=shape.Point( 0.6240, 0.0404), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=0.3480, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8771, z0=0.0286, kappa=1.6824, delta=0.4348, radius=0.2310, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6350, 0.0263), shape.Point( 0.6350, -0.1045), shape.Point( 0.6550, -0.2344), shape.Point( 0.7400, -0.3462), shape.Point( 0.9390, -0.2528), shape.Point( 1.0560, -0.1229), shape.Point( 1.0860, 0.0263), shape.Point( 1.0560, 0.1745), shape.Point( 0.9580, 0.3054), shape.Point( 0.8210, 0.3703), shape.Point( 0.7100, 0.3606), shape.Point( 0.6550, 0.2860), shape.Point( 0.6350, 0.1561), ], x_points=[ shape.Point( 0.7300, -0.3943), ], limit_point=shape.Point( 0.6240, 0.0260), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=0.3880, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8878, z0=0.0130, kappa=1.6511, delta=0.4385, radius=0.2291, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6450, 0.0060), shape.Point( 0.6500, -0.1230), shape.Point( 0.6650, -0.2540), shape.Point( 0.7500, -0.3660), shape.Point( 0.9490, -0.2730), shape.Point( 1.0660, -0.1420), shape.Point( 1.0960, 0.0060), shape.Point( 1.0660, 0.1560), shape.Point( 0.9680, 0.2860), shape.Point( 0.8310, 0.3510), shape.Point( 0.7200, 0.3430), shape.Point( 0.6650, 0.2680), shape.Point( 0.6450, 0.1370), ], x_points=[ shape.Point( 0.7400, -0.3960), ], diverted=shape.Diverted.ANY, ), ), shape.ReferenceTimeSlice( time=0.5000, shape=shape.Shape( ip=-175000, params=shape.ParametrizedShape( r0=0.9069, z0=0.0099, kappa=1.6399, delta=0.4400, radius=0.2255, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6690, -0.1340), shape.Point( 0.6880, -0.2690), shape.Point( 0.7377, -0.3840), shape.Point( 0.8150, -0.3650), shape.Point( 0.9600, -0.2880), shape.Point( 1.0760, -0.1540), shape.Point( 1.1060, 0.0000), shape.Point( 1.0760, 0.1540), shape.Point( 0.9790, 0.2880), shape.Point( 0.8440, 0.3550), shape.Point( 0.6890, 0.2690), shape.Point( 0.6600, 0.1340), shape.Point( 0.6600, 0.0000), ], x_points=[ shape.Point( 0.7377, -0.3840), ], legs=[ shape.Point( 0.7930, -0.5700), ], limit_point=shape.Point( 0.7377, -0.3840), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=0.6200, shape=shape.Shape( ip=-200000, params=shape.ParametrizedShape( r0=0.9044, z0=0.0142, kappa=1.7484, delta=0.4440, radius=0.2257, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6690, -0.1490), shape.Point( 0.7080, -0.2840), # concave: 181.6 degrees shape.Point( 0.7377, -0.3990), shape.Point( 0.8150, -0.3800), shape.Point( 0.9600, -0.3030), shape.Point( 1.0760, -0.1690), shape.Point( 1.1060, -0.0066), shape.Point( 1.0760, 0.1659), shape.Point( 0.9790, 0.3160), shape.Point( 0.8440, 0.3910), shape.Point( 0.6890, 0.2947), shape.Point( 0.6600, 0.1435), shape.Point( 0.6600, -0.0066), ], x_points=[ shape.Point( 0.7377, -0.3990), ], legs=[ shape.Point( 0.7930, -0.5850), ], limit_point=shape.Point( 0.7377, -0.3990), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=0.9000, shape=shape.Shape( ip=-240000, params=shape.ParametrizedShape( r0=0.9010, z0=0.0152, kappa=1.7482, delta=0.4427, radius=0.2257, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6690, -0.1490), shape.Point( 0.7080, -0.2840), # concave: 181.6 degrees shape.Point( 0.7377, -0.3990), shape.Point( 0.8150, -0.3800), shape.Point( 0.9600, -0.3030), shape.Point( 1.0760, -0.1690), shape.Point( 1.1060, -0.0066), shape.Point( 1.0760, 0.1659), shape.Point( 0.9790, 0.3160), shape.Point( 0.8440, 0.3910), shape.Point( 0.6890, 0.2947), shape.Point( 0.6600, 0.1435), shape.Point( 0.6600, -0.0066), ], x_points=[ shape.Point( 0.7377, -0.3990), ], legs=[ shape.Point( 0.7930, -0.5850), ], limit_point=shape.Point( 0.7377, -0.3990), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=0.9500, shape=shape.Shape( ip=-245000, params=shape.ParametrizedShape( r0=0.8985, z0=0.0173, kappa=1.7213, delta=0.4905, radius=0.2261, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 14 points shape.Point( 0.6690, -0.1490), shape.Point( 0.7200, -0.2840), shape.Point( 0.7600, -0.3890), shape.Point( 0.8500, -0.3700), shape.Point( 0.9600, -0.2850), shape.Point( 1.0760, -0.1590), shape.Point( 1.1060, 0.0030), shape.Point( 1.0660, 0.1760), shape.Point( 1.0000, 0.2650), shape.Point( 0.9200, 0.3360), shape.Point( 0.7500, 0.3850), shape.Point( 0.6650, 0.2850), shape.Point( 0.6600, 0.1430), shape.Point( 0.6600, -0.0070), ], x_points=[ shape.Point( 0.7600, -0.3890), ], legs=[ shape.Point( 0.8430, -0.5850), ], limit_point=shape.Point( 0.7600, -0.3890), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=1.1500, shape=shape.Shape( ip=-260000, params=shape.ParametrizedShape( r0=0.8970, z0=0.0180, kappa=1.7142, delta=0.4877, radius=0.2262, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 14 points shape.Point( 0.6690, -0.1490), shape.Point( 0.7200, -0.2840), shape.Point( 0.7600, -0.3890), shape.Point( 0.8500, -0.3700), shape.Point( 0.9600, -0.2850), shape.Point( 1.0760, -0.1590), shape.Point( 1.1060, 0.0030), shape.Point( 1.0660, 0.1760), shape.Point( 1.0000, 0.2650), shape.Point( 0.9200, 0.3360), shape.Point( 0.7500, 0.3850), shape.Point( 0.6650, 0.2850), shape.Point( 0.6600, 0.1430), shape.Point( 0.6600, -0.0070), ], x_points=[ shape.Point( 0.7600, -0.3890), ], legs=[ shape.Point( 0.8430, -0.5850), ], limit_point=shape.Point( 0.7600, -0.3890), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=1.4500, shape=shape.Shape( ip=-280000, params=shape.ParametrizedShape( r0=0.8955, z0=0.0186, kappa=1.7143, delta=0.4841, radius=0.2262, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 14 points shape.Point( 0.6690, -0.1490), shape.Point( 0.7200, -0.2840), shape.Point( 0.7600, -0.3890), shape.Point( 0.8500, -0.3700), shape.Point( 0.9600, -0.2850), shape.Point( 1.0760, -0.1590), shape.Point( 1.1060, 0.0030), shape.Point( 1.0660, 0.1760), shape.Point( 1.0000, 0.2650), shape.Point( 0.9200, 0.3360), shape.Point( 0.7500, 0.3850), shape.Point( 0.6650, 0.2850), shape.Point( 0.6600, 0.1430), shape.Point( 0.6600, -0.0070), ], x_points=[ shape.Point( 0.7600, -0.3890), ], legs=[ shape.Point( 0.8430, -0.5850), ], limit_point=shape.Point( 0.7600, -0.3890), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=1.7000, shape=shape.Shape( ip=-280000, params=shape.ParametrizedShape( r0=0.8955, z0=0.0186, kappa=1.7143, delta=0.4841, radius=0.2262, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 14 points shape.Point( 0.6690, -0.1490), shape.Point( 0.7200, -0.2840), shape.Point( 0.7600, -0.3890), shape.Point( 0.8500, -0.3700), shape.Point( 0.9600, -0.2850), shape.Point( 1.0760, -0.1590), shape.Point( 1.1060, 0.0030), shape.Point( 1.0660, 0.1760), shape.Point( 1.0000, 0.2650), shape.Point( 0.9200, 0.3360), shape.Point( 0.7500, 0.3850), shape.Point( 0.6650, 0.2850), shape.Point( 0.6600, 0.1430), shape.Point( 0.6600, -0.0070), ], x_points=[ shape.Point( 0.7600, -0.3890), ], legs=[ shape.Point( 0.8430, -0.5850), ], limit_point=shape.Point( 0.7600, -0.3890), diverted=shape.Diverted.DIVERTED, ), ), shape.ReferenceTimeSlice( time=1.7600, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8873, z0=0.0281, kappa=1.6534, delta=0.4388, radius=0.2288, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6450, 0.0210), shape.Point( 0.6500, -0.1080), shape.Point( 0.6650, -0.2390), shape.Point( 0.7500, -0.3510), shape.Point( 0.9490, -0.2580), shape.Point( 1.0660, -0.1270), shape.Point( 1.0960, 0.0210), shape.Point( 1.0660, 0.1710), shape.Point( 0.9680, 0.3010), shape.Point( 0.8310, 0.3660), shape.Point( 0.7200, 0.3580), shape.Point( 0.6650, 0.2830), shape.Point( 0.6450, 0.1520), ], x_points=[ shape.Point( 0.7400, -0.3810), ], diverted=shape.Diverted.ANY, ), ), shape.ReferenceTimeSlice( time=1.7800, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8770, z0=0.0436, kappa=1.6840, delta=0.4370, radius=0.2306, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6350, 0.0413), shape.Point( 0.6350, -0.0895), shape.Point( 0.6550, -0.2194), shape.Point( 0.7400, -0.3312), shape.Point( 0.9390, -0.2378), shape.Point( 1.0560, -0.1079), shape.Point( 1.0860, 0.0413), shape.Point( 1.0560, 0.1895), shape.Point( 0.9580, 0.3204), shape.Point( 0.8210, 0.3853), shape.Point( 0.7100, 0.3756), shape.Point( 0.6550, 0.3010), shape.Point( 0.6350, 0.1711), ], x_points=[ shape.Point( 0.7300, -0.3793), ], limit_point=shape.Point( 0.6240, 0.0410), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=1.8000, shape=shape.Shape( ip=-140000, params=shape.ParametrizedShape( r0=0.8784, z0=0.0865, kappa=1.6166, delta=0.3958, radius=0.2378, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 13 points shape.Point( 0.6270, 0.0860), shape.Point( 0.6290, -0.0640), shape.Point( 0.6530, -0.1970), shape.Point( 0.7500, -0.2914), shape.Point( 0.9260, -0.2070), shape.Point( 1.0530, -0.0730), shape.Point( 1.1020, 0.0860), shape.Point( 1.0530, 0.2450), shape.Point( 0.9460, 0.3790), shape.Point( 0.8100, 0.4540), shape.Point( 0.7000, 0.4440), shape.Point( 0.6500, 0.3690), shape.Point( 0.6290, 0.2360), ], x_points=[ shape.Point( 0.7000, -0.4500), ], limit_point=shape.Point( 0.6240, 0.0860), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=1.8100, shape=shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.8865, z0=0.0501, kappa=1.3991, delta=0.1188, radius=0.2402, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6330, -0.0538), shape.Point( 0.6596, -0.1475), shape.Point( 0.7033, -0.2218), shape.Point( 0.7623, -0.2696), shape.Point( 0.8329, -0.2860), shape.Point( 0.9094, -0.2696), shape.Point( 0.9839, -0.2218), shape.Point( 1.0468, -0.1475), shape.Point( 1.0891, -0.0538), shape.Point( 1.1040, 0.0500), shape.Point( 1.0891, 0.1538), shape.Point( 1.0468, 0.2475), shape.Point( 0.9839, 0.3218), shape.Point( 0.9094, 0.3696), shape.Point( 0.8329, 0.3860), shape.Point( 0.7623, 0.3696), shape.Point( 0.7033, 0.3218), shape.Point( 0.6596, 0.2475), shape.Point( 0.6330, 0.1538), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=1.8200, shape=shape.Shape( ip=-94000, params=shape.ParametrizedShape( r0=0.8523, z0=0.0500, kappa=1.0904, delta=0.0128, radius=0.2106, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6339, -0.0207), shape.Point( 0.6627, -0.0845), shape.Point( 0.7078, -0.1352), shape.Point( 0.7653, -0.1677), shape.Point( 0.8298, -0.1789), shape.Point( 0.8951, -0.1677), shape.Point( 0.9547, -0.1352), shape.Point( 1.0024, -0.0845), shape.Point( 1.0333, -0.0207), shape.Point( 1.0440, 0.0500), shape.Point( 1.0333, 0.1207), shape.Point( 1.0024, 0.1845), shape.Point( 0.9547, 0.2352), shape.Point( 0.8951, 0.2677), shape.Point( 0.8298, 0.2789), shape.Point( 0.7653, 0.2677), shape.Point( 0.7078, 0.2352), shape.Point( 0.6627, 0.1845), shape.Point( 0.6339, 0.1207), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=1.8300, shape=shape.Shape( ip=-53000, params=shape.ParametrizedShape( r0=0.8048, z0=0.0501, kappa=1.0631, delta=0.0036, radius=0.1680, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6322, -0.0050), shape.Point( 0.6559, -0.0545), shape.Point( 0.6928, -0.0939), shape.Point( 0.7394, -0.1192), shape.Point( 0.7910, -0.1279), shape.Point( 0.8426, -0.1192), shape.Point( 0.8892, -0.0939), shape.Point( 0.9261, -0.0545), shape.Point( 0.9498, -0.0050), shape.Point( 0.9580, 0.0500), shape.Point( 0.9498, 0.1050), shape.Point( 0.9261, 0.1545), shape.Point( 0.8892, 0.1939), shape.Point( 0.8426, 0.2192), shape.Point( 0.7910, 0.2279), shape.Point( 0.7394, 0.2192), shape.Point( 0.6928, 0.1939), shape.Point( 0.6559, 0.1545), shape.Point( 0.6322, 0.1050), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=1.8400, shape=shape.Shape( ip=-22000, params=shape.ParametrizedShape( r0=0.7484, z0=0.0489, kappa=1.0666, delta=0.0258, radius=0.1176, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6297, 0.0109), shape.Point( 0.6462, -0.0243), shape.Point( 0.6718, -0.0523), shape.Point( 0.7042, -0.0703), shape.Point( 0.7400, -0.0764), shape.Point( 0.7758, -0.0703), shape.Point( 0.8082, -0.0523), shape.Point( 0.8338, -0.0243), shape.Point( 0.8503, 0.0109), shape.Point( 0.8560, 0.0500), shape.Point( 0.8503, 0.0891), shape.Point( 0.8338, 0.1243), shape.Point( 0.8082, 0.1523), shape.Point( 0.7758, 0.1703), shape.Point( 0.7400, 0.1764), shape.Point( 0.7042, 0.1703), shape.Point( 0.6718, 0.1523), shape.Point( 0.6462, 0.1243), shape.Point( 0.6297, 0.0891), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), shape.ReferenceTimeSlice( time=1.8500, shape=shape.Shape( ip=-12000, params=shape.ParametrizedShape( r0=0.7149, z0=0.0494, kappa=1.0830, delta=0.0382, radius=0.0871, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point( 0.6282, 0.0198), shape.Point( 0.6402, -0.0075), shape.Point( 0.6590, -0.0291), shape.Point( 0.6827, -0.0430), shape.Point( 0.7090, -0.0477), shape.Point( 0.7353, -0.0430), shape.Point( 0.7590, -0.0291), shape.Point( 0.7778, -0.0075), shape.Point( 0.7898, 0.0198), shape.Point( 0.7940, 0.0500), shape.Point( 0.7898, 0.0802), shape.Point( 0.7778, 0.1075), shape.Point( 0.7590, 0.1291), shape.Point( 0.7353, 0.1430), shape.Point( 0.7090, 0.1478), shape.Point( 0.6827, 0.1430), shape.Point( 0.6590, 0.1291), shape.Point( 0.6402, 0.1075), shape.Point( 0.6282, 0.0802), shape.Point( 0.6240, 0.0500), ], limit_point=shape.Point( 0.6240, 0.0500), diverted=shape.Diverted.LIMITED, ), ), ]) # Used in TCV#69545 def droplet() -> ref_gen.AbstractReferenceGenerator: """Hold the droplet at handover for TCV#69198 then ramp the Ip.""" init = ref_gen.RZIpTarget(r=0.875, z=0.55, ip=-72500) final = ref_gen.RZIpTarget(r=0.875, z=0.47, ip=-110000) return ref_gen.FixedReferenceGenerator([ ref_gen.LinearTransition( transition_steps=0, steady_steps=350, # Intentionally short. Mostly want to ramp. reference=ref_gen.make_symmetric_multidomain_rzip_reference(init)), ref_gen.LinearTransition( transition_steps=400, steady_steps=100000, # Hold forever. reference=ref_gen.make_symmetric_multidomain_rzip_reference(final)), ]) _REFERENCES = [ fundamental_capability, elongation, iter, negative_triangularity, snowflake, droplet, ] REFERENCES = {f.__name__: f for f in _REFERENCES}
deepmind-research-master
fusion_tcv/references.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Actually interact with FGE via octave.""" from typing import Dict, List import dataclasses import numpy as np from fusion_tcv import fge_state from fusion_tcv import param_variation SUBSTEPS = 5 @dataclasses.dataclass class ShotCondition: """Represents a shot and time from a real shot.""" shot: int time: float class FGESimulatorOctave: """Would interact with the FGE solver via Octave. Given that FGE isn't open source, this is just a sketch. """ def __init__( self, shot_condition: ShotCondition, power_supply_delays: Dict[str, List[float]]): """Initialize the simulator. Args: shot_condition: A ShotCondition, specifying shot number and time. This specifies the machine geometry (eg with or without the baffles), and the initial measurements, voltages, current and plasma shape. power_supply_delays: A dict with power supply delays (in seconds), keys are coil type labels ('E', 'F', 'G', 'OH'). `None` means default delays. """ del power_supply_delays # Initialize the simulator: # - Use oct2py to load FGE through Octave. # - Load the data for the shot_condition. # - Set up the reactor geometry from the shot_condition. # - Set the timestep to `tcv_common.DT / SUBSTEPS`. # - Set up the solver for singlets or droplets based on the shot_condition. self._num_plasmas = 2 if shot_condition.shot == 69198 else 1 # - Set up the power supply, including the limits, initial data, and delays. def reset(self, variation: param_variation.Settings) -> fge_state.FGEState: """Restarts the simulator with parameters.""" del variation # Update the simulator with the current physics parameters. # Reset to the initial state from the shot_condition. return fge_state.FGEState(self._num_plasmas) # Filled with the real state. def step(self, voltages: np.ndarray) -> fge_state.FGEState: """Run the simulator with `voltages`, returns the state.""" del voltages # for _ in range(SUBSTEPS): # Step the simulator with `voltages`. # raise fge_state.InvalidSolutionError if the solver doesn't converge. # raise fge_state.StopSignalException if an internal termination triggered return fge_state.FGEState(self._num_plasmas) # Filled with the real state.
deepmind-research-master
fusion_tcv/fge_octave.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Give names to parts of a numpy array.""" from typing import Iterable, List, Mapping, MutableMapping, Tuple, Union import numpy as np def lengths_to_ranges( lengths: Mapping[str, int]) -> MutableMapping[str, List[int]]: """Eg: {a: 2, b: 3} -> {a: [0, 1], b: [2, 3, 4]} .""" ranges = {} start = 0 for key, length in lengths.items(): ranges[key] = list(range(start, start + length)) start += length return ranges class NamedRanges: """Given a map of {key: count}, give various views into it.""" def __init__(self, counts: Mapping[str, int]): self._ranges = lengths_to_ranges(counts) self._size = sum(counts.values()) def __getitem__(self, name) -> List[int]: return self._ranges[name] def __contains__(self, name) -> bool: return name in self._ranges def set_range(self, name: str, value: List[int]): """Overwrite or create a custom range, which may intersect with others.""" self._ranges[name] = value def range(self, name: str) -> List[int]: return self[name] def index(self, name: str) -> int: rng = self[name] if len(rng) != 1: raise ValueError(f"{name} has multiple values") return rng[0] def count(self, name: str) -> int: return len(self[name]) def names(self) -> Iterable[str]: return self._ranges.keys() def ranges(self) -> Iterable[Tuple[str, List[int]]]: return self._ranges.items() def counts(self) -> Mapping[str, int]: return {k: len(v) for k, v in self._ranges.items()} @property def size(self) -> int: return self._size def named_array(self, array: np.ndarray) -> "NamedArray": return NamedArray(array, self) def new_named_array(self) -> "NamedArray": return NamedArray(np.zeros((self.size,)), self) def new_random_named_array(self) -> "NamedArray": return NamedArray(np.random.uniform(size=(self.size,)), self) class NamedArray: """Given a numpy array and a NamedRange, access slices by name.""" def __init__(self, array: np.ndarray, names: NamedRanges): if array.shape != (names.size,): raise ValueError(f"Wrong sizes: {array.shape} != ({names.size},)") self._array = array self._names = names def __getitem__( self, name: Union[str, Tuple[str, Union[int, List[int], slice]]]) -> np.ndarray: """Return a read-only view into the array by name.""" if isinstance(name, str): arr = self._array[self._names[name]] else: name, i = name arr = self._array[np.array(self._names[name])[i]] if not np.isscalar(arr): # Read-only because it's indexed by an array of potentially non-contiguous # indices, which isn't representable as a normal tensor, which forces a # copy and therefore writes don't modify the underlying array as expected. arr.flags.writeable = False return arr def __setitem__( self, name: Union[str, Tuple[str, Union[int, List[int], slice]]], value): """Set one or more values of a range to a value.""" if isinstance(name, str): self._array[self._names[name]] = value else: name, i = name self._array[np.array(self._names[name])[i]] = value @property def array(self) -> np.ndarray: return self._array @property def names(self) -> NamedRanges: return self._names def to_dict(self) -> Mapping[str, np.ndarray]: return {k: self[k] for k in self._names.names()}
deepmind-research-master
fusion_tcv/named_array.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for transforms.""" import math from absl.testing import absltest from fusion_tcv import transforms NAN = float("nan") class TransformsTest(absltest.TestCase): def assertNan(self, value: float): self.assertTrue(math.isnan(value)) def test_clip(self): self.assertEqual(transforms.clip(-1, 0, 1), 0) self.assertEqual(transforms.clip(5, 0, 1), 1) self.assertEqual(transforms.clip(0.5, 0, 1), 0.5) self.assertNan(transforms.clip(NAN, 0, 1)) def test_scale(self): self.assertEqual(transforms.scale(0, 0, 0.5, 0, 1), 0) self.assertEqual(transforms.scale(0.125, 0, 0.5, 0, 1), 0.25) self.assertEqual(transforms.scale(0.25, 0, 0.5, 0, 1), 0.5) self.assertEqual(transforms.scale(0.5, 0, 0.5, 0, 1), 1) self.assertEqual(transforms.scale(1, 0, 0.5, 0, 1), 2) self.assertEqual(transforms.scale(-1, 0, 0.5, 0, 1), -2) self.assertEqual(transforms.scale(0.5, 1, 0, 0, 1), 0.5) self.assertEqual(transforms.scale(0.25, 1, 0, 0, 1), 0.75) self.assertEqual(transforms.scale(0, 0, 1, -4, 4), -4) self.assertEqual(transforms.scale(0.25, 0, 1, -4, 4), -2) self.assertEqual(transforms.scale(0.5, 0, 1, -4, 4), 0) self.assertEqual(transforms.scale(0.75, 0, 1, -4, 4), 2) self.assertEqual(transforms.scale(1, 0, 1, -4, 4), 4) self.assertNan(transforms.scale(NAN, 0, 1, -4, 4)) def test_logistic(self): self.assertLess(transforms.logistic(-50), 0.000001) self.assertLess(transforms.logistic(-5), 0.01) self.assertEqual(transforms.logistic(0), 0.5) self.assertGreater(transforms.logistic(5), 0.99) self.assertGreater(transforms.logistic(50), 0.999999) self.assertAlmostEqual(transforms.logistic(0.8), math.tanh(0.4) / 2 + 0.5) self.assertNan(transforms.logistic(NAN)) def test_exp_scaled(self): t = transforms.NegExp(good=0, bad=1) self.assertNan(t([NAN])[0]) self.assertAlmostEqual(t([0])[0], 1) self.assertAlmostEqual(t([1])[0], 0.1) self.assertLess(t([50])[0], 0.000001) t = transforms.NegExp(good=10, bad=30) self.assertAlmostEqual(t([0])[0], 1) self.assertAlmostEqual(t([10])[0], 1) self.assertLess(t([3000])[0], 0.000001) t = transforms.NegExp(good=30, bad=10) self.assertAlmostEqual(t([50])[0], 1) self.assertAlmostEqual(t([30])[0], 1) self.assertAlmostEqual(t([10])[0], 0.1) self.assertLess(t([-90])[0], 0.00001) def test_neg(self): t = transforms.Neg() self.assertEqual(t([-5, -3, 0, 1, 4]), [5, 3, 0, -1, -4]) self.assertNan(t([NAN])[0]) def test_abs(self): t = transforms.Abs() self.assertEqual(t([-5, -3, 0, 1, 4]), [5, 3, 0, 1, 4]) self.assertNan(t([NAN])[0]) def test_pow(self): t = transforms.Pow(2) self.assertEqual(t([-5, -3, 0, 1, 4]), [25, 9, 0, 1, 16]) self.assertNan(t([NAN])[0]) def test_log(self): t = transforms.Log() self.assertAlmostEqual(t([math.exp(2)])[0], 2, 4) # Low precision from eps. self.assertNan(t([NAN])[0]) def test_clipped_linear(self): t = transforms.ClippedLinear(good=0.1, bad=0.3) self.assertAlmostEqual(t([0])[0], 1) self.assertAlmostEqual(t([0.05])[0], 1) self.assertAlmostEqual(t([0.1])[0], 1) self.assertAlmostEqual(t([0.15])[0], 0.75) self.assertAlmostEqual(t([0.2])[0], 0.5) self.assertAlmostEqual(t([0.25])[0], 0.25) self.assertAlmostEqual(t([0.3])[0], 0) self.assertAlmostEqual(t([0.4])[0], 0) self.assertNan(t([NAN])[0]) t = transforms.ClippedLinear(good=1, bad=0.5) self.assertAlmostEqual(t([1.5])[0], 1) self.assertAlmostEqual(t([1])[0], 1) self.assertAlmostEqual(t([0.75])[0], 0.5) self.assertAlmostEqual(t([0.5])[0], 0) self.assertAlmostEqual(t([0.25])[0], 0) def test_softplus(self): t = transforms.SoftPlus(good=0.1, bad=0.3) self.assertEqual(t([0])[0], 1) self.assertEqual(t([0.1])[0], 1) self.assertAlmostEqual(t([0.3])[0], 0.1) self.assertLess(t([0.5])[0], 0.01) self.assertNan(t([NAN])[0]) t = transforms.SoftPlus(good=1, bad=0.5) self.assertEqual(t([1.5])[0], 1) self.assertEqual(t([1])[0], 1) self.assertAlmostEqual(t([0.5])[0], 0.1) self.assertLess(t([0.1])[0], 0.01) def test_sigmoid(self): t = transforms.Sigmoid(good=0.1, bad=0.3) self.assertGreater(t([0])[0], 0.99) self.assertAlmostEqual(t([0.1])[0], 0.95) self.assertAlmostEqual(t([0.2])[0], 0.5) self.assertAlmostEqual(t([0.3])[0], 0.05) self.assertLess(t([0.4])[0], 0.01) self.assertNan(t([NAN])[0]) t = transforms.Sigmoid(good=1, bad=0.5) self.assertGreater(t([1.5])[0], 0.99) self.assertAlmostEqual(t([1])[0], 0.95) self.assertAlmostEqual(t([0.75])[0], 0.5) self.assertAlmostEqual(t([0.5])[0], 0.05) self.assertLess(t([0.25])[0], 0.01) def test_equal(self): t = transforms.Equal() self.assertEqual(t([0])[0], 1) self.assertEqual(t([0.001])[0], 0) self.assertNan(t([NAN])[0]) t = transforms.Equal(not_equal_val=0.5) self.assertEqual(t([0])[0], 1) self.assertEqual(t([0.001])[0], 0.5) if __name__ == "__main__": absltest.main()
deepmind-research-master
fusion_tcv/transforms_test.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for named_array.""" from absl.testing import absltest import numpy as np from fusion_tcv import named_array class NamedRangesTest(absltest.TestCase): def test_lengths_to_ranges(self): self.assertEqual(named_array.lengths_to_ranges({"a": 2, "b": 3}), {"a": [0, 1], "b": [2, 3, 4]}) def test_named_ranges(self): action_counts = {"E": 8, "F": 8, "OH": 2, "DUMMY": 1, "G": 1} actions = named_array.NamedRanges(action_counts) self.assertEqual(actions.range("E"), list(range(8))) self.assertEqual(actions["F"], list(range(8, 16))) self.assertEqual(actions.range("G"), [19]) self.assertEqual(actions.index("G"), 19) with self.assertRaises(ValueError): actions.index("F") for k, v in action_counts.items(): self.assertEqual(actions.count(k), v) self.assertEqual(actions.counts(), action_counts) self.assertEqual(list(actions.names()), list(action_counts.keys())) self.assertEqual(actions.size, sum(action_counts.values())) refs = actions.new_named_array() self.assertEqual(refs.array.shape, (actions.size,)) np.testing.assert_array_equal(refs.array, np.zeros((actions.size,))) refs = actions.new_random_named_array() self.assertEqual(refs.array.shape, (actions.size,)) self.assertFalse(np.array_equal(refs.array, np.zeros((actions.size,)))) class NamedArrayTest(absltest.TestCase): def test_name_array(self): action_counts = {"E": 8, "F": 8, "OH": 2, "DUMMY": 1, "G": 1} actions_ranges = named_array.NamedRanges(action_counts) actions_array = np.arange(actions_ranges.size) + 100 actions = named_array.NamedArray(actions_array, actions_ranges) for k in action_counts: self.assertEqual(list(actions[k]), [v + 100 for v in actions_ranges[k]]) actions["G"] = -5 self.assertEqual(list(actions["G"]), [-5]) self.assertEqual(actions_array[19], -5) for i in range(action_counts["E"]): actions.names.set_range(f"E_{i}", [i]) actions["E_3"] = 53 self.assertEqual(list(actions["E_1"]), [101]) self.assertEqual(list(actions["E_3"]), [53]) self.assertEqual(actions_array[3], 53) actions["F", 2] = 72 self.assertEqual(actions_array[10], 72) actions["F", [4, 5]] = 74 self.assertEqual(actions_array[12], 74) self.assertEqual(actions_array[13], 74) actions["F", 0:2] = 78 self.assertEqual(actions_array[8], 78) self.assertEqual(actions_array[9], 78) self.assertEqual(list(actions["F"]), [78, 78, 72, 111, 74, 74, 114, 115]) with self.assertRaises(ValueError): actions["F"][5] = 85 if __name__ == "__main__": absltest.main()
deepmind-research-master
fusion_tcv/named_array_test.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A trajectory for an episode.""" from typing import List import dataclasses import numpy as np @dataclasses.dataclass class Trajectory: """A trajectory of actions/obs for an episode.""" measurements: np.ndarray references: np.ndarray reward: np.ndarray actions: np.ndarray @classmethod def stack(cls, series: List["Trajectory"]) -> "Trajectory": """Stack a series of trajectories, adding a trailing time dimension.""" values = {k: np.empty(v.shape + (len(series),)) for k, v in dataclasses.asdict(series[0]).items() if v is not None} for i, ts in enumerate(series): for k, v in values.items(): v[..., i] = getattr(ts, k) out = cls(**values) return out
deepmind-research-master
fusion_tcv/trajectory.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Run an agent on the environment.""" import numpy as np from fusion_tcv import environment from fusion_tcv import trajectory def run_loop(env: environment.Environment, agent, max_steps: int = 100000) -> trajectory.Trajectory: """Run an agent.""" results = [] agent.reset() ts = env.reset() for _ in range(max_steps): obs = ts.observation action = agent.step(ts) ts = env.step(action) results.append(trajectory.Trajectory( measurements=obs["measurements"], references=obs["references"], actions=action, reward=np.array(ts.reward))) if ts.last(): break return trajectory.Trajectory.stack(results)
deepmind-research-master
fusion_tcv/run_loop.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tools for varying parameters from simulation to simulation.""" from typing import Dict, Optional, Tuple import dataclasses import numpy as np from fusion_tcv import tcv_common # Pylint does not like variable names like `qA`. # pylint: disable=invalid-name RP_DEFAULT = 5e-6 LP_DEFAULT = 2.05e-6 BP_DEFAULT = 0.25 QA_DEFAULT = 1.3 @dataclasses.dataclass class Settings: """Settings to modify solver/plasma model.""" # Inverse of the resistivity. # Plasma circuit equation is roughly # k * dIoh/dt = L * dIp/dt + R * I = Vloop # where R is roughly (1 / signeo) or rp. # Value is multiplier on the default value. # This parameter does not apply to the OhmTor diffusion. signeo: Tuple[float, float] = (1, 1) # Rp Plasma resistivity. The value is an absolute value. rp: float = RP_DEFAULT # Plasma self-inductance. The value is an absolute value. lp: float = LP_DEFAULT # Proportional to the plasma pressure. The value is an absolute value. bp: float = BP_DEFAULT # Plasma current profile. Value is absolute. qA: float = QA_DEFAULT # Initial OH coil current. Applied to both coils. ioh: Optional[float] = None # The voltage offsets for the various coils. psu_voltage_offset: Optional[Dict[str, float]] = None def _psu_voltage_offset_string(self) -> str: """Return a short-ish, readable string of the psu voltage offsets.""" if not self.psu_voltage_offset: return "None" if len(self.psu_voltage_offset) < 8: # Only a few, output individually. return ", ".join( f"{coil.replace('_00', '')}: {offset:.0f}" for coil, offset in self.psu_voltage_offset.items()) # Otherwise, too long, so output in groups. groups = [] for coil, action_range in tcv_common.TCV_ACTION_RANGES.ranges(): offsets = [self.psu_voltage_offset.get(tcv_common.TCV_ACTIONS[i], 0) for i in action_range] if any(offsets): groups.append(f"{coil}: " + ",".join(f"{offset:.0f}" for offset in offsets)) return ", ".join(groups) class ParamGenerator: """Varies parameters using uniform/loguniform distributions. Absolute parameters are varied using uniform distributions while scaling parameters use a loguniform distribution. """ def __init__(self, rp_bounds: Optional[Tuple[float, float]] = None, lp_bounds: Optional[Tuple[float, float]] = None, qA_bounds: Optional[Tuple[float, float]] = None, bp_bounds: Optional[Tuple[float, float]] = None, rp_mean: float = RP_DEFAULT, lp_mean: float = LP_DEFAULT, bp_mean: float = BP_DEFAULT, qA_mean: float = QA_DEFAULT, ioh_bounds: Optional[Tuple[float, float]] = None, psu_voltage_offset_bounds: Optional[ Dict[str, Tuple[float, float]]] = None): # Do not allow Signeo variation as this does not work with OhmTor current # diffusion. no_scaling = (1, 1) self._rp_bounds = rp_bounds if rp_bounds else no_scaling self._lp_bounds = lp_bounds if lp_bounds else no_scaling self._bp_bounds = bp_bounds if bp_bounds else no_scaling self._qA_bounds = qA_bounds if qA_bounds else no_scaling self._rp_mean = rp_mean self._lp_mean = lp_mean self._bp_mean = bp_mean self._qA_mean = qA_mean self._ioh_bounds = ioh_bounds self._psu_voltage_offset_bounds = psu_voltage_offset_bounds def generate(self) -> Settings: return Settings( signeo=(1, 1), rp=loguniform_rv(*self._rp_bounds) * self._rp_mean, lp=loguniform_rv(*self._lp_bounds) * self._lp_mean, bp=loguniform_rv(*self._bp_bounds) * self._bp_mean, qA=loguniform_rv(*self._qA_bounds) * self._qA_mean, ioh=np.random.uniform(*self._ioh_bounds) if self._ioh_bounds else None, psu_voltage_offset=( {coil: np.random.uniform(*bounds) for coil, bounds in self._psu_voltage_offset_bounds.items()} if self._psu_voltage_offset_bounds else None)) def loguniform_rv(lower, upper): """Generate loguniform random variable between min and max.""" if lower == upper: return lower assert lower < upper return np.exp(np.random.uniform(np.log(lower), np.log(upper)))
deepmind-research-master
fusion_tcv/param_variation.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The environment definitions used for our experiments.""" from fusion_tcv import environment from fusion_tcv import references from fusion_tcv import rewards_used # Used in TCV#70915 def fundamental_capability() -> environment.Environment: return environment.Environment( shot_condition=environment.ShotCondition(70166, 0.0872), reward=rewards_used.FUNDAMENTAL_CAPABILITY, reference_generator=references.fundamental_capability(), max_episode_length=10000) # Used in TCV#70920 def elongation() -> environment.Environment: return environment.Environment( shot_condition=environment.ShotCondition(70166, 0.45), reward=rewards_used.ELONGATION, reference_generator=references.elongation(), max_episode_length=5000) # Used in TCV#70600 def iter() -> environment.Environment: # pylint: disable=redefined-builtin return environment.Environment( shot_condition=environment.ShotCondition(70392, 0.0872), reward=rewards_used.ITER, reference_generator=references.iter(), max_episode_length=1000) # Used in TCV#70457 def negative_triangularity() -> environment.Environment: return environment.Environment( shot_condition=environment.ShotCondition(70166, 0.45), reward=rewards_used.NEGATIVE_TRIANGULARITY, reference_generator=references.negative_triangularity(), max_episode_length=5000) # Used in TCV#70755 def snowflake() -> environment.Environment: return environment.Environment( shot_condition=environment.ShotCondition(70166, 0.0872), reward=rewards_used.SNOWFLAKE, reference_generator=references.snowflake(), max_episode_length=10000) # Used in TCV#69545 def droplet() -> environment.Environment: return environment.Environment( shot_condition=environment.ShotCondition(69198, 0.418), reward=rewards_used.DROPLETS, reference_generator=references.droplet(), max_episode_length=2000)
deepmind-research-master
fusion_tcv/experiments.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A set of known shapes.""" from fusion_tcv import shape from fusion_tcv import tcv_common SHAPE_70166_0450 = shape.Shape( ip=-120000, params=shape.ParametrizedShape( r0=0.89, z0=0.25, kappa=1.4, delta=0.25, radius=0.25, lambda_=0, side=shape.ShapeSide.NOSHIFT), limit_point=shape.Point(tcv_common.INNER_LIMITER_R, 0.25), diverted=shape.Diverted.LIMITED) SHAPE_70166_0872 = shape.Shape( ip=-110000, params=shape.ParametrizedShape( r0=0.8796, z0=0.2339, kappa=1.2441, delta=0.2567, radius=0.2390, lambda_=0, side=shape.ShapeSide.NOSHIFT, ), points=[ # 20 points shape.Point(0.6299, 0.1413), shape.Point(0.6481, 0.0577), shape.Point(0.6804, -0.0087), shape.Point(0.7286, -0.0513), shape.Point(0.7931, -0.0660), shape.Point(0.8709, -0.0513), shape.Point(0.9543, -0.0087), shape.Point(1.0304, 0.0577), shape.Point(1.0844, 0.1413), shape.Point(1.1040, 0.2340), shape.Point(1.0844, 0.3267), shape.Point(1.0304, 0.4103), shape.Point(0.9543, 0.4767), shape.Point(0.8709, 0.5193), shape.Point(0.7931, 0.5340), shape.Point(0.7286, 0.5193), shape.Point(0.6804, 0.4767), shape.Point(0.6481, 0.4103), shape.Point(0.6299, 0.3267), shape.Point(0.6240, 0.2340), ], limit_point=shape.Point(tcv_common.INNER_LIMITER_R, 0.2339), diverted=shape.Diverted.LIMITED)
deepmind-research-master
fusion_tcv/shapes_known.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Settings for adding noise to the action and measurements.""" import numpy as np from numpy import random from fusion_tcv import tcv_common class Noise: """Class for adding noise to the action and measurements.""" def __init__(self, action_mean=None, action_std=None, measurements_mean=None, measurements_std=None, seed=None): """Initializes the class. Args: action_mean: mean of the Gaussian noise (action bias). action_std: std of the Gaussian action noise. measurements_mean: mean of the Gaussian noise (measurement bias). measurements_std: Dictionary mapping the tcv measurement names to noise. seed: seed for the random number generator. If none seed is unset. """ # Check all of the shapes are present and correct. assert action_std.shape == (tcv_common.NUM_ACTIONS,) assert action_mean.shape == (tcv_common.NUM_ACTIONS,) for name, num in tcv_common.TCV_MEASUREMENTS.items(): assert name in measurements_std assert measurements_mean[name].shape == (num,) assert measurements_std[name].shape == (num,) self._action_mean = action_mean self._action_std = action_std self._meas_mean = measurements_mean self._meas_std = measurements_std self._meas_mean_vec = tcv_common.dict_to_measurement(self._meas_mean) self._meas_std_vec = tcv_common.dict_to_measurement(self._meas_std) self._gen = random.RandomState(seed) @classmethod def use_zero_noise(cls): no_noise_mean = dict() no_noise_std = dict() for name, num in tcv_common.TCV_MEASUREMENTS.items(): no_noise_mean[name] = np.zeros((num,)) no_noise_std[name] = np.zeros((num,)) return cls( action_mean=np.zeros((tcv_common.NUM_ACTIONS)), action_std=np.zeros((tcv_common.NUM_ACTIONS)), measurements_mean=no_noise_mean, measurements_std=no_noise_std) @classmethod def use_default_noise(cls, scale=1): """Returns the default observation noise parameters.""" # There is no noise added to the actions, because the noise should be added # to the action after/as part of the power supply model as opposed to the # input to the power supply model. action_noise_mean = np.zeros((tcv_common.NUM_ACTIONS)) action_noise_std = np.zeros((tcv_common.NUM_ACTIONS)) meas_noise_mean = dict() for key, l in tcv_common.TCV_MEASUREMENTS.items(): meas_noise_mean[key] = np.zeros((l,)) meas_noise_std = dict( clint_vloop=np.array([0]), clint_rvloop=np.array([scale * 1e-4] * 37), bm=np.array([scale * 1e-4] * 38), IE=np.array([scale * 20] * 8), IF=np.array([scale * 5] * 8), IOH=np.array([scale * 20] *2), Bdot=np.array([scale * 0.05] * 20), DIOH=np.array([scale * 30]), FIR_FRINGE=np.array([0]), IG=np.array([scale * 2.5]), ONEMM=np.array([0]), vloop=np.array([scale * 0.3]), IPHI=np.array([0]), ) return cls( action_mean=action_noise_mean, action_std=action_noise_std, measurements_mean=meas_noise_mean, measurements_std=meas_noise_std) def add_action_noise(self, action): errs = self._gen.normal(size=action.shape, loc=self._action_mean, scale=self._action_std) return action + errs def add_measurement_noise(self, measurement_vec): errs = self._gen.normal(size=measurement_vec.shape, loc=self._meas_mean_vec, scale=self._meas_std_vec) # Make the IOH measurements consistent. The "real" measurements are IOH # and DIOH, so use those. errs = tcv_common.measurements_to_dict(errs) errs["IOH"][1] = errs["IOH"][0] + errs["DIOH"][0] errs = tcv_common.dict_to_measurement(errs) return measurement_vec + errs
deepmind-research-master
fusion_tcv/noise.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An agent interface for interacting with the environment.""" import abc import dm_env import numpy as np from fusion_tcv import tcv_common class AbstractAgent(abc.ABC): """Agent base class.""" def reset(self): """Reset to the initial state.""" @abc.abstractmethod def step(self, timestep: dm_env.TimeStep) -> np.ndarray: """Return the action given the current observations.""" class ZeroAgent(AbstractAgent): """An agent that always returns "zero" actions.""" def step(self, timestep: dm_env.TimeStep) -> np.ndarray: del timestep return np.zeros(tcv_common.action_spec().shape, tcv_common.action_spec().dtype)
deepmind-research-master
fusion_tcv/agent.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Environment API for FGE simulator.""" from typing import Dict, List, Optional import dm_env from dm_env import auto_reset_environment from dm_env import specs import numpy as np from fusion_tcv import fge_octave from fusion_tcv import fge_state from fusion_tcv import named_array from fusion_tcv import noise from fusion_tcv import param_variation from fusion_tcv import ref_gen from fusion_tcv import rewards from fusion_tcv import tcv_common from fusion_tcv import terminations # Re-export as fge_octave should be an implementation detail. ShotCondition = fge_octave.ShotCondition class Environment(auto_reset_environment.AutoResetEnvironment): """An environment using the FGE Solver. The simulator will return a flux map, which is the environment's hidden state, and some flux measurements, which will be used as observations. The actions represent current levels that are passed to the simulator for the next flux calculation. """ def __init__( self, shot_condition: ShotCondition, reward: rewards.AbstractReward, reference_generator: ref_gen.AbstractReferenceGenerator, max_episode_length: int = 10000, termination: Optional[terminations.Abstract] = None, obs_act_noise: Optional[noise.Noise] = None, power_supply_delays: Optional[Dict[str, List[float]]] = None, param_generator: Optional[param_variation.ParamGenerator] = None): """Initializes an Environment instance. Args: shot_condition: A ShotCondition, specifying shot number and time. This specifies the machine geometry (eg with or without the baffles), and the initial measurements, voltages, current and plasma state. reward: Function to generate a reward term. reference_generator: Generator for the signal to send to references. max_episode_length: Maximum number of steps before episode is truncated and restarted. termination: Decide if the state should be considered a termination. obs_act_noise: Type for setting the observation and action noise. If noise is set to None then the default noise level is used. power_supply_delays: A dict with power supply delays (in seconds), keys are coil type labels ('E', 'F', 'G', 'OH'). `None` means default delays. param_generator: Generator for Liuqe parameter settings. If None then the default settings are used. """ super().__init__() if power_supply_delays is None: power_supply_delays = tcv_common.TCV_ACTION_DELAYS self._simulator = fge_octave.FGESimulatorOctave( shot_condition=shot_condition, power_supply_delays=power_supply_delays) self._reward = reward self._reference_generator = reference_generator self._max_episode_length = max_episode_length self._termination = (termination if termination is not None else terminations.CURRENT_OH_IP) self._noise = (obs_act_noise if obs_act_noise is not None else noise.Noise.use_default_noise()) self._param_generator = (param_generator if param_generator is not None else param_variation.ParamGenerator()) self._params = None self._step_counter = 0 self._last_observation = None def observation_spec(self): """Defines the observations provided by the environment.""" return tcv_common.observation_spec() def action_spec(self) -> specs.BoundedArray: """Defines the actions that should be provided to `step`.""" return tcv_common.action_spec() def _reset(self) -> dm_env.TimeStep: """Starts a new episode.""" self._step_counter = 0 self._params = self._param_generator.generate() state = self._simulator.reset(self._params) references = self._reference_generator.reset() zero_act = np.zeros(self.action_spec().shape, dtype=self.action_spec().dtype) self._last_observation = self._extract_observation( state, references, zero_act) return dm_env.restart(self._last_observation) def _simulator_voltages_from_voltages(self, voltages): voltage_simulator = np.copy(voltages) if self._params.psu_voltage_offset is not None: for coil, offset in self._params.psu_voltage_offset.items(): voltage_simulator[tcv_common.TCV_ACTION_INDICES[coil]] += offset voltage_simulator = np.clip( voltage_simulator, self.action_spec().minimum, self.action_spec().maximum) g_coil = tcv_common.TCV_ACTION_RANGES.index("G") if abs(voltage_simulator[g_coil]) < tcv_common.ENV_G_COIL_DEADBAND: voltage_simulator[g_coil] = 0 return voltage_simulator def _step(self, action: np.ndarray) -> dm_env.TimeStep: """Does one step within TCV.""" voltages = self._noise.add_action_noise(action) voltage_simulator = self._simulator_voltages_from_voltages(voltages) try: state = self._simulator.step(voltage_simulator) except (fge_state.InvalidSolutionError, fge_state.StopSignalException): return dm_env.termination( self._reward.terminal_reward(), self._last_observation) references = self._reference_generator.step() self._last_observation = self._extract_observation( state, references, action) term = self._termination.terminate(state) if term: return dm_env.termination( self._reward.terminal_reward(), self._last_observation) reward, _ = self._reward.reward(voltages, state, references) self._step_counter += 1 if self._step_counter >= self._max_episode_length: return dm_env.truncation(reward, self._last_observation) return dm_env.transition(reward, self._last_observation) def _extract_observation( self, state: fge_state.FGEState, references: named_array.NamedArray, action: np.ndarray) -> Dict[str, np.ndarray]: return { "references": references.array, "measurements": self._noise.add_measurement_noise( state.get_observation_vector()), "last_action": action, }
deepmind-research-master
fusion_tcv/environment.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reward function for the fusion environment.""" import abc import collections import functools from typing import Callable, Dict, List, Optional, Text, Tuple, Union from absl import logging import dataclasses import numpy as np from fusion_tcv import combiners from fusion_tcv import fge_state from fusion_tcv import named_array from fusion_tcv import targets as targets_lib from fusion_tcv import transforms class AbstractMeasure(abc.ABC): @abc.abstractmethod def __call__(self, targets: List[targets_lib.Target]) -> List[float]: """Returns a list of error measures.""" class AbsDist(AbstractMeasure): """Return the absolute distance between the actual and target.""" @staticmethod def __call__(targets: List[targets_lib.Target]) -> List[float]: return [abs(t.actual - t.target) for t in targets] @dataclasses.dataclass(frozen=True) class MeasureDetails: min: float mean: float max: float @dataclasses.dataclass class RewardDetails: reward: float # 0-1 reward value. weighted: float # Should sum to < 0-1. weight: float measure: Optional[MeasureDetails] = None class AbstractReward(abc.ABC): """Abstract reward class.""" @abc.abstractmethod def reward( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray, ) -> Tuple[float, Dict[Text, List[RewardDetails]]]: """Returns the reward and log dict as a function of the penalty term.""" @abc.abstractmethod def terminal_reward(self) -> float: """Returns the reward if the simulator crashed.""" WeightFn = Callable[[named_array.NamedArray], float] WeightOrFn = Union[float, WeightFn] @dataclasses.dataclass class Component: target: targets_lib.AbstractTarget transforms: List[transforms.AbstractTransform] measure: AbstractMeasure = dataclasses.field(default_factory=AbsDist) weight: Union[WeightOrFn, List[WeightOrFn]] = 1 name: Optional[str] = None class Reward(AbstractReward): """Combines a bunch of reward components into a single reward. The component parts are applied in the order: target, measure, transform. - Targets represent some error value as one or more pair of values (target, actual), usually with some meaningful physical unit (eg distance, volts, etc). - Measures combine the (target, actual) into a single float, for example absolute distance, for each error value. - Transforms can make arbitrary conversions, but one of them must change from the arbitrary (often meaningful) scale to a reward in the 0-1 range. - Combiners are a special type of transform that reduces a vector of values down to a single value. The combiner can be skipped if the target only outputs a single value, or if you want a vector of outputs for the final combiner. - The component weights are passed to the final combiner, and must match the number of outputs for that component. """ def __init__(self, components: List[Component], combiner: combiners.AbstractCombiner, terminal_reward: float = -5, reward_scale: float = 0.01): self._components = components self._combiner = combiner self._terminal_reward = terminal_reward self._reward_scale = reward_scale self._weights = [] component_count = collections.Counter() for component in self._components: num_outputs = component.target.outputs for transform in component.transforms: if transform.outputs is not None: num_outputs = transform.outputs if not isinstance(component.weight, list): component.weight = [component.weight] if len(component.weight) != num_outputs: name = component.name or component.target.name raise ValueError(f"Wrong number of weights for '{name}': got:" f" {len(component.weight)}, expected: {num_outputs}") self._weights.extend(component.weight) def terminal_reward(self) -> float: return self._terminal_reward * self._reward_scale def reward( self, voltages: np.ndarray, state: fge_state.FGEState, references: named_array.NamedArray, ) -> Tuple[float, Dict[Text, List[RewardDetails]]]: values = [] weights = [weight(references) if callable(weight) else weight for weight in self._weights] reward_dict = collections.defaultdict(list) for component in self._components: name = component.name or component.target.name num_outputs = len(component.weight) component_weights = weights[len(values):(len(values) + num_outputs)] try: target = component.target(voltages, state, references) except targets_lib.TargetError: logging.exception("Target failed.") # Failed turns into minimum reward. measure = [987654321] * num_outputs transformed = [0] * num_outputs else: measure = component.measure(target) transformed = functools.reduce( (lambda e, fn: fn(e)), component.transforms, measure) assert len(transformed) == num_outputs for v in transformed: if not np.isnan(v) and not 0 <= v <= 1: raise ValueError(f"The transformed value in {name} is invalid: {v}") values.extend(transformed) for weight, value in zip(component_weights, transformed): measure = [m for m in measure if not np.isnan(m)] or [float("nan")] reward_dict[name].append(RewardDetails( value, weight * value * self._reward_scale, weight if not np.isnan(value) else 0, MeasureDetails( min(measure), sum(measure) / len(measure), max(measure)))) sum_weights = sum(sum(d.weight for d in detail) for detail in reward_dict.values()) for reward_details in reward_dict.values(): for detail in reward_details: detail.weighted /= sum_weights final_combined = self._combiner(values, weights) assert len(final_combined) == 1 return final_combined[0] * self._reward_scale, reward_dict
deepmind-research-master
fusion_tcv/rewards.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for time varying shape control.""" import copy import enum import random from typing import List, Optional, NamedTuple, Tuple, Union import dataclasses import numpy as np from scipy import interpolate from fusion_tcv import named_array from fusion_tcv import tcv_common class Point(NamedTuple): """A point in r,z coordinates.""" r: float z: float def to_polar(self) -> "PolarPoint": return PolarPoint(np.arctan2(self.z, self.r), np.sqrt(self.r**2 + self.z**2)) def __neg__(self): return Point(-self.r, -self.z) def __add__(self, pt_or_val: Union["Point", float]): if isinstance(pt_or_val, Point): return Point(self.r + pt_or_val.r, self.z + pt_or_val.z) else: return Point(self.r + pt_or_val, self.z + pt_or_val) def __sub__(self, pt_or_val: Union["Point", float]): if isinstance(pt_or_val, Point): return Point(self.r - pt_or_val.r, self.z - pt_or_val.z) else: return Point(self.r - pt_or_val, self.z - pt_or_val) def __mul__(self, pt_or_val: Union["Point", float]): if isinstance(pt_or_val, Point): return Point(self.r * pt_or_val.r, self.z * pt_or_val.z) else: return Point(self.r * pt_or_val, self.z * pt_or_val) def __truediv__(self, pt_or_val: Union["Point", float]): if isinstance(pt_or_val, Point): return Point(self.r / pt_or_val.r, self.z / pt_or_val.z) else: return Point(self.r / pt_or_val, self.z / pt_or_val) __div__ = __truediv__ def dist(p1: Union[Point, np.ndarray], p2: Union[Point, np.ndarray]) -> float: return np.hypot(*(p1 - p2)) ShapePoints = List[Point] def to_shape_points(array: np.ndarray) -> ShapePoints: return [Point(r, z) for r, z in array] def center_point(points: ShapePoints) -> Point: return sum(points, Point(0, 0)) / len(points) class ShapeSide(enum.Enum): LEFT = 0 RIGHT = 1 NOSHIFT = 2 class PolarPoint(NamedTuple): angle: float dist: float def to_point(self) -> Point: return Point(np.cos(self.angle) * self.dist, np.sin(self.angle) * self.dist) def evenly_spaced_angles(num: int): return np.arange(num) * 2 * np.pi / num def angle_aligned_dists(points: np.ndarray, angles: np.ndarray) -> np.ndarray: """Return a new set of points along angles that intersect with the shape.""" # TODO(tewalds): Walk the two arrays together for an O(n+m) algorithm instead # of the current O(n*m). This would work as long as they are both sorted # around the radial direction, so the next intersection will be near the last. return np.array([dist_angle_to_surface(points, a) for a in angles]) def angle_aligned_points(points: np.ndarray, num_points: int, origin: Point) -> np.ndarray: """Given a set of points, return a new space centered at origin.""" angles = evenly_spaced_angles(num_points) dists = angle_aligned_dists(points - origin, angles) return np.stack((np.cos(angles) * dists, np.sin(angles) * dists), axis=-1) + origin def dist_angle_to_surface(points: np.ndarray, angle: float) -> float: """Distance along a ray to the surface defined by a list of points.""" for p1, p2 in zip(points, np.roll(points, 1, axis=0)): d = dist_angle_to_segment(p1, p2, angle) if d is not None: return d raise ValueError(f"Intersecting edge not found for angle: {angle}") def dist_angle_to_segment(p1, p2, angle: float) -> Optional[float]: """Distance along a ray from the origin to a segment defined by two points.""" x0, y0 = p1[0], p1[1] x1, y1 = p2[0], p2[1] a0, b0 = np.cos(angle), np.sin(angle) a1, b1 = 0, 0 # Segment/segment algorithm inspired by https://stackoverflow.com/q/563198 denom = (b0 - b1) * (x0 - x1) - (y0 - y1) * (a0 - a1) if denom == 0: return None # Angle parallel to the segment, so can't intersect. xy = (a0 * (y1 - b1) + a1 * (b0 - y1) + x1 * (b1 - b0)) / denom eps = 0.00001 # Allow intersecting slightly beyond the endpoints. if -eps <= xy <= 1 + eps: # Check it hit the segment, not just the line. ab = (y1 * (x0 - a1) + b1 * (x1 - x0) + y0 * (a1 - x1)) / denom if ab > 0: # Otherwise it hit in the reverse direction. # If ab <= 1 then it's within the segment defined above, but given it's # a unit vector with one end at the origin this tells us the distance to # the intersection of an infinite ray out from the origin. return ab return None def dist_point_to_surface(points: np.ndarray, point: np.ndarray) -> float: """Distance from a point to the surface defined by a list of points.""" return min(dist_point_to_segment(p1, p2, point) for p1, p2 in zip(points, np.roll(points, 1, axis=0))) def dist_point_to_segment(v: np.ndarray, w: np.ndarray, p: np.ndarray) -> float: """Return minimum distance between line segment vw and point p.""" # Inspired by: https://stackoverflow.com/a/1501725 l2 = dist(v, w)**2 if l2 == 0.0: return dist(p, v) # v == w case # Consider the line extending the segment, parameterized as v + t (w - v). # We find projection of point p onto the line. # It falls where t = [(p-v) . (w-v)] / |w-v|^2 # We clamp t from [0,1] to handle points outside the segment vw. t = max(0, min(1, np.dot(p - v, w - v) / l2)) projection = v + t * (w - v) # Projection falls on the segment return dist(p, projection) def sort_by_angle(points: ShapePoints) -> ShapePoints: center = sum(points, Point(0, 0)) / len(points) return sorted(points, key=lambda p: (p - center).to_polar().angle) def spline_interpolate_points( points: ShapePoints, num_points: int, x_points: Optional[ShapePoints] = None) -> ShapePoints: """Interpolate along a spline to give a smooth evenly spaced shape.""" ends = [] if x_points: # Find the shape points that must allow sharp corners. for xp in x_points: for i, p in enumerate(points): if np.hypot(*(p - xp)) < 0.01: ends.append(i) if not ends: # No x-points forcing sharp corners, so use a periodic spline. tck, _ = interpolate.splprep(np.array(points + [points[0]]).T, s=0, per=1) unew = np.arange(num_points) / num_points out = interpolate.splev(unew, tck) assert len(out[0]) == num_points return sort_by_angle(to_shape_points(np.array(out).T)) # Generate a spline with an shape==x-point at each end. new_pts = [] for i, j in zip(ends, ends[1:] + [ends[0]]): pts = points[i:j+1] if i < j else points[i:] + points[:j+1] num_segment_points = np.round((len(pts) - 1) / len(points) * num_points) unew = np.arange(num_segment_points + 1) / num_segment_points tck, _ = interpolate.splprep(np.array(pts).T, s=0) out = interpolate.splev(unew, tck) new_pts += to_shape_points(np.array(out).T)[:-1] if len(new_pts) != num_points: raise AssertionError( f"Generated the wrong number of points: {len(new_pts)} != {num_points}") return sort_by_angle(new_pts) @dataclasses.dataclass class ParametrizedShape: """Describes a target shape from the parameter set.""" r0: float # Where to put the center along the radial axis. z0: float # Where to put the center along the vertical axis. kappa: float # Elongation of the shape. (0.8, 3) delta: float # Triangulation of the shape. (-1, 1) radius: float # Radius of the shape (0.22, 2.58) lambda_: float # Squareness of the shape. Recommend (0, 0) side: ShapeSide # Whether and which side to shift the shape to. @classmethod def uniform_random_shape( cls, r_bounds=(0.8, 0.9), z_bounds=(0, 0.2), kappa_bounds=(1.0, 1.8), # elongation delta_bounds=(-0.5, 0.6), # triangulation radius_bounds=(tcv_common.LIMITER_WIDTH / 2 - 0.04, tcv_common.LIMITER_WIDTH / 2), lambda_bounds=(0, 0), # squareness side=(ShapeSide.LEFT, ShapeSide.RIGHT)): """Return a random shape.""" return cls( r0=np.random.uniform(*r_bounds), z0=np.random.uniform(*z_bounds), kappa=np.random.uniform(*kappa_bounds), delta=np.random.uniform(*delta_bounds), radius=np.random.uniform(*radius_bounds), lambda_=np.random.uniform(*lambda_bounds), side=side if isinstance(side, ShapeSide) else random.choice(side)) def gen_points(self, num_points: int) -> Tuple[ShapePoints, Point]: """Generates a set of shape points, return (points, modified (r0, z0)).""" r0 = self.r0 z0 = self.z0 num_warped_points = 32 points = np.zeros((num_warped_points, 2)) theta = evenly_spaced_angles(num_warped_points) points[:, 0] = r0 + self.radius * np.cos(theta + self.delta * np.sin(theta) - self.lambda_ * np.sin(2 * theta)) points[:, 1] = z0 + self.radius * self.kappa * np.sin(theta) if self.side == ShapeSide.LEFT: wall_shift = np.min(points[:, 0]) - tcv_common.INNER_LIMITER_R points[:, 0] -= wall_shift r0 -= wall_shift elif self.side == ShapeSide.RIGHT: wall_shift = np.max(points[:, 0]) - tcv_common.OUTER_LIMITER_R points[:, 0] -= wall_shift r0 -= wall_shift return (spline_interpolate_points(to_shape_points(points), num_points), Point(r0, z0)) def trim_zero_points(points: ShapePoints) -> Optional[ShapePoints]: trimmed = [p for p in points if p.r != 0] return trimmed if trimmed else None class Diverted(enum.Enum): """Whether a shape is diverted or not.""" ANY = 0 LIMITED = 1 DIVERTED = 2 @classmethod def from_refs(cls, references: named_array.NamedArray) -> "Diverted": diverted = (references["diverted", 0] == 1) limited = (references["limited", 0] == 1) if diverted and limited: raise ValueError("Diverted and limited doesn't make sense.") if diverted: return cls.DIVERTED if limited: return cls.LIMITED return cls.ANY @dataclasses.dataclass class Shape: """Full specification of a shape.""" params: Optional[ParametrizedShape] = None points: Optional[ShapePoints] = None x_points: Optional[ShapePoints] = None legs: Optional[ShapePoints] = None diverted: Diverted = Diverted.ANY ip: Optional[float] = None limit_point: Optional[Point] = None @classmethod def from_references(cls, references: named_array.NamedArray) -> "Shape": """Extract a Shape from the references.""" if any(np.any(references[name] != 0) for name in ("R", "Z", "kappa", "delta", "radius", "lambda")): params = ParametrizedShape( r0=references["R"][0], z0=references["Z"][0], kappa=references["kappa"][0], delta=references["delta"][0], radius=references["radius"][0], lambda_=references["lambda"][0], side=ShapeSide.NOSHIFT) else: params = None ip = references["Ip", 0] return cls( params, points=trim_zero_points(points_from_references(references, "shape1")), x_points=trim_zero_points(points_from_references(references, "x_points")), legs=trim_zero_points(points_from_references(references, "legs")), limit_point=trim_zero_points(points_from_references( references, "limit_point")[0:1]), diverted=Diverted.from_refs(references), ip=float(ip) if ip != 0 else None) def gen_references(self) -> named_array.NamedArray: """Return the references for the parametrized shape.""" refs = tcv_common.REF_RANGES.new_named_array() if self.ip is not None: refs["Ip", 0] = self.ip refs["diverted", 0] = 1 if self.diverted == Diverted.DIVERTED else 0 refs["limited", 0] = 1 if self.diverted == Diverted.LIMITED else 0 if self.params is not None: refs["R", 0] = self.params.r0 refs["Z", 0] = self.params.z0 refs["kappa", 0] = self.params.kappa refs["delta", 0] = self.params.delta refs["radius", 0] = self.params.radius refs["lambda", 0] = self.params.lambda_ if self.points is not None: points = np.array(self.points) assert refs.names.count("shape_r") >= points.shape[0] refs["shape_r", :points.shape[0]] = points[:, 0] refs["shape_z", :points.shape[0]] = points[:, 1] if self.x_points is not None: x_points = np.array(self.x_points) assert refs.names.count("x_points_r") >= x_points.shape[0] refs["x_points_r", :x_points.shape[0]] = x_points[:, 0] refs["x_points_z", :x_points.shape[0]] = x_points[:, 1] if self.legs is not None: legs = np.array(self.legs) assert refs.names.count("legs_r") >= legs.shape[0] refs["legs_r", :legs.shape[0]] = legs[:, 0] refs["legs_z", :legs.shape[0]] = legs[:, 1] if self.limit_point is not None: refs["limit_point_r", 0] = self.limit_point.r refs["limit_point_z", 0] = self.limit_point.z return refs def canonical(self) -> "Shape": """Return a canonical shape with a fixed number of points and params.""" num_points = tcv_common.REF_RANGES.count("shape_r") out = copy.deepcopy(self) if out.points is None: if out.params is None: raise ValueError("Can't canonicalize with no params or points.") out.points, center = out.params.gen_points(num_points) out.params.r0 = center.r out.params.z0 = center.z out.params.side = ShapeSide.NOSHIFT else: out.points = spline_interpolate_points( out.points, num_points, out.x_points or []) if out.params: out.params.side = ShapeSide.NOSHIFT else: # Copied from FGE. Details: https://doi.org/10.1017/S0022377815001270 top = max(out.points, key=lambda p: p.z) left = min(out.points, key=lambda p: p.r) right = max(out.points, key=lambda p: p.r) bottom = min(out.points, key=lambda p: p.z) center = Point((left.r + right.r) / 2, (top.z + bottom.z) / 2) radius = (right.r - left.r) / 2 kappa = (top.z - bottom.z) / (right.r - left.r) delta_lower = (center.r - bottom.r) / radius # upper triangularitiy delta_upper = (center.r - top.r) / radius # lower triangularity delta = (delta_lower + delta_upper) / 2 out.params = ParametrizedShape( r0=center.r, z0=center.z, radius=radius, kappa=kappa, delta=delta, lambda_=0, side=ShapeSide.NOSHIFT) return out def points_from_references( references: named_array.NamedArray, key: str = "shape1", num: Optional[int] = None) -> ShapePoints: points = np.array([references[f"{key}_r"], references[f"{key}_z"]]).T if num is not None: points = points[:num] return to_shape_points(points) @dataclasses.dataclass class ReferenceTimeSlice: shape: Shape time: float hold: Optional[float] = None # Absolute time. def __post_init__(self): if self.hold is None: self.hold = self.time def canonicalize_reference_series( time_slices: List[ReferenceTimeSlice]) -> List[ReferenceTimeSlice]: """Canonicalize a full sequence of time slices.""" outputs = [] for ref in time_slices: ref_shape = ref.shape.canonical() prev = outputs[-1] if outputs else None if prev is not None and prev.hold + tcv_common.DT < ref.time: leg_diff = len(ref_shape.legs or []) != len(prev.shape.legs or []) xp_diff = len(ref_shape.x_points or []) != len(prev.shape.x_points or []) div_diff = ref_shape.diverted != prev.shape.diverted limit_diff = ( bool(ref_shape.limit_point and ref_shape.limit_point.r > 0) != bool(prev.shape.limit_point and prev.shape.limit_point.r > 0)) if leg_diff or xp_diff or div_diff or limit_diff: # Try not to interpolate between a real x-point and a non-existent # x-point. Non-existent x-points are represented as being at the # origin, i.e. out to the left of the vessel, and could be interpolated # into place, but that's weird, so better to pop it into existence by # adding an extra frame one before with the new shape targets. # This doesn't handle the case of multiple points appearing/disappearing # out of order, or of one moving while the other disappears. outputs.append( ReferenceTimeSlice( time=ref.time - tcv_common.DT, shape=Shape( ip=ref_shape.ip, params=ref_shape.params, points=ref_shape.points, x_points=(prev.shape.x_points if xp_diff else ref_shape.x_points), legs=(prev.shape.legs if leg_diff else ref_shape.legs), limit_point=(prev.shape.limit_point if limit_diff else ref_shape.limit_point), diverted=(prev.shape.diverted if div_diff else ref_shape.diverted)))) outputs.append(ReferenceTimeSlice(ref_shape, ref.time, ref.hold)) return outputs
deepmind-research-master
fusion_tcv/shape.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for combiners.""" import math from absl.testing import absltest from fusion_tcv import combiners NAN = float("nan") class CombinersTest(absltest.TestCase): def assertNan(self, value): self.assertLen(value, 1) self.assertTrue(math.isnan(value[0])) def test_errors(self): c = combiners.Mean() with self.assertRaises(ValueError): c([0, 1], [1]) with self.assertRaises(ValueError): c([0, 1], [1, 2, 3]) with self.assertRaises(ValueError): c([0, 1], [-1, 2]) def test_mean(self): c = combiners.Mean() self.assertEqual(c([0, 2, 4]), [2]) self.assertEqual(c([0, 0.5, 1]), [0.5]) self.assertEqual(c([0, 0.5, 1], [0, 0, 1]), [1]) self.assertEqual(c([0, 1], [1, 3]), [0.75]) self.assertEqual(c([0, NAN], [1, 3]), [0]) self.assertNan(c([NAN, NAN], [1, 3])) def test_geometric_mean(self): c = combiners.GeometricMean() self.assertEqual(c([0.5, 0]), [0]) self.assertEqual(c([0.3]), [0.3]) self.assertEqual(c([4, 4]), [4]) self.assertEqual(c([0.5, 0.5]), [0.5]) self.assertEqual(c([0.5, 0.5], [1, 3]), [0.5]) self.assertEqual(c([0.5, 1], [1, 2]), [0.5**(1/3)]) self.assertEqual(c([0.5, 1], [2, 1]), [0.5**(2/3)]) self.assertEqual(c([0.5, 0], [2, 0]), [0.5]) self.assertEqual(c([0.5, 0, 0], [2, 1, 0]), [0]) self.assertEqual(c([0.5, NAN, 0], [2, 1, 0]), [0.5]) self.assertNan(c([NAN, NAN], [1, 3])) def test_multiply(self): c = combiners.Multiply() self.assertEqual(c([0.5, 0]), [0]) self.assertEqual(c([0.3]), [0.3]) self.assertEqual(c([0.5, 0.5]), [0.25]) self.assertEqual(c([0.5, 0.5], [1, 3]), [0.0625]) self.assertEqual(c([0.5, 1], [1, 2]), [0.5]) self.assertEqual(c([0.5, 1], [2, 1]), [0.25]) self.assertEqual(c([0.5, 0], [2, 0]), [0.25]) self.assertEqual(c([0.5, 0, 0], [2, 1, 0]), [0]) self.assertEqual(c([0.5, NAN], [1, 1]), [0.5]) self.assertNan(c([NAN, NAN], [1, 3])) def test_min(self): c = combiners.Min() self.assertEqual(c([0, 1]), [0]) self.assertEqual(c([0.5, 1]), [0.5]) self.assertEqual(c([1, 0.75]), [0.75]) self.assertEqual(c([1, 3]), [1]) self.assertEqual(c([1, 1, 3], [0, 1, 1]), [1]) self.assertEqual(c([NAN, 3]), [3]) self.assertNan(c([NAN, NAN], [1, 3])) def test_max(self): c = combiners.Max() self.assertEqual(c([0, 1]), [1]) self.assertEqual(c([0.5, 1]), [1]) self.assertEqual(c([1, 0.75]), [1]) self.assertEqual(c([1, 3]), [3]) self.assertEqual(c([1, 1, 3], [0, 1, 1]), [3]) self.assertEqual(c([NAN, 3]), [3]) self.assertNan(c([NAN, NAN], [1, 3])) def test_lnorm(self): c = combiners.LNorm(1) self.assertEqual(c([0, 2, 4]), [2]) self.assertEqual(c([0, 0.5, 1]), [0.5]) self.assertEqual(c([3, 4]), [7 / 2]) self.assertEqual(c([0, 2, 4], [1, 1, 0]), [1]) self.assertEqual(c([0, 2, NAN]), [1]) self.assertNan(c([NAN, NAN], [1, 3])) c = combiners.LNorm(1, normalized=False) self.assertEqual(c([0, 2, 4]), [6]) self.assertEqual(c([0, 0.5, 1]), [1.5]) self.assertEqual(c([3, 4]), [7]) c = combiners.LNorm(2) self.assertEqual(c([3, 4]), [5 / 2**0.5]) c = combiners.LNorm(2, normalized=False) self.assertEqual(c([3, 4]), [5]) c = combiners.LNorm(math.inf) self.assertAlmostEqual(c([3, 4])[0], 4) c = combiners.LNorm(math.inf, normalized=False) self.assertAlmostEqual(c([3, 4])[0], 4) def test_smoothmax(self): # Max c = combiners.SmoothMax(math.inf) self.assertEqual(c([0, 1]), [1]) self.assertEqual(c([0.5, 1]), [1]) self.assertEqual(c([1, 0.75]), [1]) self.assertEqual(c([1, 3]), [3]) # Smooth Max c = combiners.SmoothMax(1) self.assertAlmostEqual(c([0, 1])[0], 0.7310585786300049) # Mean c = combiners.SmoothMax(0) self.assertEqual(c([0, 2, 4]), [2]) self.assertEqual(c([0, 0.5, 1]), [0.5]) self.assertEqual(c([0, 0.5, 1], [0, 0, 1]), [1]) self.assertEqual(c([0, 2, NAN]), [1]) self.assertEqual(c([0, 2, NAN], [0, 1, 1]), [2]) self.assertAlmostEqual(c([0, 1], [1, 3])[0], 0.75) self.assertNan(c([NAN, NAN], [1, 3])) # Smooth Min c = combiners.SmoothMax(-1) self.assertEqual(c([0, 1])[0], 0.2689414213699951) # Min c = combiners.SmoothMax(-math.inf) self.assertEqual(c([0, 1]), [0]) self.assertEqual(c([0.5, 1]), [0.5]) self.assertEqual(c([1, 0.75]), [0.75]) self.assertEqual(c([1, 3]), [1]) if __name__ == "__main__": absltest.main()
deepmind-research-master
fusion_tcv/combiners_test.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Print the values of references.""" from typing import Sequence from absl import app from absl import flags from fusion_tcv import named_array from fusion_tcv import references from fusion_tcv import tcv_common _refs = flags.DEFINE_enum("refs", None, references.REFERENCES.keys(), "Which references to print") _count = flags.DEFINE_integer("count", 100, "How many timesteps to print.") _freq = flags.DEFINE_integer("freq", 1, "Print only every so often.") _fields = flags.DEFINE_multi_enum( "field", None, tcv_common.REF_RANGES.names(), "Which reference fields to print, default of all.") flags.mark_flag_as_required("refs") def print_ref(step: int, ref: named_array.NamedArray): print(f"Step: {step}") for k in (_fields.value or ref.names.names()): print(f" {k}: [{', '.join(f'{v:.3f}' for v in ref[k])}]") def main(argv: Sequence[str]) -> None: if len(argv) > 1: raise app.UsageError("Too many command-line arguments.") if _freq.value <= 0: raise app.UsageError("`freq` must be >0.") ref = references.REFERENCES[_refs.value]() print_ref(0, ref.reset()) for i in range(1, _count.value + 1): for _ in range(_freq.value - 1): ref.step() print_ref(i * _freq.value, ref.step()) print(f"Stopped after {_count.value * _freq.value} steps.") if __name__ == "__main__": app.run(main)
deepmind-research-master
fusion_tcv/references_main.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The rewards used in our experiments.""" from fusion_tcv import combiners from fusion_tcv import rewards from fusion_tcv import targets from fusion_tcv import transforms # Used in TCV#70915 FUNDAMENTAL_CAPABILITY = rewards.Reward([ rewards.Component( target=targets.ShapeLCFSDistance(), transforms=[transforms.SoftPlus(good=0.005, bad=0.05), combiners.SmoothMax(-1)]), rewards.Component( target=targets.XPointFar(), transforms=[transforms.Sigmoid(good=0.3, bad=0.1), combiners.SmoothMax(-5)]), rewards.Component( target=targets.LimitPoint(), transforms=[transforms.Sigmoid(bad=0.2, good=0.1)]), rewards.Component( target=targets.XPointNormalizedFlux(num_points=1), transforms=[transforms.SoftPlus(bad=0.08)]), rewards.Component( target=targets.XPointDistance(num_points=1), transforms=[transforms.Sigmoid(good=0.01, bad=0.15)]), rewards.Component( target=targets.XPointFluxGradient(num_points=1), transforms=[transforms.SoftPlus(bad=3)], weight=0.5), rewards.Component( target=targets.Ip(), transforms=[transforms.SoftPlus(good=500, bad=20000)]), rewards.Component( target=targets.OHCurrentsClose(), transforms=[transforms.SoftPlus(good=50, bad=1050)]), ], combiners.SmoothMax(-0.5)) # Used in TCV#70920 ELONGATION = rewards.Reward([ rewards.Component( target=targets.ShapeLCFSDistance(), transforms=[transforms.SoftPlus(good=0.003, bad=0.03), combiners.SmoothMax(-1)], weight=3), rewards.Component( target=targets.ShapeRadius(), transforms=[transforms.SoftPlus(good=0.002, bad=0.02)]), rewards.Component( target=targets.ShapeElongation(), transforms=[transforms.SoftPlus(good=0.005, bad=0.2)]), rewards.Component( target=targets.ShapeTriangularity(), transforms=[transforms.SoftPlus(good=0.005, bad=0.2)]), rewards.Component( target=targets.XPointCount(), transforms=[transforms.Equal()]), rewards.Component( target=targets.LimitPoint(), # Stay away from the top/baffles. transforms=[transforms.Sigmoid(bad=0.3, good=0.2)]), rewards.Component( target=targets.Ip(), transforms=[transforms.SoftPlus(good=500, bad=30000)]), rewards.Component( target=targets.VoltageOOB(), transforms=[combiners.Mean(), transforms.SoftPlus(bad=1)]), rewards.Component( target=targets.OHCurrentsClose(), transforms=[transforms.ClippedLinear(good=50, bad=1050)]), rewards.Component( name="CurrentsFarFromZero", target=targets.EFCurrents(), transforms=[transforms.Abs(), transforms.SoftPlus(good=100, bad=50), combiners.GeometricMean()]), ], combiner=combiners.SmoothMax(-5)) # Used in TCV#70600 ITER = rewards.Reward([ rewards.Component( target=targets.ShapeLCFSDistance(), transforms=[transforms.SoftPlus(good=0.005, bad=0.05), combiners.SmoothMax(-1)], weight=3), rewards.Component( target=targets.Diverted(), transforms=[transforms.Equal()]), rewards.Component( target=targets.XPointNormalizedFlux(num_points=2), transforms=[transforms.SoftPlus(bad=0.08)], weight=[1] * 2), rewards.Component( target=targets.XPointDistance(num_points=2), transforms=[transforms.Sigmoid(good=0.01, bad=0.15)], weight=[0.5] * 2), rewards.Component( target=targets.XPointFluxGradient(num_points=2), transforms=[transforms.SoftPlus(bad=3)], weight=[0.5] * 2), rewards.Component( target=targets.LegsNormalizedFlux(), transforms=[transforms.Sigmoid(good=0.1, bad=0.3), combiners.SmoothMax(-5)], weight=2), rewards.Component( target=targets.Ip(), transforms=[transforms.SoftPlus(good=500, bad=20000)], weight=2), rewards.Component( target=targets.VoltageOOB(), transforms=[combiners.Mean(), transforms.SoftPlus(bad=1)]), rewards.Component( target=targets.OHCurrentsClose(), transforms=[transforms.ClippedLinear(good=50, bad=1050)]), rewards.Component( name="CurrentsFarFromZero", target=targets.EFCurrents(), transforms=[transforms.Abs(), transforms.SoftPlus(good=100, bad=50), combiners.GeometricMean()]), ], combiner=combiners.SmoothMax(-5)) # Used in TCV#70755 SNOWFLAKE = rewards.Reward([ rewards.Component( target=targets.ShapeLCFSDistance(), transforms=[transforms.SoftPlus(good=0.005, bad=0.05), combiners.SmoothMax(-1)], weight=3), rewards.Component( target=targets.LimitPoint(), transforms=[transforms.Sigmoid(bad=0.2, good=0.1)]), rewards.Component( target=targets.XPointNormalizedFlux(num_points=2), transforms=[transforms.SoftPlus(bad=0.08)], weight=[1] * 2), rewards.Component( target=targets.XPointDistance(num_points=2), transforms=[transforms.Sigmoid(good=0.01, bad=0.15)], weight=[0.5] * 2), rewards.Component( target=targets.XPointFluxGradient(num_points=2), transforms=[transforms.SoftPlus(bad=3)], weight=[0.5] * 2), rewards.Component( target=targets.LegsNormalizedFlux(), transforms=[transforms.Sigmoid(good=0.1, bad=0.3), combiners.SmoothMax(-5)], weight=2), rewards.Component( target=targets.Ip(), transforms=[transforms.SoftPlus(good=500, bad=20000)], weight=2), rewards.Component( target=targets.VoltageOOB(), transforms=[combiners.Mean(), transforms.SoftPlus(bad=1)]), rewards.Component( target=targets.OHCurrentsClose(), transforms=[transforms.ClippedLinear(good=50, bad=1050)]), rewards.Component( name="CurrentsFarFromZero", target=targets.EFCurrents(), transforms=[transforms.Abs(), transforms.SoftPlus(good=100, bad=50), combiners.GeometricMean()]), ], combiner=combiners.SmoothMax(-5)) # Used in TCV#70457 NEGATIVE_TRIANGULARITY = rewards.Reward([ rewards.Component( target=targets.ShapeLCFSDistance(), transforms=[transforms.SoftPlus(good=0.005, bad=0.05), combiners.SmoothMax(-1)], weight=3), rewards.Component( target=targets.ShapeRadius(), transforms=[transforms.SoftPlus(bad=0.04)]), rewards.Component( target=targets.ShapeElongation(), transforms=[transforms.SoftPlus(bad=0.5)]), rewards.Component( target=targets.ShapeTriangularity(), transforms=[transforms.SoftPlus(bad=0.5)]), rewards.Component( target=targets.Diverted(), transforms=[transforms.Equal()]), rewards.Component( target=targets.XPointNormalizedFlux(num_points=2), transforms=[transforms.SoftPlus(bad=0.08)], weight=[1] * 2), rewards.Component( target=targets.XPointDistance(num_points=2), transforms=[transforms.Sigmoid(good=0.02, bad=0.15)], weight=[0.5] * 2), rewards.Component( target=targets.XPointFluxGradient(num_points=2), transforms=[transforms.SoftPlus(bad=3)], weight=[0.5] * 2), rewards.Component( target=targets.Ip(), transforms=[transforms.SoftPlus(good=500, bad=20000)], weight=2), rewards.Component( target=targets.VoltageOOB(), transforms=[combiners.Mean(), transforms.SoftPlus(bad=1)]), rewards.Component( target=targets.OHCurrentsClose(), transforms=[transforms.ClippedLinear(good=50, bad=1050)]), rewards.Component( name="CurrentsFarFromZero", target=targets.EFCurrents(), transforms=[transforms.Abs(), transforms.SoftPlus(good=100, bad=50), combiners.GeometricMean()]), ], combiner=combiners.SmoothMax(-0.5)) # Used in TCV#69545 DROPLETS = rewards.Reward([ rewards.Component( target=targets.R(indices=[0, 1]), transforms=[transforms.Sigmoid(good=0.02, bad=0.5)], weight=[1, 1]), rewards.Component( target=targets.Z(indices=[0, 1]), transforms=[transforms.Sigmoid(good=0.02, bad=0.2)], weight=[1, 1]), rewards.Component( target=targets.Ip(indices=[0, 1]), transforms=[transforms.Sigmoid(good=2000, bad=20000)], weight=[1, 1]), rewards.Component( target=targets.OHCurrentsClose(), transforms=[transforms.ClippedLinear(good=50, bad=1050)]), ], combiner=combiners.GeometricMean())
deepmind-research-master
fusion_tcv/rewards_used.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Smart module export/import utilities.""" import inspect import pickle import tensorflow.compat.v1 as tf from tensorflow.compat.v1.io import gfile import tensorflow_hub as hub import tree as nest import wrapt _ALLOWED_TYPES = (bool, float, int, str) def _getcallargs(signature, *args, **kwargs): bound_args = signature.bind(*args, **kwargs) bound_args.apply_defaults() inputs = bound_args.arguments inputs.pop("self", None) return inputs def _to_placeholder(arg): if arg is None or isinstance(arg, bool): return arg arg = tf.convert_to_tensor(arg) return tf.placeholder(dtype=arg.dtype, shape=arg.shape) class SmartModuleExport(object): """Helper class for exporting TF-Hub modules.""" def __init__(self, object_factory): self._object_factory = object_factory self._wrapped_object = self._object_factory() self._variable_scope = tf.get_variable_scope() self._captured_calls = {} self._captured_attrs = {} def _create_captured_method(self, method_name): """Creates a wrapped method that captures its inputs.""" with tf.variable_scope(self._variable_scope): method_ = getattr(self._wrapped_object, method_name) @wrapt.decorator def wrapper(method, instance, args, kwargs): """Wrapped method to capture inputs.""" del instance specs = inspect.signature(method) inputs = _getcallargs(specs, *args, **kwargs) with tf.variable_scope(self._variable_scope): output = method(*args, **kwargs) self._captured_calls[method_name] = [inputs, specs] return output return wrapper(method_) # pylint: disable=no-value-for-parameter def __getattr__(self, name): """Helper method for accessing an attributes of the wrapped object.""" # if "_wrapped_object" not in self.__dict__: # return super(ExportableModule, self).__getattr__(name) with tf.variable_scope(self._variable_scope): attr = getattr(self._wrapped_object, name) if inspect.ismethod(attr) or inspect.isfunction(attr): return self._create_captured_method(name) else: if all([isinstance(v, _ALLOWED_TYPES) for v in nest.flatten(attr)]): self._captured_attrs[name] = attr return attr def __call__(self, *args, **kwargs): return self._create_captured_method("__call__")(*args, **kwargs) def export(self, path, session, overwrite=False): """Build the TF-Hub spec, module and sync ops.""" method_specs = {} def module_fn(): """A module_fn for use with hub.create_module_spec().""" # We will use a copy of the original object to build the graph. wrapped_object = self._object_factory() for method_name, method_info in self._captured_calls.items(): captured_inputs, captured_specs = method_info tensor_inputs = nest.map_structure(_to_placeholder, captured_inputs) method_to_call = getattr(wrapped_object, method_name) tensor_outputs = method_to_call(**tensor_inputs) flat_tensor_inputs = nest.flatten(tensor_inputs) flat_tensor_inputs = { str(k): v for k, v in zip( range(len(flat_tensor_inputs)), flat_tensor_inputs) } flat_tensor_outputs = nest.flatten(tensor_outputs) flat_tensor_outputs = { str(k): v for k, v in zip( range(len(flat_tensor_outputs)), flat_tensor_outputs) } method_specs[method_name] = dict( specs=captured_specs, inputs=nest.map_structure(lambda _: None, tensor_inputs), outputs=nest.map_structure(lambda _: None, tensor_outputs)) signature_name = ("default" if method_name == "__call__" else method_name) hub.add_signature(signature_name, flat_tensor_inputs, flat_tensor_outputs) hub.attach_message( "methods", tf.train.BytesList(value=[pickle.dumps(method_specs)])) hub.attach_message( "properties", tf.train.BytesList(value=[pickle.dumps(self._captured_attrs)])) # Create the spec that will be later used in export. hub_spec = hub.create_module_spec(module_fn, drop_collections=["sonnet"]) # Get variables values module_weights = [ session.run(v) for v in self._wrapped_object.get_all_variables() ] # create the sync ops with tf.Graph().as_default(): hub_module = hub.Module(hub_spec, trainable=True, name="hub") assign_ops = [] assign_phs = [] for _, v in sorted(hub_module.variable_map.items()): ph = tf.placeholder(shape=v.shape, dtype=v.dtype) assign_phs.append(ph) assign_ops.append(tf.assign(v, ph)) with tf.Session() as module_session: module_session.run(tf.local_variables_initializer()) module_session.run(tf.global_variables_initializer()) module_session.run( assign_ops, feed_dict=dict(zip(assign_phs, module_weights))) if overwrite and gfile.exists(path): gfile.rmtree(path) gfile.makedirs(path) hub_module.export(path, module_session) class SmartModuleImport(object): """A class for importing graph building objects from TF-Hub modules.""" def __init__(self, module): self._module = module self._method_specs = pickle.loads( self._module.get_attached_message("methods", tf.train.BytesList).value[0]) self._properties = pickle.loads( self._module.get_attached_message("properties", tf.train.BytesList).value[0]) def _create_wrapped_method(self, method): """Creates a wrapped method that converts nested inputs and outputs.""" def wrapped_method(*args, **kwargs): """A wrapped method around a TF-Hub module signature.""" inputs = _getcallargs(self._method_specs[method]["specs"], *args, **kwargs) nest.assert_same_structure(self._method_specs[method]["inputs"], inputs) flat_inputs = nest.flatten(inputs) flat_inputs = { str(k): v for k, v in zip(range(len(flat_inputs)), flat_inputs) } signature = "default" if method == "__call__" else method flat_outputs = self._module( flat_inputs, signature=signature, as_dict=True) flat_outputs = [v for _, v in sorted(flat_outputs.items())] output_spec = self._method_specs[method]["outputs"] if output_spec is None: if len(flat_outputs) != 1: raise ValueError( "Expected output containing a single tensor, found {}".format( flat_outputs)) outputs = flat_outputs[0] else: outputs = nest.unflatten_as(output_spec, flat_outputs) return outputs return wrapped_method def __getattr__(self, name): if name in self._method_specs: return self._create_wrapped_method(name) if name in self._properties: return self._properties[name] return getattr(self._module, name) def __call__(self, *args, **kwargs): return self._create_wrapped_method("__call__")(*args, **kwargs)
deepmind-research-master
option_keyboard/smart_module.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Environment with keyboard.""" import itertools from absl import logging import dm_env import numpy as np import tensorflow.compat.v1 as tf import tensorflow_hub as hub import tree from option_keyboard import smart_module class EnvironmentWithLogging(dm_env.Environment): """Wraps an environment with additional logging.""" def __init__(self, env): self._env = env self._episode_return = 0 def reset(self): self._episode_return = 0 return self._env.reset() def step(self, action): """Take action in the environment and do some logging.""" step = self._env.step(action) if step.first(): step = self._env.step(action) self._episode_return = 0 self._episode_return += step.reward return step @property def episode_return(self): return self._episode_return def action_spec(self): return self._env.action_spec() def observation_spec(self): return self._env.observation_spec() def __getattr__(self, name): return getattr(self._env, name) class EnvironmentWithKeyboard(dm_env.Environment): """Wraps an environment with a keyboard.""" def __init__(self, env, keyboard, keyboard_ckpt_path, n_actions_per_dim, additional_discount, call_and_return=False): self._env = env self._keyboard = keyboard self._discount = additional_discount self._call_and_return = call_and_return options = _discretize_actions(n_actions_per_dim, keyboard.num_cumulants) self._options_np = options options = tf.convert_to_tensor(options, dtype=tf.float32) self._options = options obs_spec = self._extract_observation(env.observation_spec()) obs_ph = tf.placeholder(shape=obs_spec.shape, dtype=obs_spec.dtype) option_ph = tf.placeholder(shape=(), dtype=tf.int32) gpi_action = self._keyboard.gpi(obs_ph, options[option_ph]) session = tf.Session() self._gpi_action = session.make_callable(gpi_action, [obs_ph, option_ph]) self._keyboard_action = session.make_callable( self._keyboard(tf.expand_dims(obs_ph, axis=0))[0], [obs_ph]) session.run(tf.global_variables_initializer()) if keyboard_ckpt_path: saver = tf.train.Saver(var_list=keyboard.variables) saver.restore(session, keyboard_ckpt_path) def _compute_reward(self, option, obs): return np.sum(self._options_np[option] * obs["cumulants"]) def reset(self): return self._env.reset() def step(self, option): """Take a step in the keyboard, then the environment.""" step_count = 0 option_step = None while True: obs = self._extract_observation(self._env.observation()) action = self._gpi_action(obs, option) action_step = self._env.step(action) step_count += 1 if option_step is None: option_step = action_step else: new_discount = ( option_step.discount * self._discount * action_step.discount) new_reward = ( option_step.reward + new_discount * action_step.reward) option_step = option_step._replace( observation=action_step.observation, reward=new_reward, discount=new_discount, step_type=action_step.step_type) if action_step.last(): break # Terminate option. if self._should_terminate(option, action_step.observation): break if not self._call_and_return: break return option_step def _should_terminate(self, option, obs): if self._compute_reward(option, obs) > 0: return True elif np.all(self._options_np[option] <= 0): # TODO(shaobohou) A hack ensure option with non-positive weights # terminates after one step return True else: return False def action_spec(self): return dm_env.specs.DiscreteArray( num_values=self._options_np.shape[0], name="action") def _extract_observation(self, obs): return obs["arena"] def observation_spec(self): return self._env.observation_spec() def __getattr__(self, name): return getattr(self._env, name) class EnvironmentWithKeyboardDirect(dm_env.Environment): """Wraps an environment with a keyboard. This is different from EnvironmentWithKeyboard as the actions space is not discretized. TODO(shaobohou) Merge the two implementations. """ def __init__(self, env, keyboard, keyboard_ckpt_path, additional_discount, call_and_return=False): self._env = env self._keyboard = keyboard self._discount = additional_discount self._call_and_return = call_and_return obs_spec = self._extract_observation(env.observation_spec()) obs_ph = tf.placeholder(shape=obs_spec.shape, dtype=obs_spec.dtype) option_ph = tf.placeholder( shape=(keyboard.num_cumulants,), dtype=tf.float32) gpi_action = self._keyboard.gpi(obs_ph, option_ph) session = tf.Session() self._gpi_action = session.make_callable(gpi_action, [obs_ph, option_ph]) self._keyboard_action = session.make_callable( self._keyboard(tf.expand_dims(obs_ph, axis=0))[0], [obs_ph]) session.run(tf.global_variables_initializer()) if keyboard_ckpt_path: saver = tf.train.Saver(var_list=keyboard.variables) saver.restore(session, keyboard_ckpt_path) def _compute_reward(self, option, obs): assert option.shape == obs["cumulants"].shape return np.sum(option * obs["cumulants"]) def reset(self): return self._env.reset() def step(self, option): """Take a step in the keyboard, then the environment.""" step_count = 0 option_step = None while True: obs = self._extract_observation(self._env.observation()) action = self._gpi_action(obs, option) action_step = self._env.step(action) step_count += 1 if option_step is None: option_step = action_step else: new_discount = ( option_step.discount * self._discount * action_step.discount) new_reward = ( option_step.reward + new_discount * action_step.reward) option_step = option_step._replace( observation=action_step.observation, reward=new_reward, discount=new_discount, step_type=action_step.step_type) if action_step.last(): break # Terminate option. if self._should_terminate(option, action_step.observation): break if not self._call_and_return: break return option_step def _should_terminate(self, option, obs): if self._compute_reward(option, obs) > 0: return True elif np.all(option <= 0): # TODO(shaobohou) A hack ensure option with non-positive weights # terminates after one step return True else: return False def action_spec(self): return dm_env.specs.BoundedArray(shape=(self._keyboard.num_cumulants,), dtype=np.float32, minimum=-1.0, maximum=1.0, name="action") def _extract_observation(self, obs): return obs["arena"] def observation_spec(self): return self._env.observation_spec() def __getattr__(self, name): return getattr(self._env, name) def _discretize_actions(num_actions_per_dim, action_space_dim, min_val=-1.0, max_val=1.0): """Discrete action space.""" if num_actions_per_dim > 1: discretized_dim_action = np.linspace( min_val, max_val, num_actions_per_dim, endpoint=True) discretized_actions = [discretized_dim_action] * action_space_dim discretized_actions = itertools.product(*discretized_actions) discretized_actions = list(discretized_actions) elif num_actions_per_dim == 1: discretized_actions = [ max_val * np.eye(action_space_dim), min_val * np.eye(action_space_dim), ] discretized_actions = np.concatenate(discretized_actions, axis=0) elif num_actions_per_dim == 0: discretized_actions = np.eye(action_space_dim) else: raise ValueError( "Unsupported num_actions_per_dim {}".format(num_actions_per_dim)) discretized_actions = np.array(discretized_actions) # Remove options with all zeros. non_zero_entries = np.sum(np.square(discretized_actions), axis=-1) != 0.0 discretized_actions = discretized_actions[non_zero_entries] logging.info("Total number of discretized actions: %s", len(discretized_actions)) logging.info("Discretized actions: %s", discretized_actions) return discretized_actions class EnvironmentWithLearnedPhi(dm_env.Environment): """Wraps an environment with learned phi model.""" def __init__(self, env, model_path): self._env = env create_ph = lambda x: tf.placeholder(shape=x.shape, dtype=x.dtype) add_batch = lambda x: tf.expand_dims(x, axis=0) # Make session and callables. with tf.Graph().as_default(): model = smart_module.SmartModuleImport(hub.Module(model_path)) obs_spec = env.observation_spec() obs_ph = tree.map_structure(create_ph, obs_spec) action_ph = tf.placeholder(shape=(), dtype=tf.int32) phis = model(tree.map_structure(add_batch, obs_ph), add_batch(action_ph)) self.num_phis = phis.shape.as_list()[-1] self._last_phis = np.zeros((self.num_phis,), dtype=np.float32) session = tf.Session() self._session = session self._phis_fn = session.make_callable( phis[0], tree.flatten([obs_ph, action_ph])) self._session.run(tf.global_variables_initializer()) def reset(self): self._last_phis = np.zeros((self.num_phis,), dtype=np.float32) return self._env.reset() def step(self, action): """Take action in the environment and do some logging.""" phis = self._phis_fn(*tree.flatten([self._env.observation(), action])) step = self._env.step(action) if step.first(): phis = self._phis_fn(*tree.flatten([self._env.observation(), action])) step = self._env.step(action) step.observation["cumulants"] = phis self._last_phis = phis return step def action_spec(self): return self._env.action_spec() def observation(self): obs = self._env.observation() obs["cumulants"] = self._last_phis return obs def observation_spec(self): obs_spec = self._env.observation_spec() obs_spec["cumulants"] = dm_env.specs.BoundedArray( shape=(self.num_phis,), dtype=np.float32, minimum=-1e9, maximum=1e9, name="collected_resources") return obs_spec def __getattr__(self, name): return getattr(self._env, name)
deepmind-research-master
option_keyboard/environment_wrappers.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Environment configurations.""" def get_task_config(): return dict( arena_size=11, num_channels=2, max_num_steps=50, # 50 for the actual task. num_init_objects=10, object_priors=[0.5, 0.5], egocentric=True, rewarder="BalancedCollectionRewarder", ) def get_pretrain_config(): return dict( arena_size=11, num_channels=2, max_num_steps=40, # 40 for pretraining. num_init_objects=10, object_priors=[0.5, 0.5], egocentric=True, default_w=(1, 1), ) def get_fig4_task_config(): return dict( arena_size=11, num_channels=2, max_num_steps=50, # 50 for the actual task. num_init_objects=10, object_priors=[0.5, 0.5], egocentric=True, default_w=(1, -1), ) def get_fig5_task_config(default_w): return dict( arena_size=11, num_channels=2, max_num_steps=50, # 50 for the actual task. num_init_objects=10, object_priors=[0.5, 0.5], egocentric=True, default_w=default_w, )
deepmind-research-master
option_keyboard/configs.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Simple Scavenger environment.""" import copy import enum import sys import dm_env import numpy as np from option_keyboard import auto_reset_environment this_module = sys.modules[__name__] class Action(enum.IntEnum): """Actions available to the player.""" UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 def _one_hot(indices, depth): return np.eye(depth)[indices] def _random_pos(arena_size): return tuple(np.random.randint(0, arena_size, size=[2]).tolist()) class Scavenger(auto_reset_environment.Base): """Simple Scavenger.""" def __init__(self, arena_size, num_channels, max_num_steps, default_w=None, num_init_objects=15, object_priors=None, egocentric=True, rewarder=None, aux_tasks_w=None): self._arena_size = arena_size self._num_channels = num_channels self._max_num_steps = max_num_steps self._num_init_objects = num_init_objects self._egocentric = egocentric self._rewarder = ( getattr(this_module, rewarder)() if rewarder is not None else None) self._aux_tasks_w = aux_tasks_w if object_priors is None: self._object_priors = np.ones(num_channels) / num_channels else: assert len(object_priors) == num_channels self._object_priors = np.array(object_priors) / np.sum(object_priors) if default_w is None: self._default_w = np.ones(shape=(num_channels,)) else: self._default_w = default_w self._num_channels_all = self._num_channels + 2 self._step_in_episode = None @property def state(self): return copy.deepcopy([ self._step_in_episode, self._walls, self._objects, self._player_pos, self._prev_collected, ]) def set_state(self, state): state_ = copy.deepcopy(state) self._step_in_episode = state_[0] self._walls = state_[1] self._objects = state_[2] self._player_pos = state_[3] self._prev_collected = state_[4] @property def player_pos(self): return self._player_pos def _reset(self): self._step_in_episode = 0 # Walls. self._walls = [] for col in range(self._arena_size): new_pos = (0, col) if new_pos not in self._walls: self._walls.append(new_pos) for row in range(self._arena_size): new_pos = (row, 0) if new_pos not in self._walls: self._walls.append(new_pos) # Objects. self._objects = dict() for _ in range(self._num_init_objects): while True: new_pos = _random_pos(self._arena_size) if new_pos not in self._objects and new_pos not in self._walls: self._objects[new_pos] = np.random.multinomial(1, self._object_priors) break # Player self._player_pos = _random_pos(self._arena_size) while self._player_pos in self._objects or self._player_pos in self._walls: self._player_pos = _random_pos(self._arena_size) self._prev_collected = np.zeros(shape=(self._num_channels,)) obs = self.observation() return dm_env.restart(obs) def _step(self, action): self._step_in_episode += 1 if action == Action.UP: new_player_pos = (self._player_pos[0], self._player_pos[1] + 1) elif action == Action.DOWN: new_player_pos = (self._player_pos[0], self._player_pos[1] - 1) elif action == Action.LEFT: new_player_pos = (self._player_pos[0] - 1, self._player_pos[1]) elif action == Action.RIGHT: new_player_pos = (self._player_pos[0] + 1, self._player_pos[1]) else: raise ValueError("Invalid action `{}`".format(action)) # Toroidal. new_player_pos = ( (new_player_pos[0] + self._arena_size) % self._arena_size, (new_player_pos[1] + self._arena_size) % self._arena_size, ) if new_player_pos not in self._walls: self._player_pos = new_player_pos # Compute rewards. consumed = self._objects.pop(self._player_pos, np.zeros(shape=(self._num_channels,))) if self._rewarder is None: reward = np.dot(consumed, np.array(self._default_w)) else: reward = self._rewarder.get_reward(self.state, consumed) self._prev_collected = np.copy(consumed) assert self._player_pos not in self._objects assert self._player_pos not in self._walls # Render everything. obs = self.observation() if self._step_in_episode < self._max_num_steps: return dm_env.transition(reward=reward, observation=obs) else: # termination with discount=1.0 return dm_env.truncation(reward=reward, observation=obs) def observation(self, force_non_egocentric=False): arena_shape = [self._arena_size] * 2 + [self._num_channels_all] arena = np.zeros(shape=arena_shape, dtype=np.float32) def offset_position(pos_): use_egocentric = self._egocentric and not force_non_egocentric offset = self._player_pos if use_egocentric else (0, 0) x = (pos_[0] - offset[0] + self._arena_size) % self._arena_size y = (pos_[1] - offset[1] + self._arena_size) % self._arena_size return (x, y) player_pos = offset_position(self._player_pos) arena[player_pos] = _one_hot(self._num_channels, self._num_channels_all) for pos, obj in self._objects.items(): x, y = offset_position(pos) arena[x, y, :self._num_channels] = obj for pos in self._walls: x, y = offset_position(pos) arena[x, y] = _one_hot(self._num_channels + 1, self._num_channels_all) collected_resources = np.copy(self._prev_collected).astype(np.float32) obs = dict( arena=arena, cumulants=collected_resources, ) if self._aux_tasks_w is not None: obs["aux_tasks_reward"] = np.dot( np.array(self._aux_tasks_w), self._prev_collected).astype(np.float32) return obs def observation_spec(self): arena = dm_env.specs.BoundedArray( shape=(self._arena_size, self._arena_size, self._num_channels_all), dtype=np.float32, minimum=0., maximum=1., name="arena") collected_resources = dm_env.specs.BoundedArray( shape=(self._num_channels,), dtype=np.float32, minimum=-1e9, maximum=1e9, name="collected_resources") obs_spec = dict( arena=arena, cumulants=collected_resources, ) if self._aux_tasks_w is not None: obs_spec["aux_tasks_reward"] = dm_env.specs.BoundedArray( shape=(len(self._aux_tasks_w),), dtype=np.float32, minimum=-1e9, maximum=1e9, name="aux_tasks_reward") return obs_spec def action_spec(self): return dm_env.specs.DiscreteArray(num_values=len(Action), name="action") class SequentialCollectionRewarder(object): """SequentialCollectionRewarder.""" def get_reward(self, state, consumed): """Get reward.""" object_counts = sum(list(state[2].values()) + [np.zeros(len(consumed))]) reward = 0.0 if np.sum(consumed) > 0: for i in range(len(consumed)): if np.all(object_counts[:i] <= object_counts[i]): reward += consumed[i] else: reward -= consumed[i] return reward class BalancedCollectionRewarder(object): """BalancedCollectionRewarder.""" def get_reward(self, state, consumed): """Get reward.""" object_counts = sum(list(state[2].values()) + [np.zeros(len(consumed))]) reward = 0.0 if np.sum(consumed) > 0: for i in range(len(consumed)): if (object_counts[i] + consumed[i]) >= np.max(object_counts): reward += consumed[i] else: reward -= consumed[i] return reward
deepmind-research-master
option_keyboard/scavenger.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Keyboard agent.""" import os import numpy as np import sonnet as snt import tensorflow.compat.v1 as tf from option_keyboard import smart_module class Agent(): """An Option Keyboard Agent.""" def __init__( self, obs_spec, action_spec, policy_weights, network_kwargs, epsilon, additional_discount, batch_size, optimizer_name, optimizer_kwargs, ): """A simple DQN agent. Args: obs_spec: The observation spec. action_spec: The action spec. policy_weights: A list of vectors each representing the cumulant weights for that particular option/policy. network_kwargs: Keyword arguments for snt.nets.MLP epsilon: Exploration probability. additional_discount: Discount on returns used by the agent. batch_size: Size of update batch. optimizer_name: Name of an optimizer from tf.train optimizer_kwargs: Keyword arguments for the optimizer. """ tf.logging.info(policy_weights) self._policy_weights = tf.convert_to_tensor( policy_weights, dtype=tf.float32) self._current_policy = None self._epsilon = epsilon self._additional_discount = additional_discount self._batch_size = batch_size self._n_actions = action_spec.num_values self._n_policies, self._n_cumulants = policy_weights.shape def create_network(): return OptionValueNet( self._n_policies, self._n_cumulants, self._n_actions, network_kwargs=network_kwargs, ) self._network = smart_module.SmartModuleExport(create_network) self._replay = [] obs_spec = self._extract_observation(obs_spec) def option_values(values, policy): return tf.tensordot( values[:, policy, ...], self._policy_weights[policy], axes=[1, 0]) # Placeholders for policy. o = tf.placeholder(shape=obs_spec.shape, dtype=obs_spec.dtype) p = tf.placeholder(shape=(), dtype=tf.int32) q = self._network(tf.expand_dims(o, axis=0)) qo = option_values(q, p) # Placeholders for update. o_tm1 = tf.placeholder(shape=(None,) + obs_spec.shape, dtype=obs_spec.dtype) a_tm1 = tf.placeholder(shape=(None,), dtype=tf.int32) c_t = tf.placeholder(shape=(None, self._n_cumulants), dtype=tf.float32) d_t = tf.placeholder(shape=(None,), dtype=tf.float32) o_t = tf.placeholder(shape=(None,) + obs_spec.shape, dtype=obs_spec.dtype) # Compute values over all options. q_tm1 = self._network(o_tm1) q_t = self._network(o_t) qo_t = option_values(q_t, p) a_t = tf.cast(tf.argmax(qo_t, axis=-1), tf.int32) qa_tm1 = _batched_index(q_tm1[:, p, ...], a_tm1) qa_t = _batched_index(q_t[:, p, ...], a_t) # TD error g = additional_discount * tf.expand_dims(d_t, axis=-1) td_error = tf.stop_gradient(c_t + g * qa_t) - qa_tm1 loss = tf.reduce_sum(tf.square(td_error) / 2) # Dummy calls to keyboard for SmartModule _ = self._network.gpi(o_tm1[0], c_t[0]) _ = self._network.num_cumulants _ = self._network.num_policies _ = self._network.num_actions with tf.variable_scope("optimizer"): self._optimizer = getattr(tf.train, optimizer_name)(**optimizer_kwargs) train_op = self._optimizer.minimize(loss) # Make session and callables. session = tf.Session() self._session = session self._update_fn = session.make_callable( train_op, [o_tm1, a_tm1, c_t, d_t, o_t, p]) self._value_fn = session.make_callable(qo, [o, p]) session.run(tf.global_variables_initializer()) self._saver = tf.train.Saver(var_list=self._network.variables) @property def keyboard(self): return self._network def _extract_observation(self, obs): return obs["arena"] def step(self, timestep, is_training=False): """Select actions according to epsilon-greedy policy.""" if timestep.first(): self._current_policy = np.random.randint(self._n_policies) if is_training and np.random.rand() < self._epsilon: return np.random.randint(self._n_actions) q_values = self._value_fn( self._extract_observation(timestep.observation), self._current_policy) return int(np.argmax(q_values)) def update(self, step_tm1, action, step_t): """Takes in a transition from the environment.""" transition = [ self._extract_observation(step_tm1.observation), action, step_t.observation["cumulants"], step_t.discount, self._extract_observation(step_t.observation), ] self._replay.append(transition) if len(self._replay) == self._batch_size: batch = list(zip(*self._replay)) + [self._current_policy] self._update_fn(*batch) self._replay = [] # Just a queue. def export(self, path): tf.logging.info("Exporting keyboard to %s", path) self._network.export( os.path.join(path, "tfhub"), self._session, overwrite=True) self._saver.save(self._session, os.path.join(path, "checkpoints")) class OptionValueNet(snt.AbstractModule): """Option Value net.""" def __init__(self, n_policies, n_cumulants, n_actions, network_kwargs, name="option_keyboard"): """Construct an Option Value Net sonnet module. Args: n_policies: Number of policies. n_cumulants: Number of cumulants. n_actions: Number of actions. network_kwargs: Network arguments. name: Name """ super(OptionValueNet, self).__init__(name=name) self._n_policies = n_policies self._n_cumulants = n_cumulants self._n_actions = n_actions self._network_kwargs = network_kwargs def _build(self, observation): values = [] flat_obs = snt.BatchFlatten()(observation) for _ in range(self._n_cumulants): net = snt.nets.MLP(**self._network_kwargs)(flat_obs) net = snt.Linear(output_size=self._n_policies * self._n_actions)(net) net = snt.BatchReshape([self._n_policies, self._n_actions])(net) values.append(net) values = tf.stack(values, axis=2) return values def gpi(self, observation, cumulant_weights): q_values = self.__call__(tf.expand_dims(observation, axis=0))[0] q_w = tf.tensordot(q_values, cumulant_weights, axes=[1, 0]) # [P,a] q_w_actions = tf.reduce_max(q_w, axis=0) action = tf.cast(tf.argmax(q_w_actions), tf.int32) return action @property def num_cumulants(self): return self._n_cumulants @property def num_policies(self): return self._n_policies @property def num_actions(self): return self._n_actions def _batched_index(values, indices): one_hot_indices = tf.one_hot(indices, values.shape[-1], dtype=values.dtype) one_hot_indices = tf.expand_dims(one_hot_indices, axis=1) return tf.reduce_sum(values * one_hot_indices, axis=-1)
deepmind-research-master
option_keyboard/keyboard_agent.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Keyboard utils.""" import numpy as np from option_keyboard import configs from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import keyboard_agent from option_keyboard import scavenger def create_and_train_keyboard(num_episodes, policy_weights=None, export_path=None): """Train an option keyboard.""" if policy_weights is None: policy_weights = np.eye(2, dtype=np.float32) env_config = configs.get_pretrain_config() env = scavenger.Scavenger(**env_config) env = environment_wrappers.EnvironmentWithLogging(env) agent = keyboard_agent.Agent( obs_spec=env.observation_spec(), action_spec=env.action_spec(), policy_weights=policy_weights, network_kwargs=dict( output_sizes=(64, 128), activate_final=True, ), epsilon=0.1, additional_discount=0.9, batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-4,)) if num_episodes: experiment.run(env, agent, num_episodes=num_episodes) agent.export(export_path) return agent def create_and_train_keyboard_with_phi(num_episodes, phi_model_path, policy_weights, export_path=None): """Train an option keyboard.""" env_config = configs.get_pretrain_config() env = scavenger.Scavenger(**env_config) env = environment_wrappers.EnvironmentWithLogging(env) env = environment_wrappers.EnvironmentWithLearnedPhi(env, phi_model_path) agent = keyboard_agent.Agent( obs_spec=env.observation_spec(), action_spec=env.action_spec(), policy_weights=policy_weights, network_kwargs=dict( output_sizes=(64, 128), activate_final=True, ), epsilon=0.1, additional_discount=0.9, batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-4,)) if num_episodes: experiment.run(env, agent, num_episodes=num_episodes) agent.export(export_path) return agent
deepmind-research-master
option_keyboard/keyboard_utils.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Run an experiment.""" from absl import app from absl import flags import tensorflow.compat.v1 as tf from option_keyboard import configs from option_keyboard import dqn_agent from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 10000, "Number of training episodes.") flags.DEFINE_integer("report_every", 200, "Frequency at which metrics are reported.") flags.DEFINE_string("output_path", None, "Path to write out training curves.") def main(argv): del argv # Create the task environment. env_config = configs.get_task_config() env = scavenger.Scavenger(**env_config) env = environment_wrappers.EnvironmentWithLogging(env) # Create the flat agent. agent = dqn_agent.Agent( obs_spec=env.observation_spec(), action_spec=env.action_spec(), network_kwargs=dict( output_sizes=(64, 128), activate_final=True, ), epsilon=0.1, additional_discount=0.9, batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-4,)) _, ema_returns = experiment.run( env, agent, num_episodes=FLAGS.num_episodes, report_every=FLAGS.report_every) if FLAGS.output_path: experiment.write_returns_to_file(FLAGS.output_path, ema_returns) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/run_dqn.py
# pylint: disable=g-bad-file-header # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for training a keyboard and then running a DQN agent on top of it.""" from absl import flags from absl.testing import absltest import tensorflow.compat.v1 as tf from option_keyboard import run_ok FLAGS = flags.FLAGS class RunDQNTest(absltest.TestCase): def test_run(self): FLAGS.num_episodes = 200 FLAGS.num_pretrain_episodes = 200 run_ok.main(None) if __name__ == '__main__': tf.disable_v2_behavior() absltest.main()
deepmind-research-master
option_keyboard/run_ok_test.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Auto-resetting environment base class. The environment API states that stepping an environment after a LAST timestep should return the first timestep of a new episode. However, environment authors sometimes don't spot this part or find it awkward to implement. This module contains a class that helps implement the reset behaviour. """ import abc import dm_env class Base(dm_env.Environment): """This class implements the required `step()` and `reset()` methods. It instead requires users to implement `_step()` and `_reset()`. This class handles the reset behaviour automatically when it detects a LAST timestep. """ def __init__(self): self._reset_next_step = True @abc.abstractmethod def _reset(self): """Returns a `timestep` namedtuple as per the regular `reset()` method.""" @abc.abstractmethod def _step(self, action): """Returns a `timestep` namedtuple as per the regular `step()` method.""" def reset(self): self._reset_next_step = False return self._reset() def step(self, action): if self._reset_next_step: return self.reset() timestep = self._step(action) self._reset_next_step = timestep.last() return timestep
deepmind-research-master
option_keyboard/auto_reset_environment.py
# pylint: disable=g-bad-file-header # Copyright 2020 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 training loop.""" import csv from absl import logging from tensorflow.compat.v1.io import gfile def _ema(base, val, decay=0.995): return base * decay + (1 - decay) * val def run(env, agent, num_episodes, report_every=200, num_eval_reps=1): """Runs an agent on an environment. Args: env: The environment. agent: The agent. num_episodes: Number of episodes to train for. report_every: Frequency at which training progress are reported (episodes). num_eval_reps: Number of eval episodes to run per training episode. Returns: A list of dicts containing training and evaluation returns, and a list of reported returns smoothed by EMA. """ returns = [] logged_returns = [] train_return_ema = 0. eval_return_ema = 0. for episode in range(num_episodes): returns.append(dict(episode=episode)) # Run a training episode. train_episode_return = run_episode(env, agent, is_training=True) train_return_ema = _ema(train_return_ema, train_episode_return) returns[-1]["train"] = train_episode_return # Run an evaluation episode. returns[-1]["eval"] = [] for _ in range(num_eval_reps): eval_episode_return = run_episode(env, agent, is_training=False) eval_return_ema = _ema(eval_return_ema, eval_episode_return) returns[-1]["eval"].append(eval_episode_return) if ((episode + 1) % report_every) == 0 or episode == 0: logged_returns.append( dict(episode=episode, train=train_return_ema, eval=[eval_return_ema])) logging.info("Episode %s, avg train return %.3f, avg eval return %.3f", episode + 1, train_return_ema, eval_return_ema) if hasattr(agent, "get_logs"): logging.info("Episode %s, agent logs: %s", episode + 1, agent.get_logs()) return returns, logged_returns def run_episode(environment, agent, is_training=False): """Run a single episode.""" timestep = environment.reset() while not timestep.last(): action = agent.step(timestep, is_training) new_timestep = environment.step(action) if is_training: agent.update(timestep, action, new_timestep) timestep = new_timestep episode_return = environment.episode_return return episode_return def write_returns_to_file(path, returns): """Write returns to file.""" with gfile.GFile(path, "w") as file: writer = csv.writer(file, delimiter=" ", quoting=csv.QUOTE_MINIMAL) writer.writerow(["episode", "train"] + [f"eval_{idx}" for idx in range(len(returns[0]["eval"]))]) for row in returns: writer.writerow([row["episode"], row["train"]] + row["eval"])
deepmind-research-master
option_keyboard/experiment.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Run an experiment.""" import os from absl import app from absl import flags import tensorflow.compat.v1 as tf import tensorflow_hub as hub from option_keyboard import configs from option_keyboard import dqn_agent from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import keyboard_utils from option_keyboard import scavenger from option_keyboard import smart_module FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 10000, "Number of training episodes.") flags.DEFINE_integer("num_pretrain_episodes", 20000, "Number of pretraining episodes.") flags.DEFINE_integer("report_every", 200, "Frequency at which metrics are reported.") flags.DEFINE_string("keyboard_path", None, "Path to pretrained keyboard model.") flags.DEFINE_string("output_path", None, "Path to write out training curves.") def main(argv): del argv # Pretrain the keyboard and save a checkpoint. if FLAGS.keyboard_path: keyboard_path = FLAGS.keyboard_path else: with tf.Graph().as_default(): export_path = "/tmp/option_keyboard/keyboard" _ = keyboard_utils.create_and_train_keyboard( num_episodes=FLAGS.num_pretrain_episodes, export_path=export_path) keyboard_path = os.path.join(export_path, "tfhub") # Load the keyboard. keyboard = smart_module.SmartModuleImport(hub.Module(keyboard_path)) # Create the task environment. base_env_config = configs.get_task_config() base_env = scavenger.Scavenger(**base_env_config) base_env = environment_wrappers.EnvironmentWithLogging(base_env) # Wrap the task environment with the keyboard. additional_discount = 0.9 env = environment_wrappers.EnvironmentWithKeyboard( env=base_env, keyboard=keyboard, keyboard_ckpt_path=None, n_actions_per_dim=3, additional_discount=additional_discount, call_and_return=False) # Create the player agent. agent = dqn_agent.Agent( obs_spec=env.observation_spec(), action_spec=env.action_spec(), network_kwargs=dict( output_sizes=(64, 128), activate_final=True, ), epsilon=0.1, additional_discount=additional_discount, batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-4,)) _, ema_returns = experiment.run( env, agent, num_episodes=FLAGS.num_episodes, report_every=FLAGS.report_every) if FLAGS.output_path: experiment.write_returns_to_file(FLAGS.output_path, ema_returns) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/run_ok.py
# pylint: disable=g-bad-file-header # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for running the simple DQN agent.""" from absl import flags from absl.testing import absltest import tensorflow.compat.v1 as tf from option_keyboard import run_dqn FLAGS = flags.FLAGS class RunDQNTest(absltest.TestCase): def test_run(self): FLAGS.num_episodes = 200 run_dqn.main(None) if __name__ == '__main__': tf.disable_v2_behavior() absltest.main()
deepmind-research-master
option_keyboard/run_dqn_test.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """DQN agent.""" import numpy as np import sonnet as snt import tensorflow.compat.v1 as tf class Agent(): """A DQN Agent.""" def __init__( self, obs_spec, action_spec, network_kwargs, epsilon, additional_discount, batch_size, optimizer_name, optimizer_kwargs, ): """A simple DQN agent. Args: obs_spec: The observation spec. action_spec: The action spec. network_kwargs: Keyword arguments for snt.nets.MLP epsilon: Exploration probability. additional_discount: Discount on returns used by the agent. batch_size: Size of update batch. optimizer_name: Name of an optimizer from tf.train optimizer_kwargs: Keyword arguments for the optimizer. """ self._epsilon = epsilon self._additional_discount = additional_discount self._batch_size = batch_size self._n_actions = action_spec.num_values self._network = ValueNet(self._n_actions, network_kwargs=network_kwargs) self._replay = [] obs_spec = self._extract_observation(obs_spec) # Placeholders for policy o = tf.placeholder(shape=obs_spec.shape, dtype=obs_spec.dtype) q = self._network(tf.expand_dims(o, axis=0)) # Placeholders for update. o_tm1 = tf.placeholder(shape=(None,) + obs_spec.shape, dtype=obs_spec.dtype) a_tm1 = tf.placeholder(shape=(None,), dtype=tf.int32) r_t = tf.placeholder(shape=(None,), dtype=tf.float32) d_t = tf.placeholder(shape=(None,), dtype=tf.float32) o_t = tf.placeholder(shape=(None,) + obs_spec.shape, dtype=obs_spec.dtype) # Compute values over all options. q_tm1 = self._network(o_tm1) q_t = self._network(o_t) a_t = tf.cast(tf.argmax(q_t, axis=-1), tf.int32) qa_tm1 = _batched_index(q_tm1, a_tm1) qa_t = _batched_index(q_t, a_t) # TD error g = additional_discount * d_t td_error = tf.stop_gradient(r_t + g * qa_t) - qa_tm1 loss = tf.reduce_sum(tf.square(td_error) / 2) with tf.variable_scope("optimizer"): self._optimizer = getattr(tf.train, optimizer_name)(**optimizer_kwargs) train_op = self._optimizer.minimize(loss) # Make session and callables. session = tf.Session() self._update_fn = session.make_callable(train_op, [o_tm1, a_tm1, r_t, d_t, o_t]) self._value_fn = session.make_callable(q, [o]) session.run(tf.global_variables_initializer()) def _extract_observation(self, obs): return obs["arena"] def step(self, timestep, is_training=False): """Select actions according to epsilon-greedy policy.""" if is_training and np.random.rand() < self._epsilon: return np.random.randint(self._n_actions) q_values = self._value_fn( self._extract_observation(timestep.observation)) return int(np.argmax(q_values)) def update(self, step_tm1, action, step_t): """Takes in a transition from the environment.""" transition = [ self._extract_observation(step_tm1.observation), action, step_t.reward, step_t.discount, self._extract_observation(step_t.observation), ] self._replay.append(transition) if len(self._replay) == self._batch_size: batch = list(zip(*self._replay)) self._update_fn(*batch) self._replay = [] # Just a queue. class ValueNet(snt.AbstractModule): """Value Network.""" def __init__(self, n_actions, network_kwargs, name="value_network"): """Construct a value network sonnet module. Args: n_actions: Number of actions. network_kwargs: Network arguments. name: Name """ super(ValueNet, self).__init__(name=name) self._n_actions = n_actions self._network_kwargs = network_kwargs def _build(self, observation): flat_obs = snt.BatchFlatten()(observation) net = snt.nets.MLP(**self._network_kwargs)(flat_obs) net = snt.Linear(output_size=self._n_actions)(net) return net @property def num_actions(self): return self._n_actions def _batched_index(values, indices): one_hot_indices = tf.one_hot(indices, values.shape[-1], dtype=values.dtype) return tf.reduce_sum(values * one_hot_indices, axis=-1)
deepmind-research-master
option_keyboard/dqn_agent.py
# pylint: disable=g-bad-file-header # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ r"""Run an experiment. Run GPE/GPI on the "balancing" task with a fixed w For example, first train a keyboard: python3 train_keyboard.py -- --logtostderr --policy_weights_name=12 Then, evaluate the keyboard with a fixed w. python3 run_true_w_fig6.py -- --logtostderr \ --keyboard_path=/tmp/option_keyboard/keyboard_12/tfhub """ import csv from absl import app from absl import flags import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.io import gfile import tensorflow_hub as hub from option_keyboard import configs from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger from option_keyboard import smart_module from option_keyboard.gpe_gpi_experiments import regressed_agent FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 1000, "Number of training episodes.") flags.DEFINE_string("keyboard_path", None, "Path to keyboard model.") flags.DEFINE_list("test_w", None, "The w to test.") flags.DEFINE_string("output_path", None, "Path to write out returns.") def main(argv): del argv # Load the keyboard. keyboard = smart_module.SmartModuleImport(hub.Module(FLAGS.keyboard_path)) # Create the task environment. base_env_config = configs.get_task_config() base_env = scavenger.Scavenger(**base_env_config) base_env = environment_wrappers.EnvironmentWithLogging(base_env) # Wrap the task environment with the keyboard. additional_discount = 0.9 env = environment_wrappers.EnvironmentWithKeyboardDirect( env=base_env, keyboard=keyboard, keyboard_ckpt_path=None, additional_discount=additional_discount, call_and_return=False) # Create the player agent. agent = regressed_agent.Agent( batch_size=10, optimizer_name="AdamOptimizer", # Disable training. optimizer_kwargs=dict(learning_rate=0.0,), init_w=[float(x) for x in FLAGS.test_w]) returns = [] for _ in range(FLAGS.num_episodes): returns.append(experiment.run_episode(env, agent)) tf.logging.info("#" * 80) tf.logging.info( f"Avg. return over {FLAGS.num_episodes} episodes is {np.mean(returns)}") tf.logging.info("#" * 80) if FLAGS.output_path: with gfile.GFile(FLAGS.output_path, "w") as file: writer = csv.writer(file, delimiter=" ", quoting=csv.QUOTE_MINIMAL) writer.writerow(["return"]) for val in returns: writer.writerow([val]) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/run_true_w_fig6.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Run an experiment. Run a q-learning agent on a task. """ from absl import app from absl import flags import tensorflow.compat.v1 as tf from option_keyboard import configs from option_keyboard import dqn_agent from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 10000, "Number of training episodes.") flags.DEFINE_list("test_w", None, "The w to test.") flags.DEFINE_integer("report_every", 200, "Frequency at which metrics are reported.") flags.DEFINE_string("output_path", None, "Path to write out training curves.") def main(argv): del argv # Create the task environment. test_w = [float(x) for x in FLAGS.test_w] env_config = configs.get_fig5_task_config(test_w) env = scavenger.Scavenger(**env_config) env = environment_wrappers.EnvironmentWithLogging(env) # Create the flat agent. agent = dqn_agent.Agent( obs_spec=env.observation_spec(), action_spec=env.action_spec(), network_kwargs=dict( output_sizes=(64, 128), activate_final=True, ), epsilon=0.1, additional_discount=0.9, batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-4,)) _, ema_returns = experiment.run( env, agent, num_episodes=FLAGS.num_episodes, report_every=FLAGS.report_every) if FLAGS.output_path: experiment.write_returns_to_file(FLAGS.output_path, ema_returns) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/run_dqn_fig5.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Train a keyboard.""" from absl import app from absl import flags import numpy as np import tensorflow.compat.v1 as tf from option_keyboard import keyboard_utils FLAGS = flags.FLAGS flags.DEFINE_integer("num_pretrain_episodes", 20000, "Number of pretraining episodes.") flags.DEFINE_string("export_path", None, "Where to save the keyboard checkpoints.") flags.DEFINE_string("policy_weights_name", None, "A string repsenting the policy weights.") def main(argv): del argv all_policy_weights = { "1": [1., 0.], "2": [0., 1.], "3": [1., -1.], "4": [-1., 1.], "5": [1., 1.], } if FLAGS.policy_weights_name: policy_weights = np.array( [all_policy_weights[v] for v in FLAGS.policy_weights_name]) num_episodes = ((FLAGS.num_pretrain_episodes // 2) * max(2, len(policy_weights))) export_path = FLAGS.export_path + "_" + FLAGS.policy_weights_name else: policy_weights = None num_episodes = FLAGS.num_pretrain_episodes export_path = FLAGS.export_path keyboard_utils.create_and_train_keyboard( num_episodes=num_episodes, policy_weights=policy_weights, export_path=export_path) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/train_keyboard.py
# pylint: disable=g-bad-file-header # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ r"""Run an experiment. Run GPE/GPI on task (1, -1) with a learned phi model and w by regression. For example, first train a phi model with 3 dimenional phi: python3 train_phi_model.py -- --logtostderr --use_random_tasks \ --export_path=/tmp/option_keyboard/phi_model_3d --num_phis=3 Then train a keyboard: python3 train_keyboard_with_phi.py -- --logtostderr \ --export_path=/tmp/option_keyboard/keyboard_3d \ --phi_model_path=/tmp/option_keyboard/phi_model_3d \ --num_phis=2 Finally, evaluate the keyboard with w by regression. python3 run_regressed_w_with_phi_fig4c.py -- --logtostderr \ --phi_model_path=/tmp/option_keyboard/phi_model_3d \ --keyboard_path=/tmp/option_keyboard/keyboard_3d/tfhub """ from absl import app from absl import flags import numpy as np import tensorflow.compat.v1 as tf import tensorflow_hub as hub from option_keyboard import configs from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger from option_keyboard import smart_module from option_keyboard.gpe_gpi_experiments import regressed_agent FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 100, "Number of training episodes.") flags.DEFINE_integer("report_every", 1, "Frequency at which metrics are reported.") flags.DEFINE_string("phi_model_path", None, "Path to phi model.") flags.DEFINE_string("keyboard_path", None, "Path to keyboard model.") flags.DEFINE_string("output_path", None, "Path to write out training curves.") def main(argv): del argv # Load the keyboard. keyboard = smart_module.SmartModuleImport(hub.Module(FLAGS.keyboard_path)) # Create the task environment. base_env_config = configs.get_fig4_task_config() base_env = scavenger.Scavenger(**base_env_config) base_env = environment_wrappers.EnvironmentWithLogging(base_env) base_env = environment_wrappers.EnvironmentWithLearnedPhi( base_env, FLAGS.phi_model_path) # Wrap the task environment with the keyboard. additional_discount = 0.9 env = environment_wrappers.EnvironmentWithKeyboardDirect( env=base_env, keyboard=keyboard, keyboard_ckpt_path=None, additional_discount=additional_discount, call_and_return=False) # Create the player agent. agent = regressed_agent.Agent( batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-2,), init_w=np.random.normal(size=keyboard.num_cumulants) * 0.1, ) _, ema_returns = experiment.run( env, agent, num_episodes=FLAGS.num_episodes, report_every=FLAGS.report_every, num_eval_reps=100) if FLAGS.output_path: experiment.write_returns_to_file(FLAGS.output_path, ema_returns) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/run_regressed_w_with_phi_fig4c.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Train simple phi model.""" import collections import random from absl import app from absl import flags from absl import logging import numpy as np import sonnet as snt import tensorflow.compat.v1 as tf import tree from option_keyboard import scavenger from option_keyboard import smart_module FLAGS = flags.FLAGS flags.DEFINE_integer("num_phis", 2, "Dimensionality of phis.") flags.DEFINE_integer("num_train_steps", 2000, "Number of training steps.") flags.DEFINE_integer("num_replay_steps", 500, "Number of replay steps.") flags.DEFINE_integer("min_replay_size", 1000, "Minimum replay size before starting training.") flags.DEFINE_integer("num_train_repeats", 10, "Number of training repeats.") flags.DEFINE_float("learning_rate", 3e-3, "Learning rate.") flags.DEFINE_bool("use_random_tasks", False, "Use random tasks.") flags.DEFINE_string("normalisation", "L2", "Normalisation method for cumulant weights.") flags.DEFINE_string("export_path", None, "Export path.") StepOutput = collections.namedtuple("StepOutput", ["obs", "actions", "rewards", "next_obs"]) def collect_experience(env, num_episodes, verbose=False): """Collect experience.""" num_actions = env.action_spec().maximum + 1 observations = [] actions = [] rewards = [] next_observations = [] for _ in range(num_episodes): timestep = env.reset() episode_return = 0 while not timestep.last(): action = np.random.randint(num_actions) observations.append(timestep.observation) actions.append(action) timestep = env.step(action) rewards.append(timestep.observation["aux_tasks_reward"]) episode_return += timestep.reward next_observations.append(timestep.observation) if verbose: logging.info("Total return for episode: %f", episode_return) observation_spec = tree.map_structure(lambda _: None, observations[0]) def stack_observations(obs_list): obs_list = [ np.stack(obs) for obs in zip(*[tree.flatten(obs) for obs in obs_list]) ] obs_dict = tree.unflatten_as(observation_spec, obs_list) obs_dict.pop("aux_tasks_reward") return obs_dict observations = stack_observations(observations) actions = np.array(actions, dtype=np.int32) rewards = np.stack(rewards) next_observations = stack_observations(next_observations) return StepOutput(observations, actions, rewards, next_observations) class PhiModel(snt.AbstractModule): """A model for learning phi.""" def __init__(self, n_actions, n_phis, network_kwargs, final_activation="sigmoid", name="PhiModel"): super(PhiModel, self).__init__(name=name) self._n_actions = n_actions self._n_phis = n_phis self._network_kwargs = network_kwargs self._final_activation = final_activation def _build(self, observation, actions): obs = observation["arena"] n_outputs = self._n_actions * self._n_phis flat_obs = snt.BatchFlatten()(obs) net = snt.nets.MLP(**self._network_kwargs)(flat_obs) net = snt.Linear(output_size=n_outputs)(net) net = snt.BatchReshape((self._n_actions, self._n_phis))(net) indices = tf.stack([tf.range(tf.shape(actions)[0]), actions], axis=1) values = tf.gather_nd(net, indices) if self._final_activation: values = getattr(tf.nn, self._final_activation)(values) return values def create_ph(tensor): return tf.placeholder(shape=(None,) + tensor.shape[1:], dtype=tensor.dtype) def main(argv): del argv if FLAGS.use_random_tasks: tasks = np.random.normal(size=(8, 2)) else: tasks = [ [1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [-1.0, 1.0], ] if FLAGS.normalisation == "L1": tasks /= np.sum(np.abs(tasks), axis=-1, keepdims=True) elif FLAGS.normalisation == "L2": tasks /= np.linalg.norm(tasks, axis=-1, keepdims=True) else: raise ValueError("Unknown normlisation_method {}".format( FLAGS.normalisation)) logging.info("Tasks: %s", tasks) env_config = dict( arena_size=11, num_channels=2, max_num_steps=100, num_init_objects=10, object_priors=[1.0, 1.0], egocentric=True, default_w=None, aux_tasks_w=tasks) env = scavenger.Scavenger(**env_config) num_actions = env.action_spec().maximum + 1 model_config = dict( n_actions=num_actions, n_phis=FLAGS.num_phis, network_kwargs=dict( output_sizes=(64, 128), activate_final=True, ), ) model = smart_module.SmartModuleExport(lambda: PhiModel(**model_config)) dummy_steps = collect_experience(env, num_episodes=10, verbose=True) num_rewards = dummy_steps.rewards.shape[-1] # Placeholders steps_ph = tree.map_structure(create_ph, dummy_steps) phis = model(steps_ph.obs, steps_ph.actions) phis_to_rewards = snt.Linear( num_rewards, initializers=dict(w=tf.zeros), use_bias=False) preds = phis_to_rewards(phis) loss_per_batch = tf.square(preds - steps_ph.rewards) loss_op = tf.reduce_mean(loss_per_batch) replay = [] # Optimizer and train op. with tf.variable_scope("optimizer"): optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate) train_op = optimizer.minimize(loss_op) # Add normalisation of weights in phis_to_rewards if FLAGS.normalisation == "L1": w_norm = tf.reduce_sum(tf.abs(phis_to_rewards.w), axis=0, keepdims=True) elif FLAGS.normalisation == "L2": w_norm = tf.norm(phis_to_rewards.w, axis=0, keepdims=True) else: raise ValueError("Unknown normlisation_method {}".format( FLAGS.normalisation)) normalise_w = tf.assign(phis_to_rewards.w, phis_to_rewards.w / tf.maximum(w_norm, 1e-6)) def filter_steps(steps): mask = np.sum(np.abs(steps.rewards), axis=-1) > 0.1 nonzero_inds = np.where(mask)[0] zero_inds = np.where(np.logical_not(mask))[0] zero_inds = np.random.choice( zero_inds, size=len(nonzero_inds), replace=False) selected_inds = np.concatenate([nonzero_inds, zero_inds]) selected_steps = tree.map_structure(lambda x: x[selected_inds], steps) return selected_steps, selected_inds with tf.Session() as sess: sess.run(tf.global_variables_initializer()) step = 0 while step < FLAGS.num_train_steps: step += 1 steps_output = collect_experience(env, num_episodes=10) selected_step_outputs, selected_inds = filter_steps(steps_output) if len(replay) > FLAGS.min_replay_size: # Do training. for _ in range(FLAGS.num_train_repeats): train_samples = random.choices(replay, k=128) train_samples = tree.map_structure( lambda *x: np.stack(x, axis=0), *train_samples) train_samples = tree.unflatten_as(steps_ph, train_samples) feed_dict = dict( zip(tree.flatten(steps_ph), tree.flatten(train_samples))) _, train_loss = sess.run([train_op, loss_op], feed_dict=feed_dict) sess.run(normalise_w) # Do evaluation. if step % 50 == 0: feed_dict = dict( zip(tree.flatten(steps_ph), tree.flatten(selected_step_outputs))) eval_loss = sess.run(loss_op, feed_dict=feed_dict) logging.info("Step %d, train loss %f, eval loss %f, replay %s", step, train_loss, eval_loss, len(replay)) print(sess.run(phis_to_rewards.get_variables())[0].T) values = dict(step=step, train_loss=train_loss, eval_loss=eval_loss) logging.info(values) # Add to replay. if step <= FLAGS.num_replay_steps: def select_fn(ind): return lambda x: x[ind] for idx in range(len(selected_inds)): replay.append( tree.flatten( tree.map_structure(select_fn(idx), selected_step_outputs))) # Export trained model. if FLAGS.export_path: model.export(FLAGS.export_path, sess, overwrite=True) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/train_phi_model.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Run an experiment. Run a q-learning agent on task (1, -1). """ from absl import app from absl import flags import tensorflow.compat.v1 as tf from option_keyboard import configs from option_keyboard import dqn_agent from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 10000, "Number of training episodes.") flags.DEFINE_integer("report_every", 5, "Frequency at which metrics are reported.") flags.DEFINE_string("output_path", None, "Path to write out training curves.") def main(argv): del argv # Create the task environment. env_config = configs.get_fig4_task_config() env = scavenger.Scavenger(**env_config) env = environment_wrappers.EnvironmentWithLogging(env) # Create the flat agent. agent = dqn_agent.Agent( obs_spec=env.observation_spec(), action_spec=env.action_spec(), network_kwargs=dict( output_sizes=(64, 128), activate_final=True, ), epsilon=0.1, additional_discount=0.9, batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-4,)) _, ema_returns = experiment.run( env, agent, num_episodes=FLAGS.num_episodes, report_every=FLAGS.report_every) if FLAGS.output_path: experiment.write_returns_to_file(FLAGS.output_path, ema_returns) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/run_dqn_fig4b.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Train a keyboard.""" from absl import app from absl import flags import numpy as np import tensorflow.compat.v1 as tf from option_keyboard import keyboard_utils FLAGS = flags.FLAGS flags.DEFINE_integer("num_pretrain_episodes", 20000, "Number of pretraining episodes.") flags.DEFINE_integer("num_phis", None, "Size of phi") flags.DEFINE_string("phi_model_path", None, "Where to load the phi model checkpoints.") flags.DEFINE_string("export_path", None, "Where to save the keyboard checkpoints.") def main(argv): del argv keyboard_utils.create_and_train_keyboard_with_phi( num_episodes=FLAGS.num_pretrain_episodes, phi_model_path=FLAGS.phi_model_path, policy_weights=np.eye(FLAGS.num_phis, dtype=np.float32), export_path=FLAGS.export_path) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/train_keyboard_with_phi.py
# pylint: disable=g-bad-file-header # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ r"""Run an experiment. Run GPE/GPI on task (1, -1) with w obtained by regression. For example, first train a keyboard: python3 train_keyboard.py -- --logtostderr --policy_weights_name=12 \ --export_path=/tmp/option_keyboard/keyboard Then, evaluate the keyboard with w by regression. python3 run_regressed_w_fig4c.py -- --logtostderr \ --keyboard_path=/tmp/option_keyboard/keyboard_12/tfhub """ from absl import app from absl import flags import numpy as np import tensorflow.compat.v1 as tf import tensorflow_hub as hub from option_keyboard import configs from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger from option_keyboard import smart_module from option_keyboard.gpe_gpi_experiments import regressed_agent FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 100, "Number of training episodes.") flags.DEFINE_integer("report_every", 1, "Frequency at which metrics are reported.") flags.DEFINE_string("keyboard_path", None, "Path to keyboard model.") flags.DEFINE_string("output_path", None, "Path to write out training curves.") def main(argv): del argv # Load the keyboard. keyboard = smart_module.SmartModuleImport(hub.Module(FLAGS.keyboard_path)) # Create the task environment. base_env_config = configs.get_fig4_task_config() base_env = scavenger.Scavenger(**base_env_config) base_env = environment_wrappers.EnvironmentWithLogging(base_env) # Wrap the task environment with the keyboard. additional_discount = 0.9 env = environment_wrappers.EnvironmentWithKeyboardDirect( env=base_env, keyboard=keyboard, keyboard_ckpt_path=None, additional_discount=additional_discount, call_and_return=False) # Create the player agent. agent = regressed_agent.Agent( batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-2,), init_w=np.random.normal(size=keyboard.num_cumulants) * 0.1, ) _, ema_returns = experiment.run( env, agent, num_episodes=FLAGS.num_episodes, report_every=FLAGS.report_every, num_eval_reps=100) if FLAGS.output_path: experiment.write_returns_to_file(FLAGS.output_path, ema_returns) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/run_regressed_w_fig4c.py
# pylint: disable=g-bad-file-header # pylint: disable=line-too-long # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ r"""Run an experiment. This script generates the raw data for the polar plots used to visualise how well a trained keyboard covers the space of w. For example, train 3 separate keyboards with different base policies: python3 train_keyboard.py --logtostderr --policy_weights_name=12 python3 train_keyboard.py --logtostderr --policy_weights_name=34 python3 train_keyboard.py --logtostderr --policy_weights_name=5 Then generate the polar plot data as follows: python3 eval_keyboard_fig5.py --logtostderr \ --keyboard_paths=/tmp/option_keyboard/keyboard_12/tfhub,/tmp/option_keyboard/keyboard_34/tfhub,/tmp/option_keyboard/keyboard_5/tfhub \ --num_episodes=1000 Example outout: [[ 0.11 0.261 -0.933 ] [ 1.302 3.955 0.54 ] [ 2.398 4.434 1.2105359 ] [ 3.459 4.606 2.087 ] [ 4.09026795 4.60911325 3.06106882] [ 4.55499485 4.71947818 3.8123229 ] [ 4.715 4.835 4.395 ] [ 4.75743564 4.64095528 4.46330207] [ 4.82518207 4.71232378 4.56190708] [ 4.831 4.7155 4.5735 ] [ 4.78074425 4.6754641 4.58312762] [ 4.70154374 4.5416429 4.47850417] [ 4.694 4.631 4.427 ] [ 4.25085125 4.56606664 3.68157677] [ 3.61726795 4.4838453 2.68154403] [ 2.714 4.43 1.554 ] [ 1.69 4.505 0.9635359 ] [ 0.894 4.043 0.424 ] [ 0.099 0.349 0.055 ]] """ import csv from absl import app from absl import flags import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.io import gfile import tensorflow_hub as hub from option_keyboard import configs from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger from option_keyboard import smart_module from option_keyboard.gpe_gpi_experiments import regressed_agent FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 1000, "Number of training episodes.") flags.DEFINE_list("keyboard_paths", [], "Path to keyboard model.") flags.DEFINE_string("output_path", None, "Path to write out returns.") def evaluate_keyboard(keyboard_path, weights_to_sweep): """Evaluate a keyboard.""" # Load the keyboard. keyboard = smart_module.SmartModuleImport(hub.Module(keyboard_path)) # Create the task environment. all_returns = [] for w_to_sweep in weights_to_sweep.tolist(): base_env_config = configs.get_fig5_task_config(w_to_sweep) base_env = scavenger.Scavenger(**base_env_config) base_env = environment_wrappers.EnvironmentWithLogging(base_env) # Wrap the task environment with the keyboard. with tf.variable_scope(None, default_name="inner_loop"): additional_discount = 0.9 env = environment_wrappers.EnvironmentWithKeyboardDirect( env=base_env, keyboard=keyboard, keyboard_ckpt_path=None, additional_discount=additional_discount, call_and_return=False) # Create the player agent. agent = regressed_agent.Agent( batch_size=10, optimizer_name="AdamOptimizer", # Disable training. optimizer_kwargs=dict(learning_rate=0.0,), init_w=w_to_sweep) returns = [] for _ in range(FLAGS.num_episodes): returns.append(experiment.run_episode(env, agent)) tf.logging.info(f"Task: {w_to_sweep}, mean returns over " f"{FLAGS.num_episodes} episodes is {np.mean(returns)}") all_returns.append(returns) return all_returns def main(argv): del argv angles_to_sweep = np.deg2rad(np.linspace(-90, 180, num=19, endpoint=True)) weights_to_sweep = np.stack( [np.sin(angles_to_sweep), np.cos(angles_to_sweep)], axis=-1) weights_to_sweep /= np.sum( np.maximum(weights_to_sweep, 0.0), axis=-1, keepdims=True) weights_to_sweep = np.clip(weights_to_sweep, -1000, 1000) tf.logging.info(weights_to_sweep) all_returns = [] for keyboard_path in FLAGS.keyboard_paths: returns = evaluate_keyboard(keyboard_path, weights_to_sweep) all_returns.append(returns) print("Results:") print(np.mean(all_returns, axis=-1).T) if FLAGS.output_path: with gfile.GFile(FLAGS.output_path, "w") as file: writer = csv.writer(file, delimiter=" ", quoting=csv.QUOTE_MINIMAL) writer.writerow(["angle", "return", "idx"]) for idx, returns in enumerate(all_returns): for row in np.array(returns).T.tolist(): assert len(angles_to_sweep) == len(row) for ang, val in zip(angles_to_sweep, row): ang = "{:.4g}".format(ang) val = "{:.4g}".format(val) writer.writerow([ang, val, idx]) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/eval_keyboard_fig5.py
# pylint: disable=g-bad-file-header # Copyright 2020 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. # ============================================================================ """Regressed agent.""" import numpy as np import tensorflow.compat.v1 as tf class Agent(): """A DQN Agent.""" def __init__( self, batch_size, optimizer_name, optimizer_kwargs, init_w, ): """A simple DQN agent. Args: batch_size: Size of update batch. optimizer_name: Name of an optimizer from tf.train optimizer_kwargs: Keyword arguments for the optimizer. init_w: The initial cumulant weight. """ self._batch_size = batch_size self._init_w = np.array(init_w) self._replay = [] # Regress w by gradient descent, could also use closed-form solution. self._n_cumulants = len(init_w) self._regressed_w = tf.get_variable( "regressed_w", dtype=tf.float32, initializer=lambda: tf.to_float(init_w)) cumulants_ph = tf.placeholder( shape=(None, self._n_cumulants), dtype=tf.float32) rewards_ph = tf.placeholder(shape=(None,), dtype=tf.float32) predicted_rewards = tf.reduce_sum( tf.multiply(self._regressed_w, cumulants_ph), axis=-1) loss = tf.reduce_sum(tf.square(predicted_rewards - rewards_ph)) with tf.variable_scope("optimizer"): self._optimizer = getattr(tf.train, optimizer_name)(**optimizer_kwargs) train_op = self._optimizer.minimize(loss) # Make session and callables. session = tf.Session() self._update_fn = session.make_callable(train_op, [cumulants_ph, rewards_ph]) self._action = session.make_callable(self._regressed_w.read_value(), []) session.run(tf.global_variables_initializer()) def step(self, timestep, is_training=False): """Select actions according to epsilon-greedy policy.""" del timestep if is_training: # Can also just use random actions at environment level. return np.random.uniform(low=-1.0, high=1.0, size=(self._n_cumulants,)) return self._action() def update(self, step_tm1, action, step_t): """Takes in a transition from the environment.""" del step_tm1, action transition = [ step_t.observation["cumulants"], step_t.reward, ] self._replay.append(transition) if len(self._replay) == self._batch_size: batch = list(zip(*self._replay)) self._update_fn(*batch) self._replay = [] # Just a queue. def get_logs(self): return dict(regressed=self._action())
deepmind-research-master
option_keyboard/gpe_gpi_experiments/regressed_agent.py
# pylint: disable=g-bad-file-header # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ r"""Run an experiment. Run GPE/GPI on task (1, -1) with the groundtruth w. For example, first train a keyboard: python3 train_keyboard.py -- --logtostderr --policy_weights_name=12 Then, evaluate the keyboard with groundtruth w. python3 run_true_w_fig4.py -- --logtostderr \ --keyboard_path=/tmp/option_keyboard/keyboard_12/tfhub """ import csv from absl import app from absl import flags import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.io import gfile import tensorflow_hub as hub from option_keyboard import configs from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger from option_keyboard import smart_module from option_keyboard.gpe_gpi_experiments import regressed_agent FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 1000, "Number of training episodes.") flags.DEFINE_string("keyboard_path", None, "Path to keyboard model.") flags.DEFINE_string("output_path", None, "Path to write out returns.") def main(argv): del argv # Load the keyboard. keyboard = smart_module.SmartModuleImport(hub.Module(FLAGS.keyboard_path)) # Create the task environment. base_env_config = configs.get_fig4_task_config() base_env = scavenger.Scavenger(**base_env_config) base_env = environment_wrappers.EnvironmentWithLogging(base_env) # Wrap the task environment with the keyboard. additional_discount = 0.9 env = environment_wrappers.EnvironmentWithKeyboardDirect( env=base_env, keyboard=keyboard, keyboard_ckpt_path=None, additional_discount=additional_discount, call_and_return=False) # Create the player agent. agent = regressed_agent.Agent( batch_size=10, optimizer_name="AdamOptimizer", # Disable training. optimizer_kwargs=dict(learning_rate=0.0,), init_w=[1., -1.]) returns = [] for _ in range(FLAGS.num_episodes): returns.append(experiment.run_episode(env, agent)) tf.logging.info("#" * 80) tf.logging.info( f"Avg. return over {FLAGS.num_episodes} episodes is {np.mean(returns)}") tf.logging.info("#" * 80) if FLAGS.output_path: with gfile.GFile(FLAGS.output_path, "w") as file: writer = csv.writer(file, delimiter=" ", quoting=csv.QUOTE_MINIMAL) writer.writerow(["return"]) for val in returns: writer.writerow([val]) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/run_true_w_fig4.py
# pylint: disable=g-bad-file-header # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ r"""Run an experiment. Run GPE/GPI on task (1, -1) with w obtained by regression. For example, first train a keyboard: python3 train_keyboard.py -- --logtostderr --policy_weights_name=12 \ --export_path=/tmp/option_keyboard/keyboard Then, evaluate the keyboard with w by regression. python3 run_regressed_w_fig4b.py -- --logtostderr \ --keyboard_path=/tmp/option_keyboard/keyboard_12/tfhub """ from absl import app from absl import flags import numpy as np import tensorflow.compat.v1 as tf import tensorflow_hub as hub from option_keyboard import configs from option_keyboard import environment_wrappers from option_keyboard import experiment from option_keyboard import scavenger from option_keyboard import smart_module from option_keyboard.gpe_gpi_experiments import regressed_agent FLAGS = flags.FLAGS flags.DEFINE_integer("num_episodes", 4000, "Number of training episodes.") flags.DEFINE_integer("report_every", 5, "Frequency at which metrics are reported.") flags.DEFINE_string("keyboard_path", None, "Path to keyboard model.") flags.DEFINE_string("output_path", None, "Path to write out training curves.") def main(argv): del argv # Load the keyboard. keyboard = smart_module.SmartModuleImport(hub.Module(FLAGS.keyboard_path)) # Create the task environment. base_env_config = configs.get_fig4_task_config() base_env = scavenger.Scavenger(**base_env_config) base_env = environment_wrappers.EnvironmentWithLogging(base_env) # Wrap the task environment with the keyboard. additional_discount = 0.9 env = environment_wrappers.EnvironmentWithKeyboardDirect( env=base_env, keyboard=keyboard, keyboard_ckpt_path=None, additional_discount=additional_discount, call_and_return=False) # Create the player agent. agent = regressed_agent.Agent( batch_size=10, optimizer_name="AdamOptimizer", optimizer_kwargs=dict(learning_rate=3e-2,), init_w=np.random.normal(size=keyboard.num_cumulants) * 0.1, ) _, ema_returns = experiment.run( env, agent, num_episodes=FLAGS.num_episodes, report_every=FLAGS.report_every, num_eval_reps=20) if FLAGS.output_path: experiment.write_returns_to_file(FLAGS.output_path, ema_returns) if __name__ == "__main__": tf.disable_v2_behavior() app.run(main)
deepmind-research-master
option_keyboard/gpe_gpi_experiments/run_regressed_w_fig4b.py
# Copyright 2020 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Loss functions to be used by LayerCollection.""" import abc from typing import Tuple, Optional, Union, Sequence import jax import jax.numpy as jnp from kfac_ferminet_alpha import distributions from kfac_ferminet_alpha import layers_and_loss_tags as tags from kfac_ferminet_alpha import utils ArrayPair = Tuple[jnp.ndarray, jnp.ndarray] FloatArray = Union[float, jnp.ndarray] Index = Tuple[int] class LossFunction(abc.ABC): """Abstract base class for loss functions. Note that unlike typical loss functions used in neural networks these are neither summed nor averaged over the batch and hence the output of evaluate() will not be a scalar. It is up to the user to then to correctly manipulate them as needed. """ def __init__(self, weight: FloatArray): self._weight = weight @property def weight(self) -> FloatArray: return self._weight @property @abc.abstractmethod def targets(self) -> Optional[jnp.ndarray]: """The targets being predicted by the model. Returns: None or Tensor of appropriate shape for calling self._evaluate() on. """ pass @property @abc.abstractmethod def inputs(self) -> Sequence[jnp.ndarray]: """The inputs to the loss function (excluding the targets).""" pass @abc.abstractmethod def copy_with_different_inputs(self, inputs: Sequence[jnp.ndarray]): pass def evaluate( self, targets: Optional[jnp.ndarray] = None, coefficient_mode: str = "regular", ) -> jnp.ndarray: """Evaluate the loss function on the targets.""" if targets is None and self.targets is None: raise ValueError("Cannot evaluate losses with unspecified targets.") elif targets is None: targets = self.targets if coefficient_mode == "regular": multiplier = self.weight elif coefficient_mode == "sqrt": multiplier = jnp.sqrt(self.weight) elif coefficient_mode == "off": multiplier = 1.0 else: raise ValueError(f"Unrecognized coefficient_mode={coefficient_mode}.") return self._evaluate(targets) * multiplier @abc.abstractmethod def _evaluate(self, targets: jnp.ndarray) -> jnp.ndarray: """Evaluates the negative log probability of the targets. Args: targets: Tensor that distribution can calculate log_prob() of. Returns: negative log probability of each target, summed across all targets. """ pass def grad_of_evaluate( self, targets: Optional[jnp.ndarray], coefficient_mode: str, ) -> Sequence[jnp.ndarray]: """Evaluates the gradient of the loss function. Note that the targets of the loss must not be `None`. Args: targets: The potential targets on which to evaluate the gradient. coefficient_mode: The coefficient mode to use for evaluation. Returns: The gradient of the loss evaluation function with respect to the inputs. """ def evaluate_sum(inputs: Sequence[jnp.ndarray]) -> jnp.ndarray: instance = self.copy_with_different_inputs(inputs) return jnp.sum(instance.evaluate(targets, coefficient_mode)) return jax.grad(evaluate_sum)(self.inputs) def multiply_ggn(self, vector: jnp.ndarray) -> jnp.ndarray: """Right-multiply a vector by the GGN. Here the 'GGN' is the GGN matrix (whose definition is slightly flexible) of the loss function with respect to its inputs. Args: vector: The vector to multiply. Must be the same shape(s) as the 'inputs' property. Returns: The vector right-multiplied by the GGN. Will be of the same shape(s) as the 'inputs' property. """ return utils.scalar_mul(self.multiply_ggn_unweighted(vector), self.weight) @abc.abstractmethod def multiply_ggn_unweighted(self, vector: jnp.ndarray) -> jnp.ndarray: """Same as `multiply_ggn`, but without taking into account the weight.""" pass def multiply_ggn_factor(self, vector: jnp.ndarray) -> jnp.ndarray: """Right-multiply a vector by a factor B of the GGN. Here the 'GGN' is the GGN matrix (whose definition is slightly flexible) of the loss function with respect to its inputs. Typically this will be block-diagonal across different cases in the batch, since the loss function is typically summed across cases. Note that B can be any matrix satisfying B * B^T = G where G is the GGN, but will agree with the one used in the other methods of this class. Args: vector: The vector to multiply. Must be of the shape given by the 'ggn_factor_inner_shape' property. Returns: The vector right-multiplied by B. Will be of the same shape(s) as the 'inputs' property. """ return utils.scalar_mul( self.multiply_ggn_factor_unweighted(vector), jnp.sqrt(self.weight)) @abc.abstractmethod def multiply_ggn_factor_unweighted(self, vector: jnp.ndarray) -> jnp.ndarray: """Same as `multiply_ggn_factor`, but without taking into account the weight.""" pass def multiply_ggn_factor_transpose(self, vector: jnp.ndarray) -> jnp.ndarray: """Right-multiply a vector by the transpose of a factor B of the GGN. Here the 'GGN' is the GGN matrix (whose definition is slightly flexible) of the loss function with respect to its inputs. Typically this will be block-diagonal across different cases in the batch, since the loss function is typically summed across cases. Note that B can be any matrix satisfying B * B^T = G where G is the GGN, but will agree with the one used in the other methods of this class. Args: vector: The vector to multiply. Must be the same shape(s) as the 'inputs' property. Returns: The vector right-multiplied by B^T. Will be of the shape given by the 'ggn_factor_inner_shape' property. """ return utils.scalar_mul( self.multiply_ggn_factor_transpose_unweighted(vector), jnp.sqrt(self.weight)) @abc.abstractmethod def multiply_ggn_factor_transpose_unweighted( self, vector: jnp.ndarray ) -> jnp.ndarray: """Same as `multiply_ggn_factor_transpose`, but without taking into account the weight.""" pass def multiply_ggn_factor_replicated_one_hot(self, index: Index) -> jnp.ndarray: """Right-multiply a replicated-one-hot vector by a factor B of the GGN. Here the 'GGN' is the GGN matrix (whose definition is slightly flexible) of the loss function with respect to its inputs. Typically this will be block-diagonal across different cases in the batch, since the loss function is typically summed across cases. A 'replicated-one-hot' vector means a tensor which, for each slice along the batch dimension (assumed to be dimension 0), is 1.0 in the entry corresponding to the given index and 0 elsewhere. Note that B can be any matrix satisfying B * B^T = G where G is the GGN, but will agree with the one used in the other methods of this class. Args: index: A tuple representing in the index of the entry in each slice that is 1.0. Note that len(index) must be equal to the number of elements of the 'ggn_factor_inner_shape' tensor minus one. Returns: The vector right-multiplied by B^T. Will be of the same shape(s) as the 'inputs' property. """ return utils.scalar_mul( self.multiply_ggn_factor_replicated_one_hot_unweighted(index), jnp.sqrt(self.weight)) @abc.abstractmethod def multiply_ggn_factor_replicated_one_hot_unweighted( self, index: Index ) -> jnp.ndarray: pass @property @abc.abstractmethod def ggn_factor_inner_shape(self) -> Sequence[int]: """The shape of the tensor returned by multiply_ggn_factor.""" pass class NegativeLogProbLoss(LossFunction): """Abstract base class for loss functions that are negative log probs.""" @property def inputs(self): return self.params @property @abc.abstractmethod def params(self): """Parameters to the underlying distribution.""" pass def multiply_fisher(self, vector: jnp.ndarray) -> jnp.ndarray: """Right-multiply a vector by the Fisher. Args: vector: The vector to multiply. Must be the same shape(s) as the 'inputs' property. Returns: The vector right-multiplied by the Fisher. Will be of the same shape(s) as the 'inputs' property. """ return utils.scalar_mul( self.multiply_fisher_unweighted(vector), self.weight) @abc.abstractmethod def multiply_fisher_unweighted(self, vector: jnp.ndarray) -> jnp.ndarray: pass def multiply_fisher_factor(self, vector: jnp.ndarray) -> jnp.ndarray: """Right-multiply a vector by a factor B of the Fisher. Here the 'Fisher' is the Fisher information matrix (i.e. expected outer- product of gradients) with respect to the parameters of the underlying probability distribution (whose log-prob defines the loss). Typically this will be block-diagonal across different cases in the batch, since the distribution is usually (but not always) conditionally iid across different cases. Note that B can be any matrix satisfying B * B^T = F where F is the Fisher, but will agree with the one used in the other methods of this class. Args: vector: The vector to multiply. Must be of the shape given by the 'fisher_factor_inner_shape' property. Returns: The vector right-multiplied by B. Will be of the same shape(s) as the 'inputs' property. """ return utils.scalar_mul( self.multiply_fisher_factor_unweighted(vector), jnp.sqrt(self.weight)) @abc.abstractmethod def multiply_fisher_factor_unweighted( self, vector: jnp.ndarray ) -> jnp.ndarray: pass def multiply_fisher_factor_transpose( self, vector: jnp.ndarray ) -> jnp.ndarray: """Right-multiply a vector by the transpose of a factor B of the Fisher. Here the 'Fisher' is the Fisher information matrix (i.e. expected outer- product of gradients) with respect to the parameters of the underlying probability distribution (whose log-prob defines the loss). Typically this will be block-diagonal across different cases in the batch, since the distribution is usually (but not always) conditionally iid across different cases. Note that B can be any matrix satisfying B * B^T = F where F is the Fisher, but will agree with the one used in the other methods of this class. Args: vector: The vector to multiply. Must be the same shape(s) as the 'inputs' property. Returns: The vector right-multiplied by B^T. Will be of the shape given by the 'fisher_factor_inner_shape' property. """ return utils.scalar_mul( self.multiply_fisher_factor_transpose_unweighted(vector), jnp.sqrt(self.weight)) @abc.abstractmethod def multiply_fisher_factor_transpose_unweighted( self, vector: jnp.ndarray ) -> jnp.ndarray: pass def multiply_fisher_factor_replicated_one_hot( self, index: Index ) -> jnp.ndarray: """Right-multiply a replicated-one-hot vector by a factor B of the Fisher. Here the 'Fisher' is the Fisher information matrix (i.e. expected outer- product of gradients) with respect to the parameters of the underlying probability distribution (whose log-prob defines the loss). Typically this will be block-diagonal across different cases in the batch, since the distribution is usually (but not always) conditionally iid across different cases. A 'replicated-one-hot' vector means a tensor which, for each slice along the batch dimension (assumed to be dimension 0), is 1.0 in the entry corresponding to the given index and 0 elsewhere. Note that B can be any matrix satisfying B * B^T = H where H is the Fisher, but will agree with the one used in the other methods of this class. Args: index: A tuple representing in the index of the entry in each slice that is 1.0. Note that len(index) must be equal to the number of elements of the 'fisher_factor_inner_shape' tensor minus one. Returns: The vector right-multiplied by B. Will be of the same shape(s) as the 'inputs' property. """ return utils.scalar_mul( self.multiply_fisher_factor_replicated_one_hot_unweighted(index), jnp.sqrt(self.weight)) @abc.abstractmethod def multiply_fisher_factor_replicated_one_hot_unweighted( self, index: Index ) -> jnp.ndarray: pass @property @abc.abstractmethod def fisher_factor_inner_shape(self) -> Sequence[int]: """The shape of the tensor returned by multiply_fisher_factor.""" pass @abc.abstractmethod def sample(self, rng_key: jnp.ndarray) -> jnp.ndarray: """Sample 'targets' from the underlying distribution.""" pass def grad_of_evaluate_on_sample( self, rng_key: jnp.ndarray, coefficient_mode: str, ) -> Sequence[jnp.ndarray]: """Evaluates the gradient of the log probability on a random sample. Args: rng_key: Jax PRNG key for sampling. coefficient_mode: The coefficient mode to use for evaluation. Returns: The gradient of the log probability of targets sampled from the distribution. """ return self.grad_of_evaluate(self.sample(rng_key), coefficient_mode) class NaturalParamsNegativeLogProbLoss(NegativeLogProbLoss, abc.ABC): """Base class for neg log prob losses whose inputs are 'natural' parameters. We will take the GGN of the loss to be the Fisher associated with the distribution, which also happens to be equal to the Hessian for this class of loss functions. See here: https://arxiv.org/abs/1412.1193 'Natural parameters' are defined for exponential-family models. See for example: https://en.wikipedia.org/wiki/Exponential_family """ def multiply_ggn_unweighted(self, vector: jnp.ndarray) -> jnp.ndarray: return self.multiply_fisher_unweighted(vector) def multiply_ggn_factor_unweighted(self, vector: jnp.ndarray) -> jnp.ndarray: return self.multiply_fisher_factor_unweighted(vector) def multiply_ggn_factor_transpose_unweighted( self, vector: jnp.ndarray ) -> jnp.ndarray: return self.multiply_fisher_factor_transpose_unweighted(vector) def multiply_ggn_factor_replicated_one_hot_unweighted( self, index: Index ) -> jnp.ndarray: return self.multiply_fisher_factor_replicated_one_hot_unweighted(index) @property def ggn_factor_inner_shape(self) -> Sequence[int]: return self.fisher_factor_inner_shape class DistributionNegativeLogProbLoss(NegativeLogProbLoss): """Base class for neg log prob losses that use the distribution classes.""" @property @abc.abstractmethod def dist(self): """The underlying distribution instance.""" pass def _evaluate(self, targets: jnp.ndarray): return -self.dist.log_prob(targets) def sample(self, rng_key: jnp.ndarray): return self.dist.sample(seed=rng_key) @property def fisher_factor_inner_shape(self) -> Sequence[int]: return self.dist.mean().shape class NormalMeanNegativeLogProbLoss(DistributionNegativeLogProbLoss, NaturalParamsNegativeLogProbLoss): """Neg log prob loss for a normal distribution parameterized by a mean vector. Note that the covariance is treated as the identity divided by 2. Also note that the Fisher for such a normal distribution with respect the mean parameter is given by: F = (1 / variance) * I See for example https://www.ii.pwr.edu.pl/~tomczak/PDF/[JMT]Fisher_inf.pdf. """ def __init__( self, mean: jnp.ndarray, targets: Optional[jnp.ndarray] = None, variance: float = 0.5, weight: float = 1.0, ): super().__init__(weight=weight) self._mean = mean self._targets = targets self._variance = variance if not isinstance(variance, float): raise ValueError("The `variance` argument should be python float.") @property def targets(self) -> Optional[jnp.ndarray]: return self._targets @property def dist(self): scale_diag = jnp.full_like(self._mean, jnp.sqrt(self._variance)) return distributions.MultivariateNormalDiag(self._mean, scale_diag) @property def params(self): return self._mean, def copy_with_different_inputs(self, inputs: Sequence[jnp.ndarray]): [mean] = inputs return NormalMeanNegativeLogProbLoss( mean=mean, targets=self.targets, variance=self._variance, weight=self.weight, ) def multiply_fisher_unweighted(self, vector: jnp.ndarray) -> jnp.ndarray: return vector / self._variance def multiply_fisher_factor_unweighted( self, vector: jnp.ndarray, ) -> jnp.ndarray: return vector / jnp.sqrt(self._variance) def multiply_fisher_factor_transpose_unweighted( self, vector: jnp.ndarray, ) -> jnp.ndarray: return self.multiply_fisher_factor_unweighted(vector) # it's symmetric def multiply_fisher_factor_replicated_one_hot_unweighted( self, index: Index, ) -> jnp.ndarray: assert len(index) == 1, f"Length of index was {len(index)}." index = index[0] ones_slice = jnp.ones([self._mean.shape[0]])[..., None] output_slice = ones_slice / jnp.sqrt(self._variance) return insert_slice_in_zeros(output_slice, 1, self._mean.shape[1], index) def insert_slice_in_zeros( slice_to_insert: jnp.ndarray, dim: int, dim_size: int, position: int, ) -> jnp.ndarray: """Inserts slice into a larger tensor of zeros. Forms a new tensor which is the same shape as slice_to_insert, except that the dimension given by 'dim' is expanded to the size given by 'dim_size'. 'position' determines the position (index) at which to insert the slice within that dimension. Assumes slice_to_insert.shape[dim] = 1. Args: slice_to_insert: The slice to insert. dim: The dimension which to expand with zeros. dim_size: The new size of the 'dim' dimension. position: The position of 'slice_to_insert' in the new tensor. Returns: The new tensor. Raises: ValueError: If the slice's shape at the given dim is not 1. """ slice_shape = slice_to_insert.shape if slice_shape[dim] != 1: raise ValueError(f"Expected slice_to_insert.shape to have {dim} dim of 1," f" but was {slice_to_insert.shape[dim]}.") before = [0] * int(len(slice_shape)) after = before[:] before[dim] = position after[dim] = dim_size - position - 1 return jnp.pad(slice_to_insert, list(zip(before, after))) # _______ _____ _ _ _ _ # |__ __| | __ \ (_) | | | | (_) # | | __ _ __ _ | |__) |___ __ _ _ ___| |_ _ __ __ _| |_ _ ___ _ __ # | |/ _` |/ _` | | _ // _ \/ _` | / __| __| '__/ _` | __| |/ _ \| '_ \ # | | (_| | (_| | | | \ \ __/ (_| | \__ \ |_| | | (_| | |_| | (_) | | | | # |_|\__,_|\__, | |_| \_\___|\__, |_|___/\__|_| \__,_|\__|_|\___/|_| |_| # __/ | __/ | # |___/ |___/ NormalMeanNegativeLogProbLoss_tag = tags.LossTag( NormalMeanNegativeLogProbLoss, num_inputs=1) def register_normal_predictive_distribution( mean: jnp.ndarray, targets: Optional[jnp.ndarray] = None, variance: float = 0.5, weight: float = 1.0, ): """Registers a normal predictive distribution. This corresponds to a squared error loss of the form weight/(2*var) * ||target - mean||^2 Args: mean: A tensor defining the mean vector of the distribution. The first dimension must be the batch size. targets: (OPTIONAL) The targets for the loss function. Only required if one wants to use the "empirical Fisher" instead of the true Fisher (which is controlled by the 'estimation_mode' to the optimizer). (Default: None) variance: float. The variance of the distribution. Note that the default value of 0.5 corresponds to a standard squared error loss weight * ||target - prediction||^2. If you want your squared error loss to be of the form 0.5*coeff*||target - prediction||^2 you should use variance=1.0. (Default: 0.5) weight: A scalar coefficient to multiply the log prob loss associated with this distribution. The Fisher will be multiplied by the corresponding factor. In general this is NOT equivalent to changing the temperature of the distribution, but in the ase of normal distributions it may be. (Default: 1.0) Returns: The mean and targets as dependable on the tag. """ if targets is None: targets = jnp.zeros_like(mean) return NormalMeanNegativeLogProbLoss_tag.bind( mean, targets, variance=variance, weight=weight, return_loss=False) def register_squared_error_loss( prediction: jnp.ndarray, targets: Optional[jnp.ndarray] = None, weight: float = 1.0, ): """Registers a squared error loss function. This assumes the squared error loss of the form ||target - prediction||^2, averaged across the mini-batch. If your loss uses a coefficient of 0.5 you need to set the "weight" argument to reflect this. Args: prediction: The prediction made by the network (i.e. its output). The first dimension must be the batch size. targets: (OPTIONAL) The targets for the loss function. Only required if one wants to use the "empirical Fisher" instead of the true Fisher (which is controlled by the 'estimation_mode' to the optimizer). (Default: None) weight: A float coefficient to multiply the loss function by. (Default: 1.0) Returns: The mean and targets as dependable on the tag. """ return register_normal_predictive_distribution( prediction, targets=targets, variance=0.5, weight=weight)
deepmind-research-master
kfac_ferminet_alpha/loss_functions.py
# Copyright 2020 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for anything that an end user would use.""" from kfac_ferminet_alpha.loss_functions import register_normal_predictive_distribution from kfac_ferminet_alpha.loss_functions import register_squared_error_loss from kfac_ferminet_alpha.optimizer import Optimizer
deepmind-research-master
kfac_ferminet_alpha/__init__.py
# Copyright 2020 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A module for registering already known functions for tagging patterns.""" import functools from typing import Sequence, Tuple, TypeVar import jax from jax import core as jax_core from jax import lax from jax import lib as jax_lib from jax.interpreters import batching as jax_batching import jax.numpy as jnp _T = TypeVar("_T") class LossTag(jax_core.Primitive): """A tagging primitive specifically for losses.""" multiple_results = True def __init__(self, cls, num_inputs: int, num_targets: int = 1): super().__init__(cls.__name__ + "_tag") self._cls = cls self._num_inputs = num_inputs self._num_targets = num_targets jax.xla.translations[self] = self.xla_translation jax.ad.primitive_jvps[self] = self.jvp # This line defines how does the tag behave under vmap. It is required for # any primitive that can be used inside a vmap. The reason why we want to # allow this is two fold - one to not break user code when the tags are not # used at all, and two - to be able to define a network with code for a # single example which is the vmap-ed for a batch. jax_batching.primitive_batchers[self] = self.batching @property def num_inputs(self) -> int: return self._num_inputs @property def num_targets(self) -> int: return self._num_targets def loss(self, *args, weight: float = 1.0, **kwargs): return self._cls(*args, weight=weight, **kwargs) def loss_evaluate(self, *args, weight: float = 1.0, **kwargs): return self.loss(*args, weight=weight, **kwargs).evaluate() def get_outputs(self, *args, weight: float, return_loss: bool, **kwargs): if len(args) < self.num_inputs: raise ValueError("Inputs to the tag are not enough.") if len(args) < self.num_inputs + self.num_targets: if len(args) != self.num_inputs: raise ValueError("Inputs to the tag are not quite enough.") if return_loss: raise ValueError("Can not have return_loss=True when there are no " "targets.") return args if len(args) > self.num_inputs + self.num_targets: raise ValueError("Inputs to the tag are too many.") if return_loss: return self.loss(*args, weight=weight, **kwargs).evaluate() else: return args def impl(self, *args, weight: float, return_loss: bool, **kwargs): return self.get_outputs(*args, weight=weight, return_loss=return_loss) def abstract_eval(self, *args, weight: float, return_loss: bool, **kwargs): jax_version = ( jax.__version_info__ if hasattr(jax, "__version_info__") else tuple(map(int, jax.__version__.split(".")))) if jax_version > (0, 3, 4): return (self.get_outputs(*args, weight=weight, return_loss=return_loss), jax_core.no_effects) return self.get_outputs(*args, weight=weight, return_loss=return_loss) def xla_translation( self, c, *args, weight: float = 1.0, return_loss: bool = False, **kwargs, ): outputs = self.get_outputs( *args, weight=weight, return_loss=return_loss, **kwargs) if isinstance(outputs, tuple): return jax_lib.xla_client.ops.Tuple(c, outputs) return outputs def jvp( self, arg_values, arg_tangents, weight: float, return_loss: bool, **kwargs, ): if len(arg_values) != len(arg_tangents): raise ValueError("Values and tangents are not the same length.") primal_output = self.bind( *arg_values, weight=weight, return_loss=return_loss, **kwargs) if len(arg_values) == self.num_inputs: tangents_out = self.get_outputs( *arg_tangents, weight=weight, return_loss=return_loss, **kwargs) elif return_loss: tangents_out = jax.jvp( functools.partial(self.loss_evaluate, weight=weight, **kwargs), arg_tangents, arg_tangents)[1] else: tangents_out = arg_tangents return primal_output, tangents_out def batching(self, batched_args, batched_dims, **kwargs): return self.bind(*batched_args, **kwargs), batched_dims[0] class LayerTag(jax_core.Primitive): """A tagging primitive that is used to mark/tag computation.""" def __init__(self, name: str, num_inputs: int, num_outputs: int): super().__init__(name) if num_outputs > 1: raise NotImplementedError( f"Only single outputs are supported, got: num_outputs={num_outputs}") self._num_outputs = num_outputs self._num_inputs = num_inputs jax.xla.translations[self] = self.xla_translation jax.ad.deflinear(self, self.transpose) jax.ad.primitive_transposes[self] = self.transpose # This line defines how does the tag behave under vmap. It is required for # any primitive that can be used inside a vmap. The reason why we want to # allow this is two fold - one to not break user code when the tags are not # used at all, and two - to be able to define a network with code for a # single example which is the vmap-ed for a batch. jax_batching.primitive_batchers[self] = self.batching @property def num_outputs(self) -> int: return self._num_outputs @property def num_inputs(self) -> int: return self._num_inputs def split_all_inputs( self, all_inputs: Sequence[_T], ) -> Tuple[Sequence[_T], Sequence[_T], Sequence[_T]]: outputs = tuple(all_inputs[:self.num_outputs]) inputs = tuple(all_inputs[self.num_outputs:self.num_outputs + self.num_inputs]) params = tuple(all_inputs[self.num_outputs + self.num_inputs:]) return outputs, inputs, params def get_outputs(self, *operands: _T, **kwargs) -> _T: assert self.num_outputs == 1 return operands[0] def xla_translation(self, c, *operands: _T, **kwargs) -> _T: return self.get_outputs(*operands, **kwargs) @staticmethod def transpose(cotangent, *operands, **kwargs): return (cotangent,) + (None,) * (len(operands) - 1) def impl(self, *operands, **kwargs): return self.get_outputs(*operands, **kwargs) def abstract_eval(self, *abstract_operands, **kwargs): jax_version = ( jax.__version_info__ if hasattr(jax, "__version_info__") else tuple(map(int, jax.__version__.split(".")))) if jax_version > (0, 3, 4): return self.get_outputs(*abstract_operands, **kwargs), jax_core.no_effects return self.get_outputs(*abstract_operands, **kwargs) def batching(self, batched_operands, batched_dims, **kwargs): return self.bind(*batched_operands, **kwargs), batched_dims[0] # _____ _ # / ____| (_) # | | __ ___ _ __ ___ _ __ _ ___ # | | |_ |/ _ \ '_ \ / _ \ '__| |/ __| # | |__| | __/ | | | __/ | | | (__ # \_____|\___|_| |_|\___|_| |_|\___| # # generic_tag = LayerTag(name="generic_tag", num_inputs=0, num_outputs=1) def register_generic(parameter: _T) -> _T: return generic_tag.bind(parameter) # _____ # | __ \ # | | | | ___ _ __ ___ ___ # | | | |/ _ \ '_ \/ __|/ _ \ # | |__| | __/ | | \__ \ __/ # |_____/ \___|_| |_|___/\___| # dense_tag = LayerTag(name="dense_tag", num_inputs=1, num_outputs=1) def register_dense(y, x, w, b=None): if b is None: return dense_tag.bind(y, x, w) return dense_tag.bind(y, x, w, b) def dense_func(x, params): """Example of a dense layer function.""" w = params[0] y = jnp.matmul(x, w) if len(params) == 1: # No bias return y # Add bias return y + params[1] def dense_tagging(jaxpr, inverse_map, values_map): """Correctly registers a dense layer pattern.""" del inverse_map in_values = [values_map[v] for v in jaxpr.invars] out_values = [values_map[v] for v in jaxpr.outvars] return register_dense(out_values[0], *in_values) # ___ _____ _____ _ _ _ # |__ \| __ \ / ____| | | | | (_) # ) | | | | | | ___ _ ____ _____ | |_ _| |_ _ ___ _ __ # / /| | | | | | / _ \| '_ \ \ / / _ \| | | | | __| |/ _ \| "_ \ # / /_| |__| | | |___| (_) | | | \ V / (_) | | |_| | |_| | (_) | | | | # |____|_____/ \_____\___/|_| |_|\_/ \___/|_|\__,_|\__|_|\___/|_| |_| # conv2d_tag = LayerTag(name="conv2d_tag", num_inputs=1, num_outputs=1) def register_conv2d(y, x, w, b=None, **kwargs): if b is None: return conv2d_tag.bind(y, x, w, **kwargs) return conv2d_tag.bind(y, x, w, b, **kwargs) def conv2d_func(x, params): """Example of a conv2d layer function.""" w = params[0] y = lax.conv_general_dilated( x, w, window_strides=(2, 2), padding="SAME", dimension_numbers=("NHWC", "HWIO", "NHWC")) if len(params) == 1: # No bias return y # Add bias return y + params[1][None, None, None] def conv2d_tagging(jaxpr, inverse_map, values_map): """Correctly registers a conv2d layer pattern.""" in_values = [values_map[v] for v in jaxpr.invars] out_values = [values_map[v] for v in jaxpr.outvars] keys = [k for k in inverse_map.keys() if isinstance(k, str)] keys = [k for k in keys if k.startswith("conv_general_dilated")] if len(keys) != 1: raise ValueError("Did not find any conv_general_dilated!") kwargs = inverse_map[keys[0]].params return register_conv2d(out_values[0], *in_values, **kwargs) # _____ _ _ _____ _ _ __ _ # / ____| | | | | / ____| | (_)/ _| | # | (___ ___ __ _| | ___ __ _ _ __ __| | | (___ | |__ _| |_| |_ # \___ \ / __/ _` | |/ _ \ / _` | '_ \ / _` | \___ \| '_ \| | _| __| # ____) | (_| (_| | | __/ | (_| | | | | (_| | ____) | | | | | | | |_ # |_____/ \___\__,_|_|\___| \__,_|_| |_|\__,_| |_____/|_| |_|_|_| \__| # scale_and_shift_tag = LayerTag( name="scale_and_shift_tag", num_inputs=1, num_outputs=1) def register_scale_and_shift(y, args, has_scale: bool, has_shift: bool): assert has_scale or has_shift x, args = args[0], args[1:] return scale_and_shift_tag.bind( y, x, *args, has_scale=has_scale, has_shift=has_shift) def scale_and_shift_func(x, params, has_scale: bool, has_shift: bool): """Example of a scale and shift function.""" if has_scale and has_shift: scale, shift = params return x * scale + shift elif has_scale: return x * params[0] elif has_shift: return x + params[0] else: raise ValueError() def scale_and_shift_tagging( jaxpr, inverse_map, values_map, has_scale: bool, has_shift: bool, ): """Correctly registers a scale and shift layer pattern.""" del inverse_map in_values = [values_map[v] for v in jaxpr.invars] out_values = [values_map[v] for v in jaxpr.outvars] return register_scale_and_shift(out_values[0], in_values, has_scale, has_shift) def batch_norm_func( inputs: Tuple[jnp.ndarray, jnp.ndarray], params: Tuple[jnp.ndarray, jnp.ndarray], ) -> jnp.ndarray: """Example of batch norm as is defined in Haiku.""" x, y = inputs scale, shift = params inv = scale * y return x * inv + shift def batch_norm_tagging_func( jaxpr, inverse_map, values_map, has_scale: bool, has_shift: bool, ): """Correctly registers a batch norm layer pattern as is defined in Haiku.""" del inverse_map in_values = [values_map[v] for v in jaxpr.invars] out_values = [values_map[v] for v in jaxpr.outvars] # The first two are both multipliers with the scale so we merge them in_values = [in_values[0] * in_values[1]] + in_values[2:] return register_scale_and_shift(out_values[0], in_values, has_scale, has_shift)
deepmind-research-master
kfac_ferminet_alpha/layers_and_loss_tags.py
# Copyright 2020 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for all distribution implementations needed for the loss functions.""" import math import jax import jax.numpy as jnp class MultivariateNormalDiag: """Multivariate normal distribution on `R^k`.""" def __init__( self, loc: jnp.ndarray, scale_diag: jnp.ndarray): """Initializes a MultivariateNormalDiag distribution. Args: loc: Mean vector of the distribution. Can also be a batch of vectors. scale_diag: Vector of standard deviations. """ super().__init__() self._loc = loc self._scale_diag = scale_diag @property def loc(self) -> jnp.ndarray: """Mean of the distribution.""" return self._loc @property def scale_diag(self) -> jnp.ndarray: """Scale of the distribution.""" return self._scale_diag def _num_dims(self) -> int: """Dimensionality of the events.""" return self._scale_diag.shape[-1] def _standardize(self, value: jnp.ndarray) -> jnp.ndarray: return (value - self._loc) / self._scale_diag def log_prob(self, value: jnp.ndarray) -> jnp.ndarray: """See `Distribution.log_prob`.""" log_unnormalized = -0.5 * jnp.square(self._standardize(value)) log_normalization = 0.5 * math.log(2 * math.pi) + jnp.log(self._scale_diag) return jnp.sum(log_unnormalized - log_normalization, axis=-1) def mean(self) -> jnp.ndarray: """Calculates the mean.""" return self.loc def sample(self, seed: jnp.ndarray) -> jnp.ndarray: """Samples an event. Args: seed: PRNG key or integer seed. Returns: A sample. """ eps = jax.random.normal(seed, self.loc.shape) return self.loc + eps * self.scale_diag
deepmind-research-master
kfac_ferminet_alpha/distributions.py