code stringlengths 17 6.64M |
|---|
def test_build_dataloader():
dataset = ToyDataset()
samples_per_gpu = 3
dataloader = build_dataloader(dataset, samples_per_gpu=samples_per_gpu, workers_per_gpu=2)
assert (dataloader.batch_size == samples_per_gpu)
assert (len(dataloader) == int(math.ceil((len(dataset) / samples_per_gpu))))
asse... |
class TestLoading(object):
@classmethod
def setup_class(cls):
cls.data_prefix = osp.join(osp.dirname(__file__), '../data')
def test_load_img(self):
results = dict(img_prefix=self.data_prefix, img_info=dict(filename='color.jpg'))
transform = LoadImageFromFile()
results = t... |
class ExampleDataset(Dataset):
def __getitem__(self, idx):
results = dict(img=torch.tensor([1]), img_metas=dict())
return results
def __len__(self):
return 1
|
class ExampleModel(nn.Module):
def __init__(self):
super(ExampleModel, self).__init__()
self.test_cfg = None
self.conv = nn.Conv2d(3, 3, 3)
def forward(self, img, img_metas, test_mode=False, **kwargs):
return img
def train_step(self, data_batch, optimizer):
loss ... |
def test_eval_hook():
with pytest.raises(TypeError):
test_dataset = ExampleModel()
data_loader = [DataLoader(test_dataset, batch_size=1, sampler=None, num_worker=0, shuffle=False)]
EvalHook(data_loader)
test_dataset = ExampleDataset()
test_dataset.evaluate = MagicMock(return_value=... |
def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False):
results = single_gpu_test(model, data_loader)
return results
|
@patch('mmseg.apis.multi_gpu_test', multi_gpu_test)
def test_dist_eval_hook():
with pytest.raises(TypeError):
test_dataset = ExampleModel()
data_loader = [DataLoader(test_dataset, batch_size=1, sampler=None, num_worker=0, shuffle=False)]
DistEvalHook(data_loader)
test_dataset = Example... |
def is_block(modules):
'Check if is ResNet building block.'
if isinstance(modules, (BasicBlock, Bottleneck, BottleneckX)):
return True
return False
|
def is_norm(modules):
'Check if is one of the norms.'
if isinstance(modules, (GroupNorm, _BatchNorm)):
return True
return False
|
def all_zeros(modules):
'Check if the weight(and bias) is all zero.'
weight_zero = torch.allclose(modules.weight.data, torch.zeros_like(modules.weight.data))
if hasattr(modules, 'bias'):
bias_zero = torch.allclose(modules.bias.data, torch.zeros_like(modules.bias.data))
else:
bias_zero ... |
def check_norm_state(modules, train_state):
'Check if norm layer is in correct train state.'
for mod in modules:
if isinstance(mod, _BatchNorm):
if (mod.training != train_state):
return False
return True
|
def test_resnet_basic_block():
with pytest.raises(AssertionError):
dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False)
BasicBlock(64, 64, dcn=dcn)
with pytest.raises(AssertionError):
plugins = [dict(cfg=dict(type='ContextBlock', ratio=(1.0 / 16)), position='after_conv3')]... |
def test_resnet_bottleneck():
with pytest.raises(AssertionError):
Bottleneck(64, 64, style='tensorflow')
with pytest.raises(AssertionError):
plugins = [dict(cfg=dict(type='ContextBlock', ratio=(1.0 / 16)), position='after_conv4')]
Bottleneck(64, 16, plugins=plugins)
with pytest.rai... |
def test_resnet_res_layer():
layer = ResLayer(Bottleneck, 64, 16, 3)
assert (len(layer) == 3)
assert (layer[0].conv1.in_channels == 64)
assert (layer[0].conv1.out_channels == 16)
for i in range(1, len(layer)):
assert (layer[i].conv1.in_channels == 64)
assert (layer[i].conv1.out_cha... |
def test_resnet_backbone():
'Test resnet backbone.'
with pytest.raises(KeyError):
ResNet(20)
with pytest.raises(AssertionError):
ResNet(50, num_stages=0)
with pytest.raises(AssertionError):
dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False)
ResNet(50, dcn... |
def test_renext_bottleneck():
with pytest.raises(AssertionError):
BottleneckX(64, 64, groups=32, base_width=4, style='tensorflow')
block = BottleneckX(64, 64, groups=32, base_width=4, stride=2, style='pytorch')
assert (block.conv2.stride == (2, 2))
assert (block.conv2.groups == 32)
assert ... |
def test_resnext_backbone():
with pytest.raises(KeyError):
ResNeXt(depth=18)
model = ResNeXt(depth=50, groups=32, base_width=4)
print(model)
for m in model.modules():
if is_block(m):
assert (m.conv2.groups == 32)
model.init_weights()
model.train()
imgs = torch.r... |
def test_fastscnn_backbone():
with pytest.raises(AssertionError):
FastSCNN(3, (32, 48), 64, (64, 96, 128), (2, 2, 1), global_out_channels=127, higher_in_channels=64, lower_in_channels=128)
model = FastSCNN()
model.init_weights()
model.train()
batch_size = 4
imgs = torch.randn(batch_siz... |
def test_resnest_bottleneck():
with pytest.raises(AssertionError):
BottleneckS(64, 64, radix=2, reduction_factor=4, style='tensorflow')
block = BottleneckS(64, 256, radix=2, reduction_factor=4, stride=2, style='pytorch')
assert (block.avd_layer.stride == 2)
assert (block.conv2.channels == 256)... |
def test_resnest_backbone():
with pytest.raises(KeyError):
ResNeSt(depth=18)
model = ResNeSt(depth=50, radix=2, reduction_factor=4, out_indices=(0, 1, 2, 3))
model.init_weights()
model.train()
imgs = torch.randn(2, 3, 224, 224)
feat = model(imgs)
assert (len(feat) == 4)
assert ... |
def _conv_has_norm(module, sync_bn):
for m in module.modules():
if isinstance(m, ConvModule):
if (not m.with_norm):
return False
if sync_bn:
if (not isinstance(m.bn, SyncBatchNorm)):
return False
return True
|
def to_cuda(module, data):
module = module.cuda()
if isinstance(data, list):
for i in range(len(data)):
data[i] = data[i].cuda()
return (module, data)
|
@patch.multiple(BaseDecodeHead, __abstractmethods__=set())
def test_decode_head():
with pytest.raises(AssertionError):
BaseDecodeHead([32, 16], 16, num_classes=19)
with pytest.raises(AssertionError):
BaseDecodeHead(32, 16, num_classes=19, in_index=[(- 1), (- 2)])
with pytest.raises(Asserti... |
def test_fcn_head():
with pytest.raises(AssertionError):
FCNHead(num_classes=19, num_convs=0)
head = FCNHead(in_channels=32, channels=16, num_classes=19)
for m in head.modules():
if isinstance(m, ConvModule):
assert (not m.with_norm)
head = FCNHead(in_channels=32, channels=... |
def test_psp_head():
with pytest.raises(AssertionError):
PSPHead(in_channels=32, channels=16, num_classes=19, pool_scales=1)
head = PSPHead(in_channels=32, channels=16, num_classes=19)
assert (not _conv_has_norm(head, sync_bn=False))
head = PSPHead(in_channels=32, channels=16, num_classes=19, ... |
def test_aspp_head():
with pytest.raises(AssertionError):
ASPPHead(in_channels=32, channels=16, num_classes=19, dilations=1)
head = ASPPHead(in_channels=32, channels=16, num_classes=19)
assert (not _conv_has_norm(head, sync_bn=False))
head = ASPPHead(in_channels=32, channels=16, num_classes=19... |
def test_psa_head():
with pytest.raises(AssertionError):
PSAHead(in_channels=32, channels=16, num_classes=19, mask_size=(39, 39), psa_type='gather')
head = PSAHead(in_channels=32, channels=16, num_classes=19, mask_size=(39, 39))
assert (not _conv_has_norm(head, sync_bn=False))
head = PSAHead(i... |
def test_gc_head():
head = GCHead(in_channels=32, channels=16, num_classes=19)
assert (len(head.convs) == 2)
assert hasattr(head, 'gc_block')
inputs = [torch.randn(1, 32, 45, 45)]
if torch.cuda.is_available():
(head, inputs) = to_cuda(head, inputs)
outputs = head(inputs)
assert (ou... |
def test_nl_head():
head = NLHead(in_channels=32, channels=16, num_classes=19)
assert (len(head.convs) == 2)
assert hasattr(head, 'nl_block')
inputs = [torch.randn(1, 32, 45, 45)]
if torch.cuda.is_available():
(head, inputs) = to_cuda(head, inputs)
outputs = head(inputs)
assert (ou... |
def test_cc_head():
head = CCHead(in_channels=32, channels=16, num_classes=19)
assert (len(head.convs) == 2)
assert hasattr(head, 'cca')
if (not torch.cuda.is_available()):
pytest.skip('CCHead requires CUDA')
inputs = [torch.randn(1, 32, 45, 45)]
(head, inputs) = to_cuda(head, inputs)
... |
def test_uper_head():
with pytest.raises(AssertionError):
UPerHead(in_channels=32, channels=16, num_classes=19)
head = UPerHead(in_channels=[32, 16], channels=16, num_classes=19, in_index=[(- 2), (- 1)])
assert (not _conv_has_norm(head, sync_bn=False))
head = UPerHead(in_channels=[32, 16], cha... |
def test_ann_head():
inputs = [torch.randn(1, 16, 45, 45), torch.randn(1, 32, 21, 21)]
head = ANNHead(in_channels=[16, 32], channels=16, num_classes=19, in_index=[(- 2), (- 1)], project_channels=8)
if torch.cuda.is_available():
(head, inputs) = to_cuda(head, inputs)
outputs = head(inputs)
... |
def test_da_head():
inputs = [torch.randn(1, 32, 45, 45)]
head = DAHead(in_channels=32, channels=16, num_classes=19, pam_channels=8)
if torch.cuda.is_available():
(head, inputs) = to_cuda(head, inputs)
outputs = head(inputs)
assert (isinstance(outputs, tuple) and (len(outputs) == 3))
f... |
def test_ocr_head():
inputs = [torch.randn(1, 32, 45, 45)]
ocr_head = OCRHead(in_channels=32, channels=16, num_classes=19, ocr_channels=8)
fcn_head = FCNHead(in_channels=32, channels=16, num_classes=19)
if torch.cuda.is_available():
(head, inputs) = to_cuda(ocr_head, inputs)
(head, inp... |
def test_enc_head():
inputs = [torch.randn(1, 32, 21, 21)]
head = EncHead(in_channels=[32], channels=16, num_classes=19, in_index=[(- 1)])
if torch.cuda.is_available():
(head, inputs) = to_cuda(head, inputs)
outputs = head(inputs)
assert (isinstance(outputs, tuple) and (len(outputs) == 2))... |
def test_dw_aspp_head():
inputs = [torch.randn(1, 32, 45, 45)]
head = DepthwiseSeparableASPPHead(c1_in_channels=0, c1_channels=0, in_channels=32, channels=16, num_classes=19, dilations=(1, 12, 24))
if torch.cuda.is_available():
(head, inputs) = to_cuda(head, inputs)
assert (head.c1_bottleneck ... |
def test_sep_fcn_head():
head = DepthwiseSeparableFCNHead(in_channels=128, channels=128, concat_input=False, num_classes=19, in_index=(- 1), norm_cfg=dict(type='BN', requires_grad=True, momentum=0.01))
x = [torch.rand(2, 128, 32, 32)]
output = head(x)
assert (output.shape == (2, head.num_classes, 32, ... |
def test_dnl_head():
head = DNLHead(in_channels=32, channels=16, num_classes=19)
assert (len(head.convs) == 2)
assert hasattr(head, 'dnl_block')
assert (head.dnl_block.temperature == 0.05)
inputs = [torch.randn(1, 32, 45, 45)]
if torch.cuda.is_available():
(head, inputs) = to_cuda(head... |
def test_emanet_head():
head = EMAHead(in_channels=32, ema_channels=24, channels=16, num_stages=3, num_bases=16, num_classes=19)
for param in head.ema_mid_conv.parameters():
assert (not param.requires_grad)
assert hasattr(head, 'ema_module')
inputs = [torch.randn(1, 32, 45, 45)]
if torch.c... |
def test_point_head():
inputs = [torch.randn(1, 32, 45, 45)]
point_head = PointHead(in_channels=[32], in_index=[0], channels=16, num_classes=19)
assert (len(point_head.fcs) == 3)
fcn_head = FCNHead(in_channels=32, channels=16, num_classes=19)
if torch.cuda.is_available():
(head, inputs) = ... |
def test_fpn():
in_channels = [256, 512, 1024, 2048]
inputs = [torch.randn(1, c, (56 // (2 ** i)), (56 // (2 ** i))) for (i, c) in enumerate(in_channels)]
fpn = FPN(in_channels, 256, len(in_channels))
outputs = fpn(inputs)
assert (outputs[0].shape == torch.Size([1, 256, 56, 56]))
assert (outpu... |
def test_depthwise_separable_conv():
with pytest.raises(AssertionError):
DepthwiseSeparableConvModule(4, 8, 2, groups=2)
conv = DepthwiseSeparableConvModule(3, 8, 2)
assert (conv.depthwise_conv.conv.groups == 3)
assert (conv.pointwise_conv.conv.kernel_size == (1, 1))
assert (not conv.depth... |
def _context_for_ohem():
return FCNHead(in_channels=32, channels=16, num_classes=19)
|
def test_ohem_sampler():
with pytest.raises(AssertionError):
sampler = OHEMPixelSampler(context=_context_for_ohem())
seg_logit = torch.randn(1, 19, 45, 45)
seg_label = torch.randint(0, 19, size=(1, 1, 89, 89))
sampler.sample(seg_logit, seg_label)
sampler = OHEMPixelSampler(cont... |
def test_inv_residual():
with pytest.raises(AssertionError):
InvertedResidual(32, 32, 3, 4)
inv_module = InvertedResidual(32, 32, 1, 4)
assert inv_module.use_res_connect
assert (inv_module.conv[0].kernel_size == (1, 1))
assert (inv_module.conv[0].padding == 0)
assert (inv_module.conv[1... |
def parse_args():
parser = argparse.ArgumentParser(description='MMSeg benchmark a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--log-interval', type=int, default=50, help='interval of logging')
ar... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
torch.backends.cudnn.benchmark = False
cfg.model.pretrained = None
cfg.data.test.test_mode = True
dataset = build_dataset(cfg.data.test)
data_loader = build_dataloader(dataset, samples_per_gpu=1, workers_per_gpu=cfg.data.wo... |
def convert_json_to_label(json_file):
label_file = json_file.replace('_polygons.json', '_labelTrainIds.png')
json2labelImg(json_file, label_file, 'trainIds')
|
def parse_args():
parser = argparse.ArgumentParser(description='Convert Cityscapes annotations to TrainIds')
parser.add_argument('cityscapes_path', help='cityscapes data path')
parser.add_argument('--gt-dir', default='gtFine', type=str)
parser.add_argument('-o', '--out-dir', help='output path')
pa... |
def main():
args = parse_args()
cityscapes_path = args.cityscapes_path
out_dir = (args.out_dir if args.out_dir else cityscapes_path)
mmcv.mkdir_or_exist(out_dir)
gt_dir = osp.join(cityscapes_path, args.gt_dir)
poly_files = []
for poly in mmcv.scandir(gt_dir, '_polygons.json', recursive=Tru... |
def convert_mat(mat_file, in_dir, out_dir):
data = loadmat(osp.join(in_dir, mat_file))
mask = data['GTcls'][0]['Segmentation'][0].astype(np.uint8)
seg_filename = osp.join(out_dir, mat_file.replace('.mat', '.png'))
Image.fromarray(mask).save(seg_filename, 'PNG')
|
def generate_aug_list(merged_list, excluded_list):
return list((set(merged_list) - set(excluded_list)))
|
def parse_args():
parser = argparse.ArgumentParser(description='Convert PASCAL VOC annotations to mmsegmentation format')
parser.add_argument('devkit_path', help='pascal voc devkit path')
parser.add_argument('aug_path', help='pascal voc aug path')
parser.add_argument('-o', '--out_dir', help='output pa... |
def main():
args = parse_args()
devkit_path = args.devkit_path
aug_path = args.aug_path
nproc = args.nproc
if (args.out_dir is None):
out_dir = osp.join(devkit_path, 'VOC2012', 'SegmentationClassAug')
else:
out_dir = args.out_dir
mmcv.mkdir_or_exist(out_dir)
in_dir = os... |
def parse_args():
parser = argparse.ArgumentParser(description='Train a segmentor')
parser.add_argument('config', help='train config file path')
parser.add_argument('--shape', type=int, nargs='+', default=[2048, 1024], help='input image size')
args = parser.parse_args()
return args
|
def main():
args = parse_args()
if (len(args.shape) == 1):
input_shape = (3, args.shape[0], args.shape[0])
elif (len(args.shape) == 2):
input_shape = ((3,) + tuple(args.shape))
else:
raise ValueError('invalid input shape')
cfg = Config.fromfile(args.config)
cfg.model.pr... |
def parse_args():
parser = argparse.ArgumentParser(description='Print the whole config')
parser.add_argument('config', help='config file path')
parser.add_argument('--options', nargs='+', action=DictAction, help='arguments in dict')
args = parser.parse_args()
return args
|
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if (args.options is not None):
cfg.merge_from_dict(args.options)
print(f'''Config:
{cfg.pretty_text}''')
cfg.dump('example.py')
|
def parse_args():
parser = argparse.ArgumentParser(description='Process a checkpoint to be published')
parser.add_argument('in_file', help='input checkpoint filename')
parser.add_argument('out_file', help='output checkpoint filename')
args = parser.parse_args()
return args
|
def process_checkpoint(in_file, out_file):
checkpoint = torch.load(in_file, map_location='cpu')
if ('optimizer' in checkpoint):
del checkpoint['optimizer']
torch.save(checkpoint, out_file)
sha = subprocess.check_output(['sha256sum', out_file]).decode()
final_file = (out_file.rstrip('.pth')... |
def main():
args = parse_args()
process_checkpoint(args.in_file, args.out_file)
|
def parse_args():
parser = argparse.ArgumentParser(description='mmseg test (and eval) a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--aug-test', action='store_true', help='Use Flip and Multi scale au... |
def main():
args = parse_args()
assert (args.out or args.eval or args.format_only or args.show or args.show_dir), 'Please specify at least one operation (save/eval/format/show the results / save the results) with the argument "--out", "--eval", "--format-only", "--show" or "--show-dir"'
if (args.eval and ... |
def parse_args():
parser = argparse.ArgumentParser(description='Train a segmentor')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work-dir', help='the dir to save logs and models')
parser.add_argument('--load-from', help='the checkpoint file to load weights from')... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if (args.options is not None):
cfg.merge_from_dict(args.options)
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
if (args.work_dir is not None):
cfg.work_dir = args.work_dir
e... |
class Mesh():
def __init__(self, name, geometry=None, geometry_path='', placement=None, color=(1.0, 0.0, 0.0, 1.0), scale=(1.0, 1.0, 1.0)):
super().__init__()
if (placement is None):
placement = pin.SE3.Identity()
assert isinstance(placement, pin.SE3), 'Use pin.SE3(R, t) with ... |
class Open3DVisualizer():
def __init__(self):
self.viz = None
self.pcd = o3d.geometry.PointCloud()
def __del__(self):
if (self.viz is not None):
self.viz.destroy_window()
def _create_viz(self):
self.viz = o3d.visualization.Visualizer()
self.viz.create... |
class Visualizer():
def __init__(self, name, model_wrapper):
self.name = name
if (self.name == 'meshcat'):
self.viz_class = MeshcatVisualizer
elif (self.name == 'gepetto'):
self.viz_class = GepettoVisualizer
else:
raise ValueError(f'Unknown visu... |
def load_dataset_geoms(filename):
with open(filename, 'rb') as f:
geoms_pkl = pkl.load(f)
dataset_geoms = []
for geoms_dict in geoms_pkl['geoms_dicts']:
geoms = Geometries()
geoms.from_dict(geoms_dict)
dataset_geoms.append(geoms)
return dataset_geoms
|
def display_start_goal(viz, robot, state, goal_state, dist_goal, start_color, goal_color):
if (viz is None):
raise ValueError('No visualizer instantiated.')
start_oMg = state.oMg
goal_oMg = goal_state.oMg
start_oMg_np = robot.get_oMg_np(start_oMg)
goal_oMg_np = robot.get_oMg_np(goal_oMg)
... |
def get_bounds_geom_objs(pos_bounds):
'\n Generate 6 faces corresponding to the agent deplacement bounds\n '
size = (pos_bounds[1] - pos_bounds[0])
center = np.mean(pos_bounds, axis=0)
thickness = 0.05
color = (1, 1, 1, 0.3)
geom_objs = []
aas = [eigenpy.AngleAxis(0, np.array([1, 0, ... |
class BaseObserver(gym.ObservationWrapper):
def __init__(self, env):
super().__init__(env)
self.obs_shape = self.env.obs_shape
self.obs_indices = self.env.obs_indices
self.observation_space = self.env.observation_space
def set_eval(self):
self.env.set_eval()
def ... |
class Node():
def __init__(self, point, parent):
if (not ((parent is None) or isinstance(parent, Node))):
raise ValueError('Parent should be None or Node type')
self.parent = parent
self.point = point
def path_from_root(self):
node = self
path = []
... |
def nearest_neighbor(x, nodes, distance_fn):
dist = [distance_fn(x, n.point) for n in nodes]
idx = np.argmin(dist)
return nodes[idx]
|
def rrt_bidir(start, goal, sample_fn, expand_fn, distance_fn, close_fn, iterations):
nodes_ab = [[], []]
for (i, x) in enumerate((start, goal)):
node = Node(x, parent=None)
nodes_ab[i].append(node)
solution = {'points': [], 'collisions': [], 'n_samples': 0, 'n_collisions': 0}
growing_i... |
def solve(env, delta_growth, iterations, simplify):
'\n collision_fn : maps x to True (free) / False (collision)\n sample_fn : return a configuration\n '
algo = rrt_bidir.rrt_bidir
model_wrapper = env.model_wrapper
delta_collision_check = env.delta_collision_check
action_range = env.robot... |
def shorten(path, expand_fn, interpolate_fn, distance_fn):
path = list(path)
current_idx = 0
target_idx = (len(path) - 1)
it = 0
while (current_idx < target_idx):
point = path[current_idx]
target = path[target_idx]
(q_stop, free) = expand_fn(point, target, limit_growth=Fals... |
def limit_step_size(path, arange_fn, step_size):
n = len(path)
new_path = []
for i in range((n - 1)):
new_path += arange_fn(path[i], path[(i + 1)], step_size)
return new_path
|
class Robot():
def __init__(self):
self.link_dim = None
def get_neutral(self):
return pin.neutral(self.model)
def _set_collision_pairs(self, model, geom_model):
raise NotImplementedError
def _build_from_urdf(self, model_wrapper, urdf_path, package_path):
model = mod... |
def get_replay_buffer(variant, expl_env):
'\n Define replay buffer specific to the mode\n '
mode = variant['mode']
if (mode == 'vanilla'):
replay_buffer = EnvReplayBuffer(env=expl_env, **variant['replay_buffer_kwargs'])
elif (mode == 'her'):
replay_buffer = ObsDictRelabelingBuffe... |
def get_networks(variant, expl_env):
'\n Define Q networks and policy network\n '
qf_kwargs = variant['qf_kwargs']
policy_kwargs = variant['policy_kwargs']
shared_base = None
(qf_class, qf_kwargs) = utils.get_q_network(variant['archi'], qf_kwargs, expl_env)
(policy_class, policy_kwargs) ... |
def get_path_collector(variant, expl_env, eval_env, policy, eval_policy):
'\n Define path collector\n '
mode = variant['mode']
if (mode == 'vanilla'):
expl_path_collector = MdpPathCollector(expl_env, policy)
eval_path_collector = MdpPathCollector(eval_env, eval_policy)
elif (mode... |
def sac(variant):
expl_env = gym.make(variant['env_name'])
eval_env = gym.make(variant['env_name'])
expl_env.seed(variant['seed'])
eval_env.set_eval()
mode = variant['mode']
archi = variant['archi']
if (mode == 'her'):
variant['her'] = dict(observation_key='observation', desired_go... |
def archi_to_network(archi_name, function_type):
allowed_function_type = ['vanilla', 'tanhgaussian']
if (function_type not in allowed_function_type):
raise ValueError(f'Function name should be in {allowed_function_type}')
return ARCHI[archi_name][function_type]
|
def get_policy_network(archi, kwargs, env, policy_type):
action_dim = env.action_space.low.size
obs_dim = env.observation_space.spaces['observation'].low.size
goal_dim = env.observation_space.spaces['representation_goal'].low.size
if (policy_type == 'tanhgaussian'):
kwargs['obs_dim'] = (obs_di... |
def get_q_network(archi, kwargs, env, classification=False):
action_dim = env.action_space.low.size
obs_dim = env.observation_space.spaces['observation'].low.size
goal_dim = env.observation_space.spaces['representation_goal'].low.size
kwargs['output_size'] = 1
q_action_dim = action_dim
if (arc... |
class MLPBlock(nn.Module):
def __init__(self, sizes, output_activation, hidden_activation=F.elu, hidden_init=ptu.fanin_init, b_init_value=0.1):
super().__init__()
self.output_activation = output_activation
self.hidden_activation = hidden_activation
self.hidden_init = hidden_init
... |
class RandomPolicy():
def __init__(self, env):
self.action_space = env.action_space
def reset(self):
pass
def get_action(self, obs):
low = np.array(self.action_space.low, ndmin=1)
dim = low.shape[0]
action = np.random.normal(size=(dim,))
action = np.tanh(... |
class StraightLinePolicy():
def __init__(self, env):
self.action_space = env.action_space
self.env = env
def reset(self):
pass
def get_action(self, obs):
current = self.env.state.q
goal = self.env.goal_state.q
action = (goal - current)[:self.action_space.... |
@click.command()
@click.argument('env_name', type=str)
@click.option('-exp', '--exp-name', default='', type=str)
@click.option('-s', '--seed', default=None, type=int)
@click.option('-h', '--horizon', default=50, type=int, help='max steps allowed')
@click.option('-e', '--episodes', default=0, type=int, help='number of... |
def check_os_environ(key, use):
if (key not in os.environ):
print(f'{key} is not defined in the os variables, it is required for {use}.')
print(f'Use home directory by default.')
return os.path.expanduser('~')
return os.environ[key]
|
def log_dir():
checkpoint = check_os_environ('CHECKPOINT', 'model checkpointing')
return checkpoint
|
@click.command(help='nmp.train env_name exp_name')
@click.argument('env-name', type=str)
@click.argument('exp-dir', type=str)
@click.option('-s', '--seed', default=None, type=int)
@click.option('-resume', '--resume/--no-resume', is_flag=True, default=False)
@click.option('-mode', '--mode', default='her')
@click.optio... |
def find_datafiles(path):
return [(os.path.join('etc', d), [os.path.join(d, f) for f in files]) for (d, folders, files) in os.walk(path)]
|
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
'3x3 convolution with padding'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
|
def conv1x1(in_planes, out_planes, stride=1):
'1x1 convolution'
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
if ((groups != 1) or (b... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
width = (int((planes * ... |
class ResNet(nn.Module):
def __init__(self, in_channels, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
... |
def _resnet(in_channels, arch, block, layers, pretrained, progress, **kwargs):
model = ResNet(in_channels, block, layers, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_dict(state_dict)
return model
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.