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 |
|---|---|---|---|---|---|---|---|---|
huawei-noah/xingtian | learner.py | Learner.submit_algorithm | submit_algorithm | Submit an algorithm, to update algorithm instance description. | [
"Submit",
"an",
"algorithm,",
"to",
"update",
"algorithm",
"instance",
"description."
] | def submit_algorithm(self, alg_instance, trainer_obj, shared_buff):
self.alg = alg_instance
self.trainer = trainer_obj
self.shared_buff = shared_buff | ['def', 'submit_algorithm(self,', 'alg_instance,', 'trainer_obj,', 'shared_buff):', 'self.alg', '=', 'alg_instance', 'self.trainer', '=', 'trainer_obj', 'self.shared_buff', '=', 'shared_buff'] | 962,212 |
huawei-noah/xingtian | remoter.py | remote_run | remote_run | Run command in remote node. | [
"Run",
"command",
"in",
"remote",
"node."
] | def remote_run(server_ip, host, passwd, cmd, remote_env):
print('remote_env:', remote_env)
_env_export = 'export PATH={}/bin:$PATH'.format(remote_env['conda'])
if 'env' in remote_env.keys():
for (_key, _val) in remote_env['env'].items():
_env_export += '&& export {}={}'.format(_key, _val... | ['def', 'remote_run(server_ip,', 'host,', 'passwd,', 'cmd,', 'remote_env):', "print('remote_env:',", 'remote_env)', '_env_export', '=', "'export", "PATH={}/bin:$PATH'.format(remote_env['conda'])", 'if', "'env'", 'in', 'remote_env.keys():', 'for', '(_key,', '_val)', 'in', "remote_env['env'].items():", '_env_export', '+=... | 962,215 |
huawei-noah/xingtian | trainer.py | build_alg_with_trainer | build_alg_with_trainer | Build an algorithm instance with multi-process trainer. | [
"Build",
"an",
"algorithm",
"instance",
"with",
"multi-process",
"trainer."
] | def build_alg_with_trainer(alg_para, model_q, model_path, process_num):
alg_para = deepcopy(alg_para)
if process_num >= 2:
shared_list_for_train = Manager().list()
(alg, subprocess_instance) = start_multi_processes(alg_para, model_q, model_path, process_num, shared_list_for_train)
else:
... | ['def', 'build_alg_with_trainer(alg_para,', 'model_q,', 'model_path,', 'process_num):', 'alg_para', '=', 'deepcopy(alg_para)', 'if', 'process_num', '>=', '2:', 'shared_list_for_train', '=', 'Manager().list()', '(alg,', 'subprocess_instance)', '=', 'start_multi_processes(alg_para,', 'model_q,', 'model_path,', 'process_n... | 962,218 |
huawei-noah/xingtian | trainer.py | start_multi_processes | start_multi_processes | Start multi processes to train. | [
"Start",
"multi",
"processes",
"to",
"train."
] | def start_multi_processes(alg_para, model_q, model_path, process_num, train_list):
array_list = init_memory(process_num)
event_dict = {}
grad_q = Queue()
for i in range(process_num):
event_dict[i] = Event()
weight_list = init_memory(1)
grad_process = [Process(target=grad_communicate, arg... | ['def', 'start_multi_processes(alg_para,', 'model_q,', 'model_path,', 'process_num,', 'train_list):', 'array_list', '=', 'init_memory(process_num)', 'event_dict', '=', '{}', 'grad_q', '=', 'Queue()', 'for', 'i', 'in', 'range(process_num):', 'event_dict[i]', '=', 'Event()', 'weight_list', '=', 'init_memory(1)', 'grad_pr... | 962,219 |
huawei-noah/xingtian | model.py | check_keep_model | check_keep_model | Check model saved count under path. | [
"Check",
"model",
"saved",
"count",
"under",
"path."
] | def check_keep_model(model_path, keep_num):
target_file = glob.glob(os.path.join(model_path, 'actor*'.format(model_path)))
if len(target_file) > keep_num:
to_rm_model = sorted(target_file, reverse=True)[keep_num:]
for item in to_rm_model:
os.remove(item) | ['def', 'check_keep_model(model_path,', 'keep_num):', 'target_file', '=', 'glob.glob(os.path.join(model_path,', "'actor*'.format(model_path)))", 'if', 'len(target_file)', '>', 'keep_num:', 'to_rm_model', '=', 'sorted(target_file,', 'reverse=True)[keep_num:]', 'for', 'item', 'in', 'to_rm_model:', 'os.remove(item)'] | 962,221 |
huawei-noah/xingtian | model.py | XTModel.set_weights | set_weights | Set weight with memory tensor. | [
"Set",
"weight",
"with",
"memory",
"tensor."
] | def set_weights(self, weights):
with self.graph.as_default():
self.actor_var.set_weights(weights) | ['def', 'set_weights(self,', 'weights):', 'with', 'self.graph.as_default():', 'self.actor_var.set_weights(weights)'] | 962,224 |
huawei-noah/xingtian | model_utils.py | get_mlp_default_settings | get_mlp_default_settings | Get default setting for mlp model. | [
"Get",
"default",
"setting",
"for",
"mlp",
"model."
] | def get_mlp_default_settings(kind):
if kind == 'hidden_sizes':
return [64, 64]
elif kind == 'activation':
return 'tanh'
else:
raise KeyError('unknown type: {}'.format(kind)) | ['def', 'get_mlp_default_settings(kind):', 'if', 'kind', '==', "'hidden_sizes':", 'return', '[64,', '64]', 'elif', 'kind', '==', "'activation':", 'return', "'tanh'", 'else:', 'raise', "KeyError('unknown", 'type:', "{}'.format(kind))"] | 962,226 |
huawei-noah/xingtian | model_utils.py | custom_norm_initializer | custom_norm_initializer | Perform Customize norm initializer for op. | [
"Perform",
"Customize",
"norm",
"initializer",
"for",
"op."
] | def custom_norm_initializer(std=0.5):
def _initializer(shape, dtype=None, partition_info=None):
out = np.random.randn(*shape).astype(np.float32)
out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True))
return tf.constant(out)
return _initializer | ['def', 'custom_norm_initializer(std=0.5):', 'def', '_initializer(shape,', 'dtype=None,', 'partition_info=None):', 'out', '=', 'np.random.randn(*shape).astype(np.float32)', 'out', '*=', 'std', '/', 'np.sqrt(np.square(out).sum(axis=0,', 'keepdims=True))', 'return', 'tf.constant(out)', 'return', '_initializer'] | 962,229 |
huawei-noah/xingtian | model_zeus.py | XTModelZeus.predict | predict | Do predict use the latest model. | [
"Do",
"predict",
"use",
"the",
"latest",
"model."
] | def predict(self, state):
return self.model.predict(state) | ['def', 'predict(self,', 'state):', 'return', 'self.model.predict(state)'] | 962,231 |
huawei-noah/xingtian | tf_compat.py | import_tf_compact | import_tf_compact | Import tensorflow with compact behavior. | [
"Import",
"tensorflow",
"with",
"compact",
"behavior."
] | def import_tf_compact():
if 'tensorflow' not in sys.modules:
try:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
except ImportError:
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
return tf
else:
return s... | ['def', 'import_tf_compact():', 'if', "'tensorflow'", 'not', 'in', 'sys.modules:', 'try:', 'import', 'tensorflow.compat.v1', 'as', 'tf', 'tf.disable_v2_behavior()', 'except', 'ImportError:', 'import', 'tensorflow', 'as', 'tf', 'tf.logging.set_verbosity(tf.logging.ERROR)', 'return', 'tf', 'else:', 'return', "sys.modules... | 962,234 |
huawei-noah/xingtian | tf_compat.py | get_tf_major | get_tf_major | Get major of tensorflow version. | [
"Get",
"major",
"of",
"tensorflow",
"version."
] | def get_tf_major():
return int(tf.__version__.split('.')[0]) | ['def', 'get_tf_major():', 'return', "int(tf.__version__.split('.')[0])"] | 962,237 |
huawei-noah/xingtian | tf_dist.py | ActionDist.sample | sample | Sample action from this distribution. | [
"Sample",
"action",
"from",
"this",
"distribution."
] | def sample(self, repeat):
raise NotImplementedError | ['def', 'sample(self,', 'repeat):', 'raise', 'NotImplementedError'] | 962,238 |
huawei-noah/xingtian | tf_utils.py | norm_initializer | norm_initializer | Build customized norm initializer. | [
"Build",
"customized",
"norm",
"initializer."
] | def norm_initializer(std=0.5):
def _initializer(shape, dtype=None, partition_info=None):
out = np.random.randn(*shape).astype(np.float32)
out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True))
return tf.constant(out)
return _initializer | ['def', 'norm_initializer(std=0.5):', 'def', '_initializer(shape,', 'dtype=None,', 'partition_info=None):', 'out', '=', 'np.random.randn(*shape).astype(np.float32)', 'out', '*=', 'std', '/', 'np.sqrt(np.square(out).sum(axis=0,', 'keepdims=True))', 'return', 'tf.constant(out)', 'return', '_initializer'] | 962,240 |
huawei-noah/xingtian | tf_utils.py | TFVariables.get_weights | get_weights | Get weights with dict type. | [
"Get",
"weights",
"with",
"dict",
"type."
] | def get_weights(self):
_weights = self.session.run(self.node_hub_with_order)
return _weights | ['def', 'get_weights(self):', '_weights', '=', 'self.session.run(self.node_hub_with_order)', 'return', '_weights'] | 962,242 |
huawei-noah/xingtian | tf_utils.py | TFVariables.set_weights | set_weights | Set weights with dict type. | [
"Set",
"weights",
"with",
"dict",
"type."
] | def set_weights(self, to_weights):
nodes_to_assign = [self._to_assign_node_dict[node_name] for node_name in to_weights.keys() if node_name in self._to_assign_node_dict]
if not nodes_to_assign:
print('to_weights: ', to_weights)
raise KeyError("NO node's weights could assign in self.graph {} vs {}... | ['def', 'set_weights(self,', 'to_weights):', 'nodes_to_assign', '=', '[self._to_assign_node_dict[node_name]', 'for', 'node_name', 'in', 'to_weights.keys()', 'if', 'node_name', 'in', 'self._to_assign_node_dict]', 'if', 'not', 'nodes_to_assign:', "print('to_weights:", "',", 'to_weights)', 'raise', 'KeyError("NO', "node's... | 962,243 |
huawei-noah/xingtian | tf_utils.py | TFVariables.set_weights_with_npz | set_weights_with_npz | Set weight with numpy file. | [
"Set",
"weight",
"with",
"numpy",
"file."
] | def set_weights_with_npz(self, npz_file: str):
weights = self.read_weights(npz_file)
self.set_weights(weights) | ['def', 'set_weights_with_npz(self,', 'npz_file:', 'str):', 'weights', '=', 'self.read_weights(npz_file)', 'self.set_weights(weights)'] | 962,246 |
huawei-noah/xingtian | dqn_cnn.py | DqnCnn.create_model | create_model | Create Deep-Q CNN network. | [
"Create",
"Deep-Q",
"CNN",
"network."
] | def create_model(self, model_info):
state = Input(shape=self.state_dim, dtype='uint8')
state1 = Lambda(lambda x: K.cast(x, dtype='float32') / 255.0)(state)
convlayer = Conv2D(32, (8, 8), strides=(4, 4), activation='relu', padding='valid')(state1)
convlayer = Conv2D(64, (4, 4), strides=(2, 2), activation... | ['def', 'create_model(self,', 'model_info):', 'state', '=', 'Input(shape=self.state_dim,', "dtype='uint8')", 'state1', '=', 'Lambda(lambda', 'x:', 'K.cast(x,', "dtype='float32')", '/', '255.0)(state)', 'convlayer', '=', 'Conv2D(32,', '(8,', '8),', 'strides=(4,', '4),', "activation='relu',", "padding='valid')(state1)", ... | 962,248 |
huawei-noah/xingtian | dqn_mlp.py | layer_add | layer_add | Compute Q given Advantage and V. | [
"Compute",
"Q",
"given",
"Advantage",
"and",
"V."
] | def layer_add(x):
return x[0] + x[1] | ['def', 'layer_add(x):', 'return', 'x[0]', '+', 'x[1]'] | 962,251 |
huawei-noah/xingtian | impala_cnn.py | impala_loss | impala_loss | Compute loss for impala. | [
"Compute",
"loss",
"for",
"impala."
] | def impala_loss(advantage):
def loss(y_true, y_pred):
policy = y_pred
log_policy = K.log(policy + 1e-10)
entropy = -policy * K.log(policy + 1e-10)
cross_entropy = -y_true * log_policy
return K.mean(advantage * cross_entropy - ENTROPY_LOSS * entropy, 1)
return loss | ['def', 'impala_loss(advantage):', 'def', 'loss(y_true,', 'y_pred):', 'policy', '=', 'y_pred', 'log_policy', '=', 'K.log(policy', '+', '1e-10)', 'entropy', '=', '-policy', '*', 'K.log(policy', '+', '1e-10)', 'cross_entropy', '=', '-y_true', '*', 'log_policy', 'return', 'K.mean(advantage', '*', 'cross_entropy', '-', 'EN... | 962,255 |
huawei-noah/xingtian | impala_mlp.py | impala_loss | impala_loss | Compute loss for IMPALA. | [
"Compute",
"loss",
"for",
"IMPALA."
] | def impala_loss(advantage):
def loss(y_true, y_pred):
policy = y_pred
log_policy = K.log(policy + 1e-10)
entropy = -policy * log_policy
cross_entropy = -y_true * log_policy
return K.mean(advantage * cross_entropy - ENTROPY_LOSS * entropy)
return loss | ['def', 'impala_loss(advantage):', 'def', 'loss(y_true,', 'y_pred):', 'policy', '=', 'y_pred', 'log_policy', '=', 'K.log(policy', '+', '1e-10)', 'entropy', '=', '-policy', '*', 'log_policy', 'cross_entropy', '=', '-y_true', '*', 'log_policy', 'return', 'K.mean(advantage', '*', 'cross_entropy', '-', 'ENTROPY_LOSS', '*',... | 962,264 |
huawei-noah/xingtian | muzero_utils.py | scale_gradient | scale_gradient | Scales the gradient for the backward pass. | [
"Scales",
"the",
"gradient",
"for",
"the",
"backward",
"pass."
] | def scale_gradient(tensor, scale):
return tensor * scale + tf.stop_gradient(tensor) * (1 - scale) | ['def', 'scale_gradient(tensor,', 'scale):', 'return', 'tensor', '*', 'scale', '+', 'tf.stop_gradient(tensor)', '*', '(1', '-', 'scale)'] | 962,275 |
huawei-noah/xingtian | ppo_mlp_zeus.py | value_loss | value_loss | Compute value loss for PPO. | [
"Compute",
"value",
"loss",
"for",
"PPO."
] | def value_loss(target_v, out_v, old_v):
vpredclipped = old_v + tf.clip_by_value(out_v - old_v, -VF_CLIP, VF_CLIP)
vf_losses1 = tf.square(out_v - target_v)
vf_losses2 = tf.square(vpredclipped - target_v)
vf_loss = 0.5 * tf.reduce_mean(tf.maximum(vf_losses1, vf_losses2))
return vf_loss | ['def', 'value_loss(target_v,', 'out_v,', 'old_v):', 'vpredclipped', '=', 'old_v', '+', 'tf.clip_by_value(out_v', '-', 'old_v,', '-VF_CLIP,', 'VF_CLIP)', 'vf_losses1', '=', 'tf.square(out_v', '-', 'target_v)', 'vf_losses2', '=', 'tf.square(vpredclipped', '-', 'target_v)', 'vf_loss', '=', '0.5', '*', 'tf.reduce_mean(tf.... | 962,276 |
huawei-noah/xingtian | qmix_tf.py | QMixModel.build_actor_graph | build_actor_graph | Build explorer graph with minimum principle. | [
"Build",
"explorer",
"graph",
"with",
"minimum",
"principle."
] | def build_actor_graph(self):
with self.graph.as_default():
with tf.variable_scope('explore_agent'):
(self.agent_outs, self.hidden_outs) = self.build_agent_net(inputs_obs=self.ph_obs, seq_max=1, obs_lengths=[1 for _ in range(self.n_agents)], hidden_state_in=self.ph_hidden_states_in)
self.... | ['def', 'build_actor_graph(self):', 'with', 'self.graph.as_default():', 'with', "tf.variable_scope('explore_agent'):", '(self.agent_outs,', 'self.hidden_outs)', '=', 'self.build_agent_net(inputs_obs=self.ph_obs,', 'seq_max=1,', 'obs_lengths=[1', 'for', '_', 'in', 'range(self.n_agents)],', 'hidden_state_in=self.ph_hidde... | 962,280 |
huawei-noah/xingtian | qmix_tf.py | QMixModel.reset_hidden_state | reset_hidden_state | Reset hidden state with value assign. | [
"Reset",
"hidden",
"state",
"with",
"value",
"assign."
] | def reset_hidden_state(self):
self.hi_out_val = self.hi_out_val_default | ['def', 'reset_hidden_state(self):', 'self.hi_out_val', '=', 'self.hi_out_val_default'] | 962,282 |
huawei-noah/xingtian | __init__.py | register_zeus | register_zeus | Import and register zeus modules automatically. | [
"Import",
"and",
"register",
"zeus",
"modules",
"automatically."
] | def register_zeus(backend):
from zeus.datasets import register_datasets
from zeus.modules import register_modules
from zeus.networks import register_networks
from zeus.evaluator import register_evaluator
from zeus.trainer import register_trainer, trainer_api
from zeus.metrics import register_met... | ['def', 'register_zeus(backend):', 'from', 'zeus.datasets', 'import', 'register_datasets', 'from', 'zeus.modules', 'import', 'register_modules', 'from', 'zeus.networks', 'import', 'register_networks', 'from', 'zeus.evaluator', 'import', 'register_evaluator', 'from', 'zeus.trainer', 'import', 'register_trainer,', 'train... | 962,302 |
huawei-noah/xingtian | __init__.py | is_torch_backend | is_torch_backend | Return whether is pytorch backend or not. | [
"Return",
"whether",
"is",
"pytorch",
"backend",
"or",
"not."
] | def is_torch_backend():
return os.environ.get('BACKEND_TYPE', None) == 'PYTORCH' | ['def', 'is_torch_backend():', 'return', "os.environ.get('BACKEND_TYPE',", 'None)', '==', "'PYTORCH'"] | 962,306 |
huawei-noah/xingtian | __init__.py | is_tf_backend | is_tf_backend | Return whether is tensorflow backend or not. | [
"Return",
"whether",
"is",
"tensorflow",
"backend",
"or",
"not."
] | def is_tf_backend():
return os.environ.get('BACKEND_TYPE', None) == 'TENSORFLOW' | ['def', 'is_tf_backend():', 'return', "os.environ.get('BACKEND_TYPE',", 'None)', '==', "'TENSORFLOW'"] | 962,307 |
huawei-noah/xingtian | config.py | build_tree | build_tree | Convert plaint dictionary to a tree dictionary. | [
"Convert",
"plaint",
"dictionary",
"to",
"a",
"tree",
"dictionary."
] | def build_tree(data):
result = {}
for (key, value) in data.items():
if '.' in key:
_keys = key.split('.')
_tree = {}
_tree[_keys[-1]] = value
_keys.reverse()
for sub_key in _keys[1:]:
_tree = {sub_key: _tree}
branch ... | ['def', 'build_tree(data):', 'result', '=', '{}', 'for', '(key,', 'value)', 'in', 'data.items():', 'if', "'.'", 'in', 'key:', '_keys', '=', "key.split('.')", '_tree', '=', '{}', '_tree[_keys[-1]]', '=', 'value', '_keys.reverse()', 'for', 'sub_key', 'in', '_keys[1:]:', '_tree', '=', '{sub_key:', '_tree}', 'branch', '=',... | 962,314 |
huawei-noah/xingtian | config_serializable.py | ConfigSerializable.rules | rules | Return rules for checking. | [
"Return",
"rules",
"for",
"checking."
] | def rules(cls):
return {} | ['def', 'rules(cls):', 'return', '{}'] | 962,317 |
huawei-noah/xingtian | config_serializable.py | ConfigSerializable.backup_original_value | backup_original_value | Backup class original data. | [
"Backup",
"class",
"original",
"data."
] | def backup_original_value(cls, force=False):
if not cls.__original__value__ or force:
cls.__original__value__ = cls().to_json()
return cls.__original__value__ | ['def', 'backup_original_value(cls,', 'force=False):', 'if', 'not', 'cls.__original__value__', 'or', 'force:', 'cls.__original__value__', '=', 'cls().to_json()', 'return', 'cls.__original__value__'] | 962,318 |
huawei-noah/xingtian | task_ops.py | TaskOps.model_zoo_path | model_zoo_path | Return model zoo path. | [
"Return",
"model",
"zoo",
"path."
] | def model_zoo_path(self):
return General.model_zoo.model_zoo_path | ['def', 'model_zoo_path(self):', 'return', 'General.model_zoo.model_zoo_path'] | 962,341 |
huawei-noah/xingtian | user_config.py | UserConfig.merge_reference | merge_reference | Merge config with reference the specified config with ref item. | [
"Merge",
"config",
"with",
"reference",
"the",
"specified",
"config",
"with",
"ref",
"item."
] | def merge_reference(child):
if not isinstance(child, dict):
return
ref = child.get('ref')
if not ref:
return
ref_dict = deepcopy(UserConfig().data)
for key in ref.split('.'):
ref_dict = ref_dict.get(key)
not_merge_keys = ['callbacks', 'lazy_built']
for key in not_merg... | ['def', 'merge_reference(child):', 'if', 'not', 'isinstance(child,', 'dict):', 'return', 'ref', '=', "child.get('ref')", 'if', 'not', 'ref:', 'return', 'ref_dict', '=', 'deepcopy(UserConfig().data)', 'for', 'key', 'in', "ref.split('.'):", 'ref_dict', '=', 'ref_dict.get(key)', 'not_merge_keys', '=', "['callbacks',", "'l... | 962,347 |
huawei-noah/xingtian | utils.py | copy_search_file | copy_search_file | Copy files from srcDir to desDir. | [
"Copy",
"files",
"from",
"srcDir",
"to",
"desDir."
] | def copy_search_file(srcDir, desDir):
ls = os.listdir(srcDir)
for line in ls:
filePath = os.path.join(srcDir, line)
if os.path.isfile(filePath):
shutil.copy(filePath, desDir) | ['def', 'copy_search_file(srcDir,', 'desDir):', 'ls', '=', 'os.listdir(srcDir)', 'for', 'line', 'in', 'ls:', 'filePath', '=', 'os.path.join(srcDir,', 'line)', 'if', 'os.path.isfile(filePath):', 'shutil.copy(filePath,', 'desDir)'] | 962,354 |
huawei-noah/xingtian | message.py | get_msg_info | get_msg_info | Get message ctr info. | [
"Get",
"message",
"ctr",
"info."
] | def get_msg_info(msg, key):
return msg['ctr_info'].get(key) | ['def', 'get_msg_info(msg,', 'key):', 'return', "msg['ctr_info'].get(key)"] | 962,356 |
huawei-noah/xingtian | message.py | set_msg_info | set_msg_info | Set message ctr info. | [
"Set",
"message",
"ctr",
"info."
] | def set_msg_info(msg, **kwargs):
msg['ctr_info'].update(**kwargs) | ['def', 'set_msg_info(msg,', '**kwargs):', "msg['ctr_info'].update(**kwargs)"] | 962,357 |
huawei-noah/xingtian | share_buffer.py | test_buf_get_live | test_buf_get_live | Test share buf live count. | [
"Test",
"share",
"buf",
"live",
"count."
] | def test_buf_get_live():
live_count = 10
logging.set_verbosity(logging.DEBUG)
share_buf = ShareBuf(live=live_count, size=20000000, start=True)
data = {'d{}'.format(i): np.array(np.arange(i)) for i in range(5, 8)}
ds = serialize(data).to_buffer()
b_id = share_buf.put(data_buffer=ds)
for _ in ... | ['def', 'test_buf_get_live():', 'live_count', '=', '10', 'logging.set_verbosity(logging.DEBUG)', 'share_buf', '=', 'ShareBuf(live=live_count,', 'size=20000000,', 'start=True)', 'data', '=', "{'d{}'.format(i):", 'np.array(np.arange(i))', 'for', 'i', 'in', 'range(5,', '8)}', 'ds', '=', 'serialize(data).to_buffer()', 'b_i... | 962,358 |
huawei-noah/xingtian | share_buffer.py | test_share_buf_io | test_share_buf_io | Test share buf io-out. | [
"Test",
"share",
"buf",
"io-out."
] | def test_share_buf_io():
logging.set_verbosity(logging.DEBUG)
share_buf = ShareBuf(live=10, size=20000000, start=True)
data = {'d{}'.format(i): np.array(np.arange(i)) for i in range(5, 8)}
print(data)
ds = serialize(data).to_buffer()
b_id = share_buf.put(data_buffer=ds)
print('b_id', b_id)
... | ['def', 'test_share_buf_io():', 'logging.set_verbosity(logging.DEBUG)', 'share_buf', '=', 'ShareBuf(live=10,', 'size=20000000,', 'start=True)', 'data', '=', "{'d{}'.format(i):", 'np.array(np.arange(i))', 'for', 'i', 'in', 'range(5,', '8)}', 'print(data)', 'ds', '=', 'serialize(data).to_buffer()', 'b_id', '=', 'share_bu... | 962,359 |
huawei-noah/xingtian | share_buffer.py | ShareBuf.plus_one_live | plus_one_live | Add one live value. | [
"Add",
"one",
"live",
"value."
] | def plus_one_live(self):
self.live_threshold += 1
self._update_vanish_attr(self.live_threshold) | ['def', 'plus_one_live(self):', 'self.live_threshold', '+=', '1', 'self._update_vanish_attr(self.live_threshold)'] | 962,361 |
huawei-noah/xingtian | share_buffer.py | ShareBuf.reduce_once | reduce_once | Reduce one times of this object. | [
"Reduce",
"one",
"times",
"of",
"this",
"object."
] | def reduce_once(self, object_id):
if object_id not in self.live_info:
logging.debug('obj_id: {} is deleted yet'.format(object_id))
else:
self.live_info[object_id] -= 1 | ['def', 'reduce_once(self,', 'object_id):', 'if', 'object_id', 'not', 'in', 'self.live_info:', "logging.debug('obj_id:", '{}', 'is', 'deleted', "yet'.format(object_id))", 'else:', 'self.live_info[object_id]', '-=', '1'] | 962,363 |
huawei-noah/xingtian | share_buffer.py | ShareBuf.put | put | Put data buffer for share. | [
"Put",
"data",
"buffer",
"for",
"share."
] | def put(self, data_buffer, special_live=None):
client = self.connect()
object_id = client.put_raw_buffer(data_buffer)
self._init_obj(object_id.binary(), special_live)
ready_vanish_ids = self._get_vanish_obj()
if ready_vanish_ids:
client.delete(ready_vanish_ids)
return object_id.binary() | ['def', 'put(self,', 'data_buffer,', 'special_live=None):', 'client', '=', 'self.connect()', 'object_id', '=', 'client.put_raw_buffer(data_buffer)', 'self._init_obj(object_id.binary(),', 'special_live)', 'ready_vanish_ids', '=', 'self._get_vanish_obj()', 'if', 'ready_vanish_ids:', 'client.delete(ready_vanish_ids)', 're... | 962,364 |
huawei-noah/xingtian | share_buffer.py | ShareBuf.get_with_live_consume | get_with_live_consume | Get a object data from plasma server with id, and reduce live count. | [
"Get",
"a",
"object",
"data",
"from",
"plasma",
"server",
"with",
"id,",
"and",
"reduce",
"live",
"count."
] | def get_with_live_consume(self, object_id_byte):
data = self._get_buf(object_id_byte)
self.reduce_once(object_id_byte)
return data | ['def', 'get_with_live_consume(self,', 'object_id_byte):', 'data', '=', 'self._get_buf(object_id_byte)', 'self.reduce_once(object_id_byte)', 'return', 'data'] | 962,366 |
huawei-noah/xingtian | share_by_plasma.py | ShareByPlasma.send | send | Send data to plasma server. | [
"Send",
"data",
"to",
"plasma",
"server."
] | def send(self, data, name=None, block=True):
data_buffer = serialize(data['data']).to_buffer()
compress_type = data['ctr_info'].get('compress_type', 'auto')
if compress_type in ['auto', 'compress']:
if sys.getsizeof(bytes(data_buffer)) > self.compress_threhold or compress_type == 'compress':
... | ['def', 'send(self,', 'data,', 'name=None,', 'block=True):', 'data_buffer', '=', "serialize(data['data']).to_buffer()", 'compress_type', '=', "data['ctr_info'].get('compress_type',", "'auto')", 'if', 'compress_type', 'in', "['auto',", "'compress']:", 'if', 'sys.getsizeof(bytes(data_buffer))', '>', 'self.compress_threho... | 962,369 |
huawei-noah/xingtian | share_by_plasma.py | ShareByPlasma.recv | recv | Receive data from plasma server. | [
"Receive",
"data",
"from",
"plasma",
"server."
] | def recv(self, name=None, block=True):
if not block and self.control_q.empty():
return None
ctr_info = self.control_q.get()
object_id = ctr_info['object_id']
compress_flag = ctr_info.get('compress_flag', False)
client = self.connect()
data = client.get_buffers([object_id])[0]
if comp... | ['def', 'recv(self,', 'name=None,', 'block=True):', 'if', 'not', 'block', 'and', 'self.control_q.empty():', 'return', 'None', 'ctr_info', '=', 'self.control_q.get()', 'object_id', '=', "ctr_info['object_id']", 'compress_flag', '=', "ctr_info.get('compress_flag',", 'False)', 'client', '=', 'self.connect()', 'data', '=',... | 962,370 |
huawei-noah/xingtian | share_by_raw_array.py | ShareByRawArray.recv | recv | Get data from share memory. | [
"Get",
"data",
"from",
"share",
"memory."
] | def recv(self, name=None):
(data_id, len_data) = self.control_q.get()
data = pyarrow.deserialize(lz4.frame.decompress(memoryview(self.mem)[int(data_id * self.size_mem_agent):int(data_id * self.size_mem_agent + len_data)]))
return data | ['def', 'recv(self,', 'name=None):', '(data_id,', 'len_data)', '=', 'self.control_q.get()', 'data', '=', 'pyarrow.deserialize(lz4.frame.decompress(memoryview(self.mem)[int(data_id', '*', 'self.size_mem_agent):int(data_id', '*', 'self.size_mem_agent', '+', 'len_data)]))', 'return', 'data'] | 962,377 |
huawei-noah/xingtian | share_by_raw_array.py | ShareByRawArray.recv_bytes | recv_bytes | Get data from share memory without deserialize. | [
"Get",
"data",
"from",
"share",
"memory",
"without",
"deserialize."
] | def recv_bytes(self, block):
(data_id, len_data) = self.control_q.get()
return memoryview(self.mem)[int(data_id * self.size_mem_agent):int(data_id * self.size_mem_agent + len_data)] | ['def', 'recv_bytes(self,', 'block):', '(data_id,', 'len_data)', '=', 'self.control_q.get()', 'return', 'memoryview(self.mem)[int(data_id', '*', 'self.size_mem_agent):int(data_id', '*', 'self.size_mem_agent', '+', 'len_data)]'] | 962,378 |
huawei-noah/xingtian | share_by_raw_array.py | ShareByRawArray.send_bytes | send_bytes | Put data in share memory without serialize. | [
"Put",
"data",
"in",
"share",
"memory",
"without",
"serialize."
] | def send_bytes(self, data):
(data_id, data_buffer) = data
memmove(addressof(self.mem) + int(data_id) * self.size_mem_agent, data_buffer, len(data_buffer))
self.control_q.put((data_id, len(data_buffer))) | ['def', 'send_bytes(self,', 'data):', '(data_id,', 'data_buffer)', '=', 'data', 'memmove(addressof(self.mem)', '+', 'int(data_id)', '*', 'self.size_mem_agent,', 'data_buffer,', 'len(data_buffer))', 'self.control_q.put((data_id,', 'len(data_buffer)))'] | 962,379 |
huawei-noah/xingtian | uni_comm.py | UniComm.send | send | Create common send interface. | [
"Create",
"common",
"send",
"interface."
] | def send(self, data, name=None, block=True, **kwargs):
return self.comm.send(data, name, block, **kwargs) | ['def', 'send(self,', 'data,', 'name=None,', 'block=True,', '**kwargs):', 'return', 'self.comm.send(data,', 'name,', 'block,', '**kwargs)'] | 962,385 |
huawei-noah/xingtian | uni_comm.py | UniComm.send_multipart | send_multipart | Create common send_multipart interface. | [
"Create",
"common",
"send_multipart",
"interface."
] | def send_multipart(self, data):
return self.comm.send_multipart(data) | ['def', 'send_multipart(self,', 'data):', 'return', 'self.comm.send_multipart(data)'] | 962,389 |
huawei-noah/xingtian | uni_comm.py | UniComm.recv_multipart | recv_multipart | Create common recv_multipart interface. | [
"Create",
"common",
"recv_multipart",
"interface."
] | def recv_multipart(self):
return self.comm.recv_multipart() | ['def', 'recv_multipart(self):', 'return', 'self.comm.recv_multipart()'] | 962,390 |
huawei-noah/xingtian | benchmark_data.py | Data.get_version | get_version | Get database version info. | [
"Get",
"database",
"version",
"info."
] | def get_version(self):
return self.VERSION | ['def', 'get_version(self):', 'return', 'self.VERSION'] | 962,391 |
huawei-noah/xingtian | check.py | make_rules | make_rules | Make new rule in dict for attr. | [
"Make",
"new",
"rule",
"in",
"dict",
"for",
"attr."
] | def make_rules(adict, attr_name, if_required, types, scpoe=None):
if attr_name not in adict:
adict[attr_name] = {}
adict[attr_name]['required'] = if_required
adict[attr_name]['type'] = types
if scpoe:
adict[attr_name]['scope'] = scpoe
return adict | ['def', 'make_rules(adict,', 'attr_name,', 'if_required,', 'types,', 'scpoe=None):', 'if', 'attr_name', 'not', 'in', 'adict:', 'adict[attr_name]', '=', '{}', "adict[attr_name]['required']", '=', 'if_required', "adict[attr_name]['type']", '=', 'types', 'if', 'scpoe:', "adict[attr_name]['scope']", '=', 'scpoe', 'return',... | 962,392 |
huawei-noah/xingtian | check.py | BaseChecking.check_all | check_all | Check rules for attr. | [
"Check",
"rules",
"for",
"attr."
] | def check_all(cls, attr_name, rules, checked_cls_name, config):
for subclass in cls.__subclasses__():
subclass.check(attr_name, rules, checked_cls_name, config) | ['def', 'check_all(cls,', 'attr_name,', 'rules,', 'checked_cls_name,', 'config):', 'for', 'subclass', 'in', 'cls.__subclasses__():', 'subclass.check(attr_name,', 'rules,', 'checked_cls_name,', 'config)'] | 962,393 |
huawei-noah/xingtian | common.py | bytes_to_str | bytes_to_str | Bytes to string, used after data transform by internet. | [
"Bytes",
"to",
"string,",
"used",
"after",
"data",
"transform",
"by",
"internet."
] | def bytes_to_str(data):
if isinstance(data, bytes):
return data if sys.version_info.major == 2 else data.decode('ascii')
if isinstance(data, dict):
return dict(map(bytes_to_str, data.items()))
if isinstance(data, tuple):
return map(bytes_to_str, data)
return data | ['def', 'bytes_to_str(data):', 'if', 'isinstance(data,', 'bytes):', 'return', 'data', 'if', 'sys.version_info.major', '==', '2', 'else', "data.decode('ascii')", 'if', 'isinstance(data,', 'dict):', 'return', 'dict(map(bytes_to_str,', 'data.items()))', 'if', 'isinstance(data,', 'tuple):', 'return', 'map(bytes_to_str,', '... | 962,400 |
huawei-noah/xingtian | common.py | get_host_ip | get_host_ip | Get local ip address. | [
"Get",
"local",
"ip",
"address."
] | def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip | ['def', 'get_host_ip():', 'try:', 's', '=', 'socket.socket(socket.AF_INET,', 'socket.SOCK_DGRAM)', "s.connect(('8.8.8.8',", '80))', 'ip', '=', 's.getsockname()[0]', 'finally:', 's.close()', 'return', 'ip'] | 962,401 |
huawei-noah/xingtian | evaluate_xt.py | make_workspace_if_not_exist | make_workspace_if_not_exist | Make workspace if not exist. | [
"Make",
"workspace",
"if",
"not",
"exist."
] | def make_workspace_if_not_exist(benchmark_args, subdir='models', task_name=None):
(workspace, archive_root, bm_id) = _make_workspace(benchmark_args, task_postfix=task_name)
make_dirs_if_not_exist(workspace)
if isinstance(subdir, str):
make_dirs_if_not_exist(os.path.join(workspace, subdir))
elif ... | ['def', 'make_workspace_if_not_exist(benchmark_args,', "subdir='models',", 'task_name=None):', '(workspace,', 'archive_root,', 'bm_id)', '=', '_make_workspace(benchmark_args,', 'task_postfix=task_name)', 'make_dirs_if_not_exist(workspace)', 'if', 'isinstance(subdir,', 'str):', 'make_dirs_if_not_exist(os.path.join(works... | 962,410 |
huawei-noah/xingtian | evaluate_xt.py | read_train_event_id | read_train_event_id | Read train event id. | [
"Read",
"train",
"event",
"id."
] | def read_train_event_id(benchmark_args):
(archive_root, bm_id) = _get_archive_bm_basic_info(benchmark_args)
return fetch_train_event(archive_root, bm_id, single=True) | ['def', 'read_train_event_id(benchmark_args):', '(archive_root,', 'bm_id)', '=', '_get_archive_bm_basic_info(benchmark_args)', 'return', 'fetch_train_event(archive_root,', 'bm_id,', 'single=True)'] | 962,412 |
huawei-noah/xingtian | evaluate_xt.py | get_bm_args_from_config | get_bm_args_from_config | Get bm args from config. | [
"Get",
"bm",
"args",
"from",
"config."
] | def get_bm_args_from_config(config):
alg_para = config['alg_para']
env_para = config['env_para']
agent_para = config['agent_para']
model_info = config['model_para']
alg_para['model_info'] = model_info
bm_info = config.get('benchmark', dict())
return parse_benchmark_args(env_para, alg_para, a... | ['def', 'get_bm_args_from_config(config):', 'alg_para', '=', "config['alg_para']", 'env_para', '=', "config['env_para']", 'agent_para', '=', "config['agent_para']", 'model_info', '=', "config['model_para']", "alg_para['model_info']", '=', 'model_info', 'bm_info', '=', "config.get('benchmark',", 'dict())', 'return', 'pa... | 962,413 |
huawei-noah/xingtian | evaluate_xt.py | read_train_records_from_config | read_train_records_from_config | Read train records from config. | [
"Read",
"train",
"records",
"from",
"config."
] | def read_train_records_from_config(config, use_index='step', stage='both'):
bm_args = get_bm_args_from_config(config)
return read_train_records(bm_args, use_index, stage) | ['def', 'read_train_records_from_config(config,', "use_index='step',", "stage='both'):", 'bm_args', '=', 'get_bm_args_from_config(config)', 'return', 'read_train_records(bm_args,', 'use_index,', 'stage)'] | 962,414 |
huawei-noah/xingtian | get_xt_config.py | finditem | finditem | Find key in dict. | [
"Find",
"key",
"in",
"dict."
] | def finditem(obj, key):
if not isinstance(obj, dict):
return None
elif key in obj:
return obj[key]
for (k, v) in obj.items():
ret_obj = finditem(v, key)
if ret_obj is not None:
return ret_obj | ['def', 'finditem(obj,', 'key):', 'if', 'not', 'isinstance(obj,', 'dict):', 'return', 'None', 'elif', 'key', 'in', 'obj:', 'return', 'obj[key]', 'for', '(k,', 'v)', 'in', 'obj.items():', 'ret_obj', '=', 'finditem(v,', 'key)', 'if', 'ret_obj', 'is', 'not', 'None:', 'return', 'ret_obj'] | 962,417 |
huawei-noah/xingtian | get_xt_config.py | parse_xt_multi_case_paras | parse_xt_multi_case_paras | Parse the multi-case config file entrance for benchmark. | [
"Parse",
"the",
"multi-case",
"config",
"file",
"entrance",
"for",
"benchmark."
] | def parse_xt_multi_case_paras(config_file, key_fields=('alg_config', 'agent_config')):
with open(config_file) as file_hander:
yaml_obj = yaml.safe_load(file_hander)
(parse_candidate, combination_count) = _get_combination_info(yaml_obj, key_fields)
para_prod_val = _get_product_value(parse_candidate)
... | ['def', 'parse_xt_multi_case_paras(config_file,', "key_fields=('alg_config',", "'agent_config')):", 'with', 'open(config_file)', 'as', 'file_hander:', 'yaml_obj', '=', 'yaml.safe_load(file_hander)', '(parse_candidate,', 'combination_count)', '=', '_get_combination_info(yaml_obj,', 'key_fields)', 'para_prod_val', '=', '... | 962,418 |
huawei-noah/xingtian | hw_cloud_helper.py | sync_data_from_s3 | sync_data_from_s3 | Sync data from user's s3 path to local machine, auto-check the local path firstly. | [
"Sync",
"data",
"from",
"user's",
"s3",
"path",
"to",
"local",
"machine,",
"auto-check",
"the",
"local",
"path",
"firstly."
] | def sync_data_from_s3(s3_path, destination):
local_makedir_if_not_existed(destination)
if not mox.file.is_directory(s3_path):
mox.file.copy(s3_path, destination)
else:
mox.file.copy_parallel(s3_path, destination) | ['def', 'sync_data_from_s3(s3_path,', 'destination):', 'local_makedir_if_not_existed(destination)', 'if', 'not', 'mox.file.is_directory(s3_path):', 'mox.file.copy(s3_path,', 'destination)', 'else:', 'mox.file.copy_parallel(s3_path,', 'destination)'] | 962,425 |
huawei-noah/xingtian | local_data.py | open_file | open_file | Need close by hand. | [
"Need",
"close",
"by",
"hand."
] | def open_file(file_path, open_type):
if file_path.startswith('s3://'):
import moxing as mox
ret_handle = mox.file.File(file_path, open_type)
else:
ret_handle = open(file_path, open_type)
return ret_handle | ['def', 'open_file(file_path,', 'open_type):', 'if', "file_path.startswith('s3://'):", 'import', 'moxing', 'as', 'mox', 'ret_handle', '=', 'mox.file.File(file_path,', 'open_type)', 'else:', 'ret_handle', '=', 'open(file_path,', 'open_type)', 'return', 'ret_handle'] | 962,426 |
huawei-noah/xingtian | logger.py | time_to_str | time_to_str | Convert seconds to days, hours, minutes and seconds. | [
"Convert",
"seconds",
"to",
"days,",
"hours,",
"minutes",
"and",
"seconds."
] | def time_to_str(sec):
(days, remainder) = divmod(sec, 60 * 60 * 24)
(hours, remainder) = divmod(remainder, 60 * 60)
(minutes, seconds) = divmod(remainder, 60)
_str = ''
if days > 0:
_str += '{:d} days, '.format(int(days))
if hours > 0:
_str += '{:d} hours, '.format(int(hours))
... | ['def', 'time_to_str(sec):', '(days,', 'remainder)', '=', 'divmod(sec,', '60', '*', '60', '*', '24)', '(hours,', 'remainder)', '=', 'divmod(remainder,', '60', '*', '60)', '(minutes,', 'seconds)', '=', 'divmod(remainder,', '60)', '_str', '=', "''", 'if', 'days', '>', '0:', '_str', '+=', "'{:d}", 'days,', "'.format(int(d... | 962,429 |
huawei-noah/xingtian | logger.py | Logger.elapsed_time | elapsed_time | Elapsed time set as an property. | [
"Elapsed",
"time",
"set",
"as",
"an",
"property."
] | def elapsed_time(self):
return time() - self.abs_start | ['def', 'elapsed_time(self):', 'return', 'time()', '-', 'self.abs_start'] | 962,430 |
huawei-noah/xingtian | logger.py | Logger.update | update | Update value could been rewrite. | [
"Update",
"value",
"could",
"been",
"rewrite."
] | def update(self, **kwargs):
self.records.update(kwargs) | ['def', 'update(self,', '**kwargs):', 'self.records.update(kwargs)'] | 962,431 |
huawei-noah/xingtian | logger.py | Logger.train_reward_avg | train_reward_avg | Train reward average could been property. | [
"Train",
"reward",
"average",
"could",
"been",
"property."
] | def train_reward_avg(self):
if not self.records['train_reward']:
return np.nan
return np.mean(self.records['train_reward'][-100:]) | ['def', 'train_reward_avg(self):', 'if', 'not', "self.records['train_reward']:", 'return', 'np.nan', 'return', "np.mean(self.records['train_reward'][-100:])"] | 962,434 |
huawei-noah/xingtian | logger.py | StatsRecorder.could_show_stats | could_show_stats | Check whether show or not. | [
"Check",
"whether",
"show",
"or",
"not."
] | def could_show_stats(self):
if self._data.get('step', 0) - self._last_show_step >= self.show_interval:
self._last_show_step = self._data.get('step', 0)
return True
return False | ['def', 'could_show_stats(self):', 'if', "self._data.get('step',", '0)', '-', 'self._last_show_step', '>=', 'self.show_interval:', 'self._last_show_step', '=', "self._data.get('step',", '0)', 'return', 'True', 'return', 'False'] | 962,438 |
huawei-noah/xingtian | logger.py | StatsRecorder.assemble_records | assemble_records | Assemble the data format for tensorboard. | [
"Assemble",
"the",
"data",
"format",
"for",
"tensorboard."
] | def assemble_records(self):
record_list = list()
for _key in BOARD_GROUP_MAP.keys():
try:
g_key = self.add_board_prefix(_key)
if not self._data[_key]:
continue
if np.nan is self._data[_key]:
continue
record_list.append((g_ke... | ['def', 'assemble_records(self):', 'record_list', '=', 'list()', 'for', '_key', 'in', 'BOARD_GROUP_MAP.keys():', 'try:', 'g_key', '=', 'self.add_board_prefix(_key)', 'if', 'not', 'self._data[_key]:', 'continue', 'if', 'np.nan', 'is', 'self._data[_key]:', 'continue', 'record_list.append((g_key,', 'self._data[_key],', "s... | 962,440 |
huawei-noah/xingtian | logger.py | StatsRecorder.process_stats | process_stats | Process a stats received. | [
"Process",
"a",
"stats",
"received."
] | def process_stats(self, stats):
if stats.get('ctr_info'):
if stats.get('ctr_info').get('cmd') == 'stats_msg{}'.format(self.name):
self.record_explore_status(stats['data'])
elif stats.get('is_bm'):
self.local_data_writer.insert_records(stats['data'])
bm_data2board = list()
... | ['def', 'process_stats(self,', 'stats):', 'if', "stats.get('ctr_info'):", 'if', "stats.get('ctr_info').get('cmd')", '==', "'stats_msg{}'.format(self.name):", "self.record_explore_status(stats['data'])", 'elif', "stats.get('is_bm'):", "self.local_data_writer.insert_records(stats['data'])", 'bm_data2board', '=', 'list()'... | 962,442 |
huawei-noah/xingtian | printer.py | print_immediately | print_immediately | Print some string immediately. | [
"Print",
"some",
"string",
"immediately."
] | def print_immediately(to_str):
print(to_str)
sys.stdout.flush() | ['def', 'print_immediately(to_str):', 'print(to_str)', 'sys.stdout.flush()'] | 962,443 |
huawei-noah/xingtian | printer.py | debug_within_interval | debug_within_interval | Print with time interval. | [
"Print",
"with",
"time",
"interval."
] | def debug_within_interval(logs=None, interval=10, func=None, human_able=False, **kwargs):
global LAST_PRINT
if time() - LAST_PRINT > interval:
if func and callable(func):
func(**kwargs)
if logs:
logs_human = pprint.pformat(logs, indent=0, width=1) if human_able else logs
... | ['def', 'debug_within_interval(logs=None,', 'interval=10,', 'func=None,', 'human_able=False,', '**kwargs):', 'global', 'LAST_PRINT', 'if', 'time()', '-', 'LAST_PRINT', '>', 'interval:', 'if', 'func', 'and', 'callable(func):', 'func(**kwargs)', 'if', 'logs:', 'logs_human', '=', 'pprint.pformat(logs,', 'indent=0,', 'widt... | 962,444 |
huawei-noah/xingtian | profiler.py | do_profile | do_profile | Create dummy for import error. | [
"Create",
"dummy",
"for",
"import",
"error."
] | def do_profile(follow=[], profiler=None):
def inner(func):
def nothing(*args, **kwargs):
return func(*args, **kwargs)
return nothing
return inner | ['def', 'do_profile(follow=[],', 'profiler=None):', 'def', 'inner(func):', 'def', 'nothing(*args,', '**kwargs):', 'return', 'func(*args,', '**kwargs)', 'return', 'nothing', 'return', 'inner'] | 962,446 |
huawei-noah/xingtian | profiler.py | save_and_dump_stats | save_and_dump_stats | Create utils for save stats into file. | [
"Create",
"utils",
"for",
"save",
"stats",
"into",
"file."
] | def save_and_dump_stats(profiler, stats_file='default_stats.pkl'):
if not profiler:
print('invalid profiler handler!')
return
if os.path.exists(stats_file):
print('remove {}, and re-write it.'.format(stats_file))
os.remove(stats_file)
else:
print('write into file: {}'... | ['def', 'save_and_dump_stats(profiler,', "stats_file='default_stats.pkl'):", 'if', 'not', 'profiler:', "print('invalid", 'profiler', "handler!')", 'return', 'if', 'os.path.exists(stats_file):', "print('remove", '{},', 'and', 're-write', "it.'.format(stats_file))", 'os.remove(stats_file)', 'else:', "print('write", 'into... | 962,447 |
huawei-noah/xingtian | profiler.py | show_stats_file | show_stats_file | Create utils for display stats. | [
"Create",
"utils",
"for",
"display",
"stats."
] | def show_stats_file(stats_file):
if not show_text:
print("Please use 'pip install line_profiler`, return with nothing do!")
return
def load_stats(filename):
with open(filename, 'rb') as stats_handle:
return pickle.load(stats_handle)
print(load_stats(stats_file))
tmp_... | ['def', 'show_stats_file(stats_file):', 'if', 'not', 'show_text:', 'print("Please', 'use', "'pip", 'install', 'line_profiler`,', 'return', 'with', 'nothing', 'do!")', 'return', 'def', 'load_stats(filename):', 'with', 'open(filename,', "'rb')", 'as', 'stats_handle:', 'return', 'pickle.load(stats_handle)', 'print(load_st... | 962,448 |
huawei-noah/xingtian | profile_stats.py | SingleTracker.average | average | Mean time of `with` interaction. | [
"Mean",
"time",
"of",
"`with`",
"interaction."
] | def average(self):
if not self.with_time_list:
return np.nan
return np.nanmean(self.with_time_list) * 1000 | ['def', 'average(self):', 'if', 'not', 'self.with_time_list:', 'return', 'np.nan', 'return', 'np.nanmean(self.with_time_list)', '*', '1000'] | 962,450 |
huawei-noah/xingtian | profile_stats.py | PredictStats.get | get | Get agent status and clear the buffer. | [
"Get",
"agent",
"status",
"and",
"clear",
"the",
"buffer."
] | def get(self):
ret = {'mean_predictor_wait_ms': self.obs_wait_time * 1000 / self.iters, 'mean_predictor_infer_ms': self.inference_time * 1000 / self.iters}
self.reset()
return ret | ['def', 'get(self):', 'ret', '=', "{'mean_predictor_wait_ms':", 'self.obs_wait_time', '*', '1000', '/', 'self.iters,', "'mean_predictor_infer_ms':", 'self.inference_time', '*', '1000', '/', 'self.iters}', 'self.reset()', 'return', 'ret'] | 962,451 |
huawei-noah/xingtian | profile_stats.py | AgentGroupStats.update_with_agent_stats | update_with_agent_stats | Update agent status to agent group. | [
"Update",
"agent",
"status",
"to",
"agent",
"group."
] | def update_with_agent_stats(self, agent_stats: list):
_steps = [sta['mean_env_step_time_ms'] for sta in agent_stats]
_infers = [sta['mean_inference_time_ms'] for sta in agent_stats]
_iters = [sta['iters'] for sta in agent_stats]
self._stats.update({'mean_env_step_ms': np.nanmean(_steps), 'mean_inference... | ['def', 'update_with_agent_stats(self,', 'agent_stats:', 'list):', '_steps', '=', "[sta['mean_env_step_time_ms']", 'for', 'sta', 'in', 'agent_stats]', '_infers', '=', "[sta['mean_inference_time_ms']", 'for', 'sta', 'in', 'agent_stats]', '_iters', '=', "[sta['iters']", 'for', 'sta', 'in', 'agent_stats]', "self._stats.up... | 962,453 |
huawei-noah/xingtian | profile_stats.py | AgentGroupStats.get | get | Get the newest one-explore-status of agent group. | [
"Get",
"the",
"newest",
"one-explore-status",
"of",
"agent",
"group."
] | def get(self):
self._stats.update({'explore_ms': self.explore_time_in_epi * 1000, 'wait_model_ms': self.wait_model_time * 1000, 'restore_model_ms': self.restore_model_time * 1000})
if self.iters > 0:
self._stats.update({'mean_env_step_ms': self.env_step_time * 1000 / self.iters, 'mean_inference_ms': sel... | ['def', 'get(self):', "self._stats.update({'explore_ms':", 'self.explore_time_in_epi', '*', '1000,', "'wait_model_ms':", 'self.wait_model_time', '*', '1000,', "'restore_model_ms':", 'self.restore_model_time', '*', '1000})', 'if', 'self.iters', '>', '0:', "self._stats.update({'mean_env_step_ms':", 'self.env_step_time', ... | 962,454 |
huawei-noah/xingtian | profile_stats.py | TimerRecorder.get_metric | get_metric | Fetch the newest time record. | [
"Fetch",
"the",
"newest",
"time",
"record."
] | def get_metric(self, fields):
ret = dict()
for _task in fields:
if not self.track_stub[_task]:
continue
ret.update({'{}_{}_mean_ms'.format(self.style, _task): 1000 * np.nanmean(self.track_stub[_task]), '{}_{}_max_ms'.format(self.style, _task): 1000 * np.max(self.track_stub[_task]), '... | ['def', 'get_metric(self,', 'fields):', 'ret', '=', 'dict()', 'for', '_task', 'in', 'fields:', 'if', 'not', 'self.track_stub[_task]:', 'continue', "ret.update({'{}_{}_mean_ms'.format(self.style,", '_task):', '1000', '*', 'np.nanmean(self.track_stub[_task]),', "'{}_{}_max_ms'.format(self.style,", '_task):', '1000', '*',... | 962,455 |
huawei-noah/xingtian | profile_stats.py | TimerRecorder.report_if_need | report_if_need | Rreport the time metric if need. | [
"Rreport",
"the",
"time",
"metric",
"if",
"need."
] | def report_if_need(self, field_sets=None, **kwargs):
if time() - self.last_report_time >= self.report_interval:
to_log = self.get_metric(field_sets or self.fields)
if kwargs:
to_log.update(kwargs)
to_log_format = pprint.pformat(to_log, indent=0, width=1)
logging.debug('\n... | ['def', 'report_if_need(self,', 'field_sets=None,', '**kwargs):', 'if', 'time()', '-', 'self.last_report_time', '>=', 'self.report_interval:', 'to_log', '=', 'self.get_metric(field_sets', 'or', 'self.fields)', 'if', 'kwargs:', 'to_log.update(kwargs)', 'to_log_format', '=', 'pprint.pformat(to_log,', 'indent=0,', 'width=... | 962,456 |
huawei-noah/xingtian | coco.py | collate_fn | collate_fn | Collate fn for data loader. | [
"Collate",
"fn",
"for",
"data",
"loader."
] | def collate_fn(batch):
return tuple(zip(*batch)) | ['def', 'collate_fn(batch):', 'return', 'tuple(zip(*batch))'] | 962,469 |
huawei-noah/xingtian | div2k.py | DIV2K.dataset_init | dataset_init | Costruct method, which will load some dateset information. | [
"Costruct",
"method,",
"which",
"will",
"load",
"some",
"dateset",
"information."
] | def dataset_init(self):
self.args.root_HR = FileOps.download_dataset(self.args.root_HR)
self.args.root_LR = FileOps.download_dataset(self.args.root_LR)
if self.args.subfile is not None:
with open(self.args.subfile) as f:
file_names = sorted([line.rstrip('\n') for line in f])
... | ['def', 'dataset_init(self):', 'self.args.root_HR', '=', 'FileOps.download_dataset(self.args.root_HR)', 'self.args.root_LR', '=', 'FileOps.download_dataset(self.args.root_LR)', 'if', 'self.args.subfile', 'is', 'not', 'None:', 'with', 'open(self.args.subfile)', 'as', 'f:', 'file_names', '=', "sorted([line.rstrip('\\n')"... | 962,470 |
huawei-noah/xingtian | auto_lane_pointlane_codec.py | PointLaneCodec.uniform_sample_lane_y_axis | uniform_sample_lane_y_axis | Ensure y from bottom of image. | [
"Ensure",
"y",
"from",
"bottom",
"of",
"image."
] | def uniform_sample_lane_y_axis(self, x_pt_list, y_pt_list):
if len(x_pt_list) < 2 or len(y_pt_list) < 2:
return (-1, -1, [], [])
max_y = y_pt_list[-1]
if max_y < self.input_height - 1:
y1 = y_pt_list[-2]
y2 = y_pt_list[-1]
x1 = x_pt_list[-2]
x2 = x_pt_list[-1]
... | ['def', 'uniform_sample_lane_y_axis(self,', 'x_pt_list,', 'y_pt_list):', 'if', 'len(x_pt_list)', '<', '2', 'or', 'len(y_pt_list)', '<', '2:', 'return', '(-1,', '-1,', '[],', '[])', 'max_y', '=', 'y_pt_list[-1]', 'if', 'max_y', '<', 'self.input_height', '-', '1:', 'y1', '=', 'y_pt_list[-2]', 'y2', '=', 'y_pt_list[-1]', ... | 962,501 |
huawei-noah/xingtian | auto_lane_pointlane_codec.py | PointLaneCodec.get_one_line_pass_anchors | get_one_line_pass_anchors | Get one line pass all anchors. | [
"Get",
"one",
"line",
"pass",
"all",
"anchors."
] | def get_one_line_pass_anchors(self, startpos, endpos, xlist, y_list, anchor_count):
anchor_list = []
anchor_distance_result = []
Gt_loc_list = []
for i in range(0, endpos - startpos + 1):
h = self.feature_height - 1 - int((startpos + i) * self.interval / self.step_h)
w = int(xlist[i] / s... | ['def', 'get_one_line_pass_anchors(self,', 'startpos,', 'endpos,', 'xlist,', 'y_list,', 'anchor_count):', 'anchor_list', '=', '[]', 'anchor_distance_result', '=', '[]', 'Gt_loc_list', '=', '[]', 'for', 'i', 'in', 'range(0,', 'endpos', '-', 'startpos', '+', '1):', 'h', '=', 'self.feature_height', '-', '1', '-', 'int((st... | 962,502 |
huawei-noah/xingtian | avazu_util.py | BaseDataset.summary | summary | Summarize the data set. | [
"Summarize",
"the",
"data",
"set."
] | def summary(self):
logging.info(self.__class__.__name__, 'data set summary:')
logging.info('train set: ', self.train_size)
logging.info('\tpositive samples: ', self.pos_train_samples)
logging.info('\tnegative samples: ', self.neg_train_samples)
logging.info('\tpositive ratio: ', self.train_pos_ratio... | ['def', 'summary(self):', 'logging.info(self.__class__.__name__,', "'data", 'set', "summary:')", "logging.info('train", 'set:', "',", 'self.train_size)', "logging.info('\\tpositive", 'samples:', "',", 'self.pos_train_samples)', "logging.info('\\tnegative", 'samples:', "',", 'self.neg_train_samples)', "logging.info('\\t... | 962,520 |
huawei-noah/xingtian | dataset.py | Dataset.transforms | transforms | Transform function which can replace transforms. | [
"Transform",
"function",
"which",
"can",
"replace",
"transforms."
] | def transforms(self):
return self._transforms | ['def', 'transforms(self):', 'return', 'self._transforms'] | 962,526 |
huawei-noah/xingtian | dataset.py | Dataset.transforms | transforms | Set function of transforms. | [
"Set",
"function",
"of",
"transforms."
] | def transforms(self, value):
self._transforms = value | ['def', 'transforms(self,', 'value):', 'self._transforms', '=', 'value'] | 962,527 |
huawei-noah/xingtian | adapter.py | TorchAdapter.sampler | sampler | Set function of sampler. | [
"Set",
"function",
"of",
"sampler."
] | def sampler(self, value):
self._sampler = value | ['def', 'sampler(self,', 'value):', 'self._sampler', '=', 'value'] | 962,588 |
huawei-noah/xingtian | adapter.py | TfAdapter.data_map_func | data_map_func | Apply data map function from raw data. | [
"Apply",
"data",
"map",
"function",
"from",
"raw",
"data."
] | def data_map_func(self, images_index, label_index):
if not self.is_detection:
(image, label) = tf.numpy_function(self._get_item, [images_index, label_index], [self.image_dtype_tf, self.label_dtype_tf])
if self.fixed_size:
image.set_shape(self.image_shape)
label.set_shape(self... | ['def', 'data_map_func(self,', 'images_index,', 'label_index):', 'if', 'not', 'self.is_detection:', '(image,', 'label)', '=', 'tf.numpy_function(self._get_item,', '[images_index,', 'label_index],', '[self.image_dtype_tf,', 'self.label_dtype_tf])', 'if', 'self.fixed_size:', 'image.set_shape(self.image_shape)', 'label.se... | 962,592 |
huawei-noah/xingtian | imagenet.py | Imagenet.input_fn | input_fn | Define input_fn used by Tensorflow Estimator. | [
"Define",
"input_fn",
"used",
"by",
"Tensorflow",
"Estimator."
] | def input_fn(self):
data_files = os.path.join(self.data_path, 'train/train-*' if self.mode == 'train' else 'val/val-*')
dataset = tf.data.Dataset.list_files(data_files, shuffle=False)
if self.world_size > 1:
dataset = dataset.shard(self.world_size, self.rank)
if self.mode == 'train':
dat... | ['def', 'input_fn(self):', 'data_files', '=', 'os.path.join(self.data_path,', "'train/train-*'", 'if', 'self.mode', '==', "'train'", 'else', "'val/val-*')", 'dataset', '=', 'tf.data.Dataset.list_files(data_files,', 'shuffle=False)', 'if', 'self.world_size', '>', '1:', 'dataset', '=', 'dataset.shard(self.world_size,', '... | 962,595 |
huawei-noah/xingtian | __init__.py | register_transforms | register_transforms | Import and register transforms automatically. | [
"Import",
"and",
"register",
"transforms",
"automatically."
] | def register_transforms(backend):
import zeus
if zeus.is_gpu_device():
from .ImageTransform import ImageTransform
from .Invert import Invert
from .MaskTransform import MaskTransform
from .Posterize import Posterize
from .RandomCrop_pair import RandomCrop_pair
from... | ['def', 'register_transforms(backend):', 'import', 'zeus', 'if', 'zeus.is_gpu_device():', 'from', '.ImageTransform', 'import', 'ImageTransform', 'from', '.Invert', 'import', 'Invert', 'from', '.MaskTransform', 'import', 'MaskTransform', 'from', '.Posterize', 'import', 'Posterize', 'from', '.RandomCrop_pair', 'import', ... | 962,600 |
huawei-noah/xingtian | device_evaluator.py | DeviceEvaluator.train_process | train_process | Validate process for the model validate worker. | [
"Validate",
"process",
"for",
"the",
"model",
"validate",
"worker."
] | def train_process(self):
init_log(level=General.logger.level, log_file='device_evaluator_{}.log'.format(self.worker_id), log_path=self.local_log_path)
logging.info('start davinci or mobile evaluate process')
self.load_model()
self.valid_loader = self._init_dataloader(mode='test')
performance = self.... | ['def', 'train_process(self):', 'init_log(level=General.logger.level,', "log_file='device_evaluator_{}.log'.format(self.worker_id),", 'log_path=self.local_log_path)', "logging.info('start", 'davinci', 'or', 'mobile', 'evaluate', "process')", 'self.load_model()', 'self.valid_loader', '=', "self._init_dataloader(mode='te... | 962,606 |
huawei-noah/xingtian | evaluator.py | Evaluator.size | size | Return the size of current evaluator list. | [
"Return",
"the",
"size",
"of",
"current",
"evaluator",
"list."
] | def size(self):
return len(self.sub_worker_list) | ['def', 'size(self):', 'return', 'len(self.sub_worker_list)'] | 962,607 |
huawei-noah/xingtian | flops_and_params.py | add_new_hooks | add_new_hooks | Add new register hooks to custom hooks. | [
"Add",
"new",
"register",
"hooks",
"to",
"custom",
"hooks."
] | def add_new_hooks(custom_hooks):
import torch.nn as nn
from thop.profile import register_hooks
from thop.vision.basic_hooks import count_softmax
from zeus.modules.operators import ops
add_register_hooks = {nn.PReLU: register_hooks[nn.ReLU], nn.ELU: register_hooks[nn.ReLU], nn.Softmax: count_softmax,... | ['def', 'add_new_hooks(custom_hooks):', 'import', 'torch.nn', 'as', 'nn', 'from', 'thop.profile', 'import', 'register_hooks', 'from', 'thop.vision.basic_hooks', 'import', 'count_softmax', 'from', 'zeus.modules.operators', 'import', 'ops', 'add_register_hooks', '=', '{nn.PReLU:', 'register_hooks[nn.ReLU],', 'nn.ELU:', '... | 962,618 |
huawei-noah/xingtian | __init__.py | register_metrics | register_metrics | Import and register metrics automatically. | [
"Import",
"and",
"register",
"metrics",
"automatically."
] | def register_metrics(backend):
if backend == 'pytorch':
from . import pytorch
elif backend == 'tensorflow':
from . import tensorflow
elif backend == 'mindspore':
from . import mindspore | ['def', 'register_metrics(backend):', 'if', 'backend', '==', "'pytorch':", 'from', '.', 'import', 'pytorch', 'elif', 'backend', '==', "'tensorflow':", 'from', '.', 'import', 'tensorflow', 'elif', 'backend', '==', "'mindspore':", 'from', '.', 'import', 'mindspore'] | 962,624 |
huawei-noah/xingtian | metrics.py | Metrics.reset | reset | Reset states for new evaluation after each epoch. | [
"Reset",
"states",
"for",
"new",
"evaluation",
"after",
"each",
"epoch."
] | def reset(self):
self.metric_results = dict() | ['def', 'reset(self):', 'self.metric_results', '=', 'dict()'] | 962,628 |
huawei-noah/xingtian | auc_metrics.py | AUC.summary | summary | Summary all cached records, here is the last pfm record. | [
"Summary",
"all",
"cached",
"records,",
"here",
"is",
"the",
"last",
"pfm",
"record."
] | def summary(self):
return self.pfm | ['def', 'summary(self):', 'return', 'self.pfm'] | 962,636 |
huawei-noah/xingtian | lane_metric.py | LaneMetricCore.summary | summary | Summary all record from result cache, and get performance. | [
"Summary",
"all",
"record",
"from",
"result",
"cache,",
"and",
"get",
"performance."
] | def summary(self):
hit_num = sum((result['hit_num'] for result in self.result_record))
pr_num = sum((result['pr_num'] for result in self.result_record))
gt_num = sum((result['gt_num'] for result in self.result_record))
precision = hit_num / (pr_num + sys.float_info.epsilon)
recall = hit_num / (gt_nu... | ['def', 'summary(self):', 'hit_num', '=', "sum((result['hit_num']", 'for', 'result', 'in', 'self.result_record))', 'pr_num', '=', "sum((result['pr_num']", 'for', 'result', 'in', 'self.result_record))', 'gt_num', '=', "sum((result['gt_num']", 'for', 'result', 'in', 'self.result_record))', 'precision', '=', 'hit_num', '/... | 962,653 |
huawei-noah/xingtian | metrics.py | MetricBase.summary | summary | Summary all cached records, called after valid. | [
"Summary",
"all",
"cached",
"records,",
"called",
"after",
"valid."
] | def summary(self):
raise NotImplementedError | ['def', 'summary(self):', 'raise', 'NotImplementedError'] | 962,657 |
huawei-noah/xingtian | compressed_model_filter.py | CompressedModelFilter.select_satisfied_model | select_satisfied_model | Select satisfied models by standard. | [
"Select",
"satisfied",
"models",
"by",
"standard."
] | def select_satisfied_model(self, standard, num):
(target, restrict) = self._parse_standard(standard)
candidates = self._filtrate(restrict)
satisfied_models = self._choose_models(candidates, target, num)
return satisfied_models | ['def', 'select_satisfied_model(self,', 'standard,', 'num):', '(target,', 'restrict)', '=', 'self._parse_standard(standard)', 'candidates', '=', 'self._filtrate(restrict)', 'satisfied_models', '=', 'self._choose_models(candidates,', 'target,', 'num)', 'return', 'satisfied_models'] | 962,691 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.