code
stringlengths
17
6.64M
def _infer_dim_tags_tuple_from_shape(shape, batch_dim_axis, time_dim_axis, feature_dim_axis, sparse, batch, size_placeholder, name, extern_data): '\n :param tuple[int|None]|list[int|None] shape: this is without batch-dim-axis\n :param int|None batch_dim_axis:\n :param int|None time_dim_axis:\n :param ...
def _auto_create_size_placeholders_on_dim_tags(name, dim_tags): '\n :param str name:\n :param tuple[Dim] dim_tags:\n ' batch_dim_axis = _batch_dim_axis_from_dim_tags_tuple(dim_tags) batch_dim_ = (dim_tags[batch_dim_axis] if (batch_dim_axis is not None) else None) if batch_dim_: batch_...
def _get_axis_wo_b(axis_wb, batch_dim_axis, batch_ndim=None): '\n :param int axis_wb: counted with batch-dim\n :param int|None batch_dim_axis:\n :param int|None batch_ndim: only used for axis_wb < 0. might be unknown (None)\n :return: axis counted without batch-dim\n :rtype: int|None\n ' if ...
def _get_axis_wb(axis_wo_b, batch_dim_axis): '\n :param int axis_wo_b: counted without batch-dim\n :param int|None batch_dim_axis:\n :return: axis counted with batch-dim\n :rtype: int\n ' if (batch_dim_axis is None): return axis_wo_b if (axis_wo_b >= batch_dim_axis): return ...
def _infer_default_shape_and_time(batch_dim_axis, time_dim_axis, feature_dim_axis, sparse, dim): '\n This is the logic to infer some sensible/default shape when it is not specified.\n As this is somewhat adhoc, this is not recommended to be used anymore.\n\n :param int|None batch_dim_axis:\n :param in...
def _default_time_dim_axis(batch_dim_axis, shape): '\n :param int|None batch_dim_axis:\n :param Sequence[int|None] shape: without batch-dim\n :return: time dim axis, counted with batch-dim\n :rtype: int|None\n ' if (batch_dim_axis is None): time_dim_axis = None else: taken_a...
def _default_time_dim_axis_no_shape(batch_dim_axis, feature_dim_axis): '\n :param int|None batch_dim_axis:\n :param int|None|NotSpecified feature_dim_axis:\n :return: time dim axis, counted with batch-dim\n :rtype: int|None\n ' if (batch_dim_axis is None): time_dim_axis = None else:...
def _default_time_dim_axis_dim_tags(dim_tags): '\n :param list[Dim]|tuple[Dim] dim_tags:\n :return: time dim axis, counted with batch-dim\n :rtype: int|None\n ' dim_tags_dyn_spatial = [i for (i, tag) in enumerate(dim_tags) if (tag.is_spatial_dim() and (tag.dimension is None))] if dim_tags_dyn_...
def _default_feature_dim_axis(batch_dim_axis, time_dim_axis, batch_shape, sparse): '\n :param int|None batch_dim_axis:\n :param int|None time_dim_axis:\n :param tuple[int|None] batch_shape:\n :param bool sparse:\n :return: feature dim axis, counted with batch-dim\n :rtype: int|None\n ' if...
class _TensorMixinBase(): name: str _dims: Tuple[(Dim, ...)] dtype: str sparse_dim: Optional[Dim] _feature_dim_axis: Optional[Union[(int, NotSpecified)]] _raw_tensor: Optional[_t.RawTensorType] raw_tensor: Optional[_t.RawTensorType] version: int _extra: Optional[_TensorExtra]
class _TensorOpOverloadsMixin(_TensorMixinBase): def __eq__(self: Tensor, other: Union[(_rf_types.RawTensorTypes, Tensor)]) -> Union[(Tensor, bool)]: if (self.raw_tensor is None): return False import returnn.frontend as rf valid_types = ((rf.Tensor, self._raw_backend.RawTensor...
def _rf(): import returnn.frontend as rf return rf
class ControlFlowContext(): '\n This represents the current control flow context, e.g. whether this runs in a loop or a conditional branch.\n\n In case of TF,\n this is a simple wrapper around the TF ControlFlowContext which comes from tf.while_loop or tf.cond.\n\n We have this wrapper to refer to a c...
class Dim(_DimMixin): '\n Represents a dimension of a tensor.\n This potentially comes with further information such as individual sequence lengths.\n See the module docstring.\n ' Types = DimTypes __slots__ = ('name', 'capacity', 'size', 'dyn_size_ext', '_dyn_size_max_value', '_extra') na...
class VerifyOutShapeException(Exception): '\n Exception via :func:`Tensor.verify_out_shape`.\n '
class MarkedDim(): '\n Base class for marked dims, e.g. optional dims, or implicit (virtual) dims.\n ' def __init__(self, tag: _d.Dim): '\n :param tag:\n ' self.tag = tag def __repr__(self): return ('%s(%r)' % (self.__class__.__name__, self.tag)) def _eq_...
class ImplicitDim(MarkedDim): '\n Represents an implicit dim (dim tag) in :class:`Data`.\n https://github.com/rwth-i6/returnn/issues/706\n '
class ImplicitSparseDim(ImplicitDim): '\n Represents an implicit dim via Data.sparse_dim.\n '
class ImplicitDynSizeDim(ImplicitDim): '\n Represents an implicit dim via dynamic dim sizes.\n https://github.com/rwth-i6/returnn/issues/706\n (For example via :class:`CumConcatLayer`.)\n '
class OptionalDim(MarkedDim): '\n Represents a dim which might exist or not.\n '
class Tensor(_TensorMixin, _TensorOpOverloadsMixin, Generic[RawTensorType]): '\n Represents a tensor, in a frame-agnostic way. See the module docstring.\n ' size_dtype = 'int32' __slots__ = ('name', '_dims', 'dtype', 'sparse_dim', '_raw_tensor', '_feature_dim_axis', 'version', '_extra') name: st...
class TensorDict(): 'dict of tensors' def __init__(self, data: Optional[_DataStrictT]=None): self.data = {} if data: self.update(data) def __repr__(self): return f'{self.__class__.__name__}({self.data})' def update(self, data: Union[(_DataAutoConvertT, TensorDict...
def _convert_to_tensor(opts: _TensorT, *, name: Optional[str]=None) -> Tensor: '\n :param opts:\n ' if isinstance(opts, Tensor): return opts assert isinstance(opts, dict) opts = opts.copy() if name: opts['name'] = name else: assert ('name' in opts), f'missing `nam...
def tensor_dict_fill_random_numpy_(tensor_dict: TensorDict, *, rnd: Union[(int, numpy.random.RandomState)]=42, dyn_dim_max_sizes: Optional[Dict[(Dim, int)]]=None, dyn_dim_min_sizes: Optional[Dict[(Dim, int)]]=None): '\n Random fill with NumPy arrays.\n\n :param tensor_dict:\n :param rnd:\n :param dyn_...
def tensor_fill_random_numpy_(x: Tensor, *, min_val: int=0, max_val: Optional[int]=None, rnd: numpy.random.RandomState, dyn_dim_max_sizes: Optional[Dict[(Dim, int)]]=None, dyn_dim_min_sizes: Optional[Dict[(Dim, int)]]=None) -> bool: 'fill. return whether sth was filled' if (dyn_dim_max_sizes is None): ...
def executing_eagerly(): '\n :return: True if we are currently executing eagerly.\n :rtype: bool\n ' if hasattr(tf, 'executing_eagerly'): return tf.executing_eagerly() return False
class MPIClusterResolver(tf.distribute.cluster_resolver.ClusterResolver): '\n ClusterResolver for MPI.\n Distributed TF is in general totally independent of MPI.\n We only use MPI here to figure out the ClusterSpec.\n After this is set up, MPI will not be used anymore.\n TF itself will not make use...
def _get_open_port(): '\n https://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python\n\n :rtype: int\n ' import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 0)) s.listen(1) port = s.getsockname()[1] s.close() return port
class LocalOnlyClusterResolver(tf.distribute.cluster_resolver.ClusterResolver): '\n Cluster resolver for one local instance.\n ' def __init__(self): self._port = _get_open_port() self._host = ('localhost:%i' % self._port) self.task_type = 'worker' self.task_id = 0 ...
class _Controller(): '\n The controller encapsulates the logic needed for distributed TF in RETURNN.\n It would be setup via :func:`init_distributed_tf`.\n\n We currently check for the TF_CONFIG env var,\n and if set, use the :class:`TFConfigClusterResolver`.\n Otherwise we assume a MPI setup, and ...
class ReturnnDefaultStrategy(tf.distribute.Strategy): '\n RETURNN default strategy.\n ' def __init__(self): super(ReturnnDefaultStrategy, self).__init__(extended=ReturnnDefaultStrategyExtended(self))
class ReturnnDefaultStrategyExtended(DefaultDistributionExtended): '\n RETURNN default strategy extended.\n '
def init_distributed_tf(config): '\n This is called early in startup of RETURNN.\n\n :param Config config:\n ' global _controller assert (not _controller), 'init_distributed_tf called twice?' _controller = _Controller(config=config)
def is_enabled(): '\n :rtype: bool\n ' return bool(_controller)
def get_session_target(): '\n This would be called if you have a local custom graph in the current process (replica)\n and want to execute parts of it. This is e.g. the case for between-graph replication.\n After creating the graph, you would create a session\n which connects to the server returned by...
@contextlib.contextmanager def _temporary_init_distributed_tf(config): '\n This is useful for tests.\n\n :param config:\n :return: scope where we have initialized distributed TF, and going out-of-scope will uninit again\n ' global _controller init_distributed_tf(config=config) (yield) ...
class ReturnnLayersBackend(Backend[Layer]): '\n RETURNN layers backend (using TF), where raw_tensor represents a RETURNN layer\n ' RawTensorType = Layer is_tensorflow = True is_backend_raw_tensor_dim_tag_independent = False @staticmethod def executing_eagerly() -> bool: 'executi...
def _random_replay_eval(*, self, source, idx: int, **_kwargs): from returnn.tf.layers.basic import LayerBase assert isinstance(self, LayerBase) idx def _py_func() -> numpy.ndarray: elem = ReturnnLayersBackend._random_journal.get_next(new_out_template=self.output) assert isinstance(ele...
def unique_tensor_list(tensors: Iterable[Tensor]) -> List[Tensor]: '\n :param list[Tensor] tensors:\n :return: list with unique tensors\n :rtype: list[Tensor]\n ' seen = set() out = [] for tensor in tensors: if (RefIdEq(tensor) not in seen): out.append(tensor) ...
def copy(tensor: Tensor[rfl.Layer], *, name: Union[(rfl.Layer, str)]) -> Tensor[rfl.Layer]: 'copy' return rfl.make_layer({'class': 'copy', 'from': tensor}, name=name)
def identity_with_control_deps(tensor: Tensor[rfl.Layer], control_deps: Sequence[Tensor[rfl.Layer]], *, name: Optional[Union[(str, rfl.Layer)]]=None) -> Tensor[rfl.Layer]: '\n :param tensor:\n :param control_deps:\n :param name:\n :return: tensor with control deps\n ' return rfl.make_layer({'cl...
def constant(value: Union[(int, float)], *, name: Union[(str, rfl.Layer)]): 'constant' return rfl.make_layer({'class': 'constant', 'value': value, 'is_output_layer': True}, name=name)
def constant_value(x: Tensor[rfl.Layer]) -> Optional[Union[(int, float, complex, bool, str)]]: '\n If the tensor is a constant, return its value.\n ' if (x.raw_tensor.layer_dict and (x.raw_tensor.layer_dict['class'] == 'constant')): return x.raw_tensor.layer_dict['value'] return None
def zeros_like_as_output_in_scope(tensor: Tensor, *, name: rfl.Layer): '\n :param tensor:\n :param name:\n :return:\n ' args = {} if tensor.sparse_dim: args['sparse_dim'] = tensor.sparse_dim shape_deps = rfl.get_dim_deps(tensor.dims) if shape_deps: args['shape_deps'] = ...
def mark_as_output_in_scope(tensor: Tensor, scope: rfl.Layer) -> Tensor: '\n Mark this as an output.\n ' assert tensor.raw_tensor.layer_dict, f'mark_as_output can only be called on a layer, not a layer-ref {tensor}.' res = tensor if (tensor.raw_tensor is scope.children.get('output')): pa...
def get_last_hidden_state(source: Tensor, *, out_dim: Optional[Dim]=NotSpecified, combine: str=NotSpecified, key: Optional[Union[(str, int)]]=NotSpecified) -> Tensor: '\n Will combine (concat or add or so) all the last hidden states from all sources.\n\n :param nn.Tensor source:\n :param nn.Dim|None out_...
class Cond(Generic[T]): '\n Conditional branching. Basically behaves like ``if ... else ...``.\n Only one branch will be executed, and the condition needs to be a bool scalar.\n This wraps to :class:`CondLayer` in RETURNN and to ``tf.cond`` in TensorFlow.\n\n Example::\n\n with Cond(cond) as co...
class CondModule(rf.Module): '\n This module is used internally by :class:`Cond` to create the RETURNN :class:`CondLayer` for the conditional code.\n This module would not be directly used by the user.\n ' def __init__(self, cond: Cond): super(CondModule, self).__init__() self.cond =...
def get_net_dict(*, epoch: int, step: int) -> Tuple[(Dict[(str, Any)], rf.Module)]: 'called from the RETURNN config' BehaviorVersion.set_min_behavior_version(rfl.min_returnn_behavior_version) rf.select_backend_returnn_layers_tf() rfl.Layer.reset_default_root() config = get_global_config() rand...
def _eval_func_get_epoch(self: LayerBase, **_kwargs) -> tf.Tensor: run_opts = self.network.get_root_network().get_run_opts() def _py_func_get_epoch() -> int: return run_opts['epoch'] (epoch,) = tf_compat.v1.py_func(_py_func_get_epoch, [], [tf.int32], stateful=True) assert isinstance(epoch, tf...
def enable_debug_eager_mode(): '\n For debugging.\n\n Enables TF eager mode.\n Also, all layers will directly be created, and then due to TF eager mode directly evaluated.\n ' global _debug_eager_mode_enabled import tensorflow as tf tf.compat.v1.enable_eager_execution() _debug_eager_mo...
def disable_debug_eager_mode(): '\n For debugging.\n\n Enables TF eager mode.\n Also, all layers will directly be created, and then due to TF eager mode directly evaluated.\n ' global _debug_eager_mode_enabled import tensorflow as tf tf.compat.v1.disable_eager_execution() _debug_eager_...
def is_debug_eager_mode_enabled() -> bool: '\n :return: True if debug eager mode is enabled.\n ' return _debug_eager_mode_enabled
def get_dim_deps(dim: Union[(Dim, Sequence[Dim])]) -> List[Tensor]: '\n :return: the tensors the dim tag depends on.\n This is needed for some functions (layers) such as `nn.constant` or `nn.random_...`.\n https://github.com/rwth-i6/returnn/issues/1096\n ' if isinstance(dim, (tuple, list, set)...
def _register_dim_deps_when_novel(dim: Dim, deps: List[Tensor]): if dim.derived_from_op: return dim = dim.get_same_base() if (dim in _dim_deps): old_deps = _dim_deps[dim] if (not _deps_valid_in_cur_name_ctx(old_deps)): _dim_deps.pop(dim) elif (any(((not dep.avai...
def _deps_valid_in_cur_name_ctx(deps: List[Tensor]) -> bool: cur_root = rfl.Layer.top().root for dep in deps: assert isinstance(dep, Tensor) assert isinstance(dep.raw_tensor, rfl.Layer) if (dep.raw_tensor.root != cur_root): return False return True
def _register_dim_via_dyn_layer(dim: Dim) -> bool: '\n Given is any custom length tensor (dyn layer),\n and we make a dim from that.\n We do that via the range_from_length layer.\n\n :param dim:\n :return: whether we registered the dim\n ' if (dim.is_static() or dim.is_batch_dim()): ...
class Layer(): '\n This is a helper class to keep track of the current name context when creating layers.\n Usually you do not need to access this directly\n except for creating the root name ctx\n and getting out the final RETURNN config or net dict.\n\n A name ctx represents one absolute layer na...
class _ReturnnConfigSerializer(): '\n Serializes a RETURNN config to a string.\n\n The config consists of generic RETURNN settings (behavior_version and maybe others)\n generic imports (e.g. "from returnn.tf.util.data import Data, Dim, ..."),\n dim tags, extern_data and the net dict.\n\n It is poss...
class _NetDictBuilderCtx(): '\n Context for building the net.\n ' def __init__(self, *, root_module: rf.Module, name_path_cache: _NamePathCache): self.root_module = root_module self.cache = name_path_cache class _StackInfo(): def __init__(self, *, parent: Optional[_NetDict...
class Net(): '\n Represents a RETURNN (sub) network.\n ' def __init__(self, *, name_ctx: Layer): self.name_ctx = name_ctx def __repr__(self): return f'Net{self.name_ctx!r}'
class ReturnnDimTagsProxy(): '\n When serialized via __repr__, this represents a dict unique_name -> dim tag.\n All usages in the network and extern_data will also get proxies when serialized point to this dict.\n ' class DimRefProxy(): '\n This will be a reference to the global dim_t...
class _NamePathCache(): def __init__(self): self.module_to_name_path = {} self.tensor_to_name_path = {} self.name_path_to_module = {} def register_module(self, module: rf.Module, name_path: Sequence[str]): '\n Register some module (e.g. root module).\n ' ...
def _resolve_param_tensor(param: rf.Parameter[rfl.Layer]) -> rf.Tensor[rfl.Layer]: '\n Get the original tensor from a parameter, pointing to the VariableLayer.\n Via parameter_assign, the current param tensor might be some variable read,\n not the original VariableLayer.\n\n :param param:\n :return...
def _auto_setup_parent_name_ctx(*, ignore_top_stack_frames: int=1) -> Layer: '\n Sets up a NameCtx corresponding to the Python call stack trace.\n\n From the call stack, we consider methods from modules (rf.Module subclasses)\n or global functions on tensors.\n\n There are some heuristics involved but...
def auto_setup_name_ctx_ignore_func(func: Union[(types.FunctionType, Callable)]): '\n Registers the func in the blacklist.\n ' _AutoSetupNameCtxCodeBlacklist.add(func.__code__)
class Loop(): '\n This represents a RecLayer subnetwork in RETURNN,\n i.e. where the calculation per step is defined explicitly.\n\n (For RecLayer with a predefined unit, see :class:`Rec`.\n Or for example :class:`Lstm`.)\n\n To define a loop like this pseudo Python code::\n\n x # given, sha...
class LoopModule(rf.Module): '\n This module is used internally by :class:`Loop` to create the RETURNN :class:`RecLayer` for the loop.\n This module would not be directly used by the user.\n ' def __init__(self, loop: Loop): super(LoopModule, self).__init__() self.loop = loop de...
class _LoopStateHolder(): def __init__(self, loop: Loop): self._loop = loop self._state = {} def __repr__(self): return f'{self._loop}.state' def _get_state(self, name: str) -> _LoopState: if (name in self._state): return self._state[name] raise Attri...
class _LoopState(): '\n Represents some recurrent state, to be used with :class:`Loop`.\n It can also represent some nested hierarchy of states.\n ' def __init__(self, *, name: str, loop: Loop, initial: Union[(Tensor, Any)]): '\n :param name:\n :param loop:\n :param init...
def _rec_unstack(source: Tensor, *, axis: Dim, declare_rec_time: bool=NotSpecified, name: Optional[Union[(str, rfl.Layer)]]=None) -> Tensor: '\n This is supposed to be used inside a :class:`RecLayer`.\n The input is supposed to be outside the rec layer (i.e. via ``base:``).\n Uses tf.TensorArray and then...
def make_layer(layer_dict: rfl.LayerDictRaw, *, name: Optional[Union[(str, rfl.Layer)]]=None, out: Optional[Tensor]=None, predefined_out_data: Optional[Tensor]=None, name_ctx_ignore_top_stack_frames: int=0) -> Tensor[rfl.Layer]: '\n Creates the layer. This also registers the layer instance in the top name ctx....
def _get_sub_layer(layer: Tensor[rfl.Layer], name: str, *, data: Tensor) -> Tensor: '\n Like the "{layer}/{name}" syntax in RETURNN.\n Normally this should only be needed for internal usage.\n ' out = layer.raw_tensor.get_child_tensor(name, data=data) if rfl.is_debug_eager_mode_enabled(): ...
def _tensor_from_layer_dict(layer_dict: rfl.LayerDictRaw, *, layer: rfl.Layer) -> Tensor[rfl.Layer]: '\n Use RETURNN layer_class.get_out_data_from_opts to get the :class:`Data`.\n For this function, we need to set up some dummy network and dummy source layers.\n ' from returnn.tf.network import TFNet...
class ReturnnConstructTemplateException(Exception): '\n In :func:`_data_from_layer_dict`, when we call layer_class.get_out_data_from_opts,\n we potentially can get errors, often due to user mistakes.\n We wrap those errors in this exception for better reporting.\n '
def _init_global_batch() -> BatchInfo: root_name_ctx = rfl.Layer.top().root if root_name_ctx.global_batch: return root_name_ctx.global_batch if rfl.is_debug_eager_mode_enabled(): root_name_ctx.global_batch = BatchInfo.make_global_batch_info(tf.constant(3, name='global_batch')) else: ...
def _get_raw_layer_by_name(name: str, *, scope: rfl.Layer, data: Tensor): '\n Special layer can be "data:..." or whatever.\n ' scope.get_child_with_tensor(name, data=data)
def register_extern_data(data: Tensor[rfl.Layer]): '\n Register extern data from root ctx.\n As a side effect, it registers the given data as extern data,\n and this will be included when creating the RETURNN config,\n via :func:`NameCtx.get_returnn_config`.\n ' assert isinstance(data, Tensor) ...
def _make_random_tf_tensor_for_returnn_data(data: Tensor) -> tf.Tensor: shape = [] for dim in data.dim_tags: if dim.is_batch_dim(): assert data.batch shape.append(data.batch.dim) elif (dim.dimension is not None): shape.append(dim.dimension) else: ...
class MaskedComputation(): '\n This is expected to be inside a :class:`Loop`.\n\n Usage example::\n\n loop = nn.Loop(...)\n loop.state.y = ... # some initial output\n loop.state.h = ... # some initial state\n with loop:\n\n mask = ... # dtype bool, shape [batch] or wh...
class MaskedComputationModule(rf.Module): '\n This is for internal use by :class:`MaskedComputation`.\n ' def __init__(self, masked_computation: MaskedComputation): super().__init__() self.masked_computation = masked_computation def __call__(self) -> Tensor: '\n Make...
def parameter_assign(param: rf.Parameter, value: Tensor, *, op: str='assign') -> None: '\n Parameter assign.\n\n :param param:\n :param value:\n :param op:\n :return:\n ' if (param.raw_tensor.layer_dict['class'] == 'variable'): assign_helper_initial_read = _AssignHelper(param=param, ...
class _AssignHelper(): def __init__(self, *, param: rf.Parameter[Layer], read_layer_name: str, read_control_deps: Optional[Sequence[Tensor]]): self.param = param self.read_layer_name = read_layer_name self.read_control_deps = read_control_deps self.old_param_copy: Tensor[rfl.Layer...
class PrevTensorRef(Tensor): '\n Refers to a layer from the previous loop iteration.\n ' @classmethod def get_prev_ref(cls, *, cur_layer_name_ctx: rfl.Layer, initial: Tensor) -> PrevTensorRef: '\n Create prev ref.\n ' parent_name_ctx = cur_layer_name_ctx.parent ...
class TFBackend(Backend[tf.Tensor]): '\n TensorFlow low-level backend, operating on tf.Tensor\n ' RawTensorType = tf.Tensor is_tensorflow = True @staticmethod def executing_eagerly() -> bool: '\n :return: whether we are in eager execution mode\n ' return tf.exe...
class HorovodContext(): '\n This setups some helper functions.\n ' def __init__(self, config): '\n :param Config config:\n ' import horovod print('Horovod:', horovod.__version__, horovod.__file__) import horovod.tensorflow as hvd hvd.init() ...
def get_ctx(config=None): '\n :param Config|None config:\n :returns: the global context if Horovod is enabled, or None otherwise.\n If we did not setup the context yet, it will automatically create it.\n :rtype: HorovodContext|None\n ' global _is_set_up, _ctx if _is_set_up: return...
class HyperParam(): '\n Represents one hyper parameter.\n ' def __init__(self, dtype=None, bounds=None, classes=None, log=False, default=None): '\n :param str|type|None|list dtype: e.g. "float", "int" or "bool", or if Collection, will be classes\n :param None|list[int|float] bound...
class TrainException(Exception): '\n Exception from training.\n '
class Individual(): '\n One instance of hyper params.\n ' def __init__(self, hyper_param_mapping, name): '\n :param dict[HyperParam] hyper_param_mapping:\n :param str name:\n ' self.hyper_param_mapping = hyper_param_mapping self.cost = None self.name...
class Optimization(): '\n Hyper parameter optimization handler class.\n ' def __init__(self, config, train_data): '\n :param returnn.config.Config config:\n :param Dataset train_data:\n ' self.config = config self.opts = CollectionReadCheckCovered(config.get...
class _IndividualTrainer(): def __init__(self, optim, individual, gpu_ids): '\n :param Optimization optim:\n :param Individual individual:\n :param set[int] gpu_ids:\n ' self.optim = optim self.individual = individual self.runner = None self.gpu...
class _AttribOrKey(): ColTypeConfig = Config ColTypeDict = dict ColTypeObj = object def __init__(self, key, col_type): '\n :param str|object key:\n :param type[object]|type[dict] col_type:\n ' self.key = key self.col_type = col_type def __str__(self):...
class _AttrChain(): def __init__(self, base): '\n :param object|dict base:\n ' self.base = base self.chain = [] self.value = base def __str__(self): return ''.join(map(str, self.chain)) def __repr__(self): return ('<%s %r %r>' % (self.__clas...
def hash_str_djb2(s): '\n :param str s:\n :rtype: int\n ' v = 5381 for x in s: v = (((v << 5) + v) + ord(x)) v = (v & 4294967295) return v
def hash_seq(ls): '\n :param list|tuple ls:\n :rtype: int\n ' v = 5381 for x in ls: v = ((1000003 * v) + hash_obj(x)) v = (v & 4294967295) return v
def hash_int(x): '\n :param int x:\n :rtype: int\n ' return (((x << 11) + x) & 4294967295)
def hash_obj(x): '\n :param tuple|list|str|_AttribOrKey|_AttrChain x:\n :rtype: int\n ' if isinstance(x, (list, tuple)): return hash_seq(x) if isinstance(x, str): return hash_str_djb2(x) if isinstance(x, _AttribOrKey): return hash_str_djb2(x.key) if isinstance(x, _...
class LayerBase(object): '\n This is the base class for all layers.\n Every layer by default has a list of source layers `sources`\n and defines `self.output` which is of type :class:`Data`.\n It shares some common functionality across all layers, such as explicitly defining the output format,\n so...
class InternalLayer(LayerBase): '\n This is not supposed to be used by the user.\n It is used by some code to construct a wrapper layer or so.\n ' def __init__(self, output: Data, debug_type_name: Optional[str]=None, **kwargs): '\n :param output:\n :param debug_type_name: just ...