code
stringlengths
17
6.64M
class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), (- 1))
class IgnoreInput(nn.Module): def __init__(self, n_experts): super().__init__() self.weights = Parameter(torch.Tensor(n_experts)) def forward(self, x): sft = F.softmax(self.weights, dim=0) return torch.stack([sft for _ in range(x.shape[0])], dim=0)
class TaskonomyFeaturesOnlyNet(nn.Module): def __init__(self, n_frames, n_map_channels=0, use_target=True, output_size=512, num_tasks=1, extra_kwargs={}): super(TaskonomyFeaturesOnlyNet, self).__init__() self.n_frames = n_frames self.use_target = use_target self.use_map = (n_map_c...
class Expert(): def __init__(self, data_dir, compare_with_saved_trajs=False, follower=None): self.data_dir = data_dir self.compare_with_saved_trajs = compare_with_saved_trajs self.traj_dir = None self.action_idx = 0 self.same_as_il = True self.follower = None ...
class ForwardModel(nn.Module): def __init__(self, state_shape, action_shape, hidden_size): super().__init__() self.fc1 = init_(nn.Linear((state_shape + action_shape[1]), hidden_size)) self.fc2 = init_(nn.Linear(hidden_size, state_shape)) def forward(self, state, action): x = ...
class InverseModel(nn.Module): def __init__(self, input_size, hidden_size, output_size): super().__init__() self.fc1 = init_(nn.Linear((input_size * 2), hidden_size)) self.fc2 = init_(nn.Linear(hidden_size, output_size)) def forward(self, phi_t, phi_t_plus_1): x = torch.cat([...
def action_to_one_hot(action: int) -> np.array: one_hot = np.zeros(len(SimulatorActions), dtype=np.float32) one_hot[action] = 1 return one_hot
class ShortestPathFollower(): 'Utility class for extracting the action on the shortest path to the\n goal.\n Args:\n sim: HabitatSim instance.\n goal_radius: Distance between the agent and the goal for it to be\n considered successful.\n return_one_hot: If true, returns a...
class RLSidetuneWrapper(nn.Module): def __init__(self, n_frames, blind=False, **kwargs): super(RLSidetuneWrapper, self).__init__() extra_kwargs = kwargs.pop('extra_kwargs') assert ('main_perception_network' in extra_kwargs), 'For RLSidetuneWrapper, need to include main class' asse...
class RLSidetuneNetwork(nn.Module): def __init__(self, n_frames, n_map_channels=0, use_target=True, output_size=512, num_tasks=1, extra_kwargs={}): super(RLSidetuneNetwork, self).__init__() assert ('sidetune_kwargs' in extra_kwargs), 'Cannot use sidetune network without kwargs' self.sidet...
def getNChannels(): return N_CHANNELS
class BaseModelSRL(nn.Module): '\n Base Class for a SRL network\n It implements a getState method to retrieve a state from observations\n ' def __init__(self): super(BaseModelSRL, self).__init__() def getStates(self, observations): '\n :param observations: (th.Tensor)\n ...
class BaseModelAutoEncoder(BaseModelSRL): '\n Base Class for a SRL network (autoencoder family)\n It implements a getState method to retrieve a state from observations\n ' def __init__(self, n_frames, n_map_channels=0, use_target=True, output_size=512): super(BaseModelAutoEncoder, self).__in...
def conv3x3(in_planes, out_planes, stride=1): '"\n From PyTorch Resnet implementation\n 3x3 convolution with padding\n :param in_planes: (int)\n :param out_planes: (int)\n :param stride: (int)\n ' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def srl_features_transform(task_path, dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns takes 'env' and returns transform, outpu...
class TriangleModel(nn.Module): def __init__(self, network_constructors, n_channels_lists, universal_kwargses=[{}]): super().__init__() self.chains = nn.ModuleList() for (network_constructor, n_channels_list, universal_kwargs) in zip(network_constructors, n_channels_lists, universal_kwarg...
class UNet_up_block(nn.Module): def __init__(self, prev_channel, input_channel, output_channel, up_sample=True): super().__init__() self.up_sampling = nn.Upsample(scale_factor=2, mode='bilinear') self.conv1 = nn.Conv2d((prev_channel + input_channel), output_channel, 3, padding=1) ...
class UNet_down_block(nn.Module): def __init__(self, input_channel, output_channel, down_size=True): super().__init__() self.conv1 = nn.Conv2d(input_channel, output_channel, 3, padding=1) self.bn1 = nn.GroupNorm(8, output_channel) self.conv2 = nn.Conv2d(output_channel, output_chan...
class UNet(nn.Module): def __init__(self, downsample=6, in_channels=3, out_channels=3): super().__init__() (self.in_channels, self.out_channels, self.downsample) = (in_channels, out_channels, downsample) self.down1 = UNet_down_block(in_channels, 16, False) self.down_blocks = nn.Mo...
class UNetHeteroscedasticFull(nn.Module): def __init__(self, downsample=6, in_channels=3, out_channels=3, eps=1e-05): super().__init__() (self.in_channels, self.out_channels, self.downsample) = (in_channels, out_channels, downsample) self.down1 = UNet_down_block(in_channels, 16, False) ...
class UNetHeteroscedasticIndep(nn.Module): def __init__(self, downsample=6, in_channels=3, out_channels=3, eps=1e-05): super().__init__() (self.in_channels, self.out_channels, self.downsample) = (in_channels, out_channels, downsample) self.down1 = UNet_down_block(in_channels, 16, False) ...
class UNetHeteroscedasticPooled(nn.Module): def __init__(self, downsample=6, in_channels=3, out_channels=3, eps=1e-05, use_clamp=False): super().__init__() (self.in_channels, self.out_channels, self.downsample) = (in_channels, out_channels, downsample) self.down1 = UNet_down_block(in_chan...
class UNetReshade(nn.Module): def __init__(self, downsample=6, in_channels=3, out_channels=3): super().__init__() (self.in_channels, self.out_channels, self.downsample) = (in_channels, out_channels, downsample) self.down1 = UNet_down_block(in_channels, 16, False) self.down_blocks ...
class ConvBlock(nn.Module): def __init__(self, f1, f2, kernel_size=3, padding=1, use_groupnorm=True, groups=8, dilation=1, transpose=False): super().__init__() self.transpose = transpose self.conv = nn.Conv2d(f1, f2, (kernel_size, kernel_size), dilation=dilation, padding=(padding * dilati...
def load_from_file(net, checkpoint_path): checkpoint = torch.load(checkpoint_path) sd = {k.replace('module.', ''): v for (k, v) in checkpoint['state_dict'].items()} net.load_state_dict(sd) for p in net.parameters(): p.requires_grad = False return net
def blind(output_size, dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns takes 'env' and returns transform, output_size, dtype\n...
def pixels_as_state(output_size, dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns takes 'env' and returns transform, output_siz...
class GaussianSmoothing(nn.Module): '\n Apply gaussian smoothing on a\n 1d, 2d or 3d tensor. Filtering is performed seperately for each channel\n in the input using a depthwise convolution.\n Arguments:\n channels (int, sequence): Number of channels of the input tensors. Output will\n ...
class GaussianSmoothing(nn.Module): '\n Apply gaussian smoothing on a\n 1d, 2d or 3d tensor. Filtering is performed seperately for each channel\n in the input using a depthwise convolution.\n Arguments:\n channels (int, sequence): Number of channels of the input tensors. Output will\n ...
class TransformFactory(object): @staticmethod def independent(names_to_transforms, multithread=False, keep_unnamed=True): def processing_fn(obs_space): ' Obs_space is expected to be a 1-layer deep spaces.Dict ' transforms = {} sensor_space = {} transfo...
class Pipeline(object): def __init__(self, env_or_pipeline): pass def forward(self): pass
def identity_transform(): def _thunk(obs_space): return ((lambda x: x), obs_space) return _thunk
def fill_like(output_size, fill_value=0.0, dtype=torch.float32): def _thunk(obs_space): tensor = torch.ones((1,), dtype=dtype) def _process(x): return tensor.new_full(output_size, fill_value).numpy() return (_process, spaces.Box((- 1), 1, output_size, tensor.numpy().dtype)) ...
def rescale_centercrop_resize(output_size, dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n\n obs_space: Should be form WxHxC\n Returns:\n a function which returns ta...
def rescale_centercrop_resize_collated(output_size, dtype=np.float32): " rescale_centercrop_resize\n\n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n\n obs_space: Should be form WxHxC\n Returns:\n a function which retur...
def rescale(): " Rescales observations to a new values\n\n Returns:\n a function which returns takes 'env' and returns transform, output_size, dtype\n " def _rescale_thunk(obs_space): obs_shape = obs_space.shape np_pipeline = vision.transforms.Compose([vision.transforms.T...
def grayscale_rescale(): " Rescales observations to a new values\n\n Returns:\n a function which returns takes 'env' and returns transform, output_size, dtype\n " def _grayscale_rescale_thunk(obs_space): pipeline = vision.transforms.Compose([vision.transforms.ToPILImage(), vision...
def cross_modal_transform(eval_to_get_net, output_shape=(3, 84, 84), dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns takes 'en...
def cross_modal_transform_collated(eval_to_get_net, output_shape=(3, 84, 84), dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns ...
def pixels_as_state(output_size, dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns takes 'env' and returns transform, output_siz...
def taskonomy_features_transform_collated(task_path, encoder_type='taskonomy', dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns...
def taskonomy_features_transforms_collated(task_paths, encoder_type='taskonomy', dtype=np.float32): num_tasks = 0 if ((task_paths != 'pixels_as_state') and (task_paths != 'blind')): task_path_list = [tp.strip() for tp in task_paths.split(',')] num_tasks = len(task_path_list) assert (nu...
def image_to_input_collated(output_size, dtype=np.float32): def _thunk(obs_space): def runner(x): assert (x.shape[2] == x.shape[1]), 'we are only using square data, data format: N,H,W,C' if isinstance(x, torch.Tensor): x = torch.cuda.FloatTensor(x.cuda()) ...
def map_pool_collated(output_size, dtype=np.float32): def _thunk(obs_space): def runner(x): with torch.no_grad(): assert (x.shape[2] == x.shape[1]), 'we are only using square data, data format: N,H,W,C' if isinstance(x, torch.Tensor): x = t...
def map_pool(output_size, dtype=np.float32): def _thunk(obs_space): def runner(x): with torch.no_grad(): assert (x.shape[0] == x.shape[1]), 'we are only using square data, data format: N,H,W,C' if isinstance(x, torch.Tensor): x = torch.cuda...
class Pipeline(object): def __init__(self, env_or_pipeline): pass def forward(self): pass
def identity_transform(): def _thunk(obs_space): return ((lambda x: x), obs_space) return _thunk
def fill_like(output_size, fill_value=0.0, dtype=torch.float32): def _thunk(obs_space): tensor = torch.ones((1,), dtype=dtype) def _process(x): return tensor.new_full(output_size, fill_value).numpy() return (_process, spaces.Box((- 1), 1, output_size, tensor.numpy().dtype)) ...
def rescale_centercrop_resize(output_size, dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n\n obs_space: Should be form WxHxC\n Returns:\n a function which returns ta...
def rescale_centercrop_resize_collated(output_size, dtype=np.float32): " rescale_centercrop_resize\n\n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n\n obs_space: Should be form WxHxC\n Returns:\n a function which retur...
def rescale(): " Rescales observations to a new values\n\n Returns:\n a function which returns takes 'env' and returns transform, output_size, dtype\n " def _rescale_thunk(obs_space): obs_shape = obs_space.shape np_pipeline = vision.transforms.Compose([vision.transforms.T...
def grayscale_rescale(): " Rescales observations to a new values\n\n Returns:\n a function which returns takes 'env' and returns transform, output_size, dtype\n " def _grayscale_rescale_thunk(obs_space): pipeline = vision.transforms.Compose([vision.transforms.ToPILImage(), vision...
def cross_modal_transform(eval_to_get_net, output_shape=(3, 84, 84), dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns takes 'en...
def image_to_input_collated(output_size, dtype=np.float32): def _thunk(obs_space): def runner(x): assert (x.shape[2] == x.shape[1]), 'Input image must be square, of the form: N,H,W,C' if isinstance(x, torch.Tensor): x = torch.cuda.FloatTensor(x.cuda()) ...
def map_pool(output_size, dtype=np.float32): def _thunk(obs_space): def runner(x): with torch.no_grad(): assert (x.shape[0] == x.shape[1]), 'we are only using square data, data format: N,H,W,C' if isinstance(x, torch.Tensor): x = torch.cuda...
def map_pool_collated(output_size, dtype=np.float32): def _thunk(obs_space): def runner(x): with torch.no_grad(): assert (x.shape[2] == x.shape[1]), 'we are only using square data, data format: N,H,W,C' if isinstance(x, torch.Tensor): x = t...
def taskonomy_features_transform(task_path, model='TaskonomyEncoder', dtype=np.float32, device=None, normalize_outputs=False): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n ...
def _load_encoder(encoder_path): if (('student' in encoder_path) or ('distil' in encoder_path)): net = FCN5(normalize_outputs=True, eval_only=True, train=False) else: net = TaskonomyEncoder() net.eval() checkpoint = torch.load(encoder_path) state_dict = checkpoint['state_dict'] ...
def _load_encoders_seq(encoder_paths): experts = [] for encoder_path in encoder_paths: try: encoder = _load_encoder(encoder_path) experts.append(encoder) except RuntimeError as e: warnings.warn(f'Unable to load {encoder_path} due to {e}') raise e...
def _load_encoders_parallel(encoder_paths, n_processes=None): n_processes = (len(encoder_paths) if (n_processes is None) else min(len(encoder_paths), n_processes)) n_parallel = min(multiprocessing.cpu_count(), n_processes) pool = multiprocessing.Pool(min(n_parallel, n_processes)) experts = pool.map(_l...
def taskonomy_multi_features_transform(task_paths, dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns takes 'env' and returns tra...
def taskonomy_features_transform_collated(task_path, dtype=np.float32): " rescale_centercrop_resize\n \n Args:\n output_size: A tuple CxWxH\n dtype: of the output (must be np, not torch)\n \n Returns:\n a function which returns takes 'env' and returns t...
def taskonomy_features_transforms_collated(task_paths, encoder_type='taskonomy', dtype=np.float32): num_tasks = 0 if ((task_paths != 'pixels_as_state') and (task_paths != 'blind')): task_path_list = [tp.strip() for tp in task_paths.split(',')] num_tasks = len(task_path_list) assert (nu...
class A2C_ACKTR(object): def __init__(self, actor_critic, value_loss_coef, entropy_coef, lr=None, eps=None, alpha=None, max_grad_norm=None, acktr=False): self.actor_critic = actor_critic self.acktr = acktr self.value_loss_coef = value_loss_coef self.entropy_coef = entropy_coef ...
class QLearner(nn.Module): def __init__(self, actor_network, target_network, action_dim, batch_size, lr, eps, gamma, copy_frequency, start_schedule, schedule_timesteps, initial_p, final_p): super(QLearner, self).__init__() self.actor_network = actor_network self.target_network = target_ne...
class LearningSchedule(object): def __init__(self, start_schedule, schedule_timesteps, initial_p=1.0, final_p=0.05): self.initial_p = initial_p self.final_p = final_p self.schedule_timesteps = schedule_timesteps self.start_schedule = start_schedule def value(self, t): ...
def _extract_patches(x, kernel_size, stride, padding): if ((padding[0] + padding[1]) > 0): x = F.pad(x, (padding[1], padding[1], padding[0], padding[0])).data x = x.unfold(2, kernel_size[0], stride[0]) x = x.unfold(3, kernel_size[1], stride[1]) x = x.transpose_(1, 2).transpose_(2, 3).contiguou...
def compute_cov_a(a, classname, layer_info, fast_cnn): batch_size = a.size(0) if (classname == 'Conv2d'): if fast_cnn: a = _extract_patches(a, *layer_info) a = a.view(a.size(0), (- 1), a.size((- 1))) a = a.mean(1) else: a = _extract_patches(a, *l...
def compute_cov_g(g, classname, layer_info, fast_cnn): batch_size = g.size(0) if (classname == 'Conv2d'): if fast_cnn: g = g.view(g.size(0), g.size(1), (- 1)) g = g.sum((- 1)) else: g = g.transpose(1, 2).transpose(2, 3).contiguous() g = g.view((-...
def update_running_stat(aa, m_aa, momentum): m_aa *= (momentum / (1 - momentum)) m_aa += aa m_aa *= (1 - momentum)
class SplitBias(nn.Module): def __init__(self, module): super(SplitBias, self).__init__() self.module = module self.add_bias = AddBias(module.bias.data) self.module.bias = None def forward(self, input): x = self.module(input) x = self.add_bias(x) retur...
class KFACOptimizer(optim.Optimizer): def __init__(self, model, lr=0.25, momentum=0.9, stat_decay=0.99, kl_clip=0.001, damping=0.01, weight_decay=0, fast_cnn=False, Ts=1, Tf=10): defaults = dict() def split_bias(module): for (mname, child) in module.named_children(): ...
class PPO(object): def __init__(self, actor_critic, clip_param, ppo_epoch, num_mini_batch, value_loss_coef, entropy_coef, lr=None, eps=None, max_grad_norm=None, amsgrad=True, weight_decay=0.0): self.actor_critic = actor_critic self.clip_param = clip_param self.ppo_epoch = ppo_epoch ...
class PPOCuriosity(object): def __init__(self, actor_critic, clip_param, ppo_epoch, num_mini_batch, value_loss_coef, entropy_coef, optimizer=None, lr=None, eps=None, max_grad_norm=None, amsgrad=True, weight_decay=0.0): self.actor_critic = actor_critic self.clip_param = clip_param self.ppo...
class PPOReplayCuriosity(object): def __init__(self, actor_critic, clip_param, ppo_epoch, num_mini_batch, value_loss_coef, entropy_coef, on_policy_epoch, off_policy_epoch, lr=None, eps=None, max_grad_norm=None, amsgrad=True, weight_decay=0.0, curiosity_reward_coef=0.1, forward_loss_coef=0.2, inverse_loss_coef=0....
class PPOReplay(object): def __init__(self, actor_critic: BasePolicy, clip_param, ppo_epoch, num_mini_batch, value_loss_coef, entropy_coef, on_policy_epoch, off_policy_epoch, num_steps, n_frames, lr=None, eps=None, max_grad_norm=None, amsgrad=True, weight_decay=0.0, gpu_devices=None, loss_kwargs={}, cache_kwargs...
class Categorical(nn.Module): def __init__(self, num_inputs, num_outputs): super(Categorical, self).__init__() self.num_outputs = num_outputs init_ = (lambda m: init(m, nn.init.orthogonal_, (lambda x: nn.init.constant_(x, 0)), gain=0.01)) self.linear = init_(nn.Linear(num_inputs, ...
class DiagGaussian(nn.Module): def __init__(self, num_inputs, num_outputs): super(DiagGaussian, self).__init__() self.num_outputs = num_outputs init_ = (lambda m: init(m, init_normc_, (lambda x: nn.init.constant_(x, 0)))) self.fc_mean = init_(nn.Linear(num_inputs, num_outputs)) ...
class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), (- 1))
class LearnerModel(nn.Module): def __init__(self, num_inputs): super().__init__() @property def state_size(self): raise NotImplementedError('state_size not implemented in abstract class LearnerModel') @property def output_size(self): raise NotImplementedError('output_siz...
class CNNModel(nn.Module): def __init__(self, num_inputs, use_gru, input_transforms=None): super().__init__() self.input_transforms = input_transforms
class CNNBase(nn.Module): def __init__(self, num_inputs, use_gru): super(CNNBase, self).__init__() init_ = (lambda m: init(m, nn.init.orthogonal_, (lambda x: nn.init.constant_(x, 0)), nn.init.calculate_gain('relu'))) self.main = nn.Sequential(init_(nn.Conv2d(num_inputs, 32, 8, stride=4)),...
class MLPBase(nn.Module): def __init__(self, num_inputs): super(MLPBase, self).__init__() init_ = (lambda m: init(m, init_normc_, (lambda x: nn.init.constant_(x, 0)))) self.actor = nn.Sequential(init_(nn.Linear(num_inputs, 64)), nn.Tanh(), init_(nn.Linear(64, 64)), nn.Tanh()) self...
class PreprocessingTranforms(object): def __init__(self, input_dims): pass def forward(self, batch): pass
class SegmentTree(): def __init__(self, size): self.index = 0 self.size = size self.full = False self.sum_tree = ([0] * ((2 * size) - 1)) self.data = ([None] * size) self.max = 1 def _propagate(self, index, value): parent = ((index - 1) // 2) (...
class ReplayMemory(): def __init__(self, device, history_length, discount, multi_step, priority_weight, priority_exponent, capacity, blank_state): self.device = device self.capacity = capacity self.history = history_length self.discount = discount self.n = multi_step ...
class RolloutSensorDictCuriosityReplayBuffer(object): def __init__(self, num_steps, num_processes, obs_shape, action_space, state_size, actor_critic, use_gae, gamma, tau, memory_size=10000): self.num_steps = num_steps self.num_processes = num_processes self.state_size = state_size ...
class SegmentTree(object): def __init__(self, capacity, operation, neutral_element): "Build a Segment Tree data structure.\n\n https://en.wikipedia.org/wiki/Segment_tree\n\n Can be used as regular array, but with two\n important differences:\n\n a) setting item's value is ...
class SumSegmentTree(SegmentTree): def __init__(self, capacity): super(SumSegmentTree, self).__init__(capacity=capacity, operation=operator.add, neutral_element=0.0) def sum(self, start=0, end=None): 'Returns arr[start] + ... + arr[end]' return super(SumSegmentTree, self).reduce(star...
class MinSegmentTree(SegmentTree): def __init__(self, capacity): super(MinSegmentTree, self).__init__(capacity=capacity, operation=min, neutral_element=float('inf')) def min(self, start=0, end=None): 'Returns min(arr[start], ..., arr[end])' return super(MinSegmentTree, self).reduce(...
class AddBias(nn.Module): def __init__(self, bias): super(AddBias, self).__init__() self._bias = nn.Parameter(bias.unsqueeze(1)) def forward(self, x): if (x.dim() == 2): bias = self._bias.t().view(1, (- 1)) else: bias = self._bias.t().view(1, (- 1), 1,...
def init(module, weight_init, bias_init, gain=1): weight_init(module.weight.data, gain=gain) bias_init(module.bias.data) return module
def init_normc_(weight, gain=1): weight.normal_(0, 1) weight *= (gain / torch.sqrt(weight.pow(2).sum(1, keepdim=True)))
def load_experiment_configs(log_dir, uuid=None): ' \n Loads all experiments in a given directory \n Optionally, may be restricted to those with a given uuid\n ' dirs = [f for f in os.listdir(log_dir) if os.path.isdir(os.path.join(log_dir, f))] results = [] for d in dirs: c...
def load_experiment_config_paths(log_dir, uuid=None): dirs = [f for f in os.listdir(log_dir) if os.path.isdir(os.path.join(log_dir, f))] results = [] for d in dirs: cfg_path = os.path.join(log_dir, d, 'config.json') if (not os.path.exists(cfg_path)): continue with open(...
def checkpoint_name(checkpoint_dir, epoch='latest'): return os.path.join(checkpoint_dir, 'ckpt-{}.dat'.format(epoch))
def last_archived_run(base_dir, uuid): " Returns the name of the last archived run. Of the form:\n 'UUID_run_K'\n " archive_dir = os.path.join(base_dir, 'archive') existing_runs = glob.glob(os.path.join(archive_dir, (uuid + '_run_*'))) print(os.path.join(archive_dir, (uuid + '_run_*'))) ...
def archive_current_run(base_dir, uuid): ' Archives the current run. That is, it moves everything\n base_dir/*uuid* -> base_dir/archive/uuid_run_K/\n where K is determined automatically.\n ' matching_files = glob.glob(os.path.join(base_dir, (('*' + uuid) + '*'))) if (len(matching_files) =...
def save_checkpoint(obj, directory, step_num, use_thread=False): if use_thread: warnings.warn('use_threads set to True, but done synchronously still') os.makedirs(directory, exist_ok=True) torch.save(obj, checkpoint_name(directory), pickle_module=pickle) torch.save(obj, checkpoint_name(directo...
class VisdomMonitor(Monitor): def __init__(self, env, directory, video_callable=None, force=False, resume=False, write_upon_reset=False, uid=None, mode=None, server='localhost', env='main', port=8097): super(VisdomMonitor, self).__init__(env, directory, video_callable=video_callable, force=force, resume=...