text
stringlengths
81
112k
If Luigi has forked, we have a different PID, and need to reconnect. def get_bite(self): """ If Luigi has forked, we have a different PID, and need to reconnect. """ config = hdfs_config.hdfs() if self.pid != os.getpid() or not self._bite: client_kwargs = dict(filter...
Use snakebite.rename, if available. :param path: source file(s) :type path: either a string or sequence of strings :param dest: destination file (single input) or directory (multiple) :type dest: string :return: list of renamed items def move(self, path, dest): """ ...
Use snakebite.rename_dont_move, if available. :param path: source path (single input) :type path: string :param dest: destination path :type dest: string :return: True if succeeded :raises: snakebite.errors.FileAlreadyExistsException def rename_dont_move(self, path, des...
Use snakebite.delete, if available. :param path: delete-able file(s) or directory(ies) :type path: either a string or a sequence of strings :param recursive: delete directories trees like \\*nix: rm -r :type recursive: boolean, default is True :param skip_trash: do or don't move...
Use snakebite.chmod, if available. :param path: update-able file(s) :type path: either a string or sequence of strings :param permissions: \\*nix style permission number :type permissions: octal :param recursive: change just listed entry(ies) or all in directories :type ...
Use snakebite.chown/chgrp, if available. One of owner or group must be set. Just setting group calls chgrp. :param path: update-able file(s) :type path: either a string or sequence of strings :param owner: new owner, can be blank :type owner: string :param group: new gr...
Use snakebite.count, if available. :param path: directory to count the contents of :type path: string :return: dictionary with content_size, dir_count and file_count keys def count(self, path): """ Use snakebite.count, if available. :param path: directory to count the ...
Use snakebite.copyToLocal, if available. :param path: HDFS file :type path: string :param local_destination: path on the system running Luigi :type local_destination: string def get(self, path, local_destination): """ Use snakebite.copyToLocal, if available. :p...
Using snakebite getmerge to implement this. :param path: HDFS directory :param local_destination: path on the system running Luigi :return: merge of the directory def get_merge(self, path, local_destination): """ Using snakebite getmerge to implement this. :param path: H...
Use snakebite.mkdir, if available. Snakebite's mkdir method allows control over full path creation, so by default, tell it to build a full path to work like ``hadoop fs -mkdir``. :param path: HDFS path to create :type path: string :param parents: create any missing parent direc...
Use snakebite.ls to get the list of items in a directory. :param path: the directory to list :type path: string :param ignore_directories: if True, do not yield directory entries :type ignore_directories: boolean, default is False :param ignore_files: if True, do not yield file ...
Singleton getter def instance(cls, *args, **kwargs): """ Singleton getter """ if cls._instance is None: cls._instance = cls(*args, **kwargs) loaded = cls._instance.reload() logging.getLogger('luigi-interface').info('Loaded %r', loaded) return cls._instance
Imports task dynamically given a module and a task name. def load_task(module, task_name, params_str): """ Imports task dynamically given a module and a task name. """ if module is not None: __import__(module) task_cls = Register.get_task_cls(task_name) return task_cls.from_str_params(p...
Internal note: This function will be deleted soon. def task_family(cls): """ Internal note: This function will be deleted soon. """ if not cls.get_task_namespace(): return cls.__name__ else: return "{}.{}".format(cls.get_task_namespace(), cls.__name__)
Return all of the registered classes. :return: an ``dict`` of task_family -> class def _get_reg(cls): """Return all of the registered classes. :return: an ``dict`` of task_family -> class """ # We have to do this on-demand in case task names have changed later reg = ...
The writing complement of _get_reg def _set_reg(cls, reg): """The writing complement of _get_reg """ cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS]
Returns an unambiguous class or raises an exception. def get_task_cls(cls, name): """ Returns an unambiguous class or raises an exception. """ task_cls = cls._get_reg().get(name) if not task_cls: raise TaskClassNotFoundException(cls._missing_task_msg(name)) ...
Compiles and returns all parameters for all :py:class:`Task`. :return: a generator of tuples (TODO: we should make this more elegant) def get_all_params(cls): """ Compiles and returns all parameters for all :py:class:`Task`. :return: a generator of tuples (TODO: we should make this mo...
Simple unweighted Levenshtein distance def _editdistance(a, b): """ Simple unweighted Levenshtein distance """ r0 = range(0, len(b) + 1) r1 = [0] * (len(b) + 1) for i in range(0, len(a)): r1[0] = i + 1 for j in range(0, len(b)): c = 0 if a[i] is...
>>> list(Register._module_parents('a.b')) ['a.b', 'a', ''] def _module_parents(module_name): ''' >>> list(Register._module_parents('a.b')) ['a.b', 'a', ''] ''' spl = module_name.split('.') for i in range(len(spl), 0, -1): yield '.'.join(spl[0:i]) ...
Retrieve task statuses from ECS API Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids def _get_task_statuses(task_ids, cluster): """ Retrieve task statuses from ECS API Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids """ response = client.describe_tasks(tasks...
Poll task status until STOPPED def _track_tasks(task_ids, cluster): """Poll task status until STOPPED""" while True: statuses = _get_task_statuses(task_ids, cluster) if all([status == 'STOPPED' for status in statuses]): logger.info('ECS tasks {0} STOPPED'.format(','.join(task_ids)))...
Override to provide code for creating the target table. By default it will be created using types (optionally) specified in columns. If overridden, use the provided connection object for setting up the table in order to create the table and insert data using the same transaction. def create_t...
Override to perform custom queries. Any code here will be formed in the same transaction as the main copy, just prior to copying data. Example use cases include truncating the table or removing all data older than X in the database to keep a rolling window of data available in the table. def i...
Grab all the values in task_instance that are found in task_cls. def common_params(task_instance, task_cls): """ Grab all the values in task_instance that are found in task_cls. """ if not isinstance(task_cls, task.Register): raise TypeError("task_cls must be an uninstantiated Task") task_...
Lets a task call methods on subtask(s). The way this works is that the subtask is run as a part of the task, but the task itself doesn't have to care about the requirements of the subtasks. The subtask doesn't exist from the scheduler's point of view, and its dependencies are instead required by the ma...
Return a previous Task of the same family. By default checks if this task family only has one non-global parameter and if it is a DateParameter, DateHourParameter or DateIntervalParameter in which case it returns with the time decremented by 1 (hour, day or interval) def previous(task): """ Return...
Given that we want one of the hadoop cli clients (unlike snakebite), this one will return the right one. def create_hadoopcli_client(): """ Given that we want one of the hadoop cli clients (unlike snakebite), this one will return the right one. """ version = hdfs_config.get_configured_hadoop_ve...
Use ``hadoop fs -stat`` to check file existence. def exists(self, path): """ Use ``hadoop fs -stat`` to check file existence. """ cmd = load_hadoop_cmd() + ['fs', '-stat', path] logger.debug('Running file existence check: %s', subprocess.list2cmdline(cmd)) p = subproces...
No explicit -p switch, this version of Hadoop always creates parent directories. def mkdir(self, path, parents=True, raise_if_exists=False): """ No explicit -p switch, this version of Hadoop always creates parent directories. """ try: self.call_check(load_hadoop_cmd() + ['fs...
Runs the `hive` from the command line, passing in the given args, and returning stdout. With the apache release of Hive, so of the table existence checks (which are done using DESCRIBE do not exit with a return code of 0 so we need an option to ignore the return code and just return stdout for parsing ...
Runs the contents of the given script in hive and returns stdout. def run_hive_script(script): """ Runs the contents of the given script in hive and returns stdout. """ if not os.path.isfile(script): raise RuntimeError("Hive script: {0} does not exist.".format(script)) return run_hive(['-f'...
Returns a dict of key=value settings to be passed along to the hive command line via --hiveconf. By default, sets mapred.job.name to task_id and if not None, sets: * mapred.reduce.tasks (n_reduce_tasks) * mapred.fairscheduler.pool (pool) or mapred.job.queue.name (pool) * hive.ex...
Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail def prepare_outputs(self, job): """ Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail ...
Returns the path to this table in HDFS. def path(self): """ Returns the path to this table in HDFS. """ location = self.client.table_location(self.table, self.database) if not location: raise Exception("Couldn't find location for table: {0}".format(str(self))) ...
Mark this update as complete. We index the parameters `update_id` and `date`. def touch(self): """ Mark this update as complete. We index the parameters `update_id` and `date`. """ marker_key = self.marker_key() self.redis_client.hset(marker_key, 'update_id', s...
Meant to be used as a context manager. def global_instance(cls, cmdline_args, allow_override=False): """ Meant to be used as a context manager. """ orig_value = cls._instance assert (orig_value is None) or allow_override new_value = None try: new_valu...
Get the local task arguments as a dictionary. The return value is in the form ``dict(my_param='my_value', ...)`` def _get_task_kwargs(self): """ Get the local task arguments as a dictionary. The return value is in the form ``dict(my_param='my_value', ...)`` """ res = {} ...
Check if the user passed --help[-all], if so, print a message and exit. def _possibly_exit_with_help(parser, known_args): """ Check if the user passed --help[-all], if so, print a message and exit. """ if known_args.core_help or known_args.core_help_all: parser.print_help() ...
Compute path given current file and relative path. def relpath(self, current_file, rel_path): """ Compute path given current file and relative path. """ script_dir = os.path.dirname(os.path.abspath(current_file)) rel_path = os.path.abspath(os.path.join(script_dir, rel_path)) ...
Returns an array of args to pass to the job. def args(self): """ Returns an array of args to pass to the job. """ arglist = [] for k, v in six.iteritems(self.requires_hadoop()): arglist.append('--' + k) arglist.extend([t.output().path for t in flatten(v)]...
Adds an event to the event file. Args: event: An `Event` protocol buffer. def add_event(self, event): """Adds an event to the event file. Args: event: An `Event` protocol buffer. """ if not isinstance(event, event_pb2.Event): raise TypeError("Ex...
Enqueue the given bytes to be written asychronously def write(self, bytestring): '''Enqueue the given bytes to be written asychronously''' with self._lock: if self._closed: raise IOError('Writer is closed') self._byte_queue.put(bytestring)
Write all the enqueued bytestring before this flush call to disk. Block until all the above bytestring are written. def flush(self): '''Write all the enqueued bytestring before this flush call to disk. Block until all the above bytestring are written. ''' with self._lock: ...
Closes the underlying writer, flushing any pending writes first. def close(self): '''Closes the underlying writer, flushing any pending writes first.''' if not self._closed: with self._lock: if not self._closed: self._closed = True sel...
Extract device name from a tf.Event proto carrying tensor value. def _extract_device_name_from_event(event): """Extract device name from a tf.Event proto carrying tensor value.""" plugin_data_content = json.loads( tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content)) return plugin_data_con...
Create a dict() as the outgoing data in the tensor data comm route. Note: The tensor data in the comm route does not include the value of the tensor in its entirety in general. Only if a tensor satisfies the following conditions will its entire value be included in the return value of this method: 1. Has a n...
Add a GraphDef. Args: run_key: A key for the run, containing information about the feeds, fetches, and targets. device_name: The name of the device that the `GraphDef` is for. graph_def: An instance of the `GraphDef` proto. debug: Whether `graph_def` consists of the debug ops. def ...
Get the runtime GraphDef protos associated with a run key. Args: run_key: A Session.run kay. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `dict` mapping device name to `GraphDef` protos. def get_graphs(self, run_key, debug=False): """Get the runtime GraphDef...
Get the runtime GraphDef proto associated with a run key and a device. Args: run_key: A Session.run kay. device_name: Name of the device in question. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `GraphDef` proto. def get_graph(self, run_key, device_name, d...
Obtain possibly base-expanded node name. Base-expansion is the transformation of a node name which happens to be the name scope of other nodes in the same graph. For example, if two nodes, called 'a/b' and 'a/b/read' in a graph, the name of the first node will be base-expanded to 'a/b/(b)'. This m...
Implementation of the core metadata-carrying Event proto callback. Args: event: An Event proto that contains core metadata about the debugged Session::Run() in its log_message.message field, as a JSON string. See the doc string of debug_data.DebugDumpDir.core_metadata for details. def on_cor...
Implementation of the GraphDef-carrying Event proto callback. Args: graph_def: A GraphDef proto. N.B.: The GraphDef is from the core runtime of a debugged Session::Run() call, after graph partition. Therefore it may differ from the GraphDef available to the general TensorBoard. For ex...
Records the summary values based on an updated message from the debugger. Logs an error message if writing the event to disk fails. Args: event: The Event proto to be processed. def on_value_event(self, event): """Records the summary values based on an updated message from the debugger. Logs a...
Add a DebuggedSourceFile proto. def add_debugged_source_file(self, debugged_source_file): """Add a DebuggedSourceFile proto.""" # TODO(cais): Should the key include a host name, for certain distributed # cases? key = debugged_source_file.file_path self._source_file_host[key] = debugged_source_fil...
Get the traceback of an op in the latest version of the TF graph. Args: op_name: Name of the op. Returns: Creation traceback of the op, in the form of a list of 2-tuples: (file_path, lineno) Raises: ValueError: If the op with the given name cannot be found in the latest ...
Get the lists of ops created at lines of a specified source file. Args: file_path: Path to the source file. Returns: A dict mapping line number to a list of 2-tuples, `(op_name, stack_position)` `op_name` is the name of the name of the op whose creation traceback includes the...
Query tensor store for a given debugged tensor value. Args: watch_key: The watch key of the debugged tensor being sought. Format: <node_name>:<output_slot>:<debug_op> E.g., Dense_1/MatMul:0:DebugIdentity. time_indices: Optional time indices string By default, the lastest time in...
Construct a werkzeug Response. Responses are transmitted to the browser with compression if: a) the browser supports it; b) it's sane to compress the content_type in question; and c) the content isn't already compressed, as indicated by the content_encoding parameter. Browser and proxy caching is completely...
Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some file-system.. This function returns the longest ance...
Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. def _protobuf_value_type(value): """Returns the type of the google.protobuf.Value message as an ...
Returns a string representation of given google.protobuf.Value message. Args: value: google.protobuf.Value message. Assumed to be of type 'number', 'string' or 'bool'. def _protobuf_value_to_string(value): """Returns a string representation of given google.protobuf.Value message. Args: value: goo...
Finds the experiment associcated with the metadata.EXPERIMENT_TAG tag. Caches the experiment if it was found. Returns: The experiment or None if no such experiment is found. def _find_experiment_tag(self): """Finds the experiment associcated with the metadata.EXPERIMENT_TAG tag. Caches the exp...
Computes a minimal Experiment protocol buffer by scanning the runs. def _compute_experiment_from_runs(self): """Computes a minimal Experiment protocol buffer by scanning the runs.""" hparam_infos = self._compute_hparam_infos() if not hparam_infos: return None metric_infos = self._compute_metric_i...
Computes a list of api_pb2.HParamInfo from the current run, tag info. Finds all the SessionStartInfo messages and collects the hparams values appearing in each one. For each hparam attempts to deduce a type that fits all its values. Finally, sets the 'domain' of the resulting HParamInfo to be discrete ...
Builds an HParamInfo message from the hparam name and list of values. Args: name: string. The hparam name. values: list of google.protobuf.Value messages. The list of values for the hparam. Returns: An api_pb2.HParamInfo message. def _compute_hparam_info_from_values(self, name, valu...
Computes the list of metric names from all the scalar (run, tag) pairs. The return value is a list of (tag, group) pairs representing the metric names. The list is sorted in Python tuple-order (lexicographical). For example, if the scalar (run, tag) pairs are: ("exp/session1", "loss") ("exp/sessio...
Handles the request specified on construction. Returns: An Experiment object. def run(self): """Handles the request specified on construction. Returns: An Experiment object. """ experiment = self._context.experiment() if experiment is None: raise error.HParamsError( ...
Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. metric_infos: Array of api_pb2.MetricInfo messages. Describes the metrics used in the experiment. See the document...
Constructs a SessionStartInfo protobuffer. Creates a summary that contains a training session metadata information. One such summary per training session should be created. Each should have a different run. Args: hparams: A dictionary with string keys. Describes the hyperparameter values used...
Constructs a SessionEndInfo protobuffer. Creates a summary that contains status information for a completed training session. Should be exported after the training session is completed. One such summary per training session should be created. Each should have a different run. Args: status: A tensorboard...
Returns a summary holding the given HParamsPluginData message. Helper function. Args: tag: string. The tag to use. hparams_plugin_data: The HParamsPluginData message to use. def _summary(tag, hparams_plugin_data): """Returns a summary holding the given HParamsPluginData message. Helper function. ...
Helper that returns if parent/item is a directory. def _IsDirectory(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item))
List all the plugins that have registered assets in logdir. If the plugins_dir does not exist, it returns an empty list. This maintains compatibility with old directories that have no plugins written. Args: logdir: A directory that was created by a TensorFlow events writer. Returns: a list of plugin ...
List all the assets that are available for given plugin in a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: A string name of a plugin to list assets for. Returns: A string list of available plugin assets. If the plugin subdirectory does not exis...
Retrieve a particular plugin asset from a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: The plugin we want an asset from. asset_name: The name of the requested asset. Returns: string contents of the plugin asset. Raises: KeyError: if the...
Result of the form `(body, mime_type)`, or `ValueError`. def distributions_impl(self, tag, run): """Result of the form `(body, mime_type)`, or `ValueError`.""" (histograms, mime_type) = self._histograms_plugin.histograms_impl( tag, run, downsample_to=self.SAMPLE_SIZE) return ([self._compress(histog...
Given a tag and single run, return an array of compressed histograms. def distributions_route(self, request): """Given a tag and single run, return an array of compressed histograms.""" tag = request.args.get('tag') run = request.args.get('run') try: (body, mime_type) = self.distributions_impl(ta...
Loads new values. The watcher will load from one path at a time; as soon as that path stops yielding events, it will move on to the next path. We assume that old paths are never modified after a newer path has been written. As a result, Load() can be called multiple times in a row without losing events...
Internal implementation of Load(). The only difference between this and Load() is that the latter will throw DirectoryDeletedError on I/O errors if it thinks that the directory has been permanently deleted. Yields: All values that have not been yielded yet. def _LoadInternal(self): """Inter...
Sets the current path to watch for new events. This also records the size of the old path, if any. If the size can't be found, an error is logged. Args: path: The full path of the file to watch. def _SetPath(self, path): """Sets the current path to watch for new events. This also records t...
Gets the next path to load from. This function also does the checking for out-of-order writes as it iterates through the paths. Returns: The next path to load events from, or None if there are no more paths. def _GetNextPath(self): """Gets the next path to load from. This function also doe...
Returns whether the path has had an out-of-order write. def _HasOOOWrite(self, path): """Returns whether the path has had an out-of-order write.""" # Check the sizes of each path before the current one. size = tf.io.gfile.stat(path).length old_size = self._finalized_sizes.get(path, None) if size !=...
Returns a number of examples from the provided path. Args: path: A string path to the examples. num_examples: The maximum number of examples to return from the path. parse_examples: If true then parses the serialized proto from the path into proto objects. Defaults to True. sampling_odds: Odd...
Send an RPC request to the Servomatic prediction service. Args: examples: A list of examples that matches the model spec. serving_bundle: A `ServingBundle` object that contains the information to make the serving request. Returns: A ClassificationResponse or RegressionResponse proto. def call_s...
Convert `value` to a new-style value, if necessary and possible. An "old-style" value is a value that uses any `value` field other than the `tensor` field. A "new-style" value is a value that uses the `tensor` field. TensorBoard continues to support old-style values on disk; this method converts them to new-st...
Obtains a mapping between routes and handlers. Stores the logdir. Returns: A mapping between routes and handlers (functions that respond to requests). def get_plugin_apps(self): """Obtains a mapping between routes and handlers. Stores the logdir. Returns: A mapping between routes and ha...
Returns JSON of the specified examples. Args: request: A request that should contain 'examples_path' and 'max_examples'. Returns: JSON of up to max_examlpes of the examples in the path. def _examples_from_path_handler(self, request): """Returns JSON of the specified examples. Args: ...
Updates the specified example. Args: request: A request that should contain 'index' and 'example'. Returns: An empty response. def _update_example(self, request): """Updates the specified example. Args: request: A request that should contain 'index' and 'example'. Returns: ...
Duplicates the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. def _duplicate_example(self, request): """Duplicates the specified example. Args: request: A request that should contain 'index'. Returns: An empty respons...
Deletes the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. def _delete_example(self, request): """Deletes the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. ""...
Parses comma separated request arguments Args: request: A request that should contain 'inference_address', 'model_name', 'model_version', 'model_signature'. Returns: A tuple of lists for model parameters def _parse_request_arguments(self, request): """Parses comma separated request ar...
Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'inference_address', 'model_name', 'model_type, 'model_version', 'model_signature' and 'label_vocab_path'. Returns: A list of JSON objects, one for each chart. def _infer(self, request): ...
Returns a list of JSON objects for each feature in the example. Args: request: A request for features. Returns: A list with a JSON object for each feature. Numeric features are represented as {name: observedMin: observedMax:}. Categorical features are repesented as {name: samples:[]}. ...
Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'feature_name', 'example_index', 'inference_address', 'model_name', 'model_type', 'model_version', and 'model_signature'. Returns: A list of JSON objects, one for each chart. def _i...
Serves a pre-gzipped static asset from the zip file. def _serve_asset(self, path, gzipped_asset_bytes, request): """Serves a pre-gzipped static asset from the zip file.""" mimetype = mimetypes.guess_type(path)[0] or 'application/octet-stream' return http_util.Respond( request, gzipped_asset_bytes, ...
Serve a JSON object containing some base properties used by the frontend. * data_location is either a path to a directory or an address to a database (depending on which mode TensorBoard is running in). * window_title is the title of the TensorBoard web page. def _serve_environment(self, request): "...
Serve a JSON array of run names, ordered by run started time. Sort order is by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name. def _serve_runs(self, request): """Serve a JSON array of run names, ordered by run started time. Sort o...
Serve a JSON array of experiments. Experiments are ordered by experiment started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the experiment name. def _serve_experiments(self, request): """Serve a JSON array of experiments. Experiments are ordered by expe...
Serve a JSON runs of an experiment, specified with query param `experiment`, with their nested data, tag, populated. Runs returned are ordered by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name. Tags are sorted by its name, displayNam...