python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
|---|---|---|
# 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], # pytype: disable=signature-mismatch # overriding-return-type-checks
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
|
# 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.
"""Setup for pip package."""
from setuptools import setup
REQUIRED_PACKAGES = (
"absl-py",
"dataclasses",
"jax",
"networkx",
"numpy",
"ordered-set",
"typing",
)
LONG_DESCRIPTION = "\n".join([
"Kronecker-Factored Approximate Curvature (K-FAC) optimizer implemented in "
"JAX.",
"",
"Accompanying code for 'Better, Faster Fermionic Neural Networks'",
"James S. Spencer, David Pfau, Aleksandar Botev, and W. M. C. Foulkes.",
"https://arxiv.org/abs/2011.07125.",
])
setup(
name="kfac_ferminet_alpha",
version="0.0.1",
description="A K-FAC optimizer implemented in JAX",
long_description=LONG_DESCRIPTION,
url="https://github.com/deepmind/deepmind-research/kfac_ferminet_alpha",
author="DeepMind",
package_dir={"kfac_ferminet_alpha": "."},
packages=["kfac_ferminet_alpha"],
install_requires=REQUIRED_PACKAGES,
platforms=["any"],
license="Apache License, Version 2.0",
)
|
deepmind-research-master
|
kfac_ferminet_alpha/setup.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.
"""Example of running KFAC."""
from absl import app
from absl import flags
import jax
import jax.numpy as jnp
import numpy as np
import kfac_ferminet_alpha as kfac_ferminet_alpha
from kfac_ferminet_alpha import utils
TRAINING_STEPS = flags.DEFINE_integer(
name="training_steps",
default=100,
help="Number of training steps to perform")
BATCH_SIZE = flags.DEFINE_integer(
name="batch_size", default=128, help="Batch size")
LEARNING_RATE = flags.DEFINE_float(
name="learning_rate", default=1e-3, help="Learning rate")
L2_REG = flags.DEFINE_float(
name="l2_reg", default=1e-3, help="L2 regularization coefficient")
MOMENTUM = flags.DEFINE_float(
name="momentum", default=0.8, help="Momentum coefficient")
DAMPING = flags.DEFINE_float(
name="damping", default=1e-2, help="Damping coefficient")
MULTI_DEVICE = flags.DEFINE_bool(
name="multi_device",
default=False,
help="Whether the computation should be replicated across multiple devices")
SEED = flags.DEFINE_integer(name="seed", default=12412321, help="JAX RNG seed")
def glorot_uniform(shape, key):
dim_in = np.prod(shape[:-1])
dim_out = shape[-1]
c = jnp.sqrt(6 / (dim_in + dim_out))
return jax.random.uniform(key, shape=shape, minval=-c, maxval=c)
def fully_connected_layer(params, x):
w, b = params
return jnp.matmul(x, w) + b[None]
def model_init(rng_key, batch, encoder_sizes=(1000, 500, 250, 30)):
"""Initialize the standard autoencoder."""
x_size = batch.shape[-1]
decoder_sizes = encoder_sizes[len(encoder_sizes) - 2::-1]
sizes = (x_size,) + encoder_sizes + decoder_sizes + (x_size,)
keys = jax.random.split(rng_key, len(sizes) - 1)
params = []
for rng_key, dim_in, dim_out in zip(keys, sizes, sizes[1:]):
# Glorot uniform initialization
w = glorot_uniform((dim_in, dim_out), rng_key)
b = jnp.zeros([dim_out])
params.append((w, b))
return params, None
def model_loss(params, inputs, l2_reg):
"""Evaluate the standard autoencoder."""
h = inputs.reshape([inputs.shape[0], -1])
for i, layer_params in enumerate(params):
h = fully_connected_layer(layer_params, h)
# Last layer does not have a nonlinearity
if i % 4 != 3:
h = jnp.tanh(h)
l2_value = 0.5 * sum(jnp.square(p).sum() for p in jax.tree_leaves(params))
error = jax.nn.sigmoid(h) - inputs.reshape([inputs.shape[0], -1])
mean_squared_error = jnp.mean(jnp.sum(error * error, axis=1), axis=0)
regularized_loss = mean_squared_error + l2_reg * l2_value
return regularized_loss, dict(mean_squared_error=mean_squared_error)
def random_data(multi_device, batch_shape, rng):
if multi_device:
shape = (multi_device,) + tuple(batch_shape)
else:
shape = tuple(batch_shape)
while True:
rng, key = jax.random.split(rng)
yield jax.random.normal(key, shape)
def main(argv):
del argv # Unused.
learning_rate = jnp.asarray([LEARNING_RATE.value])
momentum = jnp.asarray([MOMENTUM.value])
damping = jnp.asarray([DAMPING.value])
# RNG keys
global_step = jnp.zeros([])
rng = jax.random.PRNGKey(SEED.value)
params_key, opt_key, step_key, data_key = jax.random.split(rng, 4)
dataset = random_data(MULTI_DEVICE.value, (BATCH_SIZE.value, 20), data_key)
example_batch = next(dataset)
if MULTI_DEVICE.value:
global_step = utils.replicate_all_local_devices(global_step)
learning_rate = utils.replicate_all_local_devices(learning_rate)
momentum = utils.replicate_all_local_devices(momentum)
damping = utils.replicate_all_local_devices(damping)
params_key, opt_key = utils.replicate_all_local_devices(
(params_key, opt_key))
step_key = utils.make_different_rng_key_on_all_devices(step_key)
split_key = jax.pmap(lambda x: tuple(jax.random.split(x)))
jit_init_parameters_func = jax.pmap(model_init)
else:
split_key = jax.random.split
jit_init_parameters_func = jax.jit(model_init)
# Initialize or load parameters
params, func_state = jit_init_parameters_func(params_key, example_batch)
# Make optimizer
optim = kfac_ferminet_alpha.Optimizer(
value_and_grad_func=jax.value_and_grad(
lambda p, x: model_loss(p, x, L2_REG.value), has_aux=True),
l2_reg=L2_REG.value,
value_func_has_aux=True,
value_func_has_state=False,
value_func_has_rng=False,
learning_rate_schedule=None,
momentum_schedule=None,
damping_schedule=None,
norm_constraint=1.0,
num_burnin_steps=10,
)
# Initialize optimizer
opt_state = optim.init(params, opt_key, example_batch, func_state)
for t in range(TRAINING_STEPS.value):
step_key, key_t = split_key(step_key)
params, opt_state, stats = optim.step(
params,
opt_state,
key_t,
dataset,
learning_rate=learning_rate,
momentum=momentum,
damping=damping)
global_step = global_step + 1
# Log any of the statistics
print(f"iteration: {t}")
print(f"mini-batch loss = {stats['loss']}")
if "aux" in stats:
for k, v in stats["aux"].items():
print(f"{k} = {v}")
print("----")
if __name__ == "__main__":
app.run(main)
|
deepmind-research-master
|
kfac_ferminet_alpha/example.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.
"""Utilities related to multi-device operations."""
import collections
from typing import Any, Mapping, Optional, Sequence, Tuple, TypeVar, Union
import dataclasses
import jax
from jax import core
from jax import lax
import jax.numpy as jnp
from jax.scipy import linalg
import jax.tree_util as tree_util
T = TypeVar("T")
def wrap_if_pmap(p_func):
def p_func_if_pmap(obj, axis_name):
try:
core.axis_frame(axis_name)
return p_func(obj, axis_name)
except NameError:
return obj
return p_func_if_pmap
pmean_if_pmap = wrap_if_pmap(lax.pmean)
psum_if_pmap = wrap_if_pmap(lax.psum)
compute_mean = jax.pmap(lambda x: lax.pmean(x, "i"), axis_name="i")
compute_sum = jax.pmap(lambda x: lax.psum(x, "i"), axis_name="i")
def get_first(obj: T) -> T:
return jax.tree_map(lambda x: x[0], obj)
def get_mean(obj: T) -> T:
return get_first(compute_mean(obj))
def get_sum(obj: T) -> T:
return get_first(compute_sum(obj))
broadcast_all_local_devices = jax.pmap(lambda x: x)
def replicate_all_local_devices(obj: T) -> T:
n = jax.local_device_count()
obj_stacked = jax.tree_map(lambda x: jnp.stack([x] * n, axis=0), obj)
return broadcast_all_local_devices(obj_stacked)
def make_different_rng_key_on_all_devices(rng: jnp.ndarray) -> jnp.ndarray:
rng = jax.random.fold_in(rng, jax.host_id())
rng = jax.random.split(rng, jax.local_device_count())
return broadcast_all_local_devices(rng)
p_split = jax.pmap(lambda key: tuple(jax.random.split(key)))
def scalar_mul(obj: T, scalar: Union[float, jnp.ndarray]) -> T:
return jax.tree_map(lambda x: x * scalar, obj)
def scalar_div(obj: T, scalar: Union[float, jnp.ndarray]) -> T:
return jax.tree_map(lambda x: x / scalar, obj)
def make_func_args(params, func_state, rng, batch, has_state: bool,
has_rng: bool):
"""Correctly puts all arguments to the function together."""
func_args = (params,)
if has_state:
if func_state is None:
raise ValueError("The `func_state` is None, but the argument `has_state` "
"is True.")
func_args += (func_state,)
if has_rng:
if rng is None:
raise ValueError("The `rng` is None, but the argument `has_rng` is True.")
func_args += (rng,)
func_args += (batch,)
return func_args
def extract_func_outputs(
raw_outputs: Any,
has_aux: bool,
has_state: bool,
) -> Tuple[jnp.ndarray, Any, Any]:
"""Given the function output returns separately the loss, func_state, aux."""
if not has_aux and not has_state:
return raw_outputs, None, None
loss, other = raw_outputs
if has_aux and has_state:
func_state, aux = other
elif has_aux:
func_state, aux = None, other
else:
func_state, aux = other, None
return loss, func_state, aux
def inner_product(obj1: T, obj2: T) -> jnp.ndarray:
if jax.tree_structure(obj1) != jax.tree_structure(obj2):
raise ValueError("The two structures are not identical.")
elements_product = jax.tree_map(lambda x, y: jnp.sum(x * y), obj1, obj2)
return sum(jax.tree_flatten(elements_product)[0])
def psd_inv_cholesky(matrix: jnp.ndarray, damping: jnp.ndarray) -> jnp.ndarray:
assert matrix.ndim == 2
identity = jnp.eye(matrix.shape[0])
matrix = matrix + damping * identity
return linalg.solve(matrix, identity, sym_pos=True)
def solve_maybe_small(a: jnp.ndarray, b: jnp.ndarray) -> jnp.ndarray:
"""Computes a^-1 b more efficiently for small matrices."""
assert a.shape[-1] == a.shape[-2] == b.shape[-1]
d = a.shape[-1]
if d == 0:
return a
elif d == 1:
return b / a[..., 0]
elif d == 2:
det = a[..., 0, 0] * a[..., 1, 1] - a[..., 0, 1] * a[..., 1, 0]
b_0 = a[..., 1, 1] * b[..., 0] - a[..., 0, 1] * b[..., 1]
b_1 = a[..., 0, 0] * b[..., 1] - a[..., 1, 0] * b[..., 0]
return jnp.stack([b_0, b_1], axis=-1) / det
elif d == 3:
raise NotImplementedError()
return jnp.linalg.solve(a, b)
def pi_adjusted_inverse(
factor_0: jnp.ndarray,
factor_1: jnp.ndarray,
damping: jnp.ndarray,
pmap_axis_name: str,
) -> Tuple[jnp.ndarray, jnp.ndarray]:
"""Performs inversion with pi-adjusted damping."""
# Compute the norms of each factor
norm_0 = jnp.trace(factor_0)
norm_1 = jnp.trace(factor_1)
# We need to sync the norms here, because reduction can be non-deterministic.
# They specifically are on GPUs by default for better performance.
# Hence although factor_0 and factor_1 are synced, the trace operation above
# can still produce different answers on different devices.
norm_0, norm_1 = pmean_if_pmap((norm_0, norm_1), axis_name=pmap_axis_name)
# Compute the overall scale
scale = norm_0 * norm_1
def regular_inverse(
operand: Sequence[jnp.ndarray]) -> Tuple[jnp.ndarray, jnp.ndarray]:
factor0, factor1, norm0, norm1, s, d = operand
# Special cases with one or two scalar factors
if factor0.size == 1 and factor1.size == 1:
value = jnp.ones_like(factor0) / jnp.sqrt(s)
return value, value
if factor0.size == 1:
factor1_normed = factor1 / norm1
damping1 = d / norm1
factor1_inv = psd_inv_cholesky(factor1_normed, damping1)
return jnp.full((1, 1), s), factor1_inv
if factor1.size == 1:
factor0_normed = factor0 / norm0
damping0 = d / norm0
factor0_inv = psd_inv_cholesky(factor0_normed, damping0)
return factor0_inv, jnp.full((1, 1), s)
# Invert first factor
factor0_normed = factor0 / norm0
damping0 = jnp.sqrt(d * factor1.shape[0] / (s * factor0.shape[0]))
factor0_inv = psd_inv_cholesky(factor0_normed, damping0) / jnp.sqrt(s)
# Invert second factor
factor1_normed = factor1 / norm1
damping1 = jnp.sqrt(d * factor0.shape[0] / (s * factor1.shape[0]))
factor1_inv = psd_inv_cholesky(factor1_normed, damping1) / jnp.sqrt(s)
return factor0_inv, factor1_inv
def zero_inverse(
operand: Sequence[jnp.ndarray]) -> Tuple[jnp.ndarray, jnp.ndarray]:
return (jnp.eye(factor_0.shape[0]) / jnp.sqrt(operand[-1]),
jnp.eye(factor_1.shape[0]) / jnp.sqrt(operand[-1]))
# In the special case where for some reason one of the factors is zero, then
# the correct inverse of `(0 kron A + lambda I)` is
# `(I/sqrt(lambda) kron (I/sqrt(lambda)`. However, because one of the norms is
# zero, then `pi` and `1/pi` would be 0 and infinity leading to NaN values.
# Hence, we need to make this check explicitly.
return lax.cond(
jnp.greater(scale, 0.0),
regular_inverse,
zero_inverse,
operand=(factor_0, factor_1, norm_0, norm_1, scale, damping))
def convert_value_and_grad_to_value_func(
value_and_grad_func,
has_aux: bool = False,
):
"""Converts a value_and_grad function to value_func only."""
def value_func(*args, **kwargs):
out, _ = value_and_grad_func(*args, **kwargs)
if has_aux:
return out[0]
else:
return out
return value_func
def check_structure_shapes_and_dtype(obj1: T, obj2: T) -> None:
"""Verifies that the two objects have the same pytree structure."""
assert jax.tree_structure(obj1) == jax.tree_structure(obj2)
for v1, v2 in zip(jax.tree_flatten(obj1)[0], jax.tree_flatten(obj2)[0]):
assert v1.shape == v2.shape
assert v1.dtype == v2.dtype
def check_first_dim_is_batch_size(batch_size: int, *args: jnp.ndarray) -> None:
for i, arg in enumerate(args):
if arg.shape[0] != batch_size:
raise ValueError(f"Expecting first dimension of arg[{i}] with shape "
f"{arg.shape} to be equal to the batch size "
f"{batch_size}.")
def py_tree_registered_dataclass(cls, *args, **kwargs):
"""Creates a new dataclass type and registers it as a pytree node."""
dcls = dataclasses.dataclass(cls, *args, **kwargs)
tree_util.register_pytree_node(
dcls,
lambda instance: ( # pylint: disable=g-long-lambda
[getattr(instance, f.name)
for f in dataclasses.fields(instance)], None),
lambda _, instance_args: dcls(*instance_args))
return dcls
class WeightedMovingAverage:
"""A wrapped class for a variable for which we keep exponential moving average."""
def __init__(self, weight: jnp.ndarray, array: jnp.ndarray):
self._weight = weight
self._array = array
@staticmethod
def zero(shape: Sequence[int]) -> "WeightedMovingAverage":
return WeightedMovingAverage(weight=jnp.zeros([]), array=jnp.zeros(shape))
@property
def weight(self) -> jnp.ndarray:
return self._weight
@property
def value(self) -> jnp.ndarray:
return self._array / self._weight
@property
def raw_value(self) -> jnp.ndarray:
return self._array
def update(self, value: jnp.ndarray, old_weight_multiplier: float,
new_weight: float) -> None:
self._weight = old_weight_multiplier * self._weight + new_weight
self._array = old_weight_multiplier * self._array + new_weight * value
def sync(self, pmap_axis_name: str) -> None:
self._array = pmean_if_pmap(self._array, pmap_axis_name)
def __str__(self) -> str:
return (f"ExponentialMovingAverage(weight={self._weight}, "
f"array={self._array})")
def __repr__(self) -> str:
return self.__str__()
tree_util.register_pytree_node(
WeightedMovingAverage,
lambda instance: ((instance.weight, instance.raw_value), None),
lambda _, instance_args: WeightedMovingAverage(*instance_args),
)
class Stateful:
"""A class for stateful objects."""
def __init__(self, stateful_fields_names: Optional[Sequence[str]] = ()):
self.__stateful_fields_names = stateful_fields_names
def _add_stateful_fields_names(self, value: Sequence[str]) -> None:
self.__stateful_fields_names += tuple(value)
def get_state(self) -> Mapping[str, Any]:
"""Returns the state of the object."""
state = dict()
for name in self.__stateful_fields_names:
state[name] = Stateful._get_state_from_instance(getattr(self, name))
return state
def set_state(self, value):
"""Sets the state of the object with the provided value and returns the object."""
assert isinstance(value, dict)
for name in self.__stateful_fields_names:
setattr(self, name,
Stateful._set_state_to_instance(getattr(self, name), value[name]))
return self
def clear_state(self) -> None:
"""Clears the state of the object."""
for name in self.__stateful_fields_names:
setattr(self, name,
Stateful._clear_state_from_instance(getattr(self, name)))
def pop_state(self) -> Mapping[str, Any]:
"""Returns the current state of the object, while simultaneously clearing it."""
state = self.get_state()
self.clear_state()
return state
@staticmethod
def _get_state_from_instance(obj):
"""Recursively gets the state of the object and returns it."""
if isinstance(obj, Stateful):
return obj.get_state()
if isinstance(obj, list):
return [Stateful._get_state_from_instance(i) for i in obj]
if isinstance(obj, tuple):
return tuple(Stateful._get_state_from_instance(i) for i in obj)
if isinstance(obj, collections.OrderedDict):
return collections.OrderedDict(
(k, Stateful._get_state_from_instance(v)) for k, v in obj.items())
if isinstance(obj, dict):
return dict(
(k, Stateful._get_state_from_instance(v)) for k, v in obj.items())
return obj
@staticmethod
def _set_state_to_instance(obj, value):
"""Recursively sets the state of the object and returns it."""
if isinstance(obj, Stateful):
obj.set_state(value)
return obj
if isinstance(value, list):
if obj is None:
obj = [None] * len(value)
return [
Stateful._set_state_to_instance(obj_i, value_i)
for obj_i, value_i in zip(obj, value)
]
if isinstance(value, tuple):
if obj is None:
obj = [None] * len(value)
return tuple(
Stateful._set_state_to_instance(obj_i, value_i)
for obj_i, value_i in zip(obj, value))
if isinstance(value, collections.OrderedDict):
if obj is None:
obj = dict((k, None) for k in value)
return collections.OrderedDict(
(k, Stateful._set_state_to_instance(obj[k], value[k])) for k in obj)
if isinstance(value, dict):
obj = dict((k, None) for k in value)
return dict(
(k, Stateful._set_state_to_instance(obj[k], value[k])) for k in obj)
return value
@staticmethod
def _clear_state_from_instance(obj):
"""Recursively clears the state of the object and returns it."""
if isinstance(obj, Stateful):
obj.clear_state()
return obj
if isinstance(obj, list):
return [Stateful._clear_state_from_instance(obj_i) for obj_i in obj]
if isinstance(obj, tuple):
return tuple(Stateful._clear_state_from_instance(obj_i) for obj_i in obj)
if isinstance(obj, collections.OrderedDict):
return collections.OrderedDict(
(k, Stateful._clear_state_from_instance(obj[k])) for k in obj)
if isinstance(obj, dict):
return dict((k, Stateful._clear_state_from_instance(obj[k])) for k in obj)
return None
@staticmethod
def infer_class_state(class_type):
"""Infers a stateful class state attributes from class annotations."""
if not issubclass(class_type, Stateful):
raise ValueError(
f"In order to annotate a class as stateful it must inherit "
f"{Stateful!r}")
class_type = dataclasses.dataclass(
class_type, init=False, repr=False, eq=False) # pytype: disable=wrong-keyword-args
fields_names = tuple(field.name for field in dataclasses.fields(class_type))
original_init = getattr(class_type, "__init__", None)
if original_init is None:
def injected_init(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs) # pylint: disable=bad-super-call
Stateful._add_stateful_fields_names(self, fields_names)
for field_name in fields_names:
if getattr(self, field_name, None) is None:
setattr(self, field_name, None)
setattr(class_type, "__init__", injected_init)
else:
def injected_init(self, *args, **kwargs):
original_init(self, *args, **kwargs)
Stateful._add_stateful_fields_names(self, fields_names)
for field_name in fields_names:
if getattr(self, field_name, None) is None:
setattr(self, field_name, None)
setattr(class_type, "__init__", injected_init)
return class_type
def compute_sq_norm_relative_abs_diff(obj, pmap_axis_name):
sq_norm = inner_product(obj, obj)
synced_sq_norm = psum_if_pmap(sq_norm, pmap_axis_name)
synced_sq_norm = (synced_sq_norm - sq_norm) / (jax.device_count() - 1.0)
sq_norm_abs_diff = jnp.abs(sq_norm - synced_sq_norm)
return sq_norm_abs_diff / sq_norm
def product(iterable_object):
x = 1
for element in iterable_object:
x *= element
return x
|
deepmind-research-master
|
kfac_ferminet_alpha/utils.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 the main curvature optimizer class."""
from typing import Any, Callable, Iterator, Mapping, Optional, Sequence, Tuple, Union
import jax
import jax.lax as lax
import jax.numpy as jnp
import jax.random as jnr
from kfac_ferminet_alpha import estimator
from kfac_ferminet_alpha import tag_graph_matcher as tgm
from kfac_ferminet_alpha import utils
ScheduleType = Callable[[jnp.ndarray], Optional[jnp.ndarray]]
Parameters = Any
Batch = Any
FuncState = Any
State = Mapping[str, Any]
@utils.Stateful.infer_class_state
class Optimizer(utils.Stateful):
"""The default optimizer class."""
velocities: Parameters
estimator: estimator.CurvatureEstimator
step_counter: jnp.ndarray
def __init__(
self,
value_and_grad_func,
l2_reg: Union[float, jnp.ndarray],
value_func_has_aux: bool = False,
value_func_has_state: bool = False,
value_func_has_rng: bool = False,
learning_rate_schedule: Optional[ScheduleType] = None,
momentum_schedule: Optional[ScheduleType] = None,
damping_schedule: Optional[ScheduleType] = None,
min_damping: Union[float, jnp.ndarray] = 1e-8,
max_damping: Union[float, jnp.ndarray] = jnp.inf,
norm_constraint: Optional[Union[float, jnp.ndarray]] = None,
num_burnin_steps: int = 10,
estimation_mode: str = "fisher_gradients",
curvature_ema: Union[float, jnp.ndarray] = 0.95,
inverse_update_period: int = 5,
register_only_generic: bool = False,
layer_tag_to_block_cls: Optional[estimator.TagMapping] = None,
patterns_to_skip: Sequence[str] = (),
donate_parameters: bool = False,
donate_optimizer_state: bool = False,
donate_batch_inputs: bool = False,
donate_func_state: bool = False,
batch_process_func: Optional[Callable[[Any], Any]] = None,
multi_device: bool = False,
use_jax_cond: bool = True,
debug: bool = False,
pmap_axis_name="kfac_axis",
):
"""Initializes the K-FAC optimizer with the given settings.
Args:
value_and_grad_func: Python callable. The function should return the value
of the loss to be optimized and its gradients. If the argument
`value_func_has_aux` is `False` then the interface should be: loss,
loss_grads = value_and_grad_func(params, batch)
If `value_func_has_aux` is `True` then the interface should be: (loss,
aux), loss_grads = value_and_grad_func(params, batch)
l2_reg: Scalar. Set this value to tell the optimizer what L2
regularization coefficient you are using (if any). Note the coefficient
appears in the regularizer as coeff / 2 * sum(param**2). Note that the
user is still responsible for adding regularization to the loss.
value_func_has_aux: Boolean. Specifies whether the provided callable
`value_and_grad_func` returns the loss value only, or also some
auxiliary data. (Default: False)
value_func_has_state: Boolean. Specifies whether the provided callable
`value_and_grad_func` has a persistent state that is inputed and
it also outputs an update version of it. (Default: False)
value_func_has_rng: Boolean. Specifies whether the provided callable
`value_and_grad_func` additionally takes as input an rng key.
(Default: False)
learning_rate_schedule: Callable. A schedule for the learning rate. This
should take as input the current step number and return a single
`jnp.ndarray` that represents the learning rate. (Default: None)
momentum_schedule: Callable. A schedule for the momentum. This should take
as input the current step number and return a single `jnp.ndarray`
that represents the momentum. (Default: None)
damping_schedule: Callable. A schedule for the damping. This should take
as input the current step number and return a single `jnp.ndarray`
that represents the learning rate. (Default: None)
min_damping: Scalar. Minimum value the damping parameter can take. Note
that the default value of 1e-8 is quite arbitrary, and you may have to
adjust this up or down for your particular problem. If you are using a
non-zero value of l2_reg you *may* be able to set this to
zero. (Default: 1e-8)
max_damping: Scalar. Maximum value the damping parameter can take.
(Default: Infinity)
norm_constraint: Scalar. If specified, the update is scaled down so that
its approximate squared Fisher norm `v^T F v` is at most the specified
value.(Note that here `F` is the approximate curvature matrix, not the
exact.) (Default: None)
num_burnin_steps: Int. At the start of optimization, e.g. the first step,
before performing the actual step the optimizer will perform this many
times updates to the curvature approximation without updating the
actual parameters. (Default: 10)
estimation_mode: String. The type of estimator to use for the curvature
matrix. Can be one of: * fisher_empirical * fisher_exact *
fisher_gradients * fisher_curvature_prop * ggn_exact *
ggn_curvature_prop See the doc-string for CurvatureEstimator (in
estimator.py) for a more
detailed description of these options. (Default: 'fisher_gradients').
curvature_ema: The decay factor used when calculating the covariance
estimate moving averages. (Default: 0.95)
inverse_update_period: Int. The number of steps in between updating the
the computation of the inverse curvature approximation. (Default: 5)
register_only_generic: Boolean. Whether when running the auto-tagger to
register only generic parameters, or allow it to use the graph matcher
to automatically pick up any kind of layer tags. (Default: False)
layer_tag_to_block_cls: Dictionary. A mapping from layer tags to block
classes which to override the default choices of block approximation for
that specific tag. See the doc-string for CurvatureEstimator (in
estimator.py) for a more detailed description of this.
patterns_to_skip: Tuple. A list of any patterns that should be skipped by
the graph matcher when auto-tagging.
donate_parameters: Boolean. Whether to use jax's `donate_argnums` to
donate the parameter values of each call to `step`. Note that this
implies that you will not be able to access the old parameter values'
buffers after calling into `step`.
donate_optimizer_state: Boolean. Whether to use jax's `donate_argnums` to
donate the optimizer state of each call to `step`. Note that this
implies that you will not be able to access the old optimizer state
values' buffers after calling into `step`.
donate_batch_inputs: Boolean. Whether to use jax's `donate_argnums` to
donate the batch values of each call to `step`. Note that this implies
that you will not be able to access the old batch values' buffers after
calling into `step`.
donate_func_state: Boolean. Whether to use jax's `donate_argnums` to
donate the persistent function state of each call to `step`. Note that
this implies that you will not be able to access the old function state
values' buffers after calling into `step`.
batch_process_func: Callable. A function which to be called on each batch
before feeding to the KFAC on device. This could be useful for specific
device input optimizations.
multi_device: Boolean. Whether to use `pmap` and run the optimizer on
multiple devices. (Default: False)
use_jax_cond: Not used for the moment.
debug: Boolean. If non of the step or init functions would be jitted. Note
that this also overrides `multi_device` and prevents using `pmap`.
(Default: False)
pmap_axis_name: String. The name of the `pmap` axis to use when
`multi_device` is set to True. (Default: curvature_axis)
"""
super().__init__()
self.value_and_grad_func = value_and_grad_func
self.value_func_has_aux = value_func_has_aux
self.value_func_has_state = value_func_has_state
self.value_func_has_rng = value_func_has_rng
self.value_func = utils.convert_value_and_grad_to_value_func(
value_and_grad_func, has_aux=value_func_has_aux)
self.l2_reg = l2_reg
self.learning_rate_schedule = learning_rate_schedule
if momentum_schedule is not None:
def schedule_with_first_step_zero(global_step: jnp.ndarray):
value = momentum_schedule(global_step)
check = jnp.equal(global_step, 0)
return check * jnp.zeros_like(value) + (1 - check) * value
self.momentum_schedule = schedule_with_first_step_zero
else:
self.momentum_schedule = None
self.damping_schedule = damping_schedule
self.min_damping = min_damping
self.max_damping = max_damping
self.norm_constraint = norm_constraint
self.num_burnin_steps = num_burnin_steps
self.estimation_mode = estimation_mode
self.curvature_ema = curvature_ema
self.inverse_update_period = inverse_update_period
self.register_only_generic = register_only_generic
self.layer_tag_to_block_cls = layer_tag_to_block_cls
self.patterns_to_skip = patterns_to_skip
self.donate_parameters = donate_parameters
self.donate_optimizer_state = donate_optimizer_state
self.donate_batch_inputs = donate_batch_inputs
self.donate_func_state = donate_func_state
self.batch_process_func = batch_process_func or (lambda x: x)
self.multi_device = multi_device
self.use_jax_cond = use_jax_cond
self.debug = debug
self.pmap_axis_name = pmap_axis_name if multi_device else None
self._rng_split = utils.p_split if multi_device else jnr.split
# Attributes filled in during self.init()
self.finalized = False
self.tagged_func = None
self.flat_params_shapes = None
self.params_treedef = None
# Special attributes related to jitting/pmap
self._jit_init = None
self._jit_burnin = None
self._jit_step = None
def finalize(
self,
params: Parameters,
rng: jnp.ndarray,
batch: Batch,
func_state: Optional[FuncState] = None,
) -> None:
"""Finalizes the optimizer by tracing the model function with the params and batch."""
if self.finalized:
raise ValueError("Optimizer has already been finalized.")
if self.multi_device:
# We assume that the parameters and batch are replicated, while tracing
# must happen with parameters for a single device call
params, rng, batch = jax.tree_map(lambda x: x[0], (params, rng, batch))
if func_state is not None:
func_state = jax.tree_map(lambda x: x[0], func_state)
batch = self.batch_process_func(batch)
# These are all tracing operations and we can run them with abstract values
func_args = utils.make_func_args(params, func_state, rng, batch,
self.value_func_has_state,
self.value_func_has_rng)
# Run all tracing with abstract values so no computation is done
flat_params, self.params_treedef = jax.tree_flatten(params)
self.flat_params_shapes = tuple(p.shape for p in flat_params)
self.tagged_func = tgm.auto_register_tags(
func=self.value_func,
func_args=func_args,
params_index=0,
register_only_generic=self.register_only_generic,
patterns_to_skip=self.patterns_to_skip)
self.estimator = estimator.CurvatureEstimator(
self.tagged_func,
func_args,
self.l2_reg,
self.estimation_mode,
layer_tag_to_block_cls=self.layer_tag_to_block_cls)
# Arguments: params, opt_state, rng, batch, func_state
donate_argnums = []
if self.donate_parameters:
donate_argnums.append(0)
if self.donate_optimizer_state:
donate_argnums.append(1)
if self.donate_batch_inputs:
donate_argnums.append(3)
if self.donate_func_state and self.value_func_has_state:
donate_argnums.append(4)
donate_argnums = tuple(donate_argnums)
if self.debug:
self._jit_init = self._init
self._jit_burnin = self._burnin
self._jit_step = self._step
elif self.multi_device:
self._jit_init = jax.pmap(
self._init, axis_name=self.pmap_axis_name, donate_argnums=[0])
# batch size is static argnum and is at index 5
self._jit_burnin = jax.pmap(
self._burnin,
axis_name=self.pmap_axis_name,
static_broadcasted_argnums=[5])
self._jit_step = jax.pmap(
self._step,
axis_name=self.pmap_axis_name,
donate_argnums=donate_argnums,
static_broadcasted_argnums=[5])
else:
self._jit_init = jax.jit(self._init, donate_argnums=[0])
# batch size is static argnum and is at index 5
self._jit_burnin = jax.jit(self._burnin, static_argnums=[5])
self._jit_step = jax.jit(
self._step, donate_argnums=donate_argnums, static_argnums=[5])
self.finalized = True
def _init(self, rng: jnp.ndarray) -> State:
"""This is the non-jitted version of initializing the state."""
flat_velocities = [jnp.zeros(shape) for shape in self.flat_params_shapes]
return dict(
velocities=jax.tree_unflatten(self.params_treedef, flat_velocities),
estimator=self.estimator.init(rng, None),
step_counter=jnp.asarray(0))
def verify_args_and_get_step_counter(
self,
params: Parameters,
state: State,
rng: jnp.ndarray,
data_iterator: Iterator[Batch],
func_state: Optional[FuncState] = None,
learning_rate: Optional[jnp.ndarray] = None,
momentum: Optional[jnp.ndarray] = None,
damping: Optional[jnp.ndarray] = None,
global_step_int: Optional[int] = None,
) -> int:
"""Verifies that the arguments passed to `Optimizer.step` are correct."""
if not self.finalized:
rng, rng_finalize = self._rng_split(rng)
self.finalize(params, rng_finalize, next(data_iterator), func_state)
# Verify correct arguments invocation
if self.learning_rate_schedule is not None and learning_rate is not None:
raise ValueError("When you have passed a `learning_rate_schedule` you "
"should not pass a value to the step function.")
if self.momentum_schedule is not None and momentum is not None:
raise ValueError("When you have passed a `momentum_schedule` you should "
"not pass a value to the step function.")
if self.damping_schedule is not None and damping is not None:
raise ValueError("When you have passed a `damping_schedule` you should "
"not pass a value to the step function.")
# Do a bunrnin on the first iteration
if global_step_int is None:
if self.multi_device:
return int(utils.get_first(state["step_counter"]))
else:
return int(state["step_counter"])
return global_step_int
def _burnin(
self,
params: Parameters,
state: State,
rng: jnp.ndarray,
batch: Batch,
func_state: Optional[FuncState],
batch_size: Optional[int],
) -> Tuple[State, Optional[FuncState]]:
"""This is the non-jitted version of a single burnin step."""
self.set_state(state)
batch = self.batch_process_func(batch)
rng, func_rng = jnr.split(rng) if self.value_func_has_rng else (rng, None)
func_args = utils.make_func_args(params, func_state, func_rng, batch,
self.value_func_has_state,
self.value_func_has_rng)
# Compute batch size
if batch_size is None:
batch_size = jax.tree_flatten(batch)[0][0].shape[0]
# Update curvature estimate
ema_old, ema_new = 1.0, 1.0 / self.num_burnin_steps
self.estimator.update_curvature_matrix_estimate(ema_old, ema_new,
batch_size, rng, func_args,
self.pmap_axis_name)
if func_state is not None:
out, _ = self.value_and_grad_func(*func_args)
_, func_state, _ = utils.extract_func_outputs(out,
self.value_func_has_aux,
self.value_func_has_state)
return self.pop_state(), func_state
def _step(
self,
params: Parameters,
state: State,
rng: jnp.ndarray,
batch: Batch,
func_state: Optional[FuncState],
batch_size: Optional[int],
learning_rate: Optional[jnp.ndarray],
momentum: Optional[jnp.ndarray],
damping: Optional[jnp.ndarray],
) -> Union[Tuple[Parameters, State, FuncState, Mapping[str, jnp.ndarray]],
Tuple[Parameters, State, Mapping[str, jnp.ndarray]]]:
"""This is the non-jitted version of a single step."""
# Unpack and set the state
self.set_state(state)
if damping is not None:
assert self.estimator.damping is None
self.estimator.damping = damping
else:
assert self.estimator.damping is not None
# Preprocess the batch and construct correctly the function arguments
batch = self.batch_process_func(batch)
rng, func_rng = jnr.split(rng) if self.value_func_has_rng else (rng, None)
func_args = utils.make_func_args(params, func_state, func_rng, batch,
self.value_func_has_state,
self.value_func_has_rng)
# Compute the batch size
if batch_size is None:
batch_size = jax.tree_flatten(batch)[0][0].shape[0]
# Compute schedules if applicable
if self.learning_rate_schedule is not None:
assert learning_rate is None
learning_rate = self.learning_rate_schedule(self.step_counter)
else:
assert learning_rate is not None
if self.momentum_schedule is not None:
assert momentum is None
momentum = self.momentum_schedule(self.step_counter)
else:
assert momentum is not None
if self.damping_schedule is not None:
assert damping is None
damping = self.damping_schedule(self.step_counter)
else:
assert damping is not None
# Compute current loss and gradients
out, grads = self.value_and_grad_func(*func_args)
loss, new_func_state, aux = utils.extract_func_outputs(
out, self.value_func_has_aux, self.value_func_has_state)
# Sync loss and grads
loss, grads = utils.pmean_if_pmap((loss, grads), self.pmap_axis_name)
# Update curvature estimate
self.estimator.update_curvature_matrix_estimate(
self.curvature_ema,
1.0,
batch_size,
rng,
func_args,
self.pmap_axis_name,
)
# Optionally update the inverse estimate
self.estimator.set_state(
lax.cond(
self.step_counter % self.inverse_update_period == 0,
lambda s: self.estimator.update_curvature_estimate_inverse( # pylint: disable=g-long-lambda
self.pmap_axis_name, s),
lambda s: s,
self.estimator.pop_state()))
# Compute proposed directions
vectors = self.propose_directions(
grads,
self.velocities,
learning_rate,
momentum,
)
# The learning rate is defined as the negative of the coefficient by which
# we multiply the gradients, while the momentum is the coefficient by
# which we multiply the velocities.
neg_learning_rate = -learning_rate # pytype: disable=unsupported-operands # trace-all-classes
# Compute the coefficients of the update vectors
assert neg_learning_rate is not None and momentum is not None
coefficients = (neg_learning_rate, momentum)
# Update velocities and compute new delta
self.velocities, delta = self.velocities_and_delta(
self.velocities,
vectors,
coefficients,
)
# Update parameters: params = params + delta
params = jax.tree_map(jnp.add, params, delta)
# Optionally compute the reduction ratio and update the damping
self.estimator.damping = None
rho = jnp.nan
# Statistics with useful information
stats = dict()
stats["step"] = self.step_counter
stats["loss"] = loss
stats["learning_rate"] = -coefficients[0]
stats["momentum"] = coefficients[1]
stats["damping"] = damping
stats["rho"] = rho
if self.value_func_has_aux:
stats["aux"] = aux
self.step_counter = self.step_counter + 1
if self.value_func_has_state:
return params, self.pop_state(), new_func_state, stats # pytype: disable=bad-return-type # jax-ndarray
else:
assert new_func_state is None
return params, self.pop_state(), stats # pytype: disable=bad-return-type # jax-ndarray
def init(
self,
params: Parameters,
rng: jnp.ndarray,
batch: Batch,
func_state: Optional[FuncState] = None,
) -> State:
"""Initializes the optimizer and returns the appropriate optimizer state."""
if not self.finalized:
self.finalize(params, rng, batch, func_state)
return self._jit_init(rng)
def step(
self,
params: Parameters,
state: Mapping[str, Any],
rng: jnp.ndarray,
data_iterator: Iterator[Any],
func_state: Any = None,
learning_rate: Optional[jnp.ndarray] = None,
momentum: Optional[jnp.ndarray] = None,
damping: Optional[jnp.ndarray] = None,
batch_size: Optional[int] = None,
global_step_int: Optional[int] = None,
) -> Union[Tuple[Parameters, State, FuncState, Mapping[str, jnp.ndarray]],
Tuple[Parameters, State, Mapping[str, jnp.ndarray]]]:
"""Performs a single update step using the optimizer.
Args:
params: The parameters of the model.
state: The state of the optimizer.
rng: A Jax PRNG key.
data_iterator: An iterator that returns a batch of data.
func_state: Any function state that gets passed in and returned.
learning_rate: This must be provided when
`use_adaptive_learning_rate=False` and `learning_rate_schedule=None`.
momentum: This must be provided when
`use_adaptive_momentum=False` and `momentum_schedule=None`.
damping: This must be provided when
`use_adaptive_damping=False` and `damping_schedule=None`.
batch_size: The batch size to use for KFAC. The default behaviour when it
is None is to use the leading dimension of the first data array.
global_step_int: The global step as a python int. Note that this must
match the step inte rnal to the optimizer that is part of its state.
Returns:
(params, state, stats)
where:
params: The updated model parameters.
state: The updated optimizer state.
stats: A dictionary of key statistics provided to be logged.
"""
step_counter_int = self.verify_args_and_get_step_counter(
params=params,
state=state,
rng=rng,
data_iterator=data_iterator,
func_state=func_state,
learning_rate=learning_rate,
momentum=momentum,
damping=damping,
global_step_int=global_step_int)
if step_counter_int == 0:
for _ in range(self.num_burnin_steps):
rng, rng_burn = self._rng_split(rng)
batch = next(data_iterator)
state, func_state = self._jit_burnin(params, state, rng_burn, batch,
func_state, batch_size)
# On the first step we always treat the momentum as 0.0
if self.momentum_schedule is None:
momentum = jnp.zeros([])
if self.multi_device:
momentum = utils.replicate_all_local_devices(momentum)
batch = next(data_iterator)
return self._jit_step(params, state, rng, batch, func_state, batch_size,
learning_rate, momentum, damping)
def propose_directions(
self,
grads: Parameters,
velocities: Parameters,
learning_rate: Optional[jnp.ndarray],
momentum: Optional[jnp.ndarray],
) -> Tuple[Parameters, Parameters]:
"""Computes the vector proposals for the next step."""
del momentum # not used in this, but could be used in subclasses
preconditioned_grads = self.estimator.multiply_matpower(grads, -1)
if self.norm_constraint is not None:
assert learning_rate is not None
sq_norm_grads = utils.inner_product(preconditioned_grads, grads)
sq_norm_scaled_grads = sq_norm_grads * learning_rate**2
# We need to sync the norms here, because reduction can be
# non-deterministic. They specifically are on GPUs by default for better
# performance. Hence although grads and preconditioned_grads are synced,
# the inner_product operation can still produce different answers on
# different devices.
sq_norm_scaled_grads = utils.pmean_if_pmap(sq_norm_scaled_grads,
self.pmap_axis_name)
max_coefficient = jnp.sqrt(self.norm_constraint / sq_norm_scaled_grads)
coefficient = jnp.minimum(max_coefficient, 1)
preconditioned_grads = utils.scalar_mul(preconditioned_grads, coefficient)
return preconditioned_grads, velocities
def velocities_and_delta(
self,
velocities: Parameters,
vectors: Sequence[Parameters],
coefficients: Sequence[jnp.ndarray],
) -> Sequence[Parameters]:
"""Computes the new velocities and delta (update to parameters)."""
del velocities
assert len(vectors) == len(coefficients)
delta = utils.scalar_mul(vectors[0], coefficients[0])
for vi, wi in zip(vectors[1:], coefficients[1:]):
delta = jax.tree_map(jnp.add, delta, utils.scalar_mul(vi, wi))
return delta, delta
|
deepmind-research-master
|
kfac_ferminet_alpha/optimizer.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.
"""Defines the high-level Fisher estimator class."""
import collections
from typing import Any, Callable, Mapping, Optional, Sequence, Union, TypeVar
import jax
import jax.numpy as jnp
import jax.random as jnr
import numpy as np
from kfac_ferminet_alpha import curvature_blocks
from kfac_ferminet_alpha import tracer
from kfac_ferminet_alpha import utils
_CurvatureBlock = curvature_blocks.CurvatureBlock
TagMapping = Mapping[str, curvature_blocks.CurvatureBlockCtor]
BlockVector = Sequence[jnp.ndarray]
_StructureT = TypeVar("_StructureT")
_OptionalStateT = TypeVar("_OptionalStateT", bound=Optional[Mapping[str, Any]])
@utils.Stateful.infer_class_state
class CurvatureEstimator(utils.Stateful):
"""Curvature estimator class supporting various curvature approximations."""
blocks: "collections.OrderedDict[str, _CurvatureBlock]"
damping: Optional[jnp.ndarray]
def __init__(self,
tagged_func: Callable[[Any], jnp.ndarray],
func_args: Sequence[Any],
l2_reg: Union[float, jnp.ndarray],
estimation_mode: str = "fisher_gradients",
params_index: int = 0,
layer_tag_to_block_cls: Optional[TagMapping] = None):
"""Create a FisherEstimator object.
Args:
tagged_func: The function which evaluates the model, in which layer and
loss tags has already been registered.
func_args: Arguments to trace the function for layer and loss tags.
l2_reg: Scalar. The L2 regularization coefficient, which represents
the following regularization function: `coefficient/2 ||theta||^2`.
estimation_mode: The type of curvature estimator to use. One of: *
'fisher_gradients' - the basic estimation approach from the original
K-FAC paper. (Default) * 'fisher_curvature_prop' - method which
estimates the Fisher using self-products of random 1/-1 vectors times
"half-factors" of the
Fisher, as described here: https://arxiv.org/abs/1206.6464 *
'fisher_exact' - is the obvious generalization of Curvature
Propagation to compute the exact Fisher (modulo any additional
diagonal or Kronecker approximations) by looping over one-hot
vectors for each coordinate of the output instead of using 1/-1
vectors. It is more expensive to compute than the other three
options by a factor equal to the output dimension, roughly
speaking. * 'fisher_empirical' - computes the 'empirical' Fisher
information matrix (which uses the data's distribution for the
targets, as opposed to the true Fisher which uses the model's
distribution) and requires that each registered loss have
specified targets. * 'ggn_curvature_prop' - Analogous to
fisher_curvature_prop, but estimates the Generalized
Gauss-Newton matrix (GGN). * 'ggn_exact'- Analogous to
fisher_exact, but estimates the Generalized Gauss-Newton matrix
(GGN).
params_index: The index of the arguments accepted by `func` which
correspond to parameters.
layer_tag_to_block_cls: An optional dict mapping tags to specific classes
of block approximations, which to override the default ones.
"""
if estimation_mode not in ("fisher_gradients", "fisher_empirical",
"fisher_exact", "fisher_curvature_prop",
"ggn_exact", "ggn_curvature_prop"):
raise ValueError(f"Unrecognised estimation_mode={estimation_mode}.")
super().__init__()
self.tagged_func = tagged_func
self.l2_reg = l2_reg
self.estimation_mode = estimation_mode
self.params_index = params_index
self.vjp = tracer.trace_estimator_vjp(self.tagged_func)
# Figure out the mapping from layer
self.layer_tag_to_block_cls = curvature_blocks.copy_default_tag_to_block()
if layer_tag_to_block_cls is None:
layer_tag_to_block_cls = dict()
layer_tag_to_block_cls = dict(**layer_tag_to_block_cls)
self.layer_tag_to_block_cls.update(layer_tag_to_block_cls)
# Create the blocks
self._in_tree = jax.tree_structure(func_args)
self._jaxpr = jax.make_jaxpr(self.tagged_func)(*func_args).jaxpr
self._layer_tags, self._loss_tags = tracer.extract_tags(self._jaxpr)
self.blocks = collections.OrderedDict()
counters = dict()
for eqn in self._layer_tags:
cls = self.layer_tag_to_block_cls[eqn.primitive.name]
c = counters.get(cls.__name__, 0)
self.blocks[cls.__name__ + "_" + str(c)] = cls(eqn)
counters[cls.__name__] = c + 1
@property
def diagonal_weight(self) -> jnp.ndarray:
return self.l2_reg + self.damping
def vectors_to_blocks(
self,
parameter_structured_vector: Any,
) -> Sequence[BlockVector]:
"""Splits the parameters to values for the corresponding blocks."""
in_vars = jax.tree_unflatten(self._in_tree, self._jaxpr.invars)
params_vars = in_vars[self.params_index]
params_vars_flat = jax.tree_flatten(params_vars)[0]
params_values_flat = jax.tree_flatten(parameter_structured_vector)[0]
assert len(params_vars_flat) == len(params_values_flat)
params_dict = dict(zip(params_vars_flat, params_values_flat))
per_block_vectors = []
for eqn in self._layer_tags:
if eqn.primitive.name == "generic_tag":
block_vars = eqn.invars
else:
block_vars = eqn.primitive.split_all_inputs(eqn.invars)[2] # pytype: disable=attribute-error # trace-all-classes
per_block_vectors.append(tuple(params_dict.pop(v) for v in block_vars))
if params_dict:
raise ValueError(f"From the parameters the following structure is not "
f"assigned to any block: {params_dict}. Most likely "
f"this part of the parameters is not part of the graph "
f"reaching the losses.")
return tuple(per_block_vectors)
def blocks_to_vectors(self, per_block_vectors: Sequence[BlockVector]) -> Any:
"""Reverses the function self.vectors_to_blocks."""
in_vars = jax.tree_unflatten(self._in_tree, self._jaxpr.invars)
params_vars = in_vars[self.params_index]
assigned_dict = dict()
for eqn, block_values in zip(self._layer_tags, per_block_vectors):
if eqn.primitive.name == "generic_tag":
block_params = eqn.invars
else:
block_params = eqn.primitive.split_all_inputs(eqn.invars)[2] # pytype: disable=attribute-error # trace-all-classes
assigned_dict.update(zip(block_params, block_values))
params_vars_flat, params_tree = jax.tree_flatten(params_vars)
params_values_flat = [assigned_dict[v] for v in params_vars_flat]
assert len(params_vars_flat) == len(params_values_flat)
return jax.tree_unflatten(params_tree, params_values_flat)
def init(
self,
rng: jnp.ndarray,
init_damping: Optional[jnp.ndarray],
) -> Mapping[str, Any]:
"""Returns an initialized variables for the curvature approximations and the inverses.."""
return dict(
blocks=collections.OrderedDict(
(name, block.init(block_rng)) #
for (name, block), block_rng #
in zip(self.blocks.items(), jnr.split(rng, len(self.blocks)))),
damping=init_damping)
@property
def mat_type(self) -> str:
return self.estimation_mode.split("_")[0]
def vec_block_apply(
self,
func: Callable[[_CurvatureBlock, BlockVector], BlockVector],
parameter_structured_vector: Any,
) -> Any:
"""Executes func for each approximation block on vectors."""
per_block_vectors = self.vectors_to_blocks(parameter_structured_vector)
assert len(per_block_vectors) == len(self.blocks)
results = jax.tree_map(func, tuple(self.blocks.values()),
per_block_vectors)
parameter_structured_result = self.blocks_to_vectors(results)
utils.check_structure_shapes_and_dtype(parameter_structured_vector,
parameter_structured_result)
return parameter_structured_result
def multiply_inverse(self, parameter_structured_vector: Any) -> Any:
"""Multiplies the vectors by the corresponding (damped) inverses of the blocks.
Args:
parameter_structured_vector: Structure equivalent to the parameters of the
model.
Returns:
A structured identical to `vectors` containing the product.
"""
return self.multiply_matpower(parameter_structured_vector, -1)
def multiply(self, parameter_structured_vector: Any) -> Any:
"""Multiplies the vectors by the corresponding (damped) blocks.
Args:
parameter_structured_vector: A vector in the same structure as the
parameters of the model.
Returns:
A structured identical to `vectors` containing the product.
"""
return self.multiply_matpower(parameter_structured_vector, 1)
def multiply_matpower(
self,
parameter_structured_vector: _StructureT,
exp: int,
) -> _StructureT:
"""Multiplies the vectors by the corresponding matrix powers of the blocks.
Args:
parameter_structured_vector: A vector in the same structure as the
parameters of the model.
exp: A float representing the power to raise the blocks by before
multiplying it by the vector.
Returns:
A structured identical to `vectors` containing the product.
"""
def func(block: _CurvatureBlock, vec: BlockVector) -> BlockVector:
return block.multiply_matpower(vec, exp, self.diagonal_weight)
return self.vec_block_apply(func, parameter_structured_vector)
def update_curvature_matrix_estimate(
self,
ema_old: Union[float, jnp.ndarray],
ema_new: Union[float, jnp.ndarray],
batch_size: int,
rng: jnp.ndarray,
func_args: Sequence[Any],
pmap_axis_name: str,
) -> None:
"""Updates the curvature estimate."""
# Compute the losses and the VJP function from the function inputs
losses, losses_vjp = self.vjp(func_args)
# Helper function that updates the blocks given a vjp vector
def _update_blocks(vjp_vec_, ema_old_, ema_new_):
blocks_info_ = losses_vjp(vjp_vec_)
for block_, block_info_ in zip(self.blocks.values(), blocks_info_):
block_.update_curvature_matrix_estimate(
info=block_info_,
batch_size=batch_size,
ema_old=ema_old_,
ema_new=ema_new_,
pmap_axis_name=pmap_axis_name)
if self.estimation_mode == "fisher_gradients":
keys = jnr.split(rng, len(losses)) if len(losses) > 1 else [rng]
vjp_vec = tuple(
loss.grad_of_evaluate_on_sample(key, coefficient_mode="sqrt")
for loss, key in zip(losses, keys))
_update_blocks(vjp_vec, ema_old, ema_new)
elif self.estimation_mode in ("fisher_curvature_prop",
"ggn_curvature_prop"):
keys = jnr.split(rng, len(losses)) if len(losses) > 1 else [rng]
vjp_vec = []
for loss, key in zip(losses, keys):
if self.estimation_mode == "fisher_curvature_prop":
random_b = jnr.bernoulli(key, shape=loss.fisher_factor_inner_shape())
vjp_vec.append(loss.multiply_fisher_factor(random_b * 2.0 - 1.0))
else:
random_b = jnr.bernoulli(key, shape=loss.ggn_factor_inner_shape())
vjp_vec.append(loss.multiply_ggn_factor(random_b * 2.0 - 1.0))
_update_blocks(tuple(vjp_vec), ema_old, ema_new)
elif self.estimation_mode in ("fisher_exact", "ggn_exact"):
# We use the following trick to simulate summation. The equation is:
# estimate = ema_old * estimate + ema_new * (sum_i estimate_index_i)
# weight = ema_old * weight + ema_new
# Instead we update the estimate n times with the following updates:
# for k = 1
# estimate_k = ema_old * estimate + (ema_new/n) * (n*estimate_index_k)
# weight_k = ema_old * weight + (ema_new/n)
# for k > 1:
# estimate_k = 1.0 * estimate_k-1 + (ema_new/n) * (n*estimate_index_k)
# weight_k = 1.0 * weight_k-1 + (ema_new/n)
# Which is mathematically equivalent to the original version.
zero_tangents = jax.tree_map(jnp.zeros_like,
list(loss.inputs for loss in losses))
if self.estimation_mode == "fisher_exact":
num_indices = [
(l, int(np.prod(l.fisher_factor_inner_shape[1:]))) for l in losses
]
else:
num_indices = [
(l, int(np.prod(l.ggn_factor_inner_shape()))) for l in losses
]
total_num_indices = sum(n for _, n in num_indices)
for i, (loss, loss_num_indices) in enumerate(num_indices):
for index in range(loss_num_indices):
vjp_vec = zero_tangents.copy()
if self.estimation_mode == "fisher_exact":
vjp_vec[i] = loss.multiply_fisher_factor_replicated_one_hot([index])
else:
vjp_vec[i] = loss.multiply_ggn_factor_replicated_one_hot([index])
if isinstance(vjp_vec[i], jnp.ndarray):
# In the special case of only one parameter, it still needs to be a
# tuple for the tangents.
vjp_vec[i] = (vjp_vec[i],)
vjp_vec[i] = jax.tree_map(lambda x: x * total_num_indices, vjp_vec[i])
_update_blocks(tuple(vjp_vec), ema_old, ema_new / total_num_indices)
ema_old = 1.0
elif self.estimation_mode == "fisher_empirical":
raise NotImplementedError()
else:
raise ValueError(f"Unrecognised estimation_mode={self.estimation_mode}")
def update_curvature_estimate_inverse(
self,
pmap_axis_name: str,
state: _OptionalStateT,
) -> _OptionalStateT:
if state is not None:
old_state = self.get_state()
self.set_state(state)
for block in self.blocks.values():
block.update_curvature_inverse_estimate(self.diagonal_weight,
pmap_axis_name)
if state is None:
return None
else:
state = self.pop_state()
self.set_state(old_state)
return state
|
deepmind-research-master
|
kfac_ferminet_alpha/estimator.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 of the different curvature blocks."""
import abc
from typing import Any, Callable, Dict, Mapping, MutableMapping, Optional, Sequence, Union
import jax
from jax import core
import jax.numpy as jnp
from kfac_ferminet_alpha import tag_graph_matcher as tgm
from kfac_ferminet_alpha import utils
_Arrays = Sequence[jnp.ndarray]
_BlockInfo = Mapping[str, Any]
class CurvatureBlock(utils.Stateful, abc.ABC):
"""Top level class."""
def __init__(self, layer_tag_eq: tgm.jax_core.JaxprEqn):
super(CurvatureBlock, self).__init__()
self._layer_tag_eq = layer_tag_eq
@property
def layer_tag_primitive(self) -> tgm.tags.LayerTag:
assert isinstance(self._layer_tag_eq.primitive, tgm.tags.LayerTag)
return self._layer_tag_eq.primitive
@property
def outputs_shapes(self) -> Sequence[Sequence[int]]:
output_vars = self.layer_tag_primitive.split_all_inputs(
self._layer_tag_eq.invars)[0]
return jax.tree_map(lambda x: x.aval.shape, output_vars)
@property
def inputs_shapes(self) -> Sequence[Sequence[int]]:
input_vars = self.layer_tag_primitive.split_all_inputs(
self._layer_tag_eq.invars)[1]
return jax.tree_map(lambda x: x.aval.shape, input_vars)
@property
def params_shapes(self) -> Sequence[Sequence[int]]:
params_vars = self.layer_tag_primitive.split_all_inputs(
self._layer_tag_eq.invars)[2]
return jax.tree_map(lambda x: x.aval.shape, params_vars)
@abc.abstractmethod
def init(self, rng: jnp.ndarray) -> MutableMapping[str, Any]:
"""This initializes/creates all of the arrays for the state of the block.
Usually this would include the arrays used for storing the curvature
approximation, as well as the arrays for storing any approximate
inverses/powers of the curvature block.
Args:
rng: The Jax PRNG key to use if any of the state is supposed to be
initialized randomly.
Returns:
A mutable mapping of the state.
"""
@abc.abstractmethod
def update_curvature_matrix_estimate(
self,
info: _BlockInfo,
batch_size: int,
ema_old: Union[float, jnp.ndarray],
ema_new: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
pass
@abc.abstractmethod
def update_curvature_inverse_estimate(
self,
diagonal_weight: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
pass
@abc.abstractmethod
def multiply_matpower(
self,
vec: _Arrays,
exp: Union[float, int],
diagonal_weight: Union[float, jnp.ndarray]
) -> _Arrays:
pass
CurvatureBlockCtor = Callable[[core.JaxprEqn], CurvatureBlock]
@utils.Stateful.infer_class_state
class NaiveDiagonal(CurvatureBlock):
"""The naively estimated diagonal block."""
diagonal_factor: utils.WeightedMovingAverage
def init(self, rng: jnp.ndarray) -> Dict[str, Any]:
del rng
return dict(
diagonal_factor=utils.WeightedMovingAverage.zero(
self.outputs_shapes[0])
)
def update_curvature_matrix_estimate(
self,
info: _BlockInfo,
batch_size: int,
ema_old: Union[float, jnp.ndarray],
ema_new: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
dw, = info["outputs_tangent"]
diagonal_update = dw * dw / batch_size
self.diagonal_factor.update(diagonal_update, ema_old, ema_new)
self.diagonal_factor.sync(pmap_axis_name)
def update_curvature_inverse_estimate(
self,
diagonal_weight: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
pass
def multiply_matpower(
self,
vec: _Arrays,
exp: Union[float, int],
diagonal_weight: Union[float, jnp.ndarray]
) -> _Arrays:
w, = vec
if exp == 1:
return w * (self.diagonal_factor.value + diagonal_weight),
elif exp == -1:
return w / (self.diagonal_factor.value + diagonal_weight),
else:
raise NotImplementedError()
@utils.Stateful.infer_class_state
class TwoKroneckerFactored(CurvatureBlock, abc.ABC):
"""A factor that is the Kronecker product of two matrices."""
inputs_factor: utils.WeightedMovingAverage
inputs_factor_inverse: jnp.ndarray
outputs_factor: utils.WeightedMovingAverage
outputs_factor_inverse: jnp.ndarray
extra_scale: Optional[Union[int, float, jnp.ndarray]]
@property
def has_bias(self) -> bool:
return len(self._layer_tag_eq.invars) == 4
@abc.abstractmethod
def input_size(self) -> int:
pass
@abc.abstractmethod
def output_size(self) -> int:
pass
def compute_extra_scale(self) -> Optional[Union[int, float, jnp.ndarray]]:
return 1
def init(self, rng: jnp.ndarray) -> Dict[str, Any]:
# The extra scale is technically a constant, but in general it could be
# useful for anyone examining the state to know it explicitly,
# hence we actually keep it as part of the state.
d_in = self.input_size()
d_out = self.output_size()
return dict(
inputs_factor=utils.WeightedMovingAverage.zero([d_in, d_in]),
inputs_factor_inverse=jnp.zeros([d_in, d_in]),
outputs_factor=utils.WeightedMovingAverage.zero([d_out, d_out]),
outputs_factor_inverse=jnp.zeros([d_out, d_out]),
extra_scale=self.compute_extra_scale()
)
def update_curvature_inverse_estimate(
self,
diagonal_weight: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
self.inputs_factor.sync(pmap_axis_name)
self.outputs_factor.sync(pmap_axis_name)
# This computes the approximate inverse factor using the pi-adjusted
# inversion from the original KFAC paper.
# Note that the damping is divided by extra_scale since:
# (s * A kron B + lambda I)^-1 = s^-1 (A kron B + s^-1 * lambda I)^-1
# And the extra division by the scale is included in `multiply_matpower`.
(self.inputs_factor_inverse,
self.outputs_factor_inverse) = utils.pi_adjusted_inverse(
factor_0=self.inputs_factor.value,
factor_1=self.outputs_factor.value,
damping=diagonal_weight / self.extra_scale,
pmap_axis_name=pmap_axis_name)
def multiply_matpower(
self,
vec: _Arrays,
exp: Union[float, int],
diagonal_weight: Union[float, jnp.ndarray]
) -> _Arrays:
if self.has_bias:
w, b = vec
vec = jnp.concatenate([w.reshape([-1, w.shape[-1]]), b[None]], axis=0)
else:
w, = vec
vec = w.reshape([-1, w.shape[-1]])
if exp == 1:
inputs_factor, outputs_factor = (self.inputs_factor.value,
self.outputs_factor.value)
scale = self.extra_scale
elif exp == -1:
inputs_factor, outputs_factor = (self.inputs_factor_inverse,
self.outputs_factor_inverse)
scale = 1.0 / self.extra_scale
diagonal_weight = 0
else:
raise NotImplementedError()
result = jnp.matmul(inputs_factor, vec)
result = jnp.matmul(result, outputs_factor)
result = result * scale + diagonal_weight * vec
if self.has_bias:
w_new, b_new = result[:-1], result[-1]
return w_new.reshape(w.shape), b_new
else:
return result.reshape(w.shape),
class DenseTwoKroneckerFactored(TwoKroneckerFactored):
"""Factor for a standard dense layer."""
def input_size(self) -> int:
if self.has_bias:
return self.params_shapes[0][0] + 1
else:
return self.params_shapes[0][0]
def output_size(self) -> int:
return self.params_shapes[0][1]
def update_curvature_matrix_estimate(
self,
info: _BlockInfo,
batch_size: int,
ema_old: Union[float, jnp.ndarray],
ema_new: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
del pmap_axis_name
(x,), (dy,) = info["inputs"], info["outputs_tangent"]
utils.check_first_dim_is_batch_size(batch_size, x, dy)
if self.has_bias:
x_one = jnp.ones_like(x[:, :1])
x = jnp.concatenate([x, x_one], axis=1)
input_stats = jnp.matmul(x.T, x) / batch_size
output_stats = jnp.matmul(dy.T, dy) / batch_size
self.inputs_factor.update(input_stats, ema_old, ema_new)
self.outputs_factor.update(output_stats, ema_old, ema_new)
@utils.Stateful.infer_class_state
class ScaleAndShiftDiagonal(CurvatureBlock):
"""A scale and shift block with a diagonal approximation to the curvature."""
scale_factor: Optional[utils.WeightedMovingAverage]
shift_factor: Optional[utils.WeightedMovingAverage]
@property
def has_scale(self) -> bool:
return self._layer_tag_eq.params["has_scale"]
@property
def has_shift(self) -> bool:
return self._layer_tag_eq.params["has_shift"]
def init(self, rng: jnp.ndarray) -> Dict[str, Any]:
del rng
if self.has_scale and self.has_shift:
return dict(
scale_factor=utils.WeightedMovingAverage.zero(
self.params_shapes[0]
),
shift_factor=utils.WeightedMovingAverage.zero(
self.params_shapes[1]
)
)
elif self.has_scale:
return dict(
scale_factor=utils.WeightedMovingAverage.zero(
self.params_shapes[0]
),
shift_factor=None
)
elif self.has_shift:
return dict(
scale_factor=None,
shift_factor=utils.WeightedMovingAverage.zero(
self.params_shapes[0]
),
)
else:
raise ValueError("Neither `has_scale` nor `has_shift`.")
def update_curvature_matrix_estimate(
self,
info: _BlockInfo,
batch_size: int,
ema_old: Union[float, jnp.ndarray],
ema_new: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
(x,), (dy,) = info["inputs"], info["outputs_tangent"]
utils.check_first_dim_is_batch_size(batch_size, x, dy)
if self.has_scale:
assert self.scale_factor is not None
scale_shape = info["params"][0].shape
full_scale_shape = (1,) * (len(x.shape) - len(scale_shape)) + scale_shape
axis = [i for i, s in enumerate(full_scale_shape) if s == 1 and i != 0]
d_scale = jnp.sum(x * dy, axis=axis)
scale_diag_update = jnp.sum(d_scale * d_scale, axis=0) / batch_size
self.scale_factor.update(scale_diag_update, ema_old, ema_new) # pytype: disable=attribute-error # trace-all-classes
self.scale_factor.sync(pmap_axis_name) # pytype: disable=attribute-error # trace-all-classes
if self.has_shift:
assert self.shift_factor is not None
shift_shape = info["params"][1].shape
full_shift_shape = (1,) * (len(x.shape) - len(shift_shape)) + shift_shape
axis = [i for i, s in enumerate(full_shift_shape) if s == 1 and i != 0]
d_shift = jnp.sum(dy, axis=axis)
shift_diag_update = jnp.sum(d_shift * d_shift, axis=0) / batch_size
self.shift_factor.update(shift_diag_update, ema_old, ema_new) # pytype: disable=attribute-error # trace-all-classes
self.shift_factor.sync(pmap_axis_name) # pytype: disable=attribute-error # trace-all-classes
def update_curvature_inverse_estimate(
self,
diagonal_weight: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
pass
def multiply_matpower(
self,
vec: _Arrays,
exp: Union[float, int],
diagonal_weight: Union[float, jnp.ndarray]
) -> _Arrays:
if self.has_scale and self.has_shift:
factors = (self.scale_factor.value, self.shift_factor.value) # pytype: disable=attribute-error # trace-all-classes
elif self.has_scale:
factors = (self.scale_factor.value,) # pytype: disable=attribute-error # trace-all-classes
elif self.has_shift:
factors = (self.shift_factor.value,) # pytype: disable=attribute-error # trace-all-classes
else:
raise ValueError("Neither `has_scale` nor `has_shift`.")
factors = jax.tree_map(lambda x: x + diagonal_weight, factors)
if exp == 1:
return jax.tree_map(jnp.multiply, vec, factors)
elif exp == -1:
return jax.tree_map(jnp.divide, vec, factors)
else:
raise NotImplementedError()
@utils.Stateful.infer_class_state
class ScaleAndShiftFull(CurvatureBlock):
"""A scale and shift block with full approximation to the curvature."""
factor: utils.WeightedMovingAverage
inverse_factor: jnp.ndarray
@property
def _has_scale(self) -> bool:
return self._layer_tag_eq.params["has_scale"]
@property
def _has_shift(self) -> bool:
return self._layer_tag_eq.params["has_shift"]
def init(self, rng: jnp.ndarray) -> Dict[str, Any]:
del rng
dims = sum(utils.product(shape) for shape in self.params_shapes)
return dict(
factor=utils.WeightedMovingAverage.zero([dims, dims]),
inverse_factor=jnp.zeros([dims, dims])
)
def update_curvature_matrix_estimate(
self,
info: _BlockInfo,
batch_size: int,
ema_old: Union[float, jnp.ndarray],
ema_new: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
del pmap_axis_name
(x,), (dy,) = info["inputs"], info["outputs_tangent"]
utils.check_first_dim_is_batch_size(batch_size, x, dy)
grads = list()
if self._has_scale:
# Scale gradients
scale_shape = info["params"][0].shape
full_scale_shape = (1,) * (len(x.shape) - len(scale_shape)) + scale_shape
axis = [i for i, s in enumerate(full_scale_shape) if s == 1 and i != 0]
d_scale = jnp.sum(x * dy, axis=axis)
d_scale = d_scale.reshape([batch_size, -1])
grads.append(d_scale)
if self._has_shift:
# Shift gradients
shift_shape = info["params"][1].shape
full_shift_shape = (1,) * (len(x.shape) - len(shift_shape)) + shift_shape
axis = [i for i, s in enumerate(full_shift_shape) if s == 1 and i != 0]
d_shift = jnp.sum(dy, axis=axis)
d_shift = d_shift.reshape([batch_size, -1])
grads.append(d_shift)
grads = jnp.concatenate(grads, axis=1)
factor_update = jnp.matmul(grads.T, grads) / batch_size
self.factor.update(factor_update, ema_old, ema_new)
def update_curvature_inverse_estimate(
self,
diagonal_weight: Union[float, jnp.ndarray],
pmap_axis_name: str
) -> None:
self.factor.sync(pmap_axis_name)
self.inverse_factor = utils.psd_inv_cholesky(self.factor.value,
diagonal_weight)
def multiply_matpower(
self,
vec: _Arrays,
exp: Union[float, int],
diagonal_weight: Union[float, jnp.ndarray]
) -> _Arrays:
# Remember the vector is a tuple of all parameters
if self._has_scale and self._has_shift:
flat_vec = jnp.concatenate([v.flatten() for v in vec])
else:
flat_vec = vec[0].flatten()
if exp == 1:
flat_result = (
jnp.matmul(self.factor.value, flat_vec) + diagonal_weight * flat_vec)
elif exp == -1:
flat_result = jnp.matmul(self.inverse_factor, flat_vec)
else:
raise NotImplementedError()
if self._has_scale and self._has_shift:
scale_dims = int(vec[0].size)
scale_result = flat_result[:scale_dims].reshape(vec[0].shape)
shift_result = flat_result[scale_dims:].reshape(vec[1].shape)
return scale_result, shift_result
else:
return flat_vec.reshape(vec[0].shape),
_default_tag_to_block: MutableMapping[str, CurvatureBlockCtor] = dict(
dense_tag=DenseTwoKroneckerFactored,
generic_tag=NaiveDiagonal,
scale_and_shift_tag=ScaleAndShiftDiagonal,
)
def copy_default_tag_to_block() -> MutableMapping[str, CurvatureBlockCtor]:
return dict(_default_tag_to_block)
def get_default_tag_to_block(tag_name: str) -> CurvatureBlockCtor:
return _default_tag_to_block[tag_name]
def set_default_tag_to_block(
tag_name: str,
block_class: CurvatureBlockCtor,
) -> None:
_default_tag_to_block[tag_name] = block_class
|
deepmind-research-master
|
kfac_ferminet_alpha/curvature_blocks.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 the Jax tracer functionality for tags."""
import functools
from typing import Any, Callable, Sequence, Tuple
import jax
from jax import core
from jax import util as jax_util
import jax.numpy as jnp
from kfac_ferminet_alpha import layers_and_loss_tags as tags
from kfac_ferminet_alpha import tag_graph_matcher as tgm
from kfac_ferminet_alpha import utils
_Function = Callable[[Any], Any]
_Loss = tags.LossTag
def extract_tags(
jaxpr: core.Jaxpr
) -> Tuple[Sequence[core.JaxprEqn], Sequence[core.JaxprEqn]]:
"""Extracts all of the tag equations."""
# Loop through equations and evaluate primitives using `bind`
layer_tags = []
loss_tags = []
for eqn in jaxpr.eqns:
if isinstance(eqn.primitive, tags.LossTag):
loss_tags.append(eqn)
elif isinstance(eqn.primitive, tags.LayerTag):
layer_tags.append(eqn)
return tuple(layer_tags), tuple(loss_tags)
def construct_compute_losses_inputs(
jaxpr: core.Jaxpr,
consts: Tuple[Any],
num_losses: int,
primals: Any,
params_index: int) -> Callable[[Any], Sequence[Sequence[jnp.ndarray]]]:
"""Constructs a function that computes all of the inputs to all losses."""
primals_ = list(primals)
def forward_compute_losses(
params_primals: Any,
) -> Sequence[Sequence[jnp.ndarray]]:
primals_[params_index] = params_primals
flat_args = jax.tree_flatten(primals_)[0]
# Mapping from variable -> value
env = dict()
read = functools.partial(tgm.read_env, env)
write = functools.partial(tgm.write_env, env)
# Bind args and consts to environment
jax_util.safe_map(write, jaxpr.invars, flat_args)
jax_util.safe_map(write, jaxpr.constvars, consts)
# Loop through equations and evaluate primitives using `bind`
losses_so_far = 0
loss_tags = []
for eqn in jaxpr.eqns:
tgm.evaluate_eqn(eqn, jax_util.safe_map(read, eqn.invars), write)
if isinstance(eqn.primitive, tags.LossTag):
loss_tags.append(eqn)
losses_so_far += 1
if num_losses is not None and losses_so_far == num_losses:
break
return tuple(tuple(read(v) for v in tag.invars) for tag in loss_tags)
# return tuple(jax_util.safe_map(read, tag.invars) for tag in loss_tags)
return forward_compute_losses
# We know when `.primitive` will be either a `LossTag` or a `LayerTag`, however
# pytype cannot infer its subclass, so we need to unbox it.
def _unbox_loss_tag(jaxpr_eqn: core.JaxprEqn) -> tags.LossTag:
assert isinstance(jaxpr_eqn.primitive, tags.LossTag)
return jaxpr_eqn.primitive
def _unbox_layer_tag(jaxpr_eqn: core.JaxprEqn) -> tags.LayerTag:
assert isinstance(jaxpr_eqn.primitive, tags.LayerTag)
return jaxpr_eqn.primitive
def trace_losses_matrix_vector_vjp(tagged_func: _Function,
params_index: int = 0):
"""Returns the Jacobian-transposed vector product (backward mode) function in equivalent form to jax.vjp."""
def vjp(*primals):
typed_jaxpr = jax.make_jaxpr(tagged_func)(*primals)
jaxpr, consts = typed_jaxpr.jaxpr, typed_jaxpr.literals
_, loss_jaxpr_eqns = extract_tags(jaxpr)
n = len(loss_jaxpr_eqns)
losses_func = construct_compute_losses_inputs(
jaxpr, consts, n, primals, params_index)
losses_inputs, full_vjp_func = jax.vjp(losses_func, primals[params_index])
losses = []
for jaxpr_eqn, inputs in zip(loss_jaxpr_eqns, losses_inputs):
loss_tag = _unbox_loss_tag(jaxpr_eqn)
losses.append(loss_tag.loss(*inputs, weight=jaxpr_eqn.params["weight"]))
losses = tuple(losses)
def vjp_func(tangents):
flat_tangents = jax.tree_flatten(tangents)[0]
loss_invars = []
loss_targets = []
for jaxpr_eqn, inputs in zip(loss_jaxpr_eqns, losses_inputs):
num_inputs = _unbox_loss_tag(jaxpr_eqn).num_inputs
loss_invars.append(tuple(jaxpr_eqn.invars[:num_inputs]))
loss_targets.append(inputs[num_inputs:])
treedef = jax.tree_structure(loss_invars)
tangents = jax.tree_unflatten(treedef, flat_tangents)
# Since the losses could also take and targets as inputs and we don't want
# this function to computes vjp w.r.t to those (e.g. the user should not
# be providing tangent vectors for the targets, only for inputs) we have
# to manually fill in these "extra" tangents with zeros.
targets_tangents = jax.tree_map(jnp.zeros_like, loss_targets)
tangents = tuple(ti + tti for ti, tti in zip(tangents, targets_tangents))
input_tangents = full_vjp_func(tangents)[0]
return input_tangents,
return losses, vjp_func
return vjp
def trace_losses_matrix_vector_jvp(
tagged_func: _Function,
params_index: int = 0):
"""Returns the Jacobian vector product (forward mode) function in equivalent form to jax.jvp."""
def jvp(primals, params_tangents):
typed_jaxpr = jax.make_jaxpr(tagged_func)(*primals)
jaxpr, consts = typed_jaxpr.jaxpr, typed_jaxpr.literals
_, loss_tags = extract_tags(jaxpr)
n = len(loss_tags)
losses_func = construct_compute_losses_inputs(jaxpr, consts, n,
primals, params_index)
primals = (primals[params_index],)
tangents = (params_tangents,)
(primals_out, tangents_out) = jax.jvp(losses_func, primals, tangents)
tangents_out = tuple(tuple(t[:tag.primitive.num_inputs])
for t, tag in zip(tangents_out, loss_tags))
losses = tuple(tag.primitive.loss(*inputs, weight=tag.params["weight"])
for tag, inputs in zip(loss_tags, primals_out))
return losses, tangents_out
return jvp
def trace_losses_matrix_vector_hvp(tagged_func, params_index=0):
"""Returns the Hessian vector product function of **the tagged losses**, rather than the output value of `tagged_func`."""
# The function uses backward-over-forward mode.
def hvp(primals, params_tangents):
typed_jaxpr = jax.make_jaxpr(tagged_func)(*primals)
jaxpr, consts = typed_jaxpr.jaxpr, typed_jaxpr.literals
_, loss_tags = extract_tags(jaxpr)
n = len(loss_tags)
losses_func = construct_compute_losses_inputs(
jaxpr, consts, n, primals, params_index)
def losses_sum(param_primals):
loss_inputs = losses_func(param_primals)
losses = [
_unbox_loss_tag(jaxpr_eqn).loss(
*inputs, weight=jaxpr_eqn.params["weight"])
for jaxpr_eqn, inputs in zip(loss_tags, loss_inputs)
]
# This computes the sum of losses evaluated. Makes it easier as we can
# now use jax.grad rather than jax.vjp for taking derivatives.
return sum(jnp.sum(loss.evaluate(None)) for loss in losses)
def grads_times_tangents(params_primals):
grads = jax.grad(losses_sum)(params_primals)
return utils.inner_product(grads, params_tangents)
return jax.grad(grads_times_tangents)(primals[params_index])
return hvp
def trace_estimator_vjp(tagged_func: _Function) -> _Function:
"""Creates the function needed for an estimator of curvature matrices.
Args:
tagged_func: An function that has been annotated with tags both for layers
and losses.
Returns:
A function with the same signatures as `tagged_func`, which when provided
with inputs returns two things:
1. The instances of all losses objected that are tagged.
2. A second function, which when provide with tangent vectors for each
of the loss instances' parameters, returns for every tagged layer a
dictionary containing the following elements:
inputs - The primal values of the inputs to the layer.
outputs - The primal values of the outputs to the layer.
params - The primal values of the layer.
inputs_tangent - The tangent value of layer, given the provided
tangents of the losses.
inputs_tangent - The tangent value of layer, given the provided
tangents of the losses.
inputs_tangent - The tangent value of layer, given the provided
tangents of the losses.
"""
def full_vjp_func(func_args):
# Trace the tagged function
typed_jaxpr = jax.make_jaxpr(tagged_func)(*func_args)
jaxpr, consts = typed_jaxpr.jaxpr, typed_jaxpr.literals
layer_tags, loss_tags = extract_tags(jaxpr)
layer_vars_flat = jax.tree_flatten([tag.invars for tag in layer_tags])[0]
layer_input_vars = tuple(set(layer_vars_flat))
def forward():
own_func_args = func_args
# Mapping from variable -> value
env = dict()
read = functools.partial(tgm.read_env, env)
write = functools.partial(tgm.write_env, env)
# Bind args and consts to environment
jax_util.safe_map(write, jaxpr.invars, jax.tree_flatten(own_func_args)[0])
jax_util.safe_map(write, jaxpr.constvars, consts)
# Loop through equations and evaluate primitives using `bind`
num_losses_passed = 0
for eqn in jaxpr.eqns:
tgm.evaluate_eqn(eqn, jax_util.safe_map(read, eqn.invars), write)
if isinstance(eqn.primitive, tags.LossTag):
num_losses_passed += 1
if num_losses_passed == len(loss_tags):
break
if num_losses_passed != len(loss_tags):
raise ValueError("This should be unreachable.")
return jax_util.safe_map(read, layer_input_vars)
def forward_aux(aux):
own_func_args = func_args
# Mapping from variable -> value
env = dict()
read = functools.partial(tgm.read_env, env)
def write(var, val):
if not isinstance(var, jax.core.Literal):
val = val + aux[var] if var in aux else val
env[var] = val
# Bind args and consts to environment
jax_util.safe_map(write, jaxpr.invars, jax.tree_flatten(own_func_args)[0])
jax_util.safe_map(write, jaxpr.constvars, consts)
# Loop through equations and evaluate primitives using `bind`
num_losses_passed = 0
losses_inputs_values = []
losses_kwargs_values = []
for eqn in jaxpr.eqns:
input_values = jax_util.safe_map(read, eqn.invars)
tgm.evaluate_eqn(eqn, input_values, write)
if isinstance(eqn.primitive, tags.LossTag):
loss = eqn.primitive.loss(*input_values, weight=eqn.params["weight"])
losses_inputs_values.append(loss.inputs)
losses_kwargs_values.append(dict(
targets=loss.targets,
weight=eqn.params["weight"]
))
num_losses_passed += 1
if num_losses_passed == len(loss_tags):
break
if num_losses_passed != len(loss_tags):
raise ValueError("This should be unreachable.")
# Read the inputs to the loss functions, but also return the target values
return tuple(losses_inputs_values), tuple(losses_kwargs_values)
layer_input_values = forward()
primals_dict = dict(zip(layer_input_vars, layer_input_values))
primals_dict.update(zip(jaxpr.invars, jax.tree_flatten(func_args)[0]))
aux_values = jax.tree_map(jnp.zeros_like, layer_input_values)
aux_dict = dict(zip(layer_input_vars, aux_values))
losses_args, aux_vjp, losses_kwargs = jax.vjp(forward_aux, aux_dict,
has_aux=True)
losses = tuple(tag.primitive.loss(*inputs, **kwargs)
for tag, inputs, kwargs in
zip(loss_tags, losses_args, losses_kwargs))
def vjp_func(tangents):
all_tangents = aux_vjp(tangents)
tangents_dict, inputs_tangents = all_tangents[0], all_tangents[1:]
inputs_tangents = jax.tree_flatten(inputs_tangents)[0]
tangents_dict.update(zip(jaxpr.invars, inputs_tangents))
read_primals = functools.partial(tgm.read_env, primals_dict)
read_tangents = functools.partial(tgm.read_env, tangents_dict)
layers_info = []
for jaxpr_eqn in layer_tags:
layer_tag = _unbox_layer_tag(jaxpr_eqn)
info = dict()
primals = jax_util.safe_map(read_primals, tuple(jaxpr_eqn.invars))
(
info["outputs"],
info["inputs"],
info["params"],
) = layer_tag.split_all_inputs(primals)
tangents = jax_util.safe_map(read_tangents, tuple(jaxpr_eqn.invars))
(
info["outputs_tangent"],
info["inputs_tangent"],
info["params_tangent"],
) = layer_tag.split_all_inputs(tangents)
layers_info.append(info)
return tuple(layers_info)
return losses, vjp_func
return full_vjp_func
|
deepmind-research-master
|
kfac_ferminet_alpha/tracer.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 tagging and graph manipulation."""
import collections
import functools
import itertools
from typing import Any, NamedTuple, Sequence
from absl import logging
import jax
from jax import core as jax_core
from jax import lax
from jax import util as jax_util
from jax.interpreters import partial_eval as pe
import jax.numpy as jnp
import networkx as nx
from networkx.algorithms import isomorphism
import numpy as np
import ordered_set
from kfac_ferminet_alpha import layers_and_loss_tags as tags
USE_NETWORKX = False
def match_nodes(g1, g2, mapping, node1, node2):
"""Matching nodes when doing graph search."""
if not kfac_node_match(g1.nodes[node1], g2.nodes[node2]):
return False
# Check predecessors
p1 = set(n for n in g1.predecessors(node1) if n in mapping.keys())
p2 = set(n for n in g2.predecessors(node2) if n in mapping.values())
if len(p1) != len(p2):
return False
for p1_i in p1:
if mapping[p1_i] not in p2:
return False
# Check successors
s1 = set(n for n in g1.successors(node1) if n in mapping.keys())
s2 = set(n for n in g2.successors(node2) if n in mapping.values())
if len(s1) != len(s2):
return False
for s1_i in s1:
if mapping[s1_i] not in s2:
return False
return True
def generate_candidates(g1, g2, mapping, node1, node2):
"""Generates the initial candidates for graph search."""
# Check predecessors
p1 = set(n for n in g1.predecessors(node1) if n not in mapping.keys())
p2 = set(n for n in g2.predecessors(node2) if n not in mapping.values())
candidates = ordered_set.OrderedSet(itertools.product(p1, p2))
s1 = set(n for n in g1.successors(node1) if n not in mapping.keys())
s2 = set(n for n in g2.successors(node2) if n not in mapping.values())
candidates.update(list(itertools.product(s1, s2)))
return candidates
def find_mappings(pattern, graph, mapping, terminals):
"""Finds all mappings from graph search of the pattern."""
if len(mapping) == len(pattern):
for k, v in terminals.items():
v.add(mapping[k])
return [frozenset(mapping.items())]
mappings = set()
nodes_list = list(mapping.keys())
for node1 in reversed(nodes_list):
for s1 in pattern.successors(node1):
if s1 not in mapping.keys():
for s2 in graph.successors(mapping[node1]):
if s2 not in mapping.values():
if s1 not in terminals or s2 not in terminals[s1]:
if match_nodes(pattern, graph, mapping, s1, s2):
mapping[s1] = s2
mappings.update(
find_mappings(pattern, graph, mapping, terminals))
mapping.pop(s1)
for p1 in pattern.predecessors(node1):
if p1 not in mapping.keys():
for p2 in graph.predecessors(mapping[node1]):
if p2 not in mapping.values():
if p1 not in terminals or p2 not in terminals[p1]:
if match_nodes(pattern, graph, mapping, p1, p2):
mapping[p1] = p2
mappings.update(
find_mappings(pattern, graph, mapping, terminals))
mapping.pop(p1)
return mappings
def match_pattern(pattern, graph):
"""Given a pattern returns all matches inside the graph."""
if USE_NETWORKX:
matcher = isomorphism.GraphMatcher(
graph, pattern, node_match=kfac_node_match)
mappings = list(
dict((k, v)
for v, k in mapping.items())
for mapping in matcher.subgraph_isomorphisms_iter())
else:
mapping = collections.OrderedDict()
params1 = [n for n in pattern.nodes if pattern.nodes[n]["op"] == "param"]
params2 = [n for n in graph.nodes if graph.nodes[n]["op"] == "param"]
terminals = {
n: set() for n in pattern.nodes if not list(pattern.successors(n))
}
mappings = set()
for node1, node2 in itertools.product(params1, params2):
mapping[node1] = node2
mappings.update(find_mappings(pattern, graph, mapping, terminals))
mapping.pop(node1)
for v in terminals.values():
v.clear()
mappings = list(dict(mapping) for mapping in mappings)
var_mappings = []
for mapping in mappings:
var_mappings.append(dict())
for k, v in mapping.items():
cond = pattern.nodes[k]["op"] in ("param", "array")
source = pattern.nodes[k]["var"] if cond else k
target = graph.nodes[v]["var"] if cond else graph.nodes[v]["eqn"]
var_mappings[-1][source] = target
return var_mappings
def read_env(env, var):
# Literals are values baked into the Jaxpr
if isinstance(var, jax.core.Literal):
return var.val
return env[var]
def write_env(env, var, val):
env[var] = val
def abstract_single_value(value):
if isinstance(value, jnp.ndarray):
value = jax_core.ShapedArray(np.shape(value), np.result_type(value))
return pe.PartialVal.unknown(value)
else:
return value
def abstract_args(args):
return jax.tree_map(abstract_single_value, args)
def _extract_call_jaxpr(primitive, params):
if not (primitive.call_primitive or primitive.map_primitive):
return None, params
else:
params = dict(params)
return params.pop("call_jaxpr"), params
def evaluate_eqn(eqn, in_values, write_func):
"""Evaluate a single Jax equation and writes the outputs."""
in_values = list(in_values)
# This is logic specifically to handle `xla_call`
call_jaxpr, params = _extract_call_jaxpr(eqn.primitive, eqn.params)
if call_jaxpr:
subfuns = [
jax.core.lu.wrap_init(
functools.partial(jax.core.eval_jaxpr, call_jaxpr, ()))
]
else:
subfuns = []
ans = eqn.primitive.bind(*(subfuns + in_values), **params)
if eqn.primitive.multiple_results:
jax_util.safe_map(write_func, eqn.outvars, ans)
else:
write_func(eqn.outvars[0], ans)
return ans
def clean_jaxpr_eqns(jaxpr, preserve_tags=True):
"""Performs dead code elimination on the jaxpr, preserving loss and layer tags."""
eqns = []
dependants = set(jaxpr.outvars)
for eqn in reversed(jaxpr.eqns):
check = False
for v in eqn.outvars:
if v in dependants:
dependants.remove(v)
check = True
if isinstance(eqn.primitive, (tags.LossTag, tags.LayerTag)):
check = check or preserve_tags
if check:
eqns.append(eqn)
new_dependants = set(
v for v in eqn.invars if not isinstance(v, jax_core.Literal))
dependants = dependants.union(new_dependants)
# Dependants should only be invars
dependants = dependants - set(jaxpr.invars + jaxpr.constvars)
if dependants:
raise ValueError("Something went wrong with the dead code elimination.")
return reversed(eqns)
def broadcast_merger(f):
"""Transforms `f` into a function where all consecutive broadcasts are merged."""
def merged_func(*func_args):
typed_jaxpr, out_avals = jax.make_jaxpr(f, return_shape=True)(*func_args)
out_tree = jax.tree_structure(out_avals)
jaxpr, consts = typed_jaxpr.jaxpr, typed_jaxpr.literals
# Mapping from variable -> value
env = dict()
read = functools.partial(read_env, env)
write = functools.partial(write_env, env)
# Bind args and consts to environment
flat_args = jax.tree_flatten(func_args)[0]
jax_util.safe_map(write, jaxpr.invars, flat_args)
jax_util.safe_map(write, jaxpr.constvars, consts)
# Bind args and consts to environment
jax_util.safe_map(write, jaxpr.invars, flat_args)
jax_util.safe_map(write, jaxpr.constvars, consts)
# Loop through equations and evaluate primitives using `bind`
broadcasts_outputs = dict()
for eqn in clean_jaxpr_eqns(jaxpr):
# We ignore broadcasting of constants
if (eqn.primitive.name == "broadcast_in_dim" and
not all(isinstance(v, jax_core.Literal) for v in eqn.invars)):
if eqn.invars[0] in broadcasts_outputs:
x, dims = broadcasts_outputs[eqn.invars[0]]
kept_dims = eqn.params["broadcast_dimensions"]
kept_dims = [kept_dims[d] for d in dims]
y = lax.broadcast_in_dim(x, eqn.params["shape"], kept_dims)
jax_util.safe_map(write, eqn.outvars, [y])
broadcasts_outputs[eqn.outvars[0]] = (x, kept_dims)
else:
inputs = jax_util.safe_map(read, eqn.invars)
evaluate_eqn(eqn, inputs, write)
broadcasts_outputs[eqn.outvars[0]] = (
inputs[0], eqn.params["broadcast_dimensions"])
else:
evaluate_eqn(eqn, jax_util.safe_map(read, eqn.invars), write)
return jax.tree_unflatten(out_tree, jax_util.safe_map(read, jaxpr.outvars))
return merged_func
class JaxGraph(NamedTuple):
jaxpr: Any
consts: Any
params: Any
params_tree: Any
in_tree: Any
out_tree: Any
digraph: nx.DiGraph
tagging_func: Any
SPECIAL_OP_COMPARE_RULES = dict()
def default_compare(node1, node2):
if node1["op"] != node2["op"]:
return False
params1, params2 = node1["eqn"].params, node2["eqn"].params
if set(params1.keys()) != set(params2.keys()):
return False
for k in params1.keys():
if params1[k] != params2[k]:
return False
return True
def reshape_compare(node1, node2):
"""Compares two reshape nodes."""
assert node1["op"] == node2["op"] == "reshape"
params1, params2 = node1["eqn"].params, node2["eqn"].params
if params1["dimensions"] != params2["dimensions"]:
return False
return True
def broadcast_in_dim_compare(node1, node2):
"""Compares two reshape nodes."""
assert node1["op"] == node2["op"] == "broadcast_in_dim"
return True
def conv_compare(node1, node2):
"""Compares two conv_general_dialted nodes."""
assert node1["op"] == node2["op"] == "conv_general_dilated"
params1, params2 = node1["eqn"].params, node2["eqn"].params
for k in ("window_strides", "padding", "lhs_dilation", "rhs_dilation",
"lhs_shape", "rhs_shape"):
if len(params1[k]) != len(params2[k]):
return False
if (len(params1["dimension_numbers"].lhs_spec) != #
len(params2["dimension_numbers"].lhs_spec)):
return False
if (len(params1["dimension_numbers"].rhs_spec) != #
len(params2["dimension_numbers"].rhs_spec)):
return False
if (len(params1["dimension_numbers"].out_spec) != #
len(params2["dimension_numbers"].out_spec)):
return False
if ((params1["feature_group_count"] > 1) != #
(params2["feature_group_count"] > 1)):
return False
if ((params1["batch_group_count"] > 1) != #
(params2["batch_group_count"] > 1)):
return False
return True
SPECIAL_OP_COMPARE_RULES["reshape"] = reshape_compare
SPECIAL_OP_COMPARE_RULES["broadcast_in_dim"] = broadcast_in_dim_compare
SPECIAL_OP_COMPARE_RULES["conv_general_dilated"] = conv_compare
def kfac_node_match(node1, node2):
"""Checks if two nodes are equivalent."""
# Parameters match with each other and nothing else
if node1["op"] == "param" and node2["op"] == "param":
return True
# return node1["rank"] == node2["rank"]
if node1["op"] == "param" or node2["op"] == "param":
return False
# Arrays always match each other and nothing else
if node1["op"] == "array" and node2["op"] == "array":
return True
if node1["op"] == "array" or node2["op"] == "array":
return False
# Operators match first on name
if node1["op"] != node2["op"]:
return False
compare = SPECIAL_OP_COMPARE_RULES.get(node1["op"], default_compare)
return compare(node1, node2)
def var_to_str(var):
"""Returns a string representation of the variable of a Jax expression."""
if isinstance(var, jax.core.Literal):
return str(var)
elif not isinstance(var, jax.core.Var):
raise ValueError(f"Idk what to do with this {type(var)}?")
c = int(var.count)
if c == -1:
return "_"
str_rep = ""
while c > 25:
str_rep += chr(c % 26 + ord("a"))
c = c // 26
str_rep += chr(c + ord("a"))
return str_rep[::-1]
def extract_param_vars_flat(jaxpr, in_tree, params_index):
if params_index is None:
params_index = []
elif isinstance(params_index, int):
params_index = [params_index]
in_vars = jax.tree_unflatten(in_tree, jaxpr.invars)
return jax.tree_flatten([in_vars[i] for i in params_index])
def fill_jaxpr_to_graph(graph, jaxpr, in_vars=None, out_vars=None):
"""Fills the graph with the jaxpr."""
in_vars = in_vars or [var_to_str(v) for v in jaxpr.invars + jaxpr.constvars]
in_map = dict(zip(jaxpr.invars + jaxpr.constvars, in_vars))
out_vars = out_vars or [var_to_str(v) for v in jaxpr.outvars]
out_map = dict(zip(jaxpr.outvars, out_vars))
for eqn in jaxpr.eqns:
in_vars = []
for v in eqn.invars:
if isinstance(v, jax.core.Literal):
in_vars.append(var_to_str(v))
else:
in_vars.append(in_map.get(v, var_to_str(v)))
out_vars = [out_map.get(v, var_to_str(v)) for v in eqn.outvars]
in_str = ",".join(in_vars)
out_str = ",".join(out_vars)
if isinstance(eqn.primitive, tags.LossTag):
func_name = "__loss_tag"
elif isinstance(eqn.primitive, tags.LayerTag):
func_name = "__layer_tag"
else:
func_name = eqn.primitive.name
node_c = f"{func_name}({in_str})->{out_str}"
graph.add_node(node_c, op=eqn.primitive.name, eqn=eqn)
# Create incoming edges
for v, name in zip(eqn.invars, in_vars):
if not isinstance(v, jax.core.Literal):
graph.add_edge(name, node_c)
# Create output nodes and edges
for v, name in zip(eqn.outvars, out_vars):
graph.add_node(name, op="array", var=v)
graph.add_edge(node_c, name)
def create_digraph(jaxpr, params):
"""Creates a directed graph from the given jaxpr and parameters."""
graph = nx.DiGraph()
# Create input nodes
for v in jaxpr.invars + jaxpr.constvars:
if v in params:
graph.add_node(var_to_str(v), op="param", var=v)
else:
graph.add_node(var_to_str(v), op="array", var=v)
fill_jaxpr_to_graph(graph, jaxpr)
return graph
def function_to_jax_graph(func, args, params_index, tagging_func=None):
"""Creates a `JaxGraph` instance from the provided function."""
in_tree = jax.tree_structure(args)
typed_jaxpr = jax.make_jaxpr(func)(*args)
jaxpr, consts = typed_jaxpr.jaxpr, typed_jaxpr.literals
params, params_tree = extract_param_vars_flat(jaxpr, in_tree, params_index)
digraph = create_digraph(jaxpr, params)
if tagging_func is not None:
tagging_func = functools.partial(tagging_func, jaxpr)
return JaxGraph(
jaxpr=jaxpr,
consts=consts,
params=params,
params_tree=params_tree,
in_tree=in_tree,
out_tree=None,
digraph=digraph,
tagging_func=tagging_func)
def print_nice_jaxpr(jaxpr):
for eqn in jaxpr.eqns:
print(tuple(eqn.invars), "->", eqn.primitive.name, tuple(eqn.outvars))
def auto_register_tags(func,
func_args,
params_index: int = 0,
register_only_generic: bool = False,
compute_only_loss_tags: bool = True,
patterns_to_skip: Sequence[str] = ()):
"""Transform the function to one that is populated with tags."""
func = broadcast_merger(func)
graph = function_to_jax_graph(func, func_args, params_index=params_index)
matches = dict()
# Extract the tagged losses variables and all their ancestors
loss_output_vars = []
num_losses = 0
loss_ancestors = set()
for node in graph.digraph.nodes:
if node.startswith("__loss_tag"):
num_losses += 1
ancestors = nx.ancestors(graph.digraph, node)
ancestors.add(node)
for output_node in node.split("->")[-1].split(","):
ancestors.add(output_node)
loss_output_vars.append(graph.digraph.nodes[output_node]["var"])
loss_ancestors = loss_ancestors.union(ancestors)
loss_output_vars = tuple(loss_output_vars)
# Extract the sub-graph that leads to losses
sub_graph = nx.induced_subgraph(graph.digraph, loss_ancestors)
# First collect all parameters that are already part of a layer tag
tagged_params = dict()
pattern_counters = dict()
for tag_node in (
node for node in sub_graph.nodes if node.startswith("__layer_tag")):
inputs = graph.digraph.nodes[tag_node]["eqn"].invars
tag_instance = graph.digraph.nodes[tag_node]["eqn"].primitive
if tag_instance.name == "generic_tag":
tag_params = tag_instance.split_all_inputs(inputs)[0]
else:
tag_params = tag_instance.split_all_inputs(inputs)[2]
pattern_number = pattern_counters.get(tag_instance.name, 0)
for param in tag_params:
if param not in graph.params:
raise ValueError(f"You have registered a layer tag with parameter "
f"that is not part of the parameters at index "
f"{params_index}.")
if param in tagged_params:
raise ValueError(f"You have registered twice the parameter {param}.")
tagged_params[param] = f"Manual[{tag_instance.name}_{pattern_number}]"
if tag_instance.name not in pattern_counters:
pattern_counters[tag_instance.name] = 1
else:
pattern_counters[tag_instance.name] += 1
if not register_only_generic:
for pattern_name, patterns in get_graph_patterns():
if pattern_name in patterns_to_skip:
logging.info("Skipping graph pattern %s", pattern_name)
continue
logging.info("Matching graph pattern %s", pattern_name)
for pattern in patterns:
for match_map in match_pattern(pattern.digraph, sub_graph):
if len(pattern.jaxpr.outvars) > 1:
raise NotImplementedError()
output = pattern.jaxpr.outvars[0]
if matches.get(match_map[output]) is not None:
raise ValueError(f"Found more than one match for equation "
f"{match_map[output]}. Examine the jaxpr:\n "
f"{graph.jaxpr}")
# Mark the parameters as already tagged
match_params = set()
match_params_already_tagged = False
for param in match_map.values():
if param in graph.params:
match_params.add(param)
if param in tagged_params.keys():
match_params_already_tagged = True
# Register the match only if no parameters are already registered
if not match_params_already_tagged:
matches[match_map[output]] = (match_map, pattern.tagging_func)
pattern_number = pattern_counters.get(pattern_name, 0)
for param in match_params:
tagged_params[param] = f"Auto[{pattern_name}_{pattern_number}]"
if pattern_name not in pattern_counters:
pattern_counters[pattern_name] = 1
else:
pattern_counters[pattern_name] += 1
# Mark remaining parameters as orphans
orphan_params = sorted(
set(graph.params) - set(tagged_params.keys()), key=lambda v: v.count)
params_regs = [tagged_params.get(p, "Orphan") for p in graph.params]
params_regs = jax.tree_unflatten(graph.params_tree, params_regs)
logging.info("=" * 50)
logging.info("Graph parameter registrations:")
logging.info(params_regs)
logging.info("=" * 50)
# Construct a function with all of the extra tag registrations
@functools.wraps(func)
def wrapped_auto_registered(*args):
flat_args, _ = jax.tree_flatten(args)
# Mapping from variable -> value
env = {}
read = functools.partial(read_env, env)
write = functools.partial(write_env, env)
def tag(var):
if matches.get(var) is not None:
inv_map, tagging_func = matches[var]
var_map = {k: v for k, v in inv_map.items() if not isinstance(k, str)}
val_map = jax.tree_map(read, var_map)
val = tagging_func(inv_map, val_map)
env[var] = val
# Bind args and consts to environment
jax_util.safe_map(write, graph.jaxpr.invars, flat_args)
jax_util.safe_map(write, graph.jaxpr.constvars, graph.consts)
# Register any orphan parameters as generic
for param_var in orphan_params:
write(param_var, tags.register_generic(read(param_var)))
# Set the correct output variables
if compute_only_loss_tags:
output_vars = loss_output_vars
out_tree = jax.tree_structure(loss_output_vars)
else:
output_vars = graph.jaxpr.outvars
out_tree = graph.out_tree
# Loop through equations and evaluate primitives using `bind`
losses_evaluated = 0
for eqn in graph.jaxpr.eqns:
evaluate_eqn(eqn, jax_util.safe_map(read, eqn.invars), write)
jax_util.safe_map(tag, eqn.outvars)
# If we want to output only tagged losses
if isinstance(eqn.primitive, tags.LossTag):
losses_evaluated += 1
if compute_only_loss_tags and num_losses == losses_evaluated:
break
outputs = jax_util.safe_map(read, output_vars)
return jax.tree_unflatten(out_tree, outputs)
return wrapped_auto_registered
# Registered graphs
NAME_TO_JAX_GRAPH = dict()
DEFERRED_REGISTRATIONS = []
def register_function(name, func, tagging_func, example_args, params_index,
precedence):
"""Registers a function as a pattern in the graph matcher registry.
The graph matcher needs to trace at least once the full function, which means
you need to provide it with dummy arguments. The shapes of the arguments do
not matter, as the graph matcher ignores their values, however the rank does.
Especially if there is some broadcasting happening you should register with
every possible broadcast pattern. As a general advice avoid using a shape to
be 1, unless you want the pattern to specifically match that, as some
operations, like squeeze for example, can have special behaviour then.
Args:
name: The name of the pattern that is being registered to.
func: The function that performs the computation.
tagging_func: Function that correctly creates the tag.
example_args: Example arguments that can be inputted into `func`.
params_index: Specifies at which index of the `example_args` are considered
a parameter.
precedence: This specifies what precedence the graph matcher is going to
assign to the provided pattern. The graph matcher will go from lowest to
highest precedence, randomly breaking ties, when matching. Note that the
pattern that matches a parameter with the lowest precedence will get
registered and no other will. Specifically useful when there is a pattern
for a layer with and without bias, in which case the with bias
registration always should go with lower precedence.
"""
# This is required because we can not use Jax before InitGoogle() runs
def register():
jnp_args = jax.tree_map(jnp.asarray, example_args)
graph = function_to_jax_graph(
func, jnp_args, params_index=params_index, tagging_func=tagging_func)
if NAME_TO_JAX_GRAPH.get(name) is None:
NAME_TO_JAX_GRAPH[name] = (precedence, [])
assert precedence == NAME_TO_JAX_GRAPH[name][0]
NAME_TO_JAX_GRAPH[name][1].append(graph)
DEFERRED_REGISTRATIONS.append(register)
def get_graph_patterns():
"""Returns all graph patterns sorted by their precedence."""
while DEFERRED_REGISTRATIONS:
DEFERRED_REGISTRATIONS.pop()()
return [(name, pattern) for name, (_, pattern) in sorted(
NAME_TO_JAX_GRAPH.items(), key=lambda pair: pair[1][0])]
# Dense with bias
register_function(
"dense_with_bias",
tags.dense_func,
tags.dense_tagging,
[np.zeros([11, 13]), [np.zeros([13, 7]), np.zeros([7])]],
params_index=1,
precedence=0)
# Dense without bias
register_function(
"dense_no_bias",
tags.dense_func,
tags.dense_tagging, [np.zeros([11, 13]), [np.zeros([13, 7])]],
params_index=1,
precedence=1)
# Conv2d with bias
register_function(
"conv2d_with_bias",
tags.conv2d_func,
tags.conv2d_tagging,
[np.zeros([2, 8, 8, 5]), [np.zeros([3, 3, 5, 4]),
np.zeros([4])]],
params_index=1,
precedence=0)
# Conv2d without bias
register_function(
"conv2d_no_bias",
tags.conv2d_func,
tags.conv2d_tagging, [np.zeros([2, 8, 8, 5]), [np.zeros([3, 3, 5, 4])]],
params_index=1,
precedence=1)
# Standard scale and shift with both scale and shift
register_function(
"scale_and_shift",
functools.partial(
tags.scale_and_shift_func, has_scale=True, has_shift=True),
functools.partial(
tags.scale_and_shift_tagging, has_scale=True, has_shift=True),
[np.zeros([2, 13]), [np.zeros([13]), np.zeros([13])]],
params_index=1,
precedence=0)
# Same but no broadcasting
register_function(
"scale_and_shift",
functools.partial(
tags.scale_and_shift_func, has_scale=True, has_shift=True),
functools.partial(
tags.scale_and_shift_tagging, has_scale=True, has_shift=True),
[np.zeros([13]), [np.zeros([13]), np.zeros([13])]],
params_index=1,
precedence=0)
# Scale and shift as implemented in batch norm layers in Haiku
register_function(
"scale_and_shift",
tags.batch_norm_func,
functools.partial(
tags.batch_norm_tagging_func, has_scale=True, has_shift=True),
[[np.zeros([2, 13]), np.zeros([13])], [np.zeros([13]),
np.zeros([13])]],
params_index=1,
precedence=0)
# Same but no broadcasting
register_function(
"scale_and_shift",
tags.batch_norm_func,
functools.partial(
tags.batch_norm_tagging_func, has_scale=True, has_shift=True),
[[np.zeros([13]), np.zeros([13])], [np.zeros([13]),
np.zeros([13])]],
params_index=1,
precedence=0)
# Only scale
register_function(
"scale_only",
functools.partial(
tags.scale_and_shift_func, has_scale=True, has_shift=False),
functools.partial(
tags.scale_and_shift_tagging, has_scale=True, has_shift=False),
[np.zeros([2, 13]), [np.zeros([13])]],
params_index=1,
precedence=1)
|
deepmind-research-master
|
kfac_ferminet_alpha/tag_graph_matcher.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.
import unittest
from absl.testing import absltest
import jax
import jax.numpy as jnp
import jax.random as jnr
from kfac_ferminet_alpha import layers_and_loss_tags
from kfac_ferminet_alpha import loss_functions
from kfac_ferminet_alpha import tag_graph_matcher
from kfac_ferminet_alpha.tests import common
def tagged_autoencoder(all_params, x_in):
h_in = x_in
layers_values = []
for i, params in enumerate(all_params):
h_out = common.fully_connected_layer(params, h_in)
h_out = layers_and_loss_tags.register_dense(h_out, h_in, params[0],
params[1],)
layers_values.append((h_out, h_in))
# Last layer does not have a nonlinearity
if i % 4 != 3:
h_in = jnp.tanh(h_out)
else:
h_in = h_out
h1, _ = loss_functions.register_normal_predictive_distribution(
h_in, targets=x_in, weight=1.0)
h2, t2 = loss_functions.register_normal_predictive_distribution(
h_in, targets=x_in, weight=0.1)
return [[h1, t2], [h2, t2]]
class TestGraphMatcher(unittest.TestCase):
"""Class for running all of the tests for integrating the systems."""
def _test_jaxpr(self, init_func, model_func, tagged_model, data_shape):
data_shape = tuple(data_shape)
rng_key = jnr.PRNGKey(12345)
init_key, data_key = jnr.split(rng_key)
params = init_func(init_key, data_shape)
data = jnr.normal(data_key, (11,) + data_shape)
func = tag_graph_matcher.auto_register_tags(model_func, (params, data))
jaxpr = jax.make_jaxpr(func)(params, data).jaxpr
tagged_jaxpr = jax.make_jaxpr(tagged_model)(params, data).jaxpr
self.assertEqual(len(jaxpr.invars), len(tagged_jaxpr.invars))
self.assertEqual(len(jaxpr.constvars), len(tagged_jaxpr.constvars))
self.assertEqual(len(jaxpr.outvars), len(tagged_jaxpr.outvars))
for eq, tagged_eq in zip(jaxpr.eqns, tagged_jaxpr.eqns):
eq_in_vars = [v for v in eq.invars]
tagged_in_vars = [v for v in tagged_eq.invars]
self.assertEqual(len(eq_in_vars), len(tagged_in_vars))
self.assertEqual(len(eq.outvars), len(tagged_eq.outvars))
self.assertEqual(eq.primitive, tagged_eq.primitive)
for variable, t_variable in zip(eq_in_vars + eq.outvars,
tagged_in_vars + tagged_eq.outvars):
if isinstance(variable, jax.core.Literal):
self.assertEqual(variable.aval, t_variable.aval)
else:
if variable.count != t_variable.count:
print("0")
self.assertEqual(variable.count, t_variable.count)
def test_autoencoder(self):
self._test_jaxpr(common.init_autoencoder, common.autoencoder,
tagged_autoencoder, [784])
if __name__ == "__main__":
absltest.main()
|
deepmind-research-master
|
kfac_ferminet_alpha/tests/graph_matcher_test.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.
import unittest
from absl.testing import absltest
import jax
import jax.numpy as jnp
import jax.random as jnr
import numpy as np
from kfac_ferminet_alpha import loss_functions
from kfac_ferminet_alpha import tag_graph_matcher as tgm
from kfac_ferminet_alpha import tracer
from kfac_ferminet_alpha import utils
from kfac_ferminet_alpha.tests import common
def autoencoder_aux(all_aux, all_params, x_in):
h_in = x_in
layers_values = []
for i, (params, aux) in enumerate(zip(all_params, all_aux)):
h_out = common.fully_connected_layer(params, h_in + aux[1]) + aux[0]
layers_values.append((h_out, h_in))
# Last layer does not have a nonlinearity
if i % 4 != 3:
h_in = jnp.tanh(h_out)
else:
h_in = h_out
h1, _ = loss_functions.register_normal_predictive_distribution(h_in, x_in)
h2, _ = loss_functions.register_normal_predictive_distribution(
h_in, targets=x_in, weight=0.1)
l1 = (h1 - x_in)**2 + jnp.log(jnp.pi) / 2
l2 = (h2 - x_in)**2 + jnp.log(jnp.pi) / 2
return [l1, l2 * 0.1], layers_values
class TestTracer(unittest.TestCase):
"""Class for running all of the tests for integrating the systems."""
@staticmethod
def generate_data(init_func, func, data_shape, rng_key):
n = 3
rng_key, key = jnr.split(rng_key)
params = init_func(key, data_shape)
rng_key, key = jnr.split(rng_key)
p_tangents = init_func(key, data_shape)
rng_key, key = jnr.split(rng_key)
data = jnr.normal(key, [n] + data_shape)
loss_vals, layer_vals = func(params, data)
h = layer_vals[-1][0]
keys = jnr.split(key, len(loss_vals))
h_tangents = tuple(jnr.normal(key, shape=h.shape) for key in keys)
return params, data, p_tangents, h_tangents
def assertStructureAllClose(self, x, y, rtol=1E-5, atol=1E-5, **kwargs):
x_v, x_tree = jax.tree_flatten(x)
y_v, y_tree = jax.tree_flatten(y)
self.assertEqual(x_tree, y_tree)
for xi, yi in zip(x_v, y_v):
self.assertEqual(xi.shape, yi.shape)
self.assertEqual(xi.dtype, yi.dtype)
np.testing.assert_allclose(xi, yi, rtol=rtol, atol=atol, **kwargs)
def test_tacer_jvp(self):
init_func = common.init_autoencoder
func = common.autoencoder
data_shape = [784]
rng_key = jnr.PRNGKey(12345)
params, data, p_tangents, _ = self.generate_data(init_func, func,
data_shape, rng_key)
def no_data_func(args):
outputs = func(args, data)
return outputs[0], outputs[1][-1][0]
# True computation
(primals_out, tangents_out) = jax.jvp(no_data_func, [params], [p_tangents])
loss_vals, _ = primals_out
_, h_tangents = tangents_out
loss_tangents = ((h_tangents,),) * len(loss_vals)
# Tracer computation
tracer_jvp = tracer.trace_losses_matrix_vector_jvp(func)
tracer_losses, tracer_loss_tangents = tracer_jvp((params, data), p_tangents)
tracer_losses = [loss.evaluate(None) for loss in tracer_losses]
self.assertStructureAllClose(loss_vals, tracer_losses)
self.assertStructureAllClose(loss_tangents, tracer_loss_tangents)
def test_tracer_vjp(self):
init_func = common.init_autoencoder
func = common.autoencoder
data_shape = [784]
rng_key = jnr.PRNGKey(12345)
params, data, _, h_tangents = self.generate_data(init_func, func,
data_shape, rng_key)
def no_data_func(args):
outputs = func(args, data)
return outputs[0], outputs[1][-1][0]
# True computation
(loss_vals, _), vjp_func = jax.vjp(no_data_func, params)
loss_tangents = jax.tree_map(jnp.zeros_like, loss_vals)
summed_h_tangents = sum(jax.tree_flatten(h_tangents)[0])
p_tangents = vjp_func((loss_tangents, summed_h_tangents))
# Tracer computation
trace_vjp = tracer.trace_losses_matrix_vector_vjp(func)
tracer_losses, tracer_vjp_func = trace_vjp(params, data)
tracer_losses = [loss.evaluate(None) for loss in tracer_losses]
tracer_p_tangents = tracer_vjp_func(h_tangents)
self.assertStructureAllClose(loss_vals, tracer_losses)
self.assertStructureAllClose(p_tangents, tracer_p_tangents, atol=3e-6)
def test_tracer_hvp(self):
init_func = common.init_autoencoder
func = common.autoencoder
data_shape = [784]
rng_key = jnr.PRNGKey(12345)
params, data, p_tangents, _ = self.generate_data(init_func, func,
data_shape, rng_key)
def no_data_func(args):
outputs = func(args, data)
return sum(jax.tree_map(jnp.sum, outputs[0]))
# True computation
grad_func = jax.grad(no_data_func)
def grad_time_tangents(args):
return utils.inner_product(grad_func(args), p_tangents)
hvp = jax.grad(grad_time_tangents)
hvp_vectors = hvp(params)
# Tracer computation
tracer_hvp = tracer.trace_losses_matrix_vector_hvp(func)
tracer_hvp_vectors = tracer_hvp((params, data), p_tangents)
self.assertStructureAllClose(hvp_vectors, tracer_hvp_vectors, atol=1e-4)
def test_trace_estimator(self):
init_func = common.init_autoencoder
func = common.autoencoder
aux_func = autoencoder_aux
data_shape = [784]
rng_key = jnr.PRNGKey(12345)
params, data, _, h_tangents = self.generate_data(init_func, func,
data_shape, rng_key)
def aux_last_layer(aux, args):
outs = aux_func(aux, args, data)
return outs[1][-1][0]
# True computation
loss_vals, layer_vals = func(params, data)
aux_vals = jax.tree_map(jnp.zeros_like, layer_vals)
_, vjp = jax.vjp(aux_last_layer, aux_vals, params)
summed_h_tangents = sum(jax.tree_flatten(h_tangents)[0])
aux_tangents, p_tangents = vjp(summed_h_tangents)
layers_info = []
for aux_p, p_p in zip(layer_vals, params):
info = dict()
info["outputs"] = (aux_p[0],)
info["inputs"] = (aux_p[1],)
info["params"] = (p_p[0], p_p[1])
layers_info.append(info)
for i, (aux_t, p_t) in enumerate(zip(aux_tangents, p_tangents)):
info = dict()
info["outputs_tangent"] = (aux_t[0],)
info["inputs_tangent"] = (aux_t[1],)
info["params_tangent"] = (p_t[0], p_t[1])
layers_info[i].update(info)
layers_info = tuple(layers_info)
func = tgm.auto_register_tags(func, (params, data))
tracer_vjp = tracer.trace_estimator_vjp(func)
tracer_losses, tracer_vjp_func = tracer_vjp((params, data))
tracer_losses = [loss.evaluate(None) for loss in tracer_losses]
tracer_outputs = tracer_vjp_func((h_tangents[:1], h_tangents[1:]))
self.assertStructureAllClose(loss_vals, tracer_losses)
self.assertStructureAllClose(tracer_outputs, layers_info, atol=3e-6)
if __name__ == "__main__":
absltest.main()
|
deepmind-research-master
|
kfac_ferminet_alpha/tests/tracer_test.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.
"""Common functions used across more than one test."""
import jax
import jax.numpy as jnp
import jax.random as jnr
from kfac_ferminet_alpha import loss_functions
def fully_connected_layer(params, x):
w, b = params
return jnp.matmul(x, w) + b[None]
def init_autoencoder(key, data_shape):
"""Initialize the standard autoencoder."""
assert len(data_shape) == 1
x_size = data_shape[0]
sizes = [x_size, 1000, 500, 250, 30, 250, 500, 1000, x_size]
keys = jnr.split(key, len(sizes) - 1)
params = []
for key, dim_in, dim_out in zip(keys, sizes, sizes[1:]):
# Glorot uniform initialization
c = jnp.sqrt(6 / (dim_in + dim_out))
w = jax.random.uniform(key, shape=(dim_in, dim_out), minval=-c, maxval=c)
b = jnp.zeros([dim_out])
params.append((w, b))
return params
def autoencoder(all_params, x_in):
"""Evaluate the standard autoencoder.
Note that the objective of this autoencoder is not standard, bur rather a sum
of the standard sigmoid crossentropy and squared loss. The reason for this is
to test on handling multiple losses.
Args:
all_params: All parameter values.
x_in: Inputs to the network.
Returns:
The value of the two losses and intermediate layer values.
"""
h_in = x_in
layers_values = []
for i, params in enumerate(all_params):
h_out = fully_connected_layer(params, h_in)
layers_values.append((h_out, h_in))
# Last layer does not have a nonlinearity
if i % 4 != 3:
# h_in = nn.leaky_relu(h_out)
h_in = jnp.tanh(h_out)
else:
h_in = h_out
h1, _ = loss_functions.register_normal_predictive_distribution(h_in, x_in)
h2, _ = loss_functions.register_normal_predictive_distribution(
h_in, targets=x_in, weight=0.1)
l1 = (h1 - x_in)**2 + jnp.log(jnp.pi) / 2
l1 = jnp.sum(l1, axis=-1)
l2 = (h2 - x_in)**2 + jnp.log(jnp.pi) / 2
l2 = jnp.sum(l2, axis=-1)
return [l1, l2 * 0.1], layers_values
|
deepmind-research-master
|
kfac_ferminet_alpha/tests/common.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.
"""Decoder architectures to be used with VAE."""
import abc
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
class DecoderBase(hk.Module):
"""Base class for decoder network classes."""
def __init__(self, obs_var: float):
"""Class initializer.
Args:
obs_var: oversation variance of the dataset.
"""
super().__init__()
self._obs_var = obs_var
@abc.abstractmethod
def __call__(self, z: jnp.ndarray) -> jnp.ndarray:
"""Reconstruct from a given latent sample.
Args:
z: latent samples of shape (batch_size, latent_dim)
Returns:
Reconstruction with shape (batch_size, ...).
"""
def data_fidelity(
self,
input_data: jnp.ndarray,
recons: jnp.ndarray,
) -> jnp.ndarray:
"""Compute Data fidelity (recons loss) for given input and recons.
Args:
input_data: Input batch of shape (batch_size, ...).
recons: Reconstruction of the input data. An array with the same shape as
`input_data.data`.
Returns:
Computed data fidelity term across batch of data. An array of shape
`(batch_size,)`.
"""
error = (input_data - recons).reshape(input_data.shape[0], -1)
return -0.5 * jnp.sum(jnp.square(error), axis=1) / self._obs_var
class ColorMnistMLPDecoder(DecoderBase):
"""MLP decoder for Color Mnist."""
_hidden_units = (200, 200, 200, 200)
_image_dims = (28, 28, 3) # Dimensions of a single MNIST image.
def __call__(self, z: jnp.ndarray) -> jnp.ndarray:
"""Reconstruct with given latent sample.
Args:
z: latent samples of shape (batch_size, latent_dim)
Returns:
Reconstructions data of shape (batch_size, 28, 28, 3).
"""
out = z
for units in self._hidden_units:
out = hk.Linear(units)(out)
out = jax.nn.relu(out)
out = hk.Linear(np.product(self._image_dims))(out)
out = jax.nn.sigmoid(out)
return jnp.reshape(out, (-1,) + self._image_dims)
|
deepmind-research-master
|
avae/decoders.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.
"""Checkpointing functionality."""
import os
from typing import Any, Mapping, Optional
from absl import logging
import dill
import jax
import jax.numpy as jnp
class Checkpointer:
"""A checkpoint saving and loading class."""
def __init__(self, checkpoint_dir: str, filename: str):
"""Class initializer.
Args:
checkpoint_dir: Checkpoint directory.
filename: Filename of checkpoint in checkpoint directory.
"""
self._checkpoint_dir = checkpoint_dir
if not os.path.isdir(self._checkpoint_dir):
os.mkdir(self._checkpoint_dir)
self._checkpoint_path = os.path.join(self._checkpoint_dir, filename)
def save_checkpoint(
self,
experiment_state: Mapping[str, jnp.ndarray],
opt_state: Mapping[str, jnp.ndarray],
step: int,
extra_checkpoint_info: Optional[Mapping[str, Any]] = None) -> None:
"""Save checkpoint with experiment state and step information.
Args:
experiment_state: Experiment params to be stored.
opt_state: Optimizer state to be stored.
step: Training iteration step.
extra_checkpoint_info: Extra information to be stored.
"""
if jax.host_id() != 0:
return
checkpoint_data = dict(
experiment_state=jax.tree_map(jax.device_get, experiment_state),
opt_state=jax.tree_map(jax.device_get, opt_state),
step=step)
if extra_checkpoint_info is not None:
for key in extra_checkpoint_info:
checkpoint_data[key] = extra_checkpoint_info[key]
with open(self._checkpoint_path, 'wb') as checkpoint_file:
dill.dump(checkpoint_data, checkpoint_file, protocol=2)
def load_checkpoint(
self) -> Optional[Mapping[str, Mapping[str, jnp.ndarray]]]:
"""Load and return checkpoint data.
Returns:
Loaded checkpoint if it exists else returns None.
"""
if os.path.exists(self._checkpoint_path):
with open(self._checkpoint_path, 'rb') as checkpoint_file:
checkpoint_data = dill.load(checkpoint_file)
logging.info('Loading checkpoint from %s, saved at step %d',
self._checkpoint_path, checkpoint_data['step'])
return checkpoint_data
else:
logging.warning('No pre-saved checkpoint found at %s',
self._checkpoint_path)
return None
|
deepmind-research-master
|
avae/checkpointer.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.
"""Encoder architectures to be used with VAE."""
import abc
from typing import Generic, TypeVar
import haiku as hk
import jax
import jax.numpy as jnp
from avae import types
_Params = TypeVar('_Params')
class EncoderBase(hk.Module, Generic[_Params]):
"""Abstract class for encoder architectures."""
def __init__(self, latent_dim: int):
"""Class initializer.
Args:
latent_dim: Latent dimensions of the model.
"""
super().__init__()
self._latent_dim = latent_dim
@abc.abstractmethod
def __call__(self, input_data: jnp.ndarray) -> _Params:
"""Return posterior distribution over latents.
Args:
input_data: Input batch of shape (batch_size, ...).
Returns:
Parameters of the posterior distribution over the latents.
"""
@abc.abstractmethod
def sample(self, posterior: _Params, key: jnp.ndarray) -> jnp.ndarray:
"""Sample from the given posterior distribution.
Args:
posterior: Parameters of posterior distribution over the latents.
key: Random number generator key.
Returns:
Sample from the posterior distribution over latents,
shape[batch_size, latent_dim]
"""
class ColorMnistMLPEncoder(EncoderBase[types.NormalParams]):
"""MLP encoder for ColorMnist."""
_hidden_units = (200, 200, 200, 200)
def __call__(
self, input_data: jnp.ndarray) -> types.NormalParams:
"""Return posterior distribution over latents.
Args:
input_data: Input batch of shape (batch_size, ...).
Returns:
Posterior distribution over the latents.
"""
out = hk.Flatten()(input_data)
for units in self._hidden_units:
out = hk.Linear(units)(out)
out = jax.nn.relu(out)
out = hk.Linear(2 * self._latent_dim)(out)
return _normal_params_from_logits(out)
def sample(
self,
posterior: types.NormalParams,
key: jnp.ndarray,
) -> jnp.ndarray:
"""Sample from the given normal posterior (mean, var) distribution.
Args:
posterior: Posterior over the latents.
key: Random number generator key.
Returns:
Sample from the posterior distribution over latents,
shape[batch_size, latent_dim]
"""
eps = jax.random.normal(
key, shape=(posterior.mean.shape[0], self._latent_dim))
return posterior.mean + eps * posterior.variance
def _normal_params_from_logits(
logits: jnp.ndarray) -> types.NormalParams:
"""Construct mean and variance of normal distribution from given logits."""
mean, log_variance = jnp.split(logits, 2, axis=1)
variance = jnp.exp(log_variance)
return types.NormalParams(mean=mean, variance=variance)
|
deepmind-research-master
|
avae/encoders.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.
"""Useful dataclasses types used across the code."""
from typing import Optional
import dataclasses
import jax.numpy as jnp
import numpy as np
@dataclasses.dataclass(frozen=True)
class ELBOOutputs:
elbo: jnp.ndarray
data_fidelity: jnp.ndarray
kl: jnp.ndarray
@dataclasses.dataclass(frozen=True)
class LabelledData:
"""A batch of labelled examples.
Attributes:
data: Array of shape (batch_size, ...).
label: Array of shape (batch_size, ...).
"""
data: np.ndarray
label: Optional[np.ndarray]
@dataclasses.dataclass(frozen=True)
class NormalParams:
"""Parameters of a normal distribution.
Attributes:
mean: Array of shape (batch_size, latent_dim).
variance: Array of shape (batch_size, latent_dim).
"""
mean: jnp.ndarray
variance: jnp.ndarray
|
deepmind-research-master
|
avae/types.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.
"""Various KL implementations in JAX."""
import jax.numpy as jnp
def kl_p_with_uniform_normal(mean: jnp.ndarray,
variance: jnp.ndarray) -> jnp.ndarray:
r"""KL between p_dist with uniform normal prior.
Args:
mean: Mean of the gaussian distribution, shape (latent_dims,)
variance: Variance of the gaussian distribution, shape (latent_dims,)
Returns:
KL divergence KL(P||N(0, 1)) shape ()
"""
if len(variance.shape) == 2:
# If `variance` is a full covariance matrix
variance_trace = jnp.trace(variance)
_, ldet1 = jnp.linalg.slogdet(variance)
else:
variance_trace = jnp.sum(variance)
ldet1 = jnp.sum(jnp.log(variance))
mean_contribution = jnp.sum(jnp.square(mean))
res = -ldet1
res += variance_trace + mean_contribution - mean.shape[0]
return res * 0.5
|
deepmind-research-master
|
avae/kl.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.
"""VAE style training."""
from typing import Any, Callable, Iterator, Sequence, Mapping, Tuple, Optional
import haiku as hk
import jax
import jax.numpy as jnp
import optax
from avae import checkpointer
from avae import types
def train(
train_data_iterator: Iterator[types.LabelledData],
test_data_iterator: Iterator[types.LabelledData],
elbo_fun: hk.Transformed,
learning_rate: float,
checkpoint_dir: str,
checkpoint_filename: str,
checkpoint_every: int,
test_every: int,
iterations: int,
rng_seed: int,
test_functions: Optional[Sequence[Callable[[Mapping[str, jnp.ndarray]],
Tuple[str, float]]]] = None,
extra_checkpoint_info: Optional[Mapping[str, Any]] = None):
"""Train VAE with given data iterator and elbo definition.
Args:
train_data_iterator: Iterator of batched training data.
test_data_iterator: Iterator of batched testing data.
elbo_fun: Haiku transfomed function returning elbo.
learning_rate: Learning rate to be used with optimizer.
checkpoint_dir: Path of the checkpoint directory.
checkpoint_filename: Filename of the checkpoint.
checkpoint_every: Checkpoint every N iterations.
test_every: Test and log results every N iterations.
iterations: Number of training iterations to perform.
rng_seed: Seed for random number generator.
test_functions: Test function iterable, each function takes test data and
outputs extra info to print at test and log time.
extra_checkpoint_info: Extra info to put inside saved checkpoint.
"""
rng_seq = hk.PRNGSequence(jax.random.PRNGKey(rng_seed))
opt_init, opt_update = optax.chain(
# Set the parameters of Adam. Note the learning_rate is not here.
optax.scale_by_adam(b1=0.9, b2=0.999, eps=1e-8),
# Put a minus sign to *minimise* the loss.
optax.scale(-learning_rate))
@jax.jit
def loss(params, key, data):
elbo_outputs = elbo_fun.apply(params, key, data)
return -jnp.mean(elbo_outputs.elbo)
@jax.jit
def loss_test(params, key, data):
elbo_output = elbo_fun.apply(params, key, data)
return (-jnp.mean(elbo_output.elbo), jnp.mean(elbo_output.data_fidelity),
jnp.mean(elbo_output.kl))
@jax.jit
def update_step(params, key, data, opt_state):
grads = jax.grad(loss, has_aux=False)(params, key, data)
updates, opt_state = opt_update(grads, opt_state, params)
params = optax.apply_updates(params, updates)
return params, opt_state
exp_checkpointer = checkpointer.Checkpointer(
checkpoint_dir, checkpoint_filename)
experiment_data = exp_checkpointer.load_checkpoint()
if experiment_data is not None:
start = experiment_data['step']
params = experiment_data['experiment_state']
opt_state = experiment_data['opt_state']
else:
start = 0
params = elbo_fun.init(
next(rng_seq), next(train_data_iterator).data)
opt_state = opt_init(params)
for step in range(start, iterations, 1):
if step % test_every == 0:
test_loss, ll, kl = loss_test(params, next(rng_seq),
next(test_data_iterator).data)
output_message = (f'Step {step} elbo {-test_loss:0.2f} LL {ll:0.2f} '
f'KL {kl:0.2f}')
if test_functions:
for test_function in test_functions:
name, test_output = test_function(params)
output_message += f' {name}: {test_output:0.2f}'
print(output_message)
params, opt_state = update_step(params, next(rng_seq),
next(train_data_iterator).data, opt_state)
if step % checkpoint_every == 0:
exp_checkpointer.save_checkpoint(
params, opt_state, step, extra_checkpoint_info)
|
deepmind-research-master
|
avae/train.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.
"""Dataset iterators Mnist, ColorMnist."""
import enum
import jax.numpy as jnp
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from avae import types
class Dataset(enum.Enum):
color_mnist = enum.auto()
class MnistDataIterator(object):
"""Mnist data iterator class.
Data is obtained as dataclass, types.LabelledData.
"""
def __init__(self, subset: str, batch_size: int):
"""Class initializer.
Args:
subset: Subset of dataset.
batch_size: Batch size of the returned dataset iterator.
"""
datasets = tfds.load('mnist')
train_dataset = datasets[subset]
def _map_fun(x):
return {'data': tf.cast(x['image'], tf.float32) / 255.0,
'label': x['label']}
train_dataset = train_dataset.map(_map_fun)
train_dataset = train_dataset.batch(batch_size,
drop_remainder=True).repeat()
self._iterator = iter(tfds.as_numpy(train_dataset))
self._batch_size = batch_size
def __iter__(self):
return self
def __next__(self) -> types.LabelledData:
return types.LabelledData(**next(self._iterator))
class ColorMnistDataIterator(MnistDataIterator):
"""Color Mnist data iterator.
Each ColorMnist image is of shape (28, 28, 3). ColorMnist digit can have 7
different colors by permution of RGB channels (turning on and off RGB
channels, except for all channels off permutation).
Data is obtained as dataclass, util_dataclasses.LabelledData.
"""
def __next__(self) -> types.LabelledData:
mnist_batch = next(self._iterator)
mnist_image = mnist_batch['data']
# Colors are supported by turning off and on RGB channels.
# Thus possible colors are
# [black (excluded), red, green, yellow, blue, magenta, cyan, white]
# color_id takes value from [1,8)
color_id = np.random.randint(7, size=self._batch_size) + 1
red_channel_bool = np.mod(color_id, 2)
red_channel_bool = jnp.reshape(red_channel_bool, [-1, 1, 1, 1])
blue_channel_bool = np.floor_divide(color_id, 4)
blue_channel_bool = jnp.reshape(blue_channel_bool, [-1, 1, 1, 1])
green_channel_bool = np.mod(np.floor_divide(color_id, 2), 2)
green_channel_bool = jnp.reshape(green_channel_bool, [-1, 1, 1, 1])
color_mnist_image = jnp.stack([
jnp.multiply(red_channel_bool, mnist_image),
jnp.multiply(blue_channel_bool, mnist_image),
jnp.multiply(green_channel_bool, mnist_image)], axis=3)
color_mnist_image = jnp.reshape(color_mnist_image, [-1, 28, 28, 3])
# Color id takes value [1, 8)
# Although to make classification code easier `color` label attached to data
# takes value in [0, 7) (by subtracting 1 from color id)
return types.LabelledData(
data=color_mnist_image, label=mnist_batch['label'])
|
deepmind-research-master
|
avae/data_iterators.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.
"""Main file for training VAE/AVAE."""
import enum
from absl import app
from absl import flags
import haiku as hk
from avae import data_iterators
from avae import decoders
from avae import encoders
from avae import train
from avae import vae
class Model(enum.Enum):
vae = enum.auto()
avae = enum.auto()
class EncoderArch(enum.Enum):
color_mnist_mlp_encoder = 'ColorMnistMLPEncoder'
class DecoderArch(enum.Enum):
color_mnist_mlp_decoder = 'ColorMnistMLPDecoder'
_DATASET = flags.DEFINE_enum_class(
'dataset', data_iterators.Dataset.color_mnist, data_iterators.Dataset,
'Dataset to train on')
_LATENT_DIM = flags.DEFINE_integer('latent_dim', 32,
'Number of latent dimensions.')
_TRAIN_BATCH_SIZE = flags.DEFINE_integer('train_batch_size', 64,
'Train batch size.')
_TEST_BATCH_SIZE = flags.DEFINE_integer('test_batch_size', 64,
'Testing batch size.')
_TEST_EVERY = flags.DEFINE_integer('test_every', 1000,
'Test every N iterations.')
_ITERATIONS = flags.DEFINE_integer('iterations', 102000,
'Number of training iterations.')
_OBS_VAR = flags.DEFINE_float('obs_var', 0.5,
'Observation variance of the data. (Default 0.5)')
_MODEL = flags.DEFINE_enum_class('model', Model.avae, Model,
'Model used for training.')
_RHO = flags.DEFINE_float('rho', 0.8, 'Rho parameter used with AVAE or SE.')
_LEARNING_RATE = flags.DEFINE_float('learning_rate', 1e-4, 'Learning rate.')
_RNG_SEED = flags.DEFINE_integer('rng_seed', 0,
'Seed for random number generator.')
_CHECKPOINT_DIR = flags.DEFINE_string('checkpoint_dir', '/tmp/',
'Directory for checkpointing.')
_CHECKPOINT_FILENAME = flags.DEFINE_string(
'checkpoint_filename', 'color_mnist_avae_mlp', 'Checkpoint filename.')
_CHECKPOINT_EVERY = flags.DEFINE_integer(
'checkpoint_every', 1000, 'Checkpoint every N steps.')
_ENCODER = flags.DEFINE_enum_class(
'encoder', EncoderArch.color_mnist_mlp_encoder, EncoderArch,
'Encoder class name.')
_DECODER = flags.DEFINE_enum_class(
'decoder', DecoderArch.color_mnist_mlp_decoder, DecoderArch,
'Decoder class name.')
def main(_):
if _DATASET.value is data_iterators.Dataset.color_mnist:
train_data_iterator = iter(
data_iterators.ColorMnistDataIterator('train', _TRAIN_BATCH_SIZE.value))
test_data_iterator = iter(
data_iterators.ColorMnistDataIterator('test', _TEST_BATCH_SIZE.value))
def _elbo_fun(input_data):
if _ENCODER.value is EncoderArch.color_mnist_mlp_encoder:
encoder = encoders.ColorMnistMLPEncoder(_LATENT_DIM.value)
if _DECODER.value is DecoderArch.color_mnist_mlp_decoder:
decoder = decoders.ColorMnistMLPDecoder(_OBS_VAR.value)
vae_obj = vae.VAE(encoder, decoder, _RHO.value)
if _MODEL.value is Model.vae:
return vae_obj.vae_elbo(input_data, hk.next_rng_key())
else:
return vae_obj.avae_elbo(input_data, hk.next_rng_key())
elbo_fun = hk.transform(_elbo_fun)
extra_checkpoint_info = {
'dataset': _DATASET.value.name,
'encoder': _ENCODER.value.name,
'decoder': _DECODER.value.name,
'obs_var': _OBS_VAR.value,
'rho': _RHO.value,
'latent_dim': _LATENT_DIM.value,
}
train.train(
train_data_iterator=train_data_iterator,
test_data_iterator=test_data_iterator,
elbo_fun=elbo_fun,
learning_rate=_LEARNING_RATE.value,
checkpoint_dir=_CHECKPOINT_DIR.value,
checkpoint_filename=_CHECKPOINT_FILENAME.value,
checkpoint_every=_CHECKPOINT_EVERY.value,
test_every=_TEST_EVERY.value,
iterations=_ITERATIONS.value,
rng_seed=_RNG_SEED.value,
extra_checkpoint_info=extra_checkpoint_info)
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
avae/train_main.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.
"""Standard VAE class."""
from typing import Optional
import jax
import jax.numpy as jnp
from avae import decoders
from avae import encoders
from avae import kl
from avae import types
class VAE:
"""VAE class.
This class defines the ELBO used in training VAE models. It also adds function
for forward passing data through VAE.
"""
def __init__(self, encoder: encoders.EncoderBase,
decoder: decoders.DecoderBase, rho: Optional[float] = None):
"""Class initializer.
Args:
encoder: Encoder network architecture.
decoder: Decoder network architecture.
rho: Rho parameter used in AVAE training.
"""
self._encoder = encoder
self._decoder = decoder
self._rho = rho
def vae_elbo(
self, input_data: jnp.ndarray,
key: jnp.ndarray) -> types.ELBOOutputs:
"""ELBO for training VAE.
Args:
input_data: Input batch of shape (batch_size, ...).
key: Key for random number generator.
Returns:
Computed VAE Elbo as type util_dataclasses.ELBOOutputs
"""
posterior = self._encoder(input_data)
samples = self._encoder.sample(posterior, key)
kls = jax.vmap(kl.kl_p_with_uniform_normal, [0])(
posterior.mean, posterior.variance)
recons = self._decoder(samples)
data_fidelity = self._decoder.data_fidelity(input_data, recons)
elbo = data_fidelity - kls
return types.ELBOOutputs(elbo, data_fidelity, kls)
def avae_elbo(
self, input_data: jnp.ndarray,
key: jnp.ndarray) -> types.ELBOOutputs:
"""ELBO for training AVAE model.
Args:
input_data: Input batch of shape (batch_size, ...).
key: Key for random number generator.
Returns:
Computed AVAE Elbo in nested tuple (Elbo, (data_fidelity, KL)). All arrays
have batch dimension intact.
"""
aux_images = jax.lax.stop_gradient(self(input_data, key))
posterior = self._encoder(input_data)
samples = self._encoder.sample(posterior, key)
kls = jax.vmap(kl.kl_p_with_uniform_normal, [0, 0])(
posterior.mean, posterior.variance)
recons = self._decoder(samples)
data_fidelity = self._decoder.data_fidelity(input_data, recons)
elbo = data_fidelity - kls
aux_posterior = self._encoder(aux_images)
latent_mean = posterior.mean
latent_var = posterior.variance
aux_latent_mean = aux_posterior.mean
aux_latent_var = aux_posterior.variance
latent_dim = latent_mean.shape[1]
def _reduce(x):
return jnp.mean(jnp.sum(x, axis=1))
# Computation of <log p(Z_aux | Z)>.
expected_log_conditional = (
aux_latent_var + jnp.square(self._rho) * latent_var +
jnp.square(aux_latent_mean - self._rho * latent_mean))
expected_log_conditional = _reduce(expected_log_conditional)
expected_log_conditional /= 2.0 * (1.0 - jnp.square(self._rho))
expected_log_conditional = (latent_dim *
jnp.log(1.0 / (2 * jnp.pi)) -
expected_log_conditional)
elbo += expected_log_conditional
# Entropy of Z_aux
elbo += _reduce(0.5 * jnp.log(2 * jnp.pi * jnp.e * aux_latent_var))
return types.ELBOOutputs(elbo, data_fidelity, kls)
def __call__(
self, input_data: jnp.ndarray,
key: jnp.ndarray) -> jnp.ndarray:
"""Reconstruction of the input data.
Args:
input_data: Input batch of shape (batch_size, ...).
key: Key for random number generator.
Returns:
Reconstruction of the input data as jnp.ndarray of shape
[batch_dim, observation_dims].
"""
posterior = self._encoder(input_data)
samples = self._encoder.sample(posterior, key)
recons = self._decoder(samples)
return recons
|
deepmind-research-master
|
avae/vae.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.
"""Example code for running model on CLEVRER."""
import json
from absl import app
from absl import flags
import numpy as np
import tensorflow.compat.v1 as tf
from object_attention_for_reasoning import model as modellib
BATCH_SIZE = 1
NUM_FRAMES = 25
NUM_OBJECTS = 8
_BASE_DIR = flags.DEFINE_string(
"base_dir", "./clevrer_monet_latents",
"Directory containing checkpoints and MONet latents.")
_SCENE_IDX = flags.DEFINE_string(
"scene_idx", 1000, "Scene index of CLEVRER video.")
def load_monet_latents(base_dir, scene_index):
filename = f"{base_dir}/train/{scene_index}.npz"
with open(filename, "rb") as f:
return np.load(f)
def _split_string(s):
"""Splits string to words and standardize alphabet."""
return s.lower().replace("?", "").split()
def _pad(array, length):
"""Pad an array to desired length."""
return np.pad(array, [(0, length - array.shape[0])], mode="constant")
def encode_sentence(token_map, sentence, pad_length):
"""Encode CLEVRER question/choice sentences as sequence of token ids."""
ret = np.array(
[token_map["question_vocab"][w] for w in _split_string(sentence)],
np.int32)
return _pad(ret, pad_length)
def encode_choices(token_map, choices):
"""Encode CLEVRER choices."""
arrays = [encode_sentence(token_map, choice["choice"],
modellib.MAX_CHOICE_LENGTH)
for choice in choices]
return _pad(np.stack(arrays, axis=0), modellib.NUM_CHOICES)
def main(unused_argv):
base_dir = _BASE_DIR.value
with open(f"{base_dir}/vocab.json", "rb") as f:
token_map = json.load(f)
reverse_answer_lookup = {v: k for k, v in token_map["answer_vocab"].items()}
with open(f"{base_dir}/train.json", "rb") as f:
questions_data = json.load(f)
tf.reset_default_graph()
model = modellib.ClevrerTransformerModel(**modellib.PRETRAINED_MODEL_CONFIG)
inputs_descriptive = {
"monet_latents": tf.placeholder(
tf.float32,
[BATCH_SIZE, NUM_FRAMES, NUM_OBJECTS, modellib.EMBED_DIM]),
"question": tf.placeholder(
tf.int32, [BATCH_SIZE, modellib.MAX_QUESTION_LENGTH]),
}
inputs_mc = {
"monet_latents": tf.placeholder(
tf.float32,
[BATCH_SIZE, NUM_FRAMES, NUM_OBJECTS, modellib.EMBED_DIM]),
"question": tf.placeholder(tf.int32,
[BATCH_SIZE, modellib.MAX_QUESTION_LENGTH]),
"choices": tf.placeholder(
tf.int32, [BATCH_SIZE, modellib.NUM_CHOICES,
modellib.MAX_CHOICE_LENGTH]),
}
output_descriptive = model.apply_model_descriptive(inputs_descriptive)
output_mc = model.apply_model_mc(inputs_mc)
# Restore from checkpoint
saver = tf.train.Saver()
checkpoint_dir = f"{base_dir}/checkpoints/"
sess = tf.train.SingularMonitoredSession(checkpoint_dir=checkpoint_dir)
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
saver.restore(sess, ckpt.model_checkpoint_path)
def eval_descriptive(monet_latents, question_json):
# CLEVRER provides videos with 128 frames. In our model, we subsample 25
# frames (as was done in Yi et al (2020)).
# For training, we randomize the choice of 25 frames, and for evaluation, we
# sample the 25 frames as evenly as possible.
# We do that by doing strided sampling of the frames.
stride, rem = divmod(monet_latents.shape[0], NUM_FRAMES)
monet_latents = monet_latents[None, :-rem:stride]
assert monet_latents.shape[1] == NUM_FRAMES
question = encode_sentence(token_map, question_json["question"],
modellib.MAX_QUESTION_LENGTH)
batched_question = np.expand_dims(question, axis=0)
logits = sess.run(output_descriptive, feed_dict={
inputs_descriptive["monet_latents"]: monet_latents,
inputs_descriptive["question"]: batched_question,
})
descriptive_answer = np.argmax(logits)
return reverse_answer_lookup[descriptive_answer]
def eval_mc(monet_latents, question_json):
stride, rem = divmod(monet_latents.shape[0], NUM_FRAMES)
monet_latents = monet_latents[None, :-rem:stride]
assert monet_latents.shape[1] == NUM_FRAMES
question = encode_sentence(
token_map, question_json["question"], modellib.MAX_QUESTION_LENGTH)
choices = encode_choices(
token_map, question_json["choices"])
mc_answer = sess.run(output_mc, feed_dict={
inputs_mc["monet_latents"]: monet_latents,
inputs_mc["question"]: np.expand_dims(question, axis=0),
inputs_mc["choices"]: np.expand_dims(choices, axis=0),
})
return mc_answer >= 0
sample_scene_idx = _SCENE_IDX.value
question_json = questions_data[sample_scene_idx]["questions"][0]
print("Descriptive Question: ", question_json["question"])
print("Model Answer: ",
eval_descriptive(load_monet_latents(base_dir, sample_scene_idx),
question_json))
print("True Answer: ", question_json["answer"])
question_json = questions_data[sample_scene_idx]["questions"][-1]
print("Multiple-Choice Question: ", question_json["question"])
for i, choice_json in enumerate(question_json["choices"]):
print(f"{i+1}) {choice_json['choice']}")
print("Model Answer: ",
eval_mc(load_monet_latents(base_dir, sample_scene_idx), question_json))
print("True Answer: ",
[choice_json["answer"] for choice_json in question_json["choices"]])
if __name__ == "__main__":
app.run(main)
|
deepmind-research-master
|
object_attention_for_reasoning/run_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.
"""Model code. Provided settings are identical to what was used in the paper."""
import sonnet as snt
import tensorflow.compat.v1 as tf
from object_attention_for_reasoning import transformer
QUESTION_VOCAB_SIZE = 82
ANSWER_VOCAB_SIZE = 22
MAX_QUESTION_LENGTH = 20
MAX_CHOICE_LENGTH = 12
NUM_CHOICES = 4
EMBED_DIM = 16
PRETRAINED_MODEL_CONFIG = dict(
use_relative_positions=True,
shuffle_objects=True,
transformer_layers=28,
head_size=128,
num_heads=10,
embed_dim=EMBED_DIM,
)
def append_ids(tensor, id_vector, axis):
id_vector = tf.constant(id_vector, tf.float32)
for a in range(len(tensor.shape)):
if a != axis:
id_vector = tf.expand_dims(id_vector, axis=a)
tiling_vector = [s if i != axis else 1 for i, s in enumerate(tensor.shape)]
id_tensor = tf.tile(id_vector, tiling_vector)
return tf.concat([tensor, id_tensor], axis=axis)
class ClevrerTransformerModel(object):
"""Model from Ding et al. 2020 (https://arxiv.org/abs/2012.08508)."""
def __init__(self, use_relative_positions, shuffle_objects,
transformer_layers, num_heads, head_size, embed_dim):
"""Instantiate Sonnet modules."""
self._embed_dim = embed_dim
self._embed = snt.Embed(QUESTION_VOCAB_SIZE, embed_dim - 2)
self._shuffle_objects = shuffle_objects
self._memory_transformer = transformer.TransformerTower(
value_size=embed_dim + 2,
num_heads=num_heads,
num_layers=transformer_layers,
use_relative_positions=use_relative_positions,
causal=False)
self._final_layer_mc = snt.Sequential(
[snt.Linear(head_size), tf.nn.relu, snt.Linear(1)])
self._final_layer_descriptive = snt.Sequential(
[snt.Linear(head_size), tf.nn.relu,
snt.Linear(ANSWER_VOCAB_SIZE)])
self._dummy = tf.get_variable("dummy", [embed_dim + 2], tf.float32,
initializer=tf.zeros_initializer)
self._infill_linear = snt.Linear(embed_dim + 2)
self._mask_embedding = tf.get_variable(
"mask", [embed_dim + 2], tf.float32, initializer=tf.zeros_initializer)
def _apply_transformers(self, lang_embedding, vision_embedding):
"""Applies transformer to language and vision input.
Args:
lang_embedding: tensor,
vision_embedding: tensor, "validation", or "test".
Returns:
tuple, output at dummy token, all output embeddings, infill loss
"""
def _unroll(tensor):
"""Unroll the time dimension into the object dimension."""
return tf.reshape(
tensor, [tensor.shape[0], -1, tensor.shape[3]])
words = append_ids(lang_embedding, [1, 0], axis=2)
dummy_word = tf.tile(self._dummy[None, None, :], [tf.shape(words)[0], 1, 1])
vision_embedding = append_ids(vision_embedding, [0, 1], axis=3)
vision_over_time = _unroll(vision_embedding)
transformer_input = tf.concat([dummy_word, words, vision_over_time], axis=1)
output, _ = self._memory_transformer(transformer_input,
is_training=False)
return output[:, 0, :]
def apply_model_descriptive(self, inputs):
"""Applies model to CLEVRER descriptive questions.
Args:
inputs: dict of form: {
"question": tf.int32 tensor of shape [batch, MAX_QUESTION_LENGTH],
"monet_latents": tf.float32 tensor of shape [batch, frames, 8, 16],
}
Returns:
Tensor of shape [batch, ANSWER_VOCAB_SIZE], representing logits for each
possible answer word.
"""
question = inputs["question"]
# Shape: [batch, question_len, embed_dim-2]
question_embedding = self._embed(question)
# Shape: [batch, question_len, embed_dim]
question_embedding = append_ids(question_embedding, [0, 1], 2)
choices_embedding = self._embed(
tf.zeros([question.shape[0], MAX_CHOICE_LENGTH], tf.int64))
choices_embedding = append_ids(choices_embedding, [0, 1], 2)
# Shape: [batch, choices, question_len + choice_len, embed_dim]
lang_embedding = tf.concat([question_embedding, choices_embedding], axis=1)
# Shape: [batch, frames, num_objects, embed_dim]
vision_embedding = inputs["monet_latents"]
if self._shuffle_objects:
vision_embedding = tf.transpose(vision_embedding, [2, 1, 0, 3])
vision_embedding = tf.random.shuffle(vision_embedding)
vision_embedding = tf.transpose(vision_embedding, [2, 1, 0, 3])
output = self._apply_transformers(lang_embedding, vision_embedding)
output = self._final_layer_descriptive(output)
return output
def apply_model_mc(self, inputs):
"""Applies model to CLEVRER multiple-choice questions.
Args:
inputs: dict of form: {
"question": tf.int32 tensor of shape [batch, MAX_QUESTION_LENGTH],
"choices": tf.int32 tensor of shape [batch, 4, MAX_CHOICE_LENGTH],
"monet_latents": tf.float32 tensor of shape [batch, frames, 8, 16],
}
Returns:
Tensor of shape [batch, 4], representing logits for each choice
"""
question = inputs["question"]
choices = inputs["choices"]
# Shape: [batch, question_len, embed_dim-2]
question_embedding = self._embed(question)
# Shape: [batch, question_len, embed_dim]
question_embedding = append_ids(question_embedding, [1, 0], 2)
# Shape: [batch, choices, choice_len, embed_dim-2]
choices_embedding = snt.BatchApply(self._embed)(choices)
# Shape: [batch, choices, choice_len, embed_dim]
choices_embedding = append_ids(choices_embedding, [0, 1], 3)
# Shape: [batch, choices, question_len + choice_len, embed_dim]
lang_embedding = tf.concat([
tf.tile(question_embedding[:, None],
[1, choices_embedding.shape[1], 1, 1]),
choices_embedding], axis=2)
# Shape: [batch, frames, num_objects, embed_dim]
vision_embedding = inputs["monet_latents"]
if self._shuffle_objects:
vision_embedding = tf.transpose(vision_embedding, [2, 1, 0, 3])
vision_embedding = tf.random.shuffle(vision_embedding)
vision_embedding = tf.transpose(vision_embedding, [2, 1, 0, 3])
output_per_choice = []
for c in range(NUM_CHOICES):
output = self._apply_transformers(
lang_embedding[:, c, :, :], vision_embedding)
output_per_choice.append(output)
output = tf.stack(output_per_choice, axis=1)
output = tf.squeeze(snt.BatchApply(self._final_layer_mc)(output), axis=2)
return output
|
deepmind-research-master
|
object_attention_for_reasoning/model.py
|
# Fork of Sonnet transformer model with small modifications
#
# Copyright 2017 The Sonnet Authors. 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.
# ============================================================================
"""Implementation of Transformer networks.
Size glossary:
* Batch size (B).
* Sequence length (N).
* Memory size (M). The size of the optional memory, passed in via `state`.
* Number of heads (H): the number of attention heads.
* Value size (V): the size of each value embedding per head.
* Key size (K): the size of each key embedding per head. Equally, the size
of each query embedding per head. Typically K <= V.
* Embedding size (HV). The size of the activation or embedding relating to
each input between layers. Equal to value_size * num_heads.
* All attention size (F). The size of all attention activations over every
head.
* QKV size (F / H): The size of the query, key and value per head. Equal to
2K + V or equivalently F / H.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as np
from sonnet.python.modules import base
from sonnet.python.modules import basic
from sonnet.python.modules import layer_norm as snt_ln
from sonnet.python.modules import util
from sonnet.python.modules.nets import mlp as snt_mlp
import tensorflow.compat.v1 as tf
AttentionState = collections.namedtuple('AttentionState',
('queries', 'keys', 'values', 'logits',
'weights', 'embeddings', 'read_words'))
CompressedMemoryState = collections.namedtuple(
'CompressedMemoryState', ('episodic_memory', 'compressed_memory', 'index'))
def rel_shift(position_logits):
"""Shifting of logits for relative attention.
Args:
position_logits: A tensor of shape [B, H, N, N + M].
Returns:
The shifted logits. Example, for input (H=1, B=1):
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
the function outputs:
[1, 0, 5, 4, 3]
[2, 1, 0, 5, 4]
[3, 2, 1, 0, 5]
[4, 3, 2, 1, 0]
[5, 4, 3, 2, 1]
Raises:
ValueError if position_logits is not 4D.
Note: this is not an exact shift as the upper triangle is non-zero. This
works as intended in the causally-masked case. If this is used with un-masked
attention, we'd want these to also be zero.
"""
if position_logits.get_shape().ndims != 4:
raise ValueError('Expected 4D position logits.')
input_shape = position_logits.shape
batch_size = input_shape[0]
num_heads = input_shape[1]
t1 = input_shape[2]
t2 = input_shape[3]
# We prepend zeros on the final timescale dimension.
to_pad = tf.zeros([batch_size, num_heads, t1, 1])
position_logits = tf.concat([to_pad, position_logits], -1)
# Reshape trick to shift input.
position_logits = tf.reshape(position_logits,
[batch_size, num_heads, t2 + 1, t1])
# Remove extra time dimension and re-shape.
position_logits = position_logits[:, :, 1:]
position_logits = tf.reshape(position_logits, input_shape)
return position_logits
def _layer_norm(inputs):
if inputs.get_shape().ndims > 2:
return basic.BatchApply(snt_ln.LayerNorm())(inputs)
else:
return snt_ln.LayerNorm()(inputs)
def _concat_and_slice(prev_memory, new_memory):
original_memory_size = prev_memory.get_shape().as_list()[1]
concat_memory = tf.concat([prev_memory, new_memory], 1)
memory = concat_memory[:, -original_memory_size:]
return memory, concat_memory
def simple_attention(queries, keys, values):
logits = tf.matmul(queries, keys, transpose_b=True)
weights = tf.nn.softmax(logits)
return tf.matmul(weights, values)
class ResidualDropoutWrapper(base.AbstractModule):
"""Wrapper class that applies residual connections, dropout and layer norm.
By default applies a relu to the module output before the other operations.
"""
def __init__(self,
layer,
dropout_rate,
layer_norm='input',
name='residual_dropout_wrapper'):
self._module = layer
self._dropout_rate = dropout_rate
self._layer_norm = layer_norm
super(ResidualDropoutWrapper, self).__init__(name=name)
def _build(self, inputs, *args, **kwargs):
if self._layer_norm in ('both', 'input'):
normed_inputs = _layer_norm(inputs)
else:
normed_inputs = inputs
module_output = self._module(normed_inputs, *args, **kwargs)
module_state = None
# If module outputs multiple items, assumes (output, state) tuple.
if isinstance(module_output, tuple):
module_output, module_state = module_output
if kwargs['is_training']: # kwargs must contain is_training.
module_output = tf.nn.dropout(module_output, rate=self._dropout_rate)
output = inputs + module_output
if self._layer_norm in ('both', 'output'):
output = _layer_norm(output)
if module_state is None:
return output
else:
return output, module_state
def future_mask(chunk_size, dtype):
"""Creates attention mask to ensure an element i cannot attend to j > i."""
square = tf.ones([chunk_size, chunk_size], dtype=dtype)
# Create upper diagonal matrix and remove diagonal entries (allow self-attn).
mask = tf.matrix_band_part(square, 0, -1) - tf.matrix_band_part(square, 0, 0)
# Multiply by -1e6 and expand to broadcast with [B, H, N, N] logits.
mask = -1e6 * tf.reshape(mask, [1, 1, chunk_size, chunk_size])
return mask
def _memory_size(state):
if isinstance(state, CompressedMemoryState):
return (state.episodic_memory.get_shape().as_list()[1] +
state.compressed_memory.get_shape().as_list()[1])
else:
return state.get_shape().as_list()[1]
def create_mask(inputs, state, equal_window):
"""Creates mask for future sequence positions.
Args:
inputs: inputs tensor of shape [B, N, D]
state: optional tensor of shape [B, M, D], CompressedMemoryState or a list
where the ith entry corresponds to the ith layer's state.
equal_window: if True, then each activation has an equally-sized attention
window of length 'M'. This only makes sense if a state is given.
Returns:
Float tensor of shape [1, 1, N, N + M], to be summed with logits.
"""
chunk_size = inputs.get_shape().as_list()[1]
dtype = inputs.dtype
mask = future_mask(chunk_size, dtype)
if state is not None:
if isinstance(state, (tuple, list)):
largest_memory_layer = np.argmax([_memory_size(s) for s in state])
state = state[largest_memory_layer]
mem_size = _memory_size(state)
mask = tf.concat(
[tf.zeros([1, 1, chunk_size, mem_size], dtype=dtype), mask], 3)
if equal_window:
attn_mask = tf.ones([chunk_size, chunk_size], dtype=dtype)
mask_dia = tf.cast(tf.matrix_band_part(attn_mask, 0, 0), dtype=dtype)
mask_l = tf.cast(tf.matrix_band_part(attn_mask, -1, 0), dtype=dtype)
start_mask = tf.reshape(mask_l - mask_dia,
[1, 1, chunk_size, chunk_size]) * -1e6
mask = tf.concat(
[mask[:, :, :, :chunk_size] + start_mask, mask[:, :, :, chunk_size:]],
3)
return mask
def default_mlp(hidden_sizes, activate_final=False, init_std=2., **kwargs):
"""Standard batch-applied MLP for transformer modules."""
init = {'w': tf.variance_scaling_initializer(init_std, distribution='normal')}
mlp = snt_mlp.MLP(
hidden_sizes,
activate_final=activate_final,
use_dropout=True,
initializers=init,
**kwargs)
return basic.BatchApply(mlp)
def get_position_encodings(sequence_length,
hidden_size,
clamp_value,
max_timescale=10000.,
min_timescale=2.0):
"""Creates sinusoidal encodings of shape [1, N + M, D]."""
# NOTE: when not using relative position encodings, min_timescale must be 2.0
# and hidden_size must be an even number. Otherwise, the dimensions do not
# match.
pos_seq = tf.range(sequence_length - 1, -1, -1.0)
if clamp_value > 0:
pos_seq = tf.minimum(pos_seq, clamp_value)
freqs = tf.range(0, hidden_size, min_timescale)
inv_freq = 1 / (max_timescale**(freqs / hidden_size))
sinusoid_inp = tf.einsum('i,j->ij', pos_seq, inv_freq)
pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], -1)
pos_emb = tf.expand_dims(pos_emb, 0)
output_dim = pos_emb.get_shape().as_list()[-1]
if output_dim != hidden_size:
raise ValueError(
'position embedding dimension ({}) does not match that of the input ({}).'
.format(output_dim, hidden_size))
return pos_emb
class MultiheadAttention(base.AbstractModule):
"""Implements multi-head attention with optional state context."""
def __init__(self,
value_size,
key_size,
num_heads,
mask=None,
scaling=True,
positional_encodings=None,
use_relative_positions=False,
init_std=2.,
name='multihead_attention'):
"""Creates a MultiheadAttention module.
Args:
value_size: V parameter. See size glossary in class docstring.
key_size: K parameter. See size glossary in class docstring.
num_heads: The number of independent queries per timestep.
mask: Optional mask to attention logits. This can prevent attending to
future positions or unused memory slots.
scaling: Whether to scale the attention logits.
positional_encodings: Either None (none given), or an iterable of
`(key_positional_encodings, query_positional_encodings)` tuples, where
the first encodings in the list indicate the oldest entries in memory
and the final encodings indicate the newest entries in memory and the
sequence.
use_relative_positions: If True then relative positions are incorporated,
vs absolute, into the attention logits. This is done exactly as
described in the TransformerXL, Dai et al. 2019.
init_std: scaling of standard deviation for weight matrices init.
name: Name of module.
"""
super(MultiheadAttention, self).__init__(name=name)
self._value_size = value_size
self._key_size = key_size
self._sizes = {
'value': self._value_size,
'key': self._key_size,
'query': self._key_size,
'relative_keys': self._key_size,
'relative_keys_0': self._key_size,
}
self._num_heads = num_heads
self._mask = mask
self._scaling = scaling
self._positional_encodings = positional_encodings
self._use_relative_positions = use_relative_positions
self._init = {'w': tf.variance_scaling_initializer(init_std)}
@util.reuse_variables
def multihead_linear(self, inputs, name):
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
hidden_size = self._sizes[name]
input_size = inputs.shape[-1].value
w = tf.get_variable(
'linear/w',
shape=[input_size, self._num_heads * hidden_size],
initializer=self._init['w'])
w = tf.reshape(w, [input_size, self._num_heads, hidden_size])
out = tf.einsum('bij,jhk->bhik', inputs, w)
return out
def _build(self,
inputs,
query_inputs=None,
state=None,
is_training=False,
dropout_keep_prob=0.5,
key_value_inputs=None):
"""Calculates multi-layer self attention.
Args:
inputs: Tensor of shape [batch_size, num_steps, output_dim_size]. Inputs
used as the query, key, and value to the attention layer.
query_inputs: optional Tensor of shape [batch_size, num_steps,
output_dim_size]. Query inputs to the attention layer. Set when
query_inputs is different from the inputs argument.
state: optional CompressedMemoryState or a Tensor of shape [batch_size,
memory_size, dim_size] concatenated to the inputs. Set when attend to
the memory from previous steps.
is_training: if currently training.
dropout_keep_prob: dropout rate applied to attention weights.
key_value_inputs: optional Tensor of shape [batch_size, num_steps,
output_dim_size]. It is used as the key and value of the multihead
attention. Set when the key and value are different from the inputs
argument.
Returns:
output: the result Tensor of shape
[batch_size, num_steps, output_dim_size].
attention_state: named tuple of AttentionState.
"""
if key_value_inputs is not None and state is not None:
raise ValueError('Only one of the key_value_input and state is needed.')
embedding_size = self._value_size * self._num_heads
q_inputs = inputs if query_inputs is None else query_inputs
# Denoted by L. If query_inputs is None, L = N.
_, query_size = q_inputs.get_shape().as_list()[:2]
if key_value_inputs is not None:
k_inputs = key_value_inputs
v_inputs = k_inputs
elif state is not None:
if isinstance(state, CompressedMemoryState):
state_memory_list = [state.compressed_memory, state.episodic_memory]
else:
state_memory_list = [state]
k_inputs = tf.concat(state_memory_list + [inputs], 1)
v_inputs = k_inputs
else:
k_inputs = inputs
v_inputs = inputs
# Batch size denoted by B
batch_size = tf.shape(inputs)[0]
# Chunk_size denoted by N
chunk_size = inputs.get_shape().as_list()[1]
# Denoted by N + M
att_size = k_inputs.get_shape().as_list()[1]
if self._positional_encodings and not self._use_relative_positions:
if len(self._positional_encodings) != 1:
raise ValueError(
'Absolute positional encodings only supported for 1 memory. '
'Found %i.' % len(self._positional_encodings))
key_positions, query_positions = self._positional_encodings[0]
k_inputs += key_positions
q_inputs += query_positions
# [B, H, L, K]
q = self.multihead_linear(q_inputs, 'query')
# [B, H, N + M, K]
k = self.multihead_linear(k_inputs, 'key')
# [B, H, N + M, V]
v = self.multihead_linear(v_inputs, 'value')
# Scaling the dot-product
if self._scaling:
q *= self._key_size**-0.5
# [B, H, L, N + M]
if self._use_relative_positions:
r_w_bias = tf.get_variable(
'r_w_bias', [1, self._num_heads, 1, self._key_size],
dtype=inputs.dtype)
content_logits = tf.matmul(q + r_w_bias, k, transpose_b=True)
all_relative_logits = []
# Loop over multiple positional encodings, for the case of multiple
# memory types.
for i, positional_encodings in enumerate(self._positional_encodings):
key_positions, query_positions = positional_encodings
if key_positions.get_shape().as_list()[-1] != att_size:
key_positions = key_positions[:, -att_size:] # Crop to layer mem size
is_final = i == len(self._positional_encodings) - 1
suffix = '' if is_final else '_%d' % i
relative_keys = self.multihead_linear(
key_positions, name='relative_keys' + suffix)
# [B, H, N, D]
r_r_bias = tf.get_variable(
'r_r_bias' + suffix, [1, self._num_heads, 1, self._key_size],
dtype=inputs.dtype)
relative_keys = tf.tile(relative_keys, [batch_size, 1, 1, 1])
relative_logits = tf.matmul(
q + r_r_bias, relative_keys, transpose_b=True)
relative_logits = rel_shift(relative_logits)
if not is_final: # Include relative positions for input sequence.
relative_logits = relative_logits[:, :, :, :-chunk_size]
all_relative_logits.append(relative_logits)
all_relative_logits = tf.concat(all_relative_logits, 3)
logits = content_logits + all_relative_logits
else:
# [B, H, N, N + M]
logits = tf.matmul(q, k, transpose_b=True)
content_logits = logits
if self._mask is not None:
if self._mask.get_shape().as_list()[-1] != att_size:
mask = self._mask[:, :, :, -att_size:]
else:
mask = self._mask
logits += mask
weights = tf.nn.softmax(logits)
if is_training:
weights = tf.nn.dropout(weights, dropout_keep_prob)
# [B, L, H, V], where V is value_size
output_transpose = tf.einsum('bhij,bhjk->bihk', weights, v)
# [B, L, H, V] -> [B, L, HV]
attended_inputs = basic.BatchReshape([query_size, embedding_size])(
output_transpose)
# Apply final mlp to mix information between heads.
output = basic.BatchApply(basic.Linear(embedding_size))(attended_inputs)
attention_state = AttentionState(
queries=q,
keys=k,
values=v,
weights=weights,
logits=content_logits,
embeddings=inputs,
read_words=output)
return output, attention_state
class TransformerTower(base.AbstractModule):
"""Transformer tower.
Deep residual network using blocks of attention and MLPs, specified in
Vaswani et al. 2017.
"""
def __init__(self,
value_size,
num_heads,
num_layers,
causal=True,
key_size=None,
shared_attention=False,
output_size=None,
mlp_hidden_sizes=tuple([1024]),
dropout_rate=0.1,
use_relative_positions=True,
clamp_time_range=0,
same_attention_length=False,
layer_norm='input',
name='transformer_tower'):
"""Initializes TransformerTower.
Args:
value_size: dimensionality of values per-head.
num_heads: number of attention heads.
num_layers: number of transformer blocks, where each block contains a
multi-head attention layer and an MLP.
causal: if True, applies a causal mask.
key_size: optional dimensionality of key size. If unspecified then it is
set to `value_size`.
shared_attention: if True, attention params are shared across all layers.
output_size: if set, the desired output dimensionality. By default the
output size is `value_size` x `num_heads`.
mlp_hidden_sizes: tuple containing dimensionality of mlp layer(s). If
multiple values are specified, the mlp contains multiple layers for each
transformer block.
dropout_rate: dropout rate applied to hidden activations, attention, and
positional encodings.
use_relative_positions: if False, applies absolute positional encodings.
If true, uses relative positional encodings from Dai et al. 2019.
clamp_time_range: clamps max temporal positional encoding if specified.
same_attention_length: if True, attention is masked to ensure each
position in the sequence contains the same length of attention.
layer_norm: Where to apply layer-norm in Transformer block. Can be one of
'input' (Vaswani et al. 2017), 'output', or 'both'.
name: name of variable scope.
"""
super(TransformerTower, self).__init__(name=name)
self._causal = causal
self._mask = None
if key_size is None:
key_size = value_size
self._key_size = key_size
self._value_size = value_size
self._shared_attention = shared_attention
self._num_heads = num_heads
self._num_layers = num_layers
self._output_size = output_size
self._embedding_size = self._value_size * self._num_heads
self._mlp_hidden_sizes = list(mlp_hidden_sizes) + [self._embedding_size]
self._multihead_attention = None
self._object_embeddings = None
self._dropout_rate = dropout_rate
self._positional_encodings = None
self._use_relative_positions = use_relative_positions
self._clamp_time_range = clamp_time_range
self._same_attention_length = same_attention_length
self._layer_norm = layer_norm
self._attention_modules = []
self._object_mlps = []
def get_sublayers(self, is_training):
if self._multihead_attention is None or not self._shared_attention:
attention_module = MultiheadAttention(
value_size=self._value_size,
key_size=self._key_size,
num_heads=self._num_heads,
mask=self._mask,
positional_encodings=self._positional_encodings,
use_relative_positions=self._use_relative_positions,
init_std=2. / np.sqrt(self._num_layers),
)
self._multihead_attention = ResidualDropoutWrapper(
attention_module, self._dropout_rate, layer_norm=self._layer_norm)
mlp = default_mlp(
self._mlp_hidden_sizes, init_std=2. / np.sqrt(self._num_layers))
object_mlp = ResidualDropoutWrapper(
mlp, self._dropout_rate, layer_norm=self._layer_norm)
self._attention_modules.append(attention_module)
self._object_mlps.append(mlp)
return self._multihead_attention, object_mlp
def _build(self,
inputs,
state=None,
condition=None,
is_training=True,
final_layer_key_value_inputs=None):
"""Calculates multi-layer self attention and mlp transformation.
Args:
inputs: Tensor of shape [batch_size, num_steps, dim_size].
state: optional list of length num_layers of tensors of shape
[batch_size, memory_size, dim_size].
condition: optional tensor to condition on. The shape is shape
[batch_size, dim_size].
is_training: If true, dropout is applied.
final_layer_key_value_inputs: optional Tensor to be used as the key and
value for the final multi-head attention layer of shape
[batch_size, num_steps, dim_size]. Useful when the tower is a Seq2Seq
decoder and it can attend to encoder outputs.
Returns:
output: tensor of shape [batch_size, num_steps, output_dim_size].
state: list of length `num_layers` containing AttentionState tuples.
"""
# inputs: [B, N, F]
if final_layer_key_value_inputs is not None and state is not None and len(
state) == (self._num_layers - 1):
raise ValueError('When the final_layer_key_value_input is set, exclude'
'the state of the last layer.')
if condition is not None:
condition_tile = tf.tile(
tf.expand_dims(condition, 1), [1, tf.shape(inputs)[1], 1])
inputs = tf.concat([inputs, condition_tile], -1)
# Map inputs to be of `embedding_size` dimension.
if inputs.get_shape().as_list()[-1] != self._embedding_size:
inputs = default_mlp([self._embedding_size], activate_final=True)(
inputs,
is_training=is_training,
dropout_keep_prob=1 - self._dropout_rate)
if state is None:
memory_sizes = [0]
elif isinstance(state[0], CompressedMemoryState):
cm_mem_size = max(_memory_size(s.compressed_memory) for s in state)
em_mem_size = max(_memory_size(s.episodic_memory) for s in state)
memory_sizes = [cm_mem_size, em_mem_size]
else:
memory_sizes = [max([_memory_size(s) for s in state])]
chunk_size = inputs.get_shape().as_list()[1]
self._positional_encodings = []
# Creates positional encodings for different memory types.
for i, memory_size in enumerate(memory_sizes):
seq_len = chunk_size + memory_size
key_positions = get_position_encodings(
sequence_length=seq_len,
hidden_size=inputs.get_shape().as_list()[2],
clamp_value=self._clamp_time_range,
)
if is_training:
key_positions = tf.nn.dropout(key_positions, rate=self._dropout_rate)
key_positions = tf.cast(key_positions, dtype=inputs.dtype)
query_positions = key_positions[:, -chunk_size:, :]
self._positional_encodings.append((key_positions, query_positions))
if self._causal:
self._mask = create_mask(inputs, state, self._same_attention_length)
layer_i_inputs = inputs
attention_states = []
key_value_inputs = None
for i in range(self._num_layers):
with tf.variable_scope('layer_%d' % i, reuse=tf.AUTO_REUSE):
multihead_attention, object_mlp = self.get_sublayers(is_training)
# Multihead attention with residuals.
state_i = None if state is None else state[i]
if i == (self._num_layers -
1) and final_layer_key_value_inputs is not None:
# When the final_layer_key_value_inputs is set, the finaly layer
# of attention will use it as the key & value, thus no need for state.
key_value_inputs = final_layer_key_value_inputs
state_i = None
attention_outputs, attention_state = multihead_attention(
layer_i_inputs,
state=state_i,
is_training=is_training,
dropout_keep_prob=1. - self._dropout_rate,
key_value_inputs=key_value_inputs)
attention_states.append(attention_state)
# Feed-forward with residuals.
output = object_mlp(
attention_outputs,
is_training=is_training,
dropout_keep_prob=1 - self._dropout_rate)
layer_i_inputs = output
if self._output_size is not None:
output = basic.BatchApply(
basic.Linear(self._output_size, use_bias=False))(
output)
return output, attention_states
def attention_module(self, i):
"""Returns the i-th layer attention module."""
return self._attention_modules[i]
|
deepmind-research-master
|
object_attention_for_reasoning/transformer.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.
"""Tokenizer implementation mapping strings to their UTF-8 bytes."""
from typing import Union
import numpy as np
class BytesTokenizer:
"""Tokenizes string to utf-8 bytes."""
def __init__(self):
self._num_reserved_tokens = 6 # PAD, BOS, EOS, MASK, CLS, SEP
def to_string(self, inputs: np.ndarray) -> str:
inputs_no_special = (
inputs[inputs >= self._num_reserved_tokens] - self._num_reserved_tokens)
decoded_bytes = inputs_no_special.astype(np.uint8).tobytes()
return decoded_bytes.decode('utf-8', errors='replace')
def to_int(self, inputs: Union[str, bytes]) -> np.ndarray:
if isinstance(inputs, str):
inputs = inputs.encode('utf-8')
encoded = np.frombuffer(inputs, np.uint8).astype(np.int32)
encoded = encoded + self._num_reserved_tokens
return encoded.astype(np.int32)
@property
def vocab_size(self) -> int:
return 256 + self._num_reserved_tokens
@property
def pad_token(self) -> int:
return 0
@property
def bos_token(self) -> int:
return 1
@property
def eos_token(self) -> int:
return 2
@property
def mask_token(self) -> int:
return 3
@property
def cls_token(self) -> int:
return 4
@property
def sep_token(self) -> int:
return 5
|
deepmind-research-master
|
perceiver/bytes_tokenizer.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.
"""Perceiver architecture and components."""
import abc
import math
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
from perceiver import io_processors
from perceiver import position_encoding
# -----------------------------------------------------------
# ---------------------- Primitives -----------------------
# -----------------------------------------------------------
def attend(q, k, v, dropout_prob=0.0, attention_mask=None):
"""Computes multi-head attention using a query, key and value.
Args:
q: Query with shape [batch, q_indices, num_heads, head_dim].
k: Key with shape [batch, kv_indices, num_heads, head_dim].
v: Value with shape [batch, kv_indices, num_heads, head_dim].
dropout_prob: dropout probability on the attention weights.
attention_mask: Array of shape [batch, q_indices, kv_indices] indicating
which attentions are valid
Returns:
Output of the attention with shape [batch, q_indices, hiddens]
"""
batch, q_indices, num_heads, q_head_dim = q.shape
_, _, _, v_head_dim = v.shape
hiddens = num_heads * v_head_dim
attention = jnp.einsum('bthd,bThd->bhtT', q, k)
scale = 1. / math.sqrt(q_head_dim)
attention *= scale
if attention_mask is not None:
# Use large_k instead of np.NINF because np.NINF breaks for causal-masked
# left-padded sampling.
large_k = jnp.array(1e4 if attention.dtype == jnp.float16 else 1e30,
dtype=attention.dtype)
attention = jnp.where(attention_mask[:, None, :, :], attention,
-large_k)
normalized = jax.nn.softmax(attention)
if dropout_prob > 0:
normalized = hk.dropout(hk.next_rng_key(), dropout_prob, normalized)
summed = jnp.einsum('bhtT,bThd->bthd', normalized, v)
summed = jnp.reshape(summed, [batch, q_indices, hiddens])
if attention_mask is not None:
# If all attended tokens are masked, or for masked tokens
# some rows of logits gets completely masked, in which case the softmax
# gives a uniform row and we obtain non-zero outputs where it should be
# zero. We force zeros.
wipe_attn = jnp.all(
attention_mask == 0, axis=2, keepdims=True) # shape (B, T, 1)
summed = jnp.where(wipe_attn, jnp.zeros_like(summed), summed)
return summed
def conv_1d(
output_channels,
init_scale=1.0,
with_bias=True,
name=None):
"""A 1D convolution."""
return hk.Linear(
output_size=output_channels,
with_bias=with_bias,
w_init=hk.initializers.VarianceScaling(init_scale),
name=name)
def layer_norm(x, name=None):
return hk.LayerNorm(axis=-1, create_scale=True, create_offset=True,
name=name)(x)
def make_cross_attention_mask(query_mask, kv_mask):
batch_size, query_len = query_mask.shape
_, key_len = kv_mask.shape
mask = jax.vmap(jnp.outer)(query_mask, kv_mask)
assert mask.shape == (batch_size, query_len, key_len)
return mask
# -----------------------------------------------------------
# ----------------------- Modules -------------------------
# -----------------------------------------------------------
class Attention(hk.Module):
"""Multi-headed {cross, self}-attention."""
def __init__(self,
num_heads=8,
init_scale=1.0,
with_final_bias=True,
final_init_scale_multiplier=1.,
dropout_prob=0.0,
qk_channels=None,
v_channels=None,
output_channels=None,
name=None):
super(Attention, self).__init__(name=name)
self._num_heads = num_heads
self._init_scale = init_scale
self._with_final_bias = with_final_bias
self._final_init_scale = final_init_scale_multiplier * init_scale
self._dropout_prob = dropout_prob
# If none of these are passed, the Q input determines the output shape:
self._qk_channels = qk_channels
self._v_channels = v_channels
self._output_channels = output_channels
def __call__(self, inputs_q, inputs_kv, attention_mask=None):
# Q and K must have the same number of channels.
# Default to preserving Q's input's shape.
if self._qk_channels is None:
self._qk_channels = inputs_q.shape[-1]
# V's num_channels determines the shape of the output of QKV-attention.
# Default to the same number of channels used in the key-query operation.
if self._v_channels is None:
self._v_channels = self._qk_channels
# Project the output of QKV attention to a desired number of channels.
# Default to the same number as the output of the QKV attention operation.
if self._output_channels is None:
self._output_channels = self._v_channels
if self._qk_channels % self._num_heads != 0:
raise ValueError(f'qk_channels ({self._qk_channels}) must be divisible by'
f' num_heads ({self._num_heads}).')
if self._v_channels % self._num_heads != 0:
raise ValueError(f'v_channels ({self._v_channels}) must be divisible by'
f' num_heads ({self._num_heads}).')
qk_channels_per_head = self._qk_channels // self._num_heads
v_channels_per_head = self._v_channels // self._num_heads
# Project QKV to a common feature dimension.
q = conv_1d(self._qk_channels, init_scale=self._init_scale)(inputs_q)
k = conv_1d(self._qk_channels, init_scale=self._init_scale)(inputs_kv)
v = conv_1d(self._v_channels, init_scale=self._init_scale)(inputs_kv)
# Reshape channels for multi-head attention.
batch, q_time, _ = q.shape
_, kv_time, _ = k.shape
q = jnp.reshape(q, [batch, q_time, self._num_heads, qk_channels_per_head])
k = jnp.reshape(k, [batch, kv_time, self._num_heads, qk_channels_per_head])
v = jnp.reshape(v, [batch, kv_time, self._num_heads, v_channels_per_head])
result = attend(q, k, v, dropout_prob=self._dropout_prob,
attention_mask=attention_mask)
return conv_1d(
self._output_channels,
with_bias=self._with_final_bias,
init_scale=self._final_init_scale)(result)
class MLP(hk.Module):
"""A Transformer-style dense module to follow attention."""
def __init__(self,
widening_factor=4,
dropout_prob=0.0,
init_scale=1.,
name=None):
super(MLP, self).__init__(name=name)
self._widening_factor = widening_factor
self._dropout_prob = dropout_prob
self._init_scale = init_scale
def __call__(self, x, *, is_training):
dropout_prob = self._dropout_prob if is_training else 0.0
output_channels = x.shape[-1]
x = conv_1d(
output_channels=self._widening_factor * output_channels,
init_scale=self._init_scale)(x)
x = jax.nn.gelu(x)
x = conv_1d(
output_channels=output_channels,
init_scale=self._init_scale)(x)
return hk.dropout(hk.next_rng_key(), dropout_prob, x)
class SelfAttention(hk.Module):
"""A self-attention module, including a dense block."""
def __init__(self,
widening_factor=4,
dropout_prob=0.0,
dropout_attn_prob=0.0,
num_heads=8,
att_init_scale=1.0,
dense_init_scale=1.0,
qk_channels=None,
v_channels=None,
name=None):
super(SelfAttention, self).__init__(name=name)
self._widening_factor = widening_factor
self._dropout_prob = dropout_prob
self._dropout_attn_prob = dropout_attn_prob
self._num_heads = num_heads
self._att_init_scale = att_init_scale
self._dense_init_scale = dense_init_scale
self._qk_channels = qk_channels
self._v_channels = v_channels
def __call__(self,
inputs,
*,
attention_mask=None,
is_training):
dropout_prob = self._dropout_prob if is_training else 0.0
dropout_attn_prob = self._dropout_attn_prob if is_training else 0.0
x = inputs
qkv_inputs = layer_norm(inputs)
attention = Attention(
num_heads=self._num_heads,
init_scale=self._att_init_scale,
qk_channels=self._qk_channels,
v_channels=self._v_channels,
dropout_prob=dropout_attn_prob)(qkv_inputs, qkv_inputs,
attention_mask=attention_mask)
attention = hk.dropout(hk.next_rng_key(), dropout_prob, attention)
x += attention
x += MLP(
widening_factor=self._widening_factor,
dropout_prob=dropout_prob,
init_scale=self._dense_init_scale)(
layer_norm(x), is_training=is_training)
return x
class CrossAttention(hk.Module):
"""A cross-attention module, including a dense block."""
def __init__(self,
widening_factor=1,
dropout_prob=0.0,
dropout_attn_prob=0.0,
num_heads=8,
att_init_scale=1.0,
dense_init_scale=1.0,
shape_for_attn='kv',
use_query_residual=True,
qk_channels=None,
v_channels=None,
name=None):
super(CrossAttention, self).__init__(name=name)
self._widening_factor = widening_factor
self._dropout_prob = dropout_prob
self._dropout_attn_prob = dropout_attn_prob
self._num_heads = num_heads
self._att_init_scale = att_init_scale
self._dense_init_scale = dense_init_scale
self._shape_for_attn = shape_for_attn
self._use_query_residual = use_query_residual
self._qk_channels = qk_channels
self._v_channels = v_channels
def __call__(self,
inputs_q,
inputs_kv,
*,
attention_mask=None,
is_training):
dropout_prob = self._dropout_prob if is_training else 0.0
dropout_attn_prob = self._dropout_attn_prob if is_training else 0.0
output_channels = inputs_q.shape[-1]
if self._shape_for_attn == 'q':
qk_channels = inputs_q.shape[-1]
elif self._shape_for_attn == 'kv':
qk_channels = inputs_kv.shape[-1]
else:
raise ValueError(f'Unknown value {self._shape_for_attn} for '
'shape_for_attention.')
v_channels = None
if self._qk_channels is not None:
qk_channels = self._qk_channels
if self._v_channels is not None:
v_channels = self._v_channels
attention = Attention(
num_heads=self._num_heads,
init_scale=self._att_init_scale,
dropout_prob=dropout_attn_prob,
qk_channels=qk_channels,
v_channels=v_channels,
output_channels=output_channels)(layer_norm(inputs_q),
layer_norm(inputs_kv),
attention_mask=attention_mask)
attention = hk.dropout(hk.next_rng_key(), dropout_prob, attention)
# Optionally include a residual to the query.
# Consider omitting the residual if the semantics of query and output
# are different, e.g. if queries are positions and outputs are pixels.
if self._use_query_residual:
x = inputs_q + attention
else:
x = attention
x += MLP(
widening_factor=self._widening_factor,
dropout_prob=dropout_prob,
init_scale=self._dense_init_scale)(
layer_norm(x), is_training=is_training)
return x
# -----------------------------------------------------------
# ----------------------- Perceiver -----------------------
# -----------------------------------------------------------
class Perceiver(hk.Module):
"""The Perceiver: a scalable, fully attentional architecture."""
def __init__(
self,
encoder,
decoder,
input_preprocessor=None,
output_postprocessor=None,
name='perceiver'):
super().__init__(name=name)
# Feature and task parameters:
self._input_preprocessor = input_preprocessor
self._output_postprocessor = output_postprocessor
self._decoder = decoder
self._encoder = encoder
def __call__(self, inputs, *, is_training, subsampled_output_points=None,
pos=None, input_mask=None, query_mask=None):
if self._input_preprocessor:
network_input_is_1d = self._encoder._input_is_1d
inputs, modality_sizes, inputs_without_pos = self._input_preprocessor(
inputs, pos=pos, is_training=is_training,
network_input_is_1d=network_input_is_1d)
else:
modality_sizes = None
inputs_without_pos = None
# Get the queries for encoder and decoder cross-attends.
encoder_query = self._encoder.latents(inputs)
decoder_query = self._decoder.decoder_query(
inputs, modality_sizes, inputs_without_pos,
subsampled_points=subsampled_output_points)
# Run the network forward:
z = self._encoder(inputs, encoder_query,
is_training=is_training, input_mask=input_mask)
_, output_modality_sizes = self._decoder.output_shape(
inputs)
output_modality_sizes = output_modality_sizes or modality_sizes
outputs = self._decoder(
decoder_query, z, is_training=is_training, query_mask=query_mask)
if self._output_postprocessor:
outputs = self._output_postprocessor(outputs, is_training=is_training,
modality_sizes=output_modality_sizes)
return outputs
class PerceiverEncoder(hk.Module):
"""The Perceiver Encoder: a scalable, fully attentional encoder."""
def __init__(
self,
# The encoder has a total of
# num_self_attends_per_block * num_blocks
# self-attend layers. We share weights between blocks.
num_self_attends_per_block=6,
num_blocks=8,
z_index_dim=512,
num_z_channels=1024,
qk_channels=None,
v_channels=None,
num_cross_attend_heads=1,
num_self_attend_heads=8,
cross_attend_widening_factor=1,
self_attend_widening_factor=1,
dropout_prob=0.0,
z_pos_enc_init_scale=0.02,
cross_attention_shape_for_attn='kv',
use_query_residual=True,
name='perceiver_encoder'):
super().__init__(name=name)
# Check that we can use multihead-attention with these shapes.
if num_z_channels % num_self_attend_heads != 0:
raise ValueError(f'num_z_channels ({num_z_channels}) must be divisible by'
f' num_self_attend_heads ({num_self_attend_heads}).')
if num_z_channels % num_cross_attend_heads != 0:
raise ValueError(f'num_z_channels ({num_z_channels}) must be divisible by'
f' num_cross_attend_heads ({num_cross_attend_heads}).')
self._input_is_1d = True
self._num_blocks = num_blocks
# Construct the latent array initial state.
self.z_pos_enc = position_encoding.TrainablePositionEncoding(
index_dim=z_index_dim,
num_channels=num_z_channels,
init_scale=z_pos_enc_init_scale)
# Construct the cross attend:
self.cross_attend = CrossAttention(
dropout_prob=dropout_prob,
num_heads=num_cross_attend_heads,
widening_factor=cross_attend_widening_factor,
shape_for_attn=cross_attention_shape_for_attn,
qk_channels=qk_channels,
v_channels=v_channels,
use_query_residual=use_query_residual)
# Construct the block of self-attend layers.
# We get deeper architectures by applying this block more than once.
self.self_attends = []
for _ in range(num_self_attends_per_block):
self_attend = SelfAttention(
num_heads=num_self_attend_heads,
dropout_prob=dropout_prob,
qk_channels=qk_channels,
v_channels=v_channels,
widening_factor=self_attend_widening_factor)
self.self_attends.append(self_attend)
def latents(self, inputs):
# Initialize the latent array for the initial cross-attend.
return self.z_pos_enc(batch_size=inputs.shape[0])
def __call__(self, inputs, z, *, is_training, input_mask=None):
attention_mask = None
if input_mask is not None:
attention_mask = make_cross_attention_mask(
query_mask=jnp.ones(z.shape[:2], dtype=jnp.int32),
kv_mask=input_mask)
z = self.cross_attend(z, inputs, is_training=is_training,
attention_mask=attention_mask)
for _ in range(self._num_blocks):
for self_attend in self.self_attends:
z = self_attend(z, is_training=is_training)
return z
class AbstractPerceiverDecoder(hk.Module, metaclass=abc.ABCMeta):
"""Abstract Perceiver decoder."""
@abc.abstractmethod
def decoder_query(self, inputs, modality_sizes=None, inputs_without_pos=None,
subsampled_points=None):
raise NotImplementedError
@abc.abstractmethod
def output_shape(self, inputs):
raise NotImplementedError
@abc.abstractmethod
def __call__(self, query, z, *, is_training, query_mask=None):
raise NotImplementedError
class ProjectionDecoder(AbstractPerceiverDecoder):
"""Baseline projection decoder (no cross-attention)."""
def __init__(
self,
num_classes,
final_avg_before_project=False,
name='projection_decoder'):
super().__init__(name=name)
self._final_avg_before_project = final_avg_before_project
self._num_classes = num_classes
self.final_layer = hk.Linear(
num_classes, w_init=jnp.zeros, name='logits')
def decoder_query(self, inputs, modality_sizes=None, inputs_without_pos=None,
subsampled_points=None):
return None
def output_shape(self, inputs):
return ((inputs.shape[0], self._num_classes), None)
def __call__(self, query, z, *, is_training, query_mask=None):
# b x n_z x c -> b x c
z = jnp.mean(z, axis=1, dtype=z.dtype)
# b x c -> b x n_logits
logits = self.final_layer(z)
return logits
class BasicDecoder(AbstractPerceiverDecoder):
"""Cross-attention-based decoder."""
def __init__(self,
output_num_channels,
position_encoding_type='trainable',
# Ignored if position_encoding_type == 'none':
output_index_dims=None,
subsampled_index_dims=None,
num_z_channels=1024,
qk_channels=None,
v_channels=None,
use_query_residual=False,
output_w_init=None,
concat_preprocessed_input=False,
num_heads=1,
name='basic_decoder',
final_project=True,
**position_encoding_kwargs):
super().__init__(name=name)
self._position_encoding_type = position_encoding_type
# If `none`, the decoder will not construct any position encodings.
# You should construct your own when quering the decoder.
self.output_pos_enc = None
if self._position_encoding_type != 'none':
self.output_pos_enc = position_encoding.build_position_encoding(
position_encoding_type,
index_dims=output_index_dims,
**position_encoding_kwargs)
self._output_index_dim = output_index_dims
if subsampled_index_dims is None:
subsampled_index_dims = output_index_dims
self._subsampled_index_dims = subsampled_index_dims
self._output_num_channels = output_num_channels
self._output_w_init = output_w_init
self._use_query_residual = use_query_residual
self._qk_channels = qk_channels
self._v_channels = v_channels
self._final_project = final_project
self._num_heads = num_heads
self._concat_preprocessed_input = concat_preprocessed_input
def output_shape(self, inputs):
return ((inputs[0], self._subsampled_index_dims, self._output_num_channels),
None)
def decoder_query(self, inputs, modality_sizes=None,
inputs_without_pos=None, subsampled_points=None):
assert self._position_encoding_type != 'none' # Queries come from elsewhere
if subsampled_points is not None:
# unravel_index returns a tuple (x_idx, y_idx, ...)
# stack to get the [n, d] tensor of coordinates
pos = jnp.stack(
jnp.unravel_index(subsampled_points, self._output_index_dim),
axis=1)
# Map these coordinates to [-1, 1]
pos = -1 + 2 * pos / jnp.array(self._output_index_dim)[None, :]
pos = jnp.broadcast_to(pos[None],
[inputs.shape[0], pos.shape[0], pos.shape[1]])
pos_emb = self.output_pos_enc(
batch_size=inputs.shape[0],
pos=pos)
pos_emb = jnp.reshape(pos_emb, [pos_emb.shape[0], -1, pos_emb.shape[-1]])
else:
pos_emb = self.output_pos_enc(batch_size=inputs.shape[0])
if self._concat_preprocessed_input:
if inputs_without_pos is None:
raise ValueError('Value is required for inputs_without_pos if'
' concat_preprocessed_input is True')
pos_emb = jnp.concatenate([inputs_without_pos, pos_emb], axis=-1)
return pos_emb
def __call__(self, query, z, *, is_training,
query_mask=None):
# Cross-attention decoding.
# key, value: B x N x K; query: B x M x K
# Attention maps -> B x N x M
# Output -> B x M x K
# Construct cross attention and linear layer lazily, in case we don't need
# them.
attention_mask = None
if query_mask is not None:
attention_mask = make_cross_attention_mask(
query_mask=query_mask,
kv_mask=jnp.ones(z.shape[:2], dtype=jnp.int32))
decoding_cross_attn = CrossAttention(
dropout_prob=0.0,
num_heads=self._num_heads,
widening_factor=1,
shape_for_attn='kv',
qk_channels=self._qk_channels,
v_channels=self._v_channels,
use_query_residual=self._use_query_residual)
final_layer = hk.Linear(
self._output_num_channels, w_init=self._output_w_init, name='output')
output = decoding_cross_attn(query, z, is_training=is_training,
attention_mask=attention_mask)
if self._final_project:
output = final_layer(output)
return output
class ClassificationDecoder(AbstractPerceiverDecoder):
"""Cross-attention based classification decoder.
Light-weight wrapper of `BasicDecoder` for logit output.
"""
def __init__(self,
num_classes,
name='classification_decoder',
**decoder_kwargs):
super().__init__(name=name)
self._num_classes = num_classes
self.decoder = BasicDecoder(
output_index_dims=(1,), # Predict a single logit array.
output_num_channels=num_classes,
**decoder_kwargs)
def decoder_query(self, inputs, modality_sizes=None,
inputs_without_pos=None, subsampled_points=None):
return self.decoder.decoder_query(inputs, modality_sizes,
inputs_without_pos,
subsampled_points=subsampled_points)
def output_shape(self, inputs):
return (inputs.shape[0], self._num_classes), None
def __call__(self, query, z, *, is_training, query_mask=None):
# B x 1 x num_classes -> B x num_classes
logits = self.decoder(query, z, is_training=is_training)
return logits[:, 0, :]
class MultimodalDecoder(AbstractPerceiverDecoder):
"""Multimodal decoding by composing uni-modal decoders.
The modalities argument of the constructor is a dictionary mapping modality
name to the decoder of that modality. That decoder will be used to construct
queries for that modality. However, there is a shared cross attention across
all modalities, using the concatenated per-modality query vectors.
"""
def __init__(self, modalities, num_outputs, output_num_channels,
min_padding_size=2,
subsampled_index_dims=None,
name='multimodal_decoder', **decoder_kwargs):
super().__init__(name=name)
self._modalities = modalities
self._subsampled_index_dims = subsampled_index_dims
self._min_padding_size = min_padding_size
self._output_num_channels = output_num_channels
self._num_outputs = num_outputs
self._decoder = BasicDecoder(
output_index_dims=(num_outputs,),
output_num_channels=output_num_channels,
position_encoding_type='none',
**decoder_kwargs)
def decoder_query(self, inputs, modality_sizes, inputs_without_pos=None, # pytype: disable=signature-mismatch # overriding-parameter-count-checks
subsampled_points=None):
# Partition the flat inputs among the different modalities
inputs = io_processors.restructure(modality_sizes, inputs)
# Obtain modality-specific decoders' queries
subsampled_points = subsampled_points or dict()
decoder_queries = dict()
for modality, decoder in self._modalities.items():
# Get input_without_pos for this modality if it exists.
input_without_pos = None
if inputs_without_pos is not None:
input_without_pos = inputs_without_pos.get(modality, None)
decoder_queries[modality] = decoder.decoder_query(
inputs=inputs[modality],
modality_sizes=None,
inputs_without_pos=input_without_pos,
subsampled_points=subsampled_points.get(modality, None)
)
# Pad all queries with trainable position encodings to make them
# have the same channels
num_channels = (max(query.shape[2] for query in decoder_queries.values())
+ self._min_padding_size)
def embed(modality, x):
x = jnp.reshape(x, [x.shape[0], np.prod(x.shape[1:-1]), x.shape[-1]])
pos = position_encoding.TrainablePositionEncoding(
1, num_channels=num_channels - x.shape[2],
init_scale=0.02, name=f'{modality}_padding')(x.shape[0])
pos = jnp.broadcast_to(
pos, [x.shape[0], x.shape[1], num_channels - x.shape[2]])
return jnp.concatenate([x, pos], axis=2)
# Apply a predictable ordering to the modalities
return jnp.concatenate([
embed(modality, decoder_queries[modality])
for modality in sorted(self._modalities.keys())
], axis=1)
def output_shape(self, inputs):
if self._subsampled_index_dims is not None:
subsampled_index_dims = sum(self._subsampled_index_dims.values())
else:
subsampled_index_dims = self._num_outputs
return ((inputs.shape[0], subsampled_index_dims, self._output_num_channels),
self._subsampled_index_dims)
def __call__(self, query, z, *, is_training, query_mask=None):
# B x 1 x num_classes -> B x num_classes
return self._decoder(query, z, is_training=is_training)
class BasicVideoAutoencodingDecoder(AbstractPerceiverDecoder):
"""Cross-attention based video-autoencoding decoder.
Light-weight wrapper of `BasicDecoder` with video reshaping logic.
"""
def __init__(self,
output_shape,
position_encoding_type,
name='basic_video_autoencoding_decoder',
**decoder_kwargs):
super().__init__(name=name)
if len(output_shape) != 4: # B, T, H, W
raise ValueError(f'Expected rank 4 output_shape, got {output_shape}.')
# Build the decoder components:
self._output_shape = output_shape
self._output_num_channels = decoder_kwargs['output_num_channels']
self.decoder = BasicDecoder(
output_index_dims=self._output_shape[1:4], # T*H*W
position_encoding_type=position_encoding_type,
**decoder_kwargs)
def decoder_query(self, inputs, modality_sizes=None,
inputs_without_pos=None, subsampled_points=None):
return self.decoder.decoder_query(inputs,
modality_sizes=modality_sizes,
inputs_without_pos=inputs_without_pos,
subsampled_points=subsampled_points)
def output_shape(self, inputs):
return ([inputs.shape[0]] + self._output_shape[1:] +
[self._output_num_channels], None)
def __call__(self, query, z, *, is_training, query_mask=None):
output = self.decoder(query, z, is_training=is_training)
output = jnp.reshape(output, self._output_shape + [output.shape[-1]])
return output
class FlowDecoder(AbstractPerceiverDecoder):
"""Cross-attention based flow decoder."""
def __init__(self,
output_image_shape,
output_num_channels=2,
rescale_factor=100.0,
name='flow_decoder',
**decoder_kwargs):
super().__init__(name=name)
self._output_image_shape = output_image_shape
self._output_num_channels = output_num_channels
self._rescale_factor = rescale_factor
self.decoder = BasicDecoder(
output_num_channels=output_num_channels,
**decoder_kwargs)
def output_shape(self, inputs):
# The channel dimensions of output here don't necessarily correspond to
# (u, v) of flow: they may contain dims needed for the post-processor.
return ((inputs.shape[0],) + tuple(self._output_image_shape) + (
self._output_num_channels,), None)
def decoder_query(
self, inputs, modality_sizes=None, inputs_without_pos=None,
subsampled_points=None):
if subsampled_points is not None:
raise ValueError("FlowDecoder doesn't support subsampling yet.")
# assumes merged in time
return inputs
def __call__(self, query, z, *, is_training, query_mask=None):
# Output flow and rescale.
preds = self.decoder(query, z, is_training=is_training)
preds /= self._rescale_factor
return preds.reshape([preds.shape[0]] + list(self._output_image_shape) +
[preds.shape[-1]])
|
deepmind-research-master
|
perceiver/perceiver.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.
"""Position encodings and utilities."""
import abc
import functools
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
def generate_fourier_features(
pos, num_bands, max_resolution=(224, 224),
concat_pos=True, sine_only=False):
"""Generate a Fourier frequency position encoding with linear spacing.
Args:
pos: The position of n points in d dimensional space.
A jnp array of shape [n, d].
num_bands: The number of bands (K) to use.
max_resolution: The maximum resolution (i.e. the number of pixels per dim).
A tuple representing resolution for each dimension
concat_pos: Concatenate the input position encoding to the Fourier features?
sine_only: Whether to use a single phase (sin) or two (sin/cos) for each
frequency band.
Returns:
embedding: A 1D jnp array of shape [n, n_channels]. If concat_pos is True
and sine_only is False, output dimensions are ordered as:
[dim_1, dim_2, ..., dim_d,
sin(pi*f_1*dim_1), ..., sin(pi*f_K*dim_1), ...,
sin(pi*f_1*dim_d), ..., sin(pi*f_K*dim_d),
cos(pi*f_1*dim_1), ..., cos(pi*f_K*dim_1), ...,
cos(pi*f_1*dim_d), ..., cos(pi*f_K*dim_d)],
where dim_i is pos[:, i] and f_k is the kth frequency band.
"""
min_freq = 1.0
# Nyquist frequency at the target resolution:
freq_bands = jnp.stack([
jnp.linspace(min_freq, res / 2, num=num_bands, endpoint=True)
for res in max_resolution], axis=0)
# Get frequency bands for each spatial dimension.
# Output is size [n, d * num_bands]
per_pos_features = pos[:, :, None] * freq_bands[None, :, :]
per_pos_features = jnp.reshape(per_pos_features,
[-1, np.prod(per_pos_features.shape[1:])])
if sine_only:
# Output is size [n, d * num_bands]
per_pos_features = jnp.sin(jnp.pi * (per_pos_features))
else:
# Output is size [n, 2 * d * num_bands]
per_pos_features = jnp.concatenate(
[jnp.sin(jnp.pi * per_pos_features),
jnp.cos(jnp.pi * per_pos_features)], axis=-1)
# Concatenate the raw input positions.
if concat_pos:
# Adds d bands to the encoding.
per_pos_features = jnp.concatenate([pos, per_pos_features], axis=-1)
return per_pos_features
def build_linear_positions(index_dims, output_range=(-1.0, 1.0)):
"""Generate an array of position indices for an N-D input array.
Args:
index_dims: The shape of the index dimensions of the input array.
output_range: The min and max values taken by each input index dimension.
Returns:
A jnp array of shape [index_dims[0], index_dims[1], .., index_dims[-1], N].
"""
def _linspace(n_xels_per_dim):
return jnp.linspace(
output_range[0], output_range[1],
num=n_xels_per_dim,
endpoint=True, dtype=jnp.float32)
dim_ranges = [
_linspace(n_xels_per_dim) for n_xels_per_dim in index_dims]
array_index_grid = jnp.meshgrid(*dim_ranges, indexing='ij')
return jnp.stack(array_index_grid, axis=-1)
class AbstractPositionEncoding(hk.Module, metaclass=abc.ABCMeta):
"""Abstract Perceiver decoder."""
@abc.abstractmethod
def __call__(self, batch_size, pos):
raise NotImplementedError
class TrainablePositionEncoding(AbstractPositionEncoding):
"""Trainable position encoding."""
def __init__(self, index_dim, num_channels=128, init_scale=0.02, name=None):
super(TrainablePositionEncoding, self).__init__(name=name)
self._index_dim = index_dim
self._num_channels = num_channels
self._init_scale = init_scale
def __call__(self, batch_size, pos=None):
del pos # Unused.
pos_embs = hk.get_parameter(
'pos_embs', [self._index_dim, self._num_channels],
init=hk.initializers.TruncatedNormal(stddev=self._init_scale))
if batch_size is not None:
pos_embs = jnp.broadcast_to(
pos_embs[None, :, :], (batch_size,) + pos_embs.shape)
return pos_embs
def _check_or_build_spatial_positions(pos, index_dims, batch_size):
"""Checks or builds spatial position features (x, y, ...).
Args:
pos: None, or an array of position features. If None, position features
are built. Otherwise, their size is checked.
index_dims: An iterable giving the spatial/index size of the data to be
featurized.
batch_size: The batch size of the data to be featurized.
Returns:
An array of position features, of shape [batch_size, prod(index_dims)].
"""
if pos is None:
pos = build_linear_positions(index_dims)
pos = jnp.broadcast_to(pos[None], (batch_size,) + pos.shape)
pos = jnp.reshape(pos, [batch_size, np.prod(index_dims), -1])
else:
# Just a warning label: you probably don't want your spatial features to
# have a different spatial layout than your pos coordinate system.
# But feel free to override if you think it'll work!
assert pos.shape[-1] == len(index_dims)
return pos
class FourierPositionEncoding(AbstractPositionEncoding):
"""Fourier (Sinusoidal) position encoding."""
def __init__(self, index_dims, num_bands, concat_pos=True,
max_resolution=None, sine_only=False, name=None):
super(FourierPositionEncoding, self).__init__(name=name)
self._num_bands = num_bands
self._concat_pos = concat_pos
self._sine_only = sine_only
self._index_dims = index_dims
# Use the index dims as the maximum resolution if it's not provided.
self._max_resolution = max_resolution or index_dims
def __call__(self, batch_size, pos=None):
pos = _check_or_build_spatial_positions(pos, self._index_dims, batch_size)
build_ff_fn = functools.partial(
generate_fourier_features,
num_bands=self._num_bands,
max_resolution=self._max_resolution,
concat_pos=self._concat_pos,
sine_only=self._sine_only)
return jax.vmap(build_ff_fn, 0, 0)(pos)
class PositionEncodingProjector(AbstractPositionEncoding):
"""Projects a position encoding to a target size."""
def __init__(self, output_size, base_position_encoding, name=None):
super(PositionEncodingProjector, self).__init__(name=name)
self._output_size = output_size
self._base_position_encoding = base_position_encoding
def __call__(self, batch_size, pos=None):
base_pos = self._base_position_encoding(batch_size, pos)
projected_pos = hk.Linear(output_size=self._output_size)(base_pos)
return projected_pos
def build_position_encoding(
position_encoding_type,
index_dims,
project_pos_dim=-1,
trainable_position_encoding_kwargs=None,
fourier_position_encoding_kwargs=None,
name=None):
"""Builds the position encoding."""
if position_encoding_type == 'trainable':
assert trainable_position_encoding_kwargs is not None
output_pos_enc = TrainablePositionEncoding(
# Construct 1D features:
index_dim=np.prod(index_dims),
name=name,
**trainable_position_encoding_kwargs)
elif position_encoding_type == 'fourier':
assert fourier_position_encoding_kwargs is not None
output_pos_enc = FourierPositionEncoding(
index_dims=index_dims,
name=name,
**fourier_position_encoding_kwargs)
else:
raise ValueError(f'Unknown position encoding: {position_encoding_type}.')
if project_pos_dim > 0:
# Project the position encoding to a target dimension:
output_pos_enc = PositionEncodingProjector(
output_size=project_pos_dim,
base_position_encoding=output_pos_enc)
return output_pos_enc
|
deepmind-research-master
|
perceiver/position_encoding.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 io_processors."""
import numpy as np
import tensorflow as tf
from perceiver import io_processors
def _create_test_image(shape):
image = np.arange(np.prod(np.array(shape)))
return np.reshape(image, shape)
def test_space_to_depth_image():
image_shape = (2, 3 * 5, 3 * 7, 11)
image = _create_test_image(image_shape)
output = io_processors.space_to_depth(image, spatial_block_size=3)
assert output.shape == (2, 5, 7, 3 * 3 * 11)
def test_space_to_depth_video():
image_shape = (2, 5 * 7, 3 * 11, 3 * 13, 17)
image = _create_test_image(image_shape)
output = io_processors.space_to_depth(image, spatial_block_size=3,
temporal_block_size=5)
assert output.shape == (2, 7, 11, 13, 5 * 3 * 3 * 17)
def test_reverse_space_to_depth_image():
image_shape = (2, 5, 7, 3 * 3 * 11)
image = _create_test_image(image_shape)
output = io_processors.reverse_space_to_depth(image, spatial_block_size=3)
assert output.shape == (2, 3 * 5, 3 * 7, 11)
def test_reverse_space_to_depth_video():
image_shape = (2, 7, 11, 13, 5 * 3 * 3 * 17)
image = _create_test_image(image_shape)
output = io_processors.reverse_space_to_depth(
image, spatial_block_size=3, temporal_block_size=5)
assert output.shape == (2, 5 * 7, 3 * 11, 3 * 13, 17)
def test_extract_patches():
image_shape = (2, 5, 7, 3)
image = _create_test_image(image_shape)
sizes = [1, 2, 3, 1]
strides = [1, 1, 2, 1]
rates = [1, 2, 1, 1]
for padding in ["VALID", "SAME"]:
jax_patches = io_processors.extract_patches(
image, sizes=sizes, strides=strides, rates=rates, padding=padding)
tf_patches = tf.image.extract_patches(
image, sizes=sizes, strides=strides, rates=rates, padding=padding)
assert np.array_equal(
np.array(jax_patches),
tf_patches.numpy())
|
deepmind-research-master
|
perceiver/io_processors_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.
"""IO pre- and post-processors for Perceiver."""
import functools
import math
from typing import Any, Callable, Mapping, Optional, Sequence, Tuple
import einops
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
from perceiver import position_encoding
ModalitySizeT = Mapping[str, int]
PreprocessorOutputT = Tuple[jnp.ndarray, Optional[jnp.ndarray], jnp.ndarray]
PreprocessorT = Callable[..., PreprocessorOutputT]
PostprocessorT = Callable[..., Any]
def reverse_space_to_depth(
frames: jnp.ndarray,
temporal_block_size: int = 1,
spatial_block_size: int = 1) -> jnp.ndarray:
"""Reverse space to depth transform."""
if len(frames.shape) == 4:
return einops.rearrange(
frames, 'b h w (dh dw c) -> b (h dh) (w dw) c',
dh=spatial_block_size, dw=spatial_block_size)
elif len(frames.shape) == 5:
return einops.rearrange(
frames, 'b t h w (dt dh dw c) -> b (t dt) (h dh) (w dw) c',
dt=temporal_block_size, dh=spatial_block_size, dw=spatial_block_size)
else:
raise ValueError(
'Frames should be of rank 4 (batch, height, width, channels)'
' or rank 5 (batch, time, height, width, channels)')
def space_to_depth(
frames: jnp.ndarray,
temporal_block_size: int = 1,
spatial_block_size: int = 1) -> jnp.ndarray:
"""Space to depth transform."""
if len(frames.shape) == 4:
return einops.rearrange(
frames, 'b (h dh) (w dw) c -> b h w (dh dw c)',
dh=spatial_block_size, dw=spatial_block_size)
elif len(frames.shape) == 5:
return einops.rearrange(
frames, 'b (t dt) (h dh) (w dw) c -> b t h w (dt dh dw c)',
dt=temporal_block_size, dh=spatial_block_size, dw=spatial_block_size)
else:
raise ValueError(
'Frames should be of rank 4 (batch, height, width, channels)'
' or rank 5 (batch, time, height, width, channels)')
def extract_patches(images: jnp.ndarray,
sizes: Sequence[int],
strides: Sequence[int],
rates: Sequence[int],
padding: str = 'VALID') -> jnp.ndarray:
"""Extract patches from images.
This function is a wrapper for jax.lax.conv_general_dilated_patches
to conforms to the same interface as tf.image.extract_patches.
The function extracts patches of shape sizes from the input images in the same
manner as a convolution with kernel of shape sizes, stride equal to strides,
and the given padding scheme.
The patches are stacked in the channel dimension.
Args:
images: input batch of images of shape [B, H, W, C].
sizes: size of extracted patches. Must be [1, size_rows, size_cols, 1].
strides: strides, must be [1, stride_rows, stride_cols, 1].
rates: sampling rate (as in dilated convolutions),
must be [1, rate_rows, rate_cols, 1].
padding: padding algorithm to use.
Returns:
Tensor of shape [B, patch_rows, patch_cols, size_rows * size_cols * C]
"""
if len(sizes) != 4 or sizes[0] != 1 or sizes[3] != 1:
raise ValueError(
f'Shape of sizes must be [1, size_rows, size_cols, 1], got {sizes}.')
if len(strides) != 4 or strides[0] != 1 or strides[3] != 1:
raise ValueError(
f'Shape of strides must be [1, size_rows, size_cols, 1], '
f'got {strides}.')
if len(rates) != 4 or rates[0] != 1 or rates[3] != 1:
raise ValueError(
f'Shape of rates must be [1, size_rows, size_cols, 1], got {rates}.')
if images.ndim != 4:
raise ValueError(
f'Rank of images must be 4 (got tensor of shape {jnp.shape(images)})')
# Rearrange axes of images to NCHW for conv_general_dilated_patches
images = einops.rearrange(images, 'n h w c -> n c h w')
channels = images.shape[1]
patches = jax.lax.conv_general_dilated_patches(
images, sizes[1:-1], strides[1:-1], padding, rhs_dilation=rates[1:-1])
# conv_general_dilated_patches returns patches in channel-major order.
# Rearrange to match interface of tf.image.extract_patches.
patches = einops.rearrange(patches, 'n (c ph pw) h w -> n h w (ph pw c)',
c=channels, ph=sizes[1], pw=sizes[2])
return patches
def patches_for_flow(inputs: jnp.ndarray) -> jnp.ndarray:
"""Extract 3x3x2 image patches for flow inputs."""
def pad_and_extract_patches(inputs):
padded_inputs = jnp.pad(inputs, [[0, 0], [1, 1], [1, 1], [0, 0]],
mode='constant')
return extract_patches(
padded_inputs,
sizes=[1, 3, 3, 1],
strides=[1, 1, 1, 1],
padding='VALID',
rates=[1, 1, 1, 1])
return jax.vmap(pad_and_extract_patches, in_axes=1, out_axes=1)(inputs)
# ------------------------------------------------------------
# ------------------- Up/down-sampling ---------------------
# ------------------------------------------------------------
class Conv2DDownsample(hk.Module):
"""Downsamples 4x by applying a 2D convolution and doing max pooling."""
def __init__(
self,
num_layers: int = 1,
num_channels: int = 64,
use_batchnorm: bool = True,
bn_config: Optional[Mapping[str, float]] = None,
name: Optional[str] = None,
):
"""Constructs a Conv2DDownsample model.
Args:
num_layers: The number of conv->max_pool layers.
num_channels: The number of conv output channels.
use_batchnorm: Whether to use batchnorm.
bn_config: A dictionary of two elements, ``decay_rate`` and ``eps`` to be
passed on to the :class:`~haiku.BatchNorm` layers. By default the
``decay_rate`` is ``0.9`` and ``eps`` is ``1e-5``.
name: Name of the module.
"""
super().__init__(name=name)
self._num_layers = num_layers
self._use_batchnorm = use_batchnorm
bn_config = dict(bn_config or {})
bn_config.setdefault('decay_rate', 0.9)
bn_config.setdefault('eps', 1e-5)
bn_config.setdefault('create_scale', True)
bn_config.setdefault('create_offset', True)
self.layers = []
for _ in range(self._num_layers):
conv = hk.Conv2D(
output_channels=num_channels,
kernel_shape=7,
stride=2,
with_bias=False,
padding='SAME',
name='conv')
if use_batchnorm:
batchnorm = hk.BatchNorm(name='batchnorm', **bn_config)
else:
batchnorm = None
self.layers.append(dict(conv=conv, batchnorm=batchnorm))
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
test_local_stats: bool = False) -> jnp.ndarray:
out = inputs
for layer in self.layers:
out = layer['conv'](out)
if layer['batchnorm'] is not None:
out = layer['batchnorm'](out, is_training, test_local_stats)
out = jax.nn.relu(out)
out = hk.max_pool(out,
window_shape=(1, 3, 3, 1),
strides=(1, 2, 2, 1),
padding='SAME')
return out
class Conv2DUpsample(hk.Module):
"""Upsamples 4x using 2 2D transposed convolutions."""
def __init__(
self,
n_outputs: int,
name: Optional[str] = None,
):
"""Constructs a Conv2DUpsample model.
Args:
n_outputs: The number of output channels of the module.
name: Name of the module.
"""
super().__init__(name=name)
self.transp_conv1 = hk.Conv2DTranspose(
output_channels=n_outputs*2,
kernel_shape=4,
stride=2,
with_bias=True,
padding='SAME',
name='transp_conv_1')
self.transp_conv2 = hk.Conv2DTranspose(
output_channels=n_outputs,
kernel_shape=4,
stride=2,
with_bias=True,
padding='SAME',
name='transp_conv_2')
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
test_local_stats: bool = False) -> jnp.ndarray:
out = inputs
out = self.transp_conv1(out)
out = jax.nn.relu(out)
out = self.transp_conv2(out)
return out
class Conv3DUpsample(hk.Module):
"""Simple convolutional auto-encoder."""
def __init__(self,
n_outputs: int,
n_time_upsamples: int = 2,
n_space_upsamples: int = 4,
name: Optional[str] = None):
super().__init__(name=name)
self._n_outputs = n_outputs
self._n_time_upsamples = n_time_upsamples
self._n_space_upsamples = n_space_upsamples
def __call__(self, x: jnp.ndarray, *, is_training: bool) -> jnp.ndarray:
n_upsamples = max(self._n_time_upsamples, self._n_space_upsamples)
time_stride = 2
space_stride = 2
for i in range(n_upsamples):
if i >= self._n_time_upsamples:
time_stride = 1
if i >= self._n_space_upsamples:
space_stride = 1
channels = self._n_outputs * pow(2, n_upsamples - 1 - i)
x = hk.Conv3DTranspose(output_channels=channels,
stride=[time_stride, space_stride, space_stride],
kernel_shape=[4, 4, 4],
name=f'conv3d_transpose_{i}')(x)
if i != n_upsamples - 1:
x = jax.nn.relu(x)
return x
class ImagePreprocessor(hk.Module):
"""Image preprocessing for Perceiver Encoder."""
def __init__(
self,
prep_type='conv',
spatial_downsample: int = 4,
temporal_downsample: int = 1,
position_encoding_type: str = 'fourier',
n_extra_pos_mlp: int = 0,
num_channels: int = 64,
conv_after_patching: bool = False,
conv2d_use_batchnorm: bool = True,
concat_or_add_pos: str = 'concat',
name: Optional[str] = None,
**position_encoding_kwargs):
super().__init__(name=name)
if prep_type not in ('conv', 'patches', 'pixels', 'conv1x1'):
raise ValueError('Invalid prep_type!')
if concat_or_add_pos not in ['concat', 'add']:
raise ValueError(
f'Invalid value {concat_or_add_pos} for concat_or_add_pos.')
self._prep_type = prep_type
self._spatial_downsample = spatial_downsample
self._temporal_downsample = temporal_downsample
self._concat_or_add_pos = concat_or_add_pos
self._conv_after_patching = conv_after_patching
self._num_channels = num_channels
if self._prep_type == 'conv':
# Downsampling with conv is currently restricted
convnet_num_layers = math.log(spatial_downsample, 4)
convnet_num_layers_is_int = (
convnet_num_layers == np.round(convnet_num_layers))
if not convnet_num_layers_is_int or temporal_downsample != 1:
raise ValueError('Only powers of 4 expected for spatial '
'and 1 expected for temporal '
'downsampling with conv.')
self.convnet = Conv2DDownsample(
num_layers=int(convnet_num_layers),
num_channels=num_channels,
use_batchnorm=conv2d_use_batchnorm)
elif self._prep_type == 'conv1x1':
assert temporal_downsample == 1, 'conv1x1 does not downsample in time.'
self.convnet_1x1 = hk.Conv2D(
num_channels, kernel_shape=[1, 1],
# spatial_downsample is unconstrained for 1x1 convolutions.
stride=[spatial_downsample, spatial_downsample])
# Partially construct the positional encoding function.
# We fully construct it when we know the input size.
self._positional_encoding_ctor = functools.partial(
position_encoding.build_position_encoding,
position_encoding_type=position_encoding_type,
**position_encoding_kwargs)
# Stack MLPs to get a deeper positional embedding.
self._n_extra_pos_mlp = n_extra_pos_mlp
def _build_network_inputs(
self, inputs: jnp.ndarray, pos: jnp.ndarray,
network_input_is_1d: bool = True) -> Tuple[jnp.ndarray, jnp.ndarray]:
"""Construct the final input, including position encoding."""
batch_size = inputs.shape[0]
index_dims = inputs.shape[1:-1]
# Reshape input features to a 1D index dimension if necessary.
if len(inputs.shape) > 3 and network_input_is_1d:
inputs = jnp.reshape(
inputs, [batch_size, np.prod(index_dims), -1])
# Construct the position encoding.
pos_enc = self._positional_encoding_ctor(
index_dims=index_dims)(batch_size=batch_size, pos=pos)
for i in range(0, self._n_extra_pos_mlp):
pos_enc += hk.Linear(pos_enc.shape[-1])(pos_enc)
if i < (self._n_extra_pos_mlp-1):
pos_enc = jax.nn.relu(pos_enc)
if not network_input_is_1d:
# Reshape pos to match the input feature shape
# if the network takes non-1D inputs
sh = inputs.shape
pos_enc = jnp.reshape(pos_enc, list(sh)[:-1]+[-1])
if self._concat_or_add_pos == 'concat':
inputs_with_pos = jnp.concatenate([inputs, pos_enc], axis=-1)
elif self._concat_or_add_pos == 'add':
inputs_with_pos = inputs + pos_enc
return inputs_with_pos, inputs
def __call__(
self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
network_input_is_1d: bool = True) -> PreprocessorOutputT:
if self._prep_type == 'conv':
# Convnet image featurization.
# Downsamples spatially by a factor of 4
conv = self.convnet
if len(inputs.shape) == 5:
conv = hk.BatchApply(conv)
inputs = conv(inputs, is_training=is_training)
elif self._prep_type == 'conv1x1':
# maps inputs to 64d
conv = self.convnet_1x1
if len(inputs.shape) == 5:
conv = hk.BatchApply(conv)
inputs = conv(inputs)
elif self._prep_type == 'patches':
# Space2depth featurization.
# Video: B x T x H x W x C
inputs = space_to_depth(
inputs,
temporal_block_size=self._temporal_downsample,
spatial_block_size=self._spatial_downsample)
if inputs.ndim == 5 and inputs.shape[1] == 1:
# for flow
inputs = jnp.squeeze(inputs, axis=1)
if self._conv_after_patching:
inputs = hk.Linear(self._num_channels, name='patches_linear')(inputs)
elif self._prep_type == 'pixels':
# if requested, downsamples in the crudest way
if inputs.ndim == 4:
inputs = inputs[:,
::self._spatial_downsample, ::self._spatial_downsample]
elif inputs.ndim == 5:
inputs = inputs[:, ::self._temporal_downsample,
::self._spatial_downsample, ::self._spatial_downsample]
else:
raise ValueError('Unsupported data format for pixels.')
inputs, inputs_without_pos = self._build_network_inputs(
inputs, pos, network_input_is_1d)
modality_sizes = None # Size for each modality, only needed for multimodal
return inputs, modality_sizes, inputs_without_pos
class ImagePostprocessor(hk.Module):
"""Image postprocessing for Perceiver."""
def __init__(
self,
postproc_type: str = 'pixels',
spatial_upsample: int = 1,
temporal_upsample: int = 1,
n_outputs: int = -1, # only relevant for 'conv1x1', 'conv', and 'raft'
input_reshape_size: Optional[Sequence[int]] = None,
name: Optional[str] = None):
super().__init__(name=name)
if postproc_type not in ('conv', 'patches', 'pixels', 'raft', 'conv1x1'):
raise ValueError('Invalid postproc_type!')
# Architecture parameters:
self._postproc_type = postproc_type
self._temporal_upsample = temporal_upsample
self._spatial_upsample = spatial_upsample
self._input_reshape_size = input_reshape_size
if self._postproc_type == 'pixels':
# No postprocessing.
if self._temporal_upsample != 1 or self._spatial_upsample != 1:
raise ValueError('Pixels postprocessing should not currently upsample.')
elif self._postproc_type == 'conv1x1':
assert self._temporal_upsample == 1, 'conv1x1 does not upsample in time.'
if n_outputs == -1:
raise ValueError('Expected value for n_outputs')
self.conv1x1 = hk.Conv2D(
n_outputs, kernel_shape=[1, 1],
# spatial_downsample is unconstrained for 1x1 convolutions.
stride=[self._spatial_upsample, self._spatial_upsample])
elif self._postproc_type == 'conv':
if n_outputs == -1:
raise ValueError('Expected value for n_outputs')
if self._temporal_upsample != 1:
def int_log2(x):
return int(np.round(np.log(x) / np.log(2)))
self.convnet = Conv3DUpsample(
n_outputs, int_log2(temporal_upsample), int_log2(spatial_upsample))
else:
self.convnet = Conv2DUpsample(n_outputs)
def __call__(
self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
modality_sizes: Optional[ModalitySizeT] = None) -> jnp.ndarray:
if self._input_reshape_size is not None:
inputs = jnp.reshape(
inputs,
[inputs.shape[0]] + list(self._input_reshape_size)
+ [inputs.shape[-1]])
if self._postproc_type == 'conv' or self._postproc_type == 'raft':
# Convnet image featurization.
conv = self.convnet
if len(inputs.shape) == 5 and self._temporal_upsample == 1:
conv = hk.BatchApply(conv)
inputs = conv(inputs, is_training=is_training)
elif self._postproc_type == 'conv1x1':
inputs = self.conv1x1(inputs)
elif self._postproc_type == 'patches':
inputs = reverse_space_to_depth(
inputs, self._temporal_upsample, self._spatial_upsample)
return inputs
class OneHotPreprocessor(hk.Module):
"""One-hot preprocessor for Perceiver Encoder."""
def __init__(self, name: Optional[str] = None):
super().__init__(name=name)
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
network_input_is_1d: bool = True) -> PreprocessorOutputT:
# Add a dummy index dimension.
inputs = inputs[:, None, :]
# No position encodings, so the 1st (input) and 3rd (inputs_without_pos)
# outputs are identical.
return inputs, None, inputs
class AudioPreprocessor(hk.Module):
"""Audio preprocessing for Perceiver Encoder."""
def __init__(
self,
prep_type: str = 'patches',
samples_per_patch: int = 96,
position_encoding_type: str = 'fourier',
n_extra_pos_mlp: int = 0,
concat_or_add_pos: str = 'concat',
name: Optional[str] = None,
**position_encoding_kwargs):
super().__init__(name=name)
if prep_type not in ('patches',):
raise ValueError('Invalid prep_type!')
if concat_or_add_pos not in ['concat', 'add']:
raise ValueError(
f'Invalid value {concat_or_add_pos} for concat_or_add_pos.')
self._samples_per_patch = samples_per_patch
self._concat_or_add_pos = concat_or_add_pos
# Partially construct the positional encoding function.
# We fully construct it when we know the input size.
self._positional_encoding_ctor = functools.partial(
position_encoding.build_position_encoding,
position_encoding_type=position_encoding_type,
**position_encoding_kwargs)
# for deeper positional embeddings
self._n_extra_pos_mlp = n_extra_pos_mlp
def _build_network_inputs(
self, inputs: jnp.ndarray,
pos: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]:
"""Construct the final input, including position encoding."""
batch_size = inputs.shape[0]
index_dims = inputs.shape[1:-1]
# Construct the position encoding.
pos_enc = self._positional_encoding_ctor(
index_dims=index_dims)(batch_size=batch_size, pos=pos)
for i in range(0, self._n_extra_pos_mlp):
pos_enc += hk.Linear(pos_enc.shape[-1])(pos_enc)
if i < (self._n_extra_pos_mlp-1):
pos_enc = jax.nn.relu(pos_enc)
if self._concat_or_add_pos == 'concat':
inputs_with_pos = jnp.concatenate([inputs, pos_enc], axis=-1)
elif self._concat_or_add_pos == 'add':
inputs_with_pos = inputs + pos_enc
return inputs_with_pos, inputs
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
network_input_is_1d: bool = True) -> PreprocessorOutputT:
inputs = jnp.reshape(inputs, [inputs.shape[0], -1,
self._samples_per_patch])
inputs, inputs_without_pos = self._build_network_inputs(inputs, pos)
modality_sizes = None # Size for each modality, only needed for multimodal
return inputs, modality_sizes, inputs_without_pos
class AudioPostprocessor(hk.Module):
"""Audio postprocessing for Perceiver."""
def __init__(
self,
postproc_type: str = 'patches', # 'conv', 'patches', 'pixels'
samples_per_patch: int = 96,
name: Optional[str] = None):
super().__init__(name=name)
if postproc_type not in ('patches',):
raise ValueError('Invalid postproc_type!')
self._samples_per_patch = samples_per_patch
# Architecture parameters:
self._postproc_type = postproc_type
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
modality_sizes: Optional[ModalitySizeT] = None) -> jnp.ndarray:
out = hk.Linear(self._samples_per_patch)(inputs)
return jnp.reshape(out, [inputs.shape[0], -1])
class IdentityPostprocessor(hk.Module):
"""Passes through the inputs unchanged."""
def __init__(self, name: Optional[str] = None):
super().__init__(name=name)
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
modality_sizes: Optional[ModalitySizeT] = None) -> jnp.ndarray:
return inputs
def restructure(modality_sizes: ModalitySizeT,
inputs: jnp.ndarray) -> Mapping[str, jnp.ndarray]:
"""Partitions a [B, N, C] tensor into tensors for each modality.
Args:
modality_sizes: dict specifying the size of the modality
inputs: input tensor
Returns:
dict mapping name of modality to its associated tensor.
"""
outputs = {}
index = 0
# Apply a predictable ordering to the modalities
for modality in sorted(modality_sizes.keys()):
size = modality_sizes[modality]
inp = inputs[:, index:index + size]
index += size
outputs[modality] = inp
return outputs
class MultimodalPreprocessor(hk.Module):
"""Multimodal preprocessing for Perceiver Encoder.
Inputs for each modality is preprocessed then padded with trainable position
embeddings to have the same number of channels.
"""
def __init__(
self,
modalities: Mapping[str, PreprocessorT],
mask_probs: Optional[Mapping[str, float]] = None,
min_padding_size: int = 2,
name: Optional[str] = None):
"""Constructor.
Args:
modalities: dict mapping modality name to preprocessor
mask_probs: dict mapping modality name to masking probability of that
modality
min_padding_size: the minimum padding size for all modalities.
The final output will have num_channels equal to the maximum channels
across all modalities plus min_padding_size.
name: name of module
"""
super().__init__(name=name)
self._modalities = modalities
self._min_padding_size = min_padding_size
self._mask_probs = mask_probs
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
network_input_is_1d: bool = True) -> PreprocessorOutputT:
outputs = {}
inputs_without_pos = {}
for modality, preprocessor in self._modalities.items():
outputs[modality], _, inputs_without_pos[modality] = preprocessor(
inputs[modality], is_training=is_training, pos=pos,
network_input_is_1d=network_input_is_1d)
common_channel_size = (max(o.shape[2] for o in outputs.values())
+ self._min_padding_size)
padded = {}
modality_sizes = {}
for modality, output in outputs.items():
pos_enc = position_encoding.TrainablePositionEncoding(
1, num_channels=common_channel_size-output.shape[2],
init_scale=0.02, name=f'{modality}_padding')
padding = jnp.broadcast_to(
pos_enc(batch_size=output.shape[0]),
[output.shape[0], output.shape[1],
common_channel_size-output.shape[2]])
output_padded = jnp.concatenate([output, padding], axis=2)
if self._mask_probs is not None:
# Randomly mask out each token corresponding to this modality
mask_token = position_encoding.TrainablePositionEncoding(
1, num_channels=output_padded.shape[2],
init_scale=0.02, name=f'{modality}_mask_token')(output.shape[0])
mask_prob = self._mask_probs[modality]
rng = hk.next_rng_key()
mask = jax.random.bernoulli(rng, mask_prob,
shape=[output.shape[0], output.shape[1]])
mask = jnp.expand_dims(mask, axis=2)
output_padded = (1 - mask) * output_padded + mask * mask_token
padded[modality] = output_padded
modality_sizes[modality] = output_padded.shape[1]
# Apply a predictable ordering to the modalities
padded_ls = [padded[k] for k in sorted(padded.keys())]
return (jnp.concatenate(padded_ls, axis=1), # pytype: disable=bad-return-type # jax-ndarray
modality_sizes,
inputs_without_pos)
class MultimodalPostprocessor(hk.Module):
"""Multimodal postprocessing for Perceiver."""
def __init__(
self,
modalities: Mapping[str, PostprocessorT],
input_is_dict: bool = False,
name: Optional[str] = None):
"""Constructor.
Args:
modalities: dict mapping modality name to post processor for that modality
input_is_dict: If True, input is assumed to be dictionary structured,
and outputs keep the same dictionary shape. If False, input is a tensor
which is sliced up during postprocessing by `modality_sizes`.
name: name of the module
"""
super().__init__(name=name)
self._modalities = modalities
self._input_is_dict = input_is_dict
def __call__(
self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
modality_sizes: Optional[ModalitySizeT] = None) -> Mapping[str,
jnp.ndarray]:
if not self._input_is_dict:
# Slice up modalities by their sizes.
assert modality_sizes is not None
inputs = restructure(modality_sizes=modality_sizes, inputs=inputs)
outputs = {modality: postprocessor(
inputs[modality], is_training=is_training, pos=pos, modality_sizes=None)
for modality, postprocessor in self._modalities.items()}
return outputs
class ClassificationPostprocessor(hk.Module):
"""Classification postprocessing for Perceiver."""
def __init__(
self,
num_classes: int,
name: Optional[str] = None):
super().__init__(name=name)
self._num_classes = num_classes
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
modality_sizes: Optional[ModalitySizeT] = None) -> jnp.ndarray:
logits = hk.Linear(self._num_classes)(inputs)
return logits[:, 0, :]
class ProjectionPostprocessor(hk.Module):
"""Projection postprocessing for Perceiver."""
def __init__(
self,
num_outputs: int,
name: Optional[str] = None):
super().__init__(name=name)
self._num_outputs = num_outputs
def __call__(self, inputs: jnp.ndarray, *,
is_training: bool,
pos: Optional[jnp.ndarray] = None,
modality_sizes: Optional[ModalitySizeT] = None) -> jnp.ndarray:
logits = hk.Linear(self._num_outputs)(inputs)
return logits
class EmbeddingDecoder(hk.Module):
"""Haiku module to decode embeddings."""
def __init__(self, embedding_matrix: jnp.ndarray, name='embedding_decoder'):
"""Constructs the module.
Args:
embedding_matrix: Array of shape [vocab_size, d_model].
name: Name of the module.
"""
super().__init__(name=name)
self._embedding_matrix = embedding_matrix
self._vocab_size, self._d_model = embedding_matrix.shape
def __call__(self, embeddings: jnp.ndarray) -> jnp.ndarray:
batch_size, seq_len, _ = embeddings.shape
output = jnp.matmul(
embeddings.reshape([-1, self._d_model]), # Flatten batch dim
jnp.transpose(self._embedding_matrix))
bias = hk.get_parameter('bias', shape=[self._vocab_size], init=jnp.zeros)
output = output + bias
return output.reshape([batch_size, seq_len, self._vocab_size])
|
deepmind-research-master
|
perceiver/io_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.
"""ImageNet dataset with pre-processing and augmentation.
Deng, et al CVPR 2009 - ImageNet: A large-scale hierarchical image database.
https://image-net.org/
"""
import enum
from typing import Any, Generator, Mapping, Optional, Sequence, Text, Tuple
import jax
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
import tensorflow_probability as tfp
from perceiver.train import autoaugment
Batch = Mapping[Text, np.ndarray]
MEAN_RGB = (0.485 * 255, 0.456 * 255, 0.406 * 255)
STDDEV_RGB = (0.229 * 255, 0.224 * 255, 0.225 * 255)
AUTOTUNE = tf.data.experimental.AUTOTUNE
INPUT_DIM = 224 # The number of pixels in the image resize.
class Split(enum.Enum):
"""ImageNet dataset split."""
TRAIN = 1
TRAIN_AND_VALID = 2
VALID = 3
TEST = 4
@classmethod
def from_string(cls, name: Text) -> 'Split':
return {'TRAIN': Split.TRAIN, 'TRAIN_AND_VALID': Split.TRAIN_AND_VALID,
'VALID': Split.VALID, 'VALIDATION': Split.VALID,
'TEST': Split.TEST}[name.upper()]
@property
def num_examples(self):
return {Split.TRAIN_AND_VALID: 1281167, Split.TRAIN: 1271167,
Split.VALID: 10000, Split.TEST: 50000}[self]
def load(
split: Split,
*,
is_training: bool,
# batch_dims should be:
# [device_count, per_device_batch_size] or [total_batch_size]
batch_dims: Sequence[int],
augmentation_settings: Mapping[str, Any],
# The shape to which images are resized.
im_dim: int = INPUT_DIM,
threadpool_size: int = 48,
max_intra_op_parallelism: int = 1,
) -> Generator[Batch, None, None]:
"""Loads the given split of the dataset."""
start, end = _shard(split, jax.host_id(), jax.host_count())
im_size = (im_dim, im_dim)
total_batch_size = np.prod(batch_dims)
tfds_split = tfds.core.ReadInstruction(_to_tfds_split(split),
from_=start, to=end, unit='abs')
ds = tfds.load('imagenet2012:5.*.*', split=tfds_split,
decoders={'image': tfds.decode.SkipDecoding()})
options = tf.data.Options()
options.experimental_threading.private_threadpool_size = threadpool_size
options.experimental_threading.max_intra_op_parallelism = (
max_intra_op_parallelism)
options.experimental_optimization.map_parallelization = True
if is_training:
options.experimental_deterministic = False
ds = ds.with_options(options)
if is_training:
if jax.host_count() > 1:
# Only cache if we are reading a subset of the dataset.
ds = ds.cache()
ds = ds.repeat()
ds = ds.shuffle(buffer_size=10 * total_batch_size, seed=0)
else:
if split.num_examples % total_batch_size != 0:
raise ValueError(f'Test/valid must be divisible by {total_batch_size}')
def crop_augment_preprocess(example):
image, _ = _preprocess_image(
example['image'], is_training, im_size, augmentation_settings)
label = tf.cast(example['label'], tf.int32)
out = {'images': image, 'labels': label}
if is_training:
if augmentation_settings['cutmix']:
out['mask'] = cutmix_padding(*im_size)
out['cutmix_ratio'] = tf.reduce_mean(out['mask'])
if augmentation_settings['mixup_alpha'] is not None:
beta = tfp.distributions.Beta(
augmentation_settings['mixup_alpha'],
augmentation_settings['mixup_alpha'])
out['mixup_ratio'] = beta.sample()
return out
ds = ds.map(crop_augment_preprocess, num_parallel_calls=AUTOTUNE)
# Mixup/cutmix by temporarily batching (using the per-device batch size):
use_cutmix = augmentation_settings['cutmix']
use_mixup = augmentation_settings['mixup_alpha'] is not None
if is_training and (use_cutmix or use_mixup):
inner_batch_size = batch_dims[-1]
# Apply mixup, cutmix, or mixup + cutmix on batched data.
# We use data from 2 batches to produce 1 mixed batch.
ds = ds.batch(inner_batch_size * 2)
if not use_cutmix and use_mixup:
ds = ds.map(my_mixup, num_parallel_calls=AUTOTUNE)
elif use_cutmix and not use_mixup:
ds = ds.map(my_cutmix, num_parallel_calls=AUTOTUNE)
elif use_cutmix and use_mixup:
ds = ds.map(my_mixup_cutmix, num_parallel_calls=AUTOTUNE)
# Unbatch for further processing.
ds = ds.unbatch()
for batch_size in reversed(batch_dims):
ds = ds.batch(batch_size)
ds = ds.prefetch(AUTOTUNE)
yield from tfds.as_numpy(ds)
# cutmix_padding, my_cutmix, my_mixup, and my_mixup_cutmix taken from:
# https://github.com/deepmind/deepmind-research/blob/master/nfnets/dataset.py
def cutmix_padding(h, w):
"""Returns image mask for CutMix.
Taken from (https://github.com/google/edward2/blob/master/experimental
/marginalization_mixup/data_utils.py#L367)
Args:
h: image height.
w: image width.
"""
r_x = tf.random.uniform([], 0, w, tf.int32)
r_y = tf.random.uniform([], 0, h, tf.int32)
# Beta dist in paper, but they used Beta(1,1) which is just uniform.
image1_proportion = tf.random.uniform([])
patch_length_ratio = tf.math.sqrt(1 - image1_proportion)
r_w = tf.cast(patch_length_ratio * tf.cast(w, tf.float32), tf.int32)
r_h = tf.cast(patch_length_ratio * tf.cast(h, tf.float32), tf.int32)
bbx1 = tf.clip_by_value(tf.cast(r_x - r_w // 2, tf.int32), 0, w)
bby1 = tf.clip_by_value(tf.cast(r_y - r_h // 2, tf.int32), 0, h)
bbx2 = tf.clip_by_value(tf.cast(r_x + r_w // 2, tf.int32), 0, w)
bby2 = tf.clip_by_value(tf.cast(r_y + r_h // 2, tf.int32), 0, h)
# Create the binary mask.
pad_left = bbx1
pad_top = bby1
pad_right = tf.maximum(w - bbx2, 0)
pad_bottom = tf.maximum(h - bby2, 0)
r_h = bby2 - bby1
r_w = bbx2 - bbx1
mask = tf.pad(
tf.ones((r_h, r_w)),
paddings=[[pad_top, pad_bottom], [pad_left, pad_right]],
mode='CONSTANT',
constant_values=0)
mask.set_shape((h, w))
return mask[..., None] # Add channel dim.
def my_cutmix(batch):
"""Apply CutMix: https://arxiv.org/abs/1905.04899."""
batch = dict(**batch)
bs = tf.shape(batch['images'])[0] // 2
mask = batch['mask'][:bs]
images = (mask * batch['images'][:bs] + (1.0 - mask) * batch['images'][bs:])
mix_labels = batch['labels'][bs:]
labels = batch['labels'][:bs]
ratio = batch['cutmix_ratio'][:bs]
return {'images': images, 'labels': labels,
'mix_labels': mix_labels, 'ratio': ratio}
def my_mixup(batch):
"""Apply mixup: https://arxiv.org/abs/1710.09412."""
batch = dict(**batch)
bs = tf.shape(batch['images'])[0] // 2
ratio = batch['mixup_ratio'][:bs, None, None, None]
images = (ratio * batch['images'][:bs] + (1.0 - ratio) * batch['images'][bs:])
mix_labels = batch['labels'][bs:]
labels = batch['labels'][:bs]
ratio = ratio[..., 0, 0, 0] # Unsqueeze
return {'images': images, 'labels': labels,
'mix_labels': mix_labels, 'ratio': ratio}
def my_mixup_cutmix(batch):
"""Apply mixup to half the batch, and cutmix to the other."""
batch = dict(**batch)
bs = tf.shape(batch['images'])[0] // 4
mixup_ratio = batch['mixup_ratio'][:bs, None, None, None]
mixup_images = (mixup_ratio * batch['images'][:bs]
+ (1.0 - mixup_ratio) * batch['images'][bs:2*bs])
mixup_labels = batch['labels'][:bs]
mixup_mix_labels = batch['labels'][bs:2*bs]
cutmix_mask = batch['mask'][2*bs:3*bs]
cutmix_images = (cutmix_mask * batch['images'][2*bs:3*bs]
+ (1.0 - cutmix_mask) * batch['images'][-bs:])
cutmix_labels = batch['labels'][2*bs:3*bs]
cutmix_mix_labels = batch['labels'][-bs:]
cutmix_ratio = batch['cutmix_ratio'][2*bs : 3*bs]
return {'images': tf.concat([mixup_images, cutmix_images], axis=0),
'labels': tf.concat([mixup_labels, cutmix_labels], axis=0),
'mix_labels': tf.concat([mixup_mix_labels, cutmix_mix_labels], 0),
'ratio': tf.concat([mixup_ratio[..., 0, 0, 0], cutmix_ratio], axis=0)}
def _to_tfds_split(split: Split) -> tfds.Split:
"""Returns the TFDS split appropriately sharded."""
# NOTE: Imagenet did not release labels for the test split used in the
# competition, so it has been typical at DeepMind to consider the VALID
# split the TEST split and to reserve 10k images from TRAIN for VALID.
if split in (
Split.TRAIN, Split.TRAIN_AND_VALID, Split.VALID):
return tfds.Split.TRAIN
else:
assert split == Split.TEST
return tfds.Split.VALIDATION
def _shard(
split: Split, shard_index: int, num_shards: int) -> Tuple[int, int]:
"""Returns [start, end) for the given shard index."""
assert shard_index < num_shards
arange = np.arange(split.num_examples)
shard_range = np.array_split(arange, num_shards)[shard_index]
start, end = shard_range[0], (shard_range[-1] + 1)
if split == Split.TRAIN:
# Note that our TRAIN=TFDS_TRAIN[10000:] and VALID=TFDS_TRAIN[:10000].
offset = Split.VALID.num_examples
start += offset
end += offset
return start, end
def _preprocess_image(
image_bytes: tf.Tensor,
is_training: bool,
image_size: Sequence[int],
augmentation_settings: Mapping[str, Any],
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Returns processed and resized images."""
# Get the image crop.
if is_training:
image, im_shape = _decode_and_random_crop(image_bytes)
image = tf.image.random_flip_left_right(image)
else:
image, im_shape = _decode_and_center_crop(image_bytes)
assert image.dtype == tf.uint8
# Optionally apply RandAugment: https://arxiv.org/abs/1909.13719
if is_training:
if augmentation_settings['randaugment'] is not None:
# Input and output images are dtype uint8.
image = autoaugment.distort_image_with_randaugment(
image,
num_layers=augmentation_settings['randaugment']['num_layers'],
magnitude=augmentation_settings['randaugment']['magnitude'])
# Resize and normalize the image crop.
# NOTE: Bicubic resize (1) casts uint8 to float32 and (2) resizes without
# clamping overshoots. This means values returned will be outside the range
# [0.0, 255.0] (e.g. we have observed outputs in the range [-51.1, 336.6]).
image = tf.image.resize(
image, image_size, tf.image.ResizeMethod.BICUBIC)
image = _normalize_image(image)
return image, im_shape
def _normalize_image(image: tf.Tensor) -> tf.Tensor:
"""Normalize the image to zero mean and unit variance."""
image -= tf.constant(MEAN_RGB, shape=[1, 1, 3], dtype=image.dtype)
image /= tf.constant(STDDEV_RGB, shape=[1, 1, 3], dtype=image.dtype)
return image
def _distorted_bounding_box_crop(
image_bytes: tf.Tensor,
*,
jpeg_shape: tf.Tensor,
bbox: tf.Tensor,
min_object_covered: float,
aspect_ratio_range: Tuple[float, float],
area_range: Tuple[float, float],
max_attempts: int,
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Generates cropped_image using one of the bboxes randomly distorted."""
bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box(
jpeg_shape,
bounding_boxes=bbox,
min_object_covered=min_object_covered,
aspect_ratio_range=aspect_ratio_range,
area_range=area_range,
max_attempts=max_attempts,
use_image_if_no_bounding_boxes=True)
# Crop the image to the specified bounding box.
offset_y, offset_x, _ = tf.unstack(bbox_begin)
target_height, target_width, _ = tf.unstack(bbox_size)
crop_window = [offset_y, offset_x, target_height, target_width]
if image_bytes.dtype == tf.dtypes.string:
image = tf.image.decode_and_crop_jpeg(image_bytes,
tf.stack(crop_window),
channels=3)
else:
image = tf.image.crop_to_bounding_box(image_bytes, *crop_window)
im_shape = tf.stack([target_height, target_width])
return image, im_shape
def _decode_whole_image(image_bytes: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:
image = tf.io.decode_jpeg(image_bytes, channels=3)
im_shape = tf.io.extract_jpeg_shape(image_bytes, output_type=tf.int32)
return image, im_shape
def _decode_and_random_crop(
image_bytes: tf.Tensor
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Make a random crop of INPUT_DIM."""
if image_bytes.dtype == tf.dtypes.string:
jpeg_shape = tf.image.extract_jpeg_shape(image_bytes)
else:
jpeg_shape = tf.shape(image_bytes)
bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
image, im_shape = _distorted_bounding_box_crop(
image_bytes,
jpeg_shape=jpeg_shape,
bbox=bbox,
min_object_covered=0.1,
aspect_ratio_range=(3 / 4, 4 / 3),
area_range=(0.08, 1.0),
max_attempts=10)
if tf.reduce_all(tf.equal(jpeg_shape, tf.shape(image))):
# If the random crop failed fall back to center crop.
image, im_shape = _decode_and_center_crop(image_bytes, jpeg_shape)
return image, im_shape
def _center_crop(image, crop_dim):
"""Center crops an image to a target dimension."""
image_height = image.shape[0]
image_width = image.shape[1]
offset_height = ((image_height - crop_dim) + 1) // 2
offset_width = ((image_width - crop_dim) + 1) // 2
return tf.image.crop_to_bounding_box(
image, offset_height, offset_width, crop_dim, crop_dim)
def _decode_and_center_crop(
image_bytes: tf.Tensor,
jpeg_shape: Optional[tf.Tensor] = None,
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Crops to center of image with padding then scales."""
if jpeg_shape is None:
if image_bytes.dtype == tf.dtypes.string:
jpeg_shape = tf.image.extract_jpeg_shape(image_bytes)
else:
jpeg_shape = tf.shape(image_bytes)
image_height = jpeg_shape[0]
image_width = jpeg_shape[1]
padded_center_crop_size = tf.cast(
((INPUT_DIM / (INPUT_DIM + 32)) *
tf.cast(tf.minimum(image_height, image_width), tf.float32)), tf.int32)
offset_height = ((image_height - padded_center_crop_size) + 1) // 2
offset_width = ((image_width - padded_center_crop_size) + 1) // 2
crop_window = [offset_height, offset_width,
padded_center_crop_size, padded_center_crop_size]
if image_bytes.dtype == tf.dtypes.string:
image = tf.image.decode_and_crop_jpeg(image_bytes,
tf.stack(crop_window),
channels=3)
else:
image = tf.image.crop_to_bounding_box(image_bytes, *crop_window)
im_shape = tf.stack([padded_center_crop_size, padded_center_crop_size])
return image, im_shape
|
deepmind-research-master
|
perceiver/train/dataset.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 reference training pipeline for Perceiver/Perceiver IO on ImageNet.
We use the Jaxline (https://github.com/deepmind/jaxline) training framework.
Two sets of hyperparameters are provided, the hyperparameters we used for the
Perceiver IO paper, and scaled-down hyperparameters for local testing.
This script should run out-of-the-box with the local hyper parameters.
The scaled-up hyperparameters requires a distributed learning setup to run,
and this script will need to be adapted to your specific setup.
"""
import functools
from typing import Generator, Mapping, Text, Tuple
from absl import app
from absl import flags
from absl import logging
import haiku as hk
import jax
import jax.numpy as jnp
from jaxline import base_config
from jaxline import experiment
from jaxline import platform
from jaxline import utils as jl_utils
from ml_collections import config_dict
import numpy as np
import optax
from perceiver import io_processors
from perceiver import perceiver
from perceiver.train import dataset
from perceiver.train import utils
FLAGS = flags.FLAGS
OptState = Tuple[optax.TraceState, optax.ScaleByScheduleState, optax.ScaleState]
Scalars = Mapping[Text, jnp.ndarray]
N_TRAIN_EXAMPLES = dataset.Split.TRAIN_AND_VALID.num_examples
N_CLASSES = 1000
# Only local/debug parameters are supported out of the box.
# To use the scaled-up hyperparameters, please adapt this script to your
# training setup and set this flag to False
IS_LOCAL = True
def get_training_steps(batch_size, n_epochs):
return (N_TRAIN_EXAMPLES * n_epochs) // batch_size
def get_config():
"""Return config object for training."""
use_debug_settings = IS_LOCAL
config = base_config.get_base_config()
# Experiment config.
local_batch_size = 2
# Modify this to adapt to your custom distributed learning setup
num_devices = 1
config.train_batch_size = local_batch_size * num_devices
config.n_epochs = 110
def _default_or_debug(default_value, debug_value):
return debug_value if use_debug_settings else default_value
n_train_examples = N_TRAIN_EXAMPLES
num_classes = N_CLASSES
config.experiment_kwargs = config_dict.ConfigDict(
dict(
config=dict(
optimizer=dict(
base_lr=5e-4,
max_norm=10.0, # < 0 to turn off.
schedule_type='constant_cosine',
weight_decay=1e-1,
decay_pos_embs=True,
scale_by_batch=True,
cosine_decay_kwargs=dict(
init_value=0.0,
warmup_epochs=0,
end_value=0.0,
),
step_decay_kwargs=dict(
decay_boundaries=[0.5, 0.8, 0.95],
decay_rate=0.1,
),
constant_cosine_decay_kwargs=dict(
constant_fraction=0.5,
end_value=0.0,
),
optimizer='lamb',
# Optimizer-specific kwargs:
adam_kwargs=dict(
b1=0.9,
b2=0.999,
eps=1e-8,
),
lamb_kwargs=dict(
b1=0.9,
b2=0.999,
eps=1e-6,
),
),
# Don't specify output_channels - it's not used for
# classifiers.
model=dict(
perceiver_kwargs=dict(
input_preprocessor=dict(
prep_type='pixels',
# Channels for conv/conv1x1 preprocessing:
num_channels=64,
# -------------------------
# Position encoding arguments:
# -------------------------
position_encoding_type='fourier',
concat_or_add_pos='concat',
spatial_downsample=1,
# If >0, project position to this size:
project_pos_dim=-1,
trainable_position_encoding_kwargs=dict(
num_channels=258, # Match default # for Fourier.
init_scale=0.02,
),
fourier_position_encoding_kwargs=dict(
num_bands=64,
max_resolution=(224, 224),
sine_only=False,
concat_pos=True,
),
),
encoder=dict(
num_self_attends_per_block=_default_or_debug(6, 2),
# Weights won't be shared if num_blocks is set to 1.
num_blocks=_default_or_debug(8, 2),
z_index_dim=512,
num_z_channels=1024,
num_cross_attend_heads=1,
num_self_attend_heads=8,
cross_attend_widening_factor=1,
self_attend_widening_factor=1,
dropout_prob=0.0,
# Position encoding for the latent array.
z_pos_enc_init_scale=0.02,
cross_attention_shape_for_attn='kv',
use_query_residual=True,
),
decoder=dict(
num_z_channels=1024,
use_query_residual=True,
# Position encoding for the output logits.
position_encoding_type='trainable',
trainable_position_encoding_kwargs=dict(
num_channels=1024,
init_scale=0.02,
),
),
),
),
training=dict(
images_per_epoch=n_train_examples,
label_smoothing=0.1,
n_epochs=config.get_oneway_ref('n_epochs'),
batch_size=config.get_oneway_ref('train_batch_size')
),
data=dict(
num_classes=num_classes,
# Run on smaller images to debug.
im_dim=_default_or_debug(224, 32),
augmentation=dict(
# Typical randaug params:
# num_layers in [1, 3]
# magnitude in [5, 30]
# Set randaugment to None to disable.
randaugment=dict(
num_layers=4,
magnitude=5),
cutmix=True,
# Mixup alpha should be in [0, 1].
# Set to None to disable.
mixup_alpha=0.2,
),
),
evaluation=dict(
subset='test',
batch_size=2,
),
)
)
)
# Training loop config.
config.training_steps = get_training_steps(
config.get_oneway_ref('train_batch_size'),
config.get_oneway_ref('n_epochs'))
config.log_train_data_interval = 60
config.log_tensors_interval = 60
config.save_checkpoint_interval = 300
config.eval_specific_checkpoint_dir = ''
config.best_model_eval_metric = 'eval_top_1_acc'
config.checkpoint_dir = '/tmp/perceiver_imagnet_checkpoints'
config.train_checkpoint_all_hosts = False
# Prevents accidentally setting keys that aren't recognized (e.g. in tests).
config.lock()
return config
class Experiment(experiment.AbstractExperiment):
"""ImageNet experiment."""
# A map from object properties that will be checkpointed to their name
# in a checkpoint. Currently we assume that these are all sharded
# device arrays.
CHECKPOINT_ATTRS = {
'_params': 'params',
'_state': 'state',
'_opt_state': 'opt_state',
}
def __init__(self, mode, init_rng, config):
"""Initializes experiment."""
super(Experiment, self).__init__(mode=mode, init_rng=init_rng)
self.mode = mode
self.init_rng = init_rng
self.config = config
# Checkpointed experiment state.
self._params = None
self._state = None
self._opt_state = None
# Input pipelines.
self._train_input = None
self._eval_input = None
self.forward = hk.transform_with_state(self._forward_fn)
# NOTE: We "donate" the `params, state, opt_state` arguments which allows
# JAX (on some backends) to reuse the device memory associated with these
# inputs to store the outputs of our function (which also start with
# `params, state, opt_state`).
self._update_func = jax.pmap(self._update_func, axis_name='i',
donate_argnums=(0, 1, 2))
self._eval_batch = jax.jit(self._eval_batch)
def _forward_fn(
self,
inputs: dataset.Batch,
is_training: bool,
) -> jnp.ndarray:
images = inputs['images']
perceiver_kwargs = self.config.model.perceiver_kwargs
input_preprocessor = io_processors.ImagePreprocessor(
**perceiver_kwargs['input_preprocessor'])
encoder = perceiver.PerceiverEncoder(**perceiver_kwargs['encoder'])
decoder = perceiver.ClassificationDecoder(
self.config.data.num_classes,
**perceiver_kwargs['decoder'])
model = perceiver.Perceiver(
encoder=encoder,
decoder=decoder,
input_preprocessor=input_preprocessor)
return model(images, is_training=is_training)
# _ _
# | |_ _ __ __ _(_)_ __
# | __| '__/ _` | | '_ \
# | |_| | | (_| | | | | |
# \__|_| \__,_|_|_| |_|
#
def step(self, global_step: int, rng: jnp.ndarray, # pytype: disable=signature-mismatch # jax-ndarray
*unused_args, **unused_kwargs):
"""See base class."""
if self._train_input is None:
self._initialize_train()
inputs = next(self._train_input)
self._params, self._state, self._opt_state, scalars = (
self._update_func(
self._params, self._state, self._opt_state, inputs, rng, global_step
))
scalars = jl_utils.get_first(scalars)
return scalars
def _initialize_train(self):
self._train_input = jl_utils.py_prefetch(self._build_train_input)
total_batch_size = self.config.training.batch_size
steps_per_epoch = (
self.config.training.images_per_epoch / self.config.training.batch_size)
total_steps = self.config.training.n_epochs * steps_per_epoch
# Scale by the (negative) learning rate.
self._lr_schedule = utils.get_learning_rate_schedule(
total_batch_size, steps_per_epoch, total_steps, self.config.optimizer)
self._optimizer = utils.make_optimizer(
self.config.optimizer,
self._lr_schedule)
# Check we haven't already restored params
if self._params is None:
logging.info('Initializing parameters.')
inputs = next(self._train_input)
init_net = jax.pmap(lambda *a: self.forward.init(*a, is_training=True))
init_opt = jax.pmap(self._optimizer.init)
# Init uses the same RNG key on all hosts+devices to ensure everyone
# computes the same initial state.
init_rng = jl_utils.bcast_local_devices(self.init_rng)
self._params, self._state = init_net(init_rng, inputs)
self._opt_state = init_opt(self._params)
def _load_data(self, split, is_training, batch_dims):
"""Wrapper for dataset loading."""
return dataset.load(
split=split,
is_training=is_training,
batch_dims=batch_dims,
im_dim=self.config.data.im_dim,
augmentation_settings=self.config.data.augmentation,
)
def _build_train_input(self) -> Generator[dataset.Batch, None, None]:
"""See base class."""
num_devices = jax.device_count()
global_batch_size = self.config.training.batch_size
per_device_batch_size, ragged = divmod(global_batch_size, num_devices)
if ragged:
raise ValueError(
f'Global batch size {global_batch_size} must be divisible by '
f'num devices {num_devices}')
split = dataset.Split.TRAIN_AND_VALID
return self._load_data(
split=split,
is_training=True,
batch_dims=[jax.local_device_count(), per_device_batch_size])
def _one_hot(self, value):
"""One-hot encoding potentially over a sequence of labels."""
y = jax.nn.one_hot(value, self.config.data.num_classes)
return y
def _loss_fn(
self,
params: hk.Params,
state: hk.State,
inputs: dataset.Batch,
rng: jnp.ndarray,
) -> Tuple[jnp.ndarray, Tuple[Scalars, hk.State]]:
logits, state = self.forward.apply(
params, state, rng, inputs, is_training=True)
label = self._one_hot(inputs['labels'])
# Handle cutmix/mixup label mixing:
if 'mix_labels' in inputs:
logging.info('Using mixup or cutmix!')
mix_label = self._one_hot(inputs['mix_labels'])
mix_ratio = inputs['ratio'][:, None]
label = mix_ratio * label + (1. - mix_ratio) * mix_label
# Apply label-smoothing to one-hot labels.
label_smoothing = self.config.training.label_smoothing
if not (label_smoothing >= 0. and label_smoothing < 1.):
raise ValueError(
f"'label_smoothing is {label_smoothing} and should be in [0, 1)")
if label_smoothing > 0:
smooth_positives = 1. - label_smoothing
smooth_negatives = label_smoothing / self.config.data.num_classes
label = smooth_positives * label + smooth_negatives
loss_w_batch = utils.softmax_cross_entropy(logits, label)
loss = jnp.mean(loss_w_batch, dtype=loss_w_batch.dtype)
scaled_loss = loss / jax.device_count()
metrics = utils.topk_correct(logits, inputs['labels'], prefix='')
metrics = jax.tree_map(jnp.mean, metrics)
top_1_acc = metrics['top_1_acc']
top_5_acc = metrics['top_5_acc']
loss_scalars = dict(
loss=loss,
top_1_acc=top_1_acc,
top_5_acc=top_5_acc,
)
return scaled_loss, (loss_scalars, state)
def _update_func(
self,
params: hk.Params,
state: hk.State,
opt_state: OptState,
inputs: dataset.Batch,
rng: jnp.ndarray,
global_step: int,
) -> Tuple[hk.Params, hk.State, OptState, Scalars]:
"""Applies an update to parameters and returns new state."""
# This function computes the gradient of the first output of loss_fn and
# passes through the other arguments unchanged.
grad_loss_fn = jax.grad(self._loss_fn, has_aux=True)
scaled_grads, (loss_scalars, state) = grad_loss_fn(
params, state, inputs, rng)
grads = jax.lax.psum(scaled_grads, axis_name='i')
# Grab the learning rate to log before performing the step.
learning_rate = self._lr_schedule(global_step)
# Compute and apply updates via our optimizer.
updates, opt_state = self._optimizer.update(grads, opt_state, params)
params = optax.apply_updates(params, updates)
n_params = 0
for k in params.keys(): # pytype: disable=attribute-error # numpy-scalars
for l in params[k]:
n_params = n_params + np.prod(params[k][l].shape) # pytype: disable=attribute-error # numpy-scalars
# Scalars to log (note: we log the mean across all hosts/devices).
scalars = {'learning_rate': learning_rate,
'n_params (M)': float(n_params/1e6),
'global_gradient_norm': optax.global_norm(grads)}
loss_scalars = {f'train_{k}': v for k, v in loss_scalars.items()}
scalars.update(loss_scalars)
scalars = jax.lax.pmean(scalars, axis_name='i')
return params, state, opt_state, scalars
# _
# _____ ____ _| |
# / _ \ \ / / _` | |
# | __/\ V / (_| | |
# \___| \_/ \__,_|_|
#
def evaluate(self, global_step, rng, **unused_args):
"""See base class."""
global_step = np.array(jl_utils.get_first(global_step))
scalars = jax.device_get(self._eval_epoch(jl_utils.get_first(rng)))
logging.info('[Step %d] Eval scalars: %s', global_step, scalars)
return scalars
def _eval_batch(
self,
params: hk.Params,
state: hk.State,
inputs: dataset.Batch,
rng: jnp.ndarray,
) -> Scalars:
"""Evaluates a batch."""
logits, _ = self.forward.apply(
params, state, rng, inputs, is_training=False)
labels = self._one_hot(inputs['labels'])
loss = utils.softmax_cross_entropy(logits, labels)
metrics = utils.topk_correct(logits, inputs['labels'], prefix='')
metrics = jax.tree_map(jnp.mean, metrics)
top_1_acc = metrics['top_1_acc']
top_5_acc = metrics['top_5_acc']
bs = logits.shape[0]
top_1_acc = jnp.expand_dims(top_1_acc, axis=0) * bs
top_5_acc = jnp.expand_dims(top_5_acc, axis=0) * bs
# NOTE: Returned values will be summed and finally divided by num_samples.
return {
'eval_loss': loss,
'eval_top_1_acc': top_1_acc, 'eval_top_5_acc': top_5_acc}
def _build_eval_input(self) -> Generator[dataset.Batch, None, None]:
split = dataset.Split.from_string(self.config.evaluation.subset)
return self._load_data(
split=split,
is_training=False,
batch_dims=[self.config.evaluation.batch_size])
def _eval_epoch(self, rng):
"""Evaluates an epoch."""
num_samples = 0.
summed_scalars = None
params = jl_utils.get_first(self._params)
state = jl_utils.get_first(self._state)
for inputs in self._build_eval_input():
num_samples += inputs['labels'].shape[0]
scalars = self._eval_batch(params, state, inputs, rng)
# Accumulate the sum of scalars for each step.
scalars = jax.tree_map(lambda x: jnp.sum(x, axis=0), scalars)
if summed_scalars is None:
summed_scalars = scalars
else:
summed_scalars = jax.tree_map(jnp.add, summed_scalars, scalars)
mean_scalars = jax.tree_map(lambda x: x / num_samples, summed_scalars)
return mean_scalars
if __name__ == '__main__':
flags.mark_flag_as_required('config')
app.run(functools.partial(platform.main, Experiment))
|
deepmind-research-master
|
perceiver/train/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.
"""Utilities."""
from typing import Callable, List, Mapping, NamedTuple, Optional, Tuple, Union
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
Batch = Mapping[str, np.ndarray]
OptState = Tuple[optax.TraceState, optax.ScaleByScheduleState, optax.ScaleState]
Scalars = Mapping[str, jnp.ndarray]
ParamsOrState = Union[hk.Params, hk.State]
NORM_NAMES = ['layer_norm', 'batchnorm']
# any_in and topk_correct taken from
# https://github.com/deepmind/deepmind-research/blob/master/nfnets/utils.py
@jax.vmap
def any_in(prediction, target):
"""For each row in a and b, checks if any element of a is in b."""
return jnp.isin(prediction, target)
def topk_correct(logits, labels, mask=None, prefix='', topk=(1, 5)):
"""Calculate top-k error for multiple k values."""
metrics = {}
argsorted_logits = jnp.argsort(logits)
for k in topk:
pred_labels = argsorted_logits[..., -k:]
# Get the number of examples where the label is in the top-k predictions
correct = any_in(pred_labels, labels).any(axis=-1).astype(jnp.float32)
if mask is not None:
correct *= mask
metrics[f'{prefix}top_{k}_acc'] = correct
return metrics
def softmax_cross_entropy(logits, labels):
"""Computes softmax cross entropy given logits and one-hot class labels.
Args:
logits: Logit output values.
labels: Ground truth one-hot-encoded labels.
Returns:
Loss value with the same shape as `labels`;
"""
return jnp.asarray(optax.softmax_cross_entropy(logits, labels))
def _get_batch_scaled_lr(total_batch_size, lr, scale_by_batch=True):
# This is the linear scaling rule in Section 5.1 of
# https://arxiv.org/pdf/1706.02677.pdf.
if scale_by_batch:
lr = (lr * total_batch_size) / 256
return lr
def get_learning_rate_schedule(
total_batch_size, steps_per_epoch, total_steps, optimizer_config):
"""Build the learning rate schedule function."""
base_lr = _get_batch_scaled_lr(total_batch_size, optimizer_config.base_lr,
optimizer_config.scale_by_batch)
schedule_type = optimizer_config.schedule_type
if schedule_type == 'steps':
boundaries = optimizer_config.step_decay_kwargs.decay_boundaries
boundaries.sort()
decay_rate = optimizer_config.step_decay_kwargs.decay_rate
boundaries_and_scales = {
int(boundary * total_steps): decay_rate for boundary in boundaries}
schedule_fn = optax.piecewise_constant_schedule(
init_value=base_lr, boundaries_and_scales=boundaries_and_scales)
elif schedule_type == 'cosine':
warmup_steps = (optimizer_config.cosine_decay_kwargs.warmup_epochs
* steps_per_epoch)
# Batch scale the other lr values as well:
init_value = _get_batch_scaled_lr(
total_batch_size,
optimizer_config.cosine_decay_kwargs.init_value,
optimizer_config.scale_by_batch)
end_value = _get_batch_scaled_lr(
total_batch_size,
optimizer_config.cosine_decay_kwargs.end_value,
optimizer_config.scale_by_batch)
schedule_fn = optax.warmup_cosine_decay_schedule(
init_value=init_value,
peak_value=base_lr,
warmup_steps=warmup_steps,
decay_steps=total_steps,
end_value=end_value)
elif schedule_type == 'constant_cosine':
# Convert end_value to alpha, used by cosine_decay_schedule.
alpha = optimizer_config.constant_cosine_decay_kwargs.end_value / base_lr
# Number of steps spent in constant phase.
constant_steps = int(
optimizer_config.constant_cosine_decay_kwargs.constant_fraction
* total_steps)
decay_steps = total_steps - constant_steps
constant_phase = optax.constant_schedule(value=base_lr)
decay_phase = optax.cosine_decay_schedule(
init_value=base_lr,
decay_steps=decay_steps,
alpha=alpha)
schedule_fn = optax.join_schedules(
schedules=[constant_phase, decay_phase],
boundaries=[constant_steps])
else:
raise ValueError(f'Unknown learning rate schedule: {schedule_type}')
return schedule_fn
def _weight_decay_exclude(
exclude_names: Optional[List[str]] = None
) -> Callable[[str, str, jnp.ndarray], bool]:
"""Logic for deciding which parameters to include for weight decay..
Args:
exclude_names: an optional list of names to include for weight_decay. ['w']
by default.
Returns:
A predicate that returns True for params that need to be excluded from
weight_decay.
"""
# By default weight_decay the weights but not the biases.
if not exclude_names:
exclude_names = ['b']
def exclude(module_name: str, name: str, value: jnp.array):
del value
# Do not weight decay the parameters of normalization blocks.
if any([norm_name in module_name for norm_name in NORM_NAMES]):
return True
else:
return name in exclude_names
return exclude
class AddWeightDecayState(NamedTuple):
"""Stateless transformation."""
def add_weight_decay(
weight_decay: float,
exclude_names: Optional[List[str]] = None) -> optax.GradientTransformation:
"""Add parameter scaled by `weight_decay` to the `updates`.
Same as optax.add_decayed_weights but can exclude parameters by name.
Args:
weight_decay: weight_decay coefficient.
exclude_names: an optional list of names to exclude for weight_decay. ['b']
by default.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return AddWeightDecayState()
def update_fn(updates, state, params):
exclude = _weight_decay_exclude(exclude_names=exclude_names)
u_ex, u_in = hk.data_structures.partition(exclude, updates)
_, p_in = hk.data_structures.partition(exclude, params)
u_in = jax.tree_map(lambda g, p: g + weight_decay * p, u_in, p_in)
updates = hk.data_structures.merge(u_ex, u_in)
return updates, state
return optax.GradientTransformation(init_fn, update_fn)
def make_optimizer(optimizer_config, lr_schedule):
"""Construct the optax optimizer with given LR schedule."""
if (optimizer_config.get('decay_pos_embs') is None or
optimizer_config.decay_pos_embs):
# Decay learned position embeddings by default.
weight_decay_exclude_names = ['b']
else:
weight_decay_exclude_names = ['pos_embs', 'b']
optax_chain = []
if optimizer_config.max_norm > 0:
optax_chain.append(
optax.clip_by_global_norm(optimizer_config.max_norm))
if optimizer_config.optimizer == 'adam':
# See: https://arxiv.org/abs/1412.6980
optax_chain.extend([
optax.scale_by_adam(**optimizer_config.adam_kwargs),
add_weight_decay(
optimizer_config.weight_decay,
exclude_names=weight_decay_exclude_names)
])
elif optimizer_config.optimizer == 'lamb':
# See: https://arxiv.org/abs/1904.00962
optax_chain.extend([
optax.scale_by_adam(**optimizer_config.lamb_kwargs),
add_weight_decay(
optimizer_config.weight_decay,
exclude_names=weight_decay_exclude_names),
optax.scale_by_trust_ratio()
])
else:
raise ValueError(f'Undefined optimizer {optimizer_config.optimizer}')
# Scale by the (negative) learning rate.
optax_chain.extend([
optax.scale_by_schedule(lr_schedule),
optax.scale(-1),
])
return optax.chain(*optax_chain)
|
deepmind-research-master
|
perceiver/train/utils.py
|
# Copyright 2019 The TensorFlow Authors. 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.
# ==============================================================================
"""AutoAugment and RandAugment policies for enhanced image preprocessing.
AutoAugment Reference: https://arxiv.org/abs/1805.09501
RandAugment Reference: https://arxiv.org/abs/1909.13719
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import math
from ml_collections import config_dict
import tensorflow.compat.v1 as tf
from tensorflow_addons import image as contrib_image
# pylint: disable=deprecated-method
# This signifies the max integer that the controller RNN could predict for the
# augmentation scheme.
_MAX_LEVEL = 10.
def policy_v0():
"""Autoaugment policy that was used in AutoAugment Paper."""
# Each tuple is an augmentation operation of the form
# (operation, probability, magnitude). Each element in policy is a
# sub-policy that will be applied sequentially on the image.
policy = [
[('Equalize', 0.8, 1), ('ShearY', 0.8, 4)],
[('Color', 0.4, 9), ('Equalize', 0.6, 3)],
[('Color', 0.4, 1), ('Rotate', 0.6, 8)],
[('Solarize', 0.8, 3), ('Equalize', 0.4, 7)],
[('Solarize', 0.4, 2), ('Solarize', 0.6, 2)],
[('Color', 0.2, 0), ('Equalize', 0.8, 8)],
[('Equalize', 0.4, 8), ('SolarizeAdd', 0.8, 3)],
[('ShearX', 0.2, 9), ('Rotate', 0.6, 8)],
[('Color', 0.6, 1), ('Equalize', 1.0, 2)],
[('Invert', 0.4, 9), ('Rotate', 0.6, 0)],
[('Equalize', 1.0, 9), ('ShearY', 0.6, 3)],
[('Color', 0.4, 7), ('Equalize', 0.6, 0)],
[('Posterize', 0.4, 6), ('AutoContrast', 0.4, 7)],
[('Solarize', 0.6, 8), ('Color', 0.6, 9)],
[('Solarize', 0.2, 4), ('Rotate', 0.8, 9)],
[('Rotate', 1.0, 7), ('TranslateY', 0.8, 9)],
[('ShearX', 0.0, 0), ('Solarize', 0.8, 4)],
[('ShearY', 0.8, 0), ('Color', 0.6, 4)],
[('Color', 1.0, 0), ('Rotate', 0.6, 2)],
[('Equalize', 0.8, 4), ('Equalize', 0.0, 8)],
[('Equalize', 1.0, 4), ('AutoContrast', 0.6, 2)],
[('ShearY', 0.4, 7), ('SolarizeAdd', 0.6, 7)],
[('Posterize', 0.8, 2), ('Solarize', 0.6, 10)],
[('Solarize', 0.6, 8), ('Equalize', 0.6, 1)],
[('Color', 0.8, 6), ('Rotate', 0.4, 5)],
]
return policy
def policy_vtest():
"""Autoaugment test policy for debugging."""
# Each tuple is an augmentation operation of the form
# (operation, probability, magnitude). Each element in policy is a
# sub-policy that will be applied sequentially on the image.
policy = [
[('TranslateX', 1.0, 4), ('Equalize', 1.0, 10)],
]
return policy
def blend(image1, image2, factor):
"""Blend image1 and image2 using 'factor'.
Factor can be above 0.0. A value of 0.0 means only image1 is used.
A value of 1.0 means only image2 is used. A value between 0.0 and
1.0 means we linearly interpolate the pixel values between the two
images. A value greater than 1.0 "extrapolates" the difference
between the two pixel values, and we clip the results to values
between 0 and 255.
Args:
image1: An image Tensor of type uint8.
image2: An image Tensor of type uint8.
factor: A floating point value above 0.0.
Returns:
A blended image Tensor of type uint8.
"""
if factor == 0.0:
return tf.convert_to_tensor(image1)
if factor == 1.0:
return tf.convert_to_tensor(image2)
image1 = tf.to_float(image1)
image2 = tf.to_float(image2)
difference = image2 - image1
scaled = factor * difference
# Do addition in float.
temp = tf.to_float(image1) + scaled
# Interpolate
if factor > 0.0 and factor < 1.0:
# Interpolation means we always stay within 0 and 255.
return tf.cast(temp, tf.uint8)
# Extrapolate:
#
# We need to clip and then cast.
return tf.cast(tf.clip_by_value(temp, 0.0, 255.0), tf.uint8)
def cutout(image, pad_size, replace=0):
"""Apply cutout (https://arxiv.org/abs/1708.04552) to image.
This operation applies a (2*pad_size x 2*pad_size) mask of zeros to
a random location within `img`. The pixel values filled in will be of the
value `replace`. The located where the mask will be applied is randomly
chosen uniformly over the whole image.
Args:
image: An image Tensor of type uint8.
pad_size: Specifies how big the zero mask that will be generated is that
is applied to the image. The mask will be of size
(2*pad_size x 2*pad_size).
replace: What pixel value to fill in the image in the area that has
the cutout mask applied to it.
Returns:
An image Tensor that is of type uint8.
"""
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
# Sample the center location in the image where the zero mask will be applied.
cutout_center_height = tf.random_uniform(
shape=[], minval=0, maxval=image_height,
dtype=tf.int32)
cutout_center_width = tf.random_uniform(
shape=[], minval=0, maxval=image_width,
dtype=tf.int32)
lower_pad = tf.maximum(0, cutout_center_height - pad_size)
upper_pad = tf.maximum(0, image_height - cutout_center_height - pad_size)
left_pad = tf.maximum(0, cutout_center_width - pad_size)
right_pad = tf.maximum(0, image_width - cutout_center_width - pad_size)
cutout_shape = [image_height - (lower_pad + upper_pad),
image_width - (left_pad + right_pad)]
padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
mask = tf.pad(
tf.zeros(cutout_shape, dtype=image.dtype),
padding_dims, constant_values=1)
mask = tf.expand_dims(mask, -1)
mask = tf.tile(mask, [1, 1, 3])
image = tf.where(
tf.equal(mask, 0),
tf.ones_like(image, dtype=image.dtype) * replace,
image)
return image
def solarize(image, threshold=128):
# For each pixel in the image, select the pixel
# if the value is less than the threshold.
# Otherwise, subtract the pixel from 255.
return tf.where(image < threshold, image, 255 - image)
def solarize_add(image, addition=0, threshold=128):
# For each pixel in the image less than threshold
# we add 'addition' amount to it and then clip the
# pixel value to be between 0 and 255. The value
# of 'addition' is between -128 and 128.
added_image = tf.cast(image, tf.int64) + addition
added_image = tf.cast(tf.clip_by_value(added_image, 0, 255), tf.uint8)
return tf.where(image < threshold, added_image, image)
def color(image, factor):
"""Equivalent of PIL Color."""
degenerate = tf.image.grayscale_to_rgb(tf.image.rgb_to_grayscale(image))
return blend(degenerate, image, factor)
def contrast(image, factor):
"""Equivalent of PIL Contrast."""
degenerate = tf.image.rgb_to_grayscale(image)
# Cast before calling tf.histogram.
degenerate = tf.cast(degenerate, tf.int32)
# Compute the grayscale histogram, then compute the mean pixel value,
# and create a constant image size of that value. Use that as the
# blending degenerate target of the original image.
hist = tf.histogram_fixed_width(degenerate, [0, 255], nbins=256)
mean = tf.reduce_sum(tf.cast(hist, tf.float32)) / 256.0
degenerate = tf.ones_like(degenerate, dtype=tf.float32) * mean
degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)
degenerate = tf.image.grayscale_to_rgb(tf.cast(degenerate, tf.uint8))
return blend(degenerate, image, factor)
def brightness(image, factor):
"""Equivalent of PIL Brightness."""
degenerate = tf.zeros_like(image)
return blend(degenerate, image, factor)
def posterize(image, bits):
"""Equivalent of PIL Posterize."""
shift = 8 - bits
return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift)
def rotate(image, degrees, replace):
"""Rotates the image by degrees either clockwise or counterclockwise.
Args:
image: An image Tensor of type uint8.
degrees: Float, a scalar angle in degrees to rotate all images by. If
degrees is positive the image will be rotated clockwise otherwise it will
be rotated counterclockwise.
replace: A one or three value 1D tensor to fill empty pixels caused by
the rotate operation.
Returns:
The rotated version of image.
"""
# Convert from degrees to radians.
degrees_to_radians = math.pi / 180.0
radians = degrees * degrees_to_radians
# In practice, we should randomize the rotation degrees by flipping
# it negatively half the time, but that's done on 'degrees' outside
# of the function.
image = contrib_image.rotate(wrap(image), radians)
return unwrap(image, replace)
def translate_x(image, pixels, replace):
"""Equivalent of PIL Translate in X dimension."""
image = contrib_image.translate(wrap(image), [-pixels, 0])
return unwrap(image, replace)
def translate_y(image, pixels, replace):
"""Equivalent of PIL Translate in Y dimension."""
image = contrib_image.translate(wrap(image), [0, -pixels])
return unwrap(image, replace)
def shear_x(image, level, replace):
"""Equivalent of PIL Shearing in X dimension."""
# Shear parallel to x axis is a projective transform
# with a matrix form of:
# [1 level
# 0 1].
image = contrib_image.transform(
wrap(image), [1., level, 0., 0., 1., 0., 0., 0.])
return unwrap(image, replace)
def shear_y(image, level, replace):
"""Equivalent of PIL Shearing in Y dimension."""
# Shear parallel to y axis is a projective transform
# with a matrix form of:
# [1 0
# level 1].
image = contrib_image.transform(
wrap(image), [1., 0., 0., level, 1., 0., 0., 0.])
return unwrap(image, replace)
def autocontrast(image):
"""Implements Autocontrast function from PIL using TF ops.
Args:
image: A 3D uint8 tensor.
Returns:
The image after it has had autocontrast applied to it and will be of type
uint8.
"""
def scale_channel(image):
"""Scale the 2D image using the autocontrast rule."""
# A possibly cheaper version can be done using cumsum/unique_with_counts
# over the histogram values, rather than iterating over the entire image.
# to compute mins and maxes.
lo = tf.to_float(tf.reduce_min(image))
hi = tf.to_float(tf.reduce_max(image))
# Scale the image, making the lowest value 0 and the highest value 255.
def scale_values(im):
scale = 255.0 / (hi - lo)
offset = -lo * scale
im = tf.to_float(im) * scale + offset
im = tf.clip_by_value(im, 0.0, 255.0)
return tf.cast(im, tf.uint8)
result = tf.cond(hi > lo, lambda: scale_values(image), lambda: image)
return result
# Assumes RGB for now. Scales each channel independently
# and then stacks the result.
s1 = scale_channel(image[:, :, 0])
s2 = scale_channel(image[:, :, 1])
s3 = scale_channel(image[:, :, 2])
image = tf.stack([s1, s2, s3], 2)
return image
def sharpness(image, factor):
"""Implements Sharpness function from PIL using TF ops."""
orig_image = image
image = tf.cast(image, tf.float32)
# Make image 4D for conv operation.
image = tf.expand_dims(image, 0)
# SMOOTH PIL Kernel.
kernel = tf.constant(
[[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=tf.float32,
shape=[3, 3, 1, 1]) / 13.
# Tile across channel dimension.
kernel = tf.tile(kernel, [1, 1, 3, 1])
strides = [1, 1, 1, 1]
with tf.device('/cpu:0'):
# Some augmentation that uses depth-wise conv will cause crashing when
# training on GPU. See (b/156242594) for details.
degenerate = tf.nn.depthwise_conv2d(
image, kernel, strides, padding='VALID', rate=[1, 1])
degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)
degenerate = tf.squeeze(tf.cast(degenerate, tf.uint8), [0])
# For the borders of the resulting image, fill in the values of the
# original image.
mask = tf.ones_like(degenerate)
padded_mask = tf.pad(mask, [[1, 1], [1, 1], [0, 0]])
padded_degenerate = tf.pad(degenerate, [[1, 1], [1, 1], [0, 0]])
result = tf.where(tf.equal(padded_mask, 1), padded_degenerate, orig_image)
# Blend the final result.
return blend(result, orig_image, factor)
def equalize(image):
"""Implements Equalize function from PIL using TF ops."""
def scale_channel(im, c):
"""Scale the data in the channel to implement equalize."""
im = tf.cast(im[:, :, c], tf.int32)
# Compute the histogram of the image channel.
histo = tf.histogram_fixed_width(im, [0, 255], nbins=256)
# For the purposes of computing the step, filter out the nonzeros.
nonzero = tf.where(tf.not_equal(histo, 0))
nonzero_histo = tf.reshape(tf.gather(histo, nonzero), [-1])
step = (tf.reduce_sum(nonzero_histo) - nonzero_histo[-1]) // 255
def build_lut(histo, step):
# Compute the cumulative sum, shifting by step // 2
# and then normalization by step.
lut = (tf.cumsum(histo) + (step // 2)) // step
# Shift lut, prepending with 0.
lut = tf.concat([[0], lut[:-1]], 0)
# Clip the counts to be in range. This is done
# in the C code for image.point.
return tf.clip_by_value(lut, 0, 255)
# If step is zero, return the original image. Otherwise, build
# lut from the full histogram and step and then index from it.
result = tf.cond(tf.equal(step, 0),
lambda: im,
lambda: tf.gather(build_lut(histo, step), im))
return tf.cast(result, tf.uint8)
# Assumes RGB for now. Scales each channel independently
# and then stacks the result.
s1 = scale_channel(image, 0)
s2 = scale_channel(image, 1)
s3 = scale_channel(image, 2)
image = tf.stack([s1, s2, s3], 2)
return image
def invert(image):
"""Inverts the image pixels."""
image = tf.convert_to_tensor(image)
return 255 - image
def wrap(image):
"""Returns 'image' with an extra channel set to all 1s."""
shape = tf.shape(image)
extended_channel = tf.ones([shape[0], shape[1], 1], image.dtype)
extended = tf.concat([image, extended_channel], 2)
return extended
def unwrap(image, replace):
"""Unwraps an image produced by wrap.
Where there is a 0 in the last channel for every spatial position,
the rest of the three channels in that spatial dimension are grayed
(set to 128). Operations like translate and shear on a wrapped
Tensor will leave 0s in empty locations. Some transformations look
at the intensity of values to do preprocessing, and we want these
empty pixels to assume the 'average' value, rather than pure black.
Args:
image: A 3D Image Tensor with 4 channels.
replace: A one or three value 1D tensor to fill empty pixels.
Returns:
image: A 3D image Tensor with 3 channels.
"""
image_shape = tf.shape(image)
# Flatten the spatial dimensions.
flattened_image = tf.reshape(image, [-1, image_shape[2]])
# Find all pixels where the last channel is zero.
alpha_channel = flattened_image[:, 3]
replace = tf.concat([replace, tf.ones([1], image.dtype)], 0)
# Where they are zero, fill them in with 'replace'.
flattened_image = tf.where(
tf.equal(alpha_channel, 0),
tf.ones_like(flattened_image, dtype=image.dtype) * replace,
flattened_image)
image = tf.reshape(flattened_image, image_shape)
image = tf.slice(image, [0, 0, 0], [image_shape[0], image_shape[1], 3])
return image
NAME_TO_FUNC = {
'AutoContrast': autocontrast,
'Equalize': equalize,
'Invert': invert,
'Rotate': rotate,
'Posterize': posterize,
'Solarize': solarize,
'SolarizeAdd': solarize_add,
'Color': color,
'Contrast': contrast,
'Brightness': brightness,
'Sharpness': sharpness,
'ShearX': shear_x,
'ShearY': shear_y,
'TranslateX': translate_x,
'TranslateY': translate_y,
'Cutout': cutout,
}
def _randomly_negate_tensor(tensor):
"""With 50% prob turn the tensor negative."""
should_flip = tf.cast(tf.floor(tf.random_uniform([]) + 0.5), tf.bool)
final_tensor = tf.cond(should_flip, lambda: tensor, lambda: -tensor)
return final_tensor
def _rotate_level_to_arg(level):
level = (level/_MAX_LEVEL) * 30.
level = _randomly_negate_tensor(level)
return (level,)
def _shrink_level_to_arg(level):
"""Converts level to ratio by which we shrink the image content."""
if level == 0:
return (1.0,) # if level is zero, do not shrink the image
# Maximum shrinking ratio is 2.9.
level = 2. / (_MAX_LEVEL / level) + 0.9
return (level,)
def _enhance_level_to_arg(level):
return ((level/_MAX_LEVEL) * 1.8 + 0.1,)
def _shear_level_to_arg(level):
level = (level/_MAX_LEVEL) * 0.3
# Flip level to negative with 50% chance.
level = _randomly_negate_tensor(level)
return (level,)
def _translate_level_to_arg(level, translate_const):
level = (level/_MAX_LEVEL) * float(translate_const)
# Flip level to negative with 50% chance.
level = _randomly_negate_tensor(level)
return (level,)
def level_to_arg(hparams):
return {
'AutoContrast': lambda level: (),
'Equalize': lambda level: (),
'Invert': lambda level: (),
'Rotate': _rotate_level_to_arg,
'Posterize': lambda level: (int((level/_MAX_LEVEL) * 4),),
'Solarize': lambda level: (int((level/_MAX_LEVEL) * 256),),
'SolarizeAdd': lambda level: (int((level/_MAX_LEVEL) * 110),),
'Color': _enhance_level_to_arg,
'Contrast': _enhance_level_to_arg,
'Brightness': _enhance_level_to_arg,
'Sharpness': _enhance_level_to_arg,
'ShearX': _shear_level_to_arg,
'ShearY': _shear_level_to_arg,
'Cutout': lambda level: (int((level/_MAX_LEVEL) * hparams.cutout_const),),
# pylint:disable=g-long-lambda
'TranslateX': lambda level: _translate_level_to_arg(
level, hparams.translate_const),
'TranslateY': lambda level: _translate_level_to_arg(
level, hparams.translate_const),
# pylint:enable=g-long-lambda
}
def _parse_policy_info(name, prob, level, replace_value, augmentation_hparams):
"""Return the function that corresponds to `name` and update `level` param."""
func = NAME_TO_FUNC[name]
args = level_to_arg(augmentation_hparams)[name](level)
# Check to see if prob is passed into function. This is used for operations
# where we alter bboxes independently.
# pytype:disable=wrong-arg-types
if 'prob' in inspect.getargspec(func)[0]:
args = tuple([prob] + list(args))
# pytype:enable=wrong-arg-types
# Add in replace arg if it is required for the function that is being called.
# pytype:disable=wrong-arg-types
if 'replace' in inspect.getargspec(func)[0]:
# Make sure replace is the final argument
assert 'replace' == inspect.getargspec(func)[0][-1]
args = tuple(list(args) + [replace_value])
# pytype:enable=wrong-arg-types
return (func, prob, args)
def _apply_func_with_prob(func, image, args, prob):
"""Apply `func` to image w/ `args` as input with probability `prob`."""
assert isinstance(args, tuple)
# If prob is a function argument, then this randomness is being handled
# inside the function, so make sure it is always called.
# pytype:disable=wrong-arg-types
if 'prob' in inspect.getargspec(func)[0]:
prob = 1.0
# pytype:enable=wrong-arg-types
# Apply the function with probability `prob`.
should_apply_op = tf.cast(
tf.floor(tf.random_uniform([], dtype=tf.float32) + prob), tf.bool)
augmented_image = tf.cond(
should_apply_op,
lambda: func(image, *args),
lambda: image)
return augmented_image
def select_and_apply_random_policy(policies, image):
"""Select a random policy from `policies` and apply it to `image`."""
policy_to_select = tf.random_uniform([], maxval=len(policies), dtype=tf.int32)
# Note that using tf.case instead of tf.conds would result in significantly
# larger graphs and would even break export for some larger policies.
for (i, policy) in enumerate(policies):
image = tf.cond(
tf.equal(i, policy_to_select),
lambda selected_policy=policy: selected_policy(image),
lambda: image)
return image
def build_and_apply_nas_policy(policies, image,
augmentation_hparams):
"""Build a policy from the given policies passed in and apply to image.
Args:
policies: list of lists of tuples in the form `(func, prob, level)`, `func`
is a string name of the augmentation function, `prob` is the probability
of applying the `func` operation, `level` is the input argument for
`func`.
image: tf.Tensor that the resulting policy will be applied to.
augmentation_hparams: Hparams associated with the NAS learned policy.
Returns:
A version of image that now has data augmentation applied to it based on
the `policies` pass into the function.
"""
replace_value = [128, 128, 128]
# func is the string name of the augmentation function, prob is the
# probability of applying the operation and level is the parameter associated
# with the tf op.
# tf_policies are functions that take in an image and return an augmented
# image.
tf_policies = []
for policy in policies:
tf_policy = []
# Link string name to the correct python function and make sure the correct
# argument is passed into that function.
for policy_info in policy:
policy_info = list(policy_info) + [replace_value, augmentation_hparams]
tf_policy.append(_parse_policy_info(*policy_info))
# Now build the tf policy that will apply the augmentation procedue
# on image.
def make_final_policy(tf_policy_):
def final_policy(image_):
for func, prob, args in tf_policy_:
image_ = _apply_func_with_prob(
func, image_, args, prob)
return image_
return final_policy
tf_policies.append(make_final_policy(tf_policy))
augmented_image = select_and_apply_random_policy(
tf_policies, image)
return augmented_image
def distort_image_with_autoaugment(image, augmentation_name):
"""Applies the AutoAugment policy to `image`.
AutoAugment is from the paper: https://arxiv.org/abs/1805.09501.
Args:
image: `Tensor` of shape [height, width, 3] representing an image.
augmentation_name: The name of the AutoAugment policy to use. The available
options are `v0` and `test`. `v0` is the policy used for
all of the results in the paper and was found to achieve the best results
on the COCO dataset. `v1`, `v2` and `v3` are additional good policies
found on the COCO dataset that have slight variation in what operations
were used during the search procedure along with how many operations are
applied in parallel to a single image (2 vs 3).
Returns:
A tuple containing the augmented versions of `image`.
"""
available_policies = {'v0': policy_v0,
'test': policy_vtest}
if augmentation_name not in available_policies:
raise ValueError('Invalid augmentation_name: {}'.format(augmentation_name))
policy = available_policies[augmentation_name]()
# Hparams that will be used for AutoAugment.
augmentation_hparams = config_dict.ConfigDict(dict(
cutout_const=100, translate_const=250))
return build_and_apply_nas_policy(policy, image, augmentation_hparams)
def distort_image_with_randaugment(image, num_layers, magnitude):
"""Applies the RandAugment policy to `image`.
RandAugment is from the paper https://arxiv.org/abs/1909.13719,
Args:
image: `Tensor` of shape [height, width, 3] representing an image.
num_layers: Integer, the number of augmentation transformations to apply
sequentially to an image. Represented as (N) in the paper. Usually best
values will be in the range [1, 3].
magnitude: Integer, shared magnitude across all augmentation operations.
Represented as (M) in the paper. Usually best values are in the range
[5, 30].
Returns:
The augmented version of `image`.
"""
replace_value = [128] * 3
tf.logging.info('Using RandAug.')
augmentation_hparams = config_dict.ConfigDict(dict(
cutout_const=40, translate_const=100))
available_ops = [
'AutoContrast', 'Equalize', 'Invert', 'Rotate', 'Posterize',
'Solarize', 'Color', 'Contrast', 'Brightness', 'Sharpness',
'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Cutout', 'SolarizeAdd']
for layer_num in range(num_layers):
op_to_select = tf.random_uniform(
[], maxval=len(available_ops), dtype=tf.int32)
random_magnitude = float(magnitude)
with tf.name_scope('randaug_layer_{}'.format(layer_num)):
for (i, op_name) in enumerate(available_ops):
prob = tf.random_uniform([], minval=0.2, maxval=0.8, dtype=tf.float32)
func, _, args = _parse_policy_info(op_name, prob, random_magnitude,
replace_value, augmentation_hparams)
image = tf.cond(
tf.equal(i, op_to_select),
# pylint:disable=g-long-lambda
lambda selected_func=func, selected_args=args: selected_func(
image, *selected_args),
# pylint:enable=g-long-lambda
lambda: image)
return image
|
deepmind-research-master
|
perceiver/train/autoaugment.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.
"""Atari RL Unplugged datasets.
Examples in the dataset represent SARSA transitions stored during a
DQN training run as described in https://arxiv.org/pdf/1907.04543.
For every training run we have recorded all 50 million transitions corresponding
to 200 million environment steps (4x factor because of frame skipping). There
are 5 separate datasets for each of the 45 games.
Every transition in the dataset is a tuple containing the following features:
* o_t: Observation at time t. Observations have been processed using the
canonical Atari frame processing, including 4x frame stacking. The shape
of a single observation is [84, 84, 4].
* a_t: Action taken at time t.
* r_t: Reward after a_t.
* d_t: Discount after a_t.
* o_tp1: Observation at time t+1.
* a_tp1: Action at time t+1.
* extras:
* episode_id: Episode identifier.
* episode_return: Total episode return computed using per-step [-1, 1]
clipping.
"""
import functools
import os
from typing import Dict
from acme import wrappers
import dm_env
from dm_env import specs
from dopamine.discrete_domains import atari_lib
import reverb
import tensorflow as tf
# 9 tuning games.
TUNING_SUITE = [
'BeamRider',
'DemonAttack',
'DoubleDunk',
'IceHockey',
'MsPacman',
'Pooyan',
'RoadRunner',
'Robotank',
'Zaxxon',
]
# 36 testing games.
TESTING_SUITE = [
'Alien',
'Amidar',
'Assault',
'Asterix',
'Atlantis',
'BankHeist',
'BattleZone',
'Boxing',
'Breakout',
'Carnival',
'Centipede',
'ChopperCommand',
'CrazyClimber',
'Enduro',
'FishingDerby',
'Freeway',
'Frostbite',
'Gopher',
'Gravitar',
'Hero',
'Jamesbond',
'Kangaroo',
'Krull',
'KungFuMaster',
'NameThisGame',
'Phoenix',
'Pong',
'Qbert',
'Riverraid',
'Seaquest',
'SpaceInvaders',
'StarGunner',
'TimePilot',
'UpNDown',
'VideoPinball',
'WizardOfWor',
'YarsRevenge',
]
# Total of 45 games.
ALL = TUNING_SUITE + TESTING_SUITE
def _decode_frames(pngs: tf.Tensor):
"""Decode PNGs.
Args:
pngs: String Tensor of size (4,) containing PNG encoded images.
Returns:
4 84x84 grayscale images packed in a (84, 84, 4) uint8 Tensor.
"""
# Statically unroll png decoding
frames = [tf.image.decode_png(pngs[i], channels=1) for i in range(4)]
frames = tf.concat(frames, axis=2)
frames.set_shape((84, 84, 4))
return frames
def _make_reverb_sample(o_t: tf.Tensor,
a_t: tf.Tensor,
r_t: tf.Tensor,
d_t: tf.Tensor,
o_tp1: tf.Tensor,
a_tp1: tf.Tensor,
extras: Dict[str, tf.Tensor]) -> reverb.ReplaySample:
"""Create Reverb sample with offline data.
Args:
o_t: Observation at time t.
a_t: Action at time t.
r_t: Reward at time t.
d_t: Discount at time t.
o_tp1: Observation at time t+1.
a_tp1: Action at time t+1.
extras: Dictionary with extra features.
Returns:
Replay sample with fake info: key=0, probability=1, table_size=0.
"""
info = reverb.SampleInfo(
key=tf.constant(0, tf.uint64),
probability=tf.constant(1.0, tf.float64),
table_size=tf.constant(0, tf.int64),
priority=tf.constant(1.0, tf.float64),
times_sampled=tf.constant(1, tf.int32))
data = (o_t, a_t, r_t, d_t, o_tp1, a_tp1, extras)
return reverb.ReplaySample(info=info, data=data)
def _tf_example_to_reverb_sample(tf_example: tf.train.Example
) -> reverb.ReplaySample:
"""Create a Reverb replay sample from a TF example."""
# Parse tf.Example.
feature_description = {
'o_t': tf.io.FixedLenFeature([4], tf.string),
'o_tp1': tf.io.FixedLenFeature([4], tf.string),
'a_t': tf.io.FixedLenFeature([], tf.int64),
'a_tp1': tf.io.FixedLenFeature([], tf.int64),
'r_t': tf.io.FixedLenFeature([], tf.float32),
'd_t': tf.io.FixedLenFeature([], tf.float32),
'episode_id': tf.io.FixedLenFeature([], tf.int64),
'episode_return': tf.io.FixedLenFeature([], tf.float32),
}
data = tf.io.parse_single_example(tf_example, feature_description)
# Process data.
o_t = _decode_frames(data['o_t'])
o_tp1 = _decode_frames(data['o_tp1'])
a_t = tf.cast(data['a_t'], tf.int32)
a_tp1 = tf.cast(data['a_tp1'], tf.int32)
episode_id = tf.bitcast(data['episode_id'], tf.uint64)
# Build Reverb replay sample.
extras = {
'episode_id': episode_id,
'return': data['episode_return']
}
return _make_reverb_sample(o_t, a_t, data['r_t'], data['d_t'], o_tp1, a_tp1,
extras)
def dataset(path: str,
game: str,
run: int,
num_shards: int = 100,
shuffle_buffer_size: int = 100000) -> tf.data.Dataset:
"""TF dataset of Atari SARSA tuples."""
path = os.path.join(path, f'{game}/run_{run}')
filenames = [f'{path}-{i:05d}-of-{num_shards:05d}' for i in range(num_shards)]
file_ds = tf.data.Dataset.from_tensor_slices(filenames)
file_ds = file_ds.repeat().shuffle(num_shards)
example_ds = file_ds.interleave(
functools.partial(tf.data.TFRecordDataset, compression_type='GZIP'),
cycle_length=tf.data.experimental.AUTOTUNE,
block_length=5)
example_ds = example_ds.shuffle(shuffle_buffer_size)
return example_ds.map(_tf_example_to_reverb_sample,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
class AtariDopamineWrapper(dm_env.Environment):
"""Wrapper for Atari Dopamine environmnet."""
def __init__(self, env, max_episode_steps=108000):
self._env = env
self._max_episode_steps = max_episode_steps
self._episode_steps = 0
self._reset_next_episode = True
def reset(self):
self._episode_steps = 0
self._reset_next_step = False
observation = self._env.reset()
return dm_env.restart(observation.squeeze(-1))
def step(self, action):
if self._reset_next_step:
return self.reset()
observation, reward, terminal, _ = self._env.step(action.item())
observation = observation.squeeze(-1)
discount = 1 - float(terminal)
self._episode_steps += 1
if terminal:
self._reset_next_episode = True
return dm_env.termination(reward, observation)
elif self._episode_steps == self._max_episode_steps:
self._reset_next_episode = True
return dm_env.truncation(reward, observation, discount)
else:
return dm_env.transition(reward, observation, discount)
def observation_spec(self):
space = self._env.observation_space
return specs.Array(space.shape[:-1], space.dtype)
def action_spec(self):
return specs.DiscreteArray(self._env.action_space.n)
def environment(game: str) -> dm_env.Environment:
"""Atari environment."""
env = atari_lib.create_atari_environment(game_name=game,
sticky_actions=True)
env = AtariDopamineWrapper(env)
env = wrappers.FrameStackingWrapper(env, num_frames=4)
return wrappers.SinglePrecisionWrapper(env)
|
deepmind-research-master
|
rl_unplugged/atari.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.
"""Real World RL for RL Unplugged datasets.
Examples in the dataset represent SARS transitions stored when running a
partially online trained agent as described in https://arxiv.org/abs/1904.12901.
We release 8 datasets in total -- with no combined challenge and easy combined
challenge on the cartpole, walker, quadruped, and humanoid tasks. For details
on how the dataset was generated, please refer to the paper.
Every transition in the dataset is a tuple containing the following features:
* o_t: Observation at time t. Observations have been processed using the
canonical
* a_t: Action taken at time t.
* r_t: Reward at time t.
* d_t: Discount at time t.
* o_tp1: Observation at time t+1.
* a_tp1: Action taken at time t+1. This is set to equal to the last action
for the last timestep.
Note that this serves as an example. For optimal data loading speed, consider
separating out data preprocessing from the data loading loop during training,
e.g. saving the preprocessed data.
"""
import collections
import functools
import os
from typing import Any, Dict, Optional, Sequence
from acme import wrappers
import dm_env
import realworldrl_suite.environments as rwrl_envs
import reverb
import tensorflow as tf
import tree
DELIMITER = ':'
# Control suite tasks have 1000 timesteps per episode. One additional timestep
# accounts for the very first observation where no action has been taken yet.
DEFAULT_NUM_TIMESTEPS = 1001
def _decombine_key(k: str, delimiter: str = DELIMITER) -> Sequence[str]:
return k.split(delimiter)
def tf_example_to_feature_description(example,
num_timesteps=DEFAULT_NUM_TIMESTEPS):
"""Takes a string tensor encoding an tf example and returns its features."""
if not tf.executing_eagerly():
raise AssertionError(
'tf_example_to_reverb_sample() only works under eager mode.')
example = tf.train.Example.FromString(example.numpy())
ret = {}
for k, v in example.features.feature.items():
l = len(v.float_list.value)
if l % num_timesteps:
raise ValueError('Unexpected feature length %d. It should be divisible '
'by num_timesteps: %d' % (l, num_timesteps))
size = l // num_timesteps
ret[k] = tf.io.FixedLenFeature([num_timesteps, size], tf.float32)
return ret
def tree_deflatten_with_delimiter(
flat_dict: Dict[str, Any], delimiter: str = DELIMITER) -> Dict[str, Any]:
"""De-flattens a dict to its originally nested structure.
Does the opposite of {combine_nested_keys(k) :v
for k, v in tree.flatten_with_path(nested_dicts)}
Example: {'a:b': 1} -> {'a': {'b': 1}}
Args:
flat_dict: the keys of which equals the `path` separated by `delimiter`.
delimiter: the delimiter that separates the keys of the nested dict.
Returns:
An un-flattened dict.
"""
root = collections.defaultdict(dict)
for delimited_key, v in flat_dict.items():
keys = _decombine_key(delimited_key, delimiter=delimiter)
node = root
for k in keys[:-1]:
node = node[k]
node[keys[-1]] = v
return dict(root)
def get_slice_of_nested(nested: Dict[str, Any], start: int,
end: int) -> Dict[str, Any]:
return tree.map_structure(lambda item: item[start:end], nested)
def repeat_last_and_append_to_nested(nested: Dict[str, Any]) -> Dict[str, Any]:
return tree.map_structure(
lambda item: tf.concat((item, item[-1:]), axis=0), nested)
def tf_example_to_reverb_sample(example,
feature_description,
num_timesteps=DEFAULT_NUM_TIMESTEPS):
"""Converts the episode encoded as a tf example into SARSA reverb samples."""
example = tf.io.parse_single_example(example, feature_description)
kv = tree_deflatten_with_delimiter(example)
output = (
get_slice_of_nested(kv['observation'], 0, num_timesteps - 1),
get_slice_of_nested(kv['action'], 1, num_timesteps),
kv['reward'][1:num_timesteps],
# The two fields below aren't needed for learning,
# but are kept here to be compatible with acme learner format.
kv['discount'][1:num_timesteps],
get_slice_of_nested(kv['observation'], 1, num_timesteps),
repeat_last_and_append_to_nested(
get_slice_of_nested(kv['action'], 2, num_timesteps)))
ret = tf.data.Dataset.from_tensor_slices(output)
ret = ret.map(lambda *x: reverb.ReplaySample(info=b'None', data=x)) # pytype: disable=wrong-arg-types
return ret
def dataset(path: str,
combined_challenge: str,
domain: str,
task: str,
difficulty: str,
num_shards: int = 100,
shuffle_buffer_size: int = 100000) -> tf.data.Dataset:
"""TF dataset of RWRL SARSA tuples."""
path = os.path.join(
path,
f'combined_challenge_{combined_challenge}/{domain}/{task}/'
f'offline_rl_challenge_{difficulty}'
)
filenames = [
f'{path}/episodes.tfrecord-{i:05d}-of-{num_shards:05d}'
for i in range(num_shards)
]
file_ds = tf.data.Dataset.from_tensor_slices(filenames)
file_ds = file_ds.repeat().shuffle(num_shards)
tf_example_ds = file_ds.interleave(
tf.data.TFRecordDataset,
cycle_length=tf.data.experimental.AUTOTUNE,
block_length=5)
# Take one item to get the output types and shapes.
example_item = None
for example_item in tf.data.TFRecordDataset(filenames[:1]).take(1):
break
if example_item is None:
raise ValueError('Empty dataset')
feature_description = tf_example_to_feature_description(example_item)
reverb_ds = tf_example_ds.interleave(
functools.partial(
tf_example_to_reverb_sample, feature_description=feature_description),
num_parallel_calls=tf.data.experimental.AUTOTUNE,
deterministic=False)
reverb_ds = reverb_ds.prefetch(100)
reverb_ds = reverb_ds.shuffle(shuffle_buffer_size)
return reverb_ds
def environment(
combined_challenge: str,
domain: str,
task: str,
log_output: Optional[str] = None,
environment_kwargs: Optional[Dict[str, Any]] = None) -> dm_env.Environment:
"""RWRL environment."""
env = rwrl_envs.load(
domain_name=domain,
task_name=task,
log_output=log_output,
environment_kwargs=environment_kwargs,
combined_challenge=combined_challenge)
return wrappers.SinglePrecisionWrapper(env)
|
deepmind-research-master
|
rl_unplugged/rwrl.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.
r"""Atari dataset example.
Instructions:
> mkdir -p /tmp/dataset/Asterix
> gsutil cp gs://rl_unplugged/atari/Asterix/run_1-00000-of-00100 \
/tmp/dataset/Asterix/run_1-00000-of-00001
> python atari_example.py --path=/tmp/dataset --game=Asterix
"""
from absl import app
from absl import flags
from acme import specs
import tree
from rl_unplugged import atari
flags.DEFINE_string('path', '/tmp/dataset', 'Path to dataset.')
flags.DEFINE_string('game', 'Asterix', 'Game.')
FLAGS = flags.FLAGS
def main(_):
ds = atari.dataset(FLAGS.path, FLAGS.game, 1,
num_shards=1,
shuffle_buffer_size=1)
for sample in ds.take(1):
print('Data spec')
print(tree.map_structure(lambda x: (x.dtype, x.shape), sample.data))
env = atari.environment(FLAGS.game)
print('Environment spec')
print(specs.make_environment_spec(env))
print('Environment observation')
timestep = env.reset()
print(tree.map_structure(lambda x: (x.dtype, x.shape), timestep.observation))
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
rl_unplugged/atari_example.py
|
# pylint: disable=line-too-long
# 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.
r"""RWRL dataset example.
Instructions:
> export TMP_PATH=/tmp/dataset/rwrl
> export DATA_PATH=combined_challenge_easy/quadruped/walk/offline_rl_challenge_easy
> mkdir -p $TMP_PATH/$DATA_PATH
> gsutil cp gs://rl_unplugged/rwrl/$DATA_PATH/episodes.tfrecord-00001-of-00015 \
$TMP_PATH/$DATA_PATH/episodes.tfrecord-00000-of-00001
> python rwrl_example.py --path=$TMP_PATH
"""
# pylint: enable=line-too-long
from absl import app
from absl import flags
import tree
from rl_unplugged import rwrl
flags.DEFINE_string('path', '/tmp/dataset', 'Path to dataset.')
def main(_):
ds = rwrl.dataset(
flags.FLAGS.path,
combined_challenge='easy',
domain='quadruped',
task='walk',
difficulty='easy',
num_shards=1,
shuffle_buffer_size=1)
for replay_sample in ds.take(1):
print(tree.map_structure(lambda x: (x.dtype, x.shape), replay_sample.data))
break
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
rl_unplugged/rwrl_example.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.
"""Networks used for training agents.
"""
from acme.tf import networks as acme_networks
from acme.tf import utils as tf2_utils
import numpy as np
import sonnet as snt
import tensorflow as tf
def instance_norm_and_elu(x):
mean = tf.reduce_mean(x, axis=[1, 2], keepdims=True)
x_ = x - mean
var = tf.reduce_mean(x_**2, axis=[1, 2], keepdims=True)
x_norm = x_ / (var + 1e-6)
return tf.nn.elu(x_norm)
class ControlNetwork(snt.Module):
"""Image, proprio and optionally action encoder used for actors and critics.
"""
def __init__(self,
proprio_encoder_size: int,
proprio_keys=None,
activation=tf.nn.elu):
"""Creates a ControlNetwork.
Args:
proprio_encoder_size: Size of the linear layer for the proprio encoder.
proprio_keys: Optional list of names of proprioceptive observations.
Defaults to all observations. Note that if this is specified, any
observation not contained in proprio_keys will be ignored by the agent.
activation: Linear layer activation function.
"""
super().__init__(name='control_network')
self._activation = activation
self._proprio_keys = proprio_keys
self._proprio_encoder = acme_networks.LayerNormMLP([proprio_encoder_size])
def __call__(self, inputs, action: tf.Tensor = None, task=None):
"""Evaluates the ControlNetwork.
Args:
inputs: A dictionary of agent observation tensors.
action: Agent actions.
task: Optional encoding of the task.
Raises:
ValueError: if neither proprio_input is provided.
ValueError: if some proprio input looks suspiciously like pixel inputs.
Returns:
Processed network output.
"""
if not isinstance(inputs, dict):
inputs = {'inputs': inputs}
proprio_input = []
# By default, treat all observations as proprioceptive.
if self._proprio_keys is None:
self._proprio_keys = list(sorted(inputs.keys()))
for key in self._proprio_keys:
proprio_input.append(snt.Flatten()(inputs[key]))
if np.prod(inputs[key].shape[1:]) > 32*32*3:
raise ValueError(
'This input does not resemble a proprioceptive '
'state: {} with shape {}'.format(
key, inputs[key].shape))
# Append optional action input (i.e. for critic networks).
if action is not None:
proprio_input.append(action)
proprio_input = tf2_utils.batch_concat(proprio_input)
proprio_state = self._proprio_encoder(proprio_input)
return proprio_state
|
deepmind-research-master
|
rl_unplugged/networks.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.
"""Control RL Unplugged datasets.
Examples in the dataset represent sequences stored when running a partially
trained agent (trained in online way) as described in
https://arxiv.org/abs/2006.13888.
Every dataset has a SARSA version, and datasets for environments for solving
which we believe one may need a recurrent agent also include a version of the
dataset with overlapping sequences of length 40.
Datasets for the dm_control_suite environments only include proprio
observations, while datasets for dm_locomotion include both pixel and proprio
observations.
"""
import collections
import functools
import os
from typing import Dict, Optional, Tuple, Set
from acme import wrappers
from acme.adders import reverb as adders
from dm_control import composer
from dm_control import suite
from dm_control.composer.variation import colors
from dm_control.composer.variation import distributions
from dm_control.locomotion import arenas
from dm_control.locomotion import props
from dm_control.locomotion import tasks
from dm_control.locomotion import walkers
from dm_env import specs
import numpy as np
import reverb
import tensorflow as tf
import tree
def _build_rodent_escape_env():
"""Build environment where a rodent escapes from a bowl."""
walker = walkers.Rat(
observable_options={'egocentric_camera': dict(enabled=True)},
)
arena = arenas.bowl.Bowl(
size=(20., 20.),
aesthetic='outdoor_natural')
locomotion_task = tasks.escape.Escape(
walker=walker,
arena=arena,
physics_timestep=0.001,
control_timestep=.02)
raw_env = composer.Environment(
time_limit=20,
task=locomotion_task,
strip_singleton_obs_buffer_dim=True)
return raw_env
def _build_rodent_maze_env():
"""Build environment where a rodent runs to targets."""
walker = walkers.Rat(
observable_options={'egocentric_camera': dict(enabled=True)},
)
wall_textures = arenas.labmaze_textures.WallTextures(
style='style_01')
arena = arenas.mazes.RandomMazeWithTargets(
x_cells=11,
y_cells=11,
xy_scale=.5,
z_height=.3,
max_rooms=4,
room_min_size=4,
room_max_size=5,
spawns_per_room=1,
targets_per_room=3,
wall_textures=wall_textures,
aesthetic='outdoor_natural')
rodent_task = tasks.random_goal_maze.ManyGoalsMaze(
walker=walker,
maze_arena=arena,
target_builder=functools.partial(
props.target_sphere.TargetSphere,
radius=0.05,
height_above_ground=.125,
rgb1=(0, 0, 0.4),
rgb2=(0, 0, 0.7)),
target_reward_scale=50.,
contact_termination=False,
control_timestep=.02,
physics_timestep=0.001)
raw_env = composer.Environment(
time_limit=30,
task=rodent_task,
strip_singleton_obs_buffer_dim=True)
return raw_env
def _build_rodent_corridor_gaps():
"""Build environment where a rodent runs over gaps."""
walker = walkers.Rat(
observable_options={'egocentric_camera': dict(enabled=True)},
)
platform_length = distributions.Uniform(low=0.4, high=0.8)
gap_length = distributions.Uniform(low=0.05, high=0.2)
arena = arenas.corridors.GapsCorridor(
corridor_width=2,
platform_length=platform_length,
gap_length=gap_length,
corridor_length=40,
aesthetic='outdoor_natural')
rodent_task = tasks.corridors.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_position=(5, 0, 0),
walker_spawn_rotation=0,
target_velocity=1.0,
contact_termination=False,
terminate_at_height=-0.3,
physics_timestep=0.001,
control_timestep=.02)
raw_env = composer.Environment(
time_limit=30,
task=rodent_task,
strip_singleton_obs_buffer_dim=True)
return raw_env
def _build_rodent_two_touch_env():
"""Build environment where a rodent touches targets."""
walker = walkers.Rat(
observable_options={'egocentric_camera': dict(enabled=True)},
)
arena_floor = arenas.floors.Floor(
size=(10., 10.), aesthetic='outdoor_natural')
task_reach = tasks.reach.TwoTouch(
walker=walker,
arena=arena_floor,
target_builders=[
functools.partial(
props.target_sphere.TargetSphereTwoTouch,
radius=0.025),
],
randomize_spawn_rotation=True,
target_type_rewards=[25.],
shuffle_target_builders=False,
target_area=(1.5, 1.5),
physics_timestep=0.001,
control_timestep=.02)
raw_env = composer.Environment(
time_limit=30,
task=task_reach,
strip_singleton_obs_buffer_dim=True)
return raw_env
def _build_humanoid_walls_env():
"""Build humanoid walker walls environment."""
walker = walkers.CMUHumanoidPositionControlled(
name='walker',
observable_options={'egocentric_camera': dict(enabled=True)},
)
wall_width = distributions.Uniform(low=1, high=7)
wall_height = distributions.Uniform(low=2.5, high=4.0)
swap_wall_side = distributions.Bernoulli(prob=0.5)
wall_r = distributions.Uniform(low=0.5, high=0.6)
wall_g = distributions.Uniform(low=0.21, high=0.41)
wall_rgba = colors.RgbVariation(r=wall_r, g=wall_g, b=0, alpha=1)
arena = arenas.WallsCorridor(
wall_gap=5.0,
wall_width=wall_width,
wall_height=wall_height,
swap_wall_side=swap_wall_side,
wall_rgba=wall_rgba,
corridor_width=10,
corridor_length=100)
humanoid_task = tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_rotation=1.57, # pi / 2
physics_timestep=0.005,
control_timestep=0.03)
raw_env = composer.Environment(
time_limit=30,
task=humanoid_task,
strip_singleton_obs_buffer_dim=True)
return raw_env
def _build_humanoid_corridor_env():
"""Build humanoid walker walls environment."""
walker = walkers.CMUHumanoidPositionControlled(
name='walker',
observable_options={'egocentric_camera': dict(enabled=True)},
)
arena = arenas.EmptyCorridor(
corridor_width=10,
corridor_length=100)
humanoid_task = tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_rotation=1.57, # pi / 2
physics_timestep=0.005,
control_timestep=0.03)
raw_env = composer.Environment(
time_limit=30,
task=humanoid_task,
strip_singleton_obs_buffer_dim=True)
return raw_env
def _build_humanoid_corridor_gaps():
"""Build humanoid walker walls environment."""
walker = walkers.CMUHumanoidPositionControlled(
name='walker',
observable_options={'egocentric_camera': dict(enabled=True)},
)
platform_length = distributions.Uniform(low=0.3, high=2.5)
gap_length = distributions.Uniform(low=0.75, high=1.25)
arena = arenas.GapsCorridor(
corridor_width=10,
platform_length=platform_length,
gap_length=gap_length,
corridor_length=100)
humanoid_task = tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_position=(2, 0, 0),
walker_spawn_rotation=1.57, # pi / 2
physics_timestep=0.005,
control_timestep=0.03)
raw_env = composer.Environment(
time_limit=30,
task=humanoid_task,
strip_singleton_obs_buffer_dim=True)
return raw_env
class MujocoActionNormalizer(wrappers.EnvironmentWrapper):
"""Rescale actions to [-1, 1] range for mujoco physics engine.
For control environments whose actions have bounded range in [-1, 1], this
adaptor rescale actions to the desired range. This allows actor network to
output unscaled actions for better gradient dynamics.
"""
def __init__(self, environment, rescale='clip'):
super().__init__(environment)
self._rescale = rescale
def step(self, action):
"""Rescale actions to [-1, 1] range before stepping wrapped environment."""
if self._rescale == 'tanh':
scaled_actions = tree.map_structure(np.tanh, action)
elif self._rescale == 'clip':
scaled_actions = tree.map_structure(lambda a: np.clip(a, -1., 1.), action)
else:
raise ValueError('Unrecognized scaling option: %s' % self._rescale)
return self._environment.step(scaled_actions)
class NormilizeActionSpecWrapper(wrappers.EnvironmentWrapper):
"""Turn each dimension of the actions into the range of [-1, 1]."""
def __init__(self, environment):
super().__init__(environment)
action_spec = environment.action_spec()
# pytype: disable=attribute-error # always-use-return-annotations
self._scale = action_spec.maximum - action_spec.minimum
self._offset = action_spec.minimum
minimum = action_spec.minimum * 0 - 1.
maximum = action_spec.minimum * 0 + 1.
self._action_spec = specs.BoundedArray(
action_spec.shape,
action_spec.dtype,
minimum,
maximum,
name=action_spec.name)
# pytype: enable=attribute-error # always-use-return-annotations
def _from_normal_actions(self, actions):
actions = 0.5 * (actions + 1.0) # a_t is now in the range [0, 1]
# scale range to [minimum, maximum]
return actions * self._scale + self._offset
def step(self, action):
action = self._from_normal_actions(action)
return self._environment.step(action)
def action_spec(self):
return self._action_spec
class FilterObservationsWrapper(wrappers.EnvironmentWrapper):
"""Filter out all the observations not specified to this wrapper."""
def __init__(self, environment, observations_to_keep):
super().__init__(environment)
self._observations_to_keep = observations_to_keep
spec = self._environment.observation_spec()
filtered = [(k, spec[k]) for k in observations_to_keep]
self._observation_spec = collections.OrderedDict(filtered)
def _filter_observation(self, timestep):
observation = timestep.observation
filtered = [(k, observation[k]) for k in self._observations_to_keep]
return timestep._replace(observation=collections.OrderedDict(filtered))
def step(self, action):
return self._filter_observation(self._environment.step(action))
def reset(self):
return self._filter_observation(self._environment.reset())
def observation_spec(self):
return self._observation_spec
class ControlSuite:
"""Create bits needed to run agents on an Control Suite dataset."""
def __init__(self, task_name='humanoid_run'):
"""Initializes datasets/environments for the Deepmind Control suite.
Args:
task_name: take name. Must be one of,
finger_turn_hard, manipulator_insert_peg, humanoid_run,
cartpole_swingup, cheetah_run, fish_swim, manipulator_insert_ball,
walker_stand, walker_walk
"""
self.task_name = task_name
self._uint8_features = set([])
self._environment = None
if task_name == 'swim':
self._domain_name = 'fish'
self._task_name = 'swim'
self._shapes = {
'observation/target': (3,),
'observation/velocity': (13,),
'observation/upright': (1,),
'observation/joint_angles': (7,),
'action': (5,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()
}
elif task_name == 'humanoid_run':
self._domain_name = 'humanoid'
self._task_name = 'run'
self._shapes = {
'observation/velocity': (27,),
'observation/com_velocity': (3,),
'observation/torso_vertical': (3,),
'observation/extremities': (12,),
'observation/head_height': (1,),
'observation/joint_angles': (21,),
'action': (21,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()
}
elif task_name == 'manipulator_insert_ball':
self._domain_name = 'manipulator'
self._task_name = 'insert_ball'
self._shapes = {
'observation/arm_pos': (16,),
'observation/arm_vel': (8,),
'observation/touch': (5,),
'observation/hand_pos': (4,),
'observation/object_pos': (4,),
'observation/object_vel': (3,),
'observation/target_pos': (4,),
'action': (5,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()}
elif task_name == 'manipulator_insert_peg':
self._domain_name = 'manipulator'
self._task_name = 'insert_peg'
self._shapes = {
'observation/arm_pos': (16,),
'observation/arm_vel': (8,),
'observation/touch': (5,),
'observation/hand_pos': (4,),
'observation/object_pos': (4,),
'observation/object_vel': (3,),
'observation/target_pos': (4,),
'episodic_reward': (),
'action': (5,),
'discount': (),
'reward': (),
'step_type': ()}
elif task_name == 'cartpole_swingup':
self._domain_name = 'cartpole'
self._task_name = 'swingup'
self._shapes = {
'observation/position': (3,),
'observation/velocity': (2,),
'action': (1,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()}
elif task_name == 'walker_walk':
self._domain_name = 'walker'
self._task_name = 'walk'
self._shapes = {
'observation/orientations': (14,),
'observation/velocity': (9,),
'observation/height': (1,),
'action': (6,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()}
elif task_name == 'walker_stand':
self._domain_name = 'walker'
self._task_name = 'stand'
self._shapes = {
'observation/orientations': (14,),
'observation/velocity': (9,),
'observation/height': (1,),
'action': (6,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()}
elif task_name == 'cheetah_run':
self._domain_name = 'cheetah'
self._task_name = 'run'
self._shapes = {
'observation/position': (8,),
'observation/velocity': (9,),
'action': (6,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()}
elif task_name == 'finger_turn_hard':
self._domain_name = 'finger'
self._task_name = 'turn_hard'
self._shapes = {
'observation/position': (4,),
'observation/velocity': (3,),
'observation/touch': (2,),
'observation/target_position': (2,),
'observation/dist_to_target': (1,),
'action': (2,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()}
else:
raise ValueError('Task \'{}\' not found.'.format(task_name))
self._data_path = 'dm_control_suite/{}/train'.format(task_name)
@property
def shapes(self):
return self._shapes
@property
def data_path(self):
return self._data_path
@property
def uint8_features(self):
return self._uint8_features
@property
def environment(self):
"""Build and return the environment."""
if self._environment is not None:
return self._environment
self._environment = suite.load(
domain_name=self._domain_name,
task_name=self._task_name)
self._environment = wrappers.SinglePrecisionWrapper(self._environment)
self._environment = NormilizeActionSpecWrapper(self._environment)
return self._environment
class CmuThirdParty:
"""Create bits needed to run agents on an locomotion humanoid dataset."""
def __init__(self, task_name='humanoid_walls'):
# 'humanoid_corridor|humanoid_gaps|humanoid_walls'
self._task_name = task_name
self._pixel_keys = self.get_pixel_keys()
self._uint8_features = set(['observation/walker/egocentric_camera'])
self.additional_paths = {}
self._proprio_keys = [
'walker/joints_vel',
'walker/sensors_velocimeter',
'walker/sensors_gyro',
'walker/joints_pos',
'walker/world_zaxis',
'walker/body_height',
'walker/sensors_accelerometer',
'walker/end_effectors_pos'
]
self._shapes = {
'observation/walker/joints_vel': (56,),
'observation/walker/sensors_velocimeter': (3,),
'observation/walker/sensors_gyro': (3,),
'observation/walker/joints_pos': (56,),
'observation/walker/world_zaxis': (3,),
'observation/walker/body_height': (1,),
'observation/walker/sensors_accelerometer': (3,),
'observation/walker/end_effectors_pos': (12,),
'observation/walker/egocentric_camera': (
64,
64,
3,
),
'action': (56,),
'discount': (),
'reward': (),
'episodic_reward': (),
'step_type': ()
}
if task_name == 'humanoid_corridor':
self._data_path = 'dm_locomotion/humanoid_corridor/seq2/train'
elif task_name == 'humanoid_gaps':
self._data_path = 'dm_locomotion/humanoid_gaps/seq2/train'
elif task_name == 'humanoid_walls':
self._data_path = 'dm_locomotion/humanoid_walls/seq40/train'
else:
raise ValueError('Task \'{}\' not found.'.format(task_name))
@staticmethod
def get_pixel_keys():
return ('walker/egocentric_camera',)
@property
def uint8_features(self):
return self._uint8_features
@property
def shapes(self):
return self._shapes
@property
def data_path(self):
return self._data_path
@property
def environment(self):
"""Build and return the environment."""
if self._task_name == 'humanoid_corridor':
self._environment = _build_humanoid_corridor_env()
elif self._task_name == 'humanoid_gaps':
self._environment = _build_humanoid_corridor_gaps()
elif self._task_name == 'humanoid_walls':
self._environment = _build_humanoid_walls_env()
self._environment = NormilizeActionSpecWrapper(self._environment)
self._environment = MujocoActionNormalizer(
environment=self._environment, rescale='clip')
self._environment = wrappers.SinglePrecisionWrapper(self._environment)
all_observations = list(self._proprio_keys) + list(self._pixel_keys)
self._environment = FilterObservationsWrapper(self._environment,
all_observations)
return self._environment
class Rodent:
"""Create bits needed to run agents on an Rodent dataset."""
def __init__(self, task_name='rodent_gaps'):
# 'rodent_escape|rodent_two_touch|rodent_gaps|rodent_mazes'
self._task_name = task_name
self._pixel_keys = self.get_pixel_keys()
self._uint8_features = set(['observation/walker/egocentric_camera'])
self._proprio_keys = [
'walker/joints_pos', 'walker/joints_vel', 'walker/tendons_pos',
'walker/tendons_vel', 'walker/appendages_pos', 'walker/world_zaxis',
'walker/sensors_accelerometer', 'walker/sensors_velocimeter',
'walker/sensors_gyro', 'walker/sensors_touch',
]
self._shapes = {
'observation/walker/joints_pos': (30,),
'observation/walker/joints_vel': (30,),
'observation/walker/tendons_pos': (8,),
'observation/walker/tendons_vel': (8,),
'observation/walker/appendages_pos': (15,),
'observation/walker/world_zaxis': (3,),
'observation/walker/sensors_accelerometer': (3,),
'observation/walker/sensors_velocimeter': (3,),
'observation/walker/sensors_gyro': (3,),
'observation/walker/sensors_touch': (4,),
'observation/walker/egocentric_camera': (64, 64, 3),
'action': (38,),
'discount': (),
'reward': (),
'step_type': ()
}
if task_name == 'rodent_gaps':
self._data_path = 'dm_locomotion/rodent_gaps/seq2/train'
elif task_name == 'rodent_escape':
self._data_path = 'dm_locomotion/rodent_bowl_escape/seq2/train'
elif task_name == 'rodent_two_touch':
self._data_path = 'dm_locomotion/rodent_two_touch/seq40/train'
elif task_name == 'rodent_mazes':
self._data_path = 'dm_locomotion/rodent_mazes/seq40/train'
else:
raise ValueError('Task \'{}\' not found.'.format(task_name))
@staticmethod
def get_pixel_keys():
return ('walker/egocentric_camera',)
@property
def shapes(self):
return self._shapes
@property
def uint8_features(self):
return self._uint8_features
@property
def data_path(self):
return self._data_path
@property
def environment(self):
"""Return environment."""
if self._task_name == 'rodent_escape':
self._environment = _build_rodent_escape_env()
elif self._task_name == 'rodent_gaps':
self._environment = _build_rodent_corridor_gaps()
elif self._task_name == 'rodent_two_touch':
self._environment = _build_rodent_two_touch_env()
elif self._task_name == 'rodent_mazes':
self._environment = _build_rodent_maze_env()
self._environment = NormilizeActionSpecWrapper(self._environment)
self._environment = MujocoActionNormalizer(
environment=self._environment, rescale='clip')
self._environment = wrappers.SinglePrecisionWrapper(self._environment)
all_observations = list(self._proprio_keys) + list(self._pixel_keys)
self._environment = FilterObservationsWrapper(self._environment,
all_observations)
return self._environment
def _parse_seq_tf_example(example, uint8_features, shapes):
"""Parse tf.Example containing one or two episode steps."""
def to_feature(key, shape):
if key in uint8_features:
return tf.io.FixedLenSequenceFeature(
shape=[], dtype=tf.string, allow_missing=True)
else:
return tf.io.FixedLenSequenceFeature(
shape=shape, dtype=tf.float32, allow_missing=True)
feature_map = {}
for k, v in shapes.items():
feature_map[k] = to_feature(k, v)
parsed = tf.io.parse_single_example(example, features=feature_map)
observation = {}
restructured = {}
for k in parsed.keys():
if 'observation' not in k:
restructured[k] = parsed[k]
continue
if k in uint8_features:
observation[k.replace('observation/', '')] = tf.reshape(
tf.io.decode_raw(parsed[k], out_type=tf.uint8), (-1,) + shapes[k])
else:
observation[k.replace('observation/', '')] = parsed[k]
restructured['observation'] = observation
restructured['length'] = tf.shape(restructured['action'])[0]
return restructured
def _build_sequence_example(sequences):
"""Convert raw sequences into a Reverb sequence sample."""
data = adders.Step(
observation=sequences['observation'],
action=sequences['action'],
reward=sequences['reward'],
discount=sequences['discount'],
start_of_episode=(),
extras=())
info = reverb.SampleInfo(
key=tf.constant(0, tf.uint64),
probability=tf.constant(1.0, tf.float64),
table_size=tf.constant(0, tf.int64),
priority=tf.constant(1.0, tf.float64),
times_sampled=tf.constant(1.0, tf.int32))
return reverb.ReplaySample(info=info, data=data)
def _build_sarsa_example(sequences):
"""Convert raw sequences into a Reverb n-step SARSA sample."""
o_tm1 = tree.map_structure(lambda t: t[0], sequences['observation'])
o_t = tree.map_structure(lambda t: t[1], sequences['observation'])
a_tm1 = tree.map_structure(lambda t: t[0], sequences['action'])
a_t = tree.map_structure(lambda t: t[1], sequences['action'])
r_t = tree.map_structure(lambda t: t[0], sequences['reward'])
p_t = tree.map_structure(lambda t: t[0], sequences['discount'])
info = reverb.SampleInfo(
key=tf.constant(0, tf.uint64),
probability=tf.constant(1.0, tf.float64),
table_size=tf.constant(0, tf.int64),
priority=tf.constant(1.0, tf.float64),
times_sampled=tf.constant(1.0, tf.int32))
return reverb.ReplaySample(info=info, data=(o_tm1, a_tm1, r_t, p_t, o_t, a_t))
def _padded_batch(example_ds, batch_size, shapes, drop_remainder=False):
"""Batch data while handling unequal lengths."""
padded_shapes = {}
padded_shapes['observation'] = {}
for k, v in shapes.items():
if 'observation' in k:
padded_shapes['observation'][
k.replace('observation/', '')] = (-1,) + v
else:
padded_shapes[k] = (-1,) + v
padded_shapes['length'] = ()
return example_ds.padded_batch(batch_size,
padded_shapes=padded_shapes,
drop_remainder=drop_remainder)
def dataset(root_path: str,
data_path: str,
shapes: Dict[str, Tuple[int]],
num_threads: int,
batch_size: int,
uint8_features: Optional[Set[str]] = None,
num_shards: int = 100,
shuffle_buffer_size: int = 100000,
sarsa: bool = True) -> tf.data.Dataset:
"""Create tf dataset for training."""
uint8_features = uint8_features if uint8_features else {}
path = os.path.join(root_path, data_path)
filenames = [f'{path}-{i:05d}-of-{num_shards:05d}' for i in range(num_shards)]
file_ds = tf.data.Dataset.from_tensor_slices(filenames)
file_ds = file_ds.repeat().shuffle(num_shards)
example_ds = file_ds.interleave(
functools.partial(tf.data.TFRecordDataset, compression_type='GZIP'),
cycle_length=tf.data.experimental.AUTOTUNE,
block_length=5)
example_ds = example_ds.shuffle(shuffle_buffer_size)
def map_func(example):
example = _parse_seq_tf_example(example, uint8_features, shapes)
return example
example_ds = example_ds.map(map_func, num_parallel_calls=num_threads)
example_ds = example_ds.repeat().shuffle(batch_size * 10)
if sarsa:
example_ds = example_ds.map(
_build_sarsa_example,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
example_ds.batch(batch_size)
else:
example_ds = _padded_batch(
example_ds, batch_size, shapes, drop_remainder=True)
example_ds = example_ds.map(
_build_sequence_example,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
example_ds = example_ds.prefetch(tf.data.experimental.AUTOTUNE)
return example_ds
|
deepmind-research-master
|
rl_unplugged/dm_control_suite.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.
r"""DM control suite and locomotion dataset examples.
Example:
Instructions:
> export TMP_PATH=/tmp/dataset
> export TASK_NAME=humanoid_run
> mkdir -p $TMP_PATH/$TASK_NAME
> gsutil cp gs://rl_unplugged/dm_control_suite/$TASK_NAME/train-00000-of-00100 \
$TMP_PATH/dm_control_suite/$TASK_NAME/train-00000-of-00001
> python dm_control_suite_example.py --path=$TMP_PATH \
--task_class=control_suite --task_name=$TASK_NAME
"""
from absl import app
from absl import flags
import tree
from rl_unplugged import dm_control_suite
flags.DEFINE_string('path', '/tmp/dataset', 'Path to dataset.')
flags.DEFINE_string('task_name', 'humanoid_run', 'Game.')
flags.DEFINE_enum('task_class', 'control_suite',
['humanoid', 'rodent', 'control_suite'],
'Task classes.')
FLAGS = flags.FLAGS
def main(_):
if FLAGS.task_class == 'control_suite':
task = dm_control_suite.ControlSuite(task_name=FLAGS.task_name)
elif FLAGS.task_class == 'humanoid':
task = dm_control_suite.CmuThirdParty(task_name=FLAGS.task_name)
elif FLAGS.task_class == 'rodent':
task = dm_control_suite.Rodent(task_name=FLAGS.task_name)
ds = dm_control_suite.dataset(root_path=FLAGS.path,
data_path=task.data_path,
shapes=task.shapes,
num_threads=1,
batch_size=2,
uint8_features=task.uint8_features,
num_shards=1,
shuffle_buffer_size=10)
for sample in ds.take(1):
print('Data spec')
print(tree.map_structure(lambda x: (x.dtype, x.shape), sample.data))
environment = task.environment
timestep = environment.reset()
print(tree.map_structure(lambda x: (x.dtype, x.shape), timestep.observation))
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
rl_unplugged/dm_control_suite_example.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Setup for pip package."""
from setuptools import find_packages
from setuptools import setup
setup(
name='wikigraphs',
version='0.1.0',
description='A Wikipedia - knowledge graph paired dataset.',
url='https://github.com/deepmind/deepmind-research/tree/master/wikigraphs',
author='DeepMind',
author_email='luyuwang@google.com',
packages=find_packages(),
license='Apache 2.0',
)
|
deepmind-research-master
|
wikigraphs/setup.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Data Parallel Updater for Graph2text data."""
import functools
import os
import pickle
from absl import logging
import haiku as hk
import jax
from jax.tree_util import tree_map
import numpy as np
import optax
def call_fn_with_state_keys(jit_fn, state, other_inputs, keys):
"""Executes `jit_fn`, filtering out all keys except some subset."""
state = state.copy()
extra_state = {}
for k in list(state.keys()):
if k not in keys:
extra_state[k] = state.pop(k)
return jit_fn(state, *other_inputs), extra_state
class Updater:
"""Graph2text model updater with multi-GPU support."""
def __init__(self, loss_fn, optimizer, devices=None, has_graph=False):
self._net_init_fn, self._apply_fn = hk.transform_with_state(
functools.partial(loss_fn, is_training=True))
_, self._eval_apply_fn = hk.transform_with_state(
functools.partial(loss_fn, is_training=False))
if optimizer is None:
optimizer = optax.identity()
self._optimizer = optimizer
self._num_devices = jax.local_device_count()
if devices is None:
devices = []
for host_id in range(jax.process_count()):
for device_id in jax.local_devices(host_id):
devices.append(device_id)
else:
self._num_devices = min(self._num_devices, len(devices))
def _pmap(f, static_broadcasted_argnums=()):
return jax.pmap(f, axis_name='i', devices=devices,
static_broadcasted_argnums=static_broadcasted_argnums)
def handle_graph_size(fn):
def _fn(*args):
batch = args[-1].copy()
max_graph_size = batch['max_graph_size']
del batch['max_graph_size']
args = args[:-1] + (batch, max_graph_size)
return fn(*args)
return _fn
# Try to jit.
if has_graph:
# If the model contains full graphs, we need to set the max_graph_size
# as a statically broadcasted argument.
self._init_fn = handle_graph_size(_pmap(self._init, 4))
self._update_fn = handle_graph_size(_pmap(self._update, 2))
self._eval_fn = handle_graph_size(_pmap(self._eval, 2))
else:
self._init_fn = _pmap(self._init)
self._update_fn = _pmap(self._update)
self._eval_fn = _pmap(self._eval)
def _init(self, master_rng, params, network_state, data, max_graph_size=None):
"""Initializes state of the updater."""
out_rng, init_rng = jax.random.split(master_rng)
if max_graph_size is not None:
new_params, new_network_state = self._net_init_fn(
init_rng, data, max_graph_size)
else:
new_params, new_network_state = self._net_init_fn(init_rng, data)
if params is None:
params = new_params
if network_state is None:
network_state = new_network_state
opt_state = self._optimizer.init(params)
return dict(
replicated_step=0,
rng=out_rng,
state=network_state,
opt_state=opt_state,
params=params,
)
def init(self, master_rng, data, params=None, network_state=None,
replicated_params=False):
"""Initializes state of the updater."""
data = self._preprocess(data)
rngs = np.array([master_rng] * self._num_devices)
if not replicated_params and params is not None:
params = jax.tree_map(
lambda x: np.array([x] * self._num_devices), params)
state = self._init_fn(rngs, params, network_state, data)
state['step'] = np.array(0, dtype=np.int64)
# Wait for initialization to finish before starting training to keep
# memory usage low.
flat_params = jax.tree_leaves(state['params'])
if flat_params:
jax.tree_leaves(state['params'])[0].block_until_ready()
return state
def _update(self, state, data, max_graph_size=None):
"""Updates parameters."""
replicated_step = state['replicated_step']
rng = state['rng']
opt_state = state['opt_state']
params = state['params']
net_state = state['state']
rng, new_rng = jax.random.split(rng)
rng = jax.random.fold_in(rng, jax.lax.axis_index('i'))
def _loss(params, state, batch, rng):
if max_graph_size is not None:
(loss, metrics), state = self._apply_fn(params, state, rng, batch,
max_graph_size)
else:
(loss, metrics), state = self._apply_fn(params, state, rng, batch)
return loss, (metrics, state)
(loss, (metrics, new_net_state)), g = jax.value_and_grad(
_loss, has_aux=True)(params, net_state, data, rng)
g = jax.lax.pmean(g, axis_name='i')
loss = jax.lax.pmean(loss, axis_name='i')
metrics = jax.lax.pmean(metrics, axis_name='i')
updates, new_opt_state = self._optimizer.update(g, opt_state, params)
new_params = optax.apply_updates(params, updates)
new_state = dict(
replicated_step=replicated_step + 1,
rng=new_rng,
state=new_net_state,
opt_state=new_opt_state,
params=new_params,
)
metrics['loss'] = loss
metrics['step'] = replicated_step
return new_state, metrics
def update(self, state, data):
"""Updates the state using some data and returns metrics."""
data = self._preprocess(data)
(state, out), extra_state = call_fn_with_state_keys(
self._update_fn, state, [data], keys=set([
'state', 'params', 'rng', 'replicated_step', 'opt_state']))
state.update(extra_state)
state['step'] += 1
return state, tree_map(lambda x: x[0], out)
def _eval(self, state, data, max_graph_size=None):
"""Evaluates the current state on the given data."""
if max_graph_size is not None:
(loss, metrics), new_state = self._eval_apply_fn(
state['params'], state['state'], state['rng'], data, max_graph_size)
else:
(loss, metrics), new_state = self._eval_apply_fn(
state['params'], state['state'], state['rng'], data)
state['state'] = new_state
loss = jax.lax.pmean(loss, axis_name='i')
metrics = jax.lax.pmean(metrics, axis_name='i')
metrics['loss'] = loss
metrics['step'] = state['replicated_step']
return state, metrics
def eval_return_state(self, state, data):
"""Returns metrics without updating the model."""
data = self._preprocess(data)
(state, out), extra_state = call_fn_with_state_keys(
self._eval_fn, state, [data], keys=set([
'state', 'params', 'rng', 'replicated_step']))
state.update(extra_state)
return state, tree_map(lambda x: x[0], out)
def eval(self, state, data):
"""Returns metrics without updating the model."""
_, out = self.eval_return_state(state, data)
return out
def _preprocess(self, data):
"""Reshapes input so that it can be distributed across multiple cores."""
multi_inputs = data.copy()
def add_core_dimension(x):
if np.isscalar(x):
return x
if x.shape[0] % self._num_devices != 0:
raise ValueError(f'The batch size must be a multiple of the number of'
f' devices. Got batch size = {x.shape[0]} and number'
f' of devices = {self._num_devices}.')
prefix = (self._num_devices, x.shape[0] // self._num_devices)
return np.reshape(x, prefix + x.shape[1:])
multi_inputs = tree_map(add_core_dimension, multi_inputs)
return multi_inputs
def params(self, state):
"""Returns model parameters."""
return tree_map(lambda x: x[0], state['params'])
def opt_state(self, state):
"""Returns the state of the optimiser."""
return tree_map(lambda x: x[0], state['opt_state'])
def network_state(self, state):
"""Returns the model's state."""
return tree_map(lambda x: x[0], state['state'])
def to_checkpoint_state(self, state):
"""Transforms the updater state into a checkpointable state."""
checkpoint_state = state.copy()
# Wrapper around checkpoint_state['step'] so we can get [0].
checkpoint_state['step'] = checkpoint_state['step'][np.newaxis]
# Unstack the replicated contents.
checkpoint_state = tree_map(lambda x: x[0], checkpoint_state)
return checkpoint_state
def from_checkpoint_state(self, checkpoint_state):
"""Initializes the updater state from the checkpointed state."""
# Expand the checkpoint so we have a copy for each device.
state = tree_map(lambda x: np.stack(jax.local_device_count() * [x]),
checkpoint_state)
state['step'] = state['step'][0] # Undo stacking for step.
return state
class CheckpointingUpdater:
"""A checkpointing wrapper around an Updater."""
def __init__(self,
inner: Updater,
checkpoint_dir: str):
self._inner = inner
self._checkpoint_dir = checkpoint_dir
def _checkpoint_paths(self):
return [p for p in os.listdir(self._checkpoint_dir) if 'checkpoint' in p]
def init(self, rng, data, params=None, network_state=None):
"""Initialize experiment state."""
if not os.path.exists(self._checkpoint_dir) or not self._checkpoint_paths():
os.makedirs(self._checkpoint_dir, exist_ok=True)
return self._inner.init(rng, data, params, network_state)
return self.load_checkpoint()
def init_from_checkpoint(self, rng, data, checkpoint_state):
params = self._inner.params(checkpoint_state)
network_state = None
return self._inner.init(rng, data, params, network_state)
def eval_return_state(self, state, data):
return self._inner.eval_return_state(state, data)
def save_checkpoint(self, state):
path = os.path.join(self._checkpoint_dir, 'checkpoint.pkl')
logging.info('Serializing experiment state to %s', path)
checkpoint_state = self._inner.to_checkpoint_state(jax.device_get(state))
with open(path, 'wb') as f:
pickle.dump(checkpoint_state, f)
def load_checkpoint(self):
checkpoint = os.path.join(self._checkpoint_dir,
self._checkpoint_paths()[-1])
logging.info('Loading checkpoint from %s', checkpoint)
with open(checkpoint, 'rb') as f:
state = pickle.load(f)
return self._inner.from_checkpoint_state(state)
def update(self, state, data):
"""Update experiment state."""
state, out = self._inner.update(state, data)
return state, out
|
deepmind-research-master
|
wikigraphs/updaters.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Utility functions for the training script."""
import collections
import math
import random
from absl import flags
from absl import logging
import jax.numpy as jnp
import jraph
import numpy as np
import sklearn
from wikigraphs.data import paired_dataset as pd
from wikigraphs.data import tokenizers
from wikigraphs.data import wikitext as wt
from wikigraphs.model import graph_net as gn
from wikigraphs.model import sampler as transformer_sampler
from wikigraphs.model import transformer
FLAGS = flags.FLAGS
VOCAB_FILES_MAP = {
'wikitext': '/tmp/data/wikitext-vocab.csv',
'freebase2wikitext': '/tmp/data/text-vocab.csv',
}
GRAPH_VOCAB_FILE = '/tmp/data/graph-vocab.csv'
def init_tokenizer(dataset_name):
"""Initialie the tokenizer."""
logging.info('Loading tokenizer...')
tokenizer = tokenizers.WordTokenizer(VOCAB_FILES_MAP[dataset_name])
logging.info('Vocab size: %d', tokenizer.vocab_size)
return tokenizer
def init_graph_tokenizer():
"""Initialie the tokenizer."""
logging.info('Loading graph tokenizer...')
tokenizer = tokenizers.GraphTokenizer(GRAPH_VOCAB_FILE)
logging.info('Vocab size: %d', tokenizer.vocab_size)
return tokenizer
def get_dataset_class(dataset_name, model_type, job_mode='train'):
"""Get the dataset class used for all jobs."""
if dataset_name == 'freebase2wikitext':
if model_type == 'bow2text':
return pd.Bow2TextDataset
elif FLAGS.model_type == 'graph2text':
return pd.Graph2TextDataset
elif FLAGS.model_type == 'text':
if job_mode in ['train', 'eval']:
return pd.TextOnlyDataset
else:
# for sampling: taking the unique graphs for a fair comparison
return pd.Bow2TextDataset
else:
# Add other graph2text data here.
raise NotImplementedError()
else:
def dataset(graph_tokenizer, *args, **kwargs):
del graph_tokenizer
return wt.Dataset(*args, **kwargs)
return dataset
def preprocess(batch, model_type, num_devices=1):
"""Preprocess the batch before sending to the model."""
if model_type == 'text':
if 'graphs' in batch:
del batch['graphs']
elif model_type == 'bow2text':
# Do nothing, bow2text data is already in a good form.
pass
else: # graph2text
if num_devices == 1:
graphs = gn.pad_graphs(jraph.batch(batch['graphs']))
else:
# We need to first batch graphs into num_devices batchs.
graphs = gn.batch_graphs_by_device(batch['graphs'], num_devices)
# Then we pad them to the maximum graph size in the batch and concat.
# This way graphs can be distributed to each device through pmap.
graphs = gn.pad_graphs_by_device(graphs)
max_graph_size = gn.pad_size(graphs.n_node.max())
batch.update({
'graphs': graphs,
'max_graph_size': max_graph_size})
return batch
def text_model_fn(vocab_size):
return transformer.TransformerXL(
vocab_size=vocab_size,
emb_dim=FLAGS.emb_dim,
num_layers=FLAGS.num_layers,
num_heads=FLAGS.num_heads,
dropout_prob=FLAGS.dropout,
dropout_attn_prob=FLAGS.dropout_attn,
self_att_init_scale=FLAGS.self_att_init_scale,
dense_init_scale=FLAGS.dense_init_scale,
dense_dim=FLAGS.dense_dim,
tail_shrink_factor=FLAGS.tail_shrink_factor,
relative_pos_clamp_len=FLAGS.clamp_len or None)
def graph2text_model_fn(vocab_size):
"""Get graph2text transformer model."""
return transformer.Graph2TextTransformer(
vocab_size=vocab_size,
emb_dim=FLAGS.emb_dim,
num_layers=FLAGS.num_layers,
num_heads=FLAGS.num_heads,
dropout_prob=FLAGS.dropout,
dropout_attn_prob=FLAGS.dropout_attn,
self_att_init_scale=FLAGS.self_att_init_scale,
dense_init_scale=FLAGS.dense_init_scale,
dense_dim=FLAGS.dense_dim,
tail_shrink_factor=FLAGS.tail_shrink_factor,
relative_pos_clamp_len=FLAGS.clamp_len or None,
gnn_embed_dim=FLAGS.gnn_embed_dim,
gnn_num_layers=FLAGS.gnn_num_layers,
gnn_layer_norm=FLAGS.gnn_layer_norm)
def bow2text_model_fn(vocab_size):
"""Get the bow2text model."""
return transformer.Bow2TextTransformer(
vocab_size=vocab_size,
emb_dim=FLAGS.emb_dim,
num_layers=FLAGS.num_layers,
num_heads=FLAGS.num_heads,
dropout_prob=FLAGS.dropout,
dropout_attn_prob=FLAGS.dropout_attn,
self_att_init_scale=FLAGS.self_att_init_scale,
dense_init_scale=FLAGS.dense_init_scale,
dense_dim=FLAGS.dense_dim,
tail_shrink_factor=FLAGS.tail_shrink_factor,
relative_pos_clamp_len=FLAGS.clamp_len or None,
bow_embedding_dim=FLAGS.bow_embedding_dim,
bow_n_tokens=FLAGS.bow_n_tokens)
def build_loss_fn(vocab_size, cache_steps):
"""Build the appropriate loss function according to the configs."""
if FLAGS.model_type == 'text':
def loss_fn(data, is_training=True):
return text_model_fn(vocab_size=vocab_size).loss(
data['obs'], data['target'], data['mask'],
is_training=is_training,
should_reset=data['should_reset'],
cache_steps=cache_steps)
elif FLAGS.model_type == 'graph2text':
def loss_fn(data, max_graph_size, is_training=True):
return graph2text_model_fn(vocab_size=vocab_size).loss(
data['graphs'], max_graph_size, True,
data['obs'], data['target'], data['mask'],
is_training=is_training,
should_reset=data['should_reset'],
cache_steps=cache_steps)
elif FLAGS.model_type == 'bow2text':
def loss_fn(data, is_training=True):
return bow2text_model_fn(vocab_size=vocab_size).loss(
data['graphs'], data['obs'], data['target'], data['mask'],
is_training=is_training,
should_reset=data['should_reset'],
cache_steps=cache_steps)
else:
raise ValueError(f'Unknown model type "{FLAGS.model_type}".')
return loss_fn
def build_sampler(tokenizer, device=None):
"""Build the appropriate sampler according to the configs."""
if FLAGS.model_type == 'text':
model_fn = lambda prompts: text_model_fn(tokenizer.vocab_size)( # pylint: disable=g-long-lambda
prompts, is_training=False, cache_steps=FLAGS.sample_memory_size)
sampler_class = transformer_sampler.TransformerXLSampler
elif FLAGS.model_type == 'graph2text':
def model_fn(graphs, max_graph_size, prompts):
return graph2text_model_fn(tokenizer.vocab_size)(
graphs, max_graph_size, True, prompts, is_training=False,
cache_steps=FLAGS.sample_memory_size)
sampler_class = transformer_sampler.Graph2TextTransformerSampler
elif FLAGS.model_type == 'bow2text':
def model_fn(graphs, prompts):
return bow2text_model_fn(tokenizer.vocab_size)(
graphs, prompts, is_training=False,
cache_steps=FLAGS.sample_memory_size)
sampler_class = transformer_sampler.Bow2TextTransformerSampler
sampler = sampler_class(model_fn, FLAGS.sampling_temperature, device)
return sampler
def schedule(i, lr_schedule, init_lr, min_lr_ratio, max_steps):
if lr_schedule == 'cosine':
cosine_decay = 0.5 * (1 + jnp.cos(jnp.pi * i / max_steps))
decayed = (1 - min_lr_ratio) * cosine_decay + min_lr_ratio
return init_lr * decayed
else:
return jnp.where(
i > 350000, init_lr / 3**3,
jnp.where(i > 250000, init_lr / 3**2,
jnp.where(i > 150000, init_lr / 3, init_lr)))
def evaluate(eval_set, initial_state, updater, eval_batch_size=1,
preprocess_fn=None, max_eval_samples=-1,
print_progress_every=None):
"""Evaluate a model on given dataset."""
total_losses = []
total_counts = []
token_accuracy = []
seq_accuracy = []
state = initial_state
step = state['step']
for i, batch in enumerate(eval_set):
state, eval_out = updater.eval_return_state(state, preprocess_fn(batch))
total_losses.append(eval_out['total_loss'])
total_counts.append(eval_out['total_count'])
token_accuracy.append(
eval_out['token_accuracy'] * eval_out['total_count'])
seq_accuracy.append(eval_out['seq_accuracy'])
if print_progress_every and (i + 1) % print_progress_every == 0:
total_loss = float(jnp.array(total_losses).sum())
total_count = float(jnp.array(total_counts).sum())
avg_loss = total_loss / total_count
bpc = avg_loss * np.log2(np.e)
perplexity = np.exp(avg_loss)
logging.info(
'Evaluated %d batches, total tokens %d, average loss %g,'
' bpc %g, perplexity %g.',
i + 1, total_count, avg_loss, bpc, perplexity)
if 0 < max_eval_samples <= (i + 1) * eval_batch_size:
break
total_loss = jnp.array(total_losses).sum()
total_count = jnp.array(total_counts).sum()
avg_loss = total_loss / total_count
eval_out = dict(total_loss=float(total_loss),
total_count=float(total_count),
loss=float(avg_loss),
token_accuracy=float(
jnp.array(token_accuracy).sum() / total_count),
seq_accuracy=float(
jnp.array(seq_accuracy).sum() / len(seq_accuracy)),
step=float(step),
bits_per_token=float(avg_loss) * np.log2(np.e),
perplexity=np.exp(float(avg_loss)))
return eval_out, state
def extract_title(text, tokenizer):
r"""Extract the title in the text.
The wikitext articles is in the format of `\n = TITLE = \n \n...`. We extract
the title as the tokens from the start to when the `\n \n` first appears.
Args:
text: tokenized input text using `tokenizer`.
tokenizer: text tokenizer.
Returns:
title_end_idx: a numpy.array of shape (batch_size,), it indicates the index
in `text` that marks the end of the title.
"""
batch_size, text_length = text.shape
title_end_idx = np.ones(batch_size, dtype=np.int32)
newline_token = tokenizer.encode('\n')[0]
for b in range(batch_size):
prev_token = 1 # start tokens
for i in range(1, text_length): # skip start token
# when we first see '\n \n', that is the title
if prev_token == newline_token and text[b, i] == newline_token:
title_end_idx[b] = i
break
else:
prev_token = text[b, i]
return title_end_idx
def construct_prompts(text, batch_size, sample_length, tokenizer, prompt_title):
"""Construct prompts for text generation.
Args:
text: tokenized input text using `tokenizer`.
batch_size: the size of the batch.
sample_length: the length of the sample to be generated.
tokenizer: text tokenizer.
prompt_title: whether to return a prompt with the title of the `text`.
Returns:
prompts: a numpy.array of shape [batch_size, sample_length], in which -1
indicates tokens that need to be generated using the sampler.
"""
prompts = -np.ones((batch_size, sample_length), dtype=np.int32)
prompts[:, 0] = tokenizer.bos_token()
if prompt_title and text is not None:
title_end_idx = extract_title(text, tokenizer)
for i in range(batch_size):
prompts[i, 1:title_end_idx[i]+1] = text[i, 1:title_end_idx[i]+1]
return prompts
def generate_samples(params, tokenizer, sampler, model_type, prompts, graphs):
"""Generate a batch of samples using a sampler."""
if model_type == 'text':
samples = sampler.sample(params, prompts)
elif model_type == 'graph2text':
samples = sampler.sample(params, prompts, graphs, pad=True)
elif model_type == 'bow2text':
samples = sampler.sample(params, prompts, graphs)
else:
raise ValueError(f'Unknown model_type {model_type}')
return [tokenizer.decode(s) for s in samples], samples
def take_unique_graphs(data_iter, model_type):
"""Filter data such that it only returns batches with unique graphs."""
prev_graphs = None
for batch in data_iter:
graphs = batch.get('graphs', None)
# If there's no graph in batch, don't do any filtering
if graphs is None:
yield batch
else:
if prev_graphs is None:
prev_graphs = graphs
yield batch
else:
if model_type == 'graph2text':
not_same_graph = (prev_graphs.nodes.shape != graphs.nodes.shape or
not (prev_graphs.nodes == graphs.nodes).all())
else:
not_same_graph = (prev_graphs.shape != graphs.shape or
not (prev_graphs == graphs).all())
if not_same_graph:
prev_graphs = graphs
yield batch
def compute_map_sklearn(pred, gt):
"""Computes mAP using scikit-learn."""
assert len(gt.shape) == len(pred.shape) == 2, (
'gt should be a one-hot encoding with the same shape as pred')
ap = [
sklearn.metrics.average_precision_score(
gt[c, :], pred[c, :], average=None)
for c in range(gt.shape[0])
]
return sum(ap) / len(ap)
def compute_recall_at_k(pred, k=1):
"""Computes recall@1 score."""
num_articles = pred.shape[1]
return sklearn.metrics.top_k_accuracy_score(
np.arange(num_articles), pred, k=k)
def compute_text_graph_relevance(
eval_set, initial_state, updater, eval_batch_size=1, preprocess_fn=None,
print_progress_every=None):
"""Compute the text and graph relevance a model on given dataset."""
assert eval_batch_size == 1
num_articles = eval_set.num_articles
tokens_count = np.zeros((num_articles, num_articles))
log_probs = np.zeros((num_articles, num_articles)) # [graphs, texts]
state = initial_state
for i, batch in enumerate(eval_set):
state, eval_out = updater.eval_return_state(state, preprocess_fn(batch))
graph_id = batch['graph_id'][0]
seq_id = batch['seq_id'][0]
tokens_count[graph_id, seq_id] += eval_out['total_count']
log_probs[graph_id, seq_id] += eval_out['log_probs']
if print_progress_every is not None and (i + 1) % print_progress_every == 0:
logging.info('Evaluated %d samples', i + 1)
log_probs_per_token = log_probs / tokens_count
labels = np.eye(num_articles)
eval_out = dict(
log_probs=log_probs,
tokens_count=tokens_count,
log_probs_per_token=log_probs_per_token,
text2graph_recall_at_1=compute_recall_at_k(log_probs_per_token.T, k=1),
text2graph_recall_at_5=compute_recall_at_k(log_probs_per_token.T, k=5),
text2graph_map=compute_map_sklearn(log_probs_per_token.T, labels),
graph2text_recall_at_1=compute_recall_at_k(log_probs_per_token, k=1),
graph2text_recall_at_5=compute_recall_at_k(log_probs_per_token, k=5),
graph2text_map=compute_map_sklearn(log_probs_per_token, labels))
return eval_out, state
def _get_ngrams(segment, max_order):
"""Extracts all n-grams upto a given maximum order from an input segment.
Args:
segment: text segment from which n-grams will be extracted.
max_order: maximum length in tokens of the n-grams returned by this
methods.
Returns:
The Counter containing all n-grams upto max_order in segment
with a count of how many times each n-gram occurred.
"""
ngram_counts = collections.Counter()
for order in range(1, max_order + 1):
for i in range(0, len(segment) - order + 1):
ngram = tuple(segment[i:i+order])
ngram_counts[ngram] += 1
return ngram_counts
def compute_bleu(reference_corpus, translation_corpus, max_order=4,
smooth=False):
"""Computes BLEU score of translated segments against one or more references.
Originally from tensor2tensor/tensor2tensor/utils/bleu_hook.py
Args:
reference_corpus: list of lists of references for each translation. Each
reference should be tokenized into a list of tokens.
translation_corpus: list of translations to score. Each translation
should be tokenized into a list of tokens.
max_order: Maximum n-gram order to use when computing BLEU score.
smooth: Whether or not to apply Lin et al. 2004 smoothing.
Returns:
BLEU score and n-gram precisions.
"""
matches_by_order = [0] * max_order
possible_matches_by_order = [0] * max_order
reference_length = 0
translation_length = 0
for (references, translation) in zip(reference_corpus,
translation_corpus):
reference_length += min(len(r) for r in references)
translation_length += len(translation)
merged_ref_ngram_counts = collections.Counter()
for reference in references:
merged_ref_ngram_counts |= _get_ngrams(reference, max_order)
translation_ngram_counts = _get_ngrams(translation, max_order)
overlap = translation_ngram_counts & merged_ref_ngram_counts
for ngram in overlap:
matches_by_order[len(ngram)-1] += overlap[ngram]
for order in range(1, max_order+1):
possible_matches = len(translation) - order + 1
if possible_matches > 0:
possible_matches_by_order[order-1] += possible_matches
if random.random() < 0.01:
print('==========')
for k, v in overlap.items():
if len(k) >= 3:
print('%s : %d' % (str(k), v))
# print(matches_by_order)
# print(possible_matches_by_order)
precisions = [0] * max_order
for i in range(0, max_order):
if smooth:
precisions[i] = ((matches_by_order[i] + 1.) /
(possible_matches_by_order[i] + 1.))
else:
if possible_matches_by_order[i] > 0:
precisions[i] = (float(matches_by_order[i]) /
possible_matches_by_order[i])
else:
precisions[i] = 0.0
if min(precisions) > 0:
p_log_sum = sum((1. / max_order) * math.log(p) for p in precisions)
geo_mean = math.exp(p_log_sum)
else:
geo_mean = 0
ratio = float(translation_length) / reference_length
if ratio > 1.0:
bp = 1.
else:
bp = math.exp(1 - 1. / ratio)
bleu = geo_mean * bp
return bleu, precisions
|
deepmind-research-master
|
wikigraphs/utils.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Train a transformer for language modeling on Wikitext-103."""
import concurrent
import functools
import os
import pickle
import time
from absl import app
from absl import flags
from absl import logging
import jax
import jraph
import numpy as np
import optax
from updaters import CheckpointingUpdater
from updaters import Updater
import utils
# Train
flags.DEFINE_integer('train_batch_size', 4, '(Per-Device) batch size for'
' training.')
flags.DEFINE_integer('train_timesteps', 150, 'Sequence length to learn on')
flags.DEFINE_integer('train_memory_size', 150, 'Memory size for transformer XL')
flags.DEFINE_bool('debug', False, 'Whether to turn on debugging mode')
flags.DEFINE_string('job_mode', 'train',
'One of `train`, `eval`, `sample`, `retrieve`.')
flags.DEFINE_integer('random_seed', 42, 'Random seed id.')
flags.DEFINE_integer('num_gpus', 8, 'Number of GPUs for training.')
# Eval
flags.DEFINE_integer('eval_batch_size', 1, 'Evaluation batch size')
flags.DEFINE_string('eval_subset', 'valid', 'Which subset to evaluate on,'
' one of `valid`, `test`.')
flags.DEFINE_integer('eval_every', 10, 'Evaluation frequency.')
flags.DEFINE_integer('eval_timesteps', 64, 'Sequence length to learn on')
flags.DEFINE_integer('eval_memory_size', 640, 'Memory size for transformer XL')
flags.DEFINE_integer('max_eval_samples', -1, 'Max number of eval samples. Set'
' as -1 to use the entire eval set.')
# Model
flags.DEFINE_integer('emb_dim', 410, 'model width')
flags.DEFINE_integer('num_heads', 10, 'Number of attention heads')
flags.DEFINE_integer('num_layers', 16, 'Number of transformer layers')
flags.DEFINE_integer('dense_dim', 2100, 'Size of dense hidden layer.')
flags.DEFINE_integer('tail_shrink_factor', 4,
'Low-frequency vocabulary shrinkage factor in adaptive'
' softmax.')
flags.DEFINE_string('emb_type', 'adaptive_softmax', 'Type of the word embedding'
' layer.')
flags.DEFINE_integer('clamp_len', 400, 'Clamp length for transformer XL.')
flags.DEFINE_float('dropout', 0.1, 'Dropout rate for the transformer layers.')
flags.DEFINE_float('dropout_attn', 0.0, 'Dropout rate for the attention'
' weights.')
flags.DEFINE_float('self_att_init_scale', 0.02,
'Self attention module initilization scale.')
flags.DEFINE_float('dense_init_scale', 0.02,
'Dense module initilization scale.')
# Graph neural net configs
flags.DEFINE_string('gnn_embed_type', 'adaptive', 'Token embedding type for the'
' graph.')
flags.DEFINE_integer('gnn_embed_dim', 128, 'Graph node embedding size.')
flags.DEFINE_integer('gnn_num_layers', 1, 'Number of layers in the GNN.')
flags.DEFINE_bool('gnn_layer_norm', True, 'Whether to use layer norm in GNN.')
# Bag-of-words to text configs
flags.DEFINE_integer('bow_embedding_dim', 256, 'Size of the bow embeddings.')
flags.DEFINE_integer('bow_n_tokens', 1, 'Number of tokens to use for the'
' bow2text model.')
# Sampling
flags.DEFINE_float('sampling_temperature', 0.8, 'Temperature used for'
' sampling. Sampling becomes more deterministic with a'
' lower temperature. Setting temperature to 1.0 samples'
' from the model distribution.')
flags.DEFINE_bool('prompt_title', False, 'Whether to prompt title when sample')
flags.DEFINE_integer('sample_length', 512, 'Length of samples.')
flags.DEFINE_integer('sample_memory_size', 640, 'Memory size for sampling.')
flags.DEFINE_integer('num_samples', 1000, 'Maximum number of samples to'
' generate.')
# Optimization
flags.DEFINE_float('init_lr', 0.00025, 'Initial learning rate.')
flags.DEFINE_float('min_lr_ratio', 0.0, 'Minimum learning rate as a ratio of'
' `init_lr`.')
flags.DEFINE_string('lr_schedule', 'cosine', 'One of `default`, `cosine`.')
flags.DEFINE_float('grad_clip', 0.25, 'Maximum gradient norm allowed for'
' clipping, set to a very large number to disable clipping.')
flags.DEFINE_integer('max_steps', 200_000, 'Number of training steps.')
flags.DEFINE_string('checkpoint_dir', '/tmp/graph2text',
'Directory to store checkpoints.')
# Data
flags.DEFINE_string('dataset', 'freebase2wikitext', 'Which dataset to train on,'
' one of "wikitext", "freebase2wikitext".')
flags.DEFINE_string('model_type', 'graph2text', 'One of "text", "graph2text",'
' "bow2text".')
flags.DEFINE_string('graph_data_version', 'max256', 'One of "max256", "max512",'
' "max1024".')
flags.DEFINE_integer('log_every', 50, 'Log every this many steps.')
flags.DEFINE_integer('ckpt_every', 1000, 'Checkpoint every this many steps.')
FLAGS = flags.FLAGS
def _preprocess(batch, num_devices=1):
return utils.preprocess(batch, FLAGS.model_type, num_devices)
def _train(updater, train_dataset, num_devices):
"""Train the transformer model."""
# Initialize parameters.
logging.info('Initializing parameters...')
rng = jax.random.PRNGKey(FLAGS.random_seed)
state = updater.init(
rng, _preprocess(train_dataset.return_faux_batch(), num_devices))
logging.info('Starting train loop...')
prev_time = time.time()
while True:
data = next(train_dataset)
state, metrics = updater.update(state, _preprocess(data, num_devices))
# We use JAX runahead to mask data preprocessing and JAX dispatch overheads.
# Using values from state/metrics too often will block the runahead and can
# cause these overheads to become more prominent.
step = np.array(metrics['step'])
if step % FLAGS.log_every == 0:
steps_per_sec = FLAGS.log_every / (time.time() - prev_time)
prev_time = time.time()
metrics.update({'steps_per_sec': steps_per_sec})
logging.info({k: float(v) for k, v in metrics.items()})
if step % FLAGS.ckpt_every == 0:
updater.save_checkpoint(state)
if step > FLAGS.max_steps:
break
def _eval(updater, eval_dataset):
"""Evaluate the transformer model."""
checkpoint_state = updater.load_checkpoint()
rng = jax.random.PRNGKey(FLAGS.random_seed)
state = updater.init_from_checkpoint(
rng, _preprocess(eval_dataset.return_faux_batch()), checkpoint_state)
eval_out, state = utils.evaluate(
eval_dataset, state, updater, FLAGS.eval_batch_size, _preprocess,
FLAGS.max_eval_samples, print_progress_every=20)
logging.info('Eval output: %s', eval_out)
def _retrieve(updater, eval_dataset):
"""Graph and text retrieval using the transformer model."""
checkpoint_state = updater.load_checkpoint()
rng = jax.random.PRNGKey(FLAGS.random_seed)
state = updater.init_from_checkpoint(
rng, _preprocess(eval_dataset.return_faux_batch()), checkpoint_state)
retrieval_out, _ = utils.compute_text_graph_relevance(
eval_dataset, state, updater, preprocess_fn=_preprocess,
print_progress_every=20)
logging.info('Retrieval output: %s', retrieval_out)
def _sample(eval_dataset, tokenizer, devices, batch_size=1):
"""Evaluate the graph2text transformer."""
checkpoint_dir = os.path.join(FLAGS.checkpoint_dir, 'checkpoint.pkl')
logging.info('Loading checkpoint from %s', checkpoint_dir)
with open(checkpoint_dir, 'rb') as f:
state = pickle.load(f)
if FLAGS.model_type == 'graph2text':
# process list of graphs into a batch
eval_dataset = map(lambda x: dict( # pylint: disable=g-long-lambda
obs=x['obs'],
target=x['target'],
should_reset=x['should_reset'],
mask=x['mask'],
graphs=jraph.batch(x['graphs']),
), eval_dataset)
eval_dataset = utils.take_unique_graphs(eval_dataset, FLAGS.model_type)
samplers = []
for device in devices:
sampler = utils.build_sampler(tokenizer, device=device)
samplers.append(sampler)
step = state['step']
params = state['params']
sample_logger = []
with concurrent.futures.ThreadPoolExecutor(
max_workers=len(samplers)) as executor:
futures = dict()
for sampler in samplers:
batch = next(eval_dataset)
prompts = utils.construct_prompts(
batch['obs'], batch_size, FLAGS.sample_length, tokenizer,
prompt_title=FLAGS.prompt_title)
if FLAGS.model_type in ['graph2text', 'bow2text']:
future = executor.submit(
utils.generate_samples, params, tokenizer, sampler,
model_type=FLAGS.model_type, prompts=prompts,
graphs=batch['graphs'])
futures[future] = (sampler, batch['graphs'], batch['obs'])
else:
future = executor.submit(
utils.generate_samples, params, tokenizer, sampler,
model_type=FLAGS.model_type, prompts=prompts, graphs=None)
futures[future] = (sampler, batch['obs'])
n_samples = 0
while n_samples < FLAGS.num_samples:
for future, future_items in list(futures.items()):
if not future.done():
continue
samples, tokens = future.result()
if FLAGS.model_type == 'graph2text':
sampler, graphs, text = future_items
graphs = jraph.unbatch(graphs)
elif FLAGS.model_type == 'bow2text':
sampler, graphs, text = future_items
else:
sampler, text = future_items
if FLAGS.model_type in ['graph2text', 'bow2text']:
for s, g, tk, txt in zip(samples, graphs, tokens, text):
# Only log a small fraction of the generated samples, if we are
# generating non-stop. Otherwise log every sample.
logging.info('[step %d]', step)
logging.info('graph=\n%r', g)
logging.info('sample=\n%s', s)
if FLAGS.model_type == 'graph2text':
sample_logger.append({
'step': step,
'sample': s,
'sample_tokens': tk,
'ground_truth_text': txt,
})
elif FLAGS.model_type == 'bow2text':
sample_logger.append({
'step': step,
'bow': g,
'sample': s,
'sample_tokens': tk,
'ground_truth_text': txt,
})
else:
for s, tk, txt in zip(samples, tokens, text):
# Only log a small fraction of the generated samples, if we are
# generating non-stop. Otherwise log every sample.
logging.info('[step %d]', step)
logging.info('sample=\n%s', s)
sample_logger.append({
'step': step,
'sample': s,
'sample_tokens': tk,
'ground_truth_text': txt,
})
n_samples += len(samples)
logging.info('Finished generating %d samples', n_samples)
del futures[future]
if n_samples < FLAGS.num_samples:
batch = next(eval_dataset)
prompts = utils.construct_prompts(
batch['obs'], batch_size, FLAGS.sample_length, tokenizer,
prompt_title=FLAGS.prompt_title)
if FLAGS.model_type in ['graph2text', 'bow2text']:
future = executor.submit(
utils.generate_samples, params, tokenizer, sampler,
model_type=FLAGS.model_type, prompts=prompts,
graphs=batch['graphs'])
futures[future] = (sampler, batch['graphs'], batch['obs'])
else:
future = executor.submit(
utils.generate_samples, params, tokenizer, sampler,
model_type=FLAGS.model_type, prompts=prompts, graphs=None)
futures[future] = (sampler, batch['obs'])
logging.info('Finished')
path = os.path.join(FLAGS.checkpoint_dir, 'samples.pkl')
with open(path, 'wb') as f:
pickle.dump(dict(samples=sample_logger), f)
logging.info('Samples saved to %s', path)
def main(_):
# Create the dataset.
tokenizer = utils.init_tokenizer(FLAGS.dataset)
graph_tokenizer = utils.init_graph_tokenizer()
dataset_class = utils.get_dataset_class(FLAGS.dataset, FLAGS.model_type)
has_graph = True if FLAGS.model_type == 'graph2text' else False
local_devices = jax.local_devices()
num_gpus = min(FLAGS.num_gpus, len(local_devices))
if FLAGS.job_mode == 'train':
train_dataset = dataset_class(
tokenizer=tokenizer,
graph_tokenizer=graph_tokenizer,
batch_size=FLAGS.train_batch_size,
subset='train',
timesteps=FLAGS.train_timesteps,
version=FLAGS.graph_data_version,
shuffle_data=True,
repeat=True,
debug=FLAGS.debug)
train_iter = iter(train_dataset)
loss_fn = utils.build_loss_fn(vocab_size=tokenizer.vocab_size,
cache_steps=FLAGS.train_memory_size)
optimizer = optax.chain(
optax.clip_by_global_norm(FLAGS.grad_clip),
optax.scale_by_adam(),
optax.scale_by_schedule(functools.partial(
utils.schedule,
lr_schedule=FLAGS.lr_schedule,
init_lr=FLAGS.init_lr,
min_lr_ratio=FLAGS.min_lr_ratio,
max_steps=FLAGS.max_steps)),
optax.scale(-1))
optimizer = optax.apply_if_finite(optimizer, max_consecutive_errors=5)
updater = Updater(loss_fn, optimizer,
devices=local_devices[:num_gpus],
has_graph=has_graph)
updater = CheckpointingUpdater(updater, FLAGS.checkpoint_dir)
_train(updater, train_iter, num_gpus)
elif FLAGS.job_mode == 'eval':
eval_dataset = dataset_class(
tokenizer=tokenizer,
graph_tokenizer=graph_tokenizer,
batch_size=FLAGS.eval_batch_size,
subset=FLAGS.eval_subset,
timesteps=FLAGS.eval_timesteps,
version=FLAGS.graph_data_version,
shuffle_data=False,
repeat=False,
debug=FLAGS.debug)
eval_iter = iter(eval_dataset)
loss_fn = utils.build_loss_fn(vocab_size=tokenizer.vocab_size,
cache_steps=FLAGS.eval_memory_size)
# only use one device for evaluation
devices = local_devices[:1]
updater = Updater(loss_fn, optimizer=None, devices=devices,
has_graph=has_graph)
updater = CheckpointingUpdater(updater, FLAGS.checkpoint_dir)
_eval(updater, eval_iter)
elif FLAGS.job_mode == 'sample':
eval_dataset = dataset_class(
tokenizer=tokenizer,
graph_tokenizer=graph_tokenizer,
batch_size=1,
subset=FLAGS.eval_subset,
timesteps=FLAGS.sample_length,
version=FLAGS.graph_data_version,
shuffle_data=False,
repeat=True,
debug=FLAGS.debug)
eval_iter = iter(eval_dataset)
_sample(eval_iter, tokenizer, local_devices[:num_gpus])
elif FLAGS.job_mode == 'retrieve':
eval_dataset = dataset_class(
tokenizer=tokenizer,
graph_tokenizer=graph_tokenizer,
batch_size=1,
subset=FLAGS.eval_subset,
timesteps=FLAGS.eval_timesteps,
version=FLAGS.graph_data_version,
shuffle_data=False,
repeat=False,
graph_retrieval_dataset=True,
debug=FLAGS.debug)
eval_iter = iter(eval_dataset)
loss_fn = utils.build_loss_fn(vocab_size=tokenizer.vocab_size,
cache_steps=FLAGS.eval_memory_size)
# only use one device for evaluation
devices = local_devices[:1]
updater = Updater(loss_fn, optimizer=None, devices=devices,
has_graph=has_graph)
updater = CheckpointingUpdater(updater, FLAGS.checkpoint_dir)
_retrieve(updater, eval_iter)
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
wikigraphs/main.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Script for building vocabulary files for datasets."""
import collections
import csv
import enum
import io
import os
from typing import List, Tuple
from absl import app
from absl import flags
from absl import logging
from wikigraphs.data import io_tools
from wikigraphs.data import paired_dataset
from wikigraphs.data import tokenizers
from wikigraphs.data import wikitext
class DatasetType(enum.Enum):
text = 1
graph = 2
wikitext = 3
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '', 'Path to the directory that contains the'
' unzipped wikitext-103 data.')
flags.DEFINE_string('vocab_file_path', '', 'Path to the output vocab file.')
flags.DEFINE_enum_class('data_type', DatasetType.wikitext, DatasetType,
'One of {`wikitext`, `graph`, `text`}.')
flags.DEFINE_integer('threshold', 1, 'Frequency threshold for a word to be'
' included in the vocabulary.')
flags.DEFINE_string('version', 'max256', 'Which version of paired data to use.')
def get_vocab(dataset: wikitext.RawDataset) -> List[Tuple[str, int]]:
"""Build vocabulary, return (word, count) tuples sorted by count."""
vocab = collections.defaultdict(int)
for pair in dataset:
for t in pair.text.split(' '):
if t:
vocab[t] += 1
return sorted(vocab.items(), key=lambda t: -t[1])
def write_vocab(vocab: List[Tuple[str, int]], output_path: str):
"""Write a vocab list to a file."""
output_dir = os.path.dirname(output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(output_path, mode='wb') as f_:
with io.TextIOWrapper(f_, encoding='utf-8') as f:
w = csv.writer(f)
w.writerows(vocab)
def build_wikitext_vocab():
logging.info('Loading the dataset.')
dataset = wikitext.RawDataset(subset='train', data_dir=FLAGS.data_dir)
logging.info('Building the vocab.')
vocab = get_vocab(dataset)
logging.info('Finished, vocab size %d, total number of tokens %d',
len(vocab), sum([c for _, c in vocab]))
logging.info('Writing the vocab to %s', FLAGS.vocab_file_path)
write_vocab(vocab, FLAGS.vocab_file_path)
def build_graph_vocab():
"""Build vocabulary for graph data."""
logging.info('Loading the dataset.')
dataset = paired_dataset.ParsedDataset(
subset='train', data_dir=FLAGS.data_dir, version=FLAGS.version)
logging.info('Building graph vocab.')
vocab = collections.defaultdict(int)
for pair in dataset:
graph = pair.graph
for n in graph.nodes():
for t in tokenizers.GraphTokenizer.split_node(n):
if t:
vocab[t] += 1
for _, _, e in graph.edges():
for t in tokenizers.GraphTokenizer.split_edge(e):
if t:
vocab[t] += 1
vocab = sorted(vocab.items(), key=lambda t: -t[1])
vocab = [k for k, v in vocab if v >= FLAGS.threshold]
logging.info('Finished, vocab size %d.', len(vocab))
logging.info('Writing the vocab to %s.', FLAGS.vocab_file_path)
io_tools.write_txt_file(FLAGS.vocab_file_path, '\n'.join(vocab),
# Some unicode characters requires utf-16 to encode.
encoding='utf-16')
def build_text_vocab():
"""Build vocabulary for the text part of the graph-to-text data."""
logging.info('Loading the dataset.')
dataset = paired_dataset.ParsedDataset(
subset='train', data_dir=FLAGS.data_dir, version=FLAGS.version)
logging.info('Building text vocab.')
vocab = collections.defaultdict(int)
for pair in dataset:
for t in pair.text.split(' '):
if t:
vocab[t] += 1
vocab = sorted(vocab.items(), key=lambda t: -t[1])
logging.info('Finished, vocab size %d, total number of tokens %d.',
len(vocab), sum([v for _, v in vocab]))
vocab = [(k, v) for k, v in vocab if v >= FLAGS.threshold]
logging.info('After filtering, vocab size %d.', len(vocab))
logging.info('Writing the vocab to %s.', FLAGS.vocab_file_path)
write_vocab(vocab, FLAGS.vocab_file_path)
def main(_):
if FLAGS.data_type == DatasetType.wikitext:
build_wikitext_vocab()
elif FLAGS.data_type == DatasetType.text:
build_text_vocab()
elif FLAGS.data_type == DatasetType.graph:
build_graph_vocab()
else:
raise ValueError(f'Unknown data type {FLAGS.data_type}.')
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
wikigraphs/scripts/build_vocab.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
r"""Tool to visualize graphs.
You need to have the command line tool `dot` installed locally, for example by
`sudo apt-get install graphviz`.
Example usage:
python visualize_graph.py \
--logtostderr --graph_ids=0:48 --truncate_limit=500 --layout=fdp
"""
import html
import os
import textwrap
from absl import app
from absl import flags
from absl import logging
from wikigraphs.data import io_tools
from wikigraphs.data import paired_dataset as pd
FLAGS = flags.FLAGS
flags.DEFINE_string('subset', 'valid', 'Which subset to choose graphs from.')
flags.DEFINE_string('graph_ids', '', 'A comma-separated string of graph IDs'
' (0-based), for example `1,2,3`. Or alternatively a'
' range, e.g. `0:10` which is equivalent to'
' `0,1,2,3,...,9`.')
flags.DEFINE_string('version', 'max256', 'Which version of data to load.')
flags.DEFINE_string('data_dir', '', 'Path to a directory that contains the raw'
' paired data, if provided.')
flags.DEFINE_string('output_dir', '/tmp/graph_vis', 'Output directory to save'
' the visualized graphs.')
flags.DEFINE_integer('truncate_limit', -1, 'Maximum length for graph nodes in'
' visualization.')
flags.DEFINE_string('layout', 'fdp', 'Which one of the dot layout to use.')
def truncate(s: str) -> str:
if FLAGS.truncate_limit > 0 and len(s) > FLAGS.truncate_limit:
s = s[:FLAGS.truncate_limit] + '...'
return s
def format_label(s: str, width: int = 40) -> str:
"""Format a node / edge label."""
s = io_tools.normalize_freebase_string(s)
s = truncate(s)
lines = s.split('\\n')
output_lines = []
for line in lines:
line = html.escape(line)
if width > 0:
output_lines += textwrap.wrap(line, width)
else:
output_lines.append(line)
return '<' + '<br/>'.join(output_lines) + '>'
def graph_to_dot(graph_text_pair: io_tools.GraphTextPair) -> str:
"""Convert a graph to a dot file."""
dot = ['digraph {', 'node [shape=rect];']
graph = pd.Graph.from_edges(graph_text_pair.edges)
center_node_id = graph.node2id(graph_text_pair.center_node)
for i, n in enumerate(graph.nodes()):
color = '#f5dc98' if i == center_node_id else (
'#b0ffad' if not(n[0] == '"' and n[-1] == '"') else '#ffffff')
label = format_label(n)
dot.append(f'{i} [ label = {label}, fillcolor="{color}", style="filled"];')
for i, j, e in graph.edges():
dot.append(f'{i} -> {j} [ label = {format_label(e, width=0)} ];')
dot.append('}')
return '\n'.join(dot)
def visualize_graph(graph_text_pair: io_tools.GraphTextPair,
graph_id: int,
output_dir: str):
"""Visualize a graph and save the visualization to the specified directory."""
dot = graph_to_dot(graph_text_pair)
output_file = os.path.join(output_dir, f'{graph_id}.dot')
logging.info('Writing output to %s', output_file)
with open(output_file, 'w') as f:
f.write(dot)
pdf_output = os.path.join(output_dir, f'{graph_id}.pdf')
os.system(f'dot -K{FLAGS.layout} -Tpdf -o {pdf_output} {output_file}')
def main(_):
logging.info('Loading the %s set of data.', FLAGS.subset)
pairs = list(pd.RawDataset(subset=FLAGS.subset,
data_dir=FLAGS.data_dir or None,
shuffle_data=False,
version=FLAGS.version))
logging.info('Loaded %d graph-text pairs.')
if ':' in FLAGS.graph_ids:
start, end = [int(i) for i in FLAGS.graph_ids.split(':')]
graph_ids = list(range(start, end))
else:
graph_ids = [int(i) for i in FLAGS.graph_ids.split(',')]
logging.info('Visualizing graphs with ID %r', graph_ids)
if not os.path.exists(FLAGS.output_dir):
os.makedirs(FLAGS.output_dir)
for gid in graph_ids:
visualize_graph(pairs[gid], gid, FLAGS.output_dir)
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
wikigraphs/scripts/visualize_graph.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Preprocess freebase data and pair with wikitext."""
import os
from absl import app
from absl import flags
from absl import logging
from wikigraphs.data import io_tools
from wikigraphs.data import wikitext
FLAGS = flags.FLAGS
flags.DEFINE_string('freebase_dir', '', 'Directory that containns Freebase'
' graphs.')
flags.DEFINE_string('output_dir', '', 'Path to output directory to store the'
' paired dataset.')
def pair_graphs_with_wikitext(subset: str, graph_dir: str, output_dir: str):
"""Pair graphs with wikitext articles, and write to output directory."""
logging.info('Pairing graphs from the %s set from %s with wikitext.',
subset, graph_dir)
graphs = list(io_tools.graphs_from_file(
os.path.join(graph_dir, f'{subset}.gz')))
title2graph = {
io_tools.normalize_freebase_string(g.title).replace(' ', ''): g
for g in graphs}
n_graphs = len(graphs)
# Use raw version of the wikitext data as the tokenized version has <unk> in
# titles which is bad for matching. We will handle the <unk>s through the
# tokenizer to make sure our data are equivalent to that of the tokenized
# version of wikitext-103.
wikitext_articles = list(wikitext.RawDataset(subset=subset, version='raw'))
n_wiki = len(wikitext_articles)
logging.info('Loaded %d graphs and %d wikitext articles in total.',
n_graphs, n_wiki)
# Keep track of the article titles in the dataset. Unfortunately wikitext-103
# has about 1% of duplicated articles, we want to take care of that.
retrieved_titles = set()
pairs = []
n_duplicates = 0
for a in wikitext_articles:
title = wikitext.normalize_title(a.title).replace(' ', '')
g = title2graph.get(title, None)
if g is not None:
if title not in retrieved_titles:
retrieved_titles.add(title)
pairs.append(io_tools.GraphTextPair(
center_node=g.center,
title=g.title,
edges=g.edges,
text=a.text))
else:
n_duplicates += 1
n_pairs = len(pairs)
logging.info('Matched %d/%d = %.1f%% of wikitext articles,'
' and %d/%d = %.1f%% of graphs.',
n_pairs, n_wiki, float(n_pairs) / n_wiki * 100,
n_pairs, n_graphs, float(n_pairs) / n_graphs * 100)
logging.info('Detected %d/%d = %.1f%% of duplicated wikitext articles.',
n_duplicates, n_wiki, float(n_duplicates) / n_wiki * 100)
io_tools.write_pairs_to_gzip_txt_file(
os.path.join(output_dir, f'{subset}.gz'), pairs)
def main(_):
for subset in ['train', 'valid', 'test']:
pair_graphs_with_wikitext(subset, FLAGS.freebase_dir, FLAGS.output_dir)
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
wikigraphs/scripts/freebase_preprocess.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Compute the bleu score on generated text and the ground truth."""
import math
import os
import pickle
from absl import app
from absl import flags
from absl import logging
import numpy as np
import utils
flags.DEFINE_string('checkpoint_dir', '/tmp/transformerXL',
'Checkpoint directory to load saved samples.')
flags.DEFINE_string('dataset', 'freebase2wikitext', 'Which dataset to the model'
' is trained on, one of "wikitext", "freebase2wikitext".')
FLAGS = flags.FLAGS
def group_samples(samples, tokenizer):
"""Groups generated and ground truth texts."""
groups = {}
for i, row in enumerate(samples):
gt = tokenizer.decode(row['ground_truth_text'])
sample = tokenizer.decode(row['sample_tokens'])
if gt not in groups:
groups[gt] = (gt.split(), [sample.split()])
else:
groups[gt][-1].append(sample.split())
if (i + 1) % 100 == 0:
logging.info('Processed %d samples', i + 1)
return groups
def eval_samples(raw_samples, tokenizer):
"""Evaluates generated samples."""
gt_refs = []
samples = []
groups = group_samples(raw_samples, tokenizer)
groups = list(groups.values())
avg_group_size = np.mean([len(g[-1]) for g in groups])
logging.info('Average samples per example: %.2f', avg_group_size)
avg_group_size = int(math.ceil(avg_group_size))
for i, (gt, s) in enumerate(groups):
gt_refs.append(gt)
idx = i % len(groups)
samples.append(groups[idx][-1])
gt_bleu, gt_n_grams = utils.compute_bleu(samples, gt_refs)
logging.info('Processed %d samples in total.', sum([len(s) for s in samples]))
flat_samples = []
for s in samples:
flat_samples.extend(s)
logging.info('Average sample len: %.2f',
np.mean([len(s) for s in flat_samples]))
logging.info('Average ground-truth len: %.2f',
np.mean([len(gt) for gt in gt_refs]))
logging.info('Ground-truth BLEU: %6.2f, n-gram precision: (%s)',
gt_bleu * 100,
', '.join(['%6.2f%%' % (s * 100) for s in gt_n_grams]))
def main(_):
tokenizer = utils.init_tokenizer(FLAGS.dataset)
checkpoint_dir = os.path.join(FLAGS.checkpoint_dir, 'samples.pkl')
logging.info('Loading samples from %s', checkpoint_dir)
with open(checkpoint_dir, 'rb') as f:
samples = pickle.load(f)['samples']
eval_samples(samples, tokenizer)
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
wikigraphs/scripts/compute_blue_score.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.