code
stringlengths
17
6.64M
class MultiProcDataset(CachedDataset2): '\n Dataset which uses multi-processing to load the data from another dataset.\n\n To get deterministic behavior, it will use round-robin scheduling.\n\n There is one process just for generating the sequence order, i.e. list of sequences.\n Then there are ``num_...
class NormalizationData(object): 'This class holds normalization data for inputs and outputs.\n It also contains methods to create the normalization HDF file.\n ' GROUP_INPUTS = 'inputs' GROUP_OUTPUTS = 'outputs' DATASET_MEAN = 'mean' DATASET_MEAN_OF_SQUARES = 'meanOfSquares' DATASET_VAR...
class NumpyDumpDataset(Dataset): '\n For ``tools/dump-dataset.py --type=numpy``.\n ' file_format_data = '%i.data' file_format_targets = '%i.targets' def __init__(self, prefix, postfix='.txt.gz', start_seq=0, end_seq=None, num_inputs=None, num_outputs=None, **kwargs): super(NumpyDumpData...
class SprintDatasetBase(Dataset): "\n In Sprint, we use this object for multiple purposes:\n - Multiple epoch handling via SprintInterface.getSegmentList().\n For this, we get the segment list from Sprint and use the Dataset\n shuffling method.\n - Fill in data which we get via SprintInterface....
class ExternSprintDataset(SprintDatasetBase): '\n This is a Dataset which you can use directly in RETURNN.\n You can use it to get any type of data from Sprint (RWTH ASR toolkit),\n e.g. you can use Sprint to do feature extraction and preprocessing.\n\n This class is like SprintDatasetBase, except tha...
class SprintCacheDataset(CachedDataset2): '\n Can directly read Sprint cache files (and bundle files).\n Supports both cached features and cached alignments.\n For alignments, you need to provide all options for the AllophoneLabeling class, such as allophone file, etc.\n ' class SprintCacheReader...
def demo(): '\n Demo.\n ' print('SprintDataset demo.') from argparse import ArgumentParser from returnn.util.basic import progress_bar_with_time from returnn.log import log from returnn.config import Config from returnn.datasets.basic import init_dataset arg_parser = ArgumentPars...
class StereoDataset(CachedDataset2): 'The purpose of this dataset is to be a base dataset for datasets which\n have an easy to use interface for using RETURNN as a regression tool\n ' def __init__(self, partition_epoch=1, **kwargs): 'constructor' super(StereoDataset, self).__init__(**kw...
class StereoHdfDataset(StereoDataset): "A stereo dataset which needs an hdf file as input. The hdf file\n is supposed to always have group 'inputs' and for the training data it\n also needs to contain the group 'outputs'. Each group is supposed to\n contain one dataset per sequence. The names of the data...
class DatasetWithTimeContext(StereoHdfDataset): 'This dataset composes a context feature by stacking together time frames.' def __init__(self, hdfFile, tau=1, **kwargs): 'Constructor\n\n :type hdfFile: string\n :param hdfFile: see the StereoHdfDataset\n :type tau: int\n :p...
def str_to_numpy_array(s: str) -> numpy.ndarray: '\n Canonical way to make a Numpy array for a Python string.\n\n For :class:`returnn.tensor.Tensor` instances on Numpy arrays,\n the dtype logic assumes this behavior.\n\n :param s: string\n :return: numpy array, `dtype.kind == "U"`\n ' return...
class Vocabulary(object): '\n Represents a vocabulary (set of words, and their ids).\n Used by :class:`BytePairEncoding`.\n ' _cache = {} @classmethod def create_vocab(cls, **opts): '\n :param opts: kwargs for class\n :rtype: Vocabulary|BytePairEncoding|CharacterTargets...
class BytePairEncoding(Vocabulary): '\n Vocab based on Byte-Pair-Encoding (BPE).\n This will encode the text on-the-fly with BPE.\n\n Reference:\n Rico Sennrich, Barry Haddow and Alexandra Birch (2016). Neural Machine Translation of Rare Words with Subword Units.\n Proceedings of the 54th Annual Me...
class SamplingBytePairEncoding(Vocabulary): '\n Vocab based on Byte-Pair-Encoding (BPE).\n Like :class:`BytePairEncoding`, but here we randomly sample from different possible BPE splits.\n This will encode the text on-the-fly with BPE.\n ' def __init__(self, vocab_file, breadth_prob, seq_postfix=...
class SentencePieces(Vocabulary): '\n Uses the SentencePiece software,\n which supports different kind of subword units (including BPE, unigram, ...).\n\n https://github.com/google/sentencepiece/\n https://github.com/google/sentencepiece/tree/master/python\n\n Dependency::\n\n pip3 install --u...
class CharacterTargets(Vocabulary): '\n Uses characters as target labels.\n Also see :class:`Utf8ByteTargets`.\n ' def __init__(self, vocab_file, seq_postfix=None, unknown_label='@', labels=None, **kwargs): '\n :param str|None vocab_file:\n :param list[int]|None seq_postfix: la...
class Utf8ByteTargets(Vocabulary): '\n Uses bytes as target labels from UTF8 encoded text. All bytes (0-255) are allowed.\n Also see :class:`CharacterTargets`.\n ' def __init__(self, seq_postfix=None): '\n :param list[int]|None seq_postfix: labels will be added to the seq in self.get_...
class EngineBase(): '\n Base class for a backend engine, such as :class:`TFEngine.Engine`.\n ' def __init__(self, config: Optional[Config]=None): '\n :param config:\n ' if (config is None): config = get_global_config(auto_create=True) self.config = conf...
class BatchSeqCopyPart(): '\n A batch used for training in RETURNN can consist of several parts from sequences,\n ordered in various ways. The dataset, depending on the configuration, can\n generate these. For the non-recurrent case, we usually concatenate\n them together into one slice. For the re...
class Batch(): '\n A batch can consists of several sequences (= segments).\n This is basically just a list of BatchSeqCopyPart.\n ' def __init__(self): self.max_num_frames_per_slice = NumbersDict(0) self.num_slices = 0 self.seqs = [] def __repr__(self): return ('...
class BatchSetGenerator(): '\n This will give you the next batches (list[Batch]) such that you can use them for assign_dev_data().\n We get those batches from a generator, i.e. lazily on-the-fly. This is the whole point of BatchSetGenerator\n - that we must not know the whole list of batches in advance.\...
def is_checked_out(): '\n Checks if the git submodule is checkout out.\n\n :rtype: bool\n ' return os.path.isfile(('%s/src/rnnt_entrypoint.cpp' % submodule_dir))
def init_warprnnt(verbose=False): '\n Initializes and compiles the library. Caches the TF module.\n\n :param bool verbose:\n ' global _tf_mod if _tf_mod: return assert is_checked_out(), 'submodule not checked out? Run `git submodule update --init --recursive`' src_files = [('%s/sr...
def rnnt_loss(acts, labels, input_lengths, label_lengths, blank_label=0): 'Computes the RNNT loss between a sequence of activations and a\n ground truth labeling.\n Args:\n acts: A 4-D Tensor of floats. The dimensions\n should be (B, T, U, V), where B is the minibatch index,\n ...
@ops.RegisterGradient('WarpRNNT') def _warprnnt_loss_grad(op, grad_loss, _): grad = op.outputs[1] grad_loss = tf.reshape(grad_loss, ((- 1), 1, 1, 1)) return [(grad_loss * grad), None, None, None]
def is_checked_out(): '\n Checks if the git submodule is checkout out.\n\n :rtype: bool\n ' return os.path.isfile(('%s/core.cu' % submodule_dir))
def init_warprna(verbose=False): '\n Initializes and compiles the library. Caches the TF module.\n\n :param bool verbose:\n ' global _tf_mod if _tf_mod: return assert is_checked_out(), 'submodule not checked out? Run `git submodule update --init --recursive`' enable_gpu = OpCodeCo...
def rna_loss(log_probs, labels, input_lengths, label_lengths, blank_label=0): 'Computes the RNA loss between a sequence of activations and a\n ground truth labeling.\n Args:\n log_probs: A 4-D Tensor of floats. The dimensions\n should be (B, T, U, V), where B is the minibatch ind...
@ops.RegisterGradient('WarpRNA') def _warprna_loss_grad(op, grad_loss, _): grad = op.outputs[1] grad_loss = tf.reshape(grad_loss, ((- 1), 1, 1, 1)) return [(grad_loss * grad), None, None, None, None]
def main(): 'main warp-rna demo' print('Hello, running WarpRna demo') test_warprna_forward()
def test_warprna_forward(): 'test warp-rna forward' assert is_checked_out() import numpy as np expected_costs = np.array([2.6347387, 2.4651031]) expected_grads = np.array([[[[(- 0.34075904), (- 0.65924096), 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[(- 0.09434381), (- 0.24641524), 0.0], [(- 0.4480...
def detach_control_inputs(sgv): 'Detach all the external control inputs of the subgraph sgv.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n ' sgv = subgraph.make_view(sgv) for op in ...
def detach_control_outputs(sgv, control_outputs): 'Detach all the external control outputs of the subgraph sgv.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n control_outputs: a util.Contr...
def detach_inputs(sgv, control_inputs=False): 'Detach the inputs of a subgraph view.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n Note that sgv is modified in place.\n control_inp...
def detach_outputs(sgv, control_outputs=None): 'Detach the output of a subgraph view.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n Note that sgv is modified in place.\n control_ou...
def detach(sgv, control_inputs=False, control_outputs=None, control_ios=None): 'Detach both the inputs and the outputs of a subgraph view.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n ...
def connect(sgv0, sgv1, disconnect_first=False): 'Connect the outputs of sgv0 to the inputs of sgv1.\n\n Args:\n sgv0: the first subgraph to have its outputs swapped. This argument is\n converted to a subgraph using the same rules as the function\n subgraph.make_view.\n Note that sgv0...
def bypass(sgv): 'Bypass the given subgraph by connecting its inputs to its outputs.\n\n Args:\n sgv: the subgraph view to be bypassed. This argument is converted to a\n subgraph using the same rules than the function subgraph.make_view.\n Note that sgv is modified in place.\n Returns:\n ...
def _check_ts_compatibility(ts0, ts1): "Make sure the shape and dtype of the two tensor's lists are compatible.\n\n Args:\n ts0: an object convertible to a list of `tf.Tensor`.\n ts1: an object convertible to a list of `tf.Tensor`.\n Raises:\n ValueError: if any pair of tensors (same index in...
class _RerouteMode(object): "Enums for reroute's mode.\n\n swap: the end of tensors a and b are swapped.\n a2b: the end of the tensor a are also rerouted to the end of the tensor b\n (the end of b is left dangling).\n b2a: the end of the tensor b are also rerouted to the end of the tensor a\n ...
def _reroute_t(t0, t1, consumers1, can_modify=None, cannot_modify=None): 'Reroute the end of the tensors (t0,t1).\n\n Warning: this function is directly manipulating the internals of the\n `tf.Graph`.\n\n Args:\n t0: a tf.Tensor.\n t1: a tf.Tensor.\n consumers1: The consumers of t1 which n...
def _reroute_ts(ts0, ts1, mode, can_modify=None, cannot_modify=None): 'Reroute the end of the tensors in each pair (t0,t1) in ts0 x ts1.\n\n This function is the back-bone of the Graph-Editor. It is essentially a thin\n wrapper on top of the tf.Operation._update_input.\n\n Given a pair of tensor t0, t1 i...
def swap_ts(ts0, ts1, can_modify=None, cannot_modify=None): "For each tensor's pair, swap the end of (t0,t1).\n\n B0 B1 B0 B1\n | | => X\n A0 A1 A0 A1\n\n Args:\n ts0: an object convertible to a list of `tf.Tensor`.\n ts1: an object convertible to a list of `tf.Tenso...
def reroute_ts(ts0, ts1, can_modify=None, cannot_modify=None): "For each tensor's pair, replace the end of t1 by the end of t0.\n\n B0 B1 B0 B1\n | | => |/\n A0 A1 A0 A1\n\n The end of the tensors in ts1 are left dangling.\n\n Args:\n ts0: an object convertible to a lis...
def _reroute_sgv_remap(sgv0, sgv1, mode): 'Remap in place the inputs of two subgraph views to mimic the reroute.\n\n This function is meant to used by reroute_inputs only.\n\n Args:\n sgv0: the first subgraph to have its inputs remapped.\n sgv1: the second subgraph to have its inputs remapped.\n ...
def _reroute_sgv_inputs(sgv0, sgv1, mode): 'Re-route all the inputs of two subgraphs.\n\n Args:\n sgv0: the first subgraph to have its inputs swapped. This argument is\n converted to a subgraph using the same rules than the function\n subgraph.make_view.\n sgv1: the second subgraph to h...
def _reroute_sgv_outputs(sgv0, sgv1, mode): 'Re-route all the outputs of two operations.\n\n Args:\n sgv0: the first subgraph to have its outputs swapped. This argument is\n converted to a subgraph using the same rules than the function\n subgraph.make_view.\n sgv1: the second subgraph ...
def _reroute_sgv(sgv0, sgv1, mode): 'Re-route both the inputs and the outputs of the two subgraph views.\n\n This involves swapping all the inputs/outputs of the two subgraph views.\n\n Args:\n sgv0: the first subgraph to be swapped. This argument is converted to a\n subgraph using the same rule...
def swap_inputs(sgv0, sgv1): 'Swap all the inputs of sgv0 and sgv1 (see reroute_inputs).' return _reroute_sgv_inputs(sgv0, sgv1, _RerouteMode.swap)
def reroute_inputs(sgv0, sgv1): 'Re-route all the inputs of two subgraphs.\n\n Args:\n sgv0: the first subgraph to have its inputs swapped. This argument is\n converted to a subgraph using the same rules than the function\n subgraph.make_view.\n sgv1: the second subgraph to have its inp...
def swap_outputs(sgv0, sgv1): 'Swap all the outputs of sgv0 and sgv1 (see reroute_outputs).' return _reroute_sgv_outputs(sgv0, sgv1, _RerouteMode.swap)
def reroute_outputs(sgv0, sgv1): 'Re-route all the outputs of two operations.\n\n Args:\n sgv0: the first subgraph to have its outputs swapped. This argument is\n converted to a subgraph using the same rules than the function\n subgraph.make_view.\n sgv1: the second subgraph to have its...
def swap_ios(sgv0, sgv1): 'Swap the inputs and outputs of sgv1 to sgv0 (see _reroute_sgv).' return _reroute_sgv(sgv0, sgv1, _RerouteMode.swap)
def reroute_ios(sgv0, sgv1): 'Re-route the inputs and outputs of sgv0 to sgv1 (see _reroute_sgv).' return _reroute_sgv(sgv0, sgv1, _RerouteMode.a2b)
def remove_control_inputs(op, cops): 'Remove the control inputs cops from co.\n\n Warning: this function is directly manipulating the internals of the\n `tf.Graph`.\n\n Args:\n op: a `tf.Operation` from which to remove the control inputs.\n cops: an object convertible to a list of `tf.Operation...
def add_control_inputs(op, cops): 'Add the control inputs cops to op.\n\n Warning: this function is directly manipulating the internals of the tf.Graph.\n\n Args:\n op: a tf.Operation to which the control inputs are added.\n cops: an object convertible to a list of `tf.Operation`.\n Raises:\n ...
def can_be_regex(obj): 'Return True if obj can be turned into a regular expression.' return isinstance(obj, (string_types + (_RE_TYPE,)))
def make_regex(obj): 'Return a compiled regular expression.\n\n Args:\n obj: a string or a regular expression.\n Returns:\n A compiled regular expression.\n Raises:\n ValueError: if obj could not be converted to a regular expression.\n ' if (not can_be_regex(obj)): raise Val...
def _get_input_ts(ops): 'Compute the list of unique input tensors of all the op in ops.\n\n Args:\n ops: an object convertible to a list of `tf.Operation`.\n Returns:\n The list of unique input tensors of all the op in ops.\n Raises:\n TypeError: if ops cannot be converted to a list of `tf...
def _get_output_ts(ops): 'Compute the list of unique output tensors of all the op in ops.\n\n Args:\n ops: an object convertible to a list of tf.Operation.\n Returns:\n The list of unique output tensors of all the op in ops.\n Raises:\n TypeError: if ops cannot be converted to a list of tf...
def filter_ts(ops, positive_filter): 'Get all the tensors which are input or output of an op in ops.\n\n Args:\n ops: an object convertible to a list of `tf.Operation`.\n positive_filter: a function deciding whether to keep a tensor or not.\n If `True`, all the tensors are returned.\n Retur...
def filter_ts_from_regex(ops, regex): 'Get all the tensors linked to ops that match the given regex.\n\n Args:\n ops: an object convertible to a list of tf.Operation.\n regex: a regular expression matching the tensors\' name.\n For example, "^foo(/.*)?:\\d+$" will match all the tensors in the ...
def filter_ops(ops, positive_filter): 'Get the ops passing the given filter.\n\n Args:\n ops: an object convertible to a list of tf.Operation.\n positive_filter: a function deciding where to keep an operation or not.\n If True, all the operations are returned.\n Returns:\n A list of se...
def filter_ops_from_regex(ops, regex): 'Get all the operations that match the given regex.\n\n Args:\n ops: an object convertible to a list of `tf.Operation`.\n regex: a regular expression matching the operation\'s name.\n For example, `"^foo(/.*)?$"` will match all the operations in the "foo"...
def get_name_scope_ops(ops, scope): 'Get all the operations under the given scope path.\n\n Args:\n ops: an object convertible to a list of tf.Operation.\n scope: a scope path.\n Returns:\n A list of tf.Operation.\n Raises:\n TypeError: if ops cannot be converted to a list of tf.Opera...
def check_cios(control_inputs=False, control_outputs=None, control_ios=None): 'Do various check on control_inputs and control_outputs.\n\n Args:\n control_inputs: A boolean indicating whether control inputs are enabled.\n control_outputs: An instance of util.ControlOutputs or None. If not None,\n ...
def get_ops_ios(ops, control_inputs=False, control_outputs=None, control_ios=None): 'Return all the `tf.Operation` which are connected to an op in ops.\n\n Args:\n ops: an object convertible to a list of `tf.Operation`.\n control_inputs: A boolean indicating whether control inputs are enabled.\n ...
def compute_boundary_ts(ops): 'Compute the tensors at the boundary of a set of ops.\n\n This function looks at all the tensors connected to the given ops (in/out)\n and classify them into three categories:\n 1) input tensors: tensors whose generating operation is not in ops.\n 2) output tensors: tenso...
def get_within_boundary_ops(ops, seed_ops, boundary_ops=(), inclusive=True, control_inputs=False, control_outputs=None, control_ios=None): 'Return all the `tf.Operation` within the given boundary.\n\n Args:\n ops: an object convertible to a list of `tf.Operation`. those ops define the\n set in whic...
def get_forward_walk_ops(seed_ops, inclusive=True, within_ops=None, within_ops_fn=None, stop_at_ts=(), control_outputs=None): 'Do a forward graph walk and return all the visited ops.\n\n Args:\n seed_ops: an iterable of operations from which the forward graph\n walk starts. If a list of tensors is ...
def get_backward_walk_ops(seed_ops, inclusive=True, within_ops=None, within_ops_fn=None, stop_at_ts=(), control_inputs=False): 'Do a backward graph walk and return all the visited ops.\n\n Args:\n seed_ops: an iterable of operations from which the backward graph\n walk starts. If a list of tensors ...
def get_walks_intersection_ops(forward_seed_ops, backward_seed_ops, forward_inclusive=True, backward_inclusive=True, within_ops=None, within_ops_fn=None, control_inputs=False, control_outputs=None, control_ios=None): 'Return the intersection of a forward and a backward walk.\n\n Args:\n forward_seed_ops: ...
def get_walks_union_ops(forward_seed_ops, backward_seed_ops, forward_inclusive=True, backward_inclusive=True, within_ops=None, within_ops_fn=None, control_inputs=False, control_outputs=None, control_ios=None): 'Return the union of a forward and a backward walk.\n\n Args:\n forward_seed_ops: an iterable of...
def select_ops(*args, **kwargs): 'Helper to select operations.\n\n Args:\n *args: list of 1) regular expressions (compiled or not) or 2) (array of)\n `tf.Operation`. `tf.Tensor` instances are silently ignored.\n **kwargs: \'graph\': `tf.Graph` in which to perform the regex query.This is\n ...
def select_ts(*args, **kwargs): 'Helper to select tensors.\n\n Args:\n *args: list of 1) regular expressions (compiled or not) or 2) (array of)\n `tf.Tensor`. `tf.Operation` instances are silently ignored.\n **kwargs: \'graph\': `tf.Graph` in which to perform the regex query.This is\n r...
def select_ops_and_ts(*args, **kwargs): 'Helper to select operations and tensors.\n\n Args:\n *args: list of 1) regular expressions (compiled or not) or 2) (array of)\n `tf.Operation` 3) (array of) tf.Tensor. Regular expressions matching\n tensors must start with the comment `"(?#ts)"`, for ...
def _finalize_index(index_or_t, ts): 'Returns index as is or return index of tensor in `ts`.' if isinstance(index_or_t, six.integer_types): return index_or_t else: return ts.index(index_or_t)
def _finalize_indices(list_of_index_or_t, ts): "Returns index in `indices` as is or replace with tensor's index." return [_finalize_index(index_or_t, ts) for index_or_t in list_of_index_or_t]
def _check_within_range(mapping, n, repetition): 'Check is the mapping is valid.\n\n Args:\n mapping: an iterable of integer.\n n: define the input domain as [0, n-1]. Note that the mapping can be\n under-complete, that is, it can only contain a subset of the integers on\n [0, n-1].\n ...
class SubGraphView(object): 'A subgraph view on an existing `tf.Graph`.\n\n An instance of this class is a subgraph view on an existing `tf.Graph`.\n "subgraph" means that it can represent part of the whole `tf.Graph`.\n "view" means that it only provides a passive observation and do not to act\n on t...
def _check_graph(sgv, graph): 'Check if sgv belongs to the given graph.\n\n Args:\n sgv: a SubGraphView.\n graph: a graph or None.\n Returns:\n The SubGraphView sgv.\n Raises:\n TypeError: if sgv is not a SubGraphView or if graph is not None and not\n a tf.Graph.\n ValueEr...
def make_view(*args, **kwargs): 'Create a SubGraphView from selected operations and passthrough tensors.\n\n Args:\n *args: list of 1) regular expressions (compiled or not) or 2) (array of)\n `tf.Operation` 3) (array of) `tf.Tensor`. Those objects will be converted\n into a list of operation...
def make_view_from_scope(scope, graph): 'Make a subgraph from a name scope.\n\n Args:\n scope: the name of the scope.\n graph: the `tf.Graph`.\n Returns:\n A subgraph view representing the given scope.\n ' ops = select.get_name_scope_ops(graph, scope) return SubGraphView(ops)
def replace_t_with_placeholder_handler(info, t): 'Transform a tensor into a placeholder tensor.\n\n This handler is typically used to transform a subgraph input tensor into a\n placeholder.\n\n Args:\n info: Transform._TmpInfo instance.\n t: tensor whose input must be transformed into a place h...
def keep_t_if_possible_handler(info, t): 'Transform a tensor into itself (identity) if possible.\n\n This handler transform a tensor into itself if the source and destination\n graph are the same. Otherwise it will create a placeholder.\n This handler is typically used to transform a hidden input tensors...
def assign_renamed_collections_handler(info, elem, elem_): 'Add the transformed elem to the (renamed) collections of elem.\n\n A collection is renamed only if is not a known key, as described in\n `tf.compat.v1.GraphKeys`.\n\n Args:\n info: Transform._TmpInfo instance.\n elem: the original elem...
def transform_op_if_inside_handler(info, op, keep_if_possible=True): 'Transform an optional op only if it is inside the subgraph.\n\n This handler is typically use to handle original op: it is fine to keep them\n if they are inside the subgraph, otherwise they are just ignored.\n\n Args:\n info: Tra...
def copy_op_handler(info, op, new_inputs, copy_shape=False, nodedef_fn=None): 'Copy a `tf.Operation`.\n\n Args:\n info: Transform._TmpInfo instance.\n op: the `tf.Operation` to be copied.\n new_inputs: The new inputs for this op.\n copy_shape: also copy the shape of the tensor\n nodede...
class TransformerInfo(object): ' "Contains information about the result of a transform operation.' def __init__(self, info): 'Constructor.\n\n Args:\n info: an instance of Transformer._TmpInfo containing various internal\n information about the transform operation.\n ...
class _TmpInfo(object): 'Transformer temporary data.\n\n An instance of this class holds all the information relevant to a call\n to a transformer instance (that is, a call to __call__). An instance\n is created for the life-time of the __call__ function and is passed as\n argument to the handlers.\n ...
class Transformer(object): 'Transform a subgraph into another one.\n\n By default, the constructor create a transform which copy a subgraph and\n replaces inputs with placeholders. This behavior can be modified by changing\n the handlers.\n ' def __init__(self): 'Transformer constructor.\...
def copy(sgv, dst_graph=None, dst_scope='', src_scope='', reuse_dst_scope=False): 'Copy a subgraph.\n\n Args:\n sgv: the source subgraph-view. This argument is converted to a subgraph\n using the same rules than the function subgraph.make_view.\n dst_graph: the destination graph.\n dst_sc...
def copy_with_input_replacements(sgv, replacement_ts, dst_graph=None, dst_scope='', src_scope='', reuse_dst_scope=False): 'Copy a subgraph, replacing some of its inputs.\n\n Note a replacement only happens if the tensor to be replaced\n is an input of the given subgraph. The inputs of a subgraph can\n be...
def _add_control_flow_ops(ops, control_ios): 'Complete `ops` so that the transformed graph is valid.\n\n Partially copying a graph can lead to a malformed graph. For instance,\n copying half of a while construct is likely to result in an invalid graph.\n This function attempts to add missing ops so that ...
def graph_replace(target_ts, replacement_ts, dst_scope='', src_scope='', reuse_dst_scope=False): 'Create a new graph which compute the targets from the replaced Tensors.\n\n Args:\n target_ts: a single tf.Tensor or an iterable of tf.Tensor.\n replacement_ts: dictionary mapping from original tensors t...
def concatenate_unique(la, lb): 'Add all the elements of `lb` to `la` if they are not there already.\n\n The elements added to `la` maintain ordering with respect to `lb`.\n\n Args:\n la: List of Python objects.\n lb: List of Python objects.\n Returns:\n `la`: The list `la` with missing el...
class ListView(object): 'Immutable list wrapper.\n\n This class is strongly inspired by the one in tf.Operation.\n ' def __init__(self, list_): if (not isinstance(list_, list)): raise TypeError('Expected a list, got: {}.'.format(type(list_))) self._list = list_ def __it...
def is_iterable(obj): 'Return true if the object is iterable.' if isinstance(obj, tf_ops.Tensor): return False try: _ = iter(obj) except Exception: return False return True
def flatten_tree(tree, leaves=None): 'Flatten a tree into a list.\n\n Args:\n tree: iterable or not. If iterable, its elements (child) can also be\n iterable or not.\n leaves: list to which the tree leaves are appended (None by default).\n Returns:\n A list of all the leaves in the tre...
def transform_tree(tree, fn, iterable_type=tuple): 'Transform all the nodes of a tree.\n\n Args:\n tree: iterable or not. If iterable, its elements (child) can also be\n iterable or not.\n fn: function to apply to each leaves.\n iterable_type: type use to construct the resulting tree for ...