python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
|---|---|---|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Transformer blocks."""
import math
from typing import Callable, Optional
import haiku as hk
from haiku import initializers as init
import jax
import jax.numpy as jnp
from wikigraphs.model.embedding import RelativePositionEmbedding
def conv1d(x, num_units, init_scale=0.02, with_bias=True):
return hk.Conv1D(
output_channels=num_units, kernel_shape=1, with_bias=with_bias,
w_init=init.RandomNormal(stddev=init_scale))(x)
def layer_norm(x):
return hk.LayerNorm(axis=-1, create_scale=True, create_offset=True)(x)
class FeedForwardBlock(hk.Module):
"""Feed forward block."""
def __init__(self,
dense_dim: int = 2100,
dropout_prob: float = 0.1,
init_scale: float = 1.,
name: Optional[str] = None):
"""Initializes a FeedForwardBlock.
Args:
dense_dim: feature size of the feedforward block.
dropout_prob: dropout probability.
init_scale: the initialization scale of the VarianceScaling used for the
feedforward layer.
name: Optional name for this Haiku module.
"""
super(FeedForwardBlock, self).__init__(name=name)
self._dense_dim = dense_dim
self._dropout_prob = dropout_prob
self._init_scale = init_scale
def __call__(self, x: jnp.ndarray) -> jnp.ndarray:
hiddens = x.shape[-1]
x = conv1d(x, num_units=self._dense_dim, init_scale=self._init_scale)
x = jax.nn.relu(x)
x = hk.dropout(hk.next_rng_key(), self._dropout_prob, x)
x = conv1d(x, num_units=hiddens, init_scale=self._init_scale)
return hk.dropout(hk.next_rng_key(), self._dropout_prob, x)
def get_reset_attention_mask(should_reset: jnp.ndarray) -> jnp.ndarray:
"""Maps a reset token vector into an attention mask that consists of blocks.
A sequence of should reset tokens such as:
[0, 1, 0, 1, 0, 0]
transforms into an attention mask such as:
[[1, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1]]
Args:
should_reset: Reset tokens with shape [batch, timesteps].
Returns:
attention_mask: Attention mask with shape [batch, timesteps, timesteps].
"""
should_reset = jnp.cumsum(should_reset, axis=-1)
attention_mask = should_reset[:, :, None] == should_reset[:, None, :]
return attention_mask.astype(jnp.float32)
def attend(q: jnp.ndarray,
k: jnp.ndarray,
v: jnp.ndarray,
mask: Optional[jnp.ndarray] = None,
attend_fn:
Optional[Callable[[jnp.ndarray, jnp.ndarray], jnp.ndarray]] = None,
dropout_prob: float = 0.0,
extra_k: Optional[jnp.ndarray] = None,
extra_v: Optional[jnp.ndarray] = None,
extra_mask: Optional[jnp.ndarray] = None) -> jnp.ndarray:
"""Computes multi-head attention using the given query, key and value.
Args:
q: Query with shape [batch, q_timesteps, num_heads, head_dim].
k: Key with shape [batch, timesteps, num_heads, head_dim].
v: Value with shape [batch, timesteps, num_heads, head_dim].
mask: Attention mask to apply [batch, 1, q_timesteps, timesteps].
attend_fn: An optionally defined attend function. The default attend_fn is
is jnp.einsum('bthd,bThd->bhtT', q, k).
dropout_prob: dropout probability on the attention weights.
extra_k: Extra keys to attend to, if provided. Note the extra keys and
values do not apply the specified attention_fn, but instead use the
default dot-product attention. [batch, timesteps_extra, num_heads,
head_dim].
extra_v: Extra values to attend to, if provided. [batch, timesteps_extra,
num_heads, head_dim].
extra_mask: Extra attention mask to apply on the extra inputs [batch, 1,
q_timesteps, timesteps_extra].
Returns:
Output of the attention with shape [batch, timesteps, hiddens]
"""
infinity_proxy = 1e9
batch, q_time, num_heads, head_dim = q.shape
hiddens = num_heads * head_dim
_, kv_time, _, _ = k.shape
expected_kv_shape = (batch, kv_time, num_heads, head_dim)
if k.shape != expected_kv_shape:
raise ValueError(
f'Expected key shape {expected_kv_shape} but got shape {k.shape}')
if v.shape != expected_kv_shape:
raise ValueError(
f'Expected value shape {expected_kv_shape} but got shape {v.shape}')
if attend_fn is not None:
attention = attend_fn(q, k)
else:
attention = jnp.einsum('bthd,bThd->bhtT', q, k)
if mask is not None:
attention = attention * mask - infinity_proxy * (1 - mask)
if extra_k is not None and extra_v is not None:
extra_time = extra_k.shape[1]
expected_extra_shape = (batch, extra_time, num_heads, head_dim)
if extra_k.shape != expected_extra_shape:
raise ValueError(
f'Expected extra key shape {expected_extra_shape} but got'
f' {extra_k.shape}')
if extra_v.shape != expected_extra_shape:
raise ValueError(
f'Expected extra value shape {expected_extra_shape} but got'
f' {extra_v.shape}')
# [B, H, t, T']
extra_attention = jnp.einsum('bthd,bThd->bhtT', q, extra_k)
if extra_mask is not None:
extra_attention = extra_attention * extra_mask - infinity_proxy * (
1 - extra_mask)
# [B, H, t, T+T']
attention = jnp.concatenate([attention, extra_attention], axis=-1)
# [B, T+T', H, D]
v = jnp.concatenate([v, extra_v], axis=1)
scale = 1. / math.sqrt(head_dim)
attention *= scale
normalized = jax.nn.softmax(attention)
if dropout_prob > 0:
normalized = hk.dropout(hk.next_rng_key(), dropout_prob, normalized)
summed = jnp.einsum('bhtT,bThd->bthd', normalized, v)
return jnp.reshape(summed, [batch, q_time, hiddens])
class Attention(hk.Module):
"""Attention with memory (https://arxiv.org/abs/1901.02860).
This implementation leverages the `state` in Haiku, in which the inputs are
stored as `states`. At each step, these states in memory are updated with a
rolling window.
"""
def __init__(self,
r_w_bias: Optional[jnp.ndarray] = None,
r_r_bias: Optional[jnp.ndarray] = None,
num_heads: int = 8,
init_scale: float = 1.0,
with_final_bias: bool = False,
final_init_scale_multiplier: float = 1.,
relative_pos_clamp_len: Optional[int] = None,
dropout_prob: float = 0.0,
name: Optional[str] = None):
"""Initializes a Attention module.
Args:
r_w_bias: global content bias.
r_r_bias: global positional bias.
num_heads: number of attention heads.
init_scale: the initialization scale of the VarianceScaling used for the
linear layer.
with_final_bias: whether to let final layer have biases.
final_init_scale_multiplier: how much to scale the initialization scale of
the output layer.
relative_pos_clamp_len: clamp length of the relative position embeddings.
dropout_prob: dropout probability.
name: Optional name for this Haiku module.
"""
super(Attention, self).__init__(name=name)
self._r_w_bias = r_w_bias
self._r_r_bias = r_r_bias
self._num_heads = num_heads
self._init_scale = init_scale
self._with_final_bias = with_final_bias
self._final_init_scale = final_init_scale_multiplier * init_scale
self._relative_pos_clamp_len = relative_pos_clamp_len
self._dropout_prob = dropout_prob
def _update_cache(self,
key: jnp.ndarray,
value: jnp.ndarray,
cache_steps: Optional[int] = None,
axis: int = 1) -> jnp.ndarray:
"""Update the cache stored in hk.state."""
cache_shape = list(value.shape)
value_steps = cache_shape[axis]
if cache_steps is not None:
cache_shape[axis] += cache_steps
cache = hk.get_state(
key, shape=cache_shape, dtype=value.dtype, init=jnp.zeros)
# Overwrite at index 0, then rotate timesteps left so what was just
# inserted is first.
value = jax.lax.dynamic_update_slice(
cache, value, jnp.zeros(len(cache_shape), dtype=jnp.int32))
value = jnp.roll(value, -value_steps, axis)
hk.set_state(key, value)
return value
def _update_memory(self,
mem: jnp.ndarray,
mask: jnp.ndarray,
input_length: int,
cache_steps: int,
should_reset: jnp.ndarray) -> jnp.ndarray:
"""Logic for using and updating cached activations."""
batch_size = mem.shape[0]
if cache_steps > 0:
# Tells us how much of the cache should be used.
cache_progress_idx = hk.get_state(
'cache_progress_idx', [batch_size], dtype=jnp.int32, init=jnp.zeros)
hk.set_state('cache_progress_idx', cache_progress_idx + input_length)
mem = self._update_cache('mem', mem, cache_steps=cache_steps)
if mask is None:
mask = jnp.ones((batch_size, 1, input_length, input_length))
cache_mask = (jnp.arange(cache_steps - 1, -1, -1)[None, None, None, :]
< cache_progress_idx[:, None, None, None])
cache_mask = jnp.broadcast_to(
cache_mask, (batch_size, 1, input_length, cache_steps))
mask = jnp.concatenate([cache_mask, mask], axis=-1)
if should_reset is not None:
if cache_steps > 0:
should_reset = self._update_cache('should_reset', should_reset,
cache_steps=cache_steps)
reset_mask = get_reset_attention_mask(should_reset)[:, None, :, :]
mask *= reset_mask[:, :, cache_steps:, :]
return mem, mask
def __call__(self,
x: jnp.ndarray,
mask: Optional[jnp.ndarray] = None,
should_reset: Optional[jnp.ndarray] = None,
cache_steps: int = 0,
extra: Optional[jnp.ndarray] = None,
extra_mask: Optional[jnp.ndarray] = None) -> jnp.ndarray:
"""Compute the multi-head attention.
Args:
x: input [batch, x_timesteps, in_dim].
mask: attention mask [batch, 1, x_timesteps, y_timesteps].
should_reset: reset marker [batch, timesteps].
cache_steps: number of timesteps in the cache.
extra: if provided should be extra key-value input
[batch, extra_timesteps, in_dim'].
extra_mask: if provided should be the mask for extra key-value input,
[batch, extra_timesteps].
Returns:
output: attention output [batch, x_timesteps, in_dim].
"""
hiddens_in = x.shape[-1]
steps = x.shape[1]
qkv_hiddens = hiddens_in
y, mask = self._update_memory(x, mask, steps, cache_steps, should_reset)
q = conv1d(x, qkv_hiddens, init_scale=self._init_scale, with_bias=False)
k = conv1d(y, qkv_hiddens, init_scale=self._init_scale, with_bias=False)
v = conv1d(y, qkv_hiddens, init_scale=self._init_scale, with_bias=False)
batch, q_time, _ = q.shape
_, kv_time, _ = k.shape
head_dim = qkv_hiddens // self._num_heads
assert qkv_hiddens % self._num_heads == 0, 'Head dim should be an integer.'
q = jnp.reshape(q, [batch, q_time, self._num_heads, head_dim])
k = jnp.reshape(k, [batch, kv_time, self._num_heads, head_dim])
v = jnp.reshape(v, [batch, kv_time, self._num_heads, head_dim])
attend_fn = RelativePositionEmbedding(
dim=qkv_hiddens, dropout_rate=self._dropout_prob,
r_w_bias=self._r_w_bias, r_r_bias=self._r_r_bias,
init_scale=self._init_scale, clamp_len=self._relative_pos_clamp_len)
if extra is not None:
extra_k = conv1d(extra, qkv_hiddens, init_scale=self._init_scale,
with_bias=False)
extra_v = conv1d(extra, qkv_hiddens, init_scale=self._init_scale,
with_bias=False)
extra_time = extra.shape[1]
extra_k = jnp.reshape(
extra_k, [batch, extra_time, self._num_heads, head_dim])
extra_v = jnp.reshape(
extra_v, [batch, extra_time, self._num_heads, head_dim])
if extra_mask is not None:
extra_mask = extra_mask[:, None, None, :]
attn_vec = attend(q, k, v, mask=mask, attend_fn=attend_fn,
dropout_prob=self._dropout_prob,
extra_k=extra_k, extra_v=extra_v, extra_mask=extra_mask)
else:
attn_vec = attend(q, k, v, mask=mask, attend_fn=attend_fn,
dropout_prob=self._dropout_prob)
attn_out = conv1d(attn_vec, hiddens_in, with_bias=self._with_final_bias,
init_scale=self._final_init_scale)
return hk.dropout(hk.next_rng_key(), self._dropout_prob, attn_out)
class SelfAttentionBlock(hk.Module):
"""Self attention block."""
def __init__(self,
r_w_bias: Optional[jnp.ndarray] = None,
r_r_bias: Optional[jnp.ndarray] = None,
causal: bool = False,
num_heads: int = 8,
dropout_prob: float = 0.1,
dropout_attn_prob: float = 0.0,
init_scale: float = 1.0,
relative_pos_clamp_len: Optional[int] = None,
name: Optional[str] = None):
"""Initializes a SelfAttentionBlock.
Args:
r_w_bias: global content bias.
r_r_bias: global positional bias.
causal: whether to apply a causal mask to the input.
num_heads: number of attention heads.
dropout_prob: dropout probability.
dropout_attn_prob: dropout probability of the attention module.
init_scale: the initialization scale of the VarianceScaling used for the
linear layer.
relative_pos_clamp_len: clamp length of the relative position embeddings.
name: Optional name for this Haiku module.
"""
super(SelfAttentionBlock, self).__init__(name=name)
self._r_w_bias = r_w_bias
self._r_r_bias = r_r_bias
self._causal = causal
self._num_heads = num_heads
self._dropout_prob = dropout_prob
self._dropout_attn_prob = dropout_attn_prob
self._init_scale = init_scale
self._relative_pos_clamp_len = relative_pos_clamp_len
def __call__(self,
x: jnp.ndarray,
mask: Optional[jnp.ndarray] = None,
should_reset: Optional[jnp.ndarray] = None,
cache_steps: int = 0,
extra: Optional[jnp.ndarray] = None,
extra_mask: Optional[jnp.ndarray] = None) -> jnp.ndarray:
"""Computes the outputs of the self attention block.
Args:
x: query input [batch, x_timesteps, in_dim].
mask: attention mask [batch, 1, 1, x_timesteps].
should_reset: reset marker [batch, timesteps].
cache_steps: number of timesteps in the cache.
extra: if provided should be extra key-value input
[batch, extra_timesteps, in_dim'].
extra_mask: if provided should be the mask for extra key-value input,
[batch, extra_timesteps].
Returns:
output: block output [batch, x_timesteps, in_dim].
"""
if self._causal:
timesteps = x.shape[1]
batch_size = x.shape[0]
t = jnp.arange(timesteps, dtype=jnp.int32)
causal_mask = (t[:, None] >= t[None, :])[None, None, :, :]
causal_mask = causal_mask.astype(x.dtype)
if mask is None:
mask = jnp.broadcast_to(
causal_mask, (batch_size, 1, timesteps, timesteps))
else:
mask *= causal_mask
x = Attention(
self._r_w_bias,
self._r_r_bias,
num_heads=self._num_heads,
init_scale=self._init_scale,
relative_pos_clamp_len=self._relative_pos_clamp_len,
dropout_prob=self._dropout_attn_prob)(
x, mask=mask, should_reset=should_reset,
cache_steps=cache_steps, extra=extra, extra_mask=extra_mask)
else:
x = Attention(
self._r_w_bias,
self._r_r_bias,
num_heads=self._num_heads,
init_scale=self._init_scale,
dropout_prob=self._dropout_attn_prob)(
x, mask=mask, extra=extra, extra_mask=extra_mask)
return hk.dropout(hk.next_rng_key(), self._dropout_prob, x)
class GPT2Block(hk.Module):
"""GPT-2 style transformer block with memory."""
def __init__(self,
r_w_bias: Optional[jnp.ndarray] = None,
r_r_bias: Optional[jnp.ndarray] = None,
causal: bool = True,
dense_dim: int = 2100,
dropout_prob: float = 0.1,
dropout_attn_prob: float = 0.0,
num_heads: int = 8,
self_att_init_scale: float = 0.02,
dense_init_scale: float = 0.02,
relative_pos_clamp_len: Optional[int] = None,
name: Optional[str] = None):
"""Initializes a GPT2Block.
Args:
r_w_bias: global content bias.
r_r_bias: global positional bias.
causal: whether to apply a causal mask to the input.
dense_dim: feature size of the feedforward block.
dropout_prob: dropout probability.
dropout_attn_prob: dropout probability of the attention module.
num_heads: number of attention heads.
self_att_init_scale: the initialization scale of the VarianceScaling
used for the linear layer in the attention module.
dense_init_scale: the initialization scale of the VarianceScaling
used for the linear layer in the feedforward module.
relative_pos_clamp_len: clamp length of the relative position embeddings.
name: Optional name for this Haiku module.
"""
super(GPT2Block, self).__init__(name=name)
self._r_w_bias = r_w_bias
self._r_r_bias = r_r_bias
self._causal = causal
self._dense_dim = dense_dim
self._dropout_prob = dropout_prob
self._dropout_attn_prob = dropout_attn_prob
self._num_heads = num_heads
self._self_att_init_scale = self_att_init_scale
self._dense_init_scale = dense_init_scale
self._relative_pos_clamp_len = relative_pos_clamp_len
def __call__(self,
x: jnp.ndarray,
mask: Optional[jnp.ndarray] = None,
is_training: bool = True,
should_reset: Optional[jnp.ndarray] = None,
cache_steps: int = 0,
extra: Optional[jnp.ndarray] = None,
extra_mask: Optional[jnp.ndarray] = None) -> jnp.ndarray:
"""Computes the outputs of the GPT-2 block.
Args:
x: query input [batch, x_timesteps, in_dim].
mask: attention mask [batch, 1, 1, x_timesteps].
is_training: whether the current stage is training or not.
should_reset: reset marker [batch, timesteps].
cache_steps: number of timesteps in the cache.
extra: if provided should be extra key-value input
[batch, extra_timesteps, in_dim'].
extra_mask: if provided should be the mask for extra key-value input,
[batch, extra_timesteps].
Returns:
output: block output [batch, x_timesteps, in_dim].
"""
dropout_prob = self._dropout_prob if is_training else 0.0
dropout_attn_prob = self._dropout_attn_prob if is_training else 0.0
x = layer_norm(x + SelfAttentionBlock(
self._r_w_bias,
self._r_r_bias,
causal=self._causal,
num_heads=self._num_heads,
dropout_prob=dropout_prob,
dropout_attn_prob=dropout_attn_prob,
init_scale=self._self_att_init_scale,
relative_pos_clamp_len=self._relative_pos_clamp_len)(
x, mask=mask, should_reset=should_reset,
cache_steps=cache_steps, extra=extra, extra_mask=extra_mask))
x = layer_norm(x + FeedForwardBlock(
dense_dim=self._dense_dim,
dropout_prob=dropout_prob,
init_scale=self._dense_init_scale)(x))
return x
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/transformer_block.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tests for wikigraphs.model.transformer."""
from absl import logging
from absl.testing import absltest
import haiku as hk
import jax
import jax.numpy as jnp
import jraph
import numpy as np
import optax
from wikigraphs.model import embedding
from wikigraphs.model import transformer as models
def tree_size(nest):
return sum(x.size for x in jax.tree_util.tree_leaves(nest))
class TransformerXlTest(absltest.TestCase):
def test_transformer_param_count(self):
seqs = np.array([[1, 2, 3, 0, 0],
[3, 3, 5, 1, 2]], dtype=np.int32)
x = seqs[:, :-1]
y = seqs[:, 1:]
vocab_size = 267_735
def forward(inputs, labels):
input_mask = (labels != 0).astype(jnp.float32)
model = models.TransformerXL(
vocab_size=vocab_size,
emb_dim=210,
num_layers=2,
num_heads=10,
dropout_prob=0.0,
dropout_attn_prob=0.0,
self_att_init_scale=0.02,
dense_init_scale=0.02,
dense_dim=2100,
cutoffs=(20000, 40000, 200000), # WikiText-103
relative_pos_clamp_len=None,
)
return model.loss(inputs, labels, mask=input_mask, cache_steps=2)
init_fn, apply_fn = hk.transform_with_state(forward)
key = hk.PRNGSequence(8)
params, state = init_fn(next(key), x, y)
out, _ = apply_fn(params, state, next(key), x, y)
loss, metrics = out
logging.info('loss: %g', loss)
logging.info('metrics: %r', metrics)
param_count = tree_size(params)
self.assertEqual(param_count, 58_704_438)
def test_transformer_with_extra_runs(self):
extra = np.array([[1, 1, 0, 0],
[2, 2, 2, 2],
[3, 3, 3, 0]], dtype=np.int32)
seqs = np.array([[1, 2, 3, 0, 0],
[2, 4, 5, 6, 0],
[3, 3, 5, 1, 2]], dtype=np.int32)
x = seqs[:, :-1]
y = seqs[:, 1:]
vocab_size = seqs.max() + 1
extra_vocab_size = extra.max() + 1
def forward(inputs, labels, extra):
input_mask = (labels != 0).astype(jnp.float32)
extra_mask = (extra != 0).astype(jnp.float32)
extra = hk.Embed(vocab_size=extra_vocab_size, embed_dim=16)(extra)
model = models.TransformerXL(
vocab_size=vocab_size,
emb_dim=16,
num_layers=2,
num_heads=4,
cutoffs=[],
)
return model.loss(inputs, labels, mask=input_mask,
extra=extra, extra_mask=extra_mask)
init_fn, apply_fn = hk.transform_with_state(forward)
key = hk.PRNGSequence(8)
params, state = init_fn(next(key), x, y, extra)
out, _ = apply_fn(params, state, next(key), x, y, extra)
loss, metrics = out
logging.info('loss: %g', loss)
logging.info('metrics: %r', metrics)
def test_graph_embedding_model_runs(self):
graph = jraph.GraphsTuple(
nodes=np.array([[0, 1, 1],
[1, 2, 0],
[0, 3, 0],
[0, 4, 4]], dtype=np.float32),
edges=np.array([[1, 1],
[2, 2],
[3, 3]], dtype=np.float32),
senders=np.array([0, 1, 2], dtype=np.int32),
receivers=np.array([1, 2, 3], dtype=np.int32),
n_node=np.array([4], dtype=np.int32),
n_edge=np.array([3], dtype=np.int32),
globals=None)
embed_dim = 3
def forward(graph):
return embedding.GraphEmbeddingModel(embed_dim=3, num_layers=2)(graph)
init_fn, apply_fn = hk.without_apply_rng(hk.transform(forward))
key = hk.PRNGSequence(8)
params = init_fn(next(key), graph)
out = apply_fn(params, graph)
self.assertEqual(out.nodes.shape, (graph.nodes.shape[0], embed_dim))
self.assertEqual(out.edges.shape, (graph.edges.shape[0], embed_dim))
np.testing.assert_array_equal(out.senders, graph.senders)
np.testing.assert_array_equal(out.receivers, graph.receivers)
np.testing.assert_array_equal(out.n_node, graph.n_node)
def test_unpack_and_pad(self):
x = np.array([1, 1, 2, 2, 2, 3, 4, 4], dtype=np.float32)
s = np.array([2, 3, 1, 2], dtype=np.int32)
tensors, mask = models.unpack_and_pad(x, s, pad_size=s.max(), pad_value=0)
np.testing.assert_array_equal(
tensors,
[[1, 1, 0],
[2, 2, 2],
[3, 0, 0],
[4, 4, 0]])
np.testing.assert_array_equal(
mask,
[[1, 1, 0],
[1, 1, 1],
[1, 0, 0],
[1, 1, 0]])
# [n, 1] tensor
x = np.array([1, 1, 2, 2, 2, 3, 4, 4], dtype=np.float32)[:, None]
s = np.array([2, 3, 1, 2], dtype=np.int32)
tensors, mask = models.unpack_and_pad(x, s, pad_size=s.max(), pad_value=0)
np.testing.assert_array_equal(
tensors,
np.array([[1, 1, 0],
[2, 2, 2],
[3, 0, 0],
[4, 4, 0]])[:, :, None])
np.testing.assert_array_equal(
mask,
[[1, 1, 0],
[1, 1, 1],
[1, 0, 0],
[1, 1, 0]])
def test_graph_conditioned_transformer_runs(self):
graphs = jraph.GraphsTuple(
nodes=np.ones((4, 3), dtype=np.float32),
edges=np.ones((3, 1), dtype=np.float32),
senders=np.array([0, 2, 3], dtype=np.int32),
receivers=np.array([1, 3, 2], dtype=np.int32),
n_node=np.array([2, 2], dtype=np.int32),
n_edge=np.array([1, 2], dtype=np.int32),
globals=None,
)
seqs = np.array([[1, 1, 0],
[2, 2, 2]], dtype=np.int32)
vocab_size = seqs.max() + 1
embed_dim = 8
x = seqs[:, :-1]
y = seqs[:, 1:]
def forward(graphs, inputs, labels):
graphs = models.GraphEmbeddingModel(embed_dim=embed_dim,
num_layers=2)(graphs)
extra, extra_mask = models.unpack_and_pad(graphs.nodes,
graphs.n_node,
graphs.n_node.max())
input_mask = (labels != 0).astype(jnp.float32)
transformer = models.TransformerXL(vocab_size=vocab_size,
emb_dim=embed_dim,
num_layers=2,
num_heads=4,
cutoffs=[])
return transformer.loss(inputs, labels, mask=input_mask, extra=extra,
extra_mask=extra_mask)
init_fn, apply_fn = hk.transform_with_state(forward)
key = hk.PRNGSequence(8)
params, state = init_fn(next(key), graphs, x, y)
out, _ = apply_fn(params, state, next(key), graphs, x, y)
loss, metrics = out
logging.info('loss: %g', loss)
logging.info('metrics: %r', metrics)
def test_graph_conditioned_transformer_learns(self):
graphs = jraph.GraphsTuple(
nodes=np.ones((4, 3), dtype=np.float32),
edges=np.ones((3, 1), dtype=np.float32),
senders=np.array([0, 2, 3], dtype=np.int32),
receivers=np.array([1, 3, 2], dtype=np.int32),
n_node=np.array([2, 2], dtype=np.int32),
n_edge=np.array([1, 2], dtype=np.int32),
globals=None,
)
seqs = np.array([[1, 2, 2, 0],
[1, 3, 3, 3]], dtype=np.int32)
vocab_size = seqs.max() + 1
embed_dim = 8
max_graph_size = graphs.n_node.max()
logging.info('Training seqs: %r', seqs)
x = seqs[:, :-1]
y = seqs[:, 1:]
def model_fn(vocab_size, embed_dim):
return models.Graph2TextTransformer(
vocab_size=vocab_size,
emb_dim=embed_dim,
num_layers=2,
num_heads=4,
cutoffs=[],
gnn_embed_dim=embed_dim,
gnn_num_layers=2)
def forward(graphs, inputs, labels, max_graph_size):
input_mask = (labels != 0).astype(jnp.float32)
return model_fn(vocab_size, embed_dim).loss(
graphs, max_graph_size, False, inputs, labels, mask=input_mask)
init_fn, apply_fn = hk.transform_with_state(forward)
rng = hk.PRNGSequence(8)
params, state = init_fn(next(rng), graphs, x, y, max_graph_size)
def apply(*args, **kwargs):
out, state = apply_fn(*args, **kwargs)
return out[0], (out[1], state)
apply = jax.jit(apply, static_argnums=6)
optimizer = optax.chain(
optax.scale_by_adam(),
optax.scale(-1e-3))
opt_state = optimizer.init(params)
for i in range(500):
(loss, model_state), grad = jax.value_and_grad(apply, has_aux=True)(
params, state, next(rng), graphs, x, y, max_graph_size)
metrics, state = model_state
updates, opt_state = optimizer.update(grad, opt_state, params)
params = optax.apply_updates(params, updates)
if (i + 1) % 100 == 0:
logging.info(
'Step %d, %r', i + 1, {k: float(v) for k, v in metrics.items()})
logging.info('Loss: %.8f', loss)
self.assertLess(loss, 1.0)
def test_bow_transformer_runs(self):
bow = np.array([[0, 0, 1, 0, 2, 0, 0, 1],
[0, 1, 0, 0, 1, 0, 1, 0],
[1, 0, 0, 0, 1, 0, 0, 1]], dtype=np.int32)
seqs = np.array([[1, 2, 3, 0, 0],
[2, 4, 5, 6, 0],
[3, 3, 5, 1, 2]], dtype=np.int32)
x = seqs[:, :-1]
y = seqs[:, 1:]
vocab_size = seqs.max() + 1
def forward(bow, inputs, labels):
model = models.Bow2TextTransformer(
vocab_size=vocab_size,
emb_dim=16,
num_layers=2,
num_heads=4,
cutoffs=[])
return model.loss(bow, inputs, labels)
init_fn, apply_fn = hk.transform_with_state(forward)
key = hk.PRNGSequence(8)
params, state = init_fn(next(key), bow, x, y)
out, _ = apply_fn(params, state, next(key), bow, x, y)
loss, metrics = out
logging.info('loss: %g', loss)
logging.info('metrics: %r', metrics)
def test_bow_transformer_learns(self):
bow = np.array([[0, 0, 1, 0, 2, 0, 0, 1],
[0, 1, 0, 0, 1, 0, 1, 0],
[1, 0, 0, 0, 1, 0, 0, 1]], dtype=np.int32)
seqs = np.array([[1, 2, 2, 3, 0, 0],
[1, 2, 4, 5, 6, 0],
[1, 3, 3, 5, 4, 2]], dtype=np.int32)
x = seqs[:, :-1]
y = seqs[:, 1:]
vocab_size = seqs.max() + 1
def model_fn():
return models.Bow2TextTransformer(
vocab_size=vocab_size,
emb_dim=16,
num_layers=2,
num_heads=4,
cutoffs=[])
def loss_fn(bow, inputs, labels):
mask = (labels != 0).astype(jnp.float32)
return model_fn().loss(bow, inputs, labels, mask=mask)
init_fn, apply_fn = hk.transform_with_state(loss_fn)
key = hk.PRNGSequence(8)
params, state = init_fn(next(key), bow, x, y)
def apply(*args, **kwargs):
out, state = apply_fn(*args, **kwargs)
return out[0], (out[1], state)
value_and_grad = jax.jit(jax.value_and_grad(apply, has_aux=True))
optimizer = optax.chain(
optax.scale_by_adam(),
optax.scale(-1e-3))
opt_state = optimizer.init(params)
for i in range(800):
(loss, model_state), grad = value_and_grad(
params, state, next(key), bow, x, y)
metrics, state = model_state
updates, opt_state = optimizer.update(grad, opt_state, params)
params = optax.apply_updates(params, updates)
if (i + 1) % 100 == 0:
logging.info('Step %d, %r', i + 1,
{k: float(v) for k, v in metrics.items()})
logging.info('Loss: %.8f', loss)
self.assertLess(loss, 0.1)
if __name__ == '__main__':
absltest.main()
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/transformer_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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Transformer embedding modules."""
from typing import List, Optional
import haiku as hk
from haiku import initializers as init
import jax
import jax.numpy as jnp
import jraph
from wikigraphs.model import graph_net as gn
def get_pos_start(timesteps: int, batch_size: int) -> jnp.ndarray:
"""Find the right slice of positional embeddings for incremental sampling."""
pos_start = hk.get_state(
'cache_progress_idx', [batch_size], dtype=jnp.int32, init=jnp.zeros)
hk.set_state('cache_progress_idx', pos_start + timesteps)
return pos_start
class SinusoidalPositionEmbedding(hk.Module):
"""Position encoding, using mixture of sinusoidal signals."""
def __init__(self,
dim: int,
cache_steps: int = 0,
reverse_order: bool = False,
clamp_len: Optional[int] = None,
name: Optional[str] = None):
"""Initialize a SinusoidalPositionEmbedding.
Args:
dim: Embedding dimension.
cache_steps: The length of the memory.
reverse_order: If set to True, position index is reversed.
clamp_len: position beyond clamp_len will be reset to clamp_len, default
to not clamping.
name: Optional name for this Haiku module.
"""
super(SinusoidalPositionEmbedding, self).__init__(name=name)
self._dim = dim
self._cache_steps = cache_steps
self._reverse_order = reverse_order
self._clamp_len = clamp_len
self._inv_freq = 1.0 / (
10000 ** (jnp.arange(0, dim, 2).astype(jnp.float32) / dim))
def __call__(self, timesteps: int, batch_size: int) -> jnp.ndarray:
"""Computes the sinusoidal position embedding.
Args:
timesteps: The length of the sequence.
batch_size: The size of the batch.
Returns:
Sinusoidal position embedding.
"""
full_length = timesteps + self._cache_steps
if self._reverse_order:
positions = jnp.arange(full_length - 1, -1, -1)
positions = jnp.repeat(positions[None, :], batch_size, axis=0)
else:
if self._cache_steps > 0:
positions = (get_pos_start(timesteps, batch_size)[:, None]
+ jnp.arange(timesteps)[None, :])
else:
positions = jnp.arange(0, full_length)
positions = jnp.repeat(positions[None, :], batch_size, axis=0)
if self._clamp_len is not None:
positions = jnp.minimum(positions, self._clamp_len)
scaled_time = positions[:, :, None] * self._inv_freq[None, None, :]
return jnp.concatenate([jnp.sin(scaled_time), jnp.cos(scaled_time)], axis=2)
def relative_shift(x: jnp.ndarray) -> jnp.ndarray:
"""Shift the relative logits."""
x_shape = list(x.shape)
x = jnp.pad(x, [[0, 0], [0, 0], [0, 0], [1, 0]])
x = jnp.reshape(
x, [x_shape[0], x_shape[1], x_shape[3] + 1, x_shape[2]])[:, :, 1:, :]
x = jnp.reshape(x, x_shape)
return x
class RelativePositionEmbedding(hk.Module):
"""Position encoding, using relative positions than absolute positions."""
def __init__(self,
dim: int,
dropout_rate: float,
r_w_bias: jnp.ndarray,
r_r_bias: jnp.ndarray,
init_scale: float = 0.02,
clamp_len: Optional[int] = None,
name: Optional[str] = None):
"""Initialize a RelativePositionEmbedding.
Args:
dim: Embedding dimension.
dropout_rate: dropout rate.
r_w_bias: global content bias.
r_r_bias: global positional bias.
init_scale: the initialization scale of the RandomNormal used for the
linear layer.
clamp_len: position beyond clamp_len will be reset to clamp_len, default
to not clamping.
name: Optional name for this Haiku module.
"""
super(RelativePositionEmbedding, self).__init__(name=name)
self._dim = dim
self._dropout_rate = dropout_rate
self._r_w_bias = r_w_bias
self._r_r_bias = r_r_bias
self._init_scale = init_scale
self._sinusoidal_pos_emb = SinusoidalPositionEmbedding(
dim=dim,
reverse_order=True,
clamp_len=clamp_len,
name=name)
def __call__(self, q: jnp.ndarray, k: jnp.ndarray) -> jnp.ndarray:
"""Computes the relative position embedding.
Args:
q: The query.
k: The key.
Returns:
Relative position embedding.
"""
# Use key instead of query to obtain the length.
batch_size, key_length, num_heads, head_dim = list(k.shape)
# Content based addressing and global content bias
content_score = jnp.einsum('bthd,bThd->bhtT', q + self._r_w_bias, k)
# Relative position encoding
positional_encodings = self._sinusoidal_pos_emb(key_length, batch_size)
positional_encodings = hk.dropout(hk.next_rng_key(), self._dropout_rate,
positional_encodings)
rel_pos_emb = hk.Conv1D(
output_channels=self._dim, kernel_shape=1, with_bias=False,
w_init=init.RandomNormal(stddev=self._init_scale))(positional_encodings)
rel_pos_emb = jnp.reshape(rel_pos_emb, [
batch_size, key_length, num_heads, head_dim])
# Content dependent positional bias and global positional bias
rel_pos_score = jnp.einsum('bthd,bThd->bhtT', q + self._r_r_bias,
rel_pos_emb)
rel_pos_score = relative_shift(rel_pos_score)
assert content_score.shape == rel_pos_score.shape
return content_score + rel_pos_score
def hierarchical_logprobs(
logits: jnp.ndarray,
class_logits: jnp.ndarray,
cutoffs: List[int]) -> jnp.ndarray:
"""Hierarchical log-probs for adaptive softmax."""
sizes = [y - x for x, y in zip(cutoffs[:-1], cutoffs[1:])]
num_tails = len(sizes) - 1
split_logits = jnp.split(logits, cutoffs[1:-1], axis=-1)
all_head_logits = jnp.concatenate([split_logits[0], class_logits], -1)
# Mask out item 0, the NULL token
all_head_logits += jnp.concatenate(
[jnp.ones([1], dtype=logits.dtype) * -10,
jnp.zeros([sizes[0] + num_tails - 1], dtype=logits.dtype)], 0)
all_head_logprobs = jax.nn.log_softmax(all_head_logits)
head_logprobs, class_logprobs = jnp.split(all_head_logprobs,
[sizes[0]], axis=-1)
tail_logprobs = []
for i, tail_size in enumerate(sizes[1:]): # pylint: disable=unused-variable
tail_logprobs += [jax.nn.log_softmax(split_logits[i + 1])
+ class_logprobs[..., [i]]]
return jnp.concatenate([head_logprobs] + tail_logprobs, -1)
class AdaptiveSoftmaxEmbedding(hk.Module):
"""Adaptive inputs and softmax (https://arxiv.org/abs/1809.10853)."""
def __init__(self,
dim: int,
vocab_size: int,
cutoffs: List[int],
tail_shrink_factor: int = 4,
hierarchical: bool = True,
init_std: float = 0.02,
init_proj_std: float = 0.01,
dtype: jnp.dtype = jnp.float32,
name: Optional[str] = None):
"""Initialize a AdaptiveSoftmaxEmbedding.
Args:
dim: dimensionality of the hidden space.
vocab_size: the size of the vocabulary.
cutoffs: the cutoff indices of the vocabulary used for the adaptive
softmax embedding.
tail_shrink_factor: how many times to shrink the hidden dimensionality
for low-frequency vocabulary after each cutoff.
hierarchical: whether to use hierarchical softmax.
init_std: standard deviation of the Normal distribution used to initialize
the embedding weights.
init_proj_std: standard deviation of the Normal distribution used to
initialize the projection weights.
dtype: Optional data type default to jnp.float32.
name: Optional name for this Haiku module.
"""
super(AdaptiveSoftmaxEmbedding, self).__init__(name=name)
self._hidden_size = dim
self._vocab_size = vocab_size
self._cutoffs = [0] + list(cutoffs) + [self._vocab_size]
self._tail_shrink_factor = tail_shrink_factor
self._hierarchical = hierarchical
self._dtype = dtype
self._embeddings = []
self._projections = []
self._bias = hk.get_parameter(
'bias', [self._vocab_size], dtype=self._dtype, init=jnp.zeros)
l_cutoffs = self._cutoffs[:-1]
r_cutoffs = self._cutoffs[1:]
for i, (l_cutoff, r_cutoff) in enumerate(zip(l_cutoffs, r_cutoffs)):
hidden_size = self._hidden_size // (self._tail_shrink_factor ** i)
embedding = hk.get_parameter(
f'embeddings_{l_cutoff}_{r_cutoff}',
[r_cutoff - l_cutoff, hidden_size],
dtype=self._dtype,
init=hk.initializers.RandomNormal(stddev=init_std))
self._embeddings += [embedding]
if self._tail_shrink_factor != 1:
projection = hk.get_parameter(
f'projection_{l_cutoff}_{r_cutoff}',
[hidden_size, self._hidden_size],
dtype=self._dtype,
init=hk.initializers.RandomNormal(stddev=init_proj_std))
self._projections += [projection]
if self._tail_shrink_factor != 1:
self._output_projection = hk.get_parameter(
'output_head_projection',
[self._hidden_size, self._hidden_size],
dtype=self._dtype,
init=hk.initializers.RandomNormal(stddev=init_proj_std))
if self._hierarchical:
self._class_weights = hk.get_parameter(
'tail_class_weights',
[self._hidden_size, len(cutoffs)],
init=hk.initializers.RandomNormal(stddev=init_std))
self._class_bias = hk.get_parameter(
'tail_class_bias',
[len(cutoffs)],
dtype=self._dtype,
init=jnp.zeros)
@hk.transparent
def build_embeddings(self):
"""Builds input embeddings."""
if self._projections:
embedding_mat = [
jnp.dot(emb, proj) for emb, proj in zip(self._embeddings,
self._projections)]
else:
embedding_mat = self._embeddings
input_embeddings = jnp.concatenate(embedding_mat, 0)
return input_embeddings
@hk.transparent
def build_output_embeddings(self):
"""Builds separate output embeddings."""
if self._projections:
projections = [self._output_projection] + self._projections[1:]
embedding_mat = [jnp.dot(emb, proj)
for emb, proj in zip(self._embeddings, projections)]
else:
embedding_mat = self._embeddings
output_embeddings = jnp.concatenate(embedding_mat, 0)
return jnp.transpose(output_embeddings)
def embed_input(self, input_tokens: jnp.ndarray) -> jnp.ndarray:
"""Embeds the input."""
assert jnp.issubdtype(input_tokens.dtype, jnp.integer)
input_embeddings = self.build_embeddings()
embedded_inputs = input_embeddings[input_tokens]
return embedded_inputs * self._hidden_size ** 0.5
def embed_output(self, inputs: jnp.ndarray) -> jnp.ndarray:
"""Outputs logits."""
output_embs = self.build_output_embeddings()
logits = jnp.einsum('btd,dv->btv', inputs, output_embs) + self._bias
if self._hierarchical:
class_logits = jnp.dot(inputs, self._class_weights) + self._class_bias
logprobs = hierarchical_logprobs(logits, class_logits, self._cutoffs)
return logprobs
else:
return logits
class GraphEmbeddingModel(hk.Module):
"""A single graph network for embedding graph data."""
def __init__(self,
embed_dim: int,
num_layers: int,
msg_hidden_size_factor: int = 2,
use_layer_norm: bool = False,
name: Optional[str] = None):
"""Constructor.
Args:
embed_dim: node embedding size.
num_layers: number of message passing layers to use.
msg_hidden_size_factor: size of the message network hiddens as a factor
of embed_dim.
use_layer_norm: whether to apply layer norm on node updates.
name: optional name for this module.
"""
super().__init__(name=name)
self._embed_dim = embed_dim
self._num_layers = num_layers
self._msg_hidden_size_factor = msg_hidden_size_factor
self._use_layer_norm = use_layer_norm
def __call__(self, graphs: jraph.GraphsTuple) -> jraph.GraphsTuple:
"""Compute embeddings for each node in the graphs.
Args:
graphs: a set of graphs batched into a single graph. The nodes and edges
are represented as feature tensors.
Returns:
graphs: new graph with node embeddings updated (shape [n_nodes,
embed_dim]).
"""
nodes = hk.Linear(self._embed_dim)(graphs.nodes)
edges = hk.Linear(self._embed_dim)(graphs.edges)
nodes = hk.LayerNorm(axis=-1, create_scale=True, create_offset=True)(
jax.nn.gelu(nodes))
edges = hk.LayerNorm(axis=-1, create_scale=True, create_offset=True)(
jax.nn.gelu(edges))
graphs = graphs._replace(nodes=nodes, edges=edges)
graphs = gn.SimpleGraphNet(
num_layers=self._num_layers,
msg_hidden_size_factor=self._msg_hidden_size_factor,
layer_norm=self._use_layer_norm)(graphs)
return graphs
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/embedding.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Graph net utils."""
from typing import Union, List, Optional
import haiku as hk
import jax
import jax.numpy as jnp
import jraph
import numpy as np
ArrayType = Union[np.ndarray, jnp.ndarray]
def pad_size(in_size: int):
out_size = 1
while out_size < in_size:
out_size *= 2
return out_size
def pad_graphs(
graphs: jraph.GraphsTuple,
pad_n_nodes: Optional[int] = None,
pad_n_edges: Optional[int] = None) -> jraph.GraphsTuple:
"""Pad graphs to have a canonical number of nodes and edges.
Here we pad the number of nodes and number of edges to powers of 2 by adding a
placeholder graph to the end of the batch. So that the batch gets at most 2x
as large as before, and number of graphs increase by 1.
Note this method always adds at least one new node to the placeholder graph to
make sure any edges if added are valid.
Args:
graphs: a batch of graphs.
pad_n_nodes: (optional) number of nodes to pad to.
pad_n_edges: (optional) number of edges to pad to.
Returns:
padded: the input batch padded to canonical sizes.
"""
n_nodes, node_dim = graphs.nodes.shape
n_edges, edge_dim = graphs.edges.shape
# Add at least one extra node to the placeholder graph.
if pad_n_nodes is None:
pad_n_nodes = pad_size(n_nodes + 1)
if pad_n_edges is None:
pad_n_edges = pad_size(n_edges)
nodes = np.concatenate([
graphs.nodes,
np.zeros((pad_n_nodes - n_nodes, node_dim), dtype=graphs.nodes.dtype)
], axis=0)
edges = np.concatenate([
graphs.edges,
np.zeros((pad_n_edges - n_edges, edge_dim), dtype=graphs.edges.dtype)
], axis=0)
# Add padding edges
senders = np.concatenate([
graphs.senders,
np.full(pad_n_edges - n_edges, n_nodes, dtype=graphs.senders.dtype)
], axis=0)
receivers = np.concatenate([
graphs.receivers,
np.full(pad_n_edges - n_edges, n_nodes, dtype=graphs.receivers.dtype)
], axis=0)
n_node = np.concatenate([
graphs.n_node, np.full(1, pad_n_nodes - n_nodes)], axis=0)
n_edge = np.concatenate([
graphs.n_edge, np.full(1, pad_n_edges - n_edges)], axis=0)
return jraph.GraphsTuple(
nodes=nodes, edges=edges, senders=senders, receivers=receivers,
n_node=n_node, n_edge=n_edge, globals=None)
def batch_graphs_by_device(
graphs: List[jraph.GraphsTuple],
num_devices: int
) -> List[jraph.GraphsTuple]:
"""Batch a list of graphs into num_devices batched graphs.
The input graphs are grouped into num_devices groups. Within each group the
graphs are merged. This is needed for parallelizing the graphs using pmap.
Args:
graphs: a list of graphs to be merged.
num_devices: the number of local devices.
Returns:
graph: a size num_devices list of merged graphs.
"""
bs = len(graphs)
assert bs % num_devices == 0, (
'Batch size {} is not divisible by {} devices.'.format(bs, num_devices))
bs_per_device = bs // num_devices
graphs_on_devices = []
for i in range(num_devices):
graphs_on_device_i = graphs[i*bs_per_device:(i+1)*bs_per_device]
graphs_on_device_i = jraph.batch(graphs_on_device_i)
graphs_on_devices.append(graphs_on_device_i)
return graphs_on_devices
def pad_graphs_by_device(graphs: List[jraph.GraphsTuple]) -> jraph.GraphsTuple:
"""Pad and concatenate the list of graphs.
Each graph in the list is padded according to the maximum n_nodes and n_edges
in the list, such that all graphs have the same length. Then they are
concatenated. This is need for pmap.
Args:
graphs: a list of graphs.
Returns:
graph: a single padded and merged graph.
"""
# Add at least one extra node to the placeholder graph.
pad_n_nodes = pad_size(max([g.nodes.shape[0] for g in graphs]) + 1)
pad_n_edges = pad_size(max([g.edges.shape[0] for g in graphs]))
padded_graphs = [pad_graphs(g, pad_n_nodes, pad_n_edges) for g in graphs]
nodes = []
edges = []
senders = []
receivers = []
n_node = []
n_edge = []
for g in padded_graphs:
assert g.nodes.shape[0] == pad_n_nodes
assert g.edges.shape[0] == pad_n_edges
assert g.senders.size == pad_n_edges
assert g.receivers.size == pad_n_edges
assert g.n_node.size == padded_graphs[0].n_node.size
assert g.n_edge.size == padded_graphs[0].n_edge.size
nodes.append(g.nodes)
edges.append(g.edges)
senders.append(g.senders)
receivers.append(g.receivers)
n_node.append(g.n_node)
n_edge.append(g.n_edge)
return jraph.GraphsTuple(
nodes=np.concatenate(nodes, axis=0),
edges=np.concatenate(edges, axis=0),
senders=np.concatenate(senders, axis=0),
receivers=np.concatenate(receivers, axis=0),
n_node=np.concatenate(n_node, axis=0),
n_edge=np.concatenate(n_edge, axis=0),
globals=None)
class MLPMessagePassingLayer(hk.Module):
"""Message passing layer implemented as MLPs."""
def __init__(self,
node_hidden_sizes: List[int],
msg_hidden_sizes: List[int],
residual: bool = True,
layer_norm: bool = False,
name: Optional[str] = None):
"""Constructor.
Args:
node_hidden_sizes: hidden sizes for the node update model.
msg_hidden_sizes: hidden sizes for the edge message model.
residual: set to True to use residual connections, this will also mean the
input dimension is appended to `node_hidden_sizes` as the output size.
layer_norm: whether to apply layer norm on the node representations.
name: name for this module.
"""
super().__init__(name=name)
self._node_hidden_sizes = node_hidden_sizes
self._msg_hidden_sizes = msg_hidden_sizes
self._residual = residual
self._layer_norm = layer_norm
def _compute_messages(self, graph: jraph.GraphsTuple) -> ArrayType:
"""Compute the messages on each edge."""
x = jnp.concatenate([graph.nodes[graph.senders],
graph.nodes[graph.receivers],
graph.edges], axis=-1)
return hk.nets.MLP(self._msg_hidden_sizes, activate_final=True)(x)
def _update_nodes(self, graph: jraph.GraphsTuple,
messages: ArrayType) -> ArrayType:
"""Compute updated node representations."""
x = jax.ops.segment_sum(messages, graph.receivers,
num_segments=graph.nodes.shape[0])
x = jnp.concatenate([graph.nodes, x], axis=-1)
layer_sizes = self._node_hidden_sizes[:]
if self._residual:
layer_sizes += [graph.nodes.shape[-1]]
x = hk.nets.MLP(layer_sizes, activate_final=False)(x)
if self._layer_norm:
x = hk.LayerNorm(axis=-1, create_scale=True, create_offset=True)(x)
if self._residual:
return graph.nodes + x
else:
return x
def __call__(self, graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
"""Apply this layer on the input graph."""
messages = self._compute_messages(graph)
updated_nodes = self._update_nodes(graph, messages)
return graph._replace(nodes=updated_nodes)
class SimpleGraphNet(hk.Module):
"""A simple graph net module, a stack of message passing layers."""
def __init__(self,
num_layers: int,
msg_hidden_size_factor: int = 2,
layer_norm: bool = False,
name: Optional[str] = None):
"""Constructor.
Args:
num_layers: number of message passing layers in the network.
msg_hidden_size_factor: size of message module hidden sizes as a factor of
the input node feature dimensionality.
layer_norm: whether to apply layer norm on node updates.
name: name of this module.
"""
super().__init__(name=name)
self._num_layers = num_layers
self._msg_hidden_size_factor = msg_hidden_size_factor
self._layer_norm = layer_norm
def __call__(self, graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
"""Run the simple graph net on the input data.
Args:
graph: input graph.
Returns:
graph: output graph.
"""
input_node_dim = graph.nodes.shape[-1]
msg_hidden_size = input_node_dim * self._msg_hidden_size_factor
for _ in range(self._num_layers):
graph = MLPMessagePassingLayer(
node_hidden_sizes=[],
msg_hidden_sizes=[msg_hidden_size],
layer_norm=self._layer_norm)(graph)
return graph
def add_reverse_edges(graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
"""Add edges in the reverse direction, copy edge features."""
senders = np.concatenate([graph.senders, graph.receivers], axis=0)
receivers = np.concatenate([graph.receivers, graph.senders], axis=0)
edges = np.concatenate([graph.edges, graph.edges], axis=0)
return graph._replace(senders=senders, receivers=receivers, edges=edges)
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/graph_net.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""WikiGraphs model modules."""
from . import embedding
from . import graph_net
from . import sampler
from . import transformer
from . import transformer_block
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/__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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tests for wikigraphs.model.sampler."""
from absl.testing import absltest
import jraph
import numpy as np
from wikigraphs.model import sampler
from wikigraphs.model import transformer as models
class SamplerTest(absltest.TestCase):
def test_uncond_sampler_runs(self):
prompt = np.array([[0, 1, 2, -1, -1],
[0, 1, 2, -1, -1]], dtype=np.int32)
vocab_size = prompt.max() + 1
bos_token = 0
memory_size = 2
params = None
def model_fn(x):
return models.TransformerXL(
vocab_size=vocab_size,
emb_dim=8,
num_layers=2,
num_heads=4,
cutoffs=[])(x, is_training=False, cache_steps=memory_size)
uncond_sampler = sampler.TransformerXLSampler(model_fn)
sample = uncond_sampler.sample(params, prompt)
self.assertTrue((sample[:, 0] == bos_token).all())
self.assertTrue((sample != -1).all())
self.assertEqual(sample.shape, prompt.shape)
sample2 = uncond_sampler.sample(params, prompt)
self.assertTrue((sample2[:, 0] == bos_token).all())
self.assertTrue((sample2 != -1).all())
self.assertEqual(sample2.shape, prompt.shape)
self.assertTrue((sample != sample2).any())
def test_bow2text_sampler_runs(self):
bow = np.array([[0, 0, 1, 0, 2, 0, 0, 1],
[0, 1, 0, 0, 1, 0, 1, 0]], dtype=np.int32)
prompt = np.array([[0, 1, 2, -1, -1, -1],
[0, 1, 2, -1, -1, -1]], dtype=np.int32)
vocab_size = prompt.max() + 1
bos_token = 0
memory_size = 2
params = None
def model_fn(bow, x):
return models.Bow2TextTransformer(
vocab_size=vocab_size,
emb_dim=16,
num_layers=2,
num_heads=4,
cutoffs=[])(bow, x, is_training=False, cache_steps=memory_size)
bow_sampler = sampler.Bow2TextTransformerSampler(model_fn)
sample = bow_sampler.sample(params, prompt, bow)
self.assertTrue((sample[:, 0] == bos_token).all())
self.assertTrue((sample != -1).all())
self.assertEqual(sample.shape, prompt.shape)
sample2 = bow_sampler.sample(params, prompt, bow)
self.assertTrue((sample2[:, 0] == bos_token).all())
self.assertTrue((sample2 != -1).all())
self.assertEqual(sample2.shape, prompt.shape)
self.assertTrue((sample != sample2).any())
def test_graph2text_sampler_runs(self):
graphs = jraph.GraphsTuple(
nodes=np.ones((4, 3), dtype=np.float32),
edges=np.ones((3, 1), dtype=np.float32),
senders=np.array([0, 2, 3], dtype=np.int32),
receivers=np.array([1, 3, 2], dtype=np.int32),
n_node=np.array([2, 2], dtype=np.int32),
n_edge=np.array([1, 2], dtype=np.int32),
globals=None,
)
prompt = np.array([[0, 1, 2, -1, -1, -1],
[0, 1, 2, -1, -1, -1]], dtype=np.int32)
vocab_size = prompt.max() + 1
bos_token = 0
memory_size = 2
params = None
def model_fn(graphs, max_graph_size, x):
return models.Graph2TextTransformer(
vocab_size=vocab_size,
emb_dim=8,
num_layers=2,
num_heads=4,
cutoffs=[],
gnn_embed_dim=8,
gnn_num_layers=2)(
graphs, max_graph_size, True, x,
is_training=False, cache_steps=memory_size)
graph_sampler = sampler.Graph2TextTransformerSampler(model_fn)
sample = graph_sampler.sample(params, prompt, graphs)
self.assertTrue((sample[:, 0] == bos_token).all())
self.assertTrue((sample != -1).all())
self.assertEqual(sample.shape, prompt.shape)
sample2 = graph_sampler.sample(params, prompt, graphs)
self.assertTrue((sample2[:, 0] == bos_token).all())
self.assertTrue((sample2 != -1).all())
self.assertEqual(sample2.shape, prompt.shape)
self.assertTrue((sample != sample2).any())
if __name__ == '__main__':
absltest.main()
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/sampler_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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Jax implementation of the Transformer-XL model."""
from typing import Dict, List, Optional, Tuple
import haiku as hk
from haiku import initializers as init
import jax
import jax.numpy as jnp
import jraph
import numpy as np
from wikigraphs.model import transformer_block
from wikigraphs.model.embedding import AdaptiveSoftmaxEmbedding
from wikigraphs.model.embedding import GraphEmbeddingModel
# For WikiText-103
DEFAULT_CUTOFFS = (20000 + 1, 40000 + 1, 200000 + 1)
def sequence_prediction_metrics(
logits: jnp.ndarray,
labels: jnp.ndarray,
mask: Optional[jnp.ndarray] = None
) -> Dict[str, float]:
"""Compute the metrics for sequence prediction.
Args:
logits: [B, T, V] array of logits.
labels: [B, T] array of labels.
mask: [B, T] array of binary masks, if provided.
Returns:
metrics: a dictionary of metrics.
"""
vocab_size = logits.shape[-1]
logps = jax.nn.log_softmax(logits)
labels_one_hot = hk.one_hot(labels, vocab_size)
class_logps = jnp.sum(logps * labels_one_hot, axis=-1)
prediction_correct = jnp.argmax(logits, axis=-1) == labels
if mask is not None:
masked_logps = mask * class_logps
total_count = jnp.sum(mask)
tokens_correct = jnp.sum(prediction_correct * mask)
seq_correct = jnp.all(
jnp.logical_or(prediction_correct, jnp.logical_not(mask)), axis=-1)
else:
masked_logps = class_logps
total_count = np.prod(class_logps.shape)
tokens_correct = jnp.sum(prediction_correct)
seq_correct = jnp.all(prediction_correct, axis=-1)
token_accuracy = tokens_correct.astype(jnp.float32) / total_count
seq_accuracy = jnp.mean(seq_correct)
log_probs = jnp.mean(jnp.sum(masked_logps, axis=-1))
total_loss = -jnp.sum(masked_logps)
loss = total_loss / total_count
return dict(
loss=loss,
total_loss=total_loss,
total_count=total_count,
token_accuracy=token_accuracy,
seq_accuracy=seq_accuracy,
log_probs=log_probs,
)
class TransformerXL(hk.Module):
"""TransformerXL language model with memory using GPT2 blocks.
TransformerXL: https://arxiv.org/abs/1901.02860
GPT-2: http://www.persagen.com/files/misc/radford2019language.pdf
"""
def __init__(self,
vocab_size: int = 256,
emb_dim: int = 256,
num_layers: int = 10,
num_heads: int = 8,
dropout_prob: float = 0.1,
dropout_attn_prob: float = 0.0,
self_att_init_scale: float = 0.02,
dense_init_scale: float = 0.02,
dense_dim: int = 2100,
cutoffs: List[int] = DEFAULT_CUTOFFS,
tail_shrink_factor: int = 1,
relative_pos_clamp_len: Optional[int] = None,
name: Optional[str] = None):
"""Initialize a TransformerXL.
Args:
vocab_size: the size of the vocabulary.
emb_dim: the dimensionality of the embeddings.
num_layers: number of transformer blocks.
num_heads: number of attention heads.
dropout_prob: dropout probability.
dropout_attn_prob: dropout probability of the attention module.
self_att_init_scale: the initialization scale of the VarianceScaling
used for the linear layer in the attention module.
dense_init_scale: the initialization scale of the VarianceScaling
used for the linear layer in the feedforward module.
dense_dim: feature size of the feedforward block.
cutoffs: the cutoff indices of the vocabulary used for the adaptive
softmax embedding.
tail_shrink_factor: how many times to shrink the hidden dimensionality
for low-frequency vocabulary after each cutoff in the adaptive softmax
embedding.
relative_pos_clamp_len: clamp length of the relative position embeddings.
name: Optional name for this Haiku module.
"""
super().__init__(name=name)
self._vocab_size = vocab_size
self._emb_dim = emb_dim
self._num_layers = num_layers
self._num_heads = num_heads
self._dropout_prob = dropout_prob
self._dropout_attn_prob = dropout_attn_prob
self._self_att_init_scale = self_att_init_scale
self._dense_init_scale = dense_init_scale
self._dense_dim = dense_dim
self._relative_pos_clamp_len = relative_pos_clamp_len
self._io_emb = AdaptiveSoftmaxEmbedding(
emb_dim, vocab_size, cutoffs=cutoffs,
tail_shrink_factor=tail_shrink_factor)
def __call__(self,
x: jnp.ndarray,
mask: Optional[jnp.ndarray] = None,
is_training: bool = True,
should_reset: Optional[jnp.ndarray] = None,
cache_steps: int = 0,
extra: Optional[jnp.ndarray] = None,
extra_mask: Optional[jnp.ndarray] = None) -> jnp.ndarray:
"""Computes the outputs of the TransformerXL.
Args:
x: [batch, timesteps]. Inputs at time step t.
mask: [batch, timesteps]. It indicates what tokens to be predicted. In
other words it corresponds to non-pad tokens in x_{t+1}.
is_training: whether the current stage is training or not.
should_reset: reset marker [batch, timesteps].
cache_steps: number of timesteps in the cache.
extra: if provided should be extra key-value input
[batch, extra_timesteps, in_dim].
extra_mask: if provided should be the mask for extra key-value input,
[batch, extra_timesteps].
Returns:
output: transformer output [batch, timesteps].
"""
if cache_steps == 0:
cache_steps = x.shape[1]
if should_reset is None:
should_reset = jnp.where(x == 1, 1, 0)
h = self._io_emb.embed_input(x)
if mask is not None:
attention_mask = mask[:, None, None, :]
else:
attention_mask = None
head_dim = self._emb_dim // self._num_heads
assert self._emb_dim % self._num_heads == 0, 'Head dim should be an int.'
# Biases for relative position embedding shared across all layers
r_w_bias = hk.get_parameter(
'r_w_bias', [1, 1, self._num_heads, head_dim],
init=init.RandomNormal(stddev=self._self_att_init_scale))
r_r_bias = hk.get_parameter(
'r_r_bias', [1, 1, self._num_heads, head_dim],
init=init.RandomNormal(stddev=self._self_att_init_scale))
for i in range(self._num_layers):
if mask is not None:
h *= mask[:, :, None]
h = transformer_block.GPT2Block(
r_w_bias=r_w_bias,
r_r_bias=r_r_bias,
causal=True,
dense_dim=self._dense_dim,
dropout_prob=self._dropout_prob,
dropout_attn_prob=self._dropout_attn_prob,
num_heads=self._num_heads,
self_att_init_scale=self._self_att_init_scale,
dense_init_scale=self._dense_init_scale,
relative_pos_clamp_len=self._relative_pos_clamp_len,
name='transformer_block_{}'.format(i),
)(
h, mask=attention_mask, is_training=is_training,
should_reset=should_reset, cache_steps=cache_steps,
extra=extra, extra_mask=extra_mask)
if mask is not None:
h *= mask[:, :, None]
return self._io_emb.embed_output(h)
def loss(self,
inputs: jnp.ndarray,
labels: jnp.ndarray,
mask: Optional[jnp.ndarray] = None,
is_training: bool = True,
should_reset: Optional[jnp.ndarray] = None,
cache_steps: int = 0,
extra: Optional[jnp.ndarray] = None,
extra_mask: Optional[jnp.ndarray] = None
) -> Tuple[float, Dict[str, float]]:
"""Computes the loss of the TransformerXL.
Args:
inputs: [batch, timesteps].
labels: [batch, timesteps].
mask: [batch, timesteps]. It indicates what tokens to be predicted. In
other words it corresponds to non-pad tokens in the `labels`.
is_training: whether the current stage is training or not.
should_reset: reset marker [batch, timesteps].
cache_steps: number of timesteps in the cache.
extra: if provided should be extra key-value input
[batch, extra_timesteps, in_dim].
extra_mask: if provided should be the mask for extra key-value input,
[batch, extra_timesteps].
Returns:
output: loss and a dict containing metrics.
"""
# [B, T, V]
logits = self(inputs, mask=mask, is_training=is_training,
should_reset=should_reset, cache_steps=cache_steps,
extra=extra, extra_mask=extra_mask)
metrics = sequence_prediction_metrics(logits, labels, mask)
return metrics['loss'], metrics
def repeat_rows(a: jnp.ndarray, repeats: int, out_length: int) -> jnp.ndarray:
"""Repeat rows of input tensor a.
Output is
[a[0],
a[0],
...
a[0], # A total of repeats[0] copies of a[0].
a[1],
a[1],
...,
a[1], # A total of repeats[1] copies of a[1].
...
a[n-1]], # A total of repeats[n-1] copies of a[n-1].
Args:
a: [n_rows, ...] input tensor.
repeats: [n_rows] int tensor, the number of repeats for each row.
out_length: number of rows in the output, it should be the same as
sum(repeats), provided to be static for jit.
Returns:
out: [out_length, ...] output tensor.
"""
a = jnp.asarray(a)
n = a.shape[0]
assert n == repeats.size
chunk_start = jnp.cumsum(repeats)
idx = jnp.sum(jnp.arange(out_length)[:, None] >= chunk_start[None, :],
axis=-1)
return a[idx]
def unpack_and_pad(
packed: jnp.ndarray,
split_sizes: jnp.ndarray,
pad_size: int,
pad_value: int = 0) -> Tuple[jnp.ndarray, jnp.ndarray]:
"""Unpack and pad tensors to a standard size.
Args:
packed: a [total_size, ...] tensor, which contains n individual tensors
concatenated along the 0-th axis.
split_sizes: size [n] int tensor, size of each individual tensor.
pad_size: size for each split to pad to.
pad_value: the value to use for padding.
Returns:
tensors: [n, pad_size, ...] tensor, tensors[i] is the i-th individual tensor
padded to pad_size length.
mask: [n, pad_size] mask tensor indicating which value is padded.
"""
in_shape = list(packed.shape)
total_size = in_shape[0]
n_splits = split_sizes.shape[0]
idx = jnp.arange(pad_size)
masks = split_sizes[:, None] > idx[None, :]
out_shape = in_shape[:]
out_shape[0] = n_splits * pad_size
out = jnp.full(out_shape, pad_value, dtype=packed.dtype)
# Index for the rows of `packed`:
# Define split_start[k] = sum_{i=0}^{k-1} split_sizes[i], which is the
# starting index of split k. So if split_start[k] <= i < split_start[k+1]
# then index belongs to split k. We therefore have:
# idx[i] = k * pad_size + i - split_start[k]
cumsum = jnp.concatenate([jnp.array([0], dtype=split_sizes.dtype),
jnp.cumsum(split_sizes)[:-1]])
idx = jnp.arange(total_size)
idx += repeat_rows(jnp.arange(n_splits), split_sizes, total_size) * pad_size
idx -= repeat_rows(cumsum, split_sizes, total_size)
out = out.at[idx].set(packed)
out = out.reshape([n_splits, pad_size] + out_shape[1:])
return out, masks
class Graph2TextTransformer(hk.Module):
"""A graph2text TransformerXL model.
It embeds the graph with a simple graph neural network model, and passes the
graph embeddings to the TransformerXL model, which are presented as the extra
inputs to attend to in addition to the text embeddings inputs.
"""
def __init__(self,
*transformer_args,
gnn_embed_dim: int = 128,
gnn_num_layers: int = 5,
gnn_layer_norm: bool = False,
name: Optional[str] = None,
**transformer_kwargs):
"""Constructor.
Args:
*transformer_args: args for the transformer module.
gnn_embed_dim: node embedding size.
gnn_num_layers: number of message passing layers to use.
gnn_layer_norm: whether to use layer norm in the GNN.
name: optional name for this module.
**transformer_kwargs: kwargs for the transformer module.
"""
super().__init__(name=name)
self._transformer = TransformerXL(*transformer_args, **transformer_kwargs)
self._gnn = GraphEmbeddingModel(
embed_dim=gnn_embed_dim,
num_layers=gnn_num_layers,
use_layer_norm=gnn_layer_norm)
def _encode_graphs(self,
graphs: jraph.GraphsTuple,
pad_n_nodes: Optional[int] = None,
padded: bool = False) -> Tuple[jnp.ndarray, jnp.ndarray]:
"""Encode graphs so that it can be used in the transformer.
Args:
graphs: a graph structured using jraph.GraphsTuple.
pad_n_nodes: size for each node to pad to.
padded: Whether to pad each graph to the same number of nodes.
Returns:
tensors: unpacked and padded graph nodes.
mask: mask tensor indicating which value is padded.
"""
graphs = self._gnn(graphs)
if pad_n_nodes is None:
pad_n_nodes = graphs.n_node.max()
out, mask = unpack_and_pad(graphs.nodes, graphs.n_node, pad_n_nodes)
if padded:
# Remove the padding graph from the batch
return out[:-1], mask[:-1]
else:
return out, mask
def __call__(self,
graphs: jraph.GraphsTuple,
pad_n_nodes: int,
batch_padded: bool,
*args, **kwargs):
"""Computes the outputs of the graph2text TransformerXL.
Args:
graphs: a graph structured using graph_net.Graph.
pad_n_nodes: size for each node to pad to.
batch_padded: whether the graph batch is padded or not.
*args: args to the TransformerXL model.
**kwargs: kwargs to the TransformerXL model.
Returns:
output: transformer output [batch, timesteps].
"""
extra, extra_mask = self._encode_graphs(graphs, pad_n_nodes, batch_padded)
return self._transformer(
*args, extra=extra, extra_mask=extra_mask, **kwargs)
def loss(self,
graphs: jraph.GraphsTuple,
pad_n_nodes: int,
batch_padded: bool,
inputs: jnp.ndarray,
labels: jnp.ndarray,
mask: jnp.ndarray,
**kwargs):
"""Computes the loss of the graph2text TransformerXL.
Args:
graphs: a graph structured using graph_net.Graph.
pad_n_nodes: size for each node to pad to.
batch_padded: whether the graph batch is padded or not.
inputs: [batch, timesteps].
labels: [batch, timesteps].
mask: [batch, timesteps].
**kwargs: kwargs to the TransformerXL model.
Returns:
output: loss and a dict containing metrics.
"""
extra, extra_mask = self._encode_graphs(graphs, pad_n_nodes, batch_padded)
return self._transformer.loss(
inputs, labels, mask, extra=extra, extra_mask=extra_mask, **kwargs)
class Bow2TextTransformer(hk.Module):
"""A bag-of-words to text TransformerXL model.
This model embeds bag-of-words into vectors and the text transformer can then
condition on these vectors to generate text.
More specifically, the bow embedded vectors will be treated as extra tokens
that the transformer can attend to, in addition to the text data it is already
modelling.
To make the model more expressive, we allow each bag-of-words to be embedded
into potentially more than 1 vectors, and the transformer will treat them as
more than 1 extra tokens correspondingly.
"""
def __init__(self,
*transformer_args,
bow_embedding_dim: int = 256,
bow_n_tokens: int = 1,
name: Optional[str] = None,
**transformer_kwargs):
"""Constructor.
Args:
*transformer_args: the TransformerXL constructor arguments.
bow_embedding_dim: dimensionality for the bag-of-words embeddings.
bow_n_tokens: number of extra tokens to create for the bag-of-words
representations.
name: optional name for this module.
**transformer_kwargs: kwargs for the transformer module.
"""
super().__init__(name=name)
self._transformer = TransformerXL(*transformer_args, **transformer_kwargs)
self._bow_embedding_dim = bow_embedding_dim
self._bow_n_tokens = bow_n_tokens
def _encode_bow(self, bow: jnp.ndarray) -> jnp.ndarray:
"""Encode the bag-of-words into tensors that can be used by the transormer.
Args:
bow: a [batch_size, bow_vocab_size] tensor, each row is a bow vector.
Returns:
embeddings: [batch_size, bow_n_tokens, bow_embedding_dim] tensor.
"""
batch_size = bow.shape[0]
bow = bow.astype(jnp.float32)
# [B, D * n]
embeddings = hk.Linear(self._bow_embedding_dim * self._bow_n_tokens)(bow)
embeddings = transformer_block.layer_norm(jax.nn.gelu(embeddings))
return jnp.reshape(
embeddings, [batch_size, self._bow_n_tokens, self._bow_embedding_dim])
def __call__(self, bow: jnp.ndarray, *args, **kwargs):
"""Compute the output of this bag-of-words-to-text transformer model.
Args:
bow: a [batch_size, bow_vocab_size] tensor, each row is a bow vector.
*args: args to the TransformerXL model.
**kwargs: kwargs to the TransformerXL model.
Returns:
output: transformer output [batch, timesteps].
"""
return self._transformer(*args, extra=self._encode_bow(bow), **kwargs)
def loss(self, bow: jnp.ndarray, *args, **kwargs):
"""Computes the loss of the graph2text TransformerXL.
Args:
bow: a [batch_size, bow_vocab_size] tensor, each row is a bow vector.
*args: args to the TransformerXL model.
**kwargs: kwargs to the TransformerXL model.
Returns:
output: loss and a dict containing metrics.
"""
return self._transformer.loss(*args, extra=self._encode_bow(bow), **kwargs)
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/transformer.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tests for wikigraphs.model.graph_net."""
from absl import logging
from absl.testing import absltest
import haiku as hk
import jax
import jax.numpy as jnp
import jraph
import numpy as np
import optax
from wikigraphs.model import graph_net as gn
class GraphNetTest(absltest.TestCase):
def test_node_classification(self):
# If node has more than 2 neighbors --> class 1, otherwise class 0.
# Graph structure:
# 1 4
# | \ / |
# | 0 - 3 |
# | / \ |
# 2 5
edges = np.array([
[0, 1],
[1, 2],
[2, 0],
[0, 3],
[3, 4],
[4, 5],
[5, 3],
], dtype=np.int32)
n_node = edges.max() + 1
n_edge = edges.shape[0]
g = jraph.GraphsTuple(
senders=edges[:, 0],
receivers=edges[:, 1],
edges=np.ones((edges.shape[0], 1), dtype=np.float32),
nodes=np.ones((n_node, 1), dtype=np.float32),
n_node=np.array([n_node], dtype=np.int32),
n_edge=np.array([n_edge], dtype=np.int32),
globals=None)
g = gn.add_reverse_edges(g)
targets = np.array([1, 0, 0, 1, 0, 0], dtype=np.int32)
n_classes = 2
def forward(graph, targets):
model = gn.SimpleGraphNet(num_layers=5, layer_norm=False)
graph = model(graph)
nodes = graph.nodes
logits = hk.Linear(n_classes)(nodes)
pred = logits.argmax(axis=-1)
accuracy = (pred == targets).mean()
targets = jax.nn.one_hot(targets, n_classes, dtype=jnp.float32)
return -jnp.mean(jnp.sum(
jax.nn.log_softmax(logits, axis=-1) * targets, axis=-1)), accuracy
init_fn, apply_fn = hk.without_apply_rng(hk.transform(forward))
rng = hk.PRNGSequence(0)
params = init_fn(next(rng), g, targets)
optimizer = optax.chain(
optax.scale_by_adam(),
optax.scale(-1e-3))
opt_state = optimizer.init(params)
apply_fn = jax.jit(apply_fn)
for i in range(500):
(loss, acc), grad = jax.value_and_grad(apply_fn,
has_aux=True)(params, g, targets)
updates, opt_state = optimizer.update(grad, opt_state, params)
params = optax.apply_updates(params, updates)
if (i + 1) % 100 == 0:
logging.info('Step %d, loss %.8f, accuracy %.4f', i + 1, loss, acc)
self.assertLess(loss, 0.01)
self.assertEqual(acc, 1.0)
def test_pad_size(self):
self.assertEqual(gn.pad_size(1), 1)
self.assertEqual(gn.pad_size(5), 8)
self.assertEqual(gn.pad_size(7), 8)
self.assertEqual(gn.pad_size(101), 128)
def test_pad_graphs(self):
# No new edges to add
graphs = jraph.GraphsTuple(
nodes=np.arange(6)[:, None],
edges=np.arange(4)[:, None],
senders=np.array([0, 2, 3, 4]),
receivers=np.array([1, 3, 4, 5]),
n_node=np.array([2, 4]),
n_edge=np.array([1, 3]),
globals=None)
padded = gn.pad_graphs(graphs)
np.testing.assert_array_equal(
padded.nodes,
np.array([0, 1, 2, 3, 4, 5, 0, 0])[:, None])
np.testing.assert_array_equal(padded.edges, graphs.edges)
np.testing.assert_array_equal(padded.senders, graphs.senders)
np.testing.assert_array_equal(padded.receivers, graphs.receivers)
np.testing.assert_array_equal(padded.n_node, [2, 4, 2])
np.testing.assert_array_equal(padded.n_edge, [1, 3, 0])
# Add just a single default node
graphs = jraph.GraphsTuple(
nodes=np.arange(7)[:, None],
edges=np.arange(5)[:, None],
senders=np.array([0, 2, 3, 5, 6]),
receivers=np.array([1, 3, 4, 6, 5]),
n_node=np.array([2, 3, 2]),
n_edge=np.array([1, 2, 2]),
globals=None)
padded = gn.pad_graphs(graphs)
np.testing.assert_array_equal(
padded.nodes,
np.array([0, 1, 2, 3, 4, 5, 6, 0])[:, None])
np.testing.assert_array_equal(
padded.edges,
np.array([0, 1, 2, 3, 4, 0, 0, 0])[:, None])
np.testing.assert_array_equal(
padded.senders,
[0, 2, 3, 5, 6, 7, 7, 7])
np.testing.assert_array_equal(
padded.receivers,
[1, 3, 4, 6, 5, 7, 7, 7])
np.testing.assert_array_equal(
padded.n_node, [2, 3, 2, 1])
np.testing.assert_array_equal(
padded.n_edge, [1, 2, 2, 3])
# Num. nodes is a power of 2 but we still pad at least one extra node
graphs = jraph.GraphsTuple(
nodes=np.arange(8)[:, None],
edges=np.arange(5)[:, None],
senders=np.array([0, 2, 3, 5, 6]),
receivers=np.array([1, 3, 4, 6, 7]),
n_node=np.array([2, 3, 3]),
n_edge=np.array([1, 2, 2]),
globals=None)
padded = gn.pad_graphs(graphs)
np.testing.assert_array_equal(
padded.nodes,
np.array([0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0])[:, None])
np.testing.assert_array_equal(
padded.edges,
np.array([0, 1, 2, 3, 4, 0, 0, 0])[:, None])
np.testing.assert_array_equal(
padded.senders,
[0, 2, 3, 5, 6, 8, 8, 8])
np.testing.assert_array_equal(
padded.receivers,
[1, 3, 4, 6, 7, 8, 8, 8])
np.testing.assert_array_equal(
padded.n_node, [2, 3, 3, 8])
np.testing.assert_array_equal(
padded.n_edge, [1, 2, 2, 3])
def test_batch_graphs_by_device(self):
# batch 4 graphs for 2 devices
num_devices = 2
graphs = [
jraph.GraphsTuple(
nodes=np.arange(2)[:, None],
edges=np.arange(2)[:, None],
senders=np.array([0, 1]),
receivers=np.array([1, 0]),
n_node=np.array([2]),
n_edge=np.array([2]),
globals=None),
jraph.GraphsTuple(
nodes=np.arange(3)[:, None],
edges=np.arange(1)[:, None],
senders=np.array([2]),
receivers=np.array([0]),
n_node=np.array([3]),
n_edge=np.array([1]),
globals=None),
jraph.GraphsTuple(
nodes=np.arange(4)[:, None],
edges=np.arange(2)[:, None],
senders=np.array([1, 0]),
receivers=np.array([2, 3]),
n_node=np.array([4]),
n_edge=np.array([2]),
globals=None),
jraph.GraphsTuple(
nodes=np.arange(5)[:, None],
edges=np.arange(3)[:, None],
senders=np.array([2, 1, 3]),
receivers=np.array([1, 4, 0]),
n_node=np.array([5]),
n_edge=np.array([3]),
globals=None),
]
batched = gn.batch_graphs_by_device(graphs, num_devices)
self.assertLen(batched, num_devices)
np.testing.assert_array_equal(
batched[0].nodes,
np.array([0, 1, 0, 1, 2])[:, None])
np.testing.assert_array_equal(
batched[0].edges,
np.array([0, 1, 0])[:, None])
np.testing.assert_array_equal(
batched[0].senders,
np.array([0, 1, 4]))
np.testing.assert_array_equal(
batched[0].receivers,
np.array([1, 0, 2]))
np.testing.assert_array_equal(
batched[0].n_node,
np.array([2, 3]))
np.testing.assert_array_equal(
batched[0].n_edge,
np.array([2, 1]))
np.testing.assert_array_equal(
batched[1].nodes,
np.array([0, 1, 2, 3, 0, 1, 2, 3, 4])[:, None])
np.testing.assert_array_equal(
batched[1].edges,
np.array([0, 1, 0, 1, 2])[:, None])
np.testing.assert_array_equal(
batched[1].senders,
np.array([1, 0, 6, 5, 7]))
np.testing.assert_array_equal(
batched[1].receivers,
np.array([2, 3, 5, 8, 4]))
np.testing.assert_array_equal(
batched[1].n_node,
np.array([4, 5]))
np.testing.assert_array_equal(
batched[1].n_edge,
np.array([2, 3]))
def test_pad_graphs_by_device(self):
graphs = [
jraph.GraphsTuple(
nodes=np.arange(5)[:, None], # pad to 8
edges=np.arange(3)[:, None], # pad to 4
senders=np.array([0, 1, 4]), # pad to 4
receivers=np.array([1, 0, 2]), # pad to 4
n_node=np.array([2, 3]), # pad to 3
n_edge=np.array([2, 1]), # pad to 3
globals=None),
jraph.GraphsTuple(
nodes=np.arange(4)[:, None], # pad to 8
edges=np.arange(1)[:, None], # pad to 4
senders=np.array([1]), # pad to 4
receivers=np.array([0]), # pad to 4
n_node=np.array([2, 2]), # pad to 3
n_edge=np.array([1, 0]), # pad to 3
globals=None),
]
padded = gn.pad_graphs_by_device(graphs)
np.testing.assert_array_equal(
padded.nodes,
np.array([0, 1, 2, 3, 4, 0, 0, 0,
0, 1, 2, 3, 0, 0, 0, 0])[:, None])
np.testing.assert_array_equal(
padded.edges,
np.array([0, 1, 2, 0, 0, 0, 0, 0])[:, None])
np.testing.assert_array_equal(
padded.senders,
np.array([0, 1, 4, 5, 1, 4, 4, 4]))
np.testing.assert_array_equal(
padded.receivers,
np.array([1, 0, 2, 5, 0, 4, 4, 4]))
np.testing.assert_array_equal(
padded.n_node,
np.array([2, 3, 3, 2, 2, 4]))
np.testing.assert_array_equal(
padded.n_edge,
np.array([2, 1, 1, 1, 0, 3]))
if __name__ == '__main__':
absltest.main()
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/graph_net_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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Samplers for the graph2text transformers."""
import abc
from typing import Any, Optional, Mapping
import haiku as hk
import jax
import jax.numpy as jnp
import jraph
import numpy as np
from wikigraphs.model import graph_net as gn
class BaseSampler:
"""Base class for transformer samplers."""
def __init__(self,
model_fn,
temperature: float = 1.0,
device: Optional[Any] = None,
rng: Optional[np.ndarray] = None):
"""Constructor.
Args:
model_fn: a transformer language model defined in model.transformer.
temperature: sampling temperature.
device: the sampler will run on this device if provided.
rng: random number generator.
"""
self._temperature = temperature
self._device = device or jax.local_devices()[0]
init_fn, apply_fn = hk.transform_with_state(model_fn)
if rng is None:
rng = jax.random.PRNGKey(np.random.randint(2**32))
rng = jax.random.fold_in(rng, jax.host_id())
self._rng = rng
self._init_state = None
self._jit_model(init_fn, apply_fn)
def _jit_model(self, init_fn, apply_fn):
"""Jit the `init_fn` and `apply_fn`."""
pass
@abc.abstractmethod
def _sample(self,
params: Mapping[str, Any],
state: Mapping[str, Any],
rng: jnp.ndarray,
x: jnp.ndarray,
**kwargs) -> np.ndarray:
"""Generate samples.
Args:
params: parameters of the transformer.
state: state of the transformer.
rng: random number generator.
x: a prompt of shape [batch_size, sample_len], in which an entry of -1
indicates it will be generate at that place. Otherwise it acts as the
prompt.
**kwargs: additional inputs.
Returns:
output: [batch_size, sample_len] tensor, the generated sequence.
"""
@abc.abstractmethod
def sample(self,
params: Mapping[str, Any],
x: jnp.ndarray,
**kwargs) -> jnp.ndarray:
"""Generate samples based on the given parameters and prompts.
Args:
params: parameters of the transformer.
x: a prompt of shape [batch_size, sample_len], in which an entry of -1
indicates it will be generate at that place. Otherwise it acts as the
prompt.
**kwargs: additional inputs.
Returns:
output: the generated sequence.
"""
class TransformerXLSampler(BaseSampler):
"""Sampling from the TransformerXL model."""
def _jit_model(self, init_fn, apply_fn):
"""Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`."""
self._init_fn = jax.jit(init_fn, device=self._device)
self._apply_fn = apply_fn
self._sample_fn = jax.jit(self._sample, device=self._device)
def _sample(self,
params: Mapping[str, Any],
state: Mapping[str, Any],
rng: jnp.ndarray,
x: jnp.ndarray) -> np.ndarray:
"""Generate unconditional samples.
Args:
params: parameters of the transformer.
state: state of the transformer.
rng: random number generator.
x: a prompt of shape [batch_size, sample_len], in which an entry of -1
indicates it will be generate at that place. Otherwise it acts as the
prompt.
Returns:
output: [batch_size, sample_len] tensor, the generated sequence.
"""
batch_size, sample_len = x.shape
def one_step(params, state, rng, i, x):
step_sample = jax.lax.dynamic_slice(x, [0, i], [batch_size, 1])
rng, rng_ = jax.random.split(rng)
# step_sample shape is [batch_size, 1].
logits, state = self._apply_fn(params, state, rng_, step_sample)
rng, rng_ = jax.random.split(rng)
step_sample = jax.random.categorical(rng_, logits / self._temperature)
update = jnp.where(x[:, i + 1] < 0, step_sample[:, 0], x[:, i + 1])[:,
None]
x = jax.lax.dynamic_update_slice(x, update, [0, i + 1])
return state, rng, x
def loop_body(i, data):
state, rng, x = data
return one_step(params, state, rng, i, x)
_, _, x = jax.lax.fori_loop(0, sample_len - 1, loop_body,
(state, rng, x))
return x
def sample(self,
params: Mapping[str, Any],
x: jnp.ndarray) -> jnp.ndarray:
"""Generate samples based on the given graphs and parameters.
Args:
params: parameters of the transformer.
x: a prompt of shape [batch_size, sample_len], in which an entry of -1
indicates it will be generate at that place. Otherwise it acts as the
prompt.
Returns:
output: the generated sequence.
"""
if self._init_state is None:
self._rng, rng = jax.random.split(self._rng)
self._init_params, self._init_state = self._init_fn(rng, x[:, :1])
if params is None:
params = self._init_params
self._rng, rng = jax.random.split(self._rng)
sample = self._sample_fn(params, self._init_state, rng, x)
return sample
class Bow2TextTransformerSampler(BaseSampler):
"""Sampling from the TransformerXL model."""
def _jit_model(self, init_fn, apply_fn):
"""Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`."""
self._init_fn = jax.jit(init_fn, device=self._device)
self._apply_fn = apply_fn
self._sample_fn = jax.jit(self._sample, device=self._device)
def _sample(self,
params: Mapping[str, Any],
state: Mapping[str, Any],
rng: jnp.ndarray,
bow: jnp.ndarray,
x: jnp.ndarray) -> np.ndarray:
"""Generate samples conditioned on the bag-of-words of the graph.
Args:
params: parameters of the transformer.
state: state of the transformer.
rng: random number generator.
bow: a [batch_size, bow_vocab_size] tensor, each row is a bow vector.
x: a prompt of shape [batch_size, sample_len], in which an entry of -1
indicates it will be generate at that place. Otherwise it acts as the
prompt.
Returns:
output: [batch_size, sample_len] tensor, the generated sequence.
"""
batch_size, sample_len = x.shape
def one_step(params, state, rng, i, x):
step_sample = jax.lax.dynamic_slice(x, [0, i], [batch_size, 1])
rng, rng_ = jax.random.split(rng)
# step_sample shape is [batch_size, 1].
logits, state = self._apply_fn(params, state, rng_, bow, step_sample)
rng, rng_ = jax.random.split(rng)
step_sample = jax.random.categorical(rng_, logits / self._temperature)
update = jnp.where(x[:, i + 1] < 0, step_sample[:, 0], x[:, i + 1])[:,
None]
x = jax.lax.dynamic_update_slice(x, update, [0, i + 1])
return state, rng, x
def loop_body(i, data):
state, rng, x = data
return one_step(params, state, rng, i, x)
_, _, x = jax.lax.fori_loop(0, sample_len - 1, loop_body,
(state, rng, x))
return x
def sample(self,
params: Mapping[str, Any],
x: jnp.ndarray,
bow: jnp.ndarray) -> jnp.ndarray:
"""Generate samples based on the given graphs and parameters.
Args:
params: parameters of the transformer.
x: a prompt of shape [batch_size, sample_len], in which an entry of -1
indicates it will be generate at that place. Otherwise it acts as the
prompt.
bow: a [batch_size, bow_vocab_size] tensor, each row is a bow vector.
Returns:
output: the generated sequence.
"""
if self._init_state is None:
self._rng, rng = jax.random.split(self._rng)
self._init_params, self._init_state = self._init_fn(rng, bow, x[:, :1])
if params is None:
params = self._init_params
self._rng, rng = jax.random.split(self._rng)
sample = self._sample_fn(params, self._init_state, rng, bow, x)
return sample
class Graph2TextTransformerSampler(BaseSampler):
"""Sampling from the Graph2Text TransformerXL model."""
def _jit_model(self, init_fn, apply_fn):
"""Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`."""
# `pad_n_nodes` is set as a static argument.
self._init_fn = jax.jit(init_fn, device=self._device, static_argnums=2)
self._apply_fn = apply_fn
self._sample_fn = jax.jit(self._sample, device=self._device,
static_argnums=4)
def _sample(self,
params: Mapping[str, Any],
state: Mapping[str, Any],
rng: jnp.ndarray,
graphs: jraph.GraphsTuple,
pad_n_nodes: int,
x: jnp.ndarray) -> np.ndarray:
"""Generate samples conditioned on the bag-of-words reprensation of graph.
Args:
params: parameters of the transformer.
state: state of the transformer.
rng: random number generator.
graphs: a graph structured using graph_net.Graph.
pad_n_nodes: size for each node to pad to.
x: a prompt of shape [batch_size, sample_len], in which an entry of -1
indicates it will be generate at that place. Otherwise it acts as the
prompt.
Returns:
output: [batch_size, sample_len] tensor, the generated sequence.
"""
batch_size, sample_len = x.shape
def one_step(params, state, rng, i, x):
step_sample = jax.lax.dynamic_slice(x, [0, i], [batch_size, 1])
rng, rng_ = jax.random.split(rng)
# step_sample shape is [batch_size, 1].
logits, state = self._apply_fn(
params, state, rng_, graphs, pad_n_nodes, step_sample)
rng, rng_ = jax.random.split(rng)
step_sample = jax.random.categorical(rng_, logits / self._temperature)
update = jnp.where(x[:, i + 1] < 0, step_sample[:, 0], x[:, i + 1])[:,
None]
x = jax.lax.dynamic_update_slice(x, update, [0, i + 1])
return state, rng, x
def loop_body(i, data):
state, rng, x = data
return one_step(params, state, rng, i, x)
_, _, x = jax.lax.fori_loop(0, sample_len - 1, loop_body,
(state, rng, x))
return x
def sample(self,
params: Mapping[str, Any],
x: jnp.ndarray,
graphs: jraph.GraphsTuple,
pad: bool = True) -> jnp.ndarray:
"""Generate samples based on the given graphs and parameters.
Args:
params: parameters of the transformer.
x: a prompt of shape [batch_size, sample_len], in which an entry of -1
indicates it will be generate at that place. Otherwise it acts as the
prompt.
graphs: a graph structured using graph_net.Graph.
pad: whether to pad the graph nodes and edges or not.
Returns:
output: the generated sequence.
"""
if pad:
graphs = gn.pad_graphs(graphs)
max_graph_size = gn.pad_size(graphs.n_node.max())
else:
max_graph_size = graphs.n_node.max()
if self._init_state is None:
self._rng, rng = jax.random.split(self._rng)
self._init_params, self._init_state = self._init_fn(
rng, graphs, max_graph_size, x[:, :1])
if params is None:
params = self._init_params
self._rng, rng = jax.random.split(self._rng)
sample = self._sample_fn(
params, self._init_state, rng, graphs, max_graph_size, x)
return sample
|
deepmind-research-master
|
wikigraphs/wikigraphs/model/sampler.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tests for wikigraphs.data.wikitext."""
from absl.testing import absltest
from wikigraphs.data import tokenizers
from wikigraphs.data import wikitext
WIKITEXT_ROOT = '/tmp/data/wikitext-103'
WIKITEXT_VOCAB_FILE = '/tmp/data/wikitext-vocab.csv'
class WikitextTest(absltest.TestCase):
def test_wikitext_size(self):
valid_set = wikitext.RawDataset(
subset='valid', shuffle_data=False, data_dir=WIKITEXT_ROOT)
n_tokens = 0
n_articles = 0
for article in valid_set:
n_tokens += len([t for t in article.text.split(' ') if t])
n_articles += 1
# Dataset size must match published values.
self.assertEqual(n_tokens, 217646)
self.assertEqual(n_articles, 60)
def test_wikitext_dataset_size(self):
tokenizer = tokenizers.WordTokenizer(vocab_file=WIKITEXT_VOCAB_FILE)
batch_size = 4
timesteps = 256
valid_set = wikitext.WikitextDataset(
tokenizer=tokenizer, batch_size=batch_size, timesteps=timesteps,
subset='valid', shuffle_data=False, repeat=False,
data_dir=WIKITEXT_ROOT)
n_tokens = 0
n_bos = 0
for batch in valid_set:
n_tokens += (batch['obs'] != tokenizer.pad_token()).sum()
n_bos += (batch['obs'] == tokenizer.bos_token()).sum()
self.assertEqual(
batch['obs'].shape, (batch_size, timesteps))
self.assertEqual(
batch['target'].shape, (batch_size, timesteps))
self.assertEqual(
batch['should_reset'].shape, (batch_size, timesteps))
self.assertEqual(
batch['mask'].shape, (batch_size, timesteps))
n_tokens -= n_bos
self.assertEqual(n_tokens, 217646)
self.assertEqual(n_bos, 60)
if __name__ == '__main__':
absltest.main()
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/wikitext_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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tests for wikigraphs.data.tokenizers."""
from absl.testing import absltest
from wikigraphs.data import tokenizers
WIKITEXT_VOCAB_FILE = '/tmp/data/wikitext-vocab.csv'
GRAPH_VOCAB_FILE = '/tmp/data/graph-vocab.csv'
class TokenizerTest(absltest.TestCase):
def test_tokenizer(self):
tokenizer = tokenizers.WordTokenizer(vocab_file=WIKITEXT_VOCAB_FILE)
# Vocab size must match published number.
self.assertEqual(tokenizer.vocab_size, 267735 + 2)
s = 'Hello world ! \n How are you ?'
encoded = tokenizer.encode(s, prepend_bos=True)
self.assertEqual(encoded.shape, (9,))
decoded = tokenizer.decode(encoded)
self.assertEqual(s, decoded)
def test_graph_tokenizer_tokenize_nodes_edges(self):
self.assertEqual(
tokenizers.GraphTokenizer.split_node(
'"Hello, how are you?"'),
['hello', ',', 'how', 'are', 'you', '?'])
self.assertEqual(
tokenizers.GraphTokenizer.split_node(
'"This building was built in 1998."'),
['this', 'building', 'was', 'built', 'in', '<number>', '.'])
self.assertEqual(
tokenizers.GraphTokenizer.split_node('ns/m.030ssw'),
['<entity>'])
self.assertEqual(
tokenizers.GraphTokenizer.split_edge('ns/common.topic.description'),
['common', 'topic', 'description'])
self.assertEqual(
tokenizers.GraphTokenizer.split_edge('ns/type.object.name'),
['type', 'object', 'name'])
def test_graph_tokenizer_vocab(self):
tokenizer = tokenizers.GraphTokenizer(vocab_file=GRAPH_VOCAB_FILE)
self.assertEqual(tokenizer.vocab_size, 31087 + 3)
if __name__ == '__main__':
absltest.main()
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/tokenizers_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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Some tools for processing data."""
from typing import Any, Iterator
from absl import logging
import numpy as np
def pad_to(x: np.array, size: int, axis: int = -1, pad_value: float = 0.):
"""Pad an array to the specified size along a specified axis."""
if x.shape[axis] > size:
raise ValueError(f'Data item has size {x.shape[axis]} larger than {size}'
f' in axis {axis} already.')
elif x.shape[axis] == size:
return x
else:
pad_amount = [(0, 0)] * x.ndim
pad_amount[axis] = (0, size - x.shape[axis])
return np.pad(x, pad_amount, mode='constant', constant_values=pad_value)
def dynamic_batch(
iterable: Iterator[Any],
batch_size: int,
timesteps: int,
return_incomplete_batch: bool = False,
pad: bool = False,
pad_value: float = 0.) -> Iterator[Any]:
"""Batches up values in iterable to [batch_size, timesteps].
This function takes items from the iterable and pack them into the batch.
Sequence #i in the batch is a continuation from the sequence #i in the
previous batch, i.e. it will start from where the previous sequence left over.
When an item is finished, a new item is taken from the iterable to append to
the sequence and fill the batch.
This function is designed for language modeling, where the input and the
target sequences are offset by one. We take that into account by making sure
neighboring batches have one token overlap.
Example:
If the iterable contains [[0, 1, 2], [10, 11, 12, 13, 14], [20, 21, 22]] and
batch size is 2, timesteps is 3, then the first batch would be:
[[0, 1, 2],
[10, 11, 12]]
then the second batch:
[[2, 20, 21], # seq 0 finished, continuing from seq 2
[12, 13, 14]]
Note the overlap of 1 token between these two batches, and the continuation
of sequences across batches.
Args:
iterable: the iterable that yields sequences of integer token IDs.
batch_size: number of examples in a batch.
timesteps: length of each sequence in a batch.
return_incomplete_batch: if True return the incomplete batches, which
typically appears at the end of the dataset.
pad: set to True to pad the incomplete batches.
pad_value: the value to use for padding.
Yields:
batches: where batches['obs'] are the observations of size
[batch_size, timesteps], and batches['should_reset'] is a 0/1 mask of
the same size that marks sequence boundaries, e.g. the entries in this
mask are all 0 except at locations where a new sequence is starting.
"""
if return_incomplete_batch and not pad:
raise ValueError(
f'If return_incomplete_batch, then pad must be True, currently {pad}.')
iterator = iter(iterable)
elems = []
for _ in range(batch_size):
item = next(iterator)
elems.append(item)
start_batch = [True] * batch_size
iter_finished = False
loaded_finished = False
while not (iter_finished and loaded_finished):
batch = []
for i in range(batch_size):
# should_reset value is 1 when a new sequence begins.
# [old[-3], old[-2], old[-1], new[0], new[1], new[2]]
# [0, 0, 0, 1, 0, 0]
should_reset = np.zeros(timesteps, np.float32)
if start_batch[i]:
should_reset[0] = 1
# Pack new examples in the sequence until they go beyond the required
# timesteps.
while len(elems[i]) < timesteps:
should_reset[len(elems[i])] = 1
try:
item = next(iterator)
except StopIteration:
iter_finished = True
break
elems[i] = np.concatenate([elems[i], item])
batch.append(dict(obs=elems[i][:timesteps], should_reset=should_reset))
# Shift and make sure we have a 1 token overlap.
elems[i] = elems[i][timesteps - 1:]
# Since the last token is shifted to be the first token of the next batch,
# We need to make sure reset is handled properly as well.
start_batch[i] = (should_reset[-1] == 1)
# If any loaded data is not yet consumed in the output we should keep
# generating.
loaded_finished = all(e.size == 0 for e in elems)
if not return_incomplete_batch:
elem_len = len(batch[0]['obs'])
if (elem_len != timesteps or
not all(len(x['obs']) == elem_len for x in batch[1:])):
logging.info('Dropping the (last?) incomplete batch.')
break
if pad:
for x in batch:
x['obs'] = pad_to(x['obs'], timesteps, axis=0, pad_value=pad_value)
yield dict(
obs=np.stack([x['obs'] for x in batch], axis=0),
should_reset=np.stack([x['should_reset'] for x in batch], axis=0))
def batch_graph_text_pairs(
iterable: Iterator[Any],
batch_size: int,
timesteps: int,
pad_value: float = 0.,
seq_and_graph_id: bool = False) -> Iterator[Any]:
"""Batch graph and text pairs.
This method pairs text with graphs, each text sequence is split into chunks
(with an overlap of 1) of size `timesteps`, and the graph associated with the
text is used and associated with each chunk as well. The last incomplete
chunk of each text sequence is padded with the `pad_value`.
Args:
iterable: Iterable that returns (graph, sequence) pairs, graph can be
anything, and sequence is a list of tokenized token IDs.
batch_size: Number of examples in a batch.
timesteps: Window size for the sequences.
pad_value: Value to use for padding.
seq_and_graph_id: whether the `iterable` contains `seq_id` and `graph_id`.
Yields:
batch: a batch of text sequence paired with graphs.
"""
iterator = iter(iterable)
seqs = [None] * batch_size
graphs = [None] * batch_size
graph_ids = [None] * batch_size
seq_ids = [None] * batch_size
iter_finished = False
loaded_finished = False
while not (iter_finished and loaded_finished):
batch = []
for idx in range(batch_size):
should_reset = np.zeros(timesteps, np.float32)
# pylint: disable=g-explicit-length-test
if seqs[idx] is None or len(seqs[idx]) == 0:
should_reset[0] = 1
# One sequence exhausted, get the next example.
try:
if seq_and_graph_id:
(graph, seq), (graph_id, seq_id) = next(iterator)
graph_ids[idx] = graph_id
seq_ids[idx] = seq_id
else:
graph, seq = next(iterator)
seqs[idx] = seq
graphs[idx] = graph
except StopIteration:
iter_finished = True
seqs[idx] = np.array([pad_value], dtype=np.int32)
graphs[idx] = None
example = dict(obs=seqs[idx][:timesteps], graph=graphs[idx],
should_reset=should_reset)
if seq_and_graph_id:
example['seq_id'] = seq_ids[idx]
example['graph_id'] = graph_ids[idx]
batch.append(example)
# Make sure that there is an overlap, as we generate targets by shifting
# the tensor by 1 timestep. So the next element should be shifted by
# `timesteps - 1' timesteps.
seqs[idx] = seqs[idx][timesteps - 1:]
# Make sure all loaded data are consumed in the output
loaded_finished = all(s.size == 0 for s in seqs)
# Also check for the last batch to avoid returning a fully empty batch
if iter_finished and all([np.all(b['obs'] == pad_value) for b in batch]):
break
# pad sequences to specified length
for e in batch:
e['obs'] = pad_to(e['obs'], timesteps, axis=0, pad_value=pad_value)
stacked_batch = dict(
obs=np.stack([e['obs'] for e in batch], axis=0),
graphs=[e['graph'] for e in batch],
should_reset=np.stack([e['should_reset'] for e in batch], axis=0))
if seq_and_graph_id:
stacked_batch['seq_id'] = np.stack(
[e['seq_id'] for e in batch], axis=0)
stacked_batch['graph_id'] = np.stack(
[e['graph_id'] for e in batch], axis=0)
yield stacked_batch
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/tools.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""WikiGraphs data modules."""
from . import dataset
from . import io_tools
from . import paired_dataset
from . import tokenizers
from . import tools
from . import wikitext
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/__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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Some tools for I/O."""
import gzip
import io
import os
import re
from typing import NamedTuple, List, Iterator
from absl import logging
def read_txt_file(file_path: str, encoding: str = 'utf-8') -> str:
"""Read a plain txt file."""
with open(file_path, 'rb') as f:
content = f.read()
return content.decode(encoding)
def write_txt_file(file_path: str, txt: str, encoding: str = 'utf-8'):
"""Write the given txt string to file."""
make_dir_if_necessary(file_path)
with open(file_path, 'wb') as f:
f.write(txt.encode(encoding, 'surrogatepass'))
def read_gzip_txt_file(file_path: str, encoding: str = 'utf-8') -> str:
"""Read gzipped txt file."""
with open(file_path, 'rb') as f:
content = f.read()
with gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb') as f:
content = f.read()
return content.decode(encoding)
def make_dir_if_necessary(output_path):
output_dir = os.path.dirname(output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
def write_lines_to_gzipped_file(file_path, lines):
make_dir_if_necessary(file_path)
with open(file_path, 'wb') as f_zip:
with gzip.GzipFile(fileobj=f_zip, mode='wb') as f:
f.write('\n'.join(lines).encode('utf-8'))
class Graph(NamedTuple):
title: str
center: str
edges: List[str]
def graphs_from_file(file_path: str) -> Iterator[Graph]:
"""Read freebase graphs from file.
Args:
file_path: path to the input `.gz` file that contains a list of graphs.
Yields:
graphs: a list of read from the file.
"""
content = read_gzip_txt_file(file_path)
graph_header_sep_re = re.compile(
r'(<graph center=[^ ]+ title="[^"]+">\n)')
graph_header_re = re.compile(
r'<graph center=([^ ]+) title="([^"]+)">\n')
parts = graph_header_sep_re.split(content)
# Skip the first part which is empty
for i in range(1, len(parts), 2):
header, body = parts[i], parts[i + 1]
m = graph_header_re.match(header)
yield Graph(title=m.group(2),
center=m.group(1),
edges=body.strip().split('\n'))
_UNICODE_RE = re.compile(r'(\$[0-9A-Fa-f]{4})')
def normalize_freebase_string(s: str) -> str:
"""Expand the `$xxxx` escaped unicode characters in the input string."""
# '"' is escaped as '``', convert it back.
s.replace('``', '"')
parts = _UNICODE_RE.split(s)
parts = [p if not _UNICODE_RE.match(p) else chr(int(p[1:], base=16))
for p in parts]
return ''.join(parts).replace('_', ' ')
class GraphTextPair(NamedTuple):
"""Text paired with raw graph represented as in `edges`."""
center_node: str
title: str
edges: List[str]
text: str
def pair2lines(pair):
lines = [f'<graph center={pair.center_node} title="{pair.title}">']
lines.append('<section id="text">')
lines.append(pair.text)
lines.append('<section id="edges">')
lines.extend(pair.edges)
return lines
def write_pairs_to_gzip_txt_file(file_path, pairs):
logging.info('Writing %d pairs to %s.', len(pairs), file_path)
lines = []
for p in pairs:
lines.extend(pair2lines(p))
write_lines_to_gzipped_file(file_path, lines)
def read_pairs_from_gzip_txt_file(file_path: str) -> Iterator[GraphTextPair]:
"""Read graph-text pairs from gzip txt files.
Args:
file_path: a `.gz` file of graph-text pairs written in the same format as
using the `write_pairs_to_gzip_txt_file` function.
Yields:
Graph-text pairs from this file.
"""
content = read_gzip_txt_file(file_path)
graph_header_sep_re = re.compile(
r'(<graph center=[^ ]+ title="[^"]+">)')
graph_header_re = re.compile(
r'<graph center=([^ ]+) title="([^"]+)">$')
section_sep_re = re.compile(r'\n(<section id="[^"]+">\n)')
parts = graph_header_sep_re.split(content)
# Skip the first part which is empty
for i in range(1, len(parts), 2):
header, body = parts[i], parts[i + 1]
m = graph_header_re.match(header)
# 5 parts total, empty first part, "text", text section, "edges", edges
# section.
section_parts = section_sep_re.split(body)
yield GraphTextPair(center_node=m.group(1),
title=m.group(2),
text=section_parts[2],
edges=section_parts[-1].strip().split('\n'))
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/io_tools.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tests for wikigraphs.data.tools."""
from absl.testing import absltest
import numpy as np
from wikigraphs.data import tools
class ToolsTest(absltest.TestCase):
def test_padding(self):
np.testing.assert_array_equal(
tools.pad_to(np.arange(3), 5),
[0, 1, 2, 0, 0])
np.testing.assert_array_equal(
tools.pad_to(np.arange(3), 5, pad_value=-1),
[0, 1, 2, -1, -1])
np.testing.assert_array_equal(
tools.pad_to(np.arange(6).reshape(2, 3), 4, axis=0, pad_value=-1),
[[0, 1, 2],
[3, 4, 5],
[-1, -1, -1],
[-1, -1, -1]])
np.testing.assert_array_equal(
tools.pad_to(np.arange(6).reshape(2, 3), 4, axis=-1, pad_value=-1),
[[0, 1, 2, -1],
[3, 4, 5, -1]])
def test_dynamic_batch(self):
def dataset():
data = [[1, 2, 2, 2],
[1, 3, 3],
[1, 4]]
for d in data:
yield np.array(d, dtype=np.int32)
batches = list(tools.dynamic_batch(
dataset(), batch_size=2, timesteps=3, return_incomplete_batch=False))
self.assertLen(batches, 1)
np.testing.assert_array_equal(
batches[0]['obs'],
[[1, 2, 2], [1, 3, 3]])
np.testing.assert_array_equal(
batches[0]['should_reset'],
[[1, 0, 0], [1, 0, 0]])
batches = list(tools.dynamic_batch(
dataset(), batch_size=2, timesteps=3, return_incomplete_batch=True,
pad=True, pad_value=0))
# Note `return_incomplete_batch=False` drops all the incomplete batches,
# and this can be more than just the last batch.
self.assertLen(batches, 3)
np.testing.assert_array_equal(
batches[0]['obs'],
[[1, 2, 2], [1, 3, 3]])
np.testing.assert_array_equal(
batches[0]['should_reset'],
[[1, 0, 0], [1, 0, 0]])
np.testing.assert_array_equal(
batches[1]['obs'],
[[2, 2, 1], [3, 0, 0]])
np.testing.assert_array_equal(
batches[1]['should_reset'],
[[0, 0, 1], [0, 1, 0]])
np.testing.assert_array_equal(
batches[2]['obs'],
[[1, 4, 0], [0, 0, 0]])
np.testing.assert_array_equal(
batches[2]['should_reset'],
[[1, 0, 1], [1, 0, 0]])
with self.assertRaises(ValueError):
batches = list(tools.dynamic_batch(
dataset(), batch_size=2, timesteps=3, return_incomplete_batch=True,
pad=False))
def test_batch_graph_text_pairs(self):
def source():
yield (1, np.array([1, 1, 1, 1, 1], dtype=np.int32))
yield (2, np.array([2, 2], dtype=np.int32))
yield (3, np.array([3, 3, 3, 3, 3, 3], dtype=np.int32))
data_iter = tools.batch_graph_text_pairs(
source(), batch_size=2, timesteps=3, pad_value=0)
batches = list(data_iter)
self.assertLen(batches, 4)
batch = batches[0]
np.testing.assert_array_equal(
batch['obs'],
[[1, 1, 1],
[2, 2, 0]])
self.assertEqual(batch['graphs'], [1, 2])
np.testing.assert_array_equal(
batch['should_reset'],
[[1, 0, 0],
[1, 0, 0]])
batch = batches[1]
np.testing.assert_array_equal(
batch['obs'],
[[1, 1, 1],
[3, 3, 3]])
self.assertEqual(batch['graphs'], [1, 3])
np.testing.assert_array_equal(
batch['should_reset'],
[[0, 0, 0],
[1, 0, 0]])
batch = batches[2]
np.testing.assert_array_equal(
batch['obs'],
[[1, 0, 0],
[3, 3, 3]])
self.assertEqual(batch['graphs'], [1, 3])
np.testing.assert_array_equal(
batch['should_reset'],
[[0, 0, 0],
[0, 0, 0]])
batch = batches[3]
np.testing.assert_array_equal(
batch['obs'],
[[0, 0, 0],
[3, 3, 0]])
self.assertEqual(batch['graphs'], [None, 3])
np.testing.assert_array_equal(
batch['should_reset'],
[[1, 0, 0],
[0, 0, 0]])
def test_batch_graph_text_pairs_batch_size1(self):
def source():
yield (0, np.array([1, 2], dtype=np.int32))
yield (1, np.array([1, 2, 3, 4, 5, 6], dtype=np.int32))
data_iter = tools.batch_graph_text_pairs(
source(), batch_size=1, timesteps=3, pad_value=0)
batches = list(data_iter)
batch = batches[0]
np.testing.assert_array_equal(batch['obs'], [[1, 2, 0]])
self.assertEqual(batch['graphs'], [0])
np.testing.assert_array_equal(batch['should_reset'], [[1, 0, 0]])
batch = batches[1]
np.testing.assert_array_equal(batch['obs'], [[1, 2, 3]])
self.assertEqual(batch['graphs'], [1])
np.testing.assert_array_equal(batch['should_reset'], [[1, 0, 0]])
batch = batches[2]
np.testing.assert_array_equal(batch['obs'], [[3, 4, 5]])
self.assertEqual(batch['graphs'], [1])
np.testing.assert_array_equal(batch['should_reset'], [[0, 0, 0]])
batch = batches[3]
np.testing.assert_array_equal(batch['obs'], [[5, 6, 0]])
self.assertEqual(batch['graphs'], [1])
np.testing.assert_array_equal(batch['should_reset'], [[0, 0, 0]])
self.assertLen(batches, 4)
if __name__ == '__main__':
absltest.main()
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/tools_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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tools for accessing the graph-text paired datasets."""
import abc
import collections
from typing import List, Tuple, NamedTuple, Any, Dict, Optional, Union
from absl import logging
import jax.numpy as jnp
import jraph
import numpy as np
from wikigraphs.data import dataset
from wikigraphs.data import io_tools
from wikigraphs.data import tokenizers
from wikigraphs.data import tools
ArrayType = Union[np.ndarray, jnp.ndarray]
DATA_ROOT = '/tmp/data/wikigraphs'
class RawDataset(dataset.Dataset):
"""The untokenized raw dataset."""
def __init__(self,
subset: str = 'train',
shuffle_data: bool = False,
data_dir: str = None,
version: str = 'max256'):
"""Constructor.
Args:
subset: which subset to load.
shuffle_data: set to True to randomly shuffle the data.
data_dir: if provided this will be used instead of the default location to
look for data, it must contain files like `train.gz`, `valid.gz` and
`test.gz`.
version: which version of the data to load, this must be the name of a
directory in `DATA_ROOT`.
"""
super().__init__()
self._subset = subset
self._shuffle_data = shuffle_data
self._data_dir = data_dir or DATA_ROOT
self._dataset = None
allowed_versions = ('max256', 'max512', 'max1024')
if version not in allowed_versions:
raise ValueError(f'Version {version} not one of the allowed versions:'
f' {allowed_versions}.')
self._version = version
def _load_data(self):
"""Load and prepare the data iterator."""
if self._dataset is None:
self._dataset = list(io_tools.read_pairs_from_gzip_txt_file(
f'{self._data_dir}/{self._version}/{self._subset}.gz'))
def source():
n_pairs = len(self._dataset)
if self._shuffle_data:
idx = np.random.permutation(n_pairs)
else:
idx = np.arange(n_pairs)
for i in range(n_pairs):
yield self._dataset[idx[i]]
return source()
class Graph:
"""A convenience class for representing graphs."""
def __init__(self, nodes: List[str], edges: List[Tuple[int, int, str]]):
"""Construct a graph from a list of nodes and edges.
Args:
nodes: a list of node attributes, one for each node.
edges: a list of (source_node_id, target_node_id, edge_attribute) for each
edge.
"""
self._nodes = nodes
self._edges = edges
self._node2id = {n: i for i, n in enumerate(nodes)}
def nodes(self) -> List[str]:
return self._nodes
def edges(self) -> List[Tuple[int, int, str]]:
return self._edges
def node2id(self, node: str) -> int:
return self._node2id[node]
@classmethod
def from_edges(cls, edges: List[str]) -> 'Graph':
"""Build a graph instance from a list of edges."""
node2id = dict()
parsed_edges = []
next_node_id = 0
for e in edges:
src, edge, tgt = e.split('\t')[:3]
src_id = node2id.get(src, next_node_id)
if src_id == next_node_id:
node2id[src] = src_id
next_node_id += 1
tgt_id = node2id.get(tgt, next_node_id)
if tgt_id == next_node_id:
node2id[tgt] = tgt_id
next_node_id += 1
parsed_edges.append((src_id, tgt_id, edge))
id2node = {i: n for n, i in node2id.items()}
return Graph(nodes=[id2node[i] for i in range(next_node_id)],
edges=parsed_edges)
def to_edges(self) -> List[str]:
r"""Convert graph to a list of edges.
The converted list of edges should be compatible with the format specified
in io_tools and compatible with the `from_edges` method above.
Returns:
edges: one edge per line, with the (source, target, edge_type) separated
by `\t`.
"""
edges = []
for s, t, e in self._edges:
edges.append(f'{self._nodes[s]}\t{e}\t{self._nodes[t]}')
return edges
@classmethod
def subsample_nodes(
cls, graph: 'Graph', subsample_rate: float = 1.0, center_node: str = None
) -> 'Graph':
"""Subsample the nodes of a graph."""
graph_size = len(graph.nodes())
if subsample_rate == 1.0 or graph_size <= 1:
return graph
subsampled_nodes_id = np.arange(graph_size)
if subsample_rate < 1.0:
subsample_graph_size = int(subsample_rate * graph_size)
if center_node is not None:
# We need to keep the center node during subsampling
center_node_id = graph.node2id(center_node)
subsampled_nodes_id = subsampled_nodes_id[
subsampled_nodes_id != center_node_id]
subsample_graph_size = max(1, subsample_graph_size - 1)
subsampled_nodes_id = np.random.choice(
subsampled_nodes_id, subsample_graph_size, replace=False)
subsampled_nodes_id = np.append(subsampled_nodes_id, center_node_id)
else:
subsampled_nodes_id = np.random.choice(
subsampled_nodes_id, subsample_graph_size, replace=False)
subsampled_nodes_id = np.sort(subsampled_nodes_id)
map_subsampled_nodes_id = {
old_id: new_id for new_id, old_id in enumerate(subsampled_nodes_id)}
nodes = []
edges = []
for node_id, n in enumerate(graph.nodes()):
if node_id in subsampled_nodes_id:
nodes.append(n)
for out_node, in_node, e in graph.edges():
if out_node in subsampled_nodes_id and in_node in subsampled_nodes_id:
edges.append((map_subsampled_nodes_id[out_node],
map_subsampled_nodes_id[in_node], e))
return Graph(nodes=nodes, edges=edges)
class ParsedGraphTextPair(NamedTuple):
"""Graph-text pair with graph parsed into a `Graph` instance."""
center_node: str
title: str
text: str
graph: Graph
class ParsedDataset(dataset.Dataset):
"""Raw dataset + parsing graphs into Graph instances."""
def __init__(self,
subset: str = 'train',
shuffle_data: bool = False,
data_dir: str = None,
version: str = 'max256'):
"""Constructor.
Args:
subset: which subset to load.
shuffle_data: set to True to randomly shuffle the data.
data_dir: if provided this will be used instead of the default location to
look for data, it must contain files like `train.gz`, `valid.gz` and
`test.gz`.
version: which version of the data to load, this must be the name of a
directory in `DATA_ROOT`.
"""
super().__init__()
self._raw_data = RawDataset(subset=subset, shuffle_data=False,
data_dir=data_dir, version=version)
self._shuffle_data = shuffle_data
self._dataset = None
def _load_data(self):
if self._dataset is None:
# pylint: disable=g-complex-comprehension
self._dataset = [ParsedGraphTextPair(center_node=pair.center_node,
title=pair.title,
text=pair.text,
graph=Graph.from_edges(pair.edges))
for pair in self._raw_data]
def source():
n_pairs = len(self._dataset)
if self._shuffle_data:
idx = np.random.permutation(n_pairs)
else:
idx = np.arange(n_pairs)
for i in range(n_pairs):
yield self._dataset[idx[i]]
return source()
class BaseGraph2TextDataset(dataset.Dataset):
"""Base dataset class for graph-to-text tasks."""
def __init__(self,
tokenizer: tokenizers.Tokenizer,
graph_tokenizer: Optional[tokenizers.GraphTokenizer] = None,
batch_size: int = 1,
timesteps: int = 128,
subset: str = 'train',
shuffle_data: bool = False,
repeat: bool = False,
version: str = 'max256',
data_dir: str = None,
subsample_nodes: float = 1.0,
graph_retrieval_dataset: bool = False,
debug: bool = False):
"""Constructor.
Args:
tokenizer: the tokenizer for text data.
graph_tokenizer: the tokenizer for graph data.
batch_size: number of sequences to put in a batch.
timesteps: number of tokens to put in a sequence in a batch.
subset: which subset to load.
shuffle_data: whether to shuffle data.
repeat: set to True to repeat the dataset infinitely, otherwise do only
one pass through the dataset.
version: which version of the data to load.
data_dir: if set load data instead from this directory, and ignore
`version`.
subsample_nodes: the proportion of the nodes in a graph to keep.
graph_retrieval_dataset: whether to construct the dataset for graph
retrieval tasks.
debug: set to True to use debug mode and only load a small number of
examples.
"""
super().__init__()
self._parsed_data = ParsedDataset(subset=subset,
shuffle_data=False,
data_dir=data_dir,
version=version)
self._tokenizer = tokenizer
self._graph_tokenizer = graph_tokenizer
self._batch_size = batch_size
self._timesteps = timesteps
self._subset = subset
self._shuffle_data = shuffle_data
self._repeat = repeat
self._subsample_nodes = subsample_nodes
self._graph_retrieval_dataset = graph_retrieval_dataset
self._debug = debug
self._dataset = None
@property
def num_articles(self):
return self._num_articles
@abc.abstractmethod
def _process_graph(self, center_node: str, graph: Graph):
"""Process the graph part of a `ParsedGraphTextPair` instance."""
def _process_graph_text_pair(
self, pair: ParsedGraphTextPair) -> Tuple[Any, np.ndarray]:
"""Process the given graph-text pair and prepare one example.
Args:
pair: the input `ParsedGraphTextPair` instance.
Returns:
graph: the processed graph content.
text: the tokenized text, a sequence of token IDs.
"""
return (self._process_graph(pair.center_node, pair.graph),
self._tokenizer.encode(
pair.text, prepend_bos=True, append_eos=True))
def _load_data(self):
"""Prepare the data."""
if self._dataset is None:
if self._debug:
data = [next(self._parsed_data) for _ in range(10)]
else:
data = list(self._parsed_data)
self._dataset = [self._process_graph_text_pair(p) for p in data]
self._num_articles = len(self._dataset)
logging.info('Loaded a total of %d examples from %s set.',
self._num_articles, self._subset)
if self._graph_retrieval_dataset:
# For graph retrieval tasks we pair all texts and graphs in the dataset,
# and indicate their (text_id, graph_id)
retrieval_data = []
for i, (g1, _) in enumerate(self._dataset):
for j, (_, t2) in enumerate(self._dataset):
retrieval_data.append(((g1, t2), (i, j)))
self._dataset = retrieval_data
logging.info('Constructed %d pairs.', len(self._dataset))
def source():
n_examples = len(self._dataset)
if self._shuffle_data:
idx = np.random.permutation(n_examples)
else:
idx = np.arange(n_examples)
for i in range(n_examples):
yield self._dataset[idx[i]]
def maybe_repeated_source():
if self._repeat:
while True:
yield from source()
else:
yield from source()
data_iter = tools.batch_graph_text_pairs(
maybe_repeated_source(),
self._batch_size,
self._timesteps + 1,
pad_value=self._tokenizer.pad_token(),
seq_and_graph_id=self._graph_retrieval_dataset)
if self._graph_retrieval_dataset:
data_iter = map(lambda x: dict( # pylint: disable=g-long-lambda
obs=x['obs'][:, :-1],
target=x['obs'][:, 1:],
should_reset=x['should_reset'][:, :-1],
# If target is a <pad> token then that target should not be predicted.
mask=(x['obs'][:, 1:] != self._tokenizer.pad_token()).astype(
np.float32),
seq_id=x['seq_id'],
graph_id=x['graph_id'],
graphs=self._process_graph_batch(x['graphs']),
), data_iter)
else:
data_iter = map(lambda x: dict( # pylint: disable=g-long-lambda
obs=x['obs'][:, :-1],
target=x['obs'][:, 1:],
should_reset=x['should_reset'][:, :-1],
# If target is a <pad> token then that target should not be predicted.
mask=(x['obs'][:, 1:] != self._tokenizer.pad_token()).astype(
np.float32),
graphs=self._process_graph_batch(x['graphs']),
), data_iter)
# Filter out batches that does not have targets.
# This may happen when an observation contains a single last token of the
# sequence, which was predicted as target in the previous batch, and only
# used as observation in this batch, without a matching target. In this
# case all the masks are 0, therefore this batch provides no training signal
# and we can safely remove this batch. This also avoids some potential
# downstream issues.
data_iter = filter(lambda x: x['mask'].sum() > 0, data_iter)
return data_iter
@abc.abstractmethod
def _process_graph_batch(self, graphs: List[Any]):
"""Process a batch of graph data.
Args:
graphs: a list of graph data, each as returned by `_process_graph`.
Returns:
processed_graphs: processed tensor(s) that can be directly fed into a
model.
"""
@abc.abstractmethod
def return_faux_batch(self) -> Dict[str, np.ndarray]:
"""Return a fake batch with the right shapes and dtypes."""
class TextOnlyDataset(BaseGraph2TextDataset):
"""Text-only version of the paired dataset."""
def __init__(self,
tokenizer: tokenizers.Tokenizer,
graph_tokenizer: Optional[tokenizers.GraphTokenizer] = None,
batch_size: int = 1,
timesteps: int = 128,
subset: str = 'train',
shuffle_data: bool = False,
repeat: bool = False,
version: str = 'max256',
data_dir: str = None,
debug: bool = False,
**kwargs):
"""Constructor.
Args:
tokenizer: the tokenizer for text data.
graph_tokenizer: not used, keeping it here for compatibility with other
graph2text datasets.
batch_size: number of sequences to put in a batch.
timesteps: number of tokens to put in a sequence in a batch.
subset: which subset to load.
shuffle_data: whether to shuffle data.
repeat: set to True to repeat the dataset infinitely, otherwise do only
one pass through the dataset.
version: which version of the data to load.
data_dir: if set load data instead from this directory, and ignore
`version`.
debug: set to True to use debug mode and only load a small number of
examples.
**kwargs: other arguments (for interface compatibility).
"""
del graph_tokenizer
super().__init__(tokenizer=tokenizer,
graph_tokenizer=None,
batch_size=batch_size,
timesteps=timesteps,
subset=subset,
shuffle_data=shuffle_data,
repeat=repeat,
version=version,
data_dir=data_dir,
debug=debug)
def _process_graph_batch(self, graphs: List[Any]):
del graphs
return None
def _process_graph(self, center_node: str, graph: Graph):
del center_node
del graph
return None
def __next__(self):
batch = super().__next__()
# Data should be text-only.
del batch['graphs']
return batch
def return_faux_batch(self):
"""Return a fake batch with the right shapes and types."""
obs = np.zeros((self._batch_size, self._timesteps), dtype=np.int32)
target = np.zeros_like(obs)
should_reset = np.zeros_like(obs, dtype=np.float32)
mask = np.zeros_like(obs, dtype=np.float32)
return dict(obs=obs, target=target, should_reset=should_reset, mask=mask)
class Bow2TextDataset(BaseGraph2TextDataset):
"""Dataset for bag-of-words to text."""
def _process_graph(self, center_node: str, graph: Graph):
"""Process the graph part of a `ParsedGraphTextPair` instance."""
# We don't use center node in a bag-of-words representation
del center_node
if self._subsample_nodes < 1.0:
graph = Graph.subsample_nodes(graph, self._subsample_nodes)
bow = np.zeros(self._graph_tokenizer.vocab_size, dtype=np.int32)
for n in graph.nodes():
for t in self._graph_tokenizer.encode_node(n):
bow[t] += 1
for _, _, e in graph.edges():
for t in self._graph_tokenizer.encode_edge(e):
bow[t] += 1
return bow
def _process_graph_batch(self, graphs: List[Any]):
"""Process a batch of graph data.
Args:
graphs: a list of graph data, each as returned by `_process_graph`.
Returns:
processed_graphs: processed tensor(s) that can be directly fed into a
model.
"""
empty_graph_bow = np.zeros(self._graph_tokenizer.vocab_size, dtype=np.int32)
graphs = [g if g is not None else empty_graph_bow for g in graphs]
# B x [V] -> [B, V]
return np.stack(graphs, axis=0)
def return_faux_batch(self):
obs = np.zeros((self._batch_size, self._timesteps), dtype=np.int32)
target = np.zeros_like(obs)
should_reset = np.zeros_like(obs, dtype=np.float32)
mask = np.zeros_like(obs, dtype=np.float32)
graphs = np.zeros((self._batch_size, self._graph_tokenizer.vocab_size),
dtype=np.float32)
return dict(obs=obs, target=target, should_reset=should_reset, mask=mask,
graphs=graphs)
class Graph2TextDataset(BaseGraph2TextDataset):
"""Graph-to-text dataset.
This dataset encodes the graph nodes and edges using a bag-of-words
representation.
"""
def __init__(self,
tokenizer: tokenizers.Tokenizer,
graph_tokenizer: tokenizers.GraphTokenizer,
batch_size: int = 1,
timesteps: int = 128,
subset: str = 'train',
shuffle_data: bool = False,
repeat: bool = False,
version: str = 'max256',
data_dir: str = None,
subsample_nodes: float = 1.0,
graph_retrieval_dataset: bool = False,
debug: bool = False):
"""Constructor.
Args:
tokenizer: the tokenizer for text data.
graph_tokenizer: the tokenizer for graph data.
batch_size: number of sequences to put in a batch.
timesteps: number of tokens to put in a sequence in a batch.
subset: which subset to load.
shuffle_data: whether to shuffle data.
repeat: set to True to repeat the dataset infinitely, otherwise do only
one pass through the dataset.
version: which version of the data to load.
data_dir: if set load data instead from this directory, and ignore
`version`.
subsample_nodes: the proportion of the nodes in a graph to keep.
graph_retrieval_dataset: whether to construct the dataset for graph
retrieval tasks.
debug: set to True to use debug mode and only load a small number of
examples.
"""
self._graph_feature_dim = graph_tokenizer.vocab_size
super().__init__(tokenizer=tokenizer,
graph_tokenizer=graph_tokenizer,
batch_size=batch_size,
timesteps=timesteps,
subset=subset,
shuffle_data=shuffle_data,
repeat=repeat,
version=version,
data_dir=data_dir,
subsample_nodes=subsample_nodes,
graph_retrieval_dataset=graph_retrieval_dataset,
debug=debug)
self._placeholder_graph = self._process_graph(
center_node='<pad>',
graph=Graph(nodes=['<pad>'], edges=[]))
def _process_graph(self, center_node: str, graph: Graph):
"""Process the graph part of a `ParsedGraphTextPair` instance."""
if self._subsample_nodes < 1.0:
graph = Graph.subsample_nodes(graph, self._subsample_nodes, center_node)
nodes = graph.nodes()
edges = graph.edges()
n_edges = len(edges)
sender = np.zeros(n_edges, dtype=np.int32)
receiver = np.zeros(n_edges, dtype=np.int32)
nodes_bow = []
edges_bow = []
for n in nodes:
bow = collections.defaultdict(int)
for t in self._graph_tokenizer.encode_node(n):
bow[t] += 1
nodes_bow.append(bow)
for i, (s, r, e) in enumerate(edges):
bow = collections.defaultdict(int)
for t in self._graph_tokenizer.encode_edge(e):
bow[t] += 1
edges_bow.append(bow)
sender[i] = s
receiver[i] = r
return (nodes_bow, edges_bow, sender, receiver, graph.node2id(center_node))
def _to_graph_with_features(
self, nodes_bow, edges_bow, sender, receiver, center_node_id):
"""Convert the input to a `jraph.GraphsTuple` instance."""
n_nodes = len(nodes_bow)
n_edges = len(edges_bow)
# +1 for the center node indicator
nodes = np.zeros((n_nodes, self._graph_feature_dim + 1), dtype=np.float32)
edges = np.zeros((n_edges, self._graph_feature_dim), dtype=np.float32)
nodes[center_node_id][-1] = 1
for i, bow in enumerate(nodes_bow):
for t, c in bow.items():
nodes[i][t] = c
for i, bow in enumerate(edges_bow):
for t, c in bow.items():
edges[i][t] = c
return jraph.GraphsTuple(
nodes=nodes, edges=edges, senders=sender, receivers=receiver,
globals=None, n_node=np.array([n_nodes], dtype=np.int32),
n_edge=np.array([n_edges], dtype=np.int32))
def _process_graph_batch(self, graphs: List[Any]):
"""Process a batch of graph data.
Args:
graphs: a list of graph data, each as returned by `_process_graph`.
Returns:
processed_graphs: a list of processed tensor(s).
"""
graphs = [g if g is not None else self._placeholder_graph for g in graphs]
return [self._to_graph_with_features(*g) for g in graphs]
def return_faux_batch(self) -> Dict[str, np.ndarray]:
"""Return a fake batch with the right shapes and dimensions."""
obs = np.zeros([self._batch_size, self._timesteps], dtype=np.int32)
target = np.zeros([self._batch_size, self._timesteps], dtype=np.int32)
should_reset = np.zeros_like(obs, np.float32)
mask = np.zeros_like(obs, np.float32)
# A batch should contain `batch_size` graphs. Here we make sure each graph
# has one node and one edge.
graphs = self._batch_size * [jraph.GraphsTuple(
nodes=np.zeros([1, self._graph_feature_dim + 1], dtype=np.float32),
edges=np.zeros([1, self._graph_feature_dim], dtype=np.float32),
senders=np.zeros([1], dtype=np.int32),
receivers=np.zeros([1], dtype=np.int32),
n_node=np.ones(1, dtype=np.int32),
n_edge=np.ones(1, dtype=np.int32),
globals=None)]
return dict(obs=obs, target=target, mask=mask, should_reset=should_reset,
graphs=graphs)
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/paired_dataset.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Base class of the datasets."""
import abc
from typing import Any, Iterator
class Dataset(abc.ABC):
"""Base class for all datasets.
All sub-classes should define `_load_data()` where an iterator
`self._data_iter` should be instantiated that iterates over the dataset.
"""
def __init__(self):
"""Constructor."""
self._data_iter = None # An iterator produced by `self._load_data`.
@abc.abstractmethod
def _load_data(self) -> Iterator[Any]:
"""Prepare data for another pass through the dataset.
This method should return a generator in a child class.
"""
def __next__(self):
return next(self._data_iter)
def __iter__(self):
self._data_iter = self._load_data()
return self
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/dataset.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Wikitext-103 datasets."""
import re
from typing import NamedTuple, List
from absl import logging
import numpy as np
from wikigraphs.data import dataset
from wikigraphs.data import tokenizers
from wikigraphs.data import tools
# The data directory that contains subdirectories `wikitext-103` and
# `wikitext-103-raw`.
DATA_ROOT = '/tmp/data/wikitext-103'
class WikitextArticle(NamedTuple):
title: str
text: str
def articles_from_file(file_path: str) -> List[WikitextArticle]:
"""Read wikitext articles from file.
Args:
file_path: path to the input `.tokens` file.
Returns:
A list of `WikitextArticle` tuples.
"""
with open(file_path, mode='rb') as f:
content = f.read()
content = content.decode('utf-8')
title_re = re.compile(r'(\n = ([^=].*) = \n \n)')
parts = title_re.split(content)
# Skip the first part which is empty
return [WikitextArticle(title=parts[i+1], text=parts[i] + parts[i+2])
for i in range(1, len(parts), 3)]
class RawDataset(dataset.Dataset):
"""Raw text dataset for wikitext-103."""
def __init__(self,
subset: str = 'train',
shuffle_data: bool = False,
data_dir: str = None,
version: str = 'tokens'):
"""Constructor.
Args:
subset: which subset to load, one of {"train", "valid", "test"}.
shuffle_data: if set to True the data will be randomly shuffled.
data_dir: if provided will be used instead of the default `DATA_ROOT` as
the directory that contains the data.
version: one of {'tokens', 'raw'}
"""
super().__init__()
self._subset = subset
self._shuffle_data = shuffle_data
self._data_dir = data_dir or DATA_ROOT
self._dataset = None
allowed_versions = ('tokens', 'raw')
if version not in allowed_versions:
raise ValueError(f'Version must be one of {allowed_versions}.')
self._version = version
def _load_data(self):
"""Prepare data for another pass through the dataset."""
if self._dataset is None:
data_root = self._data_dir + ('-raw' if self._version == 'raw' else '')
self._dataset = articles_from_file(
f'{data_root}/wiki.{self._subset}.{self._version}')
def source():
n_articles = len(self._dataset)
if self._shuffle_data:
idx = np.random.permutation(n_articles)
else:
idx = np.arange(n_articles)
for i in range(n_articles):
yield self._dataset[idx[i]]
return source()
def normalize_title(title: str) -> str:
"""Normalize the wikitext article title by handling special characters."""
return title.replace(
'@-@', '-').replace('@,@', ',').replace('@.@', '.').replace(' ', '')
class WikitextDataset(dataset.Dataset):
"""Tokenized dataset for wikitext-103."""
def __init__(self,
tokenizer: tokenizers.Tokenizer,
batch_size: int = 1,
timesteps: int = 128,
subset: str = 'train',
shuffle_data: bool = True,
data_dir: str = None,
repeat: bool = False,
debug: bool = False,
**kwargs):
"""Constructor.
Args:
tokenizer: a tokenizer for text data.
batch_size: number of sequences to put into a batch.
timesteps: length of the sequences.
subset: which subset to load, one of {"train", "valid", "test"}.
shuffle_data: if set to True the data will be randomly shuffled.
data_dir: if provided will be used instead of the default `DATA_ROOT` as
the directory that contains the data.
repeat: set to False to go through the data only once, otherwise go
through the data indefinitely.
debug: set to True to only load a small amount of data for fast debugging.
**kwargs: other arguments (for interface compatibility).
"""
super().__init__()
self._tokenizer = tokenizer
self._batch_size = batch_size
self._timesteps = timesteps
self._subset = subset
self._shuffle_data = shuffle_data
self._data_dir = data_dir
self._repeat = repeat
self._debug = debug
self._dataset = None
def _load_data(self):
"""Prepare data for one pass through the dataset."""
# Pre-tokenize everything in our dataset so we don't have to when going
# through the data more than once.
if not self._dataset:
raw_dataset = RawDataset(
subset=self._subset, shuffle_data=False, data_dir=self._data_dir)
if self._debug:
# Load a small number of examples for debugging.
self._dataset = [
self._tokenizer.encode(next(raw_dataset).text, prepend_bos=True)
for _ in range(5)]
else:
self._dataset = [self._tokenizer.encode(item.text, prepend_bos=True)
for item in raw_dataset]
logging.info('%s set loaded, total %d examples.',
self._subset, len(self._dataset))
def source():
idx = np.random.permutation(len(self._dataset))
for i in idx:
yield self._dataset[i]
def repeated_source():
if self._repeat:
while True:
yield from source()
else:
yield from source()
data_iter = tools.dynamic_batch(
repeated_source(),
self._batch_size,
self._timesteps + 1, # Extra token to count for the overlap.
return_incomplete_batch=True,
pad=True,
pad_value=self._tokenizer.pad_token())
data_iter = map(lambda x: dict( # pylint: disable=g-long-lambda
obs=x['obs'][:, :-1],
target=x['obs'][:, 1:],
should_reset=x['should_reset'][:, :-1],
mask=(x['obs'][:, 1:] != self._tokenizer.pad_token()).astype(
np.float32),
), data_iter)
return data_iter
def return_faux_batch(self):
"""Return a fake batch with the right shapes and dtypes."""
obs = np.zeros((self._batch_size, self._timesteps), dtype=np.int32)
target = np.zeros_like(obs, dtype=np.int32)
should_reset = np.zeros_like(obs, dtype=np.float32)
mask = np.zeros_like(obs, dtype=np.float32)
return dict(obs=obs, target=target, should_reset=should_reset, mask=mask)
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/wikitext.py
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tests for wikigraphs.data.paired_dataset."""
from absl.testing import absltest
import jraph
from wikigraphs.data import io_tools
from wikigraphs.data import paired_dataset
from wikigraphs.data import tokenizers
from wikigraphs.data import wikitext
WIKITEXT_ROOT = '/tmp/data/wikitext-103'
WIKIGRAPHS_ROOT = '/tmp/data/wikigraphs'
WIKITEXT_VOCAB_FILE = '/tmp/data/wikitext-vocab.csv'
GRAPH_VOCAB_FILE = '/tmp/data/graph-vocab.csv'
class PairedDatasetTest(absltest.TestCase):
def test_raw_paired_dataset_size(self):
dataset = paired_dataset.RawDataset(
subset='valid', shuffle_data=False, data_dir=WIKIGRAPHS_ROOT)
pairs = list(dataset)
self.assertLen(pairs, 48)
self.assertEqual(pairs[0].title, 'Homarus_gammarus')
self.assertEqual(pairs[-1].title, 'Rakie_Ayola')
# Make sure the content of the articles match the original
wikitext_set = wikitext.RawDataset(
subset='valid', shuffle_data=False, version='raw',
data_dir=WIKITEXT_ROOT)
title2article = {wikitext.normalize_title(a.title).replace(' ', ''): a.text
for a in wikitext_set}
for p in pairs:
title = io_tools.normalize_freebase_string(p.title).replace(' ', '')
article = title2article.get(title, None)
self.assertIsNotNone(article)
self.assertEqual(article, p.text)
def test_graph_from_edges(self):
edges = ['A\tE1\tB',
'A\tE2\tC',
'B\tE1\tC',
'C\tE3\tD',
'C\tE2\tE']
graph = paired_dataset.Graph.from_edges(edges)
self.assertEqual(graph.nodes(), ['A', 'B', 'C', 'D', 'E'])
self.assertEqual(graph.edges(), [(0, 1, 'E1'),
(0, 2, 'E2'),
(1, 2, 'E1'),
(2, 3, 'E3'),
(2, 4, 'E2')])
def test_graph_to_edges(self):
edges = ['A\tE1\tB',
'A\tE2\tC',
'B\tE1\tC',
'C\tE3\tD',
'C\tE2\tE']
graph = paired_dataset.Graph.from_edges(edges)
self.assertEqual(graph.to_edges(), edges)
def test_bow2text_dataset(self):
tokenizer = tokenizers.WordTokenizer(vocab_file=WIKITEXT_VOCAB_FILE)
graph_tokenizer = tokenizers.GraphTokenizer(vocab_file=GRAPH_VOCAB_FILE)
batch_size = 4
seq_len = 256
dataset = paired_dataset.Bow2TextDataset(
tokenizer,
graph_tokenizer,
batch_size=batch_size,
timesteps=seq_len,
subset='valid',
subsample_nodes=0.7,
repeat=False,
data_dir=WIKIGRAPHS_ROOT)
num_tokens = 0
for batch in dataset:
num_tokens += batch['mask'].sum()
self.assertEqual(batch['graphs'].shape,
(batch_size, graph_tokenizer.vocab_size))
raw_dataset = paired_dataset.RawDataset(subset='valid', shuffle_data=False)
raw_num_tokens = 0
n_pairs = 0
for pair in raw_dataset:
raw_num_tokens += len(tokenizer.encode(
pair.text, prepend_bos=True, append_eos=True))
n_pairs += 1
# The first token of each example is not counted by `mask` as it masks the
# targets, and the first token of each example never appears in the targets.
self.assertEqual(raw_num_tokens, num_tokens + n_pairs)
def test_graph2text_dataset(self):
tokenizer = tokenizers.WordTokenizer(vocab_file=WIKITEXT_VOCAB_FILE)
graph_tokenizer = tokenizers.GraphTokenizer(vocab_file=GRAPH_VOCAB_FILE)
batch_size = 4
seq_len = 256
dataset = paired_dataset.Graph2TextDataset(
tokenizer,
graph_tokenizer,
batch_size=batch_size,
timesteps=seq_len,
subsample_nodes=0.8,
subset='valid',
data_dir=WIKIGRAPHS_ROOT)
data_iter = iter(dataset)
batch = next(data_iter)
self.assertEqual(batch['obs'].shape, (batch_size, seq_len))
self.assertEqual(batch['target'].shape, (batch_size, seq_len))
self.assertEqual(batch['should_reset'].shape, (batch_size, seq_len))
self.assertEqual(batch['mask'].shape, (batch_size, seq_len))
self.assertIsInstance(batch['graphs'], list)
self.assertLen(batch['graphs'], batch_size)
for i in range(batch_size):
self.assertIsInstance(batch['graphs'][i], jraph.GraphsTuple)
# +1 for the center_node mask
self.assertEqual(
batch['graphs'][i].nodes.shape[-1], graph_tokenizer.vocab_size + 1)
self.assertEqual(
batch['graphs'][i].edges.shape[-1], graph_tokenizer.vocab_size)
n_edges = batch['graphs'][i].n_edge
self.assertEqual(batch['graphs'][i].senders.shape, (n_edges,))
self.assertEqual(batch['graphs'][i].receivers.shape, (n_edges,))
# Make sure the token count matches across the tokenized data and the raw
# data set.
num_tokens = 0
for batch in dataset:
num_tokens += batch['mask'].sum()
raw_dataset = paired_dataset.RawDataset(subset='valid', shuffle_data=False)
raw_num_tokens = 0
n_pairs = 0
for pair in raw_dataset:
raw_num_tokens += len(tokenizer.encode(
pair.text, prepend_bos=True, append_eos=True))
n_pairs += 1
# The first token of each example is not counted by `mask` as it masks the
# targets, and the first token of each example never appears in the targets.
self.assertEqual(raw_num_tokens, num_tokens + n_pairs)
def test_text_only_dataset(self):
tokenizer = tokenizers.WordTokenizer(vocab_file=WIKITEXT_VOCAB_FILE)
batch_size = 4
seq_len = 256
dataset = paired_dataset.TextOnlyDataset(
tokenizer,
batch_size=batch_size,
timesteps=seq_len,
subset='valid',
data_dir=WIKIGRAPHS_ROOT)
data_iter = iter(dataset)
batch = next(data_iter)
faux_batch = dataset.return_faux_batch()
self.assertCountEqual(list(batch.keys()),
['obs', 'target', 'should_reset', 'mask'])
self.assertCountEqual(list(faux_batch.keys()),
['obs', 'target', 'should_reset', 'mask'])
for k, v in batch.items():
faux_v = faux_batch[k]
self.assertEqual(v.shape, faux_v.shape)
self.assertEqual(v.dtype, faux_v.dtype)
self.assertEqual(batch['obs'].shape, (batch_size, seq_len))
self.assertEqual(batch['target'].shape, (batch_size, seq_len))
self.assertEqual(batch['should_reset'].shape, (batch_size, seq_len))
self.assertEqual(batch['mask'].shape, (batch_size, seq_len))
num_tokens = 0
for batch in dataset:
num_tokens += batch['mask'].sum()
raw_dataset = paired_dataset.RawDataset(subset='valid', shuffle_data=False)
raw_num_tokens = 0
n_pairs = 0
for pair in raw_dataset:
raw_num_tokens += len(tokenizer.encode(
pair.text, prepend_bos=True, append_eos=True))
n_pairs += 1
self.assertEqual(num_tokens + n_pairs, raw_num_tokens)
def test_bow_retrieval_dataset(self):
tokenizer = tokenizers.WordTokenizer(vocab_file=WIKITEXT_VOCAB_FILE)
graph_tokenizer = tokenizers.GraphTokenizer(vocab_file=GRAPH_VOCAB_FILE)
batch_size = 4
seq_len = 256
dataset = paired_dataset.Bow2TextDataset(
tokenizer,
graph_tokenizer,
batch_size=batch_size,
timesteps=seq_len,
subsample_nodes=0.8,
graph_retrieval_dataset=True,
subset='valid',
data_dir=WIKIGRAPHS_ROOT)
data_iter = iter(dataset)
batch = next(data_iter)
self.assertEqual(batch['obs'].shape, (batch_size, seq_len))
self.assertEqual(batch['target'].shape, (batch_size, seq_len))
self.assertEqual(batch['should_reset'].shape, (batch_size, seq_len))
self.assertEqual(batch['mask'].shape, (batch_size, seq_len))
self.assertEqual(batch['graph_id'].shape, (batch_size,))
self.assertEqual(batch['seq_id'].shape, (batch_size,))
def test_graph_retrieval_dataset(self):
tokenizer = tokenizers.WordTokenizer(vocab_file=WIKITEXT_VOCAB_FILE)
graph_tokenizer = tokenizers.GraphTokenizer(vocab_file=GRAPH_VOCAB_FILE)
batch_size = 4
seq_len = 256
dataset = paired_dataset.Graph2TextDataset(
tokenizer,
graph_tokenizer,
batch_size=batch_size,
timesteps=seq_len,
subsample_nodes=0.8,
graph_retrieval_dataset=True,
subset='valid',
data_dir=WIKIGRAPHS_ROOT)
data_iter = iter(dataset)
batch = next(data_iter)
self.assertEqual(batch['obs'].shape, (batch_size, seq_len))
self.assertEqual(batch['target'].shape, (batch_size, seq_len))
self.assertEqual(batch['should_reset'].shape, (batch_size, seq_len))
self.assertEqual(batch['mask'].shape, (batch_size, seq_len))
self.assertEqual(batch['graph_id'].shape, (batch_size,))
self.assertEqual(batch['seq_id'].shape, (batch_size,))
if __name__ == '__main__':
absltest.main()
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/paired_dataset_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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tokenizers for text data."""
import abc
import csv
import io
import re
from typing import List
import nltk
import numpy as np
from wikigraphs.data import io_tools
class Tokenizer(abc.ABC):
"""Base class for tokenizers."""
@abc.abstractmethod
def encode(self,
inputs: str,
prepend_bos: bool = False,
append_eos: bool = False) -> np.ndarray:
"""Encode input string into an array of token IDs.
Args:
inputs: a string.
prepend_bos: set to True to add <bos> token at the beginning of the token
sequence.
append_eos: set to True to add <eos> token at the end of the token
sequence.
Returns:
tokens: [n_tokens] int array.
"""
@abc.abstractmethod
def decode(self, inputs) -> str:
"""Decode a sequence of tokens back into a string.
Args:
inputs: array or list of ints.
Returns:
s: the decoded string using this tokenizer.
"""
@property
@abc.abstractmethod
def vocab_size(self) -> int:
"""Size of the vocabulary."""
@abc.abstractmethod
def pad_token(self) -> int:
"""ID of the <pad> token."""
@abc.abstractmethod
def bos_token(self) -> int:
"""ID of the <bos> token."""
class WordTokenizer(Tokenizer):
"""Word-level tokenizer for white-space separated text data."""
def __init__(self, vocab_file: str):
"""Constructor.
Args:
vocab_file: a csv vocab file.
"""
content = io_tools.read_txt_file(vocab_file, encoding='utf-8')
with io.StringIO(content) as f:
r = csv.reader(f)
vocab = [w for w, _ in r]
# Add pad and bos tokens to the vocab
to_add = ['<pad>', '<bos>']
if '<unk>' not in vocab:
to_add.append('<unk>')
vocab = to_add + vocab
# token-index mappings
self._t2i = {t: i for i, t in enumerate(vocab)}
self._i2t = {i: t for t, i in self._t2i.items()}
self._unk_token = self._t2i['<unk>']
self._bos_token = self._t2i['<bos>']
self._pad_token = self._t2i['<pad>']
@property
def vocab_size(self):
return len(self._t2i)
def encode(self, inputs, prepend_bos=False, append_eos=False):
tokens = [self._t2i.get(t, self._unk_token) for t in inputs.split(' ') if t]
if prepend_bos:
tokens = [self._bos_token] + tokens
if append_eos:
# Reuse <bos> as <eos>.
tokens.append(self._bos_token)
return np.array(tokens, dtype=np.int32)
def decode(self, inputs):
"""Decode a sequence of token IDs back into a string."""
# Remove the first <bos> token if there is any.
if inputs[0] == self._bos_token:
inputs = inputs[1:]
tokens = []
for i in inputs:
# Use <bos> also as <eos> and stop there.
if i == self._bos_token:
break
tokens.append(self._i2t[i])
return ' '.join(tokens)
def pad_token(self):
return self._pad_token
def bos_token(self):
return self._bos_token
class GraphTokenizer:
"""Tokenizer for the content on the graphs."""
def __init__(self, vocab_file: str):
"""Constructor.
Args:
vocab_file: path to a vocab file.
"""
content = io_tools.read_txt_file(vocab_file, encoding='utf-16')
vocab = content.split('\n')
vocab = ['<pad>', '<bos>', '<unk>'] + vocab
# token-index mappings
self._t2i = {t: i for i, t in enumerate(vocab)}
self._i2t = {i: t for t, i in self._t2i.items()}
self._unk_token = self._t2i['<unk>']
self._bos_token = self._t2i['<bos>']
self._pad_token = self._t2i['<pad>']
@property
def vocab_size(self):
return len(self._t2i)
def encode_node(self, txt: str) -> np.ndarray:
return np.array([self._t2i.get(t, self._unk_token)
for t in self.split_node(txt)])
def encode_edge(self, txt: str) -> np.ndarray:
return np.array([self._t2i.get(t, self._unk_token)
for t in self.split_edge(txt)])
def encode(self, inputs, prepend_bos=False, append_eos=False):
tokens = [self._t2i.get(t, self._unk_token) for t in inputs.split(' ') if t]
if prepend_bos:
tokens = [self._bos_token] + tokens
if append_eos:
# Reuse <bos> as <eos>.
tokens.append(self._bos_token)
return np.array(tokens, dtype=np.int32)
def decode(self, inputs):
"""Decode a sequence of token IDs back into a string."""
# Remove the first <bos> token if there is any.
if inputs[0] == self._bos_token:
inputs = inputs[1:]
tokens = []
for i in inputs:
# Use <bos> also as <eos> and stop there.
if i == self._bos_token:
break
tokens.append(self._i2t[i])
return ' '.join(tokens)
@classmethod
def split_node(cls, txt: str) -> List[str]:
"""Split a node string into a sequence of tokens."""
if txt[0] == '"' and txt[-1] == '"': # Node is a string literal.
tokens = nltk.wordpunct_tokenize(io_tools.normalize_freebase_string(
txt[1:-1].lower()))
for i, t in enumerate(tokens):
if t.isnumeric():
tokens[i] = '<number>'
return tokens
else: # If node is not a string literal it is always an entity.
return ['<entity>']
@classmethod
def split_edge(cls, txt: str) -> List[str]:
"""Split an edge string into a sequence of tokens."""
return re.split('[._ ]+', txt.lower().split('/')[1])
def pad_token(self):
return self._pad_token
def bos_token(self):
return self._bos_token
|
deepmind-research-master
|
wikigraphs/wikigraphs/data/tokenizers.py
|
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Data writer for Stanford Bunny experiments and other objects."""
# pylint: disable=unused-import
import copy
import io
import os
import time
from absl import app
from absl import flags
from absl import logging
from dm_control import mujoco
import numpy as np
_SHARD = flags.DEFINE_integer('shard', 0, 'Shard index')
_SIZE = flags.DEFINE_integer('size', 1000,
'Number of images to save to a shard')
_OBJECT = flags.DEFINE_string('object', 'dragon', 'Which object to render')
_PATH = flags.DEFINE_string('path', '', 'Path to folder with .stl files')
render_height = 1024
render_width = 1024
height = 256
width = 256
def get_normal(x):
"""Get vectors normal to a unit vector."""
_, _, v = np.linalg.svd(x[None, :])
return v[:, 1:]
def render(quat, light, mesh='bunny', meshdir='data'):
"""Script to render an image."""
scale, pos = None, None
if mesh == 'bunny':
scale = 0.03
pos = -1.0
elif mesh == 'dragon':
scale = 0.06
pos = -0.3
simple_world_mjcf_template = """
<mujoco>
<visual>
<headlight active="0"/>
<global offwidth="%s" offheight="%s"/>
</visual>
<compiler meshdir="%s"/>
<asset>
<mesh name="%s" file="%s.stl" scale="%g %g %g"/>
</asset>
<worldbody>
<camera name="main" pos="0 0 5" xyaxes="1 0 0 0 1 0"/>
<body name="obj" quat="{} {} {} {}">
<geom name="%s" type="mesh" mesh="%s" pos="0 0 %g"/>
</body>
<light pos="{} {} {}" directional="true" dir="{} {} {}"/>
<light pos="{} {} {}" directional="true" dir="{} {} {}"/>
</worldbody>
</mujoco>
""" % (render_width, render_height, meshdir, mesh, mesh,
scale, scale, scale, mesh, mesh, pos)
light /= np.linalg.norm(light)
quat /= np.linalg.norm(quat)
simple_world_mjcf = simple_world_mjcf_template.format(
*(np.concatenate((quat,
5*light, -5*light,
-5*light, 5*light)).tolist()))
physics = mujoco.Physics.from_xml_string(simple_world_mjcf)
data = physics.render(camera_id='main',
height=render_height,
width=render_width).astype(np.float32)
data = data.reshape((width, int(render_width/width),
height, int(render_height/height), 3))
return np.mean(np.mean(data, axis=1), axis=2)
def get_tangent(quat, light, mesh='bunny', meshdir='data',
eps=0.03, use_light=True, use_quat=True):
"""Render image along with its tangent vectors by finite differences."""
assert use_light or use_quat
n = 0
light_tangent = None
quat_tangent = None
if use_light:
light_tangent = get_normal(light)
n += 2
if use_quat:
quat_tangent = get_normal(quat)
n += 3
# a triple-wide pixel buffer
try:
data = render(quat, light, mesh=mesh, meshdir=meshdir)
image_tangent = np.zeros((n, height, width, 3), dtype=np.float32)
if use_quat:
for i in range(3):
perturbed = render(quat + eps * quat_tangent[:, i],
light, mesh=mesh, meshdir=meshdir)
image_tangent[i] = (perturbed - data).astype(np.float32) / eps
if use_light:
j = 3 if use_quat else 0
for i in range(2):
perturbed = render(quat, light + eps * light_tangent[:, i],
mesh=mesh, meshdir=meshdir)
image_tangent[i+j] = (perturbed - data) / eps
image_tangent -= np.mean(image_tangent, axis=0)[None, ...]
latent_tangent = np.block(
[[quat_tangent, np.zeros((4, 2), dtype=np.float32)],
[np.zeros((3, 3), dtype=np.float32), light_tangent]])
return (np.mean(data, axis=-1),
np.mean(image_tangent, axis=-1),
latent_tangent)
except: # pylint: disable=bare-except
logging.info('Failed with latents (quat: %s, light: %s)', quat, light)
def main(_):
images = np.zeros((_SIZE.value, height, width), dtype=np.float32)
latents = np.zeros((_SIZE.value, 7), dtype=np.float32)
image_tangents = np.zeros((_SIZE.value, 5, height, width), dtype=np.float32)
latent_tangents = np.zeros((_SIZE.value, 7, 5), dtype=np.float32)
for i in range(_SIZE.value):
light = np.random.randn(3)
light /= np.linalg.norm(light)
quat = np.random.randn(4) # rotation represented as quaternion
quat /= np.linalg.norm(quat)
latents[i] = np.concatenate((light, quat))
images[i], image_tangents[i], latent_tangents[i] = (
get_tangent(quat, light, mesh=_OBJECT.value, meshdir=_PATH.value))
logging.info('Rendered image %d of %d', i, _SIZE.value)
os.makedirs(os.path.join(_PATH.value, _OBJECT.value), exist_ok=True)
with open(os.path.join(
_PATH.value, _OBJECT.value, 'shard_%03d.npz' % _SHARD.value), 'wb') as f:
io_buffer = io.BytesIO()
np.savez(io_buffer, images, latents, image_tangents, latent_tangents)
f.write(io_buffer.getvalue())
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
geomancer/data_writer.py
|
# Copyright 2020 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 Geometric Manifold Component Estimator (GEOMANCER)."""
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from geomancer import geomancer
class GeomancerTest(parameterized.TestCase):
@parameterized.parameters(
{'zero_trace': False},
{'zero_trace': True})
def test_sym_op(self, zero_trace):
"""sym_op on tril(X) gives same result as QXQ' for symmetric X?"""
n = 5
x = np.random.randn(n, n)
x += x.T
if zero_trace:
np.fill_diagonal(x, np.diag(x)-np.trace(x)/n)
q, _ = np.linalg.qr(np.random.randn(n, n))
sym_q = geomancer.sym_op(q, zero_trace=zero_trace)
tril_x = x[np.tril_indices(n)]
if zero_trace:
tril_x = tril_x[:-1]
vec_y = sym_q @ tril_x
y = q @ x @ q.T
y_ = geomancer.vec_to_sym(vec_y, n, zero_trace=zero_trace)
np.testing.assert_allclose(y_, y)
def test_ffdiag(self):
k = 2
n = 5
w, _ = np.linalg.qr(np.random.randn(n, n))
psi = np.random.randn(k, n)
a = np.zeros((k, n, n))
for i in range(k):
a[i] = w @ np.diag(psi[i]) @ w.T
w_ = geomancer.ffdiag(a)
for i in range(k):
x = w_ @ a[i] @ w_.T
diag = np.diag(x).copy()
np.fill_diagonal(x, 1.0)
# check that x is diagonal
np.testing.assert_allclose(x, np.eye(n), rtol=1e-10, atol=1e-10)
self.assertTrue(np.all(np.min(
np.abs(diag[None, :] - psi[i][:, None]), axis=0) < 1e-10))
def test_make_nearest_neighbor_graph(self):
n = 100
# make points on a circle
data = np.zeros((n, 2))
for i in range(n):
data[i, 0] = np.sin(i*2*np.pi/n)
data[i, 1] = np.cos(i*2*np.pi/n)
graph = geomancer.make_nearest_neighbors_graph(data, 4, n=10)
for i in range(n):
self.assertLen(graph.rows[i], 4)
self.assertIn((i+1) % n, graph.rows[i])
self.assertIn((i+2) % n, graph.rows[i])
self.assertIn((i-1) % n, graph.rows[i])
self.assertIn((i-2) % n, graph.rows[i])
if __name__ == '__main__':
absltest.main()
|
deepmind-research-master
|
geomancer/geomancer_test.py
|
# Copyright 2020 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Setup for pip package."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['numpy', 'scipy', 'matplotlib', 'absl-py', 'tqdm']
setup(
name='geomancer',
version='0.1',
description='A library for the Geometric Manifold Component Estimator.',
url='https://github.com/deepmind/deepmind-research/geomancer',
author='DeepMind',
author_email='pfau@google.com',
# Contained modules and scripts.
packages=find_packages(),
install_requires=REQUIRED_PACKAGES,
platforms=['any'],
license='Apache 2.0',
)
|
deepmind-research-master
|
geomancer/setup.py
|
# Copyright 2020 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run GEOMANCER on products of synthetic manifolds."""
import re
from absl import app
from absl import flags
from absl import logging
import geomancer
from matplotlib import gridspec
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import special_ortho_group
from tqdm import tqdm
SPECIFICATION = flags.DEFINE_list(
name='specification', default=['S^2', 'S^2'], help='List of submanifolds')
NPTS = flags.DEFINE_integer(
name='npts', default=1000, help='Number of data points')
ROTATE = flags.DEFINE_boolean(
name='rotate', default=False, help='Apply random rotation to the data')
PLOT = flags.DEFINE_boolean(
name='plot', default=True, help='Whether to enable plotting')
def make_so_tangent(q):
"""Given an n x n orthonormal matrix, return a basis for its tangent space."""
n = q.shape[0]
assert np.allclose(q.T @ q, np.eye(n), atol=1e-4, rtol=1e-4)
a = np.zeros((n, n))
ii = 0
dq = np.zeros((n, n, n*(n-1)//2))
for i in range(n):
for j in range(i+1, n):
a[i, j] = 1
a[j, i] = -1
dq[..., ii] = a @ q # tangent vectors are skew-symmetric matrix times Q
a[i, j] = 0
a[j, i] = 0
ii += 1
# reshape and orthonormalize the result
return np.linalg.qr(np.reshape(dq, (n**2, n*(n-1)//2)))[0]
def make_sphere_tangent(x):
_, _, v = np.linalg.svd(x[None, :])
return v[:, 1:]
def make_true_tangents(spec, data):
"""Return a set of orthonormal bases, one for each submanifold."""
for i in range(spec.shape[1]):
assert spec[0, i] == 0 or spec[1, i] == 0
so_dim = sum(dim ** 2 for dim in spec[0])
sphere_dim = sum(dim+1 if dim > 0 else 0 for dim in spec[1])
assert so_dim + sphere_dim == data.shape[0]
ii = 0
tangents = []
for i in range(spec.shape[1]):
if spec[0, i] != 0:
dim = spec[0, i]
tangents.append(make_so_tangent(np.reshape(data[ii:ii+dim**2],
(dim, dim))))
ii += dim ** 2
else:
dim = spec[1, i]
tangents.append(make_sphere_tangent(data[ii:ii+dim+1]))
ii += dim + 1
tangents2 = []
for i in range(len(tangents)):
size1 = sum(x.shape[0] for x in tangents[:i])
size2 = sum(x.shape[0] for x in tangents[i+1:])
tangents2.append(np.concatenate(
(np.zeros((size1, tangents[i].shape[1])),
tangents[i],
np.zeros((size2, tangents[i].shape[1]))), axis=0))
return tangents2
def make_product_manifold(specification, npts):
"""Generate data from a product of manifolds with the given specification."""
data = []
tangents = []
latent_dim = 0
spec_array = np.zeros((2, len(specification)), dtype=np.int32)
for i, spec in enumerate(specification):
so_spec = re.search(r'SO\(([0-9]+)\)', spec) # matches "SO(<numbers>)"
sphere_spec = re.search(r'S\^([0-9]+)', spec) # matches "S^<numbers>"
if sphere_spec is not None:
dim = int(sphere_spec.group(1))
spec_array[1, i] = dim
latent_dim += dim
dat = np.random.randn(npts, dim+1)
dat /= np.tile(np.sqrt(np.sum(dat**2, axis=1)[..., None]),
[1, dim+1])
elif so_spec is not None:
dim = int(so_spec.group(1))
spec_array[0, i] = dim
latent_dim += dim * (dim - 1) // 2
dat = [np.ndarray.flatten(special_ortho_group.rvs(dim), order='C')
for _ in range(npts)]
dat = np.stack(dat)
else:
raise ValueError(f'Unrecognized manifold: {spec}')
data.append(dat)
data = np.concatenate(data, axis=1)
for i in range(spec_array.shape[1]):
if spec_array[0, i] != 0:
dim = spec_array[0, i]
tangents.append(np.zeros((npts, data.shape[1], dim * (dim - 1) // 2)))
elif spec_array[1, i] != 0:
dim = spec_array[1, i]
tangents.append(np.zeros((npts, data.shape[1], dim)))
for i in tqdm(range(npts)):
true_tangent = make_true_tangents(spec_array, data[i])
for j in range(len(specification)):
tangents[j][i] = true_tangent[j]
logging.info('Constructed data and true tangents for %s',
' x '.join(specification))
return data, latent_dim, tangents
def main(_):
# Generate data and run GEOMANCER
data, dim, tangents = make_product_manifold(SPECIFICATION.value, NPTS.value)
if ROTATE.value:
rot, _ = np.linalg.qr(np.random.randn(data.shape[1], data.shape[1]))
data_rot = data @ rot.T
components, spectrum = geomancer.fit(data_rot, dim)
errors = geomancer.eval_unaligned(data_rot, components, data, tangents)
else:
components, spectrum = geomancer.fit(data, dim)
errors = geomancer.eval_aligned(components, tangents)
logging.info('Error between subspaces: %.2f +/- %.2f radians',
np.mean(errors),
np.std(errors))
if PLOT.value:
# Plot spectrum
plt.figure(figsize=(8, 6))
plt.scatter(np.arange(len(spectrum)), spectrum, s=100)
largest_gap = np.argmax(spectrum[1:]-spectrum[:-1]) + 1
plt.axvline(largest_gap, linewidth=2, c='r')
plt.xticks([])
plt.yticks(fontsize=18)
plt.xlabel('Index', fontsize=24)
plt.ylabel('Eigenvalue', fontsize=24)
plt.title('GeoManCEr Eigenvalue Spectrum', fontsize=24)
# Plot subspace bases
fig = plt.figure(figsize=(8, 6))
bases = components[0]
gs = gridspec.GridSpec(1, len(bases),
width_ratios=[b.shape[1] for b in bases])
for i in range(len(bases)):
ax = plt.subplot(gs[i])
ax.imshow(bases[i])
ax.set_xticks([])
ax.set_yticks([])
ax.set_title(r'$T_{\mathbf{x}_1}\mathcal{M}_%d$' % (i+1), fontsize=18)
fig.canvas.set_window_title('GeoManCEr Results')
# Plot ground truth
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(1, len(tangents),
width_ratios=[b.shape[2] for b in tangents])
for i, spec in enumerate(SPECIFICATION.value):
ax = plt.subplot(gs[i])
ax.imshow(tangents[i][0])
ax.set_xticks([])
ax.set_yticks([])
ax.set_title(r'$T_{\mathbf{x}_1}%s$' % spec, fontsize=18)
fig.canvas.set_window_title('Ground Truth')
plt.show()
if __name__ == '__main__':
app.run(main)
|
deepmind-research-master
|
geomancer/train.py
|
# Copyright 2020 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Code for the Geometric Manifold Component Estimator (GEOMANCER)."""
import itertools
from absl import logging
import numpy as np
import scipy
import scipy.sparse
import scipy.sparse.linalg
from tqdm import tqdm
def sym_op(x, zero_trace=False):
"""Given X, makes L(A) = X @ A @ X' for symmetric matrices A.
If A is not symmetric, L(A) will return X @ (A_L + A_L') @ X' where A_L is
the lower triangular of A (with the diagonal divided by 2).
Args:
x: The matrix from which to construct the operator
zero_trace (optional): If true, restrict the operator to only act on
matrices with zero trace, effectively reducing the dimensionality by one.
Returns:
A matrix Y such that vec(L(A)) = Y @ vec(A).
"""
n = x.shape[0]
# Remember to subtract off the diagonal once
xx = (np.einsum('ik,jl->ijkl', x, x) +
np.einsum('il,jk->ijkl', x, x) -
np.einsum('ik,jl,kl->ijkl', x, x, np.eye(n)))
xx = xx[np.tril_indices(n)]
xx = xx.transpose(1, 2, 0)
xx = xx[np.tril_indices(n)]
xx = xx.T
if zero_trace:
diag_idx = np.cumsum([0]+list(range(2, n)))
proj_op = np.eye(n*(n+1)//2)[:, :-1]
proj_op[-1, diag_idx] = -1
# multiply by operator that completes last element of diagonal
# for a zero-trace matrix
xx = xx @ proj_op
xx = xx[:-1]
return xx
def vec_to_sym(x, n, zero_trace=False):
y = np.zeros((n, n))
if zero_trace:
x = np.append(x, 0.0)
y[np.tril_indices(n)] = x
y += y.T
y[np.diag_indices(n)] /= 2.0
if zero_trace:
y[-1, -1] = -np.trace(y)
return y
def ffdiag(data, lr=1.0, tol=1e-10, verbose=False, eig_init=False):
"""Orthogonal FFDiag algorithm of Ziehe et al 2004."""
n = data.shape[1]
k = data.shape[0]
c = data.copy()
if eig_init:
_, v = np.linalg.eig(data[0])
v = v.T
for i in range(k):
c[i] = v @ c[i] @ v.T
else:
v = np.eye(n)
err_ = np.inf
for t in range(10000):
w = np.zeros((n, n))
for i in range(n):
for j in range(i+1, n):
diag = c[:, i, i] - c[:, j, j]
w[i, j] = np.sum(c[:, i, j] * diag) / np.sum(diag ** 2)
w -= w.T
norm = np.linalg.svd(w, compute_uv=False).max()
if norm > lr:
w *= lr / norm
ew = scipy.linalg.expm(w)
v = ew @ v
for i in range(k):
c[i] = ew @ c[i] @ ew.T
cdiag = c.copy()
for i in range(n):
for j in range(k):
cdiag[j, i, i] = 0
err = np.linalg.norm(cdiag)
if verbose:
logging.info('Iter %d: %f', t, err)
if err_ - err < tol and err_ - err >= 0:
return v
err_ = err
return v
def avg_angle_between_subspaces(xs, ys):
"""Compute the error between two sets of subspaces."""
if len(xs) != len(ys):
return np.pi / 2 # largest possible angle
angles = []
for ys_perm in itertools.permutations(ys):
angles.append([])
for i in range(len(xs)):
if xs[i].shape[1] == ys_perm[i].shape[1]:
sigma = np.linalg.svd(xs[i].T @ ys_perm[i], compute_uv=False)
angles[-1].append(np.arccos(np.min(sigma)))
else:
angles[-1].append(np.pi / 2)
angles = np.array(angles)
return np.min(np.mean(angles, axis=1))
def make_nearest_neighbors_graph(data, k, n=1000):
"""Build exact k-nearest neighbors graph from numpy data.
Args:
data: Data to compute nearest neighbors of, each column is one point
k: number of nearest neighbors to compute
n (optional): number of neighbors to compute simultaneously
Returns:
A scipy sparse matrix in LIL format giving the symmetric nn graph.
"""
shape = data.shape
assert shape[0] % n == 0
nbr_graph = scipy.sparse.lil_matrix((shape[0], shape[0]))
norm = np.sum(data**2, axis=1)
cols = np.meshgrid(np.arange(n), np.ones(k+1))[0]
for i in tqdm(range(0, shape[0], n)):
dot = data @ data[i:i+n].T
dists = np.sqrt(np.abs(norm[:, None] - 2*dot + norm[i:i+n][None, :]))
idx = np.argpartition(dists, k, axis=0)[:k+1]
nbrs = idx[np.argsort(dists[idx, cols], axis=0), cols][1:]
for j in range(n):
nbr_graph[i+j, nbrs[:, j]] = 1
# Symmetrize graph
for i in tqdm(range(shape[0])):
for j in nbr_graph.rows[i]:
if nbr_graph[j, i] == 0:
nbr_graph[j, i] = nbr_graph[i, j]
logging.info('Symmetrized neighbor graph')
return nbr_graph
def make_tangents(data, neighbor_graph, k):
"""Construct all tangent vectors for the dataset."""
tangents = np.zeros((data.shape[0], k, data.shape[1]), dtype=np.float32)
for i in tqdm(range(data.shape[0])):
diff = data[neighbor_graph.rows[i]] - data[i]
_, _, u = np.linalg.svd(diff, full_matrices=False)
tangents[i] = u[:k]
logging.info('Computed all tangents')
return tangents
def make_connection(tangents, neighbor_graph):
"""Make connection matrices for all edges of the neighbor graph."""
connection = {}
for i in tqdm(range(tangents.shape[0])):
for j in neighbor_graph.rows[i]:
if j > i:
uy, _, ux = np.linalg.svd(tangents[j] @ tangents[i].T,
full_matrices=False)
conn = uy @ ux
connection[(i, j)] = conn
connection[(j, i)] = conn.T
logging.info('Constructed all connection matrices')
return connection
def make_laplacian(connection, neighbor_graph, sym=True, zero_trace=True):
"""Make symmetric zero-trace second-order graph connection Laplacian."""
n = neighbor_graph.shape[0]
k = list(connection.values())[0].shape[0]
bsz = (k*(k+1)//2 - 1 if zero_trace else k*(k+1)//2) if sym else k**2
data = np.zeros((neighbor_graph.nnz + n, bsz, bsz), dtype=np.float32)
indptr = []
indices = np.zeros(neighbor_graph.nnz + n)
index = 0
for i in tqdm(range(n)):
indptr.append(index)
data[index] = len(neighbor_graph.rows[i]) * np.eye(bsz)
indices[index] = i
index += 1
for j in neighbor_graph.rows[i]:
if sym:
kron = sym_op(connection[(j, i)], zero_trace=zero_trace)
else:
kron = np.kron(connection[(j, i)], connection[(j, i)])
data[index] = -kron
indices[index] = j
index += 1
indptr.append(index)
indptr = np.array(indptr)
laplacian = scipy.sparse.bsr_matrix((data, indices, indptr),
shape=(n*bsz, n*bsz))
logging.info('Built 2nd-order graph connection Laplacian.')
return laplacian
def cluster_subspaces(omega):
"""Cluster different dimensions from the eigenvectors of the Laplacian."""
w = ffdiag(omega) # simultaneous diagonalization
psi = np.zeros(omega.shape[:2])
for i in range(omega.shape[0]):
psi[i] = np.diag(w @ omega[i] @ w.T) # compute diagonals
# Compute cosine similarity of diagonal vectors
psi_outer = psi.T @ psi
psi_diag = np.diag(psi_outer)
cos_similarity = psi_outer / np.sqrt(np.outer(psi_diag, psi_diag))
adj = cos_similarity > 0.5 # adjacency matrix for graph of clusters
# Use graph Laplacian to find cliques
# (though a greedy algorithm could work too)
lapl = np.diag(np.sum(adj, axis=0)) - adj # graph Laplacian
d, v = np.linalg.eig(lapl)
# connected components of graph
cliques = np.abs(v[:, np.abs(d) < 1e-6]) > 1e-6
tangents = [w[cliques[:, i]] for i in range(sum(np.abs(d) < 1e-6))]
return tangents
def fit(data, k, gamma=None, nnbrs=None, neig=10, shard_size=1000):
"""The Geometric Manifold Component Estimator.
Args:
data: the dataset, a set of points sample from a product manifold.
k: the dimensionality of the manifold.
gamma (optional): the threshold in the spectrum at which to cut off the
number of submanifolds.
nnbrs (optional): number of neighbors to use for each point.
neig (optional): the total number of eigenvectors to compute.
shard_size (optional): the size of shard to use in knn computation.
Returns:
A list of lists of subspace bases, one list for each element of the dataset,
and the spectrum of the 2nd-order graph Laplacian.
"""
if not nnbrs:
nnbrs = 2*k
neighbor_graph = make_nearest_neighbors_graph(data, nnbrs, n=shard_size)
tangents = make_tangents(data, neighbor_graph, k)
connection = make_connection(tangents, neighbor_graph)
laplacian = make_laplacian(connection, neighbor_graph)
eigvals, eigvecs = scipy.sparse.linalg.eigsh(laplacian, k=neig, which='SM')
logging.info('Computed bottom eigenvectors of 2nd-order Laplacian')
bsz = k*(k+1)//2 - 1 # Block size for the projected 2nd-order Laplacian
if gamma:
nm = np.argwhere(eigvals < gamma)[-1, 0] + 1
else: # If no threshold is provided, just use the largest gap in the spectrum
nm = np.argmax(eigvals[1:] - eigvals[:-1]) + 1
eigvecs = eigvecs.reshape(data.shape[0], bsz, neig)
omega = np.zeros((nm, k, k), dtype=np.float32)
components = []
for i in tqdm(range(data.shape[0])):
for j in range(nm):
omega[j] = vec_to_sym(eigvecs[i, :, j], k, zero_trace=True)
components.append([tangents[i].T @ x.T for x in cluster_subspaces(omega)])
logging.info('GEOMANCER completed')
return components, eigvals
def eval_aligned(tangents, true_tangents):
"""Evaluation for aligned data."""
errors = np.zeros(len(tangents))
for i in tqdm(range(len(tangents))):
errors[i] = avg_angle_between_subspaces([gt[i] for gt in true_tangents],
tangents[i])
logging.info('Computed angles between ground truth and GEOMANCER results')
return errors
def eval_unaligned(data, tangents, true_data, true_tangents, k=10, n=1000):
"""Evaluation for unaligned data."""
logging.info('Evaluating unaligned data')
errors = np.zeros(data.shape[0])
nbrs = make_nearest_neighbors_graph(true_data, k=k, n=n)
for i in tqdm(range(data.shape[0])):
tangent = np.concatenate(tangents[i], axis=1)
true_tangent = np.concatenate([t[i] for t in true_tangents], axis=1)
dx_true = (true_data[nbrs.rows[i]] - true_data[i]) @ true_tangent
dx_result = (data[nbrs.rows[i]] - data[i]) @ tangent
# compute canonical correlations between the two dxs
xx = dx_true.T @ dx_true
yy = dx_result.T @ dx_result
xy = dx_true.T @ dx_result
xx_ = np.linalg.inv(xx)
yy_ = np.linalg.inv(yy)
foo = scipy.linalg.sqrtm(xx_) @ xy @ scipy.linalg.sqrtm(yy_)
u, _, v = np.linalg.svd(foo)
# project subspaces for results and ground truth into aligned space
proj = [v @ tangent.T @ s for s in tangents[i]]
true_proj = [u.T @ true_tangent.T @ s[i] for s in true_tangents]
errors[i] = avg_angle_between_subspaces(proj, true_proj)
return errors
|
deepmind-research-master
|
geomancer/geomancer.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A module for constructing the RGB stacking task.
This file builds the composer task containing a single sawyer robot facing
3 objects: a red, a green and a blue one.
We define:
- All the simulation objects, robot, basket, objects.
- The sensors to measure the state of the environment.
- The effector to control the robot.
- The initialization logic.
On top of this we can build a MoMa subtask environment. In this subtask
environment we will decide what the reward will be and what observations are
exposed. Thus allowing us to change the goal without changing this environment.
"""
from typing import Sequence
from dm_control import composer
from dm_control.composer.variation import distributions
from dm_control.composer.variation import rotations
from dm_robotics.geometry import pose_distribution
from dm_robotics.manipulation.props.rgb_objects import rgb_object
from dm_robotics.manipulation.standard_cell import rgb_basket
from dm_robotics.moma import base_task
from dm_robotics.moma import entity_initializer
from dm_robotics.moma import prop
from dm_robotics.moma import robot as moma_robot
from dm_robotics.moma.effectors import arm_effector as arm_effector_module
from dm_robotics.moma.effectors import cartesian_4d_velocity_effector
from dm_robotics.moma.effectors import cartesian_6d_velocity_effector
from dm_robotics.moma.effectors import default_gripper_effector
from dm_robotics.moma.effectors import min_max_effector
from dm_robotics.moma.models.arenas import empty
from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85
from dm_robotics.moma.models.end_effectors.wrist_sensors import robotiq_fts300
from dm_robotics.moma.models.robots.robot_arms import sawyer
from dm_robotics.moma.models.robots.robot_arms import sawyer_constants
from dm_robotics.moma.sensors import action_sensor
from dm_robotics.moma.sensors import camera_sensor
from dm_robotics.moma.sensors import prop_pose_sensor
from dm_robotics.moma.sensors import robot_arm_sensor
from dm_robotics.moma.sensors import robot_tcp_sensor
from dm_robotics.moma.sensors import robot_wrist_ft_sensor
from dm_robotics.moma.sensors import robotiq_gripper_sensor
from dm_robotics.moma.sensors import site_sensor
import numpy as np
# Margin from the joint limits at which to stop the Z rotation when using 4D
# control. Values chosen to match the existing PyRobot-based environments.
WRIST_RANGE = (-np.pi / 2, np.pi / 2)
# Position of the basket relative to the attachment point of the robot.
_DEFAULT_BASKET_CENTER = (0.6, 0.)
DEFAULT_BASKET_HEIGHT = 0.0498
_BASKET_ORIGIN = _DEFAULT_BASKET_CENTER + (DEFAULT_BASKET_HEIGHT,)
WORKSPACE_CENTER = np.array(_DEFAULT_BASKET_CENTER + (0.1698,))
WORKSPACE_SIZE = np.array([0.25, 0.25, 0.2])
# Maximum linear and angular velocity of the robot's TCP.
_MAX_LIN_VEL = 0.07
_MAX_ANG_VEL = 1.0
# Limits of the distributions used to sample initial positions (X, Y, Z in [m])
# for props in the basket.
_PROP_MIN_POSITION_BOUNDS = [0.50, -0.10, 0.12]
_PROP_MAX_POSITION_BOUNDS = [0.70, 0.10, 0.12]
# Limits of the distributions used to sample initial position for TCP.
_TCP_MIN_POSE_BOUNDS = [0.5, -0.14, 0.22, np.pi, 0, -np.pi / 4]
_TCP_MAX_POSE_BOUNDS = [0.7, 0.14, 0.43, np.pi, 0, np.pi / 4]
# Control timestep exposed to the agent.
_CONTROL_TIMESTEP = 0.05
# Joint state used for the nullspace.
_NULLSPACE_JOINT_STATE = [
0.0, -0.5186220703125, -0.529384765625, 1.220857421875, 0.40857421875,
1.07831640625, 0.0]
# Joint velocity magnitude limits from the Sawyer URDF.
_JOINT_VEL_LIMITS = sawyer_constants.VELOCITY_LIMITS['max']
# Identifier for the cameras. The key is the name used for the MoMa camera
# sensor and the value corresponds to the identifier of that camera in the
# mjcf model.
_CAMERA_IDENTIFIERS = {'basket_back_left': 'base/basket_back_left',
'basket_front_left': 'base/basket_front_left',
'basket_front_right': 'base/basket_front_right'}
# Configuration of the MuJoCo cameras.
_CAMERA_CONFIG = camera_sensor.CameraConfig(
width=128,
height=128,
fovy=30.,
has_rgb=True,
has_depth=False,
)
def rgb_task(red_obj_id: str,
green_obj_id: str,
blue_obj_id: str) -> base_task.BaseTask:
"""Builds a BaseTask and all dependencies.
Args:
red_obj_id: The RGB object ID that corresponds to the red object. More
information on this can be found in the RGB Objects file.
green_obj_id: See `red_obj_id`
blue_obj_id: See `red_obj_id`
Returns:
The modular manipulation (MoMa) base task for the RGB stacking environment.
A robot is placed in front of a basket containing 3 objects: a red, a green
and blue one.
"""
# Build the composer scene.
arena = _arena()
_workspace(arena)
robot = _sawyer_robot(robot_name='robot0')
arena.attach(robot.arm)
# We add a camera with a good point of view for capturing videos.
pos = '1.4 0.0 0.45'
quat = '0.541 0.455 0.456 0.541'
name = 'main_camera'
fovy = '45'
arena.mjcf_model.worldbody.add(
'camera', name=name, pos=pos, quat=quat, fovy=fovy)
props = _props(red_obj_id, green_obj_id, blue_obj_id)
for p in props:
frame = arena.add_free_entity(p)
p.set_freejoint(frame.freejoint)
# Add in the MoMa sensor to get observations from the environment.
extra_sensors = prop_pose_sensor.build_prop_pose_sensors(props)
camera_configurations = {
name: _CAMERA_CONFIG for name in _CAMERA_IDENTIFIERS.keys()}
extra_sensors.extend(
camera_sensor.build_camera_sensors(
camera_configurations, arena.mjcf_model, _CAMERA_IDENTIFIERS))
# Initializers to place the TCP and the props in the basket.
dynamic_initializer = entity_initializer.TaskEntitiesInitializer(
[_gripper_initializer(robot), _prop_initializers(props)])
moma_task = base_task.BaseTask(
task_name='rgb_stacking',
arena=arena,
robots=[robot],
props=props,
extra_sensors=extra_sensors,
extra_effectors=[],
scene_initializer=lambda _: None,
episode_initializer=dynamic_initializer,
control_timestep=_CONTROL_TIMESTEP)
return moma_task
def _workspace(arena: composer.Arena) -> rgb_basket.RGBBasket:
"""Returns the basket used in the rgb stacking environment."""
workspace = rgb_basket.RGBBasket()
attachment_site = arena.mjcf_model.worldbody.add(
'site', pos=_BASKET_ORIGIN, rgba='0 0 0 0', size='0.01')
arena.attach(workspace, attachment_site)
return workspace
def _gripper_initializer(
robot: moma_robot.Robot) -> entity_initializer.PoseInitializer:
"""Populates components with gripper initializers."""
gripper_pose_dist = pose_distribution.UniformPoseDistribution(
min_pose_bounds=_TCP_MIN_POSE_BOUNDS,
max_pose_bounds=_TCP_MAX_POSE_BOUNDS)
return entity_initializer.PoseInitializer(robot.position_gripper,
gripper_pose_dist.sample_pose)
def _prop_initializers(
props: Sequence[prop.Prop]) -> entity_initializer.PropPlacer:
"""Populates components with prop pose initializers."""
prop_position = distributions.Uniform(_PROP_MIN_POSITION_BOUNDS,
_PROP_MAX_POSITION_BOUNDS)
prop_quaternion = rotations.UniformQuaternion()
return entity_initializer.PropPlacer(
props=props,
position=prop_position,
quaternion=prop_quaternion,
settle_physics=True)
def _arena() -> composer.Arena:
"""Builds an arena Entity."""
arena = empty.Arena()
arena.mjcf_model.size.nconmax = 5000
arena.mjcf_model.size.njmax = 5000
return arena
def _sawyer_robot(robot_name: str) -> moma_robot.Robot:
"""Returns a Sawyer robot with all the sensors and effectors."""
arm = sawyer.Sawyer(
name=robot_name, actuation=sawyer_constants.Actuation.INTEGRATED_VELOCITY)
gripper = robotiq_2f85.Robotiq2F85()
wrist_ft = robotiq_fts300.RobotiqFTS300()
wrist_cameras = []
# Compose the robot after its model components are constructed. This should
# usually be done early on as some Effectors (and possibly Sensors) can only
# be constructed after the robot components have been composed.
moma_robot.standard_compose(
arm=arm, gripper=gripper, wrist_ft=wrist_ft, wrist_cameras=wrist_cameras)
# We need to measure the last action sent to the robot and the gripper.
arm_effector, arm_action_sensor = action_sensor.create_sensed_effector(
arm_effector_module.ArmEffector(
arm=arm, action_range_override=None, robot_name=robot_name))
# Effector used for the gripper. The gripper is controlled by applying the
# min or max command, this allows the agent to quicky learn how to grasp
# instead of learning how to close the gripper first.
gripper_effector, gripper_action_sensor = action_sensor.create_sensed_effector(
default_gripper_effector.DefaultGripperEffector(gripper, robot_name))
# Enable bang bang control for the gripper, this allows the agent to close and
# open the gripper faster.
gripper_effector = min_max_effector.MinMaxEffector(
base_effector=gripper_effector)
# Build the 4D cartesian controller, we use a 6D cartesian effector under the
# hood.
effector_model = cartesian_6d_velocity_effector.ModelParams(
element=arm.wrist_site, joints=arm.joints)
effector_control = cartesian_6d_velocity_effector.ControlParams(
control_timestep_seconds=_CONTROL_TIMESTEP,
max_lin_vel=_MAX_LIN_VEL,
max_rot_vel=_MAX_ANG_VEL,
joint_velocity_limits=np.array(_JOINT_VEL_LIMITS),
nullspace_gain=0.025,
nullspace_joint_position_reference=np.array(_NULLSPACE_JOINT_STATE),
regularization_weight=1e-2,
enable_joint_position_limits=True,
minimum_distance_from_joint_position_limit=0.01,
joint_position_limit_velocity_scale=0.95,
max_cartesian_velocity_control_iterations=300,
max_nullspace_control_iterations=300)
# Don't activate collision avoidance because we are restricted to the virtual
# workspace in the center of the basket.
cart_effector_6d = cartesian_6d_velocity_effector.Cartesian6dVelocityEffector(
robot_name=robot_name,
joint_velocity_effector=arm_effector,
model_params=effector_model,
control_params=effector_control)
cart_effector_4d = cartesian_4d_velocity_effector.Cartesian4dVelocityEffector(
effector_6d=cart_effector_6d,
element=arm.wrist_site,
effector_prefix=f'{robot_name}_cart_4d_vel')
# Constrain the workspace of the robot.
cart_effector_4d = cartesian_4d_velocity_effector.limit_to_workspace(
cartesian_effector=cart_effector_4d,
element=gripper.tool_center_point,
min_workspace_limits=WORKSPACE_CENTER - WORKSPACE_SIZE / 2,
max_workspace_limits=WORKSPACE_CENTER + WORKSPACE_SIZE / 2,
wrist_joint=arm.joints[-1],
wrist_limits=WRIST_RANGE,
reverse_wrist_range=True)
robot_sensors = []
# Sensor for the joint states (torques, velocities and angles).
robot_sensors.append(robot_arm_sensor.RobotArmSensor(
arm=arm, name=f'{robot_name}_arm', have_torque_sensors=True))
# Sensor for the cartesian pose of the tcp site.
robot_sensors.append(robot_tcp_sensor.RobotTCPSensor(
gripper=gripper, name=robot_name))
# Sensor for cartesian pose of the wrist site.
robot_sensors.append(site_sensor.SiteSensor(
site=arm.wrist_site, name=f'{robot_name}_wrist_site'))
# Sensor to measure the state of the gripper (position, velocity and grasp).
robot_sensors.append(robotiq_gripper_sensor.RobotiqGripperSensor(
gripper=gripper, name=f'{robot_name}_gripper'))
# Sensor for the wrench measured at the wrist sensor.
robot_sensors.append(robot_wrist_ft_sensor.RobotWristFTSensor(
wrist_ft_sensor=wrist_ft, name=f'{robot_name}_wrist'))
# Sensors to measure the last action sent to the arm joints and the gripper
# actuator.
robot_sensors.extend([arm_action_sensor, gripper_action_sensor])
return moma_robot.StandardRobot(
arm=arm,
arm_base_site_name='base_site',
gripper=gripper,
robot_sensors=robot_sensors,
wrist_cameras=wrist_cameras,
arm_effector=cart_effector_4d,
gripper_effector=gripper_effector,
wrist_ft=wrist_ft,
name=robot_name)
def _props(red: str, green: str, blue: str) -> Sequence[prop.Prop]:
"""Build task props."""
objects = ((red, 'red'), (green, 'green'), (blue, 'blue'))
color_set = [
[1, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 1, 1],
]
props = []
for i, (obj_id, color) in enumerate(objects):
p = rgb_object.RgbObjectProp(
obj_id=obj_id, color=color_set[i], name=f'rgb_object_{color}')
p = prop.WrapperProp(wrapped_entity=p, name=f'rgb_object_{color}')
props.append(p)
return props
|
rgb_stacking-main
|
rgb_stacking/task.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.
# ==============================================================================
"""Shaped and sparse reward functions for the RGB stacking task."""
from typing import Callable
from dm_control import mjcf
from dm_robotics.agentflow import spec_utils
from dm_robotics.moma import prop
import numpy as np
from rgb_stacking import physics_utils
from rgb_stacking import reward_functions
from rgb_stacking import task
# Heights above basket surface between which shaping for Lift will be computed.
_LIFT_Z_MAX_ABOVE_BASKET = 0.1
_LIFT_Z_MIN_ABOVE_BASKET = 0.055
# Height for lifting.
_LIFTING_HEIGHT = 0.04
# Cylinder around (bottom object + object height) in which the top object must
# be for it to be considered stacked.
_STACK_HORIZONTAL_TOLERANCE = 0.03
_STACK_VERTICAL_TOLERANCE = 0.01
# Target height above bottom object for hover-above reward.
_HOVER_OFFSET = 0.1
# Distances at which maximum reach reward is given and shaping decays.
_REACH_POSITION_TOLERANCE = np.array((0.02, 0.02, 0.02))
_REACH_SHAPING_TOLERANCE = 0.15
# Distances at which maximum hovering reward is given and shaping decays.
_HOVER_POSITION_TOLERANCE = np.array((0.01, 0.01, 0.01))
_HOVER_SHAPING_TOLERANCE = 0.2
# Observation keys needed to compute the different rewards.
_PINCH_POSE = 'sawyer/pinch/pose'
_FINGER_ANGLE = 'gripper/joints/angle'
_GRIPPER_GRASP = 'gripper/grasp'
_RED_OBJECT_POSE = 'rgb30_red/abs_pose'
_BLUE_OBJECT_POSE = 'rgb30_blue/abs_pose'
# Object closeness threshold for x and y axis.
_X_Y_CLOSE = 0.05
_ONTOP = 0.02
def get_shaped_stacking_reward() -> reward_functions.RewardFunction:
"""Returns a callable reward function for stacking the red block on blue."""
# # First stage: reach and grasp.
reach_red = reward_functions.DistanceReward(
key_a=_PINCH_POSE,
key_b=_RED_OBJECT_POSE,
shaping_tolerance=_REACH_SHAPING_TOLERANCE,
position_tolerance=_REACH_POSITION_TOLERANCE)
close_fingers = reward_functions.DistanceReward(
key_a=_FINGER_ANGLE,
key_b=None,
position_tolerance=None,
shaping_tolerance=255.,
loss_at_tolerance=0.95,
max_reward=1.,
offset=np.array((255,)),
dim=1)
grasp = reward_functions.Max(
terms=(
close_fingers, reward_functions.GraspReward(obs_key=_GRIPPER_GRASP)),
weights=(0.5, 1.))
reach_grasp = reward_functions.ConditionalAnd(reach_red, grasp, 0.9)
# Second stage: grasp and lift.
lift_reward = _get_reward_lift_red()
lift_red = reward_functions.Product([grasp, lift_reward])
# Third stage: hover.
top = _RED_OBJECT_POSE
bottom = _BLUE_OBJECT_POSE
place = reward_functions.DistanceReward(
key_a=top,
key_b=bottom,
offset=np.array((0., 0., _LIFTING_HEIGHT)),
position_tolerance=_HOVER_POSITION_TOLERANCE,
shaping_tolerance=_HOVER_SHAPING_TOLERANCE,
z_min=0.1)
# Fourth stage: stack.
stack = _get_reward_stack_red_on_blue()
# Final stage: stack-and-leave
stack_leave = reward_functions.Product(
terms=(_get_reward_stack_red_on_blue(), _get_reward_above_red()))
return reward_functions.Staged(
[reach_grasp, lift_red, place, stack, stack_leave], 0.01)
def get_sparse_stacking_reward() ->reward_functions.RewardFunction:
"""Sparse stacking reward for red-on-blue with the gripper moved away."""
return reward_functions.Product(
terms=(_get_reward_stack_red_on_blue(), _get_reward_above_red()))
def _get_reward_lift_red() -> reward_functions.RewardFunction:
"""Returns a callable reward function for lifting the red block."""
lift_reward = reward_functions.LiftShaped(
obj_key=_RED_OBJECT_POSE,
z_threshold=task.DEFAULT_BASKET_HEIGHT + _LIFT_Z_MAX_ABOVE_BASKET,
z_min=task.DEFAULT_BASKET_HEIGHT + _LIFT_Z_MIN_ABOVE_BASKET)
# Keep the object inside the area of the base plate.
inside_basket = reward_functions.DistanceReward(
key_a=_RED_OBJECT_POSE,
key_b=None,
position_tolerance=task.WORKSPACE_SIZE / 2.,
shaping_tolerance=1e-12, # Practically none.
loss_at_tolerance=0.95,
max_reward=1.,
offset=task.WORKSPACE_CENTER)
return reward_functions.Product([lift_reward, inside_basket])
def _get_reward_stack_red_on_blue() -> reward_functions.RewardFunction:
"""Returns a callable reward function for stacking the red block on blue."""
return reward_functions.StackPair(
obj_top=_RED_OBJECT_POSE,
obj_bottom=_BLUE_OBJECT_POSE,
obj_top_size=_LIFTING_HEIGHT,
obj_bottom_size=_LIFTING_HEIGHT,
horizontal_tolerance=_STACK_HORIZONTAL_TOLERANCE,
vertical_tolerance=_STACK_VERTICAL_TOLERANCE)
def _get_reward_above_red() -> reward_functions.RewardFunction:
"""Returns a callable reward function for being above the red block."""
return reward_functions.DistanceReward(
key_a=_PINCH_POSE,
key_b=_RED_OBJECT_POSE,
shaping_tolerance=0.05,
offset=np.array((0., 0., _HOVER_OFFSET)),
position_tolerance=np.array((1., 1., 0.03))) # Anywhere horizontally.
class SparseStack(object):
"""Sparse stack reward.
Checks that the two objects being within _X_Y_CLOSE
of each other in the x-y plane (no constraint on z-distance). Also checks
that the object are not in contact with the robot, to ensure the robot is
holding the objects in place.
"""
def __init__(self,
top_object: prop.Prop,
bottom_object: prop.Prop,
get_physics_fn: Callable[[], mjcf.Physics]):
"""Initializes the reward.
Args:
top_object: Composer entity of the top object (red).
bottom_object: Composer entity of the bottom object (blue).
get_physics_fn: Callable that returns the current mjc physics from the
environment.
"""
self._get_physics_fn = get_physics_fn
self._top_object = top_object
self._bottom_object = bottom_object
def _align(self, physics):
return np.linalg.norm(
self._top_object.get_pose(physics)[0][:2] -
self._bottom_object.get_pose(physics)[0][:2]) < _X_Y_CLOSE
def _ontop(self, physics):
return (self._top_object.get_pose(physics)[0][2] -
self._bottom_object.get_pose(physics)[0][2]) > _ONTOP
def _pile(self, physics):
geom = '{}/'.format(self._top_object.name)
if physics_utils.has_ground_collision(physics, collision_geom_prefix=geom):
return float(0.0)
if physics_utils.has_robot_collision(physics, collision_geom_prefix=geom):
return float(0.0)
return float(1.0)
def _collide(self, physics):
collision_geom_prefix_1 = '{}/'.format(self._top_object.name)
collision_geom_prefix_2 = '{}/'.format(self._bottom_object.name)
return physics_utils.has_collision(physics, [collision_geom_prefix_1],
[collision_geom_prefix_2])
def __call__(self, obs: spec_utils.ObservationValue):
del obs
physics = self._get_physics_fn()
if self._align(physics) and self._pile(physics) and self._collide(
physics) and self._ontop(physics):
return 1.0
return 0.0
def get_sparse_reward_fn(
top_object: prop.Prop,
bottom_object: prop.Prop,
get_physics_fn: Callable[[], mjcf.Physics]
) -> reward_functions.RewardFunction:
"""Sparse stacking reward for stacking two props with no robot contact.
Args:
top_object: The bottom object (blue).
bottom_object: The top object (red).
get_physics_fn: Callable that returns the current mjcf physics from the
environment.
Returns:
The sparse stack reward function.
"""
return SparseStack(
top_object=top_object,
bottom_object=bottom_object,
get_physics_fn=get_physics_fn)
|
rgb_stacking-main
|
rgb_stacking/stack_rewards.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Generic reward functions."""
from typing import Callable, Optional, Iterable
from absl import logging
from dm_robotics import agentflow as af
from dm_robotics.agentflow import spec_utils
import numpy as np
# Value returned by the gripper grasp observation when the gripper is in the
# 'grasp' state (fingers closed and exerting force)
_INWARD_GRASP = 2
# Minimal value for the position tolerance of the shaped distance rewards.
MINIMUM_POSITION_TOLERANCE = 1e-9
RewardFunction = Callable[[spec_utils.ObservationValue], float]
class RewardPreprocessor(af.TimestepPreprocessor):
"""Timestep preprocessor wrapper around a reward function."""
def __init__(self, reward_function: RewardFunction):
super().__init__()
self._reward_function = reward_function
def _process_impl(
self, timestep: af.PreprocessorTimestep) -> af.PreprocessorTimestep:
reward = self._reward_function(timestep.observation)
reward = self._out_spec.reward_spec.dtype.type(reward)
return timestep.replace(reward=reward)
def _output_spec(
self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:
return input_spec
class GraspReward:
"""Sparse reward for the gripper grasp status."""
def __init__(self, obs_key: str):
"""Creates new GraspReward function.
Args:
obs_key: Key of the grasp observation in the observation spec.
"""
self._obs_key = obs_key
def __call__(self, obs: spec_utils.ObservationValue):
is_grasped = obs[self._obs_key][0] == _INWARD_GRASP
return float(is_grasped)
class StackPair:
"""Get two objects to be above each other.
To determine the expected position the top object should be at, the size of
the objects must be specified. Currently, only objects with 3-axial symmetry
are supported; for other objects, the distance would impose a constraint on
the possible orientations.
Reward will be given if the top object's center is within a certain distance
of the point above the bottom object, with the distance tolerance being
separately configurable for the horizontal plane and the vertical axis.
By default, reward is also only given when the robot is not currently grasping
anything, though this can be deactivated.
"""
def __init__(self,
obj_top: str,
obj_bottom: str,
obj_top_size: float,
obj_bottom_size: float,
horizontal_tolerance: float,
vertical_tolerance: float,
grasp_key: str = "gripper/grasp"):
"""Initialize the module.
Args:
obj_top: Key in the observation dict containing the top object's
position.
obj_bottom: Key in the observation dict containing the bottom
object's position.
obj_top_size: Height of the top object along the vertical axis, in meters.
obj_bottom_size: Height of the bottom object along the vertical axis, in
meters.
horizontal_tolerance: Max distance from the exact stack position on the
horizontal plane to still generate reward.
vertical_tolerance: Max distance from the exact stack position along the
vertical axis to still generate reward.
grasp_key: Key in the observation dict containing the (buffered) grasp
status. Can be set to `None` to not check the grasp status to return
a reward.
"""
self._top_key = obj_top
self._bottom_key = obj_bottom
self._horizontal_tolerance = horizontal_tolerance
self._vertical_tolerance = vertical_tolerance
self._grasp_key = grasp_key
if obj_top_size <= 0. or obj_bottom_size <= 0.:
raise ValueError("Object sizes cannot be zero.")
self._expected_dist = (obj_top_size + obj_bottom_size) / 2.
def __call__(self, obs: spec_utils.ObservationValue):
top = obs[self._top_key]
bottom = obs[self._bottom_key]
horizontal_dist = np.linalg.norm(top[:2] - bottom[:2])
if horizontal_dist > self._horizontal_tolerance:
return 0.
vertical_dist = top[2] - bottom[2]
if np.abs(vertical_dist - self._expected_dist) > self._vertical_tolerance:
return 0.
if self._grasp_key is not None:
grasp = obs[self._grasp_key]
if grasp == _INWARD_GRASP:
return 0.
return 1.
def tanh_squared(x: np.ndarray, margin: float, loss_at_margin: float = 0.95):
"""Returns a sigmoidal shaping loss based on Hafner & Reidmiller (2011).
Args:
x: A numpy array representing the error.
margin: Margin parameter, a positive `float`.
loss_at_margin: The loss when `l2_norm(x) == margin`. A `float` between 0
and 1.
Returns:
Shaping loss, a `float` bounded in the half-open interval [0, 1).
Raises:
ValueError: If the value of `margin` or `loss_at_margin` is invalid.
"""
if not margin > 0:
raise ValueError("`margin` must be positive.")
if not 0.0 < loss_at_margin < 1.0:
raise ValueError("`loss_at_margin` must be between 0 and 1.")
error = np.linalg.norm(x)
# Compute weight such that at the margin tanh(w * error) = loss_at_margin
w = np.arctanh(np.sqrt(loss_at_margin)) / margin
s = np.tanh(w * error)
return s * s
class DistanceReward:
"""Shaped reward based on the distance B-A between two entities A and B."""
def __init__(
self,
key_a: str,
key_b: Optional[str],
position_tolerance: Optional[np.ndarray] = None,
shaping_tolerance: float = 0.1,
loss_at_tolerance: float = 0.95,
max_reward: float = 1.,
offset: Optional[np.ndarray] = None,
z_min: Optional[float] = None,
dim=3
):
"""Initialize the module.
Args:
key_a: Observation dict key to numpy array containing the position of
object A.
key_b: None or observation dict key to numpy array containing the position
of object B. If None, distance simplifies to d = offset - A.
position_tolerance: Vector of length `dim`. If
`distance/position_tolerance < 1`, will return `maximum_reward`
instead of shaped one. Setting this to `None`, or setting any entry
to zero or close to zero, will effectively disable tolerance.
shaping_tolerance: Scalar distance at which the loss is equal to
`loss_at_tolerance`. Must be a positive float or `None`. If `None`
reward is sparse and hence 0 is returned if
`distance > position_tolerance`.
loss_at_tolerance: The loss when `l2_norm(distance) == shaping_tolerance`.
A `float` between 0 and 1.
max_reward: Reward to return when `distance/position_tolerance < 1`.
offset: Vector of length 3 that is added to the distance, i.e.
`distance = B - A + offset`.
z_min: Absolute object height that the object A center has to above be in
order to generate reward. Used for example in hovering rewards.
dim: The dimensionality of the space in which the distance is computed
"""
self._key_a = key_a
self._key_b = key_b
self._shaping_tolerance = shaping_tolerance
self._loss_at_tolerance = loss_at_tolerance
if max_reward < 1.:
logging.warning("Maximum reward should not be below tanh maximum.")
self._max_reward = max_reward
self._z_min = z_min
self._dim = dim
if position_tolerance is None:
self._position_tolerance = np.full(
(dim,), fill_value=MINIMUM_POSITION_TOLERANCE)
else:
self._position_tolerance = position_tolerance
self._position_tolerance[self._position_tolerance == 0] = (
MINIMUM_POSITION_TOLERANCE)
if offset is None:
self._offset = np.zeros((dim,))
else:
self._offset = offset
def __call__(self, obs: spec_utils.ObservationValue) -> float:
# Check that object A is high enough before computing the reward.
if self._z_min is not None and obs[self._key_a][2] < self._z_min:
return 0.
self._current_distance = (self._offset - obs[self._key_a][0:self._dim])
if self._key_b is not None:
self._current_distance += obs[self._key_b][0:self._dim]
weighted = self._current_distance / self._position_tolerance
if np.linalg.norm(weighted) <= 1.:
return self._max_reward
if not self._shaping_tolerance:
return 0.
loss = tanh_squared(
self._current_distance, margin=self._shaping_tolerance,
loss_at_margin=self._loss_at_tolerance)
return 1.0 - loss
class LiftShaped:
"""Linear shaped reward for lifting, up to a specified height.
Once the height is above a specified threshold, reward saturates. Shaping can
also be deactivated for a sparse reward.
Requires an observation `<obs_prefix>/<obj_name>/abs_pose` containing the
pose of the object in question.
"""
def __init__(
self,
obj_key,
z_threshold,
z_min,
max_reward=1.,
shaping=True
):
"""Initialize the module.
Args:
obj_key: Key in the observation dict containing the object pose.
z_threshold: Absolute object height at which the maximum reward will be
given.
z_min: Absolute object height that the object center has to above be in
order to generate shaped reward. Ignored if `shaping` is False.
max_reward: Reward given when the object is above the `z_threshold`.
shaping: If true, will give a linear shaped reward when the object height
is above `z_min`, but below `z_threshold`.
Raises:
ValueError: if `z_min` is larger than `z_threshold`.
"""
self._field = obj_key
self._z_threshold = z_threshold
self._shaping = shaping
self._max_reward = max_reward
self._z_min = z_min
if z_min > z_threshold:
raise ValueError("Lower shaping bound cannot be below upper bound.")
def __call__(self, obs: spec_utils.ObservationValue) -> float:
obj_z = obs[self._field][2]
if obj_z <= self._z_min:
return 0.0
if obj_z >= self._z_threshold:
return self._max_reward
if self._shaping:
r = (obj_z - self._z_min) / (self._z_threshold - self._z_min)
return r
return 0.0
class Product:
"""Computes the product of a set of rewards."""
def __init__(self, terms: Iterable[RewardFunction]):
self._terms = terms
def __call__(self, obs: spec_utils.ObservationValue) -> float:
r = 1.
for term in self._terms:
r *= term(obs)
return r
class _WeightedTermReward:
"""Base class for rewards using lists of weighted terms."""
def __init__(self,
terms: Iterable[RewardFunction],
weights: Optional[Iterable[float]] = None):
"""Initialize the reward instance.
Args:
terms: List of reward callables to be operated on. Each callable must
take an observation as input, and return a float.
weights: Weight that each reward returned by the callables in `terms` will
be multiplied by. If `None`, will weight all terms with 1.0.
Raises:
ValueError: If `weights` has been specified, but its length differs from
that of `terms`.
"""
self._terms = list(terms)
self._weights = weights or [1.] * len(self._terms)
if len(self._weights) != len(self._terms):
raise ValueError("Number of terms and weights should be same.")
def _weighted_terms(
self, obs: spec_utils.ObservationValue) -> Iterable[float]:
return [t(obs) * w for t, w in zip(self._terms, self._weights)]
class Max(_WeightedTermReward):
"""Selects the maximum among a number of weighted rewards."""
def __call__(self, obs: spec_utils.ObservationValue) -> float:
return max(self._weighted_terms(obs))
class ConditionalAnd:
"""Perform an and operation conditional on term1 exceeding a threshold."""
def __init__(self,
term1: RewardFunction,
term2: RewardFunction,
threshold: float):
self._term1 = term1
self._term2 = term2
self._thresh = threshold
def __call__(self, obs: spec_utils.ObservationValue) -> float:
r1 = self._term1(obs)
r2 = self._term2(obs)
if r1 > self._thresh:
return (0.5 + r2 / 2.) * r1
else:
return r1 * 0.5
class Staged:
"""Stages the rewards.
This works by cycling through the terms backwards and using the last reward
that gives a response above the provided threshold + the number of
terms preceding it.
Rewards must be in [0;1], otherwise they will be clipped.
"""
def __init__(
self, terms: Iterable[RewardFunction], threshold: float):
def make_clipped(term: RewardFunction):
return lambda obs: np.clip(term(obs), 0., 1.)
self._terms = [make_clipped(term) for term in terms]
self._thresh = threshold
def __call__(self, obs: spec_utils.ObservationValue) -> float:
last_reward = 0.
num_stages = float(len(self._terms))
for i, term in enumerate(reversed(self._terms)):
last_reward = term(obs)
if last_reward > self._thresh:
# Found a reward above the threshold, add number of preceding terms
# and normalize with the number of terms.
return (len(self._terms) - (i + 1) + last_reward) / num_stages
# Return the accumulated rewards.
return last_reward / num_stages
|
rgb_stacking-main
|
rgb_stacking/reward_functions.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.
# ==============================================================================
"""Builds RGB stacking environment.
This file builds the RGB stacking environment used in the paper
"Beyond Pick-and-Place: Tackling robotic stacking of diverse shapes".
The environment is composed of a robot with a parallel gripper. In front
of the robot there is a basket containing 3 objects, one red, one green and one
blue. The goal is for the robot to stack the red object on top of the blue one.
In this specific file, we build the interface that is exposed to the agent,
namely the action spec, the observation spec along with the reward.
"""
import enum
from typing import Sequence
from dm_robotics import agentflow as af
from dm_robotics.agentflow.preprocessors import observation_transforms
from dm_robotics.agentflow.preprocessors import timestep_preprocessor as tsp
from dm_robotics.agentflow.subtasks import subtask_termination
from dm_robotics.manipulation.props.rgb_objects import rgb_object
from dm_robotics.moma import action_spaces
from dm_robotics.moma import subtask_env
from dm_robotics.moma import subtask_env_builder
from dm_robotics.moma.utils import mujoco_collisions
import numpy as np
from rgb_stacking import reward_functions
from rgb_stacking import stack_rewards
from rgb_stacking import task
# The environments provides stacked observations to the agent. The data of the
# previous n steps is stacked and provided as a single observation to the agent.
# We stack different observations a different number of times.
_OBSERVATION_STACK_DEPTH = 3
_ACTION_OBS_STACK_DEPTH = 2
# Number of steps in an episode
_MAX_STEPS = 400
# Timestep of the physics simulation.
_PHYSICS_TIMESTEP = 0.0005
_STATE_OBSERVATIONS = (
'action/environment',
'gripper/grasp',
'gripper/joints/angle',
'gripper/joints/velocity',
'rgb30_blue/abs_pose',
'rgb30_blue/to_pinch',
'rgb30_green/abs_pose',
'rgb30_green/to_pinch',
'rgb30_red/abs_pose',
'rgb30_red/to_pinch',
'sawyer/joints/angle',
'sawyer/joints/torque',
'sawyer/joints/velocity',
'sawyer/pinch/pose',
'sawyer/tcp/pose',
'sawyer/tcp/velocity',
'wrist/force',
'wrist/torque'
)
_VISION_OBSERVATIONS = (
'basket_back_left/pixels',
'basket_front_left/pixels',
'basket_front_right/pixels'
)
# For interactive imitation learning, the vision-based policy used the
# following proprioception and images observations from the pair of front
# cameras given by the simulated environment.
_INTERACTIVE_IMITATION_LEARNING_OBSERVATIONS = (
'sawyer/joints/angle',
'gripper/joints/angle',
'sawyer/pinch/pose',
'sawyer/tcp/pose',
'basket_front_left/pixels',
'basket_front_right/pixels'
)
# For the one-step offline policy improvement from real data, the vision-based
# policy used the following proprioception and images observations from the pair
# of front cameras given by the real environment.
_OFFLINE_POLICY_IMPROVEMENT_OBSERVATIONS = [
'sawyer/joints/angle',
'sawyer/joints/velocity',
'gripper/grasp',
'gripper/joints/angle',
'gripper/joints/velocity',
'sawyer/pinch/pose',
'basket_front_left/pixels',
'basket_front_right/pixels',]
class ObservationSet(int, enum.Enum):
"""Different possible set of observations that can be exposed."""
_observations: Sequence[str]
def __new__(cls, value: int, observations: Sequence[str]):
obj = int.__new__(cls, value)
obj._value_ = value
obj._observations = observations
return obj
@property
def observations(self):
return self._observations
STATE_ONLY = (0, _STATE_OBSERVATIONS)
VISION_ONLY = (1, _VISION_OBSERVATIONS)
ALL = (2, _STATE_OBSERVATIONS + _VISION_OBSERVATIONS)
INTERACTIVE_IMITATION_LEARNING = (
3, _INTERACTIVE_IMITATION_LEARNING_OBSERVATIONS)
OFFLINE_POLICY_IMPROVEMENT = (4, _OFFLINE_POLICY_IMPROVEMENT_OBSERVATIONS)
def rgb_stacking(
object_triplet: str = 'rgb_test_random',
observation_set: ObservationSet = ObservationSet.STATE_ONLY,
use_sparse_reward: bool = False
) -> subtask_env.SubTaskEnvironment:
"""Returns the environment.
The relevant groups can be found here:
https://github.com/deepmind/robotics/blob/main/py/manipulation/props/rgb_objects/rgb_object.py
The valid object triplets can be found under PROP_TRIPLETS in the file.
Args:
object_triplet: Triplet of RGB objects to use in the environment.
observation_set: Set of observations that en environment should expose.
use_sparse_reward: If true will use sparse reward, which is 1 if the objects
stacked and not touching the robot, and 0 otherwise.
"""
red_id, green_id, blue_id = rgb_object.PROP_TRIPLETS[object_triplet][1]
rgb_task = task.rgb_task(red_id, green_id, blue_id)
rgb_task.physics_timestep = _PHYSICS_TIMESTEP
# To speed up simulation we ensure that mujoco will no check contact between
# geoms that cannot collide.
mujoco_collisions.exclude_bodies_based_on_contype_conaffinity(
rgb_task.root_entity.mjcf_model)
# Build the agent flow subtask. This is where the task logic is defined,
# observations, and rewards.
env_builder = subtask_env_builder.SubtaskEnvBuilder()
env_builder.set_task(rgb_task)
task_env = env_builder.build_base_env()
# Define the action space, this is used to expose the actuators used in the
# base task.
effectors_action_spec = rgb_task.effectors_action_spec(
physics=task_env.physics)
robot_action_spaces = []
for rbt in rgb_task.robots:
arm_action_space = action_spaces.ArmJointActionSpace(
af.prefix_slicer(effectors_action_spec, rbt.arm_effector.prefix))
gripper_action_space = action_spaces.GripperActionSpace(
af.prefix_slicer(effectors_action_spec, rbt.gripper_effector.prefix))
robot_action_spaces.extend([arm_action_space, gripper_action_space])
composite_action_space = af.CompositeActionSpace(
robot_action_spaces)
env_builder.set_action_space(composite_action_space)
# Cast all the floating point observations to float32.
env_builder.add_preprocessor(
observation_transforms.DowncastFloatPreprocessor(np.float32))
# Concatenate the TCP and wrist site observations.
env_builder.add_preprocessor(observation_transforms.MergeObservations(
obs_to_merge=['robot0_tcp_pos', 'robot0_tcp_quat'],
new_obs='robot0_tcp_pose'))
env_builder.add_preprocessor(observation_transforms.MergeObservations(
obs_to_merge=['robot0_wrist_site_pos', 'robot0_wrist_site_quat'],
new_obs='robot0_wrist_site_pose'))
# Add in observations to measure the distance from the TCP to the objects.
for color in ('red', 'green', 'blue'):
env_builder.add_preprocessor(observation_transforms.AddObservation(
obs_name=f'{color}_to_pinch',
obs_callable=_distance_delta_obs(
f'rgb_object_{color}_pose', 'robot0_tcp_pose')))
# Concatenate the action sent to the robot joints and the gripper actuator.
env_builder.add_preprocessor(observation_transforms.MergeObservations(
obs_to_merge=['robot0_arm_joint_previous_action',
'robot0_gripper_previous_action'],
new_obs='robot0_previous_action'))
# Mapping of observation names to match the observation names in the stored
# data.
obs_mapping = {
'robot0_arm_joint_pos': 'sawyer/joints/angle',
'robot0_arm_joint_vel': 'sawyer/joints/velocity',
'robot0_arm_joint_torques': 'sawyer/joints/torque',
'robot0_tcp_pose': 'sawyer/pinch/pose',
'robot0_wrist_site_pose': 'sawyer/tcp/pose',
'robot0_wrist_site_vel_world': 'sawyer/tcp/velocity',
'robot0_gripper_pos': 'gripper/joints/angle',
'robot0_gripper_vel': 'gripper/joints/velocity',
'robot0_gripper_grasp': 'gripper/grasp',
'robot0_wrist_force': 'wrist/force',
'robot0_wrist_torque': 'wrist/torque',
'rgb_object_red_pose': 'rgb30_red/abs_pose',
'rgb_object_green_pose': 'rgb30_green/abs_pose',
'rgb_object_blue_pose': 'rgb30_blue/abs_pose',
'basket_back_left_rgb_img': 'basket_back_left/pixels',
'basket_front_left_rgb_img': 'basket_front_left/pixels',
'basket_front_right_rgb_img': 'basket_front_right/pixels',
'red_to_pinch': 'rgb30_red/to_pinch',
'blue_to_pinch': 'rgb30_blue/to_pinch',
'green_to_pinch': 'rgb30_green/to_pinch',
'robot0_previous_action': 'action/environment',
}
# Create different subsets of observations.
action_obs = {'action/environment'}
# These observations only have a single floating point value instead of an
# array.
single_value_obs = {'gripper/joints/angle',
'gripper/joints/velocity',
'gripper/grasp'}
# Rename observations.
env_builder.add_preprocessor(observation_transforms.RenameObservations(
obs_mapping, raise_on_missing=False))
if use_sparse_reward:
reward_fn = stack_rewards.get_sparse_reward_fn(
top_object=rgb_task.props[0],
bottom_object=rgb_task.props[2],
get_physics_fn=lambda: task_env.physics)
else:
reward_fn = stack_rewards.get_shaped_stacking_reward()
env_builder.add_preprocessor(reward_functions.RewardPreprocessor(reward_fn))
# We concatenate several observations from consecutive timesteps. Depending
# on the observations, we will concatenate a different number of observations.
# - Most observations are stacked 3 times
# - Camera observations are not stacked.
# - The action observation is stacked twice.
# - When stacking three scalar (i.e. numpy array of shape (1,)) observations,
# we do not add a leading dimension, so the final shape is (3,).
env_builder.add_preprocessor(
observation_transforms.StackObservations(
obs_to_stack=list(
set(_STATE_OBSERVATIONS) - action_obs - single_value_obs),
stack_depth=_OBSERVATION_STACK_DEPTH,
add_leading_dim=True))
env_builder.add_preprocessor(
observation_transforms.StackObservations(
obs_to_stack=list(single_value_obs),
stack_depth=_OBSERVATION_STACK_DEPTH,
add_leading_dim=False))
env_builder.add_preprocessor(
observation_transforms.StackObservations(
obs_to_stack=list(action_obs),
stack_depth=_ACTION_OBS_STACK_DEPTH,
add_leading_dim=True))
# Only keep the obseravtions that we want to expose to the agent.
env_builder.add_preprocessor(observation_transforms.RetainObservations(
observation_set.observations, raise_on_missing=False))
# End episodes after 400 steps.
env_builder.add_preprocessor(
subtask_termination.MaxStepsTermination(_MAX_STEPS))
return env_builder.build()
def _distance_delta_obs(key1: str, key2: str):
"""Returns a callable that returns the difference between two observations."""
def util(timestep: tsp.PreprocessorTimestep) -> np.ndarray:
return timestep.observation[key1] - timestep.observation[key2]
return util
|
rgb_stacking-main
|
rgb_stacking/environment.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests environment.py."""
from absl.testing import absltest
from dm_env import test_utils
from rgb_stacking import environment
class EnvironmentTest(test_utils.EnvironmentTestMixin, absltest.TestCase):
def make_object_under_test(self):
return environment.rgb_stacking(
object_triplet='rgb_test_triplet1',
observation_set=environment.ObservationSet.ALL)
if __name__ == '__main__':
absltest.main()
|
rgb_stacking-main
|
rgb_stacking/environment_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.
# ==============================================================================
"""Script to run a viewer to visualize the rgb stacking environment."""
from typing import Sequence
from absl import app
from absl import flags
from absl import logging
import cv2
from dm_control import viewer
from dm_robotics.manipulation.props.rgb_objects import rgb_object
from dm_robotics.moma import subtask_env
import numpy as np
from rgb_stacking import environment
from rgb_stacking.utils import policy_loading
_TEST_OBJECT_TRIPLETS = tuple(rgb_object.PROP_TRIPLETS_TEST.keys())
_ALL_OBJECT_TRIPLETS = _TEST_OBJECT_TRIPLETS + (
'rgb_train_random',
'rgb_test_random',
)
_POLICY_DIR = ('assets/saved_models')
_POLICY_PATHS = {
k: f'{_POLICY_DIR}/mpo_state_{k}' for k in _TEST_OBJECT_TRIPLETS
}
_OBJECT_TRIPLET = flags.DEFINE_enum(
'object_triplet', 'rgb_test_random', _ALL_OBJECT_TRIPLETS,
'Triplet of RGB objects to use in the environment.')
_POLICY_OBJECT_TRIPLET = flags.DEFINE_enum(
'policy_object_triplet', None, _TEST_OBJECT_TRIPLETS,
'Optional test triplet name indicating to load a policy that was trained on'
' this triplet.')
_LAUNCH_VIEWER = flags.DEFINE_bool(
'launch_viewer', True,
'Optional boolean. If True, will launch the dm_control viewer. If False'
' will load the policy, run it and save a recording of it as an .mp4.')
def run_episode_and_render(
env: subtask_env.SubTaskEnvironment,
policy: policy_loading.Policy
) -> Sequence[np.ndarray]:
"""Saves a gif of the policy running against the environment."""
rendered_images = []
logging.info('Starting the rendering of the policy, this might take some'
' time...')
state = policy.initial_state()
timestep = env.reset()
rendered_images.append(env.physics.render(camera_id='main_camera'))
while not timestep.last():
(action, _), state = policy.step(timestep, state)
timestep = env.step(action)
rendered_images.append(env.physics.render(camera_id='main_camera'))
logging.info('Done rendering!')
return rendered_images
def main(argv: Sequence[str]) -> None:
del argv
if not _LAUNCH_VIEWER.value and _POLICY_OBJECT_TRIPLET.value is None:
raise ValueError('To record a video, a policy must be given.')
# Load the rgb stacking environment.
with environment.rgb_stacking(object_triplet=_OBJECT_TRIPLET.value) as env:
# Optionally load a policy trained on one of these environments.
if _POLICY_OBJECT_TRIPLET.value is not None:
policy_path = _POLICY_PATHS[_POLICY_OBJECT_TRIPLET.value]
policy = policy_loading.policy_from_path(policy_path)
else:
policy = None
if _LAUNCH_VIEWER.value:
# The viewer requires a callable as a policy.
if policy is not None:
policy = policy_loading.StatefulPolicyCallable(policy)
viewer.launch(env, policy=policy)
else:
# Render the episode.
rendered_episode = run_episode_and_render(env, policy)
# Save as mp4 video in current directory.
height, width, _ = rendered_episode[0].shape
out = cv2.VideoWriter(
'./rendered_policy.mp4',
cv2.VideoWriter_fourcc('m', 'p', '4', 'v'),
1.0 / env.task.control_timestep, (width, height))
for image in rendered_episode:
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
out.write(image)
out.release()
if __name__ == '__main__':
app.run(main)
|
rgb_stacking-main
|
rgb_stacking/main.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""This file contains various helper functions for finding mujoco collisions.
"""
import itertools
DEFAULT_OBJECT_COLLISION_MARGIN = 0.0002
DEFAULT_COLLISION_MARGIN = 1e-8
OBJECT_GEOM_PREFIXES = ['rgb']
GROUND_GEOM_PREFIXES = ['work_surface', 'ground']
ROBOT_GEOM_PREFIXES = ['robot']
def has_object_collision(physics, collision_geom_prefix,
margin=DEFAULT_OBJECT_COLLISION_MARGIN):
"""Check for collisions between geoms and objects."""
return has_collision(
physics=physics,
collision_geom_prefix_1=[collision_geom_prefix],
collision_geom_prefix_2=OBJECT_GEOM_PREFIXES,
margin=margin)
def has_ground_collision(physics, collision_geom_prefix,
margin=DEFAULT_COLLISION_MARGIN):
"""Check for collisions between geoms and the ground."""
return has_collision(
physics=physics,
collision_geom_prefix_1=[collision_geom_prefix],
collision_geom_prefix_2=GROUND_GEOM_PREFIXES,
margin=margin)
def has_robot_collision(physics, collision_geom_prefix,
margin=DEFAULT_COLLISION_MARGIN):
"""Check for collisions between geoms and the robot."""
return has_collision(
physics=physics,
collision_geom_prefix_1=[collision_geom_prefix],
collision_geom_prefix_2=ROBOT_GEOM_PREFIXES,
margin=margin)
def has_collision(physics, collision_geom_prefix_1, collision_geom_prefix_2,
margin=DEFAULT_COLLISION_MARGIN):
"""Check for collisions between geoms."""
for contact in physics.data.contact:
if contact.dist > margin:
continue
geom1_name = physics.model.id2name(contact.geom1, 'geom')
geom2_name = physics.model.id2name(contact.geom2, 'geom')
for pair in itertools.product(
collision_geom_prefix_1, collision_geom_prefix_2):
if ((geom1_name.startswith(pair[0]) and
geom2_name.startswith(pair[1])) or
(geom2_name.startswith(pair[0]) and
geom1_name.startswith(pair[1]))):
return True
return False
|
rgb_stacking-main
|
rgb_stacking/physics_utils.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A permissive wrapper for a SavedModel."""
import copy
import inspect
from typing import Any, Callable, NamedTuple
from absl import logging
import tensorflow as tf
import tree
class _Function(NamedTuple):
"""Function exposing signature and expected canonical arguments."""
func: Callable[..., Any]
signature: inspect.Signature
structured_specs: Any
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
@property
def canonical_arguments(self) -> inspect.BoundArguments:
args, kwargs = copy.deepcopy(self.structured_specs)
return self.signature.bind(*args, **kwargs)
class PermissiveModel:
"""A permissive wrapper for a SavedModel."""
# Disable pytype attribute error checks.
_HAS_DYNAMIC_ATTRIBUTES = True
def __init__(self, model):
self.model = model
self._tables = self.model.function_tables()
self._initialized_tables = {}
def build_parameters(params):
params = [
inspect.Parameter(str(param[0], "utf-8"), param[1])
for param in params
]
# Always include a VAR_KEYWORD to capture any extraneous arguments.
if all([p.kind != inspect.Parameter.VAR_KEYWORD for p in params]):
params.append(
inspect.Parameter("__unused_kwargs", inspect.Parameter.VAR_KEYWORD))
return params
signatures = self.model.function_signatures()
if tf.executing_eagerly():
signatures = tree.map_structure(lambda x: x.numpy(), signatures)
else:
with tf.compat.v1.Session() as sess:
signatures = sess.run(signatures)
signatures = {
func_name: inspect.Signature(build_parameters(func_params))
for func_name, func_params in signatures.items()
}
self.signatures = signatures
# Attach deepfuncs.
for name in self.signatures.keys():
setattr(self, name, self._make_permissive_function(name))
def _maybe_init_tables(self, concrete_func: Any, name: str):
"""Initialise all tables for a function if they are not initialised.
Some functions rely on hash-tables that must be externally initialized. This
method will perform a one-time initialisation of the tables. It does so by
finding the corresponding op that creates the hash-table handles (these will
be different from the ones observed in the initial deepfuncs), and import
the corresponding keys and values.
Args:
concrete_func: A tf.ConcreteFunction corresponding to a deepfunc.
name: The name of the deepfunc.
"""
if name not in self._tables:
return
all_nodes = dict(
main={n.name: n for n in concrete_func.graph.as_graph_def().node})
for func_def in concrete_func.graph.as_graph_def().library.function:
all_nodes[func_def.signature.name] = {
n.name: n for n in func_def.node_def
}
for table_name, (table_keys, table_values) in self._tables[name].items():
table_op = None
for nodes in all_nodes.values():
if table_name in nodes:
if table_op is not None:
raise ValueError(f"Duplicate table op found for {table_name}")
table_op = nodes[table_name]
logging.info("Initialising table for Op `%s`", table_name)
table_handle_name = table_op.attr["shared_name"].s # pytype: disable=attribute-error
table_handle = tf.raw_ops.HashTableV2(
key_dtype=table_keys.dtype,
value_dtype=table_values.dtype,
shared_name=table_handle_name)
tf.raw_ops.LookupTableImportV2(
table_handle=table_handle, keys=table_keys, values=table_values)
self._initialized_tables[name] = self._tables.pop(name) # Only init once.
def _make_permissive_function(self, name: str) -> Callable[..., Any]:
"""Create a permissive version of a function in the SavedModel."""
if name not in self.signatures:
raise ValueError(f"No function named {name} in SavedModel, "
"options are {self.signatures}")
tf_func = getattr(self.model, name)
if hasattr(tf_func, "concrete_functions"):
# tf.RestoredFunction
concrete_func, = tf_func.concrete_functions # Expect only one.
elif hasattr(tf_func, "_list_all_concrete_functions"):
# tf.Function
all_concrete_funcs = tf_func._list_all_concrete_functions() # pylint: disable=protected-access
all_concrete_signatures = [
f.structured_input_signature for f in all_concrete_funcs
]
# This is necessary as tf.saved_model.save can force a retrace on
# tf.Function, resulting in another concrete function with identical
# signature.
unique_concrete_signatures = set([
tuple(tree.flatten_with_path(sig)) for sig in all_concrete_signatures
])
if len(unique_concrete_signatures) != 1:
raise ValueError(
"Expected exactly one unique concrete_function signature, found "
f"the following: {all_concrete_signatures}")
concrete_func = all_concrete_funcs[0]
else:
raise ValueError(f"No concrete functions found on {tf_func}")
self._maybe_init_tables(concrete_func, name)
def func(*args, **kwargs):
bound_args = self.signatures[name].bind(*args, **kwargs)
canonical_args = concrete_func.structured_input_signature
flat_bound_args = tree.flatten_with_path(
(bound_args.args, bound_args.kwargs))
flat_canonical_args = tree.flatten_with_path(canonical_args)
# Specs for error reporting.
bound_specs = tree.map_structure(
lambda x: None if x is None else object(),
(bound_args.args, bound_args.kwargs))
canonical_specs = tree.map_structure(
lambda x: None if x is None else object(), canonical_args)
# Check for missing arguments.
flat_bound_args_dict = dict(flat_bound_args)
for arg_path, arg_spec in flat_canonical_args:
if arg_path not in flat_bound_args_dict and arg_spec is not None:
raise ValueError(
f"Missing argument with path {arg_path}, expected canonical args "
f"with structure {canonical_specs}, received {bound_specs}. (All "
"required values have been replaced by object() for brevity.")
if arg_path in flat_bound_args_dict and arg_spec is None:
arg_value = flat_bound_args_dict[arg_path]
if arg_value is not None:
logging.warning(
"Received unexpected argument `%s` for path %s, replaced with "
"None.", arg_value, arg_path)
flat_bound_args_dict[arg_path] = None
# Filter out extraneous arguments and dictionary keys.
flat_canonical_args_dict = dict(flat_canonical_args)
filtered_flat_bound_args = {
arg_path: arg_value
for arg_path, arg_value in flat_bound_args_dict.items()
if arg_path in flat_canonical_args_dict
}
full_flat_bound_args = [
filtered_flat_bound_args.get(arg_path, None)
for arg_path, _ in flat_canonical_args
]
filtered_args, filtered_kwargs = tree.unflatten_as(
canonical_args, full_flat_bound_args)
return tf_func(*filtered_args, **filtered_kwargs)
return _Function(
func,
copy.deepcopy(self.signatures[name]),
copy.deepcopy(concrete_func.structured_input_signature),
)
|
rgb_stacking-main
|
rgb_stacking/utils/permissive_model.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utility for loading RGB stacking policies saved as TF SavedModel."""
from typing import NamedTuple
import dm_env
import numpy as np
# This reverb dependency is needed since otherwise loading a SavedModel throws
# an error when the ReverbDataset op is not found.
import reverb # pylint: disable=unused-import
import tensorflow as tf
import tree
import typing_extensions
from rgb_stacking.utils import permissive_model
class _MPOState(NamedTuple):
counter: tf.Tensor
actor: tree.Structure[tf.Tensor]
critic: tree.Structure[tf.Tensor]
@typing_extensions.runtime
class Policy(typing_extensions.Protocol):
def step(self, timestep: dm_env.TimeStep, state: _MPOState):
pass
def initial_state(self) -> _MPOState:
pass
def policy_from_path(saved_model_path: str) -> Policy:
"""Loads policy from stored TF SavedModel."""
policy = tf.saved_model.load(saved_model_path)
# Relax strict requirement with respect to its expected inputs, e.g. in
# regards to unused arguments.
policy = permissive_model.PermissiveModel(policy)
# The loaded policy's step function expects batched data. Wrap it so that it
# expects unbatched data.
policy_step_batch_fn = policy.step
def _expand_batch_dim(x):
return np.expand_dims(x, axis=0)
def _squeeze_batch_dim(x):
return np.squeeze(x, axis=0)
def policy_step_fn(timestep: dm_env.TimeStep, state: _MPOState):
timestep_batch = dm_env.TimeStep(
None, None, None,
tree.map_structure(_expand_batch_dim, timestep.observation))
state_batch = tree.map_structure(_expand_batch_dim, state)
output_batch = policy_step_batch_fn(timestep_batch, state_batch)
output = tree.map_structure(_squeeze_batch_dim, output_batch)
return output
policy.step = policy_step_fn
return policy
class StatefulPolicyCallable:
"""Object-oriented policy for directly using in dm_control viewer."""
def __init__(self, policy: Policy):
self._policy = policy
self._state = self._policy.initial_state()
def __call__(self, timestep: dm_env.TimeStep):
if timestep.step_type == dm_env.StepType.FIRST:
self._state = self._policy.initial_state()
(action, _), self._state = self._policy.step(timestep, self._state)
return action
|
rgb_stacking-main
|
rgb_stacking/utils/policy_loading.py
|
# Copyright 2016 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Basic random agent for DeepMind Lab."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import random
import numpy as np
import six
import deepmind_lab
def _action(*entries):
return np.array(entries, dtype=np.intc)
class DiscretizedRandomAgent(object):
"""Simple agent for DeepMind Lab."""
ACTIONS = {
'look_left': _action(-20, 0, 0, 0, 0, 0, 0),
'look_right': _action(20, 0, 0, 0, 0, 0, 0),
'look_up': _action(0, 10, 0, 0, 0, 0, 0),
'look_down': _action(0, -10, 0, 0, 0, 0, 0),
'strafe_left': _action(0, 0, -1, 0, 0, 0, 0),
'strafe_right': _action(0, 0, 1, 0, 0, 0, 0),
'forward': _action(0, 0, 0, 1, 0, 0, 0),
'backward': _action(0, 0, 0, -1, 0, 0, 0),
'fire': _action(0, 0, 0, 0, 1, 0, 0),
'jump': _action(0, 0, 0, 0, 0, 1, 0),
'crouch': _action(0, 0, 0, 0, 0, 0, 1)
}
ACTION_LIST = list(six.viewvalues(ACTIONS))
def step(self, unused_reward, unused_image):
"""Gets an image state and a reward, returns an action."""
return random.choice(DiscretizedRandomAgent.ACTION_LIST)
class SpringAgent(object):
"""A random agent using spring-like forces for its action evolution."""
def __init__(self, action_spec):
self.action_spec = action_spec
print('Starting random spring agent. Action spec:', action_spec)
self.omega = np.array([
0.1, # look left-right
0.1, # look up-down
0.1, # strafe left-right
0.1, # forward-backward
0.0, # fire
0.0, # jumping
0.0 # crouching
])
self.velocity_scaling = np.array([2.5, 2.5, 0.01, 0.01, 1, 1, 1])
self.indices = {a['name']: i for i, a in enumerate(self.action_spec)}
self.mins = np.array([a['min'] for a in self.action_spec])
self.maxs = np.array([a['max'] for a in self.action_spec])
self.reset()
self.rewards = 0
def critically_damped_derivative(self, t, omega, displacement, velocity):
r"""Critical damping for movement.
I.e., x(t) = (A + Bt) \exp(-\omega t) with A = x(0), B = x'(0) + \omega x(0)
See
https://en.wikipedia.org/wiki/Damping#Critical_damping_.28.CE.B6_.3D_1.29
for details.
Args:
t: A float representing time.
omega: The undamped natural frequency.
displacement: The initial displacement at, x(0) in the above equation.
velocity: The initial velocity, x'(0) in the above equation
Returns:
The velocity x'(t).
"""
a = displacement
b = velocity + omega * displacement
return (b - omega * t * (a + t * b)) * np.exp(-omega * t)
def step(self, reward, unused_frame):
"""Gets an image state and a reward, returns an action."""
self.rewards += reward
action = (self.maxs - self.mins) * np.random.random_sample(
size=[len(self.action_spec)]) + self.mins
# Compute the 'velocity' 1 time unit after a critical damped force
# dragged us towards the random `action`, given our current velocity.
self.velocity = self.critically_damped_derivative(1, self.omega, action,
self.velocity)
# Since walk and strafe are binary, we need some additional memory to
# smoothen the movement. Adding half of action from the last step works.
self.action = self.velocity / self.velocity_scaling + 0.5 * self.action
# Fire with p = 0.01 at each step
self.action[self.indices['FIRE']] = int(np.random.random() > 0.99)
# Jump/crouch with p = 0.005 at each step
self.action[self.indices['JUMP']] = int(np.random.random() > 0.995)
self.action[self.indices['CROUCH']] = int(np.random.random() > 0.995)
# Clip to the valid range and convert to the right dtype
return self.clip_action(self.action)
def clip_action(self, action):
return np.clip(action, self.mins, self.maxs).astype(np.intc)
def reset(self):
self.velocity = np.zeros([len(self.action_spec)])
self.action = np.zeros([len(self.action_spec)])
def run(length, width, height, fps, level, record, demo, demofiles, video):
"""Spins up an environment and runs the random agent."""
config = {
'fps': str(fps),
'width': str(width),
'height': str(height)
}
if record:
config['record'] = record
if demo:
config['demo'] = demo
if demofiles:
config['demofiles'] = demofiles
if video:
config['video'] = video
env = deepmind_lab.Lab(level, ['RGB_INTERLEAVED'], config=config)
env.reset()
# Starts the random spring agent. As a simpler alternative, we could also
# use DiscretizedRandomAgent().
agent = SpringAgent(env.action_spec())
reward = 0
for _ in six.moves.range(length):
if not env.is_running():
print('Environment stopped early')
env.reset()
agent.reset()
obs = env.observations()
action = agent.step(reward, obs['RGB_INTERLEAVED'])
reward = env.step(action, num_steps=1)
print('Finished after %i steps. Total reward received is %f'
% (length, agent.rewards))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--length', type=int, default=1000,
help='Number of steps to run the agent')
parser.add_argument('--width', type=int, default=80,
help='Horizontal size of the observations')
parser.add_argument('--height', type=int, default=80,
help='Vertical size of the observations')
parser.add_argument('--fps', type=int, default=60,
help='Number of frames per second')
parser.add_argument('--runfiles_path', type=str, default=None,
help='Set the runfiles path to find DeepMind Lab data')
parser.add_argument('--level_script', type=str,
default='tests/empty_room_test',
help='The environment level script to load')
parser.add_argument('--record', type=str, default=None,
help='Record the run to a demo file')
parser.add_argument('--demo', type=str, default=None,
help='Play back a recorded demo file')
parser.add_argument('--demofiles', type=str, default=None,
help='Directory for demo files')
parser.add_argument('--video', type=str, default=None,
help='Record the demo run as a video')
args = parser.parse_args()
if args.runfiles_path:
deepmind_lab.set_runfiles_path(args.runfiles_path)
run(args.length, args.width, args.height, args.fps, args.level_script,
args.record, args.demo, args.demofiles, args.video)
|
lab-master
|
python/random_agent.py
|
# Copyright 2016-17 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
################################################################################
"""A simple example of a random agent in deepmind_lab."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import random
import numpy as np
import six
import deepmind_lab
class RandomAgent(object):
"""Basic random agent for DeepMind Lab."""
def __init__(self, action_spec):
self.action_spec = action_spec
self.action_count = len(action_spec)
def step(self):
"""Choose a random amount of a randomly selected action."""
action_choice = random.randint(0, self.action_count - 1)
action_amount = random.randint(self.action_spec[action_choice]['min'],
self.action_spec[action_choice]['max'])
action = np.zeros([self.action_count], dtype=np.intc)
action[action_choice] = action_amount
return action
def run(width, height, level_script, frame_count):
"""Spins up an environment and runs the random agent."""
config = {'width': str(width), 'height': str(height)}
env = deepmind_lab.Lab(level_script, ['RGB_INTERLEAVED'], config=config)
env.reset()
reward = 0
agent = RandomAgent(env.action_spec())
for _ in six.moves.range(frame_count):
if not env.is_running():
print('Environment stopped early')
env.reset()
agent.reset()
action = agent.step()
reward += env.step(action, num_steps=1)
print('Finished after %i steps. Total reward received is %f'
% (frame_count, reward))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--frame_count', type=int, default=1000,
help='Number of steps to run the agent')
parser.add_argument('--width', type=int, default=80,
help='Horizontal size of the observations')
parser.add_argument('--height', type=int, default=80,
help='Vertical size of the observations')
parser.add_argument('--runfiles_path', type=str, default=None,
help='Set the runfiles path to find DeepMind Lab data')
parser.add_argument('--level_script', type=str, default='tests/demo_map',
help='The environment level script to load')
args = parser.parse_args()
if args.runfiles_path:
deepmind_lab.set_runfiles_path(args.runfiles_path)
run(args.width, args.height, args.level_script, args.frame_count)
|
lab-master
|
python/random_agent_simple.py
|
# Copyright 2019 Google LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""A DeepMind Lab Python module that implements DeepMind's dm_env API."""
import dm_env
import numpy as np
import six
import deepmind_lab
def set_runfiles_path(path):
"""Module-level function to set the path of the DeepMind Lab DSOs."""
deepmind_lab.set_runfiles_path(path)
class Lab(dm_env.Environment):
"""Implements dm_env.Environent; forwards calls to deepmind_lab."""
def __init__(self, level, observation_names, config):
self._lab = deepmind_lab.Lab(level, observation_names, config)
self._observation_names = observation_names
self._needs_reset = True
lab_action_specs = self._lab.action_spec()
self._action_spec = {}
self._action_map = {}
self._action_count = len(lab_action_specs)
for i, spec in enumerate(lab_action_specs):
name = spec["name"]
self._action_map[name] = i
self._action_spec[name] = dm_env.specs.BoundedArray(
dtype=np.dtype("int32"),
shape=(),
name=name,
minimum=spec["min"],
maximum=spec["max"])
self._observation_spec = {}
for spec in self._lab.observation_spec():
name = spec["name"]
shape = spec["shape"]
if name in self._observation_names:
if 0 in shape:
raise NotImplementedError(
"Dynamic shapes are not supported by dm_env; requested shape for "
"observation {} was {}.".format(name, shape))
self._observation_spec[name] = dm_env.specs.Array(
dtype=spec["dtype"], shape=shape, name=name)
def _observation(self):
return {
name: np.asarray(data, dtype=self._observation_spec[name].dtype)
for name, data in six.iteritems(self._lab.observations())
}
def reset(self):
self._lab.reset()
self._needs_reset = False
return dm_env.restart(self._observation())
def step(self, action):
if self._needs_reset:
return self.reset()
lab_action = np.empty(self._action_count, dtype=np.dtype("int32"))
for name, value in six.iteritems(action):
lab_action[self._action_map[name]] = value
reward = self._lab.step(lab_action)
if self._lab.is_running():
return dm_env.transition(reward=reward, observation=self._observation())
else:
self._needs_reset = True
return dm_env.termination(reward=reward, observation=self._observation())
def action_spec(self):
return self._action_spec
def observation_spec(self):
return self._observation_spec
|
lab-master
|
python/dmenv_module.py
|
"""The DeepMind Lab native module and dm_env bindings.
The native module is loaded from the DSO deepmind_lab.so. It provides
complete access to the functionality of DeepMind Lab. The API of this
module and the "Lab" type is documented in docs/users/python_api.md.
Use it as follows:
import deepmind_lab
lab = deepmind_lab.Lab(level='lt_chasm', observations=['RGB'])
# ...
The "dm_env bindings" module provides bindings to the "dm_env" API. The module
is exposed as "deepmind_lab.dmenv_module". It requires the "dm_env" module; the
PIP "dmenv_module" extra describes that dependency. Only a subset of features
is accessible this way. Use the module as follows:
from deepmind_lab import dmenv_module as dm_env_lab
lab = dm_env_lab.Lab(level='lt_chasm', observation_names=['RGB'], config={})
# ...
"""
import imp
from deepmind_lab import dmenv_module
import pkg_resources
_deepmind_lab = imp.load_dynamic(
__name__, pkg_resources.resource_filename(__name__, 'deepmind_lab.so'))
Lab = _deepmind_lab.Lab # needed from within dmenv_module
|
lab-master
|
python/pip_package/__init__.py
|
"""Setup for the deepmind_lab module."""
import setuptools
setuptools.setup(
name='deepmind-lab',
version='1.0',
description='DeepMind Lab: A 3D learning environment',
long_description='',
url='https://github.com/deepmind/lab',
author='DeepMind',
packages=setuptools.find_packages(),
install_requires=[
'numpy >= 1.13.3',
'six >= 1.10.0',
],
extras_require={
'dmenv_module': ['dm-env'],
},
include_package_data=True)
|
lab-master
|
python/pip_package/setup.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class TeamModelSelectTest(absltest.TestCase):
def test_with_six_bots(self):
player_count = 7
env = deepmind_lab.Lab(
'tests/team_model_select', [],
config={'botCount': str(player_count - 1)})
env.reset()
action_spec = env.action_spec()
action = np.zeros([len(action_spec)], dtype=np.intc)
event_names = sorted([name for name, _ in env.events()])
self.assertLen(event_names, player_count * 2)
for i in six.moves.range(player_count):
self.assertEqual(event_names[i], 'newClientInfo' + str(i + 1))
self.assertEqual(event_names[i + player_count],
'skinModified' + str(i + 1))
env.step(action, 1)
self.assertEmpty(env.events())
env.reset()
self.assertLen(env.events(), player_count * 2)
def test_without_bot(self):
env = deepmind_lab.Lab(
'tests/team_model_select', [],
config={'botCount': '0'})
env.reset()
action_spec = env.action_spec()
action = np.zeros([len(action_spec)], dtype=np.intc)
event_names = sorted([name for name, _ in env.events()])
self.assertLen(event_names, 2)
self.assertEqual(event_names[0], 'newClientInfo1')
self.assertEqual(event_names[1], 'skinModified1')
env.step(action, 1)
self.assertEmpty(env.events())
env.reset()
self.assertLen(env.events(), 2)
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/team_model_select_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests Python level cache."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import shutil
import six
import tempfile
from absl.testing import absltest
import numpy as np
import deepmind_lab
class LevelCacheTest(absltest.TestCase):
def setUp(self):
self._test_dir = tempfile.mkdtemp()
self._dummy_action = np.array([0, 0, 0, 0, 0, 0, 0], dtype=np.intc)
def tearDown(self):
shutil.rmtree(self._test_dir)
def _create_environment(self, level_cache):
return deepmind_lab.Lab(
level='contributed/dmlab30/explore_goal_locations_small',
observations=['RGB_INTERLEAVED'],
config={
'width': '96',
'height': '72',
},
level_cache=level_cache)
def test_missing_write(self):
class LevelCache(object):
def fetch(self, key, pk3_path):
del key
del pk3_path
return False
env = self._create_environment(LevelCache())
with six.assertRaisesRegex(self, AttributeError, 'write'):
env.reset(episode=1, seed=123)
env.step(self._dummy_action)
def test_missing_fetch(self):
class LevelCache(object):
def write(self, key, pk3_path):
pass
env = self._create_environment(LevelCache())
with six.assertRaisesRegex(self, AttributeError, 'fetch'):
env.reset(episode=1, seed=123)
env.step(self._dummy_action)
def test_incorrect_fetch(self):
class LevelCache(object):
def fetch(self): # Missing arguments.
return False
def write(self, key, pk3_path):
pass
env = self._create_environment(LevelCache())
with six.assertRaisesRegex(self, TypeError,
'(exactly 1|takes 1 positional) argument'):
env.reset(episode=1, seed=123)
env.step(self._dummy_action)
def test_exception_in_fetch(self):
class LevelCache(object):
def fetch(self, key, pk3_path):
del key
del pk3_path
raise ValueError('foo')
def write(self, key, pk3_path):
pass
env = self._create_environment(LevelCache())
with six.assertRaisesRegex(self, ValueError, 'foo'):
env.reset(episode=1, seed=123)
env.step(self._dummy_action)
def test_level_cache_none(self):
# This should be equivalent to not set the level cache at all and just work.
env = self._create_environment(level_cache=None)
env.reset(episode=1, seed=123)
env.step(self._dummy_action)
def test_local_level_cache(self):
num_successful_fetches = [0]
num_failed_fetches = [0]
num_writes = [0]
class LevelCache(object):
def __init__(self, cache_dir):
self._cache_dir = cache_dir
def fetch(self, key, pk3_path):
path = os.path.join(self._cache_dir, key)
if os.path.isfile(path):
shutil.copyfile(path, pk3_path)
num_successful_fetches[0] += 1
return True
num_failed_fetches[0] += 1
return False
def write(self, key, pk3_path):
path = os.path.join(self._cache_dir, key)
num_writes[0] += 1
shutil.copyfile(pk3_path, path)
env = self._create_environment(LevelCache(cache_dir=self._test_dir))
env.reset(episode=1, seed=123)
env.step(self._dummy_action)
self.assertEqual(0, num_successful_fetches[0])
self.assertEqual(1, num_failed_fetches[0])
self.assertEqual(1, num_writes[0])
env.reset(episode=1, seed=123)
env.step(self._dummy_action)
self.assertEqual(1, num_successful_fetches[0])
self.assertEqual(1, num_failed_fetches[0])
self.assertEqual(1, num_writes[0])
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/level_cache_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
from python.tests.utils import math_utils
class PlayerInfo(absltest.TestCase):
def test_movement(self):
fps = 60
env = deepmind_lab.Lab(
'tests/empty_room_test', [
'VEL.TRANS',
'VEL.ROT',
'DEBUG.POS.TRANS',
'DEBUG.POS.ROT',
'DEBUG.PLAYER_ID',
],
config={
'fps': str(fps),
'width': '80',
'height': '80',
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
env.reset()
player_id = env.observations()['DEBUG.PLAYER_ID']
self.assertEqual(player_id[0], 1)
vel = env.observations()['VEL.TRANS']
self.assertTrue(np.array_equal(vel, np.array([0, 0, 0])))
ops = [{
'axis': 0,
'fact': 320,
'lr': 0,
'bf': 1
}, {
'axis': 0,
'fact': -320,
'lr': 0,
'bf': -1
}, {
'axis': 1,
'fact': -320,
'lr': 1,
'bf': 0
}, {
'axis': 1,
'fact': 320,
'lr': -1,
'bf': 0
}]
before = env.observations()['DEBUG.POS.TRANS']
for op in ops:
action[action_index['STRAFE_LEFT_RIGHT']] = op['lr']
action[action_index['MOVE_BACK_FORWARD']] = op['bf']
for _ in six.moves.range(60):
env.step(action, 1)
vel = env.observations()['VEL.TRANS']
vel_axis = vel[op['axis']] / op['fact']
self.assertLessEqual(0, vel_axis)
if vel_axis >= 1:
break
else:
print(env.observations()['VEL.TRANS'])
self.fail('Failed to reach max velocity')
action[action_index['STRAFE_LEFT_RIGHT']] = 0
action[action_index['MOVE_BACK_FORWARD']] = 0
for _ in six.moves.range(60):
env.step(action, 1)
vel = env.observations()['VEL.TRANS']
vel_axis = vel[op['axis']] / op['fact']
if vel_axis == 0:
break
else:
print(env.observations()['VEL.TRANS'])
self.fail('Failed to stop')
after = env.observations()['DEBUG.POS.TRANS']
self.assertTrue(np.allclose(before, after, atol=3.0))
frames = 66
speed = 22
env.reset()
env.step(action, 2)
action[action_index['LOOK_LEFT_RIGHT_PIXELS_PER_FRAME']] = speed
env.step(action, frames)
action[action_index['LOOK_LEFT_RIGHT_PIXELS_PER_FRAME']] = 0
env.step(action, 10)
rot = env.observations()['DEBUG.POS.ROT']
# Angles are stored 0 East and CCW is positive. So negate speed.
yaw = math_utils.calculate_angle(fps, -speed, frames)
self.assertTrue(np.allclose(rot, np.array([0, yaw, 0]), atol=1e-2))
action[action_index['LOOK_LEFT_RIGHT_PIXELS_PER_FRAME']] = speed / -2
env.step(action, frames * 2)
action[action_index['LOOK_LEFT_RIGHT_PIXELS_PER_FRAME']] = 0
env.step(action, 10)
rot = env.observations()['DEBUG.POS.ROT']
self.assertTrue(np.allclose(rot, np.array([0, 0, 0]), atol=0.01))
speed = -10
env.reset()
env.step(action, 2)
action[action_index['LOOK_DOWN_UP_PIXELS_PER_FRAME']] = speed
env.step(action, frames)
action[action_index['LOOK_DOWN_UP_PIXELS_PER_FRAME']] = 0
env.step(action, 10)
rot = env.observations()['DEBUG.POS.ROT']
pitch = math_utils.calculate_angle(fps, speed, frames)
self.assertTrue(np.allclose(rot, np.array([pitch, 0, 0]), atol=1e-2))
action[action_index['LOOK_DOWN_UP_PIXELS_PER_FRAME']] = speed / -2
env.step(action, frames * 2)
action[action_index['LOOK_DOWN_UP_PIXELS_PER_FRAME']] = 0
env.step(action, 10)
rot = env.observations()['DEBUG.POS.ROT']
self.assertTrue(np.allclose(rot, np.array([0, 0, 0]), atol=0.01))
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/player_info_test.py
|
# Copyright 2016 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Basic test for the random Python agent."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import six
import deepmind_lab
from python import random_agent
class RandomAgentsTest(absltest.TestCase):
def test_spring_agent_run(self, length=100):
env = deepmind_lab.Lab(
'tests/empty_room_test', ['RGB_INTERLEAVED'],
config={
'fps': '60',
'controls': 'external',
'width': '80',
'height': '80'
})
env.reset()
agent = random_agent.SpringAgent(env.action_spec())
reward = 0
for _ in six.moves.range(length):
if not env.is_running():
print('Environment stopped early')
env.reset()
obs = env.observations()
action = agent.step(reward, obs['RGB_INTERLEAVED'])
reward = env.step(action, 1)
self.assertIsInstance(reward, float)
def test_discretized_random_agent_run(self, length=100):
env = deepmind_lab.Lab(
'tests/empty_room_test', ['RGB_INTERLEAVED'],
config={
'fps': '60',
'width': '80',
'height': '80'
})
env.reset()
agent = random_agent.DiscretizedRandomAgent()
reward = 0
for _ in six.moves.range(length):
if not env.is_running():
print('Environment stopped early')
env.reset()
obs = env.observations()
action = agent.step(reward, obs['RGB_INTERLEAVED'])
reward = env.step(action, 1)
self.assertIsInstance(reward, float)
def test_map_frame_count(self, length=100):
env = deepmind_lab.Lab(
'tests/empty_room_test', ['MAP_FRAME_NUMBER'],
config={'fps': '60',
'width': '80',
'height': '80'})
env.reset()
agent = random_agent.DiscretizedRandomAgent()
reward = 0
for frame in six.moves.range(length):
if not env.is_running():
print('Environment stopped early')
env.reset()
obs = env.observations()
action = agent.step(reward, None)
env.step(action, 1)
frame_number = int(obs['MAP_FRAME_NUMBER'])
self.assertEquals(frame, frame_number)
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/random_agent_test.py
|
# Copyright 2016 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Measures DeepMind Lab performance by running low-overhead Random agent."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import random
import time
import numpy as np
import six
import deepmind_lab
def _action(*entries):
return np.array(entries, dtype=np.intc)
class DiscretizedRandomAgent(object):
"""Simple agent for DeepMind Lab."""
ACTION_LIST = [
_action(0, 0, -1, 0, 0, 0, 0), # strafe_left
_action(0, 0, 1, 0, 0, 0, 0), # strafe_right
_action(0, 0, 0, 1, 0, 0, 0), # forward
_action(0, 0, 0, -1, 0, 0, 0), # backward
_action(0, 0, 0, 0, 1, 0, 0), # fire
_action(0, 0, 0, 0, 0, 1, 0), # crouch
_action(0, 0, 0, 0, 0, 0, 1), # jump
]
def step(self, unused_reward, unused_image):
"""Gets an image state and a reward, returns an action."""
return random.choice(DiscretizedRandomAgent.ACTION_LIST)
def run(length, width, height, fps, level, observation_spec):
"""Spins up an environment and runs the random agent."""
env = deepmind_lab.Lab(
level, [observation_spec],
config={
'fps': str(fps),
'width': str(width),
'height': str(height)
})
env.reset()
agent = DiscretizedRandomAgent()
reward = 0
t0 = time.time()
for _ in six.moves.range(length):
if not env.is_running():
print('Environment stopped early')
env.reset()
agent.reset()
obs = env.observations()
action = agent.step(reward, obs[observation_spec])
reward = env.step(action, num_steps=1)
t1 = time.time()
duration = t1 - t0
print('resolution: %i x %i, spec: %s, steps: %i, duration: %.1f, fps: %.1f' %
(width, height, observation_spec, length, duration, length / duration))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--runfiles_path', type=str, default=None,
help='Set the runfiles path to find DeepMind Lab data')
args = parser.parse_args()
if args.runfiles_path:
deepmind_lab.set_runfiles_path(args.runfiles_path)
# Test for 1 minute of simulation time at fixed in-game frame rate.
length = 3600
fps = 60
# Benchmark at each of the following levels at the specified resolutions and
# observation specs.
for level_script in ['nav_maze_static_01', 'lt_space_bounce_hard']:
for width, height in [(84, 84), (160, 120), (320, 240)]:
for observation_spec in ['RGB', 'RGBD']:
run(length, width, height, fps, level_script, observation_spec)
if __name__ == '__main__':
main()
|
lab-master
|
python/tests/benchmark.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests for inventory reading."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
GADGETS = {
'IMPULSE': 2, ## Contact gadget.
'RAPID': 3, ## Rapid fire gadget.
'ORB': 6, ## Area damage gadget. (Knocks players)
'BEAM': 7, ## Accurate and very rapid fire beam.
'DISC': 8, ## Powerful but long period between firing.
}
class UpdateInventoryTest(absltest.TestCase):
def test_weapon_auto_switch(self):
env = deepmind_lab.Lab(
'tests/update_inventory_test', ['DEBUG.AMOUNT', 'DEBUG.GADGET'],
config={
'fps': '60',
'width': '80',
'height': '80'
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
action[action_index['FIRE']] = 1
env.reset()
self.assertEqual(env.observations()['DEBUG.GADGET'][0], GADGETS['ORB'])
self.assertEqual(env.observations()['DEBUG.AMOUNT'][0], 2)
## Fire two orbs.
for _ in six.moves.range(600):
env.step(action, 1)
self.assertEqual(env.observations()['DEBUG.GADGET'][0], GADGETS['ORB'])
if env.observations()['DEBUG.AMOUNT'][0] == 0:
break
else:
self.fail('Failed use orbs!')
## Wait for weapon switch.
for _ in six.moves.range(600):
env.step(action, 1)
if env.observations()['DEBUG.GADGET'][0] == GADGETS['RAPID']:
break
else:
self.fail('Failed to auto switch weapon!')
self.assertEqual(env.observations()['DEBUG.AMOUNT'][0], 10)
for _ in six.moves.range(600):
env.step(action, 1)
if env.observations()['DEBUG.AMOUNT'][0] == 0:
break
else:
self.fail('Failed to use rapid!')
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/update_inventory_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
PLAYER_DEBUG_OBSERVATIONS = [
'DEBUG.PLAYER_ID',
'DEBUG.PLAYERS.ARMOR',
'DEBUG.PLAYERS.GADGET',
'DEBUG.PLAYERS.GADGET_AMOUNT',
'DEBUG.PLAYERS.HEALTH',
'DEBUG.PLAYERS.HOLDING_FLAG',
'DEBUG.PLAYERS.ID',
'DEBUG.PLAYERS.EYE.POS',
'DEBUG.PLAYERS.EYE.ROT',
'DEBUG.PLAYERS.VELOCITY',
'DEBUG.PLAYERS.SCORE',
'DEBUG.PLAYERS.IS_BOT',
'DEBUG.PLAYERS.NAME',
'DEBUG.PLAYERS.TEAM',
]
DEBUG_CAMERA_OBSERVATION = 'DEBUG.CAMERA.TOP_DOWN'
DEBUG_ICAMERA_OBSERVATION = 'DEBUG.CAMERA_INTERLEAVED.TOP_DOWN'
MAZE_LAYOUT_OBSERVATION = 'DEBUG.MAZE.LAYOUT'
TEST_MAP = """
********
* *P *
*P *
********
""".lstrip('\n')
RANDOM_DEBUG_CAMERA_PIXEL_POS_VALUES = [
([55, 122], [187, 184, 255]),
([210, 150], [76, 108, 68]),
([250, 125], [214, 148, 28]),
]
class DebugObservationTest(absltest.TestCase):
def test_amount(self):
fps = 60
player_name = 'PlayerInfoTest'
env = deepmind_lab.Lab(
'tests/debug_observation_test',
PLAYER_DEBUG_OBSERVATIONS,
config={
'fps': str(fps),
'width': '80',
'height': '80',
'playerName': player_name,
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
env.reset()
obs = env.observations()
self.assertEqual(obs['DEBUG.PLAYER_ID'], obs['DEBUG.PLAYERS.ID'][0])
names = obs['DEBUG.PLAYERS.NAME'].split('\n')
self.assertEqual(player_name, names[0])
self.assertEqual(100, obs['DEBUG.PLAYERS.GADGET_AMOUNT'][0])
self.assertEqual(100, obs['DEBUG.PLAYERS.GADGET_AMOUNT'][1])
## Empty player's gadget ammo.
action[action_index['FIRE']] = 1
for _ in six.moves.range(1000):
env.step(action)
obs = env.observations()
if obs['DEBUG.PLAYERS.GADGET_AMOUNT'][0] == 0:
break
else:
self.fail('Failed to empty gadget.')
self.assertEqual(100, obs['DEBUG.PLAYERS.GADGET_AMOUNT'][1])
action[action_index['FIRE']] = 0
action[action_index['MOVE_BACK_FORWARD']] = 1
for _ in six.moves.range(1000):
env.step(action)
obs = env.observations()
if obs['DEBUG.PLAYERS.HEALTH'][0] <= 0:
break
else:
self.fail('Failed to be tagged by agent., health still' +
str(obs['DEBUG.PLAYERS.HEALTH'][0]))
self.assertEqual(obs['DEBUG.PLAYERS.SCORE'][0], 0.)
self.assertEqual(obs['DEBUG.PLAYERS.SCORE'][1], 1.)
self.assertEqual(obs['DEBUG.PLAYERS.IS_BOT'][0], 0)
self.assertEqual(obs['DEBUG.PLAYERS.IS_BOT'][1], 1)
self.assertGreater(100, obs['DEBUG.PLAYERS.GADGET_AMOUNT'][1])
def test_maze_layout(self):
env = deepmind_lab.Lab(
'tests/debug_observation_test', [MAZE_LAYOUT_OBSERVATION], config={})
env.reset()
self.assertEqual(env.observations()[MAZE_LAYOUT_OBSERVATION], TEST_MAP)
def test_debug_camera(self):
env = deepmind_lab.Lab(
'tests/debug_observation_test',
[DEBUG_CAMERA_OBSERVATION, DEBUG_ICAMERA_OBSERVATION,
'RGB_INTERLEAVED'],
config={'width': '320', 'height': '180'})
env.reset()
camera_image = env.observations()[DEBUG_CAMERA_OBSERVATION]
icamera_image = env.observations()[DEBUG_ICAMERA_OBSERVATION]
for (x, y), rgb in RANDOM_DEBUG_CAMERA_PIXEL_POS_VALUES:
self.assertTrue(np.allclose(camera_image[:, y, x], rgb, atol=6))
self.assertTrue(np.allclose(icamera_image[y, x, :], rgb, atol=6))
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/debug_observation_test.py
|
# Copyright 2017 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Custom action tests"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import deepmind_lab
class CustomViewTest(absltest.TestCase):
def test_CustomActions(self):
env = deepmind_lab.Lab(
'tests/custom_actions_test', [],
config={'fps': '60'})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
self.assertIn('SWITCH_GADGET', action_index)
self.assertIn('SELECT_GADGET', action_index)
self.assertEqual(action_spec[action_index['SWITCH_GADGET']]['min'], -1)
self.assertEqual(action_spec[action_index['SWITCH_GADGET']]['max'], 1)
self.assertEqual(action_spec[action_index['SELECT_GADGET']]['min'], 0)
self.assertEqual(action_spec[action_index['SELECT_GADGET']]['max'], 10)
action = np.zeros([len(action_spec)], dtype=np.intc)
env.reset()
events = env.events()
self.assertEmpty(events)
env.step(action)
events = env.events()
self.assertEmpty(events)
action[action_index['SWITCH_GADGET']] = 1
env.step(action)
events = env.events()
self.assertLen(events, 1)
name, values = events[0]
self.assertEqual(name, 'SWITCH_GADGET')
self.assertEqual(values[0], '1')
action[action_index['SWITCH_GADGET']] = 0
action[action_index['SELECT_GADGET']] = 1
env.step(action)
events = env.events()
self.assertLen(events, 1)
name, values = events[0]
self.assertEqual(name, 'SELECT_GADGET')
self.assertEqual(values[0], '1')
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/custom_actions_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests for inventory modification API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class ScoreEventTest(absltest.TestCase):
def test_self_orb(self):
env = deepmind_lab.Lab(
'tests/spawn_inventory_test', ['DEBUG.POS.ROT'],
config={
'fps': '60',
'width': '80',
'height': '80'
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
action[action_index['LOOK_DOWN_UP_PIXELS_PER_FRAME']] = 100
reward = env.reset()
for _ in six.moves.range(60):
env.step(action, 1)
if env.observations()['DEBUG.POS.ROT'][0] > 85:
break
else:
self.fail('Failed to look at floor!')
action[action_index['LOOK_DOWN_UP_PIXELS_PER_FRAME']] = 0
action[action_index['FIRE']] = 1
for _ in six.moves.range(600):
reward = env.step(action, 1)
if reward < 0:
self.assertEqual(reward, -1)
break
else:
self.fail('Failed to orb floor!')
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/spawn_inventory_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests for Raycast observations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class RaycastTest(absltest.TestCase):
def test_pickup_raycast(self):
env = deepmind_lab.Lab(
'tests/raycast_test', ['RAYCASTS', 'DEBUG.POS.TRANS'],
config={
'fps': '60',
'width': '80',
'height': '80'
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
action[action_index['MOVE_BACK_FORWARD']] = 1
reward = env.reset()
raycasts = env.observations()['RAYCASTS']
self.assertEqual(raycasts[0], 1)
self.assertLess(raycasts[1], 1)
self.assertLess(raycasts[2], 1)
for _ in six.moves.range(120):
reward = env.step(action, 1)
if reward > 0:
self.assertEqual(reward, 1)
break
else:
print(env.observations()['DEBUG.POS.TRANS'])
self.fail('Failed to pickup 1st apple!')
raycasts = env.observations()['RAYCASTS']
self.assertEqual(raycasts[0], 1)
self.assertEqual(raycasts[1], 1)
self.assertLess(raycasts[2], 1)
action[action_index['STRAFE_LEFT_RIGHT']] = 1
action[action_index['MOVE_BACK_FORWARD']] = 0
for _ in six.moves.range(160):
reward = env.step(action, 1)
if reward > 0:
self.assertEqual(reward, 1)
break
else:
print(env.observations()['DEBUG.POS.TRANS'])
self.fail('Failed to pickup 2st apple!')
raycasts = env.observations()['RAYCASTS']
self.assertEqual(raycasts[0], 1)
self.assertEqual(raycasts[1], 1)
self.assertEqual(raycasts[2], 1)
action[action_index['STRAFE_LEFT_RIGHT']] = 0
action[action_index['MOVE_BACK_FORWARD']] = -1
for _ in six.moves.range(160):
reward = env.step(action, 1)
if reward > 0:
self.assertEqual(reward, 1)
break
else:
print(env.observations()['DEBUG.POS.TRANS'])
self.fail('Failed to pickup 3rd apple!')
raycasts = env.observations()['RAYCASTS']
self.assertLess(raycasts[0], 1)
self.assertEqual(raycasts[1], 1)
self.assertEqual(raycasts[2], 1)
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/raycast_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests for InFov observations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class InFovTest(absltest.TestCase):
def test_pickup_raycast(self):
env = deepmind_lab.Lab(
'tests/in_fov_test', ['FOVTESTS', 'ENTITYVIS', 'DEBUG.POS.TRANS'],
config={
'fps': '60',
'width': '80',
'height': '80'
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
action[action_index['MOVE_BACK_FORWARD']] = 1
reward = env.reset()
fov_tests = env.observations()['FOVTESTS']
self.assertEqual(fov_tests[0], 1)
self.assertEqual(fov_tests[1], 1)
self.assertEqual(fov_tests[2], 0)
entity_vis = env.observations()['ENTITYVIS']
self.assertEqual(entity_vis[0], 1)
self.assertLess(entity_vis[1], 1)
self.assertEqual(entity_vis[2], -1)
for _ in six.moves.range(120):
reward = env.step(action, 1)
if reward > 0:
self.assertEqual(reward, 1)
break
else:
print(env.observations()['DEBUG.POS.TRANS'])
self.fail('Failed to pickup 1st apple!')
fov_tests = env.observations()['FOVTESTS']
self.assertEqual(fov_tests[0], 1)
self.assertEqual(fov_tests[1], 0)
self.assertEqual(fov_tests[2], 0)
entity_vis = env.observations()['ENTITYVIS']
self.assertEqual(entity_vis[0], 1)
self.assertEqual(entity_vis[1], -1)
self.assertEqual(entity_vis[2], -1)
action[action_index['STRAFE_LEFT_RIGHT']] = 1
action[action_index['MOVE_BACK_FORWARD']] = 0
for _ in six.moves.range(160):
reward = env.step(action, 1)
if reward > 0:
self.assertEqual(reward, 1)
break
else:
print(env.observations()['DEBUG.POS.TRANS'])
self.fail('Failed to pickup 2st apple!')
fov_tests = env.observations()['FOVTESTS']
self.assertEqual(fov_tests[0], 0)
self.assertEqual(fov_tests[1], 0)
self.assertEqual(fov_tests[2], 0)
entity_vis = env.observations()['ENTITYVIS']
self.assertEqual(entity_vis[0], -1)
self.assertEqual(entity_vis[1], -1)
self.assertEqual(entity_vis[2], -1)
action[action_index['STRAFE_LEFT_RIGHT']] = 0
action[action_index['MOVE_BACK_FORWARD']] = -1
for _ in six.moves.range(160):
reward = env.step(action, 1)
if reward > 0:
self.assertEqual(reward, 1)
break
else:
print(env.observations()['DEBUG.POS.TRANS'])
self.fail('Failed to pickup 3rd apple!')
fov_tests = env.observations()['FOVTESTS']
self.assertEqual(fov_tests[0], 1)
self.assertEqual(fov_tests[1], 1)
self.assertEqual(fov_tests[2], 0)
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/in_fov_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
MAZE_LAYOUT_OBSERVATION = 'DEBUG.MAZE.LAYOUT'
MAZE_LAYOUT_TRIALS = 50
class MazeGenerationTest(absltest.TestCase):
def test_maze_layout_spread(self):
layouts = set()
for i in six.moves.range(MAZE_LAYOUT_TRIALS):
print('phase 1: trial {} out of {}'.format(i+1, MAZE_LAYOUT_TRIALS))
env = deepmind_lab.Lab(
'tests/maze_generation_test', [MAZE_LAYOUT_OBSERVATION], config={})
env.reset(seed=i+1)
layouts.add(env.observations()[MAZE_LAYOUT_OBSERVATION])
num_layouts = len(layouts)
self.assertEqual(num_layouts, MAZE_LAYOUT_TRIALS)
for i in six.moves.range(MAZE_LAYOUT_TRIALS):
print('phase 2: trial {} out of {}'.format(i+1, MAZE_LAYOUT_TRIALS))
env = deepmind_lab.Lab(
'tests/maze_generation_test', [MAZE_LAYOUT_OBSERVATION],
config={
'mixerSeed': '0',
})
env.reset(seed=i+1)
layouts.add(env.observations()[MAZE_LAYOUT_OBSERVATION])
self.assertLen(layouts, num_layouts)
for i in six.moves.range(MAZE_LAYOUT_TRIALS):
print('phase 3: trial {} out of {}'.format(i+1, MAZE_LAYOUT_TRIALS))
env = deepmind_lab.Lab(
'tests/maze_generation_test', [MAZE_LAYOUT_OBSERVATION],
config={
'mixerSeed': '1',
})
env.reset(seed=i+1)
layouts.add(env.observations()[MAZE_LAYOUT_OBSERVATION])
self.assertLen(layouts - num_layouts, MAZE_LAYOUT_TRIALS)
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/maze_generation_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests for Adding extra Entities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class ExtraEntitiesTest(absltest.TestCase):
def test_pickup_apple_run(self):
env = deepmind_lab.Lab(
'tests/extra_entities_test', ['DEBUG.POS.TRANS'],
config={
'fps': '60',
'width': '80',
'height': '80'
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
action[action_index['MOVE_BACK_FORWARD']] = 1
reward = env.reset()
expected_reward = 1
for _ in six.moves.range(60):
reward = env.step(action, 1)
if reward > 0:
self.assertEqual(reward, expected_reward)
if expected_reward == 5:
break
else:
expected_reward += 1
else:
print(env.observations()['DEBUG.POS.TRANS'])
self.fail('Failed to pickup all apples!')
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/extra_entities_test.py
|
# Copyright 2016-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Basic test for DeepMind Lab Python wrapper."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class DeepMindLabTest(absltest.TestCase):
def testInitArgs(self):
with six.assertRaisesRegex(self, TypeError, 'must be dict, not list'):
deepmind_lab.Lab('tests/empty_room_test', [], ['wrongconfig'])
with six.assertRaisesRegex(self, TypeError, 'str|bad argument type'):
deepmind_lab.Lab('tests/empty_room_test', [], {'wrongtype': 3})
with six.assertRaisesRegex(self, TypeError, 'must be list, not None'):
deepmind_lab.Lab('tests/empty_room_test', None, {})
with six.assertRaisesRegex(self, ValueError, 'Unknown observation'):
deepmind_lab.Lab('tests/empty_room_test', ['nonexisting_obs'], {})
def testReset(self):
lab = deepmind_lab.Lab('tests/empty_room_test', [], {})
with six.assertRaisesRegex(self, ValueError,
'\'seed\' must be int or None, was \'str\''):
lab.reset(seed='invalid')
def testTempFolder(self):
temp_folder = os.path.join(os.environ['TEST_TMPDIR'], 'test_temp_folder')
lab = deepmind_lab.Lab(
'contributed/dmlab30/explore_goal_locations_small', [], {},
temp_folder=temp_folder)
lab.reset()
self.assertGreaterEqual(len(os.listdir(temp_folder)), 1)
def testSpecs(self):
lab = deepmind_lab.Lab('tests/empty_room_test', [])
observation_spec = lab.observation_spec()
observation_spec_names = {o['name'] for o in observation_spec}
observation_spec_lookup = {o['name']: o for o in observation_spec}
action_names = {a['name'] for a in lab.action_spec()}
observation_set = {'RGB_INTERLEAVED', 'RGB', 'RGBD_INTERLEAVED', 'RGBD',
'BGR_INTERLEAVED', 'BGRD_INTERLEAVED'}
self.assertGreaterEqual(observation_spec_names, observation_set)
for k in observation_set:
o = observation_spec_lookup[k]
self.assertIn('shape', o)
self.assertDictContainsSubset({'dtype': np.uint8}, o)
self.assertSetEqual(
action_names,
{'LOOK_LEFT_RIGHT_PIXELS_PER_FRAME',
'LOOK_DOWN_UP_PIXELS_PER_FRAME',
'STRAFE_LEFT_RIGHT',
'MOVE_BACK_FORWARD',
'FIRE',
'JUMP',
'CROUCH'})
for a in lab.action_spec():
self.assertIs(type(a['min']), int)
self.assertIs(type(a['max']), int)
self.assertTrue(lab.close())
def testOpenClose(self):
labs = [
deepmind_lab.Lab('tests/empty_room_test', []) for _ in range(5)]
for lab in labs:
self.assertTrue(lab.close())
def testRun(self, steps=10, observation='RGB_INTERLEAVED'):
env = deepmind_lab.Lab('lt_chasm', [observation])
env.reset()
for _ in six.moves.range(steps):
obs = env.observations()
action = np.zeros((7,), dtype=np.intc)
reward = env.step(action, num_steps=4)
self.assertEqual(obs[observation].shape, (240, 320, 3))
self.assertEqual(reward, 0.0)
def testRunClosed(self):
env = deepmind_lab.Lab('lt_chasm', ['RGB_INTERLEAVED'])
env.reset(episode=42, seed=7)
env.close()
action = np.zeros((7,), dtype=np.intc)
with six.assertRaisesRegex(self, RuntimeError, 'wrong status to advance'):
env.step(action)
with six.assertRaisesRegex(self, RuntimeError, 'wrong status'):
env.observations()
def testRunfilesPath(self):
self.assertTrue(os.stat(deepmind_lab.runfiles_path()))
def testWidthHeight(self, width=80, height=80, steps=10, num_steps=1):
observation = 'RGBD'
env = deepmind_lab.Lab(
'lt_chasm', [observation],
config={'height': str(height), 'width': str(width)})
env.reset()
for _ in six.moves.range(steps):
obs = env.observations()
action = np.zeros((7,), dtype=np.intc)
reward = env.step(action, num_steps=num_steps)
self.assertEqual(obs[observation].shape, (4, width, height))
self.assertEqual(reward, 0.0)
def testStringObervations(self):
observation = 'CUSTOM_TEXT'
env = deepmind_lab.Lab(
'tests/text_observation_test', [observation],
config={'height': '32', 'width': '32'})
observation_spec = env.observation_spec()
observation_spec_lookup = {o['name']: o for o in observation_spec}
spec = observation_spec_lookup[observation]
self.assertEqual(spec['name'], observation)
self.assertEqual(spec['shape'], ())
self.assertEqual(spec['dtype'], str)
env.reset()
self.assertEqual(env.observations()[observation], 'Example Output')
def testEvents(self):
env = deepmind_lab.Lab(
'tests/event_test', [],
config={'height': '32', 'width': '32'})
env.reset(episode=1, seed=7)
events = env.events()
self.assertLen(events, 4)
name, obs = events[0]
self.assertEqual(name, 'TEXT')
self.assertEqual(obs[0], 'EPISODE 1')
name, obs = events[1]
self.assertEqual(name, 'DOUBLE')
np.testing.assert_array_equal(obs[0], np.array([[1., 0.], [0., 1.]]))
name, obs = events[2]
self.assertEqual(name, 'BYTE')
np.testing.assert_array_equal(obs[0], np.array([2, 2], dtype=np.uint8))
name, obs = events[3]
self.assertEqual(name, 'ALL')
self.assertEqual(obs[0], 'Text')
np.testing.assert_array_equal(obs[1], np.array([3], dtype=np.uint8))
np.testing.assert_array_equal(obs[2], np.array([7.]))
action = np.zeros((7,), dtype=np.intc)
env.step(action, num_steps=1)
self.assertEmpty(env.events())
env.step(action, num_steps=58)
self.assertEmpty(env.events())
env.step(action, num_steps=1)
self.assertFalse(env.is_running())
events = env.events()
self.assertLen(events, 1)
name, obs = events[0]
self.assertEqual(name, 'LOG')
self.assertEqual(obs[0], 'Episode ended')
env.reset(episode=2, seed=8)
events = env.events()
self.assertLen(events, 4)
name, obs = events[0]
self.assertEqual(name, 'TEXT')
self.assertEqual(obs[0], 'EPISODE 2')
def testVeloctyObservations(self, width=80, height=80):
noop_action = np.zeros((7,), dtype=np.intc)
forward_action = np.array([0, 0, 0, 1, 0, 0, 0], dtype=np.intc)
backward_action = - forward_action
look_sideways_action = np.array([512, 0, 0, 0, 0, 0, 0], dtype=np.intc)
env = deepmind_lab.Lab(
'seekavoid_arena_01', ['VEL.TRANS', 'VEL.ROT', 'RGBD_INTERLEAVED'],
config={'height': str(height), 'width': str(width), 'fps': '60'})
env.reset(seed=1)
# Initial landing on the ground.
env.step(noop_action, num_steps=180)
for _ in six.moves.range(3):
# Doing nothing should result in velocity observations of zero.
env.step(noop_action, num_steps=100)
obs = env.observations()
np.testing.assert_array_equal(obs['VEL.TRANS'], np.zeros((3,)))
np.testing.assert_array_equal(obs['VEL.ROT'], np.zeros((3,)))
env.step(forward_action, num_steps=100)
obs = env.observations()
forward_vel = obs['VEL.TRANS']
self.assertEqual(forward_vel[2], 0.0) # zero velocity in z direction
self.assertTrue(np.any(forward_vel))
np.testing.assert_array_equal(obs['VEL.ROT'], np.zeros((3,)))
env.step(noop_action, num_steps=4)
# Going backward should result in negative velocity of going forward
env.step(backward_action, num_steps=100)
obs = env.observations()
self.assertAlmostEqual(np.linalg.norm(obs['VEL.TRANS'] + forward_vel),
0.0, delta=3)
np.testing.assert_array_equal(obs['VEL.ROT'], np.zeros((3,)))
env.reset(seed=1)
for _ in six.moves.range(3):
env.step(noop_action, num_steps=100)
obs = env.observations()
np.testing.assert_array_equal(obs['VEL.TRANS'], np.zeros((3,)))
np.testing.assert_array_equal(obs['VEL.ROT'], np.zeros((3,)))
env.step(look_sideways_action, num_steps=100)
obs = env.observations()
sideways_vel = obs['VEL.ROT']
self.assertEqual(sideways_vel[2], 0.0)
self.assertTrue(np.any(forward_vel))
np.testing.assert_array_equal(obs['VEL.TRANS'], np.zeros((3,)))
env.step(noop_action, num_steps=4)
env.step(-look_sideways_action, num_steps=100)
obs = env.observations()
self.assertAlmostEqual(np.linalg.norm(obs['VEL.ROT'] + sideways_vel),
0.0, delta=3)
np.testing.assert_array_equal(obs['VEL.TRANS'], np.zeros((3,)))
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(os.path.join(
os.environ['TEST_SRCDIR'], 'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/dmlab_module_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Test for the EpisodeTimeMs callback."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class EpisodeTimeTest(absltest.TestCase):
def run_at_frame_rate(self, fps):
env = deepmind_lab.Lab(
'tests/episode_time_test', ['EPISODE_TIME_SECONDS'],
config={
'fps': str(fps),
'width': '32',
'height': '32'
})
env.reset()
nop = np.zeros((7,), dtype=np.intc)
for _ in six.moves.range(0, fps):
env.step(nop, 1)
obs = env.observations()
self.assertEqual(obs['EPISODE_TIME_SECONDS'][0], 1.0)
def test_at_60(self):
self.run_at_frame_rate(60)
def test_at_30(self):
self.run_at_frame_rate(30)
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/episode_time_test.py
|
# Copyright 2019 Google LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Conformance test for the dm_env API bindings."""
import os
from absl.testing import absltest
from dm_env import test_utils
import dmenv_module
class DmenvTest(test_utils.EnvironmentTestMixin, absltest.TestCase):
def make_object_under_test(self):
if 'TEST_SRCDIR' in os.environ:
dmenv_module.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
return dmenv_module.Lab(
level='tests/entity_info_test',
observation_names=['RGB_INTERLEAVED'],
config={
'fps': '60',
'width': '32',
'height': '32'
})
if __name__ == '__main__':
absltest.main()
|
lab-master
|
python/tests/dmenv_module_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Basic test for the random Python agent."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class LookatTest(absltest.TestCase):
def test_lookat_run(self):
kBrushU = 1
kIsLooking = 3
env = deepmind_lab.Lab(
'tests/lookat_test', ['LOOK_AT'],
config={
'fps': '60',
'controls': 'external',
'width': '32',
'height': '32'
})
env.reset()
noop = np.array([0, 0, 0, 0, 0, 0, 0], dtype=np.intc)
last_look_at = None
for _ in six.moves.range(10):
self.assertEqual(env.step(noop, 1), 0)
next_look_at = env.observations()['LOOK_AT']
self.assertEqual(1, next_look_at[kIsLooking])
if last_look_at is not None and np.allclose(last_look_at, next_look_at):
break
last_look_at = next_look_at
else:
self.fail('Too many iterations to stablise!')
self.assertAlmostEqual(last_look_at[kBrushU], 0.5, delta=0.1)
look_left = np.array([-5, 0, 0, 0, 0, 0, 0], dtype=np.intc)
for _ in six.moves.range(100):
env.step(look_left, 1)
next_look_at = env.observations()['LOOK_AT']
if next_look_at[kIsLooking] != 1:
self.assertAlmostEqual(last_look_at[kBrushU], 1.0, delta=0.1)
break
self.assertTrue(next_look_at[kBrushU] >= last_look_at[kBrushU])
last_look_at = next_look_at
else:
self.fail('Failed to look away from object')
look_right = np.array([5, 0, 0, 0, 0, 0, 0], dtype=np.intc)
for _ in six.moves.range(5):
env.step(look_right, 1)
next_look_at = env.observations()['LOOK_AT']
if next_look_at[kIsLooking] == 1:
last_look_at = next_look_at
break
else:
self.fail('Failed to look back to object')
for _ in six.moves.range(100):
env.step(look_right, 1)
next_look_at = env.observations()['LOOK_AT']
if next_look_at[kIsLooking] != 1:
self.assertAlmostEqual(last_look_at[kBrushU], 0.0, delta=0.1)
break
self.assertTrue(next_look_at[kBrushU] <= last_look_at[kBrushU])
last_look_at = next_look_at
else:
self.fail('Failed to all the way through object')
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/lookat_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Test for the Entity Info."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class EntityInfo(absltest.TestCase):
def test_reward_info(self):
env = deepmind_lab.Lab(
'tests/entity_info_test', ['DEBUG.PICKUPS'],
config={
'fps': '60',
'width': '32',
'height': '32'
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
env.reset()
obs = env.observations()
pickups_state = np.array([[150., 50., 16.125, 1., 1.],
[250., 50., 16.125, 1., 1.],
[350., 50., 16.125, 1., 1.],
[450., 50., 16.125, 1., -1.],
[550., 50., 16.125, 1., -1.],
[650., 50., 16.125, 1., -1.]])
self.assertTrue(np.allclose(obs['DEBUG.PICKUPS'], pickups_state))
action = np.zeros([len(action_spec)], dtype=np.intc)
action[action_index['MOVE_BACK_FORWARD']] = 1
reward = 0
for _ in six.moves.range(0, 60):
reward += env.step(action, 1)
if reward == 3:
break
else:
self.fail('Failed to all positive rewards.')
pickups_state = np.array([[150., 50., 16.125, 0., 1.],
[250., 50., 16.125, 0., 1.],
[350., 50., 16.125, 0., 1.],
[450., 50., 16.125, 1., -1.],
[550., 50., 16.125, 1., -1.],
[650., 50., 16.125, 1., -1.]])
obs = env.observations()
self.assertTrue(np.allclose(obs['DEBUG.PICKUPS'], pickups_state))
for _ in six.moves.range(0, 600):
reward += env.step(action, 1)
if reward == 0:
break
else:
self.fail('Failed to pickup last negative reward')
pickups_state = np.array([[150., 50., 16.125, 0., 1.],
[250., 50., 16.125, 0., 1.],
[350., 50., 16.125, 0., 1.],
[450., 50., 16.125, 0., -1.],
[550., 50., 16.125, 0., -1.],
[650., 50., 16.125, 0., -1.]])
obs = env.observations()
self.assertTrue(np.allclose(obs['DEBUG.PICKUPS'], pickups_state))
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/entity_info_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Make sure final reward is received."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class FinalRewardTest(absltest.TestCase):
def test_final_reward(self):
env = deepmind_lab.Lab(
'tests/final_reward_test', [],
config={
'fps': '60',
'width': '80',
'height': '80'
})
action_spec = env.action_spec()
action = np.zeros([len(action_spec)], dtype=np.intc)
env.reset()
reward = 0
for _ in six.moves.range(11):
if not env.is_running():
break
reward += env.step(action, 1)
self.assertEqual(reward, 11 * 10 / 2)
def test_final_reward_skip(self):
env = deepmind_lab.Lab(
'tests/final_reward_test', [],
config={
'fps': '60',
'width': '80',
'height': '80'
})
action_spec = env.action_spec()
action = np.zeros([len(action_spec)], dtype=np.intc)
env.reset()
reward = 0
for _ in six.moves.range(4):
if not env.is_running():
break
reward += env.step(action, 4)
self.assertEqual(reward, 11 * 10 / 2)
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/final_reward_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Set of tests for DMLab determinism."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pprint
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
# Helper function to create DMLab environment.
def make_dmlab_environment(args=None, observations=None):
config = {
'fps': '60',
'width': '32',
'height': '32',
}
if args:
for k, v in six.iteritems(args):
config[k] = v
if observations is None:
observations = ['DEBUG.POS.TRANS']
env = deepmind_lab.Lab(
'seekavoid_arena_01', observations, config=config)
env.reset(episode=1, seed=123)
return env
class DeterminismTest(absltest.TestCase):
# Tests that performing the same action N times produces the same player
# position in each environment.
def test_player_position(self, num_steps=20):
env1 = make_dmlab_environment()
env2 = make_dmlab_environment()
move_fwd = np.array([0, 0, 0, 1, 0, 0, 0], dtype=np.intc)
for _ in six.moves.range(num_steps):
self.assertEqual(env1.step(move_fwd, 1), env2.step(move_fwd, 1))
pos1 = env1.observations()['DEBUG.POS.TRANS']
pos2 = env2.observations()['DEBUG.POS.TRANS']
self.assertTrue(
np.allclose(pos1, pos2),
'Player positions differ!\n' + pprint.pformat({
'pos1': pos1,
'pos2': pos2
}))
# Test that skipping render frames simulates the same player positions as not
# frame skipping
def test_frame_skip(self, num_steps=20, repeated_actions=4):
env1 = make_dmlab_environment()
env2 = make_dmlab_environment()
move_fwd = np.array([0, 0, 0, 1, 0, 0, 0], dtype=np.intc)
for _ in six.moves.range(num_steps):
for _ in six.moves.range(repeated_actions):
env1.step(move_fwd, 1)
env2.step(move_fwd, repeated_actions)
pos1 = env1.observations()['DEBUG.POS.TRANS']
pos2 = env2.observations()['DEBUG.POS.TRANS']
self.assertTrue(
np.allclose(pos1, pos2),
'Player positions differ!\n' + pprint.pformat({
'pos1': pos1,
'pos2': pos2
}))
# Tests that calling step(a, N) is the same as calling step(a, 1) N times.
def test_repeated_actions(self, num_steps=20, repeated_actions=4):
env = make_dmlab_environment()
env_repeated = make_dmlab_environment()
self.assertEqual(num_steps % repeated_actions, 0)
move_fwd = np.array([0, 0, 0, 1, 0, 0, 0], dtype=np.intc)
for _ in six.moves.range(int(num_steps / repeated_actions)):
accum_reward = 0.0
for _ in six.moves.range(repeated_actions):
accum_reward += env.step(move_fwd, 1)
self.assertEqual(
env_repeated.step(move_fwd, repeated_actions), accum_reward)
pos1 = env.observations()['DEBUG.POS.TRANS']
pos2 = env.observations()['DEBUG.POS.TRANS']
self.assertTrue(
np.allclose(pos1, pos2),
'Player positions differ!\n' + pprint.pformat({
'pos1': pos1,
'pos2': pos2
}))
def test_pbo_pixels(self):
env = make_dmlab_environment(
args={'use_pbos': 'false'}, observations=['RGBD'])
pbo_env = make_dmlab_environment(
args={'use_pbos': 'true'}, observations=['RGBD'])
move_fwd = np.array([0, 0, 0, 1, 0, 0, 0], dtype=np.intc)
for _ in six.moves.range(5):
self.assertEqual(env.step(move_fwd, 1), pbo_env.step(move_fwd, 1))
pixels = env.observations()['RGBD']
pbo_pixels = pbo_env.observations()['RGBD']
self.assertTrue(
np.allclose(pixels, pbo_pixels),
'Pixels differ using PBOs!\n' + pprint.pformat({
'pixels': pixels,
'pbo pixels': pbo_pixels
}))
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/determinism_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Basic test for DMLab rendering."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import deepmind_lab
class RenderTest(absltest.TestCase):
def test_vert_flip_buffer(self):
noop = np.array([0, 0, 0, 0, 0, 0, 0], dtype=np.intc)
env0 = deepmind_lab.Lab(
'tests/render_test', ['RGB', 'RGB_INTERLEAVED'],
config={
'fps': '60',
'width': '512',
'height': '512',
'randomSeed': '1',
'vertFlipBuffer': '0',
})
env0.reset()
self.assertEqual(env0.step(noop, 1), 0)
image0 = np.transpose(env0.observations()['RGB'], (1, 2, 0))
env1 = deepmind_lab.Lab(
'tests/render_test', ['RGB', 'RGB_INTERLEAVED'],
config={
'fps': '60',
'width': '512',
'height': '512',
'randomSeed': '1',
'vertFlipBuffer': '1',
})
env1.reset()
self.assertEqual(env1.step(noop, 1), 0)
image1 = np.transpose(env1.observations()['RGB'], (1, 2, 0))
# Test skydome pixels.
np.testing.assert_array_equal(image1[0, 0], [150, 224, 255])
np.testing.assert_array_equal(image1[0, 511], [150, 224, 255])
np.testing.assert_array_equal(
image0, env0.observations()['RGB_INTERLEAVED'])
np.testing.assert_array_equal(
image1, env1.observations()['RGB_INTERLEAVED'])
# Delta between original and reversed flipped observations.
# Images won't be identical due to texture sampling and aliasing biases
# depending on the direction of rasterisation.
np.testing.assert_almost_equal(
np.average(abs(image0 - np.flipud(image1))) / 255, 0, decimal=2)
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/render_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class TeleporterTest(absltest.TestCase):
def test_movement(self):
fps = 60
env = deepmind_lab.Lab(
'tests/teleporter_test', [
'VEL.TRANS',
'DEBUG.POS.TRANS',
'DEBUG.POS.ROT',
],
config={
'fps': str(fps),
'width': '80',
'height': '80',
})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
env.reset()
vel = env.observations()['VEL.TRANS']
self.assertTrue(np.array_equal(vel, np.array([0, 0, 0])))
# Agent begins facing south
initial_facing = env.observations()['DEBUG.POS.ROT']
self.assertTrue(np.allclose(initial_facing, np.array([0, -90, 0]),
atol=0.1))
# Player moves straight ahead through the teleporter
action[action_index['MOVE_BACK_FORWARD']] = 1
self.assertEqual(env.events(), [])
for _ in six.moves.range(120):
p_before = env.observations()['DEBUG.POS.TRANS']
env.step(action, 1)
p_after = env.observations()['DEBUG.POS.TRANS']
if p_after[1] - p_before[1] > 100:
break
else:
self.fail('Failed to teleport')
self.assertEqual(env.events(), [('PLAYER_TELEPORTED', [])])
env.step(action, 1)
self.assertEqual(env.events(), [])
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/teleporter_test.py
|
# Copyright 2017-2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests for Adding extra Entities and their interaction with Bots."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class ExtraEntitiesWithBotsTest(absltest.TestCase):
def test_bot_with_spawned_weapon(self):
env = deepmind_lab.Lab(
'tests/extra_entities_with_bots_test', ['DEBUG.POS.TRANS'],
config={
'fps': '60',
'width': '32',
'height': '32',
'spawnWeapons': 'true'
})
noop = np.zeros([len(env.action_spec())], dtype=np.intc)
env.reset()
for _ in six.moves.range(6000):
env.step(noop, 1)
if [event for event in env.events() if event[0] == 'PLAYER_TAGGED']:
break
else:
self.fail('Failed to be tagged!')
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/extra_entities_with_bots_test.py
|
# Copyright 2017 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Basic test for the random Python agent."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import deepmind_lab
from python.tests.utils import math_utils
def DetectRed(screen):
red_count = (np.linalg.norm(screen.transpose([1, 2, 0])
- np.array([255, 0, 0]), axis=2) < 128).sum()
all_count = screen.shape[1] * screen.shape[2]
return float(red_count) / all_count > 0.01
class CustomViewTest(absltest.TestCase):
def test_LookRender(self):
env = deepmind_lab.Lab(
'tests/custom_view', ['RGB', 'RGB.LOOK_FORWARD', 'RGB.LOOK_BACK'],
config={
'fps': '60',
'width': '64',
'height': '64',
'debugCamera': 'false',
'maxAltCameraWidth': '128',
'maxAltCameraHeight': '128',
})
env.reset()
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
action = np.zeros([len(action_spec)], dtype=np.intc)
env.step(action)
player = env.observations()['RGB']
forward = env.observations()['RGB.LOOK_FORWARD']
back = env.observations()['RGB.LOOK_BACK']
self.assertEqual(player.shape, (3, 64, 64))
self.assertEqual(forward.shape, (3, 128, 128))
self.assertEqual(back.shape, (3, 128, 128))
self.assertTrue(DetectRed(player))
self.assertTrue(DetectRed(forward))
self.assertFalse(DetectRed(back))
current_angle = [0, 0]
target_angle = [180, 0]
look_speed = math_utils.calculate_speed(60, current_angle, target_angle, 8)
action[action_index['LOOK_LEFT_RIGHT_PIXELS_PER_FRAME']] = look_speed[0]
env.step(action, 8) # Turn 180 degrees.
player = env.observations()['RGB']
forward = env.observations()['RGB.LOOK_FORWARD']
back = env.observations()['RGB.LOOK_BACK']
self.assertFalse(DetectRed(player))
self.assertFalse(DetectRed(forward))
self.assertTrue(DetectRed(back))
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/custom_view_test.py
|
# Copyright 2018-2019 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import six
import deepmind_lab
def props_to_dictionary_recurse(env, key, result):
prefix_length = len(key) + 1 if key else 0
for sub_key, attribs in sorted(env.properties(key).items()):
next_key = sub_key[prefix_length:]
if attribs & deepmind_lab.LISTABLE == deepmind_lab.LISTABLE:
props_to_dictionary_recurse(env, sub_key, result.setdefault(next_key, {}))
elif attribs & deepmind_lab.READABLE == deepmind_lab.READABLE:
result[next_key] = env.read_property(sub_key)
elif attribs & deepmind_lab.WRITABLE == deepmind_lab.WRITABLE:
result[next_key] = '<write-only>'
def props_to_dictionary(env):
result = {}
props_to_dictionary_recurse(env, '', result)
return result
class Properties(absltest.TestCase):
def test_engine_properties(self):
env = deepmind_lab.Lab('tests/properties_test', [], config={'fps': '15'})
props = props_to_dictionary(env)
self.assertEqual(props['engine']['fps'], '15')
with self.assertRaises(TypeError) as context:
env.write_property('engine.fps', 'bar')
self.assertIn('\'engine.fps\' not writable.', str(context.exception))
# Check engine.notReachable wasn't registered.
self.assertNotIn('notReachable', props['engine'])
# Try and write to root engine list.
with self.assertRaises(TypeError) as context:
env.write_property('engine', 'foo')
self.assertIn('\'engine\' not writable.', str(context.exception))
def test_list_properties(self):
env = deepmind_lab.Lab('tests/properties_test', [], config={})
props = props_to_dictionary(env)
expected_params = {
'arg1': 'true',
'arg2': '19',
'arg3': 'hello',
'arrArgs': {
'1': 'arr1',
'2': 'arr2',
'3': 'arr3'
},
'subArgs': {
'sub1': 'val1',
'sub2': 'val2',
'sub3': 'val3'
}
}
self.assertEqual(props['params'], expected_params)
env.write_property('params.arrArgs.1', 'newarr1')
props = props_to_dictionary(env)
self.assertEqual(props['params']['arrArgs']['1'], 'newarr1')
env.write_property('params.arg1', 'false')
self.assertIsNotNone(props['func'])
self.assertIsNotNone(props['func']['times10'])
for i in six.moves.range(10):
self.assertEqual(env.read_property('func.times10.' + str(i)), str(i * 10))
def test_property_exceptions(self):
env = deepmind_lab.Lab('tests/properties_test', [], config={})
# Check works.
self.assertEqual(env.read_property('params.arg1'), 'true')
# Attempt to write to list.
with self.assertRaises(TypeError) as context:
env.write_property('params', 'val')
self.assertIn('\'params\' not writable.', str(context.exception))
# Attempt to write to missing.
with self.assertRaises(KeyError) as context:
env.write_property('unknown', 'val')
self.assertIn('\'unknown\' not found.', str(context.exception))
# Attempt to write wrong type.
with self.assertRaises(TypeError) as context:
env.write_property('params.arg1', 'not_bool')
self.assertIn('Type error! Cannot assign \'not_bool\' to \'params.arg1\'',
str(context.exception))
# Attempt to read list.
with self.assertRaises(TypeError) as context:
env.read_property('params')
self.assertIn('\'params\' not readable.', str(context.exception))
# Attempt to read missing.
with self.assertRaises(KeyError) as context:
env.read_property('unknown')
self.assertIn('\'unknown\' not found.', str(context.exception))
# Attempt to read wrong type.
with self.assertRaises(KeyError) as context:
env.read_property('func.times10.not_number')
self.assertIn('\'func.times10.not_number\' not found.',
str(context.exception))
# Attempt to list value.
with self.assertRaises(TypeError) as context:
env.properties('params.arg1')
self.assertIn('\'params.arg1\' not listable.', str(context.exception))
# Attempt to list to missing.
with self.assertRaises(KeyError) as context:
env.properties('unknown')
self.assertIn('\'unknown\' not found.', str(context.exception))
def test_properties_doors(self):
env = deepmind_lab.Lab(
'contributed/dmlab30/explore_obstructed_goals_small', [], config={})
self.assertEqual(env.read_property('params.episodeLengthSeconds'), '90')
env.reset(seed=4)
entity = ('***********\n'
'*** I P***\n'
'***H* PG***\n'
'*PPGIP ***\n'
'*GPP* PG***\n'
'*PGG*GGPI *\n'
'*H*H*H*H*H*\n'
'* *GPGIPPG*\n'
'* *GGP*PGP*\n'
'* IPPP*GPG*\n'
'***********\n')
variations = ('...........\n'
'.....AAA...\n'
'.....AAA...\n'
'.AAA.AAA...\n'
'.AAA.AAA...\n'
'.AAA.AAA...\n'
'...........\n'
'...AAA.AAA.\n'
'...AAA.AAA.\n'
'...AAA.AAA.\n'
'...........\n')
self.assertNotEqual(env.read_property('params.currentEntityLayer'), entity)
self.assertNotEqual(
env.read_property('params.currentVariationsLayer'), variations)
# Enable override:
env.write_property('params.overrideEntityLayer', entity)
env.write_property('params.overrideVariationsLayer', variations)
env.reset(seed=1)
self.assertEqual(env.read_property('params.currentEntityLayer'), entity)
self.assertEqual(
env.read_property('params.currentVariationsLayer'), variations)
env.reset(seed=2)
# Make sure override holds:
self.assertEqual(env.read_property('params.currentEntityLayer'), entity)
self.assertEqual(
env.read_property('params.currentVariationsLayer'), variations)
# Disable override
env.write_property('params.overrideEntityLayer', '')
env.write_property('params.overrideVariationsLayer', '')
env.reset(seed=3)
self.assertNotEqual(env.read_property('params.currentEntityLayer'), entity)
self.assertNotEqual(
env.read_property('params.currentVariationsLayer'), variations)
entity200 = env.read_property('func.entityLayer.200')
variations200 = env.read_property('func.variationsLayer.200')
entity400 = env.read_property('func.entityLayer.400')
variations400 = env.read_property('func.variationsLayer.400')
self.assertNotEqual(entity200, entity400)
self.assertNotEqual(variations200, variations400)
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/properties_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Game command tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
class GameCommandTest(absltest.TestCase):
def test_GameCommand(self):
env = deepmind_lab.Lab(
'tests/game_command_test', [],
config={'fps': '60'})
action_spec = env.action_spec()
action_index = {action['name']: i for i, action in enumerate(action_spec)}
self.assertIn('NEXT_GADGET', action_index)
action = np.zeros([len(action_spec)], dtype=np.intc)
env.reset()
action[action_index['NEXT_GADGET']] = 1
env.step(action)
events = env.events()
self.assertEqual(events[0][1][0], 'DISC')
action[action_index['NEXT_GADGET']] = 0
for _ in six.moves.range(100):
env.step(action)
events = env.events()
if events[0][1][0] == 'RAPID':
break
self.assertEqual(events[0][1][0], 'DISC')
else:
self.fail('Failed to switch gadget')
action[action_index['NEXT_GADGET']] = 1
env.step(action)
action[action_index['NEXT_GADGET']] = 0
for _ in six.moves.range(100):
env.step(action)
events = env.events()
if events[0][1][0] == 'BEAM':
break
self.assertEqual(events[0][1][0], 'RAPID')
else:
self.fail('Failed to switch gadget')
if __name__ == '__main__':
if os.environ.get('TEST_SRCDIR'):
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/game_command_test.py
|
"""Tests maze_game_controller."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
from python.tests.utils import maze_game_controller
from python.tests.utils import test_environment_decorator
class MazeGameControllerTest(absltest.TestCase):
def setUp(self):
self._env = test_environment_decorator.TestEnvironmentDecorator(
deepmind_lab.Lab('tests/maze_navigation_test',
maze_game_controller.REQUIRED_OBSERVATIONS))
self._controller = maze_game_controller.MazeGameController(self._env)
self._env.reset()
def testSpawnPosition(self):
pos = self._controller.maze_position()
self.assertTrue(np.array_equal(pos, [2, 3]))
def testMoveToReachablePos(self):
self.assertTrue(self._controller.move_to(2, 5))
pos = self._controller.maze_position()
self.assertTrue(np.array_equal(pos, [2, 5]))
def testMoveToUnreachablePos(self):
self.assertFalse(self._controller.move_to(20, 1))
self.assertFalse(self._controller.move_to(3, 4))
def testFollowPathToReachablePos(self):
path = self._controller.find_path(2, 5)
self.assertTrue(self._controller.follow_path(path))
pos = self._controller.maze_position()
self.assertTrue(np.array_equal(pos, [2, 5]))
def testFollowSparsePathToReachablePos(self):
self.assertTrue(self._controller.follow_path([(2, 5)]))
pos = self._controller.maze_position()
self.assertTrue(np.array_equal(pos, [2, 5]))
def testFollowPathToUneachablePos(self):
self.assertFalse(self._controller.follow_path([(20, 1)]))
def testFailToGoTrhoughBlockedCorridor(self):
self.assertFalse(self._controller.move_to(2, 5, blocked=[(1, 4)]))
def testPickupLocations(self):
self.assertTrue(np.array_equal(self._controller.pickup_location(0), [5, 1]))
self.assertTrue(np.array_equal(self._controller.pickup_location(1), [6, 1]))
self.assertTrue(np.array_equal(self._controller.pickup_location(2), [4, 3]))
def testPathExists(self):
path = self._controller.find_path(2, 5)
six.assertCountEqual(self, path, [(1, 3), (1, 4), (1, 5), (2, 5)])
def testPathDoesNotExist(self):
self.assertIsNone(self._controller.find_path(3, 4))
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/utils/maze_game_controller_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""A high level DM Lab controller class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import six
from python.tests.utils import math_utils
# Tolerance used when changing player orientation.
ROTATION_TOLERANCE = 2.
# Tolerance used when changing player position.
POSITION_TOLERANCE = 5.
_FPS = 60
_TURN_ACTION_NAME = 'LOOK_LEFT_RIGHT_PIXELS_PER_FRAME'
_MOVE_ACTION_NAME = 'MOVE_BACK_FORWARD'
_JUMP_ACTION_NAME = 'JUMP'
_NOOP_ACTION = np.array([0, 0, 0, 0, 0, 0, 0], dtype=np.intc)
_MIN_BRAKING_SPEED = 50.
_VELOCITY_TOLERANCE = 1e-08
_INTERNAL_ROTATION_TOLERANCE = ROTATION_TOLERANCE * .5
_INTERNAL_POSITION_TOLERANCE = POSITION_TOLERANCE * .7
_SLOW_MOVE_DISTANCE = 10.
class ControllerException(Exception):
"""Base class for all game controller exceptions."""
class EpisodeFinishedError(ControllerException):
"""Raised when an episode is finished while controller is running."""
class PathBlockedError(ControllerException):
"""Raised when player path is blocked."""
class GameController(object):
"""A high level game controller class.
The class allows interacting with DMLab environment using high level actions,
such as look at specific direction, move to specific coordinates etc.
"""
def __init__(self, env):
"""Initialize the controller."""
self._env = env
action_spec = env.action_spec()
self._action_index = {
action['name']: i
for i, action in enumerate(action_spec)
}
def look_at_2d(self, target_orientation, steps=10):
"""Rotate the player in horizontal plane towards the angle."""
delta_angle = math_utils.delta_angle_degrees(self.orientation[1],
target_orientation)
self.rotate(delta_angle, steps=steps)
def rotate(self, delta_angle, steps=10):
"""Rotate the player delta_angle degrees in horizontal plane."""
start = self.orientation
target = np.array([start[0], start[1] + delta_angle, 0.0])
speed = self._rotation_speed(delta_angle, steps=steps)
if np.abs(speed) < 1.:
return
actions = self._get_actions(_TURN_ACTION_NAME, speed)
error_message = ('Failed to reach requested orientation. Start: {0}, '
'target: {1}, current: {2}.')
for _ in six.moves.range(steps):
if self._env.is_running():
self._step(actions, 1)
else:
raise AssertionError(
error_message.format(start[1], target[1], self.orientation[1]))
if abs(math_utils.delta_angle_degrees(
self.orientation[1], target[1])) >= _INTERNAL_ROTATION_TOLERANCE:
if steps == 1:
raise AssertionError(
error_message.format(start[1], target[1], self.orientation[1]))
else:
self.rotate(
math_utils.delta_angle_degrees(self.orientation[1], target[1]),
steps=1)
def move_to(self,
target_x,
target_y,
max_steps=2000,
max_speed=None):
"""Move the player to the target location."""
pos = self.position
target = np.array([target_x, target_y, pos[2]])
if max_speed is None:
max_speed = float('inf')
direction = (target - pos)[:2]
last_pos = np.array([float('inf'), float('inf'), float('inf')])
target_orientation = np.degrees(np.arctan2(direction[1], direction[0]))
self.look_at_2d(target_orientation)
blocked_frames_count = 0
for _ in six.moves.range(max_steps):
move_action_value = 1
pos = self.position
direction = (target - pos)[:2]
distance = np.linalg.norm(direction)
speed = np.linalg.norm(self.velocity[:2])
if distance < _SLOW_MOVE_DISTANCE:
if speed > 0.0:
self.stop()
elif speed > max_speed:
move_action_value = 0
if distance < _INTERNAL_POSITION_TOLERANCE:
break
if np.linalg.norm(last_pos - pos) < .1:
blocked_frames_count += 1
if blocked_frames_count > 10:
raise PathBlockedError(
'Failed to reach target. The path might be blocked.')
else:
blocked_frames_count = 0
last_pos = pos
target_orientation = np.degrees(np.arctan2(direction[1], direction[0]))
rotation_speed = self._rotation_speed(
math_utils.delta_angle_degrees(self.orientation[1],
target_orientation),
steps=1)
actions = self._get_empty_actions()
self._set_action_value(actions, _TURN_ACTION_NAME, rotation_speed)
self._set_action_value(actions, _MOVE_ACTION_NAME, move_action_value)
self._step(actions, 1)
else:
raise AssertionError('Failed to reach target in max steps.')
def stop(self, max_steps=2000):
"""Stops the player as soon as possible."""
start_orientation = self.orientation[1]
for _ in six.moves.range(max_steps):
speed = np.linalg.norm(self.velocity[:2])
if speed < _VELOCITY_TOLERANCE and np.allclose(
self.rotation_velocity, [0.0, 0.0, 0.0],
atol=_VELOCITY_TOLERANCE):
break
if speed < _MIN_BRAKING_SPEED:
self._step(_NOOP_ACTION, 1)
else:
self.look_at_2d(
self.orientation[1] +
np.degrees(np.arctan2(self.velocity[1], self.velocity[0])),
steps=1)
self._step(self._get_actions(_MOVE_ACTION_NAME, -1), 1)
else:
raise AssertionError('Failed to stop in max steps.')
self.look_at_2d(start_orientation, steps=1)
def jump(self):
self._step(self._get_actions(_JUMP_ACTION_NAME, 1), 1)
self.stop()
def _step(self, actions, steps):
try:
return self._env.step(actions, steps)
except RuntimeError:
if self._env.is_running():
raise
else:
raise EpisodeFinishedError()
@property
def position(self):
return self._observations['DEBUG.POS.TRANS']
@property
def orientation(self):
return self._observations['DEBUG.POS.ROT']
@property
def velocity(self):
return self._observations['VEL.TRANS']
@property
def rotation_velocity(self):
return self._observations['VEL.ROT']
@property
def _observations(self):
try:
return self._env.observations()
except RuntimeError as e:
if self._env.is_running():
raise
else:
raise EpisodeFinishedError from e
def _get_empty_actions(self):
return np.zeros([len(self._action_index)], dtype=np.intc)
def _set_action_value(self, actions, action_name, action_value):
actions[self._action_index[action_name]] = action_value
def _get_actions(self, action_name, action_value):
actions = self._get_empty_actions()
self._set_action_value(actions, action_name, action_value)
return actions
def _rotation_speed(self, delta_angle, steps=10):
start = self.orientation
target = np.array([start[0], start[1] + delta_angle, 0.0])
if math_utils.angles_within_tolerance(self.orientation, target):
return 0.0
return math_utils.calculate_speed(_FPS, start, target, steps)[1]
|
lab-master
|
python/tests/utils/game_controller.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Utility methods for DMLab testing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
ROTATION_TOLERANCE = 1 # Degree
# Time dialiation works to make 60fps become exactly 16ms.
TIME_DIALATION = 0.96
# This is a natural speed to convert between mouse movement and screen
# rotation.
PIXELS_PER_FRAME_TO_DEG_PER_SECOND = 0.11 * 60
def calculate_angle(fps, rotation_speed, frames):
"""Calculates rotation angle achieved by applying the rotation_speed."""
time_seconds = TIME_DIALATION * frames / fps
angle = rotation_speed * time_seconds * PIXELS_PER_FRAME_TO_DEG_PER_SECOND
# Angles in the engine are converted to shorts to maintain determinism.
short = int(angle * (65536.0 / 360.0) + 0.5) % 65536
angle0_360 = short * 360.0 / 65536.0
# Return angle normalised to [-180, 180)
return angle0_360 if angle0_360 < 180 else angle0_360 - 360
def calculate_speed(fps, current_angle, target_angle, frames):
"""Calculates speed required to achieve the target angle."""
time_seconds = TIME_DIALATION * frames / fps
degrees_per_second = time_seconds * PIXELS_PER_FRAME_TO_DEG_PER_SECOND
return [(target_angle[0] - current_angle[0]) / degrees_per_second,
(current_angle[1] - target_angle[1]) / degrees_per_second]
def angles_within_tolerance(current_angle,
target_angle,
tolerance=ROTATION_TOLERANCE):
"""Tests whether two angles are within tolerance."""
return (
abs(delta_angle_degrees(current_angle[0], target_angle[0])) <= tolerance
and
abs(delta_angle_degrees(current_angle[1], target_angle[1])) <= tolerance)
def delta_angle_degrees(from_angle_degrees, to_angle_degrees):
"""Calculates the shortest signed delta angle."""
delta = to_angle_degrees - from_angle_degrees
return delta - 360.0 * math.floor((delta + 180.0) / 360.0)
|
lab-master
|
python/tests/utils/math_utils.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests for GameController."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import absltest
import numpy as np
import six
import deepmind_lab
from python.tests.utils import game_controller
from python.tests.utils import math_utils
from python.tests.utils import test_environment_decorator
_TEST_TRIALS = 5
class GameControllerTest(absltest.TestCase):
def setUp(self):
self._env = test_environment_decorator.TestEnvironmentDecorator(
deepmind_lab.Lab(
'seekavoid_arena_01',
['VEL.ROT', 'VEL.TRANS', 'DEBUG.POS.ROT', 'DEBUG.POS.TRANS']))
self._controller = game_controller.GameController(self._env)
self._env.reset()
def testLookAt(self):
target_angles = np.random.uniform(360, size=(_TEST_TRIALS))
for target_angle in target_angles:
self._controller.look_at_2d(target_angle)
delta = math_utils.delta_angle_degrees(self._controller.orientation[1],
target_angle)
self.assertLess(abs(delta), game_controller.ROTATION_TOLERANCE)
def testMoveTo(self):
targets = np.random.uniform(low=-100, high=100, size=(_TEST_TRIALS, 2))
for target in targets:
self._controller.move_to(target[0], target[1])
distance = np.linalg.norm(target - self._controller.position[0:2])
self.assertLess(distance, game_controller.POSITION_TOLERANCE)
def testStopping(self):
for angle in [0.0, 90., 180., -90]:
self._controller.look_at_2d(0.0)
move_forward_action = self._controller._get_actions(
game_controller._MOVE_ACTION_NAME, 1)
for _ in six.moves.range(10):
self._env.step(move_forward_action, 1)
self._controller.look_at_2d(angle)
num_steps_before_stopping = self._env.num_steps()
self._controller.stop()
num_steps_after_stopping = self._env.num_steps()
self.assertLess(num_steps_after_stopping - num_steps_before_stopping, 15)
delta = math_utils.delta_angle_degrees(self._controller.orientation[1],
angle)
self.assertLess(abs(delta), game_controller.ROTATION_TOLERANCE)
def testMovingSlowly(self):
self._controller.move_to(.0, .0)
start_steps = self._env.num_steps()
self._controller.move_to(100.0, .0)
steps_moving_fast = self._env.num_steps() - start_steps
start_steps = self._env.num_steps()
self._controller.move_to(.0, .0, max_speed=50.0)
self.assertLess(steps_moving_fast, self._env.num_steps() - start_steps)
def testControllerThrowsExceptionWhenBlocked(self):
self._controller.move_to(100.0, .0)
with self.assertRaises(game_controller.PathBlockedError):
self._controller.move_to(10000.0, .0)
def testControllerThrowsExceptionWhenEpisodeFinishes(self):
with self.assertRaises(game_controller.EpisodeFinishedError):
for _ in six.moves.range(1000):
self._controller.move_to(100.0, .0)
self._controller.move_to(0.0, .0)
if __name__ == '__main__':
if 'TEST_SRCDIR' in os.environ:
deepmind_lab.set_runfiles_path(
os.path.join(os.environ['TEST_SRCDIR'],
'org_deepmind_lab'))
absltest.main()
|
lab-master
|
python/tests/utils/game_controller_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests for math_utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from python.tests.utils import math_utils
class MathUtilsTest(absltest.TestCase):
def testDeltaAngleDegrees(self):
self.assertAlmostEqual(math_utils.delta_angle_degrees(10., 20.), 10.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(20., 10.), -10.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(10., 350.), -20.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(350., 10.), 20.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(350., 10.), 20.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(10., 190.), -180.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(190., 10.), -180.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(10., 195.), -175.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(195., 10.), 175.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(-350., -10.), -20.)
self.assertAlmostEqual(math_utils.delta_angle_degrees(-10., -350.), 20.)
def testAnglesWithinTolerance(self):
self.assertTrue(
math_utils.angles_within_tolerance(
[10., -20.], [10.5, -20.5], tolerance=1.))
self.assertTrue(
math_utils.angles_within_tolerance(
[10., 350], [-350.1, -9.6], tolerance=1.))
self.assertFalse(
math_utils.angles_within_tolerance(
[10., -20.], [11.5, -20.5], tolerance=1.))
self.assertFalse(
math_utils.angles_within_tolerance(
[10., -18.], [10.5, -20.5], tolerance=1.))
if __name__ == '__main__':
absltest.main()
|
lab-master
|
python/tests/utils/math_utils_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""An environment decorator with additional functions used for testing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from PIL import Image
_RGB_OBSERVATION_NAME = 'RGB_INTERLEAVED'
class TestEnvironmentDecorator(object):
"""A test environment decorator class.
This class provides additional functionality used for testing:
- Accumulating reward over multiple frames.
- Accumulating events over multiple frames.
- Collecting RGB observations and saving them to image files.
"""
def __init__(self, environment):
"""Initializes the decorator."""
self._environment = environment
self._rgb_history = []
self._frame_index = 0
self._events = []
self._reward_history = []
def step(self, actions, steps):
"""Advance the environment a number of steps."""
reward = self._environment.step(actions, steps)
observations = self._environment.observations()
self._save_current_frame()
self._accumulate_events(self._environment.events())
self._reward_history.append(reward)
return reward
def accumulated_reward(self):
"""Return the reward accumulated since the reset call."""
return np.sum(self._reward_history)
def reward_history(self):
"""Return the reward history accumulated since the reset call."""
return self._reward_history
def accumulated_events(self):
"""Return events accumulated since the reset call."""
return self._events
def is_running(self):
"""If the environment is in status RUNNING."""
return self._environment.is_running()
def observations(self):
"""Get the observations."""
return self._environment.observations()
def events(self):
"""Get the events."""
return self._environment.events()
def action_spec(self):
"""The shape of the actions."""
return self._environment.action_spec()
def observation_spec(self):
"""The shape of the observations."""
return self._environment.observation_spec()
def _find_observation_spec(self, name):
for spec in self._environment.observation_spec():
if name == spec['name']:
return spec
return None
def reset(self, **kwargs):
"""Reset the environment."""
result = self._environment.reset(**kwargs)
self._accumulated_reward = 0
self._events = []
self._accumulate_events(self._environment.events())
self._rgb_history = []
self._save_current_frame()
self._reward_history = []
return result
def _accumulate_events(self, events):
if events is not None:
self._events.append(events)
def save_frames(self, folder):
"""Save RGB_INTERLEAVED observations collacted since the last reset call."""
if not os.path.exists(folder):
os.makedirs(folder)
for index, image_data in enumerate(self._rgb_history):
image = Image.fromarray(np.uint8(image_data))
image.save(os.path.join(folder, 'frame{0}.png'.format(index)))
def num_steps(self):
"""Number of frames since the last reset() call."""
return self._environment.num_steps()
def _save_current_frame(self):
observations = self._environment.observations()
if _RGB_OBSERVATION_NAME in observations:
self._rgb_history.append(observations['RGB_INTERLEAVED'])
|
lab-master
|
python/tests/utils/test_environment_decorator.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Tests TestEnvironmentDecorator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
from absl.testing import absltest
import numpy as np
import six
from PIL import Image
from python.tests.utils import test_environment_decorator
_OBSERVATION_SPEC = [{'name': 'RGB_INTERLEAVED', 'shape': [1, 2, 3]}]
class EnvironmentStub(object):
def __init__(self):
self.test_observation_spec = _OBSERVATION_SPEC
self.test_observations = [
{
'RGB_INTERLEAVED':
np.array(
[[[255, 0, 0], [128, 0, 0], [0, 0, 255]],
[[0, 255, 0], [128, 0, 0], [0, 255, 0]]],
dtype=np.uint8)
},
{
'RGB_INTERLEAVED':
np.array([[[0, 255, 0], [0, 128, 0]]], dtype=np.uint8)
},
{
'RGB_INTERLEAVED':
np.array([[[0, 0, 255], [0, 0, 128]]], dtype=np.uint8)
},
]
self.test_rewards = [0, 1, 2, 3]
self._frame_index = 0
self.last_actions = None
self.last_steps = None
self.events_return = None
self.is_running_return = None
self.action_spec_return = None
self.reset_return = None
def step(self, actions, steps):
self.last_actions = actions
self.last_steps = steps
self._frame_index += 1
return self.test_rewards[self._frame_index - 1]
def is_running(self):
return self.is_running_return
def observations(self):
return self.test_observations[self._frame_index]
def events(self):
return self.events_return
def action_spec(self):
return self.action_spec_return
def observation_spec(self):
return self.test_observation_spec
def reset(self, **_):
self._frame_index = 0
return self.reset_return
def num_steps(self):
return self._frame_index
class TestEnvironmentDecoratorTest(absltest.TestCase):
def setUp(self):
self._env = EnvironmentStub()
self._decorator = test_environment_decorator.TestEnvironmentDecorator(
self._env)
def testStepIsCalled(self):
actions = object()
steps = 3
self.assertEqual(
self._decorator.step(actions, steps), self._env.test_rewards[0])
self.assertEqual(self._env.last_actions, actions)
self.assertEqual(self._env.last_steps, steps)
def testAccumulatedReward(self):
self._decorator.step(None, 1)
self._decorator.step(None, 1)
self.assertEqual(self._decorator.accumulated_reward(),
np.sum(self._env.test_rewards[0:2]))
def testResetAccumulatedReward(self):
self._decorator.step(None, 1)
self._decorator.reset()
self.assertEqual(self._decorator.accumulated_reward(), 0)
def testRewardHistory(self):
self._decorator.step(None, 1)
self._decorator.step(None, 1)
six.assertCountEqual(self,
self._decorator.reward_history(),
self._env.test_rewards[0:2])
def testResetRewardHistory(self):
self._decorator.step(None, 1)
self._decorator.reset()
six.assertCountEqual(self, self._decorator.reward_history(), [])
def testAccumulatedEvents(self):
events = ['event1', 'event2', 'event3']
self._env.events_return = events[0]
self._decorator.reset()
self._env.events_return = events[1]
self._decorator.step(None, 1)
self._env.events_return = events[2]
self._decorator.step(None, 1)
six.assertCountEqual(self, self._decorator.accumulated_events(), events)
def testResetAccumulatedEvents(self):
events = ['event1', 'event2']
self._env.events_return = events[0]
self._decorator.step(None, 1)
self._env.events_return = events[1]
self._decorator.reset()
six.assertCountEqual(self,
self._decorator.accumulated_events(), [events[1]])
def testObservationDelegation(self):
self.assertEqual(self._env.test_observations[0],
self._decorator.observations())
def testObservationSpecDelegation(self):
self.assertEqual(self._env.test_observation_spec,
self._decorator.observation_spec())
def testNumSteps(self):
self._decorator.reset()
self.assertEqual(self._decorator.num_steps(), 0)
self._decorator.step(None, None)
self.assertEqual(self._decorator.num_steps(), 1)
def testMethodDelegation(self):
method_names = ['is_running', 'events', 'action_spec', 'reset']
for name in method_names:
result = object()
setattr(self._env, name + '_return', result)
self.assertEqual(getattr(self._decorator, name)(), result)
def testSavingFrames(self):
self._decorator.reset()
self._decorator.step(None, 1)
self._decorator.step(None, 1)
temp_dir = tempfile.mkdtemp()
self._decorator.save_frames(temp_dir)
for index, observation in enumerate(self._env.test_observations):
expected_image = observation['RGB_INTERLEAVED']
image_file_name = os.path.join(temp_dir, 'frame{0}.png'.format(index))
image = np.asarray(Image.open(image_file_name))
self.assertTrue(np.array_equal(image, expected_image))
if __name__ == '__main__':
absltest.main()
|
lab-master
|
python/tests/utils/test_environment_decorator_test.py
|
# Copyright 2018 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""A high level DM Lab controller class for maze levels."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from python.tests.utils import game_controller
_MAZE_CELL_SIZE = 100.
_WALL_SYMBOL = '*'
_PICKUP_SYMBOL = 'O'
REQUIRED_OBSERVATIONS = [
'VEL.ROT', 'VEL.TRANS', 'DEBUG.POS.ROT', 'DEBUG.POS.TRANS',
'DEBUG.MAZE.LAYOUT'
]
def _create_distance_map(maze, from_x, from_y, to_x, to_y):
"""Return a distance map to position: x,y."""
if not (0 <= from_x < maze.shape[0] and 0 <= from_y < maze.shape[1]):
return None
if maze[from_x, from_y] != 0:
return None
# distance map contains -1 for unexplored cells and -2 for walls.
distance_map = -np.copy(maze) - 1
distance_map[from_x, from_y] = 0
to_explore = [(from_x, from_y)]
offsets = [[-1, 0], [1, 0], [0, -1], [0, 1]]
distance = 1
while to_explore:
next_explore = []
for pos in to_explore:
for (offset_x, offset_y) in offsets:
x = pos[0] + offset_x
y = pos[1] + offset_y
if (0 <= x < maze.shape[0] and 0 <= y < maze.shape[1] and
distance_map[x, y] == -1):
distance_map[x, y] = distance
if to_x == x and to_y == y:
return distance_map
else:
next_explore.append((x, y))
to_explore = next_explore
distance += 1
return None
def _find_path(maze, from_x, from_y, to_x, to_y):
"""Return a path from (from_x, from_y) to (to_x, to_y) or None."""
distance_map = _create_distance_map(maze, to_x, to_y, from_x, from_y)
if distance_map is None or distance_map[from_x, from_y] < 0:
return None
path = []
current_pos = [from_x, from_y]
distance = distance_map[current_pos[0], current_pos[1]]
offsets = [[-1, 0], [1, 0], [0, -1], [0, 1]]
while distance != 0:
for (offset_x, offset_y) in offsets:
x = current_pos[0] + offset_x
y = current_pos[1] + offset_y
if (0 <= x < maze.shape[0] and 0 <= y < maze.shape[1] and
distance_map[x, y] == distance - 1):
path.append((x, y))
current_pos = [x, y]
distance -= 1
break
return path
class MazeGameController(object):
"""A high level game controller class for maze levels.
The class allows navigating DMLab mazes using high level actions.
"""
def __init__(self, env):
"""Initialize the controller."""
self._env = env
self._controller = game_controller.GameController(env)
self._maze = None
self._pickup_locations = None
def maze_position(self):
"""Return location of the player in the maze."""
pos = self._env.observations()['DEBUG.POS.TRANS']
x, y = self._to_maze_coord(pos[0], pos[1])
return np.array([x, y])
def find_path(self, dest_x, dest_y, blocked=None):
"""Return path to the destination avoinding blocked cells."""
start = self.maze_position()
maze = self._get_maze()
if blocked is not None:
maze = np.copy(maze)
for (x, y) in blocked:
maze[x, y] = 1
path = _find_path(maze, start[0], start[1], dest_x, dest_y)
return path
def follow_path(self, path):
"""Move the player along the path."""
path = self._expand_path(path)
if not path:
return False
for (prev_x, prev_y), (x, y), (next_x, next_y) in zip(
path, path[1:], path[2:]):
if next_x - x != x - prev_x or next_y - y != y - prev_y:
world_x, world_y = self._to_world_coord(x, y)
self._controller.move_to(world_x, world_y)
(x, y) = path[-1]
world_x, world_y = self._to_world_coord(x, y)
self._controller.move_to(world_x, world_y)
return True
def _expand_path(self, path):
"""Return a new path that includes all intermediate steps."""
(last_x, last_y) = self.maze_position()
expanded_path = [(last_x, last_y)]
maze = self._get_maze()
for (x, y) in path:
if last_x != x or last_y != y:
local_path = _find_path(maze, last_x, last_y, x, y)
if local_path:
expanded_path += local_path
else:
return None
last_x, last_y = x, y
return expanded_path
def move_to(self, dest_x, dest_y, blocked=None):
"""Move the player to the destination avoiding blocked cells."""
path = self.find_path(dest_x, dest_y, blocked=blocked)
if path is None:
return False
elif self.follow_path(path):
return np.array_equal([dest_x, dest_y], self.maze_position())
else:
return False
def pickup_location(self, index):
"""Return location of a pickpup."""
locations = self._find_pickup_locations()
assert index >= 0 and index < len(locations)
return locations[index]
def _get_maze(self):
"""Return the current maze as a numpy array (0 - corridors, 1 - walls)."""
if self._maze is None:
maze_str = self._env.observations()['DEBUG.MAZE.LAYOUT'].strip()
lines = maze_str.split('\n')
height = len(lines)
width = 0
for line in lines:
width = max(width, len(line))
maze = np.zeros((width, height), dtype=np.int32)
for j, line in enumerate(lines):
for i, cell in enumerate(line):
if cell == _WALL_SYMBOL:
maze[i, j] = 1
self._maze = maze
return self._maze
def _to_world_coord(self, x, y):
"""Return x, y in the world space."""
maze = self._get_maze()
y = maze.shape[1] - y - 1
return (float(x) + .5) * _MAZE_CELL_SIZE, (float(y) + .5) * _MAZE_CELL_SIZE
def _to_maze_coord(self, x, y):
"""Return x, y in the maze space."""
maze = self._get_maze()
x = int(x / _MAZE_CELL_SIZE)
y = int(y / _MAZE_CELL_SIZE)
y = maze.shape[1] - y - 1
return x, y
def _find_pickup_locations(self):
"""Return locations of all pickups in the current maze."""
if self._pickup_locations is None:
maze_str = self._env.observations()['DEBUG.MAZE.LAYOUT'].strip()
lines = maze_str.split('\n')
self._pickup_locations = []
for j, line in enumerate(lines):
for i, cell in enumerate(line):
if cell == _PICKUP_SYMBOL:
self._pickup_locations.append((i, j))
return self._pickup_locations
|
lab-master
|
python/tests/utils/maze_game_controller.py
|
## Copyright (C) 2016-17 Google Inc.
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
################################################################################
"""A working example of deepmind_lab using python."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import pprint
import sys
import numpy as np
import six
import deepmind_lab
def run(level_script, config, num_episodes):
"""Construct and start the environment."""
env = deepmind_lab.Lab(level_script, ['RGB_INTERLEAVED'], config)
env.reset()
observation_spec = env.observation_spec()
print('Observation spec:')
pprint.pprint(observation_spec)
action_spec = env.action_spec()
print('Action spec:')
pprint.pprint(action_spec)
obs = env.observations() # dict of Numpy arrays
rgb_i = obs['RGB_INTERLEAVED']
print('Observation shape:', rgb_i.shape)
sys.stdout.flush()
# Create an action to move forwards.
action = np.zeros([7], dtype=np.intc)
action[3] = 1
score = 0
for _ in six.moves.range(num_episodes):
while env.is_running():
# Advance the environment 4 frames while executing the action.
reward = env.step(action, num_steps=4)
if reward != 0:
score += reward
print('Score =', score)
sys.stdout.flush()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-l', '--level_script', type=str,
default='seekavoid_arena_01',
help='The level that is to be played. Levels'
'are Lua scripts, and a script called \"name\" means that'
'a file \"assets/game_scripts/name.lua is loaded.')
parser.add_argument('-s', '--level_settings', type=str, default=[],
action='append',
help='Applies an opaque key-value setting. The setting is'
'available to the level script. This flag may be provided'
'multiple times. Universal settings are `width` and '
'`height` which give the screen size in pixels, '
'`fps` which gives the frames per second, and '
'`random_seed` which can be specified to ensure the '
'same content is generated on every run.')
parser.add_argument('--runfiles_path', type=str, default=None,
help='Set the runfiles path to find DeepMind Lab data')
parser.add_argument('--num_episodes', type=int, default=1,
help='The number of episodes to play.')
args = parser.parse_args()
# Convert list of level setting strings (of the form "key=value") into a
# `config` key/value dictionary.
config = {
k: v
for k, v in [six.ensure_str(s).split('=') for s in args.level_settings]
}
if args.runfiles_path:
deepmind_lab.set_runfiles_path(args.runfiles_path)
run(args.level_script, config, args.num_episodes)
|
lab-master
|
examples/game_main.py
|
#!/usr/bin/python
#
# 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.
"""Config file for SSL-HSIC experiment."""
from typing import Text
from absl import logging
from byol.utils import dataset
from jaxline import base_config
from ml_collections import config_dict
CONFIG = {
'default': (1000, 4096, '/tmp/ssl_hsic_final'),
'test': (0.00001, 3, '/tmp/ssl_hsic_final')
}
def get_config(config_key: Text = 'test') -> config_dict.ConfigDict:
"""Return config object, containing all hyperparameters for training."""
num_epochs, batch_size, save_dir = CONFIG[config_key]
train_images_per_epoch = dataset.Split.TRAIN_AND_VALID.num_examples
config = base_config.get_base_config()
config.experiment_kwargs = config_dict.ConfigDict(dict(
num_classes=1000,
batch_size=batch_size,
max_steps=int(num_epochs * train_images_per_epoch // batch_size),
enable_double_transpose=True,
base_target_ema=0.99,
ema_decay=0.999,
network_config=config_dict.ConfigDict(dict(
projector_hidden_size=4096,
projector_output_size=256,
predictor_hidden_size=4096,
encoder_class='ResNet50', # Should match a class in utils/networks.
encoder_config=config_dict.ConfigDict(dict(
resnet_v2=False,
width_multiplier=1)),
bn_config={
'decay_rate': .9,
'eps': 1e-5,
# Accumulate batchnorm statistics across devices.
# This should be equal to the `axis_name` argument passed
# to jax.pmap.
'cross_replica_axis': 'i',
'create_scale': True,
'create_offset': True,
})),
loss_config=config_dict.ConfigDict(dict(
num_rff_features=512,
regul_weight=3,
)),
optimizer_config=config_dict.ConfigDict(dict(
weight_decay=1e-6,
eta=1e-3,
momentum=.9,
)),
lr_schedule_config=dict(
base_learning_rate=0.4,
warmup_steps=10 * train_images_per_epoch // batch_size,
),
evaluation_config=config_dict.ConfigDict(dict(
subset='test',
batch_size=100,
)),
save_dir=save_dir, # Save the last checkpoint for evaluation.
))
config.checkpoint_dir = '/tmp/ssl_hsic'
config.train_checkpoint_all_hosts = False
config.training_steps = config.experiment_kwargs.max_steps
logging.info(config)
return config
|
ssl_hsic-main
|
ssl_hsic/config.py
|
#!/usr/bin/python
#
# 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 kernels."""
from absl.testing import absltest
from absl.testing import parameterized
from jax import numpy as jnp
from jax import random
from ssl_hsic import kernels
def inverse_multiquadratic(x, y, c):
dist = kernels.pairwise_distance_square(x, y)
return c / jnp.sqrt(dist + c ** 2)
def linear_kernel(x, y):
dist = jnp.matmul(x, jnp.transpose(y))
return dist
class KernelsTest(parameterized.TestCase):
@parameterized.parameters((8,), (128,), (4096,))
def test_get_label_weights(self, batch):
x = jnp.eye(batch)
k = linear_kernel(x, x)
h = jnp.eye(batch) - 1/batch
hkh = jnp.matmul(jnp.matmul(h, k), h)
expected_maximum = hkh.max()
expected_minimum = hkh.min()
maximium, minimum = kernels.get_label_weights(batch)
self.assertAlmostEqual(maximium, expected_maximum)
self.assertAlmostEqual(minimum, expected_minimum)
@parameterized.parameters((1, 1), (8, 1), (128, 1), (256, 1),
(1, 10), (8, 10), (128, 10), (256, 10),
(1, 0.1), (8, 0.1), (128, 0.1), (256, 0.1),)
def test_imq_rff_features(self, dim, c):
num_features = 512
rng = random.PRNGKey(42)
rng_x, rng_y, rng_rff = random.split(rng, 3)
amp, amp_probs = kernels.imq_amplitude_frequency_and_probs(dim)
x = random.uniform(rng_x, [1, dim])
x_rff = kernels.imq_rff_features(num_features, rng_rff, x, c, amp,
amp_probs)
y = random.uniform(rng_y, [1, dim])
y_rff = kernels.imq_rff_features(num_features, rng_rff, y, c, amp,
amp_probs)
expected = inverse_multiquadratic(x, y, c)
rff_approx = jnp.matmul(x_rff, y_rff.T)
self.assertAlmostEqual(rff_approx, expected, delta=0.1)
@parameterized.parameters((1, 1), (8, 1), (128, 1), (256, 1),
(1, 10), (8, 10), (128, 10), (256, 10),
(1, 0.1), (8, 0.1), (128, 0.1), (256, 0.1),)
def test_rff_approximate_hsic_xx(self, dim, c):
num_features = 512
rng = random.PRNGKey(42)
rng1, rng2, rng_x = random.split(rng, 3)
amp, amp_probs = kernels.imq_amplitude_frequency_and_probs(dim)
rff_kwargs = {'amp': amp, 'amp_probs': amp_probs}
x = random.uniform(rng_x, [1, dim])
k = inverse_multiquadratic(x, x, c)
k = k - jnp.mean(k, axis=1, keepdims=True)
hsic_xx = (k * k).mean()
hsic_xx_approx = kernels.rff_approximate_hsic_xx([x], num_features,
rng1, rng2, c, rff_kwargs)
self.assertEqual(hsic_xx_approx, hsic_xx)
if __name__ == '__main__':
absltest.main()
|
ssl_hsic-main
|
ssl_hsic/kernels_test.py
|
#!/usr/bin/python
#
# 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.
"""Config file for evaluation experiment."""
from typing import Text
from byol.utils import dataset
from jaxline import base_config
from ml_collections import config_dict
CONFIG = {
'default': (4096, '/tmp/ssl_hsic_final/checkpoint.npy'),
'test': (1, '/tmp/ssl_hsic_final/checkpoint.npy')
}
def get_config(config_key: Text = 'test') -> config_dict.ConfigDict:
"""Return config object for training."""
batch_size, checkpoint_to_evaluate = CONFIG[config_key]
train_images_per_epoch = dataset.Split.TRAIN_AND_VALID.num_examples
config = base_config.get_base_config()
config.experiment_kwargs = config_dict.ConfigDict(dict(
enable_double_transpose=True,
max_steps=90 * train_images_per_epoch // batch_size,
num_classes=1000,
ema_decay=0.999,
batch_size=batch_size,
checkpoint_to_evaluate=checkpoint_to_evaluate,
# If True, allows training without loading a checkpoint.
allow_train_from_scratch=False,
# Whether the backbone should be frozen (linear evaluation) or
# trainable (fine-tuning).
freeze_backbone=True,
optimizer_config=dict(
momentum=0.9,
nesterov=False,
),
lr_schedule_config=dict(
base_learning_rate=0.5,
warmup_steps=100,
),
network_config=dict( # Should match the evaluated checkpoint
encoder_class='ResNet50', # Should match a class in utils/networks.
encoder_config=dict(
resnet_v2=False,
width_multiplier=1),
bn_decay_rate=0.9,
),
evaluation_config=dict(
subset='test',
batch_size=100,
),
))
config.checkpoint_dir = '/tmp/ssl_hsic_eval'
config.train_checkpoint_all_hosts = False
config.training_steps = config.experiment_kwargs.max_steps
print(config)
return config
|
ssl_hsic-main
|
ssl_hsic/eval_config.py
|
#!/usr/bin/python
#
# 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.
"""SSL-HSIC pre-training."""
import functools
import os
from typing import Any, Generator, Mapping, NamedTuple, Optional, Text, Tuple
from absl import app
from absl import flags
from absl import logging
from acme.jax import utils as acme_utils
from byol.utils import augmentations
from byol.utils import dataset
from byol.utils import helpers as byol_helpers
from byol.utils import networks
from byol.utils import optimizers
from byol.utils import schedules
import haiku as hk
import jax
import jax.numpy as jnp
from jaxline import experiment
from jaxline import platform
from jaxline import utils as pipeline_utils
import numpy as np
import optax
from ssl_hsic import helpers
from ssl_hsic import kernels
import tensorflow as tf
# Type declarations.
LogsDict = Mapping[Text, jnp.ndarray]
class _ExperimentState(NamedTuple):
"""model and optimization parameters and state."""
online_params: hk.Params
target_params: hk.Params
online_state: hk.State
target_state: hk.State
kernel_params: hk.Params
kernel_opt_state: optax.OptState
opt_state: optimizers.LarsState
class _EMAState(NamedTuple):
"""EMA parameters and state."""
online_params: hk.Params
kernel_params: hk.Params
ema_params: hk.Params
ema_state: hk.State
class Experiment(experiment.AbstractExperiment):
"""Training and evaluation for SSL-HSIC experiment."""
# Holds a map from object properties that will be checkpointed to their name
# within a checkpoint. Currently it is assumed that these are all sharded
# device arrays.
CHECKPOINT_ATTRS = {
'_experiment_state': 'experiment_state',
'_ema_state': 'ema_state',
}
def __init__(
self,
mode: Text,
init_rng: jnp.DeviceArray,
num_classes: int,
batch_size: int,
max_steps: int,
enable_double_transpose: bool,
base_target_ema: float,
ema_decay: float,
network_config: Mapping[Text, Any],
loss_config: Mapping[Text, Any],
optimizer_config: Mapping[Text, Any],
lr_schedule_config: Mapping[Text, Any],
evaluation_config: Mapping[Text, Any],
save_dir: Optional[Text]):
"""Constructs the experiment.
Args:
mode: A string, equivalent to FLAGS.jaxline_mode when running normally.
init_rng: A `PRNGKey` to use for experiment initialization.
num_classes: the number of classes; used for the online evaluation.
batch_size: the total batch size; should be a multiple of the number of
available accelerators.
max_steps: the number of training steps; used for the lr/target network
ema schedules.
enable_double_transpose: see dataset.py; only has effect on TPU.
base_target_ema: the initial value for the ema decay rate of the target
network.
ema_decay: the ema decay rate for the model parameters.
network_config: the configuration for the network.
loss_config: the configuration for the SSL-HSIC loss.
optimizer_config: the configuration for the optimizer.
lr_schedule_config: the configuration for the learning rate schedule.
evaluation_config: the evaluation configuration.
save_dir: directory to save the last checkpoint if provided.
"""
super().__init__(mode, init_rng)
self._init_rng = init_rng
self._num_classes = num_classes
self._lr_schedule_config = lr_schedule_config
self._batch_size = batch_size
self._max_steps = max_steps
self._base_target_ema = base_target_ema
self._optimizer_config = optimizer_config
self._evaluation_config = evaluation_config
self._ema_decay = ema_decay
self._save_dir = save_dir
# Checkpointed experiment state.
self._experiment_state = None
self._ema_state = None
# Input pipelines.
self._train_input = None
self._eval_input = None
self._should_transpose_images = (
enable_double_transpose
and jax.local_devices()[0].platform == 'tpu')
# build the transformed ops
forward_fn = functools.partial(self._forward, **network_config)
self.forward = hk.without_apply_rng(hk.transform_with_state(forward_fn))
imq_amp, imq_amp_prob = kernels.imq_amplitude_frequency_and_probs(
network_config['projector_output_size'])
self._rff_kwargs = {'amp': imq_amp, 'amp_probs': imq_amp_prob}
self.kernel_loss_fn = hk.transform(
lambda *args: kernels.HSICLoss(**loss_config)(*args)) # pylint: disable=unnecessary-lambda
# EMA of parameters.
self.ema_update = hk.without_apply_rng(
hk.transform_with_state(self._apply_ema_update))
# training can handle multiple devices, thus the pmap
self.update_pmap = jax.pmap(self._update_fn, axis_name='i')
# evaluation can only handle single device
self.eval_batch_jit = jax.jit(self._eval_batch)
# Optimizer for kernel scale.
self.kernel_optimizer = optax.adam(3e-4, b1=0.9, b2=0.999, eps=1e-8)
def _apply_ema_update(self, params: hk.Params) -> hk.Params:
ema = jax.tree_map(
lambda x: hk.ExponentialMovingAverage(self._ema_decay),
params)
return jax.tree_multimap(lambda e, p: e(p), ema, params)
def _forward(
self,
inputs: dataset.Batch,
projector_hidden_size: int,
projector_output_size: int,
predictor_hidden_size: int,
encoder_class: Text,
encoder_config: Mapping[Text, Any],
bn_config: Mapping[Text, Any],
is_training: bool,
) -> Mapping[Text, jnp.ndarray]:
"""Forward application of architecture.
Args:
inputs: A batch of data, i.e. a dictionary, with either two keys,
(`images` and `labels`) or three keys (`view1`, `view2`, `labels`).
projector_hidden_size: hidden size of the projector MLP.
projector_output_size: output size of the projector and predictor MLPs.
predictor_hidden_size: hidden size of the predictor MLP.
encoder_class: type of the encoder (should match a class in
utils/networks).
encoder_config: passed to the encoder constructor.
bn_config: passed to the hk.BatchNorm constructors.
is_training: Training or evaluating the model? When True, inputs must
contain keys `view1` and `view2`. When False, inputs must contain key
`images`.
Returns:
All outputs of the model, i.e. a dictionary with projection, prediction
and logits keys, for either the two views, or the image.
"""
encoder = getattr(networks, encoder_class)
net = encoder(
num_classes=None, # Don't build the final linear layer
bn_config=bn_config,
**encoder_config)
projector = networks.MLP(
name='projector',
hidden_size=projector_hidden_size,
output_size=projector_output_size,
bn_config=bn_config)
predictor = networks.MLP(
name='predictor',
hidden_size=predictor_hidden_size,
output_size=projector_output_size,
bn_config=bn_config)
classifier = hk.Linear(
output_size=self._num_classes, name='classifier')
def apply_once_fn(images: jnp.ndarray, suffix: Text = ''):
images = dataset.normalize_images(images)
embedding = net(images, is_training=is_training)
proj_out = projector(embedding, is_training)
pred_out = predictor(proj_out, is_training)
# Note the stop_gradient: label information is not leaked into the
# main network.
classif_out = classifier(jax.lax.stop_gradient(embedding))
outputs = {}
outputs['projection' + suffix] = proj_out
outputs['prediction' + suffix] = pred_out
outputs['logits' + suffix] = classif_out
return outputs
if is_training:
outputs_view1 = apply_once_fn(inputs['view1'], '_view1')
outputs_view2 = apply_once_fn(inputs['view2'], '_view2')
return {**outputs_view1, **outputs_view2}
else:
return apply_once_fn(inputs['images'], '')
def _optimizer(self, learning_rate: float) -> optax.GradientTransformation:
"""Build optimizer from config."""
return optimizers.lars(
learning_rate,
weight_decay_filter=optimizers.exclude_bias_and_norm,
lars_adaptation_filter=optimizers.exclude_bias_and_norm,
**self._optimizer_config)
def loss_fn(
self,
online_params: hk.Params,
target_params: hk.Params,
kernel_params: hk.Params,
online_state: hk.State,
target_state: hk.Params,
rng: jnp.ndarray,
inputs: dataset.Batch,
) -> Tuple[jnp.ndarray, Tuple[Mapping[Text, hk.State], LogsDict]]:
"""Compute SSL-HSIC loss function.
Args:
online_params: parameters of the online network (the loss is later
differentiated with respect to the online parameters).
target_params: parameters of the target network.
kernel_params: parameters of the kernel loss.
online_state: internal state of online network.
target_state: internal state of target network.
rng: random number generator state.
inputs: inputs, containing two batches of crops from the same images,
view1 and view2 and labels
Returns:
SSL-HSIC loss, a mapping containing the online and target networks updated
states after processing inputs, and various logs.
"""
rng_aug, rng_hsic = jax.random.split(rng)
rff_kwargs = inputs['rff_kwargs']
if self._should_transpose_images:
inputs = dataset.transpose_images(inputs)
inputs = augmentations.postprocess(inputs, rng_aug)
labels = inputs['labels']
online_network_out, online_state = self.forward.apply(
params=online_params,
state=online_state,
inputs=inputs,
is_training=True)
target_network_out, target_state = self.forward.apply(
params=target_params,
state=target_state,
inputs=inputs,
is_training=True)
# Representation loss.
hiddens = [online_network_out['prediction_view1'],
online_network_out['prediction_view2'],
jax.lax.stop_gradient(target_network_out['projection_view2']),
jax.lax.stop_gradient(target_network_out['projection_view1'])]
hiddens = [byol_helpers.l2_normalize(h, axis=-1) for h in hiddens]
if jax.device_count() > 1:
feature_dim = hiddens[0].shape[-1]
hiddens = [
helpers.all_gather(h).reshape(-1, feature_dim) for h in hiddens
]
hsic_loss, summaries = self.kernel_loss_fn.apply(kernel_params, rng_hsic,
hiddens, rff_kwargs)
grad_norm_loss = -summaries['kernel_loss/grad_norm']
# Classification loss (with gradient flows stopped from flowing into the
# ResNet). This is used to provide an evaluation of the representation
# quality during training.
classif_loss = byol_helpers.softmax_cross_entropy(
logits=online_network_out['logits_view1'],
labels=jax.nn.one_hot(labels, self._num_classes))
top1_correct = byol_helpers.topk_accuracy(
online_network_out['logits_view1'],
inputs['labels'],
topk=1,
)
top5_correct = byol_helpers.topk_accuracy(
online_network_out['logits_view1'],
inputs['labels'],
topk=5,
)
top1_acc = jnp.mean(top1_correct)
top5_acc = jnp.mean(top5_correct)
classif_loss = jnp.mean(classif_loss)
loss = hsic_loss + grad_norm_loss + classif_loss
logs = dict(
loss=loss,
hsic_loss=hsic_loss,
grad_norm_loss=grad_norm_loss,
classif_loss=classif_loss,
top1_accuracy=top1_acc,
top5_accuracy=top5_acc,
**summaries,
)
return loss, (dict(online_state=online_state,
target_state=target_state), logs)
def _update_fn(
self,
experiment_state: _ExperimentState,
ema_state: _EMAState,
global_step: jnp.ndarray,
rng: jnp.ndarray,
inputs: dataset.Batch,
) -> Tuple[_ExperimentState, _EMAState, LogsDict]:
"""Update online and target parameters.
Args:
experiment_state: current network parameters and state.
ema_state: ema parameters and state.
global_step: current training step.
rng: current random number generator
inputs: inputs, containing two batches of crops from the same images,
view1 and view2 and labels
Returns:
Tuple containing the updated experiment state after processing the inputs,
EMA state after applying EMA update and various logs.
"""
online_params = experiment_state.online_params
target_params = experiment_state.target_params
online_state = experiment_state.online_state
target_state = experiment_state.target_state
opt_state = experiment_state.opt_state
kernel_params = experiment_state.kernel_params
kernel_opt_state = experiment_state.kernel_opt_state
# update online network
grad_fn = jax.grad(self.loss_fn, argnums=[0, 2], has_aux=True)
grads, (net_states, logs) = grad_fn(online_params, target_params,
kernel_params,
online_state, target_state,
rng, inputs)
# cross-device grad and logs reductions
grads = jax.tree_map(lambda v: jax.lax.pmean(v, axis_name='i'), grads)
logs = jax.tree_multimap(lambda x: jax.lax.pmean(x, axis_name='i'), logs)
learning_rate = schedules.learning_schedule(
global_step,
batch_size=self._batch_size,
total_steps=self._max_steps,
**self._lr_schedule_config)
grads, kernel_grads = grads
updates, opt_state = self._optimizer(learning_rate).update(
grads, opt_state, online_params)
online_params = optax.apply_updates(online_params, updates)
# update target network
tau = schedules.target_ema(
global_step,
base_ema=self._base_target_ema,
max_steps=self._max_steps)
target_params = jax.tree_multimap(lambda x, y: x + (1 - tau) * (y - x),
target_params, online_params)
logs['tau'] = tau
logs['learning_rate'] = learning_rate
# Update kernel parameters.
kernel_updates, kernel_opt_state = self.kernel_optimizer.update(
kernel_grads, kernel_opt_state)
kernel_params = optax.apply_updates(kernel_params, kernel_updates)
# Update EMA parameters.
(ema_online_params,
ema_kernel_params), ema_module_state = self.ema_update.apply(
ema_state.ema_params, ema_state.ema_state,
[online_params, kernel_params])
ema_state = _EMAState(
online_params=ema_online_params,
kernel_params=ema_kernel_params,
ema_params=ema_state.ema_params,
ema_state=ema_module_state)
return _ExperimentState(
online_params=online_params,
target_params=target_params,
online_state=net_states['online_state'],
target_state=net_states['target_state'],
opt_state=opt_state,
kernel_params=kernel_params,
kernel_opt_state=kernel_opt_state), ema_state, logs
def _make_initial_state(
self,
rng: jnp.ndarray,
dummy_input: dataset.Batch,
) -> Tuple[_ExperimentState, _EMAState]:
"""Initializate the experiment state and EMA state.
Args:
rng: random number generator used to initialize parameters. If working in
a multi device setup, this need to be a ShardedArray.
dummy_input: a dummy image, used to compute intermediate outputs shapes.
Returns:
Initial experiment state and EMA state.
"""
rng_online, rng_target, rng_kernel, rng_ema = jax.random.split(rng, 4)
if self._should_transpose_images:
dummy_input = dataset.transpose_images(dummy_input)
# Online and target parameters are initialized using different rngs,
# in our experiments we did not notice a significant different with using
# the same rng for both.
online_params, online_state = self.forward.init(
rng_online,
dummy_input,
is_training=True,
)
target_params, target_state = self.forward.init(
rng_target,
dummy_input,
is_training=True,
)
opt_state = self._optimizer(0).init(online_params)
out, _ = self.forward.apply(online_params, online_state, dummy_input,
is_training=True)
# Init kernel loss. It doesn't matter which hiddens to take.
hiddens = [
out['prediction_view1'], out['prediction_view2']
]
kernel_params = self.kernel_loss_fn.init(rng_kernel, hiddens,
dummy_input['rff_kwargs'])
kernel_opt_state = self.kernel_optimizer.init(kernel_params)
ema_module_params, ema_module_state = self.ema_update.init(
rng_ema, [online_params, kernel_params])
(ema_online_params,
ema_kernel_params), ema_module_state = self.ema_update.apply(
ema_module_params, ema_module_state, [online_params, kernel_params])
ema_state = _EMAState(
online_params=ema_online_params,
kernel_params=ema_kernel_params,
ema_params=ema_module_params,
ema_state=ema_module_state)
return _ExperimentState(
online_params=online_params,
target_params=target_params,
opt_state=opt_state,
online_state=online_state,
target_state=target_state,
kernel_params=kernel_params,
kernel_opt_state=kernel_opt_state,
), ema_state
def step(self, *,
global_step: jnp.ndarray,
rng: jnp.ndarray, **unused_kwargs) -> Mapping[Text, np.ndarray]:
"""Performs a single training step."""
if self._train_input is None:
self._initialize_train()
inputs = next(self._train_input)
self._experiment_state, self._ema_state, scalars = self.update_pmap(
self._experiment_state,
self._ema_state,
global_step=global_step,
rng=rng,
inputs=inputs,
)
if self._save_dir and (jax.host_id() == 0):
global_step_value = pipeline_utils.get_first(global_step)
if global_step_value == self._max_steps - 1:
f_np = lambda x: np.array(jax.device_get(pipeline_utils.get_first(x)))
np_experiment_state = jax.tree_map(f_np, self._experiment_state)
np_ema_state = jax.tree_map(f_np, self._ema_state)
path_npy = os.path.join(self._save_dir, 'checkpoint.npy')
with tf.io.gfile.GFile(path_npy, 'wb') as fp:
np.save(fp, {'experiment_state': np_experiment_state._asdict(),
'ema_state': np_ema_state._asdict()})
logging.info('Saved final checkpoint at %s', path_npy)
return pipeline_utils.get_first(scalars)
def _initialize_train(self):
"""Initialize for training."""
self._train_input = acme_utils.prefetch(self._build_train_input())
# Check we haven't already restored params
if self._experiment_state is None:
logging.info(
'Initializing parameters rather than restoring from checkpoint.')
# initialize parameters, ema parameters and setup optimizer state
inputs = next(self._train_input)
init_fn = jax.pmap(self._make_initial_state, axis_name='i')
# Init uses the same RNG key on all hosts+devices to ensure everyone
# computes the same initial state and parameters.
init_rng = byol_helpers.bcast_local_devices(self._init_rng)
self._experiment_state, self._ema_state = init_fn(rng=init_rng,
dummy_input=inputs)
def _build_train_input(self) -> Generator[dataset.Batch, None, None]:
"""Loads the (infinitely looping) dataset iterator."""
num_devices = jax.device_count()
global_batch_size = self._batch_size
per_device_batch_size, ragged = divmod(global_batch_size, num_devices)
if ragged:
raise ValueError(
f'Global batch size {global_batch_size} must be divisible by '
f'num devices {num_devices}')
ds_numpy = dataset.load(
dataset.Split.TRAIN_AND_VALID,
preprocess_mode=dataset.PreprocessMode.PRETRAIN,
transpose=self._should_transpose_images,
batch_dims=[jax.local_device_count(), per_device_batch_size])
# Add rff_kwargs to dataset, so that we don't build it as constant in the
# graph.
for inputs in ds_numpy:
# pytype: disable=unsupported-operands
inputs['rff_kwargs'] = jax.tree_map(
lambda x: np.tile(x, (jax.local_device_count(), 1)), self._rff_kwargs)
yield inputs
def _eval_batch(
self,
params: hk.Params,
state: hk.State,
batch: dataset.Batch,
) -> Mapping[Text, jnp.ndarray]:
"""Evaluates a batch.
Args:
params: Parameters of the model to evaluate. Typically EMA parameters.
state: State of the model to evaluate. Typically online state.
batch: Batch of data to evaluate (must contain keys images and labels).
Returns:
Unreduced evaluation loss and top1 accuracy on the batch.
"""
if self._should_transpose_images:
batch = dataset.transpose_images(batch)
outputs, _ = self.forward.apply(params, state, batch, is_training=False)
logits = outputs['logits']
labels = hk.one_hot(batch['labels'], self._num_classes)
loss = byol_helpers.softmax_cross_entropy(logits, labels, reduction=None)
top1_correct = byol_helpers.topk_accuracy(logits, batch['labels'], topk=1)
top5_correct = byol_helpers.topk_accuracy(logits, batch['labels'], topk=5)
# NOTE: Returned values will be summed and finally divided by num_samples.
return {
'eval_loss': loss,
'top1_accuracy': top1_correct,
'top5_accuracy': top5_correct,
}
def _eval_epoch(self, subset: Text, batch_size: int):
"""Evaluates an epoch."""
num_samples = 0.
summed_scalars = None
params = pipeline_utils.get_first(self._ema_state.online_params)
state = pipeline_utils.get_first(self._experiment_state.online_state)
split = dataset.Split.from_string(subset)
dataset_iterator = dataset.load(
split,
preprocess_mode=dataset.PreprocessMode.EVAL,
transpose=self._should_transpose_images,
batch_dims=[batch_size])
for inputs in dataset_iterator:
num_samples += inputs['labels'].shape[0]
scalars = self.eval_batch_jit(params, state, inputs)
# Accumulate the sum of scalars for each step.
scalars = jax.tree_map(lambda x: jnp.sum(x, axis=0), scalars)
if summed_scalars is None:
summed_scalars = scalars
else:
summed_scalars = jax.tree_multimap(jnp.add, summed_scalars, scalars)
mean_scalars = jax.tree_map(lambda x: x / num_samples, summed_scalars)
return mean_scalars
def evaluate(self, global_step: jnp.ndarray, **unused_args):
"""Thin wrapper around _eval_epoch."""
global_step = np.array(pipeline_utils.get_first(global_step))
scalars = jax.device_get(self._eval_epoch(**self._evaluation_config))
logging.info('[Step %d] Eval scalars: %s', global_step, scalars)
return scalars
if __name__ == '__main__':
flags.mark_flag_as_required('config')
app.run(functools.partial(platform.main, Experiment))
|
ssl_hsic-main
|
ssl_hsic/experiment.py
|
#!/usr/bin/python
#
# 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.
"""Helpers for computing SSL-HSIC losses."""
import functools
from typing import Any, Dict, List, Optional, Text, Tuple
import haiku as hk
import jax
import jax.numpy as jnp
import mpmath
import numpy as np
def pairwise_distance_square(x: jnp.ndarray,
y: jnp.ndarray, maximum=1e10) -> jnp.ndarray:
"""Computes the square of pairwise distances.
dist_ij = (x[i] - y[j])'(x[i] - y[j])
= x[i]'x[i] - 2x[i]'y[j] + y[j]'y[j]
dist = x.x_{ij,ik->i} - 2 x.y_{ik,jk->ij} + y.y_{ij,ik->i}
Args:
x: tf.Tensor [B1, d].
y: tf.Tensor [B2, d]. If y is None, then y=x.
maximum: the maximum value to avoid overflow.
Returns:
Pairwise distance matrix [B1, B2].
"""
x_sq = jnp.einsum('ij,ij->i', x, x)[:, jnp.newaxis]
y_sq = jnp.einsum('ij,ij->i', y, y)[jnp.newaxis, :]
x_y = jnp.einsum('ik,jk->ij', x, y)
dist = x_sq + y_sq - 2 * x_y
# Safe in case dist becomes negative.
return jnp.minimum(jnp.maximum(dist, 0.0), maximum)
def get_label_weights(batch: int) -> Tuple[float, float]:
"""Returns the positive and negative weights of the label kernel matrix."""
w_pos_base = jnp.atleast_2d(1.0)
w_neg_base = jnp.atleast_2d(0.0)
w_mean = (w_pos_base + w_neg_base * (batch - 1)) / batch
w_pos_base -= w_mean
w_neg_base -= w_mean
w_mean = (w_pos_base + w_neg_base * (batch - 1)) / batch
w_pos = w_pos_base - w_mean
w_neg = w_neg_base - w_mean
return w_pos[0, 0], w_neg[0, 0]
def compute_prob(n: int, x_range: np.ndarray) -> np.ndarray:
"""Compute the probablity to sample the random fourier features."""
probs = [mpmath.besselk((n - 1) / 2, x) * mpmath.power(x, (n - 1) / 2)
for x in x_range]
normalized_probs = [float(p / sum(probs)) for p in probs]
return np.array(normalized_probs)
def imq_amplitude_frequency_and_probs(n: int) -> Tuple[np.ndarray, np.ndarray]:
"""Returns the range and probablity for sampling RFF."""
x = np.linspace(1e-12, 100, 10000) # int(n * 10 / c)
p = compute_prob(n, x)
return x, p
def imq_rff_features(num_features: int, rng: jnp.DeviceArray, x: jnp.ndarray,
c: float, amp: jnp.ndarray,
amp_probs: jnp.ndarray) -> jnp.ndarray:
"""Returns the RFF feature for IMQ kernel with pre-computed amplitude prob."""
d = x.shape[-1]
rng1, rng2 = jax.random.split(rng)
amp = jax.random.choice(rng1, amp, shape=[num_features, 1], p=amp_probs)
directions = jax.random.normal(rng2, shape=(num_features, d))
b = jax.random.uniform(rng2, shape=(1, num_features)) * 2 * jnp.pi
w = directions / jnp.linalg.norm(directions, axis=-1, keepdims=True) * amp
z_x = jnp.sqrt(2 / num_features) * jnp.cos(jnp.matmul(x / c, w.T) + b)
return z_x
def rff_approximate_hsic_xy(list_hiddens: List[jnp.ndarray], w: float,
num_features: int, rng: jnp.DeviceArray, c: float,
rff_kwargs: Dict[Text, jnp.ndarray]) -> jnp.ndarray:
"""RFF approximation of Unbiased HSIC(X, Y).
Args:
list_hiddens: a list of features.
w: difference between max and min of the label Y's gram matrix.
num_features: number of RFF features used for the approximation.
rng: random seed used for sampling RFF features of the hiddens.
c: parameter of the inverse multiquadric kernel.
rff_kwargs: keyword arguments used for sampling frequencies.
Returns:
Approximation of HSIC(X, Y) where the kernel is inverse multiquadric kernel.
"""
b, _ = list_hiddens[0].shape
k = len(list_hiddens)
rff_hiddens = jnp.zeros((b, num_features))
mean = jnp.zeros((1, num_features))
n_square = (b * k) ** 2
for hidden in list_hiddens:
rff_features = imq_rff_features(num_features, rng, hidden, c, **rff_kwargs)
rff_hiddens += rff_features
mean += rff_features.sum(0, keepdims=True)
return w * ((rff_hiddens**2).sum() / (b * k * (k - 1)) -
(mean**2).sum() / n_square)
def rff_approximate_hsic_xx(
list_hiddens: List[jnp.ndarray], num_features: int, rng: jnp.DeviceArray,
rng_used: jnp.DeviceArray, c: float, rff_kwargs: Dict[Text, jnp.ndarray]
) -> jnp.ndarray:
"""RFF approximation of HSIC(X, X) where inverse multiquadric kernel is used.
Args:
list_hiddens: a list of features.
num_features: number of RFF features used for the approximation.
rng: random seed used for sampling the first RFF features.
rng_used: random seed used for sampling the second RFF features.
c: parameter of the inverse multiquadric kernel.
rff_kwargs: keyword arguments used for sampling frequencies.
Returns:
Approximation of HSIC(X, X) where the kernel is inverse multiquadric kernel.
"""
x1_rffs = []
x2_rffs = []
for xs in list_hiddens:
x1_rff = imq_rff_features(num_features, rng_used, xs, c, **rff_kwargs)
x1_rffs.append(x1_rff)
x2_rff = imq_rff_features(num_features, rng, xs, c, **rff_kwargs)
x2_rffs.append(x2_rff)
mean_x1 = (functools.reduce(jax.lax.add, x1_rffs) / len(x1_rffs)).mean(
0, keepdims=True)
mean_x2 = (functools.reduce(jax.lax.add, x2_rffs) / len(x2_rffs)).mean(
0, keepdims=True)
z = jnp.zeros(shape=(num_features, num_features), dtype=jnp.float32)
for x1_rff, x2_rff in zip(x1_rffs, x2_rffs):
z += jnp.einsum('ni,nj->ij', x1_rff - mean_x1, x2_rff - mean_x2)
return (z ** 2).sum() / ((x1_rff.shape[0] * len(list_hiddens)) ** 2)
class HSICLoss(hk.Module):
"""SSL-HSIC loss."""
def __init__(self,
num_rff_features: int,
regul_weight: float,
name: Optional[Text] = 'hsic_loss'):
"""Initialize HSICLoss.
Args:
num_rff_features: number of RFF features used for the approximation.
regul_weight: regularization weight applied for HSIC(X, X).
name: name of the module, optional.
"""
super().__init__(name=name)
self._num_rff_features = num_rff_features
self._regul_weight = regul_weight
def __call__(
self, list_hiddens: List[jnp.ndarray],
rff_kwargs: Optional[Dict[Text, Any]]
) -> Tuple[jnp.ndarray, Dict[Text, jnp.ndarray]]:
"""Returns the HSIC loss and summaries.
Args:
list_hiddens: list of hiddens from different views.
rff_kwargs: keyword args for sampling frequencies to compute RFF.
Returns:
total loss and a dictionary of summaries.
"""
b = list_hiddens[0].shape[0]
scale = hk.get_parameter('scale', shape=[], dtype=jnp.float32,
init=hk.initializers.Constant(1.))
c = jax.lax.stop_gradient(scale)
rff_kwargs = rff_kwargs or {}
w_pos, w_neg = get_label_weights(b)
rng1, rng2 = jax.random.split(hk.next_rng_key())
hsic_xy = rff_approximate_hsic_xy(list_hiddens, w_pos - w_neg,
self._num_rff_features, rng1, c,
rff_kwargs=rff_kwargs)
hsic_xx = rff_approximate_hsic_xx(list_hiddens, self._num_rff_features,
rng1, rng2, c, rff_kwargs)
total_loss = self._regul_weight * jnp.sqrt(hsic_xx) - hsic_xy
# Compute gradient norm.
n_samples = int(1024 / len(list_hiddens)) # 1024 samples in total.
sampled_hiddens_1 = jnp.concatenate([
x[jax.random.choice(hk.next_rng_key(), jnp.arange(b), (n_samples,)), :]
for x in list_hiddens
])
sampled_hiddens_2 = jnp.concatenate([
x[jax.random.choice(hk.next_rng_key(), jnp.arange(b), (n_samples,)), :]
for x in list_hiddens
])
dist_sq = jax.lax.stop_gradient(
pairwise_distance_square(sampled_hiddens_1, sampled_hiddens_2))
grad = jax.grad(lambda x, y: (y / jnp.sqrt(x + y**2)).sum())(dist_sq, scale)
grad_norm = 0.5 * jnp.log(jnp.maximum(1e-14, grad ** 2)).mean()
summaries = {'kernel_loss/hsic_xy': hsic_xy,
'kernel_loss/hsic_xx': hsic_xx,
'kernel_loss/total_loss': total_loss,
'kernel_loss/kernel_param': scale,
'kernel_loss/grad_norm': grad_norm}
return total_loss, summaries
|
ssl_hsic-main
|
ssl_hsic/kernels.py
|
#!/usr/bin/python
#
# 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.
"""Helper functions for the experiments."""
import functools
import jax
from jax import numpy as jnp
def all_gather(value: jnp.ndarray) -> jnp.ndarray:
"""All-gather implementation with gradient.
Args:
value: the jnp.array to gather from all devices.
Returns:
[replica, *shape] jnp.array
"""
num_devices = jax.device_count()
bcast_shape = (num_devices,) + value.shape
# Broadcast the value to the shape.
value_bcasted = jnp.broadcast_to(value, bcast_shape)
def all_to_all(x, concat_axis, split_axis):
"""Wrap the inner custom_gradient because it doesn't like non-array."""
@jax.custom_gradient
def _all_to_all(x):
"""Inner member that returns all-to-all and grad op."""
# convenience shorten
a2a = functools.partial(jax.lax.all_to_all, axis_name="i")
def grad_fn(g):
"""Derivative of all_to_all is just concat and split axis swap."""
return (a2a(g, split_axis=concat_axis,
concat_axis=split_axis),)
# All-to-all is the closest op to all-gather within XLA.
# returns a tuple of forward outputs and a backward fn.
return a2a(x, split_axis=split_axis,
concat_axis=concat_axis), grad_fn
return _all_to_all(x)
# return the inner gradient function
return all_to_all(value_bcasted, concat_axis=0, split_axis=0)
|
ssl_hsic-main
|
ssl_hsic/helpers.py
|
#!/usr/bin/python
#
# 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.
"""Linear evaluation or fine-tuning pipeline.
Use this experiment to evaluate a checkpoint from experiment.py
"""
import functools
from typing import Any, Generator, Mapping, NamedTuple, Optional, Text, Tuple
from absl import app
from absl import flags
from absl import logging
from acme.jax import utils as acme_utils
from byol.utils import dataset
from byol.utils import helpers
from byol.utils import networks
from byol.utils import schedules
import haiku as hk
import jax
import jax.numpy as jnp
from jaxline import experiment
from jaxline import platform
import numpy as np
import optax
import tensorflow as tf
# Type declarations.
OptState = Tuple[optax.TraceState, optax.ScaleByScheduleState, optax.ScaleState]
LogsDict = Mapping[Text, jnp.ndarray]
class _EvalExperimentState(NamedTuple):
backbone_params: hk.Params
classif_params: hk.Params
ema_classif_params: hk.Params
backbone_state: hk.State
classif_opt_state: OptState
ema_module_params: hk.Params
ema_state: hk.State
ema_backbone_params: Optional[hk.Params] = None
backbone_opt_state: Optional[OptState] = None
class EvalExperiment(experiment.AbstractExperiment):
"""Linear evaluation experiment."""
# Holds a map from object properties that will be checkpointed to their name
# within a checkpoint. Currently it is assumed that these are all sharded
# device arrays.
CHECKPOINT_ATTRS = {
'_experiment_state': 'experiment_state',
}
def __init__(
self,
mode: Text,
init_rng: jnp.DeviceArray,
num_classes: int,
batch_size: int,
max_steps: int,
ema_decay: float,
enable_double_transpose: bool,
checkpoint_to_evaluate: Optional[Text],
allow_train_from_scratch: bool,
freeze_backbone: bool,
network_config: Mapping[Text, Any],
optimizer_config: Mapping[Text, Any],
lr_schedule_config: Mapping[Text, Any],
evaluation_config: Mapping[Text, Any]):
"""Constructs the experiment.
Args:
mode: A string, equivalent to FLAGS.jaxline_mode when running normally.
init_rng: A `PRNGKey` to use for experiment initialization.
num_classes: the number of classes; used for the online evaluation.
batch_size: the total batch size; should be a multiple of the number of
available accelerators.
max_steps: the number of training steps; used for the lr/target network
ema schedules.
ema_decay: the ema decay rate for the model parameters.
enable_double_transpose: see dataset.py; only has effect on TPU.
checkpoint_to_evaluate: the path to the checkpoint to evaluate.
allow_train_from_scratch: whether to allow training without specifying a
checkpoint to evaluate (training from scratch).
freeze_backbone: whether the backbone resnet should remain frozen (linear
evaluation) or be trainable (fine-tuning).
network_config: the configuration for the network.
optimizer_config: the configuration for the optimizer.
lr_schedule_config: the configuration for the learning rate schedule.
evaluation_config: the evaluation configuration.
"""
super().__init__(mode, init_rng)
self._init_rng = init_rng
self._num_classes = num_classes
self._lr_schedule_config = lr_schedule_config
self._batch_size = batch_size
self._max_steps = max_steps
self._checkpoint_to_evaluate = checkpoint_to_evaluate
self._allow_train_from_scratch = allow_train_from_scratch
self._freeze_backbone = freeze_backbone
self._optimizer_config = optimizer_config
self._evaluation_config = evaluation_config
self._ema_decay = ema_decay
# Checkpointed experiment state.
self._experiment_state = None
# Input pipelines.
self._train_input = None
self._eval_input = None
backbone_fn = functools.partial(self._backbone_fn, **network_config)
self.forward_backbone = hk.without_apply_rng(
hk.transform_with_state(backbone_fn))
self.forward_classif = hk.without_apply_rng(hk.transform(self._classif_fn))
self.update_pmap = jax.pmap(self._update_func, axis_name='i')
self.eval_batch_jit = jax.jit(self._eval_batch)
self._is_backbone_training = not self._freeze_backbone
self._should_transpose_images = (enable_double_transpose and
jax.local_devices()[0].platform == 'tpu')
self.ema_update = hk.without_apply_rng(
hk.transform_with_state(self._apply_ema_update))
def _apply_ema_update(self, params: hk.Params) -> hk.Params:
ema = jax.tree_map(
lambda x: hk.ExponentialMovingAverage(self._ema_decay),
params)
return jax.tree_multimap(lambda e, p: e(p), ema, params)
def _backbone_fn(
self,
inputs: dataset.Batch,
encoder_class: Text,
encoder_config: Mapping[Text, Any],
bn_decay_rate: float,
is_training: bool,
) -> jnp.ndarray:
"""Forward of the encoder (backbone)."""
bn_config = {'decay_rate': bn_decay_rate}
encoder = getattr(networks, encoder_class)
model = encoder(
None,
bn_config=bn_config,
**encoder_config)
if self._should_transpose_images:
inputs = dataset.transpose_images(inputs)
images = dataset.normalize_images(inputs['images'])
return model(images, is_training=is_training)
def _classif_fn(
self,
embeddings: jnp.ndarray,
) -> jnp.ndarray:
classifier = hk.Linear(output_size=self._num_classes)
return classifier(embeddings)
# _ _
# | |_ _ __ __ _(_)_ __
# | __| '__/ _` | | '_ \
# | |_| | | (_| | | | | |
# \__|_| \__,_|_|_| |_|
#
def step(self, *,
global_step: jnp.ndarray,
rng: jnp.ndarray,
**unused_kwargs) -> Mapping[Text, np.ndarray]:
"""Performs a single training step."""
if self._train_input is None:
self._initialize_train(rng)
inputs = next(self._train_input)
self._experiment_state, scalars = self.update_pmap(
self._experiment_state, global_step, inputs)
scalars = helpers.get_first(scalars)
return scalars
def _initialize_train(self, rng: jnp.ndarray):
"""Initialize experiment state.
Args:
rng: random number generator used to initialize parameters. If working in
a multi device setup, this need to be a ShardedArray.
dummy_input: a dummy image, used to compute intermediate outputs shapes.
Returns:
Initial EvalExperiment state.
Raises:
RuntimeError: invalid or empty checkpoint.
"""
self._train_input = acme_utils.prefetch(self._build_train_input())
# Check we haven't already restored params
if self._experiment_state is None:
inputs = next(self._train_input)
if self._checkpoint_to_evaluate is not None:
# Load params from checkpoint
with tf.io.gfile.GFile(self._checkpoint_to_evaluate, 'rb') as f:
checkpoint_data = np.load(f, allow_pickle=True)
if checkpoint_data is None:
raise RuntimeError('Invalid checkpoint.')
backbone_params = checkpoint_data.item(0)['ema_state']['online_params']
backbone_state = checkpoint_data.item(
0)['experiment_state']['online_state']
backbone_params = helpers.bcast_local_devices(backbone_params)
backbone_state = helpers.bcast_local_devices(backbone_state)
else:
if not self._allow_train_from_scratch:
raise ValueError(
'No checkpoint specified, but `allow_train_from_scratch` '
'set to False')
# Initialize with random parameters
logging.info(
'No checkpoint specified, initializing the networks from scratch '
'(dry run mode)')
backbone_params, backbone_state = jax.pmap(
functools.partial(self.forward_backbone.init, is_training=True),
axis_name='i')(rng=rng, inputs=inputs)
init_experiment = jax.pmap(self._make_initial_state, axis_name='i')
# Init uses the same RNG key on all hosts+devices to ensure everyone
# computes the same initial state and parameters.
init_rng = helpers.bcast_local_devices(self._init_rng)
self._experiment_state = init_experiment(
rng=init_rng,
dummy_input=inputs,
backbone_params=backbone_params,
backbone_state=backbone_state)
# Clear the backbone optimizer's state when the backbone is frozen.
if self._freeze_backbone:
self._experiment_state = self._experiment_state._replace(
backbone_opt_state=None)
def _make_initial_state(
self,
rng: jnp.ndarray,
dummy_input: dataset.Batch,
backbone_params: hk.Params,
backbone_state: hk.Params,
) -> _EvalExperimentState:
"""_EvalExperimentState initialization."""
rng_init, rng_ema = jax.random.split(rng)
# Initialize the backbone params
# Always create the batchnorm weights (is_training=True), they will be
# overwritten when loading the checkpoint.
embeddings, _ = self.forward_backbone.apply(
backbone_params, backbone_state, dummy_input, is_training=True)
backbone_opt_state = self._optimizer(0.).init(backbone_params)
# Initialize the classifier params and optimizer_state
classif_params = self.forward_classif.init(rng_init, embeddings)
classif_opt_state = self._optimizer(0.).init(classif_params)
ema_params = {'ema_classif_params': classif_params}
if not self._freeze_backbone:
ema_params['ema_backbone_params'] = backbone_params
ema_module_params, ema_module_state = self.ema_update.init(
rng_ema, ema_params)
ema_params, ema_module_state = self.ema_update.apply(
ema_module_params, ema_module_state, ema_params)
return _EvalExperimentState(
backbone_params=backbone_params,
classif_params=classif_params,
backbone_state=backbone_state,
backbone_opt_state=backbone_opt_state,
classif_opt_state=classif_opt_state,
ema_module_params=ema_module_params,
ema_state=ema_module_state,
**ema_params
)
def _build_train_input(self) -> Generator[dataset.Batch, None, None]:
"""See base class."""
num_devices = jax.device_count()
global_batch_size = self._batch_size
per_device_batch_size, ragged = divmod(global_batch_size, num_devices)
if ragged:
raise ValueError(
f'Global batch size {global_batch_size} must be divisible by '
f'num devices {num_devices}')
return dataset.load(
dataset.Split.TRAIN_AND_VALID,
preprocess_mode=dataset.PreprocessMode.LINEAR_TRAIN,
transpose=self._should_transpose_images,
batch_dims=[jax.local_device_count(), per_device_batch_size])
def _optimizer(self, learning_rate: float):
"""Build optimizer from config."""
return optax.sgd(learning_rate, **self._optimizer_config)
def _loss_fn(
self,
backbone_params: hk.Params,
classif_params: hk.Params,
backbone_state: hk.State,
inputs: dataset.Batch,
) -> Tuple[jnp.ndarray, Tuple[jnp.ndarray, hk.State]]:
"""Compute the classification loss function.
Args:
backbone_params: parameters of the encoder network.
classif_params: parameters of the linear classifier.
backbone_state: internal state of encoder network.
inputs: inputs, containing `images` and `labels`.
Returns:
The classification loss and various logs.
"""
embeddings, backbone_state = self.forward_backbone.apply(
backbone_params,
backbone_state,
inputs,
is_training=not self._freeze_backbone)
logits = self.forward_classif.apply(classif_params, embeddings)
labels = hk.one_hot(inputs['labels'], self._num_classes)
loss = helpers.softmax_cross_entropy(logits, labels, reduction='mean')
scaled_loss = loss / jax.device_count()
return scaled_loss, (loss, backbone_state)
def _update_func(
self,
experiment_state: _EvalExperimentState,
global_step: jnp.ndarray,
inputs: dataset.Batch,
) -> Tuple[_EvalExperimentState, LogsDict]:
"""Applies an update to parameters and returns new state."""
# This function computes the gradient of the first output of loss_fn and
# passes through the other arguments unchanged.
# Gradient of the first output of _loss_fn wrt the backbone (arg 0) and the
# classifier parameters (arg 1). The auxiliary outputs are returned as-is.
grad_loss_fn = jax.grad(self._loss_fn, has_aux=True, argnums=(0, 1))
grads, aux_outputs = grad_loss_fn(
experiment_state.backbone_params,
experiment_state.classif_params,
experiment_state.backbone_state,
inputs,
)
backbone_grads, classifier_grads = grads
train_loss, new_backbone_state = aux_outputs
classifier_grads = jax.lax.psum(classifier_grads, axis_name='i')
# Compute the decayed learning rate
learning_rate = schedules.learning_schedule(
global_step,
batch_size=self._batch_size,
total_steps=self._max_steps,
**self._lr_schedule_config)
# Compute and apply updates via our optimizer.
classif_updates, new_classif_opt_state = self._optimizer(
learning_rate).update(classifier_grads,
experiment_state.classif_opt_state)
new_classif_params = optax.apply_updates(experiment_state.classif_params,
classif_updates)
ema_params = {'ema_classif_params': new_classif_params}
if self._freeze_backbone:
del backbone_grads, new_backbone_state # Unused
# The backbone is not updated.
new_backbone_params = experiment_state.backbone_params
new_backbone_opt_state = None
new_backbone_state = experiment_state.backbone_state
else:
backbone_grads = jax.lax.psum(backbone_grads, axis_name='i')
# Compute and apply updates via our optimizer.
backbone_updates, new_backbone_opt_state = self._optimizer(
learning_rate).update(backbone_grads,
experiment_state.backbone_opt_state)
new_backbone_params = optax.apply_updates(
experiment_state.backbone_params, backbone_updates)
ema_params['ema_backbone_params'] = new_backbone_params
ema_params, ema_module_state = self.ema_update.apply(
experiment_state.ema_module_params,
experiment_state.ema_state,
ema_params)
experiment_state = _EvalExperimentState(
backbone_params=new_backbone_params,
classif_params=new_classif_params,
backbone_state=new_backbone_state,
backbone_opt_state=new_backbone_opt_state,
classif_opt_state=new_classif_opt_state,
ema_module_params=experiment_state.ema_module_params,
ema_state=ema_module_state,
**ema_params
)
# Scalars to log (note: we log the mean across all hosts/devices).
scalars = {'train_loss': train_loss}
scalars = jax.lax.pmean(scalars, axis_name='i')
return experiment_state, scalars
# _
# _____ ____ _| |
# / _ \ \ / / _` | |
# | __/\ V / (_| | |
# \___| \_/ \__,_|_|
#
def evaluate(self, global_step: jnp.ndarray, **unused_args):
"""See base class."""
global_step = np.array(helpers.get_first(global_step))
scalars = jax.device_get(self._eval_epoch(**self._evaluation_config))
logging.info('[Step %d] Eval scalars: %s', global_step, scalars)
return scalars
def _eval_batch(
self,
backbone_params: hk.Params,
classif_params: hk.Params,
backbone_state: hk.State,
inputs: dataset.Batch,
) -> LogsDict:
"""Evaluates a batch."""
embeddings, backbone_state = self.forward_backbone.apply(
backbone_params, backbone_state, inputs, is_training=False)
logits = self.forward_classif.apply(classif_params, embeddings)
labels = hk.one_hot(inputs['labels'], self._num_classes)
loss = helpers.softmax_cross_entropy(logits, labels, reduction=None)
top1_correct = helpers.topk_accuracy(logits, inputs['labels'], topk=1)
top5_correct = helpers.topk_accuracy(logits, inputs['labels'], topk=5)
# NOTE: Returned values will be summed and finally divided by num_samples.
return {
'eval_loss': loss,
'top1_accuracy': top1_correct,
'top5_accuracy': top5_correct
}
def _eval_epoch(self, subset: Text, batch_size: int):
"""Evaluates an epoch."""
num_samples = 0.
summed_scalars = None
if self._experiment_state.ema_backbone_params:
backbone_params = helpers.get_first(
self._experiment_state.ema_backbone_params)
else:
backbone_params = helpers.get_first(
self._experiment_state.backbone_params)
classif_params = helpers.get_first(
self._experiment_state.ema_classif_params)
backbone_state = helpers.get_first(self._experiment_state.backbone_state)
split = dataset.Split.from_string(subset)
dataset_iterator = dataset.load(
split,
preprocess_mode=dataset.PreprocessMode.EVAL,
transpose=self._should_transpose_images,
batch_dims=[batch_size])
for inputs in dataset_iterator:
num_samples += inputs['labels'].shape[0]
scalars = self.eval_batch_jit(
backbone_params,
classif_params,
backbone_state,
inputs,
)
# Accumulate the sum of scalars for each step.
scalars = jax.tree_map(lambda x: jnp.sum(x, axis=0), scalars)
if summed_scalars is None:
summed_scalars = scalars
else:
summed_scalars = jax.tree_multimap(jnp.add, summed_scalars, scalars)
mean_scalars = jax.tree_map(lambda x: x / num_samples, summed_scalars)
return mean_scalars
if __name__ == '__main__':
flags.mark_flag_as_required('config')
app.run(functools.partial(platform.main, EvalExperiment))
|
ssl_hsic-main
|
ssl_hsic/eval_experiment.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 imp # pylint: disable=deprecated-module
import setuptools
# Additional requirements for testing.
testing_require = [
'gym',
'gym[atari]',
'mock',
'pytest-xdist',
'pytype',
]
setuptools.setup(
name='enn_acme',
description=(
'ENN_ACME. '
'An interface for designing RL agents in Acme using the ENN library.'),
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='https://github.com/deepmind/enn_acme',
author='DeepMind',
author_email='enn_acme-eng+os@google.com',
license='Apache License, Version 2.0',
# TODO(author1): Use LINT.IfChange(version) instead of imp.
version=imp.load_source('_metadata', 'enn_acme/_metadata.py').__version__,
keywords='probabilistic-inference python machine-learning',
packages=setuptools.find_packages(),
install_requires=[
'absl-py',
'bsuite',
'chex',
'dm-acme==0.4.0',
'dm-env',
'dm-haiku',
'dm-launchpad==0.5.0',
'dm-reverb==0.7.0',
'dm-sonnet',
'enn @ git+https://git@github.com/deepmind/enn',
'jax==0.3.15',
'jaxlib',
'neural_testbed @ git+https://git@github.com/deepmind/neural_testbed',
'numpy',
'optax',
'pandas',
'pyarrow',
'rlax',
'requests',
'tensorflow==2.8.0',
'tensorflow-datasets==4.4.0',
'tensorflow_probability==0.15.0',
'typing-extensions',
],
extras_require={
'testing': testing_require,
},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
|
enn_acme-master
|
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.
# ============================================================================
"""Package metadata for enn.
This is kept in a separate module so that it can be imported from setup.py, at
a time when enn's dependencies may not have been installed yet.
"""
__version__ = '0.1.0'
|
enn_acme-master
|
enn_acme/_metadata.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.
# ============================================================================
"""An interface for designing RL agents in Acme using the ENN library."""
|
enn_acme-master
|
enn_acme/__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.
# ============================================================================
"""Base classes for ENN agent design."""
import abc
import dataclasses
import typing as tp
from acme import types
import chex
import dm_env
from enn import base as enn_base
import haiku as hk
import optax
import reverb
import typing_extensions as te
Action = int
Input = tp.TypeVar('Input') # Inputs to neural network
Output = tp.TypeVar('Output') # Outputs of neural network
LossMetrics = enn_base.LossMetrics
@dataclasses.dataclass
class EnnPlanner(abc.ABC, tp.Generic[Input, Output]):
"""A planner can select actions based on an ENN knowledge representation.
The EnnPlanner is one of the core units we often change in algorithm design.
Examples might include Epsilon-Greedy, Thompson Sampling, IDS and more...
We implement some examples in `planners.py`.
The EnnPlanner is then used by an acme.Actor to select actions. However, we do
not implement this as an acme.Actor since we want to hide the variable_client
and choice of replay "adder" from action selection. For example of how this is
used to make an acme.Actor see PlannerActor in agents/acting.py.
"""
enn: enn_base.EpistemicNetwork[Input, Output]
seed: tp.Optional[int] = 0
@abc.abstractmethod
def select_action(
self, params: hk.Params, observation: Input) -> Action:
"""Selects an action given params and observation."""
def observe_first(self, timestep: dm_env.TimeStep):
"""Optional: make a first observation from the environment."""
def observe(self, action: types.NestedArray, next_timestep: dm_env.TimeStep):
"""Optional: make an observation of timestep data from the environment."""
class LearnerState(tp.NamedTuple):
"""Complete state of learner used for checkpointing / modifying loss."""
params: hk.Params
target_params: hk.Params
opt_state: optax.OptState
learner_steps: int
extra: tp.Optional[tp.Dict[str, tp.Any]] = None
class LossFn(te.Protocol[Input, Output]):
"""A LossFn defines how to process one batch of data, for one random key.
te.Protocol means that any functions with this signature are also valid
LossFn.
"""
def __call__(self,
enn: enn_base.EpistemicNetwork[Input, Output],
params: hk.Params,
state: LearnerState,
batch: reverb.ReplaySample,
key: chex.PRNGKey) -> tp.Tuple[chex.Array, LossMetrics]:
"""Compute the loss on a single batch of data, for one random key."""
|
enn_acme-master
|
enn_acme/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.
# ============================================================================
"""Q learning variants for loss function definition."""
import dataclasses
from typing import Tuple
from acme import types
import chex
from enn import base as enn_base
from enn import losses
from enn import networks
from enn_acme import base as agent_base
from enn_acme.losses import single_index
import haiku as hk
import jax
import jax.numpy as jnp
import reverb
import rlax
@dataclasses.dataclass
class ClippedQlearning(single_index.SingleLossFnArray):
"""Clipped Q learning."""
discount: float
max_abs_reward: float = 1
def __call__(
self,
apply: networks.ApplyArray,
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
index: enn_base.Index,
) -> Tuple[chex.Array, agent_base.LossMetrics]:
"""Evaluate loss for one batch, for one single index."""
transitions: types.Transition = batch.data
dummy_network_state = {}
net_out_tm1, unused_state = apply(params, dummy_network_state,
transitions.observation, index)
q_tm1 = networks.parse_net_output(net_out_tm1)
net_out_t, unused_state = apply(state.target_params, dummy_network_state,
transitions.next_observation, index)
q_t = networks.parse_net_output(net_out_t)
d_t = (transitions.discount * self.discount).astype(jnp.float32)
r_t = jnp.clip(transitions.reward, -self.max_abs_reward,
self.max_abs_reward).astype(jnp.float32)
td_errors = jax.vmap(rlax.q_learning)(
q_tm1, transitions.action, r_t, d_t, q_t)
return jnp.mean(jnp.square(td_errors)), {}
@dataclasses.dataclass
class Categorical2HotQlearning(single_index.SingleLossFnArray):
"""Q learning applied with cross-entropy loss to two-hot targets."""
discount: float
def __call__(
self,
apply: networks.ApplyArray,
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
index: enn_base.Index,
) -> Tuple[chex.Array, agent_base.LossMetrics]:
"""Evaluate loss for one batch, for one single index."""
transitions: types.Transition = batch.data
batch_idx = jnp.arange(transitions.observation.shape[0])
dummy_network_state = {}
net_out_tm1, unused_state = apply(params, dummy_network_state,
transitions.observation, index)
net_out_t, unused_state = apply(state.target_params, dummy_network_state,
transitions.next_observation, index)
# Check that network output has the right type
assert isinstance(net_out_tm1, networks.CatOutputWithPrior)
assert isinstance(net_out_t, networks.CatOutputWithPrior)
# Form target values in real space
d_t = (transitions.discount * self.discount).astype(jnp.float32)
v_t = jnp.max(net_out_t.preds, axis=-1)
target_val = transitions.reward + d_t * v_t - net_out_tm1.prior[
batch_idx, transitions.action]
# Convert values to 2-hot target probabilities
logits = net_out_tm1.train[batch_idx, transitions.action, :]
target_probs = jax.vmap(losses.transform_to_2hot, in_axes=[0, None])(
target_val, net_out_tm1.extra['atoms'])
xent_loss = -jnp.sum(target_probs * jax.nn.log_softmax(logits), axis=-1)
return jnp.mean(xent_loss), {}
|
enn_acme-master
|
enn_acme/losses/value_learning.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.
# ============================================================================
"""A LossFn computes the loss on a batch of data for one index."""
from typing import Tuple
import chex
from enn import base as enn_base
from enn import networks as enn_networks
from enn import utils
from enn_acme import base as agent_base
import haiku as hk
import jax
import jax.numpy as jnp
import reverb
import typing_extensions as te
# Simple alises for generic modules
_ENN = enn_base.EpistemicNetwork[agent_base.Input, agent_base.Output]
class SingleLossFn(te.Protocol[agent_base.Input, agent_base.Output]):
"""A SingleLossFn defines how to process one batch of data, one index."""
def __call__(
self,
apply: enn_base.ApplyFn[agent_base.Input, agent_base.Output],
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
index: enn_base.Index,
) -> Tuple[chex.Array, agent_base.LossMetrics]:
"""Compute the loss on a single batch of data, for one index."""
def average_single_index_loss(
single_loss: SingleLossFn[agent_base.Input, agent_base.Output],
num_index_samples: int = 1
) -> agent_base.LossFn[agent_base.Input, agent_base.Output]:
"""Average a single index loss over multiple index samples."""
def loss_fn(enn: _ENN[agent_base.Input, agent_base.Output],
params: hk.Params, state: agent_base.LearnerState,
batch: reverb.ReplaySample, key: chex.PRNGKey) -> chex.Array:
batched_indexer = utils.make_batch_indexer(enn.indexer, num_index_samples)
batched_loss = jax.vmap(single_loss, in_axes=[None, None, None, None, 0])
loss, metrics = batched_loss(
enn.apply, params, state, batch, batched_indexer(key))
return jnp.mean(loss), jax.tree_util.tree_map(jnp.mean, metrics)
return loss_fn
# Loss modules specialized to work only with Array inputs.
LossFnArray = agent_base.LossFn[chex.Array, enn_networks.Output]
SingleLossFnArray = SingleLossFn[chex.Array, enn_networks.Output]
|
enn_acme-master
|
enn_acme/losses/single_index.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.
# ============================================================================
"""Exposing the public methods of the losses."""
# Single Index
from enn_acme.losses.single_index import average_single_index_loss
from enn_acme.losses.single_index import LossFnArray
from enn_acme.losses.single_index import SingleLossFn
from enn_acme.losses.single_index import SingleLossFnArray
# Testing
from enn_acme.losses.testing import dummy_loss
# Additional useful functions
from enn_acme.losses.utils import add_l2_weight_decay
# Value Learning
from enn_acme.losses.value_learning import Categorical2HotQlearning
from enn_acme.losses.value_learning import ClippedQlearning
|
enn_acme-master
|
enn_acme/losses/__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.
# ============================================================================
"""Helpful functions relating to losses."""
import dataclasses
import typing as tp
import chex
from enn import base as enn_base
from enn import losses as enn_losses
from enn_acme import base as agent_base
import haiku as hk
import reverb
def add_l2_weight_decay(
loss_fn: agent_base.LossFn[agent_base.Input, agent_base.Output],
scale_fn: tp.Callable[[int], float], # Maps learner_steps --> l2 decay
predicate: tp.Optional[enn_losses.PredicateFn] = None,
) -> agent_base.LossFn[agent_base.Input, agent_base.Output]:
"""Adds l2 weight decay to a given loss function."""
def new_loss(
enn: enn_base.EpistemicNetwork[agent_base.Input, agent_base.Output],
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
key: chex.PRNGKey,
) -> tp.Tuple[chex.Array, agent_base.LossMetrics]:
loss, metrics = loss_fn(enn, params, state, batch, key)
l2_penalty = enn_losses.l2_weights_with_predicate(params, predicate)
decay = l2_penalty * scale_fn(state.learner_steps)
total_loss = loss + decay
metrics['decay'] = decay
metrics['raw_loss'] = loss
return total_loss, metrics
return new_loss
@dataclasses.dataclass
class CombineLossConfig(tp.Generic[agent_base.Input, agent_base.Output]):
loss_fn: agent_base.LossFn[agent_base.Input, agent_base.Output]
name: str = 'unnamed' # Name for the loss function
weight: float = 1. # Weight to scale the loss by
def combine_losses(
losses: tp.Sequence[CombineLossConfig[agent_base.Input, agent_base.Output]],
) -> agent_base.LossFn[agent_base.Input, agent_base.Output]:
"""Combines multiple losses into a single loss."""
def loss_fn(
enn: enn_base.EpistemicNetwork[agent_base.Input, agent_base.Output],
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
key: chex.PRNGKey,
) -> tp.Tuple[chex.Array, agent_base.LossMetrics]:
combined_loss = 0.
combined_metrics = {}
for loss_config in losses:
loss, metrics = loss_config.loss_fn(enn, params, state, batch, key)
combined_metrics[f'{loss_config.name}:loss'] = loss
for name, value in metrics.items():
combined_metrics[f'{loss_config.name}:{name}'] = value
combined_loss += loss_config.weight * loss
return combined_loss, combined_metrics
return loss_fn
|
enn_acme-master
|
enn_acme/losses/utils.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.
# ============================================================================
"""A LossFn computes the loss on a batch of data for one index."""
from typing import Tuple
import chex
from enn import networks
from enn_acme import base as agent_base
import haiku as hk
import jax.numpy as jnp
import reverb
def dummy_loss(
enn: networks.EnnNoState,
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
key: chex.PRNGKey,
) -> Tuple[chex.Array, agent_base.LossMetrics]:
"""A dummy loss function that always returns loss=1."""
del enn, params, state, batch, key
return (jnp.ones(1), {})
|
enn_acme-master
|
enn_acme/losses/testing.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.
# ============================================================================
|
enn_acme-master
|
enn_acme/experiments/__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.
# ============================================================================
"""Run a JAX agent on a bsuite experiment."""
import typing
from absl import app
from absl import flags
import acme
from acme import specs
from acme import wrappers
from acme.jax import utils
from bsuite import bsuite
from enn import networks
from enn_acme import agents as enn_agents
from enn_acme import losses
from enn_acme import planners
from enn_acme.experiments.bsuite import prior_scale
import jax.numpy as jnp
from neural_testbed import agents as testbed_agents
from neural_testbed import base as testbed_base
from neural_testbed.agents.factories import epinet
from neural_testbed.agents.factories.sweeps import testbed as factories
import numpy as np
# Which bsuite environment to run
_BSUITE_ID = flags.DEFINE_string('bsuite_id', 'catch/0',
'Which bsuite environment to run.')
_RESULTS_DIR = flags.DEFINE_string('results_dir', '/tmp/',
'Where to save csv files.')
_OVERWRITE = flags.DEFINE_bool('overwrite', True,
'Whether to overwrite results.')
# ENN training
_AGENT_ID = flags.DEFINE_string('agent_id', 'epinet',
'Which benchmark agent to run.')
_SEED = flags.DEFINE_integer('seed', 0, 'Seed for agent.')
_INDEX_DIM = flags.DEFINE_integer('index_dim', 2, '')
_HIDDEN_SIZE = flags.DEFINE_integer('hidden_size', 50, '')
_NUM_EPISODES = flags.DEFINE_integer('num_episodes', None,
'Number of episodes to run.')
_NUM_INDEX_SAMPLES = flags.DEFINE_integer(
'num_index_samples', 20, 'Number of index samples per batch of learning.')
_EPSILON = flags.DEFINE_float('epsilon', 0., 'Epsilon greedy.')
_PRIOR_SCALE = flags.DEFINE_float('prior_scale', 1.,
'Scale for prior function.')
FLAGS = flags.FLAGS
def _spec_to_prior(spec: specs.EnvironmentSpec) -> testbed_base.PriorKnowledge:
"""Converts environment spec to neural testbed prior knowledge."""
dummy_input = utils.zeros_like(spec.observations)
return testbed_base.PriorKnowledge(
input_dim=np.prod(dummy_input.shape), # Unused
num_train=100, # Unused
tau=10, # Unused
num_classes=spec.actions.num_values,
temperature=1,
)
def _wrap_with_flatten(
enn: networks.EnnArray) -> networks.EnnArray:
"""Wraps an ENN with a flattening layer."""
flatten = lambda x: jnp.reshape(x, [x.shape[0], -1])
return networks.EnnArray(
apply=lambda p, s, x, z: enn.apply(p, s, flatten(x), z),
init=lambda k, x, z: enn.init(k, flatten(x), z),
indexer=enn.indexer,
)
def make_enn(agent: str,
spec: specs.EnvironmentSpec) -> networks.EnnArray:
"""Parse the ENN from the agent name and prior."""
# Parse testbed "prior" information from environment
prior = _spec_to_prior(spec)
# Obtain the std observed of a random linear function of observations,
# calculated by letting a random agent observe 100 timesteps.
problem_std = prior_scale.problem_std(_BSUITE_ID.value)
if agent == 'epinet':
# Overriding epinet config
config = epinet.EpinetConfig(
index_dim=_INDEX_DIM.value,
prior_scale=_PRIOR_SCALE.value / problem_std,
hidden_sizes=[_HIDDEN_SIZE.value, _HIDDEN_SIZE.value],
epi_hiddens=[50],
add_hiddens=(),
seed=_SEED.value,
)
testbed_agent = epinet.make_agent(config)
enn = testbed_agent.config.enn_ctor(prior)
else:
# Use the default agent settings
paper_agent = factories.get_paper_agent(agent)
config = paper_agent.default
config.seed = _SEED.value
# Rescale problem std if available
if hasattr(config, 'prior_scale'):
config.prior_scale /= problem_std
testbed_agent = paper_agent.ctor(config)
assert isinstance(testbed_agent, testbed_agents.VanillaEnnAgent)
testbed_agent = typing.cast(testbed_agents.VanillaEnnAgent, testbed_agent)
enn = testbed_agent.config.enn_ctor(prior)
return _wrap_with_flatten(enn)
def main(_):
"""Runs a DQN agent on a given bsuite environment, logging to CSV."""
environment = bsuite.load_and_record_to_csv(
_BSUITE_ID.value, _RESULTS_DIR.value, overwrite=_OVERWRITE.value)
environment = wrappers.SinglePrecisionWrapper(environment)
spec = specs.make_environment_spec(environment)
enn = make_enn(_AGENT_ID.value, spec)
config = enn_agents.AgentConfig() # Can override options from FLAGS here.
single_loss = losses.ClippedQlearning(discount=0.99)
agent = enn_agents.EnnAgent(
environment_spec=spec,
enn=enn,
loss_fn=losses.average_single_index_loss(single_loss,
_NUM_INDEX_SAMPLES.value),
planner=planners.ThompsonQPlanner(
enn, _SEED.value, epsilon=_EPSILON.value),
config=config,
)
num_episodes = _NUM_EPISODES.value or environment.bsuite_num_episodes # pytype: disable=attribute-error
loop = acme.EnvironmentLoop(environment, agent)
loop.run(num_episodes=num_episodes)
if __name__ == '__main__':
app.run(main)
|
enn_acme-master
|
enn_acme/experiments/bsuite/run.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.
# ============================================================================
"""Handles prior rescaling on bsuite.
In our mathematical algorithm we rescale the sampled prior_fn based on the
observations of a random agent over the first 100 timesteps in bsuite. Since
our agent actually doesn't update its parameters over the first 128 steps it
is therefore mathematically equivalent to first run a uniformly random agent,
and use this value to rescale the prior at initialization.
We view this purely as a convenience in coding/implementation, and should have
absolutely no effect on the results.
For these problem_std, we sample a random linear: observation -> 1, and log
the observed standard deviation of that value.
"""
import os
import tempfile
import pyarrow.parquet as pq
import requests
def problem_std(bsuite_id: str) -> float:
"""Obtains std of a random linear function of input for that bsuite_id."""
url = 'https://storage.googleapis.com/dm-enn/prior_scaling.parquet'
with tempfile.TemporaryDirectory() as tmpdir:
response = requests.get(url, verify=False)
# Make a temporary file for downloading
bsuite_name = bsuite_id.replace('/', '-')
filepath = os.path.join(tmpdir, f'/tmp/prior_scale_{bsuite_name}.parquet')
open(filepath, 'wb').write(response.content)
# Read data from temporary file
with open(filepath, 'rb') as f:
table = pq.read_table(f)
df = table.to_pandas()
return df.loc[df.bsuite_id == bsuite_id, 'std'].iloc[0]
|
enn_acme-master
|
enn_acme/experiments/bsuite/prior_scale.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.
# ============================================================================
|
enn_acme-master
|
enn_acme/experiments/bsuite/__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 for experiments.bsuite.run."""
from absl import flags
from absl.testing import absltest
from absl.testing import flagsaver
from absl.testing import parameterized
from bsuite import sweep
from enn_acme.experiments.bsuite import run
import jax
FLAGS = flags.FLAGS
# Parse absl flags
jax.config.parse_flags_with_absl()
class RunTest(parameterized.TestCase):
@parameterized.parameters([[bsuite_id] for bsuite_id in sweep.TESTING])
def test_each_bsuite_env(self, bsuite_id: str):
with flagsaver.flagsaver(bsuite_id=bsuite_id,
num_episodes=5,
index_dim=1,):
run.main(None)
if __name__ == '__main__':
absltest.main()
|
enn_acme-master
|
enn_acme/experiments/bsuite/run_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.
# ============================================================================
# TODO(author4): Add a test for this file.
"""Run a JAX agent on a bsuite experiment."""
from absl import app
from absl import flags
import acme
from acme import specs
from acme import wrappers
from bsuite import bsuite
from enn_acme import agents
from enn_acme import base as agent_base
from enn_acme import losses as agent_losses
from enn_acme.experiments.model_based import base
from enn_acme.experiments.model_based import losses
from enn_acme.experiments.model_based import networks
from enn_acme.experiments.model_based import planners
from enn_acme.losses import utils as loss_utils
# Which bsuite environment to run
flags.DEFINE_string('bsuite_id', 'catch/0', 'Which bsuite environment to run.')
flags.DEFINE_string('results_dir', '/tmp/', 'Where to save csv files.')
flags.DEFINE_bool('overwrite', True, 'Whether to overwrite results.')
# Agent flags
flags.DEFINE_integer('seed', 0, 'Seed for experiment.')
flags.DEFINE_integer('hidden_dim', 32, 'Latent hidden.')
flags.DEFINE_integer('num_episodes', None, 'Number of episodes to run.')
flags.DEFINE_float('epsilon', 0., 'Epsilon greedy.')
flags.DEFINE_bool('use_policy_head', False,
'Whether to use the policy head to select actions.')
FLAGS = flags.FLAGS
# Shorthands for the ENN input and output types
_Input = base.Input
_Output = base.DepthOneSearchOutput
def _make_loss() -> agent_base.LossFn[_Input, _Output]:
"""Make the loss function for the model-based agent."""
reward_loss = losses.RewardLoss()
value_loss = losses.ValueLoss(discount=0.99)
policy_loss = losses.PolicyLoss(temperature=0.001, discount=0.99)
cfg_class = loss_utils.CombineLossConfig[_Input, _Output]
ave_fn = agent_losses.average_single_index_loss
loss_configs = [
cfg_class(ave_fn(reward_loss, num_index_samples=1), 'reward'),
cfg_class(ave_fn(value_loss, num_index_samples=1), 'value'),
cfg_class(ave_fn(policy_loss, num_index_samples=1), 'policy'),
]
return loss_utils.combine_losses(loss_configs)
def main(_):
"""Runs a model-based agent on a given bsuite environment, logging to CSV."""
# Load environment
environment = bsuite.load_and_record_to_csv(
FLAGS.bsuite_id, results_dir=FLAGS.results_dir, overwrite=FLAGS.overwrite)
environment = wrappers.SinglePrecisionWrapper(environment)
spec = specs.make_environment_spec(environment)
num_actions = spec.actions.num_values
# Define the model and ENN
model = networks.make_single_model(
action_embedding=networks.make_outer_one_hot_embedding(num_actions),
hidden_dim=FLAGS.hidden_dim,
num_actions=num_actions,
repr_hiddens=[20],
dynamics_hiddens=[],
pred_hiddens=[20],
)
enn = base.make_enn_onestep(model, num_actions)
# Planner
if FLAGS.use_policy_head:
planner = planners.ThompsonPolicyPlanner(enn, FLAGS.seed, FLAGS.epsilon)
else:
planner = planners.ThompsonQPlanner(
enn, FLAGS.seed, FLAGS.epsilon, discount=0.99)
# Define the agent
config = agents.AgentConfig(seed=FLAGS.seed)
agent = agents.EnnAgent[_Input, _Output](
environment_spec=spec,
enn=enn,
loss_fn=_make_loss(),
planner=planner,
config=config,
)
num_episodes = FLAGS.num_episodes or environment.bsuite_num_episodes # pytype: disable=attribute-error
loop = acme.EnvironmentLoop(environment, agent)
loop.run(num_episodes=num_episodes)
if __name__ == '__main__':
app.run(main)
|
enn_acme-master
|
enn_acme/experiments/model_based/run.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.
# ============================================================================
|
enn_acme-master
|
enn_acme/experiments/model_based/__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.
# ============================================================================
"""MLP-based models."""
import typing as tp
import chex
from enn import base as enn_base
from enn_acme.experiments.model_based import base
import haiku as hk
import jax
import jax.numpy as jnp
def make_outer_one_hot_embedding(num_actions: int) -> base.ActionEmbedding:
"""Make an outer product action embedding function.
Args:
num_actions: Number of actions.
Returns:
An action embedding function that performs outer product on a batch of
hidden representations with a one-hot vector made from an integer action.
"""
def single_embed(single_hidden: chex.Array, action: int) -> chex.Array:
one_hot = jax.nn.one_hot(action, num_actions)
return jnp.outer(single_hidden, one_hot).ravel()
return jax.vmap(single_embed, in_axes=[0, None])
def make_single_model(
action_embedding: base.ActionEmbedding,
hidden_dim: int,
num_actions: int,
repr_hiddens: tp.Sequence[int] = (),
dynamics_hiddens: tp.Sequence[int] = (),
pred_hiddens: tp.Sequence[int] = (),
layernorm: bool = False,
return_hidden_state: bool = False,
) -> base.AgentModel:
"""Creates a simple MLP-based AgentModel."""
# Write the networks without any ENN nomenclature
def repr_net(inputs: base.Input) -> base.OutputWithPrior:
output_sizes = list(repr_hiddens) + [hidden_dim]
net = hk.nets.MLP(output_sizes, name='representation')
flat_input = hk.Flatten()(inputs)
out = net(flat_input)
if layernorm:
out = hk.LayerNorm(axis=-1, create_scale=False, create_offset=False)(out)
return base.OutputWithPrior(out, prior=jnp.zeros_like(out))
def dynamics_net(inputs: base.HiddenA) -> base.OutputWithPrior:
output_sizes = list(dynamics_hiddens) + [hidden_dim]
net = hk.nets.MLP(output_sizes, name='dynamics')
out = net(inputs)
if layernorm:
out = hk.LayerNorm(axis=-1, create_scale=False, create_offset=False)(out)
return base.OutputWithPrior(out, prior=jnp.zeros_like(out))
def pred_net(inputs: base.Hidden) -> base.PredictionOutput:
hiddens = list(pred_hiddens)
r_net = hk.nets.MLP(hiddens + [1], name='prediction_r')
v_net = hk.nets.MLP(hiddens + [1], name='prediction_v')
p_net = hk.nets.MLP(hiddens + [num_actions], name='prediction_p')
reward = r_net(inputs)
value = v_net(inputs)
policy = p_net(inputs)
extra = {'hidden_state': inputs} if return_hidden_state else {}
make_output = lambda x: base.OutputWithPrior(x, prior=jnp.zeros_like(x))
return base.PredictionOutput(
reward=make_output(reward),
value=make_output(value),
policy=make_output(policy),
extra=extra,
)
return base.AgentModel(
representation=_wrap_net_fn_as_enn(repr_net),
action_embedding=action_embedding,
dynamics=_wrap_net_fn_as_enn(dynamics_net),
prediction=_wrap_net_fn_as_enn(pred_net),
)
_Input = tp.TypeVar('_Input')
_Output = tp.TypeVar('_Output')
# TODO(author4): Integrate with enn networks utils.
def _wrap_net_fn_as_enn(
net_fn: tp.Callable[[_Input], _Output], # Pre-transformed
) -> enn_base.EpistemicNetwork[_Input, _Output]:
"""Wrap pre-transformed functions as ENNs with dummy index."""
transformed = hk.without_apply_rng(hk.transform_with_state(net_fn))
def apply(params: hk.Params,
state: hk.State,
inputs: _Input,
index: enn_base.Index) -> tp.Tuple[_Output, hk.State]:
del index
return transformed.apply(params, state, inputs)
return enn_base.EpistemicNetwork[_Input, _Output](
apply=apply,
init=lambda k, x, z: transformed.init(k, x),
indexer=lambda k: k,
)
|
enn_acme-master
|
enn_acme/experiments/model_based/networks.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.
# ============================================================================
"""Value learning loss."""
import dataclasses
import typing as tp
from acme import types
import chex
from enn import base as enn_base
from enn_acme import base as agent_base
from enn_acme import losses
from enn_acme.experiments.model_based import base
import haiku as hk
import jax
import jax.numpy as jnp
import reverb
class RewardLoss(losses.SingleLossFn[base.Input, base.DepthOneSearchOutput]):
"""Learns the reward on the observed transition."""
def __call__(
self,
apply: base.ApplyOneStep,
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
index: enn_base.Index,
) -> tp.Tuple[chex.Array, agent_base.LossMetrics]:
"""Learns the reward on the observed transition."""
dummy_network_state = {}
transitions: types.Transition = batch.data
batch_size = transitions.observation.shape[0]
net_out, _ = apply(
params, dummy_network_state, transitions.observation, index)
output_tm1: base.DepthOneSearchOutput = net_out
r_hat_tm1 = base.stack_action_rewards(output_tm1) # (batch, actions)
def compute_reward_err(
reward: float, r_preds: chex.Array, action: int) -> float:
return reward - r_preds[action]
reward_err = jax.vmap(compute_reward_err)(
transitions.reward, r_hat_tm1, transitions.action)
chex.assert_shape(reward_err, [batch_size])
r_loss = jnp.mean(reward_err ** 2)
return r_loss, {}
@dataclasses.dataclass
class ValueLoss(losses.SingleLossFn[base.Input, base.DepthOneSearchOutput]):
"""Model-based value loss + one-step value equivalence."""
discount: float = 0.99
def __call__(
self,
apply: base.ApplyOneStep,
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
index: enn_base.Index,
) -> tp.Tuple[chex.Array, agent_base.LossMetrics]:
"""Learns the value on the observed transition."""
dummy_network_state = {}
transitions: types.Transition = batch.data
batch_size = transitions.observation.shape[0]
net_out_t, _ = apply(
params, dummy_network_state, transitions.observation, index)
output_t: base.DepthOneSearchOutput = net_out_t
net_out_t_target, _ = apply(state.target_params, dummy_network_state,
transitions.observation, index)
output_t_target: base.DepthOneSearchOutput = net_out_t_target
net_out_tp1_target, _ = apply(state.target_params, dummy_network_state,
transitions.next_observation, index)
output_tp1_target: base.DepthOneSearchOutput = net_out_tp1_target
# Naming: {variable}_{observation time}_{unrolled step}
# Predictions starting at o_t
v_t_0 = jnp.squeeze(output_t.root.value.preds, axis=-1) # (B,)
v_t_1 = base.stack_action_values(output_t) # (B, A)
r_t_1_target = base.stack_action_rewards(output_t_target) # (B, A)
v_t_1_target = base.stack_action_values(output_t_target) # (B, A)
# Predictions starting at o_tp1
r_tp1_1_target = base.stack_action_rewards(output_tp1_target) # (B, A)
v_tp1_1_target = base.stack_action_values(output_tp1_target) # (B, A)
# Parsing discount and actions
non_terminal_tp1 = transitions.discount.astype(jnp.float32) # (B,)
a_t = transitions.action # (B,)
# First unrolled step k=0
def compute_td_err_0(
v_t_0: chex.Array,
r_t_1: chex.Array,
v_t_1: chex.Array,
) -> float:
q_t = r_t_1 + self.discount * v_t_1
return jnp.max(q_t) - v_t_0
td_errors = jax.vmap(compute_td_err_0)(v_t_0, r_t_1_target, v_t_1_target)
chex.assert_shape(td_errors, [batch_size])
v_loss_0 = jnp.mean(td_errors ** 2)
# Second unrolled step k=1
def compute_td_err_1(
v_t_1: chex.Array,
r_tp1_1: chex.Array,
v_tp1_1: chex.Array,
non_terminal: float,
action: int,
) -> float:
q_tp1 = (r_tp1_1 + self.discount * v_tp1_1) * non_terminal
return jnp.max(q_tp1) - v_t_1[action]
td_errors = jax.vmap(compute_td_err_1)(
v_t_1, r_tp1_1_target, v_tp1_1_target, non_terminal_tp1, a_t)
chex.assert_shape(td_errors, [batch_size])
v_loss_1 = jnp.mean(td_errors ** 2)
return v_loss_0 + v_loss_1, {}
@dataclasses.dataclass
class PolicyLoss(losses.SingleLossFn[base.Input, base.DepthOneSearchOutput]):
"""Learns the greedy policy with respect to the q-values."""
temperature: float = 0.01
discount: float = 0.99
def __call__(
self,
apply: base.ApplyOneStep,
params: hk.Params,
state: agent_base.LearnerState,
batch: reverb.ReplaySample,
index: enn_base.Index,
) -> tp.Tuple[chex.Array, agent_base.LossMetrics]:
"""Learns the reward on the observed transition."""
dummy_network_state = {}
transitions: types.Transition = batch.data
batch_size = transitions.observation.shape[0]
net_out_tm1, _ = apply(
params, dummy_network_state, transitions.observation, index)
output_tm1: base.DepthOneSearchOutput = net_out_tm1
net_out_t, _ = apply(
params, dummy_network_state, transitions.next_observation, index)
output_t: base.DepthOneSearchOutput = net_out_t
# Reward, value, and policy (logits) predictions. All of these have shape
# (batch, actions).
r_tm1 = base.stack_action_rewards(output_tm1)
v_tm1 = base.stack_action_values(output_tm1)
p_tm1 = output_tm1.root.policy.preds
r_t = base.stack_action_rewards(output_t)
v_t = base.stack_action_values(output_t)
p_t = output_t.root.policy.preds
def compute_policy_loss(
logits: chex.Array,
reward: chex.Array,
value: chex.Array,
) -> float:
q_values = reward + self.discount * value
label = jax.nn.softmax(q_values / self.temperature)
return -jnp.sum(jax.lax.stop_gradient(label) * jax.nn.log_softmax(logits))
p_loss_tm1 = jax.vmap(compute_policy_loss)(p_tm1, r_tm1, v_tm1)
p_loss_t = jax.vmap(compute_policy_loss)(p_t, r_t, v_t)
chex.assert_shape(p_loss_tm1, [batch_size])
chex.assert_shape(p_loss_t, [batch_size])
p_loss = jnp.mean(p_loss_tm1 + p_loss_t)
return p_loss, {}
|
enn_acme-master
|
enn_acme/experiments/model_based/losses.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.
# ============================================================================
"""A model-based ENN agent."""
import dataclasses
import typing as tp
import chex
from enn import base
from enn.networks import base as networks_base
import haiku as hk
import jax
import jax.numpy as jnp
import typing_extensions as te
# Helpful aliases for network definition
_Enn = base.EpistemicNetwork[base.Input, base.Output] # Generic ENN
OutputWithPrior = networks_base.OutputWithPrior
Input = chex.Array # Input frame is an array
Hidden = chex.Array # Hidden state is an array
HiddenA = chex.Array # Hidden state including action representation
class ActionEmbedding(te.Protocol):
def __call__(self, hidden: Hidden, action: int) -> HiddenA:
"""Takes in a batch of hiddens and adds action to representation."""
class PredictionOutput(tp.NamedTuple):
"""Output of the prediction network."""
reward: OutputWithPrior
value: OutputWithPrior
policy: OutputWithPrior # Logits
extra: tp.Dict[str, chex.Array] = {}
@dataclasses.dataclass
class AgentModel:
"""Agent's model of the environment."""
representation: _Enn[Input, OutputWithPrior] # Maps o_t, index --> h_t
action_embedding: ActionEmbedding # Maps h_t, a_t --> h_plus_a
dynamics: _Enn[HiddenA, OutputWithPrior] # Maps h_plus_a, index --> h_tp1
prediction: _Enn[Hidden, PredictionOutput] # Maps h_tp1, index --> (r, v, p)
class DepthOneSearchOutput(tp.NamedTuple):
"""The output of depth one search over actions."""
root: PredictionOutput # Output at the root node
children: tp.Sequence[PredictionOutput] # Outputs for each action
ApplyOneStep = base.ApplyFn[Input, DepthOneSearchOutput]
EnnOneStep = _Enn[Input, DepthOneSearchOutput]
def make_enn_onestep(model: AgentModel, num_actions: int) -> EnnOneStep:
"""Combine pieces of an AgentModel for feed-forward learning.
WARNING: We assume that none of the hk.State is used. We use _ for the unused
states returned by the apply and init functions. We assume that a single
params contains *all* the params for all the network pieces. We also assume
integer actions starting from 0.
Args:
model: an AgentModel that defines the network architectures.
num_actions: number of actions to compute Q-values for (assumes 0-start).
Returns:
ENN that forwards input -> DepthOneSearchOutput as if it was feed-forward.
"""
def apply(
params: hk.Params,
dummy_state: hk.State,
inputs: Input,
index: base.Index,
) -> tp.Tuple[DepthOneSearchOutput, hk.State]:
# Form the hidden units from the representation network.
h_t, _ = model.representation.apply(params, dummy_state, inputs, index)
# Reward and value prediction at the root node
root, _ = model.prediction.apply(params, dummy_state, h_t.preds, index)
children = []
for action in range(num_actions):
# Incorporate action into representation
h_plus_a = model.action_embedding(h_t.preds, action)
# Forward the dynamics portion to make the next hidden state.
h_tp1, _ = model.dynamics.apply(params, dummy_state, h_plus_a, index)
# Forward the network predictions
output, _ = model.prediction.apply(
params, dummy_state, h_tp1.preds, index)
children.append(output)
return DepthOneSearchOutput(root, children), {}
def init(
key: chex.PRNGKey,
inputs: Input,
index: base.Index,
) -> tp.Tuple[hk.Params, hk.State]:
# Splitting random keys
repr_key, dynamic_key, pred_key = jax.random.split(key, 3)
# Dummy network state
dummy_state = {}
# Representation network
repr_params, _ = model.representation.init(repr_key, inputs, index)
# Dynamics network
h_t, _ = model.representation.apply(repr_params, dummy_state, inputs, index)
# Assumes integer actions and selects action=0
h_plus_a = model.action_embedding(h_t.preds, 0)
dynamic_params, _ = model.dynamics.init(dynamic_key, h_plus_a, index)
# Prediction network
h_tp1, _ = model.dynamics.apply(
dynamic_params, dummy_state, h_plus_a, index)
pred_params, _ = model.prediction.init(pred_key, h_tp1.preds, index)
return {**repr_params, **dynamic_params, **pred_params}, {}
return EnnOneStep(apply, init, model.prediction.indexer)
def stack_action_rewards(net_out: DepthOneSearchOutput) -> chex.Array:
"""Returns a jnp array of reward predictions of shape (batch, actions)."""
stacked_out = jax.tree_util.tree_map(
lambda *args: jnp.stack([*args], axis=1), *net_out.children)
rewards = jnp.squeeze(stacked_out.reward.preds, axis=-1)
batch_size = net_out.root.reward.preds.shape[0]
num_actions = len(net_out.children)
chex.assert_shape(rewards, [batch_size, num_actions])
return rewards
def stack_action_values(net_out: DepthOneSearchOutput) -> chex.Array:
"""Returns a jnp array of value predictions of shape (batch, actions)."""
stacked_out = jax.tree_util.tree_map(
lambda *args: jnp.stack([*args], axis=1), *net_out.children)
values = jnp.squeeze(stacked_out.value.preds, axis=-1)
batch_size = net_out.root.value.preds.shape[0]
num_actions = len(net_out.children)
chex.assert_shape(values, [batch_size, num_actions])
return values
|
enn_acme-master
|
enn_acme/experiments/model_based/base.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.