code stringlengths 17 6.64M |
|---|
def _mp_fn(index):
main()
|
def main():
parser = HfArgumentParser((ModelArguments, XFUNDataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data... |
def _mp_fn(index):
main()
|
def parse_xml(path):
tree = ET.parse(path)
img_name = path.split('/')[(- 1)][:(- 4)]
height = tree.findtext('./size/height')
width = tree.findtext('./size/width')
objects = [img_name, width, height]
for obj in tree.findall('object'):
difficult = obj.find('difficult').text
if (d... |
def gen_test_txt(txt_path):
global test_cnt
f = open(txt_path, 'w')
for (i, path) in enumerate(test_path):
img_names = open(path, 'r').readlines()
for img_name in img_names:
img_name = img_name.strip()
xml_path = (((anno_path[i] + '/') + img_name) + '.xml')
... |
def gen_train_txt(txt_path):
global train_cnt
f = open(txt_path, 'w')
for (i, path) in enumerate(trainval_path):
img_names = open(path, 'r').readlines()
for img_name in img_names:
img_name = img_name.strip()
xml_path = (((anno_path[i] + '/') + img_name) + '.xml')
... |
def conv2d(inputs, filters, kernel_size, strides=1):
def _fixed_padding(inputs, kernel_size):
pad_total = (kernel_size - 1)
pad_beg = (pad_total // 2)
pad_end = (pad_total - pad_beg)
padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]], mode='CON... |
def darknet53_body(inputs):
def res_block(inputs, filters):
shortcut = inputs
net = conv2d(inputs, (filters * 1), 1)
net = conv2d(net, (filters * 2), 3)
net = (net + shortcut)
return net
net = conv2d(inputs, 32, 3, strides=1)
net = conv2d(net, 64, 3, strides=2)
... |
def yolo_block(inputs, filters):
net = conv2d(inputs, (filters * 1), 1)
net = conv2d(net, (filters * 2), 3)
net = conv2d(net, (filters * 1), 1)
net = conv2d(net, (filters * 2), 3)
net = conv2d(net, (filters * 1), 1)
route = net
net = conv2d(net, (filters * 2), 3)
return (route, net)
|
def upsample_layer(inputs, out_shape):
(new_height, new_width) = (out_shape[1], out_shape[2])
inputs = tf.image.resize_nearest_neighbor(inputs, (new_height, new_width), name='upsampled')
return inputs
|
class MeshPly():
def __init__(self, filename, color=[0.0, 0.0, 0.0]):
f = open(filename, 'r')
self.vertices = []
self.colors = []
self.indices = []
self.normals = []
vertex_mode = False
face_mode = False
nb_vertices = 0
nb_faces = 0
... |
def get_color_table(class_num, seed=2):
random.seed(seed)
color_table = {}
for i in range(class_num):
color_table[i] = [random.randint(0, 255) for _ in range(3)]
return color_table
|
def plot_one_box(img, coord, label=None, color=None, line_thickness=None):
'\n coord: [x_min, y_min, x_max, y_max] format coordinates.\n img: img to plot on.\n label: str. The label name.\n color: int. color index.\n line_thickness: int. rectangle line thickness.\n '
tl = (line_thickness or ... |
def draw_demo_img(img, projectpts, color=(0, 255, 0)):
vertices = []
for i in range(9):
x = projectpts[i][0]
y = projectpts[i][1]
coordinates = (int(x), int(y))
vertices.append(coordinates)
cv2.circle(img, coordinates, 1, (0, 255, 255), (- 1))
cv2.line(img, vertices... |
def draw_demo_img_corners(img, projectpts, color=(0, 255, 0), nV=9, thickness=2):
vertices = []
for i in range(nV):
x = projectpts[i][0]
y = projectpts[i][1]
coordinates = (int(x), int(y))
vertices.append(coordinates)
cv2.circle(img, coordinates, 2, color, (- 1))
cv... |
def hist(latencies, labels=[], title='', filename='hist', bins=500, xlabel='Latency (cycles)'):
plt.figure(figsize=(10, 5))
for i in range(0, len(labels)):
d = latencies[i]
labels[i] += f' (μ={int(np.mean(d))}, σ={int(np.std(d))})'
plt.hist(latencies, label=labels, bins=bins, histtype='ste... |
def reject_outliers(data, m=2):
stdev = np.std(data)
mean = np.mean(data)
mask_min = (mean - (stdev * m))
mask_max = (mean + (stdev * m))
outliers = [d for d in data if ((d < mask_min) or (d > mask_max))]
print(f'Warning: removing {len(outliers)} outliers:')
print(outliers)
return [d f... |
def load_data(file, col):
print(f".. loading data from '{file}'")
d = pd.read_csv(file)
data = d[col]
print('---------------------------------------------------------------------------')
s = pd.Series(data)
print(s.describe())
print(f'med {int(np.median(data))}')
print('----------... |
def hist(latencies, labels=[], title='', filename='hist', xlabel='Latency (cycles)', legend_loc='best'):
plt.figure(figsize=(10, 5))
for i in range(0, len(labels)):
d = latencies[i]
labels[i] += f' (μ={int(np.mean(d))}, σ={int(np.std(d))})'
plt.hist(latencies, label=labels, bins=500, histt... |
def reject_outliers(data, m=3):
stdev = np.std(data)
mean = np.mean(data)
mask_min = (mean - (stdev * m))
mask_max = (mean + (stdev * m))
outliers = [d for d in data if ((d < mask_min) or (d > mask_max))]
print(f'Warning: removing {len(outliers)} outliers:')
print(outliers)
return [d f... |
def reject_syscall_inc_outliers(data):
for i in range(0, len(data)):
if (data[i] > 1000000):
print(f'Warning: removing outlier: {data[i]}')
data[i] = 0
return data
|
def load_data(file, col):
print(f".. loading data from '{file}'")
d = pd.read_csv(file)
data = d[col]
if ((file == 'logs/icx/deadline_results_syscall.txt') and (col == 'inc_count')):
data = reject_syscall_inc_outliers(data)
print('-----------------------------------------------------------... |
def get_sym_addr(name, symtab):
return symtab.get_symbol_by_name(name)[0]['st_value']
|
class ToTensor(object):
'Convert ndarrays in sample to Tensors.'
def __call__(self, sample):
(image, text, label) = (sample['image'], sample['text'], sample['label'])
return {'image': torch.from_numpy(image.astype(np.float32)), 'text': text, 'label': torch.from_numpy(label.astype(np.float32))... |
class Normalize(object):
'Input image cleaning.'
def __init__(self, mean_vector, std_devs):
(self.mean_vector, self.std_devs) = (mean_vector, std_devs)
def __call__(self, sample):
image = sample['image']
return {'image': self._normalize(image, self.mean_vector, self.std_devs), 't... |
class RandomModalityMuting(object):
'Randomly turn a mode off.'
def __init__(self, p_muting=0.1):
self.p_muting = p_muting
def __call_(self, sample):
rval = random.random()
im = sample['image']
au = sample['text']
if (rval <= self.p_muting):
vval = ran... |
class MM_IMDB(Dataset):
def __init__(self, root_dir='', transform=None, stage='train', feat_dim=100, average_text=False):
'\n Args:\n root_dir (string): Directory where data is.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n... |
def collate_imdb(list_samples):
global fdim
max_text_len = 0
for sample in list_samples:
L = len(sample['text'])
if (max_text_len < L):
max_text_len = L
list_images = (len(list_samples) * [None])
list_text = (len(list_samples) * [None])
list_labels = (len(list_sampl... |
def parse_args():
parser = argparse.ArgumentParser(description='Modality optimization.')
parser.add_argument('--checkpointdir', type=str, help='output base dir', default='/home/juanma/Documents/Checkpoints/NTU/')
parser.add_argument('--datadir', type=str, help='data directory', default='/home/juanma/Docum... |
def get_dataloaders(args):
import torchvision.transforms as transforms
from datasets import ntu as d
from torch.utils.data import DataLoader
transformer_val = transforms.Compose([d.NormalizeLen(args.vid_len), d.ToTensor()])
transformer_tra = transforms.Compose([d.AugCrop(), d.NormalizeLen(args.vid... |
def train_model(rmode, configuration, dataloaders, args, device):
dataset_sizes = {x: len(dataloaders[x].dataset) for x in ['train', 'test', 'dev']}
if (args.test_cp == ''):
num_batches_per_epoch = (dataset_sizes['train'] / args.batchsize)
criteria = [torch.nn.CrossEntropyLoss(), torch.nn.Cros... |
def parse_args():
parser = argparse.ArgumentParser(description='Modality optimization.')
parser.add_argument('--checkpointdir', type=str, help='output base dir', default='/home/juanma/Documents/Checkpoints/NTU/')
parser.add_argument('--datadir', type=str, help='data directory', default='/home/juanma/Docum... |
def inflated_resnet(**kwargs):
list_block = [Bottleneck3D, Bottleneck3D, Bottleneck3D, Bottleneck3D]
list_layers = [3, 4, 6, 3]
model = ResNet(list_block, list_layers, **kwargs)
load_pretrained_2D_weights('resnet50', model, inflation='center')
return model
|
class Bottleneck3D(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1):
super(Bottleneck3D, self).__init__()
self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm3d(planes)
self.conv2 = nn.... |
class ResNet(nn.Module):
def __init__(self, list_block, layers, **kwargs):
self.inplanes = 64
self.input_dim = 4
super(ResNet, self).__init__()
self._first_conv()
self.relu = nn.ReLU(inplace=True)
self.list_channels = [64, 128, 256, 512]
self.layer1 = self.... |
def transform_input(x, dim, T=12):
diff = (len(x.size()) - dim)
if (diff > 0):
(B, C, T, W, H) = x.size()
x = x.transpose(1, 2)
x = x.contiguous()
x = x.view((- 1), C, W, H)
elif (diff < 0):
(_, C, W, H) = x.size()
x = x.view((- 1), T, C, W, H)
x = x... |
class LRCosineAnnealingScheduler():
def __init__(self, eta_max, eta_min, Ti, Tmultiplier, num_batches_per_epoch):
self.eta_min = eta_min
self.eta_max = eta_max
self.Ti = Ti
self.Tcur = 0.0
self.nbpe = num_batches_per_epoch
self.iteration_counter = 0.0
self.... |
class FixedScheduler():
def __init__(self, lr):
self.lr = lr
def step(self):
return self.lr
def update_optimizer(self, optimizer):
state_dict = optimizer.state_dict()
for param_group in state_dict['param_groups']:
param_group['lr'] = self.lr
optimizer... |
class activ(nn.Module):
def __init__(self, args):
super(activ, self).__init__()
self.activation = args.activation
if (args.activation == 'LeakyReLU'):
self.act = torch.nn.LeakyReLU()
elif (args.activation == 'ELU'):
self.act = torch.nn.ELU()
elif (a... |
class SimpleRecurrentSurrogate(nn.Module):
def __init__(self, num_hidden=100, number_input_feats=3, size_ebedding=100):
super(SimpleRecurrentSurrogate, self).__init__()
self.num_hidden = num_hidden
self.embedding = nn.Sequential(nn.Linear(number_input_feats, size_ebedding), nn.Sigmoid())
... |
class SurrogateDataloader():
def __init__(self):
self._dict_data = {}
def add_datum(self, datum_conf, datum_acc):
seq_len = len(datum_conf)
datum_hash = datum_conf.data.tobytes()
if (seq_len in self._dict_data):
if (datum_hash in self._dict_data[seq_len]):
... |
def train_simple_surrogate(model, criterion, optimizer, data_tensors, num_epochs, device):
for epoch in range(num_epochs):
model.train(True)
for batch in range(len(data_tensors[0])):
(inputs, outputs) = (data_tensors[0][batch], data_tensors[1][batch])
inputs = inputs.to(dev... |
def train_avmnist_track_acc(model, criteria, optimizer, scheduler, dataloaders, dataset_sizes, device=None, num_epochs=200, verbose=False, multitask=False):
best_model_sd = copy.deepcopy(model.state_dict())
best_acc = 0
for epoch in range(num_epochs):
for phase in ['train', 'dev']:
if ... |
def test_avmnist_track_acc(model, dataloaders, dataset_sizes, device=None, multitask=False):
model.train(False)
phase = 'test'
running_corrects = 0
for data in dataloaders[phase]:
(rgb, snd, label) = (data['image'], data['audio'], data['label'])
rgb = rgb.to(device)
snd = snd.t... |
def train_cifar_track_acc(model, criterion, optimizer, scheduler, dataloaders, dataset_sizes, device, num_epochs=200, verbose=False, use_intermediate=False):
best_model_sd = copy.deepcopy(model.state_dict())
best_error = 1e+100
criterion2 = torch.nn.CrossEntropyLoss()
for epoch in range(num_epochs):
... |
def test_cifar_track_acc(model, dataloaders, dataset_sizes, device):
phase = 'test'
model.train(False)
running_corrects = 0
for data in dataloaders[phase]:
(rgb, gt_label) = (data[0], data[1])
rgb = rgb.to(device)
gt_label = gt_label.to(device)
(output, _) = model(rgb)
... |
def train_mmimdb_track_f1(model, criterion, optimizer, scheduler, dataloaders, dataset_sizes, device=None, num_epochs=200, verbose=False, init_f1=0.0, th_fscore=0.3):
best_model_sd = copy.deepcopy(model.state_dict())
best_f1 = init_f1
failsafe = True
cont_overloop = 0
while failsafe:
for e... |
def train_ntu_track_acc(model, criteria, optimizer, scheduler, dataloaders, dataset_sizes, device=None, num_epochs=200, verbose=False, multitask=False):
best_model_sd = copy.deepcopy(model.state_dict())
best_acc = 0
for epoch in range(num_epochs):
for phase in ['train', 'dev']:
if (pha... |
def test_ntu_track_acc(model, dataloaders, dataset_sizes, device=None, multitask=False):
model.train(False)
phase = 'test'
running_corrects = 0
for data in dataloaders[phase]:
(rgb, ske, label) = (data['rgb'], data['ske'], data['label'])
rgb = rgb.to(device)
ske = ske.to(device... |
class ModelSearcher():
def __init__(self, args):
self.args = args
def search(self):
pass
def _epnas(self, model_type, surrogate_dict, dataloaders, dataset_searchmethods, device):
surrogate = surrogate_dict['model']
s_crite = surrogate_dict['criterion']
s_data = s... |
class AVMNISTSearcher(ModelSearcher):
def __init__(self, args, device):
super(AVMNISTSearcher, self).__init__(args)
self.device = device
transformer = transforms.Compose([avmnist_data.ToTensor(), avmnist_data.Normalize((0.1307,), (0.3081,))])
dataset_training = avmnist_data.AVMnis... |
class NTUSearcher(ModelSearcher):
def __init__(self, args, device):
super(NTUSearcher, self).__init__(args)
self.device = device
transformer_val = transforms.Compose([ntu_data.NormalizeLen(args.vid_len), ntu_data.ToTensor()])
transformer_tra = transforms.Compose([ntu_data.AugCrop(... |
class CifarSearcher(ModelSearcher):
def __init__(self, args, device):
super(CifarSearcher, self).__init__(args)
self.device = device
train_indices = list(range(0, 45000))
valid_indices = list(range(45000, 50000))
transformer_train = transforms.Compose([transforms.RandomCro... |
def update_from_loss_module(monitors, output_dict, loss_update):
(tmp_monitors, tmp_outputs) = loss_update
monitors.update(tmp_monitors)
output_dict.update(tmp_outputs)
|
class Model(LeftModel):
def __init__(self, parsed_train_path, parsed_test_path, output_vocab):
self.parsed_train_path = parsed_train_path
self.parsed_test_path = parsed_test_path
logger.critical(('Train parsing: ' + self.parsed_train_path))
logger.critical(('Test parsing: ' + self... |
def make_model(parsed_train_path, parsed_test_path, output_vocab):
return Model(parsed_train_path, parsed_test_path, output_vocab)
|
def make_dataset(mode, scenes_json, questions_json, image_root, output_vocab_json):
return make_custom_transfer_dataset(scenes_json, questions_json, image_root=image_root, output_vocab_json=output_vocab_json, query_list_key=g_query_list_keys[mode], custom_fields=[], incl_scene=False)
|
def parse_arguments(notebook_options=None):
"Parse the arguments for the training (or test) execution of a ReferIt3D net.\n :param notebook_options: (list) e.g., ['--max-distractors', '100'] to give/parse arguments from inside a jupyter notebook.\n :return:\n "
parser = argparse.ArgumentParser(descri... |
def read_saved_args(config_file, override_args=None, verbose=True):
"\n :param config_file:\n :param override_args: dict e.g., {'gpu': '0'}\n :param verbose:\n :return:\n "
parser = ArgumentParser()
args = parser.parse_args([])
with open(config_file, 'r') as f_in:
args.__dict__ ... |
def apply_configs(args, config_dict):
for (k, v) in config_dict.items():
setattr(args, k, v)
|
def str2bool(v):
'\n Boolean values for argparse\n '
if isinstance(v, bool):
return v
if (v.lower() in ('yes', 'true', 't', 'y', '1')):
return True
elif (v.lower() in ('no', 'false', 'f', 'n', '0')):
return False
else:
raise argparse.ArgumentTypeError('Boolean... |
def create_dir(dir_path):
"\n Creates a directory (or nested directories) if they don't exist.\n "
if (not osp.exists(dir_path)):
os.makedirs(dir_path)
return dir_path
|
def unpickle_data(file_name, python2_to_3=False):
'\n Restore data previously saved with pickle_data().\n :param file_name: file holding the pickled data.\n :param python2_to_3: (boolean), if True, pickle happened under python2x, unpickling under python3x.\n :return: an generator over the un-pickled i... |
def read_lines(file_name):
trimmed_lines = []
with open(file_name) as fin:
for line in fin:
trimmed_lines.append(line.rstrip())
return trimmed_lines
|
def decode_stimulus_string(s):
'\n Split into scene_id, instance_label, # objects, target object id,\n distractors object id.\n :param s: the stimulus string\n '
if (len(s.split('-', maxsplit=4)) == 4):
(scene_id, instance_label, n_objects, target_id) = s.split('-', maxsplit=4)
dis... |
def objects_counter_percentile(scan_ids, all_scans, prc):
all_obs_len = list()
for scan_id in all_scans:
if (scan_id in scan_ids):
all_obs_len.append(len(all_scans[scan_id].three_d_objects))
return np.percentile(all_obs_len, prc)
|
def mean_color(scan_ids, all_scans):
mean_rgb = np.zeros((1, 3), dtype=np.float32)
n_points = 0
for scan_id in scan_ids:
color = all_scans[scan_id].color
mean_rgb += np.sum(color, axis=0)
n_points += len(color)
mean_rgb /= n_points
return mean_rgb
|
def scannet_official_train_val(pre_fix, valid_views=None, verbose=True):
"\n :param valid_views: None or list like ['00', '01']\n :return:\n "
train_split = osp.join(pre_fix, 'scannetv2_train.txt')
train_split = read_lines(train_split)
test_split = osp.join(pre_fix, 'scannetv2_val.txt')
t... |
def load_scan_related_data(pre_fix, preprocessed_scannet_file, verbose=True, add_pad=True):
(_, all_scans) = unpickle_data(preprocessed_scannet_file)
if verbose:
print('Loaded in RAM {} scans'.format(len(all_scans)))
instance_labels = set()
for scan in all_scans:
idx = np.array([o.obje... |
def load_referential_data(args, referit_csv, scans_split):
'\n :param args:\n :param referit_csv:\n :param scans_split:\n :return:\n '
referit_data_train = pd.read_csv(referit_csv)
referit_data_test = pd.read_csv(referit_csv.replace('train', 'test'))
referit_data = pd.concat([referit_da... |
def compute_auxiliary_data(referit_data, all_scans, args):
'Given a train-split compute useful quantities like mean-rgb, a word-vocabulary.\n :param referit_data: pandas Dataframe, as returned from load_referential_data()\n :param all_scans:\n :param args:\n :return:\n '
if args.vocab_file:
... |
def trim_scans_per_referit3d_data(referit_data, scans):
in_r3d = referit_data.scan_id.unique()
to_drop = []
for k in scans:
if (k not in in_r3d):
to_drop.append(k)
for k in to_drop:
del scans[k]
print('Dropped {} scans to reduce mem-foot-print.'.format(len(to_drop)))
... |
class Vocabulary(object):
'Simple vocabulary wrapper.'
def __init__(self, special_symbols=None):
self.word2idx = {}
self.idx2word = {}
self.idx = 0
self.special_symbols = None
self.intialize_special_symbols(special_symbols)
def intialize_special_symbols(self, spec... |
def build_vocab(token_list, min_word_freq):
'Build a simple vocabulary wrapper.'
counter = Counter()
for tokens in token_list:
counter.update(tokens)
words = [word for (word, cnt) in counter.items() if (cnt >= min_word_freq)]
vocab = Vocabulary()
for (i, word) in enumerate(words):
... |
def create_bare_domain() -> FunctionDomain:
domain = FunctionDomain('Left')
domain.define_type(ObjectType('Object'))
domain.define_type(ObjectType('Object_Set'))
domain.define_type(ObjectType('Action'))
domain.define_function(Function('equal', FunctionTyping[BOOL](INT64, INT64)))
domain.define... |
def create_default_parser(domain: FunctionDomain) -> NCGeneralizedFOLPythonParser:
parser = NCGeneralizedFOLPythonParser(domain, inplace_definition=True, inplace_polymorphic_function=True, inplace_definition_type=True)
return parser
|
def create_domain_from_parsing(codes: Dict[(str, List[str])]) -> FunctionDomain:
domain = create_bare_domain()
parser = create_default_parser(domain)
for (prompt, codes) in jacinle.tqdm_gofor(codes, desc='Creating domain from parsings'):
if isinstance(codes, str):
codes = [codes]
... |
def read_concepts_v1(domain: FunctionDomain) -> Tuple[(List[str], List[str], List[str])]:
ds_functions = list(domain.functions.keys())
(attribute_concepts, relational_concepts, multi_relational_concepts) = ([], [], [])
for f in ds_functions:
if ('_Object_Object_Object' in f):
multi_rel... |
def get_arity(function: Function) -> Optional[int]:
ftype = function.ftype
if (ftype.return_type != BOOL):
return None
for arg_type in ftype.argument_types:
if (arg_type.typename not in ['Object', 'Object_Set', 'Action']):
return None
return len(ftype.argument_types)
|
def read_concepts_v2(domain: FunctionDomain) -> Tuple[(List[str], List[str], List[str])]:
functions = {1: list(), 2: list(), 3: list()}
for (name, function) in domain.functions.items():
arity = get_arity(function)
if ((arity is not None) and (1 <= arity <= 3)):
functions[arity].app... |
def read_description_categories(domain: FunctionDomain) -> Tuple[List[str]]:
output = list()
for (name, t) in domain.types.items():
if (t.typename not in ('Object', 'Object_Set', 'Action')):
output.append(name)
return output
|
def make_domain(parsed_test_path: str) -> FunctionDomain:
codes = io.load_pkl(parsed_test_path)
domain = create_domain_from_parsing(codes)
return domain
|
class ExecutionTraceGetter(object):
def __init__(self, trace_obj):
self.trace_obj = trace_obj
def get(self) -> List[Tuple[(E.Expression, TensorValue)]]:
return self.trace_obj
|
def _get_self_mask(m):
self_mask = torch.eye(m.size((- 1)), dtype=m.dtype, device=m.device)
return self_mask
|
def _do_apply_self_mask(m):
if (not g_options.use_self_mask):
return m
self_mask = _get_self_mask(m)
return ((m * (1 - self_mask)) + ((- 10) * self_mask))
|
class NCGeneralizedFOLExecutor(FunctionDomainExecutor):
def __init__(self, domain: FunctionDomain, parser: Optional[ParserBase]=None, allow_shift_grounding=False):
super().__init__(domain, parser)
self.allow_shift_grounding = allow_shift_grounding
self.variable_stack = dict()
self... |
def expand_argument_values(argument_values: Sequence[TensorValue]) -> List[TensorValue]:
'Expand a list of argument values to the same batch size.\n Args:\n argument_values: a list of argument values.\n Returns:\n the result list of argument values. All return values will have the same batch s... |
class NCGeneralizedFOLPythonParser(FOLPythonParser):
def _is_quantification_expression_name(self, name: str) -> bool:
return (name in ['exists', 'forall', 'all', 'iota', 'describe', 'execute', 'point', 'count', 'view'])
def _parse_quantification_expression_inner(self, function_name: str, var: Variab... |
class LeftModel(nn.Module):
@staticmethod
@def_configs_func
def _def_configs():
configs.model.domain = 'referit3d'
configs.model.scene_graph = '3d'
configs.model.concept_embedding = 'vse'
configs.model.sg_dims = [None, 128, 128, 128]
configs.model.vse_hidden_dims =... |
class ExecutionFailed(Exception):
pass
|
class AGCNGraph():
def __init__(self, labeling_mode='spatial'):
self.A = self.get_adjacency_matrix(labeling_mode)
self.num_node = num_node
self.self_link = self_link
self.inward = inward
self.outward = outward
self.neighbor = neighbor
def get_adjacency_matrix(... |
def edge2mat(link, num_node):
A = np.zeros((num_node, num_node))
for (i, j) in link:
A[(j, i)] = 1
return A
|
def normalize_digraph(A):
Dl = np.sum(A, 0)
(h, w) = A.shape
Dn = np.zeros((w, w))
for i in range(w):
if (Dl[i] > 0):
Dn[(i, i)] = (Dl[i] ** (- 1))
AD = np.dot(A, Dn)
return AD
|
def get_spatial_graph(num_node, self_link, inward, outward):
I = edge2mat(self_link, num_node)
In = normalize_digraph(edge2mat(inward, num_node))
Out = normalize_digraph(edge2mat(outward, num_node))
A = np.stack((I, In, Out))
return A
|
class SigmoidCrossEntropy(nn.Module):
def __init__(self, one_hot=False):
super().__init__()
self.one_hot = one_hot
self.bce = nn.BCEWithLogitsLoss(reduction='none')
def forward(self, input, target):
if (not self.one_hot):
target = jactorch.one_hot_nd(target, input... |
class MultilabelSigmoidCrossEntropy(nn.Module):
def __init__(self, one_hot=False):
super().__init__()
self.one_hot = one_hot
self.bce = nn.BCEWithLogitsLoss(reduction='none')
def forward(self, input, labels):
if (type(labels) in (tuple, list)):
labels = torch.tens... |
class MultilabelSigmoidCrossEntropyAndAccuracy(nn.Module):
def __init__(self, one_hot=False, softmax=False, compute_loss=True):
super().__init__()
self.one_hot = one_hot
self.softmax = softmax
self.compute_loss = compute_loss
if self.softmax:
self.bce = nn.BCEL... |
class MultitaskLossBase(nn.Module):
def __init__(self):
super().__init__()
self._sigmoid_xent_loss = SigmoidCrossEntropy()
self._multilabel_sigmoid_xent_loss = MultilabelSigmoidCrossEntropy()
self._batched_xent_loss = nn.CrossEntropyLoss()
def _mse_loss(self, pred, label):
... |
class _PointnetSAModuleBase(nn.Module):
def __init__(self):
super().__init__()
self.npoint = None
self.groupers = None
self.mlps = None
def forward(self, xyz: torch.Tensor, features: torch.Tensor=None) -> (torch.Tensor, torch.Tensor):
"\n Parameters\n --... |
class PointnetSAModuleMSG(_PointnetSAModuleBase):
'Pointnet set abstrction layer with multiscale grouping\n\n Parameters\n ----------\n npoint : int\n Number of features\n radii : list of float32\n list of radii to group with\n nsamples : list of int32\n Number of samples in ea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.