_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q232800
run_apidoc
train
def run_apidoc(_): """This method is required by the setup method below.""" import os dirname = os.path.dirname(__file__) ignore_paths = [os.path.join(dirname, '../../aaf2/model'),] # https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py argv = [ '--force', '--no-...
python
{ "resource": "" }
q232801
MobID.from_dict
train
def from_dict(self, d): """ Set MobID from a dict """ self.length = d.get("length", 0) self.instanceHigh = d.get("instanceHigh", 0) self.instanceMid = d.get("instanceMid", 0) self.instanceLow = d.get("instanceLow", 0) material = d.get("material", {'Data1'...
python
{ "resource": "" }
q232802
MobID.to_dict
train
def to_dict(self): """ MobID representation as dict """ material = {'Data1': self.Data1, 'Data2': self.Data2, 'Data3': self.Data3, 'Data4': list(self.Data4) } return {'material':material, ...
python
{ "resource": "" }
q232803
wave_infochunk
train
def wave_infochunk(path): """ Returns a bytearray of the WAVE RIFF header and fmt chunk for a `WAVEDescriptor` `Summary` """ with open(path,'rb') as file: if file.read(4) != b"RIFF": return None data_size = file.read(4) # container size if file.read(4) != b"WAVE":...
python
{ "resource": "" }
q232804
DirEntry.pop
train
def pop(self): """ remove self from binary search tree """ entry = self parent = self.parent root = parent.child() dir_per_sector = self.storage.sector_size // 128 max_dirs_entries = self.storage.dir_sector_count * dir_per_sector count = 0 ...
python
{ "resource": "" }
q232805
CompoundFileBinary.remove
train
def remove(self, path): """ Removes both streams and storage DirEntry types from file. storage type entries need to be empty dirs. """ entry = self.find(path) if not entry: raise ValueError("%s does not exists" % path) if entry.type == 'root storage...
python
{ "resource": "" }
q232806
CompoundFileBinary.rmtree
train
def rmtree(self, path): """ Removes directory structure, similar to shutil.rmtree. """ for root, storage, streams in self.walk(path, topdown=False): for item in streams: self.free_fat_chain(item.sector_id, item.byte_size < self.min_stream_max_size) ...
python
{ "resource": "" }
q232807
CompoundFileBinary.listdir_dict
train
def listdir_dict(self, path = None): """ Return a dict containing the ``DirEntry`` objects in the directory given by path with name of the dir as key. """ if path is None: path = self.root root = self.find(path) if root is None: raise Val...
python
{ "resource": "" }
q232808
CompoundFileBinary.makedir
train
def makedir(self, path, class_id=None): """ Create a storage DirEntry name path """ return self.create_dir_entry(path, dir_type='storage', class_id=class_id)
python
{ "resource": "" }
q232809
CompoundFileBinary.makedirs
train
def makedirs(self, path): """ Recursive storage DirEntry creation function. """ root = "" assert path.startswith('/') p = path.strip('/') for item in p.split('/'): root += "/" + item if not self.exists(root): self.makedir(r...
python
{ "resource": "" }
q232810
CompoundFileBinary.move
train
def move(self, src, dst): """ Moves ``DirEntry`` from src to dst """ src_entry = self.find(src) if src_entry is None: raise ValueError("src path does not exist: %s" % src) if dst.endswith('/'): dst += src_entry.name if self.exists(dst): ...
python
{ "resource": "" }
q232811
CompoundFileBinary.open
train
def open(self, path, mode='r'): """Open stream, returning ``Stream`` object""" entry = self.find(path) if entry is None: if mode == 'r': raise ValueError("stream does not exists: %s" % path) entry = self.create_dir_entry(path, 'stream', None) els...
python
{ "resource": "" }
q232812
add2set
train
def add2set(self, pid, key, value): """low level add to StrongRefSetProperty""" prop = self.property_entries[pid] current = prop.objects.get(key, None) current_local_key = prop.references.get(key, None) if current and current is not value: current.detach() if current_local_key is None...
python
{ "resource": "" }
q232813
QDistributionalHead.histogram_info
train
def histogram_info(self) -> dict: """ Return extra information about histogram """ return { 'support_atoms': self.support_atoms, 'atom_delta': self.atom_delta, 'vmin': self.vmin, 'vmax': self.vmax, 'num_atoms': self.atoms }
python
{ "resource": "" }
q232814
QDistributionalHead.sample
train
def sample(self, histogram_logits): """ Sample from a greedy strategy with given q-value histogram """ histogram_probs = histogram_logits.exp() # Batch size * actions * atoms atoms = self.support_atoms.view(1, 1, self.atoms) # Need to introduce two new dimensions return (histogram_prob...
python
{ "resource": "" }
q232815
TextUrlSource.download
train
def download(self): """ Make sure data file is downloaded and stored properly """ if not os.path.exists(self.data_path): # Create if it doesn't exist pathlib.Path(self.data_path).mkdir(parents=True, exist_ok=True) if not os.path.exists(self.text_path): http =...
python
{ "resource": "" }
q232816
explained_variance
train
def explained_variance(returns, values): """ Calculate how much variance in returns do the values explain """ exp_var = 1 - torch.var(returns - values) / torch.var(returns) return exp_var.item()
python
{ "resource": "" }
q232817
create
train
def create(model_config, path, num_workers, batch_size, augmentations=None, tta=None): """ Create an ImageDirSource with supplied arguments """ if not os.path.isabs(path): path = model_config.project_top_dir(path) train_path = os.path.join(path, 'train') valid_path = os.path.join(path, 'valid')...
python
{ "resource": "" }
q232818
QModel.reset_weights
train
def reset_weights(self): """ Initialize weights to reasonable defaults """ self.input_block.reset_weights() self.backbone.reset_weights() self.q_head.reset_weights()
python
{ "resource": "" }
q232819
TensorAccumulator.result
train
def result(self): """ Concatenate accumulated tensors """ return {k: torch.stack(v) for k, v in self.accumulants.items()}
python
{ "resource": "" }
q232820
Provider.resolve_parameters
train
def resolve_parameters(self, func, extra_env=None): """ Resolve parameter dictionary for the supplied function """ parameter_list = [ (k, v.default == inspect.Parameter.empty) for k, v in inspect.signature(func).parameters.items() ] extra_env = extra_env if extra_env is not N...
python
{ "resource": "" }
q232821
Provider.resolve_and_call
train
def resolve_and_call(self, func, extra_env=None): """ Resolve function arguments and call them, possibily filling from the environment """ kwargs = self.resolve_parameters(func, extra_env=extra_env) return func(**kwargs)
python
{ "resource": "" }
q232822
Provider.instantiate_from_data
train
def instantiate_from_data(self, object_data): """ Instantiate object from the supplied data, additional args may come from the environment """ if isinstance(object_data, dict) and 'name' in object_data: name = object_data['name'] module = importlib.import_module(name) ...
python
{ "resource": "" }
q232823
Provider.render_configuration
train
def render_configuration(self, configuration=None): """ Render variables in configuration object but don't instantiate anything """ if configuration is None: configuration = self.environment if isinstance(configuration, dict): return {k: self.render_configuration(v) for ...
python
{ "resource": "" }
q232824
Evaluator.is_provided
train
def is_provided(self, name): """ Capability check if evaluator provides given value """ if name in self._storage: return True elif name in self._providers: return True elif name.startswith('rollout:'): rollout_name = name[8:] else: ...
python
{ "resource": "" }
q232825
Evaluator.get
train
def get(self, name): """ Return a value from this evaluator. Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times with and without no_grad() context. It is advised in such cases to not use no_grad and stick to .detach() ...
python
{ "resource": "" }
q232826
create
train
def create(model_config, batch_size, normalize=True, num_workers=0, augmentations=None): """ Create a MNIST dataset, normalized """ path = model_config.data_dir('mnist') train_dataset = datasets.MNIST(path, train=True, download=True) test_dataset = datasets.MNIST(path, train=False, download=True) ...
python
{ "resource": "" }
q232827
ClassicStorage.reset
train
def reset(self, configuration: dict) -> None: """ Whenever there was anything stored in the database or not, purge previous state and start new training process from scratch. """ self.clean(0) self.backend.store_config(configuration)
python
{ "resource": "" }
q232828
ClassicStorage.load
train
def load(self, train_info: TrainingInfo) -> (dict, dict): """ Resume learning process and return loaded hidden state dictionary """ last_epoch = train_info.start_epoch_idx model_state = torch.load(self.checkpoint_filename(last_epoch)) hidden_state = torch.load(self.check...
python
{ "resource": "" }
q232829
ClassicStorage.clean
train
def clean(self, global_epoch_idx): """ Clean old checkpoints """ if self.cleaned: return self.cleaned = True self.backend.clean(global_epoch_idx) self._make_sure_dir_exists() for x in os.listdir(self.model_config.checkpoint_dir()): match = re.ma...
python
{ "resource": "" }
q232830
ClassicStorage.checkpoint
train
def checkpoint(self, epoch_info: EpochInfo, model: Model): """ When epoch is done, we persist the training state """ self.clean(epoch_info.global_epoch_idx - 1) self._make_sure_dir_exists() # Checkpoint latest torch.save(model.state_dict(), self.checkpoint_filename(epoch_info.g...
python
{ "resource": "" }
q232831
ClassicStorage._persisted_last_epoch
train
def _persisted_last_epoch(self) -> int: """ Return number of last epoch already calculated """ epoch_number = 0 self._make_sure_dir_exists() for x in os.listdir(self.model_config.checkpoint_dir()): match = re.match('checkpoint_(\\d+)\\.data', x) if match: ...
python
{ "resource": "" }
q232832
ClassicStorage._make_sure_dir_exists
train
def _make_sure_dir_exists(self): """ Make sure directory exists """ filename = self.model_config.checkpoint_dir() pathlib.Path(filename).mkdir(parents=True, exist_ok=True)
python
{ "resource": "" }
q232833
clip_gradients
train
def clip_gradients(batch_result, model, max_grad_norm): """ Clip gradients to a given maximum length """ if max_grad_norm is not None: grad_norm = torch.nn.utils.clip_grad_norm_( filter(lambda p: p.requires_grad, model.parameters()), max_norm=max_grad_norm ) else: ...
python
{ "resource": "" }
q232834
CircularReplayBuffer.sample_trajectories
train
def sample_trajectories(self, rollout_length, batch_info) -> Trajectories: """ Sample batch of trajectories and return them """ indexes = self.backend.sample_batch_trajectories(rollout_length) transition_tensors = self.backend.get_trajectories(indexes, rollout_length) return Trajectorie...
python
{ "resource": "" }
q232835
conjugate_gradient_method
train
def conjugate_gradient_method(matrix_vector_operator, loss_gradient, nsteps, rdotr_tol=1e-10): """ Conjugate gradient algorithm """ x = torch.zeros_like(loss_gradient) r = loss_gradient.clone() p = loss_gradient.clone() rdotr = torch.dot(r, r) for i in range(nsteps): Avp = matrix_vect...
python
{ "resource": "" }
q232836
TrpoPolicyGradient.line_search
train
def line_search(self, model, rollout, original_policy_loss, original_policy_params, original_parameter_vec, full_step, expected_improvement_full): """ Find the right stepsize to make sure policy improves """ current_parameter_vec = original_parameter_vec.clone() for idx in r...
python
{ "resource": "" }
q232837
TrpoPolicyGradient.fisher_vector_product
train
def fisher_vector_product(self, vector, kl_divergence_gradient, model): """ Calculate product Hessian @ vector """ assert not vector.requires_grad, "Vector must not propagate gradient" dot_product = vector @ kl_divergence_gradient # at least one dimension spans across two contiguous sub...
python
{ "resource": "" }
q232838
TrpoPolicyGradient.value_loss
train
def value_loss(self, model, observations, discounted_rewards): """ Loss of value estimator """ value_outputs = model.value(observations) value_loss = 0.5 * F.mse_loss(value_outputs, discounted_rewards) return value_loss
python
{ "resource": "" }
q232839
TrpoPolicyGradient.calc_policy_loss
train
def calc_policy_loss(self, model, policy_params, policy_entropy, rollout): """ Policy gradient loss - calculate from probability distribution Calculate surrogate loss - advantage * policy_probability / fixed_initial_policy_probability Because we operate with logarithm of -probability (...
python
{ "resource": "" }
q232840
Transitions.shuffled_batches
train
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
{ "resource": "" }
q232841
Trajectories.to_transitions
train
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
{ "resource": "" }
q232842
Trajectories.shuffled_batches
train
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
{ "resource": "" }
q232843
Trajectories.episode_information
train
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
{ "resource": "" }
q232844
MultilayerRnnSequenceModel.forward_state
train
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
{ "resource": "" }
q232845
MultilayerRnnSequenceModel.loss_value
train
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
{ "resource": "" }
q232846
Learner.initialize_training
train
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
{ "resource": "" }
q232847
Learner.run_epoch
train
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
{ "resource": "" }
q232848
Learner.train_epoch
train
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
{ "resource": "" }
q232849
Learner.validation_epoch
train
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
{ "resource": "" }
q232850
Learner.feed_batch
train
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
{ "resource": "" }
q232851
Learner.train_batch
train
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
{ "resource": "" }
q232852
process_environment_settings
train
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
{ "resource": "" }
q232853
BufferedOffPolicyIterationReinforcer.roll_out_and_store
train
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
{ "resource": "" }
q232854
BufferedOffPolicyIterationReinforcer.train_on_replay_memory
train
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
{ "resource": "" }
q232855
conv3x3
train
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
{ "resource": "" }
q232856
load
train
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
{ "resource": "" }
q232857
TrainingInfo.restore
train
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
{ "resource": "" }
q232858
EpochResultAccumulator.result
train
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
{ "resource": "" }
q232859
EpochInfo.state_dict
train
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
{ "resource": "" }
q232860
EpochInfo.on_epoch_end
train
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
{ "resource": "" }
q232861
BatchInfo.aggregate_key
train
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
{ "resource": "" }
q232862
RlTrainCommand.run
train
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
{ "resource": "" }
q232863
RlTrainCommand.resume_training
train
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
{ "resource": "" }
q232864
RlTrainCommand._openai_logging
train
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
{ "resource": "" }
q232865
module_broadcast
train
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
{ "resource": "" }
q232866
PhaseTrainCommand._select_phase_left_bound
train
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
{ "resource": "" }
q232867
wrapped_env_maker
train
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
{ "resource": "" }
q232868
ClassicAtariEnv.instantiate
train
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
{ "resource": "" }
q232869
visdom_send_metrics
train
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
{ "resource": "" }
q232870
TrainPhase.restore
train
def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict): """ Restore learning from intermediate state. """ pass
python
{ "resource": "" }
q232871
PrioritizedCircularVecEnvBufferBackend.update_priority
train
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
{ "resource": "" }
q232872
PrioritizedCircularVecEnvBufferBackend._sample_batch_prioritized
train
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
{ "resource": "" }
q232873
take_along_axis
train
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
{ "resource": "" }
q232874
CircularVecEnvBufferBackend.get_transition
train
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
{ "resource": "" }
q232875
CircularVecEnvBufferBackend.get_transitions_forward_steps
train
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
{ "resource": "" }
q232876
CircularVecEnvBufferBackend.sample_batch_trajectories
train
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
{ "resource": "" }
q232877
CircularVecEnvBufferBackend.sample_frame_single_env
train
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
{ "resource": "" }
q232878
RecordMovieCommand.record_take
train
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
{ "resource": "" }
q232879
OuNoise.reset_training_state
train
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
{ "resource": "" }
q232880
OuNoise.forward
train
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
{ "resource": "" }
q232881
interpolate_logscale
train
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
{ "resource": "" }
q232882
interpolate_series
train
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
{ "resource": "" }
q232883
interpolate_single
train
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
{ "resource": "" }
q232884
ModelSummary.run
train
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
{ "resource": "" }
q232885
OnPolicyIterationReinforcer.initialize_training
train
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
{ "resource": "" }
q232886
convolutional_layer_series
train
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
{ "resource": "" }
q232887
Model.train
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
{ "resource": "" }
q232888
Model.summary
train
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
{ "resource": "" }
q232889
Model.hashsummary
train
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
{ "resource": "" }
q232890
RnnLinearBackboneModel.zero_state
train
def zero_state(self, batch_size): """ Initial state of the network """ return torch.zeros(batch_size, self.state_dim, dtype=torch.float32)
python
{ "resource": "" }
q232891
SupervisedModel.loss
train
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
{ "resource": "" }
q232892
ResNetV2.metrics
train
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
{ "resource": "" }
q232893
one_hot_encoding
train
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
{ "resource": "" }
q232894
merge_first_two_dims
train
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
{ "resource": "" }
q232895
DummyVecEnvWrapper.instantiate
train
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
{ "resource": "" }
q232896
DummyVecEnvWrapper.instantiate_single
train
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
{ "resource": "" }
q232897
DummyVecEnvWrapper._creation_function
train
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
{ "resource": "" }
q232898
StochasticPolicyModelSeparate.policy
train
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
{ "resource": "" }
q232899
CycleCallback._init_cycle_dict
train
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
{ "resource": "" }