id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
21,900
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
RandomNormalInitializer
def RandomNormalInitializer(stddev=1e-2): """An initializer function for random normal coefficients.""" def init(shape, rng): return (stddev * backend.random.normal(rng, shape)).astype('float32') return init
python
def RandomNormalInitializer(stddev=1e-2): """An initializer function for random normal coefficients.""" def init(shape, rng): return (stddev * backend.random.normal(rng, shape)).astype('float32') return init
[ "def", "RandomNormalInitializer", "(", "stddev", "=", "1e-2", ")", ":", "def", "init", "(", "shape", ",", "rng", ")", ":", "return", "(", "stddev", "*", "backend", ".", "random", ".", "normal", "(", "rng", ",", "shape", ")", ")", ".", "astype", "(", ...
An initializer function for random normal coefficients.
[ "An", "initializer", "function", "for", "random", "normal", "coefficients", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L42-L46
21,901
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
GlorotNormalInitializer
def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)): """An initializer function for random Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] size = onp.prod(onp.delete(shape, [in_dim, out_dim])) std = scale / np.sqrt((fan_in + fan_out) /...
python
def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)): """An initializer function for random Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] size = onp.prod(onp.delete(shape, [in_dim, out_dim])) std = scale / np.sqrt((fan_in + fan_out) /...
[ "def", "GlorotNormalInitializer", "(", "out_dim", "=", "0", ",", "in_dim", "=", "1", ",", "scale", "=", "onp", ".", "sqrt", "(", "2", ")", ")", ":", "def", "init", "(", "shape", ",", "rng", ")", ":", "fan_in", ",", "fan_out", "=", "shape", "[", "...
An initializer function for random Glorot-scaled coefficients.
[ "An", "initializer", "function", "for", "random", "Glorot", "-", "scaled", "coefficients", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L49-L56
21,902
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
GlorotUniformInitializer
def GlorotUniformInitializer(out_dim=0, in_dim=1): """An initializer function for random uniform Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] std = np.sqrt(2.0 / (fan_in + fan_out)) a = np.sqrt(3.0) * std return backend.random.uniform(rng, shap...
python
def GlorotUniformInitializer(out_dim=0, in_dim=1): """An initializer function for random uniform Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] std = np.sqrt(2.0 / (fan_in + fan_out)) a = np.sqrt(3.0) * std return backend.random.uniform(rng, shap...
[ "def", "GlorotUniformInitializer", "(", "out_dim", "=", "0", ",", "in_dim", "=", "1", ")", ":", "def", "init", "(", "shape", ",", "rng", ")", ":", "fan_in", ",", "fan_out", "=", "shape", "[", "in_dim", "]", ",", "shape", "[", "out_dim", "]", "std", ...
An initializer function for random uniform Glorot-scaled coefficients.
[ "An", "initializer", "function", "for", "random", "uniform", "Glorot", "-", "scaled", "coefficients", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L59-L66
21,903
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
one_hot
def one_hot(x, size, dtype=np.float32): """Make a n+1 dim one-hot array from n dim int-categorical array.""" return np.array(x[..., np.newaxis] == np.arange(size), dtype)
python
def one_hot(x, size, dtype=np.float32): """Make a n+1 dim one-hot array from n dim int-categorical array.""" return np.array(x[..., np.newaxis] == np.arange(size), dtype)
[ "def", "one_hot", "(", "x", ",", "size", ",", "dtype", "=", "np", ".", "float32", ")", ":", "return", "np", ".", "array", "(", "x", "[", "...", ",", "np", ".", "newaxis", "]", "==", "np", ".", "arange", "(", "size", ")", ",", "dtype", ")" ]
Make a n+1 dim one-hot array from n dim int-categorical array.
[ "Make", "a", "n", "+", "1", "dim", "one", "-", "hot", "array", "from", "n", "dim", "int", "-", "categorical", "array", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L69-L71
21,904
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
padtype_to_pads
def padtype_to_pads(in_shape, window_shape, window_strides, padding): """Convert padding string to list of pairs of pad values.""" padding = padding.upper() if padding == 'SAME': out_shape = onp.ceil( onp.true_divide(in_shape, window_strides)).astype(int) pad_sizes = [max((out_size - 1) * stride +...
python
def padtype_to_pads(in_shape, window_shape, window_strides, padding): """Convert padding string to list of pairs of pad values.""" padding = padding.upper() if padding == 'SAME': out_shape = onp.ceil( onp.true_divide(in_shape, window_strides)).astype(int) pad_sizes = [max((out_size - 1) * stride +...
[ "def", "padtype_to_pads", "(", "in_shape", ",", "window_shape", ",", "window_strides", ",", "padding", ")", ":", "padding", "=", "padding", ".", "upper", "(", ")", "if", "padding", "==", "'SAME'", ":", "out_shape", "=", "onp", ".", "ceil", "(", "onp", "....
Convert padding string to list of pairs of pad values.
[ "Convert", "padding", "string", "to", "list", "of", "pairs", "of", "pad", "values", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L181-L196
21,905
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
_flatten_output_shape
def _flatten_output_shape(input_shape, num_axis_to_keep=1): """Output shape of a flatten layer.""" if num_axis_to_keep >= len(input_shape): raise ValueError( "num_axis_to_keep[%d] should be less than input's rank[%d]" % (num_axis_to_keep, len(input_shape))) return tuple(input_shape[:num_axis_t...
python
def _flatten_output_shape(input_shape, num_axis_to_keep=1): """Output shape of a flatten layer.""" if num_axis_to_keep >= len(input_shape): raise ValueError( "num_axis_to_keep[%d] should be less than input's rank[%d]" % (num_axis_to_keep, len(input_shape))) return tuple(input_shape[:num_axis_t...
[ "def", "_flatten_output_shape", "(", "input_shape", ",", "num_axis_to_keep", "=", "1", ")", ":", "if", "num_axis_to_keep", ">=", "len", "(", "input_shape", ")", ":", "raise", "ValueError", "(", "\"num_axis_to_keep[%d] should be less than input's rank[%d]\"", "%", "(", ...
Output shape of a flatten layer.
[ "Output", "shape", "of", "a", "flatten", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L304-L311
21,906
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
_batch_norm_new_params
def _batch_norm_new_params(input_shape, rng, axis=(0, 1, 2), center=True, scale=True, **kwargs): """Helper to initialize batch norm params.""" del rng, kwargs axis = (axis,) if np.isscalar(axis) else axis shape = tuple(d for i, d in enumerate(input_shape) if i not in axis) beta = np...
python
def _batch_norm_new_params(input_shape, rng, axis=(0, 1, 2), center=True, scale=True, **kwargs): """Helper to initialize batch norm params.""" del rng, kwargs axis = (axis,) if np.isscalar(axis) else axis shape = tuple(d for i, d in enumerate(input_shape) if i not in axis) beta = np...
[ "def", "_batch_norm_new_params", "(", "input_shape", ",", "rng", ",", "axis", "=", "(", "0", ",", "1", ",", "2", ")", ",", "center", "=", "True", ",", "scale", "=", "True", ",", "*", "*", "kwargs", ")", ":", "del", "rng", ",", "kwargs", "axis", "...
Helper to initialize batch norm params.
[ "Helper", "to", "initialize", "batch", "norm", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L321-L329
21,907
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
BatchNorm
def BatchNorm(x, params, axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True, **unused_kwargs): """Layer construction function for a batch normalization layer.""" mean = np.mean(x, axis, keepdims=True) # Fast but less numerically-stable variance calculation than np.var. m1 = np.mean(x**2, axis, ...
python
def BatchNorm(x, params, axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True, **unused_kwargs): """Layer construction function for a batch normalization layer.""" mean = np.mean(x, axis, keepdims=True) # Fast but less numerically-stable variance calculation than np.var. m1 = np.mean(x**2, axis, ...
[ "def", "BatchNorm", "(", "x", ",", "params", ",", "axis", "=", "(", "0", ",", "1", ",", "2", ")", ",", "epsilon", "=", "1e-5", ",", "center", "=", "True", ",", "scale", "=", "True", ",", "*", "*", "unused_kwargs", ")", ":", "mean", "=", "np", ...
Layer construction function for a batch normalization layer.
[ "Layer", "construction", "function", "for", "a", "batch", "normalization", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L333-L357
21,908
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
Dropout
def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs): """Layer construction function for a dropout layer with given rate.""" del params, kwargs if rng is None: msg = ('Dropout layer requires apply_fun to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, in...
python
def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs): """Layer construction function for a dropout layer with given rate.""" del params, kwargs if rng is None: msg = ('Dropout layer requires apply_fun to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, in...
[ "def", "Dropout", "(", "x", ",", "params", ",", "rate", "=", "0.0", ",", "mode", "=", "'train'", ",", "rng", "=", "None", ",", "*", "*", "kwargs", ")", ":", "del", "params", ",", "kwargs", "if", "rng", "is", "None", ":", "msg", "=", "(", "'Drop...
Layer construction function for a dropout layer with given rate.
[ "Layer", "construction", "function", "for", "a", "dropout", "layer", "with", "given", "rate", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L415-L429
21,909
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
Conv._kernel_shape
def _kernel_shape(self, input_shape): """Helper to calculate the kernel shape.""" kernel_size_iter = iter(self._kernel_size) return [self._filters if c == 'O' else input_shape[self._lhs_spec.index('C')] if c == 'I' else next(kernel_size_iter) for c in self._rhs_spec]
python
def _kernel_shape(self, input_shape): """Helper to calculate the kernel shape.""" kernel_size_iter = iter(self._kernel_size) return [self._filters if c == 'O' else input_shape[self._lhs_spec.index('C')] if c == 'I' else next(kernel_size_iter) for c in self._rhs_spec]
[ "def", "_kernel_shape", "(", "self", ",", "input_shape", ")", ":", "kernel_size_iter", "=", "iter", "(", "self", ".", "_kernel_size", ")", "return", "[", "self", ".", "_filters", "if", "c", "==", "'O'", "else", "input_shape", "[", "self", ".", "_lhs_spec",...
Helper to calculate the kernel shape.
[ "Helper", "to", "calculate", "the", "kernel", "shape", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L226-L231
21,910
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
Conv._conv_shape_tuple
def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads): """Compute the shape of a conv given input shapes in canonical order.""" if isinstance(pads, str): pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads) if len(pads) != len(lhs_shape) - 2: msg = 'Wrong number of expl...
python
def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads): """Compute the shape of a conv given input shapes in canonical order.""" if isinstance(pads, str): pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads) if len(pads) != len(lhs_shape) - 2: msg = 'Wrong number of expl...
[ "def", "_conv_shape_tuple", "(", "self", ",", "lhs_shape", ",", "rhs_shape", ",", "strides", ",", "pads", ")", ":", "if", "isinstance", "(", "pads", ",", "str", ")", ":", "pads", "=", "padtype_to_pads", "(", "lhs_shape", "[", "2", ":", "]", ",", "rhs_s...
Compute the shape of a conv given input shapes in canonical order.
[ "Compute", "the", "shape", "of", "a", "conv", "given", "input", "shapes", "in", "canonical", "order", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L233-L245
21,911
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
Conv._conv_general_permutations
def _conv_general_permutations(self, dimension_numbers): """Utility for convolution dimension permutations relative to Conv HLO.""" lhs_spec, rhs_spec, out_spec = dimension_numbers lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C') charpairs = (lhs_char, rhs_char, out_char) for i, (a,...
python
def _conv_general_permutations(self, dimension_numbers): """Utility for convolution dimension permutations relative to Conv HLO.""" lhs_spec, rhs_spec, out_spec = dimension_numbers lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C') charpairs = (lhs_char, rhs_char, out_char) for i, (a,...
[ "def", "_conv_general_permutations", "(", "self", ",", "dimension_numbers", ")", ":", "lhs_spec", ",", "rhs_spec", ",", "out_spec", "=", "dimension_numbers", "lhs_char", ",", "rhs_char", ",", "out_char", "=", "(", "'N'", ",", "'C'", ")", ",", "(", "'O'", ","...
Utility for convolution dimension permutations relative to Conv HLO.
[ "Utility", "for", "convolution", "dimension", "permutations", "relative", "to", "Conv", "HLO", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L247-L275
21,912
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
Conv._conv_general_shape_tuple
def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides, padding, dimension_numbers): """Generalized computation of conv shape.""" lhs_perm, rhs_perm, out_perm = self._conv_general_permutations( dimension_numbers) lhs_trans = onp.take(lhs_shape, lhs_p...
python
def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides, padding, dimension_numbers): """Generalized computation of conv shape.""" lhs_perm, rhs_perm, out_perm = self._conv_general_permutations( dimension_numbers) lhs_trans = onp.take(lhs_shape, lhs_p...
[ "def", "_conv_general_shape_tuple", "(", "self", ",", "lhs_shape", ",", "rhs_shape", ",", "window_strides", ",", "padding", ",", "dimension_numbers", ")", ":", "lhs_perm", ",", "rhs_perm", ",", "out_perm", "=", "self", ".", "_conv_general_permutations", "(", "dime...
Generalized computation of conv shape.
[ "Generalized", "computation", "of", "conv", "shape", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L277-L286
21,913
tensorflow/tensor2tensor
tensor2tensor/rl/dopamine_connector.py
get_create_agent
def get_create_agent(agent_kwargs): """Factory for dopamine agent initialization. Args: agent_kwargs: dict of BatchDQNAgent parameters Returns: Function(sess, environment, summary_writer) -> BatchDQNAgent instance. """ def create_agent(sess, environment, summary_writer=None): """Creates a DQN a...
python
def get_create_agent(agent_kwargs): """Factory for dopamine agent initialization. Args: agent_kwargs: dict of BatchDQNAgent parameters Returns: Function(sess, environment, summary_writer) -> BatchDQNAgent instance. """ def create_agent(sess, environment, summary_writer=None): """Creates a DQN a...
[ "def", "get_create_agent", "(", "agent_kwargs", ")", ":", "def", "create_agent", "(", "sess", ",", "environment", ",", "summary_writer", "=", "None", ")", ":", "\"\"\"Creates a DQN agent.\n\n Simplified version of `dopamine.discrete_domains.train.create_agent`\n\n Args:\n ...
Factory for dopamine agent initialization. Args: agent_kwargs: dict of BatchDQNAgent parameters Returns: Function(sess, environment, summary_writer) -> BatchDQNAgent instance.
[ "Factory", "for", "dopamine", "agent", "initialization", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L274-L305
21,914
tensorflow/tensor2tensor
tensor2tensor/rl/dopamine_connector.py
get_create_batch_env_fun
def get_create_batch_env_fun(batch_env_fn, time_limit): """Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing envi...
python
def get_create_batch_env_fun(batch_env_fn, time_limit): """Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing envi...
[ "def", "get_create_batch_env_fun", "(", "batch_env_fn", ",", "time_limit", ")", ":", "def", "create_env_fun", "(", "game_name", "=", "None", ",", "sticky_actions", "=", "None", ")", ":", "del", "game_name", ",", "sticky_actions", "batch_env", "=", "batch_env_fn", ...
Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing environment.
[ "Factory", "for", "dopamine", "environment", "initialization", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L450-L468
21,915
tensorflow/tensor2tensor
tensor2tensor/rl/dopamine_connector.py
_parse_hparams
def _parse_hparams(hparams): """Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. """ prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"] ret = [] for prefix in prefixes: ret_...
python
def _parse_hparams(hparams): """Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. """ prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"] ret = [] for prefix in prefixes: ret_...
[ "def", "_parse_hparams", "(", "hparams", ")", ":", "prefixes", "=", "[", "\"agent_\"", ",", "\"optimizer_\"", ",", "\"runner_\"", ",", "\"replay_buffer_\"", "]", "ret", "=", "[", "]", "for", "prefix", "in", "prefixes", ":", "ret_dict", "=", "{", "}", "for"...
Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
[ "Split", "hparams", "based", "on", "key", "prefixes", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L471-L491
21,916
tensorflow/tensor2tensor
tensor2tensor/rl/dopamine_connector.py
_DQNAgent._build_replay_buffer
def _build_replay_buffer(self, use_staging): """Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer.""" replay_buffer_kwargs = dict( observation_shape=dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, stack_size=dqn_agent.NATURE_DQN_STACK_SIZE, replay_capacity=self._replay_capacity, ...
python
def _build_replay_buffer(self, use_staging): """Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer.""" replay_buffer_kwargs = dict( observation_shape=dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, stack_size=dqn_agent.NATURE_DQN_STACK_SIZE, replay_capacity=self._replay_capacity, ...
[ "def", "_build_replay_buffer", "(", "self", ",", "use_staging", ")", ":", "replay_buffer_kwargs", "=", "dict", "(", "observation_shape", "=", "dqn_agent", ".", "NATURE_DQN_OBSERVATION_SHAPE", ",", "stack_size", "=", "dqn_agent", ".", "NATURE_DQN_STACK_SIZE", ",", "rep...
Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer.
[ "Build", "WrappedReplayBuffer", "with", "custom", "OutOfGraphReplayBuffer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L60-L79
21,917
tensorflow/tensor2tensor
tensor2tensor/models/video/next_frame_glow.py
next_frame_glow_hparams
def next_frame_glow_hparams(): """Hparams for next_frame_glow.""" hparams = glow.glow_hparams() # Possible modes are conditional and unconditional hparams.add_hparam("gen_mode", "conditional") hparams.add_hparam("learn_top_scale", False) hparams.add_hparam("condition_all_levels", True) # For each video, s...
python
def next_frame_glow_hparams(): """Hparams for next_frame_glow.""" hparams = glow.glow_hparams() # Possible modes are conditional and unconditional hparams.add_hparam("gen_mode", "conditional") hparams.add_hparam("learn_top_scale", False) hparams.add_hparam("condition_all_levels", True) # For each video, s...
[ "def", "next_frame_glow_hparams", "(", ")", ":", "hparams", "=", "glow", ".", "glow_hparams", "(", ")", "# Possible modes are conditional and unconditional", "hparams", ".", "add_hparam", "(", "\"gen_mode\"", ",", "\"conditional\"", ")", "hparams", ".", "add_hparam", ...
Hparams for next_frame_glow.
[ "Hparams", "for", "next_frame_glow", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L37-L87
21,918
tensorflow/tensor2tensor
tensor2tensor/models/video/next_frame_glow.py
next_frame_glow_bair_quant
def next_frame_glow_bair_quant(): """Hparams to reproduce bits-per-pixel results on BAIR action-free dataset.""" hparams = next_frame_glow_hparams() hparams.video_num_input_frames = 3 hparams.video_num_target_frames = 10 hparams.num_train_frames = 4 hparams.num_cond_latents = 3 hparams.depth = 24 hparam...
python
def next_frame_glow_bair_quant(): """Hparams to reproduce bits-per-pixel results on BAIR action-free dataset.""" hparams = next_frame_glow_hparams() hparams.video_num_input_frames = 3 hparams.video_num_target_frames = 10 hparams.num_train_frames = 4 hparams.num_cond_latents = 3 hparams.depth = 24 hparam...
[ "def", "next_frame_glow_bair_quant", "(", ")", ":", "hparams", "=", "next_frame_glow_hparams", "(", ")", "hparams", ".", "video_num_input_frames", "=", "3", "hparams", ".", "video_num_target_frames", "=", "10", "hparams", ".", "num_train_frames", "=", "4", "hparams"...
Hparams to reproduce bits-per-pixel results on BAIR action-free dataset.
[ "Hparams", "to", "reproduce", "bits", "-", "per", "-", "pixel", "results", "on", "BAIR", "action", "-", "free", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L91-L111
21,919
tensorflow/tensor2tensor
tensor2tensor/models/video/next_frame_glow.py
next_frame_glow_bair_qual
def next_frame_glow_bair_qual(): """Hparams for qualitative video generation results.""" hparams = next_frame_glow_bair_quant() hparams.coupling = "additive" hparams.temperature = 0.5 hparams.coupling_width = 392 return hparams
python
def next_frame_glow_bair_qual(): """Hparams for qualitative video generation results.""" hparams = next_frame_glow_bair_quant() hparams.coupling = "additive" hparams.temperature = 0.5 hparams.coupling_width = 392 return hparams
[ "def", "next_frame_glow_bair_qual", "(", ")", ":", "hparams", "=", "next_frame_glow_bair_quant", "(", ")", "hparams", ".", "coupling", "=", "\"additive\"", "hparams", ".", "temperature", "=", "0.5", "hparams", ".", "coupling_width", "=", "392", "return", "hparams"...
Hparams for qualitative video generation results.
[ "Hparams", "for", "qualitative", "video", "generation", "results", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L115-L121
21,920
tensorflow/tensor2tensor
tensor2tensor/models/video/next_frame_glow.py
next_frame_glow_shapes
def next_frame_glow_shapes(): """Hparams for qualitative and quantitative results on shapes dataset.""" hparams = next_frame_glow_bair_quant() hparams.video_num_input_frames = 1 hparams.video_num_target_frames = 2 hparams.num_train_frames = 2 hparams.num_cond_latents = 1 hparams.coupling = "additive" hp...
python
def next_frame_glow_shapes(): """Hparams for qualitative and quantitative results on shapes dataset.""" hparams = next_frame_glow_bair_quant() hparams.video_num_input_frames = 1 hparams.video_num_target_frames = 2 hparams.num_train_frames = 2 hparams.num_cond_latents = 1 hparams.coupling = "additive" hp...
[ "def", "next_frame_glow_shapes", "(", ")", ":", "hparams", "=", "next_frame_glow_bair_quant", "(", ")", "hparams", ".", "video_num_input_frames", "=", "1", "hparams", ".", "video_num_target_frames", "=", "2", "hparams", ".", "num_train_frames", "=", "2", "hparams", ...
Hparams for qualitative and quantitative results on shapes dataset.
[ "Hparams", "for", "qualitative", "and", "quantitative", "results", "on", "shapes", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L125-L138
21,921
tensorflow/tensor2tensor
tensor2tensor/models/basic.py
basic_fc_small
def basic_fc_small(): """Small fully connected model.""" hparams = common_hparams.basic_params1() hparams.learning_rate = 0.1 hparams.batch_size = 128 hparams.hidden_size = 256 hparams.num_hidden_layers = 2 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_deca...
python
def basic_fc_small(): """Small fully connected model.""" hparams = common_hparams.basic_params1() hparams.learning_rate = 0.1 hparams.batch_size = 128 hparams.hidden_size = 256 hparams.num_hidden_layers = 2 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_deca...
[ "def", "basic_fc_small", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "learning_rate", "=", "0.1", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "hidden_size", "=", "256", "hparams", ".", "num_h...
Small fully connected model.
[ "Small", "fully", "connected", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/basic.py#L47-L58
21,922
tensorflow/tensor2tensor
tensor2tensor/data_generators/imagenet.py
imagenet_pixelrnn_generator
def imagenet_pixelrnn_generator(tmp_dir, training, size=_IMAGENET_SMALL_IMAGE_SIZE): """Image generator for Imagenet 64x64 downsampled images. It assumes that the data has been downloaded from http://image-net.org/small/*_32x32.tar or http://image...
python
def imagenet_pixelrnn_generator(tmp_dir, training, size=_IMAGENET_SMALL_IMAGE_SIZE): """Image generator for Imagenet 64x64 downsampled images. It assumes that the data has been downloaded from http://image-net.org/small/*_32x32.tar or http://image...
[ "def", "imagenet_pixelrnn_generator", "(", "tmp_dir", ",", "training", ",", "size", "=", "_IMAGENET_SMALL_IMAGE_SIZE", ")", ":", "if", "size", "==", "_IMAGENET_SMALL_IMAGE_SIZE", ":", "train_prefix", "=", "_IMAGENET_SMALL_TRAIN_PREFIX", "eval_prefix", "=", "_IMAGENET_SMAL...
Image generator for Imagenet 64x64 downsampled images. It assumes that the data has been downloaded from http://image-net.org/small/*_32x32.tar or http://image-net.org/small/*_64x64.tar into tmp_dir. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set,...
[ "Image", "generator", "for", "Imagenet", "64x64", "downsampled", "images", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L56-L98
21,923
tensorflow/tensor2tensor
tensor2tensor/data_generators/imagenet.py
imagenet_preprocess_example
def imagenet_preprocess_example(example, mode, resize_size=None, normalize=True): """Preprocessing used for Imagenet and similar problems.""" resize_size = resize_size or [299, 299] assert resize_size[0] == resize_size[1] image = example["inputs"] if mode == tf.estimator.ModeK...
python
def imagenet_preprocess_example(example, mode, resize_size=None, normalize=True): """Preprocessing used for Imagenet and similar problems.""" resize_size = resize_size or [299, 299] assert resize_size[0] == resize_size[1] image = example["inputs"] if mode == tf.estimator.ModeK...
[ "def", "imagenet_preprocess_example", "(", "example", ",", "mode", ",", "resize_size", "=", "None", ",", "normalize", "=", "True", ")", ":", "resize_size", "=", "resize_size", "or", "[", "299", ",", "299", "]", "assert", "resize_size", "[", "0", "]", "==",...
Preprocessing used for Imagenet and similar problems.
[ "Preprocessing", "used", "for", "Imagenet", "and", "similar", "problems", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L101-L116
21,924
tensorflow/tensor2tensor
tensor2tensor/data_generators/imagenet.py
_crop
def _crop(image, offset_height, offset_width, crop_height, crop_width): """Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input image size but it does assume we know the input image rank. Args: image: `Tensor` image of shape [height, width, chan...
python
def _crop(image, offset_height, offset_width, crop_height, crop_width): """Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input image size but it does assume we know the input image rank. Args: image: `Tensor` image of shape [height, width, chan...
[ "def", "_crop", "(", "image", ",", "offset_height", ",", "offset_width", ",", "crop_height", ",", "crop_width", ")", ":", "original_shape", "=", "tf", ".", "shape", "(", "image", ")", "rank_assertion", "=", "tf", ".", "Assert", "(", "tf", ".", "equal", "...
Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input image size but it does assume we know the input image rank. Args: image: `Tensor` image of shape [height, width, channels]. offset_height: `Tensor` indicating the height offset. offset_w...
[ "Crops", "the", "given", "image", "using", "the", "provided", "offsets", "and", "sizes", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L427-L466
21,925
tensorflow/tensor2tensor
tensor2tensor/data_generators/imagenet.py
distorted_bounding_box_crop
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, ...
python
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, ...
[ "def", "distorted_bounding_box_crop", "(", "image", ",", "bbox", ",", "min_object_covered", "=", "0.1", ",", "aspect_ratio_range", "=", "(", "0.75", ",", "1.33", ")", ",", "area_range", "=", "(", "0.05", ",", "1.0", ")", ",", "max_attempts", "=", "100", ",...
Generates cropped_image using a one of the bboxes randomly distorted. See `tf.image.sample_distorted_bounding_box` for more documentation. Args: image: `Tensor` of image (it will be converted to floats in [0, 1]). bbox: `Tensor` of bounding boxes arranged `[1, num_boxes, coords]` where each coordi...
[ "Generates", "cropped_image", "using", "a", "one", "of", "the", "bboxes", "randomly", "distorted", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L469-L524
21,926
tensorflow/tensor2tensor
tensor2tensor/data_generators/imagenet.py
_at_least_x_are_true
def _at_least_x_are_true(a, b, x): """At least `x` of `a` and `b` `Tensors` are true.""" match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x)
python
def _at_least_x_are_true(a, b, x): """At least `x` of `a` and `b` `Tensors` are true.""" match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x)
[ "def", "_at_least_x_are_true", "(", "a", ",", "b", ",", "x", ")", ":", "match", "=", "tf", ".", "equal", "(", "a", ",", "b", ")", "match", "=", "tf", ".", "cast", "(", "match", ",", "tf", ".", "int32", ")", "return", "tf", ".", "greater_equal", ...
At least `x` of `a` and `b` `Tensors` are true.
[ "At", "least", "x", "of", "a", "and", "b", "Tensors", "are", "true", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L552-L556
21,927
tensorflow/tensor2tensor
tensor2tensor/data_generators/imagenet.py
_do_scale
def _do_scale(image, size): """Rescale the image by scaling the smaller spatial dimension to `size`.""" shape = tf.cast(tf.shape(image), tf.float32) w_greater = tf.greater(shape[0], shape[1]) shape = tf.cond(w_greater, lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32), ...
python
def _do_scale(image, size): """Rescale the image by scaling the smaller spatial dimension to `size`.""" shape = tf.cast(tf.shape(image), tf.float32) w_greater = tf.greater(shape[0], shape[1]) shape = tf.cond(w_greater, lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32), ...
[ "def", "_do_scale", "(", "image", ",", "size", ")", ":", "shape", "=", "tf", ".", "cast", "(", "tf", ".", "shape", "(", "image", ")", ",", "tf", ".", "float32", ")", "w_greater", "=", "tf", ".", "greater", "(", "shape", "[", "0", "]", ",", "sha...
Rescale the image by scaling the smaller spatial dimension to `size`.
[ "Rescale", "the", "image", "by", "scaling", "the", "smaller", "spatial", "dimension", "to", "size", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L559-L567
21,928
tensorflow/tensor2tensor
tensor2tensor/data_generators/imagenet.py
_center_crop
def _center_crop(image, size): """Crops to center of image with specified `size`.""" image_height = tf.shape(image)[0] image_width = tf.shape(image)[1] offset_height = ((image_height - size) + 1) / 2 offset_width = ((image_width - size) + 1) / 2 image = _crop(image, offset_height, offset_width, size, size)...
python
def _center_crop(image, size): """Crops to center of image with specified `size`.""" image_height = tf.shape(image)[0] image_width = tf.shape(image)[1] offset_height = ((image_height - size) + 1) / 2 offset_width = ((image_width - size) + 1) / 2 image = _crop(image, offset_height, offset_width, size, size)...
[ "def", "_center_crop", "(", "image", ",", "size", ")", ":", "image_height", "=", "tf", ".", "shape", "(", "image", ")", "[", "0", "]", "image_width", "=", "tf", ".", "shape", "(", "image", ")", "[", "1", "]", "offset_height", "=", "(", "(", "image_...
Crops to center of image with specified `size`.
[ "Crops", "to", "center", "of", "image", "with", "specified", "size", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L570-L578
21,929
tensorflow/tensor2tensor
tensor2tensor/data_generators/imagenet.py
_normalize
def _normalize(image): """Normalize the image to zero mean and unit variance.""" offset = tf.constant(MEAN_RGB, shape=[1, 1, 3]) image -= offset scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3]) image /= scale return image
python
def _normalize(image): """Normalize the image to zero mean and unit variance.""" offset = tf.constant(MEAN_RGB, shape=[1, 1, 3]) image -= offset scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3]) image /= scale return image
[ "def", "_normalize", "(", "image", ")", ":", "offset", "=", "tf", ".", "constant", "(", "MEAN_RGB", ",", "shape", "=", "[", "1", ",", "1", ",", "3", "]", ")", "image", "-=", "offset", "scale", "=", "tf", ".", "constant", "(", "STDDEV_RGB", ",", "...
Normalize the image to zero mean and unit variance.
[ "Normalize", "the", "image", "to", "zero", "mean", "and", "unit", "variance", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L581-L588
21,930
tensorflow/tensor2tensor
tensor2tensor/trax/learning_rate.py
MultifactorSchedule
def MultifactorSchedule(history=None, factors="constant * linear_warmup * rsqrt_decay", constant=0.1, warmup_steps=100, decay_factor=0.5, steps_per_decay=20000): """Factor-based learning rate schedu...
python
def MultifactorSchedule(history=None, factors="constant * linear_warmup * rsqrt_decay", constant=0.1, warmup_steps=100, decay_factor=0.5, steps_per_decay=20000): """Factor-based learning rate schedu...
[ "def", "MultifactorSchedule", "(", "history", "=", "None", ",", "factors", "=", "\"constant * linear_warmup * rsqrt_decay\"", ",", "constant", "=", "0.1", ",", "warmup_steps", "=", "100", ",", "decay_factor", "=", "0.5", ",", "steps_per_decay", "=", "20000", ")", ...
Factor-based learning rate schedule. Interprets factors in the factors string which can consist of: * constant: interpreted as the constant value, * linear_warmup: interpreted as linear warmup until warmup_steps, * rsqrt_decay: divide by square root of max(step, warmup_steps) * decay_every: Every k steps dec...
[ "Factor", "-", "based", "learning", "rate", "schedule", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/learning_rate.py#L42-L92
21,931
tensorflow/tensor2tensor
tensor2tensor/trax/learning_rate.py
EvalAdjustingSchedule
def EvalAdjustingSchedule(history, constant=0.1, steps_to_decrease=20, improvement_margin=0.001, decrease_rate=1.5, history_mode="eval", metric="metrics/accuracy"):...
python
def EvalAdjustingSchedule(history, constant=0.1, steps_to_decrease=20, improvement_margin=0.001, decrease_rate=1.5, history_mode="eval", metric="metrics/accuracy"):...
[ "def", "EvalAdjustingSchedule", "(", "history", ",", "constant", "=", "0.1", ",", "steps_to_decrease", "=", "20", ",", "improvement_margin", "=", "0.001", ",", "decrease_rate", "=", "1.5", ",", "history_mode", "=", "\"eval\"", ",", "metric", "=", "\"metrics/accu...
Learning rate that decreases when eval metric stalls. If the chosen metric does not improve by improvement_margin for as many as steps_to_decrease steps, then the constant gets decreased by decrease rate. Finally, the MultifactorSchedule gets called with the adjusted constant. Args: history: trax.history....
[ "Learning", "rate", "that", "decreases", "when", "eval", "metric", "stalls", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/learning_rate.py#L96-L143
21,932
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
project_hidden
def project_hidden(x, projection_tensors, hidden_size, num_blocks): """Project encoder hidden state under num_blocks using projection tensors. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. projection_tensors: Projection tensors used to project the hidden state. hidden_s...
python
def project_hidden(x, projection_tensors, hidden_size, num_blocks): """Project encoder hidden state under num_blocks using projection tensors. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. projection_tensors: Projection tensors used to project the hidden state. hidden_s...
[ "def", "project_hidden", "(", "x", ",", "projection_tensors", ",", "hidden_size", ",", "num_blocks", ")", ":", "batch_size", ",", "latent_dim", ",", "_", "=", "common_layers", ".", "shape_list", "(", "x", ")", "x", "=", "tf", ".", "reshape", "(", "x", ",...
Project encoder hidden state under num_blocks using projection tensors. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. projection_tensors: Projection tensors used to project the hidden state. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in D...
[ "Project", "encoder", "hidden", "state", "under", "num_blocks", "using", "projection", "tensors", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L33-L54
21,933
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
slice_hidden
def slice_hidden(x, hidden_size, num_blocks): """Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size...
python
def slice_hidden(x, hidden_size, num_blocks): """Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size...
[ "def", "slice_hidden", "(", "x", ",", "hidden_size", ",", "num_blocks", ")", ":", "batch_size", ",", "latent_dim", ",", "_", "=", "common_layers", ".", "shape_list", "(", "x", ")", "block_dim", "=", "hidden_size", "//", "num_blocks", "x_sliced", "=", "tf", ...
Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size, latent_dim, num_blocks, block_dim].
[ "Slice", "encoder", "hidden", "state", "under", "num_blocks", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L57-L72
21,934
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
embedding_lookup
def embedding_lookup(x, means, num_blocks, block_v_size, bottleneck_kind="dvq", random_top_k=1, soft_em=False, num_samples=1, do_hard_gumbel_softmax=Fal...
python
def embedding_lookup(x, means, num_blocks, block_v_size, bottleneck_kind="dvq", random_top_k=1, soft_em=False, num_samples=1, do_hard_gumbel_softmax=Fal...
[ "def", "embedding_lookup", "(", "x", ",", "means", ",", "num_blocks", ",", "block_v_size", ",", "bottleneck_kind", "=", "\"dvq\"", ",", "random_top_k", "=", "1", ",", "soft_em", "=", "False", ",", "num_samples", "=", "1", ",", "do_hard_gumbel_softmax", "=", ...
Compute nearest neighbors and loss for training the embeddings via DVQ. Args: x: Continuous encodings of shape [batch_size, latent_dim, num_blocks, block_dim]. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. num_blocks: Number of blocks in DVQ. block_v_size: Number of tab...
[ "Compute", "nearest", "neighbors", "and", "loss", "for", "training", "the", "embeddings", "via", "DVQ", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L144-L222
21,935
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
vae
def vae(x, z_size, name=None): """Simple variational autoencoder without discretization. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. name: Name for the bottleneck scope. Returns: Embedding function, latent, loss, mu and...
python
def vae(x, z_size, name=None): """Simple variational autoencoder without discretization. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. name: Name for the bottleneck scope. Returns: Embedding function, latent, loss, mu and...
[ "def", "vae", "(", "x", ",", "z_size", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"vae\"", ")", ":", "mu", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "z_size", ","...
Simple variational autoencoder without discretization. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. name: Name for the bottleneck scope. Returns: Embedding function, latent, loss, mu and log_simga.
[ "Simple", "variational", "autoencoder", "without", "discretization", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L360-L381
21,936
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
gumbel_sample
def gumbel_sample(shape): """Sample from the Gumbel distribution, protect from overflows. Args: shape: Shape of Gumbel samples. Returns: Noise drawn from Gumbel distribution. """ uniform_samples = tf.random_uniform(shape, minval=0.00001, maxval=0.99998) return -tf.log(-tf.log(uniform_samples))
python
def gumbel_sample(shape): """Sample from the Gumbel distribution, protect from overflows. Args: shape: Shape of Gumbel samples. Returns: Noise drawn from Gumbel distribution. """ uniform_samples = tf.random_uniform(shape, minval=0.00001, maxval=0.99998) return -tf.log(-tf.log(uniform_samples))
[ "def", "gumbel_sample", "(", "shape", ")", ":", "uniform_samples", "=", "tf", ".", "random_uniform", "(", "shape", ",", "minval", "=", "0.00001", ",", "maxval", "=", "0.99998", ")", "return", "-", "tf", ".", "log", "(", "-", "tf", ".", "log", "(", "u...
Sample from the Gumbel distribution, protect from overflows. Args: shape: Shape of Gumbel samples. Returns: Noise drawn from Gumbel distribution.
[ "Sample", "from", "the", "Gumbel", "distribution", "protect", "from", "overflows", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L402-L412
21,937
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
gumbel_softmax
def gumbel_softmax(x, z_size, mode, softmax_k=0, temperature_warmup_steps=150000, summary=True, name=None): """Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottlen...
python
def gumbel_softmax(x, z_size, mode, softmax_k=0, temperature_warmup_steps=150000, summary=True, name=None): """Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottlen...
[ "def", "gumbel_softmax", "(", "x", ",", "z_size", ",", "mode", ",", "softmax_k", "=", "0", ",", "temperature_warmup_steps", "=", "150000", ",", "summary", "=", "True", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ...
Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. mode: tf.estimator.ModeKeys. softmax_k: If > 0 then do top-k softmax. temperature_warmup_steps: Number of steps it takes to decay temp...
[ "Gumbel", "softmax", "discretization", "bottleneck", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L415-L475
21,938
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
vq_body
def vq_body(x, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Discretize each x into one of codebook_size codes.""" x_shape = common_layers.shape...
python
def vq_body(x, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Discretize each x into one of codebook_size codes.""" x_shape = common_layers.shape...
[ "def", "vq_body", "(", "x", ",", "codebook_size", ",", "beta", "=", "0.25", ",", "decay", "=", "0.999", ",", "epsilon", "=", "1e-5", ",", "soft_em", "=", "False", ",", "num_samples", "=", "10", ",", "temperature", "=", "None", ",", "do_update", "=", ...
Discretize each x into one of codebook_size codes.
[ "Discretize", "each", "x", "into", "one", "of", "codebook_size", "codes", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L957-L1004
21,939
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
vq_loss
def vq_loss(x, targets, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Compute the loss of large vocab tensors using a VQAE codebook. ...
python
def vq_loss(x, targets, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Compute the loss of large vocab tensors using a VQAE codebook. ...
[ "def", "vq_loss", "(", "x", ",", "targets", ",", "codebook_size", ",", "beta", "=", "0.25", ",", "decay", "=", "0.999", ",", "epsilon", "=", "1e-5", ",", "soft_em", "=", "False", ",", "num_samples", "=", "10", ",", "temperature", "=", "None", ",", "d...
Compute the loss of large vocab tensors using a VQAE codebook. Args: x: Tensor of inputs to be quantized to nearest code targets: Tensor of target indices to target codes codebook_size: Size of quantization codebook beta: scalar float for moving averages decay: scalar float for moving averages ...
[ "Compute", "the", "loss", "of", "large", "vocab", "tensors", "using", "a", "VQAE", "codebook", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1007-L1071
21,940
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
tanh_discrete_bottleneck
def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode): """Simple discretization through tanh, flip bottleneck_noise many bits.""" x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck") d0 = tf.stop_gradient(2.0 * tf.to_floa...
python
def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode): """Simple discretization through tanh, flip bottleneck_noise many bits.""" x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck") d0 = tf.stop_gradient(2.0 * tf.to_floa...
[ "def", "tanh_discrete_bottleneck", "(", "x", ",", "bottleneck_bits", ",", "bottleneck_noise", ",", "discretize_warmup_steps", ",", "mode", ")", ":", "x", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "bottleneck_bits", ",", "name", "=", "\"tanh_discre...
Simple discretization through tanh, flip bottleneck_noise many bits.
[ "Simple", "discretization", "through", "tanh", "flip", "bottleneck_noise", "many", "bits", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1374-L1390
21,941
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
tanh_discrete_unbottleneck
def tanh_discrete_unbottleneck(x, hidden_size): """Simple un-discretization from tanh.""" x = tf.layers.dense(x, hidden_size, name="tanh_discrete_unbottleneck") return x
python
def tanh_discrete_unbottleneck(x, hidden_size): """Simple un-discretization from tanh.""" x = tf.layers.dense(x, hidden_size, name="tanh_discrete_unbottleneck") return x
[ "def", "tanh_discrete_unbottleneck", "(", "x", ",", "hidden_size", ")", ":", "x", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "hidden_size", ",", "name", "=", "\"tanh_discrete_unbottleneck\"", ")", "return", "x" ]
Simple un-discretization from tanh.
[ "Simple", "un", "-", "discretization", "from", "tanh", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1393-L1396
21,942
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
isemhash_bottleneck
def isemhash_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode, isemhash_noise_dev=0.5, isemhash_mix_prob=0.5): """Improved semantic hashing bott...
python
def isemhash_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode, isemhash_noise_dev=0.5, isemhash_mix_prob=0.5): """Improved semantic hashing bott...
[ "def", "isemhash_bottleneck", "(", "x", ",", "bottleneck_bits", ",", "bottleneck_noise", ",", "discretize_warmup_steps", ",", "mode", ",", "isemhash_noise_dev", "=", "0.5", ",", "isemhash_mix_prob", "=", "0.5", ")", ":", "with", "tf", ".", "variable_scope", "(", ...
Improved semantic hashing bottleneck.
[ "Improved", "semantic", "hashing", "bottleneck", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1399-L1426
21,943
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
isemhash_unbottleneck
def isemhash_unbottleneck(x, hidden_size, isemhash_filter_size_multiplier=1.0): """Improved semantic hashing un-bottleneck.""" filter_size = int(hidden_size * isemhash_filter_size_multiplier) x = 0.5 * (x - 1.0) # Move from [-1, 1] to [0, 1]. with tf.variable_scope("isemhash_unbottleneck"): h1a = tf.layers...
python
def isemhash_unbottleneck(x, hidden_size, isemhash_filter_size_multiplier=1.0): """Improved semantic hashing un-bottleneck.""" filter_size = int(hidden_size * isemhash_filter_size_multiplier) x = 0.5 * (x - 1.0) # Move from [-1, 1] to [0, 1]. with tf.variable_scope("isemhash_unbottleneck"): h1a = tf.layers...
[ "def", "isemhash_unbottleneck", "(", "x", ",", "hidden_size", ",", "isemhash_filter_size_multiplier", "=", "1.0", ")", ":", "filter_size", "=", "int", "(", "hidden_size", "*", "isemhash_filter_size_multiplier", ")", "x", "=", "0.5", "*", "(", "x", "-", "1.0", ...
Improved semantic hashing un-bottleneck.
[ "Improved", "semantic", "hashing", "un", "-", "bottleneck", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1429-L1437
21,944
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
parametrized_bottleneck
def parametrized_bottleneck(x, hparams): """Meta-function calling all the above bottlenecks with hparams.""" if hparams.bottleneck_kind == "tanh_discrete": d, _ = tanh_discrete_bottleneck( x, hparams.bottleneck_bits, hparams.bottleneck_noise * 0.5, hparams.discretize_warmup_steps, hparams.mode) ...
python
def parametrized_bottleneck(x, hparams): """Meta-function calling all the above bottlenecks with hparams.""" if hparams.bottleneck_kind == "tanh_discrete": d, _ = tanh_discrete_bottleneck( x, hparams.bottleneck_bits, hparams.bottleneck_noise * 0.5, hparams.discretize_warmup_steps, hparams.mode) ...
[ "def", "parametrized_bottleneck", "(", "x", ",", "hparams", ")", ":", "if", "hparams", ".", "bottleneck_kind", "==", "\"tanh_discrete\"", ":", "d", ",", "_", "=", "tanh_discrete_bottleneck", "(", "x", ",", "hparams", ".", "bottleneck_bits", ",", "hparams", "."...
Meta-function calling all the above bottlenecks with hparams.
[ "Meta", "-", "function", "calling", "all", "the", "above", "bottlenecks", "with", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1440-L1476
21,945
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
parametrized_unbottleneck
def parametrized_unbottleneck(x, hidden_size, hparams): """Meta-function calling all the above un-bottlenecks with hparams.""" if hparams.bottleneck_kind == "tanh_discrete": return tanh_discrete_unbottleneck(x, hidden_size) if hparams.bottleneck_kind == "isemhash": return isemhash_unbottleneck(x, hidden_s...
python
def parametrized_unbottleneck(x, hidden_size, hparams): """Meta-function calling all the above un-bottlenecks with hparams.""" if hparams.bottleneck_kind == "tanh_discrete": return tanh_discrete_unbottleneck(x, hidden_size) if hparams.bottleneck_kind == "isemhash": return isemhash_unbottleneck(x, hidden_s...
[ "def", "parametrized_unbottleneck", "(", "x", ",", "hidden_size", ",", "hparams", ")", ":", "if", "hparams", ".", "bottleneck_kind", "==", "\"tanh_discrete\"", ":", "return", "tanh_discrete_unbottleneck", "(", "x", ",", "hidden_size", ")", "if", "hparams", ".", ...
Meta-function calling all the above un-bottlenecks with hparams.
[ "Meta", "-", "function", "calling", "all", "the", "above", "un", "-", "bottlenecks", "with", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1479-L1489
21,946
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
iaf_hparams
def iaf_hparams(hidden_size=512, filter_size=4096): """Create hyperpameters for inverse autoregressive flows. Args: hidden_size: Width of attention layers and neural network output layer. filter_size: Hidden layer width for neural network. Returns: hparams: Hyperpameters with basic presets for inver...
python
def iaf_hparams(hidden_size=512, filter_size=4096): """Create hyperpameters for inverse autoregressive flows. Args: hidden_size: Width of attention layers and neural network output layer. filter_size: Hidden layer width for neural network. Returns: hparams: Hyperpameters with basic presets for inver...
[ "def", "iaf_hparams", "(", "hidden_size", "=", "512", ",", "filter_size", "=", "4096", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "# Attention hyperparameters.", "hparams", ".", "hidden_size", "=", "hidden_size", "hparams", ".", ...
Create hyperpameters for inverse autoregressive flows. Args: hidden_size: Width of attention layers and neural network output layer. filter_size: Hidden layer width for neural network. Returns: hparams: Hyperpameters with basic presets for inverse autoregressive flows.
[ "Create", "hyperpameters", "for", "inverse", "autoregressive", "flows", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1492-L1528
21,947
tensorflow/tensor2tensor
tensor2tensor/data_generators/lm1b.py
_original_vocab
def _original_vocab(tmp_dir): """Returns a set containing the original vocabulary. This is important for comparing with published results. Args: tmp_dir: directory containing dataset. Returns: a set of strings """ vocab_url = ("http://download.tensorflow.org/models/LM_LSTM_CNN/" "v...
python
def _original_vocab(tmp_dir): """Returns a set containing the original vocabulary. This is important for comparing with published results. Args: tmp_dir: directory containing dataset. Returns: a set of strings """ vocab_url = ("http://download.tensorflow.org/models/LM_LSTM_CNN/" "v...
[ "def", "_original_vocab", "(", "tmp_dir", ")", ":", "vocab_url", "=", "(", "\"http://download.tensorflow.org/models/LM_LSTM_CNN/\"", "\"vocab-2016-09-10.txt\"", ")", "vocab_filename", "=", "os", ".", "path", ".", "basename", "(", "vocab_url", "+", "\".en\"", ")", "voc...
Returns a set containing the original vocabulary. This is important for comparing with published results. Args: tmp_dir: directory containing dataset. Returns: a set of strings
[ "Returns", "a", "set", "containing", "the", "original", "vocabulary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/lm1b.py#L35-L55
21,948
tensorflow/tensor2tensor
tensor2tensor/data_generators/lm1b.py
_replace_oov
def _replace_oov(original_vocab, line): """Replace out-of-vocab words with "UNK". This maintains compatibility with published results. Args: original_vocab: a set of strings (The standard vocabulary for the dataset) line: a unicode string - a space-delimited sequence of words. Returns: a unicode ...
python
def _replace_oov(original_vocab, line): """Replace out-of-vocab words with "UNK". This maintains compatibility with published results. Args: original_vocab: a set of strings (The standard vocabulary for the dataset) line: a unicode string - a space-delimited sequence of words. Returns: a unicode ...
[ "def", "_replace_oov", "(", "original_vocab", ",", "line", ")", ":", "return", "u\" \"", ".", "join", "(", "[", "word", "if", "word", "in", "original_vocab", "else", "u\"UNK\"", "for", "word", "in", "line", ".", "split", "(", ")", "]", ")" ]
Replace out-of-vocab words with "UNK". This maintains compatibility with published results. Args: original_vocab: a set of strings (The standard vocabulary for the dataset) line: a unicode string - a space-delimited sequence of words. Returns: a unicode string - a space-delimited sequence of words.
[ "Replace", "out", "-", "of", "-", "vocab", "words", "with", "UNK", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/lm1b.py#L58-L71
21,949
tensorflow/tensor2tensor
tensor2tensor/models/research/cycle_gan.py
lossfn
def lossfn(real_input, fake_input, compress, hparams, lsgan, name): """Loss function.""" eps = 1e-12 with tf.variable_scope(name): d1 = discriminator(real_input, compress, hparams, "discriminator") d2 = discriminator(fake_input, compress, hparams, "discriminator", reuse=True) if...
python
def lossfn(real_input, fake_input, compress, hparams, lsgan, name): """Loss function.""" eps = 1e-12 with tf.variable_scope(name): d1 = discriminator(real_input, compress, hparams, "discriminator") d2 = discriminator(fake_input, compress, hparams, "discriminator", reuse=True) if...
[ "def", "lossfn", "(", "real_input", ",", "fake_input", ",", "compress", ",", "hparams", ",", "lsgan", ",", "name", ")", ":", "eps", "=", "1e-12", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "d1", "=", "discriminator", "(", "real_input", ...
Loss function.
[ "Loss", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/cycle_gan.py#L46-L63
21,950
tensorflow/tensor2tensor
tensor2tensor/models/research/cycle_gan.py
cycle_gan_internal
def cycle_gan_internal(inputs, targets, _, hparams): """Cycle GAN, main step used for training.""" with tf.variable_scope("cycle_gan"): # Embed inputs and targets. inputs_orig, targets_orig = tf.to_int32(inputs), tf.to_int32(targets) inputs = common_layers.embedding( inputs_orig, hparams.vocab_s...
python
def cycle_gan_internal(inputs, targets, _, hparams): """Cycle GAN, main step used for training.""" with tf.variable_scope("cycle_gan"): # Embed inputs and targets. inputs_orig, targets_orig = tf.to_int32(inputs), tf.to_int32(targets) inputs = common_layers.embedding( inputs_orig, hparams.vocab_s...
[ "def", "cycle_gan_internal", "(", "inputs", ",", "targets", ",", "_", ",", "hparams", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"cycle_gan\"", ")", ":", "# Embed inputs and targets.", "inputs_orig", ",", "targets_orig", "=", "tf", ".", "to_int32", ...
Cycle GAN, main step used for training.
[ "Cycle", "GAN", "main", "step", "used", "for", "training", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/cycle_gan.py#L72-L113
21,951
tensorflow/tensor2tensor
tensor2tensor/models/video/nfg_interpolate.py
decode_hparams
def decode_hparams(overrides=""): """Hparams for decoding.""" hparams = decoding.decode_hparams() # Number of interpolations between [0.0, 1.0]. hparams.add_hparam("num_interp", 11) # Which level(s) to interpolate. hparams.add_hparam("level_interp", [0, 1, 2]) # "all" or "ranked", interpolate all channels...
python
def decode_hparams(overrides=""): """Hparams for decoding.""" hparams = decoding.decode_hparams() # Number of interpolations between [0.0, 1.0]. hparams.add_hparam("num_interp", 11) # Which level(s) to interpolate. hparams.add_hparam("level_interp", [0, 1, 2]) # "all" or "ranked", interpolate all channels...
[ "def", "decode_hparams", "(", "overrides", "=", "\"\"", ")", ":", "hparams", "=", "decoding", ".", "decode_hparams", "(", ")", "# Number of interpolations between [0.0, 1.0].", "hparams", ".", "add_hparam", "(", "\"num_interp\"", ",", "11", ")", "# Which level(s) to i...
Hparams for decoding.
[ "Hparams", "for", "decoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/nfg_interpolate.py#L53-L67
21,952
tensorflow/tensor2tensor
tensor2tensor/models/video/nfg_interpolate.py
preprocess_frame
def preprocess_frame(frame): """Preprocess frame. 1. Converts [0, 255] to [-0.5, 0.5] 2. Adds uniform noise. Args: frame: 3-D Tensor representing pixels. Returns: frame: 3-D Tensor with values in between [-0.5, 0.5] """ # Normalize from [0.0, 1.0] -> [-0.5, 0.5] frame = common_layers.convert_r...
python
def preprocess_frame(frame): """Preprocess frame. 1. Converts [0, 255] to [-0.5, 0.5] 2. Adds uniform noise. Args: frame: 3-D Tensor representing pixels. Returns: frame: 3-D Tensor with values in between [-0.5, 0.5] """ # Normalize from [0.0, 1.0] -> [-0.5, 0.5] frame = common_layers.convert_r...
[ "def", "preprocess_frame", "(", "frame", ")", ":", "# Normalize from [0.0, 1.0] -> [-0.5, 0.5]", "frame", "=", "common_layers", ".", "convert_rgb_to_real", "(", "frame", ")", "frame", "=", "frame", "-", "0.5", "frame", ",", "_", "=", "glow_ops", ".", "uniform_binn...
Preprocess frame. 1. Converts [0, 255] to [-0.5, 0.5] 2. Adds uniform noise. Args: frame: 3-D Tensor representing pixels. Returns: frame: 3-D Tensor with values in between [-0.5, 0.5]
[ "Preprocess", "frame", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/nfg_interpolate.py#L70-L85
21,953
tensorflow/tensor2tensor
tensor2tensor/models/video/nfg_interpolate.py
frame_to_latents
def frame_to_latents(frame, hparams): """Encode frames to latents.""" # Preprocess frame = preprocess_frame(frame) # Encode [X_t] to [z^1_t, z^2_t .. z^l_t] glow_vals = glow_ops.encoder_decoder( "codec", frame, hparams, eps=None, reverse=False) z_top, _, level_eps, _, _ = glow_vals return z_top, le...
python
def frame_to_latents(frame, hparams): """Encode frames to latents.""" # Preprocess frame = preprocess_frame(frame) # Encode [X_t] to [z^1_t, z^2_t .. z^l_t] glow_vals = glow_ops.encoder_decoder( "codec", frame, hparams, eps=None, reverse=False) z_top, _, level_eps, _, _ = glow_vals return z_top, le...
[ "def", "frame_to_latents", "(", "frame", ",", "hparams", ")", ":", "# Preprocess", "frame", "=", "preprocess_frame", "(", "frame", ")", "# Encode [X_t] to [z^1_t, z^2_t .. z^l_t]", "glow_vals", "=", "glow_ops", ".", "encoder_decoder", "(", "\"codec\"", ",", "frame", ...
Encode frames to latents.
[ "Encode", "frames", "to", "latents", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/nfg_interpolate.py#L88-L97
21,954
tensorflow/tensor2tensor
tensor2tensor/models/video/nfg_interpolate.py
latents_to_frames
def latents_to_frames(z_top_interp, level_eps_interp, hparams): """Decodes latents to frames.""" # Decode [z^1_t, z^2_t .. z^l_t] to [X_t] images, _, _, _ = glow_ops.encoder_decoder( "codec", z_top_interp, hparams, eps=level_eps_interp, reverse=True) images = glow_ops.postprocess(images) return images
python
def latents_to_frames(z_top_interp, level_eps_interp, hparams): """Decodes latents to frames.""" # Decode [z^1_t, z^2_t .. z^l_t] to [X_t] images, _, _, _ = glow_ops.encoder_decoder( "codec", z_top_interp, hparams, eps=level_eps_interp, reverse=True) images = glow_ops.postprocess(images) return images
[ "def", "latents_to_frames", "(", "z_top_interp", ",", "level_eps_interp", ",", "hparams", ")", ":", "# Decode [z^1_t, z^2_t .. z^l_t] to [X_t]", "images", ",", "_", ",", "_", ",", "_", "=", "glow_ops", ".", "encoder_decoder", "(", "\"codec\"", ",", "z_top_interp", ...
Decodes latents to frames.
[ "Decodes", "latents", "to", "frames", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/nfg_interpolate.py#L100-L106
21,955
tensorflow/tensor2tensor
tensor2tensor/models/video/nfg_interpolate.py
interpolate
def interpolate(features, hparams, decode_hp): """Interpolate between the first input frame and last target frame. Args: features: dict of tensors hparams: HParams, training hparams. decode_hp: HParams, decode hparams. Returns: images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C) ...
python
def interpolate(features, hparams, decode_hp): """Interpolate between the first input frame and last target frame. Args: features: dict of tensors hparams: HParams, training hparams. decode_hp: HParams, decode hparams. Returns: images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C) ...
[ "def", "interpolate", "(", "features", ",", "hparams", ",", "decode_hp", ")", ":", "inputs", ",", "targets", "=", "features", "[", "\"inputs\"", "]", ",", "features", "[", "\"targets\"", "]", "inputs", "=", "tf", ".", "unstack", "(", "inputs", ",", "axis...
Interpolate between the first input frame and last target frame. Args: features: dict of tensors hparams: HParams, training hparams. decode_hp: HParams, decode hparams. Returns: images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C) first_frame: image, 3-D Tensor, shape=(1, H, W, ...
[ "Interpolate", "between", "the", "first", "input", "frame", "and", "last", "target", "frame", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/nfg_interpolate.py#L109-L150
21,956
tensorflow/tensor2tensor
tensor2tensor/models/video/nfg_interpolate.py
get_summaries_log_dir
def get_summaries_log_dir(decode_hp, output_dir, dataset_split): """Get nested summaries_log_dir based on decode_hp.""" child_dir = decode_hp.summaries_log_dir level_dir = "".join([str(level) for level in decode_hp.level_interp]) if decode_hp.channel_interp == "all": rank_dir = "all" else: rank_dir = ...
python
def get_summaries_log_dir(decode_hp, output_dir, dataset_split): """Get nested summaries_log_dir based on decode_hp.""" child_dir = decode_hp.summaries_log_dir level_dir = "".join([str(level) for level in decode_hp.level_interp]) if decode_hp.channel_interp == "all": rank_dir = "all" else: rank_dir = ...
[ "def", "get_summaries_log_dir", "(", "decode_hp", ",", "output_dir", ",", "dataset_split", ")", ":", "child_dir", "=", "decode_hp", ".", "summaries_log_dir", "level_dir", "=", "\"\"", ".", "join", "(", "[", "str", "(", "level", ")", "for", "level", "in", "de...
Get nested summaries_log_dir based on decode_hp.
[ "Get", "nested", "summaries_log_dir", "based", "on", "decode_hp", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/nfg_interpolate.py#L153-L164
21,957
tensorflow/tensor2tensor
tensor2tensor/models/video/nfg_interpolate.py
interpolations_to_summary
def interpolations_to_summary(sample_ind, interpolations, first_frame, last_frame, hparams, decode_hp): """Converts interpolated frames into tf summaries. The summaries consists of: 1. Image summary corresponding to the first frame. 2. Image summary corresponding to the last f...
python
def interpolations_to_summary(sample_ind, interpolations, first_frame, last_frame, hparams, decode_hp): """Converts interpolated frames into tf summaries. The summaries consists of: 1. Image summary corresponding to the first frame. 2. Image summary corresponding to the last f...
[ "def", "interpolations_to_summary", "(", "sample_ind", ",", "interpolations", ",", "first_frame", ",", "last_frame", ",", "hparams", ",", "decode_hp", ")", ":", "parent_tag", "=", "\"sample_%d\"", "%", "sample_ind", "frame_shape", "=", "hparams", ".", "problem", "...
Converts interpolated frames into tf summaries. The summaries consists of: 1. Image summary corresponding to the first frame. 2. Image summary corresponding to the last frame. 3. The interpolated frames as a gif summary. Args: sample_ind: int interpolations: Numpy array, shape=(num_interp, H, ...
[ "Converts", "interpolated", "frames", "into", "tf", "summaries", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/nfg_interpolate.py#L167-L205
21,958
tensorflow/tensor2tensor
tensor2tensor/models/video/epva_params.py
next_frame_epva
def next_frame_epva(): """EPVA hparams.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.bottom = { "inputs": modalities.video_raw_bottom, "targets": modalities.video_raw_targets_bottom, } hp...
python
def next_frame_epva(): """EPVA hparams.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.bottom = { "inputs": modalities.video_raw_bottom, "targets": modalities.video_raw_targets_bottom, } hp...
[ "def", "next_frame_epva", "(", ")", ":", "hparams", "=", "basic_deterministic_params", ".", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "video_num_input_frames", "=", "4", "hparams", ".", "video_num_target_frames", "=", "4", "hparams", ".", "bottom", ...
EPVA hparams.
[ "EPVA", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva_params.py#L27-L63
21,959
tensorflow/tensor2tensor
tensor2tensor/utils/multistep_optimizer.py
MultistepAdamOptimizer._create_slots
def _create_slots(self, var_list): """Create slot variables for Adam with accumulated gradients.""" super(MultistepAdamOptimizer, self)._create_slots(var_list) first_var = min(var_list, key=lambda x: x.name) self._create_non_slot_variable(initial_value=0 if self._n == 1 else 1, ...
python
def _create_slots(self, var_list): """Create slot variables for Adam with accumulated gradients.""" super(MultistepAdamOptimizer, self)._create_slots(var_list) first_var = min(var_list, key=lambda x: x.name) self._create_non_slot_variable(initial_value=0 if self._n == 1 else 1, ...
[ "def", "_create_slots", "(", "self", ",", "var_list", ")", ":", "super", "(", "MultistepAdamOptimizer", ",", "self", ")", ".", "_create_slots", "(", "var_list", ")", "first_var", "=", "min", "(", "var_list", ",", "key", "=", "lambda", "x", ":", "x", ".",...
Create slot variables for Adam with accumulated gradients.
[ "Create", "slot", "variables", "for", "Adam", "with", "accumulated", "gradients", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/multistep_optimizer.py#L43-L51
21,960
tensorflow/tensor2tensor
tensor2tensor/utils/multistep_optimizer.py
MultistepAdamOptimizer._apply_cond
def _apply_cond(self, apply_fn, grad, var, *args, **kwargs): """Apply conditionally if counter is zero.""" grad_acc = self.get_slot(var, "grad_acc") def apply_adam(grad_acc, apply_fn, grad, var, *args, **kwargs): total_grad = (grad_acc + grad) / tf.cast(self._n_t, grad.dtype) adam_op = apply_fn...
python
def _apply_cond(self, apply_fn, grad, var, *args, **kwargs): """Apply conditionally if counter is zero.""" grad_acc = self.get_slot(var, "grad_acc") def apply_adam(grad_acc, apply_fn, grad, var, *args, **kwargs): total_grad = (grad_acc + grad) / tf.cast(self._n_t, grad.dtype) adam_op = apply_fn...
[ "def", "_apply_cond", "(", "self", ",", "apply_fn", ",", "grad", ",", "var", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "grad_acc", "=", "self", ".", "get_slot", "(", "var", ",", "\"grad_acc\"", ")", "def", "apply_adam", "(", "grad_acc", ",...
Apply conditionally if counter is zero.
[ "Apply", "conditionally", "if", "counter", "is", "zero", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/multistep_optimizer.py#L62-L81
21,961
tensorflow/tensor2tensor
tensor2tensor/utils/multistep_optimizer.py
MultistepAdamOptimizer._finish
def _finish(self, update_ops, name_scope): """Updates beta_power variables every n batches and incrs counter.""" iter_ = self._get_iter_variable() beta1_power, beta2_power = self._get_beta_accumulators() with tf.control_dependencies(update_ops): with tf.colocate_with(iter_): def update_be...
python
def _finish(self, update_ops, name_scope): """Updates beta_power variables every n batches and incrs counter.""" iter_ = self._get_iter_variable() beta1_power, beta2_power = self._get_beta_accumulators() with tf.control_dependencies(update_ops): with tf.colocate_with(iter_): def update_be...
[ "def", "_finish", "(", "self", ",", "update_ops", ",", "name_scope", ")", ":", "iter_", "=", "self", ".", "_get_iter_variable", "(", ")", "beta1_power", ",", "beta2_power", "=", "self", ".", "_get_beta_accumulators", "(", ")", "with", "tf", ".", "control_dep...
Updates beta_power variables every n batches and incrs counter.
[ "Updates", "beta_power", "variables", "every", "n", "batches", "and", "incrs", "counter", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/multistep_optimizer.py#L103-L124
21,962
tensorflow/tensor2tensor
tensor2tensor/utils/devices.py
data_parallelism_from_flags
def data_parallelism_from_flags(daisy_chain_variables=True, all_workers=False): """Over which devices do we split each training batch. In old-fashioned async mode, we split the batch over all GPUs on the current worker. In sync mode, we split the batch over all the parameter server GPUs. This function retu...
python
def data_parallelism_from_flags(daisy_chain_variables=True, all_workers=False): """Over which devices do we split each training batch. In old-fashioned async mode, we split the batch over all GPUs on the current worker. In sync mode, we split the batch over all the parameter server GPUs. This function retu...
[ "def", "data_parallelism_from_flags", "(", "daisy_chain_variables", "=", "True", ",", "all_workers", "=", "False", ")", ":", "dp_arg_names", "=", "inspect", ".", "getargspec", "(", "data_parallelism", ")", ".", "args", "blacklist", "=", "[", "\"daisy_chain_variables...
Over which devices do we split each training batch. In old-fashioned async mode, we split the batch over all GPUs on the current worker. In sync mode, we split the batch over all the parameter server GPUs. This function returns an expert_utils.Parallelism object, which can be used to build the model. It i...
[ "Over", "which", "devices", "do", "we", "split", "each", "training", "batch", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/devices.py#L26-L59
21,963
tensorflow/tensor2tensor
tensor2tensor/data_generators/wiki_lm.py
concat_generator
def concat_generator(filename, up_threshold, low_threshold=10): """Generate concatenated lines from file upto up_threshold characters.""" txt = "" for line in tf.gfile.Open(filename): line = line.strip() if len(txt) + len(line) + 1 >= up_threshold: ret = txt txt = "" # We don't yield ver...
python
def concat_generator(filename, up_threshold, low_threshold=10): """Generate concatenated lines from file upto up_threshold characters.""" txt = "" for line in tf.gfile.Open(filename): line = line.strip() if len(txt) + len(line) + 1 >= up_threshold: ret = txt txt = "" # We don't yield ver...
[ "def", "concat_generator", "(", "filename", ",", "up_threshold", ",", "low_threshold", "=", "10", ")", ":", "txt", "=", "\"\"", "for", "line", "in", "tf", ".", "gfile", ".", "Open", "(", "filename", ")", ":", "line", "=", "line", ".", "strip", "(", "...
Generate concatenated lines from file upto up_threshold characters.
[ "Generate", "concatenated", "lines", "from", "file", "upto", "up_threshold", "characters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_lm.py#L33-L48
21,964
tensorflow/tensor2tensor
tensor2tensor/data_generators/wiki_lm.py
mix_generators
def mix_generators(generator_list): """Given python generators, generate from one, then from another, etc.""" i = 0 l = len(generator_list) stopiters_seen = 0 while stopiters_seen <= l: try: yield six.next(generator_list[i % l]) i += 1 stopiters_seen = 0 except StopIteration: i...
python
def mix_generators(generator_list): """Given python generators, generate from one, then from another, etc.""" i = 0 l = len(generator_list) stopiters_seen = 0 while stopiters_seen <= l: try: yield six.next(generator_list[i % l]) i += 1 stopiters_seen = 0 except StopIteration: i...
[ "def", "mix_generators", "(", "generator_list", ")", ":", "i", "=", "0", "l", "=", "len", "(", "generator_list", ")", "stopiters_seen", "=", "0", "while", "stopiters_seen", "<=", "l", ":", "try", ":", "yield", "six", ".", "next", "(", "generator_list", "...
Given python generators, generate from one, then from another, etc.
[ "Given", "python", "generators", "generate", "from", "one", "then", "from", "another", "etc", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_lm.py#L51-L63
21,965
tensorflow/tensor2tensor
tensor2tensor/data_generators/translate.py
compute_bleu_summaries
def compute_bleu_summaries(hook_args): """Compute BLEU core summaries using the decoder output. Args: hook_args: DecodeHookArgs namedtuple Returns: A list of tf.Summary values if hook_args.hparams contains the reference file and the translated file. """ decode_hparams = hook_args.decode_hparams ...
python
def compute_bleu_summaries(hook_args): """Compute BLEU core summaries using the decoder output. Args: hook_args: DecodeHookArgs namedtuple Returns: A list of tf.Summary values if hook_args.hparams contains the reference file and the translated file. """ decode_hparams = hook_args.decode_hparams ...
[ "def", "compute_bleu_summaries", "(", "hook_args", ")", ":", "decode_hparams", "=", "hook_args", ".", "decode_hparams", "if", "not", "(", "decode_hparams", ".", "decode_reference", "and", "decode_hparams", ".", "decode_to_file", ")", ":", "return", "None", "values",...
Compute BLEU core summaries using the decoder output. Args: hook_args: DecodeHookArgs namedtuple Returns: A list of tf.Summary values if hook_args.hparams contains the reference file and the translated file.
[ "Compute", "BLEU", "core", "summaries", "using", "the", "decoder", "output", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/translate.py#L83-L118
21,966
tensorflow/tensor2tensor
tensor2tensor/data_generators/translate.py
_preprocess_sgm
def _preprocess_sgm(line, is_sgm): """Preprocessing to strip tags in SGM files.""" if not is_sgm: return line # In SGM files, remove <srcset ...>, <p>, <doc ...> lines. if line.startswith("<srcset") or line.startswith("</srcset"): return "" if line.startswith("<doc") or line.startswith("</doc"): r...
python
def _preprocess_sgm(line, is_sgm): """Preprocessing to strip tags in SGM files.""" if not is_sgm: return line # In SGM files, remove <srcset ...>, <p>, <doc ...> lines. if line.startswith("<srcset") or line.startswith("</srcset"): return "" if line.startswith("<doc") or line.startswith("</doc"): r...
[ "def", "_preprocess_sgm", "(", "line", ",", "is_sgm", ")", ":", "if", "not", "is_sgm", ":", "return", "line", "# In SGM files, remove <srcset ...>, <p>, <doc ...> lines.", "if", "line", ".", "startswith", "(", "\"<srcset\"", ")", "or", "line", ".", "startswith", "...
Preprocessing to strip tags in SGM files.
[ "Preprocessing", "to", "strip", "tags", "in", "SGM", "files", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/translate.py#L121-L136
21,967
tensorflow/tensor2tensor
tensor2tensor/data_generators/translate.py
TranslateDistillProblem.get_or_create_vocab
def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False): """Get vocab for distill problems.""" # We assume that vocab file is present in data_dir directory where the # data generated will be stored. vocab_filepath = os.path.join(data_dir, self.vocab_filename) encoder = text_encoder.Subword...
python
def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False): """Get vocab for distill problems.""" # We assume that vocab file is present in data_dir directory where the # data generated will be stored. vocab_filepath = os.path.join(data_dir, self.vocab_filename) encoder = text_encoder.Subword...
[ "def", "get_or_create_vocab", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "force_get", "=", "False", ")", ":", "# We assume that vocab file is present in data_dir directory where the", "# data generated will be stored.", "vocab_filepath", "=", "os", ".", "path", ".",...
Get vocab for distill problems.
[ "Get", "vocab", "for", "distill", "problems", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/translate.py#L278-L284
21,968
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_trainer.py
set_hparams_from_args
def set_hparams_from_args(args): """Set hparams overrides from unparsed args list.""" if not args: return hp_prefix = "--hp_" tf.logging.info("Found unparsed command-line arguments. Checking if any " "start with %s and interpreting those as hparams " "settings.", hp_pref...
python
def set_hparams_from_args(args): """Set hparams overrides from unparsed args list.""" if not args: return hp_prefix = "--hp_" tf.logging.info("Found unparsed command-line arguments. Checking if any " "start with %s and interpreting those as hparams " "settings.", hp_pref...
[ "def", "set_hparams_from_args", "(", "args", ")", ":", "if", "not", "args", ":", "return", "hp_prefix", "=", "\"--hp_\"", "tf", ".", "logging", ".", "info", "(", "\"Found unparsed command-line arguments. Checking if any \"", "\"start with %s and interpreting those as hparam...
Set hparams overrides from unparsed args list.
[ "Set", "hparams", "overrides", "from", "unparsed", "args", "list", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_trainer.py#L138-L162
21,969
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_trainer.py
create_hparams
def create_hparams(): """Create hparams.""" if FLAGS.use_tpu and "tpu" not in FLAGS.hparams_set: tf.logging.warn("Not all hyperparameter sets work on TPU. " "Prefer hparams_sets with a '_tpu' suffix, " "e.g. transformer_tpu, if available for your model.") hparams_path =...
python
def create_hparams(): """Create hparams.""" if FLAGS.use_tpu and "tpu" not in FLAGS.hparams_set: tf.logging.warn("Not all hyperparameter sets work on TPU. " "Prefer hparams_sets with a '_tpu' suffix, " "e.g. transformer_tpu, if available for your model.") hparams_path =...
[ "def", "create_hparams", "(", ")", ":", "if", "FLAGS", ".", "use_tpu", "and", "\"tpu\"", "not", "in", "FLAGS", ".", "hparams_set", ":", "tf", ".", "logging", ".", "warn", "(", "\"Not all hyperparameter sets work on TPU. \"", "\"Prefer hparams_sets with a '_tpu' suffix...
Create hparams.
[ "Create", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_trainer.py#L165-L173
21,970
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_trainer.py
save_metadata
def save_metadata(hparams): """Saves FLAGS and hparams to output_dir.""" output_dir = os.path.expanduser(FLAGS.output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) # Save FLAGS in txt file if hasattr(FLAGS, "flags_into_string"): flags_str = FLAGS.flags_into_string() t2t_f...
python
def save_metadata(hparams): """Saves FLAGS and hparams to output_dir.""" output_dir = os.path.expanduser(FLAGS.output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) # Save FLAGS in txt file if hasattr(FLAGS, "flags_into_string"): flags_str = FLAGS.flags_into_string() t2t_f...
[ "def", "save_metadata", "(", "hparams", ")", ":", "output_dir", "=", "os", ".", "path", ".", "expanduser", "(", "FLAGS", ".", "output_dir", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "output_dir", ")", ":", "tf", ".", "gfile", ".", "Ma...
Saves FLAGS and hparams to output_dir.
[ "Saves", "FLAGS", "and", "hparams", "to", "output_dir", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_trainer.py#L313-L348
21,971
tensorflow/tensor2tensor
tensor2tensor/models/xception.py
residual_block
def residual_block(x, hparams): """A stack of convolution blocks with residual connection.""" k = (hparams.kernel_height, hparams.kernel_width) dilations_and_kernels = [((1, 1), k) for _ in range(3)] y = common_layers.subseparable_conv_block( x, hparams.hidden_size, dilations_and_kernels, ...
python
def residual_block(x, hparams): """A stack of convolution blocks with residual connection.""" k = (hparams.kernel_height, hparams.kernel_width) dilations_and_kernels = [((1, 1), k) for _ in range(3)] y = common_layers.subseparable_conv_block( x, hparams.hidden_size, dilations_and_kernels, ...
[ "def", "residual_block", "(", "x", ",", "hparams", ")", ":", "k", "=", "(", "hparams", ".", "kernel_height", ",", "hparams", ".", "kernel_width", ")", "dilations_and_kernels", "=", "[", "(", "(", "1", ",", "1", ")", ",", "k", ")", "for", "_", "in", ...
A stack of convolution blocks with residual connection.
[ "A", "stack", "of", "convolution", "blocks", "with", "residual", "connection", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/xception.py#L33-L45
21,972
tensorflow/tensor2tensor
tensor2tensor/models/xception.py
xception_internal
def xception_internal(inputs, hparams): """Xception body.""" with tf.variable_scope("xception"): cur = inputs if cur.get_shape().as_list()[1] > 200: # Large image, Xception entry flow cur = xception_entry(cur, hparams.hidden_size) else: # Small image, conv cur = common_layers.co...
python
def xception_internal(inputs, hparams): """Xception body.""" with tf.variable_scope("xception"): cur = inputs if cur.get_shape().as_list()[1] > 200: # Large image, Xception entry flow cur = xception_entry(cur, hparams.hidden_size) else: # Small image, conv cur = common_layers.co...
[ "def", "xception_internal", "(", "inputs", ",", "hparams", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"xception\"", ")", ":", "cur", "=", "inputs", "if", "cur", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", "]", ">", "200...
Xception body.
[ "Xception", "body", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/xception.py#L48-L70
21,973
tensorflow/tensor2tensor
tensor2tensor/models/xception.py
xception_entry
def xception_entry(inputs, hidden_dim): """Xception entry flow.""" with tf.variable_scope("xception_entry"): def xnet_resblock(x, filters, res_relu, name): """Resblock.""" with tf.variable_scope(name): y = common_layers.separable_conv_block( x, filters, [((1, 1), (3,...
python
def xception_entry(inputs, hidden_dim): """Xception entry flow.""" with tf.variable_scope("xception_entry"): def xnet_resblock(x, filters, res_relu, name): """Resblock.""" with tf.variable_scope(name): y = common_layers.separable_conv_block( x, filters, [((1, 1), (3,...
[ "def", "xception_entry", "(", "inputs", ",", "hidden_dim", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"xception_entry\"", ")", ":", "def", "xnet_resblock", "(", "x", ",", "filters", ",", "res_relu", ",", "name", ")", ":", "\"\"\"Resblock.\"\"\"", ...
Xception entry flow.
[ "Xception", "entry", "flow", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/xception.py#L73-L110
21,974
tensorflow/tensor2tensor
tensor2tensor/models/xception.py
xception_exit
def xception_exit(inputs): """Xception exit flow.""" with tf.variable_scope("xception_exit"): x = inputs x_shape = x.get_shape().as_list() if x_shape[1] is None or x_shape[2] is None: length_float = tf.to_float(tf.shape(x)[1]) length_float *= tf.to_float(tf.shape(x)[2]) spatial_dim_flo...
python
def xception_exit(inputs): """Xception exit flow.""" with tf.variable_scope("xception_exit"): x = inputs x_shape = x.get_shape().as_list() if x_shape[1] is None or x_shape[2] is None: length_float = tf.to_float(tf.shape(x)[1]) length_float *= tf.to_float(tf.shape(x)[2]) spatial_dim_flo...
[ "def", "xception_exit", "(", "inputs", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"xception_exit\"", ")", ":", "x", "=", "inputs", "x_shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "x_shape", "[", "1", "]", "...
Xception exit flow.
[ "Xception", "exit", "flow", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/xception.py#L113-L133
21,975
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/html.py
get_text_from_html
def get_text_from_html(html): """Returns a plaintext representation of HTML content.""" try: soup = bs4.BeautifulSoup(html, "html.parser") except: # pylint: disable=bare-except # Some docs don't parse return "" # Remove script and style tags for s in soup(["script", "style"]): s.decompose() ...
python
def get_text_from_html(html): """Returns a plaintext representation of HTML content.""" try: soup = bs4.BeautifulSoup(html, "html.parser") except: # pylint: disable=bare-except # Some docs don't parse return "" # Remove script and style tags for s in soup(["script", "style"]): s.decompose() ...
[ "def", "get_text_from_html", "(", "html", ")", ":", "try", ":", "soup", "=", "bs4", ".", "BeautifulSoup", "(", "html", ",", "\"html.parser\"", ")", "except", ":", "# pylint: disable=bare-except", "# Some docs don't parse", "return", "\"\"", "# Remove script and style ...
Returns a plaintext representation of HTML content.
[ "Returns", "a", "plaintext", "representation", "of", "HTML", "content", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/html.py#L21-L32
21,976
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/html.py
_soup_strings
def _soup_strings(soup): """Return text strings in soup.""" paragraph_tags = set([ "caption", "details", "h1", "h2", "h3", "h4", "h5", "h6", "li", "p", "td", "div", "span" ]) skip_children = None for descendant in soup.descendants: # If we've treated a tag as a contiguous paragraph, don't re-...
python
def _soup_strings(soup): """Return text strings in soup.""" paragraph_tags = set([ "caption", "details", "h1", "h2", "h3", "h4", "h5", "h6", "li", "p", "td", "div", "span" ]) skip_children = None for descendant in soup.descendants: # If we've treated a tag as a contiguous paragraph, don't re-...
[ "def", "_soup_strings", "(", "soup", ")", ":", "paragraph_tags", "=", "set", "(", "[", "\"caption\"", ",", "\"details\"", ",", "\"h1\"", ",", "\"h2\"", ",", "\"h3\"", ",", "\"h4\"", ",", "\"h5\"", ",", "\"h6\"", ",", "\"li\"", ",", "\"p\"", ",", "\"td\""...
Return text strings in soup.
[ "Return", "text", "strings", "in", "soup", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/html.py#L35-L78
21,977
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p
def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p(): """Gets to 2.92 in just under 4 days on 8 p100s.""" hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l() hparams.num_decoder_layers = 14 hparams.batch_size = 8 hparams.layer_prepostprocess_dropout = 0.2 return hparams
python
def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p(): """Gets to 2.92 in just under 4 days on 8 p100s.""" hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l() hparams.num_decoder_layers = 14 hparams.batch_size = 8 hparams.layer_prepostprocess_dropout = 0.2 return hparams
[ "def", "imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p", "(", ")", ":", "hparams", "=", "imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l", "(", ")", "hparams", ".", "num_decoder_layers", "=", "14", "hparams", ".", "batch_size", "=", "8", "hparams", ".", "layer_...
Gets to 2.92 in just under 4 days on 8 p100s.
[ "Gets", "to", "2", ".", "92", "in", "just", "under", "4", "days", "on", "8", "p100s", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L537-L543
21,978
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformerpp_base_5l_8h_big_uncond_dr00_dan_g_bs1
def imagetransformerpp_base_5l_8h_big_uncond_dr00_dan_g_bs1(): """For 256x256.""" hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g() # TODO(trandustin): I forgot to set this in the runs! Maybe it's not used in # image transformer training implementation? # hparams.img_len = 256 hparams.max_len...
python
def imagetransformerpp_base_5l_8h_big_uncond_dr00_dan_g_bs1(): """For 256x256.""" hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g() # TODO(trandustin): I forgot to set this in the runs! Maybe it's not used in # image transformer training implementation? # hparams.img_len = 256 hparams.max_len...
[ "def", "imagetransformerpp_base_5l_8h_big_uncond_dr00_dan_g_bs1", "(", ")", ":", "hparams", "=", "imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g", "(", ")", "# TODO(trandustin): I forgot to set this in the runs! Maybe it's not used in", "# image transformer training implementation?", "...
For 256x256.
[ "For", "256x256", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L565-L579
21,979
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated(): """Dilated hparams.""" hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan() hparams.gap_sizes = [0, 16, 64, 0, 16, 64, 128, 0] hparams.dec_attention_type = cia.AttentionType.DILATED hparams.block_length = 128 hparams.block_width = 128 hpara...
python
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated(): """Dilated hparams.""" hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan() hparams.gap_sizes = [0, 16, 64, 0, 16, 64, 128, 0] hparams.dec_attention_type = cia.AttentionType.DILATED hparams.block_length = 128 hparams.block_width = 128 hpara...
[ "def", "imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated", "(", ")", ":", "hparams", "=", "imagetransformer_base_8l_8h_big_cond_dr03_dan", "(", ")", "hparams", ".", "gap_sizes", "=", "[", "0", ",", "16", ",", "64", ",", "0", ",", "16", ",", "64", ",", "128"...
Dilated hparams.
[ "Dilated", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L635-L643
21,980
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer1d_base_8l_64by64
def imagetransformer1d_base_8l_64by64(): """hparams fo 12 layer big 1d model for imagenet 64x64.""" hparams = image_transformer_base() hparams.num_heads = 8 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_decoder_layers = 8 hparams.batch_size = 1 hparams.block_length = 512 hparams.blo...
python
def imagetransformer1d_base_8l_64by64(): """hparams fo 12 layer big 1d model for imagenet 64x64.""" hparams = image_transformer_base() hparams.num_heads = 8 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_decoder_layers = 8 hparams.batch_size = 1 hparams.block_length = 512 hparams.blo...
[ "def", "imagetransformer1d_base_8l_64by64", "(", ")", ":", "hparams", "=", "image_transformer_base", "(", ")", "hparams", ".", "num_heads", "=", "8", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "num_deco...
hparams fo 12 layer big 1d model for imagenet 64x64.
[ "hparams", "fo", "12", "layer", "big", "1d", "model", "for", "imagenet", "64x64", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L688-L701
21,981
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_moe_tiny
def imagetransformer_moe_tiny(): """Set of hyperparameters for a very small imagetransformer with MoE.""" hparams = imagetransformer_tiny() hparams.hidden_size = 64 hparams.batch_size = 1 hparams.num_hidden_layers = 3 hparams.dec_attention_type = cia.AttentionType.MOE_LOCAL_1D hparams.add_hparam("moe_laye...
python
def imagetransformer_moe_tiny(): """Set of hyperparameters for a very small imagetransformer with MoE.""" hparams = imagetransformer_tiny() hparams.hidden_size = 64 hparams.batch_size = 1 hparams.num_hidden_layers = 3 hparams.dec_attention_type = cia.AttentionType.MOE_LOCAL_1D hparams.add_hparam("moe_laye...
[ "def", "imagetransformer_moe_tiny", "(", ")", ":", "hparams", "=", "imagetransformer_tiny", "(", ")", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "batch_size", "=", "1", "hparams", ".", "num_hidden_layers", "=", "3", "hparams", ".", "dec_attention_...
Set of hyperparameters for a very small imagetransformer with MoE.
[ "Set", "of", "hyperparameters", "for", "a", "very", "small", "imagetransformer", "with", "MoE", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L918-L930
21,982
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_sep_channels_8l_tpu
def imagetransformer_sep_channels_8l_tpu(): """Hparams for training imagetransformer on tpu.""" hparams = imagetransformer_sep_channels_8l() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.shared_embedding_and_softmax_weights = False retu...
python
def imagetransformer_sep_channels_8l_tpu(): """Hparams for training imagetransformer on tpu.""" hparams = imagetransformer_sep_channels_8l() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.shared_embedding_and_softmax_weights = False retu...
[ "def", "imagetransformer_sep_channels_8l_tpu", "(", ")", ":", "hparams", "=", "imagetransformer_sep_channels_8l", "(", ")", "update_hparams_for_tpu", "(", "hparams", ")", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "num_heads", "=", "4", "# heads are expen...
Hparams for training imagetransformer on tpu.
[ "Hparams", "for", "training", "imagetransformer", "on", "tpu", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L941-L948
21,983
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_b10l_4h_big_uncond_dr03_tpu
def imagetransformer_b10l_4h_big_uncond_dr03_tpu(): """Small model for tpu cifar 10.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 10 hparams.block_len...
python
def imagetransformer_b10l_4h_big_uncond_dr03_tpu(): """Small model for tpu cifar 10.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 10 hparams.block_len...
[ "def", "imagetransformer_b10l_4h_big_uncond_dr03_tpu", "(", ")", ":", "hparams", "=", "imagetransformer_bas8l_8h_big_uncond_dr03_imgnet", "(", ")", "update_hparams_for_tpu", "(", "hparams", ")", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "num_heads", "=", "...
Small model for tpu cifar 10.
[ "Small", "model", "for", "tpu", "cifar", "10", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L952-L965
21,984
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_b10l_dr03_moe_tpu
def imagetransformer_b10l_dr03_moe_tpu(): """Moe tpu params.""" hparams = imagetransformer_b10l_4h_big_uncond_dr03_tpu() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 10 hparams.layer_preprocess_sequence = "none" ...
python
def imagetransformer_b10l_dr03_moe_tpu(): """Moe tpu params.""" hparams = imagetransformer_b10l_4h_big_uncond_dr03_tpu() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 10 hparams.layer_preprocess_sequence = "none" ...
[ "def", "imagetransformer_b10l_dr03_moe_tpu", "(", ")", ":", "hparams", "=", "imagetransformer_b10l_4h_big_uncond_dr03_tpu", "(", ")", "update_hparams_for_tpu", "(", "hparams", ")", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "num_heads", "=", "4", "# heads...
Moe tpu params.
[ "Moe", "tpu", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L969-L979
21,985
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_cifar_tpu_range
def imagetransformer_cifar_tpu_range(rhp): """Range of hyperparameters for vizier.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE) rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16]) rhp.set_discrete("hidden_size", [256, ...
python
def imagetransformer_cifar_tpu_range(rhp): """Range of hyperparameters for vizier.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE) rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16]) rhp.set_discrete("hidden_size", [256, ...
[ "def", "imagetransformer_cifar_tpu_range", "(", "rhp", ")", ":", "# After starting from base, set intervals for some parameters.", "rhp", ".", "set_float", "(", "\"learning_rate\"", ",", "0.01", ",", "1.0", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", ...
Range of hyperparameters for vizier.
[ "Range", "of", "hyperparameters", "for", "vizier", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L1054-L1062
21,986
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_b12l_4h_b128_h512_uncond_dr01_im
def imagetransformer_b12l_4h_b128_h512_uncond_dr01_im(): """TPU related imagenet model.""" hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_w...
python
def imagetransformer_b12l_4h_b128_h512_uncond_dr01_im(): """TPU related imagenet model.""" hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_w...
[ "def", "imagetransformer_b12l_4h_b128_h512_uncond_dr01_im", "(", ")", ":", "hparams", "=", "imagetransformer_b12l_4h_b256_uncond_dr03_tpu", "(", ")", "update_hparams_for_tpu", "(", "hparams", ")", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "optimizer", "=", ...
TPU related imagenet model.
[ "TPU", "related", "imagenet", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L1085-L1094
21,987
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_b12l_4h_b128_uncond_dr03_tpu
def imagetransformer_b12l_4h_b128_uncond_dr03_tpu(): """TPU config for cifar 10.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 2 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.block_length ...
python
def imagetransformer_b12l_4h_b128_uncond_dr03_tpu(): """TPU config for cifar 10.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 2 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.block_length ...
[ "def", "imagetransformer_b12l_4h_b128_uncond_dr03_tpu", "(", ")", ":", "hparams", "=", "imagetransformer_bas8l_8h_big_uncond_dr03_imgnet", "(", ")", "update_hparams_for_tpu", "(", "hparams", ")", "hparams", ".", "batch_size", "=", "2", "hparams", ".", "num_heads", "=", ...
TPU config for cifar 10.
[ "TPU", "config", "for", "cifar", "10", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L1110-L1126
21,988
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
imagetransformer_b12l_8h_b256_uncond_dr03_tpu
def imagetransformer_b12l_8h_b256_uncond_dr03_tpu(): """TPU related 12 layer 8 heads model.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 2 hparams.num_heads = 8 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.bl...
python
def imagetransformer_b12l_8h_b256_uncond_dr03_tpu(): """TPU related 12 layer 8 heads model.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 2 hparams.num_heads = 8 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.bl...
[ "def", "imagetransformer_b12l_8h_b256_uncond_dr03_tpu", "(", ")", ":", "hparams", "=", "imagetransformer_bas8l_8h_big_uncond_dr03_imgnet", "(", ")", "update_hparams_for_tpu", "(", "hparams", ")", "hparams", ".", "batch_size", "=", "2", "hparams", ".", "num_heads", "=", ...
TPU related 12 layer 8 heads model.
[ "TPU", "related", "12", "layer", "8", "heads", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L1130-L1143
21,989
tensorflow/tensor2tensor
tensor2tensor/rl/restarter.py
Restarter.training_loop
def training_loop(self): """Context manager wrapping the training loop, updates step counters.""" if not self.restarting: self._write_counters(self._local_step_at_start, self._global_step) tf.logging.info( "Training %s up to %d, %d to go", self.model_mode, self.target_local_step, self...
python
def training_loop(self): """Context manager wrapping the training loop, updates step counters.""" if not self.restarting: self._write_counters(self._local_step_at_start, self._global_step) tf.logging.info( "Training %s up to %d, %d to go", self.model_mode, self.target_local_step, self...
[ "def", "training_loop", "(", "self", ")", ":", "if", "not", "self", ".", "restarting", ":", "self", ".", "_write_counters", "(", "self", ".", "_local_step_at_start", ",", "self", ".", "_global_step", ")", "tf", ".", "logging", ".", "info", "(", "\"Training...
Context manager wrapping the training loop, updates step counters.
[ "Context", "manager", "wrapping", "the", "training", "loop", "updates", "step", "counters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/restarter.py#L90-L102
21,990
tensorflow/tensor2tensor
tensor2tensor/data_generators/ptb.py
_read_words
def _read_words(filename): """Reads words from a file.""" with tf.gfile.GFile(filename, "r") as f: if sys.version_info[0] >= 3: return f.read().replace("\n", " %s " % EOS).split() else: return f.read().decode("utf-8").replace("\n", " %s " % EOS).split()
python
def _read_words(filename): """Reads words from a file.""" with tf.gfile.GFile(filename, "r") as f: if sys.version_info[0] >= 3: return f.read().replace("\n", " %s " % EOS).split() else: return f.read().decode("utf-8").replace("\n", " %s " % EOS).split()
[ "def", "_read_words", "(", "filename", ")", ":", "with", "tf", ".", "gfile", ".", "GFile", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "return", "f", ".", "read", "(", ")", ...
Reads words from a file.
[ "Reads", "words", "from", "a", "file", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ptb.py#L39-L45
21,991
tensorflow/tensor2tensor
tensor2tensor/data_generators/ptb.py
_build_vocab
def _build_vocab(filename, vocab_path, vocab_size): """Reads a file to build a vocabulary of `vocab_size` most common words. The vocabulary is sorted by occurrence count and has one word per line. Originally from: https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py Args: file...
python
def _build_vocab(filename, vocab_path, vocab_size): """Reads a file to build a vocabulary of `vocab_size` most common words. The vocabulary is sorted by occurrence count and has one word per line. Originally from: https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py Args: file...
[ "def", "_build_vocab", "(", "filename", ",", "vocab_path", ",", "vocab_size", ")", ":", "data", "=", "_read_words", "(", "filename", ")", "counter", "=", "collections", ".", "Counter", "(", "data", ")", "count_pairs", "=", "sorted", "(", "counter", ".", "i...
Reads a file to build a vocabulary of `vocab_size` most common words. The vocabulary is sorted by occurrence count and has one word per line. Originally from: https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py Args: filename: file to read list of words from. vocab_path: pa...
[ "Reads", "a", "file", "to", "build", "a", "vocabulary", "of", "vocab_size", "most", "common", "words", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ptb.py#L48-L66
21,992
tensorflow/tensor2tensor
tensor2tensor/data_generators/ptb.py
_get_token_encoder
def _get_token_encoder(vocab_dir, vocab_name, filename): """Reads from file and returns a `TokenTextEncoder` for the vocabulary.""" vocab_path = os.path.join(vocab_dir, vocab_name) if not tf.gfile.Exists(vocab_path): _build_vocab(filename, vocab_path, 10000) return text_encoder.TokenTextEncoder(vocab_path)
python
def _get_token_encoder(vocab_dir, vocab_name, filename): """Reads from file and returns a `TokenTextEncoder` for the vocabulary.""" vocab_path = os.path.join(vocab_dir, vocab_name) if not tf.gfile.Exists(vocab_path): _build_vocab(filename, vocab_path, 10000) return text_encoder.TokenTextEncoder(vocab_path)
[ "def", "_get_token_encoder", "(", "vocab_dir", ",", "vocab_name", ",", "filename", ")", ":", "vocab_path", "=", "os", ".", "path", ".", "join", "(", "vocab_dir", ",", "vocab_name", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "vocab_path", "...
Reads from file and returns a `TokenTextEncoder` for the vocabulary.
[ "Reads", "from", "file", "and", "returns", "a", "TokenTextEncoder", "for", "the", "vocabulary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ptb.py#L69-L74
21,993
tensorflow/tensor2tensor
tensor2tensor/visualization/attention.py
resize
def resize(att_mat, max_length=None): """Normalize attention matrices and reshape as necessary.""" for i, att in enumerate(att_mat): # Add extra batch dim for viz code to work. if att.ndim == 3: att = np.expand_dims(att, axis=0) if max_length is not None: # Sum across different attention val...
python
def resize(att_mat, max_length=None): """Normalize attention matrices and reshape as necessary.""" for i, att in enumerate(att_mat): # Add extra batch dim for viz code to work. if att.ndim == 3: att = np.expand_dims(att, axis=0) if max_length is not None: # Sum across different attention val...
[ "def", "resize", "(", "att_mat", ",", "max_length", "=", "None", ")", ":", "for", "i", ",", "att", "in", "enumerate", "(", "att_mat", ")", ":", "# Add extra batch dim for viz code to work.", "if", "att", ".", "ndim", "==", "3", ":", "att", "=", "np", "."...
Normalize attention matrices and reshape as necessary.
[ "Normalize", "attention", "matrices", "and", "reshape", "as", "necessary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/attention.py#L62-L75
21,994
tensorflow/tensor2tensor
tensor2tensor/visualization/attention.py
_get_attention
def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts): """Compute representation of the attention ready for the d3 visualization. Args: inp_text: list of strings, words to be displayed on the left of the vis out_text: list of strings, words to be displayed on the right of the vis enc_...
python
def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts): """Compute representation of the attention ready for the d3 visualization. Args: inp_text: list of strings, words to be displayed on the left of the vis out_text: list of strings, words to be displayed on the right of the vis enc_...
[ "def", "_get_attention", "(", "inp_text", ",", "out_text", ",", "enc_atts", ",", "dec_atts", ",", "encdec_atts", ")", ":", "def", "get_full_attention", "(", "layer", ")", ":", "\"\"\"Get the full input+output - input+output attentions.\"\"\"", "enc_att", "=", "enc_atts"...
Compute representation of the attention ready for the d3 visualization. Args: inp_text: list of strings, words to be displayed on the left of the vis out_text: list of strings, words to be displayed on the right of the vis enc_atts: numpy array, encoder self-attentions [num_layers, batch_size, nu...
[ "Compute", "representation", "of", "the", "attention", "ready", "for", "the", "d3", "visualization", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/attention.py#L78-L163
21,995
tensorflow/tensor2tensor
tensor2tensor/data_generators/tokenizer.py
decode
def decode(tokens): """Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string """ token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens] ret = [] for i, token in enumerate(tokens): if i > 0 and token_is_alnum[i - 1] and token_...
python
def decode(tokens): """Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string """ token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens] ret = [] for i, token in enumerate(tokens): if i > 0 and token_is_alnum[i - 1] and token_...
[ "def", "decode", "(", "tokens", ")", ":", "token_is_alnum", "=", "[", "t", "[", "0", "]", "in", "_ALPHANUMERIC_CHAR_SET", "for", "t", "in", "tokens", "]", "ret", "=", "[", "]", "for", "i", ",", "token", "in", "enumerate", "(", "tokens", ")", ":", "...
Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string
[ "Decode", "a", "list", "of", "tokens", "to", "a", "unicode", "string", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L91-L105
21,996
tensorflow/tensor2tensor
tensor2tensor/data_generators/tokenizer.py
_read_filepattern
def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True): """Reads files matching a wildcard pattern, yielding the contents. Args: filepattern: A wildcard pattern matching one or more files. max_lines: If set, stop reading after reading this many lines. split_on_newlines: A boolean. I...
python
def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True): """Reads files matching a wildcard pattern, yielding the contents. Args: filepattern: A wildcard pattern matching one or more files. max_lines: If set, stop reading after reading this many lines. split_on_newlines: A boolean. I...
[ "def", "_read_filepattern", "(", "filepattern", ",", "max_lines", "=", "None", ",", "split_on_newlines", "=", "True", ")", ":", "filenames", "=", "sorted", "(", "tf", ".", "gfile", ".", "Glob", "(", "filepattern", ")", ")", "lines_read", "=", "0", "for", ...
Reads files matching a wildcard pattern, yielding the contents. Args: filepattern: A wildcard pattern matching one or more files. max_lines: If set, stop reading after reading this many lines. split_on_newlines: A boolean. If true, then split files by lines and strip leading and trailing whitespa...
[ "Reads", "files", "matching", "a", "wildcard", "pattern", "yielding", "the", "contents", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L108-L145
21,997
tensorflow/tensor2tensor
tensor2tensor/data_generators/tokenizer.py
corpus_token_counts
def corpus_token_counts( text_filepattern, corpus_max_lines, split_on_newlines=True): """Read the corpus and compute a dictionary of token counts. Args: text_filepattern: A pattern matching one or more files. corpus_max_lines: An integer; maximum total lines to read. split_on_newlines: A boolean. I...
python
def corpus_token_counts( text_filepattern, corpus_max_lines, split_on_newlines=True): """Read the corpus and compute a dictionary of token counts. Args: text_filepattern: A pattern matching one or more files. corpus_max_lines: An integer; maximum total lines to read. split_on_newlines: A boolean. I...
[ "def", "corpus_token_counts", "(", "text_filepattern", ",", "corpus_max_lines", ",", "split_on_newlines", "=", "True", ")", ":", "counts", "=", "collections", ".", "Counter", "(", ")", "for", "doc", "in", "_read_filepattern", "(", "text_filepattern", ",", "max_lin...
Read the corpus and compute a dictionary of token counts. Args: text_filepattern: A pattern matching one or more files. corpus_max_lines: An integer; maximum total lines to read. split_on_newlines: A boolean. If true, then split files by lines and strip leading and trailing whitespace from each l...
[ "Read", "the", "corpus", "and", "compute", "a", "dictionary", "of", "token", "counts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L148-L171
21,998
tensorflow/tensor2tensor
tensor2tensor/data_generators/tokenizer.py
vocab_token_counts
def vocab_token_counts(text_filepattern, max_lines): """Read a vocab file and return a dictionary of token counts. Reads a two-column CSV file of tokens and their frequency in a dataset. The tokens are presumed to be generated by encode() or the equivalent. Args: text_filepattern: A pattern matching one o...
python
def vocab_token_counts(text_filepattern, max_lines): """Read a vocab file and return a dictionary of token counts. Reads a two-column CSV file of tokens and their frequency in a dataset. The tokens are presumed to be generated by encode() or the equivalent. Args: text_filepattern: A pattern matching one o...
[ "def", "vocab_token_counts", "(", "text_filepattern", ",", "max_lines", ")", ":", "ret", "=", "{", "}", "for", "i", ",", "line", "in", "enumerate", "(", "_read_filepattern", "(", "text_filepattern", ",", "max_lines", "=", "max_lines", ")", ")", ":", "if", ...
Read a vocab file and return a dictionary of token counts. Reads a two-column CSV file of tokens and their frequency in a dataset. The tokens are presumed to be generated by encode() or the equivalent. Args: text_filepattern: A pattern matching one or more files. max_lines: An integer; maximum total lin...
[ "Read", "a", "vocab", "file", "and", "return", "a", "dictionary", "of", "token", "counts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L174-L197
21,999
tensorflow/tensor2tensor
tensor2tensor/serving/serving_utils.py
_make_example
def _make_example(input_ids, problem, input_feature_name="inputs"): """Make a tf.train.Example for the problem. features[input_feature_name] = input_ids Also fills in any other required features with dummy values. Args: input_ids: list<int>. problem: Problem. input_feature_name: name of feature f...
python
def _make_example(input_ids, problem, input_feature_name="inputs"): """Make a tf.train.Example for the problem. features[input_feature_name] = input_ids Also fills in any other required features with dummy values. Args: input_ids: list<int>. problem: Problem. input_feature_name: name of feature f...
[ "def", "_make_example", "(", "input_ids", ",", "problem", ",", "input_feature_name", "=", "\"inputs\"", ")", ":", "features", "=", "{", "input_feature_name", ":", "tf", ".", "train", ".", "Feature", "(", "int64_list", "=", "tf", ".", "train", ".", "Int64List...
Make a tf.train.Example for the problem. features[input_feature_name] = input_ids Also fills in any other required features with dummy values. Args: input_ids: list<int>. problem: Problem. input_feature_name: name of feature for input_ids. Returns: tf.train.Example
[ "Make", "a", "tf", ".", "train", ".", "Example", "for", "the", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/serving_utils.py#L36-L81