code
stringlengths
17
6.64M
def check_graphs(*args): 'Check that all the element in args belong to the same graph.\n\n Args:\n *args: a list of object with a obj.graph property.\n Raises:\n ValueError: if all the elements do not belong to the same graph.\n ' graph = None for (i, sgv) in enumerate(args): if...
def get_unique_graph(tops, check_types=None, none_if_empty=False): "Return the unique graph used by the all the elements in tops.\n\n Args:\n tops: list of elements to check (usually a list of tf.Operation and/or\n tf.Tensor). Or a tf.Graph.\n check_types: check that the element in tops are of...
def make_list_of_op(ops, check_graph=True, allow_graph=True, ignore_ts=False): 'Convert ops to a list of `tf.Operation`.\n\n Args:\n ops: can be an iterable of `tf.Operation`, a `tf.Graph` or a single\n operation.\n check_graph: if `True` check if all the operations belong to the same graph.\n...
def get_tensors(graph): 'get all the tensors which are input or output of an op in the graph.\n\n Args:\n graph: a `tf.Graph`.\n Returns:\n A list of `tf.Tensor`.\n Raises:\n TypeError: if graph is not a `tf.Graph`.\n ' if (not isinstance(graph, tf_ops.Graph)): raise TypeErr...
def make_list_of_t(ts, check_graph=True, allow_graph=True, ignore_ops=False): 'Convert ts to a list of `tf.Tensor`.\n\n Args:\n ts: can be an iterable of `tf.Tensor`, a `tf.Graph` or a single tensor.\n check_graph: if `True` check if all the tensors belong to the same graph.\n allow_graph: if `F...
def get_generating_ops(ts): 'Return all the generating ops of the tensors in `ts`.\n\n Args:\n ts: a list of `tf.Tensor`\n Returns:\n A list of all the generating `tf.Operation` of the tensors in `ts`.\n Raises:\n TypeError: if `ts` cannot be converted to a list of `tf.Tensor`.\n ' ...
def get_consuming_ops(ts): 'Return all the consuming ops of the tensors in ts.\n\n Args:\n ts: a list of `tf.Tensor`\n Returns:\n A list of all the consuming `tf.Operation` of the tensors in `ts`.\n Raises:\n TypeError: if ts cannot be converted to a list of `tf.Tensor`.\n ' ts = ma...
class ControlOutputs(object): 'The control outputs topology.' def __init__(self, graph): 'Create a dictionary of control-output dependencies.\n\n Args:\n graph: a `tf.Graph`.\n Returns:\n A dictionary where a key is a `tf.Operation` instance and the\n corre...
def scope_finalize(scope): if (scope and (scope[(- 1)] != '/')): scope += '/' return scope
def scope_dirname(scope): slash = scope.rfind('/') if (slash == (- 1)): return '' return scope[:(slash + 1)]
def scope_basename(scope): slash = scope.rfind('/') if (slash == (- 1)): return scope return scope[(slash + 1):]
def placeholder_name(t=None, scope=None, prefix=_DEFAULT_PLACEHOLDER_PREFIX): 'Create placeholder name for the graph editor.\n\n Args:\n t: optional tensor on which the placeholder operation\'s name will be based\n on\n scope: absolute scope with which to prefix the placeholder\'s name. None\n...
def make_placeholder_from_tensor(t, scope=None, prefix=_DEFAULT_PLACEHOLDER_PREFIX): 'Create a `tf.compat.v1.placeholder` for the Graph Editor.\n\n Note that the correct graph scope must be set by the calling function.\n\n Args:\n t: a `tf.Tensor` whose name will be used to create the placeholder (see\...
def make_placeholder_from_dtype_and_shape(dtype, shape=None, scope=None, prefix=_DEFAULT_PLACEHOLDER_PREFIX): 'Create a tf.compat.v1.placeholder for the Graph Editor.\n\n Note that the correct graph scope must be set by the calling function.\n The placeholder is named using the function placeholder_name (wi...
def get_predefined_collection_names(): 'Return all the predefined collection names.' return [getattr(tf_ops.GraphKeys, key) for key in dir(tf_ops.GraphKeys) if (not _INTERNAL_VARIABLE_RE.match(key))]
def find_corresponding_elem(target, dst_graph, dst_scope='', src_scope=''): 'Find corresponding op/tensor in a different graph.\n\n Args:\n target: A `tf.Tensor` or a `tf.Operation` belonging to the original graph.\n dst_graph: The graph in which the corresponding graph element must be found.\n ...
def find_corresponding(targets, dst_graph, dst_scope='', src_scope=''): 'Find corresponding ops/tensors in a different graph.\n\n `targets` is a Python tree, that is, a nested structure of iterable\n (list, tupple, dictionary) whose leaves are instances of\n `tf.Tensor` or `tf.Operation`\n\n Args:\n ...
class ForwardCallbackIface(): '\n Callback interface for the forward task.\n\n Define `forward_callback` in your config to an instance or class of this.\n\n https://github.com/rwth-i6/returnn/issues/1336\n ' def init(self, *, model): '\n Run at the beginning.\n ' def pr...
class Backend(Generic[T]): '\n Abstract base class for the backend, operating on tensor type T, i.e. :class:`Tensor[T]`.\n\n This class and instances do not have any state,\n and all functions are staticmethod (or classmethod).\n ' RawTensorType: Type[T] is_tensorflow: bool = False is_back...
def select_backend_tf(): '\n Selects the RETURNN layers backend (based on TF).\n ' import tensorflow as tf backend = get_backend_by_raw_tensor_type(tf.Tensor) global_backend.__class__ = backend BehaviorVersion.set_min_behavior_version(16)
def select_backend_returnn_layers_tf(): '\n Selects the RETURNN layers backend (based on TF).\n ' from returnn.tf.frontend_layers import Layer backend = get_backend_by_raw_tensor_type(Layer) global_backend.__class__ = backend
def select_backend_torch(): '\n Selects the PyTorch (low-level) backend.\n ' import torch backend = get_backend_by_raw_tensor_type(torch.Tensor) global_backend.__class__ = backend BehaviorVersion.set_min_behavior_version(16) from returnn.frontend import _native _native.setup() _n...
def get_backend_by_tensor(tensor: Tensor, *, fallback: Optional[T2]=None) -> Union[(Type[Backend[T]], T2)]: '\n :param tensor:\n :param fallback:\n ' if (fallback and (tensor.raw_tensor is None)): return fallback assert (tensor.raw_tensor is not None) return get_backend_by_raw_tensor_...
def get_backend_by_raw_tensor_type(tensor_type: Type[T]) -> Union[Type[Backend[T]]]: '\n :param tensor_type:\n ' if (tensor_type in _backend_tensor_type_dispatch_table): return _backend_tensor_type_dispatch_table[tensor_type] if (not isinstance(tensor_type, type)): raise TypeError(f'...
def register_backend_by_tensor_type(tensor_type: Type[T], backend: Type[Backend[T]]): '\n :param tensor_type:\n :param backend:\n ' _backend_tensor_type_dispatch_table[tensor_type] = backend
def _get_tensor_types_tf(): '\n :return: tuple of relevant tensor types in TF.\n Note that it is not so important to cover all, as we also check issubclass as a fallback.\n ' import tensorflow as tf ls = [tf.Tensor, tf.Variable] return tuple(ls)
def _get_tensor_types_torch(): '\n :return: tuple of relevant tensor types in PyTorch.\n Note that it is not so important to cover all, as we also check issubclass as a fallback.\n ' import torch ls = [torch.Tensor, torch.nn.Parameter] return tuple(ls)
def get_module(*, verbose: bool=False): '\n :return: native Python extension module\n ' global _module if (_module and (not verbose)): return _module src_code = '' for fn in sorted(glob((_my_dir + '/*.hpp'))): src_code += f'''// {os.path.basename(fn)} code hash md5: {_code_ha...
def _code_hash_md5(filename: str) -> str: f_code = open(filename).read() h = hashlib.md5() h.update(f_code.encode('utf8')) return h.hexdigest()
def setup(): '\n Setup the native code.\n ' global _is_set_up if _is_set_up: return _is_set_up = True from returnn.tensor import Tensor, Dim from returnn.tensor.tensor import _TensorOpOverloadsMixin, _TensorMixin from returnn.tensor.dim import _DimMixin Tensor.raw_tensor ...
def setup_torch(): '\n Like :func:`setup`, but specifically for the PyTorch backend.\n This assumes that we can `import torch`, unlike :func:`setup`.\n ' global _is_set_up_torch if _is_set_up_torch: return _is_set_up_torch = True import torch try: mod = get_module() ...
class NumpyBackend(Backend[numpy.ndarray]): 'Numpy backend' RawTensorType = numpy.ndarray @staticmethod def executing_eagerly() -> bool: 'executing eagerly' return True @staticmethod def get_dtype_name_raw(raw_tensor: numpy.ndarray) -> str: '\n :return: dtype o...
class RandomJournal(): 'random journal. see module docstring' def __init__(self): self._entries: List[RandomJournalEntry] = [] self._cur_entry_idx = 0 self._graph_reader_nodes: List[Tuple[(Tensor, rf.RunCtx)]] = [] def append(self, *, distribution: str, mean: Optional[Union[(int,...
@dataclass class RandomJournalEntry(): 'entry' out: Optional[Tensor[numpy.ndarray]] control_flow_ctx: Optional[ControlFlowContext] run_ctx: rf.RunCtx distribution: str mean: Optional[Union[(int, float, Tensor)]] = None stddev: Optional[Union[(int, float, Tensor)]] = None bound: Optiona...
def get_backend_from_tensors(*args): '\n :param args:\n :return: frontend, fallback to global frontend\n ' for x in args: if isinstance(x, Tensor): return x._raw_backend return _global_rf
def get_dtype_name(x: Union[(T, Tensor[T], int, float)]) -> str: '\n :param x: tensor\n :return: dtype of tensor, as string\n ' if isinstance(x, Tensor): return x.dtype elif isinstance(x, int): return rf.get_default_int_dtype() elif isinstance(x, float): return rf.get_...
def is_int(x: Union[(T, Tensor[T], int, float)]) -> bool: '\n :param x:\n :return: whether the dtype is int\n ' dtype = get_dtype_name(x) return (dtype.startswith('int') or dtype.startswith('uint'))
def bin_op_out_template(backend: Type[Backend], a: Union[(Tensor[T], int, float, numpy.number)], b: Union[(Tensor[T], int, float, numpy.number)], *, name: str, copy_sparse_dim: bool=True, allow_broadcast_all_sources: Optional[bool]=None, dim_order: Optional[Sequence[Dim]]=None, allow_scalar: bool=True) -> Tuple[(Tens...
def res_feature_dim(a: Tensor, b: Tensor) -> Optional[Dim]: '\n :param a:\n :param b:\n :return: feature dim if consistent or None\n ' if (a.feature_dim and (not b.feature_dim)): return a.feature_dim if (b.feature_dim and (not a.feature_dim)): return b.feature_dim if (a.fea...
def res_sparse_dim(a: Tensor, b: Tensor) -> Optional[Dim]: '\n :param a:\n :param b:\n :return: sparse dim if consistent or None\n ' if (a.sparse_dim and (not b.sparse_dim)): return a.sparse_dim if (b.sparse_dim and (not a.sparse_dim)): return b.sparse_dim if (a.sparse_dim ...
def strided_slice_raw_key(tensor: Tensor, axis: Optional[Union[(Dim, Sequence[Dim])]]=None, key: Optional[rf.ItemKeyType]=None, key_dim: Optional[Union[(Dim, Sequence[Dim])]]=None) -> Tuple[(Union[(slice, int, T, Sequence[Union[(None, slice, int, T)]])], Tuple[(Dim, ...)])]: '\n Given an axis and a key, return...
def _slice_find_sparse_dim(v: Union[(Tensor, slice, Any)]) -> Optional[Dim]: if isinstance(v, Tensor): return v.sparse_dim if isinstance(v, slice): attribs = {k: getattr(v, k) for k in ('start', 'stop', 'step')} tensors = {k: v for (k, v) in attribs.items() if isinstance(v, Tensor)} ...
def _map_slice_value_raw(v: Union[(None, slice, int, numpy.number, numpy.ndarray, Tensor[T])]) -> Union[(None, slice, int, numpy.number, T)]: if (v is None): return None if isinstance(v, slice): return slice(_map_slice_value_raw(v.start), _map_slice_value_raw(v.stop), _map_slice_value_raw(v.st...
def _slice_value_is_reduce(v: Union[(None, slice, int, numpy.number, numpy.ndarray, Tensor[T])]) -> bool: if (v is None): return False if isinstance(v, slice): return False if isinstance(v, (int, numpy.number)): return True if isinstance(v, numpy.ndarray): assert (v.ndi...
def convert_to_tensor(value: Union[(Tensor, T, RawTensorTypes)], *, dims: Sequence[Dim]=None, dtype: Optional[str]=None, sparse_dim: Optional[Dim]=None, shape: Sequence[Dim]=None, device: Optional[str]=None, keep_scalar_on_cpu: bool=False, name: Optional[str]=None, _backend: Optional[Type[Backend]]=None) -> Tensor[T]...
def copy(tensor: Tensor) -> Tensor: '\n :param tensor:\n :return: copy of tensor.\n In eager-based frameworks, it is really a copy.\n In graph-based frameworks, it might be just a copied reference if it would be immutable.\n This is really only relevant when operating on tensors which c...
def cast(tensor: Tensor, dtype: str) -> Tensor: '\n :param tensor:\n :param dtype:\n :return: tensor with the same data, but with a different dtype\n ' return tensor._raw_backend.cast(tensor, dtype=dtype)
def merge_dims(source: Tensor, *, dims: Sequence[Dim], out_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim)]: '\n Merges a list of axes into a single one. (Flatten the dims.)\n E.g. input is (batch, width, height, dim) and dims=(width,height), then we get (batch, width*height, dim).\n Or input is (batch, ...
def split_dims(source: Tensor, *, axis: Dim, dims: Sequence[Dim], pad_to_multiples: Optional[bool]=None, pad_value: Union[(None, int, float)]=None) -> Tensor: '\n Splits one axis into multiple axes.\n E.g. if you know that your feature-dim is composed by a window,\n i.e. the input is (batch, time, window...
def reshape(source: Tensor, in_dims: Sequence[Dim], out_dims: Sequence[Dim]) -> Tensor: '\n Wraps tf.reshape.\n\n You should use :func:`split_dims` or :func:`merge_dims`\n when you want to split or merge dimensions.\n This here is for doing any other kind of reshape.\n This can be used for clever i...
def split(source: Tensor, *, axis: Dim, out_dims: Sequence[Dim]) -> Tuple[(Tensor, ...)]: '\n Split the input on the specified axis (by default feature).\n Basically a wrapper around tf.split.\n\n :param source: {..., axis}\n :param axis: some static axis\n :param out_dims: list of dims where sum(o...
def expand_dim(source: Tensor, dim: Dim) -> Tensor: '\n Expand the source by the given dimension.\n\n Note that this is *never* needed for broadcasting.\n All broadcasting should always happen automatically.\n\n This might be needed for convolution or concatenation.\n ' return source._raw_backe...
def squeeze(source: Tensor, axis: Dim) -> Tensor: '\n Removes the axis with dimension of extend 1 from the source.\n ' assert (axis.dimension == 1), f'squeeze {source}: axis {axis} is not of extend 1' return source._raw_backend.squeeze(source, axis=axis)
def window(source: Tensor, *, spatial_dim: Dim, window_dim: Dim, window_right: Optional[Union[(Dim, int)]]=None, window_left: Optional[Union[(Dim, int)]]=None, padding: str='same', pad_value: Optional[Union[(int, float)]]=None, stride: int=1) -> Tuple[(Tensor, Dim)]: '\n Follows the same idea as RETURNN tf_uti...
def concat(*sources: Tuple[(Tensor, Dim)], allow_broadcast: bool=False, out_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim)]: '\n Concatenates multiple sources in the specified dimension.\n ' assert sources if (not allow_broadcast): dims = (sources[0][0].dims_set - {sources[0][1]}) f...
def concat_features(*sources: Tensor, allow_broadcast=False) -> Tensor: '\n Concatenates multiple sources, using feature_dim of each source,\n so make sure that the feature_dim is correctly set.\n ' src_pairs = [] for src in sources: assert (src.feature_dim is not None) src_pairs....
def pad(source: Tensor, *, axes: Sequence[Dim], padding: Sequence[Tuple[(Union[(Dim, int)], Union[(Dim, int)])]], out_dims: Optional[Sequence[Dim]]=None, mode: str='constant', value: Optional[Union[(rf.RawTensorTypes, Tensor)]]=None) -> Tuple[(Tensor, Sequence[Dim])]: '\n Pad values left/right in the specified...
def cum_concat_step(source: Tensor, *, prev_accum: Tensor, axis: Dim, out_spatial_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim)]: '\n Concatenates all previous frames over a time-axis.\n See RETURNN :class:`CumConcatLayer` for details.\n\n :param source: same dims as prev_accum except for the accum axi...
def masked_select(tensor: Tensor, *, mask: Tensor, dims: Sequence[Dim], out_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim)]: '\n In TF, this is ``boolean_mask``.\n The inverse of this is :func:`masked_scatter`.\n\n :param tensor:\n :param mask:\n :param dims: the order of the dims defines the form...
def masked_scatter(source: Tensor, *, mask: Tensor, dims: Sequence[Dim], in_dim: Dim) -> Tensor: '\n The inverse of :func:`masked_select`.\n\n :param source: [in_dim, F...]\n :param mask: [dims...] -> bool (e.g. [B,T])\n :param dims: the order of the dims defines the format. those dims should be exact...
def sequence_mask(dims: Union[(Dim, Sequence[Dim])], *, device: Optional[str]=None) -> Tensor: '\n :param dims:\n :param device:\n ' if isinstance(dims, Dim): dims = [dims] assert (len(dims) > 0) dyn_dims = [d for d in dims if d.need_masking()] assert (len(dyn_dims) == 1) retu...
def pack_padded(source: Tensor, *, dims: Sequence[Dim], enforce_sorted: bool=False, out_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim)]: '\n Like pack_padded_sequence. Usually the sequences are padded when they have different lengths.\n Packing means to only store the non-padded frames.\n This uses :fun...
def gather(source: Tensor, *, indices: Union[(Tensor, int)], axis: Optional[Dim]=None, clip_to_valid: bool=False) -> Tensor: '\n Gathers slices on a specified axis from the source using indices.\n If the source is of the shape ``[B,D,F1]``, and indices of shape ``[B,F2]``,\n this will yield output of the...
def scatter(source: Tensor, *, indices: Tensor, indices_dim: Union[(Dim, Sequence[Dim])], out_dim: Optional[Union[(Dim, Sequence[Dim])]]=None) -> Tensor: '\n Scatters into new zero-tensor.\n If entries in indices are duplicated, the corresponding values in source will be added together\n (scatter_add in ...
def slice(source: Tensor, *, axis: Dim, start: Optional[Union[(int, Tensor)]]=None, end: Optional[Union[(int, Tensor)]]=None, step: Optional[Union[(int, Tensor)]]=None, size: Optional[Union[(int, Tensor, Dim)]]=None, out_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim)]: '\n Slicing on the input, i.e. ``x[start...
def shift_right(source: Tensor, *, axis: Dim, pad_value: Union[(rf.RawTensorTypes, Tensor)], amount: int=1) -> Tensor: 'shift right by amount, pad left with left_pad' (padded, (padded_dim,)) = rf.pad(source, axes=[axis], padding=[(amount, 0)], mode='constant', value=pad_value) (padded_slice, _) = rf.slice...
def reverse_sequence(tensor: Tensor, *, axis: Dim) -> Tensor: '\n Similar as tf.reverse_sequence, or Torch flip (but taking seq lengths into account).\n\n :param tensor:\n :param axis:\n :return: reversed tensor, same dims\n ' indices = (rf.combine_bc(axis.get_size_tensor(), '-', rf.range_over_...
def where(cond: Union[(Tensor, rf.RawTensorTypes)], true_: Union[(Tensor, rf.RawTensorTypes)], false_: Union[(Tensor, rf.RawTensorTypes)], *, allow_broadcast_all_sources: bool=False) -> Tensor: '\n Wraps tf.where, which is SwitchLayer in RETURNN.\n\n :return: true_ if cond else false_, elemwise.\n ' ...
def sparse_to_dense(labels: Union[(Tensor, rf.RawTensorTypes)], *, label_value: Union[(Tensor, rf.RawTensorTypes)], other_value: Union[(Tensor, rf.RawTensorTypes)], axis: Optional[Dim]=None) -> Tensor: '\n Converts a sparse tensor to a dense one.\n\n This is a more generic variant of "one_hot".\n\n Note ...
def one_hot(source: Tensor) -> Tensor: '\n one_hot. special case of :func:`sparse_to_dense`.\n\n Note that usually this is not needed as most other functions should handle sparse tensors just fine\n and much more efficiently than they would be with dense tensors.\n ' return sparse_to_dense(source,...
def dot_attention(query: Tensor, keys: Tensor, values: Tensor, *, key_dim: Dim, axis: Dim, att_dropout: float=0.0, att_dropout_broadcast: Optional[bool]=None) -> Tensor: '\n Calculates attention over the given axis, for given key dim.\n Any other unrelated axes do not matter here.\n This can be used for ...
class SelfAttentionBase(rf.Module): '\n Shared base class for (non-causal) self attention (:class:`SelfAttention`)\n and causal self attention (:class:`CausalSelfAttention`).\n\n It uses :func:`dot_attention` for multi-headed dot-attention.\n ' def __init__(self, in_dim: Dim, proj_dim: Optional[D...
class SelfAttention(SelfAttentionBase): '\n Classic self attention on sequence level\n ' def __call__(self, source: Tensor, *, axis: Dim) -> Tensor: 'forward' (q, k, v) = self.forward_qkv(source) kv_axis = Dim(None, name=f'{axis.name}-kv') (k, _) = rf.replace_dim(k, in_d...
class CausalSelfAttention(SelfAttentionBase): '\n Classic causal self attention\n ' def __call__(self, source: Tensor, axis: Dim, *, state: Optional[CausalSelfAttentionState]=None) -> Tuple[(Tensor, CausalSelfAttentionState)]: 'forward' (q, k, v) = self.forward_qkv(source) (k, v...
def _causal_self_att_step(k: Tensor, v: Tensor, *, axis: Dim, state: Optional[CausalSelfAttentionState], self: rf.Module) -> Tuple[(Tensor, Tensor, Dim, CausalSelfAttentionState)]: if (axis == single_step_dim): assert state, f'{self}: need state for single step' (k, hist_dim) = rf.cum_concat_step(...
class CausalSelfAttentionState(rf.State): '\n State for :class:`StepwiseCausalSelfAttention`.\n ' def __init__(self, *_args, k_accum: Tensor=None, v_accum: Tensor=None, accum_axis: Dim=None): '\n :param k_accum: accumulated keys\n :param v_accum: accumulated values\n :param...
class RelPosSelfAttention(SelfAttentionBase): '\n Self-attention with relative positional encoding.\n This covers both Shawn et al. self-att rel pos 2018 (https://arxiv.org/abs/1803.02155),\n and Dai et al. Transformer-XL style 2019 (https://arxiv.org/abs/1901.02860).\n\n It uses :func:`relative_posit...
def _rel_pos_enc_shift(x: Tensor, axis: Dim, pos_emb_spatial_dim: Dim, hist_dim: Dim) -> Tensor: "\n :param x: [B,H,T,T*2-1]\n :param axis: T\n :param pos_emb_spatial_dim: T*2-1\n :param hist_dim: T' (equal to T but separate dim)\n :return: [B,H,T,T']\n " batch_dims = x.remaining_dims((axis,...
class RelPosCausalSelfAttention(CausalSelfAttention): '\n Self-attention with relative positional encoding.\n This covers both Shawn et al. self-att rel pos 2018 (https://arxiv.org/abs/1803.02155),\n and Dai et al. Transformer-XL style 2019 (https://arxiv.org/abs/1901.02860).\n\n It uses :func:`relati...
class CrossAttention(rf.Module): '\n Cross attention\n\n It uses :func:`dot_attention` for multi-headed dot-attention.\n ' def __init__(self, encoder_dim: Dim, query_in_dim: Dim, proj_dim: Optional[Dim], *, key_dim_total: Dim, value_dim_total: Dim, num_heads: Union[(int, Dim)], with_bias: bool=True,...
class LearnedRelativePositionalEncoding(rf.Module): '\n Learnable relative positional encoding.\n\n E.g. as used in Shawn et al, 2018 (https://arxiv.org/abs/1803.02155).\n\n https://github.com/rwth-i6/returnn_common/wiki/Relative-positional-encoding\n ' def __init__(self, feat_dim: Dim, *, clippi...
def _make_indices(query_spatial_dim: Dim, key_value_spatial_dim: Dim, query_offset: Optional[Union[(int, Tensor)]]=None) -> Tuple[(Tensor, Dim)]: kv_pos_vec = rf.range_over_dim(key_value_spatial_dim) if (query_spatial_dim == single_step_dim): indices = kv_pos_vec out_spatial_dim = key_value_sp...
def relative_positional_encoding(*, query_spatial_dim: Dim, key_value_spatial_dim: Dim, feat_dim: Dim, query_offset: int=0, dtype: Optional[str]=None) -> Tuple[(Tensor, Dim)]: '\n Implements relative positional encoding, Transformer-XL style (https://arxiv.org/abs/1901.02860),\n as used for example by :clas...
def sinusoidal_positional_encoding(*, spatial_dim: Dim, feat_dim: Dim, offset: Optional[Union[(int, Tensor)]]=None, dtype: Optional[str]=None, device: Optional[str]=None) -> Tensor: '\n Implements absolute sinusoidal positional encoding.\n\n Code adopted from :func:`relative_positional_encoding`\n and ou...
def _att_dropout_broadcast_default() -> bool: from returnn.config import get_global_config from returnn.util.basic import BehaviorVersion config = get_global_config(raise_exception=False) if config: opt = config.bool('rf_att_dropout_broadcast', None) if (opt is not None): r...
def mel_filterbank(x: Tensor, *, in_dim: Dim, out_dim: Dim, sampling_rate: Union[(int, float)], fft_length: Optional[int]=None, f_min: Optional[Union[(int, float)]]=None, f_max: Optional[Union[(int, float)]]=None): '\n Applies the Mel filterbank to the input.\n\n :param x:\n :param in_dim: expected to be...
@functools.lru_cache() def _mel_filter_bank_matrix_np(*, f_min: Union[(int, float)], f_max: Union[(int, float)], sampling_rate: Union[(int, float)], fft_size: int, nr_of_filters: int) -> numpy.ndarray: '\n Returns the filter matrix which yields the mel filter bank features, when applied to the spectrum as\n ...
def log_mel_filterbank_from_raw(raw_audio: Tensor, *, in_spatial_dim: Dim, out_dim: Dim, sampling_rate: int=16000, window_len: float=0.025, step_len: float=0.01, n_fft: Optional[int]=None, log_base: Union[(int, float)]=10) -> Tuple[(Tensor, Dim)]: '\n log mel filterbank features\n\n :param raw_audio: (..., ...
def specaugment(x: Tensor, *, spatial_dim: Dim, feature_dim: Optional[Dim]=None, global_train_step_dependent: bool=True, only_on_train: bool=True, max_consecutive_spatial_dims: int=20, max_consecutive_feature_dims: Optional[int]=None, num_spatial_mask_factor: int=100, steps: Tuple[(int, int, int)]=(0, 1000, 2000)) ->...
def random_mask(x: Tensor, *, mask_axis: Dim, broadcast_axis: Union[(Dim, Collection[Dim])], min_num: Union[(int, Tensor)], max_num: Union[(int, Tensor)], max_dims: Union[(int, Tensor)], mask_value: Union[(int, float, Tensor)]=0.0) -> Tensor: '\n :param x: (batch,time,feature)\n :param mask_axis: axis to ma...
def mask(x: Tensor, *, mask_axis: Dim, pos: Tensor, max_amount: Union[(int, Tensor)], mask_value: Union[(int, float, Tensor)]=0.0) -> Tensor: '\n :param x: (batch,time,[feature]). any dim not mask_axis or in pos.shape will be broadcasted over\n :param mask_axis:\n :param pos: (batch,) (or multiple batch ...
def is_backend_raw_tensor_dim_tag_independent() -> bool: '\n :return: whether raw tensors of the backend are independent of :class:`Dim`\n (Usually yes, e.g. :class:`tf.Tensor` or :class:`torch.Tensor`,\n but the TF-layers backend is an exception.)\n ' return _backend.global_backend.is_bac...
def cond(pred: Union[(bool, Tensor)], true_fn: Callable[([], T)], false_fn: Callable[([], T)]) -> T: '\n :param pred:\n :param true_fn:\n :param false_fn:\n :return: true_fn() if pred else false_fn()\n ' if isinstance(pred, bool): if pred: return true_fn() else: ...
def full(*, dims: Sequence[Dim], fill_value: Union[(RawTensorTypes, Tensor)], dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None) -> Tensor: '\n full, fill, constant.\n\n https://data-apis.org/array-api/latest/API_specification/generated/ar...
def constant(fill_value: RawTensorTypes, *, dims: Sequence[Dim], dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None) -> Tensor: 'alias to :func:`full`, mapping `value` to `fill_value`. also see :func:`convert_to_tensor`' return full(dims=dims...
def zeros(dims: Sequence[Dim], *, dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None) -> Tensor: '\n zeros. float by default.\n ' return full(dims=dims, fill_value=0, dtype=(dtype or rf.get_default_float_dtype()), device=device, sparse_...
def ones(dims: Sequence[Dim], *, dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None) -> Tensor: '\n ones. float by default.\n ' return full(dims=dims, fill_value=1, dtype=(dtype or rf.get_default_float_dtype()), device=device, sparse_di...
def zeros_like(other: Tensor) -> Tensor: 'zeros like other' return zeros(dims=other.dims, dtype=other.dtype, device=other.device, sparse_dim=other.sparse_dim, feature_dim=other.feature_dim)
def ones_like(other: Tensor) -> Tensor: 'ones like other' return ones(dims=other.dims, dtype=other.dtype, device=other.device, sparse_dim=other.sparse_dim, feature_dim=other.feature_dim)
class ModuleList(rf.Module, Generic[__ModT]): '\n Module list, getting passed an Iterable of Modules and creates a list of Modules in that order\n ' def __init__(self, *modules: Union[(__ModT, Iterable[__ModT], Dict[(str, __ModT)], ModuleList)]): super().__init__() if ((len(modules) == ...