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