INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Poll until all reservations completed then return cluster_info.
def await_reservations(self): """Poll until all reservations completed, then return cluster_info.""" done = False while not done: done = self._request('QUERY') time.sleep(1) return self.get_reservations()
Serializes an image/ label as a TFExample byte string
def toTFExample(image, label): """Serializes an image/label as a TFExample byte string""" example = tf.train.Example( features=tf.train.Features( feature={ 'label': tf.train.Feature(int64_list=tf.train.Int64List(value=label.astype("int64"))), 'image': tf.train.Feature(int64_list=tf.train.I...
Deserializes a TFExample from a byte string
def fromTFExample(bytestr): """Deserializes a TFExample from a byte string""" example = tf.train.Example() example.ParseFromString(bytestr) return example
Writes MNIST image/ label vectors into parallelized files on HDFS
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions): """Writes MNIST image/label vectors into parallelized files on HDFS""" # load MNIST gzip into memory with open(input_images, 'rb') as f: images = numpy.array(mnist.extract_images(f)) with open(input_labels, 'rb') as f: if f...
Reads/ verifies previously created output
def readMNIST(sc, output, format): """Reads/verifies previously created output""" output_images = output + "/images" output_labels = output + "/labels" imageRDD = None labelRDD = None if format == "pickle": imageRDD = sc.pickleFile(output_images) labelRDD = sc.pickleFile(output_labels) elif form...
Build Inception v3 model architecture.
def inference(images, num_classes, for_training=False, restore_logits=True, scope=None): """Build Inception v3 model architecture. See here for reference: http://arxiv.org/abs/1512.00567 Args: images: Images returned from inputs() or distorted_inputs(). num_classes: number of classes f...
Adds all losses for the model.
def loss(logits, labels, batch_size=None): """Adds all losses for the model. Note the final loss is not returned. Instead, the list of losses are collected by slim.losses. The losses are accumulated in tower_loss() and summed to calculate the total loss. Args: logits: List of logits from inference(). Ea...
Convenience function to create a Tensorflow - compatible absolute HDFS path from relative paths
def hdfs_path(ctx, path): """Convenience function to create a Tensorflow-compatible absolute HDFS path from relative paths Args: :ctx: TFNodeContext containing the metadata specific to this node in the cluster. :path: path to convert Returns: An absolute path prefixed with the correct filesystem sch...
Function that wraps the creation of TensorFlow tf. train. Server for a node in a distributed TensorFlow cluster.
def start_cluster_server(ctx, num_gpus=1, rdma=False): """Function that wraps the creation of TensorFlow ``tf.train.Server`` for a node in a distributed TensorFlow cluster. This is intended to be invoked from within the TF ``map_fun``, replacing explicit code to instantiate ``tf.train.ClusterSpec`` and ``tf.trai...
Convenience function to export a saved_model using provided arguments
def export_saved_model(sess, export_dir, tag_set, signatures): """Convenience function to export a saved_model using provided arguments The caller specifies the saved_model signatures in a simplified python dictionary form, as follows:: signatures = { 'signature_def_key': { 'inputs': { 'input_te...
Gets a batch of items from the input RDD.
def next_batch(self, batch_size): """Gets a batch of items from the input RDD. If multiple tensors are provided per row in the input RDD, e.g. tuple of (tensor1, tensor2, ..., tensorN) and: * no ``input_mapping`` was provided to the DataFeed constructor, this will return an array of ``batch_size`` tuples,...
Push a batch of output results to the Spark output RDD of TFCluster. inference ().
def batch_results(self, results): """Push a batch of output results to the Spark output RDD of ``TFCluster.inference()``. Note: this currently expects a one-to-one mapping of input to output data, so the length of the ``results`` array should match the length of the previously retrieved batch of input data...
Terminate data feeding early.
def terminate(self): """Terminate data feeding early. Since TensorFlow applications can often terminate on conditions unrelated to the training data (e.g. steps, accuracy, etc), this method signals the data feeding process to ignore any further incoming data. Note that Spark itself does not have a mechani...
Define/ export a single - node TF graph for inferencing
def export_fun(args): """Define/export a single-node TF graph for inferencing""" # Input placeholder for inferencing x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS * IMAGE_PIXELS], name="x") # Variables of the hidden layer hid_w = tf.Variable(tf.truncated_normal([IMAGE_PIXELS * IMAGE_PIXELS, hidden_units...
Train Inception on a dataset for a number of steps.
def train(target, dataset, cluster_spec, ctx): """Train Inception on a dataset for a number of steps.""" # Number of workers and parameter servers are infered from the workers and ps # hosts string. num_workers = len(cluster_spec.as_dict()['worker']) num_parameter_servers = len(cluster_spec.as_dict()['ps']) ...
Evaluate model on Dataset for a number of steps.
def export(_): FLAGS = tf.app.flags.FLAGS """Evaluate model on Dataset for a number of steps.""" #with tf.Graph().as_default(): tf.reset_default_graph() def preprocess_image(image_buffer): """Preprocess JPEG encoded bytes to 3D float Tensor.""" # Decode the string as an RGB JPEG. # Note that th...
* DEPRECATED *. Allocates first available GPU using cudaSetDevice () or returns 0 otherwise.
def _get_gpu(): """*DEPRECATED*. Allocates first available GPU using cudaSetDevice(), or returns 0 otherwise.""" # Note: this code executes, but Tensorflow subsequently complains that the "current context was not created by the StreamExecutor cuda_driver API" system = platform.system() if system == "Linux": ...
Get list of free GPUs according to nvidia - smi.
def get_gpus(num_gpu=1, worker_index=-1): """Get list of free GPUs according to nvidia-smi. This will retry for ``MAX_RETRIES`` times until the requested number of GPUs are available. Args: :num_gpu: number of GPUs desired. :worker_index: index "hint" for allocation of available GPUs. Returns: Co...
Get available GPUs according to utilization thresholds.
def _get_free_gpu(max_gpu_utilization=40, min_free_memory=0.5, num_gpu=1): """Get available GPUs according to utilization thresholds. Args: :max_gpu_utilization: percent utilization threshold to consider a GPU "free" :min_free_memory: percent free memory to consider a GPU "free" :num_gpu: number of req...
Build an Example proto for an example.
def _convert_to_example(filename, image_buffer, label, text, height, width): """Build an Example proto for an example. Args: filename: string, path to an image file, e.g., '/path/to/example.JPG' image_buffer: string, JPEG encoding of RGB image label: integer, identifier for the ground truth for the net...
Processes and saves list of images as TFRecord in 1 thread.
def _process_image_files_batch(coder, thread_index, ranges, name, filenames, texts, labels, num_shards): """Processes and saves list of images as TFRecord in 1 thread. Args: coder: instance of ImageCoder to provide TensorFlow image coding utils. thread_index: integer, unique ...
Process and save list of images as TFRecord of Example protos.
def _process_image_files(name, filenames, texts, labels, num_shards): """Process and save list of images as TFRecord of Example protos. Args: name: string, unique identifier specifying the data set filenames: list of strings; each string is a path to an image file texts: list of strings; each string is...
Build a list of all images files and labels in the data set.
def _find_image_files(data_dir, labels_file): """Build a list of all images files and labels in the data set. Args: data_dir: string, path to the root directory of images. Assumes that the image data set resides in JPEG files located in the following directory structure. data_dir/dog/anot...
Process a complete data set and save it as a TFRecord.
def _process_dataset(name, directory, num_shards, labels_file): """Process a complete data set and save it as a TFRecord. Args: name: string, unique identifier specifying the data set. directory: string, root path to the data set. num_shards: integer number of shards for this data set. labels_file:...
Generate batches of ImageNet images for evaluation.
def inputs(dataset, batch_size=None, num_preprocess_threads=None): """Generate batches of ImageNet images for evaluation. Use this function as the inputs for evaluating a network. Note that some (minimal) image preprocessing occurs during evaluation including central cropping and resizing of the image to fit ...
Generate batches of distorted versions of ImageNet images.
def distorted_inputs(dataset, batch_size=None, num_preprocess_threads=None): """Generate batches of distorted versions of ImageNet images. Use this function as the inputs for training a network. Distorting images provides a useful technique for augmenting the data set during training in order to make the netw...
Decode a JPEG string into one 3 - D float image Tensor.
def decode_jpeg(image_buffer, scope=None): """Decode a JPEG string into one 3-D float image Tensor. Args: image_buffer: scalar string Tensor. scope: Optional scope for name_scope. Returns: 3-D float Tensor with values ranging from [0, 1). """ with tf.name_scope(values=[image_buffer], name=scope, ...
Distort the color of the image.
def distort_color(image, thread_id=0, scope=None): """Distort the color of the image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a distinct orderin...
Distort one image for training a network.
def distort_image(image, height, width, bbox, thread_id=0, scope=None): """Distort one image for training a network. Distorting images provides a useful technique for augmenting the data set during training in order to make the network invariant to aspects of the image that do not effect the label. Args: ...
Prepare one image for evaluation.
def eval_image(image, height, width, scope=None): """Prepare one image for evaluation. Args: image: 3-D float Tensor height: integer width: integer scope: Optional scope for name_scope. Returns: 3-D float Tensor of prepared image. """ with tf.name_scope(values=[image, height, width], name...
Decode and preprocess one image for evaluation or training.
def image_preprocessing(image_buffer, bbox, train, thread_id=0): """Decode and preprocess one image for evaluation or training. Args: image_buffer: JPEG encoded string Tensor bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates a...
Parses an Example proto containing a training example of an image.
def parse_example_proto(example_serialized): """Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields: image/height: 4...
Contruct batches of training or evaluation examples from the image dataset.
def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None, num_readers=1): """Contruct batches of training or evaluation examples from the image dataset. Args: dataset: instance of Dataset class specifying the dataset. See dataset.py for details. batch_size: integer ...
Download external libraries from PyPI to SPARK_EC2_DIR/ lib/ and prepend them to our PATH.
def setup_external_libs(libs): """ Download external libraries from PyPI to SPARK_EC2_DIR/lib/ and prepend them to our PATH. """ PYPI_URL_PREFIX = "https://pypi.python.org/packages/source" SPARK_EC2_LIB_DIR = os.path.join(SPARK_EC2_DIR, "lib") if not os.path.exists(SPARK_EC2_LIB_DIR): p...
Get the EC2 instances in an existing cluster if available. Returns a tuple of lists of EC2 instance objects for the masters and slaves.
def get_existing_cluster(conn, opts, cluster_name, die_on_error=True): """ Get the EC2 instances in an existing cluster if available. Returns a tuple of lists of EC2 instance objects for the masters and slaves. """ print("Searching for existing cluster {c} in region {r}...".format( c=clust...
Check if SSH is available on a host.
def is_ssh_available(host, opts, print_ssh_output=True): """ Check if SSH is available on a host. """ s = subprocess.Popen( ssh_command(opts) + ['-t', '-t', '-o', 'ConnectTimeout=3', '%s@%s' % (opts.user, host), stringify_command('true')], stdout=subprocess.P...
Check if SSH is available on all the instances in a cluster.
def is_cluster_ssh_available(cluster_instances, opts): """ Check if SSH is available on all the instances in a cluster. """ for i in cluster_instances: dns_name = get_dns_name(i, opts.private_ips) if not is_ssh_available(host=dns_name, opts=opts): return False else: ...
Wait for all the instances in the cluster to reach a designated state.
def wait_for_cluster_state(conn, opts, cluster_instances, cluster_state): """ Wait for all the instances in the cluster to reach a designated state. cluster_instances: a list of boto.ec2.instance.Instance cluster_state: a string representing the desired state of all the instances in the cluster ...
Instruction to download and extract the tarball from Flowers website.
def download_message(self): """Instruction to download and extract the tarball from Flowers website.""" print('Failed to find any ImageNet %s files'% self.subset) print('') print('If you have already downloaded and processed the data, then make ' 'sure to set --data_dir to point to the direct...
Add supervised learning flags as well as wide - deep model type.
def define_wide_deep_flags(): """Add supervised learning flags, as well as wide-deep model type.""" flags_core.define_base() flags_core.define_benchmark() flags_core.define_performance( num_parallel_calls=False, inter_op=True, intra_op=True, synthetic_data=False, max_train_steps=False, dtype=False, ...
Export to SavedModel format.
def export_model(model, model_type, export_dir, model_column_fn): """Export to SavedModel format. Args: model: Estimator object model_type: string indicating model type. "wide", "deep" or "wide_deep" export_dir: directory to export the model. model_column_fn: Function to generate model feature colu...
Define training loop.
def run_loop(name, train_input_fn, eval_input_fn, model_column_fn, build_estimator_fn, flags_obj, tensors_to_log, early_stop=False): """Define training loop.""" model_helpers.apply_clean(flags.FLAGS) model = build_estimator_fn( model_dir=flags_obj.model_dir, model_type=flags_obj.model_type, ...
Calculate the total loss on a single tower running the ImageNet model.
def _tower_loss(images, labels, num_classes, scope, reuse_variables=None): """Calculate the total loss on a single tower running the ImageNet model. We perform 'batch splitting'. This means that we cut up a batch across multiple GPU's. For instance, if the batch size = 32 and num_gpus = 2, then each tower will...
Train on dataset for a number of steps.
def train(dataset): """Train on dataset for a number of steps.""" with tf.Graph().as_default(), tf.device('/cpu:0'): # Create a variable to count the number of train() calls. This equals the # number of batches processed * FLAGS.num_gpus. global_step = tf.get_variable( 'global_step', [], ...
Adds a Batch Normalization layer.
def batch_norm(inputs, decay=0.999, center=True, scale=False, epsilon=0.001, moving_vars='moving_vars', activation=None, is_training=True, trainable=True, restore=True, s...
Converts int_or_tuple to height width.
def _two_element_tuple(int_or_tuple): """Converts `int_or_tuple` to height, width. Several of the functions that follow accept arguments as either a tuple of 2 integers or a single integer. A single integer indicates that the 2 values of the tuple are the same. This functions normalizes the input value by ...
Adds a 2D convolution followed by an optional batch_norm layer.
def conv2d(inputs, num_filters_out, kernel_size, stride=1, padding='SAME', activation=tf.nn.relu, stddev=0.01, bias=0.0, weight_decay=0, batch_norm_params=None, is_training=True, trainable=True, ...
Adds a fully connected layer followed by an optional batch_norm layer.
def fc(inputs, num_units_out, activation=tf.nn.relu, stddev=0.01, bias=0.0, weight_decay=0, batch_norm_params=None, is_training=True, trainable=True, restore=True, scope=None, reuse=None): """Adds a fully connected layer followed by an optio...
Transform numeric labels into onehot_labels.
def one_hot_encoding(labels, num_classes, scope=None): """Transform numeric labels into onehot_labels. Args: labels: [batch_size] target labels. num_classes: total number of classes. scope: Optional scope for name_scope. Returns: one hot encoding of the labels. """ with tf.name_scope(scope, '...
Adds a Max Pooling layer.
def max_pool(inputs, kernel_size, stride=2, padding='VALID', scope=None): """Adds a Max Pooling layer. It is assumed by the wrapper that the pooling is only done per image and not in depth or batch. Args: inputs: a tensor of size [batch_size, height, width, depth]. kernel_size: a list of length 2: [ke...
Returns a dropout layer applied to the input.
def dropout(inputs, keep_prob=0.5, is_training=True, scope=None): """Returns a dropout layer applied to the input. Args: inputs: the tensor to pass to the Dropout layer. keep_prob: the probability of keeping each input unit. is_training: whether or not the model is in training mode. If so, dropout is ...
Flattens the input while maintaining the batch_size.
def flatten(inputs, scope=None): """Flattens the input while maintaining the batch_size. Assumes that the first dimension represents the batch. Args: inputs: a tensor of size [batch_size, ...]. scope: Optional scope for name_scope. Returns: a flattened tensor with shape [batch_size, k]. Raise...
Build a sequential Tower starting from inputs by using an op repeatedly.
def repeat_op(repetitions, inputs, op, *args, **kwargs): """Build a sequential Tower starting from inputs by using an op repeatedly. It creates new scopes for each operation by increasing the counter. Example: given repeat_op(3, _, ops.conv2d, 64, [3, 3], scope='conv1') it will repeat the given op under the ...
Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio event loop. The wrapped function catches all unhandled exceptions and reports them to the exception future which consumers can await upon to listen for unhandled exceptions.
def do_rpc(self, name: str, rpc_function: Callable[..., Awaitable[None]]) -> Callable[..., Awaitable[None]]: """ Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio event loop. The wrapped function catches all unhandled exceptions and reports them to t...
registerResource registers a new resource object with a given type t and name. It returns the auto - generated URN and the ID that will resolve after the deployment has completed. All properties will be initialized to property objects that the registration operation will resolve at the right time ( or remain unresolved...
def register_resource(res: 'Resource', ty: str, name: str, custom: bool, props: 'Inputs', opts: Optional['ResourceOptions']): """ registerResource registers a new resource object with a given type t and name. It returns the auto-generated URN and the ID that will resolve after the deployment has completed....
Configure sets the current ambient settings bag to the one given.
def configure(settings: Settings): """ Configure sets the current ambient settings bag to the one given. """ if not settings or not isinstance(settings, Settings): raise TypeError('Settings is expected to be non-None and of type Settings') global SETTINGS # pylint: disable=global-statement ...
Returns the current project name.
def get_project() -> Optional[str]: """ Returns the current project name. """ project = SETTINGS.project if not project: require_test_mode_enabled() raise RunError('Missing project name; for test mode, please set PULUMI_NODEJS_PROJECT') return project
Returns the current stack name.
def get_stack() -> Optional[str]: """ Returns the current stack name. """ stack = SETTINGS.stack if not stack: require_test_mode_enabled() raise RunError('Missing stack name; for test mode, please set PULUMI_NODEJS_STACK') return stack
Returns the current resource monitoring service client for RPC communications.
def get_monitor() -> Optional[resource_pb2_grpc.ResourceMonitorStub]: """ Returns the current resource monitoring service client for RPC communications. """ monitor = SETTINGS.monitor if not monitor: require_test_mode_enabled() return monitor
Serializes an arbitrary Input bag into a Protobuf structure keeping track of the list of dependent resources in the deps list. Serializing properties is inherently async because it awaits any futures that are contained transitively within the input bag.
async def serialize_properties(inputs: 'Inputs', property_deps: Dict[str, List['Resource']], input_transformer: Optional[Callable[[str], str]] = None) -> struct_pb2.Struct: """ Serializes an arbitrary Input bag into a Protobuf structure, keeping trac...
Serializes a single Input into a form suitable for remoting to the engine awaiting any futures required to do so.
async def serialize_property(value: 'Input[Any]', deps: List['Resource'], input_transformer: Optional[Callable[[str], str]] = None) -> Any: """ Serializes a single Input into a form suitable for remoting to the engine, awaiting any futures required t...
Deserializes a protobuf struct_pb2. Struct into a Python dictionary containing normal Python types.
def deserialize_properties(props_struct: struct_pb2.Struct) -> Any: """ Deserializes a protobuf `struct_pb2.Struct` into a Python dictionary containing normal Python types. """ # Check out this link for details on what sort of types Protobuf is going to generate: # https://developers.google.com/...
Deserializes a single protobuf value ( either Struct or ListValue ) into idiomatic Python values.
def deserialize_property(value: Any) -> Any: """ Deserializes a single protobuf value (either `Struct` or `ListValue`) into idiomatic Python values. """ if value == UNKNOWN: return None # ListValues are projected to lists if isinstance(value, struct_pb2.ListValue): return [d...
Recursively rewrite keys of objects returned by the engine to conform with a naming convention specified by the resource s implementation of translate_output_property.
def translate_output_properties(res: 'Resource', output: Any) -> Any: """ Recursively rewrite keys of objects returned by the engine to conform with a naming convention specified by the resource's implementation of `translate_output_property`. If output is a `dict`, every key is translated using `trans...
Resolves all outputs with resolvers exceptionally using the given exception as the reason why the resolver has failed to resolve.
def resolve_outputs_due_to_exception(resolvers: Dict[str, Resolver], exn: Exception): """ Resolves all outputs with resolvers exceptionally, using the given exception as the reason why the resolver has failed to resolve. :param resolvers: Resolvers associated with a resource's outputs. :param exn: ...
Returns an optional configuration value by its key or None if it doesn t exist.
def get(self, key: str) -> Optional[str]: """ Returns an optional configuration value by its key, or None if it doesn't exist. :param str key: The requested configuration key. :return: The configuration key's value, or None if one does not exist. :rtype: Optional[str] ""...
Returns an optional configuration value as a bool by its key or None if it doesn t exist. If the configuration value isn t a legal boolean this function will throw an error.
def get_bool(self, key: str) -> Optional[bool]: """ Returns an optional configuration value, as a bool, by its key, or None if it doesn't exist. If the configuration value isn't a legal boolean, this function will throw an error. :param str key: The requested configuration key. ...
Returns an optional configuration value as an int by its key or None if it doesn t exist. If the configuration value isn t a legal int this function will throw an error.
def get_int(self, key: str) -> Optional[int]: """ Returns an optional configuration value, as an int, by its key, or None if it doesn't exist. If the configuration value isn't a legal int, this function will throw an error. :param str key: The requested configuration key. :retur...
Returns an optional configuration value as a float by its key or None if it doesn t exist. If the configuration value isn t a legal float this function will throw an error.
def get_float(self, key: str) -> Optional[float]: """ Returns an optional configuration value, as a float, by its key, or None if it doesn't exist. If the configuration value isn't a legal float, this function will throw an error. :param str key: The requested configuration key. ...
Returns a configuration value by its given key. If it doesn t exist an error is thrown.
def require(self, key: str) -> str: """ Returns a configuration value by its given key. If it doesn't exist, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's value. :rtype: str :raises ConfigMissingError: The configur...
Returns a configuration value as a bool by its given key. If it doesn t exist or the configuration value is not a legal bool an error is thrown.
def require_bool(self, key: str) -> bool: """ Returns a configuration value, as a bool, by its given key. If it doesn't exist, or the configuration value is not a legal bool, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's v...
Returns a configuration value as an int by its given key. If it doesn t exist or the configuration value is not a legal int an error is thrown.
def require_int(self, key: str) -> int: """ Returns a configuration value, as an int, by its given key. If it doesn't exist, or the configuration value is not a legal int, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's valu...
Returns a configuration value as a float by its given key. If it doesn t exist or the configuration value is not a legal number an error is thrown.
def require_float(self, key: str) -> float: """ Returns a configuration value, as a float, by its given key. If it doesn't exist, or the configuration value is not a legal number, an error is thrown. :param str key: The requested configuration key. :return: The configuration ke...
Decorator to annotate the Asset class. Registers the decorated class as the Asset known type.
def asset(class_obj: type) -> type: """ Decorator to annotate the Asset class. Registers the decorated class as the Asset known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _asset_resource_type _asset_resource_type = class_obj return class_obj
Decorator to annotate the FileAsset class. Registers the decorated class as the FileAsset known type.
def file_asset(class_obj: type) -> type: """ Decorator to annotate the FileAsset class. Registers the decorated class as the FileAsset known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _file_asset_resource_type _file_asset_resource_type = class_obj ret...
Decorator to annotate the StringAsset class. Registers the decorated class as the StringAsset known type.
def string_asset(class_obj: type) -> type: """ Decorator to annotate the StringAsset class. Registers the decorated class as the StringAsset known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _string_asset_resource_type _string_asset_resource_type = class_o...
Decorator to annotate the RemoteAsset class. Registers the decorated class as the RemoteAsset known type.
def remote_asset(class_obj: type) -> type: """ Decorator to annotate the RemoteAsset class. Registers the decorated class as the RemoteAsset known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _remote_asset_resource_type _remote_asset_resource_type = class_o...
Decorator to annotate the Archive class. Registers the decorated class as the Archive known type.
def archive(class_obj: type) -> type: """ Decorator to annotate the Archive class. Registers the decorated class as the Archive known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _archive_resource_type _archive_resource_type = class_obj return class_obj
Decorator to annotate the AssetArchive class. Registers the decorated class as the AssetArchive known type.
def asset_archive(class_obj: type) -> type: """ Decorator to annotate the AssetArchive class. Registers the decorated class as the AssetArchive known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _asset_archive_resource_type _asset_archive_resource_type = cl...
Decorator to annotate the FileArchive class. Registers the decorated class as the FileArchive known type.
def file_archive(class_obj: type) -> type: """ Decorator to annotate the FileArchive class. Registers the decorated class as the FileArchive known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _file_archive_resource_type _file_archive_resource_type = class_o...
Decorator to annotate the RemoteArchive class. Registers the decorated class as the RemoteArchive known type.
def remote_archive(class_obj: type) -> type: """ Decorator to annotate the RemoteArchive class. Registers the decorated class as the RemoteArchive known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _remote_archive_resource_type _remote_archive_resource_type...
Decorator to annotate the CustomResource class. Registers the decorated class as the CustomResource known type.
def custom_resource(class_obj: type) -> type: """ Decorator to annotate the CustomResource class. Registers the decorated class as the CustomResource known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _custom_resource_type _custom_resource_type = class_obj ...
Logs a message to the Pulumi CLI s debug channel associating it with a resource and stream_id if provided.
def debug(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None: """ Logs a message to the Pulumi CLI's debug channel, associating it with a resource and stream_id if provided. :param str msg: The message to send to the Pulumi CLI. :param Optional[Resource] resou...
Logs a message to the Pulumi CLI s info channel associating it with a resource and stream_id if provided.
def info(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None: """ Logs a message to the Pulumi CLI's info channel, associating it with a resource and stream_id if provided. :param str msg: The message to send to the Pulumi CLI. :param Optional[Resource] resourc...
Logs a message to the Pulumi CLI s warning channel associating it with a resource and stream_id if provided.
def warn(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None: """ Logs a message to the Pulumi CLI's warning channel, associating it with a resource and stream_id if provided. :param str msg: The message to send to the Pulumi CLI. :param Optional[Resource] reso...
Logs a message to the Pulumi CLI s error channel associating it with a resource and stream_id if provided.
def error(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None): """ Logs a message to the Pulumi CLI's error channel, associating it with a resource and stream_id if provided. :param str msg: The message to send to the Pulumi CLI. :param Optional[Resource] resource: If ...
Returns the environment map that will be used for config checking when variables aren t set.
def get_config_env() -> Dict[str, Any]: """ Returns the environment map that will be used for config checking when variables aren't set. """ if 'PULUMI_CONFIG' in os.environ: env_config = os.environ['PULUMI_CONFIG'] return json.loads(env_config) return dict()
Returns a scrubbed environment variable key PULUMI_CONFIG_<k > that can be used for setting explicit varaibles. This is unlike PULUMI_CONFIG which is just a JSON - serialized bag.
def get_config_env_key(k: str) -> str: """ Returns a scrubbed environment variable key, PULUMI_CONFIG_<k>, that can be used for setting explicit varaibles. This is unlike PULUMI_CONFIG which is just a JSON-serialized bag. """ env_key = '' for c in k: if c == '_' or 'A' <= c <= 'Z' or '0...
Returns a configuration variable s value or None if it is unset.
def get_config(k: str) -> Any: """ Returns a configuration variable's value or None if it is unset. """ # If the config has been set explicitly, use it. if k in list(CONFIG.keys()): return CONFIG[k] # If there is a specific PULUMI_CONFIG_<k> environment variable, use it. env_key = g...
Run the given function inside of a new stack resource. This ensures that any stack export calls will end up as output properties on the resulting stack component in the checkpoint file. This is meant for internal runtime use only and is used by the Python SDK entrypoint program.
async def run_in_stack(func: Callable): """ Run the given function inside of a new stack resource. This ensures that any stack export calls will end up as output properties on the resulting stack component in the checkpoint file. This is meant for internal runtime use only and is used by the Python SD...
Export a stack output with a given name and value.
def output(self, name: str, value: Any): """ Export a stack output with a given name and value. """ self.outputs[name] = value
invoke dynamically invokes the function tok which is offered by a provider plugin. The inputs can be a bag of computed values ( Ts or Awaitable [ T ] s ) and the result is a Awaitable [ Any ] that resolves when the invoke finishes.
def invoke(tok: str, props: Inputs, opts: InvokeOptions = None) -> Awaitable[Any]: """ invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that resolves when the invoke ...
Exports a named stack output.
def export(name: str, value: Any): """ Exports a named stack output. :param str name: The name to assign to this output. :param Any value: The value of this output. """ stack = get_root_resource() if stack is not None: stack.output(name, value)
Fetches the provider for the given module member if this resource has been provided a specific provider for the given module member.
def get_provider(self, module_member: str) -> Optional['ProviderResource']: """ Fetches the provider for the given module member, if this resource has been provided a specific provider for the given module member. Returns None if no provider was provided. :param str module_memb...
Add an event handler to be executed when the specified event is fired.
def add_event_handler(self, event_name, handler, *args, **kwargs): """Add an event handler to be executed when the specified event is fired. Args: event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or any `event_name` added by...
Check if the specified event has the specified handler.
def has_event_handler(self, handler, event_name=None): """Check if the specified event has the specified handler. Args: handler (callable): the callable event handler. event_name: The event the handler attached to. Set this to ``None`` to search all events. ...
Remove event handler handler from registered handlers of the engine
def remove_event_handler(self, handler, event_name): """Remove event handler `handler` from registered handlers of the engine Args: handler (callable): the callable event handler that should be removed event_name: The event the handler attached to. """ if event_...
Decorator shortcut for add_event_handler.
def on(self, event_name, *args, **kwargs): """Decorator shortcut for add_event_handler. Args: event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`. ...
Execute all the handlers associated with given event.
def _fire_event(self, event_name, *event_args, **event_kwargs): """Execute all the handlers associated with given event. This method executes all handlers associated with the event `event_name`. Optional positional and keyword arguments can be used to pass arguments to **all** handlers ...
Runs the process_function over the passed data.
def run(self, data, max_epochs=1): """Runs the process_function over the passed data. Args: data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`). max_epochs (int, optional): max epochs to run for (default: 1). Returns: ...