python_code
stringlengths
0
780k
repo_name
stringlengths
7
38
file_path
stringlengths
5
103
# Copyright 2022 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generates the sorting network dataset.""" from collections import Counter import os from absl import app from absl import flags from absl import logging import jraph import numpy as np from ogb.graphproppred import GraphPropPredDataset import pandas as pd from tqdm import tqdm import ogb_utils import dataflow_parser from script_postcompute_eigedecomp import process_graph _OUT_PATH = flags.DEFINE_string('out_path', './data/ogb/ogbg-code2-norev-df', 'The path to write datasets to.') _RAW_PATH = flags.DEFINE_string('raw_path', './data/ogb', 'The path to write datasets to.') _SHARD_SIZE = flags.DEFINE_integer( 'shard_size', 10_000, 'The number of times to store in each file.') _NUM_VOCAB = flags.DEFINE_integer('num_vocab', 5000, 'the number of vocabulary used for sequence prediction') _MAX_SEQ_LEN = flags.DEFINE_integer( 'max_seq_len', 5, 'maximum sequence length to predict') _DATA_FLOW = flags.DEFINE_bool( 'data_flow', True, 'Data-flow centric graph construction') maglap_configs = [ dict(k=15, k_excl=0, q=0.1, q_absolute=False, norm_comps_sep=False, sign_rotate=False, use_symmetric_norm=True, l2_norm=True, exclude_cfg=False, exclude_ns=True) ] def process_graph_(graph, config): config = config.copy() exclude_control_flow_edges = config.pop('exclude_cfg') exclude_next_syntax_edges = config.pop('exclude_ns') mask = np.ones_like(graph.edges["edge_type"], dtype=bool) if exclude_control_flow_edges: # These edges are the sequential edges of python_graphs mask = graph.edges["edge_type"] != 1 if exclude_next_syntax_edges: # These edges are the original control flow edges of python_graphs mask = mask & (graph.edges["edge_type"] != 9) mask = mask.squeeze() senders = graph.senders[mask] receivers = graph.receivers[mask] n_dropped_edges = (~mask).sum() n_edge = graph.n_edge - n_dropped_edges graph_ = graph._replace( edges=None, senders=senders, receivers=receivers, n_edge=n_edge) return process_graph(graph_, **config) def to_graphs_tuple(raw_graph, ogb_edge_types=True, max_token_length=1_023): """Converts the OGB Code 2 to a GraphsTuple.""" if ogb_edge_types: edge_index, edge_attr = ogb_utils.augment_edge( raw_graph['edge_index'], raw_graph['node_is_attributed'], reverse=False) else: edge_index = raw_graph['edge_index'] edge_attr = dict(edge_type=raw_graph['edge_type'], edge_name=raw_graph['edge_name'], edge_order=raw_graph['edge_order']) senders = edge_index[0] receivers = edge_index[1] nodes = dict(node_feat=raw_graph['node_feat'], node_depth=raw_graph['node_depth']) if 'node_feat_raw' in raw_graph: nodes['node_feat_raw'] = raw_graph['node_feat_raw'] if 'node_feat_orig' in raw_graph: nodes['node_feat_orig'] = raw_graph['node_feat_orig'] edges = edge_attr n_node = np.array([raw_graph['num_nodes']]) n_edge = np.array([len(senders)]) graph = jraph.GraphsTuple( nodes=nodes, edges=edges, senders=senders, receivers=receivers, n_node=n_node, n_edge=n_edge, globals=None) if graph.n_node <= max_token_length: precomputed = tuple( (config, *process_graph_(graph, config)) for config in maglap_configs) else: # To make sure the shapes are constant for tfds def dummy_eigenvec(k): return np.full((graph.nodes['node_feat'].shape[0], k), np.nan, dtype=np.complex64) precomputed = tuple( (config, np.full(config['k'], np.nan, dtype=np.float32), dummy_eigenvec(config['k'])) for config in maglap_configs) graph = graph._replace(globals=dict(eigendecomposition=precomputed)) return graph def encode_raw_target(target): return np.array([s.encode('utf-8') for s in target], dtype='object') def main(*args, dataset_name='ogbg-code2', **kwargs): ds = GraphPropPredDataset(dataset_name, root=_RAW_PATH.value) vocab2idx, idx2vocab = ogb_utils.get_vocab_mapping( [ds[i][1] for i in ds.get_idx_split()['train']], _NUM_VOCAB.value) metadata = { 'vocab2idx': vocab2idx, 'idx2vocab': idx2vocab, # +2 to account for end of sequence and unknown token 'num_vocab': str(_NUM_VOCAB.value + 2).encode('utf-8'), 'max_seq_len': str(_MAX_SEQ_LEN.value).encode('utf-8') } if _DATA_FLOW.value: mapping_dir = os.path.join(_RAW_PATH.value, 'ogbg_code2', 'mapping') attr2idx = dict() for line in pd.read_csv(os.path.join(mapping_dir, 'attridx2attr.csv.gz')).values: attr2idx[line[1]] = int(line[0]) type2idx = dict() for line in pd.read_csv(os.path.join(mapping_dir, 'typeidx2type.csv.gz')).values: type2idx[line[1]] = int(line[0]) code_dict_file_path = os.path.join(mapping_dir, 'graphidx2code.json.gz') code_dict = pd.read_json(code_dict_file_path, orient='split') split_ids = ds.get_idx_split() if _DATA_FLOW.value: node_type_counter = Counter() node_value_counter = Counter() edge_name_counter = Counter() for split, ids in split_ids.items(): file_path = os.path.join(_OUT_PATH.value, split) os.makedirs(file_path, exist_ok=True) os.makedirs(os.path.join(file_path, 'raw'), exist_ok=True) buffer = [] start_id = ids[0] for id_ in tqdm(list(ids)): try: df_graph = dataflow_parser.py2ogbgraph( code_dict.iloc[id_].code, attr2idx, type2idx)[0] for node_type in df_graph['node_feat_raw'][:, 0]: node_type = node_type.decode('utf-8') node_type_counter[node_type] += 1 for node_value in df_graph['node_feat_raw'][:, 1]: node_value = node_value.decode('utf-8') node_value_counter[node_value] += 1 for edge_name in df_graph['edge_name'].squeeze(): edge_name = edge_name.decode('utf-8') edge_name_counter[edge_name] += 1 buffer.append((df_graph, ogb_utils.encode_y_to_arr( ds[id_][1], vocab2idx, _MAX_SEQ_LEN.value), encode_raw_target(ds[id_][1]), np.array(id_))) except: # pylint: disable=bare-except print(f'Error for graph {id_}') print(code_dict.iloc[id_].code) if len(buffer) >= _SHARD_SIZE.value or id_ == ids[-1]: file_name = os.path.join( file_path, 'raw', f'{start_id}_{id_}_raw.npz') np.savez_compressed(file_name, data=np.array(buffer, dtype='object')) logging.info('Wrote %d to %s', len(buffer), file_name) buffer = [] start_id = id_ topk_node_values = node_value_counter.most_common(11_972) node_values_to_idx = {k: v for v, (k, _) in enumerate(topk_node_values)} def node_values_to_idx_with_default(value): if value in node_values_to_idx: return node_values_to_idx[value] return len(node_values_to_idx) node_type_to_idx = { k: v for v, (k, _) in enumerate(node_type_counter.most_common())} edge_name_to_idx = { k: v for v, (k, _) in enumerate(edge_name_counter.most_common())} metadata['node_values_to_idx'] = node_values_to_idx metadata['node_type_to_idx'] = node_type_to_idx metadata['edge_name_to_idx'] = edge_name_to_idx file = os.path.join(_OUT_PATH.value, 'meta.npz') np.savez_compressed(file, data=np.array(metadata, dtype='object')) logging.info('Wrote %s', file) for split in split_ids.keys(): file_path = os.path.join(_OUT_PATH.value, split) files = os.listdir(os.path.join(file_path, 'raw')) for f in tqdm(files): if 'raw' not in f: continue buffer = [] for graph, *remainder in np.load( os.path.join(file_path, 'raw', f), allow_pickle=True)["data"]: node_types = [ node_type_to_idx[node_type.decode('utf-8')] for node_type in graph['node_feat_raw'][:, 0] ] node_values = [ node_values_to_idx_with_default(node_value.decode('utf-8')) for node_value in graph['node_feat_raw'][:, 1] ] graph['node_feat_orig'] = graph['node_feat'] graph['node_feat'] = np.array((node_types, node_values), dtype=np.int64).transpose() del graph['node_feat_raw'] edge_names = [ edge_name_to_idx[edge_name.decode('utf-8')] for edge_name in graph['edge_name'].squeeze() ] graph['edge_name'] = np.array( edge_names, dtype=np.int64)[:, None] graphs_tuple = to_graphs_tuple(graph, ogb_edge_types=False) buffer.append((graphs_tuple, *remainder)) file_name = os.path.join(file_path, f.replace('_raw', '')) np.savez_compressed(file_name, data=np.array(buffer, dtype='object')) logging.info('Wrote %d to %s', len(buffer), file_name) return file = os.path.join(_OUT_PATH.value, 'meta.npz') np.savez_compressed(file, data=np.array(metadata, dtype='object')) logging.info('Wrote %s', file) for split, ids in split_ids.items(): file_path = os.path.join(_OUT_PATH.value, split) buffer = [] start_id = ids[0] for id_ in tqdm(list(ids)): graphs_tuple = to_graphs_tuple(ds[id_][0]) buffer.append(( graphs_tuple, ogb_utils.encode_y_to_arr(ds[id_][1], vocab2idx, _MAX_SEQ_LEN.value), encode_raw_target(ds[id_][1]), np.array(id_))) if len(buffer) >= _SHARD_SIZE.value or id_ == ids[-1]: file_name = os.path.join(file_path, f'{start_id}_{id_}.npz') np.savez_compressed(file_name, data=np.array(buffer, dtype='object')) logging.info('Wrote %d to %s', len(buffer), file_name) buffer = [] start_id = id_ if __name__ == '__main__': app.run(main)
digraph_transformer-main
script_generate_ogb_code2_np.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Install script for setuptools.""" import os from setuptools import find_namespace_packages from setuptools import setup _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) setup( name='csuite', version='0.1.0', url='https://github.com/deepmind/csuite', license='Apache 2.0', author='DeepMind', description=( 'A collection of continuing environments for reinforcement learning.'), long_description=open(os.path.join(_CURRENT_DIR, 'README.md')).read(), long_description_content_type='text/markdown', author_email='[email protected]', keywords='reinforcement-learning environment suite python machine learning', packages=find_namespace_packages(exclude=['*_test.py']), install_requires=[ 'dm_env>=1.5', 'gym>=0.19.0', 'numpy>=1.18.0', 'Pillow>=9.0.1', 'absl-py>=0.7.1', 'pytest>=6.2.5', ], zip_safe=False, # Required for full installation. python_requires='>=3.9,<3.11', classifiers=[ # TODO(b/241264065): list classifiers. 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', ], )
csuite-main
setup.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Configuration file for the Sphinx documentation builder.""" # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # pylint: disable=g-bad-import-order # pylint: disable=g-import-not-at-top import inspect import os import sys import typing def _add_annotations_import(path): """Appends a future annotations import to the file at the given path.""" with open(path) as f: contents = f.read() if contents.startswith('from __future__ import annotations'): # If we run sphinx multiple times then we will append the future import # multiple times too. return assert contents.startswith('#'), (path, contents.split('\n')[0]) with open(path, 'w') as f: # NOTE: This is subtle and not unit tested, we're prefixing the first line # in each Python file with this future import. It is important to prefix # not insert a newline such that source code locations are accurate (we link # to GitHub). The assertion above ensures that the first line in the file is # a comment so it is safe to prefix it. f.write('from __future__ import annotations ') f.write(contents) def _recursive_add_annotations_import(): for path, _, files in os.walk('../csuite/'): for file in files: if file.endswith('.py'): _add_annotations_import(os.path.abspath(os.path.join(path, file))) if 'READTHEDOCS' in os.environ: _recursive_add_annotations_import() typing.get_type_hints = lambda obj, *unused: obj.__annotations__ sys.path.insert(0, os.path.abspath('../')) sys.path.append(os.path.abspath('ext')) import csuite from sphinxcontrib import katex # -- Project information ----------------------------------------------------- project = 'CSuite' copyright = '2022, DeepMind' # pylint: disable=redefined-builtin author = 'CSuite Contributors' # -- General configuration --------------------------------------------------- master_doc = 'index' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'myst_parser', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.doctest', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.intersphinx', 'sphinx.ext.linkcode', 'sphinx.ext.napoleon', 'sphinxcontrib.katex', 'sphinx_autodoc_typehints', 'sphinx_rtd_theme', # 'coverage_check', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for autodoc ----------------------------------------------------- autodoc_default_options = { 'member-order': 'bysource', 'special-members': True, 'exclude-members': '__repr__, __str__, __weakref__', } # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # html_favicon = '_static/favicon.ico' # -- Options for katex ------------------------------------------------------ # See: https://sphinxcontrib-katex.readthedocs.io/en/0.4.1/macros.html latex_macros = r""" \def \d #1{\operatorname{#1}} """ # Translate LaTeX macros to KaTeX and add to options for HTML builder katex_macros = katex.latex_defs_to_katex_macros(latex_macros) katex_options = 'macros: {' + katex_macros + '}' # Add LaTeX macros for LATEX builder latex_elements = {'preamble': latex_macros} # -- Source code links ------------------------------------------------------- def linkcode_resolve(domain, info): """Resolve a GitHub URL corresponding to Python object.""" if domain != 'py': return None try: mod = sys.modules[info['module']] except ImportError: return None obj = mod try: for attr in info['fullname'].split('.'): obj = getattr(obj, attr) except AttributeError: return None else: obj = inspect.unwrap(obj) try: filename = inspect.getsourcefile(obj) except TypeError: return None try: source, lineno = inspect.getsourcelines(obj) except OSError: return None return 'https://github.com/deepmind/csuite/tree/master/csuite/%s#L%d#L%d' % ( os.path.relpath(filename, start=os.path.dirname( csuite.__file__)), lineno, lineno + len(source) - 1) # -- Intersphinx configuration ----------------------------------------------- intersphinx_mapping = { 'jax': ('https://jax.readthedocs.io/en/latest/', None), } source_suffix = ['.rst', '.md']
csuite-main
docs/conf.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Helper(s) to load csuite environments.""" import enum from typing import Dict, Optional, Union from csuite.environments import access_control from csuite.environments import catch from csuite.environments import dancing_catch from csuite.environments import pendulum from csuite.environments import taxi from csuite.environments import windy_catch from csuite.environments.base import Environment from csuite.environments.experimental import pendulum_poke from csuite.utils import dm_env_wrapper from csuite.utils import gym_wrapper class EnvName(enum.Enum): ACCESS_CONTROL = 'access_control' CATCH = 'catch' DANCING_CATCH = 'dancing_catch' PENDULUM = 'pendulum' PENDULUM_POKE = 'pendulum_poke' TAXI = 'taxi' WINDY_CATCH = 'windy_catch' _ENVS = { EnvName.ACCESS_CONTROL: access_control.AccessControl, EnvName.CATCH: catch.Catch, EnvName.DANCING_CATCH: dancing_catch.DancingCatch, EnvName.WINDY_CATCH: windy_catch.WindyCatch, EnvName.TAXI: taxi.Taxi, EnvName.PENDULUM: pendulum.Pendulum, EnvName.PENDULUM_POKE: pendulum_poke.PendulumPoke, } def load(name: Union[EnvName, str], settings: Optional[Dict[str, Union[float, int, bool]]] = None): """Loads a csuite environment. Args: name: The enum or string specifying the environment name. settings: Optional `dict` of keyword arguments for the environment. Returns: An instance of the requested environment. """ name = EnvName(name) settings = settings or {} return _ENVS[name](**settings)
csuite-main
csuite/__init__.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests all environments through the csuite interface.""" import typing from absl.testing import absltest from absl.testing import parameterized import csuite from dm_env import specs import numpy as np class CSuiteTest(parameterized.TestCase): @parameterized.parameters([e.value for e in csuite.EnvName]) def test_envs(self, env_name): """Tests that we can use the environment in typical ways.""" env = csuite.load(env_name) action_spec = env.action_spec() observation_spec = env.observation_spec() obs = env.start() env.render() init_state = env.get_state() for i in range(2): with self.subTest(name="steps-render-successful", step=i): image = env.render() with self.subTest(name="steps-render-compliant", step=i): self._assert_image_compliant(image) with self.subTest(name="steps-observation_spec", step=i): observation_spec.validate(obs) with self.subTest(name="steps-step", step=i): obs, unused_reward = env.step(action_spec.generate_value()) env.set_state(init_state) @parameterized.parameters([e.value for e in csuite.EnvName]) def test_env_state_resets(self, env_name): """Tests that `get`ing and `set`ing state results in reproducibility.""" # Since each environment is different, we employ a generic strategy that # should # # a) get us to a variety of states to query the state on, # b) take a number of steps from that state to check reproducibility. # # See the implementation for the specific strategy taken. num_steps_to_check = 4 env = csuite.load(env_name) env.start() action_spec = env.action_spec() if not isinstance(action_spec, specs.DiscreteArray): raise NotImplementedError( "This test only supports environments with discrete action " "spaces for now. Please raise an issue if you want to work with a " "a non-discrete action space.") action_spec = typing.cast(specs.DiscreteArray, action_spec) for action in range(action_spec.num_values): env.step(action) orig_state = env.get_state() outputs_1 = [env.step(action) for _ in range(num_steps_to_check)] observations_1, rewards_1 = zip(*outputs_1) env.set_state(orig_state) outputs_2 = [env.step(action) for _ in range(num_steps_to_check)] observations_2, rewards_2 = zip(*outputs_2) with self.subTest("observations", action=action): self.assertSameObsSequence(observations_1, observations_2) with self.subTest("rewards", action=action): self.assertSequenceEqual(rewards_1, rewards_2) def assertSameObsSequence(self, seq1, seq2): """The observations are expected to be numpy objects.""" # self.assertSameStructure(seq1, seq2) problems = [] # (idx, problem str) for idx, (el1, el2) in enumerate(zip(seq1, seq2)): try: np.testing.assert_array_equal(el1, el2) except AssertionError as e: problems.append((idx, str(e))) if problems: self.fail( f"The observation sequences (of length {len(seq1)}) are not the " "same. The differences are:\n" + "\n".join([f"at idx={idx}: {msg}" for idx, msg in problems])) def _assert_image_compliant(self, image: np.ndarray): if not (len(image.shape) == 3 and image.shape[-1] == 3 and image.dtype == np.uint8): self.fail( "The render() method is expected to return an uint8 rgb image array. " f"Got an array of shape {image.shape}, dtype {image.dtype}.") if __name__ == "__main__": absltest.main()
csuite-main
csuite/csuite_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of the tabular Taxi environment. Environment description and details can be found in the `Taxi` environment class. The 5x5 gridworld is depicted below, where we use xy-coordinates to describe the position of the squares; the coordinate (0, 0) represents the top left corner. ||||||||||| |R: | : :G| | : | : : | | : : : : | | | : | : | |Y| : |B: | ||||||||||| """ import copy import dataclasses import enum import itertools from typing import Optional from csuite.environments import base from dm_env import specs import numpy as np from PIL import Image from PIL import ImageDraw # Default environment variables. _NUM_ROWS = 5 _NUM_COLUMNS = 5 # Passenger positions: one of the four pickup locations, or in the taxi. _NUM_POSITIONS = 5 _NUM_DEST = 4 _NUM_STATES = _NUM_ROWS * _NUM_COLUMNS * _NUM_POSITIONS * _NUM_DEST _NUM_ACTIONS = 6 # Error messages. _INVALID_ACTION = "Invalid action: expected value in [0,5] but received {}." _INVALID_TAXI_LOC = "Invalid state: expected taxi coordinates in range [0,4]." _INVALID_PASS_LOC = ("Invalid state: expected passenger location as an integer" "in [0,4].") _INVALID_DEST = ("Invalid state: expected destination location as an integer" "in [0,3].") # Dictionary mapping the four colored squares to their xy-coordinate # on the 5x5 grid, with keys 0 (Red), 1 (Green), 2 (Yellow), 3 (Blue). _COLOR_POSITIONS = { 0: (0, 0), 1: (4, 0), 2: (0, 4), 3: (3, 4), } # List of (x, y) pairs where transitioning # between each pair's shared edge is forbidden. _BLOCKED_TUPLE = ( ((1, 0), (2, 0)), ((1, 1), (2, 1)), ((0, 3), (1, 3)), ((0, 4), (1, 4)), ((2, 3), (3, 3)), ((2, 4), (3, 4)), ) # Variables for pixel visualization of the environment. _PIXELS_PER_SQ = 50 # size of each grid square. _RED_HEX = "#ff9999" _GREEN_HEX = "#9cff9c" _BLUE_HEX = "#99e2ff" _YELLOW_HEX = "#fff899" _PASS_LOC_HEX = "#d400ff" _DEST_HEX = "#008c21" _EMPTY_TAXI_HEX = "#8f8f8f" # Other derived constants used for pixel visualization. _HEIGHT = _PIXELS_PER_SQ * (_NUM_ROWS + 2) _WIDTH = _PIXELS_PER_SQ * (_NUM_COLUMNS + 2) _BORDER = [ # Bounding box for perimeter of the taxi grid. (_PIXELS_PER_SQ, _PIXELS_PER_SQ), (_PIXELS_PER_SQ * (_NUM_COLUMNS + 1), _PIXELS_PER_SQ * (_NUM_ROWS + 1)) ] _OFFSET = _PIXELS_PER_SQ // 5 # To make the taxi bounding box slightly smaller. _LINE_WIDTH_THIN = _PIXELS_PER_SQ // 50 _LINE_WIDTH_THICK = _PIXELS_PER_SQ // 10 # Dictionary mapping the four colored squares to their rectangle bounding boxes # used for visualization, with keys 0 (Red), 1 (Green), 2 (Yellow), 3 (Blue). _BOUNDING_BOXES = { idx: [(_PIXELS_PER_SQ * (x + 1), _PIXELS_PER_SQ * (y + 1)), (_PIXELS_PER_SQ * (x + 2), _PIXELS_PER_SQ * (y + 2))] for idx, (x, y) in _COLOR_POSITIONS.items() } class Action(enum.IntEnum): """Actions for the Taxi environment. There are six actions: 0: move North. 1: move West. 2: move South. 3: move East. 4: pickup the passenger. 5: dropoff the passenger. """ NORTH, WEST, SOUTH, EAST, PICKUP, DROPOFF = list(range(_NUM_ACTIONS)) @property def dx(self): """Maps EAST to 1, WEST to -1, and other actions to 0.""" if self.name == "EAST": return 1 elif self.name == "WEST": return -1 else: return 0 @property def dy(self): """Maps NORTH to -1, SOUTH to 1, and other actions to 0.""" if self.name == "NORTH": return -1 elif self.name == "SOUTH": return 1 else: return 0 @dataclasses.dataclass class State: """State of a continuing Taxi environment. The coordinate system excludes border of the map and provides the location of the taxi. The coordinate (0, 0) corresponds to the top left corner, i.e. the Red pickup location, and the coordinate (4, 4) corresponds to the bottom right corner. The passenger location is an integer in [0, 4] corresponding to the four colored squares and the fifth possible position being in the taxi. The destination is similarly numbered, but only includes the four colored squares: 0 - Red square. 1 - Green square. 2 - Yellow square. 3 - Blue square. 4 - In taxi. """ taxi_x: int taxi_y: int passenger_loc: int destination: int rng: np.random.Generator class Taxi(base.Environment): """A continuing Taxi environment. This environment originates from the paper "Hierarchical Reinforcement Learning with the MAXQ Value Function Decomposition" by Tom Dietterich. In a square grid world with four colored squares (R(ed), G(reen), Y(ellow), B(lue)), the agent must drive a taxi to various passengers' locations and drop them off at the passenger's desired location at one of the four squares. The agent receives positive reward for each passenger successfully picked up and dropped off, and receives negative reward for doing an inappropriate action (eg. dropping off the passenger at the incorrect location, attempting to pick up a passenger on an empty square, etc.). There are six possible actions, corresponding to four navigation actions (move North, South, East, and West), a pickup action, and a dropoff action. The observation space is a single state index, which encodes the possible states accounting for the taxi position, location of the passenger, and four desired destination locations. """ def __init__(self, seed=None): """Initialize Taxi environment. Args: seed: Seed for the internal random number generator. """ self._seed = seed self._state = None # Populate lookup table for observations. self.lookup_table = {} for idx, state in enumerate( itertools.product( range(_NUM_ROWS), range(_NUM_COLUMNS), range(_NUM_POSITIONS), range(_NUM_DEST))): self.lookup_table[state] = idx def start(self, seed: Optional[int] = None): """Initializes the environment and returns an initial observation.""" rng = np.random.default_rng(self._seed if seed is None else seed) self._state = State( taxi_x=rng.integers(_NUM_COLUMNS), taxi_y=rng.integers(_NUM_ROWS), passenger_loc=rng.integers(_NUM_POSITIONS - 1), destination=rng.integers(_NUM_DEST), rng=rng, ) return self._get_observation() @property def started(self): """True if the environment has been started, False otherwise.""" # An unspecified state implies that the environment needs to be started. return self._state is not None def step(self, action): """Updates the environment state and returns an observation and reward. Args: action: An integer in [0,5] indicating whether the taxi moves, picks up the passenger, or drops off the passenger. Returns: A tuple of type (int, float) giving the next observation and the reward. Raises: RuntimeError: If state has not yet been initialized by `start`. ValueError: If input action has an invalid value. """ # Check if state has been initialized. if not self.started: raise RuntimeError(base.STEP_WITHOUT_START_ERR) # Check if input action is valid. if action not in [a.value for a in Action]: raise ValueError(_INVALID_ACTION.format(action)) reward = 0 # Move taxi according to the action. self._state.taxi_y = np.clip(self._state.taxi_y + Action(action).dy, 0, _NUM_ROWS - 1) # If moving East or West, check that the taxi does not hit a barrier. if action in [Action.EAST, Action.WEST]: move = ((self._state.taxi_x, self._state.taxi_y), (self._state.taxi_x + Action(action).dx, self._state.taxi_y)) if action == Action.WEST: # Need to reverse the tuple. move = move[::-1] if move not in _BLOCKED_TUPLE: self._state.taxi_x = np.clip(self._state.taxi_x + Action(action).dx, 0, _NUM_COLUMNS - 1) # If action is pickup, check if passenger location matches current location. if action == Action.PICKUP: if self._state.passenger_loc == 4: # Passenger was already picked up. reward = -10 else: passenger_coordinates = _COLOR_POSITIONS[self._state.passenger_loc] # Check if passenger and taxi are at the same location. if passenger_coordinates != (self._state.taxi_x, self._state.taxi_y): reward = -10 else: # Passenger has been successfully picked up. self._state.passenger_loc = 4 # If action is dropoff, check if passenger is present in taxi and # desired destination matches current location. if action == Action.DROPOFF: dest_coordinates = _COLOR_POSITIONS[self._state.destination] if (self._state.passenger_loc != 4 or dest_coordinates != (self._state.taxi_x, self._state.taxi_y)): reward = -10 else: reward = 20 # Add new passenger. self._state.passenger_loc = self._state.rng.integers(_NUM_POSITIONS - 1) self._state.destination = self._state.rng.integers(_NUM_DEST) return self._get_observation(), reward def _get_observation(self): """Returns a observation index uniquely identifying the current state.""" state_tuple = (self._state.taxi_x, self._state.taxi_y, self._state.passenger_loc, self._state.destination) return self.lookup_table[state_tuple] def observation_spec(self): """Describes the observation specs of the environment.""" return specs.DiscreteArray(_NUM_STATES, dtype=int, name="observation") def action_spec(self): """Describes the action specs of the environment.""" return specs.DiscreteArray(_NUM_ACTIONS, dtype=int, name="action") def get_state(self): """Returns a copy of the current environment state.""" return copy.deepcopy(self._state) if self._state is not None else None def set_state(self, state): """Sets environment state to state provided. Args: state: A State object which overrides the current state. """ # Check that input state values are valid. if not (0 <= state.taxi_x < _NUM_COLUMNS and 0 <= state.taxi_y < _NUM_ROWS): raise ValueError(_INVALID_TAXI_LOC) elif not 0 <= state.passenger_loc < _NUM_POSITIONS: raise ValueError(_INVALID_PASS_LOC) elif not 0 <= state.destination < _NUM_DEST: raise ValueError(_INVALID_DEST) self._state = copy.deepcopy(state) def render(self) -> np.ndarray: """Creates an image of the current environment state. The underlying grid with the four colored squares are drawn. The taxi is drawn as a circle which is _PASS_LOC_HEX (purple) when the passenger is present, and _EMPTY_TAXI_HEX (grey) otherwise. The passenger location before being picked up is outlined with the color _PASS_LOC_HEX (purple), and the destination location is similarly outlined with the color _DEST_HEX (dark green). In the case where the passenger location and self._state.destination are identical, only the self._state.destination outline is visible. Returns: A NumPy array giving an image of the environment state. """ image = Image.new("RGB", (_WIDTH, _HEIGHT), "white") dct = ImageDraw.Draw(image) # First place four colored destination squares so grid lines appear on top. # Red, green, yellow, and blue squares. dct.rectangle(_BOUNDING_BOXES[0], fill=_RED_HEX) dct.rectangle(_BOUNDING_BOXES[1], fill=_GREEN_HEX) dct.rectangle(_BOUNDING_BOXES[2], fill=_YELLOW_HEX) dct.rectangle(_BOUNDING_BOXES[3], fill=_BLUE_HEX) # Draw basic grid. for row in range(1, _NUM_ROWS + 2): # horizontal grid lines. line_coordinates = [(_PIXELS_PER_SQ, _PIXELS_PER_SQ * row), (_PIXELS_PER_SQ * (_NUM_ROWS + 1), _PIXELS_PER_SQ * row)] dct.line(line_coordinates, fill="black", width=_LINE_WIDTH_THIN) for col in range(1, _NUM_COLUMNS + 2): # vertical grid lines. line_coordinates = [(_PIXELS_PER_SQ * col, _PIXELS_PER_SQ), (_PIXELS_PER_SQ * col, _PIXELS_PER_SQ * (_NUM_ROWS + 1))] dct.line(line_coordinates, fill="black", width=_LINE_WIDTH_THIN) # Draw barriers. dct.rectangle( _BORDER, # Grid perimeter. outline="black", width=_LINE_WIDTH_THICK) def get_barrier_coordinates(x, y): """Returns bounding box for barrier (length two down from input).""" return [(x, y), (x, y + 2 * _PIXELS_PER_SQ)] # Top barrier, bottom left barrier, bottom right barrier. dct.line( get_barrier_coordinates(3 * _PIXELS_PER_SQ, _PIXELS_PER_SQ), fill="black", width=_LINE_WIDTH_THICK) dct.line( get_barrier_coordinates(2 * _PIXELS_PER_SQ, 4 * _PIXELS_PER_SQ), fill="black", width=_LINE_WIDTH_THICK) dct.line( get_barrier_coordinates(4 * _PIXELS_PER_SQ, 4 * _PIXELS_PER_SQ), fill="black", width=_LINE_WIDTH_THICK) # Draw passenger location. if self._state.passenger_loc in range(4): taxi_color = _EMPTY_TAXI_HEX dct.rectangle( _BOUNDING_BOXES[self._state.passenger_loc], outline=_PASS_LOC_HEX, width=_LINE_WIDTH_THICK) else: taxi_color = _PASS_LOC_HEX # Draw taxi. def get_circle_coordinates(x, y): return [((x + 1) * _PIXELS_PER_SQ + _OFFSET, (y + 1) * _PIXELS_PER_SQ + _OFFSET), ((x + 2) * _PIXELS_PER_SQ - _OFFSET, (y + 2) * _PIXELS_PER_SQ - _OFFSET)] dct.ellipse( get_circle_coordinates(self._state.taxi_x, self._state.taxi_y), fill=taxi_color) # Draw self._state.destination location. dct.rectangle( _BOUNDING_BOXES[self._state.destination], outline=_DEST_HEX, width=_LINE_WIDTH_THICK) return np.asarray(image, dtype=np.uint8)
csuite-main
csuite/environments/taxi.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for DancingCatch.""" from absl.testing import absltest from absl.testing import parameterized from csuite.environments import dancing_catch class DancingCatchTest(parameterized.TestCase): def test_environment_setup(self): """Tests environment initialization.""" env = dancing_catch.DancingCatch() self.assertIsNotNone(env) def test_start(self): """Tests environment start.""" env = dancing_catch.DancingCatch() params = env.get_config() with self.subTest(name='step_without_start'): # Calling step before start should raise an error. with self.assertRaises(RuntimeError): env.step(dancing_catch.Action.LEFT) with self.subTest(name='start_state'): start_obs = env.start() state = env.get_state() # Paddle should be positioned at the bottom of the board. self.assertEqual(state.paddle_y, params.rows - 1) paddle_idx = state.paddle_y * params.columns + state.paddle_x self.assertEqual(start_obs[paddle_idx], 1) # First ball should be positioned at the top of the board. ball_x = state.balls[0][0] ball_y = state.balls[0][1] self.assertEqual(ball_y, 0) ball_idx = ball_y * params.columns + ball_x self.assertEqual(start_obs[ball_idx], 1) def test_invalid_state(self): """Tests setting environment state with invalid fields.""" env = dancing_catch.DancingCatch() env.start() with self.subTest(name='paddle_out_of_range'): new_state = env.get_state() new_state.paddle_x = 5 with self.assertRaises(ValueError): env.set_state(new_state) with self.subTest(name='balls_out_of_range'): new_state = env.get_state() new_state.balls = [(0, -1)] with self.assertRaises(ValueError): env.set_state(new_state) @parameterized.parameters((0, 0, 1), (2, 1, 3), (4, 3, 4)) def test_one_step(self, paddle_x, expected_left_x, expected_right_x): """Tests one environment step given the x-position of the paddle.""" env = dancing_catch.DancingCatch() env.start() with self.subTest(name='invalid_action'): with self.assertRaises(ValueError): env.step(3) with self.subTest(name='move_left_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(dancing_catch.Action.LEFT) state = env.get_state() # Paddle x-position should have moved left by 1 unless at the edge. self.assertEqual(state.paddle_x, expected_left_x) with self.subTest(name='move_right_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(dancing_catch.Action.RIGHT) state = env.get_state() # Paddle x-position should have moved right by 1 unless at the edge. self.assertEqual(state.paddle_x, expected_right_x) with self.subTest(name='stay_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(dancing_catch.Action.STAY) state = env.get_state() self.assertEqual(state.paddle_x, paddle_x) if __name__ == '__main__': absltest.main()
csuite-main
csuite/environments/dancing_catch_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for catch.""" from absl.testing import absltest from absl.testing import parameterized from csuite.environments import catch class CatchTest(parameterized.TestCase): def test_environment_setup(self): """Tests environment initialization.""" env = catch.Catch() self.assertIsNotNone(env) def test_start(self): """Tests environment start.""" env = catch.Catch() params = env.get_config() with self.subTest(name='step_without_start'): # Calling step before start should raise an error. with self.assertRaises(RuntimeError): env.step(catch.Action.LEFT) with self.subTest(name='start_state'): start_obs = env.start() state = env.get_state() # Paddle should be positioned at the bottom of the board. self.assertEqual(state.paddle_y, params.rows - 1) self.assertEqual(start_obs[state.paddle_y, state.paddle_x], 1) # First ball should be positioned at the top of the board. ball_x = state.balls[0][0] ball_y = state.balls[0][1] self.assertEqual(ball_y, 0) self.assertEqual(start_obs[ball_y, ball_x], 1) def test_invalid_state(self): """Tests setting environment state with invalid fields.""" env = catch.Catch() env.start() with self.subTest(name='paddle_out_of_range'): new_state = env.get_state() new_state.paddle_x = 5 with self.assertRaises(ValueError): env.set_state(new_state) with self.subTest(name='balls_out_of_range'): new_state = env.get_state() new_state.balls = [(0, -1)] with self.assertRaises(ValueError): env.set_state(new_state) @parameterized.parameters((0, 0, 1), (2, 1, 3), (4, 3, 4)) def test_one_step(self, paddle_x, expected_left_x, expected_right_x): """Tests one environment step given the x-position of the paddle.""" env = catch.Catch() env.start() with self.subTest(name='invalid_action'): with self.assertRaises(ValueError): env.step(3) with self.subTest(name='move_left_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(catch.Action.LEFT) state = env.get_state() # Paddle x-position should have moved left by 1 unless at the edge. self.assertEqual(state.paddle_x, expected_left_x) with self.subTest(name='move_right_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(catch.Action.RIGHT) state = env.get_state() # Paddle x-position should have moved right by 1 unless at the edge. self.assertEqual(state.paddle_x, expected_right_x) with self.subTest(name='stay_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(catch.Action.STAY) state = env.get_state() self.assertEqual(state.paddle_x, paddle_x) def test_ball_hitting_bottom(self): """Tests environment updates when a ball hits the bottom of board.""" env = catch.Catch() env.start() params = env.get_config() cur_state = env.get_state() with self.subTest(name='no_collision_with_paddle'): # Set environment state to immediately before ball falls to the bottom. cur_state.paddle_x = 0 cur_state.paddle_y = params.rows - 1 cur_state.balls = [(2, params.rows - 2)] env.set_state(cur_state) _, reward = env.step(catch.Action.STAY) # Reward returned should equal -1. self.assertEqual(reward, -1) with self.subTest(name='collision_with_paddle'): # Set environment state to immediately before ball falls to the bottom. cur_state.paddle_x = 2 cur_state.paddle_y = params.rows - 1 cur_state.balls = [(2, params.rows - 2)] env.set_state(cur_state) _, reward = env.step(catch.Action.STAY) # Reward returned should equal 1. self.assertEqual(reward, 1) def test_catching_one_ball_from_start(self): """Test running from environment start for the duration of one ball falling.""" env = catch.Catch() env.start() params = env.get_config() cur_state = env.get_state() # Set environment state such that ball and paddle are horizontally centered # and the ball is at the top of the board. cur_state.paddle_x = 2 cur_state.paddle_y = params.rows - 1 cur_state.balls = [(2, 0)] env.set_state(cur_state) # For eight steps, alternate between moving left and right. for _ in range(4): # Here reward should equal 0. _, reward = env.step(catch.Action.RIGHT) self.assertEqual(reward, 0) _, reward = env.step(catch.Action.LEFT) self.assertEqual(reward, 0) # For the last step, choose to stay - ball should fall on paddle # and reward should equal 1. _, reward = env.step(catch.Action.STAY) self.assertEqual(reward, 1) def test_catching_two_balls_from_start(self): """Test running environment for the duration of two balls falling.""" env = catch.Catch() env.start() params = env.get_config() cur_state = env.get_state() # Set environment state such that there are two balls at the top and the # second row of the board, and paddle is horizontally centered. cur_state.paddle_x = 2 cur_state.paddle_y = params.rows - 1 cur_state.balls = [(0, 1), (2, 0)] env.set_state(cur_state) # For eight steps, repeatedly move left - ball in second row should fall on # paddle. for _ in range(7): # Here reward should equal 0. _, reward = env.step(catch.Action.LEFT) self.assertEqual(reward, 0) _, reward = env.step(catch.Action.LEFT) self.assertEqual(reward, 1) # Now move right - the second ball should reach the bottom of the board # and the paddle should not catch it. _, reward = env.step(catch.Action.RIGHT) self.assertEqual(reward, -1) if __name__ == '__main__': absltest.main()
csuite-main
csuite/environments/catch_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for access_control.""" from absl.testing import absltest from absl.testing import parameterized from csuite.environments import access_control class AccessControlTest(parameterized.TestCase): def test_environment_setup(self): """Tests environment initialization.""" access_control.AccessControl() def test_start(self): """Tests environment start.""" env = access_control.AccessControl() params = env.get_config() with self.subTest(name='step_without_start'): # Calling step before start should raise an error. with self.assertRaises(RuntimeError): env.step(access_control.Action.REJECT) with self.subTest(name='start_state'): _ = env.start() state = env.get_state() self.assertEqual(state.num_busy_servers, 0) self.assertIn(state.incoming_priority, params.priorities) def test_invalid_state(self): """Tests setting environment state with invalid fields.""" env = access_control.AccessControl() _ = env.start() cur_state = env.get_state() with self.subTest(name='invalid_state'): cur_state.num_busy_servers = 5 cur_state.incoming_priority = -1 with self.assertRaises(ValueError): env.set_state(cur_state) with self.subTest(name='invalid_priority'): cur_state.num_busy_servers = -1 cur_state.incoming_priority = 8 with self.assertRaises(ValueError): env.set_state(cur_state) @parameterized.parameters(0, 1, 9, 10) def test_one_step(self, new_num_busy_servers): """Tests environment step.""" env = access_control.AccessControl() _ = env.start() params = env.get_config() with self.subTest(name='invalid_action'): with self.assertRaises(ValueError): env.step(5) with self.subTest(name='reject_step'): # Change the number of busy servers in the environment state. current_state = env.get_state() current_state.num_busy_servers = new_num_busy_servers env.set_state(current_state) next_obs, reward = env.step(access_control.Action.REJECT) state = env.get_state() # Next observation should give a valid state index, reward is zero, and # number of busy servers has not increased. self.assertIn(next_obs, range(env.num_states)) self.assertEqual(reward, 0) self.assertLessEqual(state.num_busy_servers, new_num_busy_servers) with self.subTest(name='accept_step'): # Change current state to new number of busy servers. current_state = env.get_state() current_state.num_busy_servers = new_num_busy_servers env.set_state(current_state) next_obs, reward = env.step(access_control.Action.ACCEPT) state = env.get_state() if new_num_busy_servers == params.num_servers: # all servers busy. # Reward is zero even if agent tries accepting, and number of busy # servers does not increase over the total available. self.assertEqual(reward, 0) self.assertLessEqual(state.num_busy_servers, new_num_busy_servers) else: # Reward is incoming priority, and the number of busy servers can # increase by one. self.assertIn(reward, params.priorities) self.assertLessEqual(state.num_busy_servers, new_num_busy_servers + 1) def test_runs_from_start(self): """Creates an environment and runs for 10 steps.""" env = access_control.AccessControl() _ = env.start() for _ in range(10): _, _ = env.step(access_control.Action.ACCEPT) if __name__ == '__main__': absltest.main()
csuite-main
csuite/environments/access_control_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for pendulum.""" from absl.testing import absltest from csuite.environments import pendulum class PendulumTest(absltest.TestCase): def test_environment_setup(self): """Tests environment initialization.""" env = pendulum.Pendulum() self.assertIsNotNone(env) def test_start(self): """Tests environment start.""" env = pendulum.Pendulum() with self.subTest(name='step_without_start'): # Calling step before start should raise an error. with self.assertRaises(RuntimeError): env.step(pendulum.Action.NEGATIVE) with self.subTest(name='start_state'): start_obs = env.start() # Initial cosine of the angle should be 1. # Initial sine of the angle and initial velocity should be 0. self.assertEqual(start_obs[0], 1.) self.assertEqual(start_obs[1], 0.) self.assertEqual(start_obs[2], 0.) def test_one_step(self): """Tests one environment step.""" env = pendulum.Pendulum() env.start() _, reward = env.step(pendulum.Action.NEGATIVE) self.assertEqual(reward, 0.) _, reward = env.step(pendulum.Action.POSITIVE) self.assertEqual(reward, 0.) _, reward = env.step(pendulum.Action.STAY) self.assertEqual(reward, 0.) def test_setting_state(self): """Tests setting environment state and solver.""" env = pendulum.Pendulum() old_obs = env.start() # Take two steps adding +1 torque, then set state to downwards position. for _ in range(2): old_obs, _ = env.step(pendulum.Action.POSITIVE) new_state = pendulum.State(angle=0., velocity=0.) new_obs = env.set_state(new_state) for _ in range(2): new_obs, _ = env.step(pendulum.Action.POSITIVE) # If the solver was properly updated, the two observations are the same. self.assertLessEqual(abs(new_obs[0]), old_obs[0]) self.assertLessEqual(abs(new_obs[1]), old_obs[1]) self.assertLessEqual(abs(new_obs[2]), old_obs[2]) if __name__ == '__main__': absltest.main()
csuite-main
csuite/environments/pendulum_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for WindyCatch.""" from absl.testing import absltest from absl.testing import parameterized from csuite.environments import windy_catch class WindyCatchTest(parameterized.TestCase): def test_environment_setup(self): """Tests environment initialization.""" env = windy_catch.WindyCatch() self.assertIsNotNone(env) def test_start(self): """Tests environment start.""" env = windy_catch.WindyCatch() params = env.get_config() with self.subTest(name='step_without_start'): # Calling step before start should raise an error. with self.assertRaises(RuntimeError): env.step(windy_catch.Action.LEFT) with self.subTest(name='start_state'): start_obs = env.start() state = env.get_state() # Paddle should be positioned at the bottom of the board. self.assertEqual(state.paddle_y, params.rows - 1) paddle_idx = state.paddle_y * params.columns + state.paddle_x self.assertEqual(start_obs[paddle_idx], 1) # First ball should be positioned at the top of the board. ball_x = state.balls[0][0] ball_y = state.balls[0][1] self.assertEqual(ball_y, 0) ball_idx = ball_y * params.columns + ball_x self.assertEqual(start_obs[ball_idx], 1) def test_invalid_state(self): """Tests setting environment state with invalid fields.""" env = windy_catch.WindyCatch() env.start() with self.subTest(name='paddle_out_of_range'): new_state = env.get_state() new_state.paddle_x = 5 with self.assertRaises(ValueError): env.set_state(new_state) with self.subTest(name='balls_out_of_range'): new_state = env.get_state() new_state.balls = [(0, -1)] with self.assertRaises(ValueError): env.set_state(new_state) @parameterized.parameters((0, 0, 1), (2, 1, 3), (4, 3, 4)) def test_one_step(self, paddle_x, expected_left_x, expected_right_x): """Tests one environment step given the x-position of the paddle.""" env = windy_catch.WindyCatch() env.start() with self.subTest(name='invalid_action'): with self.assertRaises(ValueError): env.step(3) with self.subTest(name='move_left_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(windy_catch.Action.LEFT) state = env.get_state() # Paddle x-position should have moved left by 1 unless at the edge. self.assertEqual(state.paddle_x, expected_left_x) with self.subTest(name='move_right_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(windy_catch.Action.RIGHT) state = env.get_state() # Paddle x-position should have moved right by 1 unless at the edge. self.assertEqual(state.paddle_x, expected_right_x) with self.subTest(name='stay_step'): current_state = env.get_state() current_state.paddle_x = paddle_x env.set_state(current_state) env.step(windy_catch.Action.STAY) state = env.get_state() self.assertEqual(state.paddle_x, paddle_x) def test_wind(self): """Tests the wind.""" env = windy_catch.WindyCatch(spawn_probability=0.0) env.start() with self.subTest(name='wind_stay'): state = env.get_state() state.balls = [(0, 0), (2, 0), (4, 0)] state.wind_direction = [True, False, False] env.set_state(state) env.step(windy_catch.Action.STAY) b0, b1, b2 = env.get_state().balls self.assertEqual(b0[0], 0) self.assertEqual(b0[1], 1) self.assertEqual(b1[0], 2) self.assertEqual(b1[1], 1) self.assertEqual(b2[0], 4) self.assertEqual(b2[1], 1) with self.subTest(name='wind_left'): state = env.get_state() state.balls = [(0, 0), (2, 0), (4, 0)] state.wind_direction = [False, True, False] env.set_state(state) env.step(windy_catch.Action.STAY) b0, b1, b2 = env.get_state().balls self.assertEqual(b0[0], 4) self.assertEqual(b0[1], 1) self.assertEqual(b1[0], 1) self.assertEqual(b1[1], 1) self.assertEqual(b2[0], 3) self.assertEqual(b2[1], 1) with self.subTest(name='wind_right'): state = env.get_state() state.balls = [(0, 0), (2, 0), (4, 0)] state.wind_direction = [False, False, True] env.set_state(state) env.step(windy_catch.Action.STAY) b0, b1, b2 = env.get_state().balls self.assertEqual(b0[0], 1) self.assertEqual(b0[1], 1) self.assertEqual(b1[0], 3) self.assertEqual(b1[1], 1) self.assertEqual(b2[0], 0) self.assertEqual(b2[1], 1) if __name__ == '__main__': absltest.main()
csuite-main
csuite/environments/windy_catch_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Common utility functions.""" import numpy as np def binary_board_to_rgb(board: np.ndarray) -> np.ndarray: """Converts a binary 2D array to an rgb array.""" board = board.astype(np.uint8) * 255 board = np.expand_dims(board, -1) board = np.tile(board, (1, 1, 3)) return board
csuite-main
csuite/environments/common.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of a continuing Catch environment. Environment description can be found in the `Catch` environment class. """ import copy import dataclasses import enum from typing import Optional from csuite.environments import base from csuite.environments import common from dm_env import specs import numpy as np # Error messages. _INVALID_ACTION = "Invalid action: expected 0, 1, or 2 but received {action}." _INVALID_PADDLE_POS = ("Invalid state: paddle should be positioned at the" " bottom of the board.") _INVALID_BALLS_RANGE = ( "Invalid state: positions of balls and paddle not in expected" " row range [0, {rows}) and column range [0, {columns}).") # Default environment variables. _ROWS = 10 _COLUMNS = 5 _SPAWN_PROBABILITY = 0.1 class Action(enum.IntEnum): LEFT = 0 STAY = 1 RIGHT = 2 @property def dx(self): """Maps LEFT to -1, STAY to 0 and RIGHT to 1.""" return self.value - 1 @dataclasses.dataclass class Params: """Parameters of a continuing Catch instance. Attributes: rows: Integer number of rows. columns: Integer number of columns. spawn_probability: Probability of a new ball spawning. """ rows: int columns: int spawn_probability: float @dataclasses.dataclass class State: """State of a continuing Catch instance. Attributes: paddle_x: An integer denoting the x-coordinate of the paddle. paddle_y: An integer denoting the y-coordinate of the paddle balls: A list of (x, y) coordinates representing the present balls. rng: Internal NumPy pseudo-random number generator, included here for reproducibility purposes. """ paddle_x: int paddle_y: int balls: list[tuple[int, int]] rng: np.random.Generator class Catch(base.Environment): """A continuing Catch environment. The agent must control a breakout-like paddle to catch as many falling balls as possible. Falling balls move strictly down in their column. In this continuing version, a new ball can spawn at the top with a low probability at each timestep. A new ball will always spawn when a ball falls to the bottom of the board. At most one ball is added at each timestep. A reward of +1 is given when the paddle successfully catches a ball and a reward of -1 is given when the paddle fails to catch a ball. The reward is 0 otherwise. There are three discrete actions: move left, move right, and stay. The observation is a binary array with shape (rows, columns) with entry one if it contains the paddle or a ball, and zero otherwise. """ def __init__(self, rows=_ROWS, columns=_COLUMNS, spawn_probability=_SPAWN_PROBABILITY, seed=None): """Initializes a continuing Catch environment. Args: rows: A positive integer denoting the number of rows. columns: A positive integer denoting the number of columns. spawn_probability: Float giving the probability of a new ball appearing. seed: Seed for the internal random number generator. """ self._seed = seed self._params = Params( rows=rows, columns=columns, spawn_probability=spawn_probability) self._state = None def start(self, seed: Optional[int] = None): """Initializes the environment and returns an initial observation.""" # The initial state has one ball appearing in a random column at the top, # and the paddle centered at the bottom. rng = np.random.default_rng(self._seed if seed is None else seed) self._state = State( paddle_x=self._params.columns // 2, paddle_y=self._params.rows - 1, balls=[(rng.integers(self._params.columns), 0)], rng=rng, ) return self._get_observation() @property def started(self): """True if the environment has been started, False otherwise.""" # An unspecified state implies that the environment needs to be started. return self._state is not None def step(self, action): """Updates the environment state and returns an observation and reward. Args: action: An integer equalling 0, 1, or 2 indicating whether to move the paddle left, stay, or move the paddle right respectively. Returns: A tuple of type (int, float) giving the next observation and the reward. Raises: RuntimeError: If state has not yet been initialized by `start`. """ # Check if state has been initialized. if not self.started: raise RuntimeError(base.STEP_WITHOUT_START_ERR) # Check if input action is valid. if action not in [Action.LEFT, Action.STAY, Action.RIGHT]: raise ValueError(_INVALID_ACTION.format(action=action)) # Move the paddle. self._state.paddle_x = np.clip( self._state.paddle_x + Action(action).dx, 0, self._params.columns - 1) # Move all balls down by one unit. self._state.balls = [(x, y + 1) for x, y in self._state.balls] # Since at most one ball is added at each timestep, at most one ball # can be at the bottom of the board, and must be the 'oldest' ball. reward = 0. if self._state.balls and self._state.balls[0][1] == self._state.paddle_y: if self._state.balls[0][0] == self._state.paddle_x: reward = 1. else: reward = -1. # Remove ball from list. self._state.balls = self._state.balls[1:] # Add new ball with given probability. if self._state.rng.random() < self._params.spawn_probability: self._state.balls.append( (self._state.rng.integers(self._params.columns), 0)) return self._get_observation(), reward def _get_observation(self) -> np.ndarray: """Converts internal environment state to an array observation. Returns: A binary array of size (rows, columns) with entry 1 if it contains either a ball or a paddle, and entry 0 if the cell is empty. """ board = np.zeros((_ROWS, _COLUMNS), dtype=int) board.fill(0) board[self._state.paddle_y, self._state.paddle_x] = 1 for x, y in self._state.balls: board[y, x] = 1 return board def observation_spec(self): """Describes the observation specs of the environment.""" return specs.BoundedArray( shape=(self._params.rows, self._params.columns), dtype=int, minimum=0, maximum=1, name="board") def action_spec(self): """Describes the action specs of the environment.""" return specs.DiscreteArray(num_values=3, dtype=int, name="action") def get_state(self): """Returns a copy of the current environment state.""" return copy.deepcopy(self._state) if self._state is not None else None def set_state(self, state): """Sets environment state to state provided. Args: state: A State object which overrides the current state. """ # Check that input state values are valid. if not (0 <= state.paddle_x < self._params.columns and state.paddle_y == self._params.rows - 1): raise ValueError(_INVALID_PADDLE_POS) for x, y in state.balls: if not (0 <= x < self._params.columns and 0 <= y < self._params.rows): raise ValueError( _INVALID_BALLS_RANGE.format( rows=self._params.rows, columns=self._params.columns)) self._state = copy.deepcopy(state) def get_config(self): """Returns a copy of the environment configuration.""" return copy.deepcopy(self._params) def render(self) -> np.ndarray: return common.binary_board_to_rgb(self._get_observation())
csuite-main
csuite/environments/catch.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for taxi.""" from absl.testing import absltest from absl.testing import parameterized from csuite.environments import taxi class TaxiTest(parameterized.TestCase): def test_environment_setup(self): """Tests environment initialization.""" env = taxi.Taxi() self.assertIsNotNone(env) def test_start(self): """Tests environment start.""" env = taxi.Taxi() with self.subTest(name='step_without_start'): # Calling step before start should raise an error. with self.assertRaises(RuntimeError): env.step(taxi.Action.NORTH) with self.subTest(name='start_state'): _ = env.start() state = env.get_state() self.assertIn(state.taxi_x, range(5)) self.assertIn(state.taxi_y, range(5)) # Original passenger location should not be in the taxi. self.assertIn(state.passenger_loc, range(4)) self.assertIn(state.destination, range(4)) @parameterized.parameters( (2, 2, taxi.Action.NORTH, True), (2, 0, taxi.Action.NORTH, False), (2, 2, taxi.Action.SOUTH, True), (2, 4, taxi.Action.SOUTH, False), (1, 4, taxi.Action.EAST, True), (1, 1, taxi.Action.EAST, False), (2, 4, taxi.Action.WEST, True), (2, 1, taxi.Action.WEST, False)) def test_one_movement_step(self, x, y, action, can_move): """Tests one step with a movement action (North, East, South, West).""" env = taxi.Taxi() env.start() cur_state = env.get_state() # Create new state from input parameters and set environment to this state. cur_state.taxi_x = x cur_state.taxi_y = y cur_state.passenger_loc = 0 cur_state.destination = 2 env.set_state(cur_state) # Take movement step provided. env.step(action) next_state = env.get_state() if can_move: self.assertEqual(next_state.taxi_x, cur_state.taxi_x + taxi.Action(action).dx) self.assertEqual(next_state.taxi_y, cur_state.taxi_y + taxi.Action(action).dy) else: self.assertEqual(next_state.taxi_x, cur_state.taxi_x) self.assertEqual(next_state.taxi_y, cur_state.taxi_y) @parameterized.parameters((0, 0, 0, 2, taxi.Action.PICKUP, True), (0, 1, 0, 2, taxi.Action.PICKUP, False), (0, 1, 4, 2, taxi.Action.PICKUP, False), (3, 4, 4, 3, taxi.Action.DROPOFF, True), (2, 4, 4, 3, taxi.Action.DROPOFF, False), (3, 4, 3, 3, taxi.Action.DROPOFF, False)) def test_pickup_dropoff(self, x, y, pass_loc, dest, action, is_success): """Tests the two passenger actions (pickup and dropoff).""" env = taxi.Taxi() env.start() cur_state = env.get_state() # Create new state from input parameters and set environment to this state. cur_state.taxi_x = x cur_state.taxi_y = y cur_state.passenger_loc = pass_loc cur_state.destination = dest env.set_state(cur_state) _, reward = env.step(action) # Check correct reward: for successful dropoffs, reward is 20. For # successful pickups, reward is 0. For incorrect actions, reward is -10. if is_success and action == taxi.Action.DROPOFF: self.assertEqual(reward, 20) elif is_success: self.assertEqual(reward, 0) else: self.assertEqual(reward, -10) if is_success and action == taxi.Action.PICKUP: # Check passenger is in the taxi. next_state = env.get_state() self.assertEqual(next_state.passenger_loc, 4) def test_runs_from_start(self): """Tests running a full passenger pickup and dropoff sequence.""" env = taxi.Taxi() env.start() cur_state = env.get_state() # Set state to have passenger and taxi on the red square, and destination # on the blue square. cur_state.taxi_x = 0 cur_state.taxi_y = 0 cur_state.passenger_loc = 0 cur_state.destination = 3 env.set_state(cur_state) # Pick up the passenger. env.step(taxi.Action.PICKUP) for _ in range(2): _, reward = env.step(taxi.Action.SOUTH) self.assertEqual(reward, 0) for _ in range(3): _, reward = env.step(taxi.Action.EAST) self.assertEqual(reward, 0) for _ in range(2): _, reward = env.step(taxi.Action.SOUTH) self.assertEqual(reward, 0) # Drop off the passenger. _, reward = env.step(taxi.Action.DROPOFF) self.assertEqual(reward, 20) if __name__ == '__main__': absltest.main()
csuite-main
csuite/environments/taxi_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of the tabular Access-Control environment. Environment description and details can be found in the `AccessControl` environment class. """ import copy import dataclasses import enum import itertools from typing import Optional from csuite.environments import base from csuite.environments import common from dm_env import specs import numpy as np # Default environment variables from Sutton&Barto Example 10.2. _NUM_SERVERS = 10 _FREE_PROBABILITY = 0.06 _PRIORITIES = (1, 2, 4, 8) # Error messages. _INVALID_ACTION = "Invalid action: expected 0 or 1 but received {action}." _INVALID_BUSY_SERVERS = ("Invalid state: num_busy_servers not in expected" "range [0, {}).") _INVALID_PRIORITY = ("Invalid state: incoming_priority not in expected" "range {}.") class Action(enum.IntEnum): REJECT = 0 ACCEPT = 1 @dataclasses.dataclass class Params: """Parameters of an Access-Control instance. Attributes: num_servers: A positive integer, denoting the total number of available servers. free_probability: A positive float, denoting the probability a busy server becomes free at each timestep. priorities: A list of floats, giving the possible priorities of incoming customers. """ num_servers: int free_probability: float priorities: list[float] @dataclasses.dataclass class State: """State of an Access-Control continuing environment. Let N be the number of servers. Attributes: num_busy_servers: An integer in the range [0, N] representing the number of busy servers. incoming_priority: An integer giving the priority of the incoming customer. rng: Internal NumPy pseudo-random number generator, included here for reproducibility purposes. """ num_busy_servers: int incoming_priority: int rng: np.random.RandomState class AccessControl(base.Environment): """An Access-Control continuing environment. Given access to a set of servers and an infinite queue of customers with different priorities, the agent must decide whether to accept or reject the next customer in line based on their priority and the number of free servers. There are two actions: accept or decline the incoming customer. Note that if no servers are available, the customer is declined regardless of the action selected. The observation is a single state index, enumerating the possible states (num_busy_servers, incoming_priority). The default environment follows that described in Sutton and Barto's book (Example 10.2 in the second edition). """ def __init__(self, num_servers=_NUM_SERVERS, free_probability=_FREE_PROBABILITY, priorities=_PRIORITIES, seed=None): """Initialize Access-Control environment. Args: num_servers: A positive integer, denoting the total number of available servers. free_probability: A positive float, denoting the probability a busy server becomes free at each timestep. priorities: A list of floats, giving the possible priorities of incoming customers. seed: Seed for the internal random number generator. """ self._seed = seed self._params = Params( num_servers=num_servers, free_probability=free_probability, priorities=priorities) self.num_states = ((self._params.num_servers + 1) * len(self._params.priorities)) # Populate lookup table for observations. self.lookup_table = {} for idx, state in enumerate( itertools.product( range(self._params.num_servers + 1), self._params.priorities)): self.lookup_table[state] = idx self._state = None self._last_action = -1 # Only used for visualization. def start(self, seed: Optional[int] = None): """Initializes the environment and returns an initial observation.""" rng = np.random.RandomState(self._seed if seed is None else seed) self._state = State( num_busy_servers=0, incoming_priority=rng.choice(self._params.priorities), rng=rng) return self._get_observation() @property def started(self): """True if the environment has been started, False otherwise.""" # An unspecified state implies that the environment needs to be started. return self._state is not None def step(self, action): """Updates the environment state and returns an observation and reward. Args: action: An integer equalling 0 or 1 to reject or accept the customer. Returns: A tuple of type (int, float) giving the next observation and the reward. Raises: RuntimeError: If state has not yet been initialized by `start`. ValueError: If input action has an invalid value. """ # Check if state has been initialized. if not self.started: raise RuntimeError(base.STEP_WITHOUT_START_ERR) # Check if input action is valid. if action not in [Action.REJECT, Action.ACCEPT]: raise ValueError(_INVALID_ACTION.format(action=action)) self._last_action = action reward = 0 # If customer is accepted, ensure there are enough free servers. if (action == Action.ACCEPT and self._state.num_busy_servers < self._params.num_servers): reward = self._state.incoming_priority self._state.num_busy_servers += 1 new_priority = self._state.rng.choice(self._params.priorities) # Update internal state by freeing busy servers with a given probability. num_busy_servers = self._state.num_busy_servers num_new_free_servers = self._state.rng.binomial( num_busy_servers, p=self._params.free_probability) self._state.num_busy_servers = num_busy_servers - num_new_free_servers self._state.incoming_priority = new_priority return self._get_observation(), reward def _get_observation(self): """Converts internal state to an index uniquely identifying the state. Returns: An integer denoting the current state's index according to the enumeration of the state space stored by the environment's lookup table. """ state_key = (self._state.num_busy_servers, self._state.incoming_priority) return self.lookup_table[state_key] def observation_spec(self): """Describes the observation specs of the environment.""" return specs.DiscreteArray(self.num_states, dtype=int, name="observation") def action_spec(self): """Describes the action specs of the environment.""" return specs.DiscreteArray(2, dtype=int, name="action") def get_state(self): """Returns a copy of the current environment state.""" return copy.deepcopy(self._state) if self._state is not None else None def set_state(self, state): """Sets environment state to state provided. Args: state: A State object which overrides the current state. """ # Check that input state values are valid. if state.num_busy_servers not in range(self._params.num_servers + 1): raise ValueError(_INVALID_BUSY_SERVERS.format(self._params.num_servers)) elif state.incoming_priority not in self._params.priorities: raise ValueError(_INVALID_PRIORITY.format(self._params.priorities)) self._state = copy.deepcopy(state) def get_config(self): """Returns a copy of the environment configuration.""" return copy.deepcopy(self._params) def render(self): board = np.ones((len(_PRIORITIES), _NUM_SERVERS + 1), dtype=np.uint8) priority = _PRIORITIES.index(self._state.incoming_priority) busy_num = self._state.num_busy_servers board[priority, busy_num] = 0 rgb_array = common.binary_board_to_rgb(board) if self._last_action == Action.ACCEPT: rgb_array[priority, busy_num, 1] = 1 # Green. elif self._last_action == Action.REJECT: rgb_array[priority, busy_num, 0] = 1 # Red. else: # Will remain black. assert self._last_action == -1, "Only other possible value." return rgb_array
csuite-main
csuite/environments/access_control.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of a continuing Pendulum environment with discrete actions. Environment description can be found in the `Pendulum' Environment class. """ import copy import dataclasses import enum from typing import Any, Callable, Optional from csuite.environments import base from dm_env import specs import numpy as np from PIL import Image from PIL import ImageDraw # Default environment variables. _NUM_ACTIONS = 3 # Size of action space discretization. _FRICTION = 0.1 _GRAVITY = 9.81 _SIMULATION_STEP_SIZE = 0.05 _ACT_STEP_PERIOD = 4 _MAX_SPEED = np.inf _REWARD_ANGLE = 30 # Converter for degrees to radians. _RADIAN_MULTIPLIER = np.pi / 180 # Error messages. _INVALID_ANGLE = ("Invalid state: expected angle to be in range [0, 2pi].") # Variables for pixel visualization of the environment. _IMAGE_SIZE = 256 _CENTER_IMAGE = _IMAGE_SIZE // 2 - 1 _SCALE_FACTOR = 0.75 _PENDULUM_WIDTH = _IMAGE_SIZE // 64 _TIP_RADIUS = _IMAGE_SIZE // 24 _LIGHT_GREEN = "#d4ffd6" # For shading the reward region. _ARROW_WIDTH = _IMAGE_SIZE // 44 _TORQUE_ANGLE = 20 class Action(enum.IntEnum): """Actions for the Pendulum environment. There are three actions: 0: Apply -1 torque. 1: Do nothing. 2: Apply +1 torque. """ NEGATIVE, STAY, POSITIVE = range(3) @property def tau(self): """Maps NEGATIVE to -1, STAY to 0, and POSITIVE to 1.""" return self.value - 1 @dataclasses.dataclass class State: """State of a continuing pendulum environment. Attributes: angle: a float in [0, 2*pi] giving the angle in radians of the pendulum. An angle of 0 indicates that the pendulum is hanging downwards. velocity: a float in [-max_speed, max_speed] giving the angular velocity. """ angle: float velocity: float @dataclasses.dataclass class Params: """Parameters of a continuing pendulum environment.""" start_state_fn: Callable[[], State] friction: float gravity: float simulation_step_size: float act_step_period: int max_speed: float reward_fn: Callable[..., float] # Default start state and reward function. def start_from_bottom(): """Returns default start state with pendulum hanging vertically downwards.""" return State(angle=0., velocity=0.) def sparse_reward(state: State, unused_torque: Any, unused_step_size: Any, reward_angle: int = _REWARD_ANGLE) -> float: """Returns a sparse reward for the continuing pendulum problem. Args: state: A State object containing the current angle and velocity. reward_angle: An integer denoting the angle from vertical, in degrees, where the pendulum is rewarding. Returns: A reward of 1 if the angle of the pendulum is within the range, and a reward of 0 otherwise. """ reward_angle_radians = reward_angle * _RADIAN_MULTIPLIER if (np.pi - reward_angle_radians < state.angle < np.pi + reward_angle_radians): return 1. else: return 0. def _alias_angle(angle: float) -> float: """Returns an angle between 0 and 2*pi.""" return angle % (2 * np.pi) class Pendulum(base.Environment): """A continuing pendulum environment. Starting from a hanging down position, swing up a single pendulum to the inverted position and maintain the pendulum in this position. Most of the default arguments model the pendulum described in "A Comparison of Direct and Model-Based Reinforcement Learning" (Atkeson & Santamaria, 1997). The key differences are the following: 1) This environment is now continuing, i.e. the "trial length" is infinite. 2) Instead of directly returning the angle of the pendulum in the observation, this environment returns the cosine and sine of the angle. 3) There are only three discrete actions (apply a torque of -1, apply a torque of +1, and apply no-op) as opposed to a continuous torque value. 4) The default reward function is implemented as a sparse reward, i.e. there is only a reward of 1 attained when the angle is in the region specified by the interval (pi - reward_angle, pi + reward_angle). The pendulum's motion is described by the equation ``` theta'' = tau - mu * theta' - g * sin(theta), ``` where theta is the angle, mu is the friction coefficient, tau is the torque, and g is the acceleration due to gravity. Observations are NumPy arrays of the form [cos(angle), sin(angle), velocity] where angle is in [0, 2*pi] and velocity is in [-max_speed, max_speed]. """ def __init__(self, start_state_fn=start_from_bottom, friction=_FRICTION, gravity=_GRAVITY, simulation_step_size=_SIMULATION_STEP_SIZE, act_step_period=_ACT_STEP_PERIOD, max_speed=_MAX_SPEED, reward_fn=sparse_reward, seed=None): """Initializes a new pendulum environment. Args: start_state_fn: A callable which returns a `State` object giving the initial state. friction: A positive float giving the coefficient of friction. gravity: A float giving the acceleration due to gravity. simulation_step_size: The step size (in seconds) of the simulation. act_step_period: An integer giving the number of simulation steps for each action input. max_speed: A float giving the maximum speed (in radians/second) allowed in the simulation. reward_fn: A callable which returns a float reward given current state. seed: Seed for the internal random number generator. """ del seed self._params = Params( start_state_fn=start_state_fn, friction=friction, gravity=gravity, simulation_step_size=simulation_step_size, act_step_period=act_step_period, max_speed=max_speed, reward_fn=reward_fn) self._state = None self._torque = 0 def start(self, seed: Optional[int] = None): """Initializes the environment and returns an initial observation.""" del seed self._state = self._params.start_state_fn() return np.array((np.cos(self._state.angle), np.sin(self._state.angle), self._state.velocity), dtype=np.float32) @property def started(self): """True if the environment has been started, False otherwise.""" # An unspecified state implies that the environment needs to be started. return self._state is not None def step(self, action): """Updates the environment state and returns an observation and reward. Args: action: An integer in {0, 1, 2} indicating whether to subtract one unit of torque, do nothing, or add one unit of torque. Returns: A tuple giving the next observation in the form of a NumPy array and the reward as a float. Raises: RuntimeError: If state has not yet been initialized by `start`. """ # Check if state has been initialized. if not self.started: raise RuntimeError(base.STEP_WITHOUT_START_ERR) self._torque = Action(action).tau # Integrate over time steps to get new angle and velocity. new_angle = self._state.angle new_velocity = self._state.velocity for _ in range(self._params.act_step_period): new_velocity += ((self._torque - self._params.friction * new_velocity - self._params.gravity * np.sin(new_angle)) * self._params.simulation_step_size) new_angle += new_velocity * self._params.simulation_step_size # Ensure the angle is between 0 and 2*pi. new_angle = _alias_angle(new_angle) # Clip velocity to max_speed. new_velocity = np.clip(new_velocity, -self._params.max_speed, self._params.max_speed) self._state = State(angle=new_angle, velocity=new_velocity) return (np.array((np.cos(self._state.angle), np.sin(self._state.angle), self._state.velocity), dtype=np.float32), self._params.reward_fn(self._state, self._torque, self._params.simulation_step_size)) def observation_spec(self): """Describes the observation specs of the environment.""" return specs.BoundedArray((3,), dtype=np.float32, minimum=[-1, -1, -self._params.max_speed], maximum=[1, 1, self._params.max_speed]) def action_spec(self): """Describes the action specs of the environment.""" return specs.DiscreteArray(_NUM_ACTIONS, dtype=int, name="action") def get_state(self): """Returns a copy of the current environment state.""" return copy.deepcopy(self._state) if self._state is not None else None def set_state(self, state): """Sets environment state to state provided. Args: state: A State object which overrides the current state. Returns: A NumPy array for the observation including the angle and velocity. """ # Check that input state values are valid. if not 0 <= state.angle <= 2 * np.pi: raise ValueError(_INVALID_ANGLE) self._state = copy.deepcopy(state) return np.array((np.cos(self._state.angle), np.sin(self._state.angle), self._state.velocity), dtype=np.float32) def render(self): image = Image.new("RGB", (_IMAGE_SIZE, _IMAGE_SIZE), "white") dct = ImageDraw.Draw(image) # Get x and y positions of the pendulum tip relative to the center. x_pos = np.sin(self._state.angle) y_pos = np.cos(self._state.angle) def abs_coordinates(x, y): """Return absolute coordinates given coordinates relative to center.""" return (x * _SCALE_FACTOR * _CENTER_IMAGE + _CENTER_IMAGE, y * _SCALE_FACTOR * _CENTER_IMAGE + _CENTER_IMAGE) # Draw reward range region. boundary_x = _CENTER_IMAGE * (1 - _SCALE_FACTOR) pendulum_bounding_box = [(boundary_x, boundary_x), (_IMAGE_SIZE - boundary_x, _IMAGE_SIZE - boundary_x)] dct.pieslice( pendulum_bounding_box, start=(270 - _REWARD_ANGLE), end=(270 + _REWARD_ANGLE), fill=_LIGHT_GREEN) # Get absolute coordinates of the pendulum tip. tip_coords = abs_coordinates(x_pos, y_pos) # Draw pendulum line. dct.line([(_CENTER_IMAGE, _CENTER_IMAGE), tip_coords], fill="black", width=_PENDULUM_WIDTH) # Draw circular pendulum tip. x, y = tip_coords tip_bounding_box = [(x - _TIP_RADIUS, y - _TIP_RADIUS), (x + _TIP_RADIUS, y + _TIP_RADIUS)] dct.ellipse(tip_bounding_box, fill="red") # Draw torque arrow. if self._torque > 0: dct.arc( pendulum_bounding_box, start=360 - _TORQUE_ANGLE, end=_TORQUE_ANGLE, fill="blue", width=_ARROW_WIDTH) # Draw arrow heads. arrow_x, arrow_y = abs_coordinates( np.cos(_TORQUE_ANGLE * _RADIAN_MULTIPLIER), -np.sin(_TORQUE_ANGLE * _RADIAN_MULTIPLIER)) dct.regular_polygon((arrow_x, arrow_y, _ARROW_WIDTH * 1.5), n_sides=3, rotation=_TORQUE_ANGLE, fill="blue") elif self._torque < 0: dct.arc( pendulum_bounding_box, start=180 - _TORQUE_ANGLE, end=180 + _TORQUE_ANGLE, fill="blue", width=_ARROW_WIDTH) # Draw arrow heads. arrow_x, arrow_y = abs_coordinates( -np.cos(_TORQUE_ANGLE * _RADIAN_MULTIPLIER), -np.sin(_TORQUE_ANGLE * _RADIAN_MULTIPLIER)) dct.regular_polygon((arrow_x, arrow_y, _ARROW_WIDTH * 1.5), n_sides=3, rotation=-_TORQUE_ANGLE, fill="blue") return np.asarray(image, dtype=np.uint8)
csuite-main
csuite/environments/pendulum.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Continuing catch environment with non-stationary permutations of the observation features. Environment description can be found in the `DancingCatch` environment class. """ import copy import dataclasses import enum from typing import Optional from csuite.environments import base from csuite.environments import common from dm_env import specs import numpy as np # Error messages. _INVALID_ACTION = "Invalid action: expected 0, 1, or 2 but received {action}." _INVALID_PADDLE_POS = ("Invalid state: paddle should be positioned at the" " bottom of the board.") _INVALID_BALLS_RANGE = ( "Invalid state: positions of balls and paddle not in expected" " row range [0, {rows}) and column range [0, {columns}).") # Default environment variables. _ROWS = 10 _COLUMNS = 5 _SPAWN_PROBABILITY = 0.1 _SWAP_EVERY = 10000 class Action(enum.IntEnum): LEFT = 0 STAY = 1 RIGHT = 2 @property def dx(self): """Maps LEFT to -1, STAY to 0 and RIGHT to 1.""" return self.value - 1 @dataclasses.dataclass class Params: """Parameters of a continuing Catch instance. Attributes: rows: Integer number of rows. columns: Integer number of columns. observation_dim: Integer dimension of the observation features. spawn_probability: Probability of a new ball spawning. swap_every: Integer giving the interval at which a swap occurs. """ rows: int columns: int observation_dim: int spawn_probability: float swap_every: int @dataclasses.dataclass class State: """State of a continuing Catch instance. Attributes: paddle_x: An integer denoting the x-coordinate of the paddle. paddle_y: An integer denoting the y-coordinate of the paddle balls: A list of (x, y) coordinates representing the present balls. shuffle_idx: Indices for performing the observation shuffle as a result of the random swaps. time_since_swap: An integer denoting how many timesteps have elapsed since the last swap. rng: Internal NumPy pseudo-random number generator, included here for reproducibility purposes. """ paddle_x: int paddle_y: int balls: list[tuple[int, int]] shuffle_idx: np.ndarray time_since_swap: int rng: np.random.Generator class DancingCatch(base.Environment): """A continuing Catch environment with random swaps. This environment is the same as the continuing Catch environment, but at each timestep, there is a low probability that two entries in the observation are swapped. The observations are flattened, with entry one if the corresponding unshuffled position contains the paddle or a ball, and zero otherwise. """ def __init__(self, rows=_ROWS, columns=_COLUMNS, spawn_probability=_SPAWN_PROBABILITY, seed=None, swap_every=_SWAP_EVERY): """Initializes a continuing Catch environment. Args: rows: A positive integer denoting the number of rows. columns: A positive integer denoting the number of columns. spawn_probability: Float giving the probability of a new ball appearing. seed: Seed for the internal random number generator. swap_every: A positive integer denoting the interval at which a swap in the observation occurs. """ self._seed = seed self._params = Params( rows=rows, columns=columns, observation_dim=rows * columns, spawn_probability=spawn_probability, swap_every=swap_every) self._state = None def start(self, seed: Optional[int] = None): """Initializes the environment and returns an initial observation.""" # The initial state has one ball appearing in a random column at the top, # and the paddle centered at the bottom. rng = np.random.default_rng(self._seed if seed is None else seed) self._state = State( paddle_x=self._params.columns // 2, paddle_y=self._params.rows - 1, balls=[(rng.integers(self._params.columns), 0)], shuffle_idx=np.arange(self._params.observation_dim), time_since_swap=0, rng=rng, ) return self._get_observation() @property def started(self): """True if the environment has been started, False otherwise.""" # An unspecified state implies that the environment needs to be started. return self._state is not None def step(self, action): """Updates the environment state and returns an observation and reward. Args: action: An integer equalling 0, 1, or 2 indicating whether to move the paddle left, stay, or move the paddle right respectively. Returns: A tuple of type (int, float) giving the next observation and the reward. Raises: RuntimeError: If state has not yet been initialized by `start`. """ # Check if state has been initialized. if not self.started: raise RuntimeError(base.STEP_WITHOUT_START_ERR) # Check if input action is valid. if action not in [Action.LEFT, Action.STAY, Action.RIGHT]: raise ValueError(_INVALID_ACTION.format(action=action)) # Move the paddle. self._state.paddle_x = np.clip(self._state.paddle_x + Action(action).dx, 0, self._params.columns - 1) # Move all balls down by one unit. self._state.balls = [(x, y + 1) for x, y in self._state.balls] # Since at most one ball is added at each timestep, at most one ball # can be at the bottom of the board, and must be the 'oldest' ball. reward = 0. if self._state.balls and self._state.balls[0][1] == self._state.paddle_y: reward = 1. if self._state.balls[0][0] == self._state.paddle_x else -1. # Remove ball from list. self._state.balls = self._state.balls[1:] # Add new ball with given probability. if self._state.rng.random() < self._params.spawn_probability: self._state.balls.append( (self._state.rng.integers(self._params.columns), 0)) # Update time since last swap. self._state.time_since_swap += 1 # Update the observation permutation indices by swapping two indices, # at the given interval. if self._state.time_since_swap % self._params.swap_every == 0: idx_1, idx_2 = self._state.rng.integers( self._params.observation_dim, size=2).T self._state.shuffle_idx[[idx_1, idx_2]] = ( self._state.shuffle_idx[[idx_2, idx_1]]) self._state.time_since_swap = 0 return self._get_observation(), reward def _get_observation(self) -> np.ndarray: """Converts internal environment state to an array observation. Returns: A binary array of size (rows, columns) with entry 1 if it contains either a ball or a paddle, and entry 0 if the cell is empty. """ board = np.zeros((_ROWS, _COLUMNS), dtype=int) board.fill(0) board[self._state.paddle_y, self._state.paddle_x] = 1 for x, y in self._state.balls: board[y, x] = 1 board = board.flatten() return board[self._state.shuffle_idx] def observation_spec(self): """Describes the observation specs of the environment.""" return specs.BoundedArray( shape=(self._params.observation_dim,), dtype=int, minimum=0, maximum=1, name="board") def action_spec(self): """Describes the action specs of the environment.""" return specs.DiscreteArray(num_values=3, dtype=int, name="action") def get_state(self): """Returns a copy of the current environment state.""" return copy.deepcopy(self._state) if self._state is not None else None def set_state(self, state): """Sets environment state to state provided. Args: state: A State object which overrides the current state. """ # Check that input state values are valid. if not (0 <= state.paddle_x < self._params.columns and state.paddle_y == self._params.rows - 1): raise ValueError(_INVALID_PADDLE_POS) for x, y in state.balls: if not (0 <= x < self._params.columns and 0 <= y < self._params.rows): raise ValueError( _INVALID_BALLS_RANGE.format( rows=self._params.rows, columns=self._params.columns)) self._state = copy.deepcopy(state) def get_config(self): """Returns a copy of the environment configuration.""" return copy.deepcopy(self._params) def render(self) -> np.ndarray: board = self._get_observation().reshape(_ROWS, _COLUMNS) return common.binary_board_to_rgb(board)
csuite-main
csuite/environments/dancing_catch.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Abstract base class for csuite environments.""" import abc from typing import Any, Optional, Tuple from dm_env import specs import numpy as np # TODO(b/243715530): The base environment should implementing this check. STEP_WITHOUT_START_ERR = ("Environment state has not been initialized. `start`" " must be called before calling `step`.") class Environment(abc.ABC): """Base class for continuing environments. Observations and valid actions are described by the `specs` module in dm_env. Environment implementations should return specs as specific as possible. Each environment will specify its own environment State, Configuration, and internal random number generator. """ @abc.abstractmethod def start(self, seed: Optional[int] = None) -> Any: """Starts (or restarts) the environment and returns an observation.""" @abc.abstractmethod def step(self, action: Any) -> Tuple[Any, Any]: """Takes a step in the environment, returning an observation and reward.""" @abc.abstractmethod def observation_spec(self) -> specs.Array: """Describes the observation space of the environment. May use a subclass of `specs.Array` that specifies additional properties such as min and max bounds on the values. """ @abc.abstractmethod def action_spec(self) -> specs.Array: """Describes the valid action space of the environment. May use a subclass of `specs.Array` that specifies additional properties such as min and max bounds on the values. """ @abc.abstractmethod def get_state(self) -> Any: """Returns the environment state.""" @abc.abstractmethod def set_state(self, state: Any): """Sets the environment state.""" @abc.abstractmethod def render(self) -> np.ndarray: """Returns an rgb (uint8) numpy array to facilitate visualization. The shape of this array should be (width, height, 3), where the last dimension is for red, green, and blue. The values are in [0, 255]. """
csuite-main
csuite/environments/base.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """WindyCatch environment. Environment description can be found in the `WindyCatch` environment class. """ import copy import dataclasses import enum from typing import Optional from csuite.environments import base from csuite.environments import common from dm_env import specs import numpy as np # Error messages. _INVALID_ACTION = "Invalid action: expected 0, 1, or 2 but received {action}." _INVALID_PADDLE_POS = ("Invalid state: paddle should be positioned at the" " bottom of the board.") _INVALID_BALLS_RANGE = ( "Invalid state: positions of balls and paddle not in expected" " row range [0, {rows}) and column range [0, {columns}).") _INVALID_WIND_DIRECTION = ( "Invalid state: expected exactly one entry of wind_direction to be True.") # Default environment variables. _ROWS = 10 _COLUMNS = 5 _SPAWN_PROBABILITY = 0.1 _CHANGE_EVERY = 100000 _WIND_DELTA = [0, -1, 1] class Action(enum.IntEnum): LEFT = 0 STAY = 1 RIGHT = 2 @property def dx(self): """Maps LEFT to -1, STAY to 0 and RIGHT to 1.""" return self.value - 1 @dataclasses.dataclass class Params: """Windy catch parameters. Attributes: rows: Integer number of rows. columns: Integer number of columns. observation_dim: Integer dimension of the observation features. spawn_probability: Probability of a new ball spawning. change_every: Integer giving the interval at which direction of the wind changes. """ rows: int columns: int observation_dim: int spawn_probability: float change_every: int @dataclasses.dataclass class State: """Windy catch state. Attributes: paddle_x: An integer denoting the x-coordinate of the paddle. paddle_y: An integer denoting the y-coordinate of the paddle balls: A list of (x, y) coordinates representing the present balls. wind_direction: List of three booleans (no wind, left wind, right wind); only one is True. time_since_wind_change: An integer denoting how many timesteps have elapsed since the last change in wind direction. rng: Internal NumPy pseudo-random number generator, included here for reproducibility purposes. """ paddle_x: int paddle_y: int balls: list[tuple[int, int]] wind_direction: list[bool] time_since_wind_change: int rng: np.random.Generator class WindyCatch(base.Environment): """A windy catch enviornment. Wind moves a falling ball by a column, depending on the direction. Leftward wind moves the ball to the left, rightware wind moves the ball to the right. If there is no wind, the ball stays in the same column. The direction of the wind (or absence thereof) is observable through three bits the activations of which are mutually exclusive. Every K steps, the wind changes to one of the three possibilities. The environment is fully-observable and has stationary dynamics. """ def __init__(self, rows=_ROWS, columns=_COLUMNS, spawn_probability=_SPAWN_PROBABILITY, seed=None, change_every=_CHANGE_EVERY): """Initialize the windy catch environment. Args: rows: A positive integer denoting the number of rows. columns: A positive integer denoting the number of columns. spawn_probability: Float giving the probability of a new ball appearing. seed: Seed for the internal random number generator. change_every: A positive integer denoting the interval at which wind changes. """ self._seed = seed self._params = Params( rows=rows, columns=columns, observation_dim=rows * columns + 3, spawn_probability=spawn_probability, change_every=change_every) self._state = None def start(self, seed: Optional[int] = None): """Initializes the environment and returns an initial observation.""" # The initial state has one ball appearing in a random column at the top, # and the paddle centered at the bottom. rng = np.random.default_rng(self._seed if seed is None else seed) self._state = State( paddle_x=self._params.columns // 2, paddle_y=self._params.rows - 1, balls=[(rng.integers(self._params.columns), 0)], wind_direction=[True, False, False], time_since_wind_change=0, rng=rng, ) return self._get_observation() @property def started(self): """True if the environment has been started, False otherwise.""" # An unspecified state implies that the environment needs to be started. return self._state is not None def step(self, action): """Updates the environment state and returns an observation and reward. Args: action: An integer equalling 0, 1, or 2 indicating whether to move the paddle left, stay, or move the paddle right respectively. Returns: A tuple of type (int, float) giving the next observation and the reward. Raises: RuntimeError: If state has not yet been initialized by `start`. """ # Check if state has been initialized. if not self.started: raise RuntimeError(base.STEP_WITHOUT_START_ERR) # Check if input action is valid. if action not in [Action.LEFT, Action.STAY, Action.RIGHT]: raise ValueError(_INVALID_ACTION.format(action=action)) # Move the paddle. self._state.paddle_x = np.clip(self._state.paddle_x + Action(action).dx, 0, self._params.columns - 1) # Move all balls down by one unit, with wind. wd = _WIND_DELTA[self._state.wind_direction.index(True)] self._state.balls = [ # x coord: applies wind; y coord: gravity ((x + wd) % self._params.columns, y + 1) for x, y in self._state.balls ] # Since at most one ball is added at each timestep, at most one ball # can be at the bottom of the board, and must be the 'oldest' ball. reward = 0. if self._state.balls and self._state.balls[0][1] == self._state.paddle_y: reward = 1. if self._state.balls[0][0] == self._state.paddle_x else -1. # Remove ball from list. self._state.balls = self._state.balls[1:] # Add new ball with given probability. if self._state.rng.random() < self._params.spawn_probability: self._state.balls.append( (self._state.rng.integers(self._params.columns), 0)) # Update time since last change in wind. self._state.time_since_wind_change += 1 # Update the wind direction. if self._state.time_since_wind_change % self._params.change_every == 0: self._state.wind_direction = [False, False, False] self._state.wind_direction[self._state.rng.integers(3)] = True self._state.time_since_wind_change = 0 return self._get_observation(), reward def _get_board(self) -> np.ndarray: board = np.zeros((_ROWS, _COLUMNS), dtype=int) board.fill(0) board[self._state.paddle_y, self._state.paddle_x] = 1 for x, y in self._state.balls: board[y, x] = 1 return board def _get_observation(self) -> np.ndarray: """Converts internal environment state to an array observation. Returns: A binary array of size (rows * columns + 3,). """ return np.concatenate([ self._get_board().flatten(), self._state.wind_direction]) def observation_spec(self): """Describes the observation specs of the environment.""" return specs.BoundedArray( shape=(self._params.observation_dim,), dtype=int, minimum=0, maximum=1, name="board") def action_spec(self): """Describes the action specs of the environment.""" return specs.DiscreteArray(num_values=3, dtype=int, name="action") def get_state(self): """Returns a copy of the current environment state.""" return copy.deepcopy(self._state) if self._state is not None else None def set_state(self, state): """Sets environment state to state provided. Args: state: A State object which overrides the current state. """ # Check that input state values are valid. if not (0 <= state.paddle_x < self._params.columns and state.paddle_y == self._params.rows - 1): raise ValueError(_INVALID_PADDLE_POS) for x, y in state.balls: if not (0 <= x < self._params.columns and 0 <= y < self._params.rows): raise ValueError( _INVALID_BALLS_RANGE.format( rows=self._params.rows, columns=self._params.columns)) if sum(state.wind_direction) != 1: raise ValueError(_INVALID_WIND_DIRECTION) self._state = copy.deepcopy(state) def get_config(self): """Returns a copy of the environment configuration.""" return copy.deepcopy(self._params) def render(self) -> np.ndarray: board = self._get_board() num_cols = board.shape[1] header = np.ones((2, num_cols), dtype=np.uint8) center = num_cols // 2 header[0, center-1:center+2] = self._state.wind_direction return common.binary_board_to_rgb(np.concatenate([board, header]))
csuite-main
csuite/environments/windy_catch.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Continuing pendulum with random perturbations in the reward region. Environment description can be found in the `PendulumPoke' Environment class. """ import copy import dataclasses import enum from typing import Any, Callable from csuite.environments import base from dm_env import specs import numpy as np from PIL import Image from PIL import ImageDraw # Default environment variables. _NUM_ACTIONS = 3 # Size of action space discretization. _FRICTION = 0.1 _GRAVITY = 9.81 _SIMULATION_STEP_SIZE = 0.05 _ACT_STEP_PERIOD = 4 _MAX_SPEED = np.inf _REWARD_ANGLE = 30 # Default environment variables for adding perturbations. _PERTURB_PROB = 0.01 # TODO(b/243969989): Decide appropriate amount of perturbation torque. _PERTURB_TORQUE = 10. # Converter for degrees to radians. _RADIAN_MULTIPLIER = np.pi / 180 # Error messages. _INVALID_ANGLE = ("Invalid state: expected angle to be in range [0, 2pi].") # Variables for pixel visualization of the environment. _IMAGE_SIZE = 256 _CENTER_IMAGE = _IMAGE_SIZE // 2 - 1 _SCALE_FACTOR = 0.75 _PENDULUM_WIDTH = _IMAGE_SIZE // 64 _TIP_RADIUS = _IMAGE_SIZE // 24 _LIGHT_GREEN = "#d4ffd6" # For shading the reward region. _ARROW_WIDTH = _IMAGE_SIZE // 44 _TORQUE_ANGLE = 20 class Action(enum.IntEnum): """Actions for the PendulumPoke environment. There are three actions: 0: Apply -1 torque. 1: Do nothing. 2: Apply +1 torque. """ NEGATIVE, STAY, POSITIVE = range(3) @property def tau(self): """Maps NEGATIVE to -1, STAY to 0, and POSITIVE to 1.""" return self.value - 1 @dataclasses.dataclass class State: """State of a PendulumPoke environment. Attributes: angle: a float in [0, 2*pi] giving the angle in radians of the pendulum. An angle of 0 indicates that the pendulum is hanging downwards. velocity: a float in [-max_speed, max_speed] giving the angular velocity. rng: Internal NumPy pseudo-random number generator, included here for reproducibility purposes. """ angle: float velocity: float rng: np.random.Generator @dataclasses.dataclass class Params: """Parameters of a PendulumPoke environment.""" friction: float gravity: float simulation_step_size: float act_step_period: int max_speed: float reward_fn: Callable[..., float] perturb_prob: float perturb_torque: float def sparse_reward(state: State, unused_torque: Any, unused_step_size: Any, reward_angle: int = _REWARD_ANGLE) -> float: """Returns a sparse reward for the continuing pendulum problem. Args: state: A State object containing the current angle and velocity. reward_angle: An integer denoting the angle from vertical, in degrees, where the pendulum is rewarding. Returns: A reward of 1 if the angle of the pendulum is within the range, and a reward of 0 otherwise. """ reward_angle_radians = reward_angle * _RADIAN_MULTIPLIER if (np.pi - reward_angle_radians < state.angle < np.pi + reward_angle_radians): return 1. else: return 0. def _alias_angle(angle: float) -> float: """Returns an angle between 0 and 2*pi.""" return angle % (2 * np.pi) class PendulumPoke(base.Environment): """A pendulum environment with a random addition of force in the reward region. This environment has the same parameters as the `Pendulum` environment, and additionally with a small probability, a force is applied to the pendulum if it is in the rewarding region to knock the pendulum over. The magnitude of the force is constant, and the direction that the force is applied is chosen uniformly at random. """ def __init__(self, friction=_FRICTION, gravity=_GRAVITY, simulation_step_size=_SIMULATION_STEP_SIZE, act_step_period=_ACT_STEP_PERIOD, max_speed=_MAX_SPEED, reward_fn=sparse_reward, perturb_prob=_PERTURB_PROB, perturb_torque=_PERTURB_TORQUE, seed=None): """Initializes a new pendulum environment with random perturbations in the rewarding region. Args: friction: A positive float giving the coefficient of friction. gravity: A float giving the acceleration due to gravity. simulation_step_size: The step size (in seconds) of the simulation. act_step_period: An integer giving the number of simulation steps for each action input. max_speed: A float giving the maximum speed (in radians/second) allowed in the simulation. reward_fn: A callable which returns a float reward given current state. perturb_prob: A float giving the probability that a random force is applied to the pendulum if it is in the rewarding region. perturb_torque: A float giving the magnitude of the random force. seed: Seed for the internal random number generator. """ self._params = Params( friction=friction, gravity=gravity, simulation_step_size=simulation_step_size, act_step_period=act_step_period, max_speed=max_speed, reward_fn=reward_fn, perturb_prob=perturb_prob, perturb_torque=perturb_torque) self._seed = seed self._state = None self._torque = 0 self._perturb_direction = 0 # For visualization purposes. def start(self, seed=None): """Initializes the environment and returns an initial observation.""" self._state = State( angle=0., velocity=0., rng=np.random.default_rng(self._seed if seed is None else seed)) return np.array((np.cos(self._state.angle), np.sin( self._state.angle), self._state.velocity), dtype=np.float32) @property def started(self): """True if the environment has been started, False otherwise.""" # An unspecified state implies that the environment needs to be started. return self._state is not None def step(self, action): """Updates the environment state and returns an observation and reward. Args: action: An integer in {0, 1, 2} indicating whether to subtract one unit of torque, do nothing, or add one unit of torque. Returns: A tuple giving the next observation in the form of a NumPy array and the reward as a float. Raises: RuntimeError: If state has not yet been initialized by `start`. """ # Check if state has been initialized. if not self.started: raise RuntimeError(base.STEP_WITHOUT_START_ERR) self._torque = Action(action).tau # Integrate over time steps to get new angle and velocity. new_angle = self._state.angle new_velocity = self._state.velocity # If the pendulum is in the rewarding region, with the given probability # add a force in a direction chosen uniformly at random. reward_angle_rad = _REWARD_ANGLE * _RADIAN_MULTIPLIER if ((np.pi - reward_angle_rad < new_angle < np.pi + reward_angle_rad) and self._state.rng.uniform() < self._params.perturb_prob): if self._state.rng.uniform() < 0.5: applied_torque = self._torque - self._params.perturb_torque self._perturb_direction = -1 else: applied_torque = self._torque + self._params.perturb_torque self._perturb_direction = 1 else: applied_torque = self._torque self._perturb_direction = 0 for _ in range(self._params.act_step_period): new_velocity += ((applied_torque - self._params.friction * new_velocity - self._params.gravity * np.sin(new_angle)) * self._params.simulation_step_size) new_angle += new_velocity * self._params.simulation_step_size # Ensure the angle is between 0 and 2*pi. new_angle = _alias_angle(new_angle) # Clip velocity to max_speed. new_velocity = np.clip(new_velocity, -self._params.max_speed, self._params.max_speed) self._state = State( angle=new_angle, velocity=new_velocity, rng=self._state.rng) return (np.array((np.cos(self._state.angle), np.sin( self._state.angle), self._state.velocity), dtype=np.float32), self._params.reward_fn(self._state, self._torque, self._params.simulation_step_size)) def observation_spec(self): """Describes the observation specs of the environment.""" return specs.BoundedArray((3,), dtype=np.float32, minimum=[-1, -1, -self._params.max_speed], maximum=[1, 1, self._params.max_speed]) def action_spec(self): """Describes the action specs of the environment.""" return specs.DiscreteArray(_NUM_ACTIONS, dtype=int, name="action") def get_state(self): """Returns a copy of the current environment state.""" return copy.deepcopy(self._state) if self._state is not None else None def set_state(self, state): """Sets environment state to state provided. Args: state: A State object which overrides the current state. Returns: A NumPy array for the observation including the angle and velocity. """ # Check that input state values are valid. if not 0 <= state.angle <= 2 * np.pi: raise ValueError(_INVALID_ANGLE) self._state = copy.deepcopy(state) return np.array((np.cos(self._state.angle), np.sin( self._state.angle), self._state.velocity), dtype=np.float32) def render(self): image = Image.new("RGB", (_IMAGE_SIZE, _IMAGE_SIZE), "white") dct = ImageDraw.Draw(image) # Get x and y positions of the pendulum tip relative to the center. x_pos = np.sin(self._state.angle) y_pos = np.cos(self._state.angle) def abs_coordinates(x, y): """Return absolute coordinates given coordinates relative to center.""" return (x * _SCALE_FACTOR * _CENTER_IMAGE + _CENTER_IMAGE, y * _SCALE_FACTOR * _CENTER_IMAGE + _CENTER_IMAGE) # Draw reward range region. boundary_x = _CENTER_IMAGE * (1 - _SCALE_FACTOR) pendulum_bounding_box = [(boundary_x, boundary_x), (_IMAGE_SIZE - boundary_x, _IMAGE_SIZE - boundary_x)] dct.pieslice( pendulum_bounding_box, start=(270 - _REWARD_ANGLE), end=(270 + _REWARD_ANGLE), fill=_LIGHT_GREEN) # Get absolute coordinates of the pendulum tip. tip_coords = abs_coordinates(x_pos, y_pos) # Draw pendulum line. dct.line([(_CENTER_IMAGE, _CENTER_IMAGE), tip_coords], fill="black", width=_PENDULUM_WIDTH) # Draw circular pendulum tip. x, y = tip_coords tip_bounding_box = [(x - _TIP_RADIUS, y - _TIP_RADIUS), (x + _TIP_RADIUS, y + _TIP_RADIUS)] dct.ellipse(tip_bounding_box, fill="red") # Draw torque arrow. if self._torque > 0: dct.arc( pendulum_bounding_box, start=360 - _TORQUE_ANGLE, end=_TORQUE_ANGLE, fill="blue", width=_ARROW_WIDTH) # Draw arrow heads. arrow_x, arrow_y = abs_coordinates( np.cos(_TORQUE_ANGLE * _RADIAN_MULTIPLIER), -np.sin(_TORQUE_ANGLE * _RADIAN_MULTIPLIER)) dct.regular_polygon((arrow_x, arrow_y, _ARROW_WIDTH * 1.5), n_sides=3, rotation=_TORQUE_ANGLE, fill="blue") elif self._torque < 0: dct.arc( pendulum_bounding_box, start=180 - _TORQUE_ANGLE, end=180 + _TORQUE_ANGLE, fill="blue", width=_ARROW_WIDTH) # Draw arrow heads. arrow_x, arrow_y = abs_coordinates( -np.cos(_TORQUE_ANGLE * _RADIAN_MULTIPLIER), -np.sin(_TORQUE_ANGLE * _RADIAN_MULTIPLIER)) dct.regular_polygon((arrow_x, arrow_y, _ARROW_WIDTH * 1.5), n_sides=3, rotation=-_TORQUE_ANGLE, fill="blue") # Drawing perturbation arrow. if self._perturb_direction == 1: tip_coords = (_IMAGE_SIZE // 4 - _TIP_RADIUS, _IMAGE_SIZE // 8) arrow_coords = [ tip_coords, (_IMAGE_SIZE // 4 + _TIP_RADIUS, _IMAGE_SIZE // 8) ] dct.line(arrow_coords, fill="red", width=_PENDULUM_WIDTH) dct.regular_polygon((tip_coords, _ARROW_WIDTH * 1.2), rotation=90, n_sides=3, fill="red") elif self._perturb_direction == -1: tip_coords = (_IMAGE_SIZE * 3 // 4 + _TIP_RADIUS, _IMAGE_SIZE // 8) arrow_coords = [(_IMAGE_SIZE * 3 // 4 - _TIP_RADIUS, _IMAGE_SIZE // 8), tip_coords] dct.line(arrow_coords, fill="red", width=_PENDULUM_WIDTH) dct.regular_polygon((tip_coords, _ARROW_WIDTH * 1.2), rotation=270, n_sides=3, fill="red") return np.asarray(image, dtype=np.uint8)
csuite-main
csuite/environments/experimental/pendulum_poke.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for pendulum_poke.""" from absl.testing import absltest from csuite.environments.experimental import pendulum_poke class PendulumTest(absltest.TestCase): def test_environment_setup(self): """Tests environment initialization.""" env = pendulum_poke.PendulumPoke() self.assertIsNotNone(env) def test_start(self): """Tests environment start.""" env = pendulum_poke.PendulumPoke() with self.subTest(name='step_without_start'): # Calling step before start should raise an error. with self.assertRaises(RuntimeError): env.step(pendulum_poke.Action.NEGATIVE) with self.subTest(name='start_state'): start_obs = env.start() # Initial cosine of the angle should be 1. # Initial sine of the angle and initial velocity should be 0. self.assertEqual(start_obs[0], 1.) self.assertEqual(start_obs[1], 0.) self.assertEqual(start_obs[2], 0.) def test_one_step(self): """Tests one environment step.""" env = pendulum_poke.PendulumPoke() env.start() _, reward = env.step(pendulum_poke.Action.NEGATIVE) self.assertEqual(reward, 0.) _, reward = env.step(pendulum_poke.Action.POSITIVE) self.assertEqual(reward, 0.) _, reward = env.step(pendulum_poke.Action.STAY) self.assertEqual(reward, 0.) def test_setting_state(self): """Tests setting environment state and solver.""" env = pendulum_poke.PendulumPoke() old_obs = env.start() prev_state = env.get_state() # Take two steps adding +1 torque, then set state to downwards position. for _ in range(2): old_obs, _ = env.step(pendulum_poke.Action.POSITIVE) new_state = pendulum_poke.State(angle=0., velocity=0., rng=prev_state.rng) new_obs = env.set_state(new_state) for _ in range(2): new_obs, _ = env.step(pendulum_poke.Action.POSITIVE) # If the solver was properly updated, the two observations are the same. self.assertLessEqual(abs(new_obs[0]), old_obs[0]) self.assertLessEqual(abs(new_obs[1]), old_obs[1]) self.assertLessEqual(abs(new_obs[2]), old_obs[2]) if __name__ == '__main__': absltest.main()
csuite-main
csuite/environments/experimental/pendulum_poke_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Wrapper for converting a csuite base.Environment to dm_env.Environment.""" from csuite.environments import base import dm_env class DMEnvFromCSuite(dm_env.Environment): """A wrapper to convert a CSuite environment to a dm_env.Environment.""" def __init__(self, csuite_env: base.Environment): self._csuite_env = csuite_env self._started = False def reset(self) -> dm_env.TimeStep: observation = self._csuite_env.start() self._started = True return dm_env.restart(observation) def step(self, action) -> dm_env.TimeStep: if not self._started: return self.reset() # Convert the csuite step result to a dm_env TimeStep. observation, reward = self._csuite_env.step(action) return dm_env.TimeStep( step_type=dm_env.StepType.MID, observation=observation, reward=reward, discount=1.0) def observation_spec(self): return self._csuite_env.observation_spec() def action_spec(self): return self._csuite_env.action_spec() def get_state(self): return self._csuite_env.get_state() def set_state(self, state): self._csuite_env.set_state(state) def render(self): return self._csuite_env.render()
csuite-main
csuite/utils/dm_env_wrapper.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test for DMEnvFromCSuite.""" from absl.testing import absltest import csuite from dm_env import test_utils class DMEnvFromCSuiteTest(test_utils.EnvironmentTestMixin, absltest.TestCase): def make_object_under_test(self): csuite_env = csuite.load('catch') return csuite.dm_env_wrapper.DMEnvFromCSuite(csuite_env) if __name__ == '__main__': absltest.main()
csuite-main
csuite/utils/dm_env_wrapper_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for GymFromCSuite.""" from absl.testing import absltest import csuite from gym.utils import env_checker as gym_env_checker class GymFromCSuiteTest(absltest.TestCase): def test_env_checker(self): csuite_env = csuite.load('catch') gym_env = csuite.gym_wrapper.GymFromCSuite(csuite_env) # Gym's env_checker.check_env throws an exception if the env does not # conform to the Gym API: gym_env_checker.check_env(gym_env) if __name__ == '__main__': absltest.main()
csuite-main
csuite/utils/gym_wrapper_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Wrapper for adapating a csuite base.Environment to OpenAI gym interface.""" import typing from typing import Any, Dict, Tuple, Optional, Union from csuite.environments import base from dm_env import specs import gym from gym import spaces import numpy as np # OpenAI gym step format = obs, reward, is_finished, other_info _GymTimestep = Tuple[np.ndarray, float, bool, Dict[str, Any]] class GymFromCSuite(gym.Env): """A wrapper to convert a CSuite environment to an OpenAI gym.Env.""" metadata = {'render.modes': ['human', 'rgb_array']} def __init__(self, csuite_env: base.Environment): self._csuite_env = csuite_env self._np_random = None # GYM env_checker requires a _np_random attr self.viewer = None def step(self, action) -> _GymTimestep: # Convert the csuite step result to a gym timestep. try: observation, reward = self._csuite_env.step(action) except RuntimeError as e: # The gym.utils.env_checker expects the following assertion. if str(e) == base.STEP_WITHOUT_START_ERR: assert False, 'Cannot call env.step() before calling reset()' return observation, reward, False, {} def reset(self, seed: Optional[int] = None, options: Optional[dict] = None): # pylint: disable=g-bare-generic if options: raise NotImplementedError('options not supported with the gym wrapper.') del options observation = self._csuite_env.start(seed) state = self._csuite_env.get_state() self._np_random = state.rng if hasattr( state, 'rng') else np.random.default_rng(seed) if gym.__version__ == '0.19.0': return observation else: return observation, {} def render(self, mode: str = 'rgb_array') -> Union[np.ndarray, bool]: if mode == 'rgb_array': return self._csuite_env.render() if mode == 'human': if self.viewer is None: # pylint: disable=import-outside-toplevel # pylint: disable=g-import-not-at-top from gym.envs.classic_control import rendering self.viewer = rendering.SimpleImageViewer() self.viewer.imshow(self._csuite_env.render()) return self.viewer.isopen @property def action_space(self) -> spaces.Discrete: action_spec = self._csuite_env.action_spec() if isinstance(action_spec, specs.DiscreteArray): action_spec = typing.cast(specs.DiscreteArray, action_spec) return spaces.Discrete(action_spec.num_values) else: raise NotImplementedError( 'The gym wrapper only supports environments with discrete action ' 'spaces. Please raise an issue if you want to work with a ' 'a non-discrete action space.') @property def observation_space(self) -> spaces.Box: obs_spec = self._csuite_env.observation_spec() if isinstance(obs_spec, specs.BoundedArray): return spaces.Box( low=float(obs_spec.minimum), high=float(obs_spec.maximum), shape=obs_spec.shape, dtype=obs_spec.dtype) return spaces.Box( low=-float('inf'), high=float('inf'), shape=obs_spec.shape, dtype=obs_spec.dtype) @property def reward_range(self) -> Tuple[float, float]: # CSuite does not return reward range. return -float('inf'), float('inf') def __getattr__(self, attr): """Delegate attribute access to underlying environment.""" return getattr(self._csuite_env, attr)
csuite-main
csuite/utils/gym_wrapper.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Install script for setuptools.""" from setuptools import find_packages from setuptools import setup setup( name='tell_me_why_explanations_rl', version='1.0', description='TODO(lampinen)', author='DeepMind', author_email='[email protected]', license='Apache License, Version 2.0', url='https://github.com/deepmind/tell_me_why_explanations_rl', packages=find_packages(), install_requires=[ 'absl-py', 'dm-env', 'numpy', 'pycolab' ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 3.9', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], )
tell_me_why_explanations_rl-main
setup.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for the odd one out environment.""" from absl.testing import absltest from absl.testing import parameterized import dm_env import numpy as np from tell_me_why_explanations_rl import odd_one_out_environment from tell_me_why_explanations_rl import odd_one_out_environment_core class OddOneOutEnvironmentTest(parameterized.TestCase): @parameterized.parameters( "red solid triangle", "green horizontal_stripes plus", "blue vertical_stripes inverse_plus", "purple checker ex", "orange grid inverse_ex", "yellow noise circle", "brown solid tee", "pink horizontal_stripes upside_down_tee", "cyan vertical_stripes h", "dark_green checker u", "dark_red grid upside_down_u", "dark_blue noise square" ) def test_template_gen(self, object_name): odd_one_out_environment._generate_template(object_name) def test_basic_core(self): chars = odd_one_out_environment_core.POSSIBLE_OBJECT_CHARS[:4] targ = chars[2] these_object_properties = [ odd_one_out_environment_core.ObjectProperties( chars[0], (1, 4), "against_wall", "triangle", "red", "noise", 0.), odd_one_out_environment_core.ObjectProperties( chars[1], (4, 1), "against_wall", "triangle", "blue", "solid", 0.), odd_one_out_environment_core.ObjectProperties( targ, (4, 4), "in_center", "square", "red", "solid", 1.), odd_one_out_environment_core.ObjectProperties( chars[3], (6, 6), "in_center", "triangle", "blue", "noise", 0.), ] game = odd_one_out_environment_core.make_game( object_properties=these_object_properties, concept_type="shape", agent_start=(2, 2)) obs, reward, discount = game.its_showtime() with self.subTest(name="ObjectAndAgentSpawns"): self.assertEqual(obs.board[4, 4], ord(targ)) self.assertEqual(obs.board[2, 2], ord(odd_one_out_environment_core.AGENT_CHAR)) self.assertEqual(game.the_plot["char_to_color_shape"][targ], "red solid square") self.assertEqual(game.the_plot["char_to_color_shape"][chars[0]], "red noise triangle") with self.subTest(name="InitialObservationsAndInstructions"): self.assertIsNone(reward) self.assertEqual(discount, 1.) self.assertEqual(game.the_plot["instruction_string"], "") self.assertEqual(game.the_plot["explanation_string"], "") with self.subTest(name="ActionAndPropertyDescriptions"): # step down and right obs, reward, _ = game.play(odd_one_out_environment_core.ACTIONS.MOVE_SE) self.assertIsNone(reward) self.assertEqual(obs.board[3, 3], ord(odd_one_out_environment_core.AGENT_CHAR)) self.assertEqual(game.the_plot["explanation_string"], "This is a red solid square in_center") with self.subTest(name="GettingObjectAndExplanation"): # move to object obs, reward, _ = game.play(3) self.assertEqual(reward, 1.) self.assertEqual(game.the_plot["instruction_string"], "") self.assertEqual(game.the_plot["explanation_string"], "Correct it is uniquely square") with self.subTest(name="ExplanationPhaseAndTermination"): # test termination of explanation phase self.assertFalse(game.game_over) game.play(odd_one_out_environment_core.ACTIONS.MOVE_W) game.play(odd_one_out_environment_core.ACTIONS.MOVE_W) game.play(odd_one_out_environment_core.ACTIONS.MOVE_E) self.assertFalse(game.game_over) game.play(odd_one_out_environment_core.ACTIONS.MOVE_E) self.assertTrue(game.game_over) with self.subTest(name="ChooseWrongObjectExplanations"): # play again but choose wrong object game = odd_one_out_environment_core.make_game( object_properties=these_object_properties, concept_type="shape", agent_start=(2, 2)) _ = game.its_showtime() obs, reward, _ = game.play(odd_one_out_environment_core.ACTIONS.MOVE_SW) self.assertEqual(obs.board[3, 1], ord(odd_one_out_environment_core.AGENT_CHAR)) self.assertEqual(game.the_plot["explanation_string"], "This is a blue solid triangle against_wall") obs, reward, _ = game.play(odd_one_out_environment_core.ACTIONS.MOVE_S) self.assertEqual(reward, 0.) self.assertEqual( game.the_plot["explanation_string"], "Incorrect other objects are blue solid triangle or against_wall") self.assertFalse(game.game_over) def test_confounding_core(self): chars = odd_one_out_environment_core.POSSIBLE_OBJECT_CHARS[:4] targ = chars[2] these_object_properties = [ odd_one_out_environment_core.ObjectProperties( chars[0], (1, 4), "against_wall", "triangle", "blue", "solid", 0.), odd_one_out_environment_core.ObjectProperties( chars[1], (4, 1), "against_wall", "triangle", "blue", "solid", 0.), odd_one_out_environment_core.ObjectProperties( targ, (4, 4), "in_center", "square", "green", "noise", 1.), odd_one_out_environment_core.ObjectProperties( chars[3], (6, 6), "in_center", "triangle", "blue", "solid", 0.), ] game = odd_one_out_environment_core.make_game( object_properties=these_object_properties, concept_type="color", agent_start=(3, 3), explain_only_concept_type=True) obs, *_ = game.its_showtime() with self.subTest(name="AgentAndObjectSpawns"): self.assertEqual(obs.board[4, 4], ord(targ)) self.assertEqual(obs.board[3, 3], ord(odd_one_out_environment_core.AGENT_CHAR)) self.assertEqual(game.the_plot["instruction_string"], "") with self.subTest(name="PropertyExplanations"): self.assertEqual(game.the_plot["explanation_string"], "This is a green") with self.subTest(name="GettingObjectRewardExplanation"): # step down and right obs, reward, _ = game.play(odd_one_out_environment_core.ACTIONS.MOVE_SE) self.assertEqual(reward, 1.) self.assertEqual(game.the_plot["explanation_string"], "Correct it is uniquely green") def test_meta_core(self): chars = odd_one_out_environment_core.POSSIBLE_OBJECT_CHARS[:4] targ = chars[0] these_object_properties = [ odd_one_out_environment_core.ObjectProperties( targ, (1, 4), "against_wall", "triangle", "blue", "noise", 0.), odd_one_out_environment_core.ObjectProperties( chars[1], (4, 1), "against_wall", "triangle", "blue", "noise", 0.), odd_one_out_environment_core.ObjectProperties( chars[2], (4, 4), "in_center", "triangle", "blue", "noise", 0.), odd_one_out_environment_core.ObjectProperties( chars[3], (6, 6), "in_center", "triangle", "blue", "noise", 0.), ] game = odd_one_out_environment_core.make_metalearning_game( object_properties=these_object_properties, concept_type="shape", transformations_allowed=1, agent_start=(1, 6), additional_extant_properties={ "color": ["red"], "shape": ["square"], "texture": ["solid"], }) obs, reward, discount = game.its_showtime() with self.subTest(name="InitialSpawnsObservationsAndInstructions"): self.assertEqual(obs.board[1, 4], ord(targ)) self.assertEqual(obs.board[1, 6], ord(odd_one_out_environment_core.AGENT_CHAR)) self.assertIsNone(reward) self.assertEqual(discount, 1.) self.assertEqual(game.the_plot["char_to_color_shape"][targ], "blue noise triangle") self.assertEqual(game.the_plot["instruction_string"], "Make an odd one out") self.assertEqual(game.the_plot["explanation_string"], "") with self.subTest(name="PropertyExplanations"): # step left obs, reward, _ = game.play(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertIsNone(reward) self.assertEqual(obs.board[1, 5], ord(odd_one_out_environment_core.AGENT_CHAR)) self.assertEqual(game.the_plot["instruction_string"], "Make an odd one out") self.assertEqual(game.the_plot["explanation_string"], "This is a blue noise triangle") self.assertFalse(game.the_plot["transformations_happening_now"]) with self.subTest(name="TransformShape"): # transform shape obs, reward, _ = game.play( odd_one_out_environment_core.ACTIONS.TRANSFORM_SHAPE) self.assertIsNone(reward) self.assertEqual(obs.board[1, 5], ord(odd_one_out_environment_core.AGENT_CHAR)) self.assertTrue(game.the_plot["transformations_happening_now"]) self.assertTrue(game.the_plot["char_to_color_shape_updated"]) self.assertEqual(game.the_plot["char_to_color_shape"][targ], "blue noise square") self.assertEqual(game.the_plot["instruction_string"], "Make an odd one out") self.assertEqual(game.the_plot["explanation_string"], "This is a blue noise square") with self.subTest(name="GetObjectAndRewardExplanation"): # move to transformed object obs, reward, _ = game.play(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertEqual(reward, 1.) self.assertFalse(game.the_plot["transformations_happening_now"]) self.assertEqual(game.the_plot["instruction_string"], "") self.assertEqual(game.the_plot["explanation_string"], "Correct the concept is shape and it is uniquely square") with self.subTest(name="FailWithoutTransformations"): # now play same game without a transformation allowed (impossible to win) game = odd_one_out_environment_core.make_metalearning_game( object_properties=these_object_properties, concept_type="shape", transformations_allowed=0, agent_start=(1, 6), additional_extant_properties={ "color": ["red"], "shape": ["square"], "texture": ["solid"], }) obs, reward, discount = game.its_showtime() self.assertEqual(game.the_plot["instruction_string"], "Find the odd one out") self.assertEqual(game.the_plot["explanation_string"], "") # step left obs, reward, _ = game.play(odd_one_out_environment_core.ACTIONS.MOVE_W) # fail to transform shape, not allowed obs, reward, _ = game.play( odd_one_out_environment_core.ACTIONS.TRANSFORM_SHAPE) self.assertIsNone(reward) self.assertEqual(obs.board[1, 5], ord(odd_one_out_environment_core.AGENT_CHAR)) self.assertFalse(game.the_plot["transformations_happening_now"]) self.assertEqual(game.the_plot["char_to_color_shape"][targ], "blue noise triangle") self.assertEqual(game.the_plot["explanation_string"], "This is a blue noise triangle") # move to object, no reward obs, reward, _ = game.play(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertEqual(reward, 0.) self.assertFalse(game.the_plot["transformations_happening_now"]) self.assertEqual(game.the_plot["instruction_string"], "") self.assertEqual( game.the_plot["explanation_string"], "Incorrect the concept is shape and other objects are triangle") def test_full_base_game(self): def _game_factory(): chars = odd_one_out_environment_core.POSSIBLE_OBJECT_CHARS[:4] these_object_properties = [ odd_one_out_environment_core.ObjectProperties( chars[0], (1, 4), "against_wall", "triangle", "red", "noise", 0.), odd_one_out_environment_core.ObjectProperties( chars[1], (4, 1), "against_wall", "triangle", "blue", "solid", 0.), odd_one_out_environment_core.ObjectProperties( chars[2], (4, 4), "in_center", "square", "red", "solid", 1.), odd_one_out_environment_core.ObjectProperties( chars[3], (6, 6), "in_center", "triangle", "blue", "noise", 0.), ] return odd_one_out_environment_core.make_game( object_properties=these_object_properties, concept_type="shape", agent_start=(2, 2)) env = odd_one_out_environment.OddOneOutEnvironment( game_factory=_game_factory, rng=np.random.default_rng(seed=1234)) result = env.reset() with self.subTest(name="InitialObservations"): view_size = odd_one_out_environment.SCROLL_CROP_SIZE upsample_size = odd_one_out_environment.UPSAMPLE_SIZE self.assertLen(result.observation, 2) self.assertEqual(result.observation[0].shape, (view_size * upsample_size, view_size * upsample_size, 3)) offset = upsample_size * (view_size // 2) # check egocentric scrolling is working, by checking agent is in center agent_template = odd_one_out_environment._CHAR_TO_TEMPLATE_BASE[ odd_one_out_environment_core.AGENT_CHAR] np.testing.assert_array_almost_equal( result.observation[0][offset:offset + upsample_size, offset:offset + upsample_size, :], agent_template / 255.) # no explanation yet self.assertEqual(result.observation[1].item(), "") with self.subTest(name="StepAndObserve"): # step down and right result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_SE) np.testing.assert_array_almost_equal( result.observation[0][offset:offset + upsample_size, offset:offset + upsample_size, :], agent_template / 255.) self.assertEqual(result.reward, 0.) self.assertEqual(result.observation[1].item(), "This is a red solid square in_center") def test_single_meta_game(self): def _game_factory(tr_al=1): chars = odd_one_out_environment_core.POSSIBLE_OBJECT_CHARS[:4] these_object_properties = [ odd_one_out_environment_core.ObjectProperties( chars[0], (1, 4), "against_wall", "triangle", "blue", "noise", 0.), odd_one_out_environment_core.ObjectProperties( chars[1], (4, 1), "against_wall", "triangle", "blue", "noise", 0.), odd_one_out_environment_core.ObjectProperties( chars[2], (4, 4), "in_center", "triangle", "blue", "noise", 0.), odd_one_out_environment_core.ObjectProperties( chars[3], (6, 6), "in_center", "triangle", "blue", "noise", 0.), ] return odd_one_out_environment_core.make_metalearning_game( object_properties=these_object_properties, concept_type="shape", transformations_allowed=tr_al, agent_start=(1, 6), additional_extant_properties={ "color": ["red"], "shape": ["square"], "texture": ["solid"], }) env = odd_one_out_environment.MetaOddOneOutEnvironment( game_factory=_game_factory, rng=np.random.default_rng(seed=1234)) result = env.reset() with self.subTest(name="InitialObservations"): self.assertLen(result.observation, 3) view_size = odd_one_out_environment.SCROLL_CROP_SIZE upsample_size = odd_one_out_environment.UPSAMPLE_SIZE self.assertEqual(result.observation[0].shape, (view_size * upsample_size, view_size * upsample_size, 3)) self.assertEqual(result.observation[1].item(), "") self.assertEqual(result.observation[2].item(), "Make an odd one out") with self.subTest(name="StepAndPropertyExplanation"): result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertEqual(result.observation[1].item(), "This is a blue noise triangle") self.assertEqual(result.observation[2].item(), "Make an odd one out") with self.subTest(name="InstructionChangesWithNoTransforms"): # now try with no transforms, to check instruction changes env = odd_one_out_environment.MetaOddOneOutEnvironment( game_factory=lambda: _game_factory(tr_al=0), rng=np.random.default_rng(seed=1234)) result = env.reset() self.assertLen(result.observation, 3) self.assertEqual(result.observation[2].item(), "Find the odd one out") def test_meta_full_task(self): env = odd_one_out_environment.metalearning_builder( num_trials_before_test=1, intervention_type="easy", concept_type="shape", explain="full", rng=np.random.default_rng(seed=1)) result = env.reset() with self.subTest(name="InitialObservations"): self.assertLen(result.observation, 3) self.assertEqual(result.observation[1].item(), "") self.assertEqual(result.observation[2].item(), "Make an odd one out") with self.subTest(name="StepAndObserve"): result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertEqual(result.observation[1].item(), "") result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertEqual(result.observation[1].item(), "This is a peach noise plus") self.assertEqual(result.reward, 0.) with self.subTest(name="ObjectChangesWithTransformation"): # check object rendering changes before -> after transformation scs = odd_one_out_environment.SCROLL_CROP_SIZE us = odd_one_out_environment.UPSAMPLE_SIZE off = us * (scs // 2) pre_object_image = result.observation[0][off:off + us, off - us:off, :] result = env.step(odd_one_out_environment_core.ACTIONS.TRANSFORM_SHAPE) self.assertEqual(result.observation[1].item(), "This is a peach noise u") self.assertEqual(result.reward, 0.) post_object_image = result.observation[0][off:off + us, off - us:off, :] self.assertFalse(np.array_equal(pre_object_image, post_object_image)) with self.subTest(name="GetObjectAndRewardExplanation"): # now grab result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertEqual(result.observation[1].item(), "Correct the concept is shape and it is uniquely u") self.assertEqual(result.reward, 1.) result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_E) result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_E) result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertEqual(result.observation[1].item(), "Correct the concept is shape and it is uniquely u") self.assertEqual(result.reward, 0.) with self.subTest(name="CheckTrialTransition"): # should trigger level transition to test level result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_W) self.assertEqual(result.observation[1].item(), "") self.assertEqual(result.observation[2].item(), "Find the odd one out") self.assertEqual(result.reward, 0.) self.assertEqual(result.step_type, dm_env.StepType.MID) with self.subTest(name="FinalTrial"): result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_NE) result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_NE) self.assertEqual(result.observation[1].item(), "This is a lavender checker triangle") result = env.step(odd_one_out_environment_core.ACTIONS.MOVE_NE) self.assertEqual(result.reward, 10.) self.assertEqual( result.observation[1].item(), "Correct the concept is shape and it is uniquely triangle") def test_confound_builder(self): env = odd_one_out_environment.confounding_builder( confounding="confounded", concept_type="texture", explain="full", rng=np.random.default_rng(seed=1)) result = env.reset() self.assertLen(result.observation, 2) current_objects = env._current_game.the_plot["char_to_color_shape"].values() self.assertLen(set(current_objects), 2) # deconfounded version env = odd_one_out_environment.confounding_builder( confounding="deconfounded", concept_type="texture", explain="full", rng=np.random.default_rng(seed=1)) result = env.reset() current_objects = env._current_game.the_plot["char_to_color_shape"].values() self.assertLen(set(current_objects), 4) @parameterized.parameters( "position_none", "shape_full", "texture_reward", "color_properties", ### confounding levels "confounding_color_none", "confounding_shape_full", "deconfounding_texture_full", ### metalearning levels "meta_3_easy_shape_full", "meta_3_hard1_color_none", "meta_3_hard3_texture_full", ) def test_from_name(self, level_name): np.random.seed(0) env = odd_one_out_environment.from_name(level_name) env.reset() view_size = odd_one_out_environment.SCROLL_CROP_SIZE upsample_size = odd_one_out_environment.UPSAMPLE_SIZE for i in range(8): result = env.step(i).observation self.assertEqual(result[0].shape, (view_size * upsample_size, view_size * upsample_size, 3)) if __name__ == "__main__": absltest.main()
tell_me_why_explanations_rl-main
tell_me_why_explanations_rl/odd_one_out_environment_test.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A base pycolab environment for finding the object that's an odd one out. The agent will be placed in a room with four objects. These objects have different colors, shapes, and possible positions. Two values of each attribute will appear in any given trial. For example, there might be red and blue objects triangles and squares, and objects either in the corner or center. Two of these attributes will be evenly distributed across the objects, so that half the objects have each value, but one will be unevenly split. For example, there might be two red and two blue objects, two triangles and two squares, but three objects in the center and only one in the corner. The agent will be rewarded for touching the object that's the odd one out. For the meta-learning task, the code in this file mostly corresponds to a single trial; the linking across trials is handled in the MetaOddOneOutEnvironment class in odd_one_out_environment.py. """ import curses import dataclasses import enum from typing import Tuple from absl import app from absl import logging import numpy as np from pycolab import ascii_art from pycolab import human_ui from pycolab import things as plab_things from pycolab.prefab_parts import sprites as prefab_sprites ROOM_SIZE = (11, 11) # one square around edge will be wall. OBJECT_POSITIONS = { "in_corner": [(1, 1), (1, 9), (9, 1), (9, 9)], "against_wall_x": [(1, 4), (1, 5), (1, 6), (9, 4), (9, 5), (9, 6)], "against_wall_y": [(4, 1), (5, 1), (6, 1), (4, 9), (5, 9), (6, 9)], "in_center": [(4, 4), (4, 5), (4, 6), (5, 4), (5, 5), (5, 6), (6, 4), (6, 5), (6, 6)]} AGENT_CHAR = "A" WALL_CHAR = "#" FLOOR_CHAR = " " RESERVED_CHARS = [AGENT_CHAR, WALL_CHAR, FLOOR_CHAR] POSSIBLE_OBJECT_CHARS = [ chr(i) for i in range(65, 91) if chr(i) not in RESERVED_CHARS ] EXPLAIN_PHASE_LENGTH = 16 EPISODE_LENGTH = 128 CORRECT_REWARD = 1. INCORRECT_REWARD = 0. META_BETWEEN_TRIAL_CLEANUP_KEYS = ( # plot items to reinitialize between trials "next_progressive_level", "explanation_string", "instruction_string", "char_to_color_shape", "char_to_color_shape_updated", "transformations_allowed", "transformations_happening_now", "extant_attributes", "concept_type", "explain", "termination_countdown", "value_multiplier", ) class ACTIONS(enum.IntEnum): """The possible actions the agent can take.""" # movement directions MOVE_N = 0 MOVE_NE = 1 MOVE_E = 2 MOVE_SE = 3 MOVE_S = 4 MOVE_SW = 5 MOVE_W = 6 MOVE_NW = 7 # transformations (used for meta environment only) TRANSFORM_COLOR = 8 TRANSFORM_TEXTURE = 9 TRANSFORM_SHAPE = 10 TRANSFORM_ACTIONS = ( ACTIONS.TRANSFORM_COLOR, ACTIONS.TRANSFORM_TEXTURE, ACTIONS.TRANSFORM_SHAPE) def terminate_episode_cleanup(the_plot): """Cleans up between trials in meta-learning setting.""" if the_plot["next_progressive_level"] is not None: the_plot.next_chapter = the_plot["next_progressive_level"] logging.info("Progressing to next level! %i", the_plot.next_chapter) # don't carry these keys over, will be reset when the new game is built for k in META_BETWEEN_TRIAL_CLEANUP_KEYS: del the_plot[k] @dataclasses.dataclass class ObjectProperties: """Class for holding the properties of objects while building.""" character: str position: Tuple[int, int] position_type: str shape: str color: str texture: str value: float class ObjectDrape(plab_things.Drape): """A `Drape` for objects in the room. See parent class for details of Drapes. These drapes handle logic of providing explanations to the agent, and handle rewards etc. if agent moves onto one. """ def __init__(self, curtain, character, object_properties, properties_string, explanation_string): assert character == object_properties.character super(ObjectDrape, self).__init__(curtain, object_properties.character) self.color = object_properties.color self.texture = object_properties.texture self.shape = object_properties.shape self.properties_string = properties_string self.explanation_string = explanation_string self.value = object_properties.value self.position = object_properties.position self.agent_is_adjacent = False def _handle_player_touch(self, the_plot): """What happens if player moves onto this object.""" if the_plot["termination_countdown"] is not None: if the_plot["termination_countdown"] < EXPLAIN_PHASE_LENGTH - 2: # touched something else already, and time passed since, terminate. the_plot.terminate_episode() else: # touched for the very first time! the_plot.add_reward(self.value) the_plot["termination_countdown"] = EXPLAIN_PHASE_LENGTH the_plot["explanation_string"] = self.explanation_string def _handle_adjacency(self, the_plot, adjacent, *args): """What happens if player is adjacent to this object.""" if adjacent: if the_plot["termination_countdown"] is None: the_plot["explanation_string"] = self.properties_string elif self.agent_is_adjacent: # no longer adjacent, but was, reset instruction if needed self.agent_is_adjacent = False if the_plot["explanation_string"] == self.properties_string: the_plot["explanation_string"] = "" def update(self, actions, board, layers, backdrop, things, the_plot): """Update state given player actions, etc. Player updates earlier.""" rows, cols = things[AGENT_CHAR].position if self.curtain[(rows, cols)]: self._handle_player_touch(the_plot) else: # is character adjacent to object? adjacent = False poss_rows = range(rows - 1, rows + 2) poss_cols = range(cols - 1, cols + 2) for x in poss_rows: for y in poss_cols: possible_position = (x, y) if self.curtain[possible_position]: adjacent = True break self._handle_adjacency(the_plot, adjacent, actions, things) class MetaObjectDrape(ObjectDrape): """A `Drape` for objects in the meta-learning version.""" def _set_value_and_explanations(self, things, the_plot): """Update value and explanations (e.g., after any transformations).""" self.value = CORRECT_REWARD for k, thing in things.items(): if k not in [self.character, AGENT_CHAR]: # if matches along relevant dimension, then not odd one out if ((the_plot["concept_type"] == "color" and thing.color == self.color) or (the_plot["concept_type"] == "texture" and thing.texture == self.texture) or (the_plot["concept_type"] == "shape" and thing.shape == self.shape)): self.value = INCORRECT_REWARD break # same with explanations if self.explanation_string: if self.value == CORRECT_REWARD: explanation_string = ["Correct the concept is"] explanation_string += [the_plot["concept_type"]] explanation_string += ["and it is uniquely"] else: explanation_string = ["Incorrect the concept is"] explanation_string += [the_plot["concept_type"]] explanation_string += ["and other objects are"] if the_plot["concept_type"] == "color": explanation_string.append(self.color) elif the_plot["concept_type"] == "shape": explanation_string.append(self.shape) elif the_plot["concept_type"] == "texture": explanation_string.append(self.texture) self.explanation_string = " ".join(explanation_string) if self.properties_string: self.properties_string = " ".join([ "This is a", self.color, self.texture, self.shape]) def _handle_player_touch(self, the_plot): if the_plot["termination_countdown"] is not None: if the_plot["termination_countdown"] < EXPLAIN_PHASE_LENGTH - 2: # touched something else already, and time passed since, terminate. terminate_episode_cleanup(the_plot) the_plot.terminate_episode() return else: the_plot.add_reward(self.value * the_plot["value_multiplier"]) the_plot["termination_countdown"] = EXPLAIN_PHASE_LENGTH the_plot["explanation_string"] = self.explanation_string the_plot["instruction_string"] = "" def _handle_adjacency(self, the_plot, adjacent, actions, things): if adjacent: if the_plot["transformations_happening_now"] and actions in [8, 9, 10]: print("transforming adjacent") original = the_plot["char_to_color_shape"][self.character] original = original.split() updated = None if actions == ACTIONS.TRANSFORM_COLOR: for other_color in the_plot["extant_attributes"]["color"]: if other_color != self.color: logging.info("Transforming: %s -> %s", self.color, other_color) self.color = other_color updated = [other_color] + original[1:] break elif actions == ACTIONS.TRANSFORM_TEXTURE: # transform texture for other_texture in the_plot["extant_attributes"]["texture"]: if other_texture != self.texture: logging.info( "Transforming: %s -> %s", self.texture, other_texture) self.texture = other_texture updated = [original[0], other_texture, original[2]] break elif actions == ACTIONS.TRANSFORM_SHAPE: # transform shape for other_shape in the_plot["extant_attributes"]["shape"]: if other_shape != self.shape: logging.info("Transforming: %s -> %s", self.shape, other_shape) self.shape = other_shape updated = original[:2] + [other_shape] break updated = " ".join(updated) the_plot["char_to_color_shape"][self.character] = updated the_plot["char_to_color_shape_updated"] = True # update value etc. anytime player is adjacent, when it matters... self._set_value_and_explanations(things, the_plot) if (the_plot["termination_countdown"] is None and the_plot["explanation_string"][:15] != "You transformed"): the_plot["explanation_string"] = self.properties_string elif self.agent_is_adjacent: # no longer adjacent, but was, reset instruction if needed self.agent_is_adjacent = False if the_plot["explanation_string"] == self.properties_string: the_plot["explanation_string"] = "" def update(self, actions, board, layers, backdrop, things, the_plot): if "char_to_color_shape" not in the_plot: # trial over, nothing left to do! return return super().update(actions, board, layers, backdrop, things, the_plot) class PlayerSprite(prefab_sprites.MazeWalker): """The player character. Player character, moves around and handles some game logic. See parent class for further details. """ def __init__(self, corner, position, character): super(PlayerSprite, self).__init__( corner, position, character, impassable="#") self.start_position = position def _terminate_episode(self, the_plot): the_plot.terminate_episode() def update(self, actions, board, layers, backdrop, things, the_plot): """Update self and game state given an action.""" # basic movement if actions == ACTIONS.MOVE_N: self._north(board, the_plot) elif actions == ACTIONS.MOVE_NE: self._northeast(board, the_plot) elif actions == ACTIONS.MOVE_E: self._east(board, the_plot) elif actions == ACTIONS.MOVE_SE: self._southeast(board, the_plot) elif actions == ACTIONS.MOVE_S: self._south(board, the_plot) elif actions == ACTIONS.MOVE_SW: self._southwest(board, the_plot) elif actions == ACTIONS.MOVE_W: self._west(board, the_plot) elif actions == ACTIONS.MOVE_NW: self._northwest(board, the_plot) # game logic if the_plot["termination_countdown"] is not None: if the_plot["termination_countdown"] == 0: self._terminate_episode(the_plot) else: the_plot["termination_countdown"] -= 1 class MetaPlayerSprite(PlayerSprite): """The player for the meta-learning tasks.""" def _terminate_episode(self, the_plot): terminate_episode_cleanup(the_plot) the_plot.terminate_episode() def update(self, actions, board, layers, backdrop, things, the_plot): if actions in TRANSFORM_ACTIONS and the_plot["transformations_allowed"] > 0: the_plot["transformations_allowed"] -= 1 the_plot["transformations_happening_now"] = True else: the_plot["transformations_happening_now"] = False if the_plot["explanation_string"][:15] == "You transformed": the_plot["explanation_string"] = "" super().update(actions, board, layers, backdrop, things, the_plot) def _generate_level_layout(object_properties, agent_start): """Generates pycolab-style ascii map containing room, objects, and agent.""" level_layout = np.array([[FLOOR_CHAR] * ROOM_SIZE[1]] * ROOM_SIZE[0]) # insert walls level_layout[0, :] = WALL_CHAR level_layout[-1, :] = WALL_CHAR level_layout[:, 0] = WALL_CHAR level_layout[:, -1] = WALL_CHAR # add agent and objects level_layout[agent_start] = AGENT_CHAR for obj in object_properties: level_layout[obj.position] = obj.character # convert to pycolab's ascii format level_layout = ["".join(x) for x in level_layout.tolist()] return level_layout def make_game(object_properties, concept_type, explain="full", agent_start=None, explain_only_concept_type=False, rng=None): """Makes a basic pycolab odd-one-out game. Args: object_properties: list of ObjectProperties for defining objects in level. concept_type: one of ["position", "color", "texture" "shape"], indicating which attribute has the odd-one-out. explain: One of "full" "reward", "properties" or "none." If none, no explanation. If "reward" the explanation describes whether the answer was correct or incorrect, and the features that show it. If "properties", will identify the properties of objects when adjacent to them. If "full", gives both properties + reward. agent_start: Optional agent start position (mostly for testing). explain_only_concept_type: explain only the single dimension corresponding to concept_type; used for the confounding experiments only. rng: An optional numpy Random Generator for choosing agent_start (if not set), to set a fixed seed use e.g. `rng=np.random.default_rng(seed=...)` Returns: this_game: Pycolab engine running the specified game. """ if rng is None: rng = np.random.default_rng() char_to_color_shape = [] drape_creators = {} forbidden_locations = [] for obj in object_properties: # can't have player starting here forbidden_locations.append(obj.position) # instruction if explain not in ["none", "full", "reward", "properties"]: raise ValueError("Unrecognized explanation type: {}".format(explain)) if explain in ["full", "properties"]: if explain_only_concept_type: properties_string = "This is a " if concept_type == "color": properties_string += obj.color elif concept_type == "texture": properties_string += obj.texture elif concept_type == "shape": properties_string += obj.shape elif concept_type == "position": properties_string += obj.position_type else: properties_string = " ".join([ "This is a", obj.color, obj.texture, obj.shape, obj.position_type]) else: properties_string = "" explanation_string = "" if explain in ["full", "reward"]: if obj.value > 0.: explanation_string = ["Correct it is uniquely"] if concept_type == "position": explanation_string.append(obj.position_type) elif concept_type == "color": explanation_string.append(obj.color) elif concept_type == "shape": explanation_string.append(obj.shape) elif concept_type == "texture": explanation_string.append(obj.texture) else: if explain_only_concept_type: explanation_string = ["Incorrect other objects are"] if concept_type == "position": explanation_string.append(obj.position_type) elif concept_type == "color": explanation_string.append(obj.color) elif concept_type == "shape": explanation_string.append(obj.shape) elif concept_type == "texture": explanation_string.append(obj.texture) else: explanation_string = [ "Incorrect other objects are", obj.color, obj.texture, obj.shape, "or", obj.position_type] explanation_string = " ".join(explanation_string) # create object builders drape_creators[obj.character] = ascii_art.Partial( ObjectDrape, object_properties=obj, properties_string=properties_string, explanation_string=explanation_string) char_to_color_shape.append( (obj.character, " ".join((obj.color, obj.texture, obj.shape)))) # set up agent start if agent_start is None: poss_starts = [] for x in range(1, 10): for y in range(1, 10): if (x, y) not in forbidden_locations: poss_starts.append((x, y)) agent_start = poss_starts[ rng.integers(len(poss_starts))] sprites = {AGENT_CHAR: PlayerSprite} # generate level and game level_layout = _generate_level_layout(object_properties, agent_start) this_game = ascii_art.ascii_art_to_game( art=level_layout, what_lies_beneath=" ", sprites=sprites, drapes=drape_creators, update_schedule=[[AGENT_CHAR], [obj.character for obj in object_properties]]) # update necessary plot information this_game.the_plot["explanation_string"] = "" this_game.the_plot["instruction_string"] = "" # only used in meta case this_game.the_plot["char_to_color_shape"] = dict(char_to_color_shape) this_game.the_plot["char_to_color_shape_updated"] = False # used for meta this_game.the_plot["termination_countdown"] = None return this_game def make_metalearning_game( object_properties, concept_type, explain="full", transformations_allowed=0, additional_extant_properties=None, agent_start=None, value_multiplier=1., next_progressive_level=None, rng=None): """Constructs a metalearning version of the game. Args: object_properties: list of (character, position, position_type, shape, color, texture, value), for placing objects in the world. concept_type: one of ["color", "texture" "shape"], indicating which attribute has the odd-one-out. explain: One of "full" "reward", "properties" or "none." If none, no explanation. If "reward" the explanation describes whether the answer was correct or incorrect, and the features that show it. If "properties", will identify the properties of objects when adjacent to them. If "full", gives both properties + reward. transformations_allowed: number of transformations of object properties that the agent is allowed to make. Use 0 to match the original task, more to allow interesting interventions on the environment. additional_extant_properties: Optional dict, used to add properties that are desired but not yet present in the scene, for transformation. Should have as keys a subset of ["color", "texture", "shape"]. agent_start: Optional agent start position (mostly for testing). value_multiplier: multiplies the rewards. next_progressive_level: if not None, the next level key to progress to. rng: An optional numpy Random Generator for choosing agent_start (if not set), to set a fixed seed use e.g. `rng=np.random.default_rng(seed=...)` Returns: this_game: Pycolab engine running the specified game. """ if rng is None: rng = np.random.default_rng() char_to_color_shape = [] drape_creators = {} forbidden_locations = [] extant_attributes = {"color": set(), "texture": set(), "shape": set()} for obj in object_properties: # can't have player starting here forbidden_locations.append(obj.position) # explanations if explain not in ["none", "full", "reward", "properties"]: raise ValueError("Unrecognized explanation type: {}".format(explain)) if explain in ["full", "properties"]: properties_string = "tbd" # will be set later as needed. else: properties_string = "" explanation_string = "" if explain in ["full", "reward"]: explanation_string = "tbd" # will be set later as needed. # create object builders drape_creators[obj.character] = ascii_art.Partial( MetaObjectDrape, object_properties=obj, properties_string=properties_string, explanation_string=explanation_string) char_to_color_shape.append( (obj.character, " ".join((obj.color, obj.texture, obj.shape)))) extant_attributes["color"].add(obj.color) extant_attributes["texture"].add(obj.texture) extant_attributes["shape"].add(obj.shape) if additional_extant_properties is not None: for k, v in additional_extant_properties.items(): extant_attributes[k].update(set(v)) # set up agent start if agent_start is None: poss_starts = [] for x in range(1, 10): for y in range(1, 10): if (x, y) not in forbidden_locations: poss_starts.append((x, y)) agent_start = poss_starts[ rng.integers(len(poss_starts))] sprites = {AGENT_CHAR: MetaPlayerSprite} # generate level and game level_layout = _generate_level_layout(object_properties, agent_start) this_game = ascii_art.ascii_art_to_game( art=level_layout, what_lies_beneath=" ", sprites=sprites, drapes=drape_creators, update_schedule=[[AGENT_CHAR], [obj.character for obj in object_properties]]) # update necessary plot information if transformations_allowed > 0: this_game.the_plot["instruction_string"] = "Make an odd one out" else: this_game.the_plot["instruction_string"] = "Find the odd one out" this_game.the_plot["explanation_string"] = "" this_game.the_plot["char_to_color_shape"] = dict(char_to_color_shape) this_game.the_plot["char_to_color_shape_updated"] = True this_game.the_plot["transformations_allowed"] = transformations_allowed this_game.the_plot["transformations_happening_now"] = False this_game.the_plot["extant_attributes"] = extant_attributes this_game.the_plot["concept_type"] = concept_type this_game.the_plot["termination_countdown"] = None this_game.the_plot["value_multiplier"] = value_multiplier this_game.the_plot["next_progressive_level"] = next_progressive_level this_game.the_plot["explain"] = explain return this_game def main(argv): if len(argv) > 2: raise app.UsageError("Too many command-line arguments.") episode_type = argv[1] if episode_type == "basic": these_object_properties = [ ObjectProperties( POSSIBLE_OBJECT_CHARS[1], (1, 4), "against_wall", "triangle", "red", "solid", INCORRECT_REWARD), ObjectProperties( POSSIBLE_OBJECT_CHARS[2], (4, 1), "against_wall", "triangle", "blue", "noise", INCORRECT_REWARD), ObjectProperties( POSSIBLE_OBJECT_CHARS[3], (4, 4), "in_center", "square", "red", "noise", CORRECT_REWARD), ObjectProperties( POSSIBLE_OBJECT_CHARS[4], (6, 6), "in_center", "triangle", "blue", "solid", INCORRECT_REWARD), ] game = make_game(object_properties=these_object_properties, concept_type="shape") elif episode_type == "meta": these_object_properties = [ ObjectProperties( POSSIBLE_OBJECT_CHARS[1], (1, 4), "against_wall", "triangle", "blue", "noise", INCORRECT_REWARD), ObjectProperties( POSSIBLE_OBJECT_CHARS[2], (4, 1), "against_wall", "triangle", "blue", "noise", INCORRECT_REWARD), ObjectProperties( POSSIBLE_OBJECT_CHARS[3], (4, 4), "in_center", "triangle", "blue", "noise", INCORRECT_REWARD), ObjectProperties( POSSIBLE_OBJECT_CHARS[4], (6, 6), "in_center", "triangle", "blue", "noise", INCORRECT_REWARD), ] game = make_metalearning_game( object_properties=these_object_properties, concept_type="shape", transformations_allowed=5, agent_start=(1, 6), additional_extant_properties={ "color": ["red"], "shape": ["square"], "texture": ["solid"], }) else: raise ValueError("Unrecognized argument: %s" % episode_type) # Note that these colors are only for human UI foreground_colors = { AGENT_CHAR: (999, 999, 999), # Agent is white WALL_CHAR: (300, 300, 300), # Wall, dark grey FLOOR_CHAR: (0, 0, 0), # Floor } keys_to_actions = { # Basic movement. curses.KEY_UP: ACTIONS.MOVE_N, curses.KEY_DOWN: ACTIONS.MOVE_S, curses.KEY_LEFT: ACTIONS.MOVE_W, curses.KEY_RIGHT: ACTIONS.MOVE_E, -1: 11, # Do nothing. } if episode_type == "basic": foreground_colors.update({ POSSIBLE_OBJECT_CHARS[1]: (900, 100, 100), POSSIBLE_OBJECT_CHARS[2]: (100, 100, 900), POSSIBLE_OBJECT_CHARS[3]: (900, 100, 100), POSSIBLE_OBJECT_CHARS[4]: (100, 100, 900), }) elif episode_type == "meta": keys_to_actions.update({ "q": ACTIONS.TRANSFORM_COLOR, "w": ACTIONS.TRANSFORM_TEXTURE, "e": ACTIONS.TRANSFORM_SHAPE, }) foreground_colors.update({ POSSIBLE_OBJECT_CHARS[1]: (100, 100, 900), POSSIBLE_OBJECT_CHARS[2]: (100, 100, 900), POSSIBLE_OBJECT_CHARS[3]: (100, 100, 900), POSSIBLE_OBJECT_CHARS[4]: (100, 100, 900), }) background_colors = { c: (0, 0, 0) for c in foreground_colors } ui = human_ui.CursesUi( keys_to_actions=keys_to_actions, delay=10000, colour_fg=foreground_colors, colour_bg=background_colors) ui.play(game) if __name__ == "__main__": app.run(main)
tell_me_why_explanations_rl-main
tell_me_why_explanations_rl/odd_one_out_environment_core.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The odd-one-out environment classes. This file builds the dm_env interfaces for the core pycolab games, which generate the inputs for the agent from the pycolab state representation, and put everything into a nice dm_env format. """ import copy import functools from absl import logging import dm_env import numpy as np from pycolab import cropping from pycolab import storytelling from tell_me_why_explanations_rl import odd_one_out_environment_core as _env_core UPSAMPLE_SIZE = 9 # pixels per game square SCROLL_CROP_SIZE = 11 OBJECT_SHAPES = [ "triangle", "plus", "inverse_plus", "ex", "inverse_ex", "circle", "tee", "upside_down_tee", "h", "u", "upside_down_u", ] OBJECT_TEXTURES = [ "solid", "horizontal_stripes", "vertical_stripes", "checker", "grid", "noise", ] COLORS = { "red": np.array([255, 0, 0]), "green": np.array([0, 255, 0]), "blue": np.array([0, 0, 255]), "purple": np.array([128, 0, 128]), "orange": np.array([255, 165, 0]), "yellow": np.array([255, 255, 0]), "brown": np.array([128, 64, 0]), "pink": np.array([255, 64, 255]), "cyan": np.array([0, 255, 255]), "dark_green": np.array([0, 100, 0]), "dark_red": np.array([100, 0, 0]), "dark_blue": np.array([0, 0, 100]), "olive": np.array([100, 100, 0]), "teal": np.array([0, 100, 100]), "lavender": np.array([215, 200, 255]), "peach": np.array([255, 210, 170]), "rose": np.array([255, 205, 230]), "light_green": np.array([200, 255, 200]), "light_yellow": np.array([255, 255, 200]), } # meta-learning only EXPERIMENT_REWARD_MULT = 1. # how big the experimentation trial rewards are TEST_REWARD_MULT = 10. # how big the final trial rewards are def _generate_template(object_name): """Generate a template image from an object color + texture + shape string.""" object_color, object_texture, object_type = object_name.split() template = np.zeros((UPSAMPLE_SIZE, UPSAMPLE_SIZE)) half = UPSAMPLE_SIZE // 2 if object_type == "triangle": for i in range(UPSAMPLE_SIZE): for j in range(UPSAMPLE_SIZE): if (j <= half and i >= 2 * (half - j)) or (j > half and i >= 2 * (j - half)): template[i, j] = 1. elif object_type == "square": template[:, :] = 1. elif object_type == "empty_square": template[:2, :] = 1. template[-2:, :] = 1. template[:, :2] = 1. template[:, -2:] = 1. elif object_type == "plus": template[:, half - 1:half + 2] = 1. template[half - 1:half + 2, :] = 1. elif object_type == "inverse_plus": template[:, :] = 1. template[:, half - 1:half + 2] = 0. template[half - 1:half + 2, :] = 0. elif object_type == "ex": for i in range(UPSAMPLE_SIZE): for j in range(UPSAMPLE_SIZE): if abs(i - j) <= 1 or abs(UPSAMPLE_SIZE - 1 - j - i) <= 1: template[i, j] = 1. elif object_type == "inverse_ex": for i in range(UPSAMPLE_SIZE): for j in range(UPSAMPLE_SIZE): if not (abs(i - j) <= 1 or abs(UPSAMPLE_SIZE - 1 - j - i) <= 1): template[i, j] = 1. elif object_type == "circle": for i in range(UPSAMPLE_SIZE): for j in range(UPSAMPLE_SIZE): if (i - half)**2 + (j - half)**2 <= half**2: template[i, j] = 1. elif object_type == "empty_circle": for i in range(UPSAMPLE_SIZE): for j in range(UPSAMPLE_SIZE): if abs((i - half)**2 + (j - half)**2 - half**2) < 6: template[i, j] = 1. elif object_type == "tee": template[:, half - 1:half + 2] = 1. template[:3, :] = 1. elif object_type == "upside_down_tee": template[:, half - 1:half + 2] = 1. template[-3:, :] = 1. elif object_type == "h": template[:, :3] = 1. template[:, -3:] = 1. template[half - 1:half + 2, :] = 1. elif object_type == "u": template[:, :3] = 1. template[:, -3:] = 1. template[-3:, :] = 1. elif object_type == "upside_down_u": template[:, :3] = 1. template[:, -3:] = 1. template[:3, :] = 1. elif object_type == "vertical_stripes": for j in range(half + UPSAMPLE_SIZE % 2): template[:, 2*j] = 1. elif object_type == "horizontal_stripes": for i in range(half + UPSAMPLE_SIZE % 2): template[2*i, :] = 1. else: raise ValueError("Unknown object: {}".format(object_type)) texture = np.ones_like(template) offset = UPSAMPLE_SIZE % 2 if object_texture == "horizontal_stripes": texture[offset::2, :] = 0. elif object_texture == "vertical_stripes": texture[:, offset::2] = 0. elif object_texture == "grid": texture[:, :] = 0. texture[offset::2, :] = 1. texture[:, offset::2] = 1. elif object_texture == "checker": texture[offset::2, ::2] = 0. texture[::2, offset::2] = 0. elif object_texture == "noise": texture = np.random.binomial(1, 0.66, texture.shape) elif object_texture != "solid": raise ValueError("Unknown texture: {}".format(object_texture)) if object_color not in COLORS: raise ValueError("Unknown color: {}".format(object_color)) template = template * texture template = np.tensordot(template, COLORS[object_color], axes=0) return template # Agent, wall, and floor templates _CHAR_TO_TEMPLATE_BASE = { _env_core.AGENT_CHAR: np.tensordot( np.ones([UPSAMPLE_SIZE, UPSAMPLE_SIZE]), np.array([255, 255, 255]), axes=0), _env_core.WALL_CHAR: np.tensordot( np.ones([UPSAMPLE_SIZE, UPSAMPLE_SIZE]), np.array([40, 40, 40]), axes=0), ## FLOOR_CHAR is now skipped, for efficiency } class OddOneOutEnvironment(dm_env.Environment): """A dm_env version of Odd One Out, including pixel observations etc.""" def __init__( self, game_factory, max_steps=_env_core.EPISODE_LENGTH, rng=None): """Construct a dm_env-compatible wrapper for pycolab games for agent use. This class inherits from dm_env and has all the expected methods and specs. It also renders the game from ascii art to pixel observations. Args: game_factory: A function that when called returns a new pycolab core game. max_steps: The maximum number of steps to allow in an episode, after which it will terminate. rng: An optional numpy Random Generator, to set a fixed seed use e.g. `rng=np.random.default_rng(seed=...)` """ self._game_factory = game_factory self._max_steps = max_steps # internal state if rng is None: rng = np.random.default_rng() self._rng = rng self._current_game = None # Current pycolab game instance. self._state = None # Current game step state. self._game_over = None # Whether the game has ended. self._char_to_template = None # Mapping of chars to images. self._cue_template = None # rendering tools self._cropper = cropping.ScrollingCropper( rows=SCROLL_CROP_SIZE, cols=SCROLL_CROP_SIZE, to_track=[_env_core.AGENT_CHAR], pad_char=_env_core.FLOOR_CHAR, scroll_margins=(None, None)) def _render_observation(self, observation): """Renders from raw pycolab image observation to agent-usable pixel ones.""" observation = self._cropper.crop(observation) obs_rows, obs_cols = observation.board.shape image = np.zeros([obs_rows * UPSAMPLE_SIZE, obs_cols * UPSAMPLE_SIZE, 3], dtype=np.float32) for i in range(obs_rows): for j in range(obs_cols): this_char = chr(observation.board[i, j]) if this_char != _env_core.FLOOR_CHAR: image[ i * UPSAMPLE_SIZE:(i + 1) * UPSAMPLE_SIZE, j * UPSAMPLE_SIZE:(j + 1) * UPSAMPLE_SIZE] = self._char_to_template[ this_char] image /= 255. # explanation observation explanation = np.array(self._current_game.the_plot["explanation_string"]) return (image, explanation) def _update_char_to_template(self): self._char_to_template = { k: _generate_template(v) for k, v in self._current_game.the_plot[ "char_to_color_shape"].items()} self._char_to_template.update(_CHAR_TO_TEMPLATE_BASE) def reset(self): """Start a new episode.""" # clear old state self._state = None self._current_game = None self._char_to_template = None self._game_over = None # Build a new game and retrieve its first set of state/reward/discount. self._current_game = self._game_factory() # set up rendering, cropping, and state for current game self._update_char_to_template() self._cropper.set_engine(self._current_game) self._state = dm_env.StepType.FIRST # let's go! observation, _, _ = self._current_game.its_showtime() observation = self._render_observation(observation) return dm_env.restart(observation) def step(self, action): """Apply action, step the world forward, and return observations.""" # If needed, reset and start new episode. if self._current_game is None or self._state.last(): return self.reset() # Execute the action in pycolab. observation, reward, discount = self._current_game.play(action) if self._current_game.the_plot["char_to_color_shape_updated"]: self._update_char_to_template() self._game_over = self._is_game_over() reward = reward if reward is not None else 0. observation = self._render_observation(observation) # Check the current status of the game. if self._game_over: self._state = dm_env.StepType.LAST else: self._state = dm_env.StepType.MID return dm_env.TimeStep( step_type=self._state, reward=reward, discount=discount, observation=observation) def observation_spec(self): image_shape = (SCROLL_CROP_SIZE * UPSAMPLE_SIZE, SCROLL_CROP_SIZE * UPSAMPLE_SIZE, 3) return ( # vision dm_env.specs.Array( shape=image_shape, dtype=np.float32, name="image"), # explanation dm_env.specs.Array( shape=[], dtype=str, name="explanation"), ) def action_spec(self): return dm_env.specs.BoundedArray( shape=[], dtype="int32", minimum=0, maximum=7, name="grid_actions") def _is_game_over(self): """Returns whether it is game over, either from the engine or timeout.""" return (self._current_game.game_over or (self._current_game.the_plot.frame >= self._max_steps)) class MetaOddOneOutEnvironment(OddOneOutEnvironment): """For metalearning version, tweaks to actions + observations.""" def _render_observation(self, observation): """Renders from raw pycolab image observation to agent-usable pixel ones.""" base_obs = super()._render_observation(observation) instruction = np.array(self._current_game.the_plot["instruction_string"]) return (*base_obs, instruction) def observation_spec(self): base_spec = super().observation_spec() return ( *base_spec, # instruction dm_env.specs.Array( shape=[], dtype=str, name="instruction"), ) def action_spec(self): return dm_env.specs.BoundedArray( shape=[], dtype="int32", minimum=0, maximum=10, name="grid_and_transform_actions") def builder(concept_type="shape", explain="full", rng=None): """Build a game factory and dm_env wrapper around the basic odd one out tasks. Args: concept_type: concept type, one of ["color", "shape", "texture", "position"] explain: How to explain, one of ["full", "properties", "reward", or "none"] rng: An optional numpy Random Generator, to set a fixed seed use e.g. `rng=np.random.default_rng(seed=...)` Returns: OddOneOutEnvironment object for the specified level. """ if concept_type not in ["shape", "color", "texture", "position"]: raise NotImplementedError( "Level construction with concepts other than shape, color, texture, or " "position is not yet supported.") if rng is None: rng = np.random.default_rng() position_types = list(_env_core.OBJECT_POSITIONS.keys()) positions = copy.deepcopy(_env_core.OBJECT_POSITIONS) colors = list(COLORS) shapes = OBJECT_SHAPES.copy() textures = OBJECT_TEXTURES.copy() def _game_factory(): """Samples pairing and positions, returns a game.""" target_object_index = rng.integers(4) rng.shuffle(position_types) for v in positions.values(): rng.shuffle(v) rng.shuffle(colors) rng.shuffle(textures) rng.shuffle(shapes) if concept_type == "color": these_colors = [colors[0]] * 4 these_colors[target_object_index] = colors[1] else: these_colors = [colors[0]] * 2 + [colors[1]] * 2 rng.shuffle(these_colors) if concept_type == "texture": these_textures = [textures[0]] * 4 these_textures[target_object_index] = textures[1] else: these_textures = [textures[0]] * 2 + [textures[1]] * 2 rng.shuffle(these_textures) if concept_type == "shape": these_shapes = [shapes[0]] * 4 these_shapes[target_object_index] = shapes[1] else: these_shapes = [shapes[0]] * 2 + [shapes[1]] * 2 rng.shuffle(these_shapes) if concept_type == "position": these_position_types = [position_types[0]] * 4 these_position_types[target_object_index] = position_types[1] else: these_position_types = [position_types[0]] * 2 + [position_types[1]] * 2 rng.shuffle(these_position_types) object_properties = [] for object_i in range(4): if object_i == target_object_index: value = 1. else: value = 0. # choose a position of this type position = positions[these_position_types[object_i]][object_i] object_properties.append( _env_core.ObjectProperties( character=_env_core.POSSIBLE_OBJECT_CHARS[object_i], position=position, position_type=these_position_types[object_i], shape=these_shapes[object_i], color=these_colors[object_i], texture=these_textures[object_i], value=value)) logging.info("Making level with object_properties: %s", object_properties) return _env_core.make_game( object_properties=object_properties, concept_type=concept_type, explain=explain, rng=rng) return OddOneOutEnvironment( game_factory=_game_factory, rng=rng) def metalearning_builder(num_trials_before_test=3, intervention_type="easy", concept_type="shape", explain="full", rng=None): """Builds a meta-learning environment with several experiment trials + test. Args: num_trials_before_test: how many "experiment" trials to have, for the agent to figure out the task intervention_type: whether the intervention levels are easy (all objects the same, change one and take it) or hard{1,2,3} (all objects differ in pairs, along 1, 2, or 3 dimension, so if you change one you have to take its pair that you've made the odd one out). concept_type: concept type, see _env_core.MetaOddOneOutEnvironment. explain: How to explain, see _env_core.MetaOddOneOutEnvironment. rng: An optional numpy Random Generator, to set a fixed seed use e.g. `rng=np.random.default_rng(seed=...)` Returns: MetaOddOneOutEnvironment object for the specified level. """ if concept_type not in ["shape", "color", "texture"]: raise NotImplementedError( "The currently supported concepts are shape, color, or texture.") if rng is None: rng = np.random.default_rng() position_types = list(_env_core.OBJECT_POSITIONS.keys()) positions = copy.deepcopy(_env_core.OBJECT_POSITIONS) colors = list(COLORS.keys()) shapes = OBJECT_SHAPES.copy() textures = OBJECT_TEXTURES.copy() def _level_factory(level_type="regular", level_args=None): if level_args is None: level_args = {} if level_type == "deconfounded": target_indices = rng.permutation(4) if concept_type == "color": target_object_index = target_indices[0] elif concept_type == "texture": target_object_index = target_indices[1] elif concept_type == "shape": target_object_index = target_indices[2] else: raise ValueError() else: target_object_index = rng.integers(4) rng.shuffle(position_types) for v in positions.values(): rng.shuffle(v) rng.shuffle(colors) rng.shuffle(textures) rng.shuffle(shapes) additional_extant_properties = {} if level_type[:-1] == "intervention_hard": num_hard_dimensions = int(level_type[-1]) assert num_hard_dimensions in [1, 2, 3] hard_dimensions = ["color", "texture", "shape"] rng.shuffle(hard_dimensions) hard_dimensions = hard_dimensions[:num_hard_dimensions] else: num_hard_dimensions = 0 hard_dimensions = [] if "intervention" in level_type: if "color" in hard_dimensions: these_colors = [colors[0]] * 2 + [colors[1]] * 2 rng.shuffle(these_colors) else: these_colors = [colors[0]] * 4 additional_extant_properties["color"] = [colors[1]] elif level_type == "deconfounded": these_colors = [colors[0]] * 4 these_colors[target_indices[0]] = colors[1] elif concept_type == "color": these_colors = [colors[0]] * 4 these_colors[target_object_index] = colors[1] else: these_colors = [colors[0]] * 2 + [colors[1]] * 2 rng.shuffle(these_colors) if "intervention" in level_type: if "texture" in hard_dimensions: these_textures = [textures[0]] * 2 + [textures[1]] * 2 rng.shuffle(these_textures) else: these_textures = [textures[0]] * 4 additional_extant_properties["texture"] = [textures[1]] elif level_type == "deconfounded": these_textures = [textures[0]] * 4 these_textures[target_indices[1]] = textures[1] elif concept_type == "texture": these_textures = [textures[0]] * 4 these_textures[target_object_index] = textures[1] else: these_textures = [textures[0]] * 2 + [textures[1]] * 2 rng.shuffle(these_textures) if "intervention" in level_type: if "shape" in hard_dimensions: these_shapes = [shapes[0]] * 2 + [shapes[1]] * 2 rng.shuffle(these_shapes) else: these_shapes = [shapes[0]] * 4 additional_extant_properties["shape"] = [shapes[1]] elif level_type == "deconfounded": these_shapes = [shapes[0]] * 4 these_shapes[target_indices[2]] = shapes[1] elif concept_type == "shape": these_shapes = [shapes[0]] * 4 these_shapes[target_object_index] = shapes[1] else: these_shapes = [shapes[0]] * 2 + [shapes[1]] * 2 rng.shuffle(these_shapes) these_position_types = [position_types[0]] * 4 object_properties = [] for object_i in range(4): if object_i == target_object_index and "intervention" not in level_type: value = 1. else: value = 0. # choose a (distinct) position of this type position = positions[these_position_types[object_i]][object_i] object_properties.append( _env_core.ObjectProperties( character=_env_core.POSSIBLE_OBJECT_CHARS[object_i], position=position, position_type=these_position_types[object_i], shape=these_shapes[object_i], color=these_colors[object_i], texture=these_textures[object_i], value=value)) logging.info("Making metalearning level with level_type: %s and " "object_properties: %s", level_type, object_properties) return _env_core.make_metalearning_game( object_properties=object_properties, concept_type=concept_type, explain=explain, additional_extant_properties=additional_extant_properties, rng=rng, **level_args) intervention_level = "intervention_" + intervention_type def _progressive_game_factory(): level_constructors = {} for i in range(num_trials_before_test): level_constructors[i] = functools.partial( _level_factory, intervention_level, dict( transformations_allowed=1, value_multiplier=EXPERIMENT_REWARD_MULT, next_progressive_level=i + 1)) i = num_trials_before_test level_constructors[i] = functools.partial( _level_factory, "deconfounded", dict( transformations_allowed=0, value_multiplier=TEST_REWARD_MULT, next_progressive_level=None)) this_story = storytelling.Story( chapters=level_constructors, first_chapter=0) return this_story num_sub_episodes = num_trials_before_test + 1 return MetaOddOneOutEnvironment( game_factory=_progressive_game_factory, max_steps=num_sub_episodes * _env_core.EPISODE_LENGTH, rng=rng) def confounding_builder(confounding, concept_type, explain="none", rng=None): """Build a game factory and dm_env wrapper around the (de)confounding tasks. Args: confounding: one of ["confounded", "deconfounded"]. concept_type: concept type, one of ["color", "shape", "texture"]. explain: How to explain, one of ["full", "properties", "reward", or "none"]. rng: An optional numpy Random Generator, to set a fixed seed use e.g. `rng=np.random.default_rng(seed=...)` Returns: OddOneOutEnvironment object for the specified level. """ if rng is None: rng = np.random.default_rng() position_types = list(_env_core.OBJECT_POSITIONS.keys()) positions = copy.deepcopy(_env_core.OBJECT_POSITIONS) colors = list(COLORS.keys()) shapes = OBJECT_SHAPES.copy() textures = OBJECT_TEXTURES.copy() def _game_factory(): target_indices = rng.permutation(4) # fixed assignment of indices (in this ordering) to attributes, # for deconfounded version. if concept_type == "color": target_object_index = target_indices[0] elif concept_type == "texture": target_object_index = target_indices[1] elif concept_type == "shape": target_object_index = target_indices[2] elif concept_type == "position": target_object_index = target_indices[3] rng.shuffle(position_types) for v in positions.values(): rng.shuffle(v) rng.shuffle(colors) rng.shuffle(textures) rng.shuffle(shapes) these_colors = [colors[0]] * 4 if concept_type == "color" or confounding == "confounded": these_colors[target_object_index] = colors[1] else: # confounding == "deconfounded" these_colors[target_indices[0]] = colors[1] these_textures = [textures[0]] * 4 if concept_type == "texture" or confounding == "confounded": these_textures[target_object_index] = textures[1] else: these_textures[target_indices[1]] = textures[1] these_shapes = [shapes[0]] * 4 if concept_type == "shape" or confounding == "confounded": these_shapes[target_object_index] = shapes[1] else: these_shapes[target_indices[2]] = shapes[1] these_position_types = [position_types[0]] * 4 object_properties = [] for object_i in range(4): if object_i == target_object_index: value = 1. else: value = 0. # choose a position of this type position = positions[these_position_types[object_i]][object_i] object_properties.append( _env_core.ObjectProperties( character=_env_core.POSSIBLE_OBJECT_CHARS[object_i], position=position, position_type=these_position_types[object_i], shape=these_shapes[object_i], color=these_colors[object_i], texture=these_textures[object_i], value=value)) logging.info("Making level with confounding: %s and " "object_properties: %s", confounding, object_properties) return _env_core.make_game( object_properties=object_properties, concept_type=concept_type, explain=explain, explain_only_concept_type=True) return OddOneOutEnvironment( game_factory=_game_factory, rng=rng) def from_name(level_name): """Simplifies building basic levels from fixed defs.""" if level_name[:4] == "meta": (_, num_experiment_trials, intervention_type, concept_type, explain) = level_name.split("_") num_experiment_trials = int(num_experiment_trials) return metalearning_builder( num_trials_before_test=num_experiment_trials, intervention_type=intervention_type, concept_type=concept_type, explain=explain) elif "confound" in level_name: confounding, concept_type, explain = level_name.split("_") return confounding_builder(confounding, concept_type, explain) else: concept_type, explain = level_name.split("_") return builder(concept_type, explain)
tell_me_why_explanations_rl-main
tell_me_why_explanations_rl/odd_one_out_environment.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """An example that builds and steps a few different environments.""" from tell_me_why_explanations_rl import odd_one_out_environment train_levels = ['color_full', 'shape_full', 'texture_full', 'position_full'] train_envs = [odd_one_out_environment.from_name(l) for l in train_levels] # try one out print(f'Loading environment {train_levels[0]}.') env = train_envs[0] timestep = env.reset() for action in range(8): timestep = env.step(action) print('Environment ran successfully.')
tell_me_why_explanations_rl-main
examples/example.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Ensembles of place and head direction cells. These classes provide the targets for the training of grid-cell networks. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf def one_hot_max(x, axis=-1): """Compute one-hot vectors setting to one the index with the maximum value.""" return tf.one_hot(tf.argmax(x, axis=axis), depth=x.get_shape()[-1], dtype=x.dtype) def softmax(x, axis=-1): """Compute softmax values for each sets of scores in x.""" return tf.nn.softmax(x, dim=axis) def softmax_sample(x): """Sample the categorical distribution from logits and sample it.""" dist = tf.contrib.distributions.OneHotCategorical(logits=x, dtype=tf.float32) return dist.sample() class CellEnsemble(object): """Abstract parent class for place and head direction cell ensembles.""" def __init__(self, n_cells, soft_targets, soft_init): self.n_cells = n_cells if soft_targets not in ["softmax", "voronoi", "sample", "normalized"]: raise ValueError else: self.soft_targets = soft_targets # Provide initialization of LSTM in the same way as targets if not specified # i.e one-hot if targets are Voronoi if soft_init is None: self.soft_init = soft_targets else: if soft_init not in [ "softmax", "voronoi", "sample", "normalized", "zeros" ]: raise ValueError else: self.soft_init = soft_init def get_targets(self, x): """Type of target.""" if self.soft_targets == "normalized": targets = tf.exp(self.unnor_logpdf(x)) elif self.soft_targets == "softmax": lp = self.log_posterior(x) targets = softmax(lp) elif self.soft_targets == "sample": lp = self.log_posterior(x) targets = softmax_sample(lp) elif self.soft_targets == "voronoi": lp = self.log_posterior(x) targets = one_hot_max(lp) return targets def get_init(self, x): """Type of initialisation.""" if self.soft_init == "normalized": init = tf.exp(self.unnor_logpdf(x)) elif self.soft_init == "softmax": lp = self.log_posterior(x) init = softmax(lp) elif self.soft_init == "sample": lp = self.log_posterior(x) init = softmax_sample(lp) elif self.soft_init == "voronoi": lp = self.log_posterior(x) init = one_hot_max(lp) elif self.soft_init == "zeros": init = tf.zeros_like(self.unnor_logpdf(x)) return init def loss(self, predictions, targets): """Loss.""" if self.soft_targets == "normalized": smoothing = 1e-2 loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=(1. - smoothing) * targets + smoothing * 0.5, logits=predictions, name="ensemble_loss") loss = tf.reduce_mean(loss, axis=-1) else: loss = tf.nn.softmax_cross_entropy_with_logits( labels=targets, logits=predictions, name="ensemble_loss") return loss def log_posterior(self, x): logp = self.unnor_logpdf(x) log_posteriors = logp - tf.reduce_logsumexp(logp, axis=2, keep_dims=True) return log_posteriors class PlaceCellEnsemble(CellEnsemble): """Calculates the dist over place cells given an absolute position.""" def __init__(self, n_cells, stdev=0.35, pos_min=-5, pos_max=5, seed=None, soft_targets=None, soft_init=None): super(PlaceCellEnsemble, self).__init__(n_cells, soft_targets, soft_init) # Create a random MoG with fixed cov over the position (Nx2) rs = np.random.RandomState(seed) self.means = rs.uniform(pos_min, pos_max, size=(self.n_cells, 2)) self.variances = np.ones_like(self.means) * stdev**2 def unnor_logpdf(self, trajs): # Output the probability of each component at each point (BxTxN) diff = trajs[:, :, tf.newaxis, :] - self.means[np.newaxis, np.newaxis, ...] unnor_logp = -0.5 * tf.reduce_sum((diff**2)/ self.variances, axis=-1) return unnor_logp class HeadDirectionCellEnsemble(CellEnsemble): """Calculates the dist over HD cells given an absolute angle.""" def __init__(self, n_cells, concentration=20, seed=None, soft_targets=None, soft_init=None): super(HeadDirectionCellEnsemble, self).__init__(n_cells, soft_targets, soft_init) # Create a random Von Mises with fixed cov over the position rs = np.random.RandomState(seed) self.means = rs.uniform(-np.pi, np.pi, (n_cells)) self.kappa = np.ones_like(self.means) * concentration def unnor_logpdf(self, x): return self.kappa * tf.cos(x - self.means[np.newaxis, np.newaxis, :])
grid-cells-master
ensembles.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Model for grid cells supervised training. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy import sonnet as snt import tensorflow as tf def displaced_linear_initializer(input_size, displace, dtype=tf.float32): stddev = 1. / numpy.sqrt(input_size) return tf.truncated_normal_initializer( mean=displace*stddev, stddev=stddev, dtype=dtype) class GridCellsRNNCell(snt.RNNCore): """LSTM core implementation for the grid cell network.""" def __init__(self, target_ensembles, nh_lstm, nh_bottleneck, nh_embed=None, dropoutrates_bottleneck=None, bottleneck_weight_decay=0.0, bottleneck_has_bias=False, init_weight_disp=0.0, name="grid_cells_core"): """Constructor of the RNN cell. Args: target_ensembles: Targets, place cells and head direction cells. nh_lstm: Size of LSTM cell. nh_bottleneck: Size of the linear layer between LSTM output and output. nh_embed: Number of hiddens between input and LSTM input. dropoutrates_bottleneck: Iterable of keep rates (0,1]. The linear layer is partitioned into as many groups as the len of this parameter. bottleneck_weight_decay: Weight decay used in the bottleneck layer. bottleneck_has_bias: If the bottleneck has a bias. init_weight_disp: Displacement in the weights initialisation. name: the name of the module. """ super(GridCellsRNNCell, self).__init__(name=name) self._target_ensembles = target_ensembles self._nh_embed = nh_embed self._nh_lstm = nh_lstm self._nh_bottleneck = nh_bottleneck self._dropoutrates_bottleneck = dropoutrates_bottleneck self._bottleneck_weight_decay = bottleneck_weight_decay self._bottleneck_has_bias = bottleneck_has_bias self._init_weight_disp = init_weight_disp self.training = False with self._enter_variable_scope(): self._lstm = snt.LSTM(self._nh_lstm) def _build(self, inputs, prev_state): """Build the module. Args: inputs: Egocentric velocity (BxN) prev_state: Previous state of the recurrent network Returns: ((predictions, bottleneck, lstm_outputs), next_state) The predictions """ conc_inputs = tf.concat(inputs, axis=1, name="conc_inputs") # Embedding layer lstm_inputs = conc_inputs # LSTM lstm_output, next_state = self._lstm(lstm_inputs, prev_state) # Bottleneck bottleneck = snt.Linear(self._nh_bottleneck, use_bias=self._bottleneck_has_bias, regularizers={ "w": tf.contrib.layers.l2_regularizer( self._bottleneck_weight_decay)}, name="bottleneck")(lstm_output) if self.training and self._dropoutrates_bottleneck is not None: tf.logging.info("Adding dropout layers") n_scales = len(self._dropoutrates_bottleneck) scale_pops = tf.split(bottleneck, n_scales, axis=1) dropped_pops = [tf.nn.dropout(pop, rate, name="dropout") for rate, pop in zip(self._dropoutrates_bottleneck, scale_pops)] bottleneck = tf.concat(dropped_pops, axis=1) # Outputs ens_outputs = [snt.Linear( ens.n_cells, regularizers={ "w": tf.contrib.layers.l2_regularizer( self._bottleneck_weight_decay)}, initializers={ "w": displaced_linear_initializer(self._nh_bottleneck, self._init_weight_disp, dtype=tf.float32)}, name="pc_logits")(bottleneck) for ens in self._target_ensembles] return (ens_outputs, bottleneck, lstm_output), tuple(list(next_state)) @property def state_size(self): """Returns a description of the state size, without batch dimension.""" return self._lstm.state_size @property def output_size(self): """Returns a description of the output size, without batch dimension.""" return tuple([ens.n_cells for ens in self._target_ensembles] + [self._nh_bottleneck, self._nh_lstm]) class GridCellsRNN(snt.AbstractModule): """RNN computes place and head-direction cell predictions from velocities.""" def __init__(self, rnn_cell, nh_lstm, name="grid_cell_supervised"): super(GridCellsRNN, self).__init__(name=name) self._core = rnn_cell self._nh_lstm = nh_lstm def _build(self, init_conds, vels, training=False): """Outputs place, and head direction cell predictions from velocity inputs. Args: init_conds: Initial conditions given by ensemble activatons, list [BxN_i] vels: Translational and angular velocities [BxTxV] training: Activates and deactivates dropout Returns: [logits_i]: logits_i: Logits predicting i-th ensemble activations (BxTxN_i) """ # Calculate initialization for LSTM. Concatenate pc and hdc activations concat_init = tf.concat(init_conds, axis=1) init_lstm_state = snt.Linear(self._nh_lstm, name="state_init")(concat_init) init_lstm_cell = snt.Linear(self._nh_lstm, name="cell_init")(concat_init) self._core.training = training # Run LSTM output_seq, final_state = tf.nn.dynamic_rnn(cell=self._core, inputs=(vels,), time_major=False, initial_state=(init_lstm_state, init_lstm_cell)) ens_targets = output_seq[:-2] bottleneck = output_seq[-2] lstm_output = output_seq[-1] # Return return (ens_targets, bottleneck, lstm_output), final_state def get_all_variables(self): return (super(GridCellsRNN, self).get_variables() + self._core.get_variables())
grid-cells-master
model.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Helper functions for creating the training graph and plotting. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import ensembles # pylint: disable=g-bad-import-order np.seterr(invalid="ignore") def get_place_cell_ensembles( env_size, neurons_seed, targets_type, lstm_init_type, n_pc, pc_scale): """Create the ensembles for the Place cells.""" place_cell_ensembles = [ ensembles.PlaceCellEnsemble( n, stdev=s, pos_min=-env_size / 2.0, pos_max=env_size / 2.0, seed=neurons_seed, soft_targets=targets_type, soft_init=lstm_init_type) for n, s in zip(n_pc, pc_scale) ] return place_cell_ensembles def get_head_direction_ensembles( neurons_seed, targets_type, lstm_init_type, n_hdc, hdc_concentration): """Create the ensembles for the Head direction cells.""" head_direction_ensembles = [ ensembles.HeadDirectionCellEnsemble( n, concentration=con, seed=neurons_seed, soft_targets=targets_type, soft_init=lstm_init_type) for n, con in zip(n_hdc, hdc_concentration) ] return head_direction_ensembles def encode_initial_conditions(init_pos, init_hd, place_cell_ensembles, head_direction_ensembles): initial_conds = [] for ens in place_cell_ensembles: initial_conds.append( tf.squeeze(ens.get_init(init_pos[:, tf.newaxis, :]), axis=1)) for ens in head_direction_ensembles: initial_conds.append( tf.squeeze(ens.get_init(init_hd[:, tf.newaxis, :]), axis=1)) return initial_conds def encode_targets(target_pos, target_hd, place_cell_ensembles, head_direction_ensembles): ensembles_targets = [] for ens in place_cell_ensembles: ensembles_targets.append(ens.get_targets(target_pos)) for ens in head_direction_ensembles: ensembles_targets.append(ens.get_targets(target_hd)) return ensembles_targets def clip_all_gradients(g, var, limit): # print(var.name) return (tf.clip_by_value(g, -limit, limit), var) def clip_bottleneck_gradient(g, var, limit): if ("bottleneck" in var.name or "pc_logits" in var.name): return (tf.clip_by_value(g, -limit, limit), var) else: return (g, var) def no_clipping(g, var): return (g, var) def concat_dict(acc, new_data): """Dictionary concatenation function.""" def to_array(kk): if isinstance(kk, np.ndarray): return kk else: return np.asarray([kk]) for k, v in new_data.iteritems(): if isinstance(v, dict): if k in acc: acc[k] = concat_dict(acc[k], v) else: acc[k] = concat_dict(dict(), v) else: v = to_array(v) if k in acc: acc[k] = np.concatenate([acc[k], v]) else: acc[k] = np.copy(v) return acc def get_scores_and_plot(scorer, data_abs_xy, activations, directory, filename, plot_graphs=True, # pylint: disable=unused-argument nbins=20, # pylint: disable=unused-argument cm="jet", sort_by_score_60=True): """Plotting function.""" # Concatenate all trajectories xy = data_abs_xy.reshape(-1, data_abs_xy.shape[-1]) act = activations.reshape(-1, activations.shape[-1]) n_units = act.shape[1] # Get the rate-map for each unit s = [ scorer.calculate_ratemap(xy[:, 0], xy[:, 1], act[:, i]) for i in xrange(n_units) ] # Get the scores score_60, score_90, max_60_mask, max_90_mask, sac = zip( *[scorer.get_scores(rate_map) for rate_map in s]) # Separations # separations = map(np.mean, max_60_mask) # Sort by score if desired if sort_by_score_60: ordering = np.argsort(-np.array(score_60)) else: ordering = range(n_units) # Plot cols = 16 rows = int(np.ceil(n_units / cols)) fig = plt.figure(figsize=(24, rows * 4)) for i in xrange(n_units): rf = plt.subplot(rows * 2, cols, i + 1) acr = plt.subplot(rows * 2, cols, n_units + i + 1) if i < n_units: index = ordering[i] title = "%d (%.2f)" % (index, score_60[index]) # Plot the activation maps scorer.plot_ratemap(s[index], ax=rf, title=title, cmap=cm) # Plot the autocorrelation of the activation maps scorer.plot_sac( sac[index], mask_params=max_60_mask[index], ax=acr, title=title, cmap=cm) # Save if not os.path.exists(directory): os.makedirs(directory) with PdfPages(os.path.join(directory, filename), "w") as f: plt.savefig(f, format="pdf") plt.close(fig) return (np.asarray(score_60), np.asarray(score_90), np.asarray(map(np.mean, max_60_mask)), np.asarray(map(np.mean, max_90_mask)))
grid-cells-master
utils.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Supervised training for the Grid cell network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import matplotlib import numpy as np import tensorflow as tf import Tkinter # pylint: disable=unused-import matplotlib.use('Agg') import dataset_reader # pylint: disable=g-bad-import-order, g-import-not-at-top import model # pylint: disable=g-bad-import-order import scores # pylint: disable=g-bad-import-order import utils # pylint: disable=g-bad-import-order # Task config tf.flags.DEFINE_string('task_dataset_info', 'square_room', 'Name of the room in which the experiment is performed.') tf.flags.DEFINE_string('task_root', None, 'Dataset path.') tf.flags.DEFINE_float('task_env_size', 2.2, 'Environment size (meters).') tf.flags.DEFINE_list('task_n_pc', [256], 'Number of target place cells.') tf.flags.DEFINE_list('task_pc_scale', [0.01], 'Place cell standard deviation parameter (meters).') tf.flags.DEFINE_list('task_n_hdc', [12], 'Number of target head direction cells.') tf.flags.DEFINE_list('task_hdc_concentration', [20.], 'Head direction concentration parameter.') tf.flags.DEFINE_integer('task_neurons_seed', 8341, 'Seeds.') tf.flags.DEFINE_string('task_targets_type', 'softmax', 'Type of target, soft or hard.') tf.flags.DEFINE_string('task_lstm_init_type', 'softmax', 'Type of LSTM initialisation, soft or hard.') tf.flags.DEFINE_bool('task_velocity_inputs', True, 'Input velocity.') tf.flags.DEFINE_list('task_velocity_noise', [0.0, 0.0, 0.0], 'Add noise to velocity.') # Model config tf.flags.DEFINE_integer('model_nh_lstm', 128, 'Number of hidden units in LSTM.') tf.flags.DEFINE_integer('model_nh_bottleneck', 256, 'Number of hidden units in linear bottleneck.') tf.flags.DEFINE_list('model_dropout_rates', [0.5], 'List of floats with dropout rates.') tf.flags.DEFINE_float('model_weight_decay', 1e-5, 'Weight decay regularisation') tf.flags.DEFINE_bool('model_bottleneck_has_bias', False, 'Whether to include a bias in linear bottleneck') tf.flags.DEFINE_float('model_init_weight_disp', 0.0, 'Initial weight displacement.') # Training config tf.flags.DEFINE_integer('training_epochs', 1000, 'Number of training epochs.') tf.flags.DEFINE_integer('training_steps_per_epoch', 1000, 'Number of optimization steps per epoch.') tf.flags.DEFINE_integer('training_minibatch_size', 10, 'Size of the training minibatch.') tf.flags.DEFINE_integer('training_evaluation_minibatch_size', 4000, 'Size of the minibatch during evaluation.') tf.flags.DEFINE_string('training_clipping_function', 'utils.clip_all_gradients', 'Function for gradient clipping.') tf.flags.DEFINE_float('training_clipping', 1e-5, 'The absolute value to clip by.') tf.flags.DEFINE_string('training_optimizer_class', 'tf.train.RMSPropOptimizer', 'The optimizer used for training.') tf.flags.DEFINE_string('training_optimizer_options', '{"learning_rate": 1e-5, "momentum": 0.9}', 'Defines a dict with opts passed to the optimizer.') # Store tf.flags.DEFINE_string('saver_results_directory', None, 'Path to directory for saving results.') tf.flags.DEFINE_integer('saver_eval_time', 2, 'Frequency at which results are saved.') # Require flags tf.flags.mark_flag_as_required('task_root') tf.flags.mark_flag_as_required('saver_results_directory') FLAGS = tf.flags.FLAGS def train(): """Training loop.""" tf.reset_default_graph() # Create the motion models for training and evaluation data_reader = dataset_reader.DataReader( FLAGS.task_dataset_info, root=FLAGS.task_root, num_threads=4) train_traj = data_reader.read(batch_size=FLAGS.training_minibatch_size) # Create the ensembles that provide targets during training place_cell_ensembles = utils.get_place_cell_ensembles( env_size=FLAGS.task_env_size, neurons_seed=FLAGS.task_neurons_seed, targets_type=FLAGS.task_targets_type, lstm_init_type=FLAGS.task_lstm_init_type, n_pc=FLAGS.task_n_pc, pc_scale=FLAGS.task_pc_scale) head_direction_ensembles = utils.get_head_direction_ensembles( neurons_seed=FLAGS.task_neurons_seed, targets_type=FLAGS.task_targets_type, lstm_init_type=FLAGS.task_lstm_init_type, n_hdc=FLAGS.task_n_hdc, hdc_concentration=FLAGS.task_hdc_concentration) target_ensembles = place_cell_ensembles + head_direction_ensembles # Model creation rnn_core = model.GridCellsRNNCell( target_ensembles=target_ensembles, nh_lstm=FLAGS.model_nh_lstm, nh_bottleneck=FLAGS.model_nh_bottleneck, dropoutrates_bottleneck=np.array(FLAGS.model_dropout_rates), bottleneck_weight_decay=FLAGS.model_weight_decay, bottleneck_has_bias=FLAGS.model_bottleneck_has_bias, init_weight_disp=FLAGS.model_init_weight_disp) rnn = model.GridCellsRNN(rnn_core, FLAGS.model_nh_lstm) # Get a trajectory batch input_tensors = [] init_pos, init_hd, ego_vel, target_pos, target_hd = train_traj if FLAGS.task_velocity_inputs: # Add the required amount of noise to the velocities vel_noise = tf.distributions.Normal(0.0, 1.0).sample( sample_shape=ego_vel.get_shape()) * FLAGS.task_velocity_noise input_tensors = [ego_vel + vel_noise] + input_tensors # Concatenate all inputs inputs = tf.concat(input_tensors, axis=2) # Replace euclidean positions and angles by encoding of place and hd ensembles # Note that the initial_conds will be zeros if the ensembles were configured # to provide that type of initialization initial_conds = utils.encode_initial_conditions( init_pos, init_hd, place_cell_ensembles, head_direction_ensembles) # Encode targets as well ensembles_targets = utils.encode_targets( target_pos, target_hd, place_cell_ensembles, head_direction_ensembles) # Estimate future encoding of place and hd ensembles inputing egocentric vels outputs, _ = rnn(initial_conds, inputs, training=True) ensembles_logits, bottleneck, lstm_output = outputs # Training loss pc_loss = tf.nn.softmax_cross_entropy_with_logits_v2( labels=ensembles_targets[0], logits=ensembles_logits[0], name='pc_loss') hd_loss = tf.nn.softmax_cross_entropy_with_logits_v2( labels=ensembles_targets[1], logits=ensembles_logits[1], name='hd_loss') total_loss = pc_loss + hd_loss train_loss = tf.reduce_mean(total_loss, name='train_loss') # Optimisation ops optimizer_class = eval(FLAGS.training_optimizer_class) # pylint: disable=eval-used optimizer = optimizer_class(**eval(FLAGS.training_optimizer_options)) # pylint: disable=eval-used grad = optimizer.compute_gradients(train_loss) clip_gradient = eval(FLAGS.training_clipping_function) # pylint: disable=eval-used clipped_grad = [ clip_gradient(g, var, FLAGS.training_clipping) for g, var in grad ] train_op = optimizer.apply_gradients(clipped_grad) # Store the grid scores grid_scores = dict() grid_scores['btln_60'] = np.zeros((FLAGS.model_nh_bottleneck,)) grid_scores['btln_90'] = np.zeros((FLAGS.model_nh_bottleneck,)) grid_scores['btln_60_separation'] = np.zeros((FLAGS.model_nh_bottleneck,)) grid_scores['btln_90_separation'] = np.zeros((FLAGS.model_nh_bottleneck,)) grid_scores['lstm_60'] = np.zeros((FLAGS.model_nh_lstm,)) grid_scores['lstm_90'] = np.zeros((FLAGS.model_nh_lstm,)) # Create scorer objects starts = [0.2] * 10 ends = np.linspace(0.4, 1.0, num=10) masks_parameters = zip(starts, ends.tolist()) latest_epoch_scorer = scores.GridScorer(20, data_reader.get_coord_range(), masks_parameters) with tf.train.SingularMonitoredSession() as sess: for epoch in range(FLAGS.training_epochs): loss_acc = list() for _ in range(FLAGS.training_steps_per_epoch): res = sess.run({'train_op': train_op, 'total_loss': train_loss}) loss_acc.append(res['total_loss']) tf.logging.info('Epoch %i, mean loss %.5f, std loss %.5f', epoch, np.mean(loss_acc), np.std(loss_acc)) if epoch % FLAGS.saver_eval_time == 0: res = dict() for _ in xrange(FLAGS.training_evaluation_minibatch_size // FLAGS.training_minibatch_size): mb_res = sess.run({ 'bottleneck': bottleneck, 'lstm': lstm_output, 'pos_xy': target_pos }) res = utils.concat_dict(res, mb_res) # Store at the end of validation filename = 'rates_and_sac_latest_hd.pdf' grid_scores['btln_60'], grid_scores['btln_90'], grid_scores[ 'btln_60_separation'], grid_scores[ 'btln_90_separation'] = utils.get_scores_and_plot( latest_epoch_scorer, res['pos_xy'], res['bottleneck'], FLAGS.saver_results_directory, filename) def main(unused_argv): tf.logging.set_verbosity(3) # Print INFO log messages. train() if __name__ == '__main__': tf.app.run()
grid-cells-master
train.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Minimal queue based TFRecord reader for the Grid Cell paper.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import tensorflow as tf nest = tf.contrib.framework.nest DatasetInfo = collections.namedtuple( 'DatasetInfo', ['basepath', 'size', 'sequence_length', 'coord_range']) _DATASETS = dict( square_room=DatasetInfo( basepath='square_room_100steps_2.2m_1000000', size=100, sequence_length=100, coord_range=((-1.1, 1.1), (-1.1, 1.1))),) def _get_dataset_files(dateset_info, root): """Generates lists of files for a given dataset version.""" basepath = dateset_info.basepath base = os.path.join(root, basepath) num_files = dateset_info.size template = '{:0%d}-of-{:0%d}.tfrecord' % (4, 4) return [ os.path.join(base, template.format(i, num_files - 1)) for i in range(num_files) ] class DataReader(object): """Minimal queue based TFRecord reader. You can use this reader to load the datasets used to train the grid cell network in the 'Vector-based Navigation using Grid-like Representations in Artificial Agents' paper. See README.md for a description of the datasets and an example of how to use the reader. """ def __init__( self, dataset, root, # Queue params num_threads=4, capacity=256, min_after_dequeue=128, seed=None): """Instantiates a DataReader object and sets up queues for data reading. Args: dataset: string, one of ['jaco', 'mazes', 'rooms_ring_camera', 'rooms_free_camera_no_object_rotations', 'rooms_free_camera_with_object_rotations', 'shepard_metzler_5_parts', 'shepard_metzler_7_parts']. root: string, path to the root folder of the data. num_threads: (optional) integer, number of threads used to feed the reader queues, defaults to 4. capacity: (optional) integer, capacity of the underlying RandomShuffleQueue, defaults to 256. min_after_dequeue: (optional) integer, min_after_dequeue of the underlying RandomShuffleQueue, defaults to 128. seed: (optional) integer, seed for the random number generators used in the reader. Raises: ValueError: if the required version does not exist; """ if dataset not in _DATASETS: raise ValueError('Unrecognized dataset {} requested. Available datasets ' 'are {}'.format(dataset, _DATASETS.keys())) self._dataset_info = _DATASETS[dataset] self._steps = _DATASETS[dataset].sequence_length with tf.device('/cpu'): file_names = _get_dataset_files(self._dataset_info, root) filename_queue = tf.train.string_input_producer(file_names, seed=seed) reader = tf.TFRecordReader() read_ops = [ self._make_read_op(reader, filename_queue) for _ in range(num_threads) ] dtypes = nest.map_structure(lambda x: x.dtype, read_ops[0]) shapes = nest.map_structure(lambda x: x.shape[1:], read_ops[0]) self._queue = tf.RandomShuffleQueue( capacity=capacity, min_after_dequeue=min_after_dequeue, dtypes=dtypes, shapes=shapes, seed=seed) enqueue_ops = [self._queue.enqueue_many(op) for op in read_ops] tf.train.add_queue_runner(tf.train.QueueRunner(self._queue, enqueue_ops)) def read(self, batch_size): """Reads batch_size.""" in_pos, in_hd, ego_vel, target_pos, target_hd = self._queue.dequeue_many( batch_size) return in_pos, in_hd, ego_vel, target_pos, target_hd def get_coord_range(self): return self._dataset_info.coord_range def _make_read_op(self, reader, filename_queue): """Instantiates the ops used to read and parse the data into tensors.""" _, raw_data = reader.read_up_to(filename_queue, num_records=64) feature_map = { 'init_pos': tf.FixedLenFeature(shape=[2], dtype=tf.float32), 'init_hd': tf.FixedLenFeature(shape=[1], dtype=tf.float32), 'ego_vel': tf.FixedLenFeature( shape=[self._dataset_info.sequence_length, 3], dtype=tf.float32), 'target_pos': tf.FixedLenFeature( shape=[self._dataset_info.sequence_length, 2], dtype=tf.float32), 'target_hd': tf.FixedLenFeature( shape=[self._dataset_info.sequence_length, 1], dtype=tf.float32), } example = tf.parse_example(raw_data, feature_map) batch = [ example['init_pos'], example['init_hd'], example['ego_vel'][:, :self._steps, :], example['target_pos'][:, :self._steps, :], example['target_hd'][:, :self._steps, :] ] return batch
grid-cells-master
dataset_reader.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Grid score calculations. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import matplotlib.pyplot as plt import numpy as np import scipy.signal def circle_mask(size, radius, in_val=1.0, out_val=0.0): """Calculating the grid scores with different radius.""" sz = [math.floor(size[0] / 2), math.floor(size[1] / 2)] x = np.linspace(-sz[0], sz[1], size[1]) x = np.expand_dims(x, 0) x = x.repeat(size[0], 0) y = np.linspace(-sz[0], sz[1], size[1]) y = np.expand_dims(y, 1) y = y.repeat(size[1], 1) z = np.sqrt(x**2 + y**2) z = np.less_equal(z, radius) vfunc = np.vectorize(lambda b: b and in_val or out_val) return vfunc(z) class GridScorer(object): """Class for scoring ratemaps given trajectories.""" def __init__(self, nbins, coords_range, mask_parameters, min_max=False): """Scoring ratemaps given trajectories. Args: nbins: Number of bins per dimension in the ratemap. coords_range: Environment coordinates range. mask_parameters: parameters for the masks that analyze the angular autocorrelation of the 2D autocorrelation. min_max: Correction. """ self._nbins = nbins self._min_max = min_max self._coords_range = coords_range self._corr_angles = [30, 45, 60, 90, 120, 135, 150] # Create all masks self._masks = [(self._get_ring_mask(mask_min, mask_max), (mask_min, mask_max)) for mask_min, mask_max in mask_parameters] # Mask for hiding the parts of the SAC that are never used self._plotting_sac_mask = circle_mask( [self._nbins * 2 - 1, self._nbins * 2 - 1], self._nbins, in_val=1.0, out_val=np.nan) def calculate_ratemap(self, xs, ys, activations, statistic='mean'): return scipy.stats.binned_statistic_2d( xs, ys, activations, bins=self._nbins, statistic=statistic, range=self._coords_range)[0] def _get_ring_mask(self, mask_min, mask_max): n_points = [self._nbins * 2 - 1, self._nbins * 2 - 1] return (circle_mask(n_points, mask_max * self._nbins) * (1 - circle_mask(n_points, mask_min * self._nbins))) def grid_score_60(self, corr): if self._min_max: return np.minimum(corr[60], corr[120]) - np.maximum( corr[30], np.maximum(corr[90], corr[150])) else: return (corr[60] + corr[120]) / 2 - (corr[30] + corr[90] + corr[150]) / 3 def grid_score_90(self, corr): return corr[90] - (corr[45] + corr[135]) / 2 def calculate_sac(self, seq1): """Calculating spatial autocorrelogram.""" seq2 = seq1 def filter2(b, x): stencil = np.rot90(b, 2) return scipy.signal.convolve2d(x, stencil, mode='full') seq1 = np.nan_to_num(seq1) seq2 = np.nan_to_num(seq2) ones_seq1 = np.ones(seq1.shape) ones_seq1[np.isnan(seq1)] = 0 ones_seq2 = np.ones(seq2.shape) ones_seq2[np.isnan(seq2)] = 0 seq1[np.isnan(seq1)] = 0 seq2[np.isnan(seq2)] = 0 seq1_sq = np.square(seq1) seq2_sq = np.square(seq2) seq1_x_seq2 = filter2(seq1, seq2) sum_seq1 = filter2(seq1, ones_seq2) sum_seq2 = filter2(ones_seq1, seq2) sum_seq1_sq = filter2(seq1_sq, ones_seq2) sum_seq2_sq = filter2(ones_seq1, seq2_sq) n_bins = filter2(ones_seq1, ones_seq2) n_bins_sq = np.square(n_bins) std_seq1 = np.power( np.subtract( np.divide(sum_seq1_sq, n_bins), (np.divide(np.square(sum_seq1), n_bins_sq))), 0.5) std_seq2 = np.power( np.subtract( np.divide(sum_seq2_sq, n_bins), (np.divide(np.square(sum_seq2), n_bins_sq))), 0.5) covar = np.subtract( np.divide(seq1_x_seq2, n_bins), np.divide(np.multiply(sum_seq1, sum_seq2), n_bins_sq)) x_coef = np.divide(covar, np.multiply(std_seq1, std_seq2)) x_coef = np.real(x_coef) x_coef = np.nan_to_num(x_coef) return x_coef def rotated_sacs(self, sac, angles): return [ scipy.ndimage.interpolation.rotate(sac, angle, reshape=False) for angle in angles ] def get_grid_scores_for_mask(self, sac, rotated_sacs, mask): """Calculate Pearson correlations of area inside mask at corr_angles.""" masked_sac = sac * mask ring_area = np.sum(mask) # Calculate dc on the ring area masked_sac_mean = np.sum(masked_sac) / ring_area # Center the sac values inside the ring masked_sac_centered = (masked_sac - masked_sac_mean) * mask variance = np.sum(masked_sac_centered**2) / ring_area + 1e-5 corrs = dict() for angle, rotated_sac in zip(self._corr_angles, rotated_sacs): masked_rotated_sac = (rotated_sac - masked_sac_mean) * mask cross_prod = np.sum(masked_sac_centered * masked_rotated_sac) / ring_area corrs[angle] = cross_prod / variance return self.grid_score_60(corrs), self.grid_score_90(corrs), variance def get_scores(self, rate_map): """Get summary of scrores for grid cells.""" sac = self.calculate_sac(rate_map) rotated_sacs = self.rotated_sacs(sac, self._corr_angles) scores = [ self.get_grid_scores_for_mask(sac, rotated_sacs, mask) for mask, mask_params in self._masks # pylint: disable=unused-variable ] scores_60, scores_90, variances = map(np.asarray, zip(*scores)) # pylint: disable=unused-variable max_60_ind = np.argmax(scores_60) max_90_ind = np.argmax(scores_90) return (scores_60[max_60_ind], scores_90[max_90_ind], self._masks[max_60_ind][1], self._masks[max_90_ind][1], sac) def plot_ratemap(self, ratemap, ax=None, title=None, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg """Plot ratemaps.""" if ax is None: ax = plt.gca() # Plot the ratemap ax.imshow(ratemap, interpolation='none', *args, **kwargs) # ax.pcolormesh(ratemap, *args, **kwargs) ax.axis('off') if title is not None: ax.set_title(title) def plot_sac(self, sac, mask_params=None, ax=None, title=None, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg """Plot spatial autocorrelogram.""" if ax is None: ax = plt.gca() # Plot the sac useful_sac = sac * self._plotting_sac_mask ax.imshow(useful_sac, interpolation='none', *args, **kwargs) # ax.pcolormesh(useful_sac, *args, **kwargs) # Plot a ring for the adequate mask if mask_params is not None: center = self._nbins - 1 ax.add_artist( plt.Circle( (center, center), mask_params[0] * self._nbins, # lw=bump_size, fill=False, edgecolor='k')) ax.add_artist( plt.Circle( (center, center), mask_params[1] * self._nbins, # lw=bump_size, fill=False, edgecolor='k')) ax.axis('off') if title is not None: ax.set_title(title)
grid-cells-master
scores.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Impala agent class, which follows the DebuggerAgent interface.""" from typing import Any, Callable import dm_env import haiku as hk import jax import jax.numpy as jnp from agent_debugger.src.agent_debugger import agent from agent_debugger.src.agent_debugger import types class ImpalaAgent(agent.DebuggerAgent): """Impala agent class.""" def __init__( self, net_factory: Callable[[], hk.RNNCore], params: hk.Params, ) -> None: """Initializes the agent. Args: net_factory: Function to create the model. params: The parameters of the agent. """ _, self._initial_state = hk.transform( lambda batch_size: net_factory().initial_state(batch_size)) self._init_fn, apply_fn = hk.without_apply_rng( hk.transform(lambda obs, state: net_factory().__call__(obs, state))) self._apply_fn = jax.jit(apply_fn) self._params = params def initial_state(self, rng: jnp.ndarray) -> types.AgentState: """Returns the agent initial state.""" # Wrapper method to avoid pytype attribute-error. return types.AgentState( internal_state=self._initial_state(self._params, rng, batch_size=1), seed=rng) def step( self, timestep: dm_env.TimeStep, state: types.AgentState, ) -> tuple[types.Action, Any, types.AgentState]: """Steps the agent in the environment.""" net_out, next_state = self._apply_fn(self._params, timestep, state.internal_state) # Sample an action and return. action = hk.multinomial(state.seed, net_out.policy_logits, num_samples=1) action = jnp.squeeze(action, axis=-1) action = int(action) new_rng, _ = jax.random.split(state.seed) new_agent_state = types.AgentState(internal_state=next_state, seed=new_rng) return action, net_out, new_agent_state
agent_debugger-main
src/impala_agent.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Neural network used in Impala trained agents.""" from typing import NamedTuple, Optional, Sequence, Union import dm_env import haiku as hk import jax.nn import jax.numpy as jnp NetState = Union[jnp.ndarray, hk.LSTMState] # Kept as a NamedTuple as jax does not support dataclasses. class NetOutput(NamedTuple): """Dataclass to define network outputs.""" policy_logits: jnp.ndarray value: jnp.ndarray class RecurrentConvNet(hk.RNNCore): """A class for Impala nets. Architecture: MLP torso -> LSTM -> MLP head -> (linear policy logits, linear value) If initialised with lstm_width=0, skips the LSTM layer. """ def __init__( self, num_actions: int, conv_widths: Sequence[int], conv_kernels: Sequence[int], padding: str, torso_widths: Sequence[int], lstm_width: Optional[int], head_widths: Sequence[int], name: str = None, ) -> None: """Initializes the impala net.""" super().__init__(name=name) self._num_actions = num_actions self._torso_widths = torso_widths self._head_widths = head_widths self._core = hk.LSTM(lstm_width) if lstm_width else None conv_layers = [] for width, kernel_size in zip(conv_widths, conv_kernels): layer = hk.Conv2D( width, kernel_shape=[kernel_size, kernel_size], padding=padding) conv_layers += [layer, jax.nn.relu] self._conv_net = hk.Sequential(conv_layers + [hk.Flatten()]) def initial_state(self, batch_size: int) -> NetState: """Returns a fresh hidden state for the LSTM core.""" return self._core.initial_state(batch_size) if self._core else jnp.zeros(()) def __call__( self, x: dm_env.TimeStep, state: NetState, ) -> tuple[NetOutput, NetState]: """Steps the net, applying a forward pass of the neural network.""" # Apply torso. observation = x.observation['board'].astype(dtype=jnp.float32) / 255 observation = jnp.expand_dims(observation, axis=0) output = self._torso(observation) if self._core is not None: output, state = self._core(output, state) policy_logits, value = self._head(output) return NetOutput(policy_logits=policy_logits[0], value=value[0]), state def _head(self, activations: jnp.ndarray) -> jnp.ndarray: """Returns new activations after applying the head network.""" pre_outputs = hk.nets.MLP(self._head_widths)(activations) policy_logits = hk.Linear(self._num_actions)(pre_outputs) value = hk.Linear(1)(pre_outputs) value = jnp.squeeze(value, axis=-1) return policy_logits, value def _torso(self, inputs: jnp.ndarray) -> jnp.ndarray: """Returns activations after applying the torso to the inputs.""" return hk.Sequential([self._conv_net, hk.nets.MLP(self._torso_widths)])( inputs)
agent_debugger-main
src/impala_net.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """This file contains the default Sprites and Drapes used in Pycoworld. Sprites and Drapes are concepts part of Pycolab, the game engine we use. Sprites are unique entities which can usually move and act in the environment. Drapes are sets of entities which are not interacting with the environment, mostly idle. """ import abc from typing import MutableMapping, Any import numpy as np from pycolab import engine from pycolab import things as plab_things from agent_debugger.src.pycoworld import default_constants Tile = default_constants.Tile class PlayerSprite(plab_things.Sprite): """A `Sprite` for our player. The player can move around freely, as long as it doesn't attempt to move into an `IMPASSABLE` tile. There's also additional effects for certain special tiles, such as a goal, lava, and water tile. """ def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: ypos, xpos = self.position height, width = board.shape # Where does the agent want to move? if actions == 0 and ypos >= 1: # go upward? if board[ypos - 1, xpos] not in default_constants.IMPASSABLE: self._position = self.Position(ypos - 1, xpos) elif actions == 1 and ypos <= height - 2: # go downward? if board[ypos + 1, xpos] not in default_constants.IMPASSABLE: self._position = self.Position(ypos + 1, xpos) elif actions == 2 and xpos >= 1: # go leftward? if board[ypos, xpos - 1] not in default_constants.IMPASSABLE: self._position = self.Position(ypos, xpos - 1) elif actions == 3 and xpos <= width - 2: # go rightward? if board[ypos, xpos + 1] not in default_constants.IMPASSABLE: self._position = self.Position(ypos, xpos + 1) ypos, xpos = self.position floor_tile = backdrop.curtain[ypos, xpos] terminals = [ Tile.TERMINAL, Tile.TERMINAL_R, Tile.TERMINAL_G, Tile.TERMINAL_B ] if floor_tile in terminals: the_plot.terminate_episode() if floor_tile in [Tile.LAVA]: the_plot.add_reward(default_constants.REWARD_LAVA) the_plot.terminate_episode() if floor_tile in [Tile.WATER]: the_plot.add_reward(default_constants.REWARD_WATER) class RewardDrape(plab_things.Drape): """A drape for small rewards.""" def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: ypos, xpos = things[chr(Tile.PLAYER)].position if self.curtain[ypos, xpos]: the_plot.add_reward(default_constants.REWARD_SMALL) self.curtain[ypos, xpos] = False class BigRewardDrape(plab_things.Drape): """A drape for big rewards.""" def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: ypos, xpos = things[chr(Tile.PLAYER)].position if self.curtain[ypos, xpos]: the_plot.add_reward(default_constants.REWARD_BIG) self.curtain[ypos, xpos] = False class ObjectDrape(plab_things.Drape): """A drape with objects that the agent can carry in its inventory.""" def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: ypos, xpos = things[chr(Tile.PLAYER)].position if self.character not in the_plot.keys(): # The inventory is empty by default. the_plot[self.character] = 0 if self.curtain[ypos, xpos]: the_plot[self.character] = the_plot[self.character] + 1 self.curtain[ypos, xpos] = False class WallDrape(plab_things.Drape): """A drape for walls, which does nothing.""" def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, Any], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: """Updates the environment with the actions.""" class SensorDrape(plab_things.Drape, abc.ABC): """A drape for plain sensors, triggering some function in the environment.""" @abc.abstractmethod def _trigger( self, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: """Triggers something in the environment as soon as the sensor is pushed.""" def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: ypos, xpos = things[chr(default_constants.Tile.PLAYER)].position if self.curtain[ypos, xpos]: # As soon as the agent steps on the sensor, we trigger it. self._trigger(board, layers, backdrop, things, the_plot) class DoorDrape(plab_things.Drape): """A drape with doors tiles. Doors come in different colors. They act as impassable tiles, unless the player has a key of the associated color in its inventory: in this case, the key is consumed and the door disappears. """ def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: ypos, xpos = things[chr(Tile.PLAYER)].position height, width = self.curtain.shape # What's the required key? key = chr(ord(self.character) - 4) # Where does the agent want to move? # If the agent wants to move into a door, then check whether # the corresponding key is available. If it is, then remove the door. if actions == 0 and ypos >= 1: # go upward? if self.curtain[ypos - 1, xpos] and the_plot[key] > 0: self.curtain[ypos - 1, xpos] = False the_plot[key] = the_plot[key] - 1 elif actions == 1 and ypos <= height - 2: # go downward? if self.curtain[ypos + 1, xpos] and the_plot[key] > 0: self.curtain[ypos + 1, xpos] = False the_plot[key] = the_plot[key] - 1 elif actions == 2 and xpos >= 1: # go leftward? if self.curtain[ypos, xpos - 1] and the_plot[key] > 0: self.curtain[ypos, xpos - 1] = False the_plot[key] = the_plot[key] - 1 elif actions == 3 and xpos <= width - 2: # go rightward? if self.curtain[ypos, xpos + 1] and the_plot[key] > 0: self.curtain[ypos, xpos + 1] = False the_plot[key] = the_plot[key] - 1 class BoxDrape(plab_things.Drape): """A drape for pushable blocks. These blocks can be pushed by the player if there is a free space behind. """ def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: ypos, xpos = things[chr(Tile.PLAYER)].position height, width = self.curtain.shape # Where does the agent want to move? if actions == 0 and ypos >= 2: # go upward? check_impassable = board[ypos - 2, xpos] not in default_constants.IMPASSABLE if self.curtain[ypos - 1, xpos] and check_impassable: self.curtain[ypos - 1, xpos] = False self.curtain[ypos - 2, xpos] = True elif actions == 1 and ypos <= height - 3: # go downward? check_impassable = board[ypos + 2, xpos] not in default_constants.IMPASSABLE if self.curtain[ypos + 1, xpos] and check_impassable: self.curtain[ypos + 1, xpos] = False self.curtain[ypos + 2, xpos] = True elif actions == 2 and xpos >= 2: # go leftward? check_impassable = board[ypos, xpos - 2] not in default_constants.IMPASSABLE if self.curtain[ypos, xpos - 1] and check_impassable: self.curtain[ypos, xpos - 1] = False self.curtain[ypos, xpos - 2] = True elif actions == 3 and xpos <= width - 3: # go rightward? check_impassable = board[ypos, xpos + 2] not in default_constants.IMPASSABLE if self.curtain[ypos, xpos + 1] and check_impassable: self.curtain[ypos, xpos + 1] = False self.curtain[ypos, xpos + 2] = True
agent_debugger-main
src/pycoworld/default_sprites_and_drapes.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Default constants for Pycoworld.""" import enum class Tile(enum.IntEnum): """Available pycoworld tiles with their IDs. This IntEnum is only provided for better readability. There is no guarantee that the raw IDs are not used anywhere in the code and no requirement to use the enum in cases where the raw IDs are more readable. """ FLOOR = 0 FLOOR_R = 1 FLOOR_B = 2 FLOOR_G = 3 WALL = 4 WALL_R = 5 WALL_B = 6 WALL_G = 7 PLAYER = 8 PLAYER_R = 9 PLAYER_B = 10 PLAYER_G = 11 TERMINAL = 12 TERMINAL_R = 13 TERMINAL_B = 14 TERMINAL_G = 15 BLOCK = 16 BLOCK_R = 17 BLOCK_B = 18 BLOCK_G = 19 REWARD = 20 REWARD_R = 21 REWARD_B = 22 REWARD_G = 23 BIG_REWARD = 24 BIG_REWARD_R = 25 BIG_REWARD_B = 26 BIG_REWARD_G = 27 HOLE = 28 HOLE_R = 29 HOLE_B = 30 HOLE_G = 31 SAND = 32 GRASS = 33 LAVA = 34 WATER = 35 KEY = 36 KEY_R = 37 KEY_B = 38 KEY_G = 39 DOOR = 40 DOOR_R = 41 DOOR_B = 42 DOOR_G = 43 SENSOR = 44 SENSOR_R = 45 SENSOR_B = 46 SENSOR_G = 47 OBJECT = 48 OBJECT_R = 49 OBJECT_B = 50 OBJECT_G = 51 # This dict defines which sensor matches which object. MATCHING_OBJECT_DICT = { Tile.SENSOR: Tile.OBJECT, Tile.SENSOR_R: Tile.OBJECT_R, Tile.SENSOR_G: Tile.OBJECT_G, Tile.SENSOR_B: Tile.OBJECT_B, } # Impassable tiles: these tiles cannot be traversed by the agent. IMPASSABLE = [ Tile.WALL, Tile.WALL_R, Tile.WALL_B, Tile.WALL_G, Tile.BLOCK, Tile.BLOCK_R, Tile.BLOCK_B, Tile.BLOCK_G, Tile.DOOR, Tile.DOOR_R, Tile.DOOR_B, Tile.DOOR_G, ] REWARD_LAVA = -10. REWARD_WATER = -1. REWARD_SMALL = 1. REWARD_BIG = 5.
agent_debugger-main
src/pycoworld/default_constants.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Pycoworld environment. Pycolab only provides a game engine, i.e. a way to create a game, with the different objects and their dynamics. However, we'd like to use a more formal interface which is an environment, with a reset(), step(), action_spec() and observation_spec() methods. We need to create an object to wrap the engine and create a true environment, inheriting dm_env.Environment. This file also contains a build_environment method, which takes a pycoworld level name, and directly creates the associated environment, ready to be used in association with the agent. """ import copy import dataclasses import itertools from typing import Any, Callable, Optional, Union import dm_env import jax.numpy as jnp import jax.random as jrandom import numpy as np from pycolab import cropping as pycolab_cropping from pycolab import engine as pycolab_engine from pycolab import rendering import tree from agent_debugger.src.pycoworld import default_constants from agent_debugger.src.pycoworld import serializable_environment from agent_debugger.src.pycoworld.levels import base_level from agent_debugger.src.pycoworld.levels import level_names _TILES = list(range(len(default_constants.Tile))) _PLAYER_TILE = chr(8) _RGB_MAPPING = {chr(n): (4 * n, 4 * n, 4 * n) for n in _TILES} class ObservationDistiller: """This class modifies the observations before they are sent to the agent.""" def __init__( self, array_converter: rendering.ObservationToArray, cropping: Optional[pycolab_cropping.ObservationCropper] = None ) -> None: """Initializes a Distiller.""" self._array_converter = array_converter cropper = pycolab_cropping.ObservationCropper self._cropping = tree.map_structure( lambda c: cropper() if c is None else c, cropping) def set_engine(self, engine: pycolab_engine.Engine) -> None: """Informs the Distiller of the current game engine in use. Args: engine: current engine in use by the `Environment` adapter. """ tree.map_structure(lambda c: c.set_engine(engine), self._cropping) def __call__(self, observation: Any) -> Any: """Distills a pycolab observation into the format required by the agent. Args: observation: observation to distill. Returns: the observation distilled for supplying to the agent. """ return tree.map_structure( lambda c: self._array_converter(c.crop(observation)), self._cropping) @dataclasses.dataclass class EnvState: """The Pycoworld environment state.""" state: Any current_game: pycolab_engine.Engine game_over: bool observation_distiller: ObservationDistiller seed: int class PycoworldEnvironment(serializable_environment.SerializableEnvironment): """A wrapper around the for_python.Environment to get and set states. The serialization is just a copy of the wrapped environment. """ def __init__( self, seed: int, game_factory: Callable[[jnp.ndarray], pycolab_engine.Engine], possible_actions: set[int], default_reward: Optional[float], observation_distiller: ObservationDistiller, max_iterations: Optional[int] = None, max_iterations_discount: Optional[float] = None, ) -> None: """Initializes the pycoworld environment.""" self._game_factory = game_factory self._default_reward = default_reward self._observation_distiller = observation_distiller self._max_iterations = max_iterations self._max_iterations_discount = max_iterations_discount self._state = None self._current_game = None self._game_over = None self._seed = seed # Compute action and observation spec. self._action_spec = dm_env.specs.DiscreteArray( len(possible_actions), dtype='int32', name='discrete') self._observation_spec = self._compute_observation_spec() def reset(self) -> dm_env.TimeStep: """Starts a new episode.""" self._current_game = self._game_factory(jrandom.PRNGKey(self._seed)) self._state = dm_env.StepType.FIRST self._observation_distiller.set_engine(self._current_game) # Collect environment returns from starting the game and update state. observations, reward, discount = self._current_game.its_showtime() self._game_over = self._is_game_over() observations, _, _ = self._standardise_timestep_values( observations, reward, discount) return dm_env.TimeStep( step_type=self._state, reward=None, discount=None, observation=observations) def step(self, action: int) -> dm_env.TimeStep: """Applies action, steps the world forward, and returns observations.""" # Clear episode internals and start a new episode, if episode ended or if # the game was not already underway. if self._state == dm_env.StepType.LAST: self._drop_last_episode() if self._current_game is None: return self.reset() # Execute the action in pycolab. observations, reward, discount = self._current_game.play(action) self._game_over = self._is_game_over() observations, reward, discount = self._standardise_timestep_values( observations, reward, discount) # Check the current status of the game. if self._game_over: self._state = dm_env.StepType.LAST else: self._state = dm_env.StepType.MID return dm_env.TimeStep( step_type=self._state, reward=reward, discount=discount, observation=observations) def observation_spec(self) -> dm_env.specs.Array: """Returns the observation specifications of the environment.""" return self._observation_spec def action_spec(self) -> dm_env.specs.Array: """Returns the action specifications of the environment.""" return self._action_spec def get_state(self) -> EnvState: """Returns the state of the pycoworld environment.""" env_state = EnvState( state=self._state, current_game=self._current_game, game_over=self._game_over, observation_distiller=self._observation_distiller, seed=self._seed) return copy.deepcopy(env_state) def set_state(self, env_state: EnvState) -> None: """Sets the state of the pycoworld environment.""" env_state = copy.deepcopy(env_state) self._state = env_state.state self._current_game = env_state.current_game self._game_over = env_state.game_over self._observation_distiller = env_state.observation_distiller self._seed = env_state.seed def _compute_observation_spec(self) -> Any: """Returns after compute the observation spec of the environment. We need a special method to do this, as we are retrieving the specs by launching a game. This is an internal and private method only. """ def obs_names_that_count_up(): for i in itertools.count(): yield 'obs{}'.format(i) names = obs_names_that_count_up() timestep = self.reset() spec_array = dm_env.specs.Array observation_spec = tree.map_structure( lambda a: spec_array(shape=a.shape, dtype=a.dtype, name=next(names)), timestep.observation) self._drop_last_episode() return observation_spec def _standardise_timestep_values( self, observations: Any, reward: Optional[float], discount: Optional[float], ) -> tuple[Any, Optional[float], Optional[float]]: """Applies defaults and standard packaging to timestep values if needed.""" observations = copy.deepcopy(self._observation_distiller(observations)) if isinstance(observations, np.ndarray): observations = {'board': observations} reward = reward if reward is not None else self._default_reward if self._max_iterations is not None and ( self._current_game.the_plot.frame >= self._max_iterations) and (not self._current_game.game_over): if self._max_iterations_discount is not None: discount = self._max_iterations_discount return observations, reward, discount def _is_game_over(self) -> bool: """Returns whether the game is over.""" # If we've reached the maximum number of game iterations, terminate the # current game. if self._max_iterations is not None and (self._current_game.the_plot.frame >= self._max_iterations): return True return self._current_game.game_over def _drop_last_episode(self) -> None: """Clears all the internal information about the game.""" self._state = None self._current_game = None self._game_over = None def build_environment( level: Union[base_level.PycoworldLevel, str], seed: int = 1, episode_length: Optional[int] = None, observation_encoding: str = 'feature_map', egocentric_horizon: Optional[int] = None, ) -> PycoworldEnvironment: """Builds and returns the environment for pycoworld. The observation is either a feature map (one hot encoding), a raw (the tile id directly) or rgb map of the board of the game. The actions are discrete and you can get the bounds via the env specs. Args: level: The level to build. seed: The seed used by the level episode_length: Number of steps in the episode observation_encoding: Must be in {feature_map, board, rgb} egocentric_horizon: The sight distance of the agent. None means the agent sees the complete board. Returns: The environment for the game """ if isinstance(level, str): level = level_names.level_by_name(level) # The distiller is used to processed the raw observation provided by pycolab # to an observation fed to the agent, here a numpy binary array. if observation_encoding == 'feature_map': array_converter = rendering.ObservationToFeatureArray( layers=list(map(chr, _TILES)), permute=(1, 2, 0)) elif observation_encoding == 'board': no_mapping = {chr(x): x for x in _TILES} array_converter = rendering.ObservationToArray(no_mapping, dtype=np.uint8) elif observation_encoding == 'rgb': array_converter = rendering.ObservationToArray( _RGB_MAPPING, permute=(1, 2, 0), dtype=np.uint8) else: raise ValueError('Observation encoding must be in {feature_map, rgb},' f'got {observation_encoding}.') if egocentric_horizon is not None: square_side_length = 2 * egocentric_horizon + 1 cropper = pycolab_cropping.ScrollingCropper( rows=square_side_length, cols=square_side_length, to_track=[_PLAYER_TILE], pad_char=chr(0), scroll_margins=(1, 1)) else: cropper = None observation_distiller = ObservationDistiller( array_converter=array_converter, cropping=cropper) return PycoworldEnvironment( seed=seed, game_factory=level.sample_game, possible_actions=set(level.actions), observation_distiller=observation_distiller, default_reward=0., max_iterations=episode_length, max_iterations_discount=1.)
agent_debugger-main
src/pycoworld/environment.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Serializable environment class. The main feature is to ability to retrieve and set the state of an environment. """ import abc from typing import Any import dm_env class SerializableEnvironment(dm_env.Environment, abc.ABC): """Abstract class with methods to set and get states. The state can be anything even though we prefer mappings like dicts for readability. It must contain all information, no compression is allowed. The state must be a parse of the environment containing only the stateful variables. There is no assumption on how the agent would use this object: please provide copies of internal attributes to avoid side effects. """ @abc.abstractmethod def get_state(self) -> Any: """Returns the state of the environment.""" @abc.abstractmethod def set_state(self, state: Any) -> Any: """Sets the state of the environment. Args: state: The state to set. """
agent_debugger-main
src/pycoworld/serializable_environment.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Grass sand level.""" from typing import Optional import jax import numpy as np from agent_debugger.src.pycoworld import default_constants from agent_debugger.src.pycoworld.levels import base_level Tile = default_constants.Tile class GrassSandLevel(base_level.PycoworldLevel): """The grass sand level. The goal position causally depends on the type of world. Similarly, the floor tiles (grass or sand) also causally depend on the type of world. Therefore, type of floor and reward position are correlated, but there is no causal link between them. """ def __init__( self, corr: float = 1.0, above: Optional[np.ndarray] = None, below: Optional[np.ndarray] = None, reward_pos: Optional[tuple[np.ndarray, np.ndarray]] = None, double_terminal_event: Optional[bool] = False, ) -> None: """Initializes the level. Args: corr: "correlation" between reward position and world. 1.0 means that the reward position will always be on "north" for sand world and on "south" for grass world. A value of 0.5 corresponds to fully randomized position independent of the world. above: a map to use. below: a background to use. reward_pos: position of the rewards. double_terminal_event: whether to have a terminal event on both sides of the maze or only beneath the reward. """ if not 0.0 <= corr <= 1.0: raise ValueError('corr variable must be a float between 0.0 and 1.0') self._corr = corr if above is None: above = np.array([[0, 0, 0, 4, 4, 4], [4, 4, 4, 4, 99, 4], [4, 4, 4, 4, 99, 4], [4, 8, 99, 99, 99, 4], [4, 4, 4, 4, 99, 4], [4, 4, 4, 4, 99, 4], [0, 0, 0, 4, 4, 4]]) self._above = above if below is None: below = np.full_like(above, Tile.FLOOR) self._below = below if reward_pos is None: self._reward_pos_top = np.array([1, 4]) self._reward_pos_bottom = np.array([5, 4]) else: self._reward_pos_top, self._reward_pos_bottom = reward_pos self._double_terminal_event = double_terminal_event def foreground_and_background( self, rng: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: """See base class.""" rng1, rng2 = jax.random.split(rng, 2) # Do not modify the base maps during sampling sampled_above = self._above.copy() sampled_below = self._below.copy() # Select world. if jax.random.uniform(rng1) < 0.5: world = 'sand' floor_type = Tile.SAND else: world = 'grass' floor_type = Tile.GRASS # Sample reward location depending on corr variable. if jax.random.uniform(rng2) <= self._corr: # Standard reward position for both worlds. if world == 'sand': used_reward_pos = self._reward_pos_top elif world == 'grass': used_reward_pos = self._reward_pos_bottom else: # Alternative reward position for both worlds. if world == 'sand': used_reward_pos = self._reward_pos_bottom elif world == 'grass': used_reward_pos = self._reward_pos_top if self._double_terminal_event: # Put terminal events everywhere first. sampled_above[self._reward_pos_top[0], self._reward_pos_top[1]] = Tile.TERMINAL_R sampled_above[self._reward_pos_bottom[0], self._reward_pos_bottom[1]] = Tile.TERMINAL_R # Draw the reward ball. sampled_above[used_reward_pos[0], used_reward_pos[1]] = Tile.REWARD # Substitute tiles with code 99 with the corresponding floor_type code. floor_tiles = np.argwhere(sampled_above == 99) for tile in floor_tiles: sampled_above[tile[0], tile[1]] = floor_type if self._double_terminal_event: # Add terminal events on both sides to the below. sampled_below[self._reward_pos_top[0], self._reward_pos_top[1]] = Tile.TERMINAL_R sampled_below[self._reward_pos_bottom[0], self._reward_pos_bottom[1]] = Tile.TERMINAL_R else: sampled_below[used_reward_pos[0], used_reward_pos[1]] = Tile.TERMINAL_R return sampled_above, sampled_below
agent_debugger-main
src/pycoworld/levels/grass_sand.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Level config.""" import abc from typing import Any, Mapping, Optional, Sequence, Union import numpy as np from pycolab import ascii_art from pycolab import engine from pycolab import things as pycolab_things from agent_debugger.src.pycoworld import default_constants from agent_debugger.src.pycoworld import default_sprites_and_drapes _ACTIONS = range(4) Tile = default_constants.Tile def default_sprites() -> dict[str, Any]: """Returns the default mapping of characters to sprites in the levels.""" return {chr(Tile.PLAYER): default_sprites_and_drapes.PlayerSprite} def default_drapes() -> dict[str, Any]: """Returns the default mapping of characters to drapes in the levels.""" return { chr(Tile.WALL): default_sprites_and_drapes.WallDrape, chr(Tile.WALL_R): default_sprites_and_drapes.WallDrape, chr(Tile.WALL_B): default_sprites_and_drapes.WallDrape, chr(Tile.WALL_G): default_sprites_and_drapes.WallDrape, chr(Tile.BLOCK): default_sprites_and_drapes.BoxDrape, chr(Tile.BLOCK_R): default_sprites_and_drapes.BoxDrape, chr(Tile.BLOCK_B): default_sprites_and_drapes.BoxDrape, chr(Tile.BLOCK_G): default_sprites_and_drapes.BoxDrape, chr(Tile.REWARD): default_sprites_and_drapes.RewardDrape, chr(Tile.REWARD_R): default_sprites_and_drapes.RewardDrape, chr(Tile.REWARD_B): default_sprites_and_drapes.RewardDrape, chr(Tile.REWARD_G): default_sprites_and_drapes.RewardDrape, chr(Tile.BIG_REWARD): default_sprites_and_drapes.BigRewardDrape, chr(Tile.BIG_REWARD_R): default_sprites_and_drapes.BigRewardDrape, chr(Tile.BIG_REWARD_B): default_sprites_and_drapes.BigRewardDrape, chr(Tile.BIG_REWARD_G): default_sprites_and_drapes.BigRewardDrape, chr(Tile.KEY): default_sprites_and_drapes.ObjectDrape, chr(Tile.KEY_R): default_sprites_and_drapes.ObjectDrape, chr(Tile.KEY_B): default_sprites_and_drapes.ObjectDrape, chr(Tile.KEY_G): default_sprites_and_drapes.ObjectDrape, chr(Tile.DOOR): default_sprites_and_drapes.DoorDrape, chr(Tile.DOOR_R): default_sprites_and_drapes.DoorDrape, chr(Tile.DOOR_B): default_sprites_and_drapes.DoorDrape, chr(Tile.DOOR_G): default_sprites_and_drapes.DoorDrape, chr(Tile.OBJECT): default_sprites_and_drapes.ObjectDrape, chr(Tile.OBJECT_R): default_sprites_and_drapes.ObjectDrape, chr(Tile.OBJECT_B): default_sprites_and_drapes.ObjectDrape, chr(Tile.OBJECT_G): default_sprites_and_drapes.ObjectDrape, } def default_schedule() -> list[str]: """Returns the default update schedule of sprites and drapes in the levels.""" return [ chr(Tile.PLAYER), # PlayerSprite chr(Tile.WALL), chr(Tile.WALL_R), chr(Tile.WALL_B), chr(Tile.WALL_G), chr(Tile.REWARD), chr(Tile.REWARD_R), chr(Tile.REWARD_B), chr(Tile.REWARD_G), chr(Tile.BIG_REWARD), chr(Tile.BIG_REWARD_R), chr(Tile.BIG_REWARD_B), chr(Tile.BIG_REWARD_G), chr(Tile.KEY), chr(Tile.KEY_R), chr(Tile.KEY_B), chr(Tile.KEY_G), chr(Tile.OBJECT), chr(Tile.OBJECT_R), chr(Tile.OBJECT_B), chr(Tile.OBJECT_G), chr(Tile.DOOR), chr(Tile.DOOR_R), chr(Tile.DOOR_B), chr(Tile.DOOR_G), chr(Tile.BLOCK), chr(Tile.BLOCK_R), chr(Tile.BLOCK_B), chr(Tile.BLOCK_G), ] def _numpy_to_str(array: np.ndarray) -> list[str]: """Converts numpy array into a list of strings. Args: array: a 2-D np.darray of np.uint8. Returns: A list of strings of equal length, corresponding to the entries in A. """ return [''.join(map(chr, row.tolist())) for row in array] def make_pycolab_engine( foreground: np.ndarray, background: Union[np.ndarray, int], sprites: Optional[Mapping[str, pycolab_things.Sprite]] = None, drapes: Optional[Mapping[str, pycolab_things.Drape]] = None, update_schedule: Optional[Sequence[str]] = None, rng: Optional[Any] = None, ) -> engine.Engine: """Builds and returns a pycoworld game engine. Args: foreground: Array of foreground tiles. background: Array of background tiles or a single tile to use as the background everywhere. sprites: Pycolab sprites. See pycolab.ascii_art.ascii_art_to_game for more information. drapes: Pycolab drapes. update_schedule: Update schedule for sprites and drapes. rng: Random key to use for pycolab. Returns: A pycolab engine with the pycoworld game. """ sprites = sprites if sprites is not None else default_sprites() drapes = drapes if drapes is not None else default_drapes() if update_schedule is None: update_schedule = default_schedule() # The pycolab engine constructor requires arrays of strings above_str = _numpy_to_str(foreground) below_str = _numpy_to_str(background) pycolab_engine = ascii_art.ascii_art_to_game( above_str, below_str, sprites, drapes, update_schedule=update_schedule) # Pycolab does not allow to add a global seed in the engine constructor. # Therefore, we have to set it manually. pycolab_engine._the_plot['rng'] = rng # pylint: disable=protected-access return pycolab_engine class PycoworldLevel(abc.ABC): """Abstract class representing a pycoworld level. A pycoworld level captures all the data that is required to define the level and implements a function that returns a pycolab game engine. """ @abc.abstractmethod def foreground_and_background( self, rng: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: """Generates the foreground and background arrays of the level.""" def sample_game(self, rng: np.ndarray) -> engine.Engine: """Samples and returns a game from this level. A level may contain random elements (e.g. a random goal location). This function samples and returns a particular game from this level. The base version calls foreground_and_background and constructs a pycolab engine using the arrays. In order to use custom sprites, drapes, and update schedule override this method and use make_pycolab_engine to create an engine. Args: rng: Random key to use for sampling. Returns: A pycolab game engine for the sampled game. """ foreground, background = self.foreground_and_background(rng) return make_pycolab_engine(foreground, background) @property def actions(self) -> Sequence[int]: return _ACTIONS
agent_debugger-main
src/pycoworld/levels/base_level.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Red-Green Apples level. In this level there are two rooms, each containing two apples, one is red and the other is green. On each episode only one of the rooms is opened (and the other is closed by a door) and the agent's goal is to enter the opened room and reach the green apple. """ from typing import Any, MutableMapping import jax import numpy as np from pycolab import engine from pycolab import things as plab_things from agent_debugger.src.pycoworld import default_sprites_and_drapes from agent_debugger.src.pycoworld.levels import base_level class RedGreenApplesLevel(base_level.PycoworldLevel): """Red-green apples level.""" def __init__(self, red_lover: bool = False): """Initializes the level. Args: red_lover: Whether the red marble gives a positive or a negative reward. True means a positive reward. """ super().__init__() self._red_lover = red_lover def foreground_and_background( self, rng: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: """See base class.""" if jax.random.uniform(rng) < 0.5: # Room on the left is open. foreground = np.array([[4, 4, 4, 4, 4, 4, 4], [4, 0, 21, 4, 21, 0, 4], [4, 0, 23, 4, 23, 0, 4], [4, 0, 4, 4, 4, 42, 4], [4, 0, 0, 8, 0, 0, 4], [4, 4, 4, 4, 4, 4, 4]]) else: # Room on the right is open. foreground = np.array([[4, 4, 4, 4, 4, 4, 4], [4, 0, 21, 4, 21, 0, 4], [4, 0, 23, 4, 23, 0, 4], [4, 42, 4, 4, 4, 0, 4], [4, 0, 0, 8, 0, 0, 4], [4, 4, 4, 4, 4, 4, 4]]) background = np.array([ [0, 0, 0, 0, 0, 0, 0], [0, 0, 13, 0, 13, 0, 0], [0, 0, 13, 0, 13, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], ]) return foreground, background def sample_game(self, rng: np.ndarray) -> engine.Engine: """See base class.""" foreground, background = self.foreground_and_background(rng) drapes = base_level.default_drapes() if self._red_lover: drapes[chr(23)] = BadAppleDrape drapes[chr(21)] = default_sprites_and_drapes.RewardDrape else: drapes[chr(21)] = BadAppleDrape drapes[chr(23)] = default_sprites_and_drapes.RewardDrape return base_level.make_pycolab_engine(foreground, background, drapes=drapes) class BadAppleDrape(plab_things.Drape): """A drape for a bad apple. Collecting the bad apple punishes the agent with a negative reward of -1. """ def update( self, actions: int, board: np.ndarray, layers: MutableMapping[str, np.ndarray], backdrop: np.ndarray, things: MutableMapping[str, Any], the_plot: engine.plot.Plot ) -> None: ypos, xpos = things[chr(8)].position # Get agent's position. # If the agent is in the same position as the bad apple give -1 reward and # consume the bad apple. if self.curtain[ypos, xpos]: the_plot.add_reward(-1.) # Remove bad apple. self.curtain[ypos, xpos] = False
agent_debugger-main
src/pycoworld/levels/red_green_apples.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for constructing pycoworld levels.""" from typing import Optional, Sequence import chex import jax import numpy as np from agent_debugger.src.pycoworld import default_constants Tile = default_constants.Tile # A 2d slice for masking out the walls of a room. _INTERIOR = (slice(1, -1),) * 2 def room( height: int, width: int, floor_tile: Tile = Tile.FLOOR, wall_tile: Tile = Tile.WALL, ) -> np.ndarray: """Returns a pycoworld representation of a room (floor surrounded by walls). Args: height: Height of the environment. width: Width of the environment. floor_tile: Tile to use for the floor. wall_tile: Tile to use for the wall. Returns: The array representation of the room. """ room_array = np.full([height, width], wall_tile, dtype=np.uint8) room_array[_INTERIOR] = floor_tile return room_array def sample_positions( rng: np.ndarray, height_range: tuple[int, int], width_range: tuple[int, int], number_samples: int, replace: bool = True, exclude: Optional[np.ndarray] = None, ) -> Sequence[tuple[int, int]]: """Uniformly samples random positions in a 2d grid. Args: rng: Jax random key to use for sampling. height_range: Range (min, 1+max) in the height of the grid to sample from. width_range: Range (min, 1+max) in the width of the grid to sample from. number_samples: Number of positions to sample. replace: Whether to sample with replacement. exclude: Array of positions to exclude from the sampling. Each row of the array represents the x,y coordinates of one position. Returns: A sequence of x,y index tuples which can be used to index a 2d numpy array. Raises: ValueError: if more positions are requested than are available when sampling without replacement. """ height = height_range[1] - height_range[0] width = width_range[1] - width_range[0] offset = np.array([height_range[0], width_range[0]]) choices = np.arange(height * width) if exclude is not None: exclude = np.asarray(exclude) # Allow the user to pass any array-like type. chex.assert_shape(exclude, (None, 2)) exclude_offset = exclude - offset exclude_indices = np.ravel_multi_index(exclude_offset.T, (height, width)) mask = np.ones_like(choices, dtype=bool) mask[exclude_indices] = False choices = choices[mask] flat_indices = jax.random.choice( rng, choices, (number_samples,), replace=replace) positions_offset = np.unravel_index(flat_indices, (height, width)) positions = positions_offset + offset[:, np.newaxis] return list(zip(*positions))
agent_debugger-main
src/pycoworld/levels/utils.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Key Door level. In this level there is a key and a door. Behind the door there is a reward. The agent must learn to collect the key, open the door and obtain the reward. """ import jax import jax.numpy as jnp import numpy as np from agent_debugger.src.pycoworld import default_constants from agent_debugger.src.pycoworld.levels import base_level from agent_debugger.src.pycoworld.levels import utils _VALID_DOORS = ['random', 'closed', 'open'] class KeyDoorLevel(base_level.PycoworldLevel): """Level in which the agent has to unlock a door to collect the reward.""" def __init__(self, door_type: str = 'random') -> None: """Initializes the level. Args: door_type: The way we sample the door state (open or closed). Must be in {'random', 'closed', 'open'}, otherwise a ValueError is raised. """ if door_type not in _VALID_DOORS: raise ValueError( f'Argument door_type has an incorrect value. Expected one ' f'of {_VALID_DOORS}, but got {door_type} instead.') self._door_type = door_type def foreground_and_background( self, rng: jnp.ndarray, ) -> tuple[np.ndarray, np.ndarray]: """Returns a tuple with the level foreground and background. We first determine the state of the door and use the tile associated with it (closed and open doors don't have the same id). Then, we sample the random player and key positions and add their tiles to the board. The background is full of floor tiles and a terminal event beneath the reward tile, so that the episode is terminated when the agent gets the reward. Args: rng: The jax random seed. Standard name for jax random seeds. """ if self._door_type == 'closed': door_state = 'closed' elif self._door_type == 'open': door_state = 'open' elif self._door_type == 'random': rng, rng1 = jax.random.split(rng) if jax.random.uniform(rng1) < 0.5: door_state = 'open' else: door_state = 'closed' foreground = np.array([[4, 4, 4, 4, 4, 0, 0], [4, 0, 0, 0, 4, 0, 0], [4, 0, 0, 0, 4, 4, 4], [4, 0, 0, 0, 0, 20, 4], [4, 4, 4, 4, 4, 4, 4]]) if door_state == 'closed': foreground[3, 4] = default_constants.Tile.DOOR_R player_pos, key_pos = utils.sample_positions( rng, height_range=(1, 4), width_range=(1, 4), number_samples=2, replace=False) foreground[player_pos] = default_constants.Tile.PLAYER foreground[key_pos] = default_constants.Tile.KEY_R background = np.zeros(foreground.shape, dtype=int) background[3, 5] = default_constants.Tile.TERMINAL_R return foreground, background
agent_debugger-main
src/pycoworld/levels/key_door.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Color memory level.""" import numpy as np from agent_debugger.src.pycoworld.levels import grass_sand class ColorMemoryLevel(grass_sand.GrassSandLevel): """A modification of the grass sand environment to test memory. The position of the reward is correlated with the floor type, as in grass_sand, but the agent has an egocentric view. Therefore, it must remember the color at the beginning to get the reward as fast as possible. """ def __init__(self, corr: float = 1.0, large: bool = False) -> None: """Initializes the level. Args: corr: see grass_sand large: whether to enlarge the initial corridor. """ if not large: above = np.array([[0, 0, 0, 0, 4, 4, 4], [0, 0, 0, 0, 4, 0, 4], [4, 4, 4, 4, 4, 0, 4], [4, 4, 4, 4, 4, 0, 4], [4, 99, 8, 0, 0, 0, 4], [4, 4, 4, 4, 4, 0, 4], [4, 4, 4, 4, 4, 0, 4], [0, 0, 0, 0, 4, 0, 4], [0, 0, 0, 0, 4, 4, 4]]) else: above = np.array([[0, 0, 0, 0, 4, 4, 4], [0, 0, 0, 0, 4, 0, 4], [4, 4, 4, 4, 4, 0, 4], [4, 4, 0, 0, 0, 0, 4], [4, 99, 8, 0, 0, 0, 4], [4, 4, 0, 0, 0, 0, 4], [4, 4, 4, 4, 4, 0, 4], [0, 0, 0, 0, 4, 0, 4], [0, 0, 0, 0, 4, 4, 4]]) below = np.zeros(above.shape, dtype=np.uint8) reward_pos = (np.array([1, 5]), np.array([7, 5])) super().__init__(corr, above, below, reward_pos, double_terminal_event=True)
agent_debugger-main
src/pycoworld/levels/color_memory.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Apples level.""" import numpy as np from agent_debugger.src.pycoworld import default_constants from agent_debugger.src.pycoworld.levels import base_level from agent_debugger.src.pycoworld.levels import utils Tile = default_constants.Tile class ApplesLevel(base_level.PycoworldLevel): """Level where the goal is to pick up the reward.""" def __init__( self, start_type: str = 'full_room', height: int = 8, width: int = 8, ) -> None: """Initializes the level. Args: start_type: The type of random initialization: 'full_room' forces random initialization using all cells in the room, 'corner' forces random initialization of the player around one corner of the room and the reward is initialized close to the other corner. height: Height of the grid. width: Width of the grid. """ if start_type not in ['full_room', 'corner']: raise ValueError('Unrecognised start type.') self._start_type = start_type self._height = height self._width = width def foreground_and_background( self, rng: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: """See base class.""" foreground = utils.room(self._height, self._width) # Sample player's and reward's initial position in the interior of the room. if self._start_type == 'full_room': player_pos, reward_pos = utils.sample_positions( rng, height_range=(1, self._height - 1), width_range=(1, self._width - 1), number_samples=2, replace=False) elif self._start_type == 'corner': # Sample positions in the top left quadrant for the player player_pos = utils.sample_positions( rng, height_range=(1, self._height // 2), width_range=(1, self._width // 2), number_samples=1)[0] # Sample positions in the bottom right quadrant for the reward reward_pos = utils.sample_positions( rng, height_range=((self._height + 1) // 2, self._height - 1), width_range=((self._width + 1) // 2, self._width - 1), number_samples=1)[0] foreground[player_pos] = Tile.PLAYER foreground[reward_pos] = Tile.REWARD background = np.full_like(foreground, Tile.FLOOR) background[reward_pos] = Tile.TERMINAL_R return foreground, background
agent_debugger-main
src/pycoworld/levels/apples.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Level names for backward compatibility. This module lists the names of levels for backward compatibililty with old code. We plan to deprecate this module in the future so please do not rely on it for new code. """ from agent_debugger.src.pycoworld.levels import apples from agent_debugger.src.pycoworld.levels import base_level from agent_debugger.src.pycoworld.levels import color_memory from agent_debugger.src.pycoworld.levels import grass_sand from agent_debugger.src.pycoworld.levels import key_door from agent_debugger.src.pycoworld.levels import red_green_apples # Provided for backward compatibility only. Please do not use in new code. def level_by_name(level_name: str) -> base_level.PycoworldLevel: """Returns the level corresponding to a given level name. Provided for backward compatibility only. Please do not use in new code. Args: level_name: Name of the level to construct. See NAMED_LEVELS for the supported level names. """ if level_name == 'apples_corner': return apples.ApplesLevel(start_type='corner') elif level_name == 'apples_full': return apples.ApplesLevel() elif level_name == 'grass_sand': return grass_sand.GrassSandLevel() elif level_name == 'grass_sand_uncorrelated': return grass_sand.GrassSandLevel(corr=0.5, double_terminal_event=True) elif level_name == 'key_door': return key_door.KeyDoorLevel() elif level_name == 'key_door_closed': return key_door.KeyDoorLevel(door_type='closed') elif level_name == 'large_color_memory': return color_memory.ColorMemoryLevel(large=True) elif level_name == 'red_green_apples': return red_green_apples.RedGreenApplesLevel() raise ValueError(f'Unknown level {level_name}.')
agent_debugger-main
src/pycoworld/levels/level_names.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Custom types used throughout the codebase. A seed is required for the agent. For the environment, it can be included but it's not mandatory in the dm_env standard. """ from typing import Any, Callable, NamedTuple import dm_env from agent_debugger.src.pycoworld import serializable_environment Action = Any Observation = Any TimeStep = dm_env.TimeStep FirstTimeStep = dm_env.StepType.FIRST MidTimeStep = dm_env.StepType.MID LastTimeStep = dm_env.StepType.LAST Environment = dm_env.Environment SerializableEnvironment = serializable_environment.SerializableEnvironment Agent = Any Rng = Any EnvState = Any EnvBuilder = Callable[[], Environment] SerializableEnvBuilder = Callable[[], SerializableEnvironment] # We don't use dataclasses as they are not supported by jax. class AgentState(NamedTuple): internal_state: Any seed: Rng
agent_debugger-main
src/agent_debugger/types.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Debugger object, main interface of the framework.""" import contextlib import operator from typing import Any, Callable, Optional, Sequence import jax.random as jrandom from agent_debugger.src.agent_debugger import agent as debugger_agent from agent_debugger.src.agent_debugger import default_interventions from agent_debugger.src.agent_debugger import node as node_lib from agent_debugger.src.pycoworld import serializable_environment class NotReachedError(RuntimeError): """Raised when a rollout did not reach the required point.""" class Debugger: """Debugger to analyze agents in an environment step by step. The debugger can be used to step an agent in an environment, intervene on the agent and environment, and extract information. The debugger object is the main API of the Agent Debugger. Attributes: interventions: The interventions module to intervene on nodes. """ def __init__( self, agent: debugger_agent.DebuggerAgent, env: serializable_environment.SerializableEnvironment, ) -> None: """Initializes the debugger with an agent and an environment.""" self._agent = agent self._env = env self._rollout_mode = False self._is_first_rollout_step = False self.interventions = default_interventions.DefaultInterventions(self._env) def get_root_node(self, seed: int = 1) -> node_lib.Node: """Returns a root node, containing an initial world state. Args: seed: The seed to use to sample the world state. """ rng = jrandom.PRNGKey(seed=seed) timestep = self._env.reset() env_state = self._env.get_state() agent_state = self._agent.initial_state(rng) return node_lib.Node( agent_state=agent_state, env_state=env_state, last_action=None, last_timestep=timestep) @contextlib.contextmanager def rollout_mode(self): """Context manager for the rollout mode. Being in rollout mode means some performance optimisation will be done when we step the agent and the environment together. Specifically, to avoid getting and setting their states at each step of the rollout rather than just once at the beginning, we pass an option to deactivate it if the rollout mode is on. In practice, this mode reduces the compute time of debugger.get_rollout while returning exactly the same result. Yields: None. The method is used inside the same object, so no need to yield any reference. """ self._rollout_mode = True self._is_first_rollout_step = True try: yield None finally: self._rollout_mode = False self._is_first_rollout_step = False def step_forward(self, node: node_lib.Node) -> node_lib.Node: """Steps from a world state, using the environment and agent dynamics. Args: node: The node to step from. Returns: The new node obtained after stepping. """ action, agent_output, new_agent_state = self._agent.step( node.last_timestep, node.agent_state) if node.forced_next_actions: action = node.forced_next_actions[0] if not self._rollout_mode or self._is_first_rollout_step: self._env.set_state(node.env_state) timestep = self._env.step(action) new_env_state = self._env.get_state() self._is_first_rollout_step = False return node_lib.Node( agent_state=new_agent_state, env_state=new_env_state, last_action=action, last_timestep=timestep, forced_next_actions=node.forced_next_actions[1:], last_agent_output=agent_output, episode_step=node.episode_step + 1) def get_rollout( self, initial_node: node_lib.Node, maximum_length: int, endpoint: Optional[Callable[[node_lib.Node], bool]] = operator.attrgetter( 'is_terminal' ), raise_endpoint_not_reached: bool = False, ) -> list[node_lib.Node]: """Returns the list of nodes obtained by stepping from an initial node. Args: initial_node: The initial node to step from. It is the first element of the returned list. maximum_length: The maximum length of the returned list. endpoint: Function that specifies when to stop the rollout. Defaulted to is_terminal. If None, the rollout stops after maximum_length iterations, and some intermediate nodes in the list can therefore be terminal. If we fell upon a terminal node in this case, we just keep on stepping the environment, which must return a FIRST node, following the dm_env API. raise_endpoint_not_reached: Whether to raise an error if the endpoint is not reached within the maximum rollout length. Returns: A list of nodes. Raises: NotReachedError: If raise_endpoint_not_reached = True and the endpoint was not reached within the maximum rollout length. ValueError: If raise_endpoint_not_reached=True while endpoint=None. """ if endpoint is None and raise_endpoint_not_reached: raise ValueError( 'Cannot raise endpoint not reached error when endpoint is None.') endpoint_reached = False with self.rollout_mode(): visited_nodes = [initial_node] for _ in range(maximum_length - 1): current_node = self.step_forward(visited_nodes[-1]) visited_nodes.append(current_node) if endpoint is not None and endpoint(current_node): endpoint_reached = True break if raise_endpoint_not_reached and not endpoint_reached: raise NotReachedError( 'Rollout did not reach the end point within the maximum length.') return visited_nodes def get_intervened_rollout( self, initial_node: node_lib.Node, maximum_length: int, rollout_breakpoint: Callable[[node_lib.Node], bool], intervention_at_breakpoint: Callable[[node_lib.Node], node_lib.Node], endpoint: Optional[Callable[[node_lib.Node], bool]] = operator.attrgetter( 'is_terminal' ), raise_breakpoint_not_reached: bool = True, ) -> list[node_lib.Node]: """Returns a modified version of get_rollout, with an intervention. The user can provide a breakpoint function to branch at a given point in the rollout. For now it is possible to branch only once in the rollout. This is a separate function from get_rollout because we must set and unset the rollout_mode of the PTS during the intervention. Args: initial_node: The initial node to step from. It is the first element of the returned list. maximum_length: The maximum length of the returned list. rollout_breakpoint: Function that specifies when to branch in the rollout, to intervene. If None, we never branch. intervention_at_breakpoint: The intervention to perform when the breakpoint is reached. endpoint: See get_rollout. raise_breakpoint_not_reached: Whether to raise an error if the breakpoint is not reached within the maximum rollout length. Returns: A list of nodes, where an intervention has been performed on one of them. Raises: NotReachedError: If raise_breakpoint_not_reached = True and the breakpoint was not reached within the maximum rollout length. ValueError: If raise_breakpoint_not_reached=True while endpoint=None. """ visited_nodes = self.get_rollout( initial_node, maximum_length, endpoint=rollout_breakpoint, raise_endpoint_not_reached=raise_breakpoint_not_reached) visited_nodes[-1] = intervention_at_breakpoint(visited_nodes[-1]) visited_nodes.extend( self.get_rollout( initial_node=visited_nodes[-1], maximum_length=maximum_length, endpoint=endpoint)[1:]) return visited_nodes def get_actions_rewards( self, rollout: Sequence[node_lib.Node], cast_action: Callable[[Any], Any] = lambda x: x, ) -> tuple[Sequence[Optional[Any]], Sequence[float]]: """Returns the actions and rewards of a rollout in a nice format. Args: rollout: The rollout of nodes to be parsed. cast_action: A function to cast the actions to the right format. """ curate = lambda x: cast_action(x) if x is not None else x actions = [curate(node.last_action) for node in rollout] rewards = [node.last_timestep.reward for node in rollout] return actions, rewards
agent_debugger-main
src/agent_debugger/debugger.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Base class of agent recognized by the Agent Debugger.""" import abc from typing import Any import chex import dm_env from agent_debugger.src.agent_debugger import types class DebuggerAgent(abc.ABC): """The standard agent interface to be used in the debugger. The internal state is wrapped with the seed. The step method takes an observation and not a timestep. The agent parameters (mostly neural network parameters) are fixed and are NOT part of the state. """ @abc.abstractmethod def initial_state(self, rng: chex.PRNGKey) -> types.AgentState: """Returns the initial state of the agent.""" @abc.abstractmethod def step( self, timestep: dm_env.TimeStep, state: types.AgentState, ) -> tuple[types.Action, Any, types.AgentState]: """Steps the agent, taking a timestep (including observation) and a state."""
agent_debugger-main
src/agent_debugger/agent.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Base interventions for the debugger.""" import copy import dataclasses from typing import Union import jax from agent_debugger.src.agent_debugger import node as node_lib from agent_debugger.src.agent_debugger import types from agent_debugger.src.pycoworld import serializable_environment class DefaultInterventions: """Object containing the default debugger interventions.""" def __init__( self, env: serializable_environment.SerializableEnvironment, ) -> None: """Initializes the default interventions object. Args: env: The environment to be able to reset after a seed intervention. """ self._env = env def change_agent_seed( self, node: node_lib.Node, seed: Union[int, types.Rng], ) -> node_lib.Node: """Intervenes to replace the agent seed, used for acting. Args: node: The node to intervene on. seed: The new seed to put to the agent state of the node. Can be int or jax.random.PRNGKey directly. Returns: A new node, whose agent seed has been updated. """ if isinstance(seed, int): seed = jax.random.PRNGKey(seed) new_agent_state = node.agent_state._replace(seed=seed) return dataclasses.replace(node, agent_state=new_agent_state) def change_env_seed( self, node: node_lib.Node, seed: int, ) -> node_lib.Node: """Intervenes to replace the seed of the environment. The state of the environment must contain an attribute 'seed' to be able to use this intervention. Args: node: The node to intervene on. seed: The new seed to put to the environment state of the node. Returns: A new node, which environment state has been modified. """ # Create the new state. state = copy.deepcopy(node.env_state) state.seed = seed self._env.set_state(state) new_timestep = self._env.reset() new_state = self._env.get_state() return dataclasses.replace( node, env_state=new_state, last_timestep=new_timestep) def change_agent_next_actions( self, node: node_lib.Node, forced_next_actions: list[types.Action], ) -> node_lib.Node: """Changes the next actions of the agent at a given node. This intervention allows the user to change the N next actions of the agent, not only the next one. When stepping the debugger from this node, the list for the next node is actualised by removing the first action (since it has just been executed). Args: node: The node to intervene on. forced_next_actions: The next actions to be taken by the agent. Returns: A new node, which, when stepped from, will force the N next actions taken by the agent. """ return dataclasses.replace(node, forced_next_actions=forced_next_actions)
agent_debugger-main
src/agent_debugger/default_interventions.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The base node interface used in the debugger.""" import dataclasses from typing import Any, Optional, Sequence from agent_debugger.src.agent_debugger import types @dataclasses.dataclass class Node: """A node is the concatenation of the agent_state and the env_state. Besides the agent and env state, it also carries the action taken by the agent and the timestep returned by the environment in the last transition. This transition can be seen as the arrow leading to the state, therefore we call it 'last_action' and 'last_timestep'. The latter will be used to step to the next state. Finally, the node also carries some future agent actions that the user wants to enforce. The first element of the list will be used to force the next transition action, and the list minus this first element will be passed to the next state. """ agent_state: types.AgentState last_action: types.Action env_state: types.EnvState last_timestep: types.TimeStep forced_next_actions: Sequence[types.Action] = () episode_step: int = 0 last_agent_output: Optional[Any] = None @property def is_terminal(self) -> bool: """Returns whether the last timestep is of step_type LAST.""" return self.last_timestep.step_type == types.LastTimeStep
agent_debugger-main
src/agent_debugger/node.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Pycoworld extractors. The extractors act on the node directly, and extract information from it. """ import numpy as np from pycolab import things from agent_debugger.src.agent_debugger import node as node_lib from agent_debugger.src.agent_debugger.pycoworld import types class PycoworldExtractors: """Object containing the pycoworld extractors.""" # pylint: disable=protected-access def get_element_positions( self, node: node_lib.Node, element_id: int, ) -> list[types.Position]: """Returns the position of a sprite/drape/background element. Args: node: The node to intervene on. element_id: The identifier of the element. A full list can be found in the pycoworld/default_constants.py file. """ engine = node.env_state.current_game element_key = chr(element_id) if element_key in engine._sprites_and_drapes: # If it is a sprite. if isinstance(engine._sprites_and_drapes[element_key], things.Sprite): return [engine._sprites_and_drapes[element_key].position] # Otherwise, it's a drape. else: curtain = engine._sprites_and_drapes[element_key].curtain list_tuples = list(zip(*np.where(curtain))) return [types.PycolabPosition(*x) for x in list_tuples] # Last resort: we look at the board and the backdrop. board = engine._board.board list_tuples = list(zip(*np.where(board == ord(element_key)))) backdrop = engine._backdrop.curtain list_tuples += list(zip(*np.where(backdrop == ord(element_key)))) return [types.PycolabPosition(*x) for x in list_tuples] def get_backdrop_curtain(self, node: node_lib.Node) -> np.ndarray: """Returns the backdrop of a pycolab engine from a node.""" return node.env_state.current_game._backdrop.curtain # pylint: enable=protected-access
agent_debugger-main
src/agent_debugger/pycoworld/extractors.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Specific types for the Pycoworld debugger.""" from typing import Union from pycolab import engine as engine_lib from pycolab import things PycolabPosition = things.Sprite.Position Position = Union[PycolabPosition, tuple[float, float]] PycolabEngine = engine_lib.Engine def to_pycolab_position(pos: Position) -> PycolabPosition: """Returns a PycolabPosition from a tuple or a PycolabPosition.""" if isinstance(pos, tuple): return PycolabPosition(*pos) return pos
agent_debugger-main
src/agent_debugger/pycoworld/types.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Specific implementation of the debugger for pycoworld.""" from agent_debugger.src.agent_debugger import agent as debugger_agent from agent_debugger.src.agent_debugger import debugger as dbg from agent_debugger.src.agent_debugger.pycoworld import extractors as pycolab_extractors from agent_debugger.src.agent_debugger.pycoworld import interventions as pycolab_interventions from agent_debugger.src.pycoworld import serializable_environment class PycoworldDebugger(dbg.Debugger): """Overriding the Debugger with additional interventions and extractors. Attributes: interventions: An object to intervene on pycoworld nodes. extractors: An object to extract information from pycoworld nodes. """ def __init__( self, agent: debugger_agent.DebuggerAgent, env: serializable_environment.SerializableEnvironment, ) -> None: """Initializes the object.""" super().__init__(agent, env) self.interventions = pycolab_interventions.PycoworldInterventions(self._env) self.extractors = pycolab_extractors.PycoworldExtractors()
agent_debugger-main
src/agent_debugger/pycoworld/debugger.py
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Pycoworld interventions. These are methods of the form (node, **params) -> new_node. """ import copy import dataclasses from typing import Any import dm_env from agent_debugger.src.agent_debugger import default_interventions from agent_debugger.src.agent_debugger import node as node_lib from agent_debugger.src.agent_debugger.pycoworld import types def _check_positive_position(position: types.Position) -> None: """Checks if the position is positive, required by pycolab.""" if position.row < 0 or position.col < 0: # pytype: disable=attribute-error # enable-nested-classes raise ValueError('The new position must have positive coordinates. Got ' f'{position}.') class InterventionContext: """Context used for interventions, exposing the engine and postprocessing. Attributes: engine: The internal Pycolab game engine, useful to perform interventions. new_node: The node after intervention, which will be returned. """ def __init__(self, node: node_lib.Node): """Initializes.""" self._node = node self._env_state = copy.deepcopy(self._node.env_state) self.engine = self._env_state.current_game self.new_node = None def __enter__(self) -> type['InterventionContext']: """Returns the object itself when we enter the context.""" return self # pytype: disable=bad-return-type def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: """Applies some postprocessing and computes the new node to return.""" self._env_state.current_game._render() # Compute the new timestep that the agent will see. new_observation = copy.deepcopy(self._node.last_timestep.observation) new_observation['board'] = self._env_state.observation_distiller( self._env_state.current_game._board) new_timestep = dm_env.TimeStep( step_type=self._node.last_timestep.step_type, reward=self._node.last_timestep.reward, discount=self._node.last_timestep.discount, observation=new_observation) self.new_node = dataclasses.replace( self._node, env_state=self._env_state, last_timestep=new_timestep) class PycoworldInterventions(default_interventions.DefaultInterventions): """Object containing the pycolab interventions.""" # pylint: disable=protected-access def set_sprite_visibility( self, node: node_lib.Node, sprite_id: int, visibility: bool, ) -> node_lib.Node: """Intervenes on a pycolab environment state to make a sprite (in)visible. Args: node: The node to intervene on. sprite_id: The identifier of the sprite. A full list can be found in the pycoworld/default_constants.py file. visibility: Whether the sprite should be made visible or invisible. Returns: A new node, where the sprite is (in)visible. """ with InterventionContext(node) as context: sprite = context.engine._sprites_and_drapes[chr(sprite_id)] # pytype: disable=attribute-error sprite._visible = visibility return context.new_node # pytype: disable=attribute-error def move_sprite_to( self, node: node_lib.Node, sprite_id: int, dest_position: types.Position, ) -> node_lib.Node: """Intervenes on a pycolab environment state to move a sprite. Args: node: The node to intervene on. sprite_id: The identifier of the sprite. A full list can be found in the pycoworld/default_constants.py file. dest_position: The desired position of the sprite. Returns: A new node, where the sprite has been moved. """ with InterventionContext(node) as context: dest_position = types.to_pycolab_position(dest_position) _check_positive_position(dest_position) sprite = context.engine._sprites_and_drapes[chr(sprite_id)] # pytype: disable=attribute-error sprite._position = dest_position return context.new_node # pytype: disable=attribute-error def move_drape_element_to( self, node: node_lib.Node, drape_id: int, start_position: types.Position, dest_position: types.Position, ) -> node_lib.Node: """Intervenes on a pycolab environment state to move a drape. Args: node: The node to intervene on. drape_id: The identifier of the drape. A full list can be found in the pycoworld/default_constants.py file. start_position: The position of the element to replace, coordinates must be positive. dest_position: The destination position of the element, coordinates must be positive. Returns: A new node, which drape has been updated. """ with InterventionContext(node) as context: dest_position = types.to_pycolab_position(dest_position) start_position = types.to_pycolab_position(start_position) _check_positive_position(start_position) _check_positive_position(dest_position) drape = context.engine._sprites_and_drapes[chr(drape_id)] # pytype: disable=attribute-error drape._c_u_r_t_a_i_n[start_position] = False drape._c_u_r_t_a_i_n[tuple(dest_position)] = True return context.new_node # pytype: disable=attribute-error def remove_drape_element( self, node: node_lib.Node, drape_id: int, position: types.Position, ) -> node_lib.Node: """Intervenes to remove an element in a drape. Args: node: The node to intervene on. drape_id: The identifier of the drape. A full list can be found in the pycoworld/default_constants.py file. position: The position of the element to remove, coordinates must be positive. Returns: A new node, which drape has been updated. """ with InterventionContext(node) as context: position = types.to_pycolab_position(position) _check_positive_position(position) drape = context.engine._sprites_and_drapes[chr(drape_id)] # pytype: disable=attribute-error drape._c_u_r_t_a_i_n[position] = False return context.new_node # pytype: disable=attribute-error def add_drape_element( self, node: node_lib.Node, drape_id: int, position: types.Position, ) -> node_lib.Node: """Intervenes to add an element in a drape. Args: node: The node to intervene on. drape_id: The identifier of the drape. A full list can be found in the pycoworld/default_constants.py file. position: The position of the element to add, coordinates must be positive. Returns: A new node, which drape has been updated. """ with InterventionContext(node) as context: position = types.to_pycolab_position(position) _check_positive_position(position) drape = context.engine._sprites_and_drapes[chr(drape_id)] # pytype: disable=attribute-error drape._c_u_r_t_a_i_n[position] = True return context.new_node # pytype: disable=attribute-error def replace_backdrop_element( self, node: node_lib.Node, position: types.Position, new_element_id: int, ) -> node_lib.Node: """Intervenes to replace an element of the backdrop. Args: node: The node to intervene on. position: The position of the element to replace, coordinates must be positive. new_element_id: The new element id to put at this position. Returns: A new node, where the backdrop has been updated. """ with InterventionContext(node) as context: position = types.to_pycolab_position(position) _check_positive_position(position) context.engine._backdrop._p_a_l_e_t_t_e._legal_characters.add( # pytype: disable=attribute-error chr(new_element_id)) context.engine._backdrop.curtain[tuple(position)] = new_element_id # pytype: disable=attribute-error return context.new_node # pytype: disable=attribute-error def set_frame_count( self, node: node_lib.Node, frame_count: int, ) -> node_lib.Node: """Changes the internal frame number of a pycolab engine. This number influences the 'plot' object, which contains the frame number as an attribute. Args: node: The node to intervene on. frame_count: the frame countto set on the engine. It must be positive. Returns: A new node, where the backdrop has been updated. """ with InterventionContext(node) as context: if frame_count < 0: raise ValueError(f'The frame count must be positive. Got {frame_count}') context.engine._the_plot._frame = frame_count # pytype: disable=attribute-error return context.new_node # pytype: disable=attribute-error # pylint: enable=protected-access
agent_debugger-main
src/agent_debugger/pycoworld/interventions.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. # ============================================================================== """Components for HRL.""" import collections from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple from absl import logging from affordances_option_models import env_utils from affordances_option_models import option_utils from affordances_option_models import rl Options = option_utils.Options Statistics = Dict[str, Any] class TransitionWithOption(NamedTuple): transition: rl.Transition option_id: Options TrajectoryWithOption = List[TransitionWithOption] def run_hrl_policy_in_env( option_policy: Callable[[int, Options], int], policy_over_options: Callable[[int], Options], option_term_fn: Callable[[TransitionWithOption], bool], max_option_length: int, num_episodes: int = 1000, max_steps_per_episode: int = 1000, initial_state: Optional[int] = None, seed: Optional[int] = None, ) -> Tuple[List[TrajectoryWithOption], List[int], List[float], Statistics]: """Executes policy in the environment.""" env = env_utils.make_taxi_environment() env.seed(seed) trajectories = [] lengths = [] rewards = [] option_lengths = [] option_rewards = [] options_per_episode = [] total_steps, total_pickups, total_illegal, total_reward = 0, 0, 0, 0 option_counts = collections.Counter() per_option_rewards = collections.Counter() for _ in range(num_episodes): episode_reward, episode_length, reward, num_options = 0, 0, 0, 0 state = env.reset() if initial_state is not None: env.s = initial_state state = env.s logging.debug('State set to %s', env.s) else: state = env.reset() transitions = [] while True: # Main rollout loop. # Step 1: Decide which option to execute. option_id = policy_over_options(state) option_counts.update({option_id: 1}) num_options += 1 option_reward = 0 for i in range(max_option_length): # Execute the option in the environment. action = option_policy(state, option_id) new_state, reward, done, _ = env.step(action) logging.debug( ('New transition: \n\t' 'State @ t = %s,\n\t' 'action = %s,\n\t' 'option= %s\n\t' 'State @ t+1 = %s,\n\t' 'reward = %s'), env_utils.int_to_state_fn(state), action, option_id, env_utils.int_to_state_fn(new_state), reward) if reward == 20: total_pickups += 1 assert done, 'Episode should terminate when pickup is successful.' if reward == -10: total_illegal += 1 transitions.append( TransitionWithOption( rl.Transition(state, action, reward, new_state, done), option_id)) state = new_state total_steps += 1 total_reward += reward episode_reward += reward episode_length += 1 option_reward += reward if option_term_fn(transitions[-1]): logging.debug('Option terminated. Option length =%d', i) break if episode_length > max_steps_per_episode: logging.debug('Episode too long') break option_rewards.append(option_reward) per_option_rewards.update({option_id: option_reward}) option_lengths.append(i + 1) if done or episode_length > max_steps_per_episode: logging.debug('Episode terminated. Length=%d', episode_length) break trajectories.append(transitions) lengths.append(episode_length) rewards.append(episode_reward) options_per_episode.append(num_options) statistics = { 'num_episodes': num_episodes, 'avg_num_steps_per_episode': total_steps / num_episodes, 'avg_num_illegal_per_step': total_illegal / total_steps, 'avg_success_per_step': total_pickups / total_steps, 'avg_reward_per_step': total_reward / total_steps, 'prop_success': total_pickups / num_episodes, 'prop_illegal': total_illegal / num_episodes, 'avg_episode_reward': sum(rewards) / len(rewards), 'min_episode_reward': min(rewards), 'max_episode_reward': max(rewards), 'min_episode_length': min(lengths), 'max_episode_length': max(lengths), 'avg_num_options_per_episode': ( sum(options_per_episode) / len(options_per_episode)), 'total_options_executed': sum(options_per_episode), 'total_steps': total_steps, 'avg_option_length': sum(option_lengths) / len(option_lengths), 'min_option_length': min(option_lengths), 'max_option_length': max(option_lengths), 'avg_option_reward': sum(option_rewards) / len(option_rewards), 'min_option_reward': min(option_rewards), 'max_option_reward': max(option_rewards), 'most_common_options': {k.name: v / sum(options_per_episode) for k, v in option_counts.most_common(10)}, 'most_common_option_reward': {k.name: (per_option_rewards[k] / v) for k, v in option_counts.most_common(10)}, } logging.info(statistics) assert sum(option_counts.values()) == sum(options_per_episode) return trajectories, lengths, rewards, statistics
affordances_option_models-main
hrl.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 option_utils.""" from absl.testing import absltest from absl.testing import parameterized from affordances_option_models import definitions from affordances_option_models import env_utils from affordances_option_models import option_utils Options = option_utils.Options OptionsAny = option_utils.OptionsAny OptionsDropping = option_utils.OptionsDropping OptionsPicking = option_utils.OptionsPicking ActionMap = definitions.ActionMap class OptionUtilsTest(parameterized.TestCase): def test_number_of_options(self): self.assertLen(option_utils.Options, 75) self.assertLen(option_utils.OptionsDropping, 25) self.assertLen(option_utils.OptionsPicking, 25) self.assertLen(option_utils.OptionsAny, 25) @parameterized.named_parameters( # GoToXX_Any: # - Grid cell of s_tp1 must match the grid cell XX. { 'testcase_name': 'GoTo 0 passenger inside. Dropping', 'option': Options.GoTo0_Any, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 0, 'action': ActionMap.DROP, 'outcome': True, }, { 'testcase_name': 'GoTo 0 passenger inside. Picking', 'option': Options.GoTo0_Any, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 0, 'action': ActionMap.PICKUP, 'outcome': True, }, { 'testcase_name': 'GoTo 0 passenger outside. Picking', 'option': Options.GoTo0_Any, 'passenger_status': 2, 'row': 0, 'col': 0, 'action': ActionMap.PICKUP, 'outcome': True, }, { 'testcase_name': 'GoTo 3 from 2 + East succeeds.', 'option': Options.GoTo3_Any, 'passenger_status': 2, 'row': 0, 'col': 2, 'action': ActionMap.EAST, 'outcome': True, }, { 'testcase_name': 'GoTo (1, 3) from (0, 3) + South succeeds.', 'option': Options.GoTo8_Any, 'passenger_status': 2, 'row': 0, 'col': 3, 'action': ActionMap.SOUTH, 'outcome': True, }, { 'testcase_name': 'GoTo (1, 3) from (0, 3) + EAST Fails.', 'option': Options.GoTo8_Any, 'passenger_status': 2, 'row': 0, 'col': 3, 'action': ActionMap.EAST, 'outcome': False, }, { 'testcase_name': 'GoTo 2 from 2 + East fails.', 'option': Options.GoTo2_Any, 'passenger_status': 2, 'row': 0, 'col': 2, 'action': ActionMap.EAST, 'outcome': False, }, # GoToXX_Drop: # - Action must be DROP. # - Grid cell of s_tp1 must match the grid cell XX. # - Passenger must be inside the taxi. { 'testcase_name': 'Drop passenger in taxi at 0', 'option': Options.GoTo0_Drop, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 0, 'action': ActionMap.DROP, 'outcome': True, }, { 'testcase_name': 'Fail to drop passenger @ 0 (not in vehicle) at 0', 'option': Options.GoTo0_Drop, 'passenger_status': 0, 'row': 0, 'col': 0, 'action': ActionMap.DROP, 'outcome': False, }, { 'testcase_name': 'Fail to drop passenger @ 2 (not in vehicle) at 0', 'option': Options.GoTo0_Drop, 'passenger_status': 2, 'row': 0, 'col': 0, 'action': ActionMap.DROP, 'outcome': False, }, { 'testcase_name': 'Drop passenger in vehicle at (0, 2)', 'option': Options.GoTo2_Drop, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 2, 'action': ActionMap.DROP, 'outcome': True, }, { 'testcase_name': 'Fail Drop passenger in vehicle at (0, 1) when at (0, 2)', 'option': Options.GoTo1_Drop, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 2, 'action': ActionMap.DROP, 'outcome': False, }, # GoToXX_Pickup: # - Action must be PICKUP. # - Grid cell of s_tp1 must match the grid cell XX. # - Passenger must be outside the taxi (doesn't matter where exactly). { 'testcase_name': 'Cannot pickup when action is move.', 'option': Options.GoTo0_Pickup, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 0, 'action': ActionMap.WEST, 'outcome': False, }, { 'testcase_name': 'Fail to pickup passenger already inside.', 'option': Options.GoTo0_Pickup, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 0, 'action': ActionMap.PICKUP, 'outcome': False, }, { 'testcase_name': 'Try to pickup passenger @ 2 at 0', 'option': Options.GoTo0_Pickup, 'passenger_status': 2, 'row': 0, 'col': 0, 'action': ActionMap.PICKUP, 'outcome': True, }, { 'testcase_name': 'Try to pickup passenger @ 0 at 0', 'option': Options.GoTo0_Pickup, 'passenger_status': 0, 'row': 0, 'col': 0, 'action': ActionMap.PICKUP, 'outcome': True, }, ) def test_check_option_termination( self, row, col, passenger_status, action, option, outcome): taxi_state = env_utils.state_to_int_fn( env_utils.TaxiState(row, col, passenger_status, 0)) self.assertEqual( option_utils.check_option_termination(taxi_state, action, option), outcome) if __name__ == '__main__': absltest.main()
affordances_option_models-main
option_utils_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. # ============================================================================== """Custom launchpad nodes. This file contains 3 custom launchpad nodes to do: 1. `Rollout`: Collecting of data from the environment. 2. `Trainer`: Training of affordance and model networks. 3. `Evaluator`: Evaluation of affordance and model networks via value iteration. Additionally there are a few private functions to: 1. Interface between the heuristic and learned version of affordances. 2. Save and load the options, policy over options, models and affordances for later use. """ import functools import itertools import os import shutil import time from typing import Any, Dict, Optional, Union from absl import logging import numpy as np import tensorflow as tf import tensorflow_probability as tfp from affordances_option_models import affordances from affordances_option_models import data as data_tools from affordances_option_models import definitions from affordances_option_models import env_utils from affordances_option_models import hrl from affordances_option_models import networks from affordances_option_models import option_utils from affordances_option_models import task_queue from affordances_option_models import training tfd = tfp.distributions def _np_save( save_path: str, array: Union[np.ndarray, Dict[Any, np.ndarray]]): """Saves a numpy array.""" with open(save_path, 'wb') as fout: np.save(fout, array, allow_pickle=True) def _np_load(load_path: str) -> np.ndarray: """Loads a numpy array.""" with open(load_path, 'rb') as fout: return np.load(fout, allow_pickle=True) @functools.lru_cache(maxsize=1) def _load_options( path_to_options: str, debugging: bool = False ) -> Dict[definitions.Options, np.ndarray]: """Loads options into a table.""" option_policy_table = {} for option_id in option_utils.Options: load_path = os.path.join(path_to_options, option_id.name + '.npz') if debugging and option_id.value > 1: # When debugging, we are just looking for if the code runs and there are # no issues. Since this is usually done locally, we bypass this by # re-using the table loaded for the first option. option_policy_table[option_id] = ( option_policy_table[option_utils.Options(1)]) logging.log_every_n_seconds(logging.WARNING, 'Debugging is on', 10) continue else: option_policy_table[option_id] = _np_load(load_path) logging.info( 'Successfully loaded option: %s from %s', option_id, load_path) return option_policy_table def _make_option_model_table( model_network: tf.keras.Model) -> Dict[str, np.ndarray]: """Creates option model table to be used in value iteration. Args: model_network: A neural network that acts as a model that accepts states and options as tf.Tensors and returns a distribution over transitions (as a tensorflow_probability distribution), option lengths and option rewards. Returns: A dictionary with the following entries: - transitions: The |S| x |A| x |S| option transition table. - rewards: The |S| x |O| table that specifies how much reward is obtained for state-option pair. - lengths: The |S| x |O| table that specifies the length of execution of each state-option pair.. """ # We create a tabular option model here for every state and option pair in # the environment. This can then be plugged into value iteration or other # planning algorithm to obtain a policy over options. logging.info('Creating option model table.') num_states = env_utils.NUM_STATES num_options = len(option_utils.Options) option_transition_table = np.zeros( (num_states, num_options, num_states), dtype=np.float) option_reward_table = np.zeros( (num_states, num_options), dtype=np.float) option_length_table = np.zeros( (num_states, num_options), dtype=np.float) # Get s_t, o_t pairs for every entry in the above matrices. s_t, o_t = list(zip(*list( itertools.product(range(num_states), range(num_options))))) s_t_tf = tf.expand_dims(tf.constant(s_t, dtype=tf.int32), -1) o_t_tf = tf.expand_dims(tf.constant(o_t, dtype=tf.int32), -1) transition_probs, o_length, o_reward = model_network(s_t_tf, o_t_tf) if hasattr(transition_probs, 'probs_parameter'): s_tp1 = transition_probs.probs_parameter().numpy() else: s_tp1 = tf.math.softmax(transition_probs.logits).numpy() option_transition_table[s_t, o_t, :] = s_tp1 option_length_table[s_t, o_t] = o_length.numpy().squeeze().round(1) option_reward_table[s_t, o_t] = o_reward.numpy().squeeze().round(1) logging.info('Option model table created.') return { 'transitions': option_transition_table, 'rewards': option_reward_table, 'lengths': option_length_table } def _make_affordance_table( affordance_network: tf.keras.Model, affordance_mask_threshold: float, ) -> np.ndarray: """Creates an affordance to be used in value iteration. Args: affordance_network: A neural network that takes in a tf.Tensor of states and options and returns a tf.Tensor of probabilities for every intent if it is affordable. Please refer to the inline comments for more details or the paper. affordance_mask_threshold: The threshold at which an affordance value between 0-1 is converted into a binary value representing the affordance. Returns: A table of shape |S| x |O| x |I| indicating for each state-option pair which intents are affordable. """ logging.info('Creating affordance table.') num_states = env_utils.NUM_STATES num_options = len(option_utils.Options) num_intents = len(definitions.Intents) # Get s_t, o_t pairs for every entry in the affordance matrix. s_t, o_t = list(zip(*list( itertools.product(range(num_states), range(num_options))))) s_t_tf = tf.expand_dims(tf.constant(s_t, dtype=tf.int32), -1) o_t_tf = tf.expand_dims(tf.constant(o_t, dtype=tf.int32), -1) affs = affordance_network(s_t_tf, o_t_tf).numpy() # (|S|x|O|, |I|) affs = affs.reshape((num_states, num_options, num_intents)) # (|S|, |O|, |I|) affs_maxed = np.max(affs, 2) # (|S|, |O|) # All options that are above the threshold should be affordable. affs_masked = affs_maxed > affordance_mask_threshold # (|S|, |O|) # If there are any states with no options affordable above the threshold, we # make sure that the most affordable option is available. This ensures that # for every (state, option) pair, at least one option is affordable. affs_maxed_idx = np.argmax(affs_maxed, 1) # (|S|, ) affs_maxed = np.eye(num_options)[affs_maxed_idx] # (|S|, |O|) # We take the OR to combine the two. affs = np.logical_or(affs_maxed, affs_masked).astype(np.float32) # (|S|, |O|) logging.info('Affordance table created.') return affs def _save_hrl_tables( total_steps: int, policy_over_options_table: np.ndarray, option_policy_table: Dict[int, np.ndarray], save_dir: str, affordances_name: str, affordances_table: np.ndarray, ): """Saves tables for HRL evaluation.""" save_path = f'{save_dir}/option_policy_table.npz' if not os.path.exists(save_path): _np_save(save_path, option_policy_table) save_dir = os.path.join( save_dir, f'hrl__affordances_{affordances_name}__numsteps_{total_steps}') if os.path.exists(save_dir): # Overrwrite the previously saved checkpoint. shutil.rmtree(save_dir) os.makedirs(save_dir) save_path = f'{save_dir}/option_model_table.npz' logging.info('Saving options to %s.', save_path) _np_save(save_path, policy_over_options_table) logging.info('Successfully saved option model.') save_path = f'{save_dir}/affordances_mask_table.npz' logging.info('Saving affordances to %s.', save_path) _np_save(save_path, affordances_table) logging.info('Successfully saved affordances.') def _save_models_and_weights( num_trajectories: int, num_steps: int, model_network: tf.keras.Model, save_dir: str, affordance_network: Optional[tf.keras.Model] = None, ): """Saves models and weights to disk.""" save_dir = os.path.join( save_dir, f'model_numtrajectories_{num_trajectories}__numsteps_{num_steps}') if os.path.exists(save_dir): # Overrwrite the previously saved checkpoint. shutil.rmtree(save_dir) os.makedirs(save_dir) option_model_table = _make_option_model_table(model_network) save_path = f'{save_dir}/option_model_table.npz' logging.info('Creating and saving option model to %s.', save_path) _np_save(save_path, option_model_table) logging.info('Successfully saved option model.') save_path = f'{save_dir}/option_model_weights.npz' logging.info('Saving weights to %s.', save_path) _np_save(save_path, model_network.get_weights()) logging.info('Successfully saved weights') if affordance_network is not None: save_path = f'{save_dir}/affordances_weights.npz' logging.info('Saving weights to %s.', save_path) _np_save(save_path, affordance_network.get_weights()) logging.info('Successfully saved weights') def _get_affordances_function( affordances_name: str, trainer_node: Optional['Trainer'], ) -> affordances.AffordancesFn: """Wraps heuristic and learned affordance setup to make them interoperable. Args: affordances_name: The name of the affordances to load. Supports `everything`, `only_pickup_drop`, `only_relevant_pickup_drop`, `learned`. trainer_node: If `affordances_name == "learned"` then a trainer_node is queried to obtain the latest affordance table. Returns: An affordance function that when called returns the relevant affordance table of shape |S| x |O| indicating which options are available in every state. """ if affordances_name == 'learned' and trainer_node is not None: def aff_fn(): return trainer_node.get_affordance_table()['affordances'] else: aff_fn = affordances.get_heuristic_affordances_by_name(affordances_name) aff_fn = functools.lru_cache()(aff_fn) return aff_fn class Trainer: """Trainer class for training models and affordances.""" def __init__( self, *, num_states: int, num_options: int, hidden_dims: int, model_learning_rate: float, affordances_name: str, stop_after_steps: int, queue, num_intents: int = 8, topic_name='default', save_path: str = '~', affordances_threshold: float = 0.5, seed: int = 0, save_every: int = -1, use_learned_affordances: bool = False, writer=None, program_stopper=None): self._program_stopper = program_stopper tf.random.set_seed(seed) self._model_network = networks.IndependentTransitionModel( num_states, num_options, hidden_dims) self._model_optimizer = tf.keras.optimizers.Adam( learning_rate=model_learning_rate) if use_learned_affordances: # When learning affordances, we learn a specialized affordance network # that gives the affordances to the model to mask the updates. self._affordance_network = networks.AffordanceNetwork( num_states, num_options, num_intents, hidden_dims) self._affordance_optimizer = tf.keras.optimizers.Adam( learning_rate=model_learning_rate) heuristic_affordance_fn = None else: # When using heuristic affordances, no affordance network is created # and instead we rely on a heuristic affordance function that provides # the relevant affordances to the model update. self._affordance_network = None self._affordance_optimizer = None heuristic_affordance_fn = affordances.get_heuristic_affordances_by_name( affordances_name) self._affordances_threshold = affordances_threshold self._model_train_step, self._affordance_train_step = ( training.get_training_steps( model_network=self._model_network, model_optimizer=self._model_optimizer, affordance_network=self._affordance_network, affordance_optimizer=self._affordance_optimizer, heuristic_affordance_fn=heuristic_affordance_fn, use_learned_affordances=use_learned_affordances, affordance_mask_threshold=affordances_threshold, ) ) self._queue = queue if stop_after_steps < 0: stop_after_steps = np.inf logging.info('Setting stop after steps to inifnity.') self._stop_after_steps = stop_after_steps logging.info('Training will proceed for %s steps.', self._stop_after_steps) self._save_dir = save_path self._writer = writer self._topic_name = topic_name self._total_steps = 0 self._last_save = 0 self._save_every = save_every def run(self): """Runs training loop.""" count = 0 total_trajectories = 0 time.sleep(5) # Give time for things to fire up. _save_models_and_weights( total_trajectories, self._total_steps, self._model_network, self._save_dir, affordance_network=self._affordance_network) while not self._queue.empty(): try: running_time = time.time() _, result = self._queue.get_task(self._topic_name) queue_get_time = time.time() - running_time running_time = time.time() total_trajectories += len(result['data']) data = training.prepare_data(result['data']) model_losses = self._model_train_step(data) affordance_losses = self._affordance_train_step(data) self._total_steps += result['total_steps'] # Log important statistics. logging_dict = { 'total_steps': self._total_steps, 'updates': count, 'total_trajectories': total_trajectories, 'step_time': time.time() - running_time, 'collection_time': result['collection_time'], 'queue_put_time': result['queue_put_time'], 'queue_get_time': queue_get_time, } logging_dict.update( {k: v.numpy().item() for k, v in model_losses.items()}) logging_dict.update( {k: v.numpy().item() for k, v in affordance_losses.items()}) if self._writer: self._writer.write(logging_dict) count += 1 if self._total_steps - self._last_save > self._save_every: _save_models_and_weights( total_trajectories, self._total_steps, self._model_network, self._save_dir, self._affordance_network) self._last_save = self._total_steps if self._total_steps > self._stop_after_steps: logging.info('Training completed after %s/%s steps.', self._total_steps, self._stop_after_steps) if self._program_stopper is not None: self._program_stopper(mark_as_completed=True) return except task_queue.QueueClosedErrors: break def get_option_model_table(self): logging.info('Get option model has been requested!') return ( _make_option_model_table(self._model_network), self._total_steps) def get_affordance_table(self): logging.info('Affordances requested.') return { 'affordances': _make_affordance_table( self._affordance_network, self._affordances_threshold) } class Evaluation: """Evaluation node for running Value Iteration on option models.""" _EVAL_NODE_SEED = 0 _OPTION_LENGTHS_TO_EVAL = (5, 100) def __init__( self, *, path_to_options: str, affordances_name: str, gamma: float, max_iterations: int, trainer_node: Optional[Trainer] = None, path_to_option_model: Optional[str] = None, writer=None, vi_writer=None, save_every: int = 1, save_path: str = '~', num_eval_episodes: int = 1000, ): self._trainer_node = trainer_node self._path_to_options = path_to_options self._path_to_option_model = path_to_option_model self._affordances_name = affordances_name self._writer = writer self._vi_writer = vi_writer self._max_iterations = max_iterations self._gamma = gamma self._save_every = save_every self._last_save = None self._save_dir = save_path self._num_eval_episodes = num_eval_episodes def _get_latest_options(self): return _load_options(self._path_to_options) def _get_latest_option_model(self): """Returns latest option model from relevant source.""" if self._path_to_option_model is None: logging.info('Getting option model from trainer node.') if self._trainer_node is None: raise RuntimeError( 'Cannot get latest option model if both path to option model and' ' trainer node is None.') return self._trainer_node.get_option_model_table() else: return _np_load(self._path_to_option_model).item(), 1 def _run_evaluation( self, option_policy_table, option_model_table, affordances_fn, total_steps=0 ): """Runs evaluation on a single set of tables.""" logging.info('Running value iteration.') if self._last_save is None: self._last_save = total_steps affordances_mask = affordances_fn() policy_over_options_table, num_iters = option_utils.learn_policy_over_options( option_reward=option_model_table['rewards'], option_transition=option_model_table['transitions'].copy(), option_length=option_model_table['lengths'], stopping_threshold=1e-8, gamma=self._gamma, affordances_fn=affordances_fn, max_iterations=self._max_iterations, seed=self._EVAL_NODE_SEED, writer=self._vi_writer) logging.info('value iteration completed in %d steps', num_iters) def option_policy(state: int, option_id: option_utils.Options) -> int: action_probabilities = option_policy_table[option_id][state] return np.argmax(action_probabilities) if not np.all(policy_over_options_table.sum(1) > 0): # Note that we do not actually check if this is a stochastic policy matrix # since the masking is not guaranteed to result in a probability matrix. # We probably want to do something like set logits to -inf and then # softmax, but since we do not actually use the proabalistic policy and # only the greedy, then this works equivalently. raise ValueError('At least one option should be affordable!') def policy_over_options(state: int) -> option_utils.Options: option_int = np.argmax(policy_over_options_table[state]) # Options are indexed from 1, the model starts at 0. return option_utils.Options(option_int + 1) def option_term_fn(transition: hrl.TransitionWithOption) -> bool: rl_transition = transition.transition env_done = rl_transition.done option_done = option_utils.check_option_termination( rl_transition.s_t, rl_transition.a_t, transition.option_id) return option_done or env_done # Verification of learned policy. all_statistics = { 'num_iters': num_iters, 'total_steps': total_steps, 'affordance_set_size': np.count_nonzero(affordances_mask), } for option_length in self._OPTION_LENGTHS_TO_EVAL: logging.info('running policy with option length = %s', option_length) _, _, _, rollout_statistics = hrl.run_hrl_policy_in_env( option_policy=option_policy, policy_over_options=policy_over_options, option_term_fn=option_term_fn, max_option_length=option_length, num_episodes=self._num_eval_episodes, seed=self._EVAL_NODE_SEED, max_steps_per_episode=100, ) all_statistics.update( {f'{k}_{option_length}': v for k, v in rollout_statistics.items()}) if total_steps - self._last_save > self._save_every: logging.info('Saving HRL tables.') _save_hrl_tables( total_steps, policy_over_options_table, option_policy_table, self._save_dir, self._affordances_name, affordances_table=affordances_mask) self._last_save = total_steps logging.info('Steps since last save: %s', total_steps - self._last_save) return all_statistics def run(self): """Runs value iteration and evaluation for the option model.""" logging.info('Starting evaluation node.') time.sleep(10) # Wait a while so network can get created etc. affordances_fn = _get_affordances_function( self._affordances_name, self._trainer_node) while True: time.sleep(1) logging.info('Obtaining the latest tables.') option_policy_table = self._get_latest_options() option_model_table, total_steps = self._get_latest_option_model() logging.info('Running an evaluation') all_statistics = self._run_evaluation( option_policy_table, option_model_table, affordances_fn, total_steps=total_steps) if not all_statistics: continue all_statistics['eval_affordances_name'] = self._affordances_name if self._writer is not None: self._writer.write(all_statistics) class Rollout: """Rollout nodes to collect data.""" def __init__( self, *, global_seed: int, max_option_length: int, batch_size: int, path_to_options: str, affordances_name: str, queue_writer=None, trainer_node=None, ): self._global_seed = global_seed self._max_option_length = max_option_length self._batch_size = batch_size self._path_to_options = path_to_options self._affordances_name = affordances_name self._queue_writer = queue_writer if affordances_name == 'learned': self._trainer_node = trainer_node else: self._trainer_node = None def _get_option_table(self): return _load_options(self._path_to_options) def run(self): """Runs the rollout node to collect data.""" logging.info('Welcome to the rollout node.') option_policy_table = self._get_option_table() affordances_fn = _get_affordances_function( self._affordances_name, self._trainer_node) logging.info('Using affordances %s in rollout node', self._affordances_name) logging.info('Now collecting data.') queue_put_time = 0 for i in itertools.count(): try: time.sleep(0.5) rollout_seed = self._global_seed + i task_key = str(rollout_seed) running_time = time.time() affordances_mask = affordances_fn() data, total_steps = data_tools.get_trajectories( num_trajectories=self._batch_size, max_trajectory_length=self._max_option_length, option_policies=option_policy_table, affordances_mask=affordances_mask, initial_state=None, uniform_random_initial_state=True, seed=rollout_seed) collection_time = time.time() - running_time logging.info( 'Collected %s trajectories (total_steps=%s) in %s seconds', self._batch_size, total_steps, collection_time) if self._queue_writer is not None: running_time = time.time() self._queue_writer.enqueue_task(task_key, { 'rollout_seed': rollout_seed, 'data': data, 'total_steps': total_steps, 'collection_time': collection_time, 'queue_put_time': queue_put_time, }) queue_put_time = time.time() - running_time else: logging.info('Data was collected but no queue to put it into.') break except task_queue.QueueClosedErrors: logging.info('Queue is empty, ending early!') break
affordances_option_models-main
custom_nodes.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 open-sourcable version of task-queue.""" import queue import time from typing import Any, Dict from absl import logging import launchpad as lp class QueueClosedError(Exception): pass QueueClosedErrors = (QueueClosedError,) class TaskQueueNode: """Light wrapper to expose the Queue as a courier node.""" def __init__(self): self._handle = None def make_node(self): return lp.CourierNode(_QueueImplementation) def register_handle(self, queue_handle): self._handle = queue_handle def reader(self): return self._handle def writer(self): return self._handle class _QueueImplementation: """Implementation of a simple queue.""" def __init__(self, **kwargs): del kwargs # Unused. self._queue = queue.Queue(maxsize=int(1e9)) self._closed = False logging.info('Queue created!') def enqueue_task(self, task_key, data): data = data.copy() data['task_key'] = task_key self._queue.put_nowait(data) logging.log_every_n_seconds( logging.INFO, 'Current queue size is %d', 60, self._queue.qsize()) logging.log_every_n_seconds(logging.INFO, '[PUT] Data = %s', 15, data) def get_task(self, topic_name): del topic_name data: Dict[str, Any] = self._queue.get() task_key = data.pop('task_key') logging.log_every_n_seconds(logging.INFO, '[GET] Data = %s', 15, data) return task_key, data def set_result(self, *args, **kwargs): self._queue.task_done() logging.log_every_n_seconds( logging.INFO, 'Task result was set %s %s', 600, args, kwargs) def closed(self): return self._closed def empty(self): return self._queue.empty() def close(self): while True: if self._queue.empty(): self._closed = True break time.sleep(5)
affordances_option_models-main
task_queue.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. # ============================================================================== """Definitions for constants, options, intents related to the taxienv.""" import enum @enum.unique class Colors(enum.Enum): """Colors for the four destinations in the environment.""" R = 0 G = 1 Y = 2 B = 3 @enum.unique class ActionMap(enum.IntEnum): """Maps human readable actions to the corresponding env integers.""" SOUTH = 0 NORTH = 1 EAST = 2 WEST = 3 PICKUP = 4 DROP = 5 # pylint: disable=invalid-name @enum.unique class Intents(enum.Enum): """Defines the 8 intents to be used in the taxi environment.""" # Passenger is outside the car at destination. R_out = enum.auto() G_out = enum.auto() B_out = enum.auto() Y_out = enum.auto() # Passenger is inside the car in destination. R_in = enum.auto() G_in = enum.auto() B_in = enum.auto() Y_in = enum.auto() # pylint: enable=invalid-name IntentsWithPassengersInside = ( Intents.R_in, Intents.G_in, Intents.B_in, Intents.Y_in ) IntentsWithPassengersOutside = ( Intents.R_out, Intents.G_out, Intents.B_out, Intents.Y_out ) COLOR_TO_INTENT_MAPPING = { Colors.R: [Intents.R_in, Intents.R_out], Colors.G: [Intents.G_in, Intents.G_out], Colors.B: [Intents.B_in, Intents.B_out], Colors.Y: [Intents.Y_in, Intents.Y_out], } class IntentStatus(enum.IntEnum): """Indicates if intents were completed or not.""" complete = 1 incomplete = 0 _NUM_GRID_CELLS = 25 # Unfortunately, we have to define each option explicitly to avoid the # limitations of the functional API given here: # https://docs.python.org/3.6/library/enum.html#functional-api # Disable linter since the `_` is important for option completion logic. # pylint: disable=invalid-name @enum.unique class Options(enum.Enum): """Options as defined by us in the taxi environment. There are three sets of options: GoToXX_Drop: Makes the taxi travel to the grid cell XX and executes the drop action at the end. Passenger must be inside the taxi. GoToXX_Pickup: Makes the taxi travel to the grid cell XX and executes the pickup action at the end. Passenger must be outside the taxi. GoToXX_Any: Makes the taxi travel to the grid cell XX. """ GoTo0_Drop = enum.auto() GoTo1_Drop = enum.auto() GoTo2_Drop = enum.auto() GoTo3_Drop = enum.auto() GoTo4_Drop = enum.auto() GoTo5_Drop = enum.auto() GoTo6_Drop = enum.auto() GoTo7_Drop = enum.auto() GoTo8_Drop = enum.auto() GoTo9_Drop = enum.auto() GoTo10_Drop = enum.auto() GoTo11_Drop = enum.auto() GoTo12_Drop = enum.auto() GoTo13_Drop = enum.auto() GoTo14_Drop = enum.auto() GoTo15_Drop = enum.auto() GoTo16_Drop = enum.auto() GoTo17_Drop = enum.auto() GoTo18_Drop = enum.auto() GoTo19_Drop = enum.auto() GoTo20_Drop = enum.auto() GoTo21_Drop = enum.auto() GoTo22_Drop = enum.auto() GoTo23_Drop = enum.auto() GoTo24_Drop = enum.auto() GoTo0_Pickup = enum.auto() GoTo1_Pickup = enum.auto() GoTo2_Pickup = enum.auto() GoTo3_Pickup = enum.auto() GoTo4_Pickup = enum.auto() GoTo5_Pickup = enum.auto() GoTo6_Pickup = enum.auto() GoTo7_Pickup = enum.auto() GoTo8_Pickup = enum.auto() GoTo9_Pickup = enum.auto() GoTo10_Pickup = enum.auto() GoTo11_Pickup = enum.auto() GoTo12_Pickup = enum.auto() GoTo13_Pickup = enum.auto() GoTo14_Pickup = enum.auto() GoTo15_Pickup = enum.auto() GoTo16_Pickup = enum.auto() GoTo17_Pickup = enum.auto() GoTo18_Pickup = enum.auto() GoTo19_Pickup = enum.auto() GoTo20_Pickup = enum.auto() GoTo21_Pickup = enum.auto() GoTo22_Pickup = enum.auto() GoTo23_Pickup = enum.auto() GoTo24_Pickup = enum.auto() GoTo0_Any = enum.auto() GoTo1_Any = enum.auto() GoTo2_Any = enum.auto() GoTo3_Any = enum.auto() GoTo4_Any = enum.auto() GoTo5_Any = enum.auto() GoTo6_Any = enum.auto() GoTo7_Any = enum.auto() GoTo8_Any = enum.auto() GoTo9_Any = enum.auto() GoTo10_Any = enum.auto() GoTo11_Any = enum.auto() GoTo12_Any = enum.auto() GoTo13_Any = enum.auto() GoTo14_Any = enum.auto() GoTo15_Any = enum.auto() GoTo16_Any = enum.auto() GoTo17_Any = enum.auto() GoTo18_Any = enum.auto() GoTo19_Any = enum.auto() GoTo20_Any = enum.auto() GoTo21_Any = enum.auto() GoTo22_Any = enum.auto() GoTo23_Any = enum.auto() GoTo24_Any = enum.auto() # pylint: enable=invalid-name # See https://docs.python.org/3/library/enum.html#iteration. OptionsDropping = tuple( member for member in Options.__members__.values() if 'Drop' in member.name) OptionsPicking = tuple(member for member in Options.__members__.values() if 'Pickup' in member.name) OptionsAny = tuple( member for member in Options.__members__.values() if 'Any' in member.name)
affordances_option_models-main
definitions.py
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities to work with intents in the taxi domain.""" from affordances_option_models import definitions from affordances_option_models import env_utils from affordances_option_models import option_utils Intents = definitions.Intents IntentStatus = definitions.IntentStatus def is_intent_completed( s_i: int, option_id: option_utils.Options, s_f: int, intent_id: Intents, ) -> IntentStatus: """Determines if a (state, option, state) transition completes an intent. Args: s_i: (Unused) The integer representing the taxi state. option_id: (Unused) The integer representation of the option. s_f: The integer representing the taxi state. intent_id: The intent to check the completion for. Returns: Status of the intent. """ del s_i, option_id # Unused. final_taxi_state = env_utils.int_to_state_fn(s_f) if intent_id not in Intents: raise ValueError( f'Unknown intent_id={intent_id}. See {Intents} for valid intents.') # Obtain which color is reached at this taxi location. color_reached = env_utils.LOCATION_TO_COLOR_MAPPING.get( (final_taxi_state.row, final_taxi_state.col), None) # Determine if the passenger is inside the car. passenger_inside_car = ( final_taxi_state.passenger_status == env_utils.PASSENGER_INSIDE_CAR_STATUS ) if color_reached is None: # No color was reached so the intent could not have been completed. return IntentStatus.incomplete # At this color, the current intent cannot be completed. if intent_id not in definitions.COLOR_TO_INTENT_MAPPING[color_reached]: return IntentStatus.incomplete # This intent is supposed to have the passenger inside the car. if (intent_id in definitions.IntentsWithPassengersInside and passenger_inside_car): return IntentStatus.complete # This intent is supposed to have the passenger outside the car. if (intent_id in definitions.IntentsWithPassengersOutside and not passenger_inside_car): if final_taxi_state.passenger_status == color_reached.value: # Color must match the passenger status. return IntentStatus.complete return IntentStatus.incomplete
affordances_option_models-main
intent_utils.py
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Reinforcement learning functions.""" import datetime from typing import Callable, List, NamedTuple, Optional, Tuple, Union from absl import logging import numpy as np from affordances_option_models import affordances from affordances_option_models import env_utils DEFAULT_GAMMA = 0.99 class Transition(NamedTuple): """Container storing the transition for tensorflow.""" # NOTE: Do not change this to a dataclass to maintain tuple semantics. s_t: int # The starting state where the action was taken. a_t: int # The action taken. r_tp1: float # The reward after taking the action. s_tp1: int # The state after taking the action. done: bool # The environment terminated after this transition. Trajectory = List[Transition] def _compute_q_v( reward_matrix, gamma, transition_matrix, values, affordance_mask=None): """Computes Q-value.""" # All transitions out of the goal state should be masked out since you cannot # actually _start_ your trajectories here and the environment terminates once # you get here. # TODO(zaf): Do this in a nicer way by doing a transition_matrix.copy() or # doing this masking somewhere else. transition_matrix[env_utils.GOAL_STATES, :] = 0 q_values = reward_matrix + gamma * np.einsum( 'ijk,k->ij', transition_matrix, values) if affordance_mask is not None: # Set Q-values that are unaffordable to the worst q-value. q_values = ( q_values * affordance_mask + (1 - affordance_mask) * np.min(q_values)) values_new = np.max(q_values, axis=1) value_diff = np.absolute(values - values_new) return q_values, values_new, value_diff def extract_greedy_policy( reward_matrix: np.ndarray, transition_matrix: np.ndarray, values: np.ndarray, gamma: Union[float, np.ndarray] = DEFAULT_GAMMA, seed: Optional[int] = None, affordances_fn: Optional[affordances.AffordancesFn] = None, ) -> np.ndarray: """Returns a table containing the best greedy actions to take.""" rng = np.random.default_rng(seed) if affordances_fn is not None: affordances_mask = affordances_fn() else: affordances_mask = None q_values, _, _ = _compute_q_v( reward_matrix, gamma, transition_matrix, values, affordances_mask) # Use "random" argmax with stochastic tie-breaking: rargmax = lambda arr: rng.choice(np.flatnonzero(arr)) best_actions = np.apply_along_axis( rargmax, 1, np.isclose(q_values, q_values.max(-1, keepdims=True))) num_states, num_actions = reward_matrix.shape del num_states pi = np.eye(num_actions)[best_actions] assert pi.shape == reward_matrix.shape return pi def value_iteration( reward_matrix: np.ndarray, transition_matrix: np.ndarray, gamma: Union[float, np.ndarray] = DEFAULT_GAMMA, stopping_threshold: float = 0.0001, max_iterations: int = 100, affordances_fn: Optional[affordances.AffordancesFn] = None, writer=None, ) -> Tuple[np.ndarray, datetime.timedelta, int]: """Obtains the optimal policy for an MDP using value iteration. Args: reward_matrix: Array of shape |S| x |A| determiniting rewards for a transition. transition_matrix: Array of shape |S| x |A| x |S| determining the probability of transitioning from (s, a) to s'. gamma: Discount factor. If this is a matrix, it must be of shape |S| x |A|. stopping_threshold: The minimum change in the values needed to prevent the algorithm from stopping early. max_iterations: The maximum number of iterations to run value iteration for. affordances_fn: A function that returns the list of affordances and a mask. writer: Writer to write data. Returns: The values (V_pi of shape |S|) at the end of value iteration. The amount of time value iteration was run for. The number of iterations value iteration ran for before exiting. """ start_time = datetime.datetime.now() num_states, num_actions, _ = transition_matrix.shape if reward_matrix.shape != (num_states, num_actions): raise ValueError( f'Reward matrix ({reward_matrix.shape})has an incompatible shape to ' f'transition matrix ({transition_matrix.shape})') values = np.zeros(num_states) if affordances_fn is not None: # Cache the mask so we don't repeatedly call it. affordances_mask = affordances_fn() else: affordances_mask = None for i in range(max_iterations): _, values, value_diff = _compute_q_v( reward_matrix, gamma, transition_matrix, values, affordances_mask) if writer is not None: writer.write({ 'iteration': i, 'max_value': np.max(values), 'min_value': np.min(values), 'mean_value': np.mean(values), 'mean_diff': np.mean(value_diff), 'max_diff': np.mean(value_diff), }) if np.all(value_diff < stopping_threshold): logging.debug('Terminating value iteration: stopping threshold reached.') break elapsed = datetime.datetime.now() - start_time logging.info( 'Value iteration completed. Value Diff: %s, iterations: %s, time : %s', np.mean(value_diff), i, elapsed) return values, elapsed, i def run_policy_in_env( policy: Callable[[int], int], num_episodes: int = 1000, max_steps_per_episode: int = 1000, initial_state: Optional[int] = None, seed: Optional[int] = None, termination_fn: Callable[[Transition], bool] = lambda t: t.done, ) -> Tuple[List[Trajectory], List[int], List[float]]: """Executes policy in the environment.""" env = env_utils.make_taxi_environment() env.seed(seed) total_steps, total_pickups, total_illegal, total_reward = 0, 0, 0, 0 trajectories = [] lengths = [] rewards = [] for _ in range(num_episodes): episode_reward, episode_length, reward = 0, 0, 0 state = env.reset() if initial_state is not None: env.s = initial_state state = env.s logging.debug('State set to %s', env.s) else: state = env.reset() transitions = [] for _ in range(max_steps_per_episode): action = policy(state) new_state, reward, done, _ = env.step(action) logging.debug( ('New transition: \n\t' 'State @ t = %s,\n\t' 'action = %s,\n\t' 'State @ t+1 = %s,\n\t' 'reward = %s'), env_utils.int_to_state_fn(state), action, env_utils.int_to_state_fn(new_state), reward) if reward == 20: total_pickups += 1 assert done, 'Episode should terminate when pickup is successful.' if reward == -10: total_illegal += 1 transitions.append( Transition(state, action, reward, new_state, done)) state = new_state total_steps += 1 total_reward += reward episode_reward += reward episode_length += 1 if termination_fn(transitions[-1]): break trajectories.append(transitions) lengths.append(episode_length) rewards.append(episode_reward) logging.debug( ('Results average over %d episodes.\n\t' 'Average timesteps per episode: %s\n\t' 'Average illegal pickups/drops per step: %s\n\t' 'Average successful pickups per step: %s\n\t' 'Average reward per step: %s\n\t' 'Average episode reward: %s\n\t' 'Min/Max episode reward: %s/%s\n\t' 'Min/Max episode length: %s/%s\n\t'), num_episodes, total_steps / num_episodes, total_illegal / total_steps, total_pickups / total_steps, total_reward / total_steps, sum(rewards) / len(rewards), min(rewards), max(rewards), min(lengths), max(lengths), ) assert len(lengths) == num_episodes assert len(rewards) == num_episodes assert len(trajectories) == num_episodes return trajectories, lengths, rewards
affordances_option_models-main
rl.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 rl.""" from absl.testing import absltest import numpy as np from affordances_option_models import env_utils from affordances_option_models import rl class RlTest(absltest.TestCase): def test_value_iteration_policy_evaluation(self): """Integration test for RL components.""" # Obtain a bad policy in the environment. _, P_matrix, R_matrix = env_utils.get_transition_and_reward_matrices() # pylint: disable=invalid-name bad_values, _, _ = rl.value_iteration(R_matrix, P_matrix, max_iterations=1) pi_bad = rl.extract_greedy_policy(R_matrix, P_matrix, bad_values, seed=1) _, lengths, rewards = rl.run_policy_in_env( lambda s: np.argmax(pi_bad[s]), num_episodes=100, max_steps_per_episode=1000, seed=1) reward_bad = rewards[-1] self.assertLessEqual( sum(rewards) / sum(lengths), -1.0, msg='Avg reward per step should be bad for the untrained policy.') # Obtain a good policy in the environment. bad_values, _, num_iterations = rl.value_iteration( R_matrix, P_matrix, max_iterations=10000) pi_good = rl.extract_greedy_policy(R_matrix, P_matrix, bad_values, seed=1) _, lengths, rewards = rl.run_policy_in_env( lambda s: np.argmax(pi_good[s]), num_episodes=100, max_steps_per_episode=1000, seed=1) reward_good = rewards[-1] self.assertLess( num_iterations, 20, msg='Value iteration should take <= 20 iterations to converge.') self.assertGreater(reward_good, reward_bad) self.assertGreater( sum(rewards) / sum(lengths), 0, msg='Avg reward per step should be > zero for the trained policy.') if __name__ == '__main__': absltest.main()
affordances_option_models-main
rl_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 intent_utils.""" from absl.testing import absltest from absl.testing import parameterized from affordances_option_models import env_utils from affordances_option_models import intent_utils Intents = intent_utils.Intents IntentStatus = intent_utils.IntentStatus class IntentUtilsTest(parameterized.TestCase): @parameterized.named_parameters( { 'testcase_name': 'Matches passenger state and taxi location', 'intent_id': Intents.R_in, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 0, 'status': IntentStatus.complete, }, { 'testcase_name': 'Does not matches passenger state and taxi location', 'intent_id': Intents.G_in, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 0, 'status': IntentStatus.incomplete, }, { 'testcase_name': 'Matches taxi location but not pass state', 'intent_id': Intents.R_out, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 0, 'col': 0, 'status': IntentStatus.incomplete, }, { 'testcase_name': 'Matches pass state but not location', 'intent_id': Intents.R_in, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 1, 'col': 0, 'status': IntentStatus.incomplete, }, { 'testcase_name': 'Matches pass state outside @ location 1.', 'intent_id': Intents.R_out, 'passenger_status': 0, 'row': 0, 'col': 0, 'status': IntentStatus.complete, }, { 'testcase_name': 'Matches pass state outside @ location 2.', 'intent_id': Intents.B_out, 'passenger_status': 3, 'row': 4, 'col': 3, 'status': IntentStatus.complete, }, { 'testcase_name': 'Matches pass state outside but wrong location.', 'intent_id': Intents.R_out, 'passenger_status': 2, 'row': 0, 'col': 0, 'status': IntentStatus.incomplete, }, { 'testcase_name': 'Does not match pass state outside @ location.', 'intent_id': Intents.G_out, 'passenger_status': 1, 'row': 0, 'col': 0, 'status': IntentStatus.incomplete, }, { 'testcase_name': 'Random location + passenger inside, incomplete 1.', 'intent_id': Intents.G_out, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 2, 'col': 2, 'status': IntentStatus.incomplete, }, { 'testcase_name': 'Random location + passenger inside, incomplete 2.', 'intent_id': Intents.G_in, 'passenger_status': env_utils.PASSENGER_INSIDE_CAR_STATUS, 'row': 2, 'col': 2, 'status': IntentStatus.incomplete, }, ) def test_is_intent_completed( self, row, col, passenger_status, intent_id, status): taxi_state = env_utils.state_to_int_fn( env_utils.TaxiState(row, col, passenger_status, 0)) self.assertEqual( intent_utils.is_intent_completed(None, None, taxi_state, intent_id), status) if __name__ == '__main__': absltest.main()
affordances_option_models-main
intent_utils_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. # ============================================================================== r"""Utilities to make it easier to work with the taxi environment. The full description of the environment can be found here https://gym.openai.com/envs/Taxi-v2/. The general idea is that the environment is a 5x5 grid world with 4 goal locations (represented by `Colors`). The taxi can be in any of the 25 states in the world. The passenger can be in one of the four goal positions or inside the taxi. The destination represents which goal position the passenger needs to be in at the end of the episode. The agent controls the taxi and gets +20 for dropping the passenger to the correct goal. The agent gets -10 if it drops the passenger to the wrong goal. The agent gets -1 for each step of the episode. """ from typing import Any, NamedTuple, Tuple import gym import numpy as np from affordances_option_models import definitions Colors = definitions.Colors PASSENGER_INSIDE_CAR_STATUS = 4 # These are the "goal" states in which you cannot enter unless you complete the # goal of dropping the passenger in the right place. We use these values in # RL algorithms to mask the transition from here to anywhere. GOAL_STATES = (0, 85, 410, 475) class TaxiState(NamedTuple): """Human readable version of taxi state.""" row: int col: int # Passenger status can be 0, 1, 2, 3, 4 where 0-3 represent where the # passenger is in one of the 4 goal locations and 4 represents the passenger # inside the car. passenger_status: int destination: int def validate(self): if self.passenger_status > PASSENGER_INSIDE_CAR_STATUS: raise ValueError('Passenger is in undefined location.') if self.destination > 3: raise ValueError('Only 4 possible destinations are valid.') if not 0 <= self.row <= 4: raise ValueError('Row must be between (0, 4)') if not 0 <= self.col <= 4: raise ValueError('Col must be between (0, 4)') def make_taxi_environment(): return gym.make('Taxi-v2').env _GLOBAL_ENV = make_taxi_environment() NUM_STATES = _GLOBAL_ENV.nS NUM_ACTIONS = _GLOBAL_ENV.nA def state_to_int_fn(taxi_state: TaxiState) -> int: """Converts a readable state in the environment to the integer state.""" taxi_state.validate() return _GLOBAL_ENV.encode(*taxi_state) def int_to_state_fn(x: int) -> TaxiState: """Converts an integer representation of state into a human readable one.""" state = TaxiState(*_GLOBAL_ENV.decode(x)) state.validate() return state # Maps human readable color from the visualization into one of 4 goal states. COLOR_TO_LOCATION_MAPPING = { Colors.R: _GLOBAL_ENV.locs[0], Colors.G: _GLOBAL_ENV.locs[1], Colors.Y: _GLOBAL_ENV.locs[2], Colors.B: _GLOBAL_ENV.locs[3] } # Maps the 4 goal states to a human readable color. LOCATION_TO_COLOR_MAPPING = {v: k for k, v in COLOR_TO_LOCATION_MAPPING.items()} def grid_cell_to_xy(pos: int, grid_size: int = 5) -> Tuple[int, int]: """Converts an integer from 0-24 into an (x, y) position.""" num_cells = grid_size * grid_size - 1 if not 0 <= pos <= num_cells: raise ValueError(f'Grid cell does not exist in grid of size {grid_size}') x = pos // grid_size y = pos % grid_size return (x, y) def get_transition_and_reward_matrices() -> Tuple[Any, np.ndarray, np.ndarray]: """Obtains transition and reward matrices for taxi as numpy arrays. Use these quantities to do value iteration and obtain the best possible flat policy. Returns: P: The internal dictionary representation of the transition matrix as given by Gym. P_matrix: A |S| x |A| x |S| probability transition matrix where P[s, a, s'] represents the probability of transitioning from state s, to s' by taking action a. R_matrix: A |S| x |A| matrix representing where R[s, a] represents the reward obtained by taking action a from state s. """ num_states = _GLOBAL_ENV.nS num_actions = _GLOBAL_ENV.nA # pylint: disable=invalid-name P = { s: {a: [tup[:3] for tup in tups] for (a, tups) in a2d.items() } for (s, a2d) in _GLOBAL_ENV.P.items() } P_matrix = np.zeros((num_states, num_actions, num_states), dtype=np.float32) R_matrix = np.zeros((num_states, num_actions)) # pylint: enable=invalid-name for (s, transition) in P.items(): for a in range(num_actions): prob, sprime, reward = transition[a][0] P_matrix[s, a, sprime] = prob R_matrix[s, a] = reward return P, P_matrix, R_matrix
affordances_option_models-main
env_utils.py
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Simple neural networks for learning affordances and models.""" from typing import Optional import tensorflow as tf import tensorflow_probability as tfp class OneHotAndConcatLayer(tf.keras.Model): """One hot's and concatenates the input data.""" def __init__(self, depth1, depth2): super().__init__() self._depth1 = depth1 self._depth2 = depth2 def __call__(self, x, y): x, y = tf.squeeze(x, 1), tf.squeeze(y, 1) return tf.concat( (tf.one_hot(x, self._depth1), tf.one_hot(y, self._depth2)), axis=1) class BaseNetwork(tf.keras.Model): """A basic network that onehot->concatenates->applies Dense.""" def __init__( self, depth1: int, depth2: int, num_outputs: int, num_hiddens: Optional[int] = None, final_with_bias: bool = True, kernel_initializer: str = 'glorot_uniform', # Default from Keras. ): super().__init__() self._concat_layer = OneHotAndConcatLayer(depth1, depth2) if num_hiddens is None or num_hiddens <= 0: self._dense_layer = None else: self._dense_layer = tf.keras.layers.Dense( num_hiddens, activation=tf.keras.activations.relu) self._out = tf.keras.layers.Dense( num_outputs, activation=tf.keras.activations.linear, use_bias=final_with_bias, kernel_initializer=kernel_initializer, ) def __call__(self, state, option): x = self._concat_layer(state, option) if self._dense_layer is not None: x = self._dense_layer(x) return self._out(x) class IndependentTransitionModel(tf.keras.Model): """Transition model without the shared representation.""" def __init__( self, num_states: int, num_options: int, num_hiddens: Optional[int] = None): super().__init__() self._logits_layer = BaseNetwork( num_states, num_options, num_states, num_hiddens) self._length_layer = BaseNetwork( num_states, num_options, 1, num_hiddens) self._reward_layer = BaseNetwork( num_states, num_options, 1, num_hiddens) def __call__(self, state, option): dist = tfp.distributions.Categorical(self._logits_layer(state, option)) length = tf.keras.activations.relu(self._length_layer(state, option)) + 1 rewards = self._reward_layer(state, option) return dist, length, rewards class AffordanceNetwork(tf.keras.Model): """Network that outputs if a certain state-option pair is affordable.""" def __init__( self, num_states: int, num_options: int, num_intents: int, num_hiddens: Optional[int] = None, # Used to rescale the logits so there is a bias towards a certain value. shift_constant: float = 2.0, ): super().__init__() self._main_layer = BaseNetwork( num_states, num_options, num_intents, num_hiddens) self._shift_constant = shift_constant def __call__(self, state, option): x = self._main_layer(state, option) x = tf.keras.activations.sigmoid(x + self._shift_constant) return x
affordances_option_models-main
networks.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 related to options and learning option policies in the Taxi-v2.""" from typing import Optional, Tuple from absl import logging import numpy as np from affordances_option_models import affordances from affordances_option_models import definitions from affordances_option_models import env_utils from affordances_option_models import rl Options = definitions.Options OptionsDropping = definitions.OptionsDropping OptionsPicking = definitions.OptionsPicking OptionsAny = definitions.OptionsAny _TRANSITION_DICT, _TRANSITION_MATRIX = ( env_utils.get_transition_and_reward_matrices()[:-1]) def check_option_termination( s_t: int, a_t: int, option: Options) -> bool: """Given an (s, a) transition, determines if an option_id terminates in P. Args: s_t: The state at time t. a_t: The action at time t. option: The option you want to check completion for. The following termination conditions apply: GoToXX_Drop: - Action must be DROP. - Grid cell of s_tp1 must match the grid cell XX. - Passenger must be inside the taxi. GoToXX_Pickup: - Action must be PICKUP. - Grid cell of s_tp1 must match the grid cell XX. - Passenger must be outside the taxi (doesn't matter where exactly). GoToXX_Any: - Grid cell of s_tp1 must match the grid cell XX. Returns: boolean indicating if the option terminates in this transition. """ if option not in Options: raise ValueError( f'Unknown Option {option}. Valid: {Options.__members__.values()}') _, s_tp1, _ = _TRANSITION_DICT[s_t][a_t][0] _, _, passenger_state, _ = env_utils.int_to_state_fn(s_t) taxi_row, taxi_col, _, _ = env_utils.int_to_state_fn(s_tp1) if option in OptionsDropping: # Option is supposed to drop off a passenger so action must be dropping. if a_t != definitions.ActionMap.DROP: return False # If passenger was not in the car, this option cannot terminate. if passenger_state != env_utils.PASSENGER_INSIDE_CAR_STATUS: return False if option in OptionsPicking: # Option is supposed to pick up a passenger so action must be picking. if a_t != definitions.ActionMap.PICKUP: return False # If the passenger is in the car, then picking up is not possible. if passenger_state == env_utils.PASSENGER_INSIDE_CAR_STATUS: return False # Now check if the option "go to" location matches the current taxi position. # Options are named "GoToXX_??" where XX us the grid index. grid_idx = int(option.name.replace('GoTo', '').split('_')[0]) grid_row, grid_col = env_utils.grid_cell_to_xy(grid_idx) if (taxi_row, taxi_col) == (grid_row, grid_col): return True else: return False def compute_per_step_matrices_for_option_learning( option: Options, r_option_completion: float = 1.0, r_other: float = 0.0, ) -> Tuple[np.ndarray, np.ndarray]: """Computes per-step matrices needed to learn option polices. Args: option: The option for which you want to compute the matrices for. r_option_completion: The reward for successful completion of the option. r_other: The reward for all other steps of the option. Returns: 1. A matrix containing the per-step rewards for the requested option. 2. A matrix containing the termination mask for the transition matrix. e.g. if the entry (s, a) has a 1, transitions can take place. If it has a zero it terminates. """ taxienv = env_utils.make_taxi_environment() num_states, num_actions = taxienv.nS, taxienv.nA option_step_reward = np.full((num_states, num_actions), r_other) option_transition_mask = np.ones((num_states, num_actions), dtype=np.float) for s in range(num_states): for a in range(num_actions): if check_option_termination(s, a, option): option_step_reward[s, a] = r_option_completion option_transition_mask[s, a] = 0.0 # No possible transitions from here. return option_step_reward, option_transition_mask def learn_option_policy( option: Options, gamma: float = rl.DEFAULT_GAMMA, stopping_threshold: float = 0.0001, max_iterations: int = 10000, seed: Optional[int] = None, ) -> Tuple[np.ndarray, int]: """Learns the low level policy for an option. Args: option: The option for which to learn the policy. gamma: Discount factor in VI. stopping_threshold: Stop if the change in value is less than this value. max_iterations: Maximum number of iterations to run VI. seed: For tie-breaking. Returns: pi_star: Low level policy, |S| x |A| that achieves the desired option. """ r_option, b_option = compute_per_step_matrices_for_option_learning(option) # The transition matrix must be masked to take into account when an option # will terminate. For example, if the option termination condition is to go to # state X, then it must not be able to go to any other state after. The # b_option matrix contains this information and we expand dimensions to # automatically broadcast and mask the usual transition matrix. b_option = np.expand_dims(b_option, -1) masked_transition_matrix = b_option * _TRANSITION_MATRIX V_star, _, num_iters = rl.value_iteration( # pylint: disable=invalid-name reward_matrix=r_option, transition_matrix=masked_transition_matrix, max_iterations=max_iterations, stopping_threshold=stopping_threshold, gamma=gamma) pi_star = rl.extract_greedy_policy( r_option, masked_transition_matrix, V_star, gamma=gamma, seed=seed) return pi_star, num_iters def learn_policy_over_options( option_reward: np.ndarray, option_transition: np.ndarray, option_length: np.ndarray, gamma: float = rl.DEFAULT_GAMMA, stopping_threshold: float = 0.0001, max_iterations: int = 10000, seed: Optional[int] = None, affordances_fn: Optional[affordances.AffordancesFn] = None, writer=None, ) -> Tuple[np.ndarray, int]: """Learns the policy over option policies. Args: option_reward: Reward matrix of shape |S| x |O| that determines the environment reward for every state option pair. option_transition: Transition matrix of shape |S| x |O| x |S| that determines the transition state after executing an option in a state. option_length: Length matrix of shape |S| x |O| that determines the Length of execution for every state option pair. gamma: Discount factor in VI. stopping_threshold: Stop if the change in value is less than this value. max_iterations: Maximum number of iterations to run VI. seed: For tie-breaking. affordances_fn: Affordances and relevant masking for the bellman update. writer: An optional writer to save data. Returns: pi_star: Policy over options, |S| x |O|. """ if option_length.min() < 1: logging.error( ('At least one option has a length < 1 at %s (values=%s). Clipping has ' 'occurred.'), np.where(option_length < 1)[0], option_length[option_length < 1]) option_length = np.clip(option_length, 1, 100) if np.any(option_transition.sum(-1).round(2) > 1): raise ValueError( 'At least one probability distribution from a (state, option) pair ' 'had a sum > 1.') if not (np.all(option_transition <= 1) and np.all(option_transition >= 0)): raise ValueError( 'At least one transitition probability is not between (0, 1).') gamma = gamma ** option_length num_states, num_options = option_reward.shape if option_transition.shape != (num_states, num_options, num_states): raise ValueError( f'Option transition matrix has shape {option_transition.shape}. ' f'Expected {(num_states, num_options, num_states)}') if gamma.shape != (num_states, num_options): raise ValueError( f'gamma matrix has shape {gamma.shape}. ' f'Expected {(num_states, num_options)}') V_star, _, num_iters = rl.value_iteration( # pylint: disable=invalid-name reward_matrix=option_reward, transition_matrix=option_transition, max_iterations=max_iterations, stopping_threshold=stopping_threshold, affordances_fn=affordances_fn, gamma=gamma, writer=writer) pi_star = rl.extract_greedy_policy( option_reward, option_transition, V_star, gamma=gamma, seed=seed, affordances_fn=affordances_fn) return pi_star, num_iters
affordances_option_models-main
option_utils.py
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Learn models by rolling out trained options in the environment. This launchpad script uses `task_queue` that creates a queue of rollout requests that collect data in parallel. The option model is then trained with the rollout data sent back by the consumers via the queue. Example commands for both heuristic: ``` python3 -m affordances_option_models.lp_learn_model_from_options \ --lp_launch_type=local_mt --num_rollout_nodes=1 --seed=0 \ --affordances_name=everything --total_steps=50000000 \ --path_to_options=/where/your/options/are/saved ``` and learned affordances: ``` python3 -m affordances_option_models.lp_learn_model_from_options -- \ --lp_launch_type=local_mt --num_rollout_nodes=1 --seed=0 \ --affordances_name=learned --affordances_threshold=0.75 \ --total_steps=50000000 --path_to_options=/where/your/options/are/saved ``` """ from absl import app from absl import flags from absl import logging from acme.utils import loggers import launchpad as lp from affordances_option_models import custom_nodes from affordances_option_models import env_utils from affordances_option_models import option_utils from affordances_option_models import task_queue ALL_AFFORDANCE_TYPES = [ 'everything', 'only_pickup_drop', 'only_relevant_pickup_drop', 'learned'] flags.DEFINE_integer('num_rollout_nodes', 1, 'Number of rollout nodes.') flags.DEFINE_string('path_to_options', None, 'Location to load the options.') flags.DEFINE_integer('total_steps', -1, 'Number of steps to do training for.') flags.DEFINE_integer('seed', 1, 'The seed to use for training.') flags.DEFINE_enum('affordances_name', 'everything', ALL_AFFORDANCE_TYPES, 'The type of affordances to use.') flags.DEFINE_float( 'affordances_threshold', None, ('A threshold between 0-1 to obtain affordance during learning. When set to' ' 0, all options are affordable. When set to 1, no options are affordable.' ' If this is None and --affordances_name=learned, and error will be' ' thrown requiring the user to set it.')) flags.DEFINE_string('save_path', '~/affordances_theory/experiment', 'Path to save affordances, models and policy over options.') FLAGS = flags.FLAGS _GLOBAL_SEED = 424242 def make_trainer_node( model_learning_rate: float, stop_after_steps: int, hidden_dims: int, program_stopper, affordances_name: str, seed: int, save_every: int, save_path: str, affordances_threshold: float = 0.5, topic_name: str = 'default', ): """Creates a training node to learn the models.""" def trainer_node(queue): logging.info('Beginning training...') log_writer = loggers.make_default_logger( 'experiment', time_delta=0, asynchronous=True) log_writer = loggers.GatedFilter.periodic(log_writer, 10) trainer = custom_nodes.Trainer( num_states=env_utils.NUM_STATES, num_options=len(option_utils.Options), hidden_dims=hidden_dims, stop_after_steps=stop_after_steps, model_learning_rate=model_learning_rate, affordances_name=affordances_name, affordances_threshold=affordances_threshold, use_learned_affordances=affordances_name == 'learned', topic_name=topic_name, queue=queue, save_path=save_path, save_every=save_every, seed=seed, program_stopper=program_stopper, writer=log_writer) return trainer return trainer_node def make_evaluation_node( path_to_options, gamma, max_iterations, affordances_name: str, save_path: str, save_every: int, ): """Creates a training node to learn the models.""" num_eval_episodes = 1 if FLAGS.lp_launch_type.startswith('test') else 1000 def evaluation_node(trainer_node): logging.info('Beginning evaluation node...') log_writer = loggers.make_default_logger( f'evaluation_{affordances_name}', time_delta=0, asynchronous=True) log_writer = loggers.GatedFilter.periodic(log_writer, 10) evaluation = custom_nodes.Evaluation( path_to_options=path_to_options, affordances_name=affordances_name, gamma=gamma, max_iterations=max_iterations, trainer_node=trainer_node, save_path=save_path, save_every=save_every, num_eval_episodes=num_eval_episodes, writer=log_writer) return evaluation return evaluation_node def _make_program(model_learning_rate: float, stop_after_steps: int, batch_size: int, path_to_options: str, max_option_length: int, affordances_name: str, use_affordances_rollout_node: bool, hidden_dims: int, save_path: str, max_iterations_for_value_iter: int, seed: int, affordances_threshold: float = 0.5, num_rollout_nodes=1): """Creates the launchpad program.""" program = lp.Program('model_learning') program_stopper = lp.make_program_stopper(FLAGS.lp_launch_type) topic_name = 'default' ############################## # Task Queue # ############################## with program.group('queue'): queue = task_queue.TaskQueueNode() queue_handle = program.add_node(queue.make_node()) queue.register_handle(queue_handle) ############################## # Training node # ############################## with program.group('trainer'): trainer_node = lp.CourierNode( make_trainer_node( model_learning_rate=model_learning_rate, stop_after_steps=stop_after_steps, hidden_dims=hidden_dims, program_stopper=program_stopper, affordances_name=affordances_name, affordances_threshold=affordances_threshold, topic_name=topic_name, save_every=200000, save_path=save_path, seed=_GLOBAL_SEED * seed, ), queue.reader()) trainer_node = program.add_node(trainer_node) ############################## # Evaluation node # ############################## with program.group('evaluator'): affordance_types = ALL_AFFORDANCE_TYPES.copy() if affordances_name == 'learned': # If the affordances are learned online, do not use heuristic affordances. affordance_types = ['learned'] else: affordance_types.remove('learned') for evaluation_affordance_name in affordance_types: evaluation_node = lp.CourierNode( make_evaluation_node( path_to_options=path_to_options, gamma=0.99, max_iterations=max_iterations_for_value_iter, affordances_name=evaluation_affordance_name, save_path=save_path, save_every=200000, ), trainer_node) program.add_node(evaluation_node) ############################## # Problems Solver # ############################## if use_affordances_rollout_node: rollout_node_affordances = affordances_name else: rollout_node_affordances = 'everything' with program.group('rollouts'): for i in range(num_rollout_nodes): rollout_node = lp.CourierNode( custom_nodes.Rollout, global_seed=seed * _GLOBAL_SEED + i, batch_size=batch_size, path_to_options=path_to_options, affordances_name=rollout_node_affordances, max_option_length=max_option_length, queue_writer=queue.writer(), trainer_node=trainer_node) program.add_node(rollout_node) return program def get_config(): """Reproduces results in the paper.""" base_config = { 'batch_size': 100, 'model_learning_rate': 1e-4, 'max_option_length': 100, 'hidden_dims': 0, 'stop_after_steps': FLAGS.total_steps, 'use_affordances_rollout_node': True, 'max_iterations_for_value_iter': 1, } return base_config def main(_): if (FLAGS.affordances_name == 'learned' and FLAGS.affordances_threshold is None): raise ValueError( 'When affordances are learned, an affordance threshold must be given.') if FLAGS.affordances_threshold is not None: if not 0 <= FLAGS.affordances_threshold <= 1: raise ValueError('Affordance threshold must be between 0 and 1.') program_config = get_config() program = _make_program( path_to_options=FLAGS.path_to_options, num_rollout_nodes=FLAGS.num_rollout_nodes, affordances_name=FLAGS.affordances_name, affordances_threshold=FLAGS.affordances_threshold, save_path=FLAGS.save_path, seed=FLAGS.seed, **program_config) lp.launch(program) if __name__ == '__main__': app.run(main)
affordances_option_models-main
lp_learn_model_from_options.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. # ============================================================================== """Heuristic affordances to aid learning a policy over options.""" from typing import Callable, List, Tuple from absl import logging import numpy as np from affordances_option_models import definitions from affordances_option_models import env_utils State = int Option = int AffordancesList = List[Tuple[State, Option]] AffordancesFn = Callable[[], np.ndarray] def _compute_affordance_mask(affordances: AffordancesList) -> np.ndarray: """Computes the affordances mask and does some error checking.""" if not affordances: raise ValueError('List of affordances cannot be empty.') logging.log_every_n( logging.INFO, 'Number of affordances: %s', 10, len(affordances)) affs = np.zeros( (env_utils.NUM_STATES, len(definitions.Options))).astype(np.float) affs[tuple(zip(*affordances))] = 1.0 if not np.all(affs.sum(1) >= 1): raise ValueError('All states must have at least one option affordable.') return affs def _all_affs() -> AffordancesList: """Returns all states + options.""" affordances = [] for state in range(env_utils.NUM_STATES): for option in definitions.Options: affordances.append((state, option.value-1)) return affordances def _pickup_drop_affs() -> AffordancesList: """Returns all pickup and drop options.""" affordances = [] for state in range(env_utils.NUM_STATES): for option in definitions.Options: if option in definitions.OptionsAny: # Skip options that do "any". continue affordances.append( # -1 from o.value since Options starts idx at 1 and matrix at 0. (state, option.value - 1) ) return affordances def _relevant_pickup_drop_affs() -> AffordancesList: """Returns only pickup and drop options that are relevant to the 4 corners.""" affordances = [] for state in range(env_utils.NUM_STATES): for option in definitions.Options: if option in definitions.OptionsAny: # Skip options that do "any". continue gridcell = int(option.name.replace('GoTo', '').split('_')[0]) target_location = env_utils.grid_cell_to_xy(gridcell) # The option goes to relevant corners of the world. if target_location in env_utils.LOCATION_TO_COLOR_MAPPING: affordances.append((state, option.value-1)) return affordances ALL_AFFORDANCES = { 'only_relevant_pickup_drop': _relevant_pickup_drop_affs, 'only_pickup_drop': _pickup_drop_affs, 'everything': _all_affs, } def get_heuristic_affordances_by_name(affordances_name: str) -> AffordancesFn: affordances = ALL_AFFORDANCES[affordances_name]() mask = _compute_affordance_mask(affordances) def _affordance_function(): return mask return _affordance_function
affordances_option_models-main
affordances.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. # ============================================================================== r"""Learn option tables for the taxi environment. This script uses task_queue to learn all the options in parallel. Ideally this only needs to be done once for the full set of options. Options will be saved individually as npz files. """ import os import time from absl import app from absl import flags from absl import logging import launchpad as lp import numpy as np from affordances_option_models import option_utils from affordances_option_models import task_queue FLAGS = flags.FLAGS _SEED = 1 flags.DEFINE_integer( 'num_consumers', len(option_utils.Options), 'Number of CPU workers per program.') flags.DEFINE_float('gamma', 0.99, 'Discount factor for training the options.') flags.DEFINE_string( 'save_path', '~/affordances_theory', 'Location to save options.') flags.DEFINE_integer( 'max_iterations', 1000, 'Maximum number of iterations to run the value iteration.') def make_writer(program_stopper): """Creates a writer node to write all options to a queue..""" def writer(queue): logging.info('Writer has started.') future_to_task_key = {} for task_key, option in enumerate(option_utils.Options): task_key = str(task_key) task_parameters = {'option': option} future = queue.enqueue_task(task_key, task_parameters) logging.info('Adding task %s: %s', task_key, task_parameters) future_to_task_key[future] = task_key logging.info('All options added to the queue. Waiting for results...') queue.close() logging.info('All results received. Done.') program_stopper(mark_as_completed=True) return writer def make_consumer(gamma, max_iterations, topic_name, save_path): """Makes the function that consumes the queue.""" save_path = os.path.join( save_path, f'gamma{gamma}', f'max_iterations{max_iterations}', 'options') if not os.path.exists(save_path): os.makedirs(save_path) logging.info('Saving to folder: %s', save_path) def consumer(queue): logging.info('Starting consumer.') time.sleep(5.0) # Wait until the writer adds all the tasks. while not queue.closed(): try: time.sleep(1.0) task_key, task_params = queue.get_task(topic_name) logging.info('Task obtained: %s with params: %s', task_key, task_params) option = task_params['option'] if option not in option_utils.Options: raise ValueError( f'Got the option: {option}. Expected: {option_utils.Options}') option_policy, num_iters = option_utils.learn_option_policy( option, gamma=gamma, stopping_threshold=1e-5, max_iterations=max_iterations, seed=_SEED) logging.info( 'Option was learned in %s iterations. Saving to disk.', num_iters) option_save_path = f'{save_path}/{option.name}.npz' with open(option_save_path, 'wb') as fout: np.save(fout, option_policy, allow_pickle=False) logging.info('Saved option to %s', option_save_path) queue.set_result( topic_name, task_key, {'option': option, 'learned': True}) except task_queue.QueueClosedError: logging.info('Queue is empty, ending early!') break logging.info('Queue is empty. Closing consumer.') return consumer def _make_program(gamma, max_iterations, save_path, num_consumers=1): """Creates the launchpad program.""" program = lp.Program('option_learning') program_stopper = lp.make_program_stopper(FLAGS.lp_launch_type) topic_name = 'default' ############################## # Task Queue # ############################## with program.group('queue'): queue = task_queue.TaskQueueNode() queue_handle = program.add_node(queue.make_node()) queue.register_handle(queue_handle) ############################## # Problems creator # ############################## with program.group('writer'): write_to_queue = make_writer(program_stopper) program.add_node( lp.PyNode(write_to_queue, queue.writer())) ############################## # Problems Solver # ############################## with program.group('consumer'): if num_consumers > len(option_utils.Options): raise ValueError('Cannot have more consumers than options!') for _ in range(num_consumers): program.add_node(lp.PyNode(make_consumer( gamma, max_iterations, topic_name, save_path), queue.reader())) return program def main(_): program = _make_program( FLAGS.gamma, FLAGS.max_iterations, FLAGS.save_path, FLAGS.num_consumers) lp.launch(program) if __name__ == '__main__': app.run(main)
affordances_option_models-main
lp_learn_options.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. # ============================================================================== """Training code for models and affordance networks.""" from typing import Any, Callable, Dict, List, Optional, Tuple, Union from absl import logging import numpy as np import tensorflow as tf from affordances_option_models import affordances NestedTensor = Union[tf.Tensor, List[tf.Tensor]] OptimizationStep = Callable[[NestedTensor], Dict[str, tf.Tensor]] def prepare_data(data: List[Tuple[Any, ...]]) -> List[tf.Tensor]: r"""Prepares the trajectory data ready for tensorflow. This function unpacks transition data and stacks them suitable for input to a neural network. The idea is: 1. Convert the transition tuples into lists containing the entries of the tuples. 2. Stack the elements for tensorflow and reshape the lists so that they are of shape (batch_size, 1). Note: That if the transition contains a tuple, it will be flattened such that the shape will be (None, 1). Args: data: A list of tuples with the transition data. Returns: A list of `tf.Tensor`s that are suitable for a neural network. """ # Transpose data from [(x1, y1), (x2, y2), ...] into # ([x1, x2, ...], [y1, y2, ...]). transposed_data = list(zip(*data)) # Convert inner lists into Tensors by stacking and reshaping them. return [tf.reshape(tf.stack(x), (-1, 1)) for x in transposed_data] def _both_are_none_or_both_are_given(entry1, entry2): return (entry1 is None) == (entry2 is None) def get_training_steps( model_network: tf.keras.Model, # pytype: disable=attribute-error model_optimizer: tf.keras.optimizers.Optimizer, # pytype: disable=attribute-error affordance_network: Optional[tf.keras.Model] = None, # pytype: disable=attribute-error affordance_optimizer: Optional[tf.keras.optimizers.Optimizer] = None, # pytype: disable=attribute-error heuristic_affordance_fn: Optional[affordances.AffordancesFn] = None, affordance_mask_threshold: float = 0.5, use_learned_affordances: bool = False, ) -> Tuple[OptimizationStep, OptimizationStep]: """Returns (optimized) training steps.""" # Error checking to make sure the correct combinations of model/affordance # nets and optimizers are given or none at all. if not _both_are_none_or_both_are_given( affordance_network, affordance_optimizer): raise ValueError('Both affordance network and optimizer have to be given.') else: use_affordances = affordance_network is not None # User friendly print outs indicate what is happening. logging.info('Using model? True. Using affordances? %s.', use_affordances) def _train_step_affordances(trajectory): """Train the affordances network.""" if affordance_network is None: return dict( total_affordance_loss=tf.constant(0.0)) with tf.GradientTape() as tape: s_t, o_t, _, _, _, achieved_intent = trajectory predicted_intent = affordance_network(s_t, o_t) achieved_intent = tf.reshape(achieved_intent, (-1, 1)) predicted_intent = tf.reshape(predicted_intent, (-1, 1)) loss = tf.keras.losses.binary_crossentropy( # pytype: disable=attribute-error achieved_intent, predicted_intent) total_loss = tf.reduce_mean(loss) grads = tape.gradient(total_loss, affordance_network.trainable_variables) if affordance_optimizer is None: raise ValueError('Please provide an affordance optimizer.') affordance_optimizer.apply_gradients( zip(grads, affordance_network.trainable_variables)) return dict(total_affordance_loss=total_loss) if heuristic_affordance_fn is not None and not use_learned_affordances: affs_matrix = heuristic_affordance_fn() heuristic_affs_matrix = affs_matrix.astype(np.float32) else: heuristic_affs_matrix = None def _train_step_model(trajectory): """Train model network.""" with tf.GradientTape() as tape: s_t, o_t, target_lengths, target_rewards, s_tp1, _ = trajectory # Here we compute the mask for each element in the batch. For each # (state, option) pair in the batch, the mask is 1 if it is part of the # affordance set. We then use this mask to zero out unaffordable states # and options so the loss not given any weight for those transitions. if heuristic_affs_matrix is not None: # Creates an index tensor indicating which state and options are in the # batch. idx = tf.concat([s_t, o_t], axis=1) # The affs_matrix is of shape |S| x |O| with 1's where that tuple is # affordable. The `gather_nd` operation picks out entries of that # matrix corresponding to the indices in the batch. mask = tf.gather_nd(heuristic_affs_matrix, idx) elif affordance_network is not None: # Use affordance network to output whether an intent can be completed at # each state action pair. affordances_predictions = affordance_network(s_t, o_t) # Use the threshold to convert this into a binary mask. masks_per_intent = tf.math.greater_equal( affordances_predictions, affordance_mask_threshold) # Reduce so that we output a single value determining if _any_ intent # can be completed from here. mask = tf.reduce_any(masks_per_intent, 1) # Prevent gradient from flowing through to the affordance network. # Technically i do not think this is possible but just in case. mask = tf.stop_gradient(tf.cast(mask, tf.float32)) else: # By default everything is affordable. mask = tf.ones_like(tf.squeeze(s_t), dtype=tf.float32) # The mask is a vector of length batch size with 1's indicating which # examples should be included in the loss. We take the sum of the mask # here to obtains the number of examples that are to be incldued. This # variable is used to divide the loss instead of taking a generic mean. num_examples = tf.math.reduce_sum(mask) transition_model, lengths, rewards = model_network(s_t, o_t) log_probs = transition_model.log_prob(tf.squeeze(s_tp1)) tf.debugging.assert_shapes([ (log_probs, (None,)) # Prevent silent broadcasting errors. ]) # Negate log_prob here because we want to maximize this via minimization. transition_loss = -log_probs * mask # pytype: disable=attribute-error lengths_loss = 0.5 * tf.keras.losses.mean_squared_error( target_lengths, lengths) * mask rewards_loss = 0.5 * tf.keras.losses.mean_squared_error( target_rewards, rewards) * mask # pytype: enable=attribute-error tf.debugging.assert_shapes([ (transition_loss, ('B',)), (lengths_loss, ('B',)), (mask, ('B',)), (rewards_loss, ('B',)), ]) transition_loss = tf.reduce_sum(transition_loss) / num_examples lengths_loss = tf.reduce_sum(lengths_loss) / num_examples rewards_loss = tf.reduce_sum(rewards_loss) / num_examples total_loss = rewards_loss + transition_loss + lengths_loss grads = tape.gradient(total_loss, model_network.trainable_variables) model_optimizer.apply_gradients( zip(grads, model_network.trainable_variables)) return dict( total_model_loss=total_loss, transition_loss=transition_loss, rewards_loss=rewards_loss, lengths_loss=lengths_loss) # Optimize training step execution by compiling them using tf.function. _train_step_affordances = tf.function(_train_step_affordances) # pylint: disable=invalid-name _train_step_model = tf.function(_train_step_model) # pylint: disable=invalid-name return _train_step_model, _train_step_affordances
affordances_option_models-main
training.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. # ============================================================================== """Generate data from taxienv.""" from typing import Dict, List, NamedTuple, Optional, Tuple from absl import logging import numpy as np from affordances_option_models import env_utils from affordances_option_models import intent_utils from affordances_option_models import option_utils from affordances_option_models import rl class IntentCompletionIndicator(NamedTuple): indicators: Tuple[int, ...] class OptionTransition(NamedTuple): """Storage for option metadata executed in a trajectory.""" # NOTE: Do not change this to a dataclass to maintain tuple semantics. initial_state: int option_id: int option_length: int option_reward: float final_state: int intents_completed: IntentCompletionIndicator def get_trajectories( option_policies: Dict[option_utils.Options, np.ndarray], num_trajectories: int = 1, max_trajectory_length: int = 12, affordances_mask: Optional[np.ndarray] = None, uniform_random_initial_state: bool = False, initial_state: Optional[int] = None, seed: Optional[int] = None) -> Tuple[List[OptionTransition], int]: """Samples trajectory transitions by executing options in an environment. Options are sampled uniformly from the `option_policies` table. They are then rolled out in the environment for `max_trajectory_length` steps. Statistics are computed about the Option execution and returned for model learning. The initial state can be sampled randomly. Args: option_policies: A dictionary mapping option_id to a numpy table representing the optimal low level policy that maximizes that option. num_trajectories: The total number of trajectories to sample. max_trajectory_length: The maximum length of the trajectory. affordances_mask: Mask for sampling over the affordances. uniform_random_initial_state: Each episode can start uniformly randomly in the environment (we do not use the internal initial state distribution, via reset() to sample starting states). initial_state: Initial state for the rollouts. seed: seed for randomness Returns: 1. Trajectories collected from the environment when executing an option from a state. They are stored as `OptionTransition` which contains metadata needed to learn a model. 2. An integer representing the total steps taken in the environment. """ rng = np.random.default_rng(seed) def rargmax(arr): """Random argmax with stochastic tie-breaking.""" arr = np.isclose(arr, arr.max(-1, keepdims=True)) return rng.choice(np.flatnonzero(arr)) max_trajectory_length = max_trajectory_length or float('inf') data = [] total_steps = [] for i in range(num_trajectories): if uniform_random_initial_state: initial_state = rng.integers(0, env_utils.NUM_STATES) logging.debug('Initial state set to %s', initial_state) elif initial_state is None: raise ValueError( 'Initial state cannot be None if uniform_random_initial_state=False') # Pick an option according to the relevant distribution. if affordances_mask is None: # Select a random option. option_id = rng.integers(1, len(option_utils.Options)) else: possible_options = np.where(affordances_mask[initial_state] > 0)[0] option_id = rng.choice(possible_options) # +1 since Options enumeration starts at 1 instead of 0. option_id = option_utils.Options(option_id + 1) logging.debug('Selected option: %s', option_id) def option_policy(x): """Executes the relevant low level option policy.""" q_values = option_policies[option_id][x] # pylint: disable=cell-var-from-loop return rargmax(q_values) def termination_fn(transition: rl.Transition): """Determines if any given transition terminates the option.""" return transition.done or option_utils.check_option_termination( transition.s_t, transition.a_t, option_id) # pylint: disable=cell-var-from-loop # Do a rollout with the selected option. trajectories, steps_per_trajectory, rewards = rl.run_policy_in_env( option_policy, num_episodes=1, initial_state=initial_state, max_steps_per_episode=max_trajectory_length, termination_fn=termination_fn, seed=seed + i if seed is not None else None, ) assert len(trajectories) == 1 total_steps.append(steps_per_trajectory[0]) trajectory = trajectories[0] first_transition = trajectory[0] final_transition = trajectory[-1] # Collect indications for every intent whether it was completed. all_intents = [] for intent_id in intent_utils.Intents: intent_completed = intent_utils.is_intent_completed( first_transition.s_t, option_id, final_transition.s_tp1, intent_id=intent_id) all_intents.append(intent_completed) # Since we get -1 reward per step, this sum doesn't need to be discounted. option_reward = sum(rewards) option_length = len(trajectory) logging.debug( 'Option Rollout: option_id=%s, Option length = %s, option reward = %s', option_id, option_length, option_reward) data.append( OptionTransition( first_transition.s_t, option_id.value - 1, # Option labels start from 1. We reindex to 0. option_length, option_reward, final_transition.s_tp1, IntentCompletionIndicator(tuple(all_intents)), )) return data, sum(total_steps)
affordances_option_models-main
data.py
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Setup for pip package.""" import os import platform import shutil import subprocess import sys import sysconfig import setuptools from setuptools.command import build_ext here = os.path.dirname(os.path.abspath(__file__)) def _get_tree_version(): """Parse the version string from tree/__init__.py.""" with open(os.path.join(here, 'tree', '__init__.py')) as f: try: version_line = next(line for line in f if line.startswith('__version__')) except StopIteration: raise ValueError('__version__ not defined in tree/__init__.py') else: ns = {} exec(version_line, ns) # pylint: disable=exec-used return ns['__version__'] def _parse_requirements(path): with open(os.path.join(here, path)) as f: return [ line.rstrip() for line in f if not (line.isspace() or line.startswith('#')) ] class CMakeExtension(setuptools.Extension): """An extension with no sources. We do not want distutils to handle any of the compilation (instead we rely on CMake), so we always pass an empty list to the constructor. """ def __init__(self, name, source_dir=''): super().__init__(name, sources=[]) self.source_dir = os.path.abspath(source_dir) class BuildCMakeExtension(build_ext.build_ext): """Our custom build_ext command. Uses CMake to build extensions instead of a bare compiler (e.g. gcc, clang). """ def run(self): self._check_build_environment() for ext in self.extensions: self.build_extension(ext) def _check_build_environment(self): """Check for required build tools: CMake, C++ compiler, and python dev.""" try: subprocess.check_call(['cmake', '--version']) except OSError as e: ext_names = ', '.join(e.name for e in self.extensions) raise RuntimeError( f'CMake must be installed to build the following extensions: {ext_names}' ) from e print('Found CMake') def build_extension(self, ext): extension_dir = os.path.abspath( os.path.dirname(self.get_ext_fullpath(ext.name))) build_cfg = 'Debug' if self.debug else 'Release' cmake_args = [ f'-DPython3_ROOT_DIR={sys.prefix}', f'-DPython3_EXECUTABLE={sys.executable}', f'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extension_dir}', f'-DCMAKE_BUILD_TYPE={build_cfg}' ] if platform.system() != 'Windows': cmake_args.extend([ f'-DPython3_LIBRARY={sysconfig.get_paths()["stdlib"]}', f'-DPython3_INCLUDE_DIR={sysconfig.get_paths()["include"]}', ]) if platform.system() == 'Darwin' and os.environ.get('ARCHFLAGS'): osx_archs = [] if '-arch x86_64' in os.environ['ARCHFLAGS']: osx_archs.append('x86_64') if '-arch arm64' in os.environ['ARCHFLAGS']: osx_archs.append('arm64') cmake_args.append(f'-DCMAKE_OSX_ARCHITECTURES={";".join(osx_archs)}') os.makedirs(self.build_temp, exist_ok=True) subprocess.check_call( ['cmake', ext.source_dir] + cmake_args, cwd=self.build_temp) subprocess.check_call( ['cmake', '--build', '.', f'-j{os.cpu_count()}', '--config', build_cfg], cwd=self.build_temp) # Force output to <extension_dir>/. Amends CMake multigenerator output paths # on Windows and avoids Debug/ and Release/ subdirs, which is CMake default. tree_dir = os.path.join(extension_dir, 'tree') # pylint:disable=unreachable for cfg in ('Release', 'Debug'): cfg_dir = os.path.join(extension_dir, cfg) if os.path.isdir(cfg_dir): for f in os.listdir(cfg_dir): shutil.move(os.path.join(cfg_dir, f), tree_dir) setuptools.setup( name='dm-tree', version=_get_tree_version(), url='https://github.com/deepmind/tree', description='Tree is a library for working with nested data structures.', author='DeepMind', author_email='[email protected]', long_description=open(os.path.join(here, 'README.md')).read(), long_description_content_type='text/markdown', # Contained modules and scripts. packages=setuptools.find_packages(), tests_require=_parse_requirements('requirements-test.txt'), test_suite='tree', cmdclass=dict(build_ext=BuildCMakeExtension), ext_modules=[CMakeExtension('_tree', source_dir='tree')], zip_safe=False, # PyPI package information. classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Software Development :: Libraries', ], license='Apache 2.0', keywords='tree nest flatten', )
tree-master
setup.py
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains _sequence_like and helpers for sequence data structures.""" import collections from collections import abc as collections_abc import types from tree import _tree # pylint: disable=g-import-not-at-top try: import wrapt ObjectProxy = wrapt.ObjectProxy except ImportError: class ObjectProxy(object): """Stub-class for `wrapt.ObjectProxy``.""" def _sorted(dictionary): """Returns a sorted list of the dict keys, with error if keys not sortable.""" try: return sorted(dictionary) except TypeError: raise TypeError("tree only supports dicts with sortable keys.") def _is_attrs(instance): return _tree.is_attrs(instance) def _is_namedtuple(instance, strict=False): """Returns True iff `instance` is a `namedtuple`. Args: instance: An instance of a Python object. strict: If True, `instance` is considered to be a `namedtuple` only if it is a "plain" namedtuple. For instance, a class inheriting from a `namedtuple` will be considered to be a `namedtuple` iff `strict=False`. Returns: True if `instance` is a `namedtuple`. """ return _tree.is_namedtuple(instance, strict) def _sequence_like(instance, args): """Converts the sequence `args` to the same type as `instance`. Args: instance: an instance of `tuple`, `list`, `namedtuple`, `dict`, or `collections.OrderedDict`. args: elements to be converted to the `instance` type. Returns: `args` with the type of `instance`. """ if isinstance(instance, (dict, collections_abc.Mapping)): # Pack dictionaries in a deterministic order by sorting the keys. # Notice this means that we ignore the original order of `OrderedDict` # instances. This is intentional, to avoid potential bugs caused by mixing # ordered and plain dicts (e.g., flattening a dict but using a # corresponding `OrderedDict` to pack it back). result = dict(zip(_sorted(instance), args)) keys_and_values = ((key, result[key]) for key in instance) if isinstance(instance, collections.defaultdict): # `defaultdict` requires a default factory as the first argument. return type(instance)(instance.default_factory, keys_and_values) elif isinstance(instance, types.MappingProxyType): # MappingProxyType requires a dict to proxy to. return type(instance)(dict(keys_and_values)) else: return type(instance)(keys_and_values) elif isinstance(instance, collections_abc.MappingView): # We can't directly construct mapping views, so we create a list instead return list(args) elif _is_namedtuple(instance) or _is_attrs(instance): if isinstance(instance, ObjectProxy): instance_type = type(instance.__wrapped__) else: instance_type = type(instance) try: if _is_attrs(instance): return instance_type( **{ attr.name: arg for attr, arg in zip(instance_type.__attrs_attrs__, args) }) else: return instance_type(*args) except Exception as e: raise TypeError( f"Couldn't traverse {instance!r} with arguments {args}") from e elif isinstance(instance, ObjectProxy): # For object proxies, first create the underlying type and then re-wrap it # in the proxy type. return type(instance)(_sequence_like(instance.__wrapped__, args)) else: # Not a namedtuple return type(instance)(args)
tree-master
tree/sequence.py
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions for working with nested data structures.""" from collections import abc as collections_abc import logging import sys from typing import Mapping, Sequence, TypeVar, Union from .sequence import _is_attrs from .sequence import _is_namedtuple from .sequence import _sequence_like from .sequence import _sorted # pylint: disable=g-import-not-at-top try: import wrapt ObjectProxy = wrapt.ObjectProxy except ImportError: class ObjectProxy(object): """Stub-class for `wrapt.ObjectProxy``.""" try: from tree import _tree except ImportError: if "sphinx" not in sys.modules: raise _tree = None # pylint: enable=g-import-not-at-top __all__ = [ "is_nested", "assert_same_structure", "unflatten_as", "flatten", "flatten_up_to", "flatten_with_path", "flatten_with_path_up_to", "map_structure", "map_structure_up_to", "map_structure_with_path", "map_structure_with_path_up_to", "traverse", "MAP_TO_NONE", ] __version__ = "0.1.8" # Note: this is *not* the same as `six.string_types`, which in Python3 is just # `(str,)` (i.e. it does not include byte strings). _TEXT_OR_BYTES = (str, bytes) _SHALLOW_TREE_HAS_INVALID_KEYS = ( "The shallow_tree's keys are not a subset of the input_tree's keys. The " "shallow_tree has the following keys that are not in the input_tree: {}.") _STRUCTURES_HAVE_MISMATCHING_TYPES = ( "The two structures don't have the same sequence type. Input structure has " "type {input_type}, while shallow structure has type {shallow_type}.") _STRUCTURES_HAVE_MISMATCHING_LENGTHS = ( "The two structures don't have the same sequence length. Input " "structure has length {input_length}, while shallow structure has length " "{shallow_length}." ) _INPUT_TREE_SMALLER_THAN_SHALLOW_TREE = ( "The input_tree has fewer elements than the shallow_tree. Input structure " "has length {input_size}, while shallow structure has length " "{shallow_size}.") _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ = ( "If shallow structure is a sequence, input must also be a sequence. " "Input has type: {}.") _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH = ( "If shallow structure is a sequence, input must also be a sequence. " "Input at path: {path} has type: {input_type}.") K = TypeVar("K") V = TypeVar("V") # A generic monomorphic structure type, e.g. ``StructureKV[str, int]`` # is an arbitrarily nested structure where keys must be of type ``str`` # and values are integers. StructureKV = Union[ Sequence["StructureKV[K, V]"], Mapping[K, "StructureKV[K, V]"], V, ] Structure = StructureKV[str, V] def _get_attrs_items(obj): """Returns a list of (name, value) pairs from an attrs instance. The list will be sorted by name. Args: obj: an object. Returns: A list of (attr_name, attr_value) pairs. """ return [(attr.name, getattr(obj, attr.name)) for attr in obj.__class__.__attrs_attrs__] def _yield_value(iterable): for _, v in _yield_sorted_items(iterable): yield v def _yield_sorted_items(iterable): """Yield (key, value) pairs for `iterable` in a deterministic order. For Sequences, the key will be an int, the array index of a value. For Mappings, the key will be the dictionary key. For objects (e.g. namedtuples), the key will be the attribute name. In all cases, the keys will be iterated in sorted order. Args: iterable: an iterable. Yields: The iterable's (key, value) pairs, in order of sorted keys. """ if isinstance(iterable, collections_abc.Mapping): # Iterate through dictionaries in a deterministic order by sorting the # keys. Notice this means that we ignore the original order of `OrderedDict` # instances. This is intentional, to avoid potential bugs caused by mixing # ordered and plain dicts (e.g., flattening a dict but using a # corresponding `OrderedDict` to pack it back). for key in _sorted(iterable): yield key, iterable[key] elif _is_attrs(iterable): for item in _get_attrs_items(iterable): yield item elif _is_namedtuple(iterable): for field in iterable._fields: yield (field, getattr(iterable, field)) else: for item in enumerate(iterable): yield item def _num_elements(structure): if _is_attrs(structure): return len(getattr(structure.__class__, "__attrs_attrs__")) else: return len(structure) def is_nested(structure): """Checks if a given structure is nested. >>> tree.is_nested(42) False >>> tree.is_nested({"foo": 42}) True Args: structure: A structure to check. Returns: `True` if a given structure is nested, i.e. is a sequence, a mapping, or a namedtuple, and `False` otherwise. """ return _tree.is_sequence(structure) def flatten(structure): r"""Flattens a possibly nested structure into a list. >>> tree.flatten([[1, 2, 3], [4, [5], [[6]]]]) [1, 2, 3, 4, 5, 6] If `structure` is not nested, the result is a single-element list. >>> tree.flatten(None) [None] >>> tree.flatten(1) [1] In the case of dict instances, the sequence consists of the values, sorted by key to ensure deterministic behavior. This is true also for :class:`~collections.OrderedDict` instances: their sequence order is ignored, the sorting order of keys is used instead. The same convention is followed in :func:`~tree.unflatten`. This correctly unflattens dicts and ``OrderedDict``\ s after they have been flattened, and also allows flattening an ``OrderedDict`` and then unflattening it back using a corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys cannot be flattened. >>> tree.flatten({100: 'world!', 6: 'Hello'}) ['Hello', 'world!'] Args: structure: An arbitrarily nested structure. Returns: A list, the flattened version of the input `structure`. Raises: TypeError: If `structure` is or contains a mapping with non-sortable keys. """ return _tree.flatten(structure) class _DotString(object): def __str__(self): return "." def __repr__(self): return "." _DOT = _DotString() def assert_same_structure(a, b, check_types=True): """Asserts that two structures are nested in the same way. >>> tree.assert_same_structure([(0, 1)], [(2, 3)]) Note that namedtuples with identical name and fields are always considered to have the same shallow structure (even with `check_types=True`). >>> Foo = collections.namedtuple('Foo', ['a', 'b']) >>> AlsoFoo = collections.namedtuple('Foo', ['a', 'b']) >>> tree.assert_same_structure(Foo(0, 1), AlsoFoo(2, 3)) Named tuples with different names are considered to have different shallow structures: >>> Bar = collections.namedtuple('Bar', ['a', 'b']) >>> tree.assert_same_structure(Foo(0, 1), Bar(2, 3)) Traceback (most recent call last): ... TypeError: The two structures don't have the same nested structure. ... Args: a: an arbitrarily nested structure. b: an arbitrarily nested structure. check_types: if `True` (default) types of sequences are checked as well, including the keys of dictionaries. If set to `False`, for example a list and a tuple of objects will look the same if they have the same size. Note that namedtuples with identical name and fields are always considered to have the same shallow structure. Raises: ValueError: If the two structures do not have the same number of elements or if the two structures are not nested in the same way. TypeError: If the two structures differ in the type of sequence in any of their substructures. Only possible if `check_types` is `True`. """ try: _tree.assert_same_structure(a, b, check_types) except (ValueError, TypeError) as e: str1 = str(map_structure(lambda _: _DOT, a)) str2 = str(map_structure(lambda _: _DOT, b)) raise type(e)("%s\n" "Entire first structure:\n%s\n" "Entire second structure:\n%s" % (e, str1, str2)) def _packed_nest_with_indices(structure, flat, index): """Helper function for ``unflatten_as``. Args: structure: Substructure (list / tuple / dict) to mimic. flat: Flattened values to output substructure for. index: Index at which to start reading from flat. Returns: The tuple (new_index, child), where: * new_index - the updated index into `flat` having processed `structure`. * packed - the subset of `flat` corresponding to `structure`, having started at `index`, and packed into the same nested format. Raises: ValueError: if `structure` contains more elements than `flat` (assuming indexing starts from `index`). """ packed = [] for s in _yield_value(structure): if is_nested(s): new_index, child = _packed_nest_with_indices(s, flat, index) packed.append(_sequence_like(s, child)) index = new_index else: packed.append(flat[index]) index += 1 return index, packed def unflatten_as(structure, flat_sequence): r"""Unflattens a sequence into a given structure. >>> tree.unflatten_as([[1, 2], [[3], [4]]], [5, 6, 7, 8]) [[5, 6], [[7], [8]]] If `structure` is a scalar, `flat_sequence` must be a single-element list; in this case the return value is ``flat_sequence[0]``. >>> tree.unflatten_as(None, [1]) 1 If `structure` is or contains a dict instance, the keys will be sorted to pack the flat sequence in deterministic order. This is true also for :class:`~collections.OrderedDict` instances: their sequence order is ignored, the sorting order of keys is used instead. The same convention is followed in :func:`~tree.flatten`. This correctly unflattens dicts and ``OrderedDict``\ s after they have been flattened, and also allows flattening an ``OrderedDict`` and then unflattening it back using a corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys cannot be unflattened. >>> tree.unflatten_as({1: None, 2: None}, ['Hello', 'world!']) {1: 'Hello', 2: 'world!'} Args: structure: Arbitrarily nested structure. flat_sequence: Sequence to unflatten. Returns: `flat_sequence` unflattened into `structure`. Raises: ValueError: If `flat_sequence` and `structure` have different element counts. TypeError: If `structure` is or contains a mapping with non-sortable keys. """ if not is_nested(flat_sequence): raise TypeError("flat_sequence must be a sequence not a {}:\n{}".format( type(flat_sequence), flat_sequence)) if not is_nested(structure): if len(flat_sequence) != 1: raise ValueError("Structure is a scalar but len(flat_sequence) == %d > 1" % len(flat_sequence)) return flat_sequence[0] flat_structure = flatten(structure) if len(flat_structure) != len(flat_sequence): raise ValueError( "Could not pack sequence. Structure had %d elements, but flat_sequence " "had %d elements. Structure: %s, flat_sequence: %s." % (len(flat_structure), len(flat_sequence), structure, flat_sequence)) _, packed = _packed_nest_with_indices(structure, flat_sequence, 0) return _sequence_like(structure, packed) def map_structure(func, *structures, **kwargs): # pylint: disable=redefined-builtin """Maps `func` through given structures. >>> structure = [[1], [2], [3]] >>> tree.map_structure(lambda v: v**2, structure) [[1], [4], [9]] >>> tree.map_structure(lambda x, y: x * y, structure, structure) [[1], [4], [9]] >>> Foo = collections.namedtuple('Foo', ['a', 'b']) >>> structure = Foo(a=1, b=2) >>> tree.map_structure(lambda v: v * 2, structure) Foo(a=2, b=4) Args: func: A callable that accepts as many arguments as there are structures. *structures: Arbitrarily nested structures of the same layout. **kwargs: The only valid keyword argument is `check_types`. If `True` (default) the types of components within the structures have to be match, e.g. ``tree.map_structure(func, [1], (1,))`` will raise a `TypeError`, otherwise this is not enforced. Note that namedtuples with identical name and fields are considered to be the same type. Returns: A new structure with the same layout as the given ones. If the `structures` have components of varying types, the resulting structure will use the same types as ``structures[0]``. Raises: TypeError: If `func` is not callable. ValueError: If the two structures do not have the same number of elements or if the two structures are not nested in the same way. TypeError: If `check_types` is `True` and any two `structures` differ in the types of their components. ValueError: If no structures were given or if a keyword argument other than `check_types` is provided. """ if not callable(func): raise TypeError("func must be callable, got: %s" % func) if not structures: raise ValueError("Must provide at least one structure") check_types = kwargs.pop("check_types", True) if kwargs: raise ValueError( "Only valid keyword arguments are `check_types` " "not: `%s`" % ("`, `".join(kwargs.keys()))) for other in structures[1:]: assert_same_structure(structures[0], other, check_types=check_types) return unflatten_as(structures[0], [func(*args) for args in zip(*map(flatten, structures))]) def map_structure_with_path(func, *structures, **kwargs): """Maps `func` through given structures. This is a variant of :func:`~tree.map_structure` which accumulates a *path* while mapping through the structures. A path is a tuple of indices and/or keys which uniquely identifies the positions of the arguments passed to `func`. >>> tree.map_structure_with_path( ... lambda path, v: (path, v**2), ... [{"foo": 42}]) [{'foo': ((0, 'foo'), 1764)}] Args: func: A callable that accepts a path and as many arguments as there are structures. *structures: Arbitrarily nested structures of the same layout. **kwargs: The only valid keyword argument is `check_types`. If `True` (default) the types of components within the structures have to be match, e.g. ``tree.map_structure_with_path(func, [1], (1,))`` will raise a `TypeError`, otherwise this is not enforced. Note that namedtuples with identical name and fields are considered to be the same type. Returns: A new structure with the same layout as the given ones. If the `structures` have components of varying types, the resulting structure will use the same types as ``structures[0]``. Raises: TypeError: If `func` is not callable or if the `structures` do not have the same layout. TypeError: If `check_types` is `True` and any two `structures` differ in the types of their components. ValueError: If no structures were given or if a keyword argument other than `check_types` is provided. """ return map_structure_with_path_up_to(structures[0], func, *structures, **kwargs) def _yield_flat_up_to(shallow_tree, input_tree, path=()): """Yields (path, value) pairs of input_tree flattened up to shallow_tree. Args: shallow_tree: Nested structure. Traverse no further than its leaf nodes. input_tree: Nested structure. Return the paths and values from this tree. Must have the same upper structure as shallow_tree. path: Tuple. Optional argument, only used when recursing. The path from the root of the original shallow_tree, down to the root of the shallow_tree arg of this recursive call. Yields: Pairs of (path, value), where path the tuple path of a leaf node in shallow_tree, and value is the value of the corresponding node in input_tree. """ if (isinstance(shallow_tree, _TEXT_OR_BYTES) or not (isinstance(shallow_tree, (collections_abc.Mapping, collections_abc.Sequence)) or _is_namedtuple(shallow_tree) or _is_attrs(shallow_tree))): yield (path, input_tree) else: input_tree = dict(_yield_sorted_items(input_tree)) for shallow_key, shallow_subtree in _yield_sorted_items(shallow_tree): subpath = path + (shallow_key,) input_subtree = input_tree[shallow_key] for leaf_path, leaf_value in _yield_flat_up_to(shallow_subtree, input_subtree, path=subpath): yield (leaf_path, leaf_value) def _multiyield_flat_up_to(shallow_tree, *input_trees): """Same as `_yield_flat_up_to`, but takes multiple input trees.""" zipped_iterators = zip(*[_yield_flat_up_to(shallow_tree, input_tree) for input_tree in input_trees]) try: for paths_and_values in zipped_iterators: paths, values = zip(*paths_and_values) yield paths[:1] + values except KeyError as e: paths = locals().get("paths", ((),)) raise ValueError(f"Could not find key '{e.args[0]}' in some `input_trees`. " "Please ensure the structure of all `input_trees` are " "compatible with `shallow_tree`. The last valid path " f"yielded was {paths[0]}.") from e def _assert_shallow_structure(shallow_tree, input_tree, path=None, check_types=True): """Asserts that `shallow_tree` is a shallow structure of `input_tree`. That is, this function recursively tests if each key in shallow_tree has its corresponding key in input_tree. Examples: The following code will raise an exception: >>> shallow_tree = {"a": "A", "b": "B"} >>> input_tree = {"a": 1, "c": 2} >>> _assert_shallow_structure(shallow_tree, input_tree) Traceback (most recent call last): ... ValueError: The shallow_tree's keys are not a subset of the input_tree's ... The following code will raise an exception: >>> shallow_tree = ["a", "b"] >>> input_tree = ["c", ["d", "e"], "f"] >>> _assert_shallow_structure(shallow_tree, input_tree) Traceback (most recent call last): ... ValueError: The two structures don't have the same sequence length. ... By setting check_types=False, we drop the requirement that corresponding nodes in shallow_tree and input_tree have to be the same type. Sequences are treated equivalently to Mappables that map integer keys (indices) to values. The following code will therefore not raise an exception: >>> _assert_shallow_structure({0: "foo"}, ["foo"], check_types=False) Args: shallow_tree: an arbitrarily nested structure. input_tree: an arbitrarily nested structure. path: if not `None`, a tuple containing the current path in the nested structure. This is only used for more informative errror messages. check_types: if `True` (default) the sequence types of `shallow_tree` and `input_tree` have to be the same. Raises: TypeError: If `shallow_tree` is a sequence but `input_tree` is not. TypeError: If the sequence types of `shallow_tree` are different from `input_tree`. Only raised if `check_types` is `True`. ValueError: If the sequence lengths of `shallow_tree` are different from `input_tree`. """ if is_nested(shallow_tree): if not is_nested(input_tree): if path is not None: raise TypeError( _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH.format( path=list(path), input_type=type(input_tree))) else: raise TypeError( _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ.format( type(input_tree))) if isinstance(shallow_tree, ObjectProxy): shallow_type = type(shallow_tree.__wrapped__) else: shallow_type = type(shallow_tree) if check_types and not isinstance(input_tree, shallow_type): # Duck-typing means that nest should be fine with two different # namedtuples with identical name and fields. shallow_is_namedtuple = _is_namedtuple(shallow_tree, False) input_is_namedtuple = _is_namedtuple(input_tree, False) if shallow_is_namedtuple and input_is_namedtuple: # pylint: disable=protected-access if not _tree.same_namedtuples(shallow_tree, input_tree): raise TypeError(_STRUCTURES_HAVE_MISMATCHING_TYPES.format( input_type=type(input_tree), shallow_type=shallow_type)) # pylint: enable=protected-access elif not (isinstance(shallow_tree, collections_abc.Mapping) and isinstance(input_tree, collections_abc.Mapping)): raise TypeError(_STRUCTURES_HAVE_MISMATCHING_TYPES.format( input_type=type(input_tree), shallow_type=shallow_type)) if _num_elements(input_tree) != _num_elements(shallow_tree): raise ValueError( _STRUCTURES_HAVE_MISMATCHING_LENGTHS.format( input_length=_num_elements(input_tree), shallow_length=_num_elements(shallow_tree))) elif _num_elements(input_tree) < _num_elements(shallow_tree): raise ValueError( _INPUT_TREE_SMALLER_THAN_SHALLOW_TREE.format( input_size=_num_elements(input_tree), shallow_size=_num_elements(shallow_tree))) shallow_iter = _yield_sorted_items(shallow_tree) input_iter = _yield_sorted_items(input_tree) def get_matching_input_branch(shallow_key): for input_key, input_branch in input_iter: if input_key == shallow_key: return input_branch raise ValueError(_SHALLOW_TREE_HAS_INVALID_KEYS.format([shallow_key])) for shallow_key, shallow_branch in shallow_iter: input_branch = get_matching_input_branch(shallow_key) _assert_shallow_structure( shallow_branch, input_branch, path + (shallow_key,) if path is not None else None, check_types=check_types) def flatten_up_to(shallow_structure, input_structure, check_types=True): """Flattens `input_structure` up to `shallow_structure`. All further nested components in `input_structure` are retained as-is. >>> structure = [[1, 1], [2, 2]] >>> tree.flatten_up_to([None, None], structure) [[1, 1], [2, 2]] >>> tree.flatten_up_to([None, [None, None]], structure) [[1, 1], 2, 2] If `shallow_structure` and `input_structure` are not nested, the result is a single-element list: >>> tree.flatten_up_to(42, 1) [1] >>> tree.flatten_up_to(42, [1, 2, 3]) [[1, 2, 3]] Args: shallow_structure: A structure with the same (but possibly more shallow) layout as `input_structure`. input_structure: An arbitrarily nested structure. check_types: If `True`, check that each node in shallow_tree has the same type as the corresponding node in `input_structure`. Returns: A list, the partially flattened version of `input_structure` wrt `shallow_structure`. Raises: TypeError: If the layout of `shallow_structure` does not match that of `input_structure`. TypeError: If `check_types` is `True` and `shallow_structure` and `input_structure` differ in the types of their components. """ _assert_shallow_structure( shallow_structure, input_structure, path=None, check_types=check_types) # Discard paths returned by _yield_flat_up_to. return [v for _, v in _yield_flat_up_to(shallow_structure, input_structure)] def flatten_with_path_up_to(shallow_structure, input_structure, check_types=True): """Flattens `input_structure` up to `shallow_structure`. This is a combination of :func:`~tree.flatten_up_to` and :func:`~tree.flatten_with_path` Args: shallow_structure: A structure with the same (but possibly more shallow) layout as `input_structure`. input_structure: An arbitrarily nested structure. check_types: If `True`, check that each node in shallow_tree has the same type as the corresponding node in `input_structure`. Returns: A list of ``(path, item)`` pairs corresponding to the partially flattened version of `input_structure` wrt `shallow_structure`. Raises: TypeError: If the layout of `shallow_structure` does not match that of `input_structure`. TypeError: If `input_structure` is or contains a mapping with non-sortable keys. TypeError: If `check_types` is `True` and `shallow_structure` and `input_structure` differ in the types of their components. """ _assert_shallow_structure( shallow_structure, input_structure, path=(), check_types=check_types) return list(_yield_flat_up_to(shallow_structure, input_structure)) def map_structure_up_to(shallow_structure, func, *structures, **kwargs): """Maps `func` through given structures up to `shallow_structure`. This is a variant of :func:`~tree.map_structure` which only maps the given structures up to `shallow_structure`. All further nested components are retained as-is. >>> structure = [[1, 1], [2, 2]] >>> tree.map_structure_up_to([None, None], len, structure) [2, 2] >>> tree.map_structure_up_to([None, [None, None]], str, structure) ['[1, 1]', ['2', '2']] Args: shallow_structure: A structure with layout common to all `structures`. func: A callable that accepts as many arguments as there are structures. *structures: Arbitrarily nested structures of the same layout. **kwargs: No valid keyword arguments. Raises: ValueError: If `func` is not callable or if `structures` have different layout or if the layout of `shallow_structure` does not match that of `structures` or if no structures were given. Returns: A new structure with the same layout as `shallow_structure`. """ return map_structure_with_path_up_to( shallow_structure, lambda _, *args: func(*args), # Discards path. *structures, **kwargs) def map_structure_with_path_up_to(shallow_structure, func, *structures, **kwargs): """Maps `func` through given structures up to `shallow_structure`. This is a combination of :func:`~tree.map_structure_up_to` and :func:`~tree.map_structure_with_path` Args: shallow_structure: A structure with layout common to all `structures`. func: A callable that accepts a path and as many arguments as there are structures. *structures: Arbitrarily nested structures of the same layout. **kwargs: No valid keyword arguments. Raises: ValueError: If `func` is not callable or if `structures` have different layout or if the layout of `shallow_structure` does not match that of `structures` or if no structures were given. Returns: Result of repeatedly applying `func`. Has the same structure layout as `shallow_tree`. """ if "check_types" in kwargs: logging.warning("The use of `check_types` is deprecated and does not have " "any effect.") del kwargs results = [] for path_and_values in _multiyield_flat_up_to(shallow_structure, *structures): results.append(func(*path_and_values)) return unflatten_as(shallow_structure, results) def flatten_with_path(structure): r"""Flattens a possibly nested structure into a list. This is a variant of :func:`~tree.flattens` which produces a list of pairs: ``(path, item)``. A path is a tuple of indices and/or keys which uniquely identifies the position of the corresponding ``item``. >>> tree.flatten_with_path([{"foo": 42}]) [((0, 'foo'), 42)] Args: structure: An arbitrarily nested structure. Returns: A list of ``(path, item)`` pairs corresponding to the flattened version of the input `structure`. Raises: TypeError: If ``structure`` is or contains a mapping with non-sortable keys. """ return list(_yield_flat_up_to(structure, structure)) #: Special value for use with :func:`traverse`. MAP_TO_NONE = object() def traverse(fn, structure, top_down=True): """Traverses the given nested structure, applying the given function. The traversal is depth-first. If ``top_down`` is True (default), parents are returned before their children (giving the option to avoid traversing into a sub-tree). >>> visited = [] >>> tree.traverse(visited.append, [(1, 2), [3], {"a": 4}], top_down=True) [(1, 2), [3], {'a': 4}] >>> visited [[(1, 2), [3], {'a': 4}], (1, 2), 1, 2, [3], 3, {'a': 4}, 4] >>> visited = [] >>> tree.traverse(visited.append, [(1, 2), [3], {"a": 4}], top_down=False) [(1, 2), [3], {'a': 4}] >>> visited [1, 2, (1, 2), 3, [3], 4, {'a': 4}, [(1, 2), [3], {'a': 4}]] Args: fn: The function to be applied to each sub-nest of the structure. When traversing top-down: If ``fn(subtree) is None`` the traversal continues into the sub-tree. If ``fn(subtree) is not None`` the traversal does not continue into the sub-tree. The sub-tree will be replaced by ``fn(subtree)`` in the returned structure (to replace the sub-tree with None, use the special value :data:`MAP_TO_NONE`). When traversing bottom-up: If ``fn(subtree) is None`` the traversed sub-tree is returned unaltered. If ``fn(subtree) is not None`` the sub-tree will be replaced by ``fn(subtree)`` in the returned structure (to replace the sub-tree with None, use the special value :data:`MAP_TO_NONE`). structure: The structure to traverse. top_down: If True, parent structures will be visited before their children. Returns: The structured output from the traversal. """ return traverse_with_path(lambda _, x: fn(x), structure, top_down=top_down) def traverse_with_path(fn, structure, top_down=True): """Traverses the given nested structure, applying the given function. The traversal is depth-first. If ``top_down`` is True (default), parents are returned before their children (giving the option to avoid traversing into a sub-tree). >>> visited = [] >>> tree.traverse_with_path( ... lambda path, subtree: visited.append((path, subtree)), ... [(1, 2), [3], {"a": 4}], ... top_down=True) [(1, 2), [3], {'a': 4}] >>> visited == [ ... ((), [(1, 2), [3], {'a': 4}]), ... ((0,), (1, 2)), ... ((0, 0), 1), ... ((0, 1), 2), ... ((1,), [3]), ... ((1, 0), 3), ... ((2,), {'a': 4}), ... ((2, 'a'), 4)] True >>> visited = [] >>> tree.traverse_with_path( ... lambda path, subtree: visited.append((path, subtree)), ... [(1, 2), [3], {"a": 4}], ... top_down=False) [(1, 2), [3], {'a': 4}] >>> visited == [ ... ((0, 0), 1), ... ((0, 1), 2), ... ((0,), (1, 2)), ... ((1, 0), 3), ... ((1,), [3]), ... ((2, 'a'), 4), ... ((2,), {'a': 4}), ... ((), [(1, 2), [3], {'a': 4}])] True Args: fn: The function to be applied to the path to each sub-nest of the structure and the sub-nest value. When traversing top-down: If ``fn(path, subtree) is None`` the traversal continues into the sub-tree. If ``fn(path, subtree) is not None`` the traversal does not continue into the sub-tree. The sub-tree will be replaced by ``fn(path, subtree)`` in the returned structure (to replace the sub-tree with None, use the special value :data:`MAP_TO_NONE`). When traversing bottom-up: If ``fn(path, subtree) is None`` the traversed sub-tree is returned unaltered. If ``fn(path, subtree) is not None`` the sub-tree will be replaced by ``fn(path, subtree)`` in the returned structure (to replace the sub-tree with None, use the special value :data:`MAP_TO_NONE`). structure: The structure to traverse. top_down: If True, parent structures will be visited before their children. Returns: The structured output from the traversal. """ def traverse_impl(path, structure): """Recursive traversal implementation.""" def subtree_fn(item): subtree_path, subtree = item return traverse_impl(path + (subtree_path,), subtree) def traverse_subtrees(): if is_nested(structure): return _sequence_like(structure, map(subtree_fn, _yield_sorted_items(structure))) else: return structure if top_down: ret = fn(path, structure) if ret is None: return traverse_subtrees() elif ret is MAP_TO_NONE: return None else: return ret else: traversed_structure = traverse_subtrees() ret = fn(path, traversed_structure) if ret is None: return traversed_structure elif ret is MAP_TO_NONE: return None else: return ret return traverse_impl((), structure)
tree-master
tree/__init__.py
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for utilities working with arbitrarily nested structures.""" import collections import doctest import types from typing import Any, Iterator, Mapping import unittest from absl.testing import parameterized import attr import numpy as np import tree import wrapt STRUCTURE1 = (((1, 2), 3), 4, (5, 6)) STRUCTURE2 = ((("foo1", "foo2"), "foo3"), "foo4", ("foo5", "foo6")) STRUCTURE_DIFFERENT_NUM_ELEMENTS = ("spam", "eggs") STRUCTURE_DIFFERENT_NESTING = (((1, 2), 3), 4, 5, (6,)) class DoctestTest(parameterized.TestCase): def testDoctest(self): extraglobs = { "collections": collections, "tree": tree, } num_failed, num_attempted = doctest.testmod( tree, extraglobs=extraglobs, optionflags=doctest.ELLIPSIS) self.assertGreater(num_attempted, 0, "No doctests found.") self.assertEqual(num_failed, 0, "{} doctests failed".format(num_failed)) class NestTest(parameterized.TestCase): def assertAllEquals(self, a, b): self.assertTrue((np.asarray(a) == b).all()) def testAttrsFlattenAndUnflatten(self): class BadAttr(object): """Class that has a non-iterable __attrs_attrs__.""" __attrs_attrs__ = None @attr.s class SampleAttr(object): field1 = attr.ib() field2 = attr.ib() field_values = [1, 2] sample_attr = SampleAttr(*field_values) self.assertFalse(tree._is_attrs(field_values)) self.assertTrue(tree._is_attrs(sample_attr)) flat = tree.flatten(sample_attr) self.assertEqual(field_values, flat) restructured_from_flat = tree.unflatten_as(sample_attr, flat) self.assertIsInstance(restructured_from_flat, SampleAttr) self.assertEqual(restructured_from_flat, sample_attr) # Check that flatten fails if attributes are not iterable with self.assertRaisesRegex(TypeError, "object is not iterable"): flat = tree.flatten(BadAttr()) @parameterized.parameters([ (1, 2, 3), ({"B": 10, "A": 20}, [1, 2], 3), ((1, 2), [3, 4], 5), (collections.namedtuple("Point", ["x", "y"])(1, 2), 3, 4), wrapt.ObjectProxy( (collections.namedtuple("Point", ["x", "y"])(1, 2), 3, 4)) ]) def testAttrsMapStructure(self, *field_values): @attr.s class SampleAttr(object): field3 = attr.ib() field1 = attr.ib() field2 = attr.ib() structure = SampleAttr(*field_values) new_structure = tree.map_structure(lambda x: x, structure) self.assertEqual(structure, new_structure) def testFlattenAndUnflatten(self): structure = ((3, 4), 5, (6, 7, (9, 10), 8)) flat = ["a", "b", "c", "d", "e", "f", "g", "h"] self.assertEqual(tree.flatten(structure), [3, 4, 5, 6, 7, 9, 10, 8]) self.assertEqual( tree.unflatten_as(structure, flat), (("a", "b"), "c", ("d", "e", ("f", "g"), "h"))) point = collections.namedtuple("Point", ["x", "y"]) structure = (point(x=4, y=2), ((point(x=1, y=0),),)) flat = [4, 2, 1, 0] self.assertEqual(tree.flatten(structure), flat) restructured_from_flat = tree.unflatten_as(structure, flat) self.assertEqual(restructured_from_flat, structure) self.assertEqual(restructured_from_flat[0].x, 4) self.assertEqual(restructured_from_flat[0].y, 2) self.assertEqual(restructured_from_flat[1][0][0].x, 1) self.assertEqual(restructured_from_flat[1][0][0].y, 0) self.assertEqual([5], tree.flatten(5)) self.assertEqual([np.array([5])], tree.flatten(np.array([5]))) self.assertEqual("a", tree.unflatten_as(5, ["a"])) self.assertEqual( np.array([5]), tree.unflatten_as("scalar", [np.array([5])])) with self.assertRaisesRegex(ValueError, "Structure is a scalar"): tree.unflatten_as("scalar", [4, 5]) with self.assertRaisesRegex(TypeError, "flat_sequence"): tree.unflatten_as([4, 5], "bad_sequence") with self.assertRaises(ValueError): tree.unflatten_as([5, 6, [7, 8]], ["a", "b", "c"]) def testFlattenDictOrder(self): ordered = collections.OrderedDict([("d", 3), ("b", 1), ("a", 0), ("c", 2)]) plain = {"d": 3, "b": 1, "a": 0, "c": 2} ordered_flat = tree.flatten(ordered) plain_flat = tree.flatten(plain) self.assertEqual([0, 1, 2, 3], ordered_flat) self.assertEqual([0, 1, 2, 3], plain_flat) def testUnflattenDictOrder(self): ordered = collections.OrderedDict([("d", 0), ("b", 0), ("a", 0), ("c", 0)]) plain = {"d": 0, "b": 0, "a": 0, "c": 0} seq = [0, 1, 2, 3] ordered_reconstruction = tree.unflatten_as(ordered, seq) plain_reconstruction = tree.unflatten_as(plain, seq) self.assertEqual( collections.OrderedDict([("d", 3), ("b", 1), ("a", 0), ("c", 2)]), ordered_reconstruction) self.assertEqual({"d": 3, "b": 1, "a": 0, "c": 2}, plain_reconstruction) def testFlattenAndUnflatten_withDicts(self): # A nice messy mix of tuples, lists, dicts, and `OrderedDict`s. named_tuple = collections.namedtuple("A", ("b", "c")) mess = [ "z", named_tuple(3, 4), { "c": [ 1, collections.OrderedDict([ ("b", 3), ("a", 2), ]), ], "b": 5 }, 17 ] flattened = tree.flatten(mess) self.assertEqual(flattened, ["z", 3, 4, 5, 1, 2, 3, 17]) structure_of_mess = [ 14, named_tuple("a", True), { "c": [ 0, collections.OrderedDict([ ("b", 9), ("a", 8), ]), ], "b": 3 }, "hi everybody", ] self.assertEqual(mess, tree.unflatten_as(structure_of_mess, flattened)) # Check also that the OrderedDict was created, with the correct key order. unflattened_ordered_dict = tree.unflatten_as( structure_of_mess, flattened)[2]["c"][1] self.assertIsInstance(unflattened_ordered_dict, collections.OrderedDict) self.assertEqual(list(unflattened_ordered_dict.keys()), ["b", "a"]) def testFlatten_numpyIsNotFlattened(self): structure = np.array([1, 2, 3]) flattened = tree.flatten(structure) self.assertLen(flattened, 1) def testFlatten_stringIsNotFlattened(self): structure = "lots of letters" flattened = tree.flatten(structure) self.assertLen(flattened, 1) self.assertEqual(structure, tree.unflatten_as("goodbye", flattened)) def testFlatten_bytearrayIsNotFlattened(self): structure = bytearray("bytes in an array", "ascii") flattened = tree.flatten(structure) self.assertLen(flattened, 1) self.assertEqual(flattened, [structure]) self.assertEqual(structure, tree.unflatten_as(bytearray("hello", "ascii"), flattened)) def testUnflattenSequenceAs_notIterableError(self): with self.assertRaisesRegex(TypeError, "flat_sequence must be a sequence"): tree.unflatten_as("hi", "bye") def testUnflattenSequenceAs_wrongLengthsError(self): with self.assertRaisesRegex( ValueError, "Structure had 2 elements, but flat_sequence had 3 elements."): tree.unflatten_as(["hello", "world"], ["and", "goodbye", "again"]) def testUnflattenSequenceAs_defaultdict(self): structure = collections.defaultdict( list, [("a", [None]), ("b", [None, None])]) sequence = [1, 2, 3] expected = collections.defaultdict( list, [("a", [1]), ("b", [2, 3])]) self.assertEqual(expected, tree.unflatten_as(structure, sequence)) def testIsSequence(self): self.assertFalse(tree.is_nested("1234")) self.assertFalse(tree.is_nested(b"1234")) self.assertFalse(tree.is_nested(u"1234")) self.assertFalse(tree.is_nested(bytearray("1234", "ascii"))) self.assertTrue(tree.is_nested([1, 3, [4, 5]])) self.assertTrue(tree.is_nested(((7, 8), (5, 6)))) self.assertTrue(tree.is_nested([])) self.assertTrue(tree.is_nested({"a": 1, "b": 2})) self.assertFalse(tree.is_nested(set([1, 2]))) ones = np.ones([2, 3]) self.assertFalse(tree.is_nested(ones)) self.assertFalse(tree.is_nested(np.tanh(ones))) self.assertFalse(tree.is_nested(np.ones((4, 5)))) # pylint does not correctly recognize these as class names and # suggests to use variable style under_score naming. # pylint: disable=invalid-name Named0ab = collections.namedtuple("named_0", ("a", "b")) Named1ab = collections.namedtuple("named_1", ("a", "b")) SameNameab = collections.namedtuple("same_name", ("a", "b")) SameNameab2 = collections.namedtuple("same_name", ("a", "b")) SameNamexy = collections.namedtuple("same_name", ("x", "y")) SameName1xy = collections.namedtuple("same_name_1", ("x", "y")) SameName1xy2 = collections.namedtuple("same_name_1", ("x", "y")) NotSameName = collections.namedtuple("not_same_name", ("a", "b")) # pylint: enable=invalid-name class SameNamedType1(SameNameab): pass # pylint: disable=g-error-prone-assert-raises def testAssertSameStructure(self): tree.assert_same_structure(STRUCTURE1, STRUCTURE2) tree.assert_same_structure("abc", 1.0) tree.assert_same_structure(b"abc", 1.0) tree.assert_same_structure(u"abc", 1.0) tree.assert_same_structure(bytearray("abc", "ascii"), 1.0) tree.assert_same_structure("abc", np.array([0, 1])) def testAssertSameStructure_differentNumElements(self): with self.assertRaisesRegex( ValueError, ("The two structures don't have the same nested structure\\.\n\n" "First structure:.*?\n\n" "Second structure:.*\n\n" "More specifically: Substructure " r'"type=tuple str=\(\(1, 2\), 3\)" is a sequence, while ' 'substructure "type=str str=spam" is not\n' "Entire first structure:\n" r"\(\(\(\., \.\), \.\), \., \(\., \.\)\)\n" "Entire second structure:\n" r"\(\., \.\)")): tree.assert_same_structure(STRUCTURE1, STRUCTURE_DIFFERENT_NUM_ELEMENTS) def testAssertSameStructure_listVsNdArray(self): with self.assertRaisesRegex( ValueError, ("The two structures don't have the same nested structure\\.\n\n" "First structure:.*?\n\n" "Second structure:.*\n\n" r'More specifically: Substructure "type=list str=\[0, 1\]" ' r'is a sequence, while substructure "type=ndarray str=\[0 1\]" ' "is not")): tree.assert_same_structure([0, 1], np.array([0, 1])) def testAssertSameStructure_intVsList(self): with self.assertRaisesRegex( ValueError, ("The two structures don't have the same nested structure\\.\n\n" "First structure:.*?\n\n" "Second structure:.*\n\n" r'More specifically: Substructure "type=list str=\[0, 1\]" ' 'is a sequence, while substructure "type=int str=0" ' "is not")): tree.assert_same_structure(0, [0, 1]) def testAssertSameStructure_tupleVsList(self): self.assertRaises( TypeError, tree.assert_same_structure, (0, 1), [0, 1]) def testAssertSameStructure_differentNesting(self): with self.assertRaisesRegex( ValueError, ("don't have the same nested structure\\.\n\n" "First structure: .*?\n\nSecond structure: ")): tree.assert_same_structure(STRUCTURE1, STRUCTURE_DIFFERENT_NESTING) def testAssertSameStructure_tupleVsNamedTuple(self): self.assertRaises(TypeError, tree.assert_same_structure, (0, 1), NestTest.Named0ab("a", "b")) def testAssertSameStructure_sameNamedTupleDifferentContents(self): tree.assert_same_structure(NestTest.Named0ab(3, 4), NestTest.Named0ab("a", "b")) def testAssertSameStructure_differentNamedTuples(self): self.assertRaises(TypeError, tree.assert_same_structure, NestTest.Named0ab(3, 4), NestTest.Named1ab(3, 4)) def testAssertSameStructure_sameNamedTupleDifferentStructuredContents(self): with self.assertRaisesRegex( ValueError, ("don't have the same nested structure\\.\n\n" "First structure: .*?\n\nSecond structure: ")): tree.assert_same_structure(NestTest.Named0ab(3, 4), NestTest.Named0ab([3], 4)) def testAssertSameStructure_differentlyNestedLists(self): with self.assertRaisesRegex( ValueError, ("don't have the same nested structure\\.\n\n" "First structure: .*?\n\nSecond structure: ")): tree.assert_same_structure([[3], 4], [3, [4]]) def testAssertSameStructure_listStructureWithAndWithoutTypes(self): structure1_list = [[[1, 2], 3], 4, [5, 6]] with self.assertRaisesRegex(TypeError, "don't have the same sequence type"): tree.assert_same_structure(STRUCTURE1, structure1_list) tree.assert_same_structure(STRUCTURE1, STRUCTURE2, check_types=False) tree.assert_same_structure(STRUCTURE1, structure1_list, check_types=False) def testAssertSameStructure_dictionaryDifferentKeys(self): with self.assertRaisesRegex(ValueError, "don't have the same set of keys"): tree.assert_same_structure({"a": 1}, {"b": 1}) def testAssertSameStructure_sameNameNamedTuples(self): tree.assert_same_structure(NestTest.SameNameab(0, 1), NestTest.SameNameab2(2, 3)) def testAssertSameStructure_sameNameNamedTuplesNested(self): # This assertion is expected to pass: two namedtuples with the same # name and field names are considered to be identical. tree.assert_same_structure( NestTest.SameNameab(NestTest.SameName1xy(0, 1), 2), NestTest.SameNameab2(NestTest.SameName1xy2(2, 3), 4)) def testAssertSameStructure_sameNameNamedTuplesDifferentStructure(self): expected_message = "The two structures don't have the same.*" with self.assertRaisesRegex(ValueError, expected_message): tree.assert_same_structure( NestTest.SameNameab(0, NestTest.SameNameab2(1, 2)), NestTest.SameNameab2(NestTest.SameNameab(0, 1), 2)) def testAssertSameStructure_differentNameNamedStructures(self): self.assertRaises(TypeError, tree.assert_same_structure, NestTest.SameNameab(0, 1), NestTest.NotSameName(2, 3)) def testAssertSameStructure_sameNameDifferentFieldNames(self): self.assertRaises(TypeError, tree.assert_same_structure, NestTest.SameNameab(0, 1), NestTest.SameNamexy(2, 3)) def testAssertSameStructure_classWrappingNamedTuple(self): self.assertRaises(TypeError, tree.assert_same_structure, NestTest.SameNameab(0, 1), NestTest.SameNamedType1(2, 3)) # pylint: enable=g-error-prone-assert-raises def testMapStructure(self): structure2 = (((7, 8), 9), 10, (11, 12)) structure1_plus1 = tree.map_structure(lambda x: x + 1, STRUCTURE1) tree.assert_same_structure(STRUCTURE1, structure1_plus1) self.assertAllEquals( [2, 3, 4, 5, 6, 7], tree.flatten(structure1_plus1)) structure1_plus_structure2 = tree.map_structure( lambda x, y: x + y, STRUCTURE1, structure2) self.assertEqual( (((1 + 7, 2 + 8), 3 + 9), 4 + 10, (5 + 11, 6 + 12)), structure1_plus_structure2) self.assertEqual(3, tree.map_structure(lambda x: x - 1, 4)) self.assertEqual(7, tree.map_structure(lambda x, y: x + y, 3, 4)) # Empty structures self.assertEqual((), tree.map_structure(lambda x: x + 1, ())) self.assertEqual([], tree.map_structure(lambda x: x + 1, [])) self.assertEqual({}, tree.map_structure(lambda x: x + 1, {})) empty_nt = collections.namedtuple("empty_nt", "") self.assertEqual(empty_nt(), tree.map_structure(lambda x: x + 1, empty_nt())) # This is checking actual equality of types, empty list != empty tuple self.assertNotEqual((), tree.map_structure(lambda x: x + 1, [])) with self.assertRaisesRegex(TypeError, "callable"): tree.map_structure("bad", structure1_plus1) with self.assertRaisesRegex(ValueError, "at least one structure"): tree.map_structure(lambda x: x) with self.assertRaisesRegex(ValueError, "same number of elements"): tree.map_structure(lambda x, y: None, (3, 4), (3, 4, 5)) with self.assertRaisesRegex(ValueError, "same nested structure"): tree.map_structure(lambda x, y: None, 3, (3,)) with self.assertRaisesRegex(TypeError, "same sequence type"): tree.map_structure(lambda x, y: None, ((3, 4), 5), [(3, 4), 5]) with self.assertRaisesRegex(ValueError, "same nested structure"): tree.map_structure(lambda x, y: None, ((3, 4), 5), (3, (4, 5))) structure1_list = [[[1, 2], 3], 4, [5, 6]] with self.assertRaisesRegex(TypeError, "same sequence type"): tree.map_structure(lambda x, y: None, STRUCTURE1, structure1_list) tree.map_structure(lambda x, y: None, STRUCTURE1, structure1_list, check_types=False) with self.assertRaisesRegex(ValueError, "same nested structure"): tree.map_structure(lambda x, y: None, ((3, 4), 5), (3, (4, 5)), check_types=False) with self.assertRaisesRegex(ValueError, "Only valid keyword argument.*foo"): tree.map_structure(lambda x: None, STRUCTURE1, foo="a") with self.assertRaisesRegex(ValueError, "Only valid keyword argument.*foo"): tree.map_structure(lambda x: None, STRUCTURE1, check_types=False, foo="a") def testMapStructureWithStrings(self): ab_tuple = collections.namedtuple("ab_tuple", "a, b") inp_a = ab_tuple(a="foo", b=("bar", "baz")) inp_b = ab_tuple(a=2, b=(1, 3)) out = tree.map_structure(lambda string, repeats: string * repeats, inp_a, inp_b) self.assertEqual("foofoo", out.a) self.assertEqual("bar", out.b[0]) self.assertEqual("bazbazbaz", out.b[1]) nt = ab_tuple(a=("something", "something_else"), b="yet another thing") rev_nt = tree.map_structure(lambda x: x[::-1], nt) # Check the output is the correct structure, and all strings are reversed. tree.assert_same_structure(nt, rev_nt) self.assertEqual(nt.a[0][::-1], rev_nt.a[0]) self.assertEqual(nt.a[1][::-1], rev_nt.a[1]) self.assertEqual(nt.b[::-1], rev_nt.b) def testAssertShallowStructure(self): inp_ab = ["a", "b"] inp_abc = ["a", "b", "c"] with self.assertRaisesRegex( ValueError, tree._STRUCTURES_HAVE_MISMATCHING_LENGTHS.format( input_length=len(inp_ab), shallow_length=len(inp_abc))): tree._assert_shallow_structure(inp_abc, inp_ab) inp_ab1 = [(1, 1), (2, 2)] inp_ab2 = [[1, 1], [2, 2]] with self.assertRaisesWithLiteralMatch( TypeError, tree._STRUCTURES_HAVE_MISMATCHING_TYPES.format( shallow_type=type(inp_ab2[0]), input_type=type(inp_ab1[0]))): tree._assert_shallow_structure(shallow_tree=inp_ab2, input_tree=inp_ab1) tree._assert_shallow_structure(inp_ab2, inp_ab1, check_types=False) inp_ab1 = {"a": (1, 1), "b": {"c": (2, 2)}} inp_ab2 = {"a": (1, 1), "b": {"d": (2, 2)}} with self.assertRaisesWithLiteralMatch( ValueError, tree._SHALLOW_TREE_HAS_INVALID_KEYS.format(["d"])): tree._assert_shallow_structure(inp_ab2, inp_ab1) inp_ab = collections.OrderedDict([("a", 1), ("b", (2, 3))]) inp_ba = collections.OrderedDict([("b", (2, 3)), ("a", 1)]) tree._assert_shallow_structure(inp_ab, inp_ba) # regression test for b/130633904 tree._assert_shallow_structure({0: "foo"}, ["foo"], check_types=False) def testFlattenUpTo(self): # Shallow tree ends at scalar. input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] shallow_tree = [[True, True], [False, True]] flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree, [[2, 2], [3, 3], [4, 9], [5, 5]]) self.assertEqual(flattened_shallow_tree, [True, True, False, True]) # Shallow tree ends at string. input_tree = [[("a", 1), [("b", 2), [("c", 3), [("d", 4)]]]]] shallow_tree = [["level_1", ["level_2", ["level_3", ["level_4"]]]]] input_tree_flattened_as_shallow_tree = tree.flatten_up_to(shallow_tree, input_tree) input_tree_flattened = tree.flatten(input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree, [("a", 1), ("b", 2), ("c", 3), ("d", 4)]) self.assertEqual(input_tree_flattened, ["a", 1, "b", 2, "c", 3, "d", 4]) # Make sure dicts are correctly flattened, yielding values, not keys. input_tree = {"a": 1, "b": {"c": 2}, "d": [3, (4, 5)]} shallow_tree = {"a": 0, "b": 0, "d": [0, 0]} input_tree_flattened_as_shallow_tree = tree.flatten_up_to(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree, [1, {"c": 2}, 3, (4, 5)]) # Namedtuples. ab_tuple = collections.namedtuple("ab_tuple", "a, b") input_tree = ab_tuple(a=[0, 1], b=2) shallow_tree = ab_tuple(a=0, b=1) input_tree_flattened_as_shallow_tree = tree.flatten_up_to(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree, [[0, 1], 2]) # Attrs. @attr.s class ABAttr(object): a = attr.ib() b = attr.ib() input_tree = ABAttr(a=[0, 1], b=2) shallow_tree = ABAttr(a=0, b=1) input_tree_flattened_as_shallow_tree = tree.flatten_up_to(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree, [[0, 1], 2]) # Nested dicts, OrderedDicts and namedtuples. input_tree = collections.OrderedDict( [("a", ab_tuple(a=[0, {"b": 1}], b=2)), ("c", {"d": 3, "e": collections.OrderedDict([("f", 4)])})]) shallow_tree = input_tree input_tree_flattened_as_shallow_tree = tree.flatten_up_to(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree, [0, 1, 2, 3, 4]) shallow_tree = collections.OrderedDict([("a", 0), ("c", {"d": 3, "e": 1})]) input_tree_flattened_as_shallow_tree = tree.flatten_up_to(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree, [ab_tuple(a=[0, {"b": 1}], b=2), 3, collections.OrderedDict([("f", 4)])]) shallow_tree = collections.OrderedDict([("a", 0), ("c", 0)]) input_tree_flattened_as_shallow_tree = tree.flatten_up_to(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree, [ab_tuple(a=[0, {"b": 1}], b=2), {"d": 3, "e": collections.OrderedDict([("f", 4)])}]) ## Shallow non-list edge-case. # Using iterable elements. input_tree = ["input_tree"] shallow_tree = "shallow_tree" flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) input_tree = ["input_tree_0", "input_tree_1"] shallow_tree = "shallow_tree" flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) # Using non-iterable elements. input_tree = [0] shallow_tree = 9 flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) input_tree = [0, 1] shallow_tree = 9 flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) ## Both non-list edge-case. # Using iterable elements. input_tree = "input_tree" shallow_tree = "shallow_tree" flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) # Using non-iterable elements. input_tree = 0 shallow_tree = 0 flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) ## Input non-list edge-case. # Using iterable elements. input_tree = "input_tree" shallow_tree = ["shallow_tree"] with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ.format(type(input_tree))): flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_shallow_tree, shallow_tree) input_tree = "input_tree" shallow_tree = ["shallow_tree_9", "shallow_tree_8"] with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ.format(type(input_tree))): flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_shallow_tree, shallow_tree) # Using non-iterable elements. input_tree = 0 shallow_tree = [9] with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ.format(type(input_tree))): flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_shallow_tree, shallow_tree) input_tree = 0 shallow_tree = [9, 8] with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ.format(type(input_tree))): flattened_input_tree = tree.flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = tree.flatten_up_to(shallow_tree, shallow_tree) self.assertEqual(flattened_shallow_tree, shallow_tree) def testByteStringsNotTreatedAsIterable(self): structure = [u"unicode string", b"byte string"] flattened_structure = tree.flatten_up_to(structure, structure) self.assertEqual(structure, flattened_structure) def testFlattenWithPathUpTo(self): def get_paths_and_values(shallow_tree, input_tree): path_value_pairs = tree.flatten_with_path_up_to(shallow_tree, input_tree) paths = [p for p, _ in path_value_pairs] values = [v for _, v in path_value_pairs] return paths, values # Shallow tree ends at scalar. input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] shallow_tree = [[True, True], [False, True]] (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree_paths, [(0, 0), (0, 1), (1, 0), (1, 1)]) self.assertEqual(flattened_input_tree, [[2, 2], [3, 3], [4, 9], [5, 5]]) self.assertEqual(flattened_shallow_tree_paths, [(0, 0), (0, 1), (1, 0), (1, 1)]) self.assertEqual(flattened_shallow_tree, [True, True, False, True]) # Shallow tree ends at string. input_tree = [[("a", 1), [("b", 2), [("c", 3), [("d", 4)]]]]] shallow_tree = [["level_1", ["level_2", ["level_3", ["level_4"]]]]] (input_tree_flattened_as_shallow_tree_paths, input_tree_flattened_as_shallow_tree) = get_paths_and_values(shallow_tree, input_tree) input_tree_flattened_paths = [ p for p, _ in tree.flatten_with_path(input_tree) ] input_tree_flattened = tree.flatten(input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree_paths, [(0, 0), (0, 1, 0), (0, 1, 1, 0), (0, 1, 1, 1, 0)]) self.assertEqual(input_tree_flattened_as_shallow_tree, [("a", 1), ("b", 2), ("c", 3), ("d", 4)]) self.assertEqual(input_tree_flattened_paths, [(0, 0, 0), (0, 0, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0, 0), (0, 1, 1, 0, 1), (0, 1, 1, 1, 0, 0), (0, 1, 1, 1, 0, 1)]) self.assertEqual(input_tree_flattened, ["a", 1, "b", 2, "c", 3, "d", 4]) # Make sure dicts are correctly flattened, yielding values, not keys. input_tree = {"a": 1, "b": {"c": 2}, "d": [3, (4, 5)]} shallow_tree = {"a": 0, "b": 0, "d": [0, 0]} (input_tree_flattened_as_shallow_tree_paths, input_tree_flattened_as_shallow_tree) = get_paths_and_values(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree_paths, [("a",), ("b",), ("d", 0), ("d", 1)]) self.assertEqual(input_tree_flattened_as_shallow_tree, [1, {"c": 2}, 3, (4, 5)]) # Namedtuples. ab_tuple = collections.namedtuple("ab_tuple", "a, b") input_tree = ab_tuple(a=[0, 1], b=2) shallow_tree = ab_tuple(a=0, b=1) (input_tree_flattened_as_shallow_tree_paths, input_tree_flattened_as_shallow_tree) = get_paths_and_values(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree_paths, [("a",), ("b",)]) self.assertEqual(input_tree_flattened_as_shallow_tree, [[0, 1], 2]) # Nested dicts, OrderedDicts and namedtuples. input_tree = collections.OrderedDict( [("a", ab_tuple(a=[0, {"b": 1}], b=2)), ("c", {"d": 3, "e": collections.OrderedDict([("f", 4)])})]) shallow_tree = input_tree (input_tree_flattened_as_shallow_tree_paths, input_tree_flattened_as_shallow_tree) = get_paths_and_values(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree_paths, [("a", "a", 0), ("a", "a", 1, "b"), ("a", "b"), ("c", "d"), ("c", "e", "f")]) self.assertEqual(input_tree_flattened_as_shallow_tree, [0, 1, 2, 3, 4]) shallow_tree = collections.OrderedDict([("a", 0), ("c", {"d": 3, "e": 1})]) (input_tree_flattened_as_shallow_tree_paths, input_tree_flattened_as_shallow_tree) = get_paths_and_values(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree_paths, [("a",), ("c", "d"), ("c", "e")]) self.assertEqual(input_tree_flattened_as_shallow_tree, [ab_tuple(a=[0, {"b": 1}], b=2), 3, collections.OrderedDict([("f", 4)])]) shallow_tree = collections.OrderedDict([("a", 0), ("c", 0)]) (input_tree_flattened_as_shallow_tree_paths, input_tree_flattened_as_shallow_tree) = get_paths_and_values(shallow_tree, input_tree) self.assertEqual(input_tree_flattened_as_shallow_tree_paths, [("a",), ("c",)]) self.assertEqual(input_tree_flattened_as_shallow_tree, [ab_tuple(a=[0, {"b": 1}], b=2), {"d": 3, "e": collections.OrderedDict([("f", 4)])}]) ## Shallow non-list edge-case. # Using iterable elements. input_tree = ["input_tree"] shallow_tree = "shallow_tree" (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree_paths, [()]) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree_paths, [()]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) input_tree = ["input_tree_0", "input_tree_1"] shallow_tree = "shallow_tree" (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree_paths, [()]) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree_paths, [()]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) # Test case where len(shallow_tree) < len(input_tree) input_tree = {"a": "A", "b": "B", "c": "C"} shallow_tree = {"a": 1, "c": 2} # Using non-iterable elements. input_tree = [0] shallow_tree = 9 (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree_paths, [()]) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree_paths, [()]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) input_tree = [0, 1] shallow_tree = 9 (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree_paths, [()]) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree_paths, [()]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) ## Both non-list edge-case. # Using iterable elements. input_tree = "input_tree" shallow_tree = "shallow_tree" (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree_paths, [()]) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree_paths, [()]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) # Using non-iterable elements. input_tree = 0 shallow_tree = 0 (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_input_tree_paths, [()]) self.assertEqual(flattened_input_tree, [input_tree]) self.assertEqual(flattened_shallow_tree_paths, [()]) self.assertEqual(flattened_shallow_tree, [shallow_tree]) ## Input non-list edge-case. # Using iterable elements. input_tree = "input_tree" shallow_tree = ["shallow_tree"] with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH.format( path=[], input_type=type(input_tree))): (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_shallow_tree_paths, [(0,)]) self.assertEqual(flattened_shallow_tree, shallow_tree) input_tree = "input_tree" shallow_tree = ["shallow_tree_9", "shallow_tree_8"] with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH.format( path=[], input_type=type(input_tree))): (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_shallow_tree_paths, [(0,), (1,)]) self.assertEqual(flattened_shallow_tree, shallow_tree) # Using non-iterable elements. input_tree = 0 shallow_tree = [9] with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH.format( path=[], input_type=type(input_tree))): (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_shallow_tree_paths, [(0,)]) self.assertEqual(flattened_shallow_tree, shallow_tree) input_tree = 0 shallow_tree = [9, 8] with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH.format( path=[], input_type=type(input_tree))): (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(shallow_tree, input_tree) (flattened_shallow_tree_paths, flattened_shallow_tree) = get_paths_and_values(shallow_tree, shallow_tree) self.assertEqual(flattened_shallow_tree_paths, [(0,), (1,)]) self.assertEqual(flattened_shallow_tree, shallow_tree) # Test that error messages include paths. input_tree = {"a": {"b": {0, 1}}} structure = {"a": {"b": [0, 1]}} with self.assertRaisesWithLiteralMatch( TypeError, tree._IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH.format( path=["a", "b"], input_type=type(input_tree["a"]["b"]))): (flattened_input_tree_paths, flattened_input_tree) = get_paths_and_values(structure, input_tree) (flattened_tree_paths, flattened_tree) = get_paths_and_values(structure, structure) self.assertEqual(flattened_tree_paths, [("a", "b", 0,), ("a", "b", 1,)]) self.assertEqual(flattened_tree, structure["a"]["b"]) def testMapStructureUpTo(self): # Named tuples. ab_tuple = collections.namedtuple("ab_tuple", "a, b") op_tuple = collections.namedtuple("op_tuple", "add, mul") inp_val = ab_tuple(a=2, b=3) inp_ops = ab_tuple(a=op_tuple(add=1, mul=2), b=op_tuple(add=2, mul=3)) out = tree.map_structure_up_to( inp_val, lambda val, ops: (val + ops.add) * ops.mul, inp_val, inp_ops, check_types=False) self.assertEqual(out.a, 6) self.assertEqual(out.b, 15) # Lists. data_list = [[2, 4, 6, 8], [[1, 3, 5, 7, 9], [3, 5, 7]]] name_list = ["evens", ["odds", "primes"]] out = tree.map_structure_up_to( name_list, lambda name, sec: "first_{}_{}".format(len(sec), name), name_list, data_list) self.assertEqual(out, ["first_4_evens", ["first_5_odds", "first_3_primes"]]) # We cannot define namedtuples within @parameterized argument lists. # pylint: disable=invalid-name Foo = collections.namedtuple("Foo", ["a", "b"]) Bar = collections.namedtuple("Bar", ["c", "d"]) # pylint: enable=invalid-name @parameterized.parameters([ dict(inputs=[], expected=[]), dict(inputs=[23, "42"], expected=[((0,), 23), ((1,), "42")]), dict(inputs=[[[[108]]]], expected=[((0, 0, 0, 0), 108)]), dict(inputs=Foo(a=3, b=Bar(c=23, d=42)), expected=[(("a",), 3), (("b", "c"), 23), (("b", "d"), 42)]), dict(inputs=Foo(a=Bar(c=23, d=42), b=Bar(c=0, d="thing")), expected=[(("a", "c"), 23), (("a", "d"), 42), (("b", "c"), 0), (("b", "d"), "thing")]), dict(inputs=Bar(c=42, d=43), expected=[(("c",), 42), (("d",), 43)]), dict(inputs=Bar(c=[42], d=43), expected=[(("c", 0), 42), (("d",), 43)]), dict(inputs=wrapt.ObjectProxy(Bar(c=[42], d=43)), expected=[(("c", 0), 42), (("d",), 43)]), ]) def testFlattenWithPath(self, inputs, expected): self.assertEqual(tree.flatten_with_path(inputs), expected) @parameterized.named_parameters([ dict(testcase_name="Tuples", s1=(1, 2), s2=(3, 4), check_types=True, expected=(((0,), 4), ((1,), 6))), dict(testcase_name="Dicts", s1={"a": 1, "b": 2}, s2={"b": 4, "a": 3}, check_types=True, expected={"a": (("a",), 4), "b": (("b",), 6)}), dict(testcase_name="Mixed", s1=(1, 2), s2=[3, 4], check_types=False, expected=(((0,), 4), ((1,), 6))), dict(testcase_name="Nested", s1={"a": [2, 3], "b": [1, 2, 3]}, s2={"b": [5, 6, 7], "a": [8, 9]}, check_types=True, expected={"a": [(("a", 0), 10), (("a", 1), 12)], "b": [(("b", 0), 6), (("b", 1), 8), (("b", 2), 10)]}), ]) def testMapWithPathCompatibleStructures(self, s1, s2, check_types, expected): def path_and_sum(path, *values): return path, sum(values) result = tree.map_structure_with_path( path_and_sum, s1, s2, check_types=check_types) self.assertEqual(expected, result) @parameterized.named_parameters([ dict(testcase_name="Tuples", s1=(1, 2, 3), s2=(4, 5), error_type=ValueError), dict(testcase_name="Dicts", s1={"a": 1}, s2={"b": 2}, error_type=ValueError), dict(testcase_name="Nested", s1={"a": [2, 3, 4], "b": [1, 3]}, s2={"b": [5, 6], "a": [8, 9]}, error_type=ValueError) ]) def testMapWithPathIncompatibleStructures(self, s1, s2, error_type): with self.assertRaises(error_type): tree.map_structure_with_path(lambda path, *s: 0, s1, s2) def testMappingProxyType(self): structure = types.MappingProxyType({"a": 1, "b": (2, 3)}) expected = types.MappingProxyType({"a": 4, "b": (5, 6)}) self.assertEqual(tree.flatten(structure), [1, 2, 3]) self.assertEqual(tree.unflatten_as(structure, [4, 5, 6]), expected) self.assertEqual(tree.map_structure(lambda v: v + 3, structure), expected) def testTraverseListsToTuples(self): structure = [(1, 2), [3], {"a": [4]}] self.assertEqual( ((1, 2), (3,), {"a": (4,)}), tree.traverse( lambda x: tuple(x) if isinstance(x, list) else x, structure, top_down=False)) def testTraverseEarlyTermination(self): structure = [(1, [2]), [3, (4, 5, 6)]] visited = [] def visit(x): visited.append(x) return "X" if isinstance(x, tuple) and len(x) > 2 else None output = tree.traverse(visit, structure) self.assertEqual([(1, [2]), [3, "X"]], output) self.assertEqual( [[(1, [2]), [3, (4, 5, 6)]], (1, [2]), 1, [2], 2, [3, (4, 5, 6)], 3, (4, 5, 6)], visited) def testMapStructureAcrossSubtreesDict(self): shallow = {"a": 1, "b": {"c": 2}} deep1 = {"a": 2, "b": {"c": 3, "d": 2}, "e": 4} deep2 = {"a": 3, "b": {"c": 2, "d": 3}, "e": 1} summed = tree.map_structure_up_to( shallow, lambda *args: sum(args), deep1, deep2) expected = {"a": 5, "b": {"c": 5}} self.assertEqual(summed, expected) concatenated = tree.map_structure_up_to( shallow, lambda *args: args, deep1, deep2) expected = {"a": (2, 3), "b": {"c": (3, 2)}} self.assertEqual(concatenated, expected) def testMapStructureAcrossSubtreesNoneValues(self): shallow = [1, [None]] deep1 = [1, [2, 3]] deep2 = [2, [3, 4]] summed = tree.map_structure_up_to( shallow, lambda *args: sum(args), deep1, deep2) expected = [3, [5]] self.assertEqual(summed, expected) def testMapStructureAcrossSubtreesList(self): shallow = [1, [1]] deep1 = [1, [2, 3]] deep2 = [2, [3, 4]] summed = tree.map_structure_up_to( shallow, lambda *args: sum(args), deep1, deep2) expected = [3, [5]] self.assertEqual(summed, expected) def testMapStructureAcrossSubtreesTuple(self): shallow = (1, (1,)) deep1 = (1, (2, 3)) deep2 = (2, (3, 4)) summed = tree.map_structure_up_to( shallow, lambda *args: sum(args), deep1, deep2) expected = (3, (5,)) self.assertEqual(summed, expected) def testMapStructureAcrossSubtreesNamedTuple(self): Foo = collections.namedtuple("Foo", ["x", "y"]) Bar = collections.namedtuple("Bar", ["x"]) shallow = Bar(1) deep1 = Foo(1, (1, 0)) deep2 = Foo(2, (2, 0)) summed = tree.map_structure_up_to( shallow, lambda *args: sum(args), deep1, deep2) expected = Bar(3) self.assertEqual(summed, expected) def testMapStructureAcrossSubtreesListTuple(self): # Tuples and lists can be used interchangeably between shallow structure # and input structures. Output takes on type of the shallow structure shallow = [1, (1,)] deep1 = [1, [2, 3]] deep2 = [2, [3, 4]] summed = tree.map_structure_up_to(shallow, lambda *args: sum(args), deep1, deep2) expected = [3, (5,)] self.assertEqual(summed, expected) shallow = [1, [1]] deep1 = [1, (2, 3)] deep2 = [2, (3, 4)] summed = tree.map_structure_up_to(shallow, lambda *args: sum(args), deep1, deep2) expected = [3, [5]] self.assertEqual(summed, expected) def testNoneNodeIncluded(self): structure = ((1, None)) self.assertEqual(tree.flatten(structure), [1, None]) def testCustomClassMapWithPath(self): class ExampleClass(Mapping[Any, Any]): """Small example custom class.""" def __init__(self, *args, **kwargs): self._mapping = dict(*args, **kwargs) def __getitem__(self, k: Any) -> Any: return self._mapping[k] def __len__(self) -> int: return len(self._mapping) def __iter__(self) -> Iterator[Any]: return iter(self._mapping) def mapper(path, value): full_path = "/".join(path) return f"{full_path}_{value}" test_input = ExampleClass({"first": 1, "nested": {"second": 2, "third": 3}}) output = tree.map_structure_with_path(mapper, test_input) expected = ExampleClass({ "first": "first_1", "nested": { "second": "nested/second_2", "third": "nested/third_3" } }) self.assertEqual(output, expected) if __name__ == "__main__": unittest.main()
tree-master
tree/tree_test.py
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Benchmarks for utilities working with arbitrarily nested structures.""" import collections import timeit import tree TIME_UNITS = [ (1, "s"), (10**-3, "ms"), (10**-6, "us"), (10**-9, "ns"), ] def format_time(time): for d, unit in TIME_UNITS: if time > d: return "{:.2f}{}".format(time / d, unit) def run_benchmark(benchmark_fn, num_iters): times = timeit.repeat(benchmark_fn, repeat=2, number=num_iters) return times[-1] / num_iters # Discard the first half for "warmup". def map_to_list(func, *args): return list(map(func, *args)) def benchmark_map(map_fn, structure): def benchmark_fn(): return map_fn(lambda v: v, structure) return benchmark_fn BENCHMARKS = collections.OrderedDict([ ("tree_map_1", benchmark_map(tree.map_structure, [0])), ("tree_map_8", benchmark_map(tree.map_structure, [0] * 8)), ("tree_map_64", benchmark_map(tree.map_structure, [0] * 64)), ("builtin_map_1", benchmark_map(map_to_list, [0])), ("builtin_map_8", benchmark_map(map_to_list, [0] * 8)), ("builtin_map_64", benchmark_map(map_to_list, [0] * 64)), ]) def main(): for name, benchmark_fn in BENCHMARKS.items(): print(name, format_time(run_benchmark(benchmark_fn, num_iters=1000))) if __name__ == "__main__": main()
tree-master
tree/tree_benchmark.py
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Configuration file for the Sphinx documentation builder.""" # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # pylint: disable=g-bad-import-order # pylint: disable=g-import-not-at-top import datetime import inspect import os import sys sys.path.insert(0, os.path.abspath('../')) import tree # -- Project information ----------------------------------------------------- project = 'Tree' copyright = f'{datetime.date.today().year}, DeepMind' # pylint: disable=redefined-builtin author = 'DeepMind' # -- General configuration --------------------------------------------------- master_doc = 'index' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.linkcode', 'sphinx.ext.napoleon', 'sphinx.ext.doctest' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for autodoc ----------------------------------------------------- autodoc_default_options = { 'member-order': 'bysource', 'special-members': True, 'exclude-members': '__repr__, __str__, __weakref__', } # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' html_theme_options = { # 'collapse_navigation': False, # 'sticky_navigation': False, } # -- Options for doctest ----------------------------------------------------- doctest_global_setup = ''' import collections import numpy as np import tree ''' # -- Source code links ------------------------------------------------------- def linkcode_resolve(domain, info): """Resolve a GitHub URL corresponding to Python object.""" if domain != 'py': return None try: mod = sys.modules[info['module']] except ImportError: return None obj = mod try: for attr in info['fullname'].split('.'): obj = getattr(obj, attr) except AttributeError: return None else: obj = inspect.unwrap(obj) try: filename = inspect.getsourcefile(obj) except TypeError: return None try: source, lineno = inspect.getsourcelines(obj) except OSError: return None # TODO(slebedev): support tags after we release an initial version. return 'https://github.com/deepmind/tree/blob/master/tree/%s#L%d#L%d' % ( os.path.relpath(filename, start=os.path.dirname( tree.__file__)), lineno, lineno + len(source) - 1)
tree-master
docs/conf.py
# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Install script for setuptools.""" import os from setuptools import find_packages from setuptools import setup _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) def _get_version(): with open(os.path.join(_CURRENT_DIR, 'tf2jax', '__init__.py')) as fp: for line in fp: if line.startswith('__version__') and '=' in line: version = line[line.find('=') + 1:].strip(' \'"\n') if version: return version raise ValueError('`__version__` not defined in `tf2jax/__init__.py`') def _parse_requirements(path): with open(os.path.join(_CURRENT_DIR, path)) as f: return [ line.rstrip() for line in f if not (line.isspace() or line.startswith('#')) ] setup( name='tf2jax', version=_get_version(), url='https://github.com/deepmind/tf2jax', license='Apache 2.0', author='DeepMind', description=('TF2JAX: Convert TensorFlow to JAX'), long_description=open(os.path.join(_CURRENT_DIR, 'README.md')).read(), long_description_content_type='text/markdown', author_email='[email protected]', keywords='jax tensorflow conversion translate', packages=find_packages(exclude=['*_test.py']), install_requires=_parse_requirements( os.path.join(_CURRENT_DIR, 'requirements.txt')), tests_require=_parse_requirements( os.path.join(_CURRENT_DIR, 'requirements_tests.txt')), zip_safe=False, # Required for full installation. include_package_data=True, python_requires='>=3.7', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries', ], )
tf2jax-main
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. # ============================================================================== """API of tf2jax.""" from tf2jax._src.config import get_config from tf2jax._src.config import override_config from tf2jax._src.config import update_config from tf2jax._src.tf2jax import AnnotatedFunction from tf2jax._src.tf2jax import convert from tf2jax._src.tf2jax import convert_from_restored from tf2jax._src.tf2jax import convert_functional from tf2jax._src.tf2jax import convert_functional_from_restored from tf2jax._src.tf2jax import MissingInputError __version__ = "0.3.6" # _________________________________________ # / Please don't use symbols in `_src` they \ # \ are not part of the tf2jax public API. / # ----------------------------------------- # \ ^__^ # \ (oo)\_______ # (__)\ )\/\ # ||----w | # || ||
tf2jax-main
tf2jax/__init__.py
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tf2jax.""" from absl.testing import absltest import tf2jax class Tf2jaxTest(absltest.TestCase): """Test tf2jax can be imported correctly.""" def test_import(self): self.assertTrue(hasattr(tf2jax, 'convert')) if __name__ == '__main__': absltest.main()
tf2jax-main
tf2jax/tf2jax_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """MHLO JAX primitive".""" import dataclasses from typing import Tuple import jax from jax import core from jax.interpreters import mlir from jax.interpreters import xla from jax.lib import xla_client as xc import jax.numpy as jnp from jaxlib.mlir import ir safe_zip = jax.util.safe_zip mhlo_apply_p = core.Primitive("mhlo_apply") mhlo_apply_p.multiple_results = True @dataclasses.dataclass(frozen=True) class MhloModule: module: str # string representation of the MLIR module. fun_name: str def __str__(self): return f"MhloModule(fun_name={self.fun_name}, ...)" def mhlo_apply(*args, module: MhloModule): ret = mhlo_apply_p.bind(*args, module=module) # TODO(shaobohou) Unpack singleton result? if len(ret) == 1: return ret[0] else: return tuple(ret) def mhlo_apply_impl(*args, module: MhloModule): return xla.apply_primitive(mhlo_apply_p, *args, module=module) mhlo_apply_p.def_impl(mhlo_apply_impl) # See https://github.com/google/jax/blob/main/jax/_src/interpreters/mlir.py#L115 # for reference def _ir_type_to_dtype(ir_type: ir.Type) -> jnp.dtype: """Converts MLIR type to JAX dtype.""" ir_to_jax = { ir.IntegerType.get_signless(1): jnp.bool_, ir.IntegerType.get_signless(8): jnp.int8, ir.IntegerType.get_signless(16): jnp.int16, ir.IntegerType.get_signless(32): jnp.int32, ir.IntegerType.get_signless(64): jnp.int64, ir.IntegerType.get_unsigned(8): jnp.uint8, ir.IntegerType.get_unsigned(16): jnp.uint16, ir.IntegerType.get_unsigned(32): jnp.uint32, ir.IntegerType.get_unsigned(64): jnp.uint64, ir.F16Type.get(): jnp.float16, ir.F32Type.get(): jnp.float32, ir.F64Type.get(): jnp.float64, ir.BF16Type.get(): jnp.bfloat16, ir.ComplexType.get(ir.F32Type.get()): jnp.complex64, ir.ComplexType.get(ir.F64Type.get()): jnp.complex128, ir.Float8E4M3B11FNUZType.get(): jnp.float8_e4m3b11fnuz, ir.Float8E4M3FNType.get(): jnp.float8_e4m3fn, ir.Float8E5M2Type.get(): jnp.float8_e5m2, } return ir_to_jax[ir_type] _UKNOWN_DIM_PREFIX = "tf2jax_unknown_dim" def mhlo_apply_abstract_eval( *in_avals: core.ShapedArray, module: MhloModule ) -> Tuple[core.ShapedArray, ...]: """Abstract evaluation rule.""" with mlir.make_ir_context(): mhlo_module = ir.Module.parse(module.module) symtab = ir.SymbolTable(mhlo_module.operation) # Check we are not reusing existing dimension vars. dynamic_count = 0 has_polymorphic = False for val in in_avals: for dim in val.shape: if not isinstance(dim, int): has_polymorphic = True if any(x.startswith(_UKNOWN_DIM_PREFIX) for x in dim.get_vars()): for dim in dim.get_vars(): if dim.startswith(_UKNOWN_DIM_PREFIX): dynamic_count = max( dynamic_count, (int(dim.removeprefix(_UKNOWN_DIM_PREFIX + "_"))), ) # Map each `dynamic`` dimension to a unique dimension variable because we # do not have the information from the avals of the original JAX function. # In practice, the output shapes may actually be much more constrained, but # the information is not available here. output_specs = [] for res in symtab["main"].type.results: if any(dim == res.get_dynamic_size() for dim in res.shape): out_shape = ", ".join( f"{_UKNOWN_DIM_PREFIX}_{(dynamic_count := dynamic_count + 1)}" if dim == res.get_dynamic_size() else str(dim) for dim in res.shape ) assert has_polymorphic, has_polymorphic if jax.__version_info__ <= (0, 4, 14): from jax.experimental.jax2tf import shape_poly # pylint: disable=g-import-not-at-top # pytype: disable=import-error else: from jax.experimental.export import shape_poly # pylint: disable=g-import-not-at-top # pytype: disable=import-error out_shape = shape_poly._parse_spec(out_shape, res.shape) # pylint: disable=protected-access else: out_shape = res.shape output_specs.append( core.ShapedArray(out_shape, _ir_type_to_dtype(res.element_type)) ) return tuple(output_specs) mhlo_apply_p.def_abstract_eval(mhlo_apply_abstract_eval) # Taken from # github.com/google/jax/blob/main/jax/experimental/jax2tf/jax_export.py#L859 def refine_polymorphic_shapes( module: ir.Module, validate_static_shapes: bool ) -> ir.Module: """Refine the polymorphic shapes inside a module. Given a module with static input shapes, but using dynamic shapes due to shape polymorphism, run shape refinement to resolve all the dynamic shapes. Args: module: A module with static input shapes but dynamic shapes inside. validate_static_shapes: Whether to check all shapes are static after refinement. Returns: The refined module. """ if xc.mlir_api_version >= 53: refined_module_str = xc._xla.mlir.refine_polymorphic_shapes( # pylint: disable=protected-access mlir.module_to_bytecode(module), enable_shape_assertions=validate_static_shapes, validate_static_shapes=validate_static_shapes, ) elif xc.mlir_api_version >= 50: refined_module_str = xc._xla.mlir.refine_polymorphic_shapes( # pylint: disable=protected-access mlir.module_to_bytecode(module) ) else: raise NotImplementedError("refine_polymorphic_shapes needs jaxlib 0.4.12") context = mlir.make_ir_context() with context: return ir.Module.parse(refined_module_str) def mhlo_apply_lowering( ctx: mlir.LoweringRuleContext, *args, module: MhloModule ): """Lowering rule.""" program_name = f"_tf2jax_mhlo_apply_fn_{module.fun_name}" mhlo_module = ir.Module.parse(module.module) if xc.mlir_api_version < 41: callee_name = mlir.merge_mhlo_modules( dst_module=ctx.module_context.module, sym_name=program_name, src_module=mhlo_module) # type: ignore else: callee_name = mlir.merge_mlir_modules( dst_module=ctx.module_context.module, sym_name=program_name, src_module=mhlo_module) symtab = ir.SymbolTable(ctx.module_context.module.operation) result_types = symtab[program_name].type.results # Paranoid checks. assert len(mlir.flatten_lowering_ir_args(args)) == len(args), ( len(mlir.flatten_lowering_ir_args(args)), len(args), ) call = mlir.func_dialect.CallOp( result_types, ir.FlatSymbolRefAttr.get(callee_name), args, ) return tuple(x for x in call.results) mlir.register_lowering(mhlo_apply_p, mhlo_apply_lowering)
tf2jax-main
tf2jax/experimental/mhlo.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==============================================================================
tf2jax-main
tf2jax/experimental/__init__.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Experimental ops".""" import functools from typing import List, Tuple from absl import logging import jax from jax.interpreters import mlir from jax.lib import xla_client as xc import jax.numpy as jnp from jaxlib.mlir import ir from tf2jax._src import config from tf2jax._src import ops from tf2jax.experimental import mhlo # See canonicalize_platform for reference # https://github.com/google/jax/blob/main/jax/_src/xla_bridge.py#L344 def _platform_to_alias(platform: str) -> str: aliases = { "cuda": "gpu", "rocm": "gpu", } return aliases.get(platform, platform) # Adapted from # https://github.com/google/jax/commit/ec8b855fa16962b1394716622c8cbc006ce76b1c @functools.lru_cache(None) def _refine_with_static_input_shapes( module_text: str, operands: Tuple[jax.core.ShapedArray, ...] ) -> str: """Refine the polymorphic shapes inside a module.""" # Wrap original main within another function with static input shapes. context = mlir.make_ir_context() with context, ir.Location.unknown(context): module = ir.Module.parse(module_text) symbol_table = ir.SymbolTable(module.operation) orig_main = symbol_table["main"] orig_main.attributes["sym_visibility"] = ir.StringAttr.get("private") symbol_table.set_symbol_name(orig_main, "_orig_main") orig_main_name = ir.StringAttr(symbol_table.insert(orig_main)).value # Use static shapes new_main_input_types = [mlir.aval_to_ir_type(x) for x in operands] orig_output_types = orig_main.type.results new_main_ftype = ir.FunctionType.get( new_main_input_types, orig_output_types ) new_main_op = mlir.func_dialect.FuncOp( "main", new_main_ftype, ip=ir.InsertionPoint.at_block_begin(module.body), ) try: new_main_op.attributes["arg_attrs"] = ir.ArrayAttr(orig_main.arg_attrs) assert new_main_op.arg_attrs == orig_main.arg_attrs except KeyError: pass try: new_main_op.attributes["res_attrs"] = ir.ArrayAttr(orig_main.result_attrs) assert new_main_op.result_attrs == orig_main.result_attrs except KeyError: pass new_main_op.attributes["sym_visibility"] = ir.StringAttr.get("public") symbol_table.insert(new_main_op) entry_block = new_main_op.add_entry_block() with ir.InsertionPoint(entry_block): orig_main_args: List[ir.Value] = [] for new_arg, orig_arg_type in jax.util.safe_zip( new_main_op.arguments, orig_main.type.inputs ): # TODO(shaobohou) Why is the ConvertOp needed? if orig_arg_type != new_arg: orig_main_args.append( mlir.hlo.ConvertOp(orig_arg_type, new_arg).result ) call = mlir.func_dialect.CallOp( orig_output_types, ir.FlatSymbolRefAttr.get(orig_main_name), orig_main_args, ) mlir.func_dialect.ReturnOp(call.results) symbol_table.set_symbol_name(new_main_op, "main") # Refinement passes. input_dims = jax.tree_util.tree_flatten([x.shape for x in operands])[0] module = mhlo.refine_polymorphic_shapes( module, validate_static_shapes=all([isinstance(x, int) for x in input_dims]), ) return mlir.module_to_string(module) @ops.register_operation("XlaCallModule") def _xla_call_module(proto): """Parse a XlaCallModule op.""" ops._check_attrs( # pylint: disable=protected-access proto, { "Tin", "Sout", "Tout", "dim_args_spec", "function_list", "module", "version", "platforms", "has_token_input_output", "disabled_checks", }, ) version = proto.attr["version"].i if version < 2: raise ValueError( f"Only version 2 (StableHLO) or above is supported, found {version}.") dim_args_spec = tuple(proto.attr["dim_args_spec"].list.s) if dim_args_spec: raise ValueError("Dynamic shapes is not yet supported, found " f"dim_args_spec={dim_args_spec}.") function_list = tuple(proto.attr["function_list"].list.func) if function_list: raise ValueError( "function_list is not yet supported for custom calls, found " f"{function_list=}" ) has_token_input_output = proto.attr["has_token_input_output"].b if has_token_input_output: raise ValueError( "has_token_input_output is not yet supported for custom calls, found " f"{has_token_input_output=}" ) disabled_checks = tuple(proto.attr["disabled_checks"].list.s) if disabled_checks: logging.warning( "XlaCallModule was serialized with the following disabled checks: %s", disabled_checks, ) target_platforms = tuple( _platform_to_alias(v.decode("utf-8").lower()) for v in proto.attr["platforms"].list.s ) def check_platforms(): jax_backend = ( jax.config.jax_default_device.platform.lower() if jax.config.jax_default_device else jax.default_backend().lower() ) if target_platforms and jax_backend not in target_platforms: platform_message = ( f"Unsupported backend: `{jax_backend}` not in `{target_platforms}`." ) if config.get_config("xlacallmodule_strict_checks"): error_message = ( platform_message + "\n" + "This error can be disabled using either" " tf2jax.update_config('xlacallmodule_strict_checks', False) or" " the context manager" " tf2jax.override_config('xlacallmodule_strict_checks', False)." " You may observe poorer performance or outright failure as a" " result." ) raise ValueError(error_message) else: warn_message = ( platform_message + "\n" + "Proceeding anyway as" " config.get_config('xlacallmodule_strict_checks') is False. You" " may observe poorer performance or outright failure." ) logging.warning(warn_message) if version >= 4: mhlo_text = xc._xla.mlir.deserialize_portable_artifact( # pylint: disable=protected-access proto.attr["module"].s ) else: with mlir.make_ir_context(): module = ir.Module.parse(proto.attr["module"].s) mhlo_text = mlir.module_to_string(module) def _func(*operands: jnp.ndarray) -> Tuple[jnp.ndarray, ...]: check_platforms() refined_mhlo_text = _refine_with_static_input_shapes( mhlo_text, tuple(jax.core.ShapedArray(x.shape, x.dtype) for x in operands), ) mhlo_module = mhlo.MhloModule(module=refined_mhlo_text, fun_name=proto.name) return mhlo.mhlo_apply(*operands, module=mhlo_module) return _func
tf2jax-main
tf2jax/experimental/ops.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """MHLO primitive tests.""" import functools from absl import logging from absl.testing import absltest from absl.testing import parameterized import chex import jax import numpy as np from tf2jax.experimental import mhlo def _convert_to_mhlo(jax_fn, inputs, *, dialect): lowered_forward = jax_fn.lower(*inputs) mhlo_text = lowered_forward.as_text(dialect=dialect) return mhlo_text def _check_transforms(fn, inputs, *, dialect): jaxpr = jax.make_jaxpr(fn)(*inputs) logging.info(jaxpr) mhlo_text = jax.jit(fn).lower(*inputs).as_text(dialect=dialect) logging.info(mhlo_text) class MhloTest(chex.TestCase): def _assert_all_close(self, expect_fn, actual_fn, inputs): expect_outputs = self.variant(expect_fn)(*inputs) actual_outputs = self.variant(actual_fn)(*inputs) logging.info(expect_outputs) logging.info(actual_outputs) chex.assert_trees_all_close(expect_outputs, actual_outputs) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( ("mhlo", "mhlo"), ("stablehlo", "stablehlo"), ) def test_one_input_and_one_output(self, dialect): @jax.jit def fn(x): return x * 2 + 3.14 inputs = (np.ones((3, 2), dtype=np.float32) * 10,) mhlo_text = _convert_to_mhlo( fn, jax.tree_map(np.zeros_like, inputs), dialect=dialect) mhlo_module = mhlo.MhloModule(module=mhlo_text, fun_name="test_module") chex.assert_trees_all_close( mhlo.mhlo_apply(*inputs, module=mhlo_module), fn(*inputs)) def make_top_fn(sub_fn): def top_fn(x): return sub_fn(x + 8) * 10 return top_fn expect_top_fn = make_top_fn(fn) actual_top_fn = make_top_fn( functools.partial(mhlo.mhlo_apply, module=mhlo_module)) self._assert_all_close(expect_top_fn, actual_top_fn, inputs) _check_transforms(actual_top_fn, inputs, dialect=dialect) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( ("mhlo", "mhlo"), ("stablehlo", "stablehlo"), ) def test_two_inputs_and_one_output(self, dialect): @jax.jit def fn(x, y): return x * 2 + y inputs = ( np.ones((3, 2), dtype=np.float32) * 10, np.ones((3, 2), dtype=np.float32) * 20, ) mhlo_text = _convert_to_mhlo( fn, jax.tree_map(np.zeros_like, inputs), dialect=dialect) mhlo_module = mhlo.MhloModule(module=mhlo_text, fun_name="test_module") chex.assert_trees_all_close( mhlo.mhlo_apply(*inputs, module=mhlo_module), fn(*inputs)) def make_top_fn(sub_fn): def top_fn(x, y): return sub_fn(x + 8, y + 9) * 10 return top_fn expect_top_fn = make_top_fn(fn) actual_top_fn = make_top_fn( functools.partial(mhlo.mhlo_apply, module=mhlo_module)) self._assert_all_close(expect_top_fn, actual_top_fn, inputs) _check_transforms(actual_top_fn, inputs, dialect=dialect) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( ("mhlo", "mhlo"), ("stablehlo", "stablehlo"), ) def test_two_inputs_and_two_outputs(self, dialect): @jax.jit def fn(x, y): return x * 2 + y, x + y * 3 inputs = ( np.ones((3, 2), dtype=np.float32) * 10, np.ones((3, 2), dtype=np.float32) * 20, ) mhlo_text = _convert_to_mhlo( fn, jax.tree_map(np.zeros_like, inputs), dialect=dialect) mhlo_module = mhlo.MhloModule(module=mhlo_text, fun_name="test_module") chex.assert_trees_all_close( mhlo.mhlo_apply(*inputs, module=mhlo_module), fn(*inputs)) def make_top_fn(sub_fn): def top_fn(x, y): res0, res1 = sub_fn(x + 8, y + 9) return res0 * 10, res1 * 3.14 return top_fn expect_top_fn = make_top_fn(fn) actual_top_fn = make_top_fn( functools.partial(mhlo.mhlo_apply, module=mhlo_module)) self._assert_all_close(expect_top_fn, actual_top_fn, inputs) _check_transforms(actual_top_fn, inputs, dialect=dialect) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( ("mhlo", "mhlo"), ("stablehlo", "stablehlo"), ) def test_boolean(self, dialect): @jax.jit def fn(x): return x > 0 inputs = ( np.ones((4,), dtype=np.int32) * 10, ) mhlo_text = _convert_to_mhlo( fn, jax.tree_map(np.zeros_like, inputs), dialect=dialect) mhlo_module = mhlo.MhloModule(module=mhlo_text, fun_name="test_module") chex.assert_trees_all_close( mhlo.mhlo_apply(*inputs, module=mhlo_module), fn(*inputs)) def make_top_fn(sub_fn): def top_fn(x): return sub_fn(x) * x return top_fn expect_top_fn = make_top_fn(fn) actual_top_fn = make_top_fn( functools.partial(mhlo.mhlo_apply, module=mhlo_module)) self._assert_all_close(expect_top_fn, actual_top_fn, inputs) if __name__ == "__main__": absltest.main()
tf2jax-main
tf2jax/experimental/mhlo_test.py
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tf2jax.""" from absl.testing import absltest from absl.testing import parameterized import jax from jax.experimental import jax2tf import jax.numpy as jnp import numpy as np import tensorflow as tf from tf2jax._src import numpy_compat _dtypes = [ tf.bool, tf.uint8, tf.uint16, tf.uint32, tf.uint64, tf.int8, tf.int16, tf.int32, tf.int64, tf.bfloat16, tf.float16, tf.float32, tf.float64, tf.complex64, tf.complex128 ] class NumpyCompatTest(parameterized.TestCase): @parameterized.named_parameters( ("np", np, numpy_compat.tf_to_np_dtypes), ("jnp", jnp, numpy_compat.tf_to_jnp_dtypes), ) def test_dtype_conversion(self, np_module, dtype_map): self.assertEqual(len(_dtypes), len(dtype_map)) for src in _dtypes: dst = "bool_" if src.name == "bool" else src.name if src.name == "bfloat16": self.assertIs(dtype_map[src], jnp.bfloat16) else: self.assertIs(dtype_map[src], getattr(np_module, dst)) def test_is_poly_dim(self): @jax.jit def jax_func(x): self.assertTrue(numpy_compat.is_poly_dim(x.shape[0])) self.assertEqual(x.shape[1], 4) return x + 3.14 tf_func = jax2tf.convert(jax_func, polymorphic_shapes=["(b, _)"]) tf_forward = tf.function(tf_func, autograph=False) tf_forward.get_concrete_function(tf.TensorSpec(shape=(None, 4))) if __name__ == "__main__": absltest.main()
tf2jax-main
tf2jax/_src/numpy_compat_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tf2jax.""" import itertools from typing import Tuple from absl.testing import parameterized import chex import jax import numpy as np import tensorflow as tf from tf2jax._src import test_util from tf2jax._src import tf2jax import tree def _parse_version(version: str) -> Tuple[int, ...]: return tuple([int(v) for v in version.split(".")]) class OpsTest(test_util.TestCase): def _test_convert(self, tf_func, inputs, *, check_shape_only=False, functional=True): if not isinstance(inputs, (list, tuple)): inputs = (inputs,) jax_func, jax_params = tf2jax.convert( tf_func, *tree.map_structure(np.zeros_like, inputs)) if functional: self.assertEmpty(jax_params, "Expected no parameters for pure Ops.") jax_func = self.variant(jax_func) rng = jax.random.PRNGKey(42) jax_results, new_jax_params = jax_func(jax_params, *inputs, rng=rng) tf_results = tf_func(*inputs) # Check outputs for tf_res, jax_res in jax.util.safe_zip( tree.flatten(tf_results), tree.flatten(jax_results) ): self.assertEqual(tf_res.shape, jax_res.shape) if not check_shape_only: self.assertAllClose(np.asarray(tf_res), jax_res, atol=1e-5) return jax_results, new_jax_params @chex.variants(with_jit=True, without_jit=True) def test_cholesky(self): np.random.seed(42) inputs = np.stack([ np.cov(np.random.normal(size=[5, 10]).astype(np.float32)) for _ in range(3) ]) @tf.function(jit_compile=True) def cholesky(x): return tf.raw_ops.Cholesky(input=x) self._test_convert(cholesky, [inputs]) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("compute_v", True), ("not_compute_v", False)), ( ("unbatched", (5, 5)), ("batched", (3, 5, 5)), ("more_batched", (2, 3, 5, 5)), ), named=True, )) def test_eig(self, compute_v, shape): if jax.default_backend().lower() != "cpu": self.skipTest("JAX only supports nonsymmetric eigendecomposition on CPU.") np.random.seed(42) inputs = np.random.normal(size=shape).astype(np.float32) # No XLA Eig kernel for CPU. is_cpu = jax.default_backend() == "cpu" @tf.function(jit_compile=not is_cpu) def eig(x): return tf.raw_ops.Eig(input=x, compute_v=compute_v, Tout=tf.complex64) tf_w, tf_v = eig(tf.constant(inputs)) jax_eig = tf2jax.convert_functional(eig, np.zeros_like(inputs)) jax_w, jax_v = self.variant(jax_eig)(inputs) # Check eigenvalues are sorted in non-descending order. # This used to be true but never guarranteed for general non-symmetric # matrices (b/239787164). # self.assertTrue( # np.all((np.absolute(tf_w)[..., :-1] - # np.absolute(tf_w)[..., 1:]) < 1e-5)) # self.assertTrue( # np.all((np.absolute(jax_w)[..., :-1] - # np.absolute(jax_w)[..., 1:]) < 1e-5)) # Check eigenvalues so because ordering is not consistent even after sorting for idx in itertools.product(*map(range, shape[:-2])): w_jax, w_tf = jax_w[idx], tf_w[idx] for i in range(shape[-1]): self.assertAllClose(min(abs(w_jax - w_tf[i])), 0., atol=1e-5) self.assertAllClose(min(abs(w_jax[i] - w_tf)), 0., atol=1e-5) if compute_v: self.assertAllClose(np.matmul(inputs, tf_v), tf_w[..., None, :] * tf_v) self.assertAllClose(np.matmul(inputs, jax_v), jax_w[..., None, :] * jax_v) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("compute_v", True), ("not_compute_v", False)), ( ("unbatched", (5, 5)), ("batched", (3, 5, 5)), ("more_batched", (2, 3, 5, 5)), ), named=True, )) def test_eigh(self, compute_v, shape): np.random.seed(42) inputs = np.random.normal(size=shape).astype(np.float32) @tf.function(jit_compile=True) def eigh(x): return tf.raw_ops.SelfAdjointEigV2(input=x, compute_v=compute_v) tf_w, tf_v = eigh(tf.constant(inputs)) jax_eigh = tf2jax.convert_functional(eigh, np.zeros_like(inputs)) jax_w, jax_v = self.variant(jax_eigh)(inputs) self.assertTrue(np.all(tf_w[..., :-1] <= tf_w[..., 1:])) self.assertTrue(np.all(jax_w[..., :-1] <= jax_w[..., 1:])) # Check eigenvalues so because ordering is not consistent even after sorting for idx in itertools.product(*map(range, shape[:-2])): w_jax, w_tf = jax_w[idx], tf_w[idx] for i in range(shape[-1]): self.assertAllClose(min(abs(w_jax - w_tf[i])), 0., atol=1e-5) self.assertAllClose(min(abs(w_jax[i] - w_tf)), 0., atol=1e-5) if compute_v: tols = dict(atol=2e-5) if jax.default_backend() in "tpu" else {} sym_inputs = np.tril(inputs) + np.swapaxes(np.tril(inputs, -1), -2, -1) self.assertAllClose( np.matmul(sym_inputs, tf_v), tf_w[..., None, :] * tf_v, **tols) self.assertAllClose( np.matmul(sym_inputs, jax_v), jax_w[..., None, :] * jax_v, **tols) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( ( ("full_matrices", True), ("not_full_matrices", False), ), ( ("unbatched", (5, 5)), ("batched", (3, 4, 5)), ("more_batched", (2, 3, 5, 4)), ), named=True, )) def test_qr(self, full_matrices, shape): np.random.seed(42) inputs = np.random.normal(size=shape).astype(np.float32) @tf.function(jit_compile=True) def qr(x): return tf.raw_ops.Qr(input=x, full_matrices=full_matrices) tf_q, tf_r = qr(tf.constant(inputs)) jax_qr = tf2jax.convert_functional(qr, np.zeros_like(inputs)) jax_q, jax_r = self.variant(jax_qr)(inputs) self.assertEqual(tf_q.shape, jax_q.shape) self.assertEqual(tf_r.shape, jax_r.shape) self.assertAllClose(jax_q, tf_q) self.assertAllClose(jax_r, tf_r) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("compute_uv", True), ("not_compute_uv", False)), ( ("full_matrices", True), ("not_full_matrices", False), ), ( ("unbatched", (3, 3)), ("batched", (3, 4, 5)), ("more_batched", (2, 3, 5, 4)), ), named=True, )) def test_svd(self, compute_uv, full_matrices, shape): np.random.seed(42) inputs = np.random.normal(size=shape).astype(np.float32) @tf.function(jit_compile=True) def svd(x): return tf.raw_ops.Svd( input=x, compute_uv=compute_uv, full_matrices=full_matrices) tf_s, tf_u, tf_v = svd(tf.constant(inputs)) jax_svd = tf2jax.convert_functional(svd, np.zeros_like(inputs)) jax_s, jax_u, jax_v = self.variant(jax_svd)(inputs) self.assertEqual(tf_s.shape, jax_s.shape) if compute_uv: self.assertEqual(tf_u.shape, jax_u.shape) self.assertEqual(tf_v.shape, jax_v.shape) # https://numpy.org/doc/stable/reference/generated/numpy.linalg.svd.html) def reconstruct(u, s, v): with tf.device("CPU"): return tf.matmul( u[..., :s.shape[-1]] * s[..., None, :], v[..., :s.shape[-1]], adjoint_b=True) # Adapted from tensorflow/python/kernel_tests/linalg/svd_op_test.py def compare_singular_vectors(x, y): # Singular vectors are only unique up to sign (complex phase factor for # complex matrices), so we normalize the sign first. sum_of_ratios = np.sum(np.divide(y, x), -2, keepdims=True) phases = np.divide(sum_of_ratios, np.abs(sum_of_ratios)) x = x * phases self.assertAllClose(x, y, atol=1e-4) tols = dict(atol=1e-5) if jax.default_backend() in ("gpu", "tpu") else {} self.assertAllClose(jax_s, tf_s, **tols) if compute_uv: tf_recon = reconstruct(tf_u, tf_s, tf_v) jax_recon = reconstruct(jax_u, jax_s, jax_v) self.assertAllClose(tf_recon, jax_recon, atol=1e-5) self.assertAllClose(inputs, tf_recon, atol=1e-5) self.assertAllClose(inputs, jax_recon, atol=1e-5) rank = min(inputs.shape[-2:]) compare_singular_vectors(tf_u[..., :rank], jax_u[..., :rank]) compare_singular_vectors(tf_v[..., :rank], jax_v[..., :rank]) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( ( ("lower", True), ("upper", False), ), ( ("adjoint", True), ("not_adjoint", False), ), ( ("unbatched", ((5, 5), (5, 5))), ("batched", ((3, 5, 5), (3, 5, 4))), ("more_batched", ((2, 3, 5, 5), (2, 3, 5, 6))), ), named=True, )) def test_triangular_solve(self, lower, adjoint, shapes): lhs_shape, rhs_shape = shapes np.random.seed(42) inputs = np.random.normal(size=lhs_shape).astype(np.float32) rhs_inputs = np.random.normal(size=rhs_shape).astype(np.float32) @tf.function(jit_compile=True) def triangular_solve(x, rhs): return tf.raw_ops.MatrixTriangularSolve( matrix=x, rhs=rhs, lower=lower, adjoint=adjoint) tf_res = triangular_solve(tf.constant(inputs), tf.constant(rhs_inputs)) jax_triangular_solve = tf2jax.convert_functional( triangular_solve, np.zeros_like(inputs), np.zeros_like(rhs_inputs)) jax_res = self.variant(jax_triangular_solve)(inputs, rhs_inputs) self.assertEqual(tf_res.shape, jax_res.shape) self.assertAllClose(jax_res, tf_res, atol=1e-5) if __name__ == "__main__": tf.test.main()
tf2jax-main
tf2jax/_src/linalg_ops_test.py
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """TF2JAX configurations.""" import contextlib from typing import Any, Union _config = dict( strict_shape_check=True, strict_dtype_check=False, force_const_float32_to_bfloat16=False, force_const_float64_to_bfloat16=False, convert_custom_gradient=True, infer_relu_from_jax2tf=True, infer_cumulative_reduction_from_jax2tf=True, raise_on_prevent_gradient=True, # TensorFlow uses high/highest precision on TPU. resize_bilinear_precision="highest", # This is temporary until checkify supports debug mode. enable_checkify_for_asserts=False, # Enable checks that each natively serialized computation is executed on a # platform for which it was lowered. xlacallmodule_strict_checks=True, ) def get_config(name: str) -> Union[bool, str]: return _config[name] def update_config(name: str, value: Any): if name in _config: _config[name] = value else: raise ValueError( f"Parameter named {name} not found in config={_config}") @contextlib.contextmanager def override_config(name: str, value: Any): old_value = get_config(name) update_config(name, value) try: yield finally: update_config(name, old_value)
tf2jax-main
tf2jax/_src/config.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. # ============================================================================== """Utililties for wrapping around numpy and jax.numpy.""" import itertools import operator from typing import Sequence, Union import jax from jax.lib import xla_client as xc import jax.numpy as jnp import numpy as np import tensorflow as tf tf_to_np_dtypes = { tf.bool: np.bool_, tf.uint8: np.uint8, tf.uint16: np.uint16, tf.uint32: np.uint32, tf.uint64: np.uint64, tf.int8: np.int8, tf.int16: np.int16, tf.int32: np.int32, tf.int64: np.int64, tf.bfloat16: jnp.bfloat16, tf.float16: np.float16, tf.float32: np.float32, tf.float64: np.float64, tf.complex64: np.complex64, tf.complex128: np.complex128, } tf_to_jnp_dtypes = { tf.bool: jnp.bool_, tf.uint8: jnp.uint8, tf.uint16: jnp.uint16, tf.uint32: jnp.uint32, tf.uint64: jnp.uint64, tf.int8: jnp.int8, tf.int16: jnp.int16, tf.int32: jnp.int32, tf.int64: jnp.int64, tf.bfloat16: jnp.bfloat16, tf.float16: jnp.float16, tf.float32: jnp.float32, tf.float64: jnp.float64, tf.complex64: jnp.complex64, tf.complex128: jnp.complex128, } _NP_LIKES = (np.ndarray, np.number, np.bool_, bool, int, float, complex) # We avoid importing jax2tf.shape_poly.is_poly_dim as jax2tf often depends # on the most recent tensorflow version. # This should reflect is_poly_dim() at # https://github.com/google/jax/blob/main/jax/experimental/jax2tf/shape_poly.py#L676 def is_poly_dim(x) -> bool: # Array types. if isinstance(x, (np.ndarray, jax.core.Tracer, xc.ArrayImpl)): return False try: # Integer types. operator.index(x) except TypeError: return True else: return False def _get_np(*args): """Select numpy backend based on input types.""" no_jax = all((isinstance(x, _NP_LIKES) or is_poly_dim(x)) for x in args) return np if no_jax else jnp def _get_dtypes(*args): """Select dtypes backend based on input types.""" no_jax = _get_np(*args) is np return tf_to_np_dtypes if no_jax else tf_to_jnp_dtypes def get_jax_dtype(dtype: tf.DType): return tf_to_jnp_dtypes[dtype] # Simple numeric ops. add = lambda x, y: _get_np(x, y).add(x, y) equal = lambda x, y: _get_np(x, y).equal(x, y) floor_divide = lambda x, y: _get_np(x, y).floor_divide(x, y) greater = lambda x, y: _get_np(x, y).greater(x, y) greater_equal = lambda x, y: _get_np(x, y).greater_equal(x, y) less = lambda x, y: _get_np(x, y).less(x, y) less_equal = lambda x, y: _get_np(x, y).less_equal(x, y) maximum = lambda x, y: _get_np(x, y).maximum(x, y) minimum = lambda x, y: _get_np(x, y).minimum(x, y) mod = lambda x, y: _get_np(x, y).mod(x, y) multiply = lambda x, y: _get_np(x, y).multiply(x, y) power = lambda x, y: _get_np(x, y).power(x, y) negative = lambda x: _get_np(x).negative(x) not_equal = lambda x, y: _get_np(x, y).not_equal(x, y) reciprocal = lambda x: _get_np(x).reciprocal(x) subtract = lambda x, y: _get_np(x, y).subtract(x, y) true_divide = lambda x, y: _get_np(x, y).true_divide(x, y) def divide(x, y): np_ = _get_np(x, y) dtype = np_.result_type(x.dtype, y.dtype) # This is necessary because for integers, divide behaves like true_divide. return np_.asarray(np_.divide(x, y), dtype) def arange(start, stop, step, dtype: tf.DType): dtype = _get_dtypes(start, stop, step)[dtype] return _get_np(start, stop, step).arange(start, stop, step, dtype=dtype) def asarray(arr, dtype: tf.DType): if is_poly_dim(arr): arr = jax.core.dimension_as_value(arr) dtype = _get_dtypes(arr)[dtype] return _get_np(arr).asarray(arr, dtype) def empty(shape, dtype: tf.DType, init: bool): del init dtype = _get_dtypes(shape)[dtype] return _get_np(shape).full(shape, dtype(), dtype=dtype) def full(shape, fill_value, dtype: tf.DType): dtype = _get_dtypes(shape)[dtype] return _get_np(shape, fill_value).full(shape, fill_value, dtype=dtype) def gather(params, indices, axis: int, batch_dims: int): """Implement gather in numpy and jax.numpy.""" if _get_np(params, indices) is np: axis = axis if axis >= 0 else params.ndim + axis batch_shape = params.shape[:batch_dims] take_shape = ( params.shape[:axis] + indices.shape[batch_dims:] + params.shape[axis + 1:]) if batch_shape: res = np.zeros(take_shape, dtype=params.dtype) for idx in itertools.product(*[range(v) for v in batch_shape]): res[idx] = np.take(params[idx], indices[idx], axis=axis - batch_dims) else: res = np.take(params, indices, axis=axis) return res else: axis = axis if axis < 0 else -(params.ndim - axis) take_fn = lambda p, i: jnp.take(p, i, axis=axis) for _ in range(batch_dims): take_fn = jax.vmap(take_fn) return take_fn(params, indices) def scatter_nd(indices, updates, shape): np_ = _get_np(indices, updates) res = np_.zeros(shape, updates.dtype) key = tuple(np_.moveaxis(indices, -1, 0)) if np_ is np: res[key] = updates else: res = res.at[key].set(updates) return res # Reduction ops. def all_(arr, axis: Union[int, Sequence[int]], keepdims: bool): axis = tuple(axis) if isinstance(axis, (list, tuple)) else (axis,) return _get_np(arr).all(arr, axis=axis, keepdims=keepdims) def any_(arr, axis: Union[int, Sequence[int]], keepdims: bool): axis = tuple(axis) if isinstance(axis, (list, tuple)) else (axis,) return _get_np(arr).any(arr, axis=axis, keepdims=keepdims) def cumsum(arr, axis: int): return _get_np(arr).cumsum(arr, axis=axis) def cumprod(arr, axis: int): return _get_np(arr).cumprod(arr, axis=axis) def max_(arr, axis: Union[int, Sequence[int]], keepdims: bool): axis = tuple(axis) if isinstance(axis, (list, tuple)) else (axis,) return _get_np(arr).max(arr, axis=axis, keepdims=keepdims) def min_(arr, axis: Union[int, Sequence[int]], keepdims: bool): axis = tuple(axis) if isinstance(axis, (list, tuple)) else (axis,) return _get_np(arr).min(arr, axis=axis, keepdims=keepdims) def prod(arr, axis: Union[int, Sequence[int]], keepdims: bool): axis = tuple(axis) if isinstance(axis, (list, tuple)) else (axis,) return _get_np(arr).prod(arr, axis=axis, keepdims=keepdims) def sum_(arr, axis: Union[int, Sequence[int]], keepdims: bool): axis = tuple(axis) if isinstance(axis, (list, tuple)) else (axis,) return _get_np(arr).sum(arr, axis=axis, keepdims=keepdims) # Array manipulation ops. def broadcast_to(arr, shape): np_ = jnp if any([is_poly_dim(x) for x in shape]) else _get_np(arr) return np_.broadcast_to(arr, shape) concatenate = lambda arrs, axis: _get_np(*arrs).concatenate(arrs, axis=axis) expand_dims = lambda arr, axis: _get_np(arr).expand_dims(arr, axis=axis) flip = lambda arr, axis: _get_np(arr).flip(arr, axis=axis) roll = lambda arr, shift, axis: _get_np(arr).roll(arr, shift=shift, axis=axis) split = lambda arr, sections, axis: _get_np(arr).split(arr, sections, axis=axis) stack = lambda arrs, axis: _get_np(*arrs).stack(arrs, axis=axis) tile = lambda arr, reps: _get_np(arr, reps).tile(arr, reps=reps) where = lambda cond, x, y: _get_np(cond, x, y).where(cond, x, y) def squeeze(arr, axis): # tf.squeeze and np/jnp.squeeze have different behaviors when axis=(). # - tf.squeeze will squeeze all dimensions. # - np/jnp.squeeze will not squeeze any dimensions. # Here we change () to None to ensure that squeeze has the same behavior # when converted from tf to np/jnp. if axis == tuple(): axis = None return _get_np(arr).squeeze(arr, axis=axis) def moveaxis( arr, source: Union[int, Sequence[int]], destination: Union[int, Sequence[int]], ): return _get_np(arr).moveaxis(arr, source=source, destination=destination) def invert_permutation(arr): if arr.ndim != 1: raise ValueError(f"Expected 1D array, found x.dims={arr.ndim}") if _get_np(arr) is np: inds = np.zeros_like(arr) inds[arr.tolist()] = np.arange(0, arr.shape[0]) return inds else: return jnp.zeros_like(arr).at[arr].set(jnp.arange(0, arr.shape[0]))
tf2jax-main
tf2jax/_src/numpy_compat.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==============================================================================
tf2jax-main
tf2jax/_src/__init__.py
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for JAX -> TF -> JAX.""" import os from absl import flags from absl.testing import absltest from absl.testing import parameterized import chex import haiku as hk import jax from jax.experimental import jax2tf import jax.numpy as jnp import numpy as np import tensorflow as tf from tf2jax._src import config from tf2jax._src import test_util from tf2jax._src import tf2jax import tree from tensorflow.compiler.xla import xla_data_pb2 # pytype: disable=import-error # Parse absl flags test_srcdir and test_tmpdir. jax.config.parse_flags_with_absl() def _bool_env(varname: str, value: bool) -> bool: val = os.getenv(varname, str(value)) return {"1": True, "0": False, "True": True, "False": False}[val] _NATIVE_SERIALIZATION = flags.DEFINE_bool( "use_jax2tf_native_serialization_in_roundtrip_test", _bool_env("USE_JAX2TF_NATIVE_SERIALIZATION_IN_ROUNDTRIP_TEST", False), "Whether to call jax2tf.convert with native serialization enabled.", ) def _compute_gradients(func, *inputs): def fn(*args): return jax.tree_util.tree_leaves(func(*args))[0] return jax.grad(lambda *args: jnp.sum(fn(*args)))(*inputs) def _jax2tf_convert(func, **kwargs): return jax2tf.convert( func, native_serialization=_NATIVE_SERIALIZATION.value, **kwargs ) def uses_native_serialization(): return _NATIVE_SERIALIZATION.value class Jax2TfTest(test_util.TestCase): def _test_convert( self, jax_func, inputs, *, with_grad, enable_xla, with_custom_grad=False, grad_tols=None, ): if uses_native_serialization(): if not enable_xla: self.skipTest("native_serialization does not support enable_xla=False.") if with_grad and not with_custom_grad: self.skipTest( "native_serialization does not support differentiation without " "custom gradient.") grad_tols = grad_tols or {} def assert_grad_all_close(*args): return self.assertAllClose(*args, **grad_tols) # Jax jax_func = self.variant(jax_func) jax_outputs = jax_func(*inputs) if with_grad: jax_grads = _compute_gradients(jax_func, *inputs) # Jax -> TF tf_func = _jax2tf_convert( jax_func, with_gradient=with_grad, enable_xla=enable_xla ) tf_func = tf.function(tf_func, jit_compile=True, autograph=False) tf_outputs = tf_func(*inputs) jax.tree_map(self.assertAllClose, jax_outputs, tf_outputs) # Jax -> TF -> Jax with config.override_config("convert_custom_gradient", with_custom_grad): rejax_func = tf2jax.convert_functional( tf_func, *tree.map_structure(np.zeros_like, inputs)) rejax_func = self.variant(rejax_func) rejax_outputs = rejax_func(*inputs) jax.tree_map(self.assertAllClose, rejax_outputs, tf_outputs) if with_grad: rejax_grads = _compute_gradients(rejax_func, *inputs) jax.tree_map(assert_grad_all_close, jax_grads, rejax_grads) # Jax -> TF -> SavedModel -> TF model = tf.Module() model.f = tf_func tmp_dir = self.create_tempdir() tf.saved_model.save(model, tmp_dir.full_path) del model restored = tf.saved_model.load(tmp_dir.full_path) restored_tf_outputs = restored.f(*inputs) jax.tree_map(self.assertAllClose, jax_outputs, restored_tf_outputs) # Jax -> TF -> SavedModel -> TF -> Jax with config.override_config("convert_custom_gradient", with_custom_grad): rejax_too_func = tf2jax.convert_functional( restored.f, *tree.map_structure(np.zeros_like, inputs)) rejax_too_func = self.variant(rejax_too_func) rejax_too_outputs = rejax_too_func(*inputs) jax.tree_map(self.assertAllClose, rejax_too_outputs, tf_outputs) if with_grad: rejax_too_grads = _compute_gradients(rejax_too_func, *inputs) jax.tree_map(assert_grad_all_close, jax_grads, rejax_too_grads) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), (("without_custom_gradient", False), ("with_custom_gradient", True)), named=True, )) def test_simple(self, with_grad, enable_xla, with_custom_grad): np.random.seed(42) def forward(x): return jnp.sin(jnp.cos(x)) inputs = np.random.normal((3, 2)).astype(np.float32) self._test_convert( forward, [inputs], with_grad=with_grad, enable_xla=enable_xla, with_custom_grad=with_custom_grad) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), (("without_custom_gradient", False), ("with_custom_gradient", True)), named=True, )) def test_mlp(self, with_grad, enable_xla, with_custom_grad): np.random.seed(42) def forward(x): mlp = hk.nets.MLP([300, 100, 10]) return mlp(x) inputs = np.random.normal(size=(8, 28 * 28)) forward = hk.transform(forward) variables = forward.init(jax.random.PRNGKey(42), jnp.zeros_like(inputs)) variables = hk.data_structures.to_mutable_dict(variables) jax_fn = hk.without_apply_rng(forward).apply self._test_convert( jax_fn, [variables, inputs], with_grad=with_grad, enable_xla=enable_xla, with_custom_grad=with_custom_grad) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), (("without_custom_gradient", False), ("with_custom_gradient", True)), named=True, )) def test_batch_norm(self, with_grad, enable_xla, with_custom_grad): np.random.seed(42) def forward(x): batch_norm = hk.BatchNorm(True, True, 0.9, eps=0.1) return batch_norm(x, is_training=True) inputs = np.random.normal(size=(8, 17)) forward = hk.transform_with_state(forward) variables, states = forward.init( jax.random.PRNGKey(42), jnp.zeros_like(inputs)) variables = hk.data_structures.to_mutable_dict(variables) states = hk.data_structures.to_mutable_dict(states) def jax_fn(params, states, x): outputs, states = hk.without_apply_rng(forward).apply(params, states, x) return outputs, hk.data_structures.to_mutable_dict(states) # Perturb variables and states. variables = tree.map_structure( lambda x: x + np.random.uniform(size=x.shape), variables) states = tree.map_structure( lambda x: x + np.random.normal(size=x.shape), states) self._test_convert( jax_fn, [variables, states, inputs], with_grad=with_grad, enable_xla=enable_xla, with_custom_grad=with_custom_grad) # Conv2D uses jax.lax.conv_general_dilated which is translated to XlaConv. @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), named=True, )) def test_conv2d(self, with_grad, enable_xla): np.random.seed(42) tols = dict(rtol=1e-5) if jax.default_backend().lower() == "gpu" else {} def forward(x): conv = hk.Conv2D( output_channels=7, kernel_shape=3, stride=1, padding="SAME") return conv(x) inputs = np.random.normal(size=(8, 28, 28, 3)) forward = hk.transform(forward) variables = forward.init(jax.random.PRNGKey(42), jnp.zeros_like(inputs)) variables = hk.data_structures.to_mutable_dict(variables) jax_fn = hk.without_apply_rng(forward).apply self._test_convert( jax_fn, [variables, inputs], with_grad=with_grad, enable_xla=enable_xla, grad_tols=tols) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), ( ("default_group_counts", dict()), ("feature_group_count", dict(feature_group_count=3)), ("batch_group_count", dict(batch_group_count=2)), ), named=True, )) def test_xla_conv(self, with_grad, enable_xla, group_counts): np.random.seed(42) kernels = np.random.normal(size=(3, 3, 3, 12)) dimension_numbers = jax.lax.ConvDimensionNumbers( lhs_spec=(0, 3, 1, 2), rhs_spec=(3, 2, 0, 1), out_spec=(0, 3, 1, 2)) def forward(x): return jax.lax.conv_general_dilated( x, rhs=kernels, window_strides=(1, 1), padding="SAME", lhs_dilation=(1, 1), rhs_dilation=(1, 1), dimension_numbers=dimension_numbers, **group_counts) feature_dim = 3 * group_counts.get("feature_group_count", 1) inputs = np.random.normal(size=(8, 28, 28, feature_dim)) forward = hk.transform(forward) variables = forward.init(jax.random.PRNGKey(42), jnp.zeros_like(inputs)) variables = hk.data_structures.to_mutable_dict(variables) jax_fn = hk.without_apply_rng(forward).apply self._test_convert( jax_fn, [variables, inputs], with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), named=True, )) def test_dot(self, with_grad, enable_xla): def forward(lhs, rhs): return jax.lax.dot(lhs, rhs) inputs = ( np.linspace(0, 1, 10 * 5).reshape(10, 5), np.linspace(-1, 0, 5 * 3).reshape(5, 3), ) self._test_convert( forward, inputs, with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), named=True, )) def test_dot_general(self, with_grad, enable_xla): dimension_numbers = (((2,), (1,)), ((0,), (0,))) def forward(lhs, rhs): return jax.lax.dot_general(lhs, rhs, dimension_numbers) inputs = ( np.linspace(0, 1, 2 * 10 * 5).reshape((2, 10, 5)), np.linspace(-1, 0, 2 * 5 * 3).reshape((2, 5, 3)), ) self._test_convert( forward, inputs, with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), named=True, )) def test_dynamic_slice(self, with_grad, enable_xla): def forward(x): return jax.lax.dynamic_slice(x, (1, 1), (2, 3)) inputs = np.linspace(0, 1, 12).reshape(3, 4) self._test_convert( forward, [inputs], with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), named=True, )) def test_dynamic_update_slice(self, with_grad, enable_xla): def forward(x, y): return jax.lax.dynamic_update_slice(x, y, (1, 2)) inputs = [ np.linspace(0, 1, 12).reshape(3, 4), 1.0 - np.linspace(0, 1, 12).reshape(3, 4), ] self._test_convert( forward, inputs, with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), named=True, )) def test_gather(self, with_grad, enable_xla): dimension_numbers = jax.lax.GatherDimensionNumbers((1,), (0,), (0, 1)) slice_sizes = (1, 3) def forward(operand, indices): return jax.lax.gather(operand, indices, dimension_numbers, slice_sizes) inputs = ( np.linspace(0, 1, 10 * 5).reshape(10, 5), np.array([[4, 2], [3, 2]]), ) self._test_convert( forward, inputs, with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), named=True, )) def test_pad(self, with_grad, enable_xla): padding_config = [(1, 2, 1), (0, 1, 0)] def forward(operand, padding_value): return jax.lax.pad(operand, padding_value, padding_config) inputs = ( np.linspace(0, 1, 2 * 3).reshape(2, 3), np.array(0.42), ) self._test_convert( forward, inputs, with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), ( ("min", jax.lax.min, jnp.inf), ("max", jax.lax.max, -jnp.inf), ("add", jax.lax.add, 0.0), ), named=True, )) def test_reduce(self, with_grad, enable_xla, reduce_fn, init_value): def forward(x): dimensions = [1, 2] return jax.lax.reduce(x, init_value, reduce_fn, dimensions) inputs = np.linspace(0, 1, 2 * 5 * 5 * 3).reshape((2, 5, 5, 3)) self._test_convert( forward, [inputs], with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), named=True, )) def test_reduce_variadic(self, with_grad, enable_xla): def forward(args): return jax.lax.reduce(args, (0.0, 1.0), lambda xs, ys: xs, [1, 2]) inputs = ( np.linspace(0, 1, 2 * 5 * 5 * 3).reshape((2, 5, 5, 3)), np.linspace(2, 3, 2 * 5 * 5 * 3).reshape((2, 5, 5, 3)), ) self._test_convert( forward, [inputs], with_grad=with_grad, enable_xla=enable_xla) # jax.lax.reduce_window is translated to XlaReduceWindow. @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), ( ("min", jax.lax.min, jnp.inf), ("max", jax.lax.max, -jnp.inf), ("add", jax.lax.add, 0.0), ), named=True, )) def test_reduce_window(self, with_grad, enable_xla, reduce_fn, init_value): np.random.seed(42) def forward(x): window_shape = [1, 2, 2, 1] return jax.lax.reduce_window(x, init_value, reduce_fn, window_shape, window_shape, "SAME") inputs = np.random.normal(size=(8, 28, 28, 3)) self._test_convert( forward, [inputs], with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), ( ("min", jax.lax.cummin), ("max", jax.lax.cummax), ("sum", jax.lax.cumsum), ("prod", jax.lax.cumprod), ), ( ("dim0", 0), ("dim1", 1), ), ( ("reverse", True), ("not_reverse", False), ), ( ("heuristic", True), ("no_heuristic", False), ), named=True, )) def test_cumulative_reduction(self, with_grad, enable_xla, reducer, axis, reverse, use_heuristic): if (with_grad and not use_heuristic and jax.default_backend().lower() == "tpu"): self.skipTest("Gradient of reduce-window not always supported on TPU") np.random.seed(42) def forward(x): return reducer(x, axis=axis, reverse=reverse) inputs = np.random.normal(size=(4, 3)) with config.override_config("infer_cumulative_reduction_from_jax2tf", use_heuristic): roundtrip_forward = tf2jax.convert_functional( tf.function(_jax2tf_convert(forward), autograph=False), inputs) roundtrip_jaxpr = jax.make_jaxpr(roundtrip_forward)(inputs) if (use_heuristic and not uses_native_serialization()): self.assertNotIn("reduce_window", roundtrip_jaxpr.pretty_print()) if (with_grad and enable_xla and reducer is jax.lax.cumprod and not use_heuristic): self.skipTest("No differentiation rule for `reduce_window` with " "`jax.lax.cumprod`.") self._test_convert( forward, [inputs], with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False),), (("enable_xla", True),), (("uint32", np.uint32),), ( ("default", xla_data_pb2.RandomAlgorithm.RNG_DEFAULT), ("threefry", xla_data_pb2.RandomAlgorithm.RNG_THREE_FRY), ("philox", xla_data_pb2.RandomAlgorithm.RNG_PHILOX), ), named=True, )) def test_rng_bit_generator(self, with_grad, enable_xla, dtype, algorithm): def forward(key): return jax.lax.rng_bit_generator( key, shape=(10, 5), dtype=dtype, algorithm=algorithm) if dtype == np.uint32: key = np.array([6, 7, 8, 9], dtype=np.uint32) else: raise ValueError(f"Unsupported dtype={dtype}") self._test_convert( forward, [key], with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( ( ("scatter", jax.lax.scatter), ("scatter_add", jax.lax.scatter_add), ("scatter_mul", jax.lax.scatter_mul), ("scatter_min", jax.lax.scatter_min), ("scatter_max", jax.lax.scatter_max), ), (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), (("unique_indices", True), ("non_unique_indices", False)), named=True, )) def test_scatter(self, scatter_fn, with_grad, enable_xla, unique_indices): if scatter_fn is jax.lax.scatter_mul and with_grad and not unique_indices: self.skipTest("Gradient is disallowed for jax.lax.scatter_mul if " "unique_indices=False") dimension_numbers = jax.lax.ScatterDimensionNumbers((1,), (0,), (0,)) def forward(operand, indices, updates): return scatter_fn( operand, indices, updates, dimension_numbers, unique_indices=unique_indices) inputs = ( np.linspace(0, 1, 10*5).reshape(10, 5), np.array([[1], [8], [4]]), np.linspace(0, 9, 9).reshape(3, 3), ) self._test_convert( forward, inputs, with_grad=with_grad, enable_xla=enable_xla) # Derivative of jax.lax.reduce_window uses XlaSelectAndScatter. @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False),), (("enable_xla", True),), ( ("min", jax.lax.min, jnp.inf), ("max", jax.lax.max, -jnp.inf), ("add", jax.lax.add, 0.0), ), named=True, )) def test_select_and_scatter(self, with_grad, enable_xla, reduce_fn, init_value): np.random.seed(42) def forward(x): window_shape = [1, 2, 2, 1] return jax.lax.reduce_window(x, init_value, reduce_fn, window_shape, window_shape, "SAME") inputs = np.random.normal(size=(8, 5, 5, 3)) jax_fn = jax.jacrev(forward) try: self._test_convert( jax_fn, [inputs], with_grad=with_grad, enable_xla=enable_xla) except tf.errors.InvalidArgumentError as e: if jax.default_backend().lower() == "tpu": # Can fail on older TPUs. self.assertIn("XLA can't use dynamic begin values for slice", str(e)) # pylint: disable=g-assert-in-except else: raise e @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("enable_xla", True),), (("2nd_last_dim", -2), ("last_dim", -1)), (("not_stable", False), ("is_stable", True)), (("one_keys", 1), ("two_keys", 2), ("three_keys", 3)), named=True, )) def test_sort_variadic(self, with_grad, enable_xla, dim, is_stable, num_keys): def forward(args): return jax.lax.sort( args, dimension=dim, is_stable=is_stable, num_keys=num_keys) inputs = ( np.array([[6., 2.], [4., 2.], [4., 1.]], np.float32), np.array([[1., 2.], [3., 4.], [5., 6.]], np.float32), np.array([[6., 5.], [4., 3.], [2., 1.]], np.float32), ) self._test_convert( forward, [inputs], with_grad=with_grad, enable_xla=enable_xla) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), named=True, ) ) def test_polymorphic_shape(self, with_grad, enable_xla): if uses_native_serialization(): if not enable_xla: self.skipTest("native_serialization does not support enable_xla=False.") inputs = np.array(range(36), dtype=np.float32).reshape(9, 4) # TF @tf.function(autograph=False) def forward(x): shape = tf.shape(x) # Manipulate polymoprhic shape. new_shape = tf.stack([tf.pow(shape[0], 1), shape[1]], axis=0) outputs = tf.broadcast_to(tf.sin(x), new_shape) outputs = tf.concat([outputs] * 2, axis=0) # Stack along unknown dim outputs = tf.concat([outputs] * 2, axis=1) # Stack along knonwn dim return outputs / tf.cast(shape[0], tf.float32) # Divide by unknown dim tf_outputs = forward(inputs) # TF -> JAX jax_func = tf2jax.convert_functional(forward, tf.TensorSpec((None, 4))) jax_func = self.variant(jax_func) jax_outputs = jax_func(inputs) self.assertAllClose(tf_outputs, jax_outputs) # TF -> JAX -> TF new_tf_forward = _jax2tf_convert( jax_func, polymorphic_shapes=["(b, _)"], with_gradient=with_grad, enable_xla=enable_xla) new_tf_forward = tf.function(new_tf_forward, autograph=False) concrete_new_tf_forward = new_tf_forward.get_concrete_function( tf.TensorSpec(shape=(None, 4))) self.assertEqual(concrete_new_tf_forward.structured_outputs.shape.as_list(), [None, 8]) new_tf_outputs = concrete_new_tf_forward(inputs) self.assertAllClose(new_tf_outputs, jax_outputs) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), named=True, ) ) def test_polymorphic_shape_refinement_dot(self, with_grad, enable_xla): if uses_native_serialization(): if not enable_xla: self.skipTest("native_serialization does not support enable_xla=False.") @jax.jit def forward(x, w): return jnp.dot(x, w) x = np.array(range(12), dtype=np.float32).reshape((3, 4)) w = np.array(range(20), dtype=np.float32).reshape((4, 5)) expected_outputs = forward(x, w) # JAX -> TF tf_fn = _jax2tf_convert( forward, polymorphic_shapes=["(b, _)", None], with_gradient=with_grad, enable_xla=enable_xla) tf_fn = tf.function(tf_fn, autograph=False) concrete_tf_fn = tf_fn.get_concrete_function( tf.TensorSpec(shape=(None, 4)), tf.TensorSpec(shape=(4, 5))) tf_outputs = concrete_tf_fn(x, w) self.assertAllClose(expected_outputs, tf_outputs) # JAX -> TF -> JAX jax_fn = tf2jax.convert_functional( tf_fn, np.zeros_like(x), np.zeros_like(w) ) jax_outputs = self.variant(jax_fn)(x, w) self.assertAllClose(expected_outputs, jax_outputs) # JAX -> TF -> JAX -> TF tf_fn2 = _jax2tf_convert( jax_fn, polymorphic_shapes=["(b, _)", None], with_gradient=with_grad, enable_xla=enable_xla) tf_fn2 = tf.function(tf_fn2, autograph=False) concrete_tf_fn2 = tf_fn2.get_concrete_function( tf.TensorSpec(shape=(None, 4)), tf.TensorSpec(shape=(4, 5))) tf_outputs2 = concrete_tf_fn2(x, w) self.assertAllClose(expected_outputs, tf_outputs2) # JAX -> TF -> JAX -> TF -> SavedModel module = tf.Module() module.fn = tf_fn2 tmp_dir = self.create_tempdir() options = tf.saved_model.SaveOptions(experimental_custom_gradients=True) tf.saved_model.save(module, tmp_dir.full_path, options=options) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), named=True, ) ) def test_polymorphic_shape_refinement_broadcast(self, with_grad, enable_xla): if uses_native_serialization(): if not enable_xla: self.skipTest("native_serialization does not support enable_xla=False.") @jax.jit def forward(x, y): return (jnp.broadcast_to(x, y.shape), x + y) x = np.array(range(12), dtype=np.float32).reshape((3, 4)) y = np.array(range(24), dtype=np.float32).reshape((2, 3, 4)) expected_outputs = forward(x, y) # JAX -> TF tf_fn = _jax2tf_convert( forward, polymorphic_shapes=["(b, _)", "(_, b, _)"], with_gradient=with_grad, enable_xla=enable_xla) tf_fn = tf.function(tf_fn, autograph=False) concrete_tf_fn = tf_fn.get_concrete_function( tf.TensorSpec(shape=(None, 4)), tf.TensorSpec(shape=(2, None, 4))) tf_outputs = concrete_tf_fn(x, y) self.assertAllClose(expected_outputs, tf_outputs) # JAX -> TF -> JAX jax_fn = tf2jax.convert_functional( tf_fn, np.zeros_like(x), np.zeros_like(y) ) jax_outputs = self.variant(jax_fn)(x, y) self.assertAllClose(expected_outputs, jax_outputs) # JAX -> TF -> JAX -> TF tf_fn2 = _jax2tf_convert( jax_fn, polymorphic_shapes=["(b, _)", "(_, b, _)"], with_gradient=with_grad, enable_xla=enable_xla) tf_fn2 = tf.function(tf_fn2, autograph=False) concrete_tf_fn2 = tf_fn2.get_concrete_function( tf.TensorSpec(shape=(None, 4)), tf.TensorSpec(shape=(2, None, 4))) tf_outputs2 = concrete_tf_fn2(x, y) self.assertAllClose(expected_outputs, tf_outputs2) # JAX -> TF -> JAX -> TF -> SavedModel module = tf.Module() module.fn = tf_fn2 tmp_dir = self.create_tempdir() options = tf.saved_model.SaveOptions(experimental_custom_gradients=True) tf.saved_model.save(module, tmp_dir.full_path, options=options) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("with_gradient", True),), (("disable_xla", False), ("enable_xla", True)), named=True, )) def test_custom_gradient(self, with_grad, enable_xla): if uses_native_serialization(): if not enable_xla: self.skipTest("native_serialization does not support enable_xla=False.") inputs = np.array(range(6), dtype=np.float32).reshape(3, 2) # JAX @jax.custom_gradient def forward(x): e = jnp.exp(x) def grad(dy): # This is deliberately the wrong gradient. return dy * (1 - 1 / (1 + e)) * jnp.sin(x) + 0.42 return jnp.sum(jnp.log(1 + e)), grad forward = self.variant(forward) expected_outputs = forward(inputs) expected_grads = jax.grad(forward)(inputs) # JAX -> TF tf_forward = _jax2tf_convert( forward, with_gradient=with_grad, enable_xla=enable_xla) tf_forward = tf.function(tf_forward, autograph=False) # JAX -> TF -> JAX with config.override_config("convert_custom_gradient", True): jax_forward = tf2jax.convert_functional(tf_forward, tf.zeros_like(inputs)) jax_forward = self.variant(jax_forward) jax_outputs = jax_forward(inputs) jax_grads = jax.grad(jax_forward)(inputs) self.assertAllClose(expected_outputs, jax_outputs) self.assertAllClose(expected_grads, jax_grads) # Jax -> TF -> SavedModel -> TF model = tf.Module() model.f = tf_forward tmp_dir = self.create_tempdir() tf.saved_model.save(model, tmp_dir.full_path) del model restored = tf.saved_model.load(tmp_dir.full_path) # Jax -> TF -> SavedModel -> TF -> Jax with config.override_config("convert_custom_gradient", True): re_jax_forward = tf2jax.convert_functional(restored.f, tf.zeros_like(inputs)) re_jax_forward = self.variant(re_jax_forward) re_jax_outputs = re_jax_forward(inputs) re_jax_grads = jax.grad(re_jax_forward)(inputs) self.assertAllClose(expected_outputs, re_jax_outputs) self.assertAllClose(expected_grads, re_jax_grads) @chex.variants(with_jit=True) @parameterized.named_parameters( chex.params_product( (("with_gradient", True),), (("disable_xla", False), ("enable_xla", True)), named=True, )) def test_custom_gradient_nested(self, with_grad, enable_xla): if uses_native_serialization(): if not enable_xla: self.skipTest("native_serialization does not support enable_xla=False.") inputs = np.array(range(6), dtype=np.float32).reshape(3, 2) # JAX @jax.custom_gradient def forward(x): e = jnp.exp(x) def grad(dy): # This is deliberately the wrong gradient. return dy * (1 - 1 / (1 + e)) * jnp.sin(x) + 0.42 return jnp.sum(jnp.log(1 + e)), grad forward = self.variant(forward) expected_outputs = forward(inputs) expected_grads = jax.grad(forward)(inputs) # JAX -> TF tf_fn = _jax2tf_convert( forward, with_gradient=with_grad, enable_xla=enable_xla) tf_fn = tf.function(tf_fn, autograph=False) # JAX -> TF -> CALL_TF -> TF. # This creates dependencies between custom gradients. call_tf_fn = jax2tf.call_tf(tf_fn) tf_fn_too = _jax2tf_convert(call_tf_fn, with_gradient=with_grad) tf_fn_too = tf.function(tf_fn_too, autograph=False) # JAX -> TF -> CALL_TF -> TF -> JAX with config.override_config("convert_custom_gradient", True): jax_fn_too = tf2jax.convert_functional(tf_fn_too, np.zeros_like(inputs)) jax_outputs = jax_fn_too(inputs) jax_grads = jax.grad(jax_fn_too)(inputs) self.assertAllClose(expected_outputs, jax_outputs) self.assertAllClose(expected_grads, jax_grads) @chex.variants(without_jit=True, with_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), (("disable_xla", False), ("enable_xla", True)), (("without_custom_gradient", False), ("with_custom_gradient", True)), named=True, )) def test_relu(self, with_grad, enable_xla, with_custom_grad): inputs = np.array([-1.0, 0.0, 1.0], np.float32) self._test_convert( jax.nn.relu, [inputs], with_grad=with_grad, enable_xla=enable_xla, with_custom_grad=with_custom_grad) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("disable_xla", False), ("enable_xla", True)), named=True, )) def test_empty_return(self, enable_xla): if uses_native_serialization(): if not enable_xla: self.skipTest("native_serialization does not support enable_xla=False.") np.random.seed(42) def forward(x): unused_y = jnp.cos(x) return () # JAX forward = self.variant(forward) inputs = np.random.normal((3, 2)) with self.assertRaisesRegex( TypeError, "Gradient only defined for scalar-output functions. Output was ()."): jax.grad(forward)(inputs) # JAX -> TF tf_forward = _jax2tf_convert( forward, with_gradient=True, enable_xla=enable_xla) tf_forward = tf.function(tf_forward, autograph=False) # JAX -> TF -> JAX with config.override_config("convert_custom_gradient", True): jax_forward = tf2jax.convert_functional(tf_forward, tf.zeros_like(inputs)) jax_forward = self.variant(jax_forward) with self.assertRaisesRegex( TypeError, "Gradient only defined for scalar-output functions. Output was ()."): jax.grad(jax_forward)(inputs) # Jax -> TF -> SavedModel -> TF model = tf.Module() model.f = tf_forward tmp_dir = self.create_tempdir() tf.saved_model.save(model, tmp_dir.full_path) del model restored = tf.saved_model.load(tmp_dir.full_path) # Jax -> TF -> SavedModel -> TF -> Jax with config.override_config("convert_custom_gradient", True): re_jax_forward = tf2jax.convert_functional(restored.f, tf.zeros_like(inputs)) re_jax_forward = self.variant(re_jax_forward) with self.assertRaisesRegex( TypeError, "Gradient only defined for scalar-output functions. Output was ()."): jax.grad(re_jax_forward)(inputs) @chex.variants(with_jit=True, without_jit=True) def test_jax2tf_nesting(self): @tf.function(autograph=False) def tf_fn(x): return tf.cos(x) def tf2jax_fn(x): jax_fn = tf2jax.convert_functional(tf_fn, x) return jnp.sin(self.variant(jax_fn)(x)) tf2jax2tf_fn = _jax2tf_convert(tf2jax_fn) tf2jax2tf_fn = tf.function(tf2jax2tf_fn, autograph=False) inputs = np.linspace(-1., 1., 6, dtype=np.float32).reshape((2, 3)) self.assertAllClose(tf.sin(tf_fn(inputs)), tf2jax2tf_fn(inputs)) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False), ("with_gradient", True)), named=True, )) def test_remat(self, with_gradient): def fn(x): return jnp.sin(jnp.sin(x)) remat_fn = jax.checkpoint(fn) inputs = ( np.linspace(0, 1, 10 * 5, dtype=np.float32).reshape(10, 5), ) self._test_convert( remat_fn, inputs, with_grad=with_gradient, enable_xla=True, with_custom_grad=True) if uses_native_serialization(): self.skipTest("Skip remat jaxpr test with native_serialization.") # Check jaxpr. tf_fn = tf.function( _jax2tf_convert(remat_fn, with_gradient=True, enable_xla=True), autograph=False) jax_fn = tf2jax.convert_functional(tf_fn, tf.TensorSpec((10, 5), tf.float32)) jax_fn = self.variant(jax_fn) out_jaxpr = jax.make_jaxpr(jax_fn)(*inputs) self.assertNotRegex(str(out_jaxpr), "remat") grad_jaxpr = jax.make_jaxpr(jax.grad(lambda x: jnp.sum(jax_fn(x))))(*inputs) self.assertRegex(str(grad_jaxpr), "optimization_barrier") @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", False),), (("enable_xla", True),), (("without_custom_gradient", False), ("with_custom_gradient", True)), named=True, )) def test_reduce_precision(self, with_grad, enable_xla, with_custom_grad): if jax.__version_info__ <= (0, 4, 4): self.skipTest("jax.lax.reduce_precision is only supported from 0.4.4 and " f"onward, found {jax.__version__}.") np.random.seed(42) def forward(x): info = jnp.finfo(jnp.bfloat16) return jax.lax.reduce_precision(x, info.nexp, info.nmant) inputs = np.random.normal((3, 2)).astype(np.float32) self._test_convert( forward, [inputs], with_grad=with_grad, enable_xla=enable_xla, with_custom_grad=with_custom_grad) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("without_gradient", True),), (("enable_xla", True), ("disable_xla", False)), (("with_custom_gradient", True),), ( ("lower", True), ("upper", False), ), ( ("unit_diagonal", True), ("not_unit_diagonal", False), ), ( ("unbatched", ((5, 5), (5, 5))), ("batched", ((3, 5, 5), (3, 5, 4))), ("more_batched", ((2, 3, 5, 5), (2, 3, 5, 6))), ), named=True, )) def test_triangular_solve( self, with_grad, enable_xla, with_custom_grad, lower, unit_diagonal, shapes, ): if uses_native_serialization(): self.skipTest( "native_serialization: Cannot serialize code with custom calls whose " "targets have no compatibility guarantees.") np.random.seed(42) lhs_shape, rhs_shape = shapes inputs = ( np.random.normal(size=lhs_shape).astype(np.float32), np.random.normal(size=rhs_shape).astype(np.float32), ) def forward(a, b): return jax.lax.linalg.triangular_solve( a, b, left_side=True, lower=lower, unit_diagonal=unit_diagonal ) tols = dict(atol=1e-5) if jax.default_backend().lower() == "tpu" else {} self._test_convert( forward, inputs, with_grad=with_grad, enable_xla=enable_xla, with_custom_grad=with_custom_grad, grad_tols=tols) def test_explicit_native_serialization(self): if test_util.parse_version(tf.version.VERSION) < test_util.parse_version( "2.12.0" ): self.skipTest(f"Requires tf 2.12.0 or later, found {tf.version.VERSION}.") def forward(x): return x + 3.14 tf_fn = jax2tf.convert(forward, native_serialization=True) tf_fn = tf.function(tf_fn, autograph=False) try: jax_fn = tf2jax.convert_functional( tf_fn, tf.TensorSpec((2, 3), tf.float32) ) jax_fn = jax.jit(jax_fn) inputs = np.linspace(-1., 1., 6, dtype=np.float32).reshape((2, 3)) self.assertAllClose(jax_fn(inputs), tf_fn(inputs)) except ValueError as e: if uses_native_serialization(): raise ValueError("Native lowering support failed.") from e elif r"Unsupported operations in graph: ['XlaCallModule']" not in str(e): raise ValueError("Unexpected unsupported operations found.") from e elif r"check for import error if you see this message" not in str(e): raise ValueError("Import/dependency error message not found.") from e else: # Expected failure. return if not uses_native_serialization(): raise ValueError( "Unexpected success with native serialization. Test may be " "misconfigured." ) if jax.default_backend().lower() != "cpu": with jax.default_device(jax.devices("cpu")[0]): with self.assertRaisesRegex(ValueError, "Unsupported backend"): _ = jax_fn(inputs) with tf2jax.config.override_config( "xlacallmodule_strict_checks", False ): self.assertAllClose(jax_fn(inputs), tf_fn(inputs)) if __name__ == "__main__": absltest.main()
tf2jax-main
tf2jax/_src/roundtrip_test.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test utils.""" import contextlib from absl import logging from absl.testing import parameterized import jax import tensorflow as tf def parse_version(version: str): return tuple(int(x.split("-")[0]) for x in version.split(".")) class TestCase(parameterized.TestCase, tf.test.TestCase): """Base class for all tests.""" def setUp(self): super().setUp() # Ensure that all TF ops are created on the proper device (TPU, GPU or CPU) jax_default_device = jax.default_backend().upper() tf_logical_devices = tf.config.list_logical_devices(jax_default_device) tf_default_device = tf_logical_devices[0] logging.info("Running tf2jax converted code on %s.", tf_default_device) self.assertEqual(jax_default_device, tf_default_device.device_type) with contextlib.ExitStack() as stack: stack.enter_context(tf.device(tf_default_device)) self.addCleanup(stack.pop_all().close)
tf2jax-main
tf2jax/_src/test_util.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. # ============================================================================== """JAX util functions.""" from typing import Optional, Sequence, Union import jax import tensorflow as tf # TODO(shaobohou) Is there a non-direct alias? from tensorflow.compiler.xla import xla_data_pb2 # pytype: disable=import-error def get_conv_sequence( value: Union[int, Sequence[int]], ndim: int, channel_index: int, ) -> Union[int, Sequence[int]]: """Format strides or dilation sequences for conv operations.""" if isinstance(value, int): return [value] * ndim elif len(value) == 1: return value * ndim elif len(value) == ndim: return value elif len(value) == ndim + 2: return value[2:] if channel_index == 1 else value[1:-1] else: raise ValueError(f"Unexpected sequence={value}.") def convolution_dimension_numbers_from_proto( message) -> jax.lax.ConvDimensionNumbers: """Converts a XLA ConvolutionDimensionNumbers to a ConvDimensionNumbers.""" proto = xla_data_pb2.ConvolutionDimensionNumbers().FromString(message) lhs_spec = ((proto.input_batch_dimension, proto.input_feature_dimension) + tuple(proto.input_spatial_dimensions)) rhs_spec = ((proto.kernel_output_feature_dimension, proto.kernel_input_feature_dimension) + tuple(proto.kernel_spatial_dimensions)) out_spec = ((proto.output_batch_dimension, proto.output_feature_dimension) + tuple(proto.output_spatial_dimensions)) return jax.lax.ConvDimensionNumbers(lhs_spec, rhs_spec, out_spec) def dot_dimension_numbers_from_proto(message) -> jax.lax.DotDimensionNumbers: proto = xla_data_pb2.DotDimensionNumbers().FromString(message) contracting_dimensions = (tuple(proto.lhs_contracting_dimensions), tuple(proto.rhs_contracting_dimensions)) batch_dimensions = (tuple(proto.lhs_batch_dimensions), tuple(proto.rhs_batch_dimensions)) return (contracting_dimensions, batch_dimensions) def gather_dimension_numbers_from_proto( message) -> jax.lax.GatherDimensionNumbers: proto = xla_data_pb2.GatherDimensionNumbers().FromString(message) return jax.lax.GatherDimensionNumbers( tuple(proto.offset_dims), tuple(proto.collapsed_slice_dims), tuple(proto.start_index_map)) def scatter_dimension_numbers_from_proto( message) -> jax.lax.ScatterDimensionNumbers: proto = xla_data_pb2.ScatterDimensionNumbers().FromString(message) return jax.lax.ScatterDimensionNumbers( tuple(proto.update_window_dims), tuple(proto.inserted_window_dims), tuple(proto.scatter_dims_to_operand_dims)) def precision_config_from_proto( message) -> Optional[Union[jax.lax.Precision, Sequence[jax.lax.Precision]]]: """Converts a PrecisionConfig proto to jax.lax.Precision.""" proto = xla_data_pb2.PrecisionConfig().FromString(message) precision_config = [ jax.lax.Precision(v) for v in proto.operand_precision ] if not precision_config: precision_config = None elif len(precision_config) == 1: precision_config = precision_config[0] else: precision_config = tuple(precision_config) return precision_config def get_random_algorithm_from_tf( algorithm: int) -> xla_data_pb2.RandomAlgorithm: """Map tf random algorithm enum to XLA random algorithm enum.""" algorithm_map = { tf.random.Algorithm.PHILOX.value: xla_data_pb2.RandomAlgorithm.RNG_PHILOX, tf.random.Algorithm.THREEFRY.value: xla_data_pb2.RandomAlgorithm.RNG_THREE_FRY, tf.random.Algorithm.AUTO_SELECT.value: xla_data_pb2.RandomAlgorithm.RNG_DEFAULT, } return algorithm_map[algorithm]
tf2jax-main
tf2jax/_src/xla_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. # ============================================================================== """Tests tf2jax.""" import inspect from absl.testing import parameterized import chex import haiku as hk import jax import jax.numpy as jnp import numpy as np import sonnet as snt import tensorflow as tf from tf2jax._src import config from tf2jax._src import tf2jax import tree # Parse absl flags test_srcdir and test_tmpdir. jax.config.parse_flags_with_absl() class TestDense(tf.Module): def __init__(self, input_dim, output_size, name=None): super().__init__(name=name) self.w = tf.Variable(tf.random.normal([input_dim, output_size]), name="w") self.b = tf.Variable(tf.zeros([output_size]), name="b") def __call__(self, x): y = tf.matmul(x, self.w) + self.b return tf.nn.relu(y) class TestMLP(tf.Module): """Variables for different dense layers will not have unique names.""" def __init__(self, input_size, sizes, name=None): super().__init__(name=name) self.layers = [] with self.name_scope: for size in sizes: self.layers.append(TestDense(input_dim=input_size, output_size=size)) input_size = size @tf.Module.with_name_scope def __call__(self, x): for layer in self.layers: x = layer(x) return x class ModelsTest(tf.test.TestCase, parameterized.TestCase): def _test_convert(self, tf_func, inputs): jax_func, jax_params = tf2jax.convert( tf.function(tf_func), np.zeros_like(inputs)) jax_func = self.variant(jax_func) (jax_results, _), jax_params = jax_func(jax_params, inputs) tf_results, tf_params = tf_func(inputs) # Check outputs for tf_res, jax_res in jax.util.safe_zip( tree.flatten(tf_results), tree.flatten(jax_results) ): self.assertAllClose(tf_res.numpy(), jax_res, atol=1e-4) # Check params (batchnorm stats changed). for tf_var in tree.flatten(tf_params): jax_var = jax_params[tf_var.name.split(":")[0]] self.assertAllClose(tf_var.numpy(), jax_var, atol=1e-5) @chex.variants(with_jit=True, without_jit=True) def test_mlp(self): tf.random.set_seed(42) inputs = np.linspace(-1., 1., 128 * 16, dtype=np.float32).reshape((128, 16)) model = snt.nets.MLP((64, 10,)) def tf_func(x): outputs = model(x) return outputs, model.variables self._test_convert(tf_func, inputs) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("inference", False), ("training", True)), named=True, )) def test_resnet(self, training): tf.random.set_seed(42) inputs = np.linspace( -1., 1., 2 * 64 * 64 * 3, dtype=np.float32).reshape((2, 64, 64, 3)) model = snt.nets.ResNet([1, 1, 1, 1], 10) def tf_func(x): outputs = model(x, is_training=training) return outputs, model.variables self._test_convert(tf_func, inputs) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("inference", False), ("training", True)), named=True, )) def test_vqvae(self, training): tf.random.set_seed(42) inputs = np.linspace( -1., 1., 2 * 64 * 64 * 3, dtype=np.float32).reshape((2, 64, 64, 3)) model = snt.nets.VectorQuantizer(3, 100, 0.1) def tf_func(x): return model(x, is_training=training), model.variables self._test_convert(tf_func, inputs) class FeaturesTest(tf.test.TestCase, parameterized.TestCase): def _setup_saved_model(self, *inputs): def tf_func(x): return tf.exp(x) # Save. model = tf.Module() model.f = tf.function(tf_func) for inp in inputs: if isinstance(inp, tf.TensorSpec): model.f.get_concrete_function(inp) # Dummy call. else: model.f(np.zeros_like(inp)) # Dummy call. tmp_dir = self.create_tempdir() tf.saved_model.save(model, tmp_dir.full_path) return tf_func, tf.saved_model.load(tmp_dir.full_path) @chex.variants(with_jit=True, without_jit=True) def test_saved_model(self): dummy_inputs = np.zeros([10, 5], dtype=np.float32) tf_func, restored = self._setup_saved_model(dummy_inputs) # Convert to Jax (with and without explicit inputs). for inp in [(), (dummy_inputs,)]: if inp: jax_func, _ = tf2jax.convert(restored.f, *inp) else: jax_func, _ = tf2jax.convert_from_restored(restored.f) jax_func = self.variant(jax_func) test_inputs = np.ones([20, 5], dtype=np.float32) expected_outputs = tf_func(test_inputs) with config.override_config("strict_shape_check", False): actual_outputs, _ = jax_func({}, test_inputs) self.assertAllClose(expected_outputs, actual_outputs) @chex.variants(with_jit=True, without_jit=True) def test_saved_model_ambiguous(self): dummy_one = np.zeros([10, 5], dtype=np.float32) dummy_two = np.zeros([10, 5, 3], dtype=np.float32) tf_func, restored = self._setup_saved_model(dummy_one, dummy_two) with self.assertRaisesRegex(ValueError, "Found 2 concrete functions"): jax_func, _ = tf2jax.convert_from_restored(restored.f) jax_func, _ = tf2jax.convert(restored.f, dummy_two) jax_func = self.variant(jax_func) test_inputs = np.ones([20, 7, 2], dtype=np.float32) expected_outputs = tf_func(test_inputs) with config.override_config("strict_shape_check", False): actual_outputs, _ = jax_func({}, test_inputs) self.assertAllClose(expected_outputs, actual_outputs) @chex.variants(with_jit=True, without_jit=True) def test_saved_model_functional(self): dummy_inputs = np.zeros([10, 5], dtype=np.float32) tf_func, restored = self._setup_saved_model(dummy_inputs) jax_func = tf2jax.convert_functional_from_restored(restored.f) jax_func = self.variant(jax_func) test_inputs = np.ones([20, 5], dtype=np.float32) expected_outputs = tf_func(test_inputs) with config.override_config("strict_shape_check", False): actual_outputs = jax_func(test_inputs) self.assertAllClose(expected_outputs, actual_outputs) @chex.variants(with_jit=True, without_jit=True) def test_saved_model_polymorphic_shape(self): dummy_input_spec = tf.TensorSpec((None, None, 2), dtype=tf.float32) tf_func, restored = self._setup_saved_model(dummy_input_spec) jax_func = tf2jax.convert_functional_from_restored(restored.f) jax_func = self.variant(jax_func) test_inputs = np.ones([10, 5, 2], dtype=np.float32) expected_outputs = tf_func(test_inputs) actual_outputs = jax_func(test_inputs) self.assertAllClose(expected_outputs, actual_outputs) @chex.variants(with_jit=True, without_jit=True) def test_strict_check(self): def tf_func(x): return x.shape orig_inputs = np.zeros((10, 5), dtype=np.float32) model = tf.Module() model.f = tf.function(tf_func) model.f(orig_inputs) tmp_dir = self.create_tempdir() tf.saved_model.save(model, tmp_dir.full_path) restored = tf.saved_model.load(tmp_dir.full_path) jax_func = tf2jax.convert_functional_from_restored(restored.f) jax_func = self.variant(jax_func) with self.subTest("valid_input_shape"): expected_outputs = tf_func(orig_inputs) with config.override_config("strict_shape_check", True): actual_outputs = jax_func(orig_inputs) self.assertAllClose(expected_outputs, actual_outputs) with config.override_config("strict_dtype_check", True): actual_outputs = jax_func(orig_inputs) self.assertAllClose(expected_outputs, actual_outputs) test_inputs = np.ones([10, 5, 2], dtype=np.float32) with self.subTest("invalid_input_shape"): expected_outputs = tf_func(test_inputs) with config.override_config("strict_shape_check", True): with self.assertRaisesRegex(ValueError, "incompatible input shape"): actual_outputs = jax_func(test_inputs) with config.override_config("strict_shape_check", False): actual_outputs = jax_func(test_inputs) self.assertNotAllClose(expected_outputs, actual_outputs) test_inputs = np.ones([10, 5], dtype=np.int32) with self.subTest("invalid_input_dtype"): expected_outputs = tf_func(test_inputs) with config.override_config("strict_dtype_check", True): with self.assertRaisesRegex(ValueError, "incompatible input dtype"): actual_outputs = jax_func(test_inputs) with config.override_config("strict_dtype_check", False): actual_outputs = jax_func(test_inputs) self.assertAllClose(expected_outputs, actual_outputs) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("float32", tf.float32), ("float64", tf.float64)), named=True, )) def test_force_bf16_consts(self, tf_dtype): @tf.function def tf_func(x): return x + tf.constant(3.14, dtype=x.dtype) np_inputs = np.array(42.0, tf_dtype.as_numpy_dtype()) tf_outputs = tf_func(np_inputs) dtype_config_name = ("force_const_float32_to_bfloat16" if tf_dtype == tf.float32 else "force_const_float64_to_bfloat16") # This is the default. with config.override_config(dtype_config_name, False): jax_func = tf2jax.convert_functional(tf_func, np_inputs) jax_func = self.variant(jax_func) orig_jax_outputs = jax_func(np_inputs) self.assertEqual( jnp.array(np_inputs).dtype, jnp.array(orig_jax_outputs).dtype) self.assertAllClose(tf_outputs, orig_jax_outputs) with config.override_config(dtype_config_name, True): jax_func = tf2jax.convert_functional(tf_func, np_inputs) jax_func = self.variant(jax_func) forced_jax_outputs = jax_func(jnp.asarray(np_inputs, jnp.bfloat16)) self.assertEqual(jnp.bfloat16, forced_jax_outputs.dtype) self.assertAllClose(tf.cast(tf_outputs, tf.bfloat16), forced_jax_outputs) @chex.variants(with_jit=True, without_jit=True) def test_force_bf16_consts_for_leaks(self): @tf.function def tf_func(x): return x + tf.constant(3.14, dtype=tf.float32) np_inputs = np.array(42.0, np.float32) tf_outputs = tf_func(np_inputs) class CachedFn(hk.Module): cache = [] def __init__(self): super().__init__(name=None) if not self.cache: with config.override_config("force_const_float32_to_bfloat16", True): self.cache.append(jax.jit( tf2jax.convert_functional(tf_func, np_inputs))) def __call__(self, x): return self.cache[0](x) def call_cached_fn(x): return CachedFn()(x) cached_fn = hk.without_apply_rng(hk.transform(call_cached_fn)) params = self.variant(cached_fn.init)(jax.random.PRNGKey(42), np_inputs) jax_inputs = jnp.asarray(np_inputs, jnp.bfloat16) jax_outputs = self.variant(cached_fn.apply)(params, jax_inputs) self.assertEqual(jnp.bfloat16, jax_outputs.dtype) self.assertAllClose(tf.cast(tf_outputs, tf.bfloat16), jax_outputs) def test_static_argnums(self): @tf.function def tf_func(x): return tf.zeros((x,)) with self.subTest("literal_input"): jax_func = tf2jax.convert_functional(tf_func, 10) self.assertEqual(jax_func(10).shape, (10,)) with self.assertRaisesRegex(ValueError, "Found unexpected literal value"): jax_func(13) with self.assertRaisesRegex(ValueError, "Found unexpected tracer"): jax.jit(jax_func)(13) with self.assertRaisesRegex(ValueError, "Found unexpected literal value"): jax.jit(jax_func, static_argnums=0)(13) with self.subTest("array_input"): jax_func = tf2jax.convert_functional(tf_func, np.array(10)) self.assertEqual(jax_func(10).shape, (10,)) self.assertEqual(jax_func(13).shape, (13,)) with self.assertRaisesRegex( TypeError, "Shapes must be 1D sequences of concrete values of integer type"): jax.jit(jax_func)(13) self.assertEqual(jax.jit(jax_func, static_argnums=0)(13).shape, (13,)) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( (("with_custom_gradient", True), ("without_custom_gradient", False)), named=True, )) def test_custom_gradient(self, use_custom_gradient): @tf.function @tf.custom_gradient def tf_func(x): e = tf.exp(x) def grad(dy): # This is deliberately the wrong gradient. return dy * (1 - 1 / (1 + e)) * tf.sin(x) + 0.42 return tf.reduce_sum(tf.math.log(1 + e)), grad np_inputs = np.array(range(6), dtype=np.float32).reshape(3, 2) tf_inputs = tf.constant(np_inputs) with tf.GradientTape() as tape: tape.watch(tf_inputs) tf_outputs = tf_func(tf_inputs) tf_grads = tape.gradient(tf_outputs, tf_inputs) with config.override_config("convert_custom_gradient", use_custom_gradient): jax_func = tf2jax.convert_functional(tf_func, np.zeros_like(np_inputs)) jax_func = self.variant(jax_func) jax_outputs = jax_func(np_inputs) jax_grads = jax.grad(jax_func)(np_inputs) self.assertAllClose(tf_outputs, jax_outputs) if use_custom_gradient: self.assertAllClose(tf_grads, jax_grads) else: self.assertNotAllClose(tf_grads, jax_grads) @chex.variants(with_jit=True, without_jit=True) def test_trainable(self): can_train = tf.Variable(3.14, trainable=True, name="can_train") not_train = tf.Variable(42., trainable=False, name="not_train") @tf.function def tf_func(x): return x + can_train + not_train np_inputs = np.array(range(6), dtype=np.float32).reshape(3, 2) jax_func, jax_params = tf2jax.convert(tf_func, np.zeros_like(np_inputs)) self.assertTrue(jax_params["can_train"].trainable) self.assertFalse(jax_params["not_train"].trainable) tf_outputs = tf_func(tf.constant(np_inputs)) jax_outputs, _ = self.variant(jax_func)(jax_params, np_inputs) self.assertAllClose(tf_outputs, jax_outputs) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( ( ("positional", ((3.14, 42.0), {})), ("positional_and_keyword", ((3.14,), dict(y=42.0))), ("keyword", ((), dict(x=3.14, y=42.0))), ), named=True, )) def test_positional_and_keyword_args(self, all_args): @tf.function def tf_func(x, y): return x + y fn_args, fn_kwargs = tree.map_structure(np.array, all_args) tf_outputs = tf_func(*fn_args, **fn_kwargs) zero_args, zero_kwargs = tree.map_structure(np.zeros_like, all_args) jax_func = tf2jax.convert_functional(tf_func, *zero_args, **zero_kwargs) jax_outputs = self.variant(jax_func)(*fn_args, **fn_kwargs) self.assertAllClose(tf_outputs, jax_outputs) @chex.variants(with_jit=True, without_jit=True) @parameterized.named_parameters( chex.params_product( ( ("no_defaults", lambda *, kw0, kw1: kw0 + kw1), ("some_defaults", lambda *, kw0=3.14, kw1: kw0 + kw1), ("all_defaults", lambda *, kw0=3.14, kw1=42.0: kw0 + kw1), ("all_defaults_some_used", lambda *, kw0=3.14, kw1=42.0, kw2=2.8: kw0 + kw1 + kw2), ), named=True, )) def test_keyword_only(self, fn): tf_func = tf.function(fn) inputs = (np.array(3.5, dtype=np.float32), np.array(7.2, dtype=np.float32)) tf_outputs = tf_func(kw0=inputs[0], kw1=inputs[1]) jax_func = tf2jax.convert_functional( tf_func, kw0=np.zeros_like(inputs[0]), kw1=np.zeros_like(inputs[1])) jax_outputs = self.variant(jax_func)(kw0=inputs[0], kw1=inputs[1]) self.assertAllClose(tf_outputs, jax_outputs) def test_metadata(self): @tf.function def tf_func(x, y, *, z): return x + y + z x = np.zeros((10, 5), np.float32) y = np.zeros((10, 1), np.float32) z = np.zeros((), np.float32) jax_func = tf2jax.convert_functional(tf_func, x, y=y, z=z) self.assertEqual(jax_func.structured_inputs, ( ( tf.TensorSpec(shape=(10, 5), dtype=tf.float32, name="x"), tf.TensorSpec(shape=(10, 1), dtype=tf.float32, name="y"), ), { "z": tf.TensorSpec(shape=(), dtype=tf.float32, name="z") }, )) self.assertEqual( jax_func.structured_outputs, tf.TensorSpec(shape=(10, 5), dtype=tf.float32, name="Identity")) expected_sig = inspect.Signature([ inspect.Parameter("x", inspect.Parameter.POSITIONAL_OR_KEYWORD), inspect.Parameter("y", inspect.Parameter.POSITIONAL_OR_KEYWORD), inspect.Parameter("z", inspect.Parameter.KEYWORD_ONLY), ]) self.assertEqual(expected_sig, jax_func.signature) self.assertEqual(expected_sig, inspect.signature(jax_func)) @chex.variants(with_jit=True, without_jit=True) def test_jit_nesting(self): @tf.function def tf_fn(x): return tf.cos(x) @jax.jit def tf2jax_fn(x): jax_fn = tf2jax.convert_functional(tf_fn, x) return jnp.sin(self.variant(jax_fn)(x)) inputs = np.linspace(-1., 1., 6, dtype=np.float32).reshape((2, 3)) self.assertAllClose(tf.sin(tf_fn(inputs)), tf2jax_fn(inputs)) @chex.variants(with_jit=True, without_jit=True) def test_non_unique_variable_names(self): model = TestMLP(input_size=5, sizes=[7, 8]) self.assertNotEqual( len(set([v.name for v in model.variables])), len(model.variables)) @tf.function def forward(x): return model(x) x = np.arange(10).reshape(2, 5).astype(np.float32) tf_outputs = forward(x) apply_fn, params = tf2jax.convert(forward, tf.TensorSpec((None, 5))) jax_outputs, _ = self.variant(apply_fn)(params, x) self.assertAllClose(tf_outputs, jax_outputs) @chex.variants(with_jit=True, without_jit=True) def test_none_in_outputs(self): @tf.function def tf_func(x): return x + 1, None, x + 3.14 jax_func = tf2jax.convert_functional(tf_func, np.zeros((3, 2))) inputs = np.ones((3, 2)) outputs = self.variant(jax_func)(inputs) self.assertAllClose(inputs + 1, outputs[0]) self.assertIsNone(outputs[1]) self.assertAllClose(inputs + 3.14, outputs[2]) @chex.variants(with_jit=True, without_jit=True) def test_missing_inputs(self): params = dict( a=np.array(3.14, np.float32), b=np.array([42, 47], np.float32) ) @tf.function def tf_func(x, params): return x + params["a"] + params["b"] np_inputs = np.array(range(6), dtype=np.float32).reshape(3, 2) jax_func = tf2jax.convert_functional( tf_func, *tree.map_structure(np.zeros_like, (np_inputs, params)) ) with self.assertRaises(tf2jax.MissingInputError): self.variant(jax_func)(np_inputs, {"a": params["a"]}) @chex.variants(with_jit=True, without_jit=True) def test_missing_params(self): variables = dict( a=tf.Variable(3.14, trainable=True, name="aaa"), b=tf.Variable(42.0, trainable=False, name="bbb"), ) @tf.function def tf_func(x): return x + variables["a"] + variables["b"] np_inputs = np.array(range(6), dtype=np.float32).reshape(3, 2) jax_func, jax_params = tf2jax.convert(tf_func, np.zeros_like(np_inputs)) with self.assertRaisesRegex( ValueError, r"Some parameters are missing, \[\'bbb\'\]." ): self.variant(jax_func)({"aaa": jax_params["aaa"]}, np_inputs) if __name__ == "__main__": tf.test.main()
tf2jax-main
tf2jax/_src/tf2jax_test.py
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Experimental functions for converting TF graphs to Jax functions.""" import dataclasses import functools from typing import Any, Callable, List, Optional, Mapping, Protocol, Sequence, Set, Tuple, Union from absl import logging import jax from jax._src.lax import control_flow as lax_control_flow from jax.experimental import checkify from jax.lib import xla_client import jax.numpy as jnp import numpy as np import tensorflow as tf from tf2jax._src import config from tf2jax._src import numpy_compat as anp from tf2jax._src import xla_utils ArrayLike = Union[np.ndarray, jnp.ndarray] # NoOp inserted to trigger side effects in function with no return values. _EMPTY_RETURN_OP_NAME = "__NO_RETURN__" _EMPTY_RETURN_VALUE = object() safe_zip = jax.util.safe_zip def _check_attrs(proto, expected: Set[str]): unexpected = [] for k, v in proto.attr.items(): # Ignore attributes with "_" prefix, as they appear to be undocumented. if k not in expected and not k.startswith("_"): unexpected.append(" `" + f"{k}={v}".strip() + "`") if unexpected: raise ValueError("\n".join( [f"Unexpected attr(s) when parsing {proto.op}: {proto.name}"] + unexpected)) def _get_jax_op( jax_op: Callable[..., Any], expected_attrs: Set[str], ) -> Callable[..., Any]: """For wrapping simple ops with no optional parameters.""" def wrapped(proto): _check_attrs(proto, expected_attrs) return jax_op return wrapped _jax_ops = { "Abs": _get_jax_op(jnp.abs, {"T"}), "Add": _get_jax_op(anp.add, {"T"}), "AddN": _get_jax_op( lambda *args: anp.sum_(anp.stack(args, axis=0), axis=0, keepdims=False), {"T", "N"}), "AddV2": _get_jax_op(anp.add, {"T"}), "ArgMax": _get_jax_op(jnp.argmax, {"T", "Tidx", "output_type"}), "ArgMin": _get_jax_op(jnp.argmin, {"T", "Tidx", "output_type"}), "Acosh": _get_jax_op(jnp.arccosh, {"T"}), "Angle": _get_jax_op(jnp.angle, {"T", "Tout"}), "Asinh": _get_jax_op(jnp.arcsinh, {"T"}), "Atanh": _get_jax_op(jnp.arctanh, {"T"}), "Atan2": _get_jax_op(jnp.arctan2, {"T"}), "BesselI0e": _get_jax_op(jax.lax.bessel_i0e, {"T"}), "BesselI1e": _get_jax_op(jax.lax.bessel_i1e, {"T"}), "BitwiseAnd": _get_jax_op(jnp.bitwise_and, {"T"}), "BitwiseOr": _get_jax_op(jnp.bitwise_or, {"T"}), "BitwiseXor": _get_jax_op(jnp.bitwise_xor, {"T"}), "BroadcastTo": _get_jax_op(anp.broadcast_to, {"T", "Tidx"}), "Ceil": _get_jax_op(jnp.ceil, {"T"}), "Cholesky": _get_jax_op(jnp.linalg.cholesky, {"T"}), "Complex": _get_jax_op(jax.lax.complex, {"T", "Tout"}), "ComplexAbs": _get_jax_op(jax.lax.abs, {"T", "Tout"}), "Conj": _get_jax_op(jax.lax.conj, {"T", "Tout"}), "Cos": _get_jax_op(jnp.cos, {"T"}), "Cosh": _get_jax_op(jnp.cosh, {"T"}), "Digamma": _get_jax_op(jax.lax.digamma, {"T"}), "Div": _get_jax_op(anp.divide, {"T"}), "Elu": _get_jax_op(jax.nn.elu, {"T"}), "Equal": _get_jax_op(anp.equal, {"T", "incompatible_shape_error"}), "Erf": _get_jax_op(jax.lax.erf, {"T"}), "Erfc": _get_jax_op(jax.lax.erfc, {"T"}), "Erfinv": _get_jax_op(jax.lax.erf_inv, {"T"}), "Exp": _get_jax_op(jnp.exp, {"T"}), "Expm1": _get_jax_op(jnp.expm1, {"T"}), "FFT": _get_jax_op( functools.partial(jnp.fft.fftn, axes=(-1,)), {"Tcomplex"}), "FFT2D": _get_jax_op( functools.partial(jnp.fft.fftn, axes=(-2, -1,)), {"Tcomplex"}), "FFT3D": _get_jax_op( functools.partial(jnp.fft.fftn, axes=(-3, -2, -1,)), {"Tcomplex"}), "Floor": _get_jax_op(jnp.floor, {"T"}), "FloorMod": _get_jax_op(anp.mod, {"T"}), "FloorDiv": _get_jax_op(anp.floor_divide, {"T"}), "Greater": _get_jax_op(anp.greater, {"T"}), "GreaterEqual": _get_jax_op(anp.greater_equal, {"T"}), "Identity": _get_jax_op(lambda x: x, {"T"}), "IFFT": _get_jax_op( functools.partial(jnp.fft.ifftn, axes=(-1,)), {"Tcomplex"}), "IFFT2D": _get_jax_op( functools.partial(jnp.fft.ifftn, axes=(-2, -1,)), {"Tcomplex"}), "IFFT3D": _get_jax_op( functools.partial(jnp.fft.ifftn, axes=(-3, -2, -1,)), {"Tcomplex"}), "IRFFT": _get_jax_op( functools.partial(jnp.fft.irfftn, axes=(-1,)), {"Tcomplex", "Treal"}), "IRFFT2D": _get_jax_op( functools.partial( jnp.fft.irfftn, axes=(-2, -1,)), {"Tcomplex", "Treal"}), "IRFFT3D": _get_jax_op( functools.partial( jnp.fft.irfftn, axes=(-3, -2, -1,)), {"Tcomplex", "Treal"}), "Igamma": _get_jax_op(jax.lax.igamma, {"T"}), "Igammac": _get_jax_op(jax.lax.igammac, {"T"}), "Imag": _get_jax_op(jax.lax.imag, {"T", "Tout"}), "IsFinite": _get_jax_op(jnp.isfinite, {"T"}), "Invert": _get_jax_op(jnp.bitwise_not, {"T"}), "InvertPermutation": _get_jax_op(anp.invert_permutation, {"T"}), "L2Loss": _get_jax_op(lambda x: 0.5 * jnp.sum(jnp.square(x)), {"T"}), "LeftShift": _get_jax_op(jnp.left_shift, {"T"}), "Less": _get_jax_op(anp.less, {"T", "incompatible_shape_error"}), "LessEqual": _get_jax_op(anp.less_equal, {"T", "incompatible_shape_error"}), "Lgamma": _get_jax_op(jax.lax.lgamma, {"T"}), "Log": _get_jax_op(jnp.log, {"T"}), "Log1p": _get_jax_op(jnp.log1p, {"T"}), "LogicalAnd": _get_jax_op(jnp.logical_and, {"T"}), "LogicalNot": _get_jax_op(jnp.logical_not, {"T"}), "LogicalOr": _get_jax_op(jnp.logical_or, {"T"}), "Minimum": _get_jax_op(anp.minimum, {"T"}), "Maximum": _get_jax_op(anp.maximum, {"T"}), "Mul": _get_jax_op(anp.multiply, {"T"}), "Neg": _get_jax_op(anp.negative, {"T"}), "NoOp": _get_jax_op(lambda: _EMPTY_RETURN_VALUE, set({})), "NotEqual": _get_jax_op(anp.not_equal, {"T", "incompatible_shape_error"}), "OnesLike": _get_jax_op(jnp.ones_like, {"T"}), "PopulationCount": _get_jax_op(jax.lax.population_count, {"T"}), "Pow": _get_jax_op(anp.power, {"T"}), "Rank": _get_jax_op(lambda x: np.array(jnp.ndim(x)), {"T"}), "Real": _get_jax_op(jax.lax.real, {"T", "Tout"}), "ReadVariableOp": _get_jax_op(lambda x: x, {"dtype"}), "RealDiv": _get_jax_op(anp.true_divide, {"T"}), "Reciprocal": _get_jax_op(anp.reciprocal, {"T"}), "Relu": _get_jax_op(jax.nn.relu, {"T"}), "Relu6": _get_jax_op(jax.nn.relu6, {"T"}), "ReverseV2": _get_jax_op(anp.flip, {"T", "Tidx"}), "RFFT": _get_jax_op( functools.partial(jnp.fft.rfftn, axes=(-1,)), {"Tcomplex", "Treal"}), "RFFT2D": _get_jax_op( functools.partial( jnp.fft.rfftn, axes=(-2, -1,)), {"Tcomplex", "Treal"}), "RFFT3D": _get_jax_op( functools.partial( jnp.fft.rfftn, axes=(-3, -2, -1,)), {"Tcomplex", "Treal"}), "RightShift": _get_jax_op(jnp.right_shift, {"T"}), "Round": _get_jax_op(jnp.round, {"T"}), "Rsqrt": _get_jax_op(jax.lax.rsqrt, {"T"}), "Shape": _get_jax_op(lambda x: np.array(jnp.shape(x)), {"T", "out_type"}), "Sigmoid": _get_jax_op(jax.nn.sigmoid, {"T"}), "Sign": _get_jax_op(jnp.sign, {"T"}), "Sin": _get_jax_op(jnp.sin, {"T"}), "Sinh": _get_jax_op(jnp.sinh, {"T"}), "Size": _get_jax_op(lambda x: np.prod(jnp.shape(x), dtype=np.int32), {"T", "out_type"}), "Softplus": _get_jax_op(jax.nn.softplus, {"T"}), "Sqrt": _get_jax_op(jnp.sqrt, {"T"}), "Square": _get_jax_op(jnp.square, {"T"}), "StopGradient": _get_jax_op(jax.lax.stop_gradient, {"T"}), "Sub": _get_jax_op(anp.subtract, {"T"}), "Tan": _get_jax_op(jnp.tan, {"T"}), "Tanh": _get_jax_op(jnp.tanh, {"T"}), "TensorListFromTensor": _get_jax_op( lambda xs, element_shape: xs, {"element_dtype", "shape_type"}), "Tile": _get_jax_op(anp.tile, {"T", "Tmultiples"}), "UnsortedSegmentMax": _get_jax_op( functools.partial(jax.ops.segment_max, indices_are_sorted=False), {"T", "Tindices", "Tnumsegments"}), "UnsortedSegmentMin": _get_jax_op( functools.partial(jax.ops.segment_min, indices_are_sorted=False), {"T", "Tindices", "Tnumsegments"}), "UnsortedSegmentProd": _get_jax_op( functools.partial(jax.ops.segment_prod, indices_are_sorted=False), {"T", "Tindices", "Tnumsegments"}), "UnsortedSegmentSum": _get_jax_op( functools.partial(jax.ops.segment_sum, indices_are_sorted=False), {"T", "Tindices", "Tnumsegments"}), "Where": _get_jax_op(jnp.argwhere, {"T"}), "ZerosLike": _get_jax_op(jnp.zeros_like, {"T"}), # The assignment logic is handled in _OpNode and convert(). "AssignAddVariableOp": _get_jax_op(jnp.add, {"dtype"}), "AssignSubVariableOp": _get_jax_op(jnp.subtract, {"dtype"}), "AssignVariableOp": _get_jax_op( lambda var, x: x, {"dtype", "validate_shape"}), } def get_parser(op_name: str) -> Callable[..., Callable[..., Any]]: return _jax_ops[op_name] def get_unsupported_operations(op_names: Sequence[str]) -> Set[str]: return {name for name in op_names if name not in _jax_ops} def _register(func: Callable[..., Any], op_name: str): curr_func = _jax_ops.get(op_name, None) if curr_func is None: _jax_ops[op_name] = func else: if curr_func != func: raise ValueError( f"{op_name} is already registered as {curr_func}, received {func}.") return func def register_operation(op_name): return functools.partial(_register, op_name=op_name) class _LibraryFunction(Protocol): # Inputs corresponding to VarHandleOp variable_input_specs: Optional[Tuple[tf.TensorSpec, ...]] = None @dataclasses.dataclass class _HigherOrderFunction: """Base class for higher order ops.""" inner_fn_names: Mapping[str, str] def get_inner_functions( self, library_functions: Mapping[str, Callable[..., Any]] ) -> Mapping[str, Callable[..., Any]]: return {k: library_functions[v] for k, v in self.inner_fn_names.items()} def get_additional_inputs( self, **inner_functions: _LibraryFunction ) -> Tuple[str, ...]: """Get additional input names required by the op.""" del inner_functions return () @register_operation("All") def _all(proto): _check_attrs(proto, {"Tidx", "keep_dims"}) keep_dims = proto.attr["keep_dims"].b return lambda x, axis: anp.all_(x, axis=axis.tolist(), keepdims=keep_dims) @register_operation("Any") def _any(proto): _check_attrs(proto, {"Tidx", "keep_dims"}) keep_dims = proto.attr["keep_dims"].b return lambda x, axis: anp.any_(x, axis=axis.tolist(), keepdims=keep_dims) @register_operation("Assert") def _assert(proto): """Parse an Assert Op.""" _check_attrs(proto, {"T", "summarize"}) logging.warning("Assert has no effect.") def _func(cond, *data): del cond, data # TODO(shaobohou) Use checkify? return _EMPTY_RETURN_VALUE return _func @register_operation("AvgPool") def _avg_pool(proto): """Parse a AvgPool Op.""" _check_attrs( proto, {"T", "padding", "explicit_paddings", "ksize", "strides", "data_format"}) explicit_paddings = tuple(proto.attr["explicit_paddings"].list.i) if explicit_paddings: raise ValueError("explicit_padding in AvgPool not yet supported.") padding = str(proto.attr["padding"].s, "utf-8") ksize = tuple(proto.attr["ksize"].list.i) strides = tuple(proto.attr["strides"].list.i) data_format = str(proto.attr["data_format"].s, "utf-8") if data_format not in ("NHWC", "NCHW"): raise ValueError(f"Found unsupported data format {data_format}.") reduce_window_args = dict( init_value=0., computation=jax.lax.add, window_dimensions=ksize, window_strides=strides, padding=padding) def _func(x: jnp.ndarray) -> jnp.ndarray: pooled = jax.lax.reduce_window(x, **reduce_window_args) if padding == "VALID": window_counts = np.prod(ksize) else: window_counts = jax.lax.reduce_window( jnp.ones_like(x), **reduce_window_args) return pooled / window_counts return _func @register_operation("BatchToSpaceND") def _batch_to_space_nd(proto): """Parse a BatchToSpaceND Op.""" _check_attrs(proto, {"T", "Tblock_shape", "Tcrops"}) def _func( operand: jnp.ndarray, block_shape: jnp.ndarray, crops: jnp.ndarray ) -> jnp.ndarray: batch, *other_shape = list(operand.shape) block_shape = block_shape.tolist() num_spatial = len(block_shape) crops = crops.tolist() spatial_shape = other_shape[:num_spatial] remaining_shape = other_shape[num_spatial:] new_shape = ( block_shape + [batch // np.prod(block_shape)] + spatial_shape + remaining_shape ) reshaped = operand.reshape(new_shape) permuted_axes = [num_spatial] for idx in range(num_spatial): permuted_axes.extend([idx + 1 + num_spatial, idx]) permuted_axes.extend(list(range(num_spatial * 2 + 1, len(new_shape)))) permuted = jnp.transpose(reshaped, axes=permuted_axes) uncropped_shape = [new_shape[num_spatial]] for idx in range(num_spatial): uncropped_shape.append(block_shape[idx] * spatial_shape[idx]) uncropped_shape.extend(remaining_shape) uncropped = permuted.reshape(uncropped_shape) cropped_slice = [slice(None)] for idx in range(num_spatial): cropped_slice.append( slice(crops[idx][0], uncropped_shape[1 + idx] - crops[idx][1]) ) cropped_slice += [slice(None)] * len(remaining_shape) cropped = uncropped[tuple(cropped_slice)] return cropped return _func @register_operation("SpaceToBatchND") def _space_to_batch_nd(proto): """Parse a SpaceToBatchND Op.""" _check_attrs(proto, {"T", "Tblock_shape", "Tpaddings"}) def _func( operand: jnp.ndarray, block_shape: jnp.ndarray, paddings: jnp.ndarray ) -> jnp.ndarray: batch, *other_shape = list(operand.shape) block_shape = block_shape.tolist() num_spatial = len(block_shape) paddings = paddings.tolist() remaining_shape = other_shape[num_spatial:] paddings = [[0, 0]] + paddings + [[0, 0]] * len(remaining_shape) padded = jnp.pad(operand, paddings) padded_shape = padded.shape new_shape = [batch] for idx in range(num_spatial): new_shape.extend( [padded_shape[idx + 1] // block_shape[idx], block_shape[idx]] ) new_shape.extend(remaining_shape) reshaped = padded.reshape(new_shape) permuted_axes = [] for idx in range(num_spatial): permuted_axes.append(idx * 2 + 2) permuted_axes += [0] for idx in range(num_spatial): permuted_axes.append(idx * 2 + 1) permuted_axes.extend(list(range(num_spatial * 2 + 1, len(new_shape)))) permuted = jnp.transpose(reshaped, axes=permuted_axes) flatten_shape = [batch * np.prod(block_shape)] for idx in range(num_spatial): flatten_shape.append(padded_shape[idx + 1] // block_shape[idx]) flatten_shape.extend(remaining_shape) flattened = permuted.reshape(flatten_shape) return flattened return _func @register_operation("BiasAdd") def _bias_add(proto): """Parse a BiasAdd Op.""" _check_attrs(proto, {"T", "data_format"}) data_format = str(proto.attr["data_format"].s, "utf-8") if data_format == "NHWC": expand_axis_fn = lambda x: [d for d in range(x.ndim) if d != x.ndim - 1] elif data_format == "NCHW": # TODO(b/266553458) this seems wrong but matches TF behaviour. expand_axis_fn = lambda x: [d for d in range(x.ndim) if d != 1] else: raise ValueError(f"Found unsupported data format {data_format}.") def _func(value: jnp.ndarray, bias: jnp.ndarray) -> jnp.ndarray: if bias.ndim != 1: raise ValueError( f"Expected `bias` as a 1D array, found array with {bias.ndim} dims.") bias = anp.expand_dims(bias, axis=expand_axis_fn(value)) return anp.add(value, bias) return _func @register_operation("Bitcast") def _bit_cast(proto): _check_attrs(proto, {"T", "type"}) dst_type = tf.as_dtype(proto.attr["type"].type) return lambda x: jax.lax.bitcast_convert_type(x, anp.get_jax_dtype(dst_type)) @register_operation("BroadcastArgs") def _broadcast_args(proto): _check_attrs(proto, {"T"}) return lambda s0, s1: np.array(np.broadcast(np.zeros(s0), np.zeros(s1)).shape) class _CaseOp(_HigherOrderFunction): """Represents a Case Op.""" def __call__(self, branch_index, *operand, **branch_fns): def create_branch(fn): return lambda args: fn(*args) branches = [create_branch(fn) for _, fn in sorted(branch_fns.items())] return jax.lax.switch(branch_index, branches=branches, operand=operand) @register_operation("StatelessCase") @register_operation("Case") def _case(proto): """Parse a Case op.""" _check_attrs(proto, {"Tin", "Tout", "output_shapes", "branches"}) branches = [f.name for f in proto.attr["branches"].list.func] output_shapes = [ [d.size for d in xs.dim] for xs in proto.attr["output_shapes"].list.shape ] del output_shapes return _CaseOp({f"fn_{k:06}": v for k, v in enumerate(branches)}) @register_operation("Cast") def _cast(proto): """Parse a Cast Op.""" _check_attrs(proto, {"SrcT", "DstT", "Truncate"}) src_type = tf.as_dtype(proto.attr["SrcT"].type) dst_type = tf.as_dtype(proto.attr["DstT"].type) truncate = proto.attr["Truncate"].b del src_type if truncate: raise ValueError(f"Cast does not support truncate={truncate}.") def _func(x: jnp.ndarray) -> jnp.ndarray: return anp.asarray(x, dst_type) return _func @register_operation("CheckNumerics") def _check_numerics(proto): """Parse an CheckNumerics Op.""" _check_attrs(proto, {"T", "message"}) message = str(proto.attr["message"].s, "utf-8") def _func(operand: jnp.ndarray) -> jnp.ndarray: if config.get_config("enable_checkify_for_asserts"): checkify.check( jnp.logical_not(jnp.any(jnp.isnan(operand))), f"{message} : Found NaN values.") checkify.check( jnp.logical_not(jnp.any(jnp.isinf(operand))), f"{message} : Found Inf values.") return operand return _func @register_operation("ConjugateTranspose") def _conjugate_transpose(proto): _check_attrs(proto, {"T", "Tperm"}) return lambda x, axes: jax.lax.conj(jnp.transpose(x, axes=axes)) @register_operation("ConcatV2") def _concatenate(proto): """Parse a ConcatV2 Op.""" _check_attrs(proto, {"T", "Tidx", "N"}) num_arrays = proto.attr["N"].i def _func(*args) -> jnp.ndarray: if len(args) != num_arrays + 1: raise ValueError( f"Concatenate expects {num_arrays} args, received {len(args)}.") *inputs, axis = args return anp.concatenate(inputs, axis=axis) return _func @register_operation("Const") def _const(proto): """Parse a Const Op.""" _check_attrs(proto, {"dtype", "value"}) value = tf.make_ndarray(proto.attr["value"].tensor) dtype = value.dtype force_float32 = config.get_config("force_const_float32_to_bfloat16") force_float64 = config.get_config("force_const_float64_to_bfloat16") if ((force_float32 and dtype == np.float32) or (force_float64 and dtype == np.float64)): # NOTE: `jnp.asarray` (rather than the `np` version) cannot be used here; # using it in a jitted context can produce runtime `UnexpectedTracerError`s. bf16_value = np.asarray(value, dtype=jnp.bfloat16) logging.warning("Converting float consts to bfloat16, from %s, to %s.", value, bf16_value) value = bf16_value return lambda: value @register_operation("Conv2D") def _conv2d(proto): """Parse a Conv2D Op.""" _check_attrs( proto, { "T", "padding", "explicit_paddings", "dilations", "strides", "data_format", "use_cudnn_on_gpu" }) explicit_paddings = tuple(proto.attr["explicit_paddings"].list.i) if explicit_paddings: raise ValueError("explicit_padding in Conv2D not yet supported.") padding = str(proto.attr["padding"].s, "utf-8") dilations = tuple(proto.attr["dilations"].list.i) strides = tuple(proto.attr["strides"].list.i) data_format = str(proto.attr["data_format"].s, "utf-8") if data_format == "NHWC": dimension_numbers = ("NHWC", "HWIO", "NHWC") strides = xla_utils.get_conv_sequence(strides, ndim=2, channel_index=-1) dilations = xla_utils.get_conv_sequence(dilations, ndim=2, channel_index=-1) feature_group_count_fn = lambda lhs, rhs: lhs.shape[3] // rhs.shape[2] elif data_format == "NCHW": dimension_numbers = ("NCHW", "HWIO", "NCHW") strides = xla_utils.get_conv_sequence(strides, ndim=2, channel_index=1) dilations = xla_utils.get_conv_sequence(dilations, ndim=2, channel_index=1) feature_group_count_fn = lambda lhs, rhs: lhs.shape[1] // rhs.shape[2] else: raise ValueError(f"Found unsupported data format {data_format}.") _ = proto.attr["use_cudnn_on_gpu"].b def _func(lhs: jnp.ndarray, rhs: jnp.ndarray) -> jnp.ndarray: feature_group_count = feature_group_count_fn(lhs, rhs) return jax.lax.conv_general_dilated( lhs, rhs, window_strides=strides, padding=padding, dimension_numbers=dimension_numbers, rhs_dilation=dilations, feature_group_count=feature_group_count) return _func @register_operation("Conv2DBackpropInput") def _conv2d_backprop_input(proto): """Parse a Conv2DBackpropInput Op.""" _check_attrs( proto, { "T", "padding", "explicit_paddings", "dilations", "strides", "data_format", "use_cudnn_on_gpu" }) explicit_paddings = tuple(proto.attr["explicit_paddings"].list.i) if explicit_paddings: raise ValueError( "explicit_padding in Conv2DBackpropInput not yet supported.") padding = str(proto.attr["padding"].s, "utf-8") dilations = tuple(proto.attr["dilations"].list.i) strides = tuple(proto.attr["strides"].list.i) data_format = str(proto.attr["data_format"].s, "utf-8") if data_format == "NHWC": dimension_numbers = ("NHWC", "HWIO", "NHWC") strides = xla_utils.get_conv_sequence(strides, ndim=2, channel_index=-1) dilations = xla_utils.get_conv_sequence(dilations, ndim=2, channel_index=-1) elif data_format == "NCHW": dimension_numbers = ("NCHW", "HWIO", "NCHW") strides = xla_utils.get_conv_sequence(strides, ndim=2, channel_index=1) dilations = xla_utils.get_conv_sequence(dilations, ndim=2, channel_index=1) else: raise ValueError(f"Found unsupported data format {data_format}.") _ = proto.attr["use_cudnn_on_gpu"].b def _func( input_sizes: jnp.ndarray, filters: jnp.ndarray, out_backprop: jnp.ndarray, ) -> jnp.ndarray: del input_sizes return jax.lax.conv_transpose( out_backprop, filters, strides=strides, padding=padding, rhs_dilation=dilations, transpose_kernel=True, dimension_numbers=dimension_numbers) return _func @register_operation("Cumsum") def _cumsum(proto): """Parse a Cumsum Op.""" _check_attrs(proto, {"T", "Tidx", "exclusive", "reverse"}) exclusive = proto.attr["exclusive"].b reverse = proto.attr["reverse"].b def _func(x: jnp.ndarray, axis: jnp.ndarray) -> jnp.ndarray: axis = axis.item() if reverse: x = anp.flip(x, axis=axis) if exclusive: pad_shape = list(x.shape) pad_shape[axis] = 1 x = anp.concatenate([np.zeros(pad_shape, dtype=x.dtype), x], axis=axis) x = x[(slice(None),) * axis + (slice(0, -1), Ellipsis)] res = anp.cumsum(x, axis=axis) if reverse: res = anp.flip(res, axis=axis) return res return _func @register_operation("Cumprod") def _cumprod(proto): """Parse a Cumprod Op.""" _check_attrs(proto, {"T", "Tidx", "exclusive", "reverse"}) exclusive = proto.attr["exclusive"].b reverse = proto.attr["reverse"].b def _func(x: jnp.ndarray, axis: jnp.ndarray) -> jnp.ndarray: axis = axis.item() if reverse: x = anp.flip(x, axis=axis) if exclusive: pad_shape = list(x.shape) pad_shape[axis] = 1 x = anp.concatenate([np.ones(pad_shape, dtype=x.dtype), x], axis=axis) x = x[(slice(None),) * axis + (slice(0, -1), Ellipsis)] res = anp.cumprod(x, axis=axis) if reverse: res = anp.flip(res, axis=axis) return res return _func @register_operation("DepthwiseConv2dNative") def _depthwise_conv2d(proto): """Parse a DepthwiseConv2d Op.""" _check_attrs(proto, { "T", "strides", "dilations", "padding", "data_format", "explicit_paddings" }) explicit_paddings = tuple(proto.attr["explicit_paddings"].list.i) if explicit_paddings: explicit_paddings = [ tuple(x) for x in np.array(explicit_paddings).reshape(4, 2).tolist() ] padding = explicit_paddings or str(proto.attr["padding"].s, "utf-8") dilations = tuple(proto.attr["dilations"].list.i) strides = tuple(proto.attr["strides"].list.i) data_format = str(proto.attr["data_format"].s, "utf-8") if data_format == "NHWC": if explicit_paddings: padding = padding[1:3] dimension_numbers = ("NHWC", "HWIO", "NHWC") strides = xla_utils.get_conv_sequence(strides, ndim=2, channel_index=-1) dilations = xla_utils.get_conv_sequence(dilations, ndim=2, channel_index=-1) channel_index = -1 elif data_format == "NCHW": if explicit_paddings: padding = padding[2:] dimension_numbers = ("NCHW", "HWIO", "NCHW") strides = xla_utils.get_conv_sequence(strides, ndim=2, channel_index=1) dilations = xla_utils.get_conv_sequence(dilations, ndim=2, channel_index=1) channel_index = 1 else: raise ValueError(f"Found unsupported data format {data_format}.") def _func(lhs: jnp.ndarray, rhs: jnp.ndarray) -> jnp.ndarray: output_dim = rhs.shape[2] * rhs.shape[3] return jax.lax.conv_general_dilated( lhs, jnp.reshape(rhs, rhs.shape[:2] + (1, output_dim)), window_strides=strides, padding=padding, dimension_numbers=dimension_numbers, rhs_dilation=dilations, feature_group_count=lhs.shape[channel_index]) return _func def _div_no_nan_forward(x: jnp.ndarray, y: jnp.ndarray) -> jnp.ndarray: """Computes a safe divide which returns 0 if y (denominator) is zero.""" div = anp.divide(x, y) return jnp.where(y == 0.0, jnp.zeros_like(div), div) @register_operation("DivNoNan") def _div_no_nan(proto): """Parse a DivNoNan op.""" _check_attrs(proto, {"T"}) @jax.custom_gradient def _func( x: jnp.ndarray, y: jnp.ndarray ) -> Tuple[ jnp.ndarray, Callable[[jnp.ndarray], Tuple[jnp.ndarray, jnp.ndarray]], ]: def _grad(g: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]: """Given upstream grad G and a Div op: Z = X/Y, the gradients are. dX = G / Y dY = -G*X / Y^2 = (X/Y) * -G / Y = -G*Z / Y Following tensorflow/tensorflow/c/experimental/gradients/math_grad.cc for handling NaNs. Args: g: Upstream gradient. Returns: forward value: div_no_nan(x, y) grad: Gradient information in TF format. """ output = _div_no_nan_forward(x, y) dx = _div_no_nan_forward(g, y) dy = _div_no_nan_forward(-g * output, y) return dx, dy return _div_no_nan_forward(x, y), _grad return _func @register_operation("Eig") def _eig(proto): """Parse an Eig Op.""" _check_attrs(proto, {"T", "Tout", "compute_v"}) compute_v = proto.attr["compute_v"].b def _func(x: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]: if compute_v: evals, evecs = jnp.linalg.eig(x) else: evals = jnp.linalg.eigvals(x) evecs = jnp.zeros(shape=(), dtype=evals.dtype) # Sorting by eigenvalues to match tf.raw_ops.Eig better. sort_fn = lambda vals, inds: vals[..., inds] for _ in range(len(x.shape) - 2): sort_fn = jax.vmap(sort_fn, in_axes=(0, 0)) einds = jnp.argsort(jnp.absolute(evals), axis=-1) evals = sort_fn(evals, einds) if compute_v: evecs = sort_fn(evecs, einds) return evals, evecs return _func @register_operation("SelfAdjointEigV2") def _eigh(proto): """Parse an SelfAdjointEigV2 Op.""" _check_attrs(proto, {"T", "compute_v"}) compute_v = proto.attr["compute_v"].b def symmetrize(x): return jnp.tril(x) + jnp.swapaxes(jnp.tril(x, -1), -2, -1) def _func(x: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]: if compute_v: evals, evecs = jnp.linalg.eigh(x, symmetrize_input=False) else: # symmetrize_input does not exist for eigvalsh. # See https://github.com/google/jax/issues/9473 evals, evecs = jnp.linalg.eigvalsh(symmetrize(x)), None # Sorting by eigenvalues to tf.raw_ops.Eig better. sort_fn = lambda vals, inds: vals[..., inds] for _ in range(len(x.shape) - 2): sort_fn = jax.vmap(sort_fn, in_axes=(0, 0)) einds = jnp.argsort(evals, axis=-1) evals = sort_fn(evals, einds) if compute_v: evecs = sort_fn(evecs, einds) else: evecs = jnp.zeros(shape=(), dtype=evals.dtype) return evals, evecs return _func @register_operation("Einsum") def _einsum(proto): """Parse an Einsum Op.""" _check_attrs(proto, {"T", "N", "equation"}) num_inputs = proto.attr["N"].i equation = str(proto.attr["equation"].s, "utf-8") def _func(*operands): if len(operands) != num_inputs: raise ValueError( f"Expected {num_inputs} input arrays, found {len(operands)}") return jnp.einsum(equation, *operands) return _func @register_operation("Empty") def _empty(proto): """Parse an Empty op.""" _check_attrs(proto, {"dtype", "init"}) dtype = tf.as_dtype(proto.attr["dtype"].type) init = proto.attr["init"].b def _func(shape: jnp.ndarray) -> jnp.ndarray: return anp.empty(shape=shape, dtype=dtype, init=init) return _func @register_operation("EnsureShape") def _ensure_shape(proto): """Parse an EnsureShape Op.""" _check_attrs(proto, {"T", "shape"}) shape = [dim.size for dim in proto.attr["shape"].shape.dim] def is_compatible(x, s): return x == -1 or s == -1 or x == s def _func(x: jnp.ndarray) -> jnp.ndarray: if len(x.shape) != len(shape) or not all( is_compatible(x, s) for x, s in safe_zip(x.shape, shape) ): raise ValueError(f"Expected shape={shape}, found {x.shape}.") return x return _func @register_operation("ExpandDims") def _expand_dims(proto): """Parse an ExpandDims Op.""" _check_attrs(proto, {"T", "Tdim"}) def _func(arr: jnp.ndarray, axis: jnp.ndarray) -> jnp.ndarray: return anp.expand_dims(arr, axis=axis.tolist()) return _func @register_operation("Fill") def _fill(proto): """Parse an Fill op.""" _check_attrs(proto, {"T", "index_type"}) dtype = tf.as_dtype(proto.attr["T"].type) def _func(shape: jnp.ndarray, fill_value: jnp.ndarray) -> jnp.ndarray: return anp.full(shape=shape, fill_value=fill_value, dtype=dtype) return _func @register_operation("FusedBatchNormV3") @register_operation("FusedBatchNormV2") @register_operation("FusedBatchNorm") def _fused_batch_norm(proto): """Parse a FusedBatchNorm Op.""" _check_attrs(proto, { "T", "U", "data_format", "epsilon", "exponential_avg_factor", "is_training" }) data_format = str(proto.attr["data_format"].s, "utf-8") if data_format == "NHWC": reduce_axis = (0, 1, 2) channel_dim = 3 elif data_format == "NCHW": reduce_axis = (0, 2, 3) channel_dim = 1 else: raise ValueError(f"Found unsupported data format {data_format}.") epsilon = proto.attr["epsilon"].f exponential_avg_factor = proto.attr["exponential_avg_factor"].f one_minus_factor = 1. - exponential_avg_factor is_training = proto.attr["is_training"].b def _func( x: jnp.ndarray, scale: jnp.ndarray, offset: jnp.ndarray, running_mean: jnp.ndarray, running_var: jnp.ndarray, ) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]: batch_mean = jnp.mean(x, axis=reduce_axis) batch_var = jnp.var(x, axis=reduce_axis) est_mean = batch_mean if is_training else running_mean est_var = batch_var if is_training else running_var # Prep for broadcasting. scale = jnp.expand_dims(scale, axis=reduce_axis) offset = jnp.expand_dims(offset, axis=reduce_axis) est_mean = jnp.expand_dims(est_mean, axis=reduce_axis) est_var = jnp.expand_dims(est_var, axis=reduce_axis) inv = scale * jax.lax.rsqrt(est_var + epsilon) norm_x = jnp.asarray((x - est_mean) * inv + offset, x.dtype) if is_training: # Apply Bessel's correction and additional smoothing. ndata = x.size / x.shape[channel_dim] correction = ndata / jnp.maximum(ndata - 1.0, 1.0) running_var = running_var if running_var.size else 0 running_mean = running_mean if running_mean.size else 0 new_var = ( one_minus_factor * running_var + exponential_avg_factor * batch_var * correction) new_mean = ( one_minus_factor * running_mean + exponential_avg_factor * batch_mean) return norm_x, new_mean, new_var else: return norm_x, running_mean, running_var return _func @register_operation("GatherNd") def _gather_nd(proto): """Parse a GatherNd Op.""" _check_attrs(proto, {"Tindices", "Tparams"}) def _func(params: jnp.ndarray, indices: jnp.ndarray) -> jnp.ndarray: return params[tuple(anp.moveaxis(indices, -1, 0))] return _func @register_operation("ResourceGather") @register_operation("GatherV2") def _gather(proto): """Parse a GatherV2 Op.""" _check_attrs(proto, { "Taxis", "Tindices", "Tparams", "batch_dims", "dtype", "validate_indices" }) batch_dims = proto.attr["batch_dims"].i if batch_dims < 0: raise ValueError(f"batch_dims={batch_dims} must be non-negative.") # TODO(b/249826984) Add test for ResourceGather, dtype and validate_indices. def _func( params: jnp.ndarray, indices: jnp.ndarray, axis: ArrayLike = np.array(0, dtype=np.int32), ) -> jnp.ndarray: return anp.gather( params, indices, axis=axis.item(), batch_dims=batch_dims) return _func @dataclasses.dataclass class _IdentityN(_HigherOrderFunction): """Represents a IdentityN Op.""" gradient_op_type: str # For debug, custom_gradient is handled by _Subgraph. def __call__(self, *args): return args @register_operation("IdentityN") def _identity_n(proto): """Parse a IdentityN Op.""" _check_attrs(proto, {"T"}) gradient_op_type = str(proto.attr["_gradient_op_type"].s, "utf-8") if gradient_op_type: logging.info("Found custom gradient %s", gradient_op_type) return _IdentityN({}, gradient_op_type=gradient_op_type) class _IfOp(_HigherOrderFunction): """Represents a If Op.""" def __call__(self, pred, *operand, then_fun, else_fun): true_fun = lambda args: then_fun(*args) false_fun = lambda args: else_fun(*args) return jax.lax.cond( pred, true_fun=true_fun, false_fun=false_fun, operand=operand) @register_operation("StatelessIf") @register_operation("If") def _if(proto): """Parse a If op.""" _check_attrs(proto, { "Tcond", "Tin", "Tout", "output_shapes", "then_branch", "else_branch" }) then_name = proto.attr["then_branch"].func.name else_name = proto.attr["else_branch"].func.name output_shapes = [ [d.size for d in xs.dim] for xs in proto.attr["output_shapes"].list.shape ] del output_shapes return _IfOp(dict(then_fun=then_name, else_fun=else_name)) @register_operation("InplaceAdd") def _inplace_add(proto): """Parse a InplaceAdd op.""" _check_attrs(proto, {"T"}) def _func( inputs: jnp.ndarray, indices: jnp.ndarray, updates: jnp.ndarray, ) -> jnp.ndarray: return jnp.asarray(inputs).at[indices].add(updates) return _func @register_operation("InplaceUpdate") def _inplace_update(proto): """Parse a InplaceUpdate op.""" _check_attrs(proto, {"T"}) def _func( inputs: jnp.ndarray, indices: jnp.ndarray, updates: jnp.ndarray, ) -> jnp.ndarray: return jnp.asarray(inputs).at[indices].set(updates) return _func @register_operation("LeakyRelu") def _leaky_relu(proto): """Parse a LeakyRelu Op.""" _check_attrs(proto, {"T", "alpha"}) alpha = proto.attr["alpha"].f def _func(features: jnp.ndarray) -> jnp.ndarray: return jax.nn.leaky_relu(features, alpha) return _func @register_operation("LogSoftmax") def _log_softmax(proto): _check_attrs(proto, {"T"}) return lambda x: jax.nn.log_softmax(x, axis=-1) @register_operation("MatMul") def _matmul(proto): """Parse a MatMul Op.""" _check_attrs(proto, {"T", "transpose_a", "transpose_b"}) transpose_a = proto.attr["transpose_a"].b transpose_b = proto.attr["transpose_b"].b def _func(a: jnp.ndarray, b: jnp.ndarray) -> jnp.ndarray: if transpose_a: a = jnp.transpose(a) if transpose_b: b = jnp.transpose(b) return jnp.matmul(a, b) return _func @register_operation("BatchMatMulV2") def _batch_matmul(proto): """Parse a BatchMatMul Op.""" _check_attrs(proto, {"T", "adj_x", "adj_y"}) adj_x = proto.attr["adj_x"].b adj_y = proto.attr["adj_y"].b # TODO(b/266553251) Add test for arrays with complex values. def _func(x: jnp.ndarray, y: jnp.ndarray) -> jnp.ndarray: if adj_x: x = jnp.conjugate(jnp.swapaxes(x, -1, -2)) if adj_y: y = jnp.conjugate(jnp.swapaxes(y, -1, -2)) return jnp.matmul(x, y) return _func @register_operation("MatrixDiagV3") def _matrix_diag(proto): """Parse a MatrixDiagV3 op.""" _check_attrs(proto, {"T", "align"}) align = str(proto.attr["align"].s, "utf-8") if align != "RIGHT_LEFT": raise ValueError(f"MatrixDiagV3 does not support `align={align}` yet.") def _func( diagonals: jnp.ndarray, k: int, num_rows: jnp.ndarray, num_cols: jnp.ndarray, padding_value: jnp.ndarray, ) -> jnp.ndarray: if num_rows != -1 or num_cols != -1: raise ValueError(f"MatrixDiagV3 does not yet support num_rows={num_rows} " f"or num_cols={num_cols}.") diag_fn = lambda inputs: jnp.diagflat(inputs, k=k) for _ in range(len(diagonals.shape) - 1): diag_fn = jax.vmap(diag_fn) outputs = diag_fn(diagonals) mask = diag_fn(jnp.ones_like(diagonals, dtype=jnp.bool_)) return jnp.where(mask, outputs, padding_value) return _func @register_operation("MatrixSetDiagV3") def _matrix_set_diag(proto): """Parse a MatrixSetDiagV3 op.""" _check_attrs(proto, {"T", "align"}) align = str(proto.attr["align"].s, "utf-8") if align != "RIGHT_LEFT": raise ValueError(f"MatrixSetDiagV3 does not support `align={align}` yet.") def _func( inputs: jnp.ndarray, diagonals: jnp.ndarray, k: jnp.ndarray, ) -> jnp.ndarray: k = k.item() def diag_fn(inps: jnp.ndarray, diag: jnp.ndarray) -> jnp.ndarray: assert len(inps.shape) == 2, inps.shape assert len(diag.shape) == 1, diag.shape if ((diag.shape[0] + k > inps.shape[1]) or (diag.shape[0] - k > inps.shape[0])): raise ValueError( f"Incompatible inputs shape ({inputs.shape}) and diagonals shape " f"({diagonals.shape}).") return jnp.diagflat(diag, k=k)[:inps.shape[0], :inps.shape[1]] for _ in range(len(diagonals.shape) - 1): diag_fn = jax.vmap(diag_fn) outputs = diag_fn(inputs, diagonals) mask = diag_fn(inputs, jnp.ones_like(diagonals, dtype=jnp.bool_)) return jnp.where(mask, outputs, inputs) return _func @register_operation("MatrixBandPart") def _matrix_band_part(proto): """Parse a MatrixBandPart op.""" _check_attrs(proto, {"T", "Tindex"}) def _func( x: jnp.ndarray, lower: jnp.ndarray, upper: jnp.ndarray, ) -> jnp.ndarray: if len(x.shape) < 2: raise ValueError( f"Expected input of at least rank 2, found {len(x.shape)}") mask_shape = x.shape[-2:] lower = lower.item() + 1 if lower.item() >= 0 else max(mask_shape) mask_lower = jnp.tril(jnp.ones(mask_shape, jnp.int32), -lower) upper = upper.item() + 1 if upper.item() >= 0 else max(mask_shape) mask_upper = jnp.triu(jnp.ones(mask_shape, jnp.int32), upper) return jnp.where((mask_lower + mask_upper) == 0, x, 0) return _func @register_operation("MatrixTriangularSolve") def _matrix_triangular_solve(proto): """Parse an MatrixTriangularSolve Op.""" _check_attrs(proto, {"T", "lower", "adjoint"}) lower = proto.attr["lower"].b adjoint = proto.attr["adjoint"].b def _func(arr: jnp.ndarray, rhs: jnp.ndarray) -> jnp.ndarray: return jax.lax.linalg.triangular_solve( arr, rhs, lower=lower, transpose_a=adjoint, conjugate_a=adjoint, left_side=True) return _func @register_operation("Max") def _max(proto): _check_attrs(proto, {"T", "Tidx", "keep_dims"}) keep_dims = proto.attr["keep_dims"].b def _func(x: jnp.ndarray, axis: jnp.ndarray) -> jnp.ndarray: return anp.max_(x, axis=axis.tolist(), keepdims=keep_dims) return _func @register_operation("MaxPool") def _max_pool(proto): """Parse a MaxPool Op.""" _check_attrs( proto, {"T", "padding", "explicit_paddings", "ksize", "strides", "data_format"}) explicit_paddings = tuple(proto.attr["explicit_paddings"].list.i) if explicit_paddings: raise ValueError("explicit_padding in MaxPool not yet supported.") padding = str(proto.attr["padding"].s, "utf-8") ksize = tuple(proto.attr["ksize"].list.i) strides = tuple(proto.attr["strides"].list.i) data_format = str(proto.attr["data_format"].s, "utf-8") if data_format not in ("NHWC", "NCHW"): raise ValueError(f"Found unsupported data format {data_format}.") def _func(x: jnp.ndarray) -> jnp.ndarray: return jax.lax.reduce_window( x, init_value=-jnp.inf, computation=jax.lax.max, window_dimensions=ksize, window_strides=strides, padding=padding) return _func @register_operation("Mean") def _mean(proto): _check_attrs(proto, {"T", "Tidx", "keep_dims"}) keep_dims = proto.attr["keep_dims"].b def _func(x: jnp.ndarray, axis: jnp.ndarray) -> jnp.ndarray: return jnp.mean(x, axis=axis.tolist(), keepdims=keep_dims) return _func @register_operation("Min") def _min(proto): _check_attrs(proto, {"T", "Tidx", "keep_dims"}) keep_dims = proto.attr["keep_dims"].b def _func(x: jnp.ndarray, axis: jnp.ndarray) -> jnp.ndarray: return anp.min_(x, axis=axis.tolist(), keepdims=keep_dims) return _func @register_operation("OneHot") def _one_hot(proto): """Parse a OneHot Op.""" _check_attrs(proto, {"T", "TI", "axis"}) axis = proto.attr["axis"].i def _func( indices: jnp.ndarray, depth: jnp.ndarray, on_value: jnp.ndarray, off_value: jnp.ndarray, ) -> jnp.ndarray: if axis != -1 and axis != len(indices.shape): raise ValueError(f"OneHot does not support axis={axis} yet, " f"indices.shape={indices.shape}.") mask = jax.nn.one_hot(indices, num_classes=depth.item(), dtype=jnp.int32) return mask * on_value + (1 - mask) * off_value return _func @register_operation("Pack") def _pack(proto): """Parse a Pack op.""" _check_attrs(proto, {"T", "axis", "N"}) num_arrays = proto.attr["N"].i axis = proto.attr["axis"].i def _func(*args) -> jnp.ndarray: if len(args) != num_arrays: raise ValueError( f"Pack expects {num_arrays} args, received {len(args)}.") return anp.stack(args, axis=axis) return _func @register_operation("Pad") def _pad(proto): _check_attrs(proto, {"T", "Tpaddings"}) return lambda x, paddings: jnp.pad(x, pad_width=paddings) @register_operation("PadV2") def _pad_v2(proto): """Parse a PadV2 op.""" _check_attrs(proto, {"T", "Tpaddings"}) def _func( inputs: jnp.ndarray, padding: Union[Sequence[Sequence[int]], Sequence[int], int], constant_values: jnp.ndarray, ) -> jnp.ndarray: return jnp.pad(inputs, pad_width=padding, constant_values=constant_values) return _func class _PartitionedCall(_HigherOrderFunction): """Represents a PartitionedCall Op.""" def __call__(self, *args, inner_fn, rng=None): return inner_fn(*args, rng=rng) def get_additional_inputs( self, **inner_functions: _LibraryFunction ) -> Tuple[str, ...]: """Get additional input names required by the op.""" return self._get_additional_inputs(**inner_functions) def _get_additional_inputs( self, inner_fn: _LibraryFunction ) -> Tuple[str, ...]: return tuple(spec.name for spec in inner_fn.variable_input_specs) @register_operation("StatefulPartitionedCall") @register_operation("PartitionedCall") def _partitioned_call(proto): """Parse a PartitionedCall op.""" _check_attrs(proto, {"f", "Tin", "Tout", "config", "config_proto", "executor_type"}) inner_fn = proto.attr["f"].func.name op_config = str(proto.attr["config"].s, "utf-8") op_config_proto = proto.attr["config_proto"].s executor_type = str(proto.attr["executor_type"].s, "utf-8") del op_config, op_config_proto, executor_type return _PartitionedCall(dict(inner_fn=inner_fn)) @register_operation("Placeholder") def _placeholder(proto): _check_attrs(proto, {"dtype", "shape"}) name = proto.name def _func(): raise ValueError(f"Placeholder `{name}` cannot be evaluated.") return _func @register_operation("PreventGradient") def _prevent_gradient(proto): """Parse a PreventGradient op.""" _check_attrs(proto, {"T", "message"}) message = str(proto.attr["message"].s, "utf-8") @jax.custom_gradient def _raise_func( operand: jnp.ndarray, ) -> Tuple[jnp.ndarray, Callable[..., Any]]: def grad_fn(_): raise LookupError(f"Gradient explicitly prevented on node {proto.name}. " f"Original reason: {message}") return operand, grad_fn def _warn_func(operand: jnp.ndarray) -> jnp.ndarray: logging.warning("PreventGradient ignored on node %s. Original reason: %s", proto.name, message) return operand if config.get_config("raise_on_prevent_gradient"): return _raise_func else: return _warn_func @register_operation("Prod") def _prod(proto): """Parse a Prod op.""" _check_attrs(proto, {"T", "Tidx", "keep_dims"}) keep_dims = proto.attr["keep_dims"].b def _func(x: jnp.ndarray, axis: jnp.ndarray) -> jnp.ndarray: return anp.prod(x, axis=axis.tolist(), keepdims=keep_dims) return _func @register_operation("Qr") def _qr(proto): """Parse an QR Op.""" _check_attrs(proto, {"T", "full_matrices"}) full_matrices = proto.attr["full_matrices"].b def _func(x: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]: return jnp.linalg.qr(x, mode="complete" if full_matrices else "reduced") return _func @register_operation("RandomStandardNormal") def _random_standard_normal(proto): """Parse a RandomStandardNormal op.""" _check_attrs(proto, {"T", "dtype", "seed", "seed2"}) seed = proto.attr["seed"].i seed2 = proto.attr["seed2"].i dtype = tf.as_dtype(proto.attr["dtype"].type) jax_dtype = anp.get_jax_dtype(dtype) if seed != 0 or seed2 != 0: logging.warning( "RandomStandardNormal does not yet support non-zero seeds, found " "seed=%s and seed2=%s.", seed, seed2) return lambda shape, *, rng: jax.random.normal(rng, shape, dtype=jax_dtype) @register_operation("RandomUniform") def _random_uniform(proto): """Parse a RandomUniform op.""" _check_attrs(proto, {"T", "dtype", "seed", "seed2"}) seed = proto.attr["seed"].i seed2 = proto.attr["seed2"].i dtype = tf.as_dtype(proto.attr["dtype"].type) jax_dtype = anp.get_jax_dtype(dtype) if seed != 0 or seed2 != 0: logging.warning( "RandomUniform does not yet support non-zero seeds, found " "seed=%s and seed2=%s.", seed, seed2) return lambda shape, *, rng: jax.random.uniform(rng, shape, dtype=jax_dtype) @register_operation("RandomUniformInt") def _random_uniform_int(proto): """Parse a RandomUniformInt op.""" _check_attrs(proto, {"T", "Tout", "seed", "seed2"}) seed = proto.attr["seed"].i seed2 = proto.attr["seed2"].i dtype = tf.as_dtype(proto.attr["Tout"].type) jax_dtype = anp.get_jax_dtype(dtype) if seed != 0 or seed2 != 0: logging.warning( "RandomUniformInt does not yet support non-zero seeds, found " "seed=%s and seed2=%s.", seed, seed2) def _func(shape, minval, maxval, *, rng): return jax.random.randint( rng, shape, minval=minval, maxval=maxval, dtype=jax_dtype) return _func @register_operation("Range") def _range(proto): """Parse a Range op.""" _check_attrs(proto, {"Tidx"}) dtype = tf.as_dtype(proto.attr["Tidx"].type) def _func( start: jnp.ndarray, limit: jnp.ndarray, delta: jnp.ndarray, ) -> jnp.ndarray: return anp.arange(start, stop=limit, step=delta, dtype=dtype) return _func @register_operation("Reshape") def _reshape(proto): _check_attrs(proto, {"T", "Tshape"}) return lambda x, shape: jnp.reshape(x, newshape=shape) @register_operation("ResizeBilinear") def _resize_bilinear(proto): """Parse a ResizeBilinear op.""" _check_attrs(proto, {"T", "align_corners", "half_pixel_centers"}) align_corners = proto.attr["align_corners"].b half_pixel_centers = proto.attr["half_pixel_centers"].b if align_corners and half_pixel_centers: # Not supported by tf.raw_ops.ResizeBilinear. raise ValueError( "align_corners=True and half_pixel_centers=True are not supported. ") def _func(images: jnp.ndarray, size: jnp.ndarray) -> jnp.ndarray: if len(images.shape) != 4: raise ValueError( "Expected A 4D tensor with shape [batch, height, width, channels], " f"found {images.shape}") inp_batch, inp_height, inp_width, inp_channels = images.shape out_height, out_width = size.tolist() height_scale = out_height / inp_height width_scale = out_width / inp_width if align_corners: if out_height > 1: height_scale = (out_height - 1) / (inp_height - 1) if out_width > 1: width_scale = (out_width - 1) / (inp_width - 1) scale = np.array((height_scale, width_scale)) translation = np.array(([0.0] * 2)) if not half_pixel_centers: translation = translation - scale * 0.5 + 0.5 return jax.image.scale_and_translate( images, shape=(inp_batch, out_height, out_width, inp_channels), spatial_dims=(1, 2), scale=scale, translation=translation, method="linear", antialias=False, precision=config.get_config("resize_bilinear_precision"), ) return _func @register_operation("ResizeNearestNeighbor") def _resize_nearest_neighbor(proto): """Parse a ResizeNearestNeighbor op.""" _check_attrs(proto, {"T", "align_corners", "half_pixel_centers"}) align_corners = proto.attr["align_corners"].b half_pixel_centers = proto.attr["half_pixel_centers"].b if align_corners or not half_pixel_centers: # Not supported by tf.raw_ops.ResizeNearestNeighbor. raise ValueError( "Only align_corners=False and half_pixel_centers=True is supported.") def _func(images: jnp.ndarray, size: jnp.ndarray) -> jnp.ndarray: if len(images.shape) != 4: raise ValueError( "Expected A 4D tensor with shape [batch, height, width, channels], " f"found {images.shape}") inp_batch, _, _, inp_channels = images.shape out_height, out_width = size.tolist() return jax.image.resize( images, shape=(inp_batch, out_height, out_width, inp_channels), method=jax.image.ResizeMethod.NEAREST, ) return _func @register_operation("Roll") def _roll(proto): """Parse a Roll Op.""" _check_attrs(proto, {"T", "Tshift", "Taxis"}) def _func( operand: jnp.ndarray, shift: jnp.ndarray, axis: jnp.ndarray, ) -> jnp.ndarray: return anp.roll(operand, shift=shift.tolist(), axis=axis.tolist()) return _func @register_operation("ScatterNd") def _scatter_nd(proto): """Parse a ScatterNd op.""" _check_attrs(proto, {"T", "Tindices"}) def _func( indices: jnp.ndarray, updates: jnp.ndarray, shape: jnp.ndarray, ) -> jnp.ndarray: return anp.scatter_nd(indices, updates, shape) return _func @register_operation("SelectV2") @register_operation("Select") def _select(proto): """Parse a Select op.""" _check_attrs(proto, {"T"}) def _func( conds: jnp.ndarray, x: jnp.ndarray, y: jnp.ndarray, ) -> jnp.ndarray: conds = anp.expand_dims(conds, axis=tuple(range(conds.ndim, x.ndim))) return anp.where(conds, x, y) return _func @register_operation("Slice") def _slice(proto): """Parse a Slice Op.""" _check_attrs(proto, {"T", "Index"}) def _func( x: jnp.ndarray, begins: jnp.ndarray, sizes: jnp.ndarray, ) -> jnp.ndarray: """`begins` and `sizes` must be concrete arrays.""" slices = [slice(b, b + s) for b, s in safe_zip(begins, sizes)] return x[tuple(slices)] return _func @register_operation("Softmax") def _softmax(proto): _check_attrs(proto, {"T"}) return lambda x: jax.nn.softmax(x, axis=-1) @register_operation("SparseSoftmaxCrossEntropyWithLogits") def _sparse_softmax_cross_entropy_with_logits(proto): """Parse a SparseSoftmaxCrossEntropyWithLogits Op.""" _check_attrs(proto, {"T", "Tlabels"}) def cross_entropy(xs, ys): return -1.0 * jnp.take_along_axis( jax.nn.log_softmax(xs, axis=-1), ys[:, jnp.newaxis], axis=-1)[:, 0] def _func(features: jnp.ndarray, labels: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]: loss = cross_entropy(features, labels) vjp_outputs, vjp_fn = jax.vjp(cross_entropy, features, labels) grads = vjp_fn(jnp.ones(vjp_outputs.shape))[0] return loss, grads return _func @register_operation("Split") def _split(proto): """Parse a Split op.""" _check_attrs(proto, {"T", "num_split"}) num_split = proto.attr["num_split"].i return lambda axis, inputs: anp.split(inputs, num_split, axis=axis) @register_operation("SplitV") def _splitv(proto): """Parse a SplitV op.""" _check_attrs(proto, {"T", "Tlen", "num_split"}) num_split = proto.attr["num_split"].i def _func( value: jnp.ndarray, size_splits: jnp.ndarray, axis: jnp.ndarray, ) -> jnp.ndarray: assert size_splits.shape[0] == num_split, (size_splits.shape[0], num_split) splits = size_splits.tolist() axis = axis.item() defined_size = sum([x for x in splits if x >= 0]) splits = [x if x >= 0 else value.shape[axis] - defined_size for x in splits] indices = np.cumsum(np.array(splits), axis=0) assert indices[-1] == value.shape[axis] return anp.split(value, indices[:-1], axis=axis) return _func @register_operation("SquaredDifference") def _squared_difference(proto): _check_attrs(proto, {"T"}) return lambda x1, x2: jnp.square(x1 - x2) @register_operation("Squeeze") def _squeeze(proto): _check_attrs(proto, {"T", "squeeze_dims"}) axis = tuple(proto.attr["squeeze_dims"].list.i) return lambda x: anp.squeeze(x, axis=axis) @register_operation("StatelessRandomGetAlg") def _stateless_random_get_alg(proto): _check_attrs(proto, set({})) # Only jax.lax.rng_bit_generator allows users to choose the algorithm. # So this will most likely be ignored. return lambda: tf.random.Algorithm.AUTO_SELECT.value @register_operation("StatelessRandomGetKeyCounter") def _stateless_random_get_key_counter(proto): _check_attrs(proto, {"T", "Tseed"}) def _func(seed: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]: assert seed.shape == (2,), seed.shape seed = jnp.sum(seed) # An arbitrary choice. return jax.random.PRNGKey(seed), jnp.array(0, dtype=jnp.int32) return _func @register_operation("StatelessMultinomial") def _stateless_multinomial(proto): """Parse a StatelessMultinomial op.""" _check_attrs(proto, {"T", "Tseed", "output_dtype"}) dtype = tf.as_dtype(proto.attr["output_dtype"].type) jax_dtype = anp.get_jax_dtype(dtype) def _func( logits: jnp.ndarray, num_samples: jnp.ndarray, seed: jnp.ndarray, ) -> jnp.ndarray: assert seed.shape == (2,), seed.shape seed = seed.astype(jnp.uint32) shape = (num_samples.item(), logits.shape[0]) samples = jax.random.categorical(seed, logits, shape=shape) return samples.astype(jax_dtype).transpose([1, 0]) return _func @register_operation("StatelessRandomNormalV2") def _stateless_random_normal_v2(proto): """Parse a StatelessRandomNormalV2 op.""" _check_attrs(proto, {"T", "Tshape", "dtype"}) dtype = tf.as_dtype(proto.attr["dtype"].type) jax_dtype = anp.get_jax_dtype(dtype) def _func( shape: Sequence[int], key: jnp.ndarray, counter: jnp.ndarray, alg: jnp.ndarray, ) -> jnp.ndarray: del counter, alg # TODO(b/266553394) combine key and counter? return jax.random.normal(key=key, shape=shape, dtype=jax_dtype) return _func @register_operation("StatelessRandomUniformV2") def _stateless_random_uniform_v2(proto): """Parse a StatelessRandomNormalV2 op.""" _check_attrs(proto, {"T", "Tshape", "dtype"}) dtype = tf.as_dtype(proto.attr["dtype"].type) jax_dtype = anp.get_jax_dtype(dtype) def _func( shape: Sequence[int], key: jnp.ndarray, counter: jnp.ndarray, alg: jnp.ndarray, ) -> jnp.ndarray: del counter, alg # TODO(b/266553394) combine key and counter? return jax.random.uniform(key=key, shape=shape, dtype=jax_dtype) return _func @register_operation("StatelessRandomUniformFullIntV2") @register_operation("StatelessRandomUniformIntV2") def _stateless_random_uniform_int_v2(proto): """Parse a StatelessRandomUniformIntV2 op.""" _check_attrs(proto, {"T", "Tshape", "dtype"}) dtype = tf.as_dtype(proto.attr["dtype"].type) jax_dtype = anp.get_jax_dtype(dtype) def _func( shape: jnp.ndarray, key: jnp.ndarray, counter: jnp.ndarray, alg: jnp.ndarray, minval: Union[jnp.ndarray, int] = jnp.iinfo(jax_dtype).min, maxval: Union[jnp.ndarray, int] = jnp.iinfo(jax_dtype).max, ) -> jnp.ndarray: del counter, alg # TODO(b/266553394) combine key and counter? return jax.random.randint( key=key, shape=shape.tolist(), minval=minval, maxval=maxval, dtype=jax_dtype, ) return _func def _split_args( args: Sequence[Any], preds: Sequence[bool], ) -> Tuple[Tuple[Tuple[int, Any]], ...]: """Split args into two lists based on some predicates.""" assert len(args) == len(preds), (len(args), len(preds)) true_args = [] false_args = [] for idx, (arg, pred) in enumerate(safe_zip(args, preds)): if pred: true_args.append((idx, arg)) else: false_args.append((idx, arg)) return tuple(true_args), tuple(false_args) def _merge_args( const_args: Sequence[Tuple[int, Any]], trace_args: Sequence[Tuple[int, Any]], ) -> Tuple[Any]: args = [None] * (len(const_args) + len(trace_args)) for idx, arg in tuple(const_args) + tuple(trace_args): args[idx] = arg assert all(x is not None for x in args) return tuple(args) class _StatelessWhile(_HigherOrderFunction): """Represents a StatelessWhile Op.""" def __call__(self, *all_args, cond_fun, body_fun, rng=None): # Pull captured arguments out of inputs to cond and body. const_idxs_args, trace_idxs_args = _split_args( all_args, body_fun.output_is_input) trace_idxs, trace_args = safe_zip(*trace_idxs_args) def real_cond(args): *cond_args, rng = args cond_idxs_args = tuple(safe_zip(trace_idxs, cond_args)) cond_args = _merge_args(const_idxs_args, cond_idxs_args) _, cond_key, _ = [None] * 3 if rng is None else jax.random.split(rng, 3) outputs = cond_fun(*cond_args, rng=cond_key) if len(outputs) != 1: raise ValueError( f"Expected cond_fun to return a single value, found {outputs}") return outputs[0] def real_body(args): *body_args, rng = args body_idxs_args = tuple(safe_zip(trace_idxs, body_args)) body_args = _merge_args(const_idxs_args, body_idxs_args) key, _, body_key = [None] * 3 if rng is None else jax.random.split(rng, 3) outputs = body_fun(*body_args, rng=body_key) outputs = tuple([outputs[idx] for idx in trace_idxs]) return outputs + (key,) def maybe_initialise(arg, spec): # TensorList inputs can be uninitialized. if isinstance(spec, jax.ShapeDtypeStruct) and arg.size == 0: return jnp.zeros(shape=spec.shape, dtype=spec.dtype) else: return arg output_specs = jax.eval_shape(real_body, trace_args + (rng,)) trace_args = tuple( maybe_initialise(arg, spec) for arg, spec in safe_zip(trace_args, output_specs[:-1])) outputs = jax.lax.while_loop(real_cond, real_body, trace_args + (rng,)) *outputs, _ = outputs # Drop rng. outputs = _merge_args( const_idxs_args, tuple(safe_zip(trace_idxs, outputs)) ) assert len(outputs) == len(all_args), (len(outputs), len(all_args)) return outputs @register_operation("StatelessWhile") @register_operation("While") def _stateless_while(proto): """Parse a StatelessWhile op.""" _check_attrs(proto, {"T", "body", "cond", "parallel_iterations", "output_shapes"}) body_name = proto.attr["body"].func.name cond_name = proto.attr["cond"].func.name parallel_iterations = proto.attr["parallel_iterations"].i output_shapes = [ [d.size for d in xs.dim] for xs in proto.attr["output_shapes"].list.shape ] del parallel_iterations, output_shapes return _StatelessWhile(dict(cond_fun=cond_name, body_fun=body_name)) @register_operation("StridedSlice") def _strided_slice(proto): """Parse a StridedSlice Op.""" _check_attrs( proto, { "T", "Index", "begin_mask", "ellipsis_mask", "end_mask", "new_axis_mask", "shrink_axis_mask" }) def unpack(x): return [(1 if(x & (1 << v)) else 0) for v in range(32)] begin_mask = unpack(proto.attr["begin_mask"].i) ellipsis_mask = unpack(proto.attr["ellipsis_mask"].i) end_mask = unpack(proto.attr["end_mask"].i) new_axis_mask = unpack(proto.attr["new_axis_mask"].i) shrink_axis_mask = unpack(proto.attr["shrink_axis_mask"].i) def _func( x: jnp.ndarray, begin: jnp.ndarray, end: jnp.ndarray, strides: jnp.ndarray, ) -> jnp.ndarray: """`begin`, `end` and `strides` must be concrete arrays.""" num_specs = len(begin) inserted = ( len(x.shape) + sum(new_axis_mask) - (num_specs - sum(ellipsis_mask))) # Rebuild slices. dim = 0 slices = [] for idx in range(num_specs): if new_axis_mask[idx] == 1: slices.append(jnp.newaxis) elif ellipsis_mask[idx] == 1: slices.append(Ellipsis) dim += inserted else: if shrink_axis_mask[idx] == 1: slices.append(begin[idx]) else: beg_dim = begin[idx] if begin_mask[idx] == 0 else None end_dim = end[idx] if end_mask[idx] == 0 else None stride = strides[idx] x_dim = x.shape[dim] if (stride == 1 and jax.core.symbolic_equal_dim(beg_dim or 0, 0) and jax.core.symbolic_equal_dim(x_dim if end_dim is None else end_dim, x_dim)): slices.append(slice(None, None, None)) else: slices.append(slice(beg_dim, end_dim, stride)) dim += 1 # TODO(b/266553742) Handle stride=1 slicing along polymoprhic dimensions. return x[tuple(slices)] return _func @register_operation("Sum") def _sum(proto): _check_attrs(proto, {"T", "Tidx", "keep_dims"}) keep_dims = proto.attr["keep_dims"].b def _func(x: jnp.ndarray, axis: jnp.ndarray) -> jnp.ndarray: return anp.sum_(x, axis=axis.tolist(), keepdims=keep_dims) return _func @register_operation("Svd") def _svd(proto): """Parse an Svd Op.""" _check_attrs(proto, {"T", "compute_uv", "full_matrices"}) compute_uv = proto.attr["compute_uv"].b full_matrices = proto.attr["full_matrices"].b def _func( x: jnp.ndarray, ) -> Tuple[jnp.ndarray, Optional[jnp.ndarray], Optional[jnp.ndarray]]: res = jnp.linalg.svd( x, compute_uv=compute_uv, full_matrices=full_matrices) if compute_uv: u, s, vh = res v = jnp.conjugate(jnp.swapaxes(vh, -1, -2)) else: u, s, v = None, res, None return s, u, v return _func @register_operation("TensorListGetItem") def _tensor_list_get_item(proto): """Parse an TensorListGetItem Op.""" _check_attrs(proto, {"element_dtype"}) dtype = tf.as_dtype(proto.attr["element_dtype"].type) dtype = anp.get_jax_dtype(dtype) def _func( xs: jnp.ndarray, index: jnp.ndarray, element_shape: jnp.ndarray, ) -> jnp.ndarray: assert xs.dtype == dtype if xs.size == 0: return np.zeros(element_shape, dtype=dtype) if isinstance(index, jax.Array): xs = jnp.array(xs) return xs[index] return _func def _create_tensor_list( num_elements: int, shape: Union[int, List[int]], dtype: Any, ) -> np.ndarray: """Create a tensor corresponding to a stacked tensor list.""" if not isinstance(shape, list): shape = [shape] # shape can be unspecified as -1. shape = [max(0, sz) for sz in shape] return np.zeros([num_elements] + shape, dtype=dtype) @register_operation("TensorListReserve") def _tensor_list_reserve(proto): """Parse an TensorListReserve Op.""" _check_attrs(proto, {"element_dtype", "shape_type"}) dtype = tf.as_dtype(proto.attr["element_dtype"].type) dtype = anp.get_jax_dtype(dtype) def _func(shape: jnp.ndarray, num_elements: jnp.ndarray) -> ArrayLike: return _create_tensor_list( num_elements.item(), shape.tolist(), dtype=dtype) return _func @register_operation("TensorListSetItem") def _tensor_list_set_item(proto): """Parse an TensorListSetItem Op.""" _check_attrs(proto, {"element_dtype", "resize_if_index_out_of_bounds"}) if proto.attr["resize_if_index_out_of_bounds"].b: raise ValueError( "resize_if_index_out_of_bounds=True in TensorListSetItem is not yet" " supported." ) dtype = tf.as_dtype(proto.attr["element_dtype"].type) dtype = anp.get_jax_dtype(dtype) def _func( xs: jnp.ndarray, index: jnp.ndarray, item: jnp.ndarray, ) -> jnp.ndarray: assert xs.shape if xs.size == 0: xs = _create_tensor_list(xs.shape[0], list(item.shape), dtype=dtype) if isinstance(index, jax.Array): xs = jnp.array(xs) return xs.at[index].set(item) return _func @register_operation("TensorListStack") def _tensor_list_stack(proto): """Parse an TensorListStack Op.""" _check_attrs(proto, {"element_dtype", "num_elements"}) dtype = tf.as_dtype(proto.attr["element_dtype"].type) dtype = anp.get_jax_dtype(dtype) def _func(xs: jnp.ndarray, shape: jnp.ndarray) -> ArrayLike: if xs.size == 0: xs = _create_tensor_list(xs.shape[0], shape.tolist(), dtype=dtype) return xs return _func @register_operation("TensorScatterUpdate") def _tensor_scatter_update(proto): """Parse an TensorScatterUpdate Op.""" _check_attrs(proto, {"T", "Tindices"}) def _func( operand: jnp.ndarray, indices: jnp.ndarray, updates: jnp.ndarray, ) -> jnp.ndarray: dimension_numbers = jax.lax.ScatterDimensionNumbers( range(1, updates.ndim), range(indices.shape[-1]), range(indices.shape[-1])) return jax.lax.scatter( operand, indices, updates, dimension_numbers=dimension_numbers) return _func @register_operation("TopKV2") def _top_k(proto): _check_attrs(proto, {"T", "sorted", "Tk", "index_type"}) sorted_arg = proto.attr["sorted"].b if not sorted_arg: raise ValueError("sorted=False in TopKV2 is not yet supported.") return jax.lax.top_k @register_operation("Transpose") def _transpose(proto): _check_attrs(proto, {"T", "Tperm"}) return lambda x, axes: jnp.transpose(x, axes=axes) @register_operation("Unpack") def _unpack(proto): """Parse a Unpack op.""" _check_attrs(proto, {"T", "axis", "num"}) axis = proto.attr["axis"].i num = proto.attr["num"].i def _func(x: jnp.ndarray) -> List[jnp.ndarray]: if x.shape[axis] != num: raise ValueError("Unpack expects dimension of {num} for axis={axis}, " "found {x.shape[axis]}, shape={x.shape}") return [anp.squeeze(v, axis=axis) for v in anp.split(x, num, axis=axis)] return _func # TODO(b271811043) Add unit test. @register_operation("VarHandleOp") def _var_handle(proto): _check_attrs( proto, {"shared_name", "container", "allowed_devices", "shape", "dtype", "debug_name"}) def _func(): raise ValueError(f"VarHandleOp `{proto.name}` cannot be evaluated.") return _func @register_operation("VariableV2") def _variable_v2(proto): _check_attrs(proto, {"container", "dtype", "shared_name", "shape"}) name = proto.name def _func(): raise ValueError(f"VariableV2 `{name}` cannot be evaluated.") return _func @register_operation("XlaConvV2") @register_operation("XlaConv") def _xla_conv(proto): """Parse a XlaConv op.""" _check_attrs( proto, { "T", "LhsT", "RhsT", "Tindices", "dimension_numbers", "precision_config", "preferred_element_type", "batch_group_count" }) dimension_numbers = xla_utils.convolution_dimension_numbers_from_proto( proto.attr["dimension_numbers"].s) precision_config = xla_utils.precision_config_from_proto( proto.attr["precision_config"].s) batch_group_count = proto.attr["batch_group_count"].i if "preferred_element_type" in proto.attr: dst_dtype = tf.as_dtype(proto.attr["preferred_element_type"].type) dst_dtype = anp.get_jax_dtype(dst_dtype) else: dst_dtype = None def _func( lhs: jnp.ndarray, rhs: jnp.ndarray, strides: jnp.ndarray, padding: jnp.ndarray, lhs_dilation: jnp.ndarray, rhs_dilation: jnp.ndarray, feature_group_count: jnp.ndarray, ) -> jnp.ndarray: return jax.lax.conv_general_dilated( lhs, rhs, window_strides=strides.tolist(), padding=[tuple(v) for v in padding], lhs_dilation=lhs_dilation.tolist(), rhs_dilation=rhs_dilation.tolist(), dimension_numbers=dimension_numbers, feature_group_count=feature_group_count.item(), batch_group_count=batch_group_count or 1, precision=precision_config, preferred_element_type=dst_dtype) return _func @register_operation("XlaDotV2") @register_operation("XlaDot") def _xla_dot(proto): """Parse a XlaDot op.""" _check_attrs( proto, { "T", "LhsT", "RhsT", "dimension_numbers", "precision_config", "preferred_element_type" }) dimension_numbers = xla_utils.dot_dimension_numbers_from_proto( proto.attr["dimension_numbers"].s) precision_config = xla_utils.precision_config_from_proto( proto.attr["precision_config"].s) if "preferred_element_type" in proto.attr: dst_dtype = tf.as_dtype(proto.attr["preferred_element_type"].type) dst_dtype = anp.get_jax_dtype(dst_dtype) else: dst_dtype = None def _func(lhs: jnp.ndarray, rhs: jnp.ndarray) -> jnp.ndarray: return jax.lax.dot_general( lhs, rhs, dimension_numbers, precision_config, preferred_element_type=dst_dtype) return _func @register_operation("XlaDynamicSlice") def _xla_dynamic_slice(proto): """Parse a XlaDynamicSlice op.""" _check_attrs(proto, {"T", "Tindices"}) return jax.lax.dynamic_slice @register_operation("XlaDynamicUpdateSlice") def _xla_dynamic_update_slice(proto): """Parse a XlaDynamicUpdateSlice op.""" _check_attrs(proto, {"T", "Tindices"}) return jax.lax.dynamic_update_slice @register_operation("XlaGather") def _xla_gather(proto): """Parse a XlaGather op.""" _check_attrs(proto, {"T", "Tindices", "dimension_numbers", "indices_are_sorted"}) dimension_numbers = xla_utils.gather_dimension_numbers_from_proto( proto.attr["dimension_numbers"].s) # This should exist on the XLA op, even though it's not exposed by JAX. indices_are_sorted = proto.attr["indices_are_sorted"].b del indices_are_sorted def _func( operand: jnp.ndarray, start_indices: jnp.ndarray, slice_indices: jnp.ndarray, ) -> jnp.ndarray: return jax.lax.gather(operand, start_indices, dimension_numbers, slice_indices) return _func @register_operation("XlaOptimizationBarrier") def _xla_optimization_barrier(proto): """Parse a XlaOptimizationBarrier op.""" _check_attrs(proto, {"T"}) def _func(*operands: jnp.ndarray) -> Tuple[jnp.ndarray, ...]: # TODO(b/241584320) Note this does not reproduce the remat transform in the # forward pass, which may require some heurstics when parsing the graphdef. return lax_control_flow.optimization_barrier_p.bind(*operands) return _func @register_operation("XlaPad") def _xla_pad(proto): """Parse a XlaPad op.""" _check_attrs(proto, {"T", "Tindices"}) def _func( operand: jnp.ndarray, padding_value: jnp.ndarray, padding_low: jnp.ndarray, padding_high: jnp.ndarray, padding_interior: jnp.ndarray,) -> jnp.ndarray: padding_config = np.stack([padding_low, padding_high, padding_interior], axis=0) padding_config = [tuple(x) for x in padding_config.transpose().tolist()] return jax.lax.pad(operand, padding_value, padding_config) return _func @register_operation("XlaReducePrecision") def _xla_reduce_precision(proto): """Parse a XlaReducePrecision op.""" _check_attrs(proto, {"T", "exponent_bits", "mantissa_bits"}) exponent = proto.attr["exponent_bits"].i mantissa = proto.attr["mantissa_bits"].i def _func(operand: jnp.ndarray) -> jnp.ndarray: return jax.lax.reduce_precision(operand, exponent, mantissa) return _func @register_operation("XlaSharding") def _xla_sharding(proto): """Parse a XlaSharding op.""" _check_attrs(proto, {"T", "sharding", "unspecified_dims"}) unspecified_dims = tuple(proto.attr["unspecified_dims"].list.i) if unspecified_dims: raise ValueError(f"{unspecified_dims=} is not yet supported.") sharding_str = proto.attr["sharding"].s # Return identity if sharding annotation is empty. if not sharding_str: return lambda x: x sharding = xla_client.OpSharding() sharding.ParseFromString(sharding_str) jax_sharding = jax.sharding.GSPMDSharding(jax.devices(), sharding) # TODO(b/235450851) Remove jax.jit once wsc is usable outside of jit. @jax.jit def _func(x: jnp.ndarray) -> jnp.ndarray: return jax.lax.with_sharding_constraint(x, jax_sharding) return _func def _maybe_get_jaxpreqn( jaxpr: jax.core.ClosedJaxpr) -> Optional[jax.core.JaxprEqn]: def is_all_vars(vs): return all([isinstance(v, jax.core.Var) for v in vs]) if (len(jaxpr.eqns) == 1 and is_all_vars(jaxpr.jaxpr.invars) and is_all_vars(jaxpr.jaxpr.outvars) and is_all_vars(jaxpr.eqns[0].invars) and is_all_vars(jaxpr.eqns[0].outvars)): return jaxpr.eqns[0] return None @dataclasses.dataclass class _XlaVariadicReduce(_HigherOrderFunction): """Represents a XlaVariadicReduce Op.""" dimensions: Sequence[int] def __call__(self, *args: jnp.ndarray, reducer: Callable[..., Any]): num_args = len(args) operands = args[:(num_args//2)] init_values = args[(num_args//2):] assert len(operands) == len(init_values) reducer_fn = lambda xs, ys: reducer(*xs, *ys) return jax.lax.reduce(operands, init_values, reducer_fn, self.dimensions) @register_operation("XlaVariadicReduceV2") def _xla_variadic_reduce(proto): """Parse a XlaVariadicReduceV2 op.""" _check_attrs(proto, {"T", "reducer", "dimensions_to_reduce"}) reducer = proto.attr["reducer"].func.name dimensions = tuple(proto.attr["dimensions_to_reduce"].list.i) return _XlaVariadicReduce(dict(reducer=reducer), dimensions=dimensions) @dataclasses.dataclass class _XlaVariadicSort(_HigherOrderFunction): """Represents a XlaVariadicSort Op.""" is_stable: bool def _compute_num_keys( self, dtypes: Sequence[jnp.dtype], comparator: Callable[..., Any], ) -> int: """Infer num_keys from the comparator and operands.""" def get_operands(): return sum([[jnp.array(0, dtype)] * 2 for dtype in dtypes], []) for idx in range(len(dtypes)): operands = get_operands() is_eq, = comparator(*operands) operands[idx * 2 + 1] = jnp.array(1, dtypes[idx]) is_lt, = comparator(*operands) if idx == 0 and (not is_lt or is_eq): raise ValueError( "Only less-than comparator is supported for XlaVariadicSort.") if is_lt: num_keys = idx + 1 else: break return num_keys def __call__(self, *args: jnp.ndarray, comparator: Callable[..., Any]): operands = args[:-1] dimension = args[-1].item() with jax.ensure_compile_time_eval(): dtypes = [x.dtype for x in operands] num_keys = self._compute_num_keys(dtypes, comparator) return jax.lax.sort( operands, dimension=dimension, is_stable=self.is_stable, num_keys=num_keys) @register_operation("XlaVariadicSort") def _xla_variadic_sort(proto): """Parse a XlaVariadicSort op.""" _check_attrs(proto, {"T", "comparator", "is_stable"}) comparator = proto.attr["comparator"].func.name is_stable = proto.attr["is_stable"].b logging.warning( "Support for XlaVariadicSort is limited, current implementation assumes " "the op is generated by `jax2tf.convert(jax.lax.sort)` and does not " "support arbitrary comparators") return _XlaVariadicSort(dict(comparator=comparator), is_stable=is_stable) # Taken from https://github.com/google/jax/blob/main/jax/_src/lax/lax.py#L1056 def _get_max_identity(dtype): if jax.dtypes.issubdtype(dtype, np.inexact): return np.array(-np.inf, dtype) elif jax.dtypes.issubdtype(dtype, np.integer): return np.array(jax.dtypes.iinfo(dtype).min, dtype) elif jax.dtypes.issubdtype(dtype, np.bool_): return np.array(False, np.bool_) # Taken from https://github.com/google/jax/blob/main/jax/_src/lax/lax.py#L1064 def _get_min_identity(dtype): if jax.dtypes.issubdtype(dtype, np.inexact): return np.array(np.inf, dtype) elif jax.dtypes.issubdtype(dtype, np.integer): return np.array(jax.dtypes.iinfo(dtype).max, dtype) elif jax.dtypes.issubdtype(dtype, np.bool_): return np.array(True, np.bool_) class _XlaReduceWindow(_HigherOrderFunction): """Represents a XlaReduceWindow Op.""" def __call__( self, operand: jnp.ndarray, init_value: jnp.ndarray, window_dimensions: jnp.ndarray, window_strides: jnp.ndarray, base_dilation: jnp.ndarray, window_dilation: jnp.ndarray, padding: jnp.ndarray, *, computation: Callable[..., Any], ): window_dimensions = window_dimensions.tolist() window_strides = window_strides.tolist() padding = padding.tolist() base_dilation = base_dilation.tolist() window_dilation = window_dilation.tolist() # Pattern matching computations that can be specialized. primitives = { jax.lax.max_p: jax.lax.max, jax.lax.min_p: jax.lax.min, jax.lax.add_p: jax.lax.add, jax.lax.mul_p: jax.lax.mul, } computation_jaxpr = jax.make_jaxpr(computation)(init_value, init_value) computation_eqn = _maybe_get_jaxpreqn(computation_jaxpr) if computation_eqn is not None and computation_eqn.primitive in primitives: computation_fn = primitives[computation_eqn.primitive] else: computation_fn = lambda *args: computation(*args)[0] logging.info("Calling reduce_window with the following computation:\n%s", computation_jaxpr) def infer_cumulative_reduction(): ndims = len(window_dimensions) assert ndims == operand.ndim reduce_axis = np.argmax(window_dimensions) reduce_dim = operand.shape[reduce_axis] dims = [1] * ndims dims[reduce_axis] = reduce_dim if not (window_dimensions == dims and window_strides == [1] * ndims and base_dilation == [1] * ndims and window_dilation == [1] * ndims): return (None, None, None) # Determine direction of reduction. normal_padding = [[0, 0]] * ndims normal_padding[reduce_axis] = [reduce_dim - 1, 0] reverse_padding = [[0, 0]] * ndims reverse_padding[reduce_axis] = [0, reduce_dim - 1] reverse = None if padding == normal_padding: reverse = False elif padding == reverse_padding: reverse = True else: return (None, None, None) if computation_fn is jax.lax.add and init_value == 0: return (jax.lax.cumsum, reduce_axis, reverse) elif computation_fn is jax.lax.mul and init_value == 1: return (jax.lax.cumprod, reduce_axis, reverse) elif (computation_fn is jax.lax.max and init_value == _get_max_identity(operand.dtype)): return (jax.lax.cummax, reduce_axis, reverse) elif (computation_fn is jax.lax.min and init_value == _get_min_identity(operand.dtype)): return (jax.lax.cummin, reduce_axis, reverse) else: return (None, None, None) reducer, reduce_axis, reverse = infer_cumulative_reduction() if reducer and config.get_config("infer_cumulative_reduction_from_jax2tf"): return reducer(operand, axis=reduce_axis, reverse=reverse) else: return jax.lax.reduce_window( operand, init_value, computation=computation_fn, window_dimensions=window_dimensions, window_strides=window_strides, padding=[tuple(v) for v in padding], base_dilation=base_dilation, window_dilation=window_dilation) @register_operation("XlaReduceWindow") def _xla_reduce_window(proto): """Parse a XlaReduceWindow op.""" _check_attrs(proto, {"T", "Tindices", "computation"}) computation = proto.attr["computation"].func.name return _XlaReduceWindow(dict(computation=computation)) @register_operation("XlaRngBitGenerator") def _xla_rng_bit_generator(proto): """Parse a XlaRngBitGenerator op.""" _check_attrs(proto, {"Tshape", "dtype"}) dtype = tf.as_dtype(proto.attr["dtype"].type) jax_dtype = anp.get_jax_dtype(dtype) if jax_dtype != jnp.uint32: raise ValueError( f"XlaRngBitGenerator currently only supports uint32, found{jax_dtype}.") def _func( algorithm: jnp.ndarray, key: jnp.ndarray, shape: jnp.ndarray, ) -> Tuple[jnp.ndarray, jnp.ndarray]: return jax.lax.rng_bit_generator( key=key.reshape(-1), shape=shape, dtype=jax_dtype, # See tensorflow/compiler/tf2xla/ops/xla_ops.cc#L812 algorithm=xla_utils.get_random_algorithm_from_tf(algorithm.item()), ) return _func @dataclasses.dataclass class _XlaScatter(_HigherOrderFunction): """Represents a XlaScatter Op.""" dimension_numbers: jax.lax.ScatterDimensionNumbers indices_are_sorted: bool def __call__( self, operand: jnp.ndarray, indices: jnp.ndarray, updates: jnp.ndarray, *, update_computation: Callable[..., Any], ) -> jnp.ndarray: dummy_zero = jnp.array(0).astype(operand.dtype) jaxpr = jax.make_jaxpr(update_computation)(dummy_zero, dummy_zero) if not jaxpr.eqns: scatter_fn = jax.lax.scatter elif len(jaxpr.eqns) == 1 and jaxpr.eqns[0].primitive == jax.lax.add_p: scatter_fn = jax.lax.scatter_add elif len(jaxpr.eqns) == 1 and jaxpr.eqns[0].primitive == jax.lax.mul_p: scatter_fn = jax.lax.scatter_mul elif len(jaxpr.eqns) == 1 and jaxpr.eqns[0].primitive == jax.lax.min_p: scatter_fn = jax.lax.scatter_min elif len(jaxpr.eqns) == 1 and jaxpr.eqns[0].primitive == jax.lax.max_p: scatter_fn = jax.lax.scatter_max else: raise ValueError( "Reducer not supported as `update_computation`, found {jaxpr}") return scatter_fn( operand, indices, updates, dimension_numbers=self.dimension_numbers, indices_are_sorted=self.indices_are_sorted) @register_operation("XlaScatter") def _xla_scatter(proto): """Parse a XlaScatter op.""" _check_attrs( proto, { "T", "Tindices", "dimension_numbers", "indices_are_sorted", "update_computation" }) dimension_numbers = xla_utils.scatter_dimension_numbers_from_proto( proto.attr["dimension_numbers"].s) update_computation = proto.attr["update_computation"].func.name indices_are_sorted = proto.attr["indices_are_sorted"].b return _XlaScatter( dict(update_computation=update_computation), dimension_numbers, indices_are_sorted) class _XlaSelectAndScatter(_HigherOrderFunction): """Represents a XlaSelectAndScatter Op.""" def __call__( self, operand: jnp.ndarray, window_dimensions: jnp.ndarray, window_strides: jnp.ndarray, padding: jnp.ndarray, source: jnp.ndarray, inner_init_value: jnp.ndarray, *, scatter: Callable[..., Any], select: Callable[..., Any], ) -> jnp.ndarray: # Because jax.lax._select_and_scatter is not part of the JAX public api, we # are using a crude pattern matching to determine the reducer used in the # original reduce_window call. scatter_jaxpr = jax.make_jaxpr(scatter)(inner_init_value, inner_init_value) scatter_eqn = _maybe_get_jaxpreqn(scatter_jaxpr) if scatter_eqn is not None and scatter_eqn.primitive is not jax.lax.add_p: raise ValueError( f"Only Add is supported as scatter function, found {scatter_jaxpr}.") # TODO(b/266553393) Support jax.lax.add for AvgPool. select_primitives = { jax.lax.ge_p: (-jnp.inf, jax.lax.max), jax.lax.le_p: (jnp.inf, jax.lax.min), } select_jaxpr = jax.make_jaxpr(select)(inner_init_value, inner_init_value) select_eqn = _maybe_get_jaxpreqn(select_jaxpr) if select_eqn is not None and select_eqn.primitive in select_primitives: init_value, computation = select_primitives[select_eqn.primitive] else: raise ValueError("Only greater_equal (Max) and less_equal (Min) are " f"supported as select function, found {select_jaxpr}") def reduce_window(x): return jax.lax.reduce_window( x, init_value, computation=computation, window_dimensions=tuple(window_dimensions.tolist()), window_strides=tuple(window_strides.tolist()), padding=[tuple(v) for v in padding.tolist()]) _, f_vjp = jax.vjp(reduce_window, operand) return f_vjp(source) @register_operation("XlaSelectAndScatter") def _xla_select_and_scatter(proto): """Parse a XlaSelectAndScatter op.""" _check_attrs(proto, {"T", "Tindices", "scatter", "select"}) scatter = proto.attr["scatter"].func.name select = proto.attr["select"].func.name return _XlaSelectAndScatter(dict(scatter=scatter, select=select)) def _searchsorted(a: jnp.ndarray, v: jnp.ndarray, side: str): """Vmapped version of searchsorted to implement LowerBound and UpperBound.""" return jax.vmap( functools.partial(jnp.searchsorted, side=side), in_axes=0, out_axes=0, )(a, v) def _lower_upper_bound(proto, side: str): """Parse a LowerBound or UpperBound op using searchsorted.""" _check_attrs(proto, {"T", "Tvalues", "out_type"}) dtype = tf.as_dtype(proto.attr["out_type"].type) if dtype != tf.int32: raise ValueError( f"Return type {dtype} not supported for LowerBound and UpperBound.") return lambda a, v: _searchsorted(a, v, side=side) @register_operation("LowerBound") def _lower_bound(proto): """Parse a LowerBound op.""" return _lower_upper_bound(proto, side="left") @register_operation("UpperBound") def _upper_bound(proto): """Parse an UpperBound op.""" return _lower_upper_bound(proto, side="right")
tf2jax-main
tf2jax/_src/ops.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. # ============================================================================== """Util functions.""" import inspect def fullargspec_to_signature(fullargspec) -> inspect.Signature: """Convert a {inspect|tf}.FullArgSpec to a inspect.Signature.""" default_offset = len(fullargspec.args) - len(fullargspec.defaults or ()) parameters = [] # Positional or keyword args. for idx, arg in enumerate(fullargspec.args): param_dict = dict(name=arg, kind=inspect.Parameter.POSITIONAL_OR_KEYWORD) if idx >= default_offset: param_dict["default"] = fullargspec.defaults[idx - default_offset] parameters.append(inspect.Parameter(**param_dict)) # Varargs if fullargspec.varargs is not None: parameters.append( inspect.Parameter( fullargspec.varargs, kind=inspect.Parameter.VAR_POSITIONAL)) # Keyword-only args. for arg in fullargspec.kwonlyargs: param_dict = dict(name=arg, kind=inspect.Parameter.KEYWORD_ONLY) if arg in (fullargspec.kwonlydefaults or {}): param_dict["default"] = fullargspec.kwonlydefaults[arg] parameters.append(inspect.Parameter(**param_dict)) # Kwargs. if fullargspec.varkw is not None: parameters.append( inspect.Parameter( fullargspec.varkw, kind=inspect.Parameter.VAR_KEYWORD)) signature = inspect.Signature(parameters) return signature
tf2jax-main
tf2jax/_src/utils.py