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