code
stringlengths
17
6.64M
class DataNotAvailableLayer(InternalLayer): '\n This is a dummy layer that is created when the output template is flagged "not available for inference".\n The output template should be passed to the constructor to correctly forward the information\n in case any dependent output is exported with "register...
class WrappedInternalLayer(InternalLayer): '\n This is not supposed to be used by the user. Like :class:`InternalLayer`, only intended for internal usage.\n This layer is supposed to logically wrap another layer.\n ' def __init__(self, base_layer, sources=None, **kwargs): '\n :param L...
class ReuseParams(): '\n This is for parameter sharing, i.e. reusing existing `tf.Variable` objects in a new layer,\n instead of creating new variables.\n :func:`ReuseParams.from_config_dict` will be called via :func:`LayerBase.transform_config_dict`.\n ' @classmethod def from_config_dict(cls...
class SearchChoices(object): '\n In beam search, after expanding the beam and then selecting the N best (beam) (see :class:`ChoiceLayer`),\n when doing this multiple times, we need to keep reference where each beam came from,\n and what the current score is, etc.\n Also we could have multiple differen...
class Loss(object): '\n Base class for all losses.\n ' class_name = None recurrent = False need_target = True _check_output_before_softmax = True def __init__(self, base_network, use_flatten_frames=True, use_normalized_loss=False, custom_norm_factor=None, custom_inv_norm_factor=None, sc...
class VariableLayer(LayerBase): '\n Represents a variable. Can add batch/time dimension if wanted. Can be trainable.\n See defaults.\n ' layer_class = 'variable' def __init__(self, shape, dtype='float32', add_batch_axis=False, add_time_axis=False, trainable=True, saveable=True, non_critical_for_...
class VariableAssignLayer(LayerBase): '\n Assigns a new value to a variable.\n ' layer_class = 'variable_assign' def __init__(self, var: LayerBase, value: LayerBase, control_dependencies: Optional[Sequence[LayerBase]]=None, op: str='assign', **kwargs): '\n :param var:\n :param...
class VariableReadLayer(LayerBase): '\n Read a variable (currently expected from VariableLayer).\n Supports control dependencies to exactly specify when it should be read.\n ' layer_class = 'variable_read' def __init__(self, var: LayerBase, control_dependencies: Optional[Sequence[LayerBase]]=Non...
class DataNotFound(Exception): '\n When accessing non-existing data key in :class:`ExternData` (e.g. extern_data).\n '
class ExternData(TensorDict): '\n This holds :class:`Data` instances for every data-key of external data from the dataset,\n i.e. the description such as shape and sparsity, etc.\n\n It is usually defined by a user config. See :func:`init_from_config`.\n ' def __init__(self, data=None, default_in...
def _extern_data_types_from_config(config): '\n :param returnn.config.Config config:\n :return: dict data_key -> kwargs of Data\n :rtype: dict[str,dict[str]]\n ' input_data_key = config.value('default_input', 'data') if config.has('extern_data'): data_dims = config.typed_dict['extern_d...
def _num_inputs_outputs_from_config(config): '\n :type config: returnn.config.Config\n :returns (num_inputs, num_outputs),\n where num_inputs is like num_outputs["data"][0],\n and num_outputs is a dict of data_key -> (dim, ndim),\n where data_key is e.g. "classes" or "data",\n di...
def _data_kwargs_from_dataset_key(dataset, key): '\n :param returnn.datasets.basic.Dataset dataset:\n :param str key:\n :rtype: dict[str]\n ' if (key in dataset.get_target_list()): available_for_inference = False else: available_for_inference = True dim = dataset.get_data_d...
class _NetworkConstructionStack(): '\n Used to keep the recursive construction state of :function:`TFNetwork.construct_layer`.\n ' def __init__(self): self.layers = [] self.in_flat_construct_count = 0 def append(self, layer_name): '\n :param str layer_name:\n ...
class TFNetwork(object): '\n The main neural network, i.e. collection of interconnected layers, i.e. computation graph with trainable params.\n ' def __init__(self, config=None, extern_data=None, rnd_seed=None, train_flag=None, eval_flag=None, search_flag=None, parent_layer=None, parent_net=None, extra...
class Subnetwork(): "\n Represents a subnetwork.\n\n Despite the different namespace, optionally some variable sharing,\n and optionally some custom input data,\n layers behave just as in the root network,\n with the same dependency resolution (both ways).\n I.e. a layer outside can depend only ...
class TFNetworkParamsSerialized(object): '\n Holds all the params as numpy arrays, including auxiliary params.\n ' def __init__(self, values_dict, global_train_step): '\n :param dict[str,dict[str,numpy.ndarray]] values_dict: dict: layer_name -> param_name -> variable numpy array\n ...
class GetLayer(): '\n Helper object which represents the get_layer function which also triggers layer construction.\n This is implemented to better handle subnetworks and to avoid a deep stack of get_layer functions.\n Instead of defining another wrapped get_layer function,\n any subnetwork can instea...
class LossHolder(): '\n This object just keeps a reference to the loss/error value,\n and does the necessary logic to collect it, and also the normalization logic.\n Every new computation (nodes in the computation graph) must be constructed on demand,\n to allow first to collect all possible losses wi...
class NetworkLayerException(Exception): '\n Some exception by the network, e.g. during construction.\n ' def __init__(self, message, layer_name, network, net_dict=None): '\n :param str message:\n :param str layer_name:\n :param TFNetwork network:\n :param dict[str]|N...
class NetworkConstructionDependencyLoopException(NetworkLayerException): '\n This is raised when there is a dependency loop in the network construction.\n ' def __init__(self, network, layer_name, constructing_layers, net_dict): '\n :param TFNetwork network:\n :param str layer_nam...
class _DelayedConstructionException(Exception): '\n When we want to do a flat construction.\n ' def __init__(self, network, layer_name, other_kwargs): '\n :param TFNetwork network:\n :param str layer_name:\n :param dict[str] other_kwargs:\n ' self.network = n...
class LayerNotFound(NetworkLayerException): '\n Via :func:`TFNetwork.get_layer`.\n '
def _help_data_or_array(value): '\n :param numpy.ndarray|bool|object value:\n :return: (info,(min,max))\n :rtype: (str,(int|float,int|float))\n ' import numpy if isinstance(value, numpy.ndarray): info = ('shape %s, dtype %s' % (value.shape, value.dtype)) if (value.size > 0): ...
def help_on_tf_exception(session, exception, fetches, feed_dict=None, meta_step_info=None, extern_data=None, file=sys.stdout): '\n Generic debugging helper, on any TF exception (or even any other exception as well).\n Will try to provide as much helpful context information as possible.\n (This is not in ...
class CustomCheckpointLoader(): '\n This uses `tf.train.NewCheckpointReader`.\n\n It would do automatic conversions if needed, e.g. between different LSTM implementations.\n However, be careful that for some LSTM implementation, there is an additional ``forget_bias``\n option, which is an additional s...
class CustomLoadParamFunc(Protocol): '\n This is a custom param importer function.\n ' def __call__(self, *, name: str, shape: Tuple[int], reader: tf.compat.v1.train.NewCheckpointReader) -> Optional[numpy.ndarray]: ...
def set_custom_post_init(var, func): '\n It registers the provided `func` such that it gets called for this variable\n in :func:`TFNetwork.initialize_params`.\n\n :param tf.Variable var:\n :param (tf.compat.v1.Session)->None func:\n ' assert callable(func) var.custom_post_init = func
def have_custom_post_init(var): '\n :param tf.Variable var:\n :return: whether :func:`set_custom_post_init` was called on this var, i.e. we have custom init\n :rtype: bool\n ' custom_post_init = getattr(var, 'custom_post_init', None) if custom_post_init: assert callable(custom_post_ini...
def py_get_sprint_automata_for_batch(sprint_opts, tags): '\n :param dict[str] sprint_opts:\n :param list[str] tags:\n :return: (edges, weights, start_end_states)\n :rtype: (numpy.ndarray, numpy.ndarray, numpy.ndarray)\n ' sprint_instance_pool = SprintInstancePool.get_global_instance(sprint_opts...
def get_sprint_automata_for_batch_op(sprint_opts, tags): '\n :param dict[str] sprint_opts:\n :param tf.Tensor tags: shape (batch,), of dtype string\n :return: (edges, weights, start_end_states). all together in one automaton.\n edges are of shape (4, num_edges), each (from, to, emission-idx, seq-idx...
def py_get_sprint_loss_and_error_signal(sprint_opts, log_posteriors, seq_lengths, seq_tags): '\n :param dict[str] sprint_opts:\n :param numpy.ndarray log_posteriors: 3d (time,batch,label)\n :param numpy.ndarray seq_lengths: 1d (batch)\n :param list[str] seq_tags: seq names\n :return: (loss, error_s...
def get_sprint_loss_and_error_signal(sprint_opts, log_posteriors, seq_lengths, seq_tags): '\n :param dict[str] sprint_opts:\n :param tf.Tensor log_posteriors: 3d (time,batch,label)\n :param tf.Tensor seq_lengths: 1d (batch,)\n :param tf.Tensor seq_tags: 1d (batch,), seq names\n :return: (loss, erro...
def _init_optimizer_classes_dict(): global _OptimizerClassesDictInitialized if _OptimizerClassesDictInitialized: return _OptimizerClassesDictInitialized = True potential_list = list(globals().items()) potential_list += list(vars(tf_compat.v1.train).items()) if (tf_version_tuple() >= (1...
def _check_valid_optimizer(optimizer_class): '\n :param type optimizer_class:\n ' if KerasOptimizer: assert issubclass(optimizer_class, (Optimizer, KerasOptimizer)) else: assert issubclass(optimizer_class, Optimizer)
def register_optimizer_class(cls, name=None): '\n :param type[Optimizer|KerasOptimizer] cls:\n :param str|None name:\n ' _init_optimizer_classes_dict() if (not name): name = cls.__name__ _check_valid_optimizer(cls) assert (name.lower() not in _OptimizerClassesDict) _OptimizerC...
def get_optimizer_class(class_name): '\n :param str|function|type[Optimizer|KerasOptimizer] class_name: e.g. "adam"\n :return: the class\n :rtype: type[Optimizer|KerasOptimizer]\n ' _init_optimizer_classes_dict() if isinstance(class_name, type): _check_valid_optimizer(class_name) ...
class Updater(object): '\n This will create the :class:`tf.compat.v1.train.Optimizer` instance given the config\n and the update-op for all trainable vars.\n See the code of :func:`Updater.create_optimizer` for valid config options.\n\n Wraps one or multiple tf.compat.v1.train.Optimizer, and extends i...
def accum_grad_multiple_step(grad, var, train_step, num_accum_steps): '\n :param tf.Tensor|tf.IndexedSlices grad:\n :param tf.Variable var:\n :param tf.Tensor train_step: int, scalar\n :param int num_accum_steps:\n :return: modified grad\n :rtype: tf.Tensor\n ' from returnn.tf.util.basic ...
class _KerasOptimizerWrapper(Optimizer): '\n Wraps a TF optimizer into a standard TF optimizer.\n ' @classmethod def get_factory(cls, keras_class): '\n :param type[T] keras_class: e.g. tf.keras.optimizers.Nadam\n :return function (kwargs)->Optimizer\n ' def cre...
class BaseCustomOptimizer(Optimizer): '\n Base class for our own optimizer implementations.\n This simplifies the interface to be implemented a bit from :class:`Optimizer`.\n You just have to implement :func:`_apply` here.\n See :class:`CustomGradientDescentOptimizer` or :class:`CustomAdamOptimizer` f...
class CustomGradientDescentOptimizer(BaseCustomOptimizer): '\n Just an example implementation for simple gradient descent.\n ' def _apply(self, grad, var, indices=None): '\n :param tf.Tensor grad:\n :param tf.Variable|resource_variable_ops.ResourceVariable var:\n :param tf....
class NormalizedSGD(CustomGradientDescentOptimizer): "\n All grads are L2 normalized (via :func:`tf.nn.l2_normalize`), otherwise it's standard SGD.\n Via: https://github.com/kmkolasinski/deep-learning-notes/tree/master/max-normed-optimizer\n " def _apply(self, grad, var, indices=None): '\n ...
class NeuralOptimizer1(BaseCustomOptimizer): '\n Via Neural Optimizer Search with Reinforcement Learning (https://proceedings.mlr.press/v70/bello17a/bello17a.pdf).\n\n Equivalent to the optimizer g * exp(sign(g) * sign(m)), we use:\n\n g * where(sign(g) == sign(m), 1.0, decrease_factor)\n\n where m ...
class GradVarianceScaledOptimizer(BaseCustomOptimizer): '\n Let m be the running average of g.\n Calculation of m: m_t <- beta1 * m_{t-1} + (1 - beta1) * g\n Same beta1 default as in Adam and in the paper: beta1=0.9\n\n Let v be the running average of the variance of g, i.e. of (g - m)^2.\n ' ...
class NadamOptimizer(tf_compat.v1.train.AdamOptimizer): '\n Optimizer that implements the Nadam algorithm.\n See [Dozat, T., 2015](http://cs229.stanford.edu/proj2015/054_report.pdf).\n\n Copied from:\n https://github.com/tensorflow/tensorflow/blob/v1.15.5/tensorflow/contrib/opt/python/training/nadam_o...
class CustomAdamOptimizer(BaseCustomOptimizer): '\n Reimplementation of Adam.\n See also :class:`tf.compat.v1.train.AdamOptimizer`.\n\n ```\n t <- t + 1\n lr_t <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t)\n\n m_t <- beta1 * m_{t-1} + (1 - beta1) * g\n v_t <- beta2 * v_{t-1} + (1 - bet...
class AMSGradOptimizer(Optimizer): '\n https://colab.research.google.com/notebook#fileId=1xXFAuHM2Ae-OmF5M8Cn9ypGCa_HHBgfG&scrollTo=N1-2wPHN1Otn\n https://openreview.net/pdf?id=ryQu7f-RZ\n https://keras.io/optimizers/\n https://ruder.io/deep-learning-optimization-2017/index.html#fixingtheexponentialmo...
def FeatureDim(description, dimension, **kwargs): '\n DEPRECATED. Use :class:`Dim` instead, and setting the `kind` is not needed anymore.\n\n :param str description:\n :param int|None dimension:\n :rtype: Dim\n ' return Dim(kind=Dim.Types.Feature, description=description, dimension=dimension, *...
def SpatialDim(description, dimension=None, **kwargs): '\n DEPRECATED. Use :class:`Dim` instead, and setting the `kind` is not needed anymore.\n\n :param str description:\n :param int|None dimension:\n :rtype: Dim\n ' return Dim(kind=Dim.Types.Spatial, description=description, dimension=dimensi...
class BatchInfo(): '\n A batched tensor is a tensor with batch dimension,\n i.e. consisting of multiple samples/sequences\n which are supposed to be totally independent of each other.\n\n The batch dim can consists out of one or more flattened "virtual" dims,\n which :class:`BatchInfo` keeps track ...
class SearchBeam(): '\n Represents info about the beam from some beam search (e.g. via :func:`beam_search`),\n e.g. such as the beam size, but also the dependencies.\n This is somewhat parallel to :class:`SearchChoices`, but simpler,\n and independent from the layers/network (:class:`returnn.tf.layers...
@contextlib.contextmanager def gradient_checkpoint_scope(): '\n :return: context manager, where all tensors created inside the scope will be recomputed at backprop time,\n based on existing tensors which have been created earlier outside the scope.\n\n If prepare_gradient_checkpointing() is not calle...
@contextlib.contextmanager def gradient_checkpoint_exclude_scope(): '\n :return: context manager, where all tensors created inside the scope will be excluded\n for recomputation at backprop time.\n ' graph = tf_compat.v1.get_default_graph() first_op_id = (graph._last_id + 1) (yield) l...
def prepare_gradient_checkpointing(): '\n Call this after the computation graph for calculating the model + loss has been created,\n before the gradients are calculated (before tf.gradients is called).\n\n This will create a copy of all the ops from within the gradient_checkpoint_scope() scope.\n\n Th...
def kenlm_checked_out(): '\n :rtype: bool\n ' return os.path.exists(('%s/lm/test.arpa' % kenlm_dir))
def get_tf_mod(verbose=False): '\n :param bool verbose:\n :return: module\n ' global _tf_mod if _tf_mod: return _tf_mod import platform from glob import glob from returnn.tf.util.basic import OpCodeCompiler assert kenlm_checked_out(), ('submodule in %r not checked out?' % ...
def ken_lm_load(filename): '\n :param str filename:\n :return: TF resource handle\n :rtype: tf.Tensor\n ' return get_tf_mod().ken_lm_load_model(filename=filename)
def ken_lm_abs_score_strings(handle, strings): '\n :param tf.Tensor handle: TF resource handle returned by :func:`ken_lm_load`\n :param tf.Tensor strings: strings which are being scores. white-space delimited words.\n :return: same shape as `strings`, float32\n :rtype: tf.Tensor\n ' return get_...
def ken_lm_abs_score_bpe_strings(handle, bpe_merge_symbol, strings): '\n :param tf.Tensor handle: TF resource handle returned by :func:`ken_lm_load`\n :param str bpe_merge_symbol: e.g. "@@"\n :param tf.Tensor strings: strings which are being scores. white-space delimited words.\n :return: same shape a...
def ken_lm_abs_score_bpe_strings_dense(handle, bpe_merge_symbol, strings, labels): '\n :param tf.Tensor handle: TF resource handle returned by :func:`ken_lm_load`\n :param str bpe_merge_symbol: e.g. "@@"\n :param tf.Tensor strings: strings which are being scores. white-space delimited words.\n :param ...
def get_fst(filename): '\n :param str filename: to OpenFst file\n :return: TF resource handle representing the FST\n :rtype: tf.Tensor\n ' return get_tf_mod().open_fst_load(filename=filename)
def fst_transition(fst_handle, states, inputs): '\n :param tf.Tensor fst_handle: via :func:`get_fst`\n :param tf.Tensor states: [batch], int32\n :param tf.Tensor inputs: [batch], int32\n :return: (next_states, output_labels, weights). next_states can be -1 if invalid. all are shape [batch].\n :rtyp...
def openfst_checked_out(): '\n :return: whether the Git submodule is checked out\n :rtype: bool\n ' return os.path.exists(('%s/src/include/fst/fst.h' % openfst_dir))
def get_tf_mod(verbose=False): '\n :param bool verbose:\n :return: module\n ' global _tf_mod if _tf_mod: return _tf_mod from glob import glob from returnn.tf.util.basic import OpCodeCompiler assert openfst_checked_out(), ('submodule in %r not checked out?' % openfst_dir) f...
def _demo(): def _make_int_list(s): '\n :param str s:\n :rtype: list[int]\n ' return [int(s_) for s_ in s.split(',')] from returnn.util import better_exchook better_exchook.install() from argparse import ArgumentParser arg_parser = ArgumentParser() arg_par...
def extern_data_template_from_config_opts(extern_data_dict: Dict[(str, Any)]) -> TensorDict: '\n :param extern_data_dict: as you would specify in the config\n :return: extern data tensor dict\n ' extern_data = TensorDict() extern_data.update(extern_data_dict, auto_convert=True) if ('seq_tag' ...
def raw_dict_to_extern_data(extern_data_raw: Dict[(str, Union[(torch.Tensor, numpy.ndarray)])], *, extern_data_template: TensorDict, device: Union[(str, torch.device)]) -> TensorDict: '\n :param extern_data_raw: This comes out of the DataLoader.\n :param extern_data_template: Specified via `extern_data` in ...
def _get_dyn_dims_from_extern_data(extern_data: TensorDict) -> List[Dim]: visited = set() res = [] for (k, v) in extern_data.data.items(): for dim in v.dims: if ((dim not in visited) and (dim.size is None)): visited.add(dim) res.append(dim) return re...
def get_batch_dim_from_extern_data(extern_data: TensorDict) -> Dim: '\n We expect that the batch dim is the first dim in any of the tensors.\n See collate_batch.\n\n We allow that the batch dim is not necessarily the global batch_dim object.\n We also allow that this is not even marked as batch dim (i...
def create_tensor(array: numpy.ndarray) -> Union[(torch.Tensor, numpy.ndarray)]: '\n Adjust non-supported dtypes\n\n :param array: numpy array to be converted\n ' if (array.dtype.kind in 'UO'): return array if (array.dtype == numpy.uint32): array = numpy.asarray(array, dtype=numpy...
def collate_batch(batch: List[Dict[(str, numpy.ndarray)]]) -> Dict[(str, Union[(torch.Tensor, numpy.ndarray)])]: '\n :param batch:\n ' assert isinstance(batch, list) assert batch, 'batch is empty?' assert isinstance(batch[0], dict) data_keys = list(batch[0].keys()) res = {} for key i...
class ChunkingIterDataPipe(torch.utils.data.IterDataPipe): "\n Splits each sequence in the given dataset into chunks according to the 'chunking' config option.\n So it transforms one sequences into multiple sequences.\n " def __init__(self, dataset: torch.utils.data.IterableDataset, chunking, *, min...
class BatchingIterDataPipe(torch.utils.data.IterDataPipe): "\n Converts a dataset yielding sequences (dict data_key -> array per sequence) into a dataset yielding lists of\n these sequences, i.e. batches.\n Sequences are grouped in-order according to the 'max_tokens' and 'max_seqs' batch size\n limits...
class LenFilterDataPipe(torch.utils.data.IterDataPipe): '\n Removes sequences which are either too long or too short from a dataset\n Returns dataset yielding list of data lengths within the defined range\n ' def __init__(self, dataset: torch.utils.data.IterableDataset, min_seq_length: Union[(int, N...
class ReturnnDatasetResetDefaultEpochCounterCallback(): '\n Default for reset_callback.\n Has an internal counter for the epoch, starting at epoch 1 (RETURNN convention).\n ' def __init__(self, dataset: ReturnnDataset): self.dataset = dataset self.epoch = 0 def __call__(self): ...
class ReturnnDatasetResetMpSharedEpochCallback(): '\n Can be used as reset_callback.\n ' def __init__(self, dataset: ReturnnDataset, epoch_mp_shared: torch.multiprocessing.Value): self.dataset = dataset self.epoch_mp_shared = epoch_mp_shared def __call__(self): epoch = self...
class ReturnnDatasetIterDataPipe(torch.utils.data.IterDataPipe): '\n Converts a RETURNN dataset into a PyTorch IterableDataset.\n ' def __init__(self, returnn_dataset: ReturnnDataset, *, reset_callback: Optional[ResetCallbackT]=None): '\n :param returnn_dataset: dataset to be wrapped\n ...
class ReturnnDatasetPerEpochMapDataPipe(torch.utils.data.MapDataPipe): '\n Converts a RETURNN dataset into a PyTorch map-style Dataset.\n ' def __int__(self, returnn_dataset: ReturnnDataset, *, reset_callback: Optional[ResetCallbackT]=None): '\n :param returnn_dataset: dataset to be wrap...
class ReturnnDatasetFullMapDataPipe(torch.utils.data.MapDataPipe): '\n Converts a RETURNN dataset into a PyTorch map-style Dataset.\n This is over the full dataset, using the default ordering.\n RETURNN-dataset-side sorting/shuffling is not supported here.\n Sorting/shuffling is intended to be done in...
def tensor_dict_numpy_to_torch_(x: TensorDict): '\n :func:`tensor_numpy_to_torch_` on all values\n ' for v in x.data.values(): tensor_numpy_to_torch_(v)
def tensor_numpy_to_torch_(x: Tensor[numpy.ndarray]): '\n torch.from_numpy() on Tensor, including dims\n ' if ((x.raw_tensor is None) or isinstance(x.raw_tensor, torch.Tensor)): pass else: assert isinstance(x.raw_tensor, numpy.ndarray) x.raw_tensor = torch.from_numpy(x.raw_te...
def tensor_dict_torch_to_numpy_(x: TensorDict): '\n :func:`tensor_torch_to_numpy_` on all values\n ' for v in x.data.values(): tensor_torch_to_numpy_(v)
def tensor_torch_to_numpy_(x: Tensor[torch.Tensor]): '\n .numpy() on Tensor, including dims\n ' if ((x.raw_tensor is None) or isinstance(x.raw_tensor, numpy.ndarray)): pass else: assert isinstance(x.raw_tensor, torch.Tensor) x.raw_tensor = x.raw_tensor.detach().cpu().numpy() ...
class DistributedContext(): '\n This class setups some helper functions for torch distributed training\n ' def __init__(self, options: Dict[(str, Any)]): import torch.distributed as dist self._opts = options dist.init_process_group(backend=self._opts.get('backend', None)) ...
def get_ctx(config=None) -> Optional[DistributedContext]: '\n :param Config|None config:\n :returns: the global context if Torch distributed is enabled, or None otherwise.\n If we did not setup the context yet, it will automatically create it.\n ' global _is_set_up, _ctx if _is_set_up: ...
def _sync_params_avg(*, module: torch.nn.Module, sync_on_cpu: bool=False): import torch.distributed as dist if (dist.get_backend() == 'gloo'): reduce_op = dist.ReduceOp.SUM elif hasattr(dist.ReduceOp, 'AVG'): reduce_op = dist.ReduceOp.AVG else: reduce_op = dist.ReduceOp.SUM ...
class Engine(EngineBase): '\n PyTorch engine\n ' def __init__(self, config: Config): '\n :param config:\n ' super(Engine, self).__init__(config=config) rf.select_backend_torch() if (util.BackendEngine.selected_engine is None): util.BackendEngine...
def _to_raw(n: Union[(int, float, Tensor)]): if isinstance(n, (int, float)): return n if isinstance(n, Tensor): return n.raw_tensor.detach().cpu().numpy() raise TypeError(f'Unexpected {n} of type {type(n)}')
def _print_process(report_prefix: str, step: int, eval_info: Optional[Dict[(str, Any)]]=None, step_duration: Optional[float]=None, log_memory_usage_device: Optional[str]=None): '\n Similar but simplified from TF engine _print_process.\n\n :param report_prefix:\n :param step:\n :param eval_info:\n :...
def _format_score(score: Dict[(str, float)]) -> str: '\n Like the TF engine format_score.\n\n :param score:\n :return: score(s) as str\n ' if (not score): return 'None' if (len(score) == 1): return _format_value(list(score.values())[0]) return ' '.join([('%s %s' % (key.spli...
def _format_value(v: Any) -> str: if isinstance(v, float): if ((abs(v) > 1000.0) or (abs(v) < 0.001)): return f'{v:.3e}' else: return f'{v:.3f}' return str(v)
def _get_gpu_device() -> Optional[str]: if torch.cuda.is_available(): return 'cuda' if (hasattr(torch.backends, 'mps') and torch.backends.mps.is_available() and torch.backends.mps.is_built()): return 'mps' return None
def get_device_from_config_opt(device: Optional[str]) -> ResultWithReason[str]: '\n :param device: as in config\n :return: resolved device\n ' if os.environ.get('PT_DEVICE'): return ResultWithReason(os.environ['PT_DEVICE'], 'PT_DEVICE env var') if (not device): device = _get_gpu_d...
def _data_loader_worker_init_func(worker_id: int): if (sys.platform == 'linux'): with open('/proc/self/comm', 'w') as f: f.write(f'TDL worker {worker_id}')
class _WrappedModuleRunStep(torch.nn.Module): '\n Wraps any Torch module (pure or RF),\n and the `forward` function calls the run step function (train_step or forward_step)\n and returns all produced raw tensors via the run context (losses or outputs) (:func:`rf.get_run_ctx`).\n This is useful to use ...
class TorchBackend(Backend[torch.Tensor]): '\n PyTorch backend\n ' RawTensorType = torch.Tensor @staticmethod def executing_eagerly() -> bool: '\n :return: whether we are executing eagerly\n ' return True @staticmethod def set_random_seed(seed: int): ...
def no_grad_trunc_normal_(tensor: torch.Tensor, mean, std, a, b, *, generator=None): '\n Code copied and adopted from torch.nn.init._no_grad_trunc_normal_,\n to support the extra `generator` argument (https://github.com/pytorch/pytorch/issues/98200).\n\n Method based on https://people.sc.fsu.edu/~jburkar...
def pt_module_to_rf_module(pt_module: torch.nn.Module) -> rf.Module: '\n :param pt_module: torch module\n :return: RF module\n ' assert isinstance(pt_module, torch.nn.Module) if isinstance(pt_module, _RFModuleAsPTModule): return pt_module.rf_module return _PTModuleAsRFModule(pt_module...
def pt_module_to_wrapped_rf_module(pt_module: torch.nn.Module) -> Optional[rf.Module]: '\n :param pt_module: torch module\n :return: RF module if the torch module is a wrapped RF module, or None otherwise\n ' assert isinstance(pt_module, torch.nn.Module) if isinstance(pt_module, _RFModuleAsPTModu...