sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def run_evaluation(self, stream_name: str) -> None: """ Run the main loop with the given stream in the prediction mode. :param stream_name: name of the stream to be evaluated """ def prediction(): logging.info('Running prediction') self._run_zeroth_epoch(...
Run the main loop with the given stream in the prediction mode. :param stream_name: name of the stream to be evaluated
entailment
def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]: """ For the given iterable of object iterations, return an iterable of the most common object at each position of the inner iterations. E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the m...
For the given iterable of object iterations, return an iterable of the most common object at each position of the inner iterations. E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the most common objects at the first and second positions respectively. :param all_vote...
entailment
def _load_models(self) -> None: """Maybe load all the models to be assembled together and save them to the ``self._models`` attribute.""" if self._models is None: logging.info('Loading %d models', len(self._model_paths)) def load_model(model_path: str): logging.d...
Maybe load all the models to be assembled together and save them to the ``self._models`` attribute.
entailment
def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch: """ Run feed-forward pass with the given batch using all the models, aggregate and return the results. .. warning:: :py:class:`Ensemble` can not be trained. :param batch: batch to be proces...
Run feed-forward pass with the given batch using all the models, aggregate and return the results. .. warning:: :py:class:`Ensemble` can not be trained. :param batch: batch to be processed :param train: ``True`` if this batch should be used for model update, ``False`` otherwise ...
entailment
def parse_fully_qualified_name(fq_name: str) -> Tuple[Optional[str], str]: """ Parse the given fully-quallified name (separated with dots) to a tuple of module and class names. :param fq_name: fully qualified name separated with dots :return: ``None`` instead of module if the given name contains no sep...
Parse the given fully-quallified name (separated with dots) to a tuple of module and class names. :param fq_name: fully qualified name separated with dots :return: ``None`` instead of module if the given name contains no separators (dots).
entailment
def get_attribute(module_name: str, attribute_name: str): """ Get the specified module attribute. It most cases, it will be a class or function. :param module_name: module name :param attribute_name: attribute name :return: module attribute """ assert isinstance(module_name, str) assert...
Get the specified module attribute. It most cases, it will be a class or function. :param module_name: module name :param attribute_name: attribute name :return: module attribute
entailment
def create_object(module_name: str, class_name: str, args: Iterable=(), kwargs: Dict[str, Any]=_EMPTY_DICT): """ Create an object instance of the given class from the given module. Args and kwargs are passed to the constructor. This mimics the following code: .. code-block:: python from m...
Create an object instance of the given class from the given module. Args and kwargs are passed to the constructor. This mimics the following code: .. code-block:: python from module import class return class(*args, **kwargs) :param module_name: module name :param class_name: clas...
entailment
def list_submodules(module_name: str) -> List[str]: # pylint: disable=invalid-sequence-index """ List full names of all the submodules in the given module. :param module_name: name of the module of which the submodules will be listed """ _module = importlib.import_module(module_name) return [...
List full names of all the submodules in the given module. :param module_name: name of the module of which the submodules will be listed
entailment
def find_class_module(module_name: str, class_name: str) \ -> Tuple[List[str], List[Tuple[str, Exception]]]: # pylint: disable=invalid-sequence-index """ Find sub-modules of the given module that contain the given class. Moreover, return a list of sub-modules that could not be imported as a list ...
Find sub-modules of the given module that contain the given class. Moreover, return a list of sub-modules that could not be imported as a list of (sub-module name, Exception) tuples. :param module_name: name of the module to be searched :param class_name: searched class name :return: a tuple of sub-mo...
entailment
def get_class_module(module_name: str, class_name: str) -> Optional[str]: """ Get a sub-module of the given module which has the given class. This method wraps `utils.reflection.find_class_module method` with the following behavior: - raise error when multiple sub-modules with different classes with t...
Get a sub-module of the given module which has the given class. This method wraps `utils.reflection.find_class_module method` with the following behavior: - raise error when multiple sub-modules with different classes with the same name are found - return None when no sub-module is found - warn about ...
entailment
def entry_point() -> None: """**cxflow** entry point.""" # make sure the path contains the current working directory sys.path.insert(0, os.getcwd()) parser = get_cxflow_arg_parser(True) # parse CLI arguments known_args, unknown_args = parser.parse_known_args() # show help if no subcomman...
**cxflow** entry point.
entailment
def get_cxflow_arg_parser(add_common_arguments: bool=False) -> ArgumentParser: """ Create the **cxflow** argument parser. :return: an instance of the parser """ # create parser main_parser = ArgumentParser('cxflow', description='cxflow: lightweight framework for...
Create the **cxflow** argument parser. :return: an instance of the parser
entailment
def _get_stream(self) -> Iterator: """Possibly create and return raw dataset stream iterator.""" if self._stream is None: self._stream = iter(self._get_stream_fn()) return self._stream
Possibly create and return raw dataset stream iterator.
entailment
def _enqueue_batches(self, stop_event: Event) -> None: """ Enqueue all the stream batches. If specified, stop after ``epoch_size`` batches. .. note:: Signal the epoch end with ``None``. Stop when: - ``stop_event`` is risen - stream ends and epoch size is not...
Enqueue all the stream batches. If specified, stop after ``epoch_size`` batches. .. note:: Signal the epoch end with ``None``. Stop when: - ``stop_event`` is risen - stream ends and epoch size is not set - specified number of batches is enqueued .. note:: ...
entailment
def _dequeue_batch(self) -> Optional[Batch]: """ Return a single batch from queue or ``None`` signaling epoch end. :raise ChildProcessError: if the enqueueing thread ended unexpectedly """ if self._enqueueing_thread is None: raise ValueError('StreamWrapper `{}` with ...
Return a single batch from queue or ``None`` signaling epoch end. :raise ChildProcessError: if the enqueueing thread ended unexpectedly
entailment
def _next_batch(self) -> Optional[Batch]: """ Return a single batch or ``None`` signaling epoch end. .. note:: Signal the epoch end with ``None``. Stop when: - stream ends and epoch size is not set - specified number of batches is returned :return: ...
Return a single batch or ``None`` signaling epoch end. .. note:: Signal the epoch end with ``None``. Stop when: - stream ends and epoch size is not set - specified number of batches is returned :return: a single batch or ``None`` signaling epoch end
entailment
def _start_thread(self): """Start an enqueueing thread.""" self._stopping_event = Event() self._enqueueing_thread = Thread(target=self._enqueue_batches, args=(self._stopping_event,)) self._enqueueing_thread.start()
Start an enqueueing thread.
entailment
def _stop_thread(self): """Stop the enqueueing thread. Keep the queue content and stream state.""" self._stopping_event.set() queue_content = [] try: # give the enqueueing thread chance to put a batch to the queue and check the stopping event while True: queu...
Stop the enqueueing thread. Keep the queue content and stream state.
entailment
def _after_n_epoch(self, epoch_id: int, **_) -> None: """ Save the model every ``n_epochs`` epoch. :param epoch_id: number of the processed epoch """ SaveEvery.save_model(model=self._model, name_suffix=str(epoch_id), on_failure=self._on_save_failure)
Save the model every ``n_epochs`` epoch. :param epoch_id: number of the processed epoch
entailment
def save_model(model: AbstractModel, name_suffix: str, on_failure: str) -> None: """ Save the given model with the given name_suffix. On failure, take the specified action. :param model: the model to be saved :param name_suffix: name to be used for saving :param on_failure: acti...
Save the given model with the given name_suffix. On failure, take the specified action. :param model: the model to be saved :param name_suffix: name to be used for saving :param on_failure: action to be taken on failure; one of :py:attr:`SAVE_FAILURE_ACTIONS` :raise IOError: on save fai...
entailment
def _get_value(self, epoch_data: EpochData) -> float: """ Retrieve the value of the monitored variable from the given epoch data. :param epoch_data: epoch data which determine whether the model will be saved or not :raise KeyError: if any of the specified stream, variable or aggregation...
Retrieve the value of the monitored variable from the given epoch data. :param epoch_data: epoch data which determine whether the model will be saved or not :raise KeyError: if any of the specified stream, variable or aggregation is not present in the ``epoch_data`` :raise TypeError: if the var...
entailment
def _is_value_better(self, new_value: float) -> bool: """ Test if the new value is better than the best so far. :param new_value: current value of the objective function """ if self._best_value is None: return True if self._condition == 'min': ret...
Test if the new value is better than the best so far. :param new_value: current value of the objective function
entailment
def after_epoch(self, epoch_data: EpochData, **_) -> None: """ Save the model if the new value of the monitored variable is better than the best value so far. :param epoch_data: epoch data to be processed """ new_value = self._get_value(epoch_data) if self._is_value_bet...
Save the model if the new value of the monitored variable is better than the best value so far. :param epoch_data: epoch data to be processed
entailment
def print_progress_bar(done: int, total: int, prefix: str = '', suffix: str = '') -> None: """ Print a progressbar with the given prefix and suffix, without newline at the end. param done: current step in computation param total: total count of steps in computation param prefix: info text displayed...
Print a progressbar with the given prefix and suffix, without newline at the end. param done: current step in computation param total: total count of steps in computation param prefix: info text displayed before the progress bar param suffix: info text displayed after the progress bar
entailment
def get_formatted_time(seconds: float) -> str: """ Convert seconds to the time format ``H:M:S.UU``. :param seconds: time in seconds :return: formatted human-readable time """ seconds = round(seconds) m, s = divmod(seconds, 60) h, m = divmod(m, 60) return '{:d}:{:02d}:{:02d}'.format(...
Convert seconds to the time format ``H:M:S.UU``. :param seconds: time in seconds :return: formatted human-readable time
entailment
def after_batch(self, stream_name: str, batch_data: Batch) -> None: """ Display the progress and ETA for the current stream in the epoch. If the stream size (total batch count) is unknown (1st epoch), print only the number of processed batches. """ if self._current_stream_name is...
Display the progress and ETA for the current stream in the epoch. If the stream size (total batch count) is unknown (1st epoch), print only the number of processed batches.
entailment
def after_epoch(self, **_) -> None: """ Reset progress counters. Save ``total_batch_count`` after the 1st epoch. """ if not self._total_batch_count_saved: self._total_batch_count = self._current_batch_count.copy() self._total_batch_count_saved = True self....
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
entailment
def after_epoch_profile(self, epoch_id, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None: """ Summarize and log the given epoch profile. The profile is expected to contain at least: - ``read_data_train``, ``eval_batch_train`` and ``after_batch_hook...
Summarize and log the given epoch profile. The profile is expected to contain at least: - ``read_data_train``, ``eval_batch_train`` and ``after_batch_hooks_train`` entries produced by the train stream (if train stream name is `train`) - ``after_epoch_hooks`` entry ...
entailment
def confusion_matrix(expected: np.ndarray, predicted: np.ndarray, num_classes: int) -> np.ndarray: """ Calculate and return confusion matrix for the predicted and expected labels :param expected: array of expected classes (integers) with shape `[num_of_data]` :param predicted: array of predicted classe...
Calculate and return confusion matrix for the predicted and expected labels :param expected: array of expected classes (integers) with shape `[num_of_data]` :param predicted: array of predicted classes (integers) with shape `[num_of_data]` :param num_classes: number of classification classes :return: c...
entailment
def _build_grid_search_commands(script: str, params: typing.Iterable[str]) -> typing.Iterable[typing.List[str]]: """ Build all grid search parameter configurations. :param script: String of command prefix, e.g. ``cxflow train -v -o log``. :param params: Iterable collection of strings in standard **cxfl...
Build all grid search parameter configurations. :param script: String of command prefix, e.g. ``cxflow train -v -o log``. :param params: Iterable collection of strings in standard **cxflow** param form, e.g. ``'numerical_param=[1, 2]'`` or ``'text_param=["hello", "cio"]'``.
entailment
def grid_search(script: str, params: typing.Iterable[str], dry_run: bool=False) -> None: """ Build all grid search parameter configurations and optionally run them. :param script: String of command prefix, e.g. ``cxflow train -v -o log``. :param params: Iterable collection of strings in standard **cxfl...
Build all grid search parameter configurations and optionally run them. :param script: String of command prefix, e.g. ``cxflow train -v -o log``. :param params: Iterable collection of strings in standard **cxflow** param form, e.g. ``'numerical_param=[1, 2]'`` or ``'text_param=["hello", "cio...
entailment
def stream_info(self) -> None: """Check and report source names, dtypes and shapes of all the streams available.""" stream_names = [stream_name for stream_name in dir(self) if 'stream' in stream_name and stream_name != 'stream_info'] logging.info('Found %s stream candidat...
Check and report source names, dtypes and shapes of all the streams available.
entailment
def parse_arg(arg: str) -> typing.Tuple[str, typing.Any]: """ Parse CLI argument in format ``key=value`` to ``(key, value)`` :param arg: CLI argument string :return: tuple (key, value) :raise: yaml.ParserError: on yaml parse error """ assert '=' in arg, 'Unrecognized argument `{}`. [name]=[...
Parse CLI argument in format ``key=value`` to ``(key, value)`` :param arg: CLI argument string :return: tuple (key, value) :raise: yaml.ParserError: on yaml parse error
entailment
def load_config(config_file: str, additional_args: typing.Iterable[str]=()) -> dict: """ Load config from YAML ``config_file`` and extend/override it with the given ``additional_args``. :param config_file: path the YAML config file to be loaded :param additional_args: additional args which may extend o...
Load config from YAML ``config_file`` and extend/override it with the given ``additional_args``. :param config_file: path the YAML config file to be loaded :param additional_args: additional args which may extend or override the config loaded from the file. :return: configuration as dict
entailment
def find_config(config_path: str) -> str: """ Derive configuration file path from the given path and check its existence. The given path is expected to be either 1. path to the file 2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE`` :param config_path: path to the conf...
Derive configuration file path from the given path and check its existence. The given path is expected to be either 1. path to the file 2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE`` :param config_path: path to the configuration file or its parent directory :return: va...
entailment
def fallback(message: str, ex: Exception) -> None: """ Fallback procedure when a cli command fails. :param message: message to be logged :param ex: Exception which caused the failure """ logging.error('%s', message) logging.exception('%s', ex) sys.exit(1)
Fallback procedure when a cli command fails. :param message: message to be logged :param ex: Exception which caused the failure
entailment
def _configure_dataset(self, data_root: str=None, download_urls: Iterable[str]=None, **kwargs) -> None: """ Save the passed values and use them as a default property implementation. :param data_root: directory to which the files will be downloaded :param download_urls: list of URLs to b...
Save the passed values and use them as a default property implementation. :param data_root: directory to which the files will be downloaded :param download_urls: list of URLs to be downloaded
entailment
def resume(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None: """ Load config from the directory specified and start the training. :param config_path: path to the config file or the directory in which it is stored :param restore_from: backend-specific...
Load config from the directory specified and start the training. :param config_path: path to the config file or the directory in which it is stored :param restore_from: backend-specific path to the already trained model to be restored from. If ``None`` is passed, it is inferred from th...
entailment
def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None: """ After epoch profile event. This event provides opportunity to process time profile of the finished epoch. :param epoch_id: finished epoch id :pa...
After epoch profile event. This event provides opportunity to process time profile of the finished epoch. :param epoch_id: finished epoch id :param profile: dictionary of lists of event timings that were measured during the epoch :param extra_streams: enumeration of additional stream n...
entailment
def load_yaml(yaml_file: str) -> Any: """ Load YAML from file. :param yaml_file: path to YAML file :return: content of the YAML as dict/list """ with open(yaml_file, 'r') as file: return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader)
Load YAML from file. :param yaml_file: path to YAML file :return: content of the YAML as dict/list
entailment
def yaml_to_file(data: Mapping, output_dir: str, name: str) -> str: """ Save the given object to the given path in YAML. :param data: dict/list to be dumped :param output_dir: target output directory :param name: target filename :return: target path """ dumped_config_f = path.join(outpu...
Save the given object to the given path in YAML. :param data: dict/list to be dumped :param output_dir: target output directory :param name: target filename :return: target path
entailment
def yaml_to_str(data: Mapping) -> str: """ Return the given given config as YAML str. :param data: configuration dict :return: given configuration as yaml str """ return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper)
Return the given given config as YAML str. :param data: configuration dict :return: given configuration as yaml str
entailment
def make_simple(data: Any) -> Any: """ Substitute all the references in the given data (typically a mapping or sequence) with the actual values. This is useful, if you loaded a yaml with RoundTripLoader and you need to dump part of it safely. :param data: data to be made simple (dict instead of Comment...
Substitute all the references in the given data (typically a mapping or sequence) with the actual values. This is useful, if you loaded a yaml with RoundTripLoader and you need to dump part of it safely. :param data: data to be made simple (dict instead of CommentedMap etc.) :return: simplified data
entailment
def reload(data: Any) -> Any: """ Dump and load yaml data. This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure the changes are propagated to anchor expansions. :param data: data to be reloaded :return: reloaded data """ return yaml.load(...
Dump and load yaml data. This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure the changes are propagated to anchor expansions. :param data: data to be reloaded :return: reloaded data
entailment
def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None: """ Call :py:meth:`_on_plateau_action` if the ``long_term`` variable mean is lower/greater than the ``short_term`` mean. """ super().after_epoch(epoch_id=epoch_id, epoch_data=epoch_data) self._saved_lo...
Call :py:meth:`_on_plateau_action` if the ``long_term`` variable mean is lower/greater than the ``short_term`` mean.
entailment
def _is_nan(self, variable: str, data) -> bool: """ Recursively search passed data and find NaNs. :param variable: name of variable to be checked :param data: data object (dict, list, scalar) :return: `True` if there is a NaN value in the data; `False` otherwise. :raise ...
Recursively search passed data and find NaNs. :param variable: name of variable to be checked :param data: data object (dict, list, scalar) :return: `True` if there is a NaN value in the data; `False` otherwise. :raise ValueError: if the variable value is of unsupported type and ``on_un...
entailment
def _check_nan(self, epoch_data: EpochData) -> None: """ Raise an exception when some of the monitored data is NaN. :param epoch_data: epoch data checked :raise KeyError: if the specified variable is not found in the stream :raise ValueError: if the variable value is of unsuppor...
Raise an exception when some of the monitored data is NaN. :param epoch_data: epoch data checked :raise KeyError: if the specified variable is not found in the stream :raise ValueError: if the variable value is of unsupported type and ``self._on_unknown_type`` is set to ``error``
entailment
def after_epoch(self, epoch_data: EpochData, **kwargs) -> None: """ If initialized to check after each epoch, stop the training once the epoch data contains a monitored variable equal to NaN. :param epoch_data: epoch data to be checked """ if self._after_epoch: ...
If initialized to check after each epoch, stop the training once the epoch data contains a monitored variable equal to NaN. :param epoch_data: epoch data to be checked
entailment
def after_batch(self, stream_name: str, batch_data) -> None: """ If initialized to check after each batch, stop the training once the batch data contains a monitored variable equal to NaN. :param stream_name: name of the stream to be checked :param batch_data: batch data to be c...
If initialized to check after each batch, stop the training once the batch data contains a monitored variable equal to NaN. :param stream_name: name of the stream to be checked :param batch_data: batch data to be checked
entailment
def after_epoch(self, epoch_id: int, **kwargs) -> None: """ Call ``_after_n_epoch`` method every ``n_epochs`` epoch. :param epoch_id: number of the processed epoch """ if epoch_id % self._n_epochs == 0: self._after_n_epoch(epoch_id=epoch_id, **kwargs)
Call ``_after_n_epoch`` method every ``n_epochs`` epoch. :param epoch_id: number of the processed epoch
entailment
def path_total_size(path_: str) -> int: """Compute total size of the given file/dir.""" if path.isfile(path_): return path.getsize(path_) total_size = 0 for root_dir, _, files in os.walk(path_): for file_ in files: total_size += path.getsize(path.join(root_dir, file_)) re...
Compute total size of the given file/dir.
entailment
def humanize_filesize(filesize: int) -> Tuple[str, str]: """Return human readable pair of size and unit from the given filesize in bytes.""" for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if filesize < 1024.0: return '{:3.1f}'.format(filesize), unit+'B' filesize /= 1024.0
Return human readable pair of size and unit from the given filesize in bytes.
entailment
def is_train_dir(dir_: str) -> bool: """Test if the given dir contains training artifacts.""" return path.exists(path.join(dir_, CXF_CONFIG_FILE)) and \ path.exists(path.join(dir_, CXF_TRACE_FILE)) and \ path.exists(path.join(dir_, CXF_LOG_FILE))
Test if the given dir contains training artifacts.
entailment
def walk_train_dirs(root_dir: str) -> Iterable[Tuple[str, Iterable[str]]]: """ Modify os.walk with the following: - return only root_dir and sub-dirs - return only training sub-dirs - stop recursion at training dirs :param root_dir: root dir to be walked :return: generator of (r...
Modify os.walk with the following: - return only root_dir and sub-dirs - return only training sub-dirs - stop recursion at training dirs :param root_dir: root dir to be walked :return: generator of (root_dir, training sub-dirs) pairs
entailment
def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None: """ Print a plain table with the details of the given trainings. :param trainings: iterable of tuples (train_dir, configuration dict, trace) """ long_table = [] for train_dir, config, trace in trainings: ...
Print a plain table with the details of the given trainings. :param trainings: iterable of tuples (train_dir, configuration dict, trace)
entailment
def _ls_print_listing(dir_: str, recursive: bool, all_: bool, long: bool) -> List[Tuple[str, dict, TrainingTrace]]: """ Print names of the train dirs contained in the given dir. :param dir_: dir to be listed :param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option) ...
Print names of the train dirs contained in the given dir. :param dir_: dir to be listed :param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option) :param all_: include train dirs with no epochs done (--all option) :param long: list more details including model name, ...
entailment
def _ls_print_summary(all_trainings: List[Tuple[str, dict, TrainingTrace]]) -> None: """ Print trainings summary. In particular print tables summarizing the number of trainings with - particular model names - particular combinations of models and datasets :param all_trainings: a list of...
Print trainings summary. In particular print tables summarizing the number of trainings with - particular model names - particular combinations of models and datasets :param all_trainings: a list of training tuples (train_dir, configuration dict, trace)
entailment
def _ls_print_verbose(training: Tuple[str, dict, str]) -> None: """ Print config and artifacts info from the given training tuple (train_dir, configuration dict, trace). :param training: training tuple (train_dir, configuration dict, trace) """ train_dir, config, _ = training print_boxed('confi...
Print config and artifacts info from the given training tuple (train_dir, configuration dict, trace). :param training: training tuple (train_dir, configuration dict, trace)
entailment
def list_train_dirs(dir_: str, recursive: bool, all_: bool, long: bool, verbose: bool) -> None: """ List training dirs contained in the given dir with options and outputs similar to the regular `ls` command. The function is accessible through cxflow CLI `cxflow ls`. :param dir_: dir to be listed :p...
List training dirs contained in the given dir with options and outputs similar to the regular `ls` command. The function is accessible through cxflow CLI `cxflow ls`. :param dir_: dir to be listed :param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option) :param all_...
entailment
def after_batch(self, stream_name: str, batch_data: Batch): """ Extend the accumulated variables with the given batch data. :param stream_name: stream name; e.g. ``train`` or any other... :param batch_data: batch data = stream sources + model outputs :raise KeyError: if the vari...
Extend the accumulated variables with the given batch data. :param stream_name: stream name; e.g. ``train`` or any other... :param batch_data: batch data = stream sources + model outputs :raise KeyError: if the variables to be aggregated are missing :raise TypeError: if the variable val...
entailment
def invoke_dataset_method(config_path: str, method_name: str, output_root: str, cl_arguments: Iterable[str]) -> None: """ Create the specified dataset and invoke its specified method. :param config_path: path to the config file or the directory in which it is stored :param method_name: name of the meth...
Create the specified dataset and invoke its specified method. :param config_path: path to the config file or the directory in which it is stored :param method_name: name of the method to be invoked on the specified dataset :param cl_arguments: additional command line arguments which will update the configu...
entailment
def _signal_handler(self, *_) -> None: """ On the first signal, increase the ``self._num_signals`` counter. Call ``sys.exit`` on any subsequent signal. """ if self._num_signals == 0: logging.warning('Interrupt signal caught - training will be terminated') ...
On the first signal, increase the ``self._num_signals`` counter. Call ``sys.exit`` on any subsequent signal.
entailment
def create_output_dir(config: dict, output_root: str, default_model_name: str='Unnamed') -> str: """ Create output_dir under the given ``output_root`` and - dump the given config to YAML file under this dir - register a file logger logging to a file under this dir :param config: config to b...
Create output_dir under the given ``output_root`` and - dump the given config to YAML file under this dir - register a file logger logging to a file under this dir :param config: config to be dumped :param output_root: dir wherein output_dir shall be created :param default_model_name: name ...
entailment
def create_dataset(config: dict, output_dir: Optional[str]=None) -> AbstractDataset: """ Create a dataset object according to the given config. Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string. :param config: config dict with dataset config ...
Create a dataset object according to the given config. Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string. :param config: config dict with dataset config :param output_dir: path to the training output dir or None :return: dataset object
entailment
def create_model(config: dict, output_dir: Optional[str], dataset: AbstractDataset, restore_from: Optional[str]=None) -> AbstractModel: """ Create a model object either from scratch of from the checkpoint in ``resume_dir``. Cxflow allows the following scenarios 1. Create model: leave ...
Create a model object either from scratch of from the checkpoint in ``resume_dir``. Cxflow allows the following scenarios 1. Create model: leave ``restore_from=None`` and specify ``class``; 2. Restore model: specify ``restore_from`` which is a backend-specific path to (a directory with) the saved model. ...
entailment
def create_hooks(config: dict, model: AbstractModel, dataset: AbstractDataset, output_dir: str) -> Iterable[AbstractHook]: """ Create hooks specified in ``config['hooks']`` list. Hook config entries may be one of the following types: .. code-block:: yaml :caption: A hook with ...
Create hooks specified in ``config['hooks']`` list. Hook config entries may be one of the following types: .. code-block:: yaml :caption: A hook with default args specified only by its name as a string; e.g. hooks: - LogVariables - cxflow_tensorflow.WriteTensorBoard ....
entailment
def run(config: dict, output_root: str, restore_from: str=None, eval: Optional[str]=None) -> None: """ Run **cxflow** training configured by the passed `config`. Unique ``output_dir`` for this training is created under the given ``output_root`` dir wherein all the training outputs are saved. The output...
Run **cxflow** training configured by the passed `config`. Unique ``output_dir`` for this training is created under the given ``output_root`` dir wherein all the training outputs are saved. The output dir name will be roughly ``[model.name]_[time]``. The training procedure consists of the following steps:...
entailment
def _safe_rmtree(dir_: str): """Wrap ``shutil.rmtree`` to inform user about (un)success.""" try: rmtree(dir_) except OSError: logging.warning('\t\t Skipping %s due to OSError', dir_) else: logging.debug('\t\t Deleted %s', dir_)
Wrap ``shutil.rmtree`` to inform user about (un)success.
entailment
def _prune_subdirs(dir_: str) -> None: """ Delete all subdirs in training log dirs. :param dir_: dir with training log dirs """ for logdir in [path.join(dir_, f) for f in listdir(dir_) if is_train_dir(path.join(dir_, f))]: for subdir in [path.join(logdir, f) for f in listdir(logdir) if path...
Delete all subdirs in training log dirs. :param dir_: dir with training log dirs
entailment
def _prune(dir_: str, epochs: int) -> None: """ Delete all training dirs with incomplete training artifacts or with less than specified epochs done. :param dir_: dir with training log dirs :param epochs: minimum number of finished epochs to keep the training logs :return: number of log dirs pruned ...
Delete all training dirs with incomplete training artifacts or with less than specified epochs done. :param dir_: dir with training log dirs :param epochs: minimum number of finished epochs to keep the training logs :return: number of log dirs pruned
entailment
def prune_train_dirs(dir_: str, epochs: int, subdirs: bool) -> None: """ Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`. :param dir_: dir to be pruned :param epochs: minimum number of finished epochs to keep the training logs :param ...
Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`. :param dir_: dir to be pruned :param epochs: minimum number of finished epochs to keep the training logs :param subdirs: delete subdirs in training log dirs
entailment
def output_names(self) -> Iterable[str]: """List of model output names.""" self._load_models() return chain.from_iterable(map(lambda m: m.output_names, self._models))
List of model output names.
entailment
def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch: """ Run all the models in-order and return accumulated outputs. N-th model is fed with the original inputs and outputs of all the models that were run before it. .. warning:: :py:class:`Seq...
Run all the models in-order and return accumulated outputs. N-th model is fed with the original inputs and outputs of all the models that were run before it. .. warning:: :py:class:`Sequence` model can not be trained. :param batch: batch to be processed :param train: ``Tru...
entailment
def _log_variables(self, epoch_data: EpochData): """ Log variables from the epoch data. .. warning:: At the moment, only scalars and dicts of scalars are properly formatted and logged. Other value types are ignored by default. One may set ``on_unknown_type`` to ...
Log variables from the epoch data. .. warning:: At the moment, only scalars and dicts of scalars are properly formatted and logged. Other value types are ignored by default. One may set ``on_unknown_type`` to ``str`` in order to log all the variables anyways. :param ep...
entailment
def get_reference_end_from_cigar(reference_start, cigar): ''' This returns the coordinate just past the last aligned base. This matches the behavior of pysam's reference_end method ''' reference_end = reference_start # iterate through cigartuple for i in ...
This returns the coordinate just past the last aligned base. This matches the behavior of pysam's reference_end method
entailment
def set_order_by_clip(self, a, b): ''' Determine which SplitPiece is the leftmost based on the side of the longest clipping operation ''' if self.is_left_clip(a.cigar): self.query_left = b self.query_right = a else: self.query_left = a ...
Determine which SplitPiece is the leftmost based on the side of the longest clipping operation
entailment
def is_left_clip(self, cigar): ''' whether the left side of the read (w/ respect to reference) is clipped. Clipping side is determined as the side with the longest clip. Adjacent clipping operations are not considered ''' left_tuple = cigar[0] right_tuple = cigar[...
whether the left side of the read (w/ respect to reference) is clipped. Clipping side is determined as the side with the longest clip. Adjacent clipping operations are not considered
entailment
def mad(arr): """ Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation """ arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays. med = np.median(arr) ...
Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation
entailment
def _is_streaming_request(self): """check request is stream request or not""" arg2 = self.argstreams[1] arg3 = self.argstreams[2] return not (isinstance(arg2, InMemStream) and isinstance(arg3, InMemStream) and ((arg2.auto_close and arg3.auto_close)...
check request is stream request or not
entailment
def should_retry_on_error(self, error): """rules for retry :param error: ProtocolException that returns from Server """ if self.is_streaming_request: # not retry for streaming request return False retry_flag = self.headers.get('re', retry.DE...
rules for retry :param error: ProtocolException that returns from Server
entailment
def client_for(service, service_module, thrift_service_name=None): """Build a synchronous client class for the given Thrift service. The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments. Given ``CommentService`` defined in ``comment.thrift`` and registe...
Build a synchronous client class for the given Thrift service. The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments. Given ``CommentService`` defined in ``comment.thrift`` and registered with Hyperbahn under the name "comment", here's how this might be ...
entailment
def generate_method(method_name): """Generate a method for a given Thrift service. Uses the provided TChannelSyncClient's threadloop in order to convert RPC calls to concurrent.futures :param method_name: Method being called. :return: A method that invokes the RPC using TChannelSyncClient """ ...
Generate a method for a given Thrift service. Uses the provided TChannelSyncClient's threadloop in order to convert RPC calls to concurrent.futures :param method_name: Method being called. :return: A method that invokes the RPC using TChannelSyncClient
entailment
def read_full(stream): """Read the full contents of the given stream into memory. :return: A future containing the complete stream contents. """ assert stream, "stream is required" chunks = [] chunk = yield stream.read() while chunk: chunks.append(chunk) chunk = yi...
Read the full contents of the given stream into memory. :return: A future containing the complete stream contents.
entailment
def maybe_stream(s): """Ensure that the given argument is a stream.""" if isinstance(s, Stream): return s if s is None: stream = InMemStream() stream.close() # we don't intend to write anything return stream if isinstance(s, unicode): s = s.encode('utf-8') ...
Ensure that the given argument is a stream.
entailment
def build_raw_error_message(protocol_exception): """build protocol level error message based on Error object""" message = ErrorMessage( id=protocol_exception.id, code=protocol_exception.code, tracing=protocol_exception.tracing, description=protocol_exception.description, ) ...
build protocol level error message based on Error object
entailment
def build_raw_request_message(self, request, args, is_completed=False): """build protocol level message based on request and args. request object contains meta information about outgoing request. args are the currently chunk data from argstreams is_completed tells the flags of the messa...
build protocol level message based on request and args. request object contains meta information about outgoing request. args are the currently chunk data from argstreams is_completed tells the flags of the message :param request: Request :param args: array of arg streams ...
entailment
def build_raw_response_message(self, response, args, is_completed=False): """build protocol level message based on response and args. response object contains meta information about outgoing response. args are the currently chunk data from argstreams is_completed tells the flags of the ...
build protocol level message based on response and args. response object contains meta information about outgoing response. args are the currently chunk data from argstreams is_completed tells the flags of the message :param response: Response :param args: array of arg streams ...
entailment
def build_request(self, message): """Build inbound request object from protocol level message info. It is allowed to take incompleted CallRequestMessage. Therefore the created request may not contain whole three arguments. :param message: CallRequestMessage :return: request obj...
Build inbound request object from protocol level message info. It is allowed to take incompleted CallRequestMessage. Therefore the created request may not contain whole three arguments. :param message: CallRequestMessage :return: request object
entailment
def build_response(self, message): """Build response object from protocol level message info It is allowed to take incompleted CallResponseMessage. Therefore the created request may not contain whole three arguments. :param message: CallResponseMessage :return: response object ...
Build response object from protocol level message info It is allowed to take incompleted CallResponseMessage. Therefore the created request may not contain whole three arguments. :param message: CallResponseMessage :return: response object
entailment
def build(self, message): """buffer all the streaming messages based on the message id. Reconstruct all fragments together. :param message: incoming message :return: next complete message or None if streaming is not done """ context = None ...
buffer all the streaming messages based on the message id. Reconstruct all fragments together. :param message: incoming message :return: next complete message or None if streaming is not done
entailment
def fragment(self, message): """Fragment message based on max payload size note: if the message doesn't need to fragment, it will return a list which only contains original message itself. :param message: raw message :return: list of messages whose sizes <= max ...
Fragment message based on max payload size note: if the message doesn't need to fragment, it will return a list which only contains original message itself. :param message: raw message :return: list of messages whose sizes <= max payload size
entailment
def verify_message(self, message): """Verify the checksum of the message.""" if verify_checksum( message, self.in_checksum.get(message.id, 0), ): self.in_checksum[message.id] = message.checksum[1] if message.flags == FlagsType.none: ...
Verify the checksum of the message.
entailment
def chain(*rws): """Build a ReadWriter from the given list of ReadWriters. .. code-block:: python chain( number(1), number(8), len_prefixed_string(number(2)), ) # == n1:1 n2:8 s~2 Reads/writes from the given ReadWriters in-order. Returns lists of value...
Build a ReadWriter from the given list of ReadWriters. .. code-block:: python chain( number(1), number(8), len_prefixed_string(number(2)), ) # == n1:1 n2:8 s~2 Reads/writes from the given ReadWriters in-order. Returns lists of values in the same order ...
entailment
def take(self, stream, num): """Read the given number of bytes from the stream. :param stream: stream to read from :param num: number of bytes to read :raises ReadError: if the stream did not yield the exact number of bytes expected """ ...
Read the given number of bytes from the stream. :param stream: stream to read from :param num: number of bytes to read :raises ReadError: if the stream did not yield the exact number of bytes expected
entailment
def get_service_methods(iface): """Get a list of methods defined in the interface for a Thrift service. :param iface: The Thrift-generated Iface class defining the interface for the service. :returns: A set containing names of the methods defined for the service. """ methods...
Get a list of methods defined in the interface for a Thrift service. :param iface: The Thrift-generated Iface class defining the interface for the service. :returns: A set containing names of the methods defined for the service.
entailment
def deprecate(message): """Loudly prints warning.""" warnings.simplefilter('default') warnings.warn(message, category=DeprecationWarning) warnings.resetwarnings()
Loudly prints warning.
entailment
def deprecated(message): """Warn every time a fn is called.""" def decorator(fn): @functools.wraps(fn) def new_fn(*args, **kwargs): deprecate(message) return fn(*args, **kwargs) return new_fn return decorator
Warn every time a fn is called.
entailment
def load(path, service=None, hostport=None, module_name=None): """Loads the Thrift file at the specified path. The file is compiled in-memory and a Python module containing the result is returned. It may be used with ``TChannel.thrift``. For example, .. code-block:: python from tchannel impor...
Loads the Thrift file at the specified path. The file is compiled in-memory and a Python module containing the result is returned. It may be used with ``TChannel.thrift``. For example, .. code-block:: python from tchannel import TChannel, thrift # Load our server's interface definition. ...
entailment
def register(dispatcher, service, handler=None, method=None): """ :param dispatcher: RequestDispatcher against which the new endpoint will be registered. :param Service service: Service object representing the service whose endpoint is being registered. :param handler: A ...
:param dispatcher: RequestDispatcher against which the new endpoint will be registered. :param Service service: Service object representing the service whose endpoint is being registered. :param handler: A function implementing the given Thrift function. :param method: ...
entailment
def interface_ip(interface): """Determine the IP assigned to us by the given network interface.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa( fcntl.ioctl( sock.fileno(), 0x8915, struct.pack('256s', interface[:15]) )[20:24] )
Determine the IP assigned to us by the given network interface.
entailment