id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
237,500 | MillionIntegrals/vel | vel/rl/api/rollout.py | Transitions.shuffled_batches | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data """
if batch_size >= self.size:
yield self
else:
batch_splits = math_util.divide_ceiling(self.size, batch_size)
indices = list(range(self.size))
np.random.shuffle(indic... | python | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data """
if batch_size >= self.size:
yield self
else:
batch_splits = math_util.divide_ceiling(self.size, batch_size)
indices = list(range(self.size))
np.random.shuffle(indic... | [
"def",
"shuffled_batches",
"(",
"self",
",",
"batch_size",
")",
":",
"if",
"batch_size",
">=",
"self",
".",
"size",
":",
"yield",
"self",
"else",
":",
"batch_splits",
"=",
"math_util",
".",
"divide_ceiling",
"(",
"self",
".",
"size",
",",
"batch_size",
")"... | Generate randomized batches of data | [
"Generate",
"randomized",
"batches",
"of",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L59-L76 |
237,501 | MillionIntegrals/vel | vel/rl/api/rollout.py | Trajectories.to_transitions | def to_transitions(self) -> 'Transitions':
""" Convert given rollout to Transitions """
# No need to propagate 'rollout_tensors' as they won't mean anything
return Transitions(
size=self.num_steps * self.num_envs,
environment_information=
[ei for l in self... | python | def to_transitions(self) -> 'Transitions':
""" Convert given rollout to Transitions """
# No need to propagate 'rollout_tensors' as they won't mean anything
return Transitions(
size=self.num_steps * self.num_envs,
environment_information=
[ei for l in self... | [
"def",
"to_transitions",
"(",
"self",
")",
"->",
"'Transitions'",
":",
"# No need to propagate 'rollout_tensors' as they won't mean anything",
"return",
"Transitions",
"(",
"size",
"=",
"self",
".",
"num_steps",
"*",
"self",
".",
"num_envs",
",",
"environment_information"... | Convert given rollout to Transitions | [
"Convert",
"given",
"rollout",
"to",
"Transitions"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L111-L123 |
237,502 | MillionIntegrals/vel | vel/rl/api/rollout.py | Trajectories.shuffled_batches | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data - only sample whole trajectories """
if batch_size >= self.num_envs * self.num_steps:
yield self
else:
rollouts_in_batch = batch_size // self.num_steps
batch_splits = math_util.di... | python | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data - only sample whole trajectories """
if batch_size >= self.num_envs * self.num_steps:
yield self
else:
rollouts_in_batch = batch_size // self.num_steps
batch_splits = math_util.di... | [
"def",
"shuffled_batches",
"(",
"self",
",",
"batch_size",
")",
":",
"if",
"batch_size",
">=",
"self",
".",
"num_envs",
"*",
"self",
".",
"num_steps",
":",
"yield",
"self",
"else",
":",
"rollouts_in_batch",
"=",
"batch_size",
"//",
"self",
".",
"num_steps",
... | Generate randomized batches of data - only sample whole trajectories | [
"Generate",
"randomized",
"batches",
"of",
"data",
"-",
"only",
"sample",
"whole",
"trajectories"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L125-L147 |
237,503 | MillionIntegrals/vel | vel/rl/api/rollout.py | Trajectories.episode_information | def episode_information(self):
""" List of information about finished episodes """
return [
info.get('episode') for infolist in self.environment_information for info in infolist if 'episode' in info
] | python | def episode_information(self):
""" List of information about finished episodes """
return [
info.get('episode') for infolist in self.environment_information for info in infolist if 'episode' in info
] | [
"def",
"episode_information",
"(",
"self",
")",
":",
"return",
"[",
"info",
".",
"get",
"(",
"'episode'",
")",
"for",
"infolist",
"in",
"self",
".",
"environment_information",
"for",
"info",
"in",
"infolist",
"if",
"'episode'",
"in",
"info",
"]"
] | List of information about finished episodes | [
"List",
"of",
"information",
"about",
"finished",
"episodes"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L164-L168 |
237,504 | MillionIntegrals/vel | vel/models/rnn/multilayer_rnn_sequence_model.py | MultilayerRnnSequenceModel.forward_state | def forward_state(self, sequence, state=None):
""" Forward propagate a sequence through the network accounting for the state """
if state is None:
state = self.zero_state(sequence.size(0))
data = self.input_block(sequence)
state_outputs = []
# for layer_length, lay... | python | def forward_state(self, sequence, state=None):
""" Forward propagate a sequence through the network accounting for the state """
if state is None:
state = self.zero_state(sequence.size(0))
data = self.input_block(sequence)
state_outputs = []
# for layer_length, lay... | [
"def",
"forward_state",
"(",
"self",
",",
"sequence",
",",
"state",
"=",
"None",
")",
":",
"if",
"state",
"is",
"None",
":",
"state",
"=",
"self",
".",
"zero_state",
"(",
"sequence",
".",
"size",
"(",
"0",
")",
")",
"data",
"=",
"self",
".",
"input... | Forward propagate a sequence through the network accounting for the state | [
"Forward",
"propagate",
"a",
"sequence",
"through",
"the",
"network",
"accounting",
"for",
"the",
"state"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/rnn/multilayer_rnn_sequence_model.py#L66-L95 |
237,505 | MillionIntegrals/vel | vel/models/rnn/multilayer_rnn_sequence_model.py | MultilayerRnnSequenceModel.loss_value | def loss_value(self, x_data, y_true, y_pred):
""" Calculate a value of loss function """
y_pred = y_pred.view(-1, y_pred.size(2))
y_true = y_true.view(-1).to(torch.long)
return F.nll_loss(y_pred, y_true) | python | def loss_value(self, x_data, y_true, y_pred):
""" Calculate a value of loss function """
y_pred = y_pred.view(-1, y_pred.size(2))
y_true = y_true.view(-1).to(torch.long)
return F.nll_loss(y_pred, y_true) | [
"def",
"loss_value",
"(",
"self",
",",
"x_data",
",",
"y_true",
",",
"y_pred",
")",
":",
"y_pred",
"=",
"y_pred",
".",
"view",
"(",
"-",
"1",
",",
"y_pred",
".",
"size",
"(",
"2",
")",
")",
"y_true",
"=",
"y_true",
".",
"view",
"(",
"-",
"1",
"... | Calculate a value of loss function | [
"Calculate",
"a",
"value",
"of",
"loss",
"function"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/rnn/multilayer_rnn_sequence_model.py#L106-L110 |
237,506 | MillionIntegrals/vel | vel/api/learner.py | Learner.initialize_training | def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare for training """
if model_state is None:
self.model.reset_weights()
else:
self.model.load_state_dict(model_state) | python | def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare for training """
if model_state is None:
self.model.reset_weights()
else:
self.model.load_state_dict(model_state) | [
"def",
"initialize_training",
"(",
"self",
",",
"training_info",
":",
"TrainingInfo",
",",
"model_state",
"=",
"None",
",",
"hidden_state",
"=",
"None",
")",
":",
"if",
"model_state",
"is",
"None",
":",
"self",
".",
"model",
".",
"reset_weights",
"(",
")",
... | Prepare for training | [
"Prepare",
"for",
"training"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L36-L41 |
237,507 | MillionIntegrals/vel | vel/api/learner.py | Learner.run_epoch | def run_epoch(self, epoch_info: EpochInfo, source: 'vel.api.Source'):
""" Run full epoch of learning """
epoch_info.on_epoch_begin()
lr = epoch_info.optimizer.param_groups[-1]['lr']
print("|-------- Epoch {:06} Lr={:.6f} ----------|".format(epoch_info.global_epoch_idx, lr))
sel... | python | def run_epoch(self, epoch_info: EpochInfo, source: 'vel.api.Source'):
""" Run full epoch of learning """
epoch_info.on_epoch_begin()
lr = epoch_info.optimizer.param_groups[-1]['lr']
print("|-------- Epoch {:06} Lr={:.6f} ----------|".format(epoch_info.global_epoch_idx, lr))
sel... | [
"def",
"run_epoch",
"(",
"self",
",",
"epoch_info",
":",
"EpochInfo",
",",
"source",
":",
"'vel.api.Source'",
")",
":",
"epoch_info",
".",
"on_epoch_begin",
"(",
")",
"lr",
"=",
"epoch_info",
".",
"optimizer",
".",
"param_groups",
"[",
"-",
"1",
"]",
"[",
... | Run full epoch of learning | [
"Run",
"full",
"epoch",
"of",
"learning"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L43-L56 |
237,508 | MillionIntegrals/vel | vel/api/learner.py | Learner.train_epoch | def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True):
""" Run a single training epoch """
self.train()
if interactive:
iterator = tqdm.tqdm(source.train_loader(), desc="Training", unit="iter", file=sys.stdout)
else:
iterator = source.trai... | python | def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True):
""" Run a single training epoch """
self.train()
if interactive:
iterator = tqdm.tqdm(source.train_loader(), desc="Training", unit="iter", file=sys.stdout)
else:
iterator = source.trai... | [
"def",
"train_epoch",
"(",
"self",
",",
"epoch_info",
",",
"source",
":",
"'vel.api.Source'",
",",
"interactive",
"=",
"True",
")",
":",
"self",
".",
"train",
"(",
")",
"if",
"interactive",
":",
"iterator",
"=",
"tqdm",
".",
"tqdm",
"(",
"source",
".",
... | Run a single training epoch | [
"Run",
"a",
"single",
"training",
"epoch"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L58-L74 |
237,509 | MillionIntegrals/vel | vel/api/learner.py | Learner.validation_epoch | def validation_epoch(self, epoch_info, source: 'vel.api.Source'):
""" Run a single evaluation epoch """
self.eval()
iterator = tqdm.tqdm(source.val_loader(), desc="Validation", unit="iter", file=sys.stdout)
with torch.no_grad():
for batch_idx, (data, target) in enumerate(it... | python | def validation_epoch(self, epoch_info, source: 'vel.api.Source'):
""" Run a single evaluation epoch """
self.eval()
iterator = tqdm.tqdm(source.val_loader(), desc="Validation", unit="iter", file=sys.stdout)
with torch.no_grad():
for batch_idx, (data, target) in enumerate(it... | [
"def",
"validation_epoch",
"(",
"self",
",",
"epoch_info",
",",
"source",
":",
"'vel.api.Source'",
")",
":",
"self",
".",
"eval",
"(",
")",
"iterator",
"=",
"tqdm",
".",
"tqdm",
"(",
"source",
".",
"val_loader",
"(",
")",
",",
"desc",
"=",
"\"Validation\... | Run a single evaluation epoch | [
"Run",
"a",
"single",
"evaluation",
"epoch"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L76-L88 |
237,510 | MillionIntegrals/vel | vel/api/learner.py | Learner.feed_batch | def feed_batch(self, batch_info, data, target):
""" Run single batch of data """
data, target = data.to(self.device), target.to(self.device)
output, loss = self.model.loss(data, target)
# Store extra batch information for calculation of the statistics
batch_info['data'] = data
... | python | def feed_batch(self, batch_info, data, target):
""" Run single batch of data """
data, target = data.to(self.device), target.to(self.device)
output, loss = self.model.loss(data, target)
# Store extra batch information for calculation of the statistics
batch_info['data'] = data
... | [
"def",
"feed_batch",
"(",
"self",
",",
"batch_info",
",",
"data",
",",
"target",
")",
":",
"data",
",",
"target",
"=",
"data",
".",
"to",
"(",
"self",
".",
"device",
")",
",",
"target",
".",
"to",
"(",
"self",
".",
"device",
")",
"output",
",",
"... | Run single batch of data | [
"Run",
"single",
"batch",
"of",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L90-L101 |
237,511 | MillionIntegrals/vel | vel/api/learner.py | Learner.train_batch | def train_batch(self, batch_info, data, target):
""" Train single batch of data """
batch_info.optimizer.zero_grad()
loss = self.feed_batch(batch_info, data, target)
loss.backward()
if self.max_grad_norm is not None:
batch_info['grad_norm'] = torch.nn.utils.clip_grad... | python | def train_batch(self, batch_info, data, target):
""" Train single batch of data """
batch_info.optimizer.zero_grad()
loss = self.feed_batch(batch_info, data, target)
loss.backward()
if self.max_grad_norm is not None:
batch_info['grad_norm'] = torch.nn.utils.clip_grad... | [
"def",
"train_batch",
"(",
"self",
",",
"batch_info",
",",
"data",
",",
"target",
")",
":",
"batch_info",
".",
"optimizer",
".",
"zero_grad",
"(",
")",
"loss",
"=",
"self",
".",
"feed_batch",
"(",
"batch_info",
",",
"data",
",",
"target",
")",
"loss",
... | Train single batch of data | [
"Train",
"single",
"batch",
"of",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L103-L115 |
237,512 | MillionIntegrals/vel | vel/util/situational.py | process_environment_settings | def process_environment_settings(default_dictionary: dict, settings: typing.Optional[dict]=None,
presets: typing.Optional[dict]=None):
""" Process a dictionary of env settings """
settings = settings if settings is not None else {}
presets = presets if presets is not None el... | python | def process_environment_settings(default_dictionary: dict, settings: typing.Optional[dict]=None,
presets: typing.Optional[dict]=None):
""" Process a dictionary of env settings """
settings = settings if settings is not None else {}
presets = presets if presets is not None el... | [
"def",
"process_environment_settings",
"(",
"default_dictionary",
":",
"dict",
",",
"settings",
":",
"typing",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"presets",
":",
"typing",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
")",
":",
"setting... | Process a dictionary of env settings | [
"Process",
"a",
"dictionary",
"of",
"env",
"settings"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/situational.py#L4-L27 |
237,513 | MillionIntegrals/vel | vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py | BufferedOffPolicyIterationReinforcer.roll_out_and_store | def roll_out_and_store(self, batch_info):
""" Roll out environment and store result in the replay buffer """
self.model.train()
if self.env_roller.is_ready_for_sampling():
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device)
... | python | def roll_out_and_store(self, batch_info):
""" Roll out environment and store result in the replay buffer """
self.model.train()
if self.env_roller.is_ready_for_sampling():
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device)
... | [
"def",
"roll_out_and_store",
"(",
"self",
",",
"batch_info",
")",
":",
"self",
".",
"model",
".",
"train",
"(",
")",
"if",
"self",
".",
"env_roller",
".",
"is_ready_for_sampling",
"(",
")",
":",
"rollout",
"=",
"self",
".",
"env_roller",
".",
"rollout",
... | Roll out environment and store result in the replay buffer | [
"Roll",
"out",
"environment",
"and",
"store",
"result",
"in",
"the",
"replay",
"buffer"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py#L109-L135 |
237,514 | MillionIntegrals/vel | vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py | BufferedOffPolicyIterationReinforcer.train_on_replay_memory | def train_on_replay_memory(self, batch_info):
""" Train agent on a memory gotten from replay buffer """
self.model.train()
# Algo will aggregate data into this list:
batch_info['sub_batch_data'] = []
for i in range(self.settings.training_rounds):
sampled_rollout = s... | python | def train_on_replay_memory(self, batch_info):
""" Train agent on a memory gotten from replay buffer """
self.model.train()
# Algo will aggregate data into this list:
batch_info['sub_batch_data'] = []
for i in range(self.settings.training_rounds):
sampled_rollout = s... | [
"def",
"train_on_replay_memory",
"(",
"self",
",",
"batch_info",
")",
":",
"self",
".",
"model",
".",
"train",
"(",
")",
"# Algo will aggregate data into this list:",
"batch_info",
"[",
"'sub_batch_data'",
"]",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"s... | Train agent on a memory gotten from replay buffer | [
"Train",
"agent",
"on",
"a",
"memory",
"gotten",
"from",
"replay",
"buffer"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py#L137-L158 |
237,515 | MillionIntegrals/vel | vel/modules/resnet_v1.py | conv3x3 | def conv3x3(in_channels, out_channels, stride=1):
"""
3x3 convolution with padding.
Original code has had bias turned off, because Batch Norm would remove the bias either way
"""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False) | python | def conv3x3(in_channels, out_channels, stride=1):
"""
3x3 convolution with padding.
Original code has had bias turned off, because Batch Norm would remove the bias either way
"""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False) | [
"def",
"conv3x3",
"(",
"in_channels",
",",
"out_channels",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_channels",
",",
"out_channels",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
... | 3x3 convolution with padding.
Original code has had bias turned off, because Batch Norm would remove the bias either way | [
"3x3",
"convolution",
"with",
"padding",
".",
"Original",
"code",
"has",
"had",
"bias",
"turned",
"off",
"because",
"Batch",
"Norm",
"would",
"remove",
"the",
"bias",
"either",
"way"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/modules/resnet_v1.py#L10-L15 |
237,516 | MillionIntegrals/vel | vel/notebook/loader.py | load | def load(config_path, run_number=0, device='cuda:0'):
""" Load a ModelConfig from filename """
model_config = ModelConfig.from_file(config_path, run_number, device=device)
return model_config | python | def load(config_path, run_number=0, device='cuda:0'):
""" Load a ModelConfig from filename """
model_config = ModelConfig.from_file(config_path, run_number, device=device)
return model_config | [
"def",
"load",
"(",
"config_path",
",",
"run_number",
"=",
"0",
",",
"device",
"=",
"'cuda:0'",
")",
":",
"model_config",
"=",
"ModelConfig",
".",
"from_file",
"(",
"config_path",
",",
"run_number",
",",
"device",
"=",
"device",
")",
"return",
"model_config"... | Load a ModelConfig from filename | [
"Load",
"a",
"ModelConfig",
"from",
"filename"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/notebook/loader.py#L4-L8 |
237,517 | MillionIntegrals/vel | vel/api/info.py | TrainingInfo.restore | def restore(self, hidden_state):
""" Restore any state from checkpoint - currently not implemented but possible to do so in the future """
for callback in self.callbacks:
callback.load_state_dict(self, hidden_state)
if 'optimizer' in hidden_state:
self.optimizer_initial_... | python | def restore(self, hidden_state):
""" Restore any state from checkpoint - currently not implemented but possible to do so in the future """
for callback in self.callbacks:
callback.load_state_dict(self, hidden_state)
if 'optimizer' in hidden_state:
self.optimizer_initial_... | [
"def",
"restore",
"(",
"self",
",",
"hidden_state",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"callback",
".",
"load_state_dict",
"(",
"self",
",",
"hidden_state",
")",
"if",
"'optimizer'",
"in",
"hidden_state",
":",
"self",
".",
"o... | Restore any state from checkpoint - currently not implemented but possible to do so in the future | [
"Restore",
"any",
"state",
"from",
"checkpoint",
"-",
"currently",
"not",
"implemented",
"but",
"possible",
"to",
"do",
"so",
"in",
"the",
"future"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L47-L53 |
237,518 | MillionIntegrals/vel | vel/api/info.py | EpochResultAccumulator.result | def result(self):
""" Return the epoch result """
final_result = {'epoch_idx': self.global_epoch_idx}
for key, value in self.frozen_results.items():
final_result[key] = value
return final_result | python | def result(self):
""" Return the epoch result """
final_result = {'epoch_idx': self.global_epoch_idx}
for key, value in self.frozen_results.items():
final_result[key] = value
return final_result | [
"def",
"result",
"(",
"self",
")",
":",
"final_result",
"=",
"{",
"'epoch_idx'",
":",
"self",
".",
"global_epoch_idx",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"frozen_results",
".",
"items",
"(",
")",
":",
"final_result",
"[",
"key",
"]",
"... | Return the epoch result | [
"Return",
"the",
"epoch",
"result"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L144-L151 |
237,519 | MillionIntegrals/vel | vel/api/info.py | EpochInfo.state_dict | def state_dict(self) -> dict:
""" Calculate hidden state dictionary """
hidden_state = {}
if self.optimizer is not None:
hidden_state['optimizer'] = self.optimizer.state_dict()
for callback in self.callbacks:
callback.write_state_dict(self.training_info, hidden_... | python | def state_dict(self) -> dict:
""" Calculate hidden state dictionary """
hidden_state = {}
if self.optimizer is not None:
hidden_state['optimizer'] = self.optimizer.state_dict()
for callback in self.callbacks:
callback.write_state_dict(self.training_info, hidden_... | [
"def",
"state_dict",
"(",
"self",
")",
"->",
"dict",
":",
"hidden_state",
"=",
"{",
"}",
"if",
"self",
".",
"optimizer",
"is",
"not",
"None",
":",
"hidden_state",
"[",
"'optimizer'",
"]",
"=",
"self",
".",
"optimizer",
".",
"state_dict",
"(",
")",
"for... | Calculate hidden state dictionary | [
"Calculate",
"hidden",
"state",
"dictionary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L186-L196 |
237,520 | MillionIntegrals/vel | vel/api/info.py | EpochInfo.on_epoch_end | def on_epoch_end(self):
""" Finish epoch processing """
self.freeze_epoch_result()
for callback in self.callbacks:
callback.on_epoch_end(self)
self.training_info.history.add(self.result) | python | def on_epoch_end(self):
""" Finish epoch processing """
self.freeze_epoch_result()
for callback in self.callbacks:
callback.on_epoch_end(self)
self.training_info.history.add(self.result) | [
"def",
"on_epoch_end",
"(",
"self",
")",
":",
"self",
".",
"freeze_epoch_result",
"(",
")",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"callback",
".",
"on_epoch_end",
"(",
"self",
")",
"self",
".",
"training_info",
".",
"history",
".",
"add",... | Finish epoch processing | [
"Finish",
"epoch",
"processing"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L203-L210 |
237,521 | MillionIntegrals/vel | vel/api/info.py | BatchInfo.aggregate_key | def aggregate_key(self, aggregate_key):
""" Aggregate values from key and put them into the top-level dictionary """
aggregation = self.data_dict[aggregate_key] # List of dictionaries of numpy arrays/scalars
# Aggregate sub batch data
data_dict_keys = {y for x in aggregation for y in x... | python | def aggregate_key(self, aggregate_key):
""" Aggregate values from key and put them into the top-level dictionary """
aggregation = self.data_dict[aggregate_key] # List of dictionaries of numpy arrays/scalars
# Aggregate sub batch data
data_dict_keys = {y for x in aggregation for y in x... | [
"def",
"aggregate_key",
"(",
"self",
",",
"aggregate_key",
")",
":",
"aggregation",
"=",
"self",
".",
"data_dict",
"[",
"aggregate_key",
"]",
"# List of dictionaries of numpy arrays/scalars",
"# Aggregate sub batch data",
"data_dict_keys",
"=",
"{",
"y",
"for",
"x",
"... | Aggregate values from key and put them into the top-level dictionary | [
"Aggregate",
"values",
"from",
"key",
"and",
"put",
"them",
"into",
"the",
"top",
"-",
"level",
"dictionary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L316-L326 |
237,522 | MillionIntegrals/vel | vel/rl/commands/rl_train_command.py | RlTrainCommand.run | def run(self):
""" Run reinforcement learning algorithm """
device = self.model_config.torch_device()
# Reinforcer is the learner for the reinforcement learning model
reinforcer = self.reinforcer.instantiate(device)
optimizer = self.optimizer_factory.instantiate(reinforcer.model... | python | def run(self):
""" Run reinforcement learning algorithm """
device = self.model_config.torch_device()
# Reinforcer is the learner for the reinforcement learning model
reinforcer = self.reinforcer.instantiate(device)
optimizer = self.optimizer_factory.instantiate(reinforcer.model... | [
"def",
"run",
"(",
"self",
")",
":",
"device",
"=",
"self",
".",
"model_config",
".",
"torch_device",
"(",
")",
"# Reinforcer is the learner for the reinforcement learning model",
"reinforcer",
"=",
"self",
".",
"reinforcer",
".",
"instantiate",
"(",
"device",
")",
... | Run reinforcement learning algorithm | [
"Run",
"reinforcement",
"learning",
"algorithm"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L62-L104 |
237,523 | MillionIntegrals/vel | vel/rl/commands/rl_train_command.py | RlTrainCommand.resume_training | def resume_training(self, reinforcer, callbacks, metrics) -> TrainingInfo:
""" Possibly resume training from a saved state from the storage """
if self.model_config.continue_training:
start_epoch = self.storage.last_epoch_idx()
else:
start_epoch = 0
training_info... | python | def resume_training(self, reinforcer, callbacks, metrics) -> TrainingInfo:
""" Possibly resume training from a saved state from the storage """
if self.model_config.continue_training:
start_epoch = self.storage.last_epoch_idx()
else:
start_epoch = 0
training_info... | [
"def",
"resume_training",
"(",
"self",
",",
"reinforcer",
",",
"callbacks",
",",
"metrics",
")",
"->",
"TrainingInfo",
":",
"if",
"self",
".",
"model_config",
".",
"continue_training",
":",
"start_epoch",
"=",
"self",
".",
"storage",
".",
"last_epoch_idx",
"("... | Possibly resume training from a saved state from the storage | [
"Possibly",
"resume",
"training",
"from",
"a",
"saved",
"state",
"from",
"the",
"storage"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L118-L139 |
237,524 | MillionIntegrals/vel | vel/rl/commands/rl_train_command.py | RlTrainCommand._openai_logging | def _openai_logging(self, epoch_result):
""" Use OpenAI logging facilities for the same type of logging """
for key in sorted(epoch_result.keys()):
if key == 'fps':
# Not super elegant, but I like nicer display of FPS
openai_logger.record_tabular(key, int(epoc... | python | def _openai_logging(self, epoch_result):
""" Use OpenAI logging facilities for the same type of logging """
for key in sorted(epoch_result.keys()):
if key == 'fps':
# Not super elegant, but I like nicer display of FPS
openai_logger.record_tabular(key, int(epoc... | [
"def",
"_openai_logging",
"(",
"self",
",",
"epoch_result",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"epoch_result",
".",
"keys",
"(",
")",
")",
":",
"if",
"key",
"==",
"'fps'",
":",
"# Not super elegant, but I like nicer display of FPS",
"openai_logger",
".... | Use OpenAI logging facilities for the same type of logging | [
"Use",
"OpenAI",
"logging",
"facilities",
"for",
"the",
"same",
"type",
"of",
"logging"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L141-L150 |
237,525 | MillionIntegrals/vel | vel/util/module_util.py | module_broadcast | def module_broadcast(m, broadcast_fn, *args, **kwargs):
""" Call given function in all submodules with given parameters """
apply_leaf(m, lambda x: module_apply_broadcast(x, broadcast_fn, args, kwargs)) | python | def module_broadcast(m, broadcast_fn, *args, **kwargs):
""" Call given function in all submodules with given parameters """
apply_leaf(m, lambda x: module_apply_broadcast(x, broadcast_fn, args, kwargs)) | [
"def",
"module_broadcast",
"(",
"m",
",",
"broadcast_fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"apply_leaf",
"(",
"m",
",",
"lambda",
"x",
":",
"module_apply_broadcast",
"(",
"x",
",",
"broadcast_fn",
",",
"args",
",",
"kwargs",
")",
")... | Call given function in all submodules with given parameters | [
"Call",
"given",
"function",
"in",
"all",
"submodules",
"with",
"given",
"parameters"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/module_util.py#L34-L36 |
237,526 | MillionIntegrals/vel | vel/commands/phase_train_command.py | PhaseTrainCommand._select_phase_left_bound | def _select_phase_left_bound(self, epoch_number):
"""
Return number of current phase.
Return index of first phase not done after all up to epoch_number were done.
"""
idx = bisect.bisect_left(self.ladder, epoch_number)
if idx >= len(self.ladder):
return len(s... | python | def _select_phase_left_bound(self, epoch_number):
"""
Return number of current phase.
Return index of first phase not done after all up to epoch_number were done.
"""
idx = bisect.bisect_left(self.ladder, epoch_number)
if idx >= len(self.ladder):
return len(s... | [
"def",
"_select_phase_left_bound",
"(",
"self",
",",
"epoch_number",
")",
":",
"idx",
"=",
"bisect",
".",
"bisect_left",
"(",
"self",
".",
"ladder",
",",
"epoch_number",
")",
"if",
"idx",
">=",
"len",
"(",
"self",
".",
"ladder",
")",
":",
"return",
"len"... | Return number of current phase.
Return index of first phase not done after all up to epoch_number were done. | [
"Return",
"number",
"of",
"current",
"phase",
".",
"Return",
"index",
"of",
"first",
"phase",
"not",
"done",
"after",
"all",
"up",
"to",
"epoch_number",
"were",
"done",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/phase_train_command.py#L29-L41 |
237,527 | MillionIntegrals/vel | vel/rl/env/classic_atari.py | wrapped_env_maker | def wrapped_env_maker(environment_id, seed, serial_id, disable_reward_clipping=False, disable_episodic_life=False,
monitor=False, allow_early_resets=False, scale_float_frames=False,
max_episode_frames=10000, frame_stack=None):
""" Wrap atari environment so that it's nicer... | python | def wrapped_env_maker(environment_id, seed, serial_id, disable_reward_clipping=False, disable_episodic_life=False,
monitor=False, allow_early_resets=False, scale_float_frames=False,
max_episode_frames=10000, frame_stack=None):
""" Wrap atari environment so that it's nicer... | [
"def",
"wrapped_env_maker",
"(",
"environment_id",
",",
"seed",
",",
"serial_id",
",",
"disable_reward_clipping",
"=",
"False",
",",
"disable_episodic_life",
"=",
"False",
",",
"monitor",
"=",
"False",
",",
"allow_early_resets",
"=",
"False",
",",
"scale_float_frame... | Wrap atari environment so that it's nicer to learn RL algorithms | [
"Wrap",
"atari",
"environment",
"so",
"that",
"it",
"s",
"nicer",
"to",
"learn",
"RL",
"algorithms"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_atari.py#L55-L98 |
237,528 | MillionIntegrals/vel | vel/rl/env/classic_atari.py | ClassicAtariEnv.instantiate | def instantiate(self, seed=0, serial_id=0, preset='default', extra_args=None) -> gym.Env:
""" Make a single environment compatible with the experiments """
settings = self.get_preset(preset)
return wrapped_env_maker(self.envname, seed, serial_id, **settings) | python | def instantiate(self, seed=0, serial_id=0, preset='default', extra_args=None) -> gym.Env:
""" Make a single environment compatible with the experiments """
settings = self.get_preset(preset)
return wrapped_env_maker(self.envname, seed, serial_id, **settings) | [
"def",
"instantiate",
"(",
"self",
",",
"seed",
"=",
"0",
",",
"serial_id",
"=",
"0",
",",
"preset",
"=",
"'default'",
",",
"extra_args",
"=",
"None",
")",
"->",
"gym",
".",
"Env",
":",
"settings",
"=",
"self",
".",
"get_preset",
"(",
"preset",
")",
... | Make a single environment compatible with the experiments | [
"Make",
"a",
"single",
"environment",
"compatible",
"with",
"the",
"experiments"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_atari.py#L115-L118 |
237,529 | MillionIntegrals/vel | vel/util/visdom.py | visdom_send_metrics | def visdom_send_metrics(vis, metrics, update='replace'):
""" Send set of metrics to visdom """
visited = {}
sorted_metrics = sorted(metrics.columns, key=_column_original_name)
for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name):
metric_list = list(metric_li... | python | def visdom_send_metrics(vis, metrics, update='replace'):
""" Send set of metrics to visdom """
visited = {}
sorted_metrics = sorted(metrics.columns, key=_column_original_name)
for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name):
metric_list = list(metric_li... | [
"def",
"visdom_send_metrics",
"(",
"vis",
",",
"metrics",
",",
"update",
"=",
"'replace'",
")",
":",
"visited",
"=",
"{",
"}",
"sorted_metrics",
"=",
"sorted",
"(",
"metrics",
".",
"columns",
",",
"key",
"=",
"_column_original_name",
")",
"for",
"metric_base... | Send set of metrics to visdom | [
"Send",
"set",
"of",
"metrics",
"to",
"visdom"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/visdom.py#L27-L71 |
237,530 | MillionIntegrals/vel | vel/api/train_phase.py | TrainPhase.restore | def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict):
"""
Restore learning from intermediate state.
"""
pass | python | def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict):
"""
Restore learning from intermediate state.
"""
pass | [
"def",
"restore",
"(",
"self",
",",
"training_info",
":",
"TrainingInfo",
",",
"local_batch_idx",
":",
"int",
",",
"model",
":",
"Model",
",",
"hidden_state",
":",
"dict",
")",
":",
"pass"
] | Restore learning from intermediate state. | [
"Restore",
"learning",
"from",
"intermediate",
"state",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/train_phase.py#L18-L22 |
237,531 | MillionIntegrals/vel | vel/rl/buffers/backend/prioritized_vec_buffer_backend.py | PrioritizedCircularVecEnvBufferBackend.update_priority | def update_priority(self, tree_idx_list, priority_list):
""" Update priorities of the elements in the tree """
for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees):
segment_tree.update(tree_idx, priority) | python | def update_priority(self, tree_idx_list, priority_list):
""" Update priorities of the elements in the tree """
for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees):
segment_tree.update(tree_idx, priority) | [
"def",
"update_priority",
"(",
"self",
",",
"tree_idx_list",
",",
"priority_list",
")",
":",
"for",
"tree_idx",
",",
"priority",
",",
"segment_tree",
"in",
"zip",
"(",
"tree_idx_list",
",",
"priority_list",
",",
"self",
".",
"segment_trees",
")",
":",
"segment... | Update priorities of the elements in the tree | [
"Update",
"priorities",
"of",
"the",
"elements",
"in",
"the",
"tree"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/prioritized_vec_buffer_backend.py#L72-L75 |
237,532 | MillionIntegrals/vel | vel/rl/buffers/backend/prioritized_vec_buffer_backend.py | PrioritizedCircularVecEnvBufferBackend._sample_batch_prioritized | def _sample_batch_prioritized(self, segment_tree, batch_size, history, forward_steps=1):
""" Return indexes of the next sample in from prioritized distribution """
p_total = segment_tree.total()
segment = p_total / batch_size
# Get batch of valid samples
batch = [
se... | python | def _sample_batch_prioritized(self, segment_tree, batch_size, history, forward_steps=1):
""" Return indexes of the next sample in from prioritized distribution """
p_total = segment_tree.total()
segment = p_total / batch_size
# Get batch of valid samples
batch = [
se... | [
"def",
"_sample_batch_prioritized",
"(",
"self",
",",
"segment_tree",
",",
"batch_size",
",",
"history",
",",
"forward_steps",
"=",
"1",
")",
":",
"p_total",
"=",
"segment_tree",
".",
"total",
"(",
")",
"segment",
"=",
"p_total",
"/",
"batch_size",
"# Get batc... | Return indexes of the next sample in from prioritized distribution | [
"Return",
"indexes",
"of",
"the",
"next",
"sample",
"in",
"from",
"prioritized",
"distribution"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/prioritized_vec_buffer_backend.py#L87-L99 |
237,533 | MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | take_along_axis | def take_along_axis(large_array, indexes):
""" Take along axis """
# Reshape indexes into the right shape
if len(large_array.shape) > len(indexes.shape):
indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.shape) - len(indexes.shape))))
return np.take_along_axis(large_array, ... | python | def take_along_axis(large_array, indexes):
""" Take along axis """
# Reshape indexes into the right shape
if len(large_array.shape) > len(indexes.shape):
indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.shape) - len(indexes.shape))))
return np.take_along_axis(large_array, ... | [
"def",
"take_along_axis",
"(",
"large_array",
",",
"indexes",
")",
":",
"# Reshape indexes into the right shape",
"if",
"len",
"(",
"large_array",
".",
"shape",
")",
">",
"len",
"(",
"indexes",
".",
"shape",
")",
":",
"indexes",
"=",
"indexes",
".",
"reshape",... | Take along axis | [
"Take",
"along",
"axis"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L7-L13 |
237,534 | MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | CircularVecEnvBufferBackend.get_transition | def get_transition(self, frame_idx, env_idx):
""" Single transition with given index """
past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx)
data_dict = {
'observations': past_frame,
'observations_next': future_frame,
'actions': self.act... | python | def get_transition(self, frame_idx, env_idx):
""" Single transition with given index """
past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx)
data_dict = {
'observations': past_frame,
'observations_next': future_frame,
'actions': self.act... | [
"def",
"get_transition",
"(",
"self",
",",
"frame_idx",
",",
"env_idx",
")",
":",
"past_frame",
",",
"future_frame",
"=",
"self",
".",
"get_frame_with_future",
"(",
"frame_idx",
",",
"env_idx",
")",
"data_dict",
"=",
"{",
"'observations'",
":",
"past_frame",
"... | Single transition with given index | [
"Single",
"transition",
"with",
"given",
"index"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L190-L205 |
237,535 | MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | CircularVecEnvBufferBackend.get_transitions_forward_steps | def get_transitions_forward_steps(self, indexes, forward_steps, discount_factor):
"""
Get dictionary of a transition data - where the target of a transition is
n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor,
and the process stops wh... | python | def get_transitions_forward_steps(self, indexes, forward_steps, discount_factor):
"""
Get dictionary of a transition data - where the target of a transition is
n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor,
and the process stops wh... | [
"def",
"get_transitions_forward_steps",
"(",
"self",
",",
"indexes",
",",
"forward_steps",
",",
"discount_factor",
")",
":",
"frame_batch_shape",
"=",
"(",
"[",
"indexes",
".",
"shape",
"[",
"0",
"]",
",",
"indexes",
".",
"shape",
"[",
"1",
"]",
"]",
"+",
... | Get dictionary of a transition data - where the target of a transition is
n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor,
and the process stops when trajectory is done. | [
"Get",
"dictionary",
"of",
"a",
"transition",
"data",
"-",
"where",
"the",
"target",
"of",
"a",
"transition",
"is",
"n",
"steps",
"forward",
"along",
"the",
"trajectory",
".",
"Rewards",
"are",
"properly",
"aggregated",
"according",
"to",
"the",
"discount",
... | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L244-L288 |
237,536 | MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | CircularVecEnvBufferBackend.sample_batch_trajectories | def sample_batch_trajectories(self, rollout_length):
""" Return indexes of next random rollout """
results = []
for i in range(self.num_envs):
results.append(self.sample_rollout_single_env(rollout_length))
return np.stack(results, axis=-1) | python | def sample_batch_trajectories(self, rollout_length):
""" Return indexes of next random rollout """
results = []
for i in range(self.num_envs):
results.append(self.sample_rollout_single_env(rollout_length))
return np.stack(results, axis=-1) | [
"def",
"sample_batch_trajectories",
"(",
"self",
",",
"rollout_length",
")",
":",
"results",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_envs",
")",
":",
"results",
".",
"append",
"(",
"self",
".",
"sample_rollout_single_env",
"(",
"ro... | Return indexes of next random rollout | [
"Return",
"indexes",
"of",
"next",
"random",
"rollout"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L310-L317 |
237,537 | MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | CircularVecEnvBufferBackend.sample_frame_single_env | def sample_frame_single_env(self, batch_size, forward_steps=1):
""" Return an in index of a random set of frames from a buffer, that have enough history and future """
# Whole idea of this function is to make sure that sample we take is far away from the point which we are
# currently writing to... | python | def sample_frame_single_env(self, batch_size, forward_steps=1):
""" Return an in index of a random set of frames from a buffer, that have enough history and future """
# Whole idea of this function is to make sure that sample we take is far away from the point which we are
# currently writing to... | [
"def",
"sample_frame_single_env",
"(",
"self",
",",
"batch_size",
",",
"forward_steps",
"=",
"1",
")",
":",
"# Whole idea of this function is to make sure that sample we take is far away from the point which we are",
"# currently writing to the buffer, which is 'discontinuous'",
"if",
... | Return an in index of a random set of frames from a buffer, that have enough history and future | [
"Return",
"an",
"in",
"index",
"of",
"a",
"random",
"set",
"of",
"frames",
"from",
"a",
"buffer",
"that",
"have",
"enough",
"history",
"and",
"future"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L346-L367 |
237,538 | MillionIntegrals/vel | vel/rl/commands/record_movie_command.py | RecordMovieCommand.record_take | def record_take(self, model, env_instance, device, take_number):
""" Record a single movie and store it on hard drive """
frames = []
observation = env_instance.reset()
if model.is_recurrent:
hidden_state = model.zero_state(1).to(device)
frames.append(env_instance.... | python | def record_take(self, model, env_instance, device, take_number):
""" Record a single movie and store it on hard drive """
frames = []
observation = env_instance.reset()
if model.is_recurrent:
hidden_state = model.zero_state(1).to(device)
frames.append(env_instance.... | [
"def",
"record_take",
"(",
"self",
",",
"model",
",",
"env_instance",
",",
"device",
",",
"take_number",
")",
":",
"frames",
"=",
"[",
"]",
"observation",
"=",
"env_instance",
".",
"reset",
"(",
")",
"if",
"model",
".",
"is_recurrent",
":",
"hidden_state",... | Record a single movie and store it on hard drive | [
"Record",
"a",
"single",
"movie",
"and",
"store",
"it",
"on",
"hard",
"drive"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/record_movie_command.py#L47-L91 |
237,539 | MillionIntegrals/vel | vel/rl/modules/noise/ou_noise.py | OuNoise.reset_training_state | def reset_training_state(self, dones, batch_info):
""" A hook for a model to react when during training episode is finished """
for idx, done in enumerate(dones):
if done > 0.5:
self.processes[idx].reset() | python | def reset_training_state(self, dones, batch_info):
""" A hook for a model to react when during training episode is finished """
for idx, done in enumerate(dones):
if done > 0.5:
self.processes[idx].reset() | [
"def",
"reset_training_state",
"(",
"self",
",",
"dones",
",",
"batch_info",
")",
":",
"for",
"idx",
",",
"done",
"in",
"enumerate",
"(",
"dones",
")",
":",
"if",
"done",
">",
"0.5",
":",
"self",
".",
"processes",
"[",
"idx",
"]",
".",
"reset",
"(",
... | A hook for a model to react when during training episode is finished | [
"A",
"hook",
"for",
"a",
"model",
"to",
"react",
"when",
"during",
"training",
"episode",
"is",
"finished"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/noise/ou_noise.py#L22-L26 |
237,540 | MillionIntegrals/vel | vel/rl/modules/noise/ou_noise.py | OuNoise.forward | def forward(self, actions, batch_info):
""" Return model step after applying noise """
while len(self.processes) < actions.shape[0]:
len_action_space = self.action_space.shape[-1]
self.processes.append(
OrnsteinUhlenbeckNoiseProcess(
np.zeros(... | python | def forward(self, actions, batch_info):
""" Return model step after applying noise """
while len(self.processes) < actions.shape[0]:
len_action_space = self.action_space.shape[-1]
self.processes.append(
OrnsteinUhlenbeckNoiseProcess(
np.zeros(... | [
"def",
"forward",
"(",
"self",
",",
"actions",
",",
"batch_info",
")",
":",
"while",
"len",
"(",
"self",
".",
"processes",
")",
"<",
"actions",
".",
"shape",
"[",
"0",
"]",
":",
"len_action_space",
"=",
"self",
".",
"action_space",
".",
"shape",
"[",
... | Return model step after applying noise | [
"Return",
"model",
"step",
"after",
"applying",
"noise"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/noise/ou_noise.py#L28-L41 |
237,541 | MillionIntegrals/vel | vel/util/intepolate.py | interpolate_logscale | def interpolate_logscale(start, end, steps):
""" Interpolate series between start and end in given number of steps - logscale interpolation """
if start <= 0.0:
warnings.warn("Start of logscale interpolation must be positive!")
start = 1e-5
return np.logspace(np.log10(float(start)), np.log1... | python | def interpolate_logscale(start, end, steps):
""" Interpolate series between start and end in given number of steps - logscale interpolation """
if start <= 0.0:
warnings.warn("Start of logscale interpolation must be positive!")
start = 1e-5
return np.logspace(np.log10(float(start)), np.log1... | [
"def",
"interpolate_logscale",
"(",
"start",
",",
"end",
",",
"steps",
")",
":",
"if",
"start",
"<=",
"0.0",
":",
"warnings",
".",
"warn",
"(",
"\"Start of logscale interpolation must be positive!\"",
")",
"start",
"=",
"1e-5",
"return",
"np",
".",
"logspace",
... | Interpolate series between start and end in given number of steps - logscale interpolation | [
"Interpolate",
"series",
"between",
"start",
"and",
"end",
"in",
"given",
"number",
"of",
"steps",
"-",
"logscale",
"interpolation"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L10-L16 |
237,542 | MillionIntegrals/vel | vel/util/intepolate.py | interpolate_series | def interpolate_series(start, end, steps, how='linear'):
""" Interpolate series between start and end in given number of steps """
return INTERP_DICT[how](start, end, steps) | python | def interpolate_series(start, end, steps, how='linear'):
""" Interpolate series between start and end in given number of steps """
return INTERP_DICT[how](start, end, steps) | [
"def",
"interpolate_series",
"(",
"start",
",",
"end",
",",
"steps",
",",
"how",
"=",
"'linear'",
")",
":",
"return",
"INTERP_DICT",
"[",
"how",
"]",
"(",
"start",
",",
"end",
",",
"steps",
")"
] | Interpolate series between start and end in given number of steps | [
"Interpolate",
"series",
"between",
"start",
"and",
"end",
"in",
"given",
"number",
"of",
"steps"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L48-L50 |
237,543 | MillionIntegrals/vel | vel/util/intepolate.py | interpolate_single | def interpolate_single(start, end, coefficient, how='linear'):
""" Interpolate single value between start and end in given number of steps """
return INTERP_SINGLE_DICT[how](start, end, coefficient) | python | def interpolate_single(start, end, coefficient, how='linear'):
""" Interpolate single value between start and end in given number of steps """
return INTERP_SINGLE_DICT[how](start, end, coefficient) | [
"def",
"interpolate_single",
"(",
"start",
",",
"end",
",",
"coefficient",
",",
"how",
"=",
"'linear'",
")",
":",
"return",
"INTERP_SINGLE_DICT",
"[",
"how",
"]",
"(",
"start",
",",
"end",
",",
"coefficient",
")"
] | Interpolate single value between start and end in given number of steps | [
"Interpolate",
"single",
"value",
"between",
"start",
"and",
"end",
"in",
"given",
"number",
"of",
"steps"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L53-L55 |
237,544 | MillionIntegrals/vel | vel/commands/summary_command.py | ModelSummary.run | def run(self, *args):
""" Print model summary """
if self.source is None:
self.model.summary()
else:
x_data, y_data = next(iter(self.source.train_loader()))
self.model.summary(input_size=x_data.shape[1:]) | python | def run(self, *args):
""" Print model summary """
if self.source is None:
self.model.summary()
else:
x_data, y_data = next(iter(self.source.train_loader()))
self.model.summary(input_size=x_data.shape[1:]) | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"source",
"is",
"None",
":",
"self",
".",
"model",
".",
"summary",
"(",
")",
"else",
":",
"x_data",
",",
"y_data",
"=",
"next",
"(",
"iter",
"(",
"self",
".",
"source",
"... | Print model summary | [
"Print",
"model",
"summary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/summary_command.py#L10-L16 |
237,545 | MillionIntegrals/vel | vel/rl/reinforcers/on_policy_iteration_reinforcer.py | OnPolicyIterationReinforcer.initialize_training | def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare models for training """
if model_state is not None:
self.model.load_state_dict(model_state)
else:
self.model.reset_weights()
self.algo.initialize(
... | python | def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare models for training """
if model_state is not None:
self.model.load_state_dict(model_state)
else:
self.model.reset_weights()
self.algo.initialize(
... | [
"def",
"initialize_training",
"(",
"self",
",",
"training_info",
":",
"TrainingInfo",
",",
"model_state",
"=",
"None",
",",
"hidden_state",
"=",
"None",
")",
":",
"if",
"model_state",
"is",
"not",
"None",
":",
"self",
".",
"model",
".",
"load_state_dict",
"(... | Prepare models for training | [
"Prepare",
"models",
"for",
"training"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/on_policy_iteration_reinforcer.py#L63-L72 |
237,546 | MillionIntegrals/vel | vel/util/network.py | convolutional_layer_series | def convolutional_layer_series(initial_size, layer_sequence):
""" Execute a series of convolutional layer transformations to the size number """
size = initial_size
for filter_size, padding, stride in layer_sequence:
size = convolution_size_equation(size, filter_size, padding, stride)
return s... | python | def convolutional_layer_series(initial_size, layer_sequence):
""" Execute a series of convolutional layer transformations to the size number """
size = initial_size
for filter_size, padding, stride in layer_sequence:
size = convolution_size_equation(size, filter_size, padding, stride)
return s... | [
"def",
"convolutional_layer_series",
"(",
"initial_size",
",",
"layer_sequence",
")",
":",
"size",
"=",
"initial_size",
"for",
"filter_size",
",",
"padding",
",",
"stride",
"in",
"layer_sequence",
":",
"size",
"=",
"convolution_size_equation",
"(",
"size",
",",
"f... | Execute a series of convolutional layer transformations to the size number | [
"Execute",
"a",
"series",
"of",
"convolutional",
"layer",
"transformations",
"to",
"the",
"size",
"number"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/network.py#L34-L41 |
237,547 | MillionIntegrals/vel | vel/api/model.py | Model.train | def train(self, mode=True):
r"""
Sets the module in training mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
... | python | def train(self, mode=True):
r"""
Sets the module in training mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
... | [
"def",
"train",
"(",
"self",
",",
"mode",
"=",
"True",
")",
":",
"super",
"(",
")",
".",
"train",
"(",
"mode",
")",
"if",
"mode",
":",
"mu",
".",
"apply_leaf",
"(",
"self",
",",
"mu",
".",
"set_train_mode",
")",
"return",
"self"
] | r"""
Sets the module in training mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
etc.
Returns:
... | [
"r",
"Sets",
"the",
"module",
"in",
"training",
"mode",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L18-L35 |
237,548 | MillionIntegrals/vel | vel/api/model.py | Model.summary | def summary(self, input_size=None, hashsummary=False):
""" Print a model summary """
if input_size is None:
print(self)
print("-" * 120)
number = sum(p.numel() for p in self.model.parameters())
print("Number of model parameters: {:,}".format(number))
... | python | def summary(self, input_size=None, hashsummary=False):
""" Print a model summary """
if input_size is None:
print(self)
print("-" * 120)
number = sum(p.numel() for p in self.model.parameters())
print("Number of model parameters: {:,}".format(number))
... | [
"def",
"summary",
"(",
"self",
",",
"input_size",
"=",
"None",
",",
"hashsummary",
"=",
"False",
")",
":",
"if",
"input_size",
"is",
"None",
":",
"print",
"(",
"self",
")",
"print",
"(",
"\"-\"",
"*",
"120",
")",
"number",
"=",
"sum",
"(",
"p",
"."... | Print a model summary | [
"Print",
"a",
"model",
"summary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L37-L51 |
237,549 | MillionIntegrals/vel | vel/api/model.py | Model.hashsummary | def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()).hexdigest() for x in child.parameters())
r... | python | def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()).hexdigest() for x in child.parameters())
r... | [
"def",
"hashsummary",
"(",
"self",
")",
":",
"children",
"=",
"list",
"(",
"self",
".",
"children",
"(",
")",
")",
"result",
"=",
"[",
"]",
"for",
"child",
"in",
"children",
":",
"result",
".",
"extend",
"(",
"hashlib",
".",
"sha256",
"(",
"x",
"."... | Print a model summary - checksums of each layer parameters | [
"Print",
"a",
"model",
"summary",
"-",
"checksums",
"of",
"each",
"layer",
"parameters"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L53-L62 |
237,550 | MillionIntegrals/vel | vel/api/model.py | RnnLinearBackboneModel.zero_state | def zero_state(self, batch_size):
""" Initial state of the network """
return torch.zeros(batch_size, self.state_dim, dtype=torch.float32) | python | def zero_state(self, batch_size):
""" Initial state of the network """
return torch.zeros(batch_size, self.state_dim, dtype=torch.float32) | [
"def",
"zero_state",
"(",
"self",
",",
"batch_size",
")",
":",
"return",
"torch",
".",
"zeros",
"(",
"batch_size",
",",
"self",
".",
"state_dim",
",",
"dtype",
"=",
"torch",
".",
"float32",
")"
] | Initial state of the network | [
"Initial",
"state",
"of",
"the",
"network"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L121-L123 |
237,551 | MillionIntegrals/vel | vel/api/model.py | SupervisedModel.loss | def loss(self, x_data, y_true):
""" Forward propagate network and return a value of loss function """
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred) | python | def loss(self, x_data, y_true):
""" Forward propagate network and return a value of loss function """
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred) | [
"def",
"loss",
"(",
"self",
",",
"x_data",
",",
"y_true",
")",
":",
"y_pred",
"=",
"self",
"(",
"x_data",
")",
"return",
"y_pred",
",",
"self",
".",
"loss_value",
"(",
"x_data",
",",
"y_true",
",",
"y_pred",
")"
] | Forward propagate network and return a value of loss function | [
"Forward",
"propagate",
"network",
"and",
"return",
"a",
"value",
"of",
"loss",
"function"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L139-L142 |
237,552 | MillionIntegrals/vel | vel/models/vision/cifar_resnet_v2.py | ResNetV2.metrics | def metrics(self):
""" Set of metrics for this model """
from vel.metrics.loss_metric import Loss
from vel.metrics.accuracy import Accuracy
return [Loss(), Accuracy()] | python | def metrics(self):
""" Set of metrics for this model """
from vel.metrics.loss_metric import Loss
from vel.metrics.accuracy import Accuracy
return [Loss(), Accuracy()] | [
"def",
"metrics",
"(",
"self",
")",
":",
"from",
"vel",
".",
"metrics",
".",
"loss_metric",
"import",
"Loss",
"from",
"vel",
".",
"metrics",
".",
"accuracy",
"import",
"Accuracy",
"return",
"[",
"Loss",
"(",
")",
",",
"Accuracy",
"(",
")",
"]"
] | Set of metrics for this model | [
"Set",
"of",
"metrics",
"for",
"this",
"model"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/vision/cifar_resnet_v2.py#L77-L81 |
237,553 | MillionIntegrals/vel | vel/util/tensor_util.py | one_hot_encoding | def one_hot_encoding(input_tensor, num_labels):
""" One-hot encode labels from input """
xview = input_tensor.view(-1, 1).to(torch.long)
onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)
onehot.scatter_(1, xview, 1)
return onehot.view(list(input_tensor.s... | python | def one_hot_encoding(input_tensor, num_labels):
""" One-hot encode labels from input """
xview = input_tensor.view(-1, 1).to(torch.long)
onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)
onehot.scatter_(1, xview, 1)
return onehot.view(list(input_tensor.s... | [
"def",
"one_hot_encoding",
"(",
"input_tensor",
",",
"num_labels",
")",
":",
"xview",
"=",
"input_tensor",
".",
"view",
"(",
"-",
"1",
",",
"1",
")",
".",
"to",
"(",
"torch",
".",
"long",
")",
"onehot",
"=",
"torch",
".",
"zeros",
"(",
"xview",
".",
... | One-hot encode labels from input | [
"One",
"-",
"hot",
"encode",
"labels",
"from",
"input"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/tensor_util.py#L4-L10 |
237,554 | MillionIntegrals/vel | vel/util/tensor_util.py | merge_first_two_dims | def merge_first_two_dims(tensor):
""" Reshape tensor to merge first two dimensions """
shape = tensor.shape
batch_size = shape[0] * shape[1]
new_shape = tuple([batch_size] + list(shape[2:]))
return tensor.view(new_shape) | python | def merge_first_two_dims(tensor):
""" Reshape tensor to merge first two dimensions """
shape = tensor.shape
batch_size = shape[0] * shape[1]
new_shape = tuple([batch_size] + list(shape[2:]))
return tensor.view(new_shape) | [
"def",
"merge_first_two_dims",
"(",
"tensor",
")",
":",
"shape",
"=",
"tensor",
".",
"shape",
"batch_size",
"=",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"1",
"]",
"new_shape",
"=",
"tuple",
"(",
"[",
"batch_size",
"]",
"+",
"list",
"(",
"shape",
"... | Reshape tensor to merge first two dimensions | [
"Reshape",
"tensor",
"to",
"merge",
"first",
"two",
"dimensions"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/tensor_util.py#L13-L18 |
237,555 | MillionIntegrals/vel | vel/rl/vecenv/dummy.py | DummyVecEnvWrapper.instantiate | def instantiate(self, parallel_envs, seed=0, preset='default') -> VecEnv:
""" Create vectorized environments """
envs = DummyVecEnv([self._creation_function(i, seed, preset) for i in range(parallel_envs)])
if self.frame_history is not None:
envs = VecFrameStack(envs, self.frame_hist... | python | def instantiate(self, parallel_envs, seed=0, preset='default') -> VecEnv:
""" Create vectorized environments """
envs = DummyVecEnv([self._creation_function(i, seed, preset) for i in range(parallel_envs)])
if self.frame_history is not None:
envs = VecFrameStack(envs, self.frame_hist... | [
"def",
"instantiate",
"(",
"self",
",",
"parallel_envs",
",",
"seed",
"=",
"0",
",",
"preset",
"=",
"'default'",
")",
"->",
"VecEnv",
":",
"envs",
"=",
"DummyVecEnv",
"(",
"[",
"self",
".",
"_creation_function",
"(",
"i",
",",
"seed",
",",
"preset",
")... | Create vectorized environments | [
"Create",
"vectorized",
"environments"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/vecenv/dummy.py#L16-L23 |
237,556 | MillionIntegrals/vel | vel/rl/vecenv/dummy.py | DummyVecEnvWrapper.instantiate_single | def instantiate_single(self, seed=0, preset='default'):
""" Create a new Env instance - single """
env = self.env.instantiate(seed=seed, serial_id=0, preset=preset)
if self.frame_history is not None:
env = FrameStack(env, self.frame_history)
return env | python | def instantiate_single(self, seed=0, preset='default'):
""" Create a new Env instance - single """
env = self.env.instantiate(seed=seed, serial_id=0, preset=preset)
if self.frame_history is not None:
env = FrameStack(env, self.frame_history)
return env | [
"def",
"instantiate_single",
"(",
"self",
",",
"seed",
"=",
"0",
",",
"preset",
"=",
"'default'",
")",
":",
"env",
"=",
"self",
".",
"env",
".",
"instantiate",
"(",
"seed",
"=",
"seed",
",",
"serial_id",
"=",
"0",
",",
"preset",
"=",
"preset",
")",
... | Create a new Env instance - single | [
"Create",
"a",
"new",
"Env",
"instance",
"-",
"single"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/vecenv/dummy.py#L25-L32 |
237,557 | MillionIntegrals/vel | vel/rl/vecenv/dummy.py | DummyVecEnvWrapper._creation_function | def _creation_function(self, idx, seed, preset):
""" Helper function to create a proper closure around supplied values """
return lambda: self.env.instantiate(seed=seed, serial_id=idx, preset=preset) | python | def _creation_function(self, idx, seed, preset):
""" Helper function to create a proper closure around supplied values """
return lambda: self.env.instantiate(seed=seed, serial_id=idx, preset=preset) | [
"def",
"_creation_function",
"(",
"self",
",",
"idx",
",",
"seed",
",",
"preset",
")",
":",
"return",
"lambda",
":",
"self",
".",
"env",
".",
"instantiate",
"(",
"seed",
"=",
"seed",
",",
"serial_id",
"=",
"idx",
",",
"preset",
"=",
"preset",
")"
] | Helper function to create a proper closure around supplied values | [
"Helper",
"function",
"to",
"create",
"a",
"proper",
"closure",
"around",
"supplied",
"values"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/vecenv/dummy.py#L34-L36 |
237,558 | MillionIntegrals/vel | vel/rl/models/stochastic_policy_model_separate.py | StochasticPolicyModelSeparate.policy | def policy(self, observations):
""" Calculate only action head for given state """
input_data = self.input_block(observations)
policy_base_output = self.policy_backbone(input_data)
policy_params = self.action_head(policy_base_output)
return policy_params | python | def policy(self, observations):
""" Calculate only action head for given state """
input_data = self.input_block(observations)
policy_base_output = self.policy_backbone(input_data)
policy_params = self.action_head(policy_base_output)
return policy_params | [
"def",
"policy",
"(",
"self",
",",
"observations",
")",
":",
"input_data",
"=",
"self",
".",
"input_block",
"(",
"observations",
")",
"policy_base_output",
"=",
"self",
".",
"policy_backbone",
"(",
"input_data",
")",
"policy_params",
"=",
"self",
".",
"action_... | Calculate only action head for given state | [
"Calculate",
"only",
"action",
"head",
"for",
"given",
"state"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/models/stochastic_policy_model_separate.py#L85-L90 |
237,559 | MillionIntegrals/vel | vel/phase/cycle.py | CycleCallback._init_cycle_dict | def _init_cycle_dict(self):
""" Populate a cycle dict """
dict_arr = np.zeros(self.epochs, dtype=int)
length_arr = np.zeros(self.epochs, dtype=int)
start_arr = np.zeros(self.epochs, dtype=int)
c_len = self.cycle_len
idx = 0
for i in range(self.cycles):
... | python | def _init_cycle_dict(self):
""" Populate a cycle dict """
dict_arr = np.zeros(self.epochs, dtype=int)
length_arr = np.zeros(self.epochs, dtype=int)
start_arr = np.zeros(self.epochs, dtype=int)
c_len = self.cycle_len
idx = 0
for i in range(self.cycles):
... | [
"def",
"_init_cycle_dict",
"(",
"self",
")",
":",
"dict_arr",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"epochs",
",",
"dtype",
"=",
"int",
")",
"length_arr",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"epochs",
",",
"dtype",
"=",
"int",
")",
"sta... | Populate a cycle dict | [
"Populate",
"a",
"cycle",
"dict"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/phase/cycle.py#L34-L53 |
237,560 | MillionIntegrals/vel | vel/phase/cycle.py | CycleCallback.on_batch_begin | def on_batch_begin(self, batch_info: BatchInfo):
""" Set proper learning rate """
cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1]
cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1]
numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch... | python | def on_batch_begin(self, batch_info: BatchInfo):
""" Set proper learning rate """
cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1]
cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1]
numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch... | [
"def",
"on_batch_begin",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"cycle_length",
"=",
"self",
".",
"cycle_lengths",
"[",
"batch_info",
".",
"local_epoch_number",
"-",
"1",
"]",
"cycle_start",
"=",
"self",
".",
"cycle_starts",
"[",
"batch_in... | Set proper learning rate | [
"Set",
"proper",
"learning",
"rate"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/phase/cycle.py#L55-L73 |
237,561 | MillionIntegrals/vel | vel/phase/cycle.py | CycleCallback.set_lr | def set_lr(self, lr):
""" Set a learning rate for the optimizer """
if isinstance(lr, list):
for group_lr, param_group in zip(lr, self.optimizer.param_groups):
param_group['lr'] = group_lr
else:
for param_group in self.optimizer.param_groups:
... | python | def set_lr(self, lr):
""" Set a learning rate for the optimizer """
if isinstance(lr, list):
for group_lr, param_group in zip(lr, self.optimizer.param_groups):
param_group['lr'] = group_lr
else:
for param_group in self.optimizer.param_groups:
... | [
"def",
"set_lr",
"(",
"self",
",",
"lr",
")",
":",
"if",
"isinstance",
"(",
"lr",
",",
"list",
")",
":",
"for",
"group_lr",
",",
"param_group",
"in",
"zip",
"(",
"lr",
",",
"self",
".",
"optimizer",
".",
"param_groups",
")",
":",
"param_group",
"[",
... | Set a learning rate for the optimizer | [
"Set",
"a",
"learning",
"rate",
"for",
"the",
"optimizer"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/phase/cycle.py#L75-L82 |
237,562 | MillionIntegrals/vel | vel/internals/parser.py | Variable.parameter_constructor | def parameter_constructor(cls, loader, node):
""" Construct variable instance from yaml node """
value = loader.construct_scalar(node)
if isinstance(value, str):
if '=' in value:
(varname, varvalue) = Parser.parse_equality(value)
return cls(varname, v... | python | def parameter_constructor(cls, loader, node):
""" Construct variable instance from yaml node """
value = loader.construct_scalar(node)
if isinstance(value, str):
if '=' in value:
(varname, varvalue) = Parser.parse_equality(value)
return cls(varname, v... | [
"def",
"parameter_constructor",
"(",
"cls",
",",
"loader",
",",
"node",
")",
":",
"value",
"=",
"loader",
".",
"construct_scalar",
"(",
"node",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"if",
"'='",
"in",
"value",
":",
"(",
"varname"... | Construct variable instance from yaml node | [
"Construct",
"variable",
"instance",
"from",
"yaml",
"node"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/parser.py#L18-L29 |
237,563 | MillionIntegrals/vel | vel/internals/parser.py | Parser.register | def register(cls):
""" Register variable handling in YAML """
if not cls.IS_LOADED:
cls.IS_LOADED = True
yaml.add_constructor('!param', Parameter.parameter_constructor, Loader=yaml.SafeLoader)
yaml.add_constructor('!env', EnvironmentVariable.parameter_constructor, Lo... | python | def register(cls):
""" Register variable handling in YAML """
if not cls.IS_LOADED:
cls.IS_LOADED = True
yaml.add_constructor('!param', Parameter.parameter_constructor, Loader=yaml.SafeLoader)
yaml.add_constructor('!env', EnvironmentVariable.parameter_constructor, Lo... | [
"def",
"register",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"IS_LOADED",
":",
"cls",
".",
"IS_LOADED",
"=",
"True",
"yaml",
".",
"add_constructor",
"(",
"'!param'",
",",
"Parameter",
".",
"parameter_constructor",
",",
"Loader",
"=",
"yaml",
".",
"S... | Register variable handling in YAML | [
"Register",
"variable",
"handling",
"in",
"YAML"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/parser.py#L74-L80 |
237,564 | MillionIntegrals/vel | vel/internals/parser.py | Parser.parse_equality | def parse_equality(cls, equality_string):
""" Parse some simple equality statements """
cls.register()
assert '=' in equality_string, "There must be an '=' sign in the equality"
[left_side, right_side] = equality_string.split('=', 1)
left_side_value = yaml.safe_load(left_side.st... | python | def parse_equality(cls, equality_string):
""" Parse some simple equality statements """
cls.register()
assert '=' in equality_string, "There must be an '=' sign in the equality"
[left_side, right_side] = equality_string.split('=', 1)
left_side_value = yaml.safe_load(left_side.st... | [
"def",
"parse_equality",
"(",
"cls",
",",
"equality_string",
")",
":",
"cls",
".",
"register",
"(",
")",
"assert",
"'='",
"in",
"equality_string",
",",
"\"There must be an '=' sign in the equality\"",
"[",
"left_side",
",",
"right_side",
"]",
"=",
"equality_string",... | Parse some simple equality statements | [
"Parse",
"some",
"simple",
"equality",
"statements"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/parser.py#L89-L100 |
237,565 | MillionIntegrals/vel | vel/storage/backend/mongodb.py | MongoDbBackend.clean | def clean(self, initial_epoch):
""" Remove entries from database that would get overwritten """
self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}}) | python | def clean(self, initial_epoch):
""" Remove entries from database that would get overwritten """
self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}}) | [
"def",
"clean",
"(",
"self",
",",
"initial_epoch",
")",
":",
"self",
".",
"db",
".",
"metrics",
".",
"delete_many",
"(",
"{",
"'run_name'",
":",
"self",
".",
"model_config",
".",
"run_name",
",",
"'epoch_idx'",
":",
"{",
"'$gt'",
":",
"initial_epoch",
"}... | Remove entries from database that would get overwritten | [
"Remove",
"entries",
"from",
"database",
"that",
"would",
"get",
"overwritten"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/backend/mongodb.py#L13-L15 |
237,566 | MillionIntegrals/vel | vel/storage/backend/mongodb.py | MongoDbBackend.store_config | def store_config(self, configuration):
""" Store model parameters in the database """
run_name = self.model_config.run_name
self.db.configs.delete_many({'run_name': self.model_config.run_name})
configuration = configuration.copy()
configuration['run_name'] = run_name
s... | python | def store_config(self, configuration):
""" Store model parameters in the database """
run_name = self.model_config.run_name
self.db.configs.delete_many({'run_name': self.model_config.run_name})
configuration = configuration.copy()
configuration['run_name'] = run_name
s... | [
"def",
"store_config",
"(",
"self",
",",
"configuration",
")",
":",
"run_name",
"=",
"self",
".",
"model_config",
".",
"run_name",
"self",
".",
"db",
".",
"configs",
".",
"delete_many",
"(",
"{",
"'run_name'",
":",
"self",
".",
"model_config",
".",
"run_na... | Store model parameters in the database | [
"Store",
"model",
"parameters",
"in",
"the",
"database"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/backend/mongodb.py#L17-L26 |
237,567 | MillionIntegrals/vel | vel/storage/backend/mongodb.py | MongoDbBackend.get_frame | def get_frame(self):
""" Get a dataframe of metrics from this storage """
metric_items = list(self.db.metrics.find({'run_name': self.model_config.run_name}).sort('epoch_idx'))
if len(metric_items) == 0:
return pd.DataFrame(columns=['run_name'])
else:
return pd.Dat... | python | def get_frame(self):
""" Get a dataframe of metrics from this storage """
metric_items = list(self.db.metrics.find({'run_name': self.model_config.run_name}).sort('epoch_idx'))
if len(metric_items) == 0:
return pd.DataFrame(columns=['run_name'])
else:
return pd.Dat... | [
"def",
"get_frame",
"(",
"self",
")",
":",
"metric_items",
"=",
"list",
"(",
"self",
".",
"db",
".",
"metrics",
".",
"find",
"(",
"{",
"'run_name'",
":",
"self",
".",
"model_config",
".",
"run_name",
"}",
")",
".",
"sort",
"(",
"'epoch_idx'",
")",
")... | Get a dataframe of metrics from this storage | [
"Get",
"a",
"dataframe",
"of",
"metrics",
"from",
"this",
"storage"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/backend/mongodb.py#L28-L34 |
237,568 | MillionIntegrals/vel | vel/rl/buffers/prioritized_circular_replay_buffer.py | PrioritizedCircularReplayBuffer._get_transitions | def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0):
""" Return batch of frames for given indexes """
if forward_steps > 1:
transition_arrays = self.backend.get_transitions_forward_steps(indexes, forward_steps, discount_factor)
else... | python | def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0):
""" Return batch of frames for given indexes """
if forward_steps > 1:
transition_arrays = self.backend.get_transitions_forward_steps(indexes, forward_steps, discount_factor)
else... | [
"def",
"_get_transitions",
"(",
"self",
",",
"probs",
",",
"indexes",
",",
"tree_idxs",
",",
"batch_info",
",",
"forward_steps",
"=",
"1",
",",
"discount_factor",
"=",
"1.0",
")",
":",
"if",
"forward_steps",
">",
"1",
":",
"transition_arrays",
"=",
"self",
... | Return batch of frames for given indexes | [
"Return",
"batch",
"of",
"frames",
"for",
"given",
"indexes"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/prioritized_circular_replay_buffer.py#L46-L75 |
237,569 | MillionIntegrals/vel | vel/rl/api/env_roller.py | EnvRollerBase.rollout | def rollout(self, batch_info: BatchInfo, model: Model, number_of_steps: int) -> Rollout:
""" Roll-out the environment and return it """
raise NotImplementedError | python | def rollout(self, batch_info: BatchInfo, model: Model, number_of_steps: int) -> Rollout:
""" Roll-out the environment and return it """
raise NotImplementedError | [
"def",
"rollout",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
",",
"model",
":",
"Model",
",",
"number_of_steps",
":",
"int",
")",
"->",
"Rollout",
":",
"raise",
"NotImplementedError"
] | Roll-out the environment and return it | [
"Roll",
"-",
"out",
"the",
"environment",
"and",
"return",
"it"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/env_roller.py#L17-L19 |
237,570 | MillionIntegrals/vel | vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py | BufferedMixedPolicyIterationReinforcer.train_epoch | def train_epoch(self, epoch_info: EpochInfo, interactive=True):
""" Train model on an epoch of a fixed number of batch updates """
epoch_info.on_epoch_begin()
if interactive:
iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch")
... | python | def train_epoch(self, epoch_info: EpochInfo, interactive=True):
""" Train model on an epoch of a fixed number of batch updates """
epoch_info.on_epoch_begin()
if interactive:
iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch")
... | [
"def",
"train_epoch",
"(",
"self",
",",
"epoch_info",
":",
"EpochInfo",
",",
"interactive",
"=",
"True",
")",
":",
"epoch_info",
".",
"on_epoch_begin",
"(",
")",
"if",
"interactive",
":",
"iterator",
"=",
"tqdm",
".",
"trange",
"(",
"epoch_info",
".",
"bat... | Train model on an epoch of a fixed number of batch updates | [
"Train",
"model",
"on",
"an",
"epoch",
"of",
"a",
"fixed",
"number",
"of",
"batch",
"updates"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py#L75-L92 |
237,571 | MillionIntegrals/vel | vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py | BufferedMixedPolicyIterationReinforcer.train_batch | def train_batch(self, batch_info: BatchInfo):
""" Single, most atomic 'step' of learning this reinforcer can perform """
batch_info['sub_batch_data'] = []
self.on_policy_train_batch(batch_info)
if self.settings.experience_replay > 0 and self.env_roller.is_ready_for_sampling():
... | python | def train_batch(self, batch_info: BatchInfo):
""" Single, most atomic 'step' of learning this reinforcer can perform """
batch_info['sub_batch_data'] = []
self.on_policy_train_batch(batch_info)
if self.settings.experience_replay > 0 and self.env_roller.is_ready_for_sampling():
... | [
"def",
"train_batch",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"batch_info",
"[",
"'sub_batch_data'",
"]",
"=",
"[",
"]",
"self",
".",
"on_policy_train_batch",
"(",
"batch_info",
")",
"if",
"self",
".",
"settings",
".",
"experience_replay",
... | Single, most atomic 'step' of learning this reinforcer can perform | [
"Single",
"most",
"atomic",
"step",
"of",
"learning",
"this",
"reinforcer",
"can",
"perform"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py#L94-L110 |
237,572 | MillionIntegrals/vel | vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py | BufferedMixedPolicyIterationReinforcer.on_policy_train_batch | def on_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'on-policy' training step of evaluating an env and a single backpropagation step """
self.model.train()
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
... | python | def on_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'on-policy' training step of evaluating an env and a single backpropagation step """
self.model.train()
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
... | [
"def",
"on_policy_train_batch",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"self",
".",
"model",
".",
"train",
"(",
")",
"rollout",
"=",
"self",
".",
"env_roller",
".",
"rollout",
"(",
"batch_info",
",",
"self",
".",
"model",
",",
"self"... | Perform an 'on-policy' training step of evaluating an env and a single backpropagation step | [
"Perform",
"an",
"on",
"-",
"policy",
"training",
"step",
"of",
"evaluating",
"an",
"env",
"and",
"a",
"single",
"backpropagation",
"step"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py#L112-L127 |
237,573 | MillionIntegrals/vel | vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py | BufferedMixedPolicyIterationReinforcer.off_policy_train_batch | def off_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'off-policy' training step of sampling the replay buffer and gradient descent """
self.model.train()
rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
ba... | python | def off_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'off-policy' training step of sampling the replay buffer and gradient descent """
self.model.train()
rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
ba... | [
"def",
"off_policy_train_batch",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"self",
".",
"model",
".",
"train",
"(",
")",
"rollout",
"=",
"self",
".",
"env_roller",
".",
"sample",
"(",
"batch_info",
",",
"self",
".",
"model",
",",
"self"... | Perform an 'off-policy' training step of sampling the replay buffer and gradient descent | [
"Perform",
"an",
"off",
"-",
"policy",
"training",
"step",
"of",
"sampling",
"the",
"replay",
"buffer",
"and",
"gradient",
"descent"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py#L129-L142 |
237,574 | MillionIntegrals/vel | vel/storage/strategy/classic_checkpoint_strategy.py | ClassicCheckpointStrategy.should_store_best_checkpoint | def should_store_best_checkpoint(self, epoch_idx, metrics) -> bool:
""" Should we store current checkpoint as the best """
if not self.store_best:
return False
metric = metrics[self.metric]
if better(self._current_best_metric_value, metric, self.metric_mode):
se... | python | def should_store_best_checkpoint(self, epoch_idx, metrics) -> bool:
""" Should we store current checkpoint as the best """
if not self.store_best:
return False
metric = metrics[self.metric]
if better(self._current_best_metric_value, metric, self.metric_mode):
se... | [
"def",
"should_store_best_checkpoint",
"(",
"self",
",",
"epoch_idx",
",",
"metrics",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"store_best",
":",
"return",
"False",
"metric",
"=",
"metrics",
"[",
"self",
".",
"metric",
"]",
"if",
"better",
"(",
... | Should we store current checkpoint as the best | [
"Should",
"we",
"store",
"current",
"checkpoint",
"as",
"the",
"best"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/strategy/classic_checkpoint_strategy.py#L27-L38 |
237,575 | MillionIntegrals/vel | vel/sources/nlp/imdb.py | create | def create(model_config, batch_size, vectors=None):
""" Create an IMDB dataset """
path = model_config.data_dir('imdb')
text_field = data.Field(lower=True, tokenize='spacy', batch_first=True)
label_field = data.LabelField(is_target=True)
train_source, test_source = IMDBCached.splits(
root=... | python | def create(model_config, batch_size, vectors=None):
""" Create an IMDB dataset """
path = model_config.data_dir('imdb')
text_field = data.Field(lower=True, tokenize='spacy', batch_first=True)
label_field = data.LabelField(is_target=True)
train_source, test_source = IMDBCached.splits(
root=... | [
"def",
"create",
"(",
"model_config",
",",
"batch_size",
",",
"vectors",
"=",
"None",
")",
":",
"path",
"=",
"model_config",
".",
"data_dir",
"(",
"'imdb'",
")",
"text_field",
"=",
"data",
".",
"Field",
"(",
"lower",
"=",
"True",
",",
"tokenize",
"=",
... | Create an IMDB dataset | [
"Create",
"an",
"IMDB",
"dataset"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/nlp/imdb.py#L48-L73 |
237,576 | MillionIntegrals/vel | vel/commands/augvis_command.py | AugmentationVisualizationCommand.run | def run(self):
""" Run the visualization """
dataset = self.source.train_dataset()
num_samples = len(dataset)
fig, ax = plt.subplots(self.cases, self.samples+1)
selected_sample = np.sort(np.random.choice(num_samples, self.cases, replace=False))
for i in range(self.case... | python | def run(self):
""" Run the visualization """
dataset = self.source.train_dataset()
num_samples = len(dataset)
fig, ax = plt.subplots(self.cases, self.samples+1)
selected_sample = np.sort(np.random.choice(num_samples, self.cases, replace=False))
for i in range(self.case... | [
"def",
"run",
"(",
"self",
")",
":",
"dataset",
"=",
"self",
".",
"source",
".",
"train_dataset",
"(",
")",
"num_samples",
"=",
"len",
"(",
"dataset",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"self",
".",
"cases",
",",
"self",
".",
... | Run the visualization | [
"Run",
"the",
"visualization"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/augvis_command.py#L14-L34 |
237,577 | MillionIntegrals/vel | vel/rl/env/classic_control.py | env_maker | def env_maker(environment_id, seed, serial_id, monitor=False, allow_early_resets=False):
""" Create a classic control environment with basic set of wrappers """
env = gym.make(environment_id)
env.seed(seed + serial_id)
# Monitoring the env
if monitor:
logdir = logger.get_dir() and os.path.j... | python | def env_maker(environment_id, seed, serial_id, monitor=False, allow_early_resets=False):
""" Create a classic control environment with basic set of wrappers """
env = gym.make(environment_id)
env.seed(seed + serial_id)
# Monitoring the env
if monitor:
logdir = logger.get_dir() and os.path.j... | [
"def",
"env_maker",
"(",
"environment_id",
",",
"seed",
",",
"serial_id",
",",
"monitor",
"=",
"False",
",",
"allow_early_resets",
"=",
"False",
")",
":",
"env",
"=",
"gym",
".",
"make",
"(",
"environment_id",
")",
"env",
".",
"seed",
"(",
"seed",
"+",
... | Create a classic control environment with basic set of wrappers | [
"Create",
"a",
"classic",
"control",
"environment",
"with",
"basic",
"set",
"of",
"wrappers"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_control.py#L25-L38 |
237,578 | MillionIntegrals/vel | vel/models/imagenet/resnet34.py | Resnet34.freeze | def freeze(self, number=None):
""" Freeze given number of layers in the model """
if number is None:
number = self.head_layers
for idx, child in enumerate(self.model.children()):
if idx < number:
mu.freeze_layer(child) | python | def freeze(self, number=None):
""" Freeze given number of layers in the model """
if number is None:
number = self.head_layers
for idx, child in enumerate(self.model.children()):
if idx < number:
mu.freeze_layer(child) | [
"def",
"freeze",
"(",
"self",
",",
"number",
"=",
"None",
")",
":",
"if",
"number",
"is",
"None",
":",
"number",
"=",
"self",
".",
"head_layers",
"for",
"idx",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"model",
".",
"children",
"(",
")",
"... | Freeze given number of layers in the model | [
"Freeze",
"given",
"number",
"of",
"layers",
"in",
"the",
"model"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/imagenet/resnet34.py#L66-L73 |
237,579 | MillionIntegrals/vel | vel/models/imagenet/resnet34.py | Resnet34.unfreeze | def unfreeze(self):
""" Unfreeze model layers """
for idx, child in enumerate(self.model.children()):
mu.unfreeze_layer(child) | python | def unfreeze(self):
""" Unfreeze model layers """
for idx, child in enumerate(self.model.children()):
mu.unfreeze_layer(child) | [
"def",
"unfreeze",
"(",
"self",
")",
":",
"for",
"idx",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"model",
".",
"children",
"(",
")",
")",
":",
"mu",
".",
"unfreeze_layer",
"(",
"child",
")"
] | Unfreeze model layers | [
"Unfreeze",
"model",
"layers"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/imagenet/resnet34.py#L75-L78 |
237,580 | MillionIntegrals/vel | vel/rl/algo/policy_gradient/acer.py | AcerPolicyGradient.update_average_model | def update_average_model(self, model):
""" Update weights of the average model with new model observation """
for model_param, average_param in zip(model.parameters(), self.average_model.parameters()):
# EWMA average model update
average_param.data.mul_(self.average_model_alpha).... | python | def update_average_model(self, model):
""" Update weights of the average model with new model observation """
for model_param, average_param in zip(model.parameters(), self.average_model.parameters()):
# EWMA average model update
average_param.data.mul_(self.average_model_alpha).... | [
"def",
"update_average_model",
"(",
"self",
",",
"model",
")",
":",
"for",
"model_param",
",",
"average_param",
"in",
"zip",
"(",
"model",
".",
"parameters",
"(",
")",
",",
"self",
".",
"average_model",
".",
"parameters",
"(",
")",
")",
":",
"# EWMA averag... | Update weights of the average model with new model observation | [
"Update",
"weights",
"of",
"the",
"average",
"model",
"with",
"new",
"model",
"observation"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/acer.py#L43-L47 |
237,581 | MillionIntegrals/vel | vel/rl/algo/policy_gradient/acer.py | AcerPolicyGradient.retrace | def retrace(self, rewards, dones, q_values, state_values, rho, final_values):
""" Calculate Q retraced targets """
rho_bar = torch.min(torch.ones_like(rho) * self.retrace_rho_cap, rho)
q_retraced_buffer = torch.zeros_like(rewards)
next_value = final_values
for i in reversed(ra... | python | def retrace(self, rewards, dones, q_values, state_values, rho, final_values):
""" Calculate Q retraced targets """
rho_bar = torch.min(torch.ones_like(rho) * self.retrace_rho_cap, rho)
q_retraced_buffer = torch.zeros_like(rewards)
next_value = final_values
for i in reversed(ra... | [
"def",
"retrace",
"(",
"self",
",",
"rewards",
",",
"dones",
",",
"q_values",
",",
"state_values",
",",
"rho",
",",
"final_values",
")",
":",
"rho_bar",
"=",
"torch",
".",
"min",
"(",
"torch",
".",
"ones_like",
"(",
"rho",
")",
"*",
"self",
".",
"ret... | Calculate Q retraced targets | [
"Calculate",
"Q",
"retraced",
"targets"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/acer.py#L170-L186 |
237,582 | MillionIntegrals/vel | vel/rl/modules/action_head.py | DiagGaussianActionHead.logprob | def logprob(self, action_sample, pd_params):
""" Log-likelihood """
means = pd_params[:, :, 0]
log_std = pd_params[:, :, 1]
std = torch.exp(log_std)
z_score = (action_sample - means) / std
return - (0.5 * ((z_score**2 + self.LOG2PI).sum(dim=-1)) + log_std.sum(dim=-1)) | python | def logprob(self, action_sample, pd_params):
""" Log-likelihood """
means = pd_params[:, :, 0]
log_std = pd_params[:, :, 1]
std = torch.exp(log_std)
z_score = (action_sample - means) / std
return - (0.5 * ((z_score**2 + self.LOG2PI).sum(dim=-1)) + log_std.sum(dim=-1)) | [
"def",
"logprob",
"(",
"self",
",",
"action_sample",
",",
"pd_params",
")",
":",
"means",
"=",
"pd_params",
"[",
":",
",",
":",
",",
"0",
"]",
"log_std",
"=",
"pd_params",
"[",
":",
",",
":",
",",
"1",
"]",
"std",
"=",
"torch",
".",
"exp",
"(",
... | Log-likelihood | [
"Log",
"-",
"likelihood"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/action_head.py#L45-L54 |
237,583 | MillionIntegrals/vel | vel/rl/modules/action_head.py | CategoricalActionHead.logprob | def logprob(self, actions, action_logits):
""" Logarithm of probability of given sample """
neg_log_prob = F.nll_loss(action_logits, actions, reduction='none')
return -neg_log_prob | python | def logprob(self, actions, action_logits):
""" Logarithm of probability of given sample """
neg_log_prob = F.nll_loss(action_logits, actions, reduction='none')
return -neg_log_prob | [
"def",
"logprob",
"(",
"self",
",",
"actions",
",",
"action_logits",
")",
":",
"neg_log_prob",
"=",
"F",
".",
"nll_loss",
"(",
"action_logits",
",",
"actions",
",",
"reduction",
"=",
"'none'",
")",
"return",
"-",
"neg_log_prob"
] | Logarithm of probability of given sample | [
"Logarithm",
"of",
"probability",
"of",
"given",
"sample"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/action_head.py#L103-L106 |
237,584 | MillionIntegrals/vel | vel/metrics/accuracy.py | Accuracy._value_function | def _value_function(self, x_input, y_true, y_pred):
""" Return classification accuracy of input """
if len(y_true.shape) == 1:
return y_pred.argmax(1).eq(y_true).double().mean().item()
else:
raise NotImplementedError | python | def _value_function(self, x_input, y_true, y_pred):
""" Return classification accuracy of input """
if len(y_true.shape) == 1:
return y_pred.argmax(1).eq(y_true).double().mean().item()
else:
raise NotImplementedError | [
"def",
"_value_function",
"(",
"self",
",",
"x_input",
",",
"y_true",
",",
"y_pred",
")",
":",
"if",
"len",
"(",
"y_true",
".",
"shape",
")",
"==",
"1",
":",
"return",
"y_pred",
".",
"argmax",
"(",
"1",
")",
".",
"eq",
"(",
"y_true",
")",
".",
"d... | Return classification accuracy of input | [
"Return",
"classification",
"accuracy",
"of",
"input"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/metrics/accuracy.py#L9-L14 |
237,585 | MillionIntegrals/vel | vel/storage/streaming/visdom.py | VisdomStreaming.on_epoch_end | def on_epoch_end(self, epoch_info):
""" Update data in visdom on push """
metrics_df = pd.DataFrame([epoch_info.result]).set_index('epoch_idx')
visdom_append_metrics(
self.vis,
metrics_df,
first_epoch=epoch_info.global_epoch_idx == 1
) | python | def on_epoch_end(self, epoch_info):
""" Update data in visdom on push """
metrics_df = pd.DataFrame([epoch_info.result]).set_index('epoch_idx')
visdom_append_metrics(
self.vis,
metrics_df,
first_epoch=epoch_info.global_epoch_idx == 1
) | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch_info",
")",
":",
"metrics_df",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"epoch_info",
".",
"result",
"]",
")",
".",
"set_index",
"(",
"'epoch_idx'",
")",
"visdom_append_metrics",
"(",
"self",
".",
"vis",
",",
... | Update data in visdom on push | [
"Update",
"data",
"in",
"visdom",
"on",
"push"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/streaming/visdom.py#L22-L30 |
237,586 | MillionIntegrals/vel | vel/storage/streaming/visdom.py | VisdomStreaming.on_batch_end | def on_batch_end(self, batch_info):
""" Stream LR to visdom """
if self.settings.stream_lr:
iteration_idx = (
float(batch_info.epoch_number) +
float(batch_info.batch_number) / batch_info.batches_per_epoch
)
lr = bat... | python | def on_batch_end(self, batch_info):
""" Stream LR to visdom """
if self.settings.stream_lr:
iteration_idx = (
float(batch_info.epoch_number) +
float(batch_info.batch_number) / batch_info.batches_per_epoch
)
lr = bat... | [
"def",
"on_batch_end",
"(",
"self",
",",
"batch_info",
")",
":",
"if",
"self",
".",
"settings",
".",
"stream_lr",
":",
"iteration_idx",
"=",
"(",
"float",
"(",
"batch_info",
".",
"epoch_number",
")",
"+",
"float",
"(",
"batch_info",
".",
"batch_number",
")... | Stream LR to visdom | [
"Stream",
"LR",
"to",
"visdom"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/streaming/visdom.py#L32-L48 |
237,587 | MillionIntegrals/vel | vel/launcher.py | main | def main():
""" Paperboy entry point - parse the arguments and run a command """
parser = argparse.ArgumentParser(description='Paperboy deep learning launcher')
parser.add_argument('config', metavar='FILENAME', help='Configuration file for the run')
parser.add_argument('command', metavar='COMMAND', hel... | python | def main():
""" Paperboy entry point - parse the arguments and run a command """
parser = argparse.ArgumentParser(description='Paperboy deep learning launcher')
parser.add_argument('config', metavar='FILENAME', help='Configuration file for the run')
parser.add_argument('command', metavar='COMMAND', hel... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Paperboy deep learning launcher'",
")",
"parser",
".",
"add_argument",
"(",
"'config'",
",",
"metavar",
"=",
"'FILENAME'",
",",
"help",
"=",
"'Configuratio... | Paperboy entry point - parse the arguments and run a command | [
"Paperboy",
"entry",
"point",
"-",
"parse",
"the",
"arguments",
"and",
"run",
"a",
"command"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/launcher.py#L10-L72 |
237,588 | MillionIntegrals/vel | vel/util/random.py | set_seed | def set_seed(seed: int):
""" Set random seed for python, numpy and pytorch RNGs """
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed) | python | def set_seed(seed: int):
""" Set random seed for python, numpy and pytorch RNGs """
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed) | [
"def",
"set_seed",
"(",
"seed",
":",
"int",
")",
":",
"random",
".",
"seed",
"(",
"seed",
")",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"torch",
".",
"random",
".",
"manual_seed",
"(",
"seed",
")"
] | Set random seed for python, numpy and pytorch RNGs | [
"Set",
"random",
"seed",
"for",
"python",
"numpy",
"and",
"pytorch",
"RNGs"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/random.py#L6-L10 |
237,589 | MillionIntegrals/vel | vel/util/better.py | better | def better(old_value, new_value, mode):
""" Check if new value is better than the old value"""
if (old_value is None or np.isnan(old_value)) and (new_value is not None and not np.isnan(new_value)):
return True
if mode == 'min':
return new_value < old_value
elif mode == 'max':
re... | python | def better(old_value, new_value, mode):
""" Check if new value is better than the old value"""
if (old_value is None or np.isnan(old_value)) and (new_value is not None and not np.isnan(new_value)):
return True
if mode == 'min':
return new_value < old_value
elif mode == 'max':
re... | [
"def",
"better",
"(",
"old_value",
",",
"new_value",
",",
"mode",
")",
":",
"if",
"(",
"old_value",
"is",
"None",
"or",
"np",
".",
"isnan",
"(",
"old_value",
")",
")",
"and",
"(",
"new_value",
"is",
"not",
"None",
"and",
"not",
"np",
".",
"isnan",
... | Check if new value is better than the old value | [
"Check",
"if",
"new",
"value",
"is",
"better",
"than",
"the",
"old",
"value"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/better.py#L4-L14 |
237,590 | MillionIntegrals/vel | vel/rl/modules/deterministic_critic_head.py | DeterministicCriticHead.reset_weights | def reset_weights(self):
""" Initialize weights to sane defaults """
init.uniform_(self.linear.weight, -3e-3, 3e-3)
init.zeros_(self.linear.bias) | python | def reset_weights(self):
""" Initialize weights to sane defaults """
init.uniform_(self.linear.weight, -3e-3, 3e-3)
init.zeros_(self.linear.bias) | [
"def",
"reset_weights",
"(",
"self",
")",
":",
"init",
".",
"uniform_",
"(",
"self",
".",
"linear",
".",
"weight",
",",
"-",
"3e-3",
",",
"3e-3",
")",
"init",
".",
"zeros_",
"(",
"self",
".",
"linear",
".",
"bias",
")"
] | Initialize weights to sane defaults | [
"Initialize",
"weights",
"to",
"sane",
"defaults"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/deterministic_critic_head.py#L20-L23 |
237,591 | MillionIntegrals/vel | vel/rl/discount_bootstrap.py | discount_bootstrap | def discount_bootstrap(rewards_buffer, dones_buffer, final_values, discount_factor, number_of_steps):
""" Calculate state values bootstrapping off the following state values """
true_value_buffer = torch.zeros_like(rewards_buffer)
# discount/bootstrap off value fn
current_value = final_values
for ... | python | def discount_bootstrap(rewards_buffer, dones_buffer, final_values, discount_factor, number_of_steps):
""" Calculate state values bootstrapping off the following state values """
true_value_buffer = torch.zeros_like(rewards_buffer)
# discount/bootstrap off value fn
current_value = final_values
for ... | [
"def",
"discount_bootstrap",
"(",
"rewards_buffer",
",",
"dones_buffer",
",",
"final_values",
",",
"discount_factor",
",",
"number_of_steps",
")",
":",
"true_value_buffer",
"=",
"torch",
".",
"zeros_like",
"(",
"rewards_buffer",
")",
"# discount/bootstrap off value fn",
... | Calculate state values bootstrapping off the following state values | [
"Calculate",
"state",
"values",
"bootstrapping",
"off",
"the",
"following",
"state",
"values"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/discount_bootstrap.py#L4-L15 |
237,592 | MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.find_project_directory | def find_project_directory(start_path) -> str:
""" Locate top-level project directory """
start_path = os.path.realpath(start_path)
possible_name = os.path.join(start_path, ModelConfig.PROJECT_FILE_NAME)
if os.path.exists(possible_name):
return start_path
else:
... | python | def find_project_directory(start_path) -> str:
""" Locate top-level project directory """
start_path = os.path.realpath(start_path)
possible_name = os.path.join(start_path, ModelConfig.PROJECT_FILE_NAME)
if os.path.exists(possible_name):
return start_path
else:
... | [
"def",
"find_project_directory",
"(",
"start_path",
")",
"->",
"str",
":",
"start_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"start_path",
")",
"possible_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"start_path",
",",
"ModelConfig",
".",
"PRO... | Locate top-level project directory | [
"Locate",
"top",
"-",
"level",
"project",
"directory"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L18-L30 |
237,593 | MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.from_file | def from_file(cls, filename: str, run_number: int, continue_training: bool = False, seed: int = None,
device: str = 'cuda', params=None):
""" Create model config from file """
with open(filename, 'r') as fp:
model_config_contents = Parser.parse(fp)
project_config_p... | python | def from_file(cls, filename: str, run_number: int, continue_training: bool = False, seed: int = None,
device: str = 'cuda', params=None):
""" Create model config from file """
with open(filename, 'r') as fp:
model_config_contents = Parser.parse(fp)
project_config_p... | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
":",
"str",
",",
"run_number",
":",
"int",
",",
"continue_training",
":",
"bool",
"=",
"False",
",",
"seed",
":",
"int",
"=",
"None",
",",
"device",
":",
"str",
"=",
"'cuda'",
",",
"params",
"=",
"None... | Create model config from file | [
"Create",
"model",
"config",
"from",
"file"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L33-L58 |
237,594 | MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.from_memory | def from_memory(cls, model_data: dict, run_number: int, project_dir: str,
continue_training=False, seed: int = None, device: str = 'cuda', params=None):
""" Create model config from supplied data """
return ModelConfig(
filename="[memory]",
configuration=model... | python | def from_memory(cls, model_data: dict, run_number: int, project_dir: str,
continue_training=False, seed: int = None, device: str = 'cuda', params=None):
""" Create model config from supplied data """
return ModelConfig(
filename="[memory]",
configuration=model... | [
"def",
"from_memory",
"(",
"cls",
",",
"model_data",
":",
"dict",
",",
"run_number",
":",
"int",
",",
"project_dir",
":",
"str",
",",
"continue_training",
"=",
"False",
",",
"seed",
":",
"int",
"=",
"None",
",",
"device",
":",
"str",
"=",
"'cuda'",
","... | Create model config from supplied data | [
"Create",
"model",
"config",
"from",
"supplied",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L61-L73 |
237,595 | MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.run_command | def run_command(self, command_name, varargs):
""" Instantiate model class """
command_descriptor = self.get_command(command_name)
return command_descriptor.run(*varargs) | python | def run_command(self, command_name, varargs):
""" Instantiate model class """
command_descriptor = self.get_command(command_name)
return command_descriptor.run(*varargs) | [
"def",
"run_command",
"(",
"self",
",",
"command_name",
",",
"varargs",
")",
":",
"command_descriptor",
"=",
"self",
".",
"get_command",
"(",
"command_name",
")",
"return",
"command_descriptor",
".",
"run",
"(",
"*",
"varargs",
")"
] | Instantiate model class | [
"Instantiate",
"model",
"class"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L109-L112 |
237,596 | MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.project_data_dir | def project_data_dir(self, *args) -> str:
""" Directory where to store data """
return os.path.normpath(os.path.join(self.project_dir, 'data', *args)) | python | def project_data_dir(self, *args) -> str:
""" Directory where to store data """
return os.path.normpath(os.path.join(self.project_dir, 'data', *args)) | [
"def",
"project_data_dir",
"(",
"self",
",",
"*",
"args",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project_dir",
",",
"'data'",
",",
"*",
"args",
")",
")"
] | Directory where to store data | [
"Directory",
"where",
"to",
"store",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L128-L130 |
237,597 | MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.output_dir | def output_dir(self, *args) -> str:
""" Directory where to store output """
return os.path.join(self.project_dir, 'output', *args) | python | def output_dir(self, *args) -> str:
""" Directory where to store output """
return os.path.join(self.project_dir, 'output', *args) | [
"def",
"output_dir",
"(",
"self",
",",
"*",
"args",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project_dir",
",",
"'output'",
",",
"*",
"args",
")"
] | Directory where to store output | [
"Directory",
"where",
"to",
"store",
"output"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L132-L134 |
237,598 | MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.project_top_dir | def project_top_dir(self, *args) -> str:
""" Project top-level directory """
return os.path.join(self.project_dir, *args) | python | def project_top_dir(self, *args) -> str:
""" Project top-level directory """
return os.path.join(self.project_dir, *args) | [
"def",
"project_top_dir",
"(",
"self",
",",
"*",
"args",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project_dir",
",",
"*",
"args",
")"
] | Project top-level directory | [
"Project",
"top",
"-",
"level",
"directory"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L136-L138 |
237,599 | MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.provide_with_default | def provide_with_default(self, name, default=None):
""" Return a dependency-injected instance """
return self.provider.instantiate_by_name_with_default(name, default_value=default) | python | def provide_with_default(self, name, default=None):
""" Return a dependency-injected instance """
return self.provider.instantiate_by_name_with_default(name, default_value=default) | [
"def",
"provide_with_default",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"provider",
".",
"instantiate_by_name_with_default",
"(",
"name",
",",
"default_value",
"=",
"default",
")"
] | Return a dependency-injected instance | [
"Return",
"a",
"dependency",
"-",
"injected",
"instance"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L165-L167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.