TF 2.0 is out! Get hands-on practice at TF World, Oct 28-31. Use code TF20 for 20% off select passes. Register now

tfa.seq2seq.BeamSearchDecoder

View source on GitHub

Class BeamSearchDecoder

BeamSearch sampling decoder.

Inherits From: BeamSearchDecoderMixin, BaseDecoder

Aliases:

NOTE If you are using the BeamSearchDecoder with a cell wrapped in AttentionWrapper, then you must ensure that:

  • The encoder output has been tiled to beam_width via tfa.seq2seq.tile_batch (NOT tf.tile).
  • The batch_size argument passed to the get_initial_state method of this wrapper is equal to true_batch_size * beam_width.
  • The initial state created with get_initial_state above contains a cell_state value containing properly tiled final state from the encoder.

An example:

tiled_encoder_outputs = tfa.seq2seq.tile_batch(
    encoder_outputs, multiplier=beam_width)
tiled_encoder_final_state = tfa.seq2seq.tile_batch(
    encoder_final_state, multiplier=beam_width)
tiled_sequence_length = tfa.seq2seq.tile_batch(
    sequence_length, multiplier=beam_width)
attention_mechanism = MyFavoriteAttentionMechanism(
    num_units=attention_depth,
    memory=tiled_inputs,
    memory_sequence_length=tiled_sequence_length)
attention_cell = AttentionWrapper(cell, attention_mechanism, ...)
decoder_initial_state = attention_cell.get_initial_state(
    batch_size=true_batch_size * beam_width, dtype=dtype)
decoder_initial_state = decoder_initial_state.clone(
    cell_state=tiled_encoder_final_state)

Meanwhile, with AttentionWrapper, coverage penalty is suggested to use when computing scores (https://arxiv.org/pdf/1609.08144.pdf). It encourages the decoding to cover all inputs.

__init__

View source

__init__(
    cell,
    beam_width,
    embedding_fn=None,
    output_layer=None,
    length_penalty_weight=0.0,
    coverage_penalty_weight=0.0,
    reorder_tensor_arrays=True,
    **kwargs
)

Initialize the BeamSearchDecoder.

Args:

  • cell: An RNNCell instance.
  • beam_width: Python integer, the number of beams.
  • embedding_fn: A callable that takes a vector tensor of ids (argmax ids).
  • output_layer: (Optional) An instance of tf.keras.layers.Layer, i.e., tf.keras.layers.Dense. Optional layer to apply to the RNN output prior to storing the result or sampling.
  • length_penalty_weight: Float weight to penalize length. Disabled with 0.0.
  • coverage_penalty_weight: Float weight to penalize the coverage of source sentence. Disabled with 0.0.
  • reorder_tensor_arrays: If True, TensorArrays' elements within the cell state will be reordered according to the beam search path. If the TensorArray can be reordered, the stacked form will be returned. Otherwise, the TensorArray will be returned as is. Set this flag to False if the cell state contains TensorArrays that are not amenable to reordering.
  • **kwargs: Dict, other keyword arguments for initialization.

Raises:

  • TypeError: if cell is not an instance of RNNCell, or output_layer is not an instance of tf.keras.layers.Layer.

Properties

activity_regularizer

Optional regularizer function for the output of this layer.

batch_size

dtype

dynamic

input

Retrieves the input tensor(s) of a layer.

Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer.

Returns:

Input tensor or list of input tensors.

Raises:

  • RuntimeError: If called in Eager mode.
  • AttributeError: If no inbound nodes are found.

input_mask

Retrieves the input mask tensor(s) of a layer.

Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer.

Returns:

Input mask tensor (potentially None) or list of input mask tensors.

Raises:

  • AttributeError: if the layer is connected to more than one incoming layers.

input_shape

Retrieves the input shape(s) of a layer.

Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer, or if all inputs have the same shape.

Returns:

Input shape, as an integer shape tuple (or list of shape tuples, one tuple per input tensor).

Raises:

  • AttributeError: if the layer has no defined input_shape.
  • RuntimeError: if called in Eager mode.

input_spec

losses

Losses which are associated with this Layer.

Variable regularization tensors are created when this property is accessed, so it is eager safe: accessing losses under a tf.GradientTape will propagate gradients back to the corresponding variables.

Returns:

A list of tensors.

metrics

name

Returns the name of this module as passed or determined in the ctor.

NOTE: This is not the same as the self.name_scope.name which includes parent module names.

name_scope

Returns a tf.name_scope instance for this class.

non_trainable_variables

non_trainable_weights

output

Retrieves the output tensor(s) of a layer.

Only applicable if the layer has exactly one output, i.e. if it is connected to one incoming layer.

Returns:

Output tensor or list of output tensors.

Raises:

  • AttributeError: if the layer is connected to more than one incoming layers.
  • RuntimeError: if called in Eager mode.

output_dtype

A (possibly nested tuple of...) dtype[s].

output_mask

Retrieves the output mask tensor(s) of a layer.

Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer.

Returns:

Output mask tensor (potentially None) or list of output mask tensors.

Raises:

  • AttributeError: if the layer is connected to more than one incoming layers.

output_shape

Retrieves the output shape(s) of a layer.

Only applicable if the layer has one output, or if all outputs have the same shape.

Returns:

Output shape, as an integer shape tuple (or list of shape tuples, one tuple per output tensor).

Raises:

  • AttributeError: if the layer has no defined output shape.
  • RuntimeError: if called in Eager mode.

output_size

submodules

Sequence of all sub-modules.

Submodules are modules which are properties of this module, or found as properties of modules which are properties of this module (and so on).

a = tf.Module()
b = tf.Module()
c = tf.Module()
a.b = b
b.c = c
assert list(a.submodules) == [b, c]
assert list(b.submodules) == [c]
assert list(c.submodules) == []

Returns:

A sequence of all submodules.

tracks_own_finished

The BeamSearchDecoder shuffles its beams and their finished state.

For this reason, it conflicts with the dynamic_decode function's tracking of finished states. Setting this property to true avoids early stopping of decoding due to mismanagement of the finished state in dynamic_decode.

Returns:

True.

trainable

trainable_variables

Sequence of variables owned by this module and it's submodules.

Returns:

A sequence of variables for the current module (sorted by attribute name) followed by variables from all submodules recursively (breadth first).

trainable_weights

updates

variables

Returns the list of all layer variables/weights.

Alias of self.weights.

Returns:

A list of variables.

weights

Returns the list of all layer variables/weights.

Returns:

A list of variables.

Methods

__call__

__call__(
    inputs,
    *args,
    **kwargs
)

Wraps call, applying pre- and post-processing steps.

Arguments:

  • inputs: input tensor(s).
  • *args: additional positional arguments to be passed to self.call.
  • **kwargs: additional keyword arguments to be passed to self.call.

Returns:

Output tensor(s).

Note:

  • The following optional keyword arguments are reserved for specific uses:
    • training: Boolean scalar tensor of Python boolean indicating whether the call is meant for training or inference.
    • mask: Boolean input mask.
  • If the layer's call method takes a mask argument (as some Keras layers do), its default value will be set to the mask generated for inputs by the previous layer (if input did come from a layer that generated a corresponding mask, i.e. if it came from a Keras layer with masking support.

Raises:

  • ValueError: if the layer's call method returns None (an invalid value).

build

build(input_shape)

Creates the variables of the layer (optional, for subclass implementers).

This is a method that implementers of subclasses of Layer or Model can override if they need a state-creation step in-between layer instantiation and layer call.

This is typically used to create the weights of Layer subclasses.

Arguments:

  • input_shape: Instance of TensorShape, or list of instances of TensorShape if the layer expects a list of inputs (one instance per input).

compute_mask

compute_mask(
    inputs,
    mask=None
)

Computes an output mask tensor.

Arguments:

  • inputs: Tensor or list of tensors.
  • mask: Tensor or list of tensors.

Returns:

None or a tensor (or list of tensors, one per output tensor of the layer).

compute_output_shape

compute_output_shape(input_shape)

Computes the output shape of the layer.

If the layer has not been built, this method will call build on the layer. This assumes that the layer will later be used with inputs that match the input shape provided here.

Arguments:

  • input_shape: Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer.

Returns:

An input shape tuple.

count_params

count_params()

Count the total number of scalars composing the weights.

Returns:

An integer count.

Raises:

  • ValueError: if the layer isn't yet built (in which case its weights aren't yet defined).

finalize

View source

finalize(
    outputs,
    final_state,
    sequence_lengths
)

Finalize and return the predicted_ids.

Args:

  • outputs: An instance of BeamSearchDecoderOutput.
  • final_state: An instance of BeamSearchDecoderState. Passed through to the output.
  • sequence_lengths: An int64 tensor shaped [batch_size, beam_width]. The sequence lengths determined for each beam during decode. NOTE These are ignored; the updated sequence lengths are stored in final_state.lengths.

Returns:

  • outputs: An instance of FinalBeamSearchDecoderOutput where the predicted_ids are the result of calling _gather_tree.
  • final_state: The same input instance of BeamSearchDecoderState.

from_config

from_config(
    cls,
    config
)

Creates a layer from its config.

This method is the reverse of get_config, capable of instantiating the same layer from the config dictionary. It does not handle layer connectivity (handled by Network), nor weights (handled by set_weights).

Arguments:

  • config: A Python dictionary, typically the output of get_config.

Returns:

A layer instance.

get_config

get_config()

Returns the config of the layer.

A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration.

The config of a layer does not include connectivity information, nor the layer class name. These are handled by Network (one layer of abstraction above).

Returns:

Python dictionary.

get_input_at

get_input_at(node_index)

Retrieves the input tensor(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A tensor (or list of tensors if the layer has multiple inputs).

Raises:

  • RuntimeError: If called in Eager mode.

get_input_mask_at

get_input_mask_at(node_index)

Retrieves the input mask tensor(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A mask tensor (or list of tensors if the layer has multiple inputs).

get_input_shape_at

get_input_shape_at(node_index)

Retrieves the input shape(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A shape tuple (or list of shape tuples if the layer has multiple inputs).

Raises:

  • RuntimeError: If called in Eager mode.

get_losses_for

get_losses_for(inputs)

Retrieves losses relevant to a specific set of inputs.

Arguments:

  • inputs: Input tensor or list/tuple of input tensors.

Returns:

List of loss tensors of the layer that depend on inputs.

get_output_at

get_output_at(node_index)

Retrieves the output tensor(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A tensor (or list of tensors if the layer has multiple outputs).

Raises:

  • RuntimeError: If called in Eager mode.

get_output_mask_at

get_output_mask_at(node_index)

Retrieves the output mask tensor(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A mask tensor (or list of tensors if the layer has multiple outputs).

get_output_shape_at

get_output_shape_at(node_index)

Retrieves the output shape(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A shape tuple (or list of shape tuples if the layer has multiple outputs).

Raises:

  • RuntimeError: If called in Eager mode.

get_updates_for

get_updates_for(inputs)

Retrieves updates relevant to a specific set of inputs.

Arguments:

  • inputs: Input tensor or list/tuple of input tensors.

Returns:

List of update ops of the layer that depend on inputs.

get_weights

get_weights()

Returns the current weights of the layer.

Returns:

Weights values as a list of numpy arrays.

initialize

View source

initialize(
    embedding,
    start_tokens,
    end_token,
    initial_state
)

Initialize the decoder.

Args:

  • embedding: A tensor from the embedding layer output, which is the params argument for embedding_lookup.
  • start_tokens: int32 vector shaped [batch_size], the start tokens.
  • end_token: int32 scalar, the token that marks end of decoding.
  • initial_state: A (possibly nested tuple of...) tensors and TensorArrays.

Returns:

(finished, start_inputs, initial_state).

Raises:

  • ValueError: If start_tokens is not a vector or end_token is not a scalar.

set_weights

set_weights(weights)

Sets the weights of the layer, from Numpy arrays.

Arguments:

  • weights: a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the layer (i.e. it should match the output of get_weights).

Raises:

  • ValueError: If the provided weights list does not match the layer's specifications.

step

View source

step(
    time,
    inputs,
    state,
    training=None,
    name=None
)

Perform a decoding step.

Args:

  • time: scalar int32 tensor.
  • inputs: A (structure of) input tensors.
  • state: A (structure of) state tensors and TensorArrays.
  • training: Python boolean. Indicates whether the layer should behave in training mode or in inference mode. Only relevant when dropout or recurrent_dropout is used.
  • name: Name scope for any created operations.

Returns:

(outputs, next_state, next_inputs, finished).

with_name_scope

with_name_scope(
    cls,
    method
)

Decorator to automatically enter the module name scope.

class MyModule(tf.Module):
  @tf.Module.with_name_scope
  def __call__(self, x):
    if not hasattr(self, 'w'):
      self.w = tf.Variable(tf.random.normal([x.shape[1], 64]))
    return tf.matmul(x, self.w)

Using the above module would produce tf.Variables and tf.Tensors whose names included the module name:

mod = MyModule()
mod(tf.ones([8, 32]))
# ==> <tf.Tensor: ...>
mod.w
# ==> <tf.Variable ...'my_module/w:0'>

Args:

  • method: The method to wrap.

Returns:

The original method wrapped such that it enters the module's name scope.