code
stringlengths
17
6.64M
def mod(a: Tensor, b: Tensor) -> Tensor: 'mod' return combine(a, 'mod', b)
def pow(a: Tensor, b: Tensor) -> Tensor: 'pow' return combine(a, 'pow', b)
def squared_difference(a: Tensor, b: Tensor) -> Tensor: 'squared_difference' return combine(a, 'squared_difference', b)
def logical_and(a: Tensor, b: Tensor) -> Tensor: 'logical_and' return combine(a, 'logical_and', b)
def logical_or(a: Tensor, b: Tensor) -> Tensor: 'logical_or' return combine(a, 'logical_or', b)
def logical_not(a: Tensor) -> Tensor: 'logical_not' return a._raw_backend.activation(a, 'logical_not')
@overload def opt_logical_or(a: bool, b: bool) -> bool: 'logical or'
def maximum(a: Tensor, b: Union[(Tensor, _RawTensorTypes)], *other_tensors) -> Tensor: 'maximum' if (not other_tensors): return combine(a, 'maximum', b) res = combine(a, 'maximum', b) for t in other_tensors: res = combine(res, 'maximum', t) return res
def minimum(a: Tensor, b: Union[(Tensor, _RawTensorTypes)], *other_tensors) -> Tensor: 'minimum' if (not other_tensors): return combine(a, 'minimum', b) res = combine(a, 'minimum', b) for t in other_tensors: res = combine(res, 'minimum', t) return res
def clip_by_value(x: Tensor, clip_value_min: Union[(Tensor, _RawTensorTypes)], clip_value_max: Union[(Tensor, _RawTensorTypes)], *, allow_broadcast_all_sources: bool=False) -> Tensor: 'clip by value' return x._raw_backend.clip_by_value(x, clip_value_min, clip_value_max, allow_broadcast_all_sources=allow_broad...
def identity(x: Tensor) -> Tensor: '\n Identity function. Just to have one canonical. Does nothing, returns the input.\n ' return x
def exp(a: Tensor) -> Tensor: 'exp' return a._raw_backend.activation(a, 'exp')
def expm1(a: Tensor) -> Tensor: 'expm1' return a._raw_backend.activation(a, 'expm1')
def log(a: Tensor) -> Tensor: 'log' return a._raw_backend.activation(a, 'log')
def safe_log(a: Tensor, *, eps: Optional[float]=None) -> Tensor: 'safe_log' if (eps is None): eps = {'float16': 6e-08, 'bfloat16': 9.1835e-41, 'float32': 1.4013e-45, 'float64': 5e-324}[a.dtype] return a._raw_backend.safe_log(a, eps=eps)
def log1p(a: Tensor) -> Tensor: 'log1p' return a._raw_backend.activation(a, 'log1p')
def sqrt(a: Tensor) -> Tensor: 'sqrt' return a._raw_backend.activation(a, 'sqrt')
def rsqrt(a: Tensor) -> Tensor: 'rsqrt' return a._raw_backend.activation(a, 'rsqrt')
def square(a: Tensor) -> Tensor: 'square' return a._raw_backend.activation(a, 'square')
def abs(a: Tensor) -> Tensor: 'abs' return a._raw_backend.activation(a, 'abs')
def tanh(a: Tensor) -> Tensor: 'tanh' return a._raw_backend.activation(a, 'tanh')
def sigmoid(a: Tensor) -> Tensor: 'sigmoid' return a._raw_backend.activation(a, 'sigmoid')
def log_sigmoid(a: Tensor) -> Tensor: 'log_sigmoid' return a._raw_backend.activation(a, 'log_sigmoid')
def sin(a: Tensor) -> Tensor: 'sin' return a._raw_backend.activation(a, 'sin')
def cos(a: Tensor) -> Tensor: 'cos' return a._raw_backend.activation(a, 'cos')
def ceil(a: Tensor) -> Tensor: 'ceil' return a._raw_backend.activation(a, 'ceil')
def floor(a: Tensor) -> Tensor: 'floor' return a._raw_backend.activation(a, 'floor')
def round(a: Tensor) -> Tensor: 'round' return a._raw_backend.activation(a, 'round')
def relu(a: Tensor) -> Tensor: 'relu' return a._raw_backend.activation(a, 'relu')
def elu(a: Tensor) -> Tensor: 'elu' return a._raw_backend.activation(a, 'elu')
def selu(a: Tensor) -> Tensor: 'selu' return a._raw_backend.activation(a, 'selu')
def silu(a: Tensor) -> Tensor: 'silu / swish.\n\n The SiLU activation function was introduced in "Gaussian Error Linear Units\n (GELUs)" [Hendrycks et al. 2016](https://arxiv.org/abs/1606.08415) and\n "Sigmoid-Weighted Linear Units for Neural Network Function Approximation in\n Reinforcement Learning"...
def softmax(a: Tensor, *, axis: Dim, use_mask: bool=True) -> Tensor: 'softmax' return a._raw_backend.softmax(a, axis=axis, use_mask=use_mask)
def log_softmax(a: Tensor, *, axis: Dim, use_mask: bool=True) -> Tensor: 'log_softmax' return a._raw_backend.log_softmax(a, axis=axis, use_mask=use_mask)
def gating(x: Tensor, *, axis: Optional[Dim]=None, gate_func=sigmoid, act_func=identity, out_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim)]: '\n Like in gated linear unit (GLU): https://arxiv.org/abs/1612.08083\n GLU refers also to the linear transformation before the gating -- this is why this function i...
def matmul(a: Tensor[T], b: Tensor[T], *, reduce: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: "\n This performs a batched matmul of two sources a and b\n (non-batched matmul and dot product are special cases).\n The underlying operation is a batched matmul (shared..., I, J) * (shared....
class Module(): '\n This can represent a subnetwork in RETURNN.\n\n You can write PyTorch-like code here, like::\n\n class MyModule(rf.Module):\n\n def __init__(self, dim: Dim, activation=tanh):\n super().__init__()\n self.layer_norm = rf.LayerNorm(dim)\n sel...
class Functional(Module): '\n Used for functions (pure functional, i.e. not methods of another module)\n and via :class:`ModuleList` to wrap up any functions or lambdas as modules.\n\n (This is often not necessary, but sometimes useful.)\n ' def __init__(self, func): super().__init__() ...
def moments(x: Tensor, axis: Union[(Dim, Sequence[Dim])]) -> Tuple[(Tensor, Tensor)]: '\n :param x: input\n :param axis: the axis to be reduced, to calculate statistics over\n :return: mean, variance. it has the same shape as the input with the axis removed\n ' mean = rf.reduce_mean(x, axis=axis) ...
class LayerNorm(rf.Module): '\n `Layer normalization <https://arxiv.org/abs/1607.06450>`__.\n\n Note that we *just* normalize over the feature-dim axis here.\n This is consistent to the default behavior of :class:`tf.keras.layers.LayerNormalization`\n and also how it is commonly used in many models, i...
class BatchNorm(rf.Module): '\n Batch normalization. https://arxiv.org/abs/1502.03167\n\n Note that the default arguments differ from corresponding batch norm in RETURNN.\n See here for discussion on defaults: https://github.com/rwth-i6/returnn/issues/522\n\n We calculate statistics over all axes exce...
def normalize(a: Tensor, *, axis: Union[(Dim, Sequence[Dim])], epsilon: float=1e-06) -> Tensor: '\n Mean- and variance-normalize some input in the given input dimension(s),\n such that the resulting tensor has mean 0 and variance 1.\n\n If you want that this can be shifted and scaled again,\n you need...
class Normalize(rf.Module): '\n :func:`normalize` with additional scale and bias\n ' def __init__(self, *, param_dims: Union[(Dim, Sequence[Dim])], epsilon: float=1e-06, scale: bool=True, bias: bool=True): '\n :param param_dims: shape of the scale and bias parameters\n :param epsi...
class Parameter(Tensor[T]): '\n This represents a (potential trainable) parameter,\n aka ``tf.Variable`` in TensorFlow,\n wrapping to ``VariableLayer`` in RETURNN.\n ' def __init__(self, dims: Sequence[Dim], dtype: Optional[str]=None, *, sparse_dim: Optional[Dim]=None, trainable: Optional[bool]=N...
def set_random_seed(seed: int): '\n Call this at the beginning of the program\n (after the RF backend was selected),\n or when the model and computation graph is supposed to be reinitialized.\n\n This initializes the random state of the backend and also the step-based random state.\n\n This is *not...
def get_random_state() -> Dict[(str, bytes)]: '\n :return: current random state, for serialization, to be able to restore it later\n ' return _global_backend.get_random_state()
def set_random_state(state: Dict[(str, bytes)]): '\n Recovers the random state.\n\n There are many potential cases where we cannot recover the state\n (e.g. different backend version, different hardware, ...),\n In this case, a run without interruption is not the same as a run with interruption.\n\n ...
def reset_step_random_state(): '\n When ``static=True`` is used in :func:`random`,\n the random state is reset to the beginning of the step.\n So this should be called in the beginning of each step.\n Also see the module docstring.\n ' _step_rnd.seed(_step_rnd_seed)
def get_static_step_based_seed(*, size=None) -> Union[(int, numpy.ndarray)]: '\n :return: from the static step-based random state, get a seed\n ' return _step_rnd.randint((2 ** 31), size=size)
def random(dims: Sequence[Dim], *, dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None, distribution: str, mean: Optional[Union[(int, float, Tensor)]]=None, stddev: Optional[Union[(int, float, Tensor)]]=None, bound: Optional[Union[(int, float, Tensor)...
def random_uniform(dims: Sequence[Dim], *, dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None, minval: Union[(int, float, Tensor)]=0, maxval: Union[(int, float, Tensor)]=1, seed: Optional[Union[(int, Sequence[int], numpy.ndarray)]]=None, algorithm: O...
def random_normal(dims: Sequence[Dim], *, dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None, mean: Optional[Union[(int, float, Tensor)]]=0.0, stddev: Optional[Union[(int, float, Tensor)]]=1.0, seed: Optional[Union[(int, Sequence[int], numpy.ndarray)...
def random_truncated_normal(dims: Sequence[Dim], *, dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None, mean: Optional[Union[(int, float, Tensor)]]=0.0, stddev: Optional[Union[(int, float, Tensor)]]=1.0, minval: Union[(int, float, Tensor)]=None, maxv...
class LSTM(rf.Module): '\n LSTM module.\n ' def __init__(self, in_dim: Dim, out_dim: Dim, *, with_bias: bool=True): '\n Code to initialize the LSTM module.\n ' super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.ff_weight = rf.Parame...
class LstmState(rf.State): 'LSTM state' def __init__(self, *_args, h: Tensor=None, c: Tensor=None): super().__init__(*_args) if (not _args): self.h = h self.c = c
class ZoneoutLSTM(LSTM): '\n Zoneout LSTM module.\n ' def __init__(self, in_dim: Dim, out_dim: Dim, *, with_bias: bool=True, zoneout_factor_cell: float=0.0, zoneout_factor_output: float=0.0, use_zoneout_output: bool=True, forget_bias: float=0.0, parts_order: str='ifco'): '\n :param in_di...
def _zoneout(*, prev: Tensor, cur: Tensor, factor: float, out_dim: Dim, dropout_broadcast: bool) -> Tensor: if (factor == 0.0): return cur return rf.cond(rf.get_run_ctx().train_flag, (lambda : (((1 - factor) * rf.dropout((cur - prev), factor, axis=(dropout_broadcast and out_dim))) + prev)), (lambda : ...
def reduce(source: Tensor[T], *, mode: str, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param mode: "sum", "max", "min", "mean", "logsumexp", "any", "all", "argmin", "argmax"\n :param axis:\n :param use_mask:...
def reduce_sum(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return: tenso...
def reduce_max(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return: tenso...
def reduce_min(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return: tenso...
def reduce_mean(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return: tens...
def reduce_logsumexp(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return:...
def reduce_any(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return: tenso...
def reduce_all(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return: tenso...
def reduce_argmin(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return: te...
def reduce_argmax(source: Tensor[T], *, axis: Union[(Dim, Sequence[Dim])], use_mask: bool=True) -> Tensor[T]: '\n Reduce the tensor along the given axis\n\n :param source:\n :param axis:\n :param use_mask: if True (default), use the time mask (part of dim tag) to ignore padding frames\n :return: te...
def reduce_out(source: Tensor, *, mode: str, num_pieces: int, out_dim: Optional[Dim]=None) -> Tensor: '\n Combination of :class:`SplitDimsLayer` applied to the feature dim\n and :class:`ReduceLayer` applied to the resulting feature dim.\n This can e.g. be used to do maxout.\n\n :param source:\n :pa...
def top_k(source: Tensor, *, axis: Union[(Dim, Sequence[Dim])], k: Optional[Union[(int, Tensor)]]=None, k_dim: Optional[Dim]=None, sorted: bool=True) -> Tuple[(Tensor, Union[(Tensor, Sequence[Tensor])], Dim)]: '\n Basically wraps tf.nn.top_k.\n Returns the top_k values and the indices.\n\n For an input [...
def reset_run_ctx(): '\n Call this after a train_step or forward_step function has been called,\n when you write your own training or forward loop.\n ' global _run_ctx _run_ctx = None
def init_train_step_run_ctx(*, train_flag: Union[(bool, Tensor)]=True, step: Union[(int, Tensor)]=0, epoch: Union[(int, Tensor)]=1): '\n Call this before the train_step function is called,\n when you write your own training loop.\n\n Also see :func:`init_forward_step_run_ctx`.\n\n :param train_flag: w...
def init_forward_step_run_ctx(*, expected_outputs: Optional[TensorDict]=None, step: Union[(int, Tensor)]=0, epoch: Union[(int, Tensor)]=1): '\n Call this before the forward_step function is called,\n when you write your own forward loop.\n\n Also see :func:`init_train_step_run_ctx`.\n ' global _ru...
def get_run_ctx() -> RunCtx: '\n :return: current run context, see :class:`RunCtx`\n ' global _run_ctx, _init_run_ctx if (_run_ctx is None): if (_init_run_ctx is None): _init_run_ctx = RunCtx(stage='init') return _init_run_ctx return _run_ctx
class RunCtx(): '\n We can either be in param-init stage,\n or in the main training (or eval) loop,\n or forwarding loop (doing recog, beam search, dumping whatever, ...).\n\n In training/eval, we expect that some loss is being defined via mark_as_loss().\n In forwarding, we expect that some output...
@dataclass class Loss(): '\n Loss via :func:`RunCtx.mark_as_loss`.\n\n We collect all relevant information here.\n ' loss: Tensor name: str scale: float = 1.0 as_error: bool = False use_normalized_loss: bool = False use_flatten_frames: bool = True custom_inv_norm_factor: Optio...
def _default_dim_order(tensor: Tensor) -> Sequence[Dim]: '\n See if some reasonable default dim order like BTF or BF is possible.\n\n :param tensor:\n :return:\n ' rem_dims = list(tensor.dims) dims = [] if tensor.have_batch_axis(): rem_dims.remove(tensor.get_batch_dim_tag()) ...
def _output_tensor_from_raw(raw_tensor, *, dims: Optional[Sequence[Dim]], name: str) -> Tensor: assert isinstance(raw_tensor, _backend.global_backend.RawTensorType) tensor = rf.convert_to_tensor(raw_tensor, dims=dims) for (axis, dim) in enumerate(tensor.dims): if (dim.dyn_size_ext and (dim.dyn_siz...
def stft(x: Tensor, *, in_spatial_dim: Dim, frame_step: int, frame_length: int, fft_length: Optional[int]=None, window_use_frame_length: bool=True, align_window_left: bool=True, window_enforce_even: bool=True, out_spatial_dim: Optional[Dim]=None, out_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim, Dim)]: '\n C...
class State(dict): '\n Covers all the state of a recurrent module,\n i.e. exactly what needs to be stored and passed into the module\n next time you call it as initial state.\n\n This behaves somewhat like a namedtuple, although we derive from dict.\n\n When you derive further from this class, make...
class TensorArray(): '\n TensorArray.\n Think of this like a list of tensors.\n E.g. if each tensor has shape (B, D), and we have N tensors,\n stacking them together would give us a tensor of shape (N, B, D).\n Reversely, unstacking a tensor of shape (N, B, D) on the N axis\n would give us a lis...
class GetModelFunc(Protocol): 'get model func' def __call__(self, *, epoch: int, step: int) -> rf.Module: ...
class StepFunc(Protocol): 'step func' def __call__(self, *, model: rf.Module, extern_data: TensorDict) -> None: ...
def get_raw_tensor_type() -> Type: '\n :return: the raw tensor type of the current selected backend, e.g. ``torch.Tensor`` or ``tf.Tensor``\n ' if TYPE_CHECKING: import torch return torch.Tensor from ._backend import global_backend return global_backend.RawTensorType
class InvalidVersion(Exception): '\n The version string is invalid.\n '
class MissingExplicitImport(ImportError): '\n Corresponding `import_` call missing.\n '
def package_path(): '\n :return: directory where packages are stored (default: ~/returnn/pkg)\n :rtype: str\n ' global _pkg_path if _pkg_path: return _pkg_path if (_EnvPkgPath in os.environ): path = os.environ[_EnvPkgPath] assert os.path.isdir(path), ('import pkg path ...
def _package_import_path(): '\n :return: directory for package import\n :rtype: str\n ' global _pkg_import_path if _pkg_import_path: return _pkg_import_path _pkg_import_path = os.environ.get(_EnvPkgImportPath, _DefaultPkgImportPath) _setup_pkg_import() return _pkg_import_path
def _package_import_pkg_path(): '\n :return: directory for package import\n :rtype: str\n ' assert ModuleNamePrefix.endswith('.') path = ('%s/%s' % (_package_import_path(), ModuleNamePrefix[:(- 1)])) return path
def _setup_pkg_import(): os.makedirs(_package_import_path(), exist_ok=True) _mk_py_pkg_dirs(_package_import_pkg_path()) if (_package_import_path() not in sys.path): sys.path.insert(0, _package_import_path())
def _mk_py_pkg_dirs(start_path, end_path=None): '\n :param str start_path:\n :param str|None end_path:\n ' if end_path: if (len(end_path) > len(start_path)): assert end_path.startswith((start_path + '/')) else: assert (start_path == end_path) else: ...
def setup_py_pkg(mod_globals): '\n This will get called to prepare any custom setup for the package.\n\n :param dict[str] mod_globals: globals() in the package\n ' mod_name = mod_globals['__name__'] logger.debug('import_ pkg mod %s %s', mod_name, mod_globals.get('__file__')) if (mod_name not ...
def _normalize_pkg_name(name): '\n :param str name:\n :rtype: str\n ' name = name.replace('.', '_') name = name.replace('-', '_') return name
def _register_module(mod_name, info): '\n :param str mod_name:\n :param object info: just used for reporting\n ' assert mod_name.startswith(ModuleNamePrefix) _registered_modules[mod_name] = info p = (- 1) while True: p = mod_name.find('.', (p + 1)) if (p < 0): ...
def module_name(repo, repo_path, path, version, make_ready=True): '\n :param str repo: e.g. "github.com/rwth-i6/returnn-experiments"\n :param str repo_path: what get_repo_path returns, e.g. "/home/az/returnn/pkg/...@v..."\n :param str path: path to file in repo. can be arbitrary (empty) with make_ready=F...
def _find_root_python_package(full_path): '\n :param str full_path: some Python file\n :return: going up from path, and first dir which does not include __init__.py\n :rtype: str\n ' p = len(full_path) while True: p = full_path.rfind('/', 0, p) assert (p > 0) d = full_p...
def stat_repo(repo, version): '\n :param str repo: e.g. "github.com/rwth-i6/returnn-experiments"\n :param str|None version: e.g. "20211231-0123abcd0123"\n ' repo_ = _get_repo(repo) repo_.get_work_dir(version)
def get_repo_path(repo, version, _report_dev_version_usage_stack_frame_depth=1): '\n :param str repo: e.g. "github.com/rwth-i6/returnn-experiments"\n :param str|None version: e.g. "20211231-0123abcd0123"\n :param int _report_dev_version_usage_stack_frame_depth:\n :return: path to repo\n :rtype: str...
def _simple_validate_repo_name(repo): '\n :param str repo:\n ' assert (('..' not in repo) and (':' not in repo))
def _main_repo_path(repo): '\n :param str repo:\n :return: main repo dir (which includes the Git objects)\n :rtype: str\n ' return ('%s/%s' % (common.package_path(), repo))
def _dev_repo_path(repo): '\n :param str repo:\n :return: dev working tree of a repo. currently the same as the main repo path\n :rtype: str\n ' return _main_repo_path(repo)