code stringlengths 17 6.64M |
|---|
def rlav3_resnet50(rla_channel=32):
' Constructs a RLAv3_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n '
print('Constructing rlav3_resnet50......')
model = RLAv3_ResNet(RLAv3_Bottleneck, [3, 4, 6, 3])
return m... |
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 RLAv4_Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16):
super(RLAv4_Bottleneck, self).__init__()
if (norm_layer is None):
... |
class RLAv4_ResNet(nn.Module):
'\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n '
def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init... |
def rlav4_resnet50(rla_channel=32):
' Constructs a RLAv4_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n '
print('Constructing rlav4_resnet50......')
model = RLAv4_ResNet(RLAv4_Bottleneck, [3, 4, 6, 3])
return m... |
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 RLAv5_Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16):
super(RLAv5_Bottleneck, self).__init__()
if (norm_layer is None):
... |
class RLAv5_ResNet(nn.Module):
'\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n '
def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init... |
def rlav5_resnet50(rla_channel=32):
' Constructs a RLAv5_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n '
print('Constructing rlav5_resnet50......')
model = RLAv5_ResNet(RLAv5_Bottleneck, [3, 4, 6, 3])
return m... |
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 RLAv6_Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16):
super(RLAv6_Bottleneck, self).__init__()
if (norm_layer is None):
... |
class RLAv6_ResNet(nn.Module):
'\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n '
def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init... |
def rlav6_resnet50(rla_channel=32):
' Constructs a RLAv6_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n '
print('Constructing rlav6_resnet50......')
model = RLAv6_ResNet(RLAv6_Bottleneck, [3, 4, 6, 3])
return m... |
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(nn.Linear(channel, (channel // reduction), bias=False), nn.ReLU(inplace=True), nn.Linear((channel // reduction), channel, bi... |
def main():
global args
args = parser.parse_args()
model = models.__dict__[args.arch]()
print(model)
input = torch.randn(1, 3, args.input_size, args.input_size)
model.train()
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
model = model.to(device)
input = in... |
def clever_format(nums, format='%.2f'):
clever_nums = []
for num in nums:
if (num > 1000000000000.0):
clever_nums.append(((format % (num / (1024 ** 4))) + 'T'))
elif (num > 1000000000.0):
clever_nums.append(((format % (num / (1024 ** 3))) + 'G'))
elif (num > 100... |
def main():
global args
args = parser.parse_args()
if (args.seed is not None):
random.seed(args.seed)
torch.manual_seed(args.seed)
cudnn.deterministic = True
warnings.warn('You have chosen to seed training. This will turn on the CUDNN deterministic setting, which can slow d... |
def main_worker(gpu, ngpus_per_node, args):
global best_acc1
args.gpu = gpu
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))
if args.distributed:
if ((args.dist_url == 'env://') and (args.rank == (- 1))):
args.rank = int(os.environ['RANK'])
... |
def train(train_loader, model, criterion, optimizer, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
losses_batch = {}
progre... |
def validate(val_loader, model, criterion, args):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(len(val_loader), [batch_time, losses, top1, top5], prefix='Test: '... |
def save_checkpoint(state, is_best, args, filename='checkpoint.pth.tar'):
save_path = ('%s/%s/' % (args.work_dir, ((args.arch + '_') + args.action)))
filepath = os.path.join(save_path, filename)
bestpath = os.path.join(save_path, 'model_best.pth.tar')
torch.save(state, filepath)
if is_best:
... |
class AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(... |
class ProgressMeter(object):
def __init__(self, num_batches, meters, prefix=''):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [(self.prefix + self.batch_fmtstr.format(batch))]
ent... |
def adjust_learning_rate(optimizer, epoch, args):
'Sets the learning rate to the initial LR decayed by 10 every 30 epochs'
lr = (args.lr * (0.1 ** (epoch // 30)))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
|
def accuracy(output, target, topk=(1,)):
'Computes the accuracy over the k top predictions for the specified values of k'
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(ta... |
def data_save(root, file):
if (not os.path.exists(root)):
os.mknod(root)
file_temp = open(root, 'r')
lines = file_temp.readlines()
if (not lines):
epoch = (- 1)
else:
epoch = lines[(- 1)][:lines[(- 1)].index(' ')]
epoch = int(epoch)
file_temp.close()
file_temp =... |
def main():
global args, best_acc1
args = parser.parse_args()
if (args.seed is not None):
random.seed(args.seed)
torch.manual_seed(args.seed)
cudnn.deterministic = True
warnings.warn('You have chosen to seed training. This will turn on the CUDNN deterministic setting, which... |
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
losses_batch = {}
model.train()
directory = ('%s/%s/' % (args.work_dir, ((args.arch + '_') + args.acti... |
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
model.eval()
with torch.no_grad():
end = time.time()
for (i, (input, target)) in enumerate(val_loader):
if (args.gpu is not No... |
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
directory = ('%s/%s/' % (args.work_dir, ((args.arch + '_') + args.action)))
filename = (directory + filename)
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, (directory + 'model_best.pth.tar'))
|
class AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += (val... |
def adjust_learning_rate(optimizer, epoch):
'Sets the learning rate to the initial LR decayed by 10 every 30 epochs'
lr = (args.lr * (0.98 ** epoch))
print('lr = ', lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
|
def accuracy(output, target, topk=(1,)):
'Computes the accuracy@k for the specified values of k'
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expan... |
def data_save(root, file):
if (not os.path.exists(root)):
os.mknod(root)
file_temp = open(root, 'r')
lines = file_temp.readlines()
if (not lines):
epoch = (- 1)
else:
epoch = lines[(- 1)][:lines[(- 1)].index(' ')]
epoch = int(epoch)
file_temp.close()
file_temp =... |
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
'The Main Window of the graphical user interface.\n\n The class MainWindow inherits from Ui_MainWindow, which is\n defined in maxent_ui.py. The latter file is autogenerated\n by pyuic from maxent_ui.ui [`pyuic5 maxent_ui.ui -o maxent_ui.py`]\n Th... |
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName('MainWindow')
MainWindow.resize(759, 629)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName('centralwidget')
self.real_freq_frame = QtWidgets.QFrame(self.... |
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
'The Main Window of the graphical user interface.\n\n The class MainWindow inherits from Ui_MainWindow, which is\n defined in maxent_ui.py. The latter file is autogenerated\n by pyuic from maxent_ui.ui [`pyuic5 maxent_ui.ui -o maxent_ui.py`]\n Th... |
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName('MainWindow')
MainWindow.resize(760, 633)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName('centralwidget')
self.real_freq_frame = QtWidgets.QFrame(self.... |
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
'The Main Window of the graphical user interface.\n\n The class MainWindow inherits from Ui_MainWindow, which is\n defined in pade_ui.py. The latter file is autogenerated\n by pyuic from pade_ui.ui [`pyuic5 pade_ui.ui -o pade_ui.py`]\n The ui fil... |
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName('MainWindow')
MainWindow.resize(800, 399)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName('centralwidget')
self.real_freq_frame = QtWidgets.QFrame(self.... |
def gauss_peak(maxpos, width, weight, wgrid):
a = ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid - maxpos) ** 2)) / (width ** 2))))
a -= ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid + maxpos) ** 2)) / (width ** 2))))
return a
|
def noise(sigma, iwgrid):
return (np.random.randn(iwgrid.shape[0]) * sigma)
|
def gauss_peak(maxpos, width, weight, wgrid):
a = ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid - maxpos) ** 2)) / (width ** 2))))
return a
|
def noise(sigma, iwgrid):
return (np.random.randn(iwgrid.shape[0]) * sigma)
|
def gauss_peak(maxpos, width, weight, wgrid):
a = ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid - maxpos) ** 2)) / (width ** 2))))
return a
|
def noise(sigma, iwgrid):
return (np.random.randn(iwgrid.shape[0]) * sigma)
|
def gauss_peak(maxpos, width, weight, wgrid):
a = ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid - maxpos) ** 2)) / (width ** 2))))
a -= ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid + maxpos) ** 2)) / (width ** 2))))
return a
|
def noise(sigma, iwgrid):
return (np.random.randn(iwgrid.shape[0]) * sigma)
|
def gauss_peak(maxpos, width, weight, wgrid):
a = ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid - maxpos) ** 2)) / (width ** 2))))
return a
|
def noise(sigma, iwgrid):
return (np.random.randn(iwgrid.shape[0]) * sigma)
|
def gauss_peak(maxpos, width, weight, wgrid):
a = ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid - maxpos) ** 2)) / (width ** 2))))
return a
|
def noise(sigma, iwgrid):
return (np.random.randn(iwgrid.shape[0]) * sigma)
|
def connect(PORT):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', PORT))
sock.listen(1)
(conn, addr) = sock.accept()
return conn
|
def send(conn, data):
coded_data = data.tostring()
conn.sendall(coded_data)
|
def recv(conn):
data = conn.recv(1024)
data_cast = array.array('f', data)
return data_cast
|
def disconnect(conn):
conn.close()
|
def get_benckmark_arg_parser():
parser = argparse.ArgumentParser('Benchmark inference speed of Deformable DETR.')
parser.add_argument('--num_iters', type=int, default=300, help='total iters to benchmark speed')
parser.add_argument('--warm_iters', type=int, default=5, help='ignore first several iters that ... |
@torch.no_grad()
def measure_average_inference_time(model, inputs, num_iters=100, warm_iters=5):
ts = []
for iter_ in range(num_iters):
torch.cuda.synchronize()
t_ = time.perf_counter()
model(inputs)
torch.cuda.synchronize()
t = (time.perf_counter() - t_)
if (it... |
def benchmark():
(args, _) = get_benckmark_arg_parser().parse_known_args()
main_args = get_main_args_parser().parse_args(_)
assert ((args.warm_iters < args.num_iters) and (args.num_iters > 0) and (args.warm_iters >= 0))
assert (args.batch_size > 0)
assert ((args.resume is None) or os.path.exists(a... |
def get_coco_api_from_dataset(dataset):
for _ in range(10):
if isinstance(dataset, torch.utils.data.Subset):
dataset = dataset.dataset
if isinstance(dataset, CocoDetection):
return dataset.coco
|
def build_dataset(image_set, args):
if (args.dataset_file == 'coco'):
return build_coco(image_set, args)
if (args.dataset_file == 'coco_panoptic'):
from .coco_panoptic import build as build_coco_panoptic
return build_coco_panoptic(image_set, args)
raise ValueError(f'dataset {args.d... |
def to_cuda(samples, targets, device):
samples = samples.to(device, non_blocking=True)
targets = [{k: v.to(device, non_blocking=True) for (k, v) in t.items()} for t in targets]
return (samples, targets)
|
class data_prefetcher():
def __init__(self, loader, device, prefetch=True):
self.loader = iter(loader)
self.prefetch = prefetch
self.device = device
if prefetch:
self.stream = torch.cuda.Stream()
self.preload()
def preload(self):
try:
... |
class PanopticEvaluator(object):
def __init__(self, ann_file, ann_folder, output_dir='panoptic_eval'):
self.gt_json = ann_file
self.gt_folder = ann_folder
if utils.is_main_process():
if (not os.path.exists(output_dir)):
os.mkdir(output_dir)
self.output_... |
class DistributedSampler(Sampler):
'Sampler that restricts data loading to a subset of the dataset.\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n and loa... |
class NodeDistributedSampler(Sampler):
'Sampler that restricts data loading to a subset of the dataset.\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n and... |
class CocoDetection(VisionDataset):
'`MS Coco Detection <http://mscoco.org/dataset/#detections-challenge2016>`_ Dataset.\n Args:\n root (string): Root directory where images are downloaded to.\n annFile (string): Path to json annotation file.\n transform (callable, optional): A function/tr... |
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, max_norm: float=0):
model.train()
criterion.train()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', utils.... |
@torch.no_grad()
def evaluate(model, criterion, postprocessors, data_loader, base_ds, device, output_dir):
model.eval()
criterion.eval()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}'))
header = 'Test:'... |
def get_args_parser():
parser = argparse.ArgumentParser('Deformable DETR Detector', add_help=False)
parser.add_argument('--lr', default=0.0002, type=float)
parser.add_argument('--lr_backbone_names', default=['backbone.0'], type=str, nargs='+')
parser.add_argument('--lr_backbone', default=2e-05, type=f... |
def main(args):
utils.init_distributed_mode(args)
print('git:\n {}\n'.format(utils.get_sha()))
if (args.frozen_weights is not None):
assert args.masks, 'Frozen training is meant for segmentation only'
print(args)
device = torch.device(args.device)
seed = (args.seed + utils.get_rank())... |
def build_model(args):
return build(args)
|
class FrozenBatchNorm2d(torch.nn.Module):
'\n BatchNorm2d where the batch statistics and the affine parameters are fixed.\n\n Copy-paste from torchvision.misc.ops with added eps before rqsrt,\n without which any other models than torchvision.models.resnet[18,34,50,101]\n produce nans.\n '
def ... |
class BackboneBase(nn.Module):
def __init__(self, backbone: nn.Module, train_backbone: bool, return_interm_layers: bool):
super().__init__()
for (name, parameter) in backbone.named_parameters():
if ((not train_backbone) or (('layer2' not in name) and ('layer3' not in name) and ('layer... |
class Backbone(BackboneBase):
'ResNet backbone with frozen BatchNorm.'
def __init__(self, name: str, train_backbone: bool, return_interm_layers: bool, dilation: bool):
norm_layer = FrozenBatchNorm2d
backbone = getattr(torchvision.models, name)(replace_stride_with_dilation=[False, False, dilat... |
class SwinBackbone(nn.Module):
def __init__(self):
super().__init__()
self.body = get_swinl()
self.features = ['res3', 'res4', 'res5']
self.strides = [8, 16, 32]
self.num_channels = [384, 768, 1536]
def forward(self, tensor_list: NestedTensor):
xs = self.body(... |
class Joiner(nn.Sequential):
def __init__(self, backbone, position_embedding):
super().__init__(backbone, position_embedding)
self.strides = backbone.strides
self.num_channels = backbone.num_channels
def forward(self, tensor_list: NestedTensor):
xs = self[0](tensor_list)
... |
def build_backbone(args):
position_embedding = build_position_encoding(args)
train_backbone = (args.lr_backbone > 0)
return_interm_layers = (args.masks or (args.num_feature_levels > 1))
if ('swin' in args.backbone):
backbone = SwinBackbone()
else:
backbone = Backbone(args.backbone,... |
def get_extensions():
this_dir = os.path.dirname(os.path.abspath(__file__))
extensions_dir = os.path.join(this_dir, 'src')
main_file = glob.glob(os.path.join(extensions_dir, '*.cpp'))
source_cpu = glob.glob(os.path.join(extensions_dir, 'cpu', '*.cpp'))
source_cuda = glob.glob(os.path.join(extensio... |
@torch.no_grad()
def check_forward_equal_with_pytorch_double():
value = (torch.rand(N, S, M, D).cuda() * 0.01)
sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda()
attention_weights = (torch.rand(N, Lq, M, L, P).cuda() + 1e-05)
attention_weights /= attention_weights.sum((- 1), keepdim=True).sum((... |
@torch.no_grad()
def check_forward_equal_with_pytorch_float():
value = (torch.rand(N, S, M, D).cuda() * 0.01)
sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda()
attention_weights = (torch.rand(N, Lq, M, L, P).cuda() + 1e-05)
attention_weights /= attention_weights.sum((- 1), keepdim=True).sum((-... |
def check_gradient_numerical(channels=4, grad_value=True, grad_sampling_loc=True, grad_attn_weight=True):
value = (torch.rand(N, S, M, channels).cuda() * 0.01)
sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda()
attention_weights = (torch.rand(N, Lq, M, L, P).cuda() + 1e-05)
attention_weights /=... |
def parse_args():
'\n Helper function parsing the command line options\n @retval ArgumentParser\n '
parser = ArgumentParser(description='PyTorch distributed training launch helper utilty that will spawn up multiple distributed processes')
parser.add_argument('--nnodes', type=int, default=1, help=... |
def main():
args = parse_args()
dist_world_size = (args.nproc_per_node * args.nnodes)
current_env = os.environ.copy()
current_env['MASTER_ADDR'] = args.master_addr
current_env['MASTER_PORT'] = str(args.master_port)
current_env['WORLD_SIZE'] = str(dist_world_size)
processes = []
for loc... |
def embed(params, data, policy, states, k=100):
if (params['embedding'] == 'a_s'):
embedding = np.concatenate([policy.forward(x, eval=False) for x in states], axis=0)
return embedding
|
def get_experiment(params):
if (params['env_name'] in ['HalfCheetah-v2', 'HalfCheetah-v1']):
params['h_dim'] = 32
params['layers'] = 2
params['sensings'] = 100
params['learning_rate'] = 0.05
params['sigma'] = 0.1
params['steps'] = 1000
elif (params['env_name'] i... |
class Learner(object):
def __init__(self, params):
params['zeros'] = False
self.agents = {i: get_policy(params, (params['seed'] + (1000 * i))) for i in range(params['num_agents'])}
self.timesteps = 0
self.w_reward = 1
self.w_size = 0
self.dists = 0
self.ada... |
def get_policy(params, seed=None):
if seed:
params['seed'] = seed
return FullyConnected(params, params['seed'])
|
class FullyConnected(object):
def __init__(self, params, seed=0):
np.random.seed(seed)
self.layers = params['layers']
self.hidden = {}
self.bias = {}
self.observation_filter = get_filter(params['ob_filter'], shape=(params['ob_dim'],))
self.update_filter = True
... |
class PointEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self):
mujoco_env.MujocoEnv.__init__(self, 'point.xml', 2)
utils.EzPickle.__init__(self)
def step(self, action):
action = np.clip(action, (- 1.0), 1.0)
self.do_simulation(action, self.frame_skip)
next_... |
def select_states(master, params, states):
if (int(params['states'].split('-')[1]) < len(states)):
selected = sample(states, int(params['states'].split('-')[1]))
return selected
else:
return states
|
def reset_ray(master, params):
ray.disconnect()
ray.shutdown()
time.sleep(5)
del os.environ['RAY_USE_NEW_GCS']
ray.init(plasma_directory='/tmp')
os.environ['RAY_USE_NEW_GCS'] = 'True'
flush_policy = ray.experimental.SimpleGcsFlushPolicy(flush_period_secs=0.1)
ray.experimental.set_flush... |
def train(params):
env = gym.make(params['env_name'])
params['ob_dim'] = env.observation_space.shape[0]
params['ac_dim'] = env.action_space.shape[0]
master = Learner(params)
n_eps = 0
n_iter = 0
ts_cumulative = 0
(ts, rollouts, rewards, max_rwds, dists, min_dists, agents, lambdas) = ([... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--env_name', type=str, default='point-v0')
parser.add_argument('--num_agents', '-na', type=int, default=5)
parser.add_argument('--seed', '-sd', type=int, default=0)
parser.add_argument('--max_iter', '-it', type=int, default=2000)
... |
def batched_weighted_sum(weights, vecs, batch_size):
total = 0
num_items_summed = 0
for (batch_weights, batch_vecs) in zip(itergroups(weights, batch_size), itergroups(vecs, batch_size)):
assert (len(batch_weights) == len(batch_vecs) <= batch_size)
total += np.dot(np.asarray(batch_weights, ... |
def itergroups(items, group_size):
assert (group_size >= 1)
group = []
for x in items:
group.append(x)
if (len(group) == group_size):
(yield tuple(group))
del group[:]
if group:
(yield tuple(group))
|
def evaluate(env, params, p):
return p.rollout(env, params['steps'], incl_data=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.