Skip to content

Commit 580fcee

Browse files
albertzZettelkasten
andcommitted
CumConcatLayer
This is for generalized self attention (#391). Co-authored-by: Frithjof <[email protected]>
1 parent c1e55d2 commit 580fcee

File tree

1 file changed

+170
-0
lines changed

1 file changed

+170
-0
lines changed

returnn/tf/layers/rec.py

+170
Original file line numberDiff line numberDiff line change
@@ -8496,3 +8496,173 @@ def get_out_data_from_opts(cls, name, sources, n_out, **kwargs):
84968496
kind=DimensionTag.Types.Spatial, description="%s_rel_pos_enc_time" % name, dimension=None)
84978497
data = data.copy_template_new_dim_tags((dummy_dim_tag, time_dim_tag, feature_dim_tag))
84988498
return data
8499+
8500+
8501+
class CumConcatLayer(_ConcatInputLayer):
8502+
"""
8503+
Concatenates all previous frames of a time-axis.
8504+
Like :class:`CumsumLayer` uses `sum`, this layer uses `concat`.
8505+
8506+
This layer expects to be inside a :class:`RecLayer`.
8507+
8508+
Inside a rec loop (not optimized out),
8509+
this will concatenate the current input
8510+
to the previous accumulated inputs.
8511+
For an input of shape `input_shape`,
8512+
it will output a tensor of shape `[new_dim] + input_shape`.
8513+
`new_dim` is a special dimension, usually of length `i`,
8514+
where `i` is the current loop frame,
8515+
i.e. the length increases in every loop frame.
8516+
`new_dim` is specified by a separate own dim tag.
8517+
For example, in the first frame,
8518+
this will be of shape `[1] + input_shape`,
8519+
in the second frame shape `[2] + input_shape`,
8520+
and so on,
8521+
and in the last frame shape `[T] + input_shape`.
8522+
8523+
Outside the rec loop (optimized out),
8524+
this layer expects an input with the time dim of the rec layer,
8525+
and returns the input as-is,
8526+
but replacing the time dim tag with the dim tag `new_dim`
8527+
converted as outside the loop.
8528+
8529+
Normally the optimization should not matter for the user,
8530+
i.e. for the user, the logical behavior is always as being inside the rec loop.
8531+
Outside the loop,
8532+
the output represents a tensor of shape `[T, new_dim] + input_shape`,
8533+
although we actually have another `new_dim` outside the loop,
8534+
and `T` is not actually there,
8535+
but we still have all the information,
8536+
because the last frame has all information.
8537+
8538+
This layer can be used as a base for auto-regressive self-attention.
8539+
"""
8540+
layer_class = "cum_concat"
8541+
recurrent = True # order matters
8542+
8543+
def __init__(self, new_dim, **kwargs):
8544+
"""
8545+
:param DimensionTag new_dim:
8546+
"""
8547+
super(CumConcatLayer, self).__init__(**kwargs)
8548+
rec_layer = self.network.get_rec_parent_layer(inside_loop=False)
8549+
assert rec_layer, "%r must be used inside a RecLayer" % self
8550+
out_axis = self.output.get_axis_from_description(new_dim)
8551+
new_dim_ = self.output.dim_tags[out_axis]
8552+
8553+
if not self.input_data.has_axis(rec_layer.time_dim_tag): # inside loop
8554+
current_data = self.input_data.copy_compatible_to(self.output, unbroadcast=False)
8555+
current_frame = current_data.placeholder # [B, 1, ..., D]
8556+
last_frames = self._rec_previous_layer.rec_vars_outputs["state"] # [B, t, ..., D]
8557+
concat_frames = tf.concat([last_frames, current_frame], axis=out_axis) # [B, t+1, ..., D]
8558+
self.rec_vars_outputs["state"] = concat_frames
8559+
self.output.placeholder = concat_frames
8560+
8561+
if not new_dim_.dyn_size_ext:
8562+
# Unbroadcasting to [B] is not needed because any layers operating on this
8563+
# should be able to handle extended dyn sizes.
8564+
# Clipping it to the max length for sequences in the loop which are already ended
8565+
# (i.e. considering the end flag)
8566+
# is also not needed because any calculations after the end are irrelevant.
8567+
# Note: In case we have some initial state/output, this can be extended.
8568+
dyn_size = self.network.get_rec_step_index() + 1 # scalar
8569+
new_dim_.dyn_size_ext = Data(
8570+
name="%s:cum-concat:size-inside" % self.name,
8571+
dim_tags=[], # scalar
8572+
placeholder=dyn_size, dtype="int32")
8573+
8574+
else: # inside loop
8575+
# If not inside a rec loop, this layer is a no-op on the tensor.
8576+
self.output.placeholder = self.input_data.placeholder
8577+
8578+
# However, we used new dim tags, which were already prepared.
8579+
# We now must fill in the extended dynamic size information.
8580+
if not new_dim_.dyn_size_ext:
8581+
# This must match the logic above for inside the loop.
8582+
# Note: In case we have some initial state/output, this can be extended.
8583+
dyn_size = tf.range(tf.math.reduce_max(rec_layer.time_dim_tag.dyn_size)) + 1 # [T]
8584+
new_dim_.dyn_size_ext = Data(
8585+
name="%s:cum-concat:size-outside" % self.name,
8586+
dim_tags=[rec_layer.time_dim_tag],
8587+
placeholder=dyn_size, dtype="int32")
8588+
8589+
@classmethod
8590+
def get_out_data_from_opts(cls, name, network, sources, new_dim, **kwargs):
8591+
"""
8592+
:param str name:
8593+
:param returnn.tf.network.TFNetwork network:
8594+
:param list[LayerBase] sources:
8595+
:param DimensionTag new_dim:
8596+
:rtype: Data
8597+
"""
8598+
assert network.is_inside_rec_layer(inside_loop=False), "CumConcatLayer %r must be used inside a RecLayer" % name
8599+
rec_time_dim = network.get_inside_rec_time_dim(inside_loop=False)
8600+
assert rec_time_dim
8601+
new_dim_base = new_dim.get_same_base()
8602+
if new_dim_base.per_spatial_frame is None:
8603+
new_dim_base.per_spatial_frame = rec_time_dim
8604+
else:
8605+
assert new_dim_base.per_spatial_frame == rec_time_dim
8606+
8607+
input_data = get_concat_sources_data_template(sources, name="%s_output" % name)
8608+
if not input_data.has_axis(rec_time_dim): # inside loop
8609+
# Currently SelectSearchSourcesLayer assumes that all rec_vars_outputs are batch-major.
8610+
# Therefore we here copy the input as batch-major, and then add the time axis at axis 1.
8611+
# In the future, when SelectSearchSourcesLayer has support for this, we can change this to operate on axis 0,
8612+
# which should be more efficient
8613+
out = input_data.copy_as_batch_major()
8614+
out = out.copy_add_dim_by_tag(new_dim_base, unbroadcast=True, axis=1)
8615+
return out
8616+
8617+
else: # outside loop
8618+
if not new_dim_base.per_spatial_frame_accumulated:
8619+
new_dim_accum = DimensionTag(
8620+
kind=new_dim_base.kind, description="%s:accumulated" % name)
8621+
new_dim_accum.same_as = new_dim_base
8622+
new_dim_base.per_spatial_frame_accumulated = new_dim_accum
8623+
else:
8624+
new_dim_accum = new_dim_base.per_spatial_frame_accumulated
8625+
# Assume that the input has the time dim from the rec layer.
8626+
axis = input_data.get_axis_from_description(rec_time_dim)
8627+
return input_data.copy_template_replace_dim_tag(axis=axis, new_dim_tag=new_dim_accum)
8628+
8629+
# noinspection PyMethodOverriding
8630+
@classmethod
8631+
def get_rec_initial_extra_outputs(cls, network, batch_dim, rec_layer, sources, output, new_dim, **kwargs):
8632+
"""
8633+
:param returnn.tf.network.TFNetwork network:
8634+
:param tf.Tensor batch_dim:
8635+
:param TFNetworkRecLayer.RecLayer|LayerBase rec_layer:
8636+
:param list[LayerBase] sources:
8637+
:param Data output:
8638+
:param DimensionTag new_dim:
8639+
:rtype: dict[str,tf.Tensor]
8640+
"""
8641+
if network.is_inside_rec_layer():
8642+
shape = []
8643+
for tag in output.dim_tags:
8644+
if tag.is_batch_dim():
8645+
shape.append(batch_dim)
8646+
elif tag == new_dim:
8647+
shape.append(0)
8648+
elif tag.dimension is not None:
8649+
shape.append(tag.dimension)
8650+
else:
8651+
assert tag.dyn_size is not None
8652+
shape.append(tf.math.reduce_max(tag.dyn_size))
8653+
return {"state": tf.zeros(shape, dtype=output.dtype)}
8654+
else:
8655+
return {}
8656+
8657+
@classmethod
8658+
def get_rec_initial_extra_outputs_shape_invariants(cls, network, sources, output, **kwargs):
8659+
"""
8660+
:param returnn.tf.network.TFNetwork network:
8661+
:param list[LayerBase] sources:
8662+
:param Data output:
8663+
:rtype: dict[str, tf.TensorShape]
8664+
"""
8665+
if network.is_inside_rec_layer():
8666+
return {"state": tf.TensorShape(output.batch_shape)}
8667+
else:
8668+
return {}

0 commit comments

Comments
 (0)