project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | trainer_lib.py | T2TExperiment.continuous_decode_on_train_data | continuous_decode_on_train_data | Decode from dataset on new checkpoint. | [
"Decode",
"from",
"dataset",
"on",
"new",
"checkpoint."
] | def continuous_decode_on_train_data(self):
for _ in next_checkpoint(self._hparams.model_dir):
self.decode(dataset_split=tf.estimator.ModeKeys.TRAIN) | ['def', 'continuous_decode_on_train_data(self):', 'for', '_', 'in', 'next_checkpoint(self._hparams.model_dir):', 'self.decode(dataset_split=tf.estimator.ModeKeys.TRAIN)'] | 966,233 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_metrics.py | compute_one_decoding_video_metrics | compute_one_decoding_video_metrics | Computes the average of all the metric for one decoding. | [
"Computes",
"the",
"average",
"of",
"all",
"the",
"metric",
"for",
"one",
"decoding."
] | def compute_one_decoding_video_metrics(iterator, feed_dict, num_videos):
(output, target) = iterator.get_next()
metrics_dict = compute_metrics(output, target)
(metrics_names, metrics) = zip(*six.iteritems(metrics_dict))
(means, update_ops) = tf.metrics.mean_tensor(metrics)
with tf.Session() as sess:... | ['def', 'compute_one_decoding_video_metrics(iterator,', 'feed_dict,', 'num_videos):', '(output,', 'target)', '=', 'iterator.get_next()', 'metrics_dict', '=', 'compute_metrics(output,', 'target)', '(metrics_names,', 'metrics)', '=', 'zip(*six.iteritems(metrics_dict))', '(means,', 'update_ops)', '=', 'tf.metrics.mean_ten... | 966,238 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_metrics.py | compute_all_metrics_statistics | compute_all_metrics_statistics | Computes statistics of metrics across multiple decodings. | [
"Computes",
"statistics",
"of",
"metrics",
"across",
"multiple",
"decodings."
] | def compute_all_metrics_statistics(all_results):
statistics = {}
for key in all_results[0].keys():
values = [result[key] for result in all_results]
values = np.vstack(values)
statistics[key + '_MEAN'] = np.mean(values, axis=0)
statistics[key + '_STD'] = np.std(values, axis=0)
... | ['def', 'compute_all_metrics_statistics(all_results):', 'statistics', '=', '{}', 'for', 'key', 'in', 'all_results[0].keys():', 'values', '=', '[result[key]', 'for', 'result', 'in', 'all_results]', 'values', '=', 'np.vstack(values)', 'statistics[key', '+', "'_MEAN']", '=', 'np.mean(values,', 'axis=0)', 'statistics[key',... | 966,239 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_metrics.py | compute_and_save_video_metrics | compute_and_save_video_metrics | Compute and saves the video metrics. | [
"Compute",
"and",
"saves",
"the",
"video",
"metrics."
] | def compute_and_save_video_metrics(output_dirs, problem_name, video_length, frame_shape):
(statistics, all_results) = compute_video_metrics_from_png_files(output_dirs, problem_name, video_length, frame_shape)
for (results, output_dir) in zip(all_results, output_dirs):
save_results(results, output_dir, p... | ['def', 'compute_and_save_video_metrics(output_dirs,', 'problem_name,', 'video_length,', 'frame_shape):', '(statistics,', 'all_results)', '=', 'compute_video_metrics_from_png_files(output_dirs,', 'problem_name,', 'video_length,', 'frame_shape)', 'for', '(results,', 'output_dir)', 'in', 'zip(all_results,', 'output_dirs)... | 966,241 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | yellowfin.py | YellowFinOptimizer.apply_gradients | apply_gradients | Applying gradients and tune hyperparams with YellowFin. | [
"Applying",
"gradients",
"and",
"tune",
"hyperparams",
"with",
"YellowFin."
] | def apply_gradients(self, grads_and_vars, global_step=None, name=None):
(self._grad, self._vars) = zip(*[(g, t) for (g, t) in grads_and_vars if g is not None])
with tf.variable_scope('apply_updates'):
if self._clip_thresh_var is not None:
(self._grad, _) = tf.clip_by_global_norm(self._grad, ... | ['def', 'apply_gradients(self,', 'grads_and_vars,', 'global_step=None,', 'name=None):', '(self._grad,', 'self._vars)', '=', 'zip(*[(g,', 't)', 'for', '(g,', 't)', 'in', 'grads_and_vars', 'if', 'g', 'is', 'not', 'None])', 'with', "tf.variable_scope('apply_updates'):", 'if', 'self._clip_thresh_var', 'is', 'not', 'None:',... | 966,242 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | series.py | Series.iteritems | iteritems | Lazily iterate over (index, value) tuples. | [
"Lazily",
"iterate",
"over",
"(index,",
"value)",
"tuples."
] | def iteritems(self):
return zip(iter(self.index), iter(self)) | ['def', 'iteritems(self):', 'return', 'zip(iter(self.index),', 'iter(self))'] | 967,278 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | range.py | RangeIndex.from_range | from_range | Create RangeIndex from a range (py3), or xrange (py2) object. | [
"Create",
"RangeIndex",
"from",
"a",
"range",
"(py3),",
"or",
"xrange",
"(py2)",
"object."
] | def from_range(cls, data, name=None, dtype=None, **kwargs):
if not isinstance(data, range):
raise TypeError('{0}(...) must be called with object coercible to a range, {1} was passed'.format(cls.__name__, repr(data)))
(start, stop, step) = get_range_parameters(data)
return RangeIndex(start, stop, ste... | ['def', 'from_range(cls,', 'data,', 'name=None,', 'dtype=None,', '**kwargs):', 'if', 'not', 'isinstance(data,', 'range):', 'raise', "TypeError('{0}(...)", 'must', 'be', 'called', 'with', 'object', 'coercible', 'to', 'a', 'range,', '{1}', 'was', "passed'.format(cls.__name__,", 'repr(data)))', '(start,', 'stop,', 'step)'... | 967,764 |
huawei-noah/xingtian | record.py | ReportRecord.checkpoint_path | checkpoint_path | Set checkpoint_path and parse value into dict. | [
"Set",
"checkpoint_path",
"and",
"parse",
"value",
"into",
"dict."
] | def checkpoint_path(self, value):
self._checkpoint_path = value | ['def', 'checkpoint_path(self,', 'value):', 'self._checkpoint_path', '=', 'value'] | 968,343 |
huawei-noah/xingtian | record.py | ReportRecord.model_path | model_path | Set model_path and parse value into dict. | [
"Set",
"model_path",
"and",
"parse",
"value",
"into",
"dict."
] | def model_path(self, value):
self._model_path = value | ['def', 'model_path(self,', 'value):', 'self._model_path', '=', 'value'] | 968,344 |
huawei-noah/xingtian | record.py | ReportRecord.weights_file | weights_file | Set weights_file and parse value int dict. | [
"Set",
"weights_file",
"and",
"parse",
"value",
"int",
"dict."
] | def weights_file(self, value):
self._weights_file = value | ['def', 'weights_file(self,', 'value):', 'self._weights_file', '=', 'value'] | 968,345 |
huawei-noah/xingtian | record.py | ReportRecord.load_dict | load_dict | Load values from dict. | [
"Load",
"values",
"from",
"dict."
] | def load_dict(self, src_dic):
if src_dic:
for (key, value) in src_dic.items():
setattr(self, key, value)
return self | ['def', 'load_dict(self,', 'src_dic):', 'if', 'src_dic:', 'for', '(key,', 'value)', 'in', 'src_dic.items():', 'setattr(self,', 'key,', 'value)', 'return', 'self'] | 968,348 |
huawei-noah/xingtian | record.py | ReportRecord.from_sample | from_sample | Load values from sample. | [
"Load",
"values",
"from",
"sample."
] | def from_sample(self, sample, desc=None):
if isinstance(sample, tuple):
sample = dict(worker_id=sample[0], desc=sample[1])
self.load_dict(sample)
if desc:
self.desc = desc
return self | ['def', 'from_sample(self,', 'sample,', 'desc=None):', 'if', 'isinstance(sample,', 'tuple):', 'sample', '=', 'dict(worker_id=sample[0],', 'desc=sample[1])', 'self.load_dict(sample)', 'if', 'desc:', 'self.desc', '=', 'desc', 'return', 'self'] | 968,349 |
huawei-noah/xingtian | report_client.py | ReportClient.broadcast | broadcast | Broadcast one record to Shared Memory. | [
"Broadcast",
"one",
"record",
"to",
"Shared",
"Memory."
] | def broadcast(cls, record):
if not record:
logging.warning('Broadcast Record is None.')
return
ShareMemory('{}.{}'.format(record.step_name, record.worker_id)).put(record.serialize())
cls._save_worker_record(record.serialize()) | ['def', 'broadcast(cls,', 'record):', 'if', 'not', 'record:', "logging.warning('Broadcast", 'Record', 'is', "None.')", 'return', "ShareMemory('{}.{}'.format(record.step_name,", 'record.worker_id)).put(record.serialize())', 'cls._save_worker_record(record.serialize())'] | 968,351 |
huawei-noah/xingtian | report_server.py | ReportServer.add_watched_var | add_watched_var | Add variable to ReportServer. | [
"Add",
"variable",
"to",
"ReportServer."
] | def add_watched_var(cls, step_name, worker_id):
cls.__variables__.add('{}.{}'.format(step_name, worker_id)) | ['def', 'add_watched_var(cls,', 'step_name,', 'worker_id):', "cls.__variables__.add('{}.{}'.format(step_name,", 'worker_id))'] | 968,354 |
huawei-noah/xingtian | report_server.py | ReportServer.remove_watched_var | remove_watched_var | Remove variable from ReportServer. | [
"Remove",
"variable",
"from",
"ReportServer."
] | def remove_watched_var(cls, step_name, worker_id):
key = '{}.{}'.format(step_name, worker_id)
if key in cls.__variables__:
cls.__variables__.remove(key) | ['def', 'remove_watched_var(cls,', 'step_name,', 'worker_id):', 'key', '=', "'{}.{}'.format(step_name,", 'worker_id)', 'if', 'key', 'in', 'cls.__variables__:', 'cls.__variables__.remove(key)'] | 968,355 |
huawei-noah/xingtian | report_server.py | ReportServer.print_best | print_best | Print best performance and desc. | [
"Print",
"best",
"performance",
"and",
"desc."
] | def print_best(self, step_name):
records = self.get_pareto_front_records(step_name)
return [dict(worker_id=record.worker_id, performance=record._performance, desc=record.desc) for record in records] | ['def', 'print_best(self,', 'step_name):', 'records', '=', 'self.get_pareto_front_records(step_name)', 'return', '[dict(worker_id=record.worker_id,', 'performance=record._performance,', 'desc=record.desc)', 'for', 'record', 'in', 'records]'] | 968,356 |
huawei-noah/xingtian | report_server.py | ReportServer.get_pareto_front_records | get_pareto_front_records | Get Pareto Front Records. | [
"Get",
"Pareto",
"Front",
"Records."
] | def get_pareto_front_records(self, step_name=None, nums=None, selected_key=None):
if not step_name:
step_name = General.step_name
records = self.all_records
if selected_key is not None:
new_records = []
selected_key.sort()
for record in records:
record._objective_... | ['def', 'get_pareto_front_records(self,', 'step_name=None,', 'nums=None,', 'selected_key=None):', 'if', 'not', 'step_name:', 'step_name', '=', 'General.step_name', 'records', '=', 'self.all_records', 'if', 'selected_key', 'is', 'not', 'None:', 'new_records', '=', '[]', 'selected_key.sort()', 'for', 'record', 'in', 'rec... | 968,358 |
huawei-noah/xingtian | report_server.py | ReportServer.restore | restore | Transfer cvs_file to records. | [
"Transfer",
"cvs_file",
"to",
"records."
] | def restore(cls):
step_path = TaskOps().step_path
_file = os.path.join(step_path, '.reports')
if os.path.exists(_file):
with open(_file, 'rb') as f:
data = pickle.load(f)
cls._hist_records = data[0]
cls.__instances__ = data[1] | ['def', 'restore(cls):', 'step_path', '=', 'TaskOps().step_path', '_file', '=', 'os.path.join(step_path,', "'.reports')", 'if', 'os.path.exists(_file):', 'with', 'open(_file,', "'rb')", 'as', 'f:', 'data', '=', 'pickle.load(f)', 'cls._hist_records', '=', 'data[0]', 'cls.__instances__', '=', 'data[1]'] | 968,359 |
huawei-noah/xingtian | report_server.py | ReportServer.backup_output_path | backup_output_path | Back up output to local path. | [
"Back",
"up",
"output",
"to",
"local",
"path."
] | def backup_output_path(self):
backup_path = TaskOps().backup_base_path
if backup_path is None:
return
FileOps.copy_folder(TaskOps().local_output_path, backup_path) | ['def', 'backup_output_path(self):', 'backup_path', '=', 'TaskOps().backup_base_path', 'if', 'backup_path', 'is', 'None:', 'return', 'FileOps.copy_folder(TaskOps().local_output_path,', 'backup_path)'] | 968,360 |
huawei-noah/xingtian | report_server.py | ReportServer.output_step_all_records | output_step_all_records | Output step all records. | [
"Output",
"step",
"all",
"records."
] | def output_step_all_records(self, step_name, desc=True, weights_file=True, performance=True):
records = self.all_records
logging.debug('All records in report, records={}'.format(self.all_records))
records = list(filter(lambda x: x.step_name == step_name, records))
logging.debug('Filter step records, rec... | ['def', 'output_step_all_records(self,', 'step_name,', 'desc=True,', 'weights_file=True,', 'performance=True):', 'records', '=', 'self.all_records', "logging.debug('All", 'records', 'in', 'report,', "records={}'.format(self.all_records))", 'records', '=', 'list(filter(lambda', 'x:', 'x.step_name', '==', 'step_name,', '... | 968,361 |
huawei-noah/xingtian | report_server.py | ReportServer.dump | dump | Dump report to file. | [
"Dump",
"report",
"to",
"file."
] | def dump(self):
try:
_file = FileOps.join_path(TaskOps().step_path, 'reports.csv')
FileOps.make_base_dir(_file)
data = self.all_records
data_dict = {}
for step in data:
step_data = step.serialize().items()
for (k, v) in step_data:
if k ... | ['def', 'dump(self):', 'try:', '_file', '=', 'FileOps.join_path(TaskOps().step_path,', "'reports.csv')", 'FileOps.make_base_dir(_file)', 'data', '=', 'self.all_records', 'data_dict', '=', '{}', 'for', 'step', 'in', 'data:', 'step_data', '=', 'step.serialize().items()', 'for', '(k,', 'v)', 'in', 'step_data:', 'if', 'k',... | 968,362 |
huawei-noah/xingtian | report_server.py | ReportServer.load_records_from_model_folder | load_records_from_model_folder | Transfer json_file to records. | [
"Transfer",
"json_file",
"to",
"records."
] | def load_records_from_model_folder(cls, model_folder):
if not model_folder or not os.path.exists(model_folder):
logging.error('Failed to load records from model folder, folder={}'.format(model_folder))
return []
records = []
pattern = FileOps.join_path(model_folder, 'desc_*.json')
files ... | ['def', 'load_records_from_model_folder(cls,', 'model_folder):', 'if', 'not', 'model_folder', 'or', 'not', 'os.path.exists(model_folder):', "logging.error('Failed", 'to', 'load', 'records', 'from', 'model', 'folder,', "folder={}'.format(model_folder))", 'return', '[]', 'records', '=', '[]', 'pattern', '=', 'FileOps.joi... | 968,363 |
huawei-noah/xingtian | share_memory.py | ClusterShareMemory.get | get | Get value from shared data. | [
"Get",
"value",
"from",
"shared",
"data."
] | def get(self):
return ast.literal_eval(self.var.get(timeout=2)) | ['def', 'get(self):', 'return', 'ast.literal_eval(self.var.get(timeout=2))'] | 968,365 |
huawei-noah/xingtian | deserialize.py | pickle_worker | pickle_worker | Pickle worker to file. | [
"Pickle",
"worker",
"to",
"file."
] | def pickle_worker(worker, id):
config_file = os.path.join(worker.get_local_worker_path(), '.{0}.c.pkl'.format(id))
worker_config = _get_worker_config(worker)
with open(config_file, 'wb') as f:
pickle.dump(worker_config, f)
worker_file = os.path.join(worker.get_local_worker_path(), '.{0}.w.pkl'.f... | ['def', 'pickle_worker(worker,', 'id):', 'config_file', '=', 'os.path.join(worker.get_local_worker_path(),', "'.{0}.c.pkl'.format(id))", 'worker_config', '=', '_get_worker_config(worker)', 'with', 'open(config_file,', "'wb')", 'as', 'f:', 'pickle.dump(worker_config,', 'f)', 'worker_file', '=', 'os.path.join(worker.get_... | 968,373 |
huawei-noah/xingtian | deserialize.py | load_worker | load_worker | Load worker from file. | [
"Load",
"worker",
"from",
"file."
] | def load_worker(worker_file):
import pickle
with open(worker_file, 'rb') as f:
worker = pickle.load(f)
return worker | ['def', 'load_worker(worker_file):', 'import', 'pickle', 'with', 'open(worker_file,', "'rb')", 'as', 'f:', 'worker', '=', 'pickle.load(f)', 'return', 'worker'] | 968,375 |
huawei-noah/xingtian | distributed_worker.py | DistributedWorker.train_process | train_process | Abstract base function for DistributedWorker to do the train process. | [
"Abstract",
"base",
"function",
"for",
"DistributedWorker",
"to",
"do",
"the",
"train",
"process."
] | def train_process(self):
raise NotImplementedError | ['def', 'train_process(self):', 'raise', 'NotImplementedError'] | 968,377 |
huawei-noah/xingtian | run_remote_worker.py | run_remote_worker | run_remote_worker | Run worker on remote mochine. | [
"Run",
"worker",
"on",
"remote",
"mochine."
] | def run_remote_worker(worker_id, worker_path, id):
from zeus.common.utils import init_log
init_log(level='info', log_file='.temp_{}.log'.format(worker_id), log_path=worker_path)
config = _load_config(worker_id, worker_path, id)
zeus.register_zeus(os.environ['BACKEND_TYPE'].lower())
if zeus.is_gpu_de... | ['def', 'run_remote_worker(worker_id,', 'worker_path,', 'id):', 'from', 'zeus.common.utils', 'import', 'init_log', "init_log(level='info',", "log_file='.temp_{}.log'.format(worker_id),", 'log_path=worker_path)', 'config', '=', '_load_config(worker_id,', 'worker_path,', 'id)', "zeus.register_zeus(os.environ['BACKEND_TYP... | 968,378 |
huawei-noah/xingtian | timm_trainer_callback.py | create_loader | create_loader | Create data loader for timm. | [
"Create",
"data",
"loader",
"for",
"timm."
] | def create_loader(dataset, input_size, batch_size, is_training=False, use_prefetcher=True, rand_erase_prob=0.0, rand_erase_mode='const', rand_erase_count=1, color_jitter=0.4, auto_augment=None, interpolation='bilinear', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_workers=1, distributed=False, crop_pct=Non... | ['def', 'create_loader(dataset,', 'input_size,', 'batch_size,', 'is_training=False,', 'use_prefetcher=True,', 'rand_erase_prob=0.0,', "rand_erase_mode='const',", 'rand_erase_count=1,', 'color_jitter=0.4,', 'auto_augment=None,', "interpolation='bilinear',", 'mean=IMAGENET_DEFAULT_MEAN,', 'std=IMAGENET_DEFAULT_STD,', 'nu... | 968,387 |
huawei-noah/xingtian | timm_trainer_callback.py | TimmTrainerCallback.before_train | before_train | Be called before the training process. | [
"Be",
"called",
"before",
"the",
"training",
"process."
] | def before_train(self, logs=None):
self._init_all_settings() | ['def', 'before_train(self,', 'logs=None):', 'self._init_all_settings()'] | 968,388 |
huawei-noah/xingtian | timm_trainer_callback.py | TimmTrainerCallback.make_batch | make_batch | Prepare batch data for train_step. | [
"Prepare",
"batch",
"data",
"for",
"train_step."
] | def make_batch(self, batch):
(input, target) = batch
if self.config.cuda and (not self.config.prefetcher):
(input, target) = (input.cuda(), target.cuda())
return (input, target) | ['def', 'make_batch(self,', 'batch):', '(input,', 'target)', '=', 'batch', 'if', 'self.config.cuda', 'and', '(not', 'self.config.prefetcher):', '(input,', 'target)', '=', '(input.cuda(),', 'target.cuda())', 'return', '(input,', 'target)'] | 968,390 |
huawei-noah/xingtian | timm_trainer_callback.py | TimmTrainerCallback.train_step | train_step | Train one step of model. | [
"Train",
"one",
"step",
"of",
"model."
] | def train_step(self, batch):
(input, target) = batch
self.trainer.optimizer.zero_grad()
logits = self.trainer.model(input)
loss = self.trainer.loss(logits, target)
if self.use_amp:
with amp.scale_loss(loss, self.trainer.optimizer) as scaled_loss:
scaled_loss.backward()
... | ['def', 'train_step(self,', 'batch):', '(input,', 'target)', '=', 'batch', 'self.trainer.optimizer.zero_grad()', 'logits', '=', 'self.trainer.model(input)', 'loss', '=', 'self.trainer.loss(logits,', 'target)', 'if', 'self.use_amp:', 'with', 'amp.scale_loss(loss,', 'self.trainer.optimizer)', 'as', 'scaled_loss:', 'scale... | 968,391 |
huawei-noah/xingtian | trainer_base.py | TrainerBase.build | build | Build the trainer by assembling the necessary components. | [
"Build",
"the",
"trainer",
"by",
"assembling",
"the",
"necessary",
"components."
] | def build(self):
logging.debug('Trainer Config: {}'.format(self.config))
self._init_hps()
self.do_validation = self.config.with_valid
self.use_syncbn = self.config.syncbn
if self.use_syncbn and zeus.is_torch_backend():
import apex
self.model = apex.parallel.convert_syncbn_model(self.... | ['def', 'build(self):', "logging.debug('Trainer", 'Config:', "{}'.format(self.config))", 'self._init_hps()', 'self.do_validation', '=', 'self.config.with_valid', 'self.use_syncbn', '=', 'self.config.syncbn', 'if', 'self.use_syncbn', 'and', 'zeus.is_torch_backend():', 'import', 'apex', 'self.model', '=', 'apex.parallel.... | 968,395 |
huawei-noah/xingtian | callback_list.py | CallbackList.set_trainer | set_trainer | Set the trainer object for callback container. | [
"Set",
"the",
"trainer",
"object",
"for",
"callback",
"container."
] | def set_trainer(self, trainer):
self.trainer = trainer
for callback in self.callbacks:
callback.set_trainer(trainer) | ['def', 'set_trainer(self,', 'trainer):', 'self.trainer', '=', 'trainer', 'for', 'callback', 'in', 'self.callbacks:', 'callback.set_trainer(trainer)'] | 968,433 |
huawei-noah/xingtian | callback_list.py | CallbackList.init_trainer | init_trainer | Call before_epoch of the managed callbacks. | [
"Call",
"before_epoch",
"of",
"the",
"managed",
"callbacks."
] | def init_trainer(self, logs=None):
logs = logs or {}
for callback in self.callbacks:
callback.init_trainer(logs) | ['def', 'init_trainer(self,', 'logs=None):', 'logs', '=', 'logs', 'or', '{}', 'for', 'callback', 'in', 'self.callbacks:', 'callback.init_trainer(logs)'] | 968,434 |
huawei-noah/xingtian | callback_list.py | CallbackList.before_train_step | before_train_step | Call before_train_step of the managed callbacks. | [
"Call",
"before_train_step",
"of",
"the",
"managed",
"callbacks."
] | def before_train_step(self, batch_index, logs=None):
logs = logs or {}
for callback in self.callbacks:
callback.before_train_step(batch_index, logs) | ['def', 'before_train_step(self,', 'batch_index,', 'logs=None):', 'logs', '=', 'logs', 'or', '{}', 'for', 'callback', 'in', 'self.callbacks:', 'callback.before_train_step(batch_index,', 'logs)'] | 968,437 |
huawei-noah/xingtian | callback_list.py | CallbackList.after_epoch | after_epoch | Call after_epoch of the managed callbacks. | [
"Call",
"after_epoch",
"of",
"the",
"managed",
"callbacks."
] | def after_epoch(self, epoch, logs=None):
logs = logs or {}
for callback in self.callbacks:
callback.after_epoch(epoch, logs) | ['def', 'after_epoch(self,', 'epoch,', 'logs=None):', 'logs', '=', 'logs', 'or', '{}', 'for', 'callback', 'in', 'self.callbacks:', 'callback.after_epoch(epoch,', 'logs)'] | 968,439 |
huawei-noah/xingtian | callback_list.py | CallbackList.after_train | after_train | Call after_train of the managed callbacks. | [
"Call",
"after_train",
"of",
"the",
"managed",
"callbacks."
] | def after_train(self, logs=None):
logs = logs or {}
for callback in self.callbacks:
callback.after_train(logs) | ['def', 'after_train(self,', 'logs=None):', 'logs', '=', 'logs', 'or', '{}', 'for', 'callback', 'in', 'self.callbacks:', 'callback.after_train(logs)'] | 968,440 |
huawei-noah/xingtian | callback_list.py | CallbackList.after_valid_step | after_valid_step | Call after_valid_step of the managed callbacks. | [
"Call",
"after_valid_step",
"of",
"the",
"managed",
"callbacks."
] | def after_valid_step(self, batch_index, logs=None):
logs = logs or {}
for callback in self.callbacks:
callback.after_valid_step(batch_index, logs) | ['def', 'after_valid_step(self,', 'batch_index,', 'logs=None):', 'logs', '=', 'logs', 'or', '{}', 'for', 'callback', 'in', 'self.callbacks:', 'callback.after_valid_step(batch_index,', 'logs)'] | 968,443 |
huawei-noah/xingtian | detection_metrics_evaluator.py | DetectionMetricsEvaluator.before_epoch | before_epoch | Be called before each epoach. | [
"Be",
"called",
"before",
"each",
"epoach."
] | def before_epoch(self, epoch, logs=None):
super().before_epoch(epoch, logs)
self.loss_sum_during_epoch_period = 0
self.step_count_during_epoch_period = 0 | ['def', 'before_epoch(self,', 'epoch,', 'logs=None):', 'super().before_epoch(epoch,', 'logs)', 'self.loss_sum_during_epoch_period', '=', '0', 'self.step_count_during_epoch_period', '=', '0'] | 968,446 |
huawei-noah/xingtian | detection_metrics_evaluator.py | DetectionMetricsEvaluator.after_train_step | after_train_step | Be called after each train batch. | [
"Be",
"called",
"after",
"each",
"train",
"batch."
] | def after_train_step(self, batch_index, logs=None):
(input, target) = self.train_batch
batch_size = input.size(0)
self.cur_loss = logs['loss']
self.loss_avg = self._average_loss_during_train_period(batch_size, self.cur_loss)
logs.update({'cur_loss': self.cur_loss, 'loss_avg': self.loss_avg}) | ['def', 'after_train_step(self,', 'batch_index,', 'logs=None):', '(input,', 'target)', '=', 'self.train_batch', 'batch_size', '=', 'input.size(0)', 'self.cur_loss', '=', "logs['loss']", 'self.loss_avg', '=', 'self._average_loss_during_train_period(batch_size,', 'self.cur_loss)', "logs.update({'cur_loss':", 'self.cur_lo... | 968,447 |
huawei-noah/xingtian | detection_progress_logger.py | DetectionProgressLogger.after_train_step | after_train_step | Be called before each batch training. | [
"Be",
"called",
"before",
"each",
"batch",
"training."
] | def after_train_step(self, batch_index, logs=None):
if self.train_verbose >= 2 and self.is_chief and (batch_index % self.train_report_steps == 0):
try:
out_buffer = OrderedDict(time=time.strftime('%Y-%m-%d @ %H:%M:%S'), epoch=f'{self.cur_epoch}/{self.epochs}', step=f'{self._format_batch(batch_in... | ['def', 'after_train_step(self,', 'batch_index,', 'logs=None):', 'if', 'self.train_verbose', '>=', '2', 'and', 'self.is_chief', 'and', '(batch_index', '%', 'self.train_report_steps', '==', '0):', 'try:', 'out_buffer', '=', "OrderedDict(time=time.strftime('%Y-%m-%d", '@', "%H:%M:%S'),", "epoch=f'{self.cur_epoch}/{self.e... | 968,449 |
huawei-noah/xingtian | detection_progress_logger.py | DetectionProgressLogger.after_valid_step | after_valid_step | Be called after each batch of the validation. | [
"Be",
"called",
"after",
"each",
"batch",
"of",
"the",
"validation."
] | def after_valid_step(self, batch_index, logs=None):
if self.valid_verbose >= 2 and self.is_chief and self.do_validation and (batch_index % self.valid_report_steps == 0):
metrics_results = logs.get('valid_step_metrics', None)
if metrics_results is not None:
out_buffer = OrderedDict(time=t... | ['def', 'after_valid_step(self,', 'batch_index,', 'logs=None):', 'if', 'self.valid_verbose', '>=', '2', 'and', 'self.is_chief', 'and', 'self.do_validation', 'and', '(batch_index', '%', 'self.valid_report_steps', '==', '0):', 'metrics_results', '=', "logs.get('valid_step_metrics',", 'None)', 'if', 'metrics_results', 'is... | 968,450 |
huawei-noah/xingtian | detection_progress_logger.py | DetectionProgressLogger.after_valid | after_valid | Be called after validation. | [
"Be",
"called",
"after",
"validation."
] | def after_valid(self, logs=None):
if self.valid_verbose >= 1 and self.is_chief and self.do_validation:
cur_valid_perfs = logs.get('cur_valid_perfs', None)
if cur_valid_perfs is not None:
log_info = 'epoch [{}/{}], current valid perfs {}'.format(self.cur_epoch + 1, self.epochs, self._form... | ['def', 'after_valid(self,', 'logs=None):', 'if', 'self.valid_verbose', '>=', '1', 'and', 'self.is_chief', 'and', 'self.do_validation:', 'cur_valid_perfs', '=', "logs.get('cur_valid_perfs',", 'None)', 'if', 'cur_valid_perfs', 'is', 'not', 'None:', 'log_info', '=', "'epoch", '[{}/{}],', 'current', 'valid', 'perfs', "{}'... | 968,451 |
huawei-noah/xingtian | lr_scheduler.py | LearningRateScheduler.before_train | before_train | Be called before training. | [
"Be",
"called",
"before",
"training."
] | def before_train(self, logs=None):
self.lr_scheduler = self.trainer.lr_scheduler | ['def', 'before_train(self,', 'logs=None):', 'self.lr_scheduler', '=', 'self.trainer.lr_scheduler'] | 968,452 |
huawei-noah/xingtian | lr_scheduler.py | LearningRateScheduler.after_epoch | after_epoch | Be called before each epoch. | [
"Be",
"called",
"before",
"each",
"epoch."
] | def after_epoch(self, epoch, logs=None):
if self.lr_scheduler and self.lr_scheduler.by_epoch:
self.lr_scheduler.step(epoch=epoch) | ['def', 'after_epoch(self,', 'epoch,', 'logs=None):', 'if', 'self.lr_scheduler', 'and', 'self.lr_scheduler.by_epoch:', 'self.lr_scheduler.step(epoch=epoch)'] | 968,454 |
huawei-noah/xingtian | lr_scheduler.py | LearningRateScheduler.after_train_step | after_train_step | Call after_train_step of the managed callbacks. | [
"Call",
"after_train_step",
"of",
"the",
"managed",
"callbacks."
] | def after_train_step(self, batch_index, logs=None):
if self.lr_scheduler and (not self.lr_scheduler.by_epoch):
step = self.trainer.batch_num_train * self.epoch + self.epoch + batch_index
self.lr_scheduler.step(epoch=step) | ['def', 'after_train_step(self,', 'batch_index,', 'logs=None):', 'if', 'self.lr_scheduler', 'and', '(not', 'self.lr_scheduler.by_epoch):', 'step', '=', 'self.trainer.batch_num_train', '*', 'self.epoch', '+', 'self.epoch', '+', 'batch_index', 'self.lr_scheduler.step(epoch=step)'] | 968,455 |
huawei-noah/xingtian | metrics_evaluator.py | MetricsEvaluator.before_train_step | before_train_step | Be called before a batch training. | [
"Be",
"called",
"before",
"a",
"batch",
"training."
] | def before_train_step(self, batch_index, logs=None):
self.train_batch = logs['train_batch'] | ['def', 'before_train_step(self,', 'batch_index,', 'logs=None):', 'self.train_batch', '=', "logs['train_batch']"] | 968,458 |
huawei-noah/xingtian | metrics_evaluator.py | MetricsEvaluator.before_valid_step | before_valid_step | Be called before a batch validation. | [
"Be",
"called",
"before",
"a",
"batch",
"validation."
] | def before_valid_step(self, batch_index, logs=None):
self.valid_batch = logs['valid_batch'] | ['def', 'before_valid_step(self,', 'batch_index,', 'logs=None):', 'self.valid_batch', '=', "logs['valid_batch']"] | 968,460 |
huawei-noah/xingtian | metrics_evaluator.py | MetricsEvaluator.after_epoch | after_epoch | Be called after each epoch. | [
"Be",
"called",
"after",
"each",
"epoch."
] | def after_epoch(self, epoch, logs=None):
self.summary_perfs = logs.get('summary_perfs', {})
self.summary_perfs.update({'loss_avg': self.loss_avg})
if self.train_metrics is not None and self.get_train_metric_after_epoch:
metrics_results = self.train_metrics.results
self.cur_train_perfs = metr... | ['def', 'after_epoch(self,', 'epoch,', 'logs=None):', 'self.summary_perfs', '=', "logs.get('summary_perfs',", '{})', "self.summary_perfs.update({'loss_avg':", 'self.loss_avg})', 'if', 'self.train_metrics', 'is', 'not', 'None', 'and', 'self.get_train_metric_after_epoch:', 'metrics_results', '=', 'self.train_metrics.resu... | 968,463 |
huawei-noah/xingtian | model_statistics.py | ModelStatistics.after_train_step | after_train_step | Be called after each batch of Training. | [
"Be",
"called",
"after",
"each",
"batch",
"of",
"Training."
] | def after_train_step(self, batch_index, logs=None):
try:
if self.input is None:
(input, target) = logs['train_batch']
self.input = torch.unsqueeze(input[0], 0)
except Exception as ex:
logging.warning('model statics failed, ex=%s', ex) | ['def', 'after_train_step(self,', 'batch_index,', 'logs=None):', 'try:', 'if', 'self.input', 'is', 'None:', '(input,', 'target)', '=', "logs['train_batch']", 'self.input', '=', 'torch.unsqueeze(input[0],', '0)', 'except', 'Exception', 'as', 'ex:', "logging.warning('model", 'statics', 'failed,', "ex=%s',", 'ex)'] | 968,469 |
huawei-noah/xingtian | model_statistics.py | ModelStatistics.after_train | after_train | Be called after train. | [
"Be",
"called",
"after",
"train."
] | def after_train(self, logs=None):
if not self.calc_params_each_epoch:
self.update_flops_params(logs=logs)
if self.calc_latency:
self.update_latency(logs=logs) | ['def', 'after_train(self,', 'logs=None):', 'if', 'not', 'self.calc_params_each_epoch:', 'self.update_flops_params(logs=logs)', 'if', 'self.calc_latency:', 'self.update_latency(logs=logs)'] | 968,471 |
huawei-noah/xingtian | runtime_callback.py | RuntimeCallback.after_epoch | after_epoch | Obtain estimated running time after epoch. | [
"Obtain",
"estimated",
"running",
"time",
"after",
"epoch."
] | def after_epoch(self, epoch, logs=None):
self.remain_time['train'] = self.rt_est.remaining_time('train', step=epoch + 1)
using_time = self.rt_est.using_time('train')
self.whole_time['train'] = self.remain_time['train'] + using_time
logs.update({'runtime': {'remain_time': self.remain_time, 'whole_time': ... | ['def', 'after_epoch(self,', 'epoch,', 'logs=None):', "self.remain_time['train']", '=', "self.rt_est.remaining_time('train',", 'step=epoch', '+', '1)', 'using_time', '=', "self.rt_est.using_time('train')", "self.whole_time['train']", '=', "self.remain_time['train']", '+', 'using_time', "logs.update({'runtime':", "{'rem... | 968,489 |
huawei-noah/xingtian | runtime_callback.py | RuntimeCallback.after_train_step | after_train_step | Obtain estimated running time after step. | [
"Obtain",
"estimated",
"running",
"time",
"after",
"step."
] | def after_train_step(self, batch_index, logs=None):
self.remain_time['epoch'] = self.rt_est.remaining_time('epoch', step=batch_index + 1)
using_time = self.rt_est.using_time('epoch')
self.whole_time['epoch'] = self.remain_time['epoch'] + using_time | ['def', 'after_train_step(self,', 'batch_index,', 'logs=None):', "self.remain_time['epoch']", '=', "self.rt_est.remaining_time('epoch',", 'step=batch_index', '+', '1)', 'using_time', '=', "self.rt_est.using_time('epoch')", "self.whole_time['epoch']", '=', "self.remain_time['epoch']", '+', 'using_time'] | 968,490 |
huawei-noah/xingtian | visual_callback.py | make_keys_readable | make_keys_readable | Make keys readable with flat&join. | [
"Make",
"keys",
"readable",
"with",
"flat&join."
] | def make_keys_readable(records):
return [('/'.join(k), v) for (k, v) in _flat_items(records)] | ['def', 'make_keys_readable(records):', 'return', "[('/'.join(k),", 'v)', 'for', '(k,', 'v)', 'in', '_flat_items(records)]'] | 968,492 |
huawei-noah/xingtian | visual_callback.py | VisualCallBack.before_train | before_train | Fetch trainer info before train stage. | [
"Fetch",
"trainer",
"info",
"before",
"train",
"stage."
] | def before_train(self, logs=None):
self._fix_path = '_'.join([self.trainer.step_name, str(self.trainer.worker_id)])
self.summary = SummaryBoard(self._archive_root, self._fix_path)
if zeus.is_tf_backend():
import tensorflow as tf
datasets = self.trainer.valid_input_fn()
data_iter = tf... | ['def', 'before_train(self,', 'logs=None):', 'self._fix_path', '=', "'_'.join([self.trainer.step_name,", 'str(self.trainer.worker_id)])', 'self.summary', '=', 'SummaryBoard(self._archive_root,', 'self._fix_path)', 'if', 'zeus.is_tf_backend():', 'import', 'tensorflow', 'as', 'tf', 'datasets', '=', 'self.trainer.valid_in... | 968,493 |
huawei-noah/xingtian | visual_callback.py | VisualCallBack.after_train | after_train | Shutdown summary after train. | [
"Shutdown",
"summary",
"after",
"train."
] | def after_train(self, logs=None):
self.summary.close() | ['def', 'after_train(self,', 'logs=None):', 'self.summary.close()'] | 968,497 |
huawei-noah/xingtian | ms_lr_scheduler.py | MultiStepLR.construct | construct | Call lr scheduler class. | [
"Call",
"lr",
"scheduler",
"class."
] | def construct(self, global_step):
lr_each_step = []
decay_step_index = [int(global_step * (self.milestones[i] / self.total_epoch)) for i in range(len(self.milestones) + 1)]
for i in range(global_step):
if i < decay_step_index[0]:
lr_each_step.append(self.base_lr)
elif i < decay_s... | ['def', 'construct(self,', 'global_step):', 'lr_each_step', '=', '[]', 'decay_step_index', '=', '[int(global_step', '*', '(self.milestones[i]', '/', 'self.total_epoch))', 'for', 'i', 'in', 'range(len(self.milestones)', '+', '1)]', 'for', 'i', 'in', 'range(global_step):', 'if', 'i', '<', 'decay_step_index[0]:', 'lr_each... | 968,507 |
huawei-noah/xingtian | warmup_scheduler_tf.py | WarmupScheduler.step | step | Step forward for current scheduler. | [
"Step",
"forward",
"for",
"current",
"scheduler."
] | def step(self, epoch=None):
self.lr.step(epoch) | ['def', 'step(self,', 'epoch=None):', 'self.lr.step(epoch)'] | 968,512 |
huawei-noah/xingtian | optimizer.py | dynamic_distributed_optimizer | dynamic_distributed_optimizer | Dynamically choose distributed optimizer. | [
"Dynamically",
"choose",
"distributed",
"optimizer."
] | def dynamic_distributed_optimizer(optimizer_class, optimizer):
class DynamicDistributedOptimizer(optimizer_class, OptimizerStep):
def __init__(self, optimizer):
optimizer_class.__init__(self, optimizer)
OptimizerStep.__init__(self, learning_rate=optimizer.base_lr, weight_decay=opti... | ['def', 'dynamic_distributed_optimizer(optimizer_class,', 'optimizer):', 'class', 'DynamicDistributedOptimizer(optimizer_class,', 'OptimizerStep):', 'def', '__init__(self,', 'optimizer):', 'optimizer_class.__init__(self,', 'optimizer)', 'OptimizerStep.__init__(self,', 'learning_rate=optimizer.base_lr,', 'weight_decay=o... | 968,514 |
huawei-noah/xingtian | optimizer.py | OptimizerStep.set_lr | set_lr | Uptate learning rate of optimizer. | [
"Uptate",
"learning",
"rate",
"of",
"optimizer."
] | def set_lr(self, learning_rate):
if hasattr(self, '_learning_rate'):
self._learning_rate = learning_rate
elif hasattr(self, '_lr'):
self._lr = learning_rate | ['def', 'set_lr(self,', 'learning_rate):', 'if', 'hasattr(self,', "'_learning_rate'):", 'self._learning_rate', '=', 'learning_rate', 'elif', 'hasattr(self,', "'_lr'):", 'self._lr', '=', 'learning_rate'] | 968,515 |
huawei-noah/xingtian | optimizer.py | OptimizerStep.step | step | Compute and update gradients. | [
"Compute",
"and",
"update",
"gradients."
] | def step(self, loss, loss_scale, global_step, var_list=None):
loss = loss + self.regularize_loss(loss)
if loss_scale != 1:
scaled_grad_vars = self.compute_gradients(loss * loss_scale, var_list=var_list)
unscaled_grad_vars = []
for (grad, var) in scaled_grad_vars:
unscaled_gra... | ['def', 'step(self,', 'loss,', 'loss_scale,', 'global_step,', 'var_list=None):', 'loss', '=', 'loss', '+', 'self.regularize_loss(loss)', 'if', 'loss_scale', '!=', '1:', 'scaled_grad_vars', '=', 'self.compute_gradients(loss', '*', 'loss_scale,', 'var_list=var_list)', 'unscaled_grad_vars', '=', '[]', 'for', '(grad,', 'va... | 968,516 |
huawei-noah/xingtian | optimizer.py | OptimizerStep.regularize_loss | regularize_loss | Compute and return l2 loss. | [
"Compute",
"and",
"return",
"l2",
"loss."
] | def regularize_loss(self, loss):
l2_loss_list = [tf.nn.l2_loss(v) for v in tf.compat.v1.trainable_variables() if 'batch_normalization' not in v.name]
loss = loss + self.weight_decay * tf.add_n(l2_loss_list)
return loss | ['def', 'regularize_loss(self,', 'loss):', 'l2_loss_list', '=', '[tf.nn.l2_loss(v)', 'for', 'v', 'in', 'tf.compat.v1.trainable_variables()', 'if', "'batch_normalization'", 'not', 'in', 'v.name]', 'loss', '=', 'loss', '+', 'self.weight_decay', '*', 'tf.add_n(l2_loss_list)', 'return', 'loss'] | 968,517 |
huawei-noah/xingtian | loss.py | NT_Xent.forward | forward | Calculate the compare loss. | [
"Calculate",
"the",
"compare",
"loss."
] | def forward(self, z_i, z_j):
N = 2 * self.batch_size
z = torch.cat((z_i, z_j), dim=0)
sim = self.similarity_f(z.unsqueeze(1), z.unsqueeze(0)) / self.temperature
sim_i_j = torch.diag(sim, self.batch_size)
sim_j_i = torch.diag(sim, -self.batch_size)
positive_samples = torch.cat((sim_i_j, sim_j_i),... | ['def', 'forward(self,', 'z_i,', 'z_j):', 'N', '=', '2', '*', 'self.batch_size', 'z', '=', 'torch.cat((z_i,', 'z_j),', 'dim=0)', 'sim', '=', 'self.similarity_f(z.unsqueeze(1),', 'z.unsqueeze(0))', '/', 'self.temperature', 'sim_i_j', '=', 'torch.diag(sim,', 'self.batch_size)', 'sim_j_i', '=', 'torch.diag(sim,', '-self.b... | 968,519 |
huawei-noah/xingtian | model.py | SimclrModel.output_channel | output_channel | Output Channel for last conv2d. | [
"Output",
"Channel",
"for",
"last",
"conv2d."
] | def output_channel(self):
return [module.out_channels for (name, module) in self.named_modules() if isinstance(module, nn.Conv2d)][-1] | ['def', 'output_channel(self):', 'return', '[module.out_channels', 'for', '(name,', 'module)', 'in', 'self.named_modules()', 'if', 'isinstance(module,', 'nn.Conv2d)][-1]'] | 968,521 |
huawei-noah/xingtian | tensorboarder.py | is_board_running | is_board_running | Check if process running. | [
"Check",
"if",
"process",
"running."
] | def is_board_running(pro_name='tensorboard'):
cmd = 'ps aux | grep "' + pro_name + '" | grep -v grep | grep -v tail | grep -v keepH5ssAlive'
try:
process_num = len(os.popen(cmd).readlines())
if process_num >= 1:
return True
else:
return False
except BaseExcept... | ['def', "is_board_running(pro_name='tensorboard'):", 'cmd', '=', "'ps", 'aux', '|', 'grep', '"\'', '+', 'pro_name', '+', '\'"', '|', 'grep', '-v', 'grep', '|', 'grep', '-v', 'tail', '|', 'grep', '-v', "keepH5ssAlive'", 'try:', 'process_num', '=', 'len(os.popen(cmd).readlines())', 'if', 'process_num', '>=', '1:', 'retur... | 968,524 |
huawei-noah/xingtian | tensorboarder.py | SummaryBoard.insert_epoch_logs | insert_epoch_logs | Insert logs after epoch. | [
"Insert",
"logs",
"after",
"epoch."
] | def insert_epoch_logs(self, logs, epoch):
for (k, v) in logs:
if not v:
continue
self.add_scalar(k, v, epoch, flush=False)
self.writer.flush() | ['def', 'insert_epoch_logs(self,', 'logs,', 'epoch):', 'for', '(k,', 'v)', 'in', 'logs:', 'if', 'not', 'v:', 'continue', 'self.add_scalar(k,', 'v,', 'epoch,', 'flush=False)', 'self.writer.flush()'] | 968,525 |
huawei-noah/xingtian | visual_rewards.py | parse_xt_train_config | parse_xt_train_config | Create utils for parse xt config file. | [
"Create",
"utils",
"for",
"parse",
"xt",
"config",
"file."
] | def parse_xt_train_config(yaml_obj):
env = yaml_obj.get('env_para')
alg = yaml_obj.get('alg_para')
_model = yaml_obj.get('model_para')
alg['model_info'] = _model
agent = yaml_obj.get('agent_para')
return (env, alg, agent) | ['def', 'parse_xt_train_config(yaml_obj):', 'env', '=', "yaml_obj.get('env_para')", 'alg', '=', "yaml_obj.get('alg_para')", '_model', '=', "yaml_obj.get('model_para')", "alg['model_info']", '=', '_model', 'agent', '=', "yaml_obj.get('agent_para')", 'return', '(env,', 'alg,', 'agent)'] | 968,530 |
huawei-noah/xingtian | visual_rewards.py | handle_once_local_data_record | handle_once_local_data_record | Handle the record from local file. | [
"Handle",
"the",
"record",
"from",
"local",
"file."
] | def handle_once_local_data_record(case_paras, use_index, stage='eval', clear_tensorboard=True):
(env_info, alg_info, agent_info) = parse_xt_train_config(case_paras)
benchmark_info = case_paras.get('benchmark', dict())
bm_args = parse_benchmark_args(env_info, alg_info, agent_info, benchmark_info)
records... | ['def', 'handle_once_local_data_record(case_paras,', 'use_index,', "stage='eval',", 'clear_tensorboard=True):', '(env_info,', 'alg_info,', 'agent_info)', '=', 'parse_xt_train_config(case_paras)', 'benchmark_info', '=', "case_paras.get('benchmark',", 'dict())', 'bm_args', '=', 'parse_benchmark_args(env_info,', 'alg_info... | 968,531 |
huawei-noah/xingtian | visual_rewards.py | write2board | write2board | Write record into tensorboard, include, loss, reward etc. | [
"Write",
"record",
"into",
"tensorboard,",
"include,",
"loss,",
"reward",
"etc."
] | def write2board(stage, record_dict, use_index, case_tb_dir):
if use_index == 'step':
x_key = 'sample_step'
elif use_index == 'sec':
x_key = 'elapsed_sec'
else:
raise KeyError("need in 'step' or 'sec', get: {}".format(use_index))
if stage == 'eval':
display_list = ['eval_r... | ['def', 'write2board(stage,', 'record_dict,', 'use_index,', 'case_tb_dir):', 'if', 'use_index', '==', "'step':", 'x_key', '=', "'sample_step'", 'elif', 'use_index', '==', "'sec':", 'x_key', '=', "'elapsed_sec'", 'else:', 'raise', 'KeyError("need', 'in', "'step'", 'or', "'sec',", 'get:', '{}".format(use_index))', 'if', ... | 968,532 |
SapienzaNLP/xl-amr | vocabulary.py | Vocabulary.extend_from_instances | extend_from_instances | Extends an already generated vocabulary using a collection of instances. | [
"Extends",
"an",
"already",
"generated",
"vocabulary",
"using",
"a",
"collection",
"of",
"instances."
] | def extend_from_instances(self, params: Params, instances: Iterable['adi.Instance']=()) -> None:
min_count = params.pop('min_count', None)
max_vocab_size = pop_max_vocab_size(params)
non_padded_namespaces = params.pop('non_padded_namespaces', DEFAULT_NON_PADDED_NAMESPACES)
pretrained_files = params.pop(... | ['def', 'extend_from_instances(self,', 'params:', 'Params,', 'instances:', "Iterable['adi.Instance']=())", '->', 'None:', 'min_count', '=', "params.pop('min_count',", 'None)', 'max_vocab_size', '=', 'pop_max_vocab_size(params)', 'non_padded_namespaces', '=', "params.pop('non_padded_namespaces',", 'DEFAULT_NON_PADDED_NA... | 968,548 |
SapienzaNLP/xl-amr | vocabulary.py | Vocabulary.is_padded | is_padded | Returns whether or not there are padding and OOV tokens added to the given namepsace. | [
"Returns",
"whether",
"or",
"not",
"there",
"are",
"padding",
"and",
"OOV",
"tokens",
"added",
"to",
"the",
"given",
"namepsace."
] | def is_padded(self, namespace: str) -> bool:
return self._index_to_token[namespace][0] == self._padding_token | ['def', 'is_padded(self,', 'namespace:', 'str)', '->', 'bool:', 'return', 'self._index_to_token[namespace][0]', '==', 'self._padding_token'] | 968,549 |
SapienzaNLP/xl-amr | graph_repair.py | GraphRepair.remove_redundant_edges | remove_redundant_edges | Edge labels such as ARGx, ARGx-of, and 'opx' should only appear at most once in each node's outgoing edges. | [
"Edge",
"labels",
"such",
"as",
"ARGx,",
"ARGx-of,",
"and",
"'opx'",
"should",
"only",
"appear",
"at",
"most",
"once",
"in",
"each",
"node's",
"outgoing",
"edges."
] | def remove_redundant_edges(self):
graph = self.graph
nodes = [node for node in graph.get_nodes()]
removed_nodes = set()
for node in nodes:
if node in removed_nodes:
continue
edges = list(graph._G.edges(node))
edge_counter = defaultdict(list)
for (source, targe... | ['def', 'remove_redundant_edges(self):', 'graph', '=', 'self.graph', 'nodes', '=', '[node', 'for', 'node', 'in', 'graph.get_nodes()]', 'removed_nodes', '=', 'set()', 'for', 'node', 'in', 'nodes:', 'if', 'node', 'in', 'removed_nodes:', 'continue', 'edges', '=', 'list(graph._G.edges(node))', 'edge_counter', '=', 'default... | 968,552 |
SapienzaNLP/xl-amr | polarity.py | Polarity.predict_polarity | predict_polarity | Use rules to predict polarity and its head. | [
"Use",
"rules",
"to",
"predict",
"polarity",
"and",
"its",
"head."
] | def predict_polarity(self):
for i in range(len(self.amr.tokens)):
if self.is_negation(i):
head = self.get_head(i)
if head is not None:
self.negations.append((i, head))
else:
self.add_special_negation(i) | ['def', 'predict_polarity(self):', 'for', 'i', 'in', 'range(len(self.amr.tokens)):', 'if', 'self.is_negation(i):', 'head', '=', 'self.get_head(i)', 'if', 'head', 'is', 'not', 'None:', 'self.negations.append((i,', 'head))', 'else:', 'self.add_special_negation(i)'] | 968,555 |
SapienzaNLP/xl-amr | sense_remover.py | SenseRemover.map_instance_to_lemmas | map_instance_to_lemmas | Get the candidate lemmas which can be used to represent the instance. | [
"Get",
"the",
"candidate",
"lemmas",
"which",
"can",
"be",
"used",
"to",
"represent",
"the",
"instance."
] | def map_instance_to_lemmas(self, instance):
if not (isinstance(instance, str) and (not re.search('^".*"$', instance))):
instance = str(instance)
if re.search('-\\d\\d$', instance):
lemmas = self.node_utils.get_lemmas(instance)
else:
lemmas = [instance]
return lemmas | ['def', 'map_instance_to_lemmas(self,', 'instance):', 'if', 'not', '(isinstance(instance,', 'str)', 'and', '(not', 're.search(\'^".*"$\',', 'instance))):', 'instance', '=', 'str(instance)', 'if', "re.search('-\\\\d\\\\d$',", 'instance):', 'lemmas', '=', 'self.node_utils.get_lemmas(instance)', 'else:', 'lemmas', '=', '[... | 968,557 |
SapienzaNLP/xl-amr | tokenizer.py | Tokenizer.batch_tokenize | batch_tokenize | Batches together tokenization of several texts, in case that is faster for particular tokenizers. | [
"Batches",
"together",
"tokenization",
"of",
"several",
"texts,",
"in",
"case",
"that",
"is",
"faster",
"for",
"particular",
"tokenizers."
] | def batch_tokenize(self, texts: List[str]) -> List[List[Token]]:
raise NotImplementedError | ['def', 'batch_tokenize(self,', 'texts:', 'List[str])', '->', 'List[List[Token]]:', 'raise', 'NotImplementedError'] | 968,568 |
SapienzaNLP/xl-amr | word_filter.py | WordFilter.filter_words | filter_words | Returns a filtered list of words. | [
"Returns",
"a",
"filtered",
"list",
"of",
"words."
] | def filter_words(self, words: List[Token]) -> List[Token]:
raise NotImplementedError | ['def', 'filter_words(self,', 'words:', 'List[Token])', '->', 'List[Token]:', 'raise', 'NotImplementedError'] | 968,570 |
SapienzaNLP/xl-amr | word_splitter.py | WordSplitter.split_words | split_words | Splits ``sentence`` into a list of :class:`Token` objects. | [
"Splits",
"``sentence``",
"into",
"a",
"list",
"of",
":class:`Token`",
"objects."
] | def split_words(self, sentence: str) -> List[Token]:
raise NotImplementedError | ['def', 'split_words(self,', 'sentence:', 'str)', '->', 'List[Token]:', 'raise', 'NotImplementedError'] | 968,572 |
SapienzaNLP/xl-amr | openai_transformer_byte_pair_indexer.py | text_standardize | text_standardize | Apply text standardization following original implementation. | [
"Apply",
"text",
"standardization",
"following",
"original",
"implementation."
] | def text_standardize(text):
text = text.replace('âÂ\x80Â\x94', '-')
text = text.replace('âÂ\x80Â\x93', '-')
text = text.replace('âÂ\x80Â\x95', '-')
text = text.replace('âÂ\x80¦', '...')
text = text.replace('Ã\x82´', "'")
text = re.sub('(-+|~+|!+|"+|;+|\\?+|\\++|,+|\\)+|\\(+|\\+|\\/+|\\*+|\... | ['def', 'text_standardize(text):', 'text', '=', "text.replace('âÂ\\x80Â\\x94',", "'-')", 'text', '=', "text.replace('âÂ\\x80Â\\x93',", "'-')", 'text', '=', "text.replace('âÂ\\x80Â\\x95',", "'-')", 'text', '=', "text.replace('âÂ\\x80¦',", "'...')", 'text', '=', "text.replace('Ã\\x82´',", '"\'")', 'text', '=', 're.... | 968,575 |
SapienzaNLP/xl-amr | token_indexer.py | TokenIndexer.get_padding_token | get_padding_token | When we need to add padding tokens, what should they look like? This method returns a "blank" token of whatever type is returned by :func:`tokens_to_indices`. | [
"When",
"we",
"need",
"to",
"add",
"padding",
"tokens,",
"what",
"should",
"they",
"look",
"like?",
"This",
"method",
"returns",
"a",
"\"blank\"",
"token",
"of",
"whatever",
"type",
"is",
"returned",
"by",
":func:`tokens_to_indices`."
] | def get_padding_token(self) -> TokenType:
raise NotImplementedError | ['def', 'get_padding_token(self)', '->', 'TokenType:', 'raise', 'NotImplementedError'] | 968,578 |
SapienzaNLP/xl-amr | token_indexer.py | TokenIndexer.get_keys | get_keys | Return a list of the keys this indexer return from ``tokens_to_indices``. | [
"Return",
"a",
"list",
"of",
"the",
"keys",
"this",
"indexer",
"return",
"from",
"``tokens_to_indices``."
] | def get_keys(self, index_name: str) -> List[str]:
return [index_name] | ['def', 'get_keys(self,', 'index_name:', 'str)', '->', 'List[str]:', 'return', '[index_name]'] | 968,581 |
SapienzaNLP/xl-amr | attachment_score.py | AttachmentScores.get_metric | get_metric | Returns ------- The accumulated metrics as a dictionary. | [
"Returns",
"-------",
"The",
"accumulated",
"metrics",
"as",
"a",
"dictionary."
] | def get_metric(self, reset: bool=False):
unlabeled_attachment_score = 0.0
labeled_attachment_score = 0.0
unlabeled_exact_match = 0.0
labeled_exact_match = 0.0
edge_loss = 0.0
edge_node_loss = 0.0
edge_label_loss = 0.0
if self._total_words > 0.0:
unlabeled_attachment_score = float... | ['def', 'get_metric(self,', 'reset:', 'bool=False):', 'unlabeled_attachment_score', '=', '0.0', 'labeled_attachment_score', '=', '0.0', 'unlabeled_exact_match', '=', '0.0', 'labeled_exact_match', '=', '0.0', 'edge_loss', '=', '0.0', 'edge_node_loss', '=', '0.0', 'edge_label_loss', '=', '0.0', 'if', 'self._total_words',... | 968,582 |
SapienzaNLP/xl-amr | metric.py | Metric.reset | reset | Reset any accumulators or internal state. | [
"Reset",
"any",
"accumulators",
"or",
"internal",
"state."
] | def reset(self) -> None:
raise NotImplementedError | ['def', 'reset(self)', '->', 'None:', 'raise', 'NotImplementedError'] | 968,584 |
SapienzaNLP/xl-amr | model.py | Model.get_parameters_for_histogram_tensorboard_logging | get_parameters_for_histogram_tensorboard_logging | Returns the name of model parameters used for logging histograms to tensorboard. | [
"Returns",
"the",
"name",
"of",
"model",
"parameters",
"used",
"for",
"logging",
"histograms",
"to",
"tensorboard."
] | def get_parameters_for_histogram_tensorboard_logging(self) -> List[str]:
return [name for (name, _) in self.named_parameters()] | ['def', 'get_parameters_for_histogram_tensorboard_logging(self)', '->', 'List[str]:', 'return', '[name', 'for', '(name,', '_)', 'in', 'self.named_parameters()]'] | 968,587 |
SapienzaNLP/xl-amr | openai_transformer_embedder.py | OpenaiTransformerEmbedder.get_output_dim | get_output_dim | The last dimension of the output, not the shape. | [
"The",
"last",
"dimension",
"of",
"the",
"output,",
"not",
"the",
"shape."
] | def get_output_dim(self):
return self._transformer.embed.embedding_dim | ['def', 'get_output_dim(self):', 'return', 'self._transformer.embed.embedding_dim'] | 968,619 |
SapienzaNLP/xl-amr | trainer.py | Trainer.train | train | Trains the supplied model with the supplied parameters. | [
"Trains",
"the",
"supplied",
"model",
"with",
"the",
"supplied",
"parameters."
] | def train(self):
try:
(epoch_counter, dev_metric_per_epoch) = self._restore_checkpoint()
except RuntimeError:
traceback.print_exc()
raise ConfigurationError('Could not recover training from the checkpoint. Did you mean to output to a different serialization directory or delete the exist... | ['def', 'train(self):', 'try:', '(epoch_counter,', 'dev_metric_per_epoch)', '=', 'self._restore_checkpoint()', 'except', 'RuntimeError:', 'traceback.print_exc()', 'raise', "ConfigurationError('Could", 'not', 'recover', 'training', 'from', 'the', 'checkpoint.', 'Did', 'you', 'mean', 'to', 'output', 'to', 'a', 'different... | 968,627 |
SapienzaNLP/xl-amr | environment.py | occupy_gpu | occupy_gpu | To prevent somebody taking you gpu if you are not using them. | [
"To",
"prevent",
"somebody",
"taking",
"you",
"gpu",
"if",
"you",
"are",
"not",
"using",
"them."
] | def occupy_gpu(device):
torch.cuda.LongTensor(0) | ['def', 'occupy_gpu(device):', 'torch.cuda.LongTensor(0)'] | 968,637 |
SapienzaNLP/xl-amr | file.py | get_spacy_model | get_spacy_model | In order to avoid loading spacy models a whole bunch of times, we'll save references to them, keyed by the options we used to create the spacy model, so any particular configuration only gets loaded once. | [
"In",
"order",
"to",
"avoid",
"loading",
"spacy",
"models",
"a",
"whole",
"bunch",
"of",
"times,",
"we'll",
"save",
"references",
"to",
"them,",
"keyed",
"by",
"the",
"options",
"we",
"used",
"to",
"create",
"the",
"spacy",
"model,",
"so",
"any",
"particul... | def get_spacy_model(spacy_model_name: str, pos_tags: bool, parse: bool, ner: bool) -> SpacyModelType:
options = (spacy_model_name, pos_tags, parse, ner)
if options not in LOADED_SPACY_MODELS:
disable = ['vectors', 'textcat']
if not pos_tags:
disable.append('tagger')
if not pa... | ['def', 'get_spacy_model(spacy_model_name:', 'str,', 'pos_tags:', 'bool,', 'parse:', 'bool,', 'ner:', 'bool)', '->', 'SpacyModelType:', 'options', '=', '(spacy_model_name,', 'pos_tags,', 'parse,', 'ner)', 'if', 'options', 'not', 'in', 'LOADED_SPACY_MODELS:', 'disable', '=', "['vectors',", "'textcat']", 'if', 'not', 'po... | 968,646 |
SapienzaNLP/xl-amr | __init__.py | is_lazy | is_lazy | Checks if the given iterable is lazy, which here just means it's not a list. | [
"Checks",
"if",
"the",
"given",
"iterable",
"is",
"lazy,",
"which",
"here",
"just",
"means",
"it's",
"not",
"a",
"list."
] | def is_lazy(iterable: Iterable[A]) -> bool:
return not isinstance(iterable, list) | ['def', 'is_lazy(iterable:', 'Iterable[A])', '->', 'bool:', 'return', 'not', 'isinstance(iterable,', 'list)'] | 968,683 |
deepmind/xmanager | auth.py | get_creds | get_creds | Gets the google credentials to be used with GCP APIs. | [
"Gets",
"the",
"google",
"credentials",
"to",
"be",
"used",
"with",
"GCP",
"APIs."
] | def get_creds(scopes: Iterable[str]=_DEFAULT_SCOPES):
(creds, _) = auth.default(scopes=scopes)
return creds | ['def', 'get_creds(scopes:', 'Iterable[str]=_DEFAULT_SCOPES):', '(creds,', '_)', '=', 'auth.default(scopes=scopes)', 'return', 'creds'] | 968,691 |
deepmind/xmanager | auth.py | enable_apis | enable_apis | Enables APIs on the GCP Project. | [
"Enables",
"APIs",
"on",
"the",
"GCP",
"Project."
] | def enable_apis():
resource = discovery.build('serviceusage', 'v1')
body = {'serviceIds': ['aiplatform.googleapis.com', 'cloudbuild.googleapis.com', 'cloudresourcemanager.googleapis.com', 'compute.googleapis.com', 'container.googleapis.com', 'containerregistry.googleapis.com', 'iam.googleapis.com', 'logging.goo... | ['def', 'enable_apis():', 'resource', '=', "discovery.build('serviceusage',", "'v1')", 'body', '=', "{'serviceIds':", "['aiplatform.googleapis.com',", "'cloudbuild.googleapis.com',", "'cloudresourcemanager.googleapis.com',", "'compute.googleapis.com',", "'container.googleapis.com',", "'containerregistry.googleapis.com'... | 968,692 |
deepmind/xmanager | auth_test.py | GetServiceAccountTest.test_get_service_account_existing_account | test_get_service_account_existing_account | Tests that `get_service_account` does nothing on a properly configured account. | [
"Tests",
"that",
"`get_service_account`",
"does",
"nothing",
"on",
"a",
"properly",
"configured",
"account."
] | def test_get_service_account_existing_account(self, sys_argv, expected_account_name):
flags.FLAGS(sys_argv)
mock_service_accounts = mock.Mock()
mock_service_accounts.list.return_value.execute.return_value = {'accounts': [{'email': f'{expected_account_name}@test-project.iam.gserviceaccount.com'}]}
mock_s... | ['def', 'test_get_service_account_existing_account(self,', 'sys_argv,', 'expected_account_name):', 'flags.FLAGS(sys_argv)', 'mock_service_accounts', '=', 'mock.Mock()', 'mock_service_accounts.list.return_value.execute.return_value', '=', "{'accounts':", "[{'email':", "f'{expected_account_name}@test-project.iam.gservice... | 968,694 |
deepmind/xmanager | auth_test.py | GetServiceAccountTest.test_get_service_account_new_account | test_get_service_account_new_account | Tests if `get_service_account` creates a new account and permissions properly. | [
"Tests",
"if",
"`get_service_account`",
"creates",
"a",
"new",
"account",
"and",
"permissions",
"properly."
] | def test_get_service_account_new_account(self, sys_argv, expected_account_name):
flags.FLAGS(sys_argv)
mock_service_accounts = mock.Mock()
mock_service_accounts.list.return_value.execute.return_value = {}
mock_service_accounts.create.return_value.execute.return_value = None
mock_projects = mock.Mock... | ['def', 'test_get_service_account_new_account(self,', 'sys_argv,', 'expected_account_name):', 'flags.FLAGS(sys_argv)', 'mock_service_accounts', '=', 'mock.Mock()', 'mock_service_accounts.list.return_value.execute.return_value', '=', '{}', 'mock_service_accounts.create.return_value.execute.return_value', '=', 'None', 'm... | 968,695 |
deepmind/xmanager | auth_test.py | GetServiceAccountTest.test_get_service_account_some_permissions | test_get_service_account_some_permissions | Tests if `get_service_account` creates permissions properly for an existing account with some permissions. | [
"Tests",
"if",
"`get_service_account`",
"creates",
"permissions",
"properly",
"for",
"an",
"existing",
"account",
"with",
"some",
"permissions."
] | def test_get_service_account_some_permissions(self, sys_argv, expected_account_name):
flags.FLAGS(sys_argv)
mock_service_accounts = mock.Mock()
mock_service_accounts.list.return_value.execute.return_value = {'accounts': [{'email': f'{expected_account_name}@test-project.iam.gserviceaccount.com'}, {'email': '... | ['def', 'test_get_service_account_some_permissions(self,', 'sys_argv,', 'expected_account_name):', 'flags.FLAGS(sys_argv)', 'mock_service_accounts', '=', 'mock.Mock()', 'mock_service_accounts.list.return_value.execute.return_value', '=', "{'accounts':", "[{'email':", "f'{expected_account_name}@test-project.iam.gservice... | 968,697 |
deepmind/xmanager | build_image.py | build | build | Build a Docker image from a Python project. | [
"Build",
"a",
"Docker",
"image",
"from",
"a",
"Python",
"project."
] | def build(py_executable: xm.PythonContainer, args: xm.SequentialArgs, env_vars: Dict[str, str], image_name: Optional[str]=None, project: Optional[str]=None, bucket: Optional[str]=None, pull_image: bool=False) -> str:
if not image_name:
image_name = _get_image_name(py_executable)
dockerfile = _create_doc... | ['def', 'build(py_executable:', 'xm.PythonContainer,', 'args:', 'xm.SequentialArgs,', 'env_vars:', 'Dict[str,', 'str],', 'image_name:', 'Optional[str]=None,', 'project:', 'Optional[str]=None,', 'bucket:', 'Optional[str]=None,', 'pull_image:', 'bool=False)', '->', 'str:', 'if', 'not', 'image_name:', 'image_name', '=', '... | 968,698 |
deepmind/xmanager | build_image.py | build_by_dockerfile | build_by_dockerfile | Build a Docker image from a Docker directory. | [
"Build",
"a",
"Docker",
"image",
"from",
"a",
"Docker",
"directory."
] | def build_by_dockerfile(path: str, dockerfile: str, image_name: str, project: Optional[str]=None, bucket: Optional[str]=None, pull_image: bool=False):
print('Building Docker image, please wait...')
if _BUILD_IMAGE_LOCALLY.value:
if docker_lib.is_docker_installed():
return docker_lib.build_do... | ['def', 'build_by_dockerfile(path:', 'str,', 'dockerfile:', 'str,', 'image_name:', 'str,', 'project:', 'Optional[str]=None,', 'bucket:', 'Optional[str]=None,', 'pull_image:', 'bool=False):', "print('Building", 'Docker', 'image,', 'please', "wait...')", 'if', '_BUILD_IMAGE_LOCALLY.value:', 'if', 'docker_lib.is_docker_in... | 968,699 |
deepmind/xmanager | cloud_build.py | Client.build_docker_image | build_docker_image | Create a Docker image via Cloud Build and push to Cloud Repository. | [
"Create",
"a",
"Docker",
"image",
"via",
"Cloud",
"Build",
"and",
"push",
"to",
"Cloud",
"Repository."
] | def build_docker_image(self, image: str, directory: str, upload_name: str) -> str:
(repository, tag) = docker_utils.parse_repository_tag(image)
if not tag:
tag = datetime.datetime.now().strftime('%Y%m%d-%H%M%S_%f')
(_, archive_path) = tempfile.mkstemp(suffix='.tar.gz')
with tarfile.open(archive_... | ['def', 'build_docker_image(self,', 'image:', 'str,', 'directory:', 'str,', 'upload_name:', 'str)', '->', 'str:', '(repository,', 'tag)', '=', 'docker_utils.parse_repository_tag(image)', 'if', 'not', 'tag:', 'tag', '=', "datetime.datetime.now().strftime('%Y%m%d-%H%M%S_%f')", '(_,', 'archive_path)', '=', "tempfile.mkste... | 968,701 |
deepmind/xmanager | cloud_build.py | Client.wait_for_build | wait_for_build | Waits for build to finish and return the image URI of the result. | [
"Waits",
"for",
"build",
"to",
"finish",
"and",
"return",
"the",
"image",
"URI",
"of",
"the",
"result."
] | def wait_for_build(self, build_id: str, kaniko_image: str) -> str:
backoff = 30
while True:
time.sleep(backoff)
result = self.cloudbuild_api.projects().builds().get(projectId=self.project, id=build_id).execute()
status = result['status']
print('Cloud Build status:', status)
... | ['def', 'wait_for_build(self,', 'build_id:', 'str,', 'kaniko_image:', 'str)', '->', 'str:', 'backoff', '=', '30', 'while', 'True:', 'time.sleep(backoff)', 'result', '=', 'self.cloudbuild_api.projects().builds().get(projectId=self.project,', 'id=build_id).execute()', 'status', '=', "result['status']", "print('Cloud", 'B... | 968,702 |
deepmind/xmanager | docker_lib.py | prepare_directory | prepare_directory | Stage all inputs into the destination directory. | [
"Stage",
"all",
"inputs",
"into",
"the",
"destination",
"directory."
] | def prepare_directory(destination_directory: str, source_directory: str, project_name: str, entrypoint_file: str, dockerfile: str) -> None:
source_path = pathlib.Path(source_directory)
size = sum((f.stat().st_size for f in source_path.glob('**/*') if f.is_file()))
print(f'Size of Docker input: {humanize.nat... | ['def', 'prepare_directory(destination_directory:', 'str,', 'source_directory:', 'str,', 'project_name:', 'str,', 'entrypoint_file:', 'str,', 'dockerfile:', 'str)', '->', 'None:', 'source_path', '=', 'pathlib.Path(source_directory)', 'size', '=', 'sum((f.stat().st_size', 'for', 'f', 'in', "source_path.glob('**/*')", 'i... | 968,703 |
deepmind/xmanager | docker_lib.py | is_docker_installed | is_docker_installed | Checks if Docker is installed and accessible. | [
"Checks",
"if",
"Docker",
"is",
"installed",
"and",
"accessible."
] | def is_docker_installed() -> bool:
try:
docker_client = docker.from_env()
logging.info('Local docker: %s', docker_client.version())
return True
except docker.errors.DockerException as e:
if 'No such file or directory' in str(e):
return False
logging.info(e)
... | ['def', 'is_docker_installed()', '->', 'bool:', 'try:', 'docker_client', '=', 'docker.from_env()', "logging.info('Local", 'docker:', "%s',", 'docker_client.version())', 'return', 'True', 'except', 'docker.errors.DockerException', 'as', 'e:', 'if', "'No", 'such', 'file', 'or', "directory'", 'in', 'str(e):', 'return', 'F... | 968,704 |
deepmind/xmanager | kubernetes.py | requirements_from_executor | requirements_from_executor | Get resource limits from the executor. | [
"Get",
"resource",
"limits",
"from",
"the",
"executor."
] | def requirements_from_executor(executor: local_executors.Kubernetes) -> k8s_client.V1ResourceRequirements:
limits = {}
for (resource, value) in executor.requirements.task_requirements.items():
if resource in xm.GpuType:
limits['nvidia.com/gpu'] = f'{value:g}'
elif resource in xm.TpuT... | ['def', 'requirements_from_executor(executor:', 'local_executors.Kubernetes)', '->', 'k8s_client.V1ResourceRequirements:', 'limits', '=', '{}', 'for', '(resource,', 'value)', 'in', 'executor.requirements.task_requirements.items():', 'if', 'resource', 'in', 'xm.GpuType:', "limits['nvidia.com/gpu']", '=', "f'{value:g}'",... | 968,709 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.