code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if preserve_batch: return reshape(input_layer, [DIM_SAME, -1]) else: return reshape(input_layer, [-1])
def flatten(input_layer, preserve_batch=True)
Flattens this. If preserve_batch is True, the result is rank 2 and the first dim (batch) is unchanged. Otherwise the result is rank 1. Args: input_layer: The Pretty Tensor object, supplied. preserve_batch: If True (the default), then preserve the first dimension. Returns: A LayerWrapper with the f...
4.500088
5.472869
0.822254
if input_layer.is_sequence(): result = [tf.stop_gradient(t) for t in input_layer.sequence] return input_layer.with_sequence(result) else: return tf.stop_gradient(input_layer)
def stop_gradient(input_layer)
Cuts off the gradient at this point. This works on both sequence and regular Pretty Tensors. Args: input_layer: The input. Returns: A new Pretty Tensor of the same type with stop_gradient applied.
2.823735
2.688257
1.050396
if phase == Phase.train: return tf.nn.dropout(input_layer, keep_prob, name=name) else: return input_layer
def dropout(input_layer, keep_prob, phase=Phase.train, name=PROVIDED)
Aplies dropout if this is in the train phase.
1.858755
1.698013
1.094665
return layers.apply_activation(input_layer.bookkeeper, input_layer.tensor, operation, activation_args=op_args, activation_kwargs=op_kwargs)
def apply_with_summary(input_layer, operation, *op_args, **op_kwargs)
Applies the given operation to `input_layer` and create a summary. Args: input_layer: The input layer for this op. operation: An operation that takes a tensor and the supplied args. *op_args: Extra arguments for operation. **op_kwargs: Keyword arguments for the operation. Returns: A new layer w...
5.820245
7.786941
0.747437
op_args = list(op_args) op_args.append(input_layer.tensor) return input_layer.with_tensor(operation(*op_args, **op_kwargs))
def _rapply(input_layer, operation, *op_args, **op_kwargs)
Applies the given operation to this after expanding op_args. Args: input_layer: The input layer for this op. operation: An operation that takes a tensor and the supplied args. *op_args: Extra arguments for operation. **op_kwargs: Keyword arguments for the operation. Returns: A new layer with op...
3.112947
3.473575
0.89618
return input_layer.with_tensor( operation(input_layer.tensor, *op_args, **op_kwargs))
def apply_op(input_layer, operation, *op_args, **op_kwargs)
Applies the given operation to this before without adding any summaries. Args: input_layer: The input layer for this op. operation: An operation that takes a tensor and the supplied args. *op_args: Extra arguments for operation. **op_kwargs: Keyword arguments for the operation. Returns: A new l...
3.9546
5.052111
0.782762
if include_self: list_of_tensors = [input_layer] list_of_tensors.extend(others) else: list_of_tensors = others return prettytensor.join_pretty_tensors(list_of_tensors, input_layer, join_function)
def join(input_layer, others, include_self=True, join_function=None)
Joins the provided PrettyTensors with this using the join function. Args: input_layer: The input layer for this op. others: Sequence of PrettyTensor objects. include_self: Whether or not this includes itself or if the value is only derived from others. join_function: The function to use for joi...
3.162744
2.706412
1.168612
shape = input_layer.shape _check_split_dims(num_splits, split_dim, shape) splits = functions.unzip(input_layer, split_dim, shape[split_dim], num_splits) return input_layer.with_sequence(splits)
def unzip(input_layer, split_dim=0, num_splits=2)
Unzips this Tensor along the split_dim into num_splits Equal chunks. Examples: * `[1, 2, 3, 4] -> [1, 3], [2, 4]` * `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [3, 3]], [[2, 2], [4, 4]]` Args: input_layer: The chainable object, supplied. split_dim: The dimension to split along. Defaults to batch. ...
4.900596
5.623195
0.871497
if input_layer.is_sequence(): all_tensors = input_layer.sequence all_tensors.extend(other_tensors or []) else: all_tensors = [input_layer] if other_tensors is None: raise ValueError('Other Tensors must be supplied.') all_tensors.extend(other_tensors) # Edge cases really only apply whe...
def concat(input_layer, concat_dim, other_tensors=None)
Concatenates input PrettyTensor with other_tensors along the specified dim. This adds the Pretty Tensor passed via input_layer to the front of the list of tensors to concat. Args: input_layer: The input layer. concat_dim: The dimension along which to concat. other_tensors: The tensors to concatenate...
4.166572
3.903802
1.067311
shape = input_layer.shape _check_split_dims(num_splits, split_dim, shape) splits = tf.split( value=input_layer, num_or_size_splits=num_splits, axis=split_dim) return input_layer.with_sequence(splits)
def split(input_layer, split_dim=0, num_splits=2)
Splits this Tensor along the split_dim into num_splits Equal chunks. Examples: * `[1, 2, 3, 4] -> [1, 2], [3, 4]` * `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [2, 2]], [[3, 3], [4, 4]]` Args: input_layer: The chainable object, supplied. split_dim: The dimension to split along. Defaults to batch. ...
3.361391
3.54985
0.946911
zipped = [] for arg in args: if isinstance(arg, prettytensor.PrettyTensor): zipped.append(arg if arg.is_sequence() else itertools.repeat(arg)) elif (isinstance(arg, collections.Sequence) and not isinstance(arg, tf.compat.bytes_or_text_types)): zipped.append(arg) else: zipp...
def _zip_with_scalars(args)
Zips across args in order and replaces non-iterables with repeats.
2.935291
2.581095
1.137227
if not input_layer.is_sequence(): raise ValueError('Can only map a sequence.') return [fn(x) for x in input_layer]
def map_(input_layer, fn)
Maps the given function across this sequence. To map an entire template across the sequence, use the `as_fn` method on the template. Args: input_layer: The input tensor. fn: A function of 1 argument that is applied to each item in the sequence. Returns: A new sequence Pretty Tensor. Raises: ...
4.600092
4.184302
1.099369
# Name is special because it can also set the name scope. kwargs.pop('name') right = kwargs.pop('right_', False) if input_layer.is_sequence(): if right: args += (input_layer,) else: args = ((input_layer,) + args) result = [op(*x, **kwargs) for x in _zip_with_scalars(args)] if len(...
def _map_or_apply(input_layer, op, *args, **kwargs)
Map op across the input if it is a sequence; otherwise apply it. Note: This takes a keyword argument `right_` to right apply the op to this input. The name is chosen to limit conflicts with other keyword arguments. Args: input_layer: The input_layer (self when chaining). op: The op to apply: *args: ...
4.027969
3.230387
1.2469
if not arrays: raise ValueError('Arrays cannot be empty.') size = len(arrays[0]) for a in arrays: if size != len(a): raise ValueError('All arrays must be the same size.') count = int(size / batch_size) for i in xrange(count): start = i * batch_size end = start + batch_size yield ...
def feed_numpy(batch_size, *arrays)
Given a set of numpy arrays, produce slices of batch_size. Note: You can use itertools.cycle to have this repeat forever. Args: batch_size: The batch_size for each array. *arrays: A list of arrays. Yields: A list of slices from the arrays of length batch_size except the last one which will conta...
2.136925
2.255379
0.947479
input_iter = iter(input_iter) next_ = list(itertools.islice(input_iter, batch_size)) while next_: yield next_ next_ = list(itertools.islice(input_iter, batch_size))
def batch(input_iter, batch_size=32)
Batches data from an iterator that returns single items at a time.
2.017139
1.906588
1.057984
with tf.name_scope(name): all_data = tf.convert_to_tensor(data) global_step = global_step or bookkeeper.global_step() count = len(data) / batch_size extra = len(data) - count * batch_size if extra: offset = tf.mod(global_step, count) return tf.slice(all_data, offset * batch_size, ...
def slice_constant(data, batch_size=32, name='constant_data', global_step=None)
Provide a slice based on the global_step. This is useful when the entire data array can be stored in memory because it allows you to feed the data very efficiently. Args: data: A numpy array or tensor. batch_size: The batch size for the produced data. name: An optional name for this data. global...
2.501427
2.591881
0.965101
session_manager = SESSION_MANAGER_FACTORY() # Initialization is handled manually at a later point and session_manager # is just used for distributed compatibility. with session_manager.prepare_session(master, None, config=config, init_fn=lambda _: None) as s...
def session(self, master='', config=None)
Takes care of starting any local servers and stopping queues on exit. In general, the Runner is designed to work with any user provided session, but this provides a convenience for properly stopping the queues. Args: master: The master session to use. config: A tf.ConfigProto or None. Yie...
10.976443
9.69432
1.132255
if self._follower: self.wait_for_initialization() else: self._init_model(sess, allow_initialize) if sess is not self._sess: if self.threads: raise ValueError('You must call stop_queues() before ' 'starting a new session with QueueRunners.') self...
def prepare_model(self, sess, allow_initialize=True)
Initialize the model and if necessary launch the queue runners.
6.121996
5.241184
1.168056
# Set list of not-yet-deleted checkpoints. self._create_initializers() if self._save_path: ckpt = tf.train.get_checkpoint_state( os.path.dirname(self._save_path), latest_filename) if ckpt and ckpt.all_model_checkpoint_paths: # Copy it because last_checkpoints is immutable....
def load_from_checkpoint(self, sess, latest_filename=None)
Loads the model from the most recent checkpoint. This gets the most current list of checkpoints each time it is called. Args: sess: The current session. latest_filename: The filename for the latest set of checkpoints, defaults to 'checkpoints'. Returns: The loaded checkpoint or N...
3.304101
3.23083
1.022679
feed_data = feed_data or itertools.repeat(()) ops = [bookkeeper.global_step()] ops.extend(op_list) sess = tf.get_default_session() self.prepare_model(sess, allow_initialize=allow_initialize) results = [] try: if num_steps is None: counter = itertools.count(0) elif...
def run_model(self, op_list, num_steps, feed_vars=(), feed_data=None, print_every=100, allow_initialize=True)
Runs `op_list` for `num_steps`. Args: op_list: A list of ops to run. num_steps: Number of steps to run this for. If feeds are used, this is a maximum. `None` can be used to signal "forever". feed_vars: The variables to feed. feed_data: An iterator that feeds data tuples. prin...
2.592392
2.598157
0.997781
costs = [train_op] if (isinstance(cost_to_log, collections.Sequence) and not isinstance(cost_to_log, six.string_types)): costs.extend(cost_to_log) else: costs.append(cost_to_log) return self.run_model(costs, num_steps, feed_var...
def train_model(self, train_op, cost_to_log, num_steps, feed_vars=(), feed_data=None, print_every=100)
Trains the given model. Args: train_op: The training operation. cost_to_log: A cost to log. num_steps: Number of batches to run. feed_vars: A list or tuple of the variables that will be fed. feed_data: A generator that produces tuples of the same length as feed_vars. pri...
2.405699
2.603987
0.923852
if not hasattr(self, '_saver'): raise ValueError('Before evaluating, you must initialize the model with ' 'load_from_checkpoint, prepare or saver.') self._run_init_test_vars_op() if (not isinstance(accuracy, collections.Sequence) or isinstance(accuracy, six.string_t...
def evaluate_model(self, accuracy, num_steps, feed_vars=(), feed_data=None, summary_tag=None, print_every=0)
Evaluates the given model. Args: accuracy: The metric that is being evaluated or a tuple of metrics. num_steps: The number of steps to run in the evaluator. feed_vars: A list or tuple of the variables that will be fed. feed_data: A generator that produces tuples of the same length as ...
3.67861
3.561675
1.032831
values = [] to_print = [] for tag, value in tags_and_values: values.append(tf.Summary.Value(tag=tag, simple_value=float(value))) to_print.append('%s=%g' % (tag, value)) if self._summary_writer: summary = tf.Summary(value=values) event = tf.Event(wall_time=time.time(), ...
def add_summaries(self, step, *tags_and_values)
Adds summaries to the writer and prints a log statement.
2.205142
2.132907
1.033867
# Load the checkpoint. while True: next_checkpoint = self.load_from_checkpoint(sess) if not next_checkpoint or next_checkpoint == current_checkpoint: print('Model not yet available, sleeping for %d seconds: ' 'path %s; found: %s' % (sleep_seconds, ...
def load_new_checkpoint_when_available( self, sess, current_checkpoint, sleep_seconds=10)
Waits for a new checkpoint to be available and then loads it. Args: sess: The current session. current_checkpoint: The current checkpoint or None to just load the next one. sleep_seconds: How long to sleep between checks. Returns: The next checkpoint to use.
3.571503
3.740972
0.954699
current_checkpoint = None try: for i in itertools.count(0): # New session each time to reset queues - Yay. with self.session() as sess: current_checkpoint = self.load_new_checkpoint_when_available( sess, current_checkpoint) # Create relevant ops befor...
def evaluate_repeatedly(self, accuracy, num_steps, feed_vars=(), feed_data=None, summary_tag=None, evaluation_times=-1)
Runs the evaluation in a loop for `evaluation_times`. On each iteration, `evaluate_model` is called with the supplied arguments. This manages the queue threads itself. Args: accuracy: The metric that is being evaluated. num_steps: The number of steps to run in the evaluator. feed_vars: A...
5.165004
5.146522
1.003591
with pt.defaults_scope(phase=phase, l2loss=0.00001): # The embedding lookup must be placed on a cpu. with tf.device('/cpu:0'): embedded = text_in.embedding_lookup(CHARS, [EMBEDDING_SIZE]) # We need to cleave the sequence because sequence lstm expect each # timestep to be in its own Tensor. ...
def create_model(text_in, labels, timesteps, per_example_weights, phase=pt.Phase.train)
Creates a model for running baby names.
7.823071
7.82674
0.999531
graph = tf.get_default_graph() collection = graph.get_collection(_BOOKKEEPER) if collection: if args or kwargs: raise ValueError('Requesting construction of a BookKeeper that already ' 'exists: %s %s' % (args, kwargs)) return collection[0] else: books = BOOKKEEPER_FAC...
def for_default_graph(*args, **kwargs)
Creates a bookkeeper for the default graph. Args: *args: Arguments to pass into Bookkeeper's constructor. **kwargs: Arguments to pass into Bookkeeper's constructor. Returns: A new Bookkeeper. Raises: ValueError: If args or kwargs are provided and the Bookkeeper already exists.
3.837646
3.526422
1.088255
graph = tf.Graph() with graph.as_default(): return for_default_graph(*args, **kwargs)
def for_new_graph(*args, **kwargs)
Creates a Bookkeeper for a new graph. You must use `m.g.as_default()` to put the graph in scope: m = Bookkeeper.for_new_graph() with m.g.as_default(): ... Args: *args: Arguments to pass into Bookkeeper's constructor. **kwargs: Arguments to pass into Bookkeeper's constructor. Returns...
4.601208
6.410109
0.717805
has_deltas = isinstance(op_list, sequence_with_deltas.SequenceWithDeltas) if (group is None or len(group.control_inputs) != len(op_list) or (has_deltas and op_list.has_changed())): if has_deltas: op_list.mark() if op_list: return tf.group(*op_list, name=name) else: return tf.n...
def regroup_if_changed(group, op_list, name=None)
Creates a new group for op_list if it has changed. Args: group: The current group. It is returned if op_list is unchanged. op_list: The list of operations to check. name: The name to use if a new group is created. Returns: Either group or a new group (or if op_list is empty then no_op).
3.626867
3.336215
1.08712
books = for_default_graph() return books.create_composite_loss(losses, regularize, include_marked=include_marked, name=name)
def create_composite_loss(losses=None, regularize=True, include_marked=True, name='cost')
Creates a loss that is the sum of all specified losses. Args: losses: A sequence of losses to include. regularize: Whether or not to include regularization losses. include_marked: Whether or not to use the marked losses. name: The name for this variable. Returns: A single tensor that is the sum...
7.512032
8.861176
0.847747
books = for_default_graph() g_step = kwargs.pop('global_step', books.global_step) total_loss = books.create_composite_loss(losses=losses, regularize=regularize, include_marked=include_marked) grads_and_vars = optimizer.co...
def apply_optimizer(optimizer, losses, regularize=True, include_marked=True, clip_gradients_by_norm=None, **kwargs)
Apply an optimizer to the graph and returns a train_op. The resulting operation will minimize the specified losses, plus the regularization losses that have been collected during graph construction and the losses that were marked by calling `mark_as_required`. It will also apply any updates that have been col...
1.951855
1.815177
1.075297
assert self._global_step is None # Force this into the top-level namescope. Instead of forcing top-level # here, we could always call this in __init__() and then keep whatever # namescopes are around then. with self.g.as_default(), self.g.name_scope(None): try: self._global_step ...
def _add_global_counter(self)
Adds a global counter, called once for setup by @property global_step.
5.560074
5.056525
1.099584
if not self.summary_collections: return with self.g.as_default(): tag = tag or _tag_for(x.name) summary = (tf.summary.scalar( tag, x, collections=self.summary_collections)) return summary
def add_scalar_summary(self, x, tag=None)
Adds a scalar summary for x.
4.555714
4.423871
1.029803
if not self.summary_collections: return with self.g.as_default(): tag = tag or _tag_for(x.name) summary = tf.summary.histogram( tag, x, collections=self.summary_collections) return summary
def add_histogram_summary(self, x, tag=None)
Add a summary operation to visualize the histogram of x's values.
3.939445
4.099005
0.961074
with self._g.as_default(): if decay < 0 or decay >= 1.0: raise ValueError('Decay is %5.2f, but has to be in [0, 1).' % decay) if avg_var is None: avg_name = '%s_average' % _bare_var_name(var) with tf.control_dependencies(None): with tf.name_scope(avg_name + '/Initi...
def exponential_moving_average(self, var, avg_var=None, decay=0.999, ignore_nan=False)
Calculates the exponential moving average. TODO(): check if this implementation of moving average can now be replaced by tensorflows implementation. Adds a variable to keep track of the exponential moving average and adds an update operation to the bookkeeper. The name of the variable is '%s_avera...
2.294168
2.204693
1.040584
if not self.summary_collections: return with self.g.as_default(): if decay < 0.9 or decay >= 1.0: raise ValueError('Decay is %5.2f, but has to be in [0, 1).' % decay) avg_var = self.exponential_moving_average(var, decay=decay, ...
def add_average_summary(self, var, tag=None, decay=0.999, ignore_nan=True)
Add a summary with the moving average of var. Adds a variable to keep track of the exponential moving average and adds an update operation to the bookkeeper. The name of the variable is '%s_average' % name prefixed with the current variable scope. Args: var: The variable for which a moving aver...
3.644886
3.584979
1.016711
# TODO(eiderman): Strip name out and just rely on the name scope. _ = name # Eliminates pylint warning. if regularization: self._g.add_to_collection(GraphKeys.REGULARIZATION_LOSSES, loss) tf.add_to_collection(GraphKeys.LOSSES, loss) if add_summaries: self.add_scalar_summary(loss, ...
def add_loss(self, loss, name=None, regularization=False, add_summaries=True)
Append a loss to the total loss for the network. Args: loss: append this loss operation name: The name for this loss, defaults to loss.op.name regularization: Set to True if this is a regularization loss. add_summaries: Set to True if you want to see scalar and average summary.
4.75033
4.369499
1.087157
all_losses = [] if losses: all_losses.extend(losses) if include_marked: all_losses.extend(self.marked_losses) if not all_losses: raise ValueError('No losses specified!') if regularize: all_losses.extend(self.regularization_losses) with self._g.as_default(): res...
def create_composite_loss(self, losses, regularize=True, include_marked=True, name='cost')
Creates a loss that is the sum of all specified losses. Args: losses: A sequence of losses to include. regularize: Whether or not to include regularization losses. include_marked: Whether or not to use the marked losses. name: The name for this variable. Returns: A single tensor t...
2.59806
2.499909
1.039262
state_shape = initial_state.get_shape().as_list() full_shape = [batch_size] + state_shape if not batch_size: # TODO(): -1 is now reserved for unknown, so this should be # updated, but that requires coordination with the binary and is # checkpoint incompatible. # TODO(eiderman): ...
def add_state(self, state_name, initial_state, batch_size=None)
Adds a state to the state saver. Args: state_name: The name of this state. initial_state: The initial state vector. Only zeros are supported. batch_size: The batch_size or None for unknown.
5.337017
5.315705
1.004009
if not isinstance(class_count, tf.compat.integral_types): raise TypeError('class_count must be an integer type.') if labels.dtype.base_dtype not in (tf.int32, tf.int64): raise TypeError('Labels must be an integer: %s' % labels.dtype) if labels.get_shape().ndims != 1: raise ValueError('Labels must b...
def to_dense_one_hot(labels, class_count)
Converts a vector that specified one-hot per batch into a dense version. Args: labels: The labels input. class_count: The number of classes as an int. Returns: One dense vector for each item in the batch. Raises: ValueError: If labels is not rank 1. TypeError: If class_count is not an integer...
2.280682
2.240657
1.017863
per_example_weights = tf.convert_to_tensor( per_example_weights, name='per_example_weights', dtype=dtype) if input_.get_shape().ndims: expected_length = input_.get_shape().dims[0] message = ('per_example_weights must have rank 1 and length %s, but was: %s' % (expected_length, per_exa...
def _convert_and_assert_per_example_weights_compatible( input_, per_example_weights, dtype)
Converts per_example_weights to a tensor and validates the shape.
2.099872
2.101217
0.99936
if regression_kwargs is None: regression_kwargs = {} if name is not None and 'name' not in regression_kwargs: regression_kwargs['name'] = name elif name is None: name = input_.tensor.op.name tensor = input_.tensor loss = regression_fn(tensor, target, *regression_args, **regression_kwargs) if...
def apply_regression(input_, regression_fn, target, regression_args=(), regression_kwargs=None, name=PROVIDED, loss_weight=None, per_example_weights=None)
Applies the given regression and adds the loss to the bookkeeper. This does not change tensor. Args: input_: A Tensor or a Pretty Tensor holding the input. regression_fn: A function that takes (in order) tensor, labels. target: The targe of the regression. regression_args: Other arguments for the r...
2.62688
2.52689
1.03957
target = _convert_and_assert_tensors_compatible(input_, target) return apply_regression(input_, functions.l2_regression_sq_loss, target, [], name='%s_loss' % name, loss_weight=loss_we...
def l2_regression( input_, target, name=PROVIDED, loss_weight=None, per_example_weights=None)
Applies an L2 Regression (Sum of Squared Error) to the target.
5.903681
5.887261
1.002789
target = _convert_and_assert_tensors_compatible(input_, target) return apply_regression(input_, functions.l1_regression_loss, target, [], name='%s_loss' % name, loss_weight=loss_weigh...
def l1_regression( input_, target, name=PROVIDED, loss_weight=None, per_example_weights=None)
Applies an L1 Regression (Sum of Absolute Error) to the target.
5.100952
5.079053
1.004312
if labels is None: raise ValueError('Labels must be set') labels = _convert_and_assert_tensors_compatible(input_, labels) if per_example_weights is not None: per_example_weights = _convert_and_assert_per_example_weights_compatible( input_, per_example_weights, dtype=input_.dtyp...
def cross_entropy(input_, labels, name=PROVIDED, loss_weight=None, per_example_weights=None)
Calculates the Cross Entropy of input_ vs labels. Args: input_: A rank 2 `Tensor` or a Pretty Tensor holding the logits. labels: A rank 2 tf.float32 or tf.float64 tensor containing the labels. name: The optional name. loss_weight: A weight to scale the loss. Used when there are multiple losses....
4.005175
4.012972
0.998057
if labels is None: raise ValueError('Labels must be set') if per_example_weights is not None: per_example_weights = _convert_and_assert_per_example_weights_compatible( input_, per_example_weights, dtype=input_.dtype) return apply_regression( input_, tf.contrib.nn.d...
def sparse_cross_entropy(input_, labels, name=PROVIDED, loss_weight=None, per_example_weights=None)
Calculates the Cross Entropy of input_ vs labels. Args: input_: A rank 2 `Tensor` or a Pretty Tensor holding the logits. labels: A rank 1 integer `Tensor` with class ordinals name: The optional name. loss_weight: A weight to scale the loss. Used when there are multiple losses. per_example_w...
3.527226
3.594293
0.981341
if target is None: raise ValueError('target must be set') target = _convert_and_assert_tensors_compatible(input_, target) with tf.name_scope('stats'): selected, sum_retrieved, sum_relevant = _compute_precision_recall( input_, target, 0, per_example_weights) precision = selected / sum_retri...
def binary_cross_entropy_with_logits(input_, target, name=PROVIDED, loss_weight=None, per_example_weights=None, per_output_weights=None...
Calculates the binary cross entropy of the input_ vs inputs. Expects unscaled logits. Do not pass in results of sigmoid operation. Args: input_: A rank 2 Tensor or a Pretty Tensor holding the logits. target: A rank 2 tf.float32 or tf.float64 tensor containing class label probabilities. Note that bin...
3.000663
3.028735
0.990731
full = input_.fully_connected(num_classes, activation_fn=None, name=name, weights=weights, bias=bias, parameter_modifier=parameter_modifier) return full....
def softmax_classifier(input_, num_classes, labels=None, loss_weight=None, per_example_weights=None, weights=None, bias=tf.zeros_initializer(), parameter_modif...
Creates a fully-connected linear layer followed by a softmax. This returns `(softmax, loss)` where `loss` is the cross entropy loss. Args: input_: A rank 2 Tensor or a Pretty Tensor holding the activation before the logits (penultimate layer). num_classes: The number of classes. labels: The targ...
2.616655
2.941513
0.889561
if labels is not None: # Cache the current layer because we only want softmax to change the head. full = input_.as_layer() return SoftmaxResult(input_.softmax_activation(), full.cross_entropy( labels, name=name, ...
def softmax(input_, labels=None, name=PROVIDED, loss_weight=None, per_example_weights=None)
Applies softmax and if labels is not None, then it also adds a loss. Args: input_: A rank 2 Tensor or a Pretty Tensor holding the logits. labels: The target labels to learn as a float tensor. Use None to not include a training loss. name: The optional name. loss_weight: A scalar multiplier for...
5.964102
6.414456
0.929791
_ = name # Eliminate warning, name used for namescoping by PT. selected, sum_retrieved, sum_relevant = _compute_precision_recall( input_, labels, threshold, per_example_weights) if phase != Phase.train: dtype = tf.float32 # Create the variables in all cases so that the load logic is easier. ...
def evaluate_precision_recall(input_, labels, threshold=0.5, per_example_weights=None, name=PROVIDED, phase=Phase.train)
Computes the precision and recall of the prediction vs the labels. Args: input_: A rank 2 Tensor or a Pretty Tensor holding the result of the model. labels: The target labels to learn as a float tensor. threshold: The threshold to use to decide if the prediction is true. per_example_weights: A Tensor...
2.442052
2.501225
0.976342
my_parameters = {} if phase in (Phase.test, Phase.infer): dtype = tf.float32 # Create the variables using tf.Variable because we don't want to share. count = tf.Variable(tf.constant(0, dtype=dtype), name='count_%d' % topk, collections=[bookkeeper.GraphK...
def _eval_metric(input_, topk, correct_predictions, examples, phase)
Creates the standard tracking varibles if in test and returns accuracy.
3.184709
3.050847
1.043877
_ = name # Suppress lint if not (tf.float32.is_compatible_with(labels.dtype) or tf.float64.is_compatible_with(labels.dtype)): raise ValueError('labels must be floating point: %s.' % labels.dtype) correct_predictions, examples = _compute_average_correct(input_, ...
def evaluate_classifier_fraction(input_, labels, per_example_weights=None, topk=1, name=PROVIDED, phase=Phase.train)
Calculates the total of correct predictions and example count. In test and infer mode, this creates variables in the graph collection pt.GraphKeys.TEST_VARIABLES and does not add them to tf.GraphKeys.ALL_VARIABLES. This means that you must initialize them separately from tf.global_variables_initializer(). ...
5.275432
4.747776
1.111138
result = input_.evaluate_classifier_fraction( labels, per_example_weights=per_example_weights, topk=topk, name=name, phase=phase) return input_.with_tensor(result[0] / result[1], result.layer_parameters)
def evaluate_classifier(input_, labels, per_example_weights=None, topk=1, name=PROVIDED, phase=Phase.train)
Calculates the total ratio of correct predictions across all examples seen. In test and infer mode, this creates variables in the graph collection pt.GraphKeys.TEST_VARIABLES and does not add them to tf.GraphKeys.ALL_VARIABLES. This means that you must initialize them separately from tf.global_variables_initi...
4.718895
5.580128
0.845661
_ = name # Suppress lint if not (tf.int32.is_compatible_with(labels.dtype) or tf.int64.is_compatible_with(labels.dtype)): raise ValueError('Labels must be an integer type.: %s.' % labels.dtype) correct_predictions, examples = _compute_sparse_average_correct( input_, labels, per_example_wei...
def evaluate_classifier_fraction_sparse(input_, labels, per_example_weights=None, topk=1, name=PROVIDED, phase=Phase.tra...
Calculates the total of correct predictions and example count. In test and infer mode, this creates variables in the graph collection pt.GraphKeys.TEST_VARIABLES and does not add them to tf.GraphKeys.ALL_VARIABLES. This means that you must initialize them separately from tf.global_variables_initializer(). ...
5.537899
4.997041
1.108236
result = input_.evaluate_classifier_fraction_sparse( labels, per_example_weights=per_example_weights, topk=topk, name=name, phase=phase) return input_.with_tensor(result[0] / result[1], result.layer_parameters)
def evaluate_classifier_sparse(input_, labels, per_example_weights=None, topk=1, name=PROVIDED, phase=Phase.train)
Calculates the total ratio of correct predictions across all examples seen. In test and infer mode, this creates variables in the graph collection pt.GraphKeys.TEST_VARIABLES and does not add them to tf.GraphKeys.ALL_VARIABLES. This means that you must initialize them separately from tf.global_variables_initi...
4.480764
5.500625
0.814592
# To apply per_example_weights, we need to collapse each row to a scalar, but # we really want the sum. labels.get_shape().assert_is_compatible_with(input_.get_shape()) relevant = tf.to_float(tf.greater(labels, 0)) retrieved = tf.to_float(tf.greater(input_, threshold)) selected = relevant * retrieved ...
def _compute_precision_recall(input_, labels, threshold, per_example_weights)
Returns the numerator of both, the denominator of precision and recall.
2.639542
2.634504
1.001912
return _compute_sparse_average_correct( input_, tf.reshape(tf.argmax(labels, 1), [-1, 1]), per_example_weights, topk=topk)
def _compute_average_correct(input_, labels, per_example_weights, topk=1)
Returns the numerator and denominator of classifier accuracy.
3.34901
3.432101
0.97579
labels = tf.to_int64(labels) labels.get_shape().assert_is_compatible_with( [input_.get_shape()[0], None]) if topk == 1: predictions = tf.reshape(tf.argmax(input_, 1), [-1, 1]) in_topk = tf.reduce_any(tf.equal(labels, predictions), reduction_indices=[1]) else: # U...
def _compute_sparse_average_correct( input_, labels, per_example_weights, topk=1)
Returns the numerator and denominator of classifier accuracy.
3.362607
3.351165
1.003414
def _fn(cell_fn): result = prettytensor.RegisterCompoundOp(**kwargs)(cell_fn) method_name = kwargs.pop('method_name', cell_fn.__name__) if method_name.endswith('_cell'): method_name = method_name[:-5] method_name = 'sequence_' + method_name class _Sequence(prettytensor.VarStoreMeth...
def register_recurrent_cell(state_fn, **kwargs)
Decorator to register the current cell function with auxiliary functions. The only current auxauxiliaryilary function is `sequence_CELL_NAME` which applies the cell function across a sequence. Note, the cell_function must have arguments like: cell_fn(input_, state_list, *args, **kwargs) If it contains...
3.718539
3.463695
1.073576
# As a compound op, it needs to respect whether or not this is a sequential # builder. if input_layer.is_sequential_builder(): layer = input_layer.as_layer() else: layer = input_layer c, h = [prettytensor.wrap(state, layer.bookkeeper) for state in states] activation_input = layer.fully_connected(...
def lstm_cell(input_layer, states, num_units, bias=tf.zeros_initializer(), peephole=True, weights=None, phase=prettytensor.Phase.train, parameter_modifier=parameters.identity)
Long short-term memory cell (LSTM). Args: input_layer: The input layer. states: The current state of the network, as [[batch, num_units], [batch, num_units]] (c, h). num_units: How big is the hidden state. bias: An initializer for the bias or a Tensor. No bias if set to None. peephole: Whet...
2.829389
2.772233
1.020617
# As a compound op, it needs to respect whether or not this is a sequential # builder. if input_layer.is_sequential_builder(): layer = input_layer.as_layer() else: layer = input_layer # We start with bias of 1.0 to not reset and not udpate. # NB We compute activation_input and activation_state in...
def gru_cell(input_layer, state, num_units, bias=tf.zeros_initializer(), weights=None, phase=prettytensor.Phase.train, parameter_modifier=parameters.identity)
Gated recurrent unit memory cell (GRU). Args: input_layer: The input layer. state: The current state of the network. For GRUs, this is a list with one element (tensor) of shape [batch, num_units]. num_units: How big is the hidden state. bias: An initializer for the bias or a Tensor. No bias if ...
4.810167
4.734886
1.015899
state_saver = input_layer.bookkeeper.recurrent_state state_names = [STATE_NAME % name + '_%d' % i for i in xrange(len(state_shapes))] if hasattr(state_saver, 'add_state'): for state_name, state_shape in zip(state_names, state_shapes): initial_state = tf.zeros(state_shape[1:], dtype=i...
def unroll_state_saver(input_layer, name, state_shapes, template, lengths=None)
Unrolls the given function with state taken from the state saver. Args: input_layer: The input sequence. name: The name of this layer. state_shapes: A list of shapes, one for each state variable. template: A template with unbound variables for input and states that returns a RecurrentResult. ...
3.679936
3.69567
0.995743
timesteps = len(input_layer.sequence) if not timesteps: raise ValueError('Empty tensor sequence.') elif timesteps == 1: result = input_layer.sequence[0] else: result = tf.concat(input_layer.sequence, 0) return input_layer.with_tensor(result).with_defaults(unroll=timesteps)
def squash_sequence(input_layer)
Squashes a sequence into a single Tensor with dim 1 being time*batch. A sequence is an array of Tensors, which is not appropriate for most operations, this squashes them together into Tensor. Defaults are assigned such that cleave_sequence requires no args. Args: input_layer: The input layer. Returns: ...
3.796699
3.360654
1.12975
if unroll is None: raise ValueError('You must set unroll either here or in the defaults.') shape = input_layer.shape if shape[0] is not None and shape[0] % unroll != 0: raise ValueError('Must divide the split dimension evenly: %d mod %d != 0' % (shape[0], unroll)) if unroll <= ...
def cleave_sequence(input_layer, unroll=None)
Cleaves a tensor into a sequence, this is the inverse of squash. Recurrent methods unroll across an array of Tensors with each one being a timestep. This cleaves the first dim so that each it is an array of Tensors. It is the inverse of squash_sequence. Args: input_layer: The input layer. unroll: The...
3.478052
3.361145
1.034782
if not isinstance(num_nodes, tf.compat.integral_types): raise ValueError('num_nodes must be an integer: %s' % num_nodes) return [(STATE_NAME % name + '_0', tf.float32, num_nodes), (STATE_NAME % name + '_1', tf.float32, num_nodes)]
def lstm_state_tuples(num_nodes, name)
Convenience so that the names of the vars are defined in the same file.
3.099082
3.022283
1.025411
if not isinstance(num_nodes, tf.compat.integral_types): raise ValueError('num_nodes must be an integer: %s' % num_nodes) return [(STATE_NAME % name + '_0', tf.float32, num_nodes)]
def gru_state_tuples(num_nodes, name)
Convenience so that the names of the vars are defined in the same file.
4.851666
4.728952
1.02595
inputs = prettytensor.wrap_sequence(sequence_input.inputs, tensor_shape=shape) targets = prettytensor.wrap_sequence(sequence_input.targets) if save_state: bookkeeper.set_recurrent_state_saver(sequence_input) return inputs, targets
def create_sequence_pretty_tensor(sequence_input, shape=None, save_state=True)
Creates a PrettyTensor object for the given sequence. The first dimension is treated as a time-dimension * batch and a default is set for `unroll` and `state_saver`. TODO(eiderman): Remove shape. Args: sequence_input: A SequenceInput or StateSavingSequenceInput shape: The shape of each item in the se...
4.692307
4.408956
1.064267
ls = [self.output] ls.extend(self.state) return ls
def flatten(self)
Create a flattened version by putting output first and then states.
14.656115
6.46223
2.267965
if tf.get_default_graph() != self._graph: raise ValueError('The current default graph is different from the graph' ' used at construction time of RecurrentRunner.') if feed_dict is None: all_feeds_dict = {} else: all_feeds_dict = dict(feed_dict) all_feeds_di...
def run(self, fetch_list, feed_dict=None, sess=None)
Runs the graph with the provided feeds and fetches. This function wraps sess.Run(), but takes care of state saving and restoring by feeding in states and storing the new state values. Args: fetch_list: A list of requested output tensors. feed_dict: A dictionary of feeds - see Session.Run(). Opt...
2.666343
2.522803
1.056897
''' Return the best IP address for this device. Returns the first matching IP: - Lowest Loopback interface - Lowest SVI address/known IP ''' # Loopbacks - first interface if (len(self.loopbacks)): ips = self.loopbacks[0].ips ...
def get_ipaddr(self)
Return the best IP address for this device. Returns the first matching IP: - Lowest Loopback interface - Lowest SVI address/known IP
6.093117
3.24142
1.879768
''' If VPC is enabled, Return the VPC domain and interface name of the VPC peerlink. ''' if (self.vpc_vbtbl == None): self.vpc_vbtbl = self.snmpobj.get_bulk(OID_VPC_PEERLINK_IF) if ((self.vpc_vbtbl == None) | (len(self.vpc_vbtbl) == 0)): return (No...
def __get_vpc_info(self, ifarr)
If VPC is enabled, Return the VPC domain and interface name of the VPC peerlink.
5.519337
4.170361
1.323467
''' Return array of MAC addresses from single node at IP ''' if (ip == '0.0.0.0'): return None ret_macs = [] snmpobj = natlas_snmp(ip) # find valid credentials for this node if (snmpobj.get_cred(self.config.snmp_creds) == 0): retu...
def get_macs(self, ip, display_progress)
Return array of MAC addresses from single node at IP
5.141366
4.63475
1.109308
''' Return array of MAC addresses for a single VLAN from a single node at an IP ''' ret_macs = [] if (snmpobj == None): snmpobj = natlas_snmp(ip) if (snmpobj.get_cred(self.config.snmp_creds) == 0): return None if (ifname_vbtbl == N...
def get_macs_for_vlan(self, ip, vlan, display_progress=0, snmpobj=None, system_name=None, ifname_vbtbl=None)
Return array of MAC addresses for a single VLAN from a single node at an IP
3.418819
3.242551
1.054361
''' Format a hex MAC string to ASCII Args: mac_hex: Value from SNMP inc_dots: 1 to format as aabb.ccdd.eeff, 0 to format aabbccddeeff Returns: String representation of the mac_hex ''' v = mac_hex[2:] ret = '' for ...
def mac_hex_to_ascii(mac_hex, inc_dots)
Format a hex MAC string to ASCII Args: mac_hex: Value from SNMP inc_dots: 1 to format as aabb.ccdd.eeff, 0 to format aabbccddeeff Returns: String representation of the mac_hex
4.410309
2.128067
2.072449
''' Get the CAM table from a switch. Args: switch_ip IP address of the device node natlas_node from new_node() vlan Filter results by VLAN MAC Filter results by MAC address (regex) ...
def get_switch_macs(self, switch_ip=None, node=None, vlan=None, mac=None, port=None, verbose=0)
Get the CAM table from a switch. Args: switch_ip IP address of the device node natlas_node from new_node() vlan Filter results by VLAN MAC Filter results by MAC address (regex) port ...
3.132972
1.870895
1.674585
''' Get the ARP table from a switch. Args: switch_ip IP address of the device ip Filter results by IP (regex) mac Filter results by MAC (regex) interf Filter results by INTERFACE (regex) ...
def get_arp_table(self, switch_ip, ip=None, mac=None, interf=None, arp_type=None)
Get the ARP table from a switch. Args: switch_ip IP address of the device ip Filter results by IP (regex) mac Filter results by MAC (regex) interf Filter results by INTERFACE (regex) arp_type ...
2.60816
2.005768
1.30033
''' Generate the node text given the format string 'fmt' ''' fmt_proc = fmt # IF blocks while (1): if_block = re.search('<%if ([^%]*): ([^%]*)%>', fmt_proc) if (if_block == None): break # evaluate condition ...
def __get_node_text(self, diagram, node, fmt)
Generate the node text given the format string 'fmt'
2.340881
2.292208
1.021234
''' Discover the network starting at the defined root node IP. Recursively enumerate the network tree up to self.depth. Populates self.nodes[] as a list of discovered nodes in the network with self.root_node being the root. This function will discover the network with mi...
def discover(self, ip)
Discover the network starting at the defined root node IP. Recursively enumerate the network tree up to self.depth. Populates self.nodes[] as a list of discovered nodes in the network with self.root_node being the root. This function will discover the network with minimal information. ...
7.001867
3.993724
1.753218
''' Enumerate the discovered nodes from discover() and update the nodes in the array with additional info. ''' if (self.root_node == None): return if (self.verbose > 0): print('\nCollecting node details...') ni = 0 for n in self.n...
def discover_details(self)
Enumerate the discovered nodes from discover() and update the nodes in the array with additional info.
4.423059
3.985091
1.109902
''' Query this node. Return node details and if we already knew about it or if this is a new node. Don't save the node to the known list, just return info about it. Args: ip: IP Address of the node. host: Hostname of this kno...
def __query_node(self, ip, host)
Query this node. Return node details and if we already knew about it or if this is a new node. Don't save the node to the known list, just return info about it. Args: ip: IP Address of the node. host: Hostname of this known (if known from CD...
5.661522
3.649366
1.551371
''' Look for known nodes by IP and HOST. If found by HOST, add the IP if not already known. Return: node: Node, if found. Otherwise None. updated: 1=updated, 0=not updated ''' # already known by IP ? for ex in self.nodes: ...
def __get_known_node(self, ip, host)
Look for known nodes by IP and HOST. If found by HOST, add the IP if not already known. Return: node: Node, if found. Otherwise None. updated: 1=updated, 0=not updated
3.899567
2.203932
1.769368
''' Given a node, recursively enumerate its adjacencies until we reach the specified depth (>0). Args: node: natlas_node object to enumerate. depth: The depth left that we can go further away from the root. ''' if (node == None): re...
def __discover_node(self, node, depth)
Given a node, recursively enumerate its adjacencies until we reach the specified depth (>0). Args: node: natlas_node object to enumerate. depth: The depth left that we can go further away from the root.
4.178483
3.656108
1.142878
''' Determine if the node is already known by hostname. If it is, return it. ''' for n in self.nodes: if (n.name == hostname): return n return None
def __get_known_node_by_host(self, hostname)
Determine if the node is already known by hostname. If it is, return it.
4.969726
2.805923
1.771156
tmp_dir, tmp_prefix = os.path.split(tmpdir_prefix) new_file = os.path.join( tempfile.mkdtemp(prefix=tmp_prefix, dir=tmp_dir), os.path.basename(volume.resolved)) writable = True if volume.type == "CreateWritableFile" else False if secret_store: ...
def create_file_and_add_volume(self, runtime, # type: List[Text] volume, # type: MapperEnt host_outdir_tgt, # type: Optional[Text] secret_store, # type: Opt...
Create the file and add a mapping.
2.917641
2.704705
1.078728
host_outdir_tgt = None # type: Optional[Text] if vol.target.startswith(container_outdir + "/"): host_outdir_tgt = os.path.join( self.outdir, vol.target[len(container_outdir) + 1:]) if not host_outdir_tgt and not any_path_okay: rais...
def add_volumes(self, pathmapper, # type: PathMapper runtime, # type: List[Text] tmpdir_prefix, # type: Text secret_store=None, # type: Optional[SecretStore] any_path_okay=False # type: bool...
Append volume mappings to the runtime option list.
3.211035
3.182798
1.008872
# type: (Text, Text, bool, subprocess.Popen) -> None # Todo: consider switching to `docker create` / `docker start` # instead of `docker run` as `docker create` outputs the container ID # to stdout, but the container is frozen, thus allowing us to start the # monitoring ...
def docker_monitor(self, cidfile, tmpdir_prefix, cleanup_cidfile, process)
Record memory usage of the running Docker container.
3.482312
3.464164
1.005239
if rec.get("class") == "File": rec["path"] = op(rec["path"]) for d in rec: adjustFiles(rec[d], op) if isinstance(rec, MutableSequence): for d in rec: adjustFiles(d, op)
def adjustFiles(rec, op): # type: (Any, Union[Callable[..., Any], partial[Any]]) -> None if isinstance(rec, MutableMapping)
Apply a mapping function to each File path in the object `rec`.
3.081656
2.549401
1.208777
# type: (Any, Any, Optional[Text], Optional[Text]) -> Text if valueFrom is not None: return "pass" if linkMerge is None: if can_assign_src_to_sink(srctype, sinktype, strict=True): return "pass" if can_assign_src_to_sink(srctype, sinktype, strict=False): ...
def check_types(srctype, sinktype, linkMerge, valueFrom)
Check if the source and sink types are "pass", "warning", or "exception".
3.399219
3.101763
1.095899
# type: (Any) -> Any if isinstance(src, MutableSequence): return [merge_flatten_type(t) for t in src] if isinstance(src, MutableMapping) and src.get("type") == "array": return src return {"items": src, "type": "array"}
def merge_flatten_type(src)
Return the merge flattened type of the source type
3.786752
4.130335
0.916815
return True if isinstance(src, MutableMapping) and isinstance(sink, MutableMapping): if sink.get("not_connected") and strict: return False if src["type"] == "array" and sink["type"] == "array": return can_assign_src_to_sink(src["items"], sink["items"], strict) ...
def can_assign_src_to_sink(src, sink, strict=False): # type: (Any, Any, bool) -> bool if src == "Any" or sink == "Any"
Check for identical type specifications, ignoring extra keys like inputBinding. src: admissible source types sink: admissible sink types In non-strict comparison, at least one source type must match one sink type. In strict comparison, all source types must match at least one sink type.
2.082447
2.100381
0.991461
# type: (MutableMapping[Text, Any], MutableMapping[Text, Any], bool) -> bool def _rec_fields(rec): # type: (MutableMapping[Text, Any]) -> MutableMapping[Text, Any] out = {} for field in rec["fields"]: name = shortname(field["name"]) out[name] = field["type"] ...
def _compare_records(src, sink, strict=False)
Compare two records, ensuring they have compatible fields. This handles normalizing record names, which will be relative to workflow step, so that they can be compared.
3.079511
3.211915
0.958777
# type: (Dict[Text, Any], List[Dict[Text, Any]], Text) -> Dict[Text, List[SrcSink]] # sourceField is either "soure" or "outputSource" validation = {"warning": [], "exception": []} # type: Dict[Text, List[SrcSink]] for sink in sinks: if sourceField in sink: valueFrom = sink.get...
def check_all_types(src_dict, sinks, sourceField)
Given a list of sinks, check if their types match with the types of their sources.
3.235249
3.215622
1.006104
self.final_status.append(process_status) self.final_output.append(out)
def output_callback(self, out, process_status)
Collect the final status and outputs.
4.272073
3.279657
1.302597
raise WorkflowException("Must provide 'basedir' in runtimeContext") finaloutdir = None # Type: Optional[Text] original_outdir = runtime_context.outdir if isinstance(original_outdir, string_types): finaloutdir = os.path.abspath(original_outdir) runtime_context = ...
def execute(self, process, # type: Process job_order_object, # type: Dict[Text, Any] runtime_context, # type: RuntimeContext logger=_logger, ): # type: (...) -> Tuple[Optional[Dict[Text, Any]], Text] if not r...
Execute the process.
3.288854
3.271262
1.005378
if request[rsc+"Min"] > maxrsc[rsc]: raise WorkflowException( "Requested at least %d %s but only %d available" % (request[rsc+"Min"], rsc, maxrsc[rsc])) if request[rsc+"Max"] < maxrsc[rsc]: result[rsc] = request[rsc+"Max"] ...
def select_resources(self, request, runtime_context): # pylint: disable=unused-argument # type: (Dict[str, int], RuntimeContext) -> Dict[str, int] result = {} # type: Dict[str, int] maxrsc = { "cores": self.max_cores, "ram": self.max_ram } for r...
Naïve check for available cpu cores and memory.
2.694724
2.294036
1.174665
try: job.run(runtime_context) except WorkflowException as err: _logger.exception("Got workflow error") self.exceptions.append(err) except Exception as err: # pylint: disable=broad-except _logger.exception("Got workflow error") ...
def _runner(self, job, runtime_context)
Job running thread.
3.501785
3.388977
1.033287
with self.pending_jobs_lock: self.pending_jobs.append(job) with self.pending_jobs_lock: n = 0 while (n+1) <= len(self.pending_jobs): job = self.pending_jobs[n] if isinstance(job, JobBase): if ((job.builder.r...
def run_job(self, job, # type: Union[JobBase, WorkflowJob, None] runtime_context # type: RuntimeContext ): # type: (...) -> None if job is not None
Execute a single Job in a seperate thread.
2.412224
2.377699
1.01452
# type: (RuntimeContext) -> None if runtime_context.workflow_eval_lock is not None: runtime_context.workflow_eval_lock.wait() if self.exceptions: raise self.exceptions[0]
def wait_for_next_completion(self, runtime_context)
Wait for jobs to finish.
4.557916
4.146678
1.099173
# type: (List[Text], Text, Text, bool) -> None runtime.append(u"--volume={}:{}:{}".format( docker_windows_path_adjust(source), target, "rw" if writable else "ro"))
def append_volume(runtime, source, target, writable=False)
Add binding arguments to the runtime list.
6.650911
5.935457
1.120539
_check_docker_machine_path(docker_windows_path_adjust( volume.resolved)) self.append_volume(runtime, volume.resolved, volume.target)
def add_file_or_directory_volume(self, runtime, # type: List[Text] volume, # type: MapperEnt host_outdir_tgt # type: Optional[Text] ): # type: (...) -> N...
Append volume a file/dir mapping to the runtime option list.
19.358959
15.635711
1.238125