code stringlengths 101 5.91M |
|---|
def test(loader, net):
net.eval()
test_loss = 0
correct = 0
cm = 0
N = len(loader.dataset)
for (idx, (data, target)) in enumerate(loader):
data = make_variable(data, requires_grad=False)
target = make_variable(target, requires_grad=False)
score = net(data)
test_lo... |
def extract_layers_from_state_dict(state_dict: dict, layer_names: List[str]):
new_state_dict = {}
for layer_name in layer_names:
if (type(layer_name) == tuple):
old_layer_name = layer_name[0]
new_layer_name = layer_name[1]
else:
old_layer_name = new_layer_name... |
def test__get_cnn_features_batch_nondefault_models():
cnn = CNN(model_config=CustomModel(model=EfficientNet(), transform=EfficientNet.transform, name=EfficientNet.name))
result = cnn._get_cnn_features_batch(TEST_IMAGE_DIR)
for i in result.values():
assert isinstance(i, np.ndarray)
assert (i.... |
def _parse_action_probs_from_action_info(action, action_info, legal_actions_list, total_num_discrete_actions):
action_probs = None
for key in ['policy_targets', 'action_probs']:
if (key in action_info):
action_probs = action_info[key]
break
if (action_probs is None):
... |
def seperate_file(dir_to_read, name, to_write_dir):
name_token = name.split('.')[0]
(article, abstract) = get_art_abs(os.path.join(dir_to_read, name))
if ((len(article) < 5) or (len(abstract) < 5)):
print('Discard: {}'.format(name))
return None
with open(os.path.join(to_write_dir, (name_... |
def load_dataset(name, cfg_path=None, vis_path=None, data_type=None):
if (cfg_path is None):
cfg = None
else:
cfg = load_dataset_config(cfg_path)
try:
builder = registry.get_builder_class(name)(cfg)
except TypeError:
print((f'''Dataset {name} not found. Available datasets... |
class ConcatDataset(torchConcatDataset):
def __init__(self, datasets):
super(ConcatDataset, self).__init__(datasets)
if hasattr(self.datasets[0], 'input_dim'):
self._input_dim = self.datasets[0].input_dim
self.input_dim = self.datasets[0].input_dim
def pull_item(self, idx... |
def _concat_dataset(cfg, default_args=None):
ann_files = cfg['ann_file']
img_prefixes = cfg.get('img_prefix', None)
seg_prefixes = cfg.get('seg_prefixes', None)
proposal_files = cfg.get('proposal_file', None)
datasets = []
num_dset = len(ann_files)
for i in range(num_dset):
data_cfg ... |
class Agent(object):
def __init__(self, model, env, args, state, device):
self.model = model
self.env = env
self.num_agents = env.n
self.state_dim = env.observation_space[0].shape[0]
if ('continuous' in args.model):
self.continuous = True
self.action_h... |
class ExampleModel(nn.Module):
def __init__(self):
super().__init__()
self.conv2d = nn.Conv2d(3, 8, 3)
def forward(self, imgs):
x = torch.randn((1, *imgs))
return self.conv2d(x) |
class StructuredSubnetConv2d(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=False, sparsity=0.5, trainable=True):
super(self.__class__, self).__init__(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding... |
class DenseNet(nn.Module):
def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, remove_linear=False):
super(DenseNet, self).__init__()
self.features = nn.Sequential(OrderedDict([('conv0', nn.Conv2d(3, num_init_features, kern... |
def tsdataset_to_dataloader(data, batch_size, lookback, horizon, num_processes):
if num_processes:
if ((batch_size % num_processes) != 0):
warnings.warn("'batch_size' cannot be divided with no remainder by 'self.num_processes'. We got 'batch_size' = {} and 'self.num_processes' = {}".format(batch... |
def qualification_loss(x_minus, x_plus, y_minus, y_plus, a, b, c, confidence=(- 0.1)):
loss1 = ts.tanh_lower(torch.sigmoid(y_minus), a, ((b * y_minus) + c), x_minus, (x_plus * 0), plot=False, num=0)
valid = (loss1 <= 0)
loss1 = torch.clamp(loss1, min=confidence)
loss2 = ts.tanh_lower(torch.sigmoid(y_plu... |
def slice_nested_dict(dict_or_array, start, stop):
if isinstance(dict_or_array, dict):
return {k: slice_nested_dict(v, start, stop) for (k, v) in dict_or_array.items()}
else:
return dict_or_array[start:stop] |
def apex_layernorm(ln_module, input_):
if apex_is_installed:
return apex.normalization.fused_layer_norm.FusedLayerNormAffineFunction.apply(input_, ln_module.weight, ln_module.bias, ln_module.normalized_shape, ln_module.eps)
else:
return ln_module(input_) |
('connect')
def connect():
mturk_info = mturk_params(request.args)
if (mturk_info is None):
mturk_info = {}
LOG.info('%s connected | mturk %s', request.sid, mturk_info)
assert (request.sid not in clients), f'Client {request.sid} already connected?'
io.emit('setup', {'sound': url_for('static'... |
def get_imagenet_labels():
path = get_imagenet_path()
dataset = datasets.ImageNet(path, split='val', transform='none')
classes_extended = dataset.classes
labels = []
for a in classes_extended:
labels.append(a[0])
return labels |
class EmptyLabel(ItemBase):
def __init__(self):
(self.obj, self.data) = (0, 0)
def __str__(self):
return ''
def __hash__(self):
return hash(str(self)) |
def resnet50Sem(cfg=None, pretrained_path=None, **kwargs):
if (cfg['resnet'] == 101):
model = ResNetSemShare4(Bottleneck, [3, 4, 23, 3])
print('Encoder: resnet101')
else:
model = ResNetSemShare4(Bottleneck, [3, 4, 6, 3])
print('Encoder: resnet50')
if (cfg['resnet'] == 101):
... |
def zscore_from_cb(cb_min, cb_max, confidence=0.95, distrib='norm'):
if (distrib == 'norm'):
quantile = norm.ppf((1 - ((1 - confidence) / 2)))
beta_hat = ((cb_min + cb_max) / 2)
zscore = (((beta_hat / (cb_max - cb_min)) * 2) * quantile)
return zscore |
class DataBatch():
def __init__(self, mxnet_module):
self._data = []
self._label = []
self.mxnet_module = mxnet_module
def append_data(self, new_data):
self._data.append(self.__as_ndarray(new_data))
def append_label(self, new_label):
self._label.append(self.__as_ndarr... |
class CloudpickleWrapper(object):
def __init__(self, x):
self.x = x
def __call__(self, *args, **kwargs):
return self.x(*args, **kwargs)
def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.x)
def __setstate__(self, ob):
import pickle
se... |
def UpWind3dRHI(dx, coe, u, spatialscheme):
rhi1 = _UpWind1dRHI(dx, [0, coe[(0, 0, 1)], coe[(0, 0, 2)]], u, spatialscheme, axis=(- 1), mode=mode)
rhi2 = _UpWind1dRHI(dx, [0, coe[(0, 1, 0)], coe[(0, 2, 0)]], u, spatialscheme, axis=(- 2), mode=mode)
rhi3 = _UpWind1dRHI(dx, [0, coe[(1, 0, 0)], coe[(2, 0, 0)]],... |
def fix_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
np.random.seed(seed)
random.seed(seed) |
def attach_multitask_transform_head(core_model, output_tasks, optimizer, with_har_head=False, har_output_shape=None, num_units_har=1024, model_name='multitask_transform'):
inputs = tf.keras.Input(shape=core_model.input.shape[1:], name='input')
intermediate_x = core_model(inputs)
outputs = []
losses = [t... |
class ParallelTrainer(LearnerCallback):
_order = (- 20)
def on_train_begin(self, **kwargs):
self.learn.model = DataParallel(self.learn.model)
def on_train_end(self, **kwargs):
self.learn.model = self.learn.model.module |
class MemorySeCo(nn.Module):
def __init__(self, feature_dim, queue_size, temperature=0.1, temperature_intra=0.1):
super(MemorySeCo, self).__init__()
self.queue_size = queue_size
self.temperature = temperature
self.temperature_intra = temperature_intra
self.index = 0
s... |
def read_pedestrian(filename):
with open(filename) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
track_dict = dict()
track_id = None
for (i, row) in enumerate(list(csv_reader)):
if (i == 0):
assert (row[KeyEnum.track_id] == Key.track_id)
... |
def associate(first_list, second_list, max_offset):
first_keys = list(first_list)
second_keys = list(second_list)
potential_matches = [((b - a), a, b) for a in first_keys for b in second_keys if ((b - a) < max_offset)]
potential_matches.sort(reverse=True)
matches = []
for (diff, a, b) in potenti... |
def build_optimizers(opt_config, runner):
if (not opt_config):
return
assert isinstance(opt_config, dict)
for (name, config) in opt_config.items():
if ((not name) or (not config)):
continue
if (name in runner.optimizers):
raise AttributeError(f'Optimizer `{nam... |
_grad()
def inference_entropy_estimation(model, x, index_slide=0, index_quantize=[0, 0, 0, 0]):
x = x.unsqueeze(0)
start = time.time()
out_net = model.forward(x, index_slide, index_quantize, get_y_hat=True)
elapsed_time = (time.time() - start)
num_pixels = ((x.size(0) * x.size(2)) * x.size(3))
e... |
class FeatureFusionNetwork(nn.Module):
def __init__(self, d_model=512, nhead=8, num_featurefusion_layers=4, dim_feedforward=2048, dropout=0.1, activation='relu'):
super().__init__()
featurefusion_layer = FeatureFusionLayer(d_model, nhead, dim_feedforward, dropout, activation)
self.encoder = ... |
class FastChatAgent(AgentClient):
def __init__(self, model_name, controller_address=None, worker_address=None, temperature=0, max_new_tokens=32, top_p=0, prompter=None, args=None, **kwargs) -> None:
if ((controller_address is None) and (worker_address is None)):
raise ValueError('Either controll... |
class EuroSATRGBDataModule(BaseDataModule):
def __init__(self, root: str='.data/eurosat-rgb', transform: T.Compose=T.Compose([T.ToTensor()]), *args, **kwargs):
super().__init__(*args, **kwargs)
self.root = root
self.transform = transform
def setup(self, stage: Optional[str]=None):
... |
_REGISTRY.register()
def build_resnet_bifpn_backbone(cfg, input_shape: ShapeSpec):
bottom_up = build_resnet_backbone(cfg, input_shape)
in_features = cfg.MODEL.FPN.IN_FEATURES
backbone = BiFPN(cfg=cfg, bottom_up=bottom_up, in_features=in_features, out_channels=cfg.MODEL.BIFPN.OUT_CHANNELS, norm=cfg.MODEL.BIF... |
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('', ':6.2f')
top5 = AverageMeter('', ':6.2f')
progress = ProgressMeter(len(train_loade... |
def _recon_lcs(x, y):
(i, j) = (len(x), len(y))
table = _lcs(x, y)
if (table[(i, j)] == 0):
return []
lcs = []
while 1:
if ((i == 0) or (j == 0)):
break
elif (x[(i - 1)] == y[(j - 1)]):
lcs = ([(x[(i - 1)], (i - 1))] + lcs)
i = (i - 1)
... |
def sepreresnetbc26b(**kwargs):
return get_sepreresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name='sepreresnetbc26b', **kwargs) |
def flow_output_evaluation_in_pandas(output_dict):
processed_dict = {}
pandas_dict = {}
for key in output_dict.keys():
val = output_dict[key]
if isinstance(val, float):
val = '{:.4f}'.format(val)
if ('metric_flow' in key):
flow_id = key.split('/')[0]
... |
def test_single_task_data_aggregation(processed_data: Dict[(str, Dict[(str, Any)])]) -> None:
task_return_ci_data = get_and_aggregate_data_single_task(processed_data=processed_data, metric_name='return', metrics_to_normalize=['return'], environment_name='env_1', task_name='task_1')
del task_return_ci_data['extr... |
def check_isfile(path):
isfile = osp.isfile(path)
if (not isfile):
print("=> Warning: no file found at '{}' (ignored)".format(path))
return isfile |
class FrameNetProcessor():
def __init__(self, frame_path=None, element_path=None, bert_model='bert-base-cased', max_length=256):
self.frame_vocabulary = Vocabulary.load(frame_path)
self.element_vocabulary = Vocabulary.load(element_path)
self.tokenizer = BertTokenizer.from_pretrained(bert_mod... |
class planarDissipativeForceFromFullDissipativeForce(planarDissipativeForce):
def __init__(self, Pot):
planarDissipativeForce.__init__(self, amp=1.0, ro=Pot._ro, vo=Pot._vo)
self._roSet = Pot._roSet
self._voSet = Pot._voSet
self._Pot = Pot
self.hasC = Pot.hasC
self.ha... |
class ChineseCLIPVisionModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def sunrise(agent, buffer, train_env, test_env, num_steps=1000000, transitions_per_step=1, max_episode_steps=100000, batch_size=512, tau=0.005, actor_lr=0.0001, critic_lr=0.0001, alpha_lr=0.0001, gamma=0.99, eval_interval=5000, eval_episodes=10, warmup_steps=1000, actor_clip=None, critic_clip=None, actor_l2=0.0, critic... |
def build_benchmark():
seq = '\nfrom neural_compressor.experimental import Benchmark\nfrom neural_compressor.data import Datasets, DATALOADERS\nfrom neural_compressor import conf\nfrom onnx import onnx_pb as onnx_proto\nfrom onnx import helper, TensorProto, numpy_helper\nfrom onnxruntime_extensions import onnx_op\n... |
class State():
weights: chex.Array
values: chex.Array
packed_items: chex.Array
remaining_budget: chex.Array
key: chex.PRNGKey |
def main(args: argparse.Namespace) -> None:
assert isinstance(args.folders, list)
assert isinstance(args.file, str)
if (args.classes is not None):
assert isinstance(args.classes, list)
file_paths = [(Path(p) / args.file) for p in args.folders]
filter = identical
if args.smooth_factor:
... |
def build(anchor_generator_config):
if (not isinstance(anchor_generator_config, anchor_generator_pb2.AnchorGenerator)):
raise ValueError('anchor_generator_config not of type anchor_generator_pb2.AnchorGenerator')
if (anchor_generator_config.WhichOneof('anchor_generator_oneof') == 'grid_anchor_generator'... |
def pool(data, name, kernel=3, stride=2, dilate=1, pad=(- 1), pool_type='max', global_pool=False):
if (pool_type == 'max+avg'):
branch1 = pool(data, '{}_branch1'.format(name), kernel=kernel, stride=stride, dilate=dilate, pad=pad, pool_type='max')
branch2 = pool(data, '{}_branch2'.format(name), kerne... |
def check_pipeline_doc(overwrite=False):
with open(PATH_TO_TOC, encoding='utf-8') as f:
content = yaml.safe_load(f.read())
api_idx = 0
while (content[api_idx]['title'] != 'API'):
api_idx += 1
api_doc = content[api_idx]['sections']
pipeline_idx = 0
while (api_doc[pipeline_idx]['ti... |
class TestOptions(BaseOptions):
def initialize(self, parser):
parser = BaseOptions.initialize(self, parser)
parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')
parser.add_argument('--load_epoch', type=str, default='500', help='which epoch to load? set to la... |
class SynthiaDataset(SparseVoxelizationDataset):
CLIP_BOUND = (((- 2000), 2000), ((- 2000), 2000), ((- 2000), 2000))
VOXEL_SIZE = 30
NUM_IN_CHANNEL = 4
BBOX_NORMALIZE_MEAN = np.array((0.0, 0.0, 0.0, 10.802, 6.258, 10.543))
BBOX_NORMALIZE_STD = np.array((3.331, 1.507, 3.007, 5.179, 1.177, 4.268))
... |
class MultiDataset():
def __init__(self, dataset_type='train'):
self._dataset_type = dataset_type
self.writer = registry.get('writer')
self._is_main_process = is_main_process()
self._global_config = registry.get('config')
def _process_datasets(self):
if ('datasets' not in... |
class TestSingleStageDetector(TestCase):
def setUp(self):
register_all_modules()
(['retinanet/retinanet_r18_fpn_1x_coco.py', 'centernet/centernet_r18_8xb16-crop512-140e_coco.py', 'fsaf/fsaf_r50_fpn_1x_coco.py', 'yolox/yolox_tiny_8xb8-300e_coco.py', 'yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', 'repp... |
def image_to_tfexample(image_data, image_format, height, width, class_id):
return tf.train.Example(features=tf.train.Features(feature={'image/encoded': bytes_feature(image_data), 'image/format': bytes_feature(image_format), 'image/class/label': int64_feature(class_id), 'image/height': int64_feature(height), 'image/... |
def get_logger(level=logging.INFO):
logger = logging.getLogger(os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1]))
logger.setLevel(level)
formatter = logging.Formatter('%(asctime)s-%(name)s[%(levelname)s]$ %(message)s', '%Y-%m-%d %H:%M:%S')
ch = logging.StreamHandler(sys.stdout)
... |
class ConditionalController(FlowController):
def __init__(self, passes, options, condition=None, **partial_controller):
self.condition = condition
super().__init__(passes, options, **partial_controller)
def __iter__(self):
if self.condition():
for pass_ in self.passes:
... |
def save_checkpoint(state, fpath='checkpoint.pth.tar'):
mkdir_if_missing(osp.dirname(fpath))
torch.save(state, fpath) |
class Evaluator():
def __init__(self, image_size: int=None):
self.image_size = image_size
self._image_generation_metrics = [tf.keras.metrics.MeanSquaredError('mse'), ImageRMSE('rmse'), tf.keras.metrics.MeanAbsoluteError('mae'), PSNRMetric('psnr'), LPIPSMetric('vgg', name='lpips'), SSIMMetric('ssim')... |
def conv3d_bn(batchNorm, in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1, bias=True):
(padding, dilation) = consistent_padding_with_dilation(padding, dilation, dim=3)
if batchNorm:
return nn.Sequential(nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding... |
def layer_name_mapping(key, file):
layer_rename_map = {'word_embeddings.weight': 'word_embeddings.weight', 'word_embeddings.norm.weight': 'word_embeddings_layernorm.weight', 'word_embeddings.norm.bias': 'word_embeddings_layernorm.bias', 'weight': 'ln_f.weight', 'bias': 'ln_f.bias'}
if (key in layer_rename_map):... |
class DeformableMLP(nn.Module):
def __init__(self, in_channels: int, out_channels: int, stride: int=1, padding: int=0, dilation: int=1, groups: int=1, bias: bool=True):
super(DeformableMLP, self).__init__()
if ((in_channels % groups) != 0):
raise ValueError('in_channels must be divisible... |
def parse_args():
parser = argparse.ArgumentParser(description='MMDet eval image prediction result for each')
parser.add_argument('config', help='test config file path')
parser.add_argument('prediction_path', help='prediction path where test pkl result')
parser.add_argument('show_dir', help='directory w... |
class GhostTopkBatchNorm2d(nn.Module):
def __init__(self, num_features, k=10, dim=1, momentum=0.1, bias=True, eps=1e-05, beta=0.75, noise=False):
super(GhostTopkBatchNorm2d, self).__init__()
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', t... |
class GANG():
def __init__(self, user_product_graph, product_user_graph, user_ground_truth, priors, mean_priors, sup_per, nor_flg, sup_flg=False):
self.pu_dim = (len(priors[0]) + len(priors[2]))
self.res_pu_spam_prior_vector = None
self.diag_pu_matrix = None
self.res_pu_spam_post_vec... |
class TestBufferedShuffleIterator(TestBase):
def test_shuffle(self):
items = list(BufferedShuffleIterator(NativeCheckpointableIterator(self.flattened_test_data.copy()), 971, 42))
self.assertMultisetEqual(items, self.flattened_test_data)
def test_shuffle_buffer_size_one(self):
items = lis... |
def calibration(model, dataloader=None, n_samples=128, calib_func=None):
if (calib_func is not None):
calib_func(model)
else:
import math
from .smooth_quant import model_forward
batch_size = dataloader.batch_size
iters = int(math.ceil((n_samples / batch_size)))
if... |
class DeResNetWeightNorm(_DeResNet):
def __init__(self, inplanes, planes, strides, output_paddings, activation):
super(DeResNetWeightNorm, self).__init__(DeResNetBlockWeightNorm, inplanes, planes, strides, output_paddings, activation) |
def main(params, dataset_name, transfer_learning=False):
identifier = time.strftime('%Y%m%d-%H%M%S')
run = '{}/sup/{}'.format(dataset_name, identifier)
if transfer_learning:
run += '-tl'
if (('train_all' in params) and params['train_all']):
run += '-test'
print("Starting run '{}'".fo... |
def tf_efficientnet_b7_ns(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet('tf_efficientnet_b7_ns', channel_multiplier=2.0, depth_multiplier=3.1, pretrained=pretrained, **kwargs)
return model |
class AudioLanguagePretrainDataset(Dataset):
def __init__(self, json_files, audio_config, blacklist=None):
self.json_data = _load_json_file(json_files, blacklist)
self.lengths = [item['duration'] for item in self.json_data]
self.sr = audio_config['sr']
if (audio_config['max_length'] ... |
def get_dataloaders(args):
dataset_type = args.dataset.input_type
if (dataset_type in dataset_functions):
((train_dataset, train_sampler, train_collate_fn), (valid_dataset, valid_sampler, valid_collate_fn), (test_dataset, test_sampler, test_collate_fn)) = dataset_functions[dataset_type](args)
else:
... |
def get_ImageNet_class_subset(class_idx, train=True, batch_size=None, shuffle=None, augm_type='test', num_workers=8, size=224, config_dict=None):
if (batch_size == None):
if train:
batch_size = DEFAULT_TRAIN_BATCHSIZE
else:
batch_size = DEFAULT_TEST_BATCHSIZE
augm_config ... |
def get_model(model):
if isinstance(model, DataParallel):
return model.module
return model |
class Ranker():
def __init__(self, index_path, faiss_index_path, nprobe, part_range, dim, inference, device, faiss_depth=1024):
self.inference = inference
self.faiss_depth = faiss_depth
if (faiss_depth is not None):
self.faiss_index = FaissIndex(index_path, faiss_index_path, npro... |
def found_in_url(df):
pred_df = pd.DataFrame(index=df.index)
pred_df['A_in_URL'] = df.apply((lambda row: check_name_in_string(row['A'], scrape_url(row['URL']))), axis=1)
pred_df['B_in_URL'] = df.apply((lambda row: check_name_in_string(row['B'], scrape_url(row['URL']))), axis=1)
return pred_df |
def test_max_iou_assigner_with_empty_gt():
self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.FloatTensor([])
assign_result = self.assign(bboxes, gt_bboxes)
expected_gt_inds = torc... |
def test_constructors():
types = [bytes, str, bool, int, float, tuple, list, dict, set]
expected = {t.__name__: t() for t in types}
if env.PY2:
expected['bytes'] = bytes()
expected['str'] = unicode()
assert (m.default_constructors() == expected)
data = {bytes: b'41', str: 42, bool: '... |
def pointnet_fp_module(xyz1, xyz2, points1, points2, mlp, is_training, bn_decay, scope, bn=True):
with tf.variable_scope(scope) as sc:
(dist, idx) = three_nn(xyz1, xyz2)
dist = tf.maximum(dist, 1e-10)
norm = tf.reduce_sum((1.0 / dist), axis=2, keep_dims=True)
norm = tf.tile(norm, [1,... |
def separate_channels_mido(items, n_channels=9, use_note_on_pitch=True):
caches = []
for i in range((n_channels + 1)):
caches.append(dict())
midi_instruments = []
for i in range((n_channels + 1)):
midi_instruments.append(dict())
for (i, ins_items) in enumerate(items):
for ite... |
class ChildThread(threading.Thread):
def __init__(self, threadID, name, counter, cuda_device, bash_command):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.cuda_device = cuda_device
self.bash_command = bash_comman... |
def download_image(args_tuple):
try:
(url, filename) = args_tuple
if (not os.path.exists(filename)):
urllib.urlretrieve(url, filename)
with open(filename) as f:
assert (hashlib.sha1(f.read()).hexdigest() != MISSING_IMAGE_SHA1)
test_read_image = io.imread(filen... |
('(float32[:], int32)', device=True, inline=True)
def area(int_pts, num_of_inter):
area_val = 0.0
for i in range((num_of_inter - 2)):
area_val += abs(trangle_area(int_pts[:2], int_pts[((2 * i) + 2):((2 * i) + 4)], int_pts[((2 * i) + 4):((2 * i) + 6)]))
return area_val |
def prepare_params(kwargs):
kwargs = prepare_mode(kwargs)
default_max_episode_steps = 50
wgcsl_params = dict()
env_name = kwargs['env_name']
def make_env(subrank=None):
try:
env = gym.make(env_name, rewrad_type='sparse')
except:
logger.log('Can not make sparse... |
class SuperMobileSPADEResnetBlock(nn.Module):
def __init__(self, fin, fout, opt):
super(SuperMobileSPADEResnetBlock, self).__init__()
self.learned_shortcut = (fin != fout)
fmiddle = min(fin, fout)
self.conv_0 = SuperConv2d(fin, fmiddle, kernel_size=3, padding=1)
self.conv_1 =... |
_model
def hrnet_w48(pretrained=True, **kwargs):
return _create_model('hrnet_w48', pretrained, kwargs) |
class GCNModel(nn.Module):
def __init__(self, config):
super(GCNModel, self).__init__()
self.config = config
self.use_cuda = self.config.use_cuda
self.in_dim = self.config.gcn['in_dim']
self.out_dim = self.config.gcn['out_dim']
self.node_emb_layer = NodeEmbedFactory()... |
class HornerMultivarPolynomialOpt(HornerMultivarPolynomial):
root_class = OptimalFactorisationRoot |
def ensure_dir(file_path):
directory = os.path.dirname(file_path)
if (not os.path.exists(directory)):
os.makedirs(directory, exist_ok=True) |
_ops.RegisterGradient('Open3DSparseConvTranspose')
def _sparse_conv_transpose_grad(op, grad):
filters = op.inputs[0]
out_importance = op.inputs[1]
inp_features = op.inputs[2]
inp_neighbors_importance_sum = op.inputs[4]
inp_neighbors_row_splits = op.inputs[5]
neighbors_index = op.inputs[6]
ne... |
def load_model_tokenizer(model_name, device='cpu'):
huggingface_model = model_dict[model_name].from_pretrained(model_name).to(device)
tokenizer = tokenizer_dict[model_name].from_pretrained(model_name)
if (model_name in ['facebook/bart-base']):
huggingface_model.config.no_repeat_ngram_size = 0
... |
def setup(args):
if args.config_file.endswith('.yaml'):
cfg = get_cfg()
cfg.merge_from_file(args.config_file)
cfg.DATALOADER.NUM_WORKERS = 0
cfg.merge_from_list(args.opts)
cfg.freeze()
else:
cfg = LazyConfig.load(args.config_file)
cfg = LazyConfig.apply_ov... |
class ASPPPooling(nn.Sequential):
def __init__(self, in_channels, out_channels):
super(ASPPPooling, self).__init__(nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU())
def forward(self, x):
size = x.shape[(- 2):]
for mod i... |
class ParserImageFolder(Parser):
def __init__(self, root, class_map='', min_count=0):
super().__init__()
self.root = root
class_to_idx = None
if class_map:
class_to_idx = load_class_map(class_map, root)
(self.samples, self.class_to_idx) = find_images_and_targets(r... |
def train(rank, world_size, cfg):
torch.manual_seed(cfg.get('seed', 1337))
torch.cuda.manual_seed(cfg.get('seed', 1337))
np.random.seed(cfg.get('seed', 1337))
random.seed(cfg.get('seed', 1337))
master_port = int(os.environ.get('MASTER_PORT', 8738))
master_addr = os.environ.get('MASTER_ADDR', '12... |
def check_config_docstrings_have_checkpoints():
configs_without_checkpoint = []
for config_class in list(CONFIG_MAPPING.values()):
checkpoint = get_checkpoint_from_config_class(config_class)
name = config_class.__name__
if ((checkpoint is None) and (name not in CONFIG_CLASSES_TO_IGNORE_F... |
def test_digits_cosine_greedi_nn():
model = SumRedundancySelection(100, 'cosine', optimizer='greedi', optimizer_kwds={'optimizer1': 'naive', 'optimizer2': 'naive'}, random_state=0)
model.fit(X_digits)
assert_array_equal(model.ranking, digits_cosine_greedi_ranking)
assert_array_almost_equal(model.gains, ... |
def rasterize(glctx, pos, tri, resolution, ranges=None, grad_db=True):
assert isinstance(glctx, RasterizeGLContext)
assert ((grad_db is True) or (grad_db is False))
grad_db = (grad_db and glctx.output_db)
assert (isinstance(pos, torch.Tensor) and isinstance(tri, torch.Tensor))
resolution = tuple(res... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.