code
stringlengths
17
6.64M
def _repo_path(repo, version): '\n :param str repo:\n :param str|None version:\n :rtype: str\n ' if (not version): return _dev_repo_path(repo) return ('%s@v%s' % (_main_repo_path(repo), version))
def _repo_remote_url(repo): '\n :param str repo:\n :rtype: str\n ' p = repo.find('/') assert (p >= 0) (host, path) = (repo[:p], repo[p:]) return ('https://%s:%s' % (host, path))
def _simple_validate_commit_rev(rev): '\n :param str rev:\n ' assert ((len(rev) >= _MinNumHashDigits) and _RevDigitsRe.match(rev))
def _simple_validate_date(date): '\n :param str date:\n ' assert ((len(date) in _DateFormatAllowedLens) and _DateRe.match(date))
def _simple_validate_version(version): '\n :param str|None version:\n ' if (not version): return (date, rev) = version.split('-') _simple_validate_date(date) _simple_validate_commit_rev(rev)
def _rev_from_version(version): '\n :param str version: e.g. "20211231-0123abcd0123"\n :return: e.g. "0123abcd0123"\n :rtype: str\n ' p = version.rfind('-') if (p < 0): _simple_validate_commit_rev(version) return version rev = version[(p + 1):] _simple_validate_commit_r...
def _version_from_date_and_rev(date, rev): '\n :param str date:\n :param str rev:\n ' _simple_validate_commit_rev(rev) return ('%s-%s' % (date, rev))
def _sys_git_clone_repo(repo): '\n :param str repo:\n ' url = _repo_remote_url(repo) main_path = _main_repo_path(repo) common.logger.info('Git clone %s', repo) check_call(['git', 'clone', url, main_path])
def _sys_git_fetch(repo): '\n :param str repo:\n ' main_path = _main_repo_path(repo) common.logger.info('Git fetch %s', repo) check_call(['git', 'fetch'], cwd=main_path)
def _sys_git_create_repo_workdir(repo, version): '\n :param str repo:\n :param str version:\n ' main_path = _main_repo_path(repo) rev = _rev_from_version(version) version_path = _repo_path(repo, version) common.logger.info('Git add worktree %s: %s', repo, version) check_call(['git', '...
def _sys_git_stat_local_rev(repo, rev): '\n :param str repo:\n :param str rev:\n :return: (full_rev, date)\n :rtype: (str|None, str|None)\n ' main_path = _main_repo_path(repo) try: out = check_output(['git', '-c', 'log.showsignature=false', 'log', '-n1', '--format=format:%H %cd', ('...
class _Repo(): def __init__(self, name): '\n :param str name: e.g. "github.com/rwth-i6/returnn-experiments"\n ' _simple_validate_repo_name(name) self.name = name self._cloned = False self._loaded_local_work_dirs = False self._dev_work_dir = None ...
class _RepoWorkDir(): def __init__(self, repo, version): '\n :param str|_Repo repo:\n :param str|None version: (normalized)\n ' if (not isinstance(repo, _Repo)): repo = _get_repo(repo) _simple_validate_version(version) self.repo = repo self...
def _get_repo(repo): '\n :param str repo:\n :rtype: _Repo\n ' assert isinstance(repo, str) obj = _repo_cache.get(repo) if obj: return obj obj = _Repo(repo) _repo_cache[repo] = obj return obj
def _report_usage_dev_version(repo_path, stack_frame_depth): '\n :param str repo_path:\n :param int stack_frame_depth:\n ' common.logger.warn('Access to development working tree: %s', repo_path) from returnn.util.basic import try_get_stack_frame frame = try_get_stack_frame(depth=(stack_frame_...
def import_(repo, path, version=None): '\n :param str repo: e.g. "github.com/rwth-i6/returnn-experiments"\n :param str path: path inside the repo, without starting "/"\n :param str|None version: e.g. "20211231-0123abcd0123". None for development working copy\n :rtype: object|types.ModuleType\n ' ...
class LearningRateControl(object): '\n Base class for learning rate control / scheduling.\n ' need_error_info = True class EpochData(): '\n Encapsulates all relevant information for one epoch,\n needed to perform learning rate scheduling,\n such as the individual scores...
class ConstantLearningRate(LearningRateControl): '\n Just a constant learning rate.\n ' need_error_info = False def calc_learning_rate_for_epoch(self, epoch): '\n Dummy constant learning rate. Returns initial learning rate.\n :type epoch: int\n :returns learning rate\n ...
class NewbobRelative(LearningRateControl): '\n If relative diff between old and new error is over some threshold, decay learning rate.\n ' @classmethod def load_initial_kwargs_from_config(cls, config): '\n :type config: returnn.config.Config\n :rtype: dict[str]\n ' ...
class NewbobAbs(LearningRateControl): '\n If absolute diff between old and new error is over some threshold, decay learning rate.\n ' @classmethod def load_initial_kwargs_from_config(cls, config): '\n :type config: returnn.config.Config\n :rtype: dict[str]\n ' k...
class NewbobMultiEpoch(LearningRateControl): '\n Like :class:`NewbobRelative`, but looks at the average relative error over multiple epochs.\n This is useful together with ``partition_epoch`` from :class:`Dataset`.\n ' @classmethod def load_initial_kwargs_from_config(cls, config): '\n ...
def learning_rate_control_type(type_name): '\n :param str type_name:\n :rtype: type[LearningRateControl]|LearningRateControl\n ' if (type_name == 'constant'): return ConstantLearningRate elif (type_name in ('newbob', 'newbob_rel', 'newbob_relative')): return NewbobRelative eli...
def load_learning_rate_control_from_config(config): '\n :type config: returnn.config.Config\n :rtype: LearningRateControl\n ' control_type = config.value('learning_rate_control', 'constant') cls = learning_rate_control_type(control_type) return cls.load_initial_from_config(config)
def demo(): '\n Demo run. Given some learning rate file (with scores / existing lrs), will calculate how lrs would have been set,\n given some config.\n ' from returnn.util import better_exchook better_exchook.install() import returnn.__main__ as rnn import sys if (len(sys.argv) <= 1)...
class Stream(): '\n Simple stream wrapper, which provides :func:`write` and :func:`flush`.\n ' def __init__(self, log, lvl): '\n :type log: logging.Logger\n :type lvl: int\n ' self.buf = io.StringIO() self.log = log self.lvl = lvl self.lock =...
class Log(): '\n The main logging class.\n ' def __init__(self): self.initialized = False self.filename = None self.v = None self.verbose = None self.v1 = None self.v2 = None self.v3 = None self.v4 = None self.v5 = None sel...
class StdoutHandler(logging.StreamHandler): '\n This class is like a StreamHandler using sys.stdout, but always uses\n whatever sys.stdout is currently set to rather than the value of\n sys.stdout at handler construction time.\n\n Copied and adopted from logging._StderrHandler.\n ' @property ...
class StreamThreadLocal(threading.local): '\n This will just buffer everything, thread-locally, and not forward it to any stream.\n The idea is that multiple tasks will run in multiple threads and you want to catch all the logging/stdout\n of each to not clutter the output, and also you want to keep it s...
class StreamDummy(): '\n This will just discard any data.\n ' def write(self, msg): '\n Ignored.\n\n :param str msg:\n ' pass def flush(self): '\n Ignored.\n '
@contextlib.contextmanager def wrap_log_streams(alternative_stream, also_sys_stdout=False, tf_log_verbosity=None): '\n :param StreamThreadLocal|StreamDummy alternative_stream:\n :param bool also_sys_stdout: wrap sys.stdout as well\n :param int|str|None tf_log_verbosity: e.g. "WARNING"\n :return: conte...
class NativeOpBaseMixin(object): '\n The purpose of having this as a separate base class is to make this independent of any Theano specific\n functionality so that we can also use this base for example for TensorFlow.\n ' def __init__(self, in_info, out_info, c_fw_code, c_bw_code=None, c_extra_suppo...
class NativeOpGenBase(): '\n Base interface for op generation.\n See NativeOp.__init__() for attribs.\n ' in_info = None out_info = None c_fw_code = None c_bw_code = None c_extra_support_code = None code_version = None grad_input_map = None theano_custom_grad = None cp...
class LstmGenericBase(NativeOpGenBase): '\n inputs:\n :param Z: {input,output,forget} gate + cell state. 3d (time,batch,dim*4)\n :param V_h: recurrent matrix. 2d (dim,dim*4)\n :param c: initial cell state. 2d (batch,dim)\n :param i: index. 2d (time,batch) -> 0 or 1\n outputs:\n :par...
class LstmLowMem(NativeOpGenBase): '\n This is designed to require minimal memory during training.\n It only stores the outputs and the cell states,\n i.e. it requires time * cells * 2 floats for memory in total.\n\n inputs:\n :param X: (time,batch,in_dim)\n :param W: forward+recurrent matri...
class NativeLstm2(NativeOpGenBase): '\n Yet another LSTM kernel.\n This kernel is about 27% than NativeLstm,\n and also has some more options (like the direction).\n But it requires time * batch * cells more memory,\n thus time * batch * cells * 6 in total.\n\n inputs:\n :param X: (time,bat...
class TwoDLSTM(NativeOpGenBase): '\n inputs:\n :param X: {input,output,forget,lambda} gate + cell state. 3d (timeT,timeS,batch,dim*5) // dim*5 or dim*1 ?\n :param V_h: recurrent matrix. 2d (dim,dim*5)\n :param V_v: recurrent matrix. 2d (dim,dim*5)\n :param W: recurrent matrix. 2d (dim,dim*5...
class Chunking(NativeOpGenBase): '\n Given an input in 3d (n_time,n_batch,n_dim), we chunk up the time dimension\n in chunks of size chunk_size, every chunk_step frames.\n This results in an 3d output (chunk_size, n_batch * n_chunks, n_dim)\n where n_chunks = floor( max(n_time - chunk_size + chunk_ste...
class UnChunking(NativeOpGenBase): '\n This reverses the output from `Chunking`, i.e. chunking the time dimension.\n We get a 3d input (chunk_size, n_batch * n_chunks, n_dim)\n and return an 3d output (n_time, n_batch, n_dim)\n where the chunks are of size chunk_size, every chunk_step frames.\n Bec...
class SubtensorBatchedIndex(NativeOpGenBase): '\n Consider you have:\n idx: 2d (n_time, n_batch) -> idx (in [0..n_dim-1])\n x: 3d (n_time, n_batch, n_dim)\n Then, this op will calculate:\n x[..., idx[...]]: 2d (n_time, n_batch)\n ' in_info = ({'name': 'x', 'ndim': 3, 'shape': (None, No...
class SparseToDense(NativeOpGenBase): '\n Expects a sparse matrix in COOrdinate format,\n where W[s0[i,b],b,s1[i]] = weight[i,b] for all i, and all batches b.\n Will return W (time,batch,dim).\n ' in_info = ({'name': '_initial_W', 'ndim': 3, 'shape': (None, None, None), 'need_contiguous': True, 'w...
class MaxAndArgmaxSparse(NativeOpGenBase): '\n Expects a sparse matrix in COOrdinate format,\n where W[s0[i,b],s1[i],b] = weight[i,b] for all i, and all batches b.\n It will return the max and argmax for all W[:,:,b]\n over the second axis.\n ' in_info = ({'name': 's0', 'ndim': 2, 'shape': (Non...
class CrossEntropySoftmaxAndGradientZSparse(NativeOpGenBase): '\n y_target is given in sparse COOrdinate format.\n We will calculate CE[t,b] = \\sum_i y_target[t,b,i] * log(softmax(z[t,b])[i]),\n for any timeframe t and batch b,\n and grad(CE[t,b], z[t,b]) = softmax(z[t,b]) - y_target[t,b].\n We al...
class FastBaumWelchOp(NativeOpGenBase): '\n inputs:\n :param am_scores: scores in -log space. 3d (time,batch,dim)\n :param edges: edges of the graph (from,to,emission_idx,sequence_idx)\n :param weights: weights of the edges\n outputs:\n :param output: Baum-Welch alignment, scores in -log...
class MultiEndFastBaumWelchOp(NativeOpGenBase): '\n inputs:\n :param am_scores: scores in -log space. 3d (time,batch,dim)\n :param edges: edges of the graph (from,to,emission_idx,sequence_idx)\n :param weights: weights of the edges\n outputs:\n :param output: Baum-Welch alignment, scores...
class SegmentFastBaumWelchOp(NativeOpGenBase): '\n Segmental Baum-Welch...\n ' in_info = ({'name': 'am_scores', 'ndim': 3, 'shape': (None, None, None), 'need_contiguous': True, 'gradient': 'disconnected'}, {'name': 'batch_idxs', 'ndim': 2, 'shape': (None, None), 'need_contiguous': True, 'gradient': 'dis...
class FastViterbiOp(NativeOpGenBase): '\n inputs:\n :param am_scores: scores in +log space. 3d (time,batch,dim)\n :param am_seq_len: (batch,)\n :param edges: edges of the graph (from,to,emission_idx,sequence_idx), i.e. (4, n_edges)\n :param weights: weights of the edges (n_edges,)\n :p...
class GetCtcFsaFastBwOp(NativeOpGenBase): '\n This implements :func:`Fsa.get_ctc_fsa_fast_bw` as a native op.\n This is for constructing a FSA with a CTC topology.\n The output format is compatible to the FastBaumWelch native op.\n\n inputs:\n :param targets: shape (batch,time), int32\n :par...
class EditDistanceOp(NativeOpGenBase): '\n Similar to :func:`tf.edit_distance`.\n Calculates the `edit distance / Levenshtein distance <https://en.wikipedia.org/wiki/Levenshtein_distance>`__.\n\n The naive implementation either goes over ``a`` and then ``b``, thus results in O(|a|*|b|) time complexity.\n...
class OptimalCompletionEditDistanceOp(NativeOpGenBase): '\n Given some prefix ``a``, what is the minimum possible edit distance to ``b`` with any possible suffix on ``a`` ?\n This is described in `Optimal Completion Distillation (OCD) <https://arxiv.org/abs/1810.01398>`__.\n The implementation is derived...
class OptimalCompletionEditDistancePerSuccessorOp(NativeOpGenBase): '\n Given some prefix ``a`` + successor,\n what is the minimum possible edit distance to ``b`` with any possible suffix on ``a`` + successor,\n for successor in ``successors``.\n This is described in `Optimal Completion Distillation (...
class NextEditDistanceRowOp(NativeOpGenBase): '\n This does a single step in calculating the edit distance table, going over the symbols in ``a``.\n Note that when you have the full sequence ``a`` in advance, :class:`EditDistanceOp` should be faster.\n However, this iterative op is useful when ``a`` is c...
class NextEditDistanceReduceOp(NativeOpGenBase): '\n Code derived from :class:`NextEditDistanceRowOp`.\n\n inputs:\n :param last_row: 2d (batch,b_time + 1), int32. last edit distances\n :param a: symbols. 2d (batch|1,n_labels), int32. current.\n :param a_n: 1d (batch,), int32. current positio...
def sparse_splice_offset_numpy(s0, idx): '\n Like sparse_slice_offset().\n ' mask = (s0 < idx) return numpy.sum(mask)
class WrapEpochValue(): '\n Use this wrapper if you want to define some value in your network\n which depends on the pretrain epoch.\n This is going to be part in your network description dict.\n ' def __init__(self, func): "\n :param ((epoch: int) -> object) func: function which s...
def find_pretrain_wrap_values(net_json): '\n See also :func:`Pretrain._resolve_wrapped_values`.\n Recursively goes through dicts, tuples and lists.\n This is a simple check to see if this is needed,\n i.e. if there are any :class:`WrapEpochValue` used.\n\n :param dict[str] net_json: network dict\n ...
class Pretrain(): '\n Start with 1 hidden layers up to N hidden layers -> N pretrain steps -> N epochs (with repetitions == 1).\n The first hidden layer is the input layer.\n This works for generic network constructions. See _construct_epoch().\n ' def __init__(self, original_network_json, networ...
def pretrain_from_config(config): '\n :type config: returnn.config.Config\n :rtype: Pretrain | None\n ' from returnn.config import network_json_from_config pretrain_type = config.bool_or_other('pretrain', None) if ((pretrain_type == 'default') or (isinstance(pretrain_type, dict) and pretrain_...
def demo(): '\n Will print out the different network topologies of the specified pretraining scheme.\n ' import returnn.util.better_exchook returnn.util.better_exchook.install() import returnn.__main__ as rnn import argparse from returnn.util.basic import obj_diff_str arg_parser = ar...
def print(*args, **kwargs): '\n ``print`` replacement.\n\n :param args:\n :param kwargs:\n ' if (not Quiet): _orig_print(*args, **kwargs)
def init(name, reference, config, sprint_unit=None, version_number=None, callback=None, **kwargs): '\n This will be called by Sprint PythonControl.\n But we also call it ourselves e.g. in getSegmentList() and SprintNnPythonLayer.\n In this specific module, we expect that there is "c2p_fd" and "p2c_fd" in...
def getSegmentList(corpusName, segmentList, config, **kwargs): '\n Sprint will directly call this function.\n ' print(('RETURNN SprintControl[pid %i] getSegmentList: corpus=%r, config=%r' % (os.getpid(), corpusName, config))) init(name='RETURNN.PythonSegmentOrder', reference=corpusName, config=confi...
class SprintNnPythonLayer(): '\n Sprint will directly call this class, i.e. create an instance of it.\n It implements the Sprint NN PythonLayer interface.\n ' def __init__(self, config, **kwargs): print(('RETURNN SprintControl[pid %i] SprintNnPythonLayer.__init__: %r, %r' % (os.getpid(), con...
class PythonControl(): '\n This will send data to RETURNN over a pipe.\n We expect that we are child process and the parent process has spawned us,\n\n An instance of this class is also the interface for multiple Sprint interfaces, i.e.:\n * PythonControl (standalone via NnTrainer tool)\n * Pyt...
def getSegmentList(corpusName, segmentList, **kwargs): '\n Called by Sprint PythonSegmentOrder.\n Set python-segment-order = true in Sprint to use this.\n\n If this is used, this gets called really early.\n If it is used together with the Sprint PythonTrainer,\n it will get called way earlier befor...
def exchook(exc_type, exc_obj, exc_tb): '\n Replacement for sys.excepthook.\n ' if (exc_type is KeyboardInterrupt): print(('SprintExternInterface[pid %i]: KeyboardInterrupt' % (os.getpid(),))) sys.exit(1) better_exchook.better_exchook(exc_type, exc_obj, exc_tb)
def init(**kwargs): '\n Called by Sprint when it initializes the PythonTrainer,\n or also for PythonControl.\n Set trainer = python-trainer in Sprint to enable PythonTrainer for the Sprint nn-trainer tool.\n Note that Sprint will call this, i.e. the trainer init lazily quite late,\n only once it se...
def _parse_config_str(config_str): assert isinstance(config_str, (str, unicode)) config_list = config_str.split(',') config = {key: value for (key, value) in [s.split(':', 1) for s in config_list if s]} return config
def _common_init(config): if (to_bool(config.get('EnableAutoNumpySharedMemPickling', False)) and (not task_system.SharedMemNumpyConfig['enabled'])): task_system.SharedMemNumpyConfig['enabled'] = True print(('SprintExternInterface[pid %i] EnableAutoNumpySharedMemPickling = True' % (os.getpid(),)))
def _init_python_trainer(inputDim, outputDim, config, targetMode, **kwargs): '\n :type inputDim: int\n :type outputDim: int\n :param str config: config string, passed by Sprint. assumed to be ","-separated\n :param str targetMode: "target-alignment" or "criterion-by-sprint" or so\n ' print(('Sp...
def _init_global_sprint_dataset(input_dim, output_dim, config): global sprintDataset if sprintDataset: return num_segments = (len(segmentOrderList) if (segmentOrderList is not None) else None) sprintDataset = ExternSprintDatasetSource(c2p_fd=int(config['c2p_fd']), p2c_fd=int(config['p2c_fd']),...
def exit(): '\n Called by Sprint, to signal that it is exiting.\n ' print('SprintExternInterface: PythonTrainer exit()') assert isInitialized sprintDataset.close()
def feedInput(features, weights=None, segmentName=None): '\n Called by Sprint.\n Unsupervised case.\n\n :param numpy.ndarray features:\n :param numpy.ndarray|None weights:\n :param str|None segmentName:\n ' feedInputAndTarget(features=features, weights=weights, segmentName=segmentName)
def feedInputAndTargetAlignment(features, targetAlignment, weights=None, segmentName=None): '\n :param numpy.ndarray features:\n :param numpy.ndarray targetAlignment:\n :param numpy.ndarray|None weights:\n :param str|None segmentName:\n ' feedInputAndTarget(features=features, alignment=targetAl...
def feedInputAndTargetSegmentOrth(features, targetSegmentOrth, weights=None, segmentName=None): '\n :param numpy.ndarray features:\n :param str targetSegmentOrth:\n :param numpy.ndarray|None weights:\n :param str|None segmentName:\n ' feedInputAndTarget(features=features, orthography=targetSegm...
def feedInputAndTarget(features, weights=None, segmentName=None, orthography=None, alignment=None, speaker_name=None, speaker_gender=None, **kwargs): '\n :param numpy.ndarray features:\n :param numpy.ndarray|None weights:\n :param str|None segmentName:\n :param str|None orthography:\n :param numpy....
class PythonControl(): '\n PythonControl, interface for Sprint.\n ' instance = None @classmethod def init(cls, **kwargs): '\n Called by global init().\n\n :rtype: PythonControl\n ' print(('SprintExternInterface[pid %i]: PythonControl %s init %r' % (os.getpid...
class ExternSprintDatasetSource(): '\n This will send data to ExternSprintDataset over a pipe.\n We expect that we are child process and the parent process has spawned us via ExternSprintDataset\n and is waiting for our data.\n ' def __init__(self, c2p_fd, p2c_fd, input_dim, output_dim, num_segme...
class DimTypes(): '\n Defines possible values for ``kind``.\n ' Unspecified = None Batch = Entity('batch') Spatial = Entity('spatial') Time = Spatial Feature = Entity('feature') Types = (Batch, Spatial, Feature)
class _DimExtra(): def __init__(self, *, dim: Dim, kind=DimTypes.Unspecified, vocab=None, undefined=False, special=False, auto_generated=False, match_priority=0, derived_from_tag=None, derived_from_op=None, batch=None, control_flow_ctx=None, src_data: Optional[_t.Tensor]=None, src_axis: Optional[int]=None): ...
class _DimMixin(): name: Optional[str] capacity: Optional[int] size: Optional[int] dyn_size_ext: Optional[_t.Tensor] _dyn_size_max_value: Optional[_t.Tensor] _extra: Optional[_DimExtra] def _handle_extra_kwargs(self: Dim, *, dyn_size: Optional[_t.RawTensorType]=None, **kwargs): if...
def _make_constant_static_dim(value, kind=None): '\n :param int value:\n :param Entity|None kind:\n :rtype: Dim\n ' return _d.Dim(dimension=value, kind=(kind or DimTypes.Unspecified), description=('unnamed_%sdim_%i' % (((kind.name + '_') if kind else ''), value)), derived_from_op=Op(kind='constant...
def _math_get_dim_via_bin_op(a: Dim, b: Dim, op_kind: str) -> Dim: assert (op_kind in {'add', 'mul'}) op_kind_ = op_kind (a_, b_) = (a, b) if (a.is_constant_static_dim() and (not b.is_constant_static_dim())): op_kind_ = (op_kind + '_left') (a_, b_) = (b, a) (cache, cache_key, res) ...
class Op(): '\n Op on :class:`Dim` which results in a derived :class:`Dim`.\n ' def __init__(self, kind, inputs, attribs=None): '\n :param str kind: "add", "sub", "mul", "ceildiv"\n :param list[Dim] inputs:\n :param dict[str]|None attribs:\n ' self.kind = kin...
def _get_description(dim, brackets=True): '\n :param Dim dim:\n :param bool brackets: add brackets when necessary\n :rtype: str\n ' if (dim.description and dim.description.startswith('unnamed_') and (dim.dimension is not None)): return str(dim.dimension) if dim.description: if ...
class _OpMultTerm(): '\n represents sth like a * b * c\n ' @classmethod def from_dim(cls, dim: Dim) -> _OpMultTerm: '\n :param dim:\n :return: op mult term\n ' dim = dim.get_same_base() if ((dim.dimension == 1) and dim.is_constant_static_dim()): ...
class _OpLinearTerm(): '\n Linear combination of :class:`_OpMultTerm`.\n Represents sth like a * b + c of :class:`Dim`.\n ' @classmethod def from_dim(cls, dim: Dim) -> _OpLinearTerm: 'from dim' res = cls.zero() res.extend_add_sub_(dim, kind='add', right=True) retu...
def _get_merged_dim_kind(dim_tags): '\n :param list[Dim]|tuple[Dim] dim_tags:\n :return: dim kind\n :rtype: Entity\n ' if any((tag.is_batch_dim() for tag in dim_tags)): return DimTypes.Batch elif any((tag.is_feature_dim() for tag in dim_tags)): return DimTypes.Feature else:...
def _representative_tag(terms: Sequence[Dim]) -> Optional[Dim]: for term_ in terms: if term_.is_dynamic_seq_length(): return term_ for term_ in terms: if (term_.kind != DimTypes.Unspecified): return term_ for term_ in terms: return term_ return None
def dim_cmp_value(obj): '\n :param Dim|_MarkedDim obj:\n :return: anything which can be compared\n ' if isinstance(obj, _d.Dim): obj = obj.get_same_base() return ('', obj.description, obj.kind, obj.dimension, (obj.dyn_size_ext.dims if (obj.dyn_size_ext is not None) else None)) if ...
def _behavior_version_reset_callback(): _DimMixin._SimpleEquality = False _DimMixin.__eq__ = _DimMixin.is_equal _DimMixin.__ne__ = _DimMixin._ne_generic
def _behavior_version_handle_new_min_version_callback(): if (util.BehaviorVersion.get() >= 16): _DimMixin._SimpleEquality = True _DimMixin.__eq__ = _DimMixin._eq_simple _DimMixin.__ne__ = _DimMixin._ne_simple
def _setup(): util.BehaviorVersion.reset_callbacks.append(_behavior_version_reset_callback) util.BehaviorVersion.handle_new_min_version_callbacks.append(_behavior_version_handle_new_min_version_callback) _behavior_version_handle_new_min_version_callback()
class _TensorExtra(): def __init__(self, *, tensor: Tensor, time_dim_axis=NotSpecified, available_for_inference=True, batch=None, beam=None, control_flow_ctx=None): '\n :param tensor:\n :param int|None|NotSpecified time_dim_axis: where we have the time dim axis, after we added the batch-dim...
class _TensorMixin(_TensorMixinBase): @staticmethod def from_tensor(x) -> Tensor: '\n :param tf.Tensor x:\n ' assert x.get_shape().is_fully_defined() x_shape = x.get_shape().as_list() return _t.Tensor(name=str(x.op.name), shape=x_shape, batch_dim_axis=None, dtype...
def infer_sparse_dim(*, name: str, sparse: Optional[bool]=None, sparse_dim, dim=NotSpecified, **_other_kwargs) -> Optional[Dim]: '\n :param name:\n :param sparse:\n :param sparse_dim:\n :param dim:\n :return: sparse dim\n ' if (sparse is None): sparse = (sparse_dim not in (None, NotS...
def infer_dim_tags(*, name, batch_dim_axis=NotSpecified, time_dim_axis=NotSpecified, feature_dim_axis=NotSpecified, dim_tags: Optional[Sequence[Dim]]=None, shape: Optional[Sequence[Optional[int]]]=None, sparse_dim: Optional[Dim]=None, dim=NotSpecified, size_placeholder=None, auto_create_placeholders=False, batch=None...
class _SizePlaceholderProxy(): '\n This is a proxy object to emulate the original Tensor.size_placeholder behavior,\n which was a dict[int,tf.Tensor], axis_wo_batch -> sizes.\n ' def __init__(self, data: Tensor): '\n :param data:\n ' self.data = data def _assert_sa...
def _batch_dim_axis_from_dim_tags_tuple(dim_tags): '\n :param Sequence[Dim] dim_tags:\n :return: batch_dim_axis. int or None if not existing\n :rtype: int|None\n ' for (axis, dim_tag) in enumerate(dim_tags): if dim_tag.is_batch_dim(): return axis return None
def _batch_shape_from_shape(shape, batch_dim_axis): '\n :param Sequence[int|None] shape: without batch-dim\n :param int|None batch_dim_axis:\n :return: shape with batch dim if existing\n :rtype: tuple[int|None]\n ' shape = tuple(shape) if (batch_dim_axis is not None): assert (0 <= b...
def _create_size_placeholder(name, axis_wo_b, tag, batch_dim): '\n :param str name:\n :param int axis_wo_b:\n :param Dim tag:\n :param Dim|None batch_dim:\n ' from returnn.tf import compat as tf_compat from returnn.tf.util.basic import reuse_name_scope with reuse_name_scope(('extern_dat...