INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns transposed version of this network. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. output_channels: Optional iterable of numbers of output channels. kernel_shapes: O...
def transpose(self, name=None, output_channels=None, kernel_shapes=None, strides=None, paddings=None, activation=None, activate_final=None, normalization_ctor=None, normalizati...
Loads the data or reads it from cache.
def _get_raw_data(subset): """Loads the data or reads it from cache.""" raw_data = _LOADED.get(subset) if raw_data is not None: return raw_data, _LOADED["vocab"] else: train_data, valid_data, test_data, vocab = ptb_reader.ptb_raw_data( FLAGS.data_path) _LOADED.update({ "train": np.ar...
A builder for the gaussian scale-mixture prior of Fortunato et al. Please see https://arxiv.org/abs/1704.02798, section 7.1 Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variable`. name: The `name` argument passed to `tf.get_variable`. *args: Po...
def custom_scale_mixture_prior_builder(getter, name, *args, **kwargs): """A builder for the gaussian scale-mixture prior of Fortunato et al. Please see https://arxiv.org/abs/1704.02798, section 7.1 Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variabl...
A builder for a particular diagonal gaussian posterior. Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variable`. name: The `name` argument passed to `tf.get_variable`. *args: Positional arguments forwarded by `tf.get_variable`. **kwargs: Keywor...
def lstm_posterior_builder(getter, name, *args, **kwargs): """A builder for a particular diagonal gaussian posterior. Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variable`. name: The `name` argument passed to `tf.get_variable`. *args: Positiona...
Construct the modules used in the graph.
def build_modules(is_training, vocab_size): """Construct the modules used in the graph.""" # Construct the custom getter which implements Bayes by Backprop. if is_training: estimator_mode = tf.constant(bbb.EstimatorModes.sample) else: estimator_mode = tf.constant(bbb.EstimatorModes.mean) lstm_bbb_cus...
This is the core model logic. Unrolls a Bayesian RNN over the given sequence. Args: data_ops: A `sequence_data.SequenceDataOps` namedtuple. embed_layer: A `snt.Embed` instance. rnn_core: A `snt.RNNCore` instance. output_linear: A `snt.Linear` instance. name_prefix: A string to use to prefix lo...
def build_logits(data_ops, embed_layer, rnn_core, output_linear, name_prefix): """This is the core model logic. Unrolls a Bayesian RNN over the given sequence. Args: data_ops: A `sequence_data.SequenceDataOps` namedtuple. embed_layer: A `snt.Embed` instance. rnn_core: A `snt.RNNCore` instance. o...
Compute the log loss given predictions and targets.
def build_loss(model_logits, sparse_targets): """Compute the log loss given predictions and targets.""" time_major_shape = [FLAGS.unroll_steps, FLAGS.batch_size] flat_batch_shape = [FLAGS.unroll_steps * FLAGS.batch_size, -1] xent = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=tf.reshape(model_lo...
Run a network on the PTB training set, checkpointing the weights.
def train(logdir): """Run a network on the PTB training set, checkpointing the weights.""" ptb_train = PTB( name="ptb_train", subset="train", seq_len=FLAGS.unroll_steps, batch_size=FLAGS.batch_size) # Connect to training set. data_ops = ptb_train() embed_layer, rnn_core, output_linea...
Throw helpful error if required dependencies not available.
def _ensure_dependency_available_at_version(package_name, min_version): """Throw helpful error if required dependencies not available.""" try: pkg = importlib.import_module(package_name) except ImportError: pip_name = package_name.replace('_', '-') raise SystemError( 'Sonnet requires %s (mini...
Create an op that scales gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these ops automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is used. This method produces a new op ...
def _scale_gradient_op(dtype): """Create an op that scales gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these ops automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is use...
Construct the data, model, loss and optimizer then train.
def build_and_train(iterations, log_stride, test=False): """Construct the data, model, loss and optimizer then train.""" # Test mode settings. batch_size = 2 if test else FLAGS.batch_size num_mems = 2 if test else FLAGS.num_mems num_heads = 1 if test else FLAGS.num_mems num_blocks = 1 if test else FLAGS.nu...
Scales gradients for the backwards pass. This might be used to, for example, allow one part of a model to learn at a lower rate than the rest. WARNING: Think carefully about how your optimizer works. If, for example, you use rmsprop, the gradient is always rescaled (with some additional epsilon) towards uni...
def scale_gradient(net, scale, name="scale_gradient"): """Scales gradients for the backwards pass. This might be used to, for example, allow one part of a model to learn at a lower rate than the rest. WARNING: Think carefully about how your optimizer works. If, for example, you use rmsprop, the gradient is ...
Dynamic unroll across input objects. Args: inputs: tensor (input_sequence_length x batch x feature_size). Encoder sequence. targets: tensor (output_sequence_length x batch x feature_size). Decoder sequence. input_sequence_length: tensor (batch). Size of each batched input ...
def _build( self, inputs, targets, input_sequence_length, output_sequence_length): """Dynamic unroll across input objects. Args: inputs: tensor (input_sequence_length x batch x feature_size). Encoder sequence. targets: tensor (output_sequence_length x batch x feature_size). Decoder ...
LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob: the probability to keep an entry when applying dropout. **kwargs: Extra keyword arguments to pass to the LSTM. Returns: A tuple (train_lstm, test_lstm) where train_lstm is an LSTM with recurrent dropout enabled to...
def lstm_with_recurrent_dropout(hidden_size, keep_prob=0.5, **kwargs): """LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob: the probability to keep an entry when applying dropout. **kwargs: Extra keyword arguments to pass to the LSTM. Returns: A tuple (train_lstm, ...
LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob_c: the probability to use the new value of the cell state rather than freezing it. keep_prob_h: the probability to use the new value of the hidden state rather than freezing it. **kwargs: Extra keyword argumen...
def lstm_with_zoneout(hidden_size, keep_prob_c=0.5, keep_prob_h=0.95, **kwargs): """LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob_c: the probability to use the new value of the cell state rather than freezing it. keep_prob_h: the probability to use the new value ...
Highway core with recurrent dropout. Args: hidden_size: (int) Hidden size dimensionality. num_layers: (int) Number of highway layers. keep_prob: the probability to keep an entry when applying dropout. **kwargs: Extra keyword arguments to pass to the highway core. Returns: A tuple (train_core, ...
def highway_core_with_recurrent_dropout( hidden_size, num_layers, keep_prob=0.5, **kwargs): """Highway core with recurrent dropout. Args: hidden_size: (int) Hidden size dimensionality. num_layers: (int) Number of highway layers. keep_prob: the probability to keep an entry when applying ...
Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates: bias of gates w_f_diag: weight for prev_cell -> forget gate peephole w_i_diag: weight for prev_cell -> input gate peephole w_o_diag:...
def get_possible_initializer_keys(cls, use_peepholes=False, use_projection=False): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates: bias of gates w_f_...
Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The batch s...
def _build(self, inputs, prev_state): """Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for the...
Initialize the variables used for the gates.
def _create_gate_variables(self, input_shape, dtype): """Initialize the variables used for the gates.""" if len(input_shape) != 2: raise ValueError( "Rank of shape must be {} not: {}".format(2, len(input_shape))) equiv_input_size = self._hidden_state_size + input_shape.dims[1].value ini...
Initialize the variables used for the peephole connections.
def _create_peephole_variables(self, dtype): """Initialize the variables used for the peephole connections.""" self._w_f_diag = tf.get_variable( self.W_F_DIAG, shape=[self._hidden_size], dtype=dtype, initializer=self._initializers.get(self.W_F_DIAG), partitioner=self._par...
Tuple of `tf.TensorShape`s indicating the size of state tensors.
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" return LSTMState(tf.TensorShape([self._hidden_state_size]), tf.TensorShape([self._hidden_size]))
Builds the default start state tensor of zeros.
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros.""" core_initial_state = self._core.initial_state( batch_size, dtype=dtyp...
Builds the default start state tensor of zeros.
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros.""" return self._core.initial_state( batch_size, dtype=dtype, trainable=t...
Wraps this RNNCore with the additional control input to the `BatchNorm`s. Example usage: lstm = snt.BatchNormLSTM(4) is_training = tf.placeholder(tf.bool) rnn_input = ... my_rnn = rnn.rnn(lstm.with_batch_norm_control(is_training), rnn_input) Args: is_training: Boolean that indic...
def with_batch_norm_control(self, is_training, test_local_stats=True): """Wraps this RNNCore with the additional control input to the `BatchNorm`s. Example usage: lstm = snt.BatchNormLSTM(4) is_training = tf.placeholder(tf.bool) rnn_input = ... my_rnn = rnn.rnn(lstm.with_batch_norm_con...
Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates: bias of gates w_f_diag: weight for prev_cell -> forget gate peephole w_i_diag: weight for prev_cell -> input gate peephole w_o_diag:...
def get_possible_initializer_keys( cls, use_peepholes=False, use_batch_norm_h=True, use_batch_norm_x=False, use_batch_norm_c=False): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates:...
Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The batch s...
def _build(self, inputs, prev_state, is_training=None, test_local_stats=True): """Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing var...
Initialize the variables used for the `BatchNorm`s (if any).
def _create_batch_norm_variables(self, dtype): """Initialize the variables used for the `BatchNorm`s (if any).""" # The paper recommends a value of 0.1 for good gradient flow through the # tanh nonlinearity (although doesn't say whether this is for all gammas, # or just some). gamma_initializer = tf...
Initialize the variables used for the gates.
def _create_gate_variables(self, input_shape, dtype): """Initialize the variables used for the gates.""" if len(input_shape) != 2: raise ValueError( "Rank of shape must be {} not: {}".format(2, len(input_shape))) input_size = input_shape.dims[1].value b_shape = [4 * self._hidden_size] ...
Builds the default start state tensor of zeros. Args: batch_size: An int, float or scalar Tensor representing the batch size. dtype: The data type to use for the state. trainable: Boolean that indicates whether to learn the initial state. trainable_initializers: An optional pair of initiali...
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros. Args: batch_size: An int, float or scalar Tensor representing the batch s...
Tuple of `tf.TensorShape`s indicating the size of state tensors.
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" if self._max_unique_stats == 1: return (tf.TensorShape([self._hidden_size]), tf.TensorShape([self._hidden_size])) else: return (tf.TensorShape([self._hidden_size]), tf.TensorS...
Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution.
def _new_convolution(self, use_bias): """Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution. """ def clean_dict(input_dict): ...
Tuple of `tf.TensorShape`s indicating the size of state tensors.
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" hidden_size = tf.TensorShape( self._input_shape[:-1] + (self._output_channels,)) return (hidden_size, hidden_size)
Connects the GRU module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The batch si...
def _build(self, inputs, prev_state): """Connects the GRU module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for thei...
Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: wt: weight for input -> T gate wh: weight for input -> H gate wtL: weight for prev state -> T gate for layer L (indexed from 0) whL: weight for prev state -> H gate for layer ...
def get_possible_initializer_keys(cls, num_layers): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: wt: weight for input -> T gate wh: weight for input -> H gate wtL: weight for prev state -> T gate for layer L (indexed fr...
Connects the highway core module into the graph. Args: inputs: Tensor of size `[batch_size, input_size]`. prev_state: Tensor of size `[batch_size, hidden_size]`. Returns: A tuple (output, next_state) where `output` is a Tensor of size `[batch_size, hidden_size]` and `next_state` is a T...
def _build(self, inputs, prev_state): """Connects the highway core module into the graph. Args: inputs: Tensor of size `[batch_size, input_size]`. prev_state: Tensor of size `[batch_size, hidden_size]`. Returns: A tuple (output, next_state) where `output` is a Tensor of size `[batc...
Obtains the list flattened output sizes of a list of cores. Args: cores: list of cores to get the shapes from. Returns: List of lists that, for each core, contains the list of its output dimensions.
def _get_flat_core_sizes(cores): """Obtains the list flattened output sizes of a list of cores. Args: cores: list of cores to get the shapes from. Returns: List of lists that, for each core, contains the list of its output dimensions. """ core_sizes_lists = [] for core in cores: flat_out...
Converts Tensor nest to a TensorShape nest, removing batch dimension.
def _get_shape_without_batch_dimension(tensor_nest): """Converts Tensor nest to a TensorShape nest, removing batch dimension.""" def _strip_batch_and_convert_to_shape(tensor): return tensor.get_shape()[1:] return nest.map_structure(_strip_batch_and_convert_to_shape, tensor_nest)
Connects the VanillaRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The b...
def _build(self, input_, prev_state): """Connects the VanillaRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for ...
Checks the output_sizes of the cores of the DeepRNN module. Raises: ValueError: if the outputs of the cores cannot be concatenated along their first dimension.
def _check_cores_output_sizes(self): """Checks the output_sizes of the cores of the DeepRNN module. Raises: ValueError: if the outputs of the cores cannot be concatenated along their first dimension. """ for core_sizes in zip(*tuple(_get_flat_core_sizes(self._cores))): first_core_li...
Connects the DeepRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The batc...
def _build(self, inputs, prev_state, **kwargs): """Connects the DeepRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct siz...
Builds the default start state for a DeepRNN. Args: batch_size: An int, float or scalar Tensor representing the batch size. dtype: The data type to use for the state. trainable: Boolean that indicates whether to learn the initial state. trainable_initializers: An initializer function or nes...
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state for a DeepRNN. Args: batch_size: An int, float or scalar Tensor representing the batch siz...
Connects the ModelRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The bat...
def _build(self, inputs, prev_state): """Connects the ModelRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for ...
Connects the BidirectionalRNN module into the graph. Args: input_sequence: tensor (time, batch, [feature_1, ..]). It must be time_major. state: tuple of states for the forward and backward cores. Returns: A dict with forward/backard states and output sequences: "outputs":{...
def _build(self, input_sequence, state): """Connects the BidirectionalRNN module into the graph. Args: input_sequence: tensor (time, batch, [feature_1, ..]). It must be time_major. state: tuple of states for the forward and backward cores. Returns: A dict with forward/backard s...
Builds the default start state for a BidirectionalRNN. The Bidirectional RNN flattens the states of its forward and backward cores and concatentates them. Args: batch_size: An int, float or scalar Tensor representing the batch size. dtype: The data type to use for the state. trainable: B...
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state for a BidirectionalRNN. The Bidirectional RNN flattens the states of its forward and backward co...
Instantiates all the linear modules used in the network. Layers are instantiated in the constructor, as opposed to the build function, because MLP implements the Transposable interface, and the transpose function can be called before the module is actually connected to the graph and build is called. ...
def _instantiate_layers(self): """Instantiates all the linear modules used in the network. Layers are instantiated in the constructor, as opposed to the build function, because MLP implements the Transposable interface, and the transpose function can be called before the module is actually connected ...
Assembles the `MLP` and connects it to the graph. Args: inputs: A 2D Tensor of size `[batch_size, input_size]`. is_training: A bool or tf.Bool Tensor. Indicates whether we are currently training. Defaults to `True`. dropout_keep_prob: The probability that each element is kept when ...
def _build(self, inputs, is_training=True, dropout_keep_prob=0.5): """Assembles the `MLP` and connects it to the graph. Args: inputs: A 2D Tensor of size `[batch_size, input_size]`. is_training: A bool or tf.Bool Tensor. Indicates whether we are currently training. Defaults to `True`. ...
Returns a tuple of all output sizes of all the layers.
def output_sizes(self): """Returns a tuple of all output sizes of all the layers.""" return tuple([l() if callable(l) else l for l in self._output_sizes])
Returns transposed `MLP`. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. activate_final: Optional boolean determining if the activation and batch normalization, if turned ...
def transpose(self, name=None, activate_final=None): """Returns transposed `MLP`. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. activate_final: Optional boolean determining i...
Creates a new MLP with the same structure. Args: name: Optional string specifying the name of the new module. The default name is constructed by appending "_clone" to the original name. Returns: A cloned `MLP` module.
def clone(self, name=None): """Creates a new MLP with the same structure. Args: name: Optional string specifying the name of the new module. The default name is constructed by appending "_clone" to the original name. Returns: A cloned `MLP` module. """ if name is None: n...
Calculates the minimum size of the input layer. Given a set of convolutional layers, calculate the minimum value of the `input_height` and `input_width`, i.e. such that the output has size 1x1. Assumes snt.VALID padding. Args: conv_layers: List of tuples `(output_channels, (kernel_size, stride),...
def _calc_min_size(self, conv_layers): """Calculates the minimum size of the input layer. Given a set of convolutional layers, calculate the minimum value of the `input_height` and `input_width`, i.e. such that the output has size 1x1. Assumes snt.VALID padding. Args: conv_layers: List of tu...
Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion this may cause, if `is_training=False` and `keep_prob` would cause dropout to be applied, an error ...
def _build(self, inputs, keep_prob=None, is_training=None, test_local_stats=True): """Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion ...
Generate one input sequence and output label. Each sequences of objects has a feature that consists of the feature vector for that object plus the encoding for its ID, the reference vector ID and the n-th value relative ID for a total feature size of: `num_objects` * 3 + `num_features` Args: ...
def _get_single_set(self, num_objects, num_features): """Generate one input sequence and output label. Each sequences of objects has a feature that consists of the feature vector for that object plus the encoding for its ID, the reference vector ID and the n-th value relative ID for a total feature siz...
Assembles a batch of input tensors and output labels. Args: batch_size: int. number of sequence batches. num_objects: int. number of objects in the sequence. num_features: int. feature size of each object. Returns: 1. np.ndarray (`batch_size`, `num_objects`, (`num_...
def _get_batch_data(self, batch_size, num_objects, num_features): """Assembles a batch of input tensors and output labels. Args: batch_size: int. number of sequence batches. num_objects: int. number of objects in the sequence. num_features: int. feature size of each object. Returns: ...
Returns set of nth-farthest input tensors and labels. Returns: 1. tf.Tensor (`batch_size`, `num_objects`, (`num_features` + 3 * `num_objects`)). 2. tf.Tensor (`batch_size`). Output object reference label.
def get_batch(self): """Returns set of nth-farthest input tensors and labels. Returns: 1. tf.Tensor (`batch_size`, `num_objects`, (`num_features` + 3 * `num_objects`)). 2. tf.Tensor (`batch_size`). Output object reference label. """ params = [self._batch_size, self._num...
Returns default (maximal) output shape for a transpose convolution. In general, there are multiple possible output shapes that a transpose convolution with a given `input_shape` can map to. This function returns the output shape which evenly divides the stride to produce the input shape in a forward convolutio...
def _default_transpose_size(input_shape, stride, kernel_shape=None, padding=SAME): """Returns default (maximal) output shape for a transpose convolution. In general, there are multiple possible output shapes that a transpose convolution with a given `input_shape` can map to. This func...
Converts a dimension to a tuple of dimensions of a given size. This is used to allow shorthand notation for various configuration parameters. A user can provide either, for example, `2` or `[2, 2]` as a kernel shape, and this function returns `(2, 2)` in both cases. Passing `[1, 2]` will return `(1, 2)`. Ar...
def _fill_shape(x, n): """Converts a dimension to a tuple of dimensions of a given size. This is used to allow shorthand notation for various configuration parameters. A user can provide either, for example, `2` or `[2, 2]` as a kernel shape, and this function returns `(2, 2)` in both cases. Passing `[1, 2]` w...
Expands x if necessary into a `n`-D kernel shape and reports errors.
def _fill_and_verify_parameter_shape(x, n, parameter_label): """Expands x if necessary into a `n`-D kernel shape and reports errors.""" try: return _fill_shape(x, n) except TypeError as e: raise base.IncompatibleShapeError("Invalid " + parameter_label + " shape: " "{}...
Verifies that the provided padding is supported and expands to size n. Args: padding: One of ALLOWED_PADDINGS, or an iterable of them. n: An integer, the size of the desired output list. Returns: If `padding` is one of ALLOWED_PADDINGS, a tuple of size `n` containing `n` copies of `padding`. I...
def _fill_and_verify_padding(padding, n): """Verifies that the provided padding is supported and expands to size n. Args: padding: One of ALLOWED_PADDINGS, or an iterable of them. n: An integer, the size of the desired output list. Returns: If `padding` is one of ALLOWED_PADDINGS, a tuple of size `n...
Whether to use SAME or VALID for the underlying convolution op. Args: padding: A tuple of members of ALLOWED_PADDINGS, e.g. as returned from `_fill_and_verify_padding`. Returns: One of CONV_OP_ALLOWED_PADDINGS, the padding method to use for the underlying convolution op. Raises: ValueErro...
def _padding_to_conv_op_padding(padding): """Whether to use SAME or VALID for the underlying convolution op. Args: padding: A tuple of members of ALLOWED_PADDINGS, e.g. as returned from `_fill_and_verify_padding`. Returns: One of CONV_OP_ALLOWED_PADDINGS, the padding method to use for the unde...
Expands the provided stride to size n and pads it with 1s.
def _fill_and_one_pad_stride(stride, n, data_format=DATA_FORMAT_NHWC): """Expands the provided stride to size n and pads it with 1s.""" if isinstance(stride, numbers.Integral) or ( isinstance(stride, collections.Iterable) and len(stride) <= n): if data_format.startswith("NC"): return (1, 1,) + _fill...
Verifies `inputs` is semantically correct. Args: inputs: An input tensor provided by the user. channel_index: The index of the channel dimension. data_format: The format of the data in `inputs`. Raises: base.IncompatibleShapeError: If the shape of `inputs` doesn't match `data_format`. ba...
def _verify_inputs(inputs, channel_index, data_format): """Verifies `inputs` is semantically correct. Args: inputs: An input tensor provided by the user. channel_index: The index of the channel dimension. data_format: The format of the data in `inputs`. Raises: base.IncompatibleShapeError: If th...
Returns a default initializer for the weights of a convolutional module.
def create_weight_initializer(fan_in_shape, dtype=tf.float32): """Returns a default initializer for the weights of a convolutional module.""" stddev = 1 / math.sqrt(np.prod(fan_in_shape)) return tf.truncated_normal_initializer(stddev=stddev, dtype=dtype)
Returns the index of the channel dimension. Args: data_format: A string of characters corresponding to Tensor dimensionality. Returns: channel_index: An integer indicating the channel dimension. Raises: ValueError: If no channel dimension was found.
def _find_channel_index(data_format): """Returns the index of the channel dimension. Args: data_format: A string of characters corresponding to Tensor dimensionality. Returns: channel_index: An integer indicating the channel dimension. Raises: ValueError: If no channel dimension was found. """ ...
Initialize and apply a bias to the outputs. Figures out the shape of the bias vector, initialize it, and applies it. Args: inputs: A Tensor of shape `data_format`. outputs: A Tensor of shape `data_format`. channel_index: The index of the channel dimension in `inputs`. data_format: Format of `input...
def _apply_bias(inputs, outputs, channel_index, data_format, output_channels, initializers, partitioners, regularizers): """Initialize and apply a bias to the outputs. Figures out the shape of the bias vector, initialize it, and applies it. Args: inputs: A Tensor of shape `data_format`. ...
Connects the _ConvND module into the graph, with input Tensor `inputs`. If this is not the first time the module has been connected to the graph, the input Tensor provided here must have the same number of channels, in order for the existing variables to be the correct size for the multiplication; the ...
def _build(self, inputs): """Connects the _ConvND module into the graph, with input Tensor `inputs`. If this is not the first time the module has been connected to the graph, the input Tensor provided here must have the same number of channels, in order for the existing variables to be the correct size...
Pad input in case the desired padding type requires it. VALID and SAME padding types are directly supported by tensorflow convolution ops, so don't require us to pad input ourselves, at least in cases where the same method is used for all dimensions. Other padding types (FULL, CAUSAL, REVERSE_CAUSAL) ...
def _pad_input(self, inputs): """Pad input in case the desired padding type requires it. VALID and SAME padding types are directly supported by tensorflow convolution ops, so don't require us to pad input ourselves, at least in cases where the same method is used for all dimensions. Other padding ...
Apply a convolution operation on `inputs` using variable `w`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. w: A weight matrix of the same type as `inputs`. Returns: outputs: The result of the convolution operation on `inputs...
def _apply_conv(self, inputs, w): """Apply a convolution operation on `inputs` using variable `w`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. w: A weight matrix of the same type as `inputs`. Returns: outputs: The resul...
Applies the passed-in mask to the convolution matrix. Returns: w: A copy of the convolution matrix that has had the mask applied. Raises: base.IncompatibleShapeError: If the mask shape has more dimensions than the weight matrix. base.IncompatibleShapeError: If the mask and the weig...
def _apply_mask(self): """Applies the passed-in mask to the convolution matrix. Returns: w: A copy of the convolution matrix that has had the mask applied. Raises: base.IncompatibleShapeError: If the mask shape has more dimensions than the weight matrix. base.IncompatibleShapeE...
Returns the number of output channels.
def output_channels(self): """Returns the number of output channels.""" if callable(self._output_channels): self._output_channels = self._output_channels() # Channel must be integer. self._output_channels = int(self._output_channels) return self._output_channels
Returns the padding algorithm used, if this is the same for all dims. Use `.paddings` if you want a tuple with the padding algorithm used for each dimension. Returns: The padding algorithm used, if this is the same for all dimensions. Raises: ValueError: If different padding algorithms ar...
def padding(self): """Returns the padding algorithm used, if this is the same for all dims. Use `.paddings` if you want a tuple with the padding algorithm used for each dimension. Returns: The padding algorithm used, if this is the same for all dimensions. Raises: ValueError: If diffe...
Returns a cloned `_ConvND` module. Args: name: Optional string assigning name of cloned module. The default name is constructed by appending "_clone" to `self.module_name`. Returns: A copy of the current class.
def clone(self, name=None): """Returns a cloned `_ConvND` module. Args: name: Optional string assigning name of cloned module. The default name is constructed by appending "_clone" to `self.module_name`. Returns: A copy of the current class. """ if name is None: name = se...
Connects the _ConvNDTranspose module into the graph. If this is not the first time the module has been connected to the graph, the input Tensor provided here must have the same final N dimensions, in order for the existing variables to be the correct size for the multiplication. The batch size may diff...
def _build(self, inputs): """Connects the _ConvNDTranspose module into the graph. If this is not the first time the module has been connected to the graph, the input Tensor provided here must have the same final N dimensions, in order for the existing variables to be the correct size for the multip...
Calculate the output shape for `inputs` after a deconvolution. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: output_shape: A tensor of shape (`batch_size`, `conv_output_shape`).
def _infer_all_output_dims(self, inputs): """Calculate the output shape for `inputs` after a deconvolution. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: output_shape: A tensor of shape (`batch_size`, `conv_output_shap...
Recover output tensor shape value to enable shape inference. The batch size of `inputs` isn't preserved by the convolution op. Calculate what the proper output shape will be for `outputs`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`...
def _recover_shape_information(self, inputs, outputs): """Recover output tensor shape value to enable shape inference. The batch size of `inputs` isn't preserved by the convolution op. Calculate what the proper output shape will be for `outputs`. Args: inputs: A Tensor of shape `data_format` and...
Returns the output shape.
def output_shape(self): """Returns the output shape.""" if self._output_shape is None: self._ensure_is_connected() if callable(self._output_shape): self._output_shape = tuple(self._output_shape()) return self._output_shape
Returns matching `Conv1D` module. Args: name: Optional string assigning name of transpose module. The default name is constructed by appending "_transpose" to `self.name`. Returns: `Conv1D` module.
def transpose(self, name=None): """Returns matching `Conv1D` module. Args: name: Optional string assigning name of transpose module. The default name is constructed by appending "_transpose" to `self.name`. Returns: `Conv1D` module. """ if name is None: name = self.module...
Returns matching `Conv2DTranspose` module. Args: name: Optional string assigning name of transpose module. The default name is constructed by appending "_transpose" to `self.name`. Returns: `Conv2DTranspose` module. Raises: base.NotSupportedError: If `rate` in any dimension > 1.
def transpose(self, name=None): """Returns matching `Conv2DTranspose` module. Args: name: Optional string assigning name of transpose module. The default name is constructed by appending "_transpose" to `self.name`. Returns: `Conv2DTranspose` module. Raises: base.NotSupported...
Returns matching `Conv2D` module. Args: name: Optional string assigning name of transpose module. The default name is constructed by appending "_transpose" to `self.name`. Returns: `Conv2D` module.
def transpose(self, name=None): """Returns matching `Conv2D` module. Args: name: Optional string assigning name of transpose module. The default name is constructed by appending "_transpose" to `self.name`. Returns: `Conv2D` module. """ if name is None: name = self.modu...
Construct the convolution weight matrix. Figures out the shape of the weight matrix, initialize it, and return it. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: w: A weight matrix of the same type as `inputs` and of s...
def _construct_w(self, inputs): """Construct the convolution weight matrix. Figures out the shape of the weight matrix, initialize it, and return it. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: w: A weight matri...
Apply a depthwise_conv2d operation on `inputs` using variable `w`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. w: A weight matrix of the same type as `inputs`. Returns: outputs: The result of the convolution operation on `i...
def _apply_conv(self, inputs, w): """Apply a depthwise_conv2d operation on `inputs` using variable `w`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. w: A weight matrix of the same type as `inputs`. Returns: outputs: The ...
Connects the module into the graph, with input Tensor `inputs`. Args: inputs: A 4D Tensor of shape: [batch_size, input_height, input_width, input_channels] and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: A tuple of two 4D Tensors, each with the same dtype as `...
def _construct_w(self, inputs): """Connects the module into the graph, with input Tensor `inputs`. Args: inputs: A 4D Tensor of shape: [batch_size, input_height, input_width, input_channels] and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: A tuple of two 4D...
Apply a `separable_conv2d` operation on `inputs` using `w`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. w: A tuple of weight matrices of the same type as `inputs`, the first being the depthwise weight matrix, and the second be...
def _apply_conv(self, inputs, w): """Apply a `separable_conv2d` operation on `inputs` using `w`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. w: A tuple of weight matrices of the same type as `inputs`, the first being the d...
Apply a `separable_conv2d` operation on `inputs` using `w`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. w: A tuple of weight matrices of the same type as `inputs`, the first being the depthwise weight matrix, and the second be...
def _apply_conv(self, inputs, w): """Apply a `separable_conv2d` operation on `inputs` using `w`. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. w: A tuple of weight matrices of the same type as `inputs`, the first being the d...
Connects the Sequential module into the graph. Args: *args: A tuple of inputs, to be unpacked as the arguments to the first layer. Returns: The output value of the last layer.
def _build(self, *args): """Connects the Sequential module into the graph. Args: *args: A tuple of inputs, to be unpacked as the arguments to the first layer. Returns: The output value of the last layer. """ net = args if not self._layers: # If the sequential is pa...
Provide a warning that get_variables on Sequential always returns ().
def get_variables(self, *args, **kwargs): """Provide a warning that get_variables on Sequential always returns ().""" tf.logging.warning( "Calling Sequential.get_variables, which will always return an empty " "tuple. get_variables() can only return variables created directly by " "a Modu...
Creates a custom getter that applies specified named arguments. Args: **kwargs: Overriding arguments for the custom getter to use in preference the named arguments it's called with. Returns: Custom getter.
def override_args(**kwargs): """Creates a custom getter that applies specified named arguments. Args: **kwargs: Overriding arguments for the custom getter to use in preference the named arguments it's called with. Returns: Custom getter. """ override_kwargs = kwargs def custom_getter(gette...
Creates a custom getter that applies specified named arguments. The returned custom getter treats the specified named arguments as revised defaults, and does not override any non-`None` argument values supplied by the original get_variable call (or by a nested scope's custom getter). Args: **kwargs: Overr...
def override_default_args(**kwargs): """Creates a custom getter that applies specified named arguments. The returned custom getter treats the specified named arguments as revised defaults, and does not override any non-`None` argument values supplied by the original get_variable call (or by a nested scope's cu...
Builds the TensorFlow variables of the migrated checkpoint. Args: checkpoint_reader: A `tf.train.NewCheckPointReader` of the checkpoint to be read from. name_value_fn: Function taking two arguments, `name` and `value`, which returns the pair of new name and value for that a variable of that name....
def _build_migrated_variables(checkpoint_reader, name_value_fn): """Builds the TensorFlow variables of the migrated checkpoint. Args: checkpoint_reader: A `tf.train.NewCheckPointReader` of the checkpoint to be read from. name_value_fn: Function taking two arguments, `name` and `value`, which re...
Serializes a `tf.SparseTensor` into `nested_proto`. Args: sparse_tensor: An instance of `tf.SparseTensor`. nested_proto: A `module_pb2.NestedData` instance to be filled from `sparse_tensor`. process_leafs: A function to be applied to the leaf valued of the nested structure. already_proces...
def _to_proto_sparse_tensor(sparse_tensor, nested_proto, process_leafs, already_processed): """Serializes a `tf.SparseTensor` into `nested_proto`. Args: sparse_tensor: An instance of `tf.SparseTensor`. nested_proto: A `module_pb2.NestedData` instance to be filled from `spa...
Deserializes a `tf.SparseTensor` from `sparse_tensor_proto`. Args: sparse_tensor_proto: A proto representing a `tf.SparseTensor`. process_leafs: A function to be applied to the leaf valued of the nested structure. Returns: An instance of `tf.SparseTensor`.
def _from_proto_sparse_tensor(sparse_tensor_proto, process_leafs): """Deserializes a `tf.SparseTensor` from `sparse_tensor_proto`. Args: sparse_tensor_proto: A proto representing a `tf.SparseTensor`. process_leafs: A function to be applied to the leaf valued of the nested structure. Returns: A...
Serializes `nested_value` into `nested_proto`. Args: nested_value: A nested Python value. nested_proto: A `module_pb2.NestedData` instance to be filled from the value in `nested_value`. process_leafs: A function to be applied to the leaf values of the nested structure. already_processed: ...
def _nested_to_proto(nested_value, nested_proto, process_leafs, already_processed): """Serializes `nested_value` into `nested_proto`. Args: nested_value: A nested Python value. nested_proto: A `module_pb2.NestedData` instance to be filled from the value in `nested_value`. pro...
Serializes `module_into`. Args: module_info: An instance of `ModuleInfo`. export_scope: Optional `string`. Name scope to remove. Returns: An instance of `module_pb2.SonnetModule`.
def _module_info_to_proto(module_info, export_scope=None): """Serializes `module_into`. Args: module_info: An instance of `ModuleInfo`. export_scope: Optional `string`. Name scope to remove. Returns: An instance of `module_pb2.SonnetModule`. """ def strip_name_scope(name_scope): return ops.s...
Deserializes `nested_proto`. Args: nested_proto: An instance of `module_pb2.NestedData`. process_leafs: A function to be applied to the leaf values of the nested structure. Returns: An instance of `string`, `tuple`, `dict` or `namedtuple`. Raises: base_errors.ModuleInfoError: If the probo...
def _nested_from_proto(nested_proto, process_leafs): """Deserializes `nested_proto`. Args: nested_proto: An instance of `module_pb2.NestedData`. process_leafs: A function to be applied to the leaf values of the nested structure. Returns: An instance of `string`, `tuple`, `dict` or `namedtuple`...
Deserializes `module_info_def` proto. Args: module_info_def: An instance of `module_pb2.SonnetModule`. import_scope: Optional `string`. Name scope to use. Returns: An instance of `ModuleInfo`. Raises: base_errors.ModuleInfoError: If the probobuf is of the wrong type or if some of its fiel...
def _module_info_from_proto(module_info_def, import_scope=None): """Deserializes `module_info_def` proto. Args: module_info_def: An instance of `module_pb2.SonnetModule`. import_scope: Optional `string`. Name scope to use. Returns: An instance of `ModuleInfo`. Raises: base_errors.ModuleInfoEr...
Deserializes the `module_info_def` proto without raising exceptions. Args: module_info_def: An instance of `module_pb2.SonnetModule`. import_scope: Optional `string`. Name scope to use. Returns: An instance of `ModuleInfo`.
def _module_info_from_proto_safe(module_info_def, import_scope=None): """Deserializes the `module_info_def` proto without raising exceptions. Args: module_info_def: An instance of `module_pb2.SonnetModule`. import_scope: Optional `string`. Name scope to use. Returns: An instance of `ModuleInfo`. "...
Returns a tf.train.CheckpointSaverHook for autosaving checkpoints.
def _configure_saver(checkpoint_dir, checkpoint_interval): """Returns a tf.train.CheckpointSaverHook for autosaving checkpoints.""" saver = tf.train.Saver() return tf.train.CheckpointSaverHook( checkpoint_dir=checkpoint_dir, save_steps=checkpoint_interval, saver=saver)
Constructs the computation graph.
def build_graph(lstm_depth=3, batch_size=32, num_embedding=32, num_hidden=128, truncation_length=64, sample_length=1000, max_grad_norm=5, initial_learning_rate=0.1, reduce_learning_rate_multiplier=0.1, optimizer_epsilon=0.01): """Constructs the computation graph.""" ...
Trains a deep LSTM model on the Tiny Shakespeare dataset.
def train(num_training_iterations, report_interval, reduce_learning_rate_interval): """Trains a deep LSTM model on the Tiny Shakespeare dataset.""" # Build the computation graph. graph_tensors, dataset_train = build_graph( lstm_depth=FLAGS.lstm_depth, batch_size=FLAGS.batch_size, num_embedd...
Builds the deep LSTM model sub-graph. Args: one_hot_input_sequence: A Tensor with the input sequence encoded as a one-hot representation. Its dimensions should be `[truncation_length, batch_size, output_size]`. Returns: Tuple of the Tensor of output logits for the batch, with dimen...
def _build(self, one_hot_input_sequence): """Builds the deep LSTM model sub-graph. Args: one_hot_input_sequence: A Tensor with the input sequence encoded as a one-hot representation. Its dimensions should be `[truncation_length, batch_size, output_size]`. Returns: Tuple of the ...
Builds sub-graph to generate a string, sampled from the model. Args: initial_logits: Starting logits to sample from. initial_state: Starting state for the RNN core. sequence_length: Number of characters to sample. Returns: A Tensor of characters, with dimensions `[sequence_length, batc...
def generate_string(self, initial_logits, initial_state, sequence_length): """Builds sub-graph to generate a string, sampled from the model. Args: initial_logits: Starting logits to sample from. initial_state: Starting state for the RNN core. sequence_length: Number of characters to sample. ...