code stringlengths 101 5.91M |
|---|
class DetaPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def assign_proto(proto, name, val):
is_repeated_field = hasattr(getattr(proto, name), 'extend')
if (is_repeated_field and (not isinstance(val, list))):
val = [val]
if isinstance(val, list):
if isinstance(val[0], dict):
for item in val:
proto_item = getattr(proto, ... |
def read_ter_output():
params = [('all-cat', 93), ('old-cat', 48), ('new-cat', 44)]
for team in teams:
for param in params:
filelines = []
out = ''
for block_id in range(1, (param[1] + 1)):
with open((((((('eval/metric_per_block/ter3ref-' + team) + '-'... |
def dec_recompose(enc_wts):
dec_wts = []
global_aggregate = {}
chunks = len(enc_wts)
for h in range(chunks):
plain_agg = Plaintext()
decryptor.decrypt(enc_wts[h], plain_agg)
crtbuilder.decompose(plain_agg)
dec_wts += [plain_agg.coeff_at(h) for h in range(plain_agg.coeff_c... |
def get_logger(log_level):
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=log_level)
logger = logging.getLogger()
return logger |
def load_checkpoint(model, pretrained_path, module=None):
if (not os.path.exists(pretrained_path)):
raise NotImplementedError(('no checkpoint file from path %s...' % pretrained_path))
state_dict = torch.load(pretrained_path, map_location='cpu')
ckpt_state_dict = state_dict
for key in state_dict.... |
def read_raw(filename):
raw_messages = []
for line in open(filename):
line = line.strip()
tokens = line.split()
assert (len(tokens) > 0), 'Blank line in text file {}'.format(filename)
user = tokens[1]
if (tokens[0] != '==='):
user = user[1:(- 1)]
if (l... |
def preprocess(ori_img):
img = transform(ori_img)
batch = torch.stack([img for _ in range(8)], 0)
return batch |
class BaseTracker():
def __init__(self, params):
self.params = params
self.visdom = None
def predicts_segmentation_mask(self):
return False
def initialize(self, image, info: dict) -> dict:
raise NotImplementedError
def track(self, image, info: dict=None) -> dict:
... |
.wrap
def record_output(output, name, output_process, student=False):
recorded_output = output
if (output_process != ''):
if (isinstance(output, dict) and (output_process in output)):
recorded_output = output[output_process]
elif (isinstance(output, (tuple, list)) and str.isnumeric(o... |
def export_onnx_model(model, path, opset=12):
import torch
x = torch.randn(100, 3, 224, 224, requires_grad=True)
torch_out = model(x)
torch.onnx.export(model, x, path, export_params=True, opset_version=opset, do_constant_folding=True, input_names=['input'], output_names=['output'], dynamic_axes={'input'... |
def check_nan(list_of_tensors, folder=None):
there_is_a_nan = False
for tensor in list_of_tensors:
if ((tensor is not None) and torch.isnan(tensor).any()):
there_is_a_nan = True
break
if there_is_a_nan:
if folder:
f = open((folder + '/NAN_ALERT.txt'), 'w')... |
class BertDictionary(Dictionary):
def __init__(self, pad='[PAD]', unk='[UNK]', cls='[CLS]', mask='[MASK]', sep='[SEP]'):
super().__init__(pad, unk)
(self.cls_word, self.mask_word, self.sep_word) = (cls, mask, sep)
self.is_start = None
self.nspecial = len(self.symbols)
def class_p... |
class TFFunnelForQuestionAnswering(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class NdimGaussian():
def __init__(self, dimensionality, eta=None, lam=None):
self.dim = dimensionality
if ((eta is not None) and (len(eta) == self.dim)):
self.eta = eta
else:
self.eta = np.zeros(self.dim)
if ((lam is not None) and (lam.shape == (self.dim, sel... |
class deeplabv3plus_en(nn.Module):
def __init__(self, num_classes=None):
super(deeplabv3plus_en, self).__init__()
self.MODEL_NUM_CLASSES = num_classes
self.backbone = None
self.backbone_layers = None
self.aspp = ASPP(dim_in=2048, dim_out=256, rate=(16 // 16), bn_mom=0.99)
... |
def get_task_dataloader(task_name, set_name, tokenizer, args, sampler, batch_size=None, knowledge=None, extra_knowledge=None):
if ('race' in task_name.lower()):
return get_race_task_dataloader(task_name, set_name, tokenizer, args, sampler, batch_size, knowledge, extra_knowledge)
else:
return get... |
class TestTreeModel():
def setup_method(self, method):
sparkConf = init_spark_conf().setMaster('local[1]').setAppName('testTreeModel')
self.sc = init_nncontext(sparkConf)
self.sqlContext = SQLContext(self.sc)
self.resource_path = os.path.join(os.path.split(__file__)[0], '../resources... |
def save_fc(fp, fc_model):
fc_model.bias.data.numpy().tofile(fp)
fc_model.weight.data.numpy().tofile(fp) |
def test_param2grid_with_iterable_types():
params = {'alpha': [np.array([0.1, 0.01]), np.array([0.1, 0.01])], 'regs': [(1, 2), (3, 4)]}
expected = [{'alpha': [0.1, 0.1], 'regs': [1, 3]}, {'alpha': [0.1, 0.1], 'regs': [1, 4]}, {'alpha': [0.1, 0.1], 'regs': [2, 3]}, {'alpha': [0.1, 0.1], 'regs': [2, 4]}, {'alpha'... |
def initialise_halo_params():
G = 1.0
epsilon = 0.07
limit = 80000
radius = 4
num_pos_particles = 5000
num_neg_particles = 45000
chunks_value = ((num_pos_particles + num_neg_particles) / 5.0)
time_steps = 1000
return (G, epsilon, limit, radius, num_pos_particles, num_neg_particles, c... |
def reset_sim(sim):
arcsim.init_physics((sys.argv[1] + '/conf.json'), (sys.argv[1] + '/out1'), False)
print(sim.obstacles[0].curr_state_mesh.dummy_node.x) |
class writer():
def open(self, filename, mode):
self._data = open(filename, 'wb')
self._data.write(struct.pack('<B', mode))
def write(self, packet):
self._data.write(hl2ss.pack_packet(packet))
def close(self):
self._data.close() |
class test_dataset():
def __init__(self, dataset='MoCA', split='TestDataset_per_sq', testsize=256):
self.testsize = testsize
self.image_list = []
self.gt_list = []
self.extra_info = []
if (dataset == 'CAD2016'):
root = Path.db_root_dir('CAD2016')
img_f... |
def get_grasp(mask):
dist = cv.distanceTransform(mask, cv.DIST_L2, 5)
center = tuple(map(round, np.argwhere((dist == dist.max())).mean(axis=0)))
center = (center[1], center[0])
(contours, _) = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
if (len(contours) > 0):
largest_con... |
class TestLogger(unittest.TestCase):
def test_logger(self):
logger.log(0, 'call logger log function.')
logger.log(1, {'msg': 'call logger log function.'})
logger.debug('call logger debug function.')
logger.debug({'msg': 'call logger debug function.'})
logger.error('call logge... |
def create_torchvision_biomodel(model_architecture, mode, layer_config: dict=None, pretrained: bool=False, progress: bool=True, num_classes: int=1000) -> BioModule:
if (not pretrained):
copy_weights = False
model = model_architecture(pretrained, progress, num_classes=num_classes)
else:
c... |
class MSELossWiedemann(MSELoss):
def __init__(self, size_average=None, reduce=None, reduction: str='mean') -> None:
super(MSELossWiedemann, self).__init__(size_average, reduce, reduction)
def forward(self, input: Tensor, target: Tensor) -> Tensor:
return mse_loss_wiedemann(input, target, reducti... |
class TimerError(Exception):
def __init__(self, message):
self.message = message
super(TimerError, self).__init__(message) |
def modify_lr(optimizer, iter_count, init_lr=0.001, all_iter=10000, decay=0.999931, prompt_every=1000):
new_lr = (init_lr * (decay ** float(iter_count)))
if (((iter_count + 1) % prompt_every) == 0):
print('INFO: Current learning rate is: {:.6f}'.format(new_lr))
for param_group in optimizer.param_gro... |
class ModelDataConfig():
name: str
system: str
role_prefix: dict
ai_role: str
eot_token: str
bos_token: Optional[str]
max_tokens: int
pad_token: int
ignore_id: int |
class RemBertConfig(PretrainedConfig):
model_type = 'rembert'
def __init__(self, vocab_size=250300, hidden_size=1152, num_hidden_layers=32, num_attention_heads=18, input_embedding_size=256, output_embedding_size=1664, intermediate_size=4608, hidden_act='gelu', hidden_dropout_prob=0.0, attention_probs_dropout_pr... |
class SSD(object):
__category__ = 'architecture'
__inject__ = ['backbone', 'multi_box_head', 'output_decoder']
__shared__ = ['num_classes']
def __init__(self, backbone, multi_box_head='MultiBoxHead', output_decoder=SSDOutputDecoder().__dict__, num_classes=21):
super(SSD, self).__init__()
... |
def get_loss(output_dict, target, spg_thresholds):
((h1, l1), (h2, l2), (h3, l3)) = spg_thresholds
upsample_module = nn.Upsample(size=(224, 224), mode='bilinear')
b2i = torch.sigmoid(upsample_module(output_dict['logits_b2']))
loss_cls = nn.CrossEntropyLoss()(output_dict['logits'], target.long())
los... |
def test_individual_importances():
data = synthetic_regression()
X = data['full']['X']
y = data['full']['y']
ebm = ExplainableBoostingRegressor()
ebm.fit(X, y)
contributions = ebm.eval_terms(X)
dict = get_individual_importances(ebm, X, contributions)
assert (dict['A'] == compute_group_im... |
def dice_loss(pred, target):
assert (pred.shape == target.shape)
assert ((pred.max() <= 1) and (pred.min() >= 0))
assert one_hot(target)
numerator = (2 * torch.sum((pred * target)))
denominator = torch.sum((pred + target))
return (1 - ((numerator + 1e-10) / (denominator + 1e-10))) |
def film_normalize_data(context, model_params, ds_train, ds_valid, path_output):
results = imed_film.get_film_metadata_models(ds_train=ds_train, metadata_type=model_params[ModelParamsKW.METADATA], debugging=context[ConfigKW.DEBUGGING])
(ds_train, train_onehotencoder, metadata_clustering_models) = results
ds... |
def cleanup_discard(d, key, val):
s = d.get(key, set())
s.discard(val)
if (len(s) == 0):
d.pop(key, None) |
class Mul2(nn.Module):
def __init__(self):
super(Mul2, self).__init__()
def forward(self, x):
assert ((type(x) == list) and (len(x) == 2))
return (x[0] * x[1]) |
def evaluate(model):
from neural_compressor.model import Model
if (isinstance(model, str) or isinstance(model, tf.compat.v1.Graph)):
model = Model(model)
model.input_tensor_names = ['image_tensor:0']
model.output_tensor_names = ['num_detections:0', 'detection_boxes:0', 'detection_scores:... |
def event2frame(event, img_size, ts, f_span, total_span, num_frame, noise, roiTL=(0, 0)):
(f_start, f_end) = f_span
(total_start, total_end) = total_span
event['x'] = event['x'].astype(int)
event['y'] = event['y'].astype(int)
event['t'] = event['t'].astype(int)
event['p'] = event['p'].astype(int... |
class PeleeNet(nn.Module):
def __init__(self, channels, init_block_channels, bottleneck_sizes, dropout_rate=0.5, in_channels=3, in_size=(224, 224), num_classes=1000):
super(PeleeNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential(... |
def api_run_func():
res = atorch.init_distributed('gloo', coworker_num_per_node=1)
assert res
dataset = ToyDataset(50)
dataloader_args = {'batch_size': 4}
io_timeout = 5
initialize_timeout = 15
shm_context = create_coworker_shm_context(dataset=dataset, dataloader_args=dataloader_args, io_tim... |
class Logger(object):
_fields = None
def fields(self):
assert (self._fields is not None), 'self.fields is not set!'
return self._fields
def fields(self, value):
self._fields
def __init__(self, fields=None):
self.fields = fields
def log(self, *args, **kwargs):
... |
def _load_cfg_from_yaml_str(str_obj):
cfg_as_dict = yaml.safe_load(str_obj)
return CfgNode(cfg_as_dict) |
class SimpleLSTM(object):
def __init__(self) -> None:
super(SimpleLSTM, self).__init__()
self.max_len = 75
self.emb_dim = 32
self.max_vocab_len = 100
self.lstm_output_size = 32
self.W_reg = regularizers.l2(0.0001)
def build_model(self):
main_input = Input(... |
def many_to_one(input_dict):
return dict(((key, val) for (keys, val) in input_dict.items() for key in keys)) |
def data_transform_3d(normalization):
data_transform = {'train': T.Compose([T.RandomFlip(), T.RandomBiasField(coefficients=(0.12, 0.15), order=2, p=0.2), T.OneOf({T.RandomNoise(): 0.5, T.RandomBlur(std=1): 0.5}, p=0.2), T.ZNormalization(masking_method=normalization)]), 'val': T.Compose([T.ZNormalization(masking_met... |
class BaseRayEstimator(BaseEstimator, metaclass=ABCMeta):
def __init__(self, **kwargs):
pass
def fit(self, **kwargs):
pass
def predict(self, **kwargs):
pass
def evaluate(self, **kwargs):
pass
def get_model(self):
pass
def setup(self, params, backend='ray',... |
def main(args):
device = torch.device(args.device)
seed = args.seed
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
model = ELFNet(args)
model = model.to(device)
model = torch.nn.DataParallel(model)
print_param(model)
param_dicts = [{'params': [p for (n, p) in mode... |
class IntEmbedding(nn.Module):
def __init__(self, num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, _weight=None, p=0, update_step=1000, bits=8, method='histogram'):
super(IntEmbedding, self).__init__()
self.num_embeddings = num_em... |
def test_transformed_views_have_same_shape_as_original(mock_data):
(brain_data, behavior_data, _) = mock_data
views = [brain_data, behavior_data]
preprocessing_steps = [StandardScaler(), StandardScaler()]
mvp = MultiViewPreprocessing(preprocessing_steps)
mvp.fit(views)
transformed_views = mvp.tr... |
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
model.train()
end = time.time()
for (i, (input, target)) in enumerate(train_loader):
data_time.u... |
class PositionwiseFeedForward(rtrans.PositionwiseFeedForward):
def __init__(self, mask_type, mask_init_value, d_model, d_ff, dropout=(0.1 / 3)):
nn.Module.__init__(self)
self.w_1 = MaskedLinear(d_model, d_ff, mask_type, mask_init_value)
self.w_2 = MaskedLinear(d_ff, d_model, mask_type, mask_... |
(autouse=True)
def _override_cache_config(cache_config: cache.CacheConfig) -> None:
def _test_auto_load() -> cache.CacheConfig:
logger = logging.getLogger('pybaseball')
logger.debug('_test_auto_load')
return cache_config
if (not hasattr(cache.cache_config, '_autoload_cache')):
ca... |
_builder('msrvtt_caption')
class MSRVTTCapBuilder(BaseDatasetBuilder):
train_dataset_cls = VideoCaptionDataset
eval_dataset_cls = VideoCaptionEvalDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/msrvtt/defaults_cap.yaml'} |
def test_digits_greedi_nn_object():
model1 = FeatureBasedSelection(100, 'sqrt')
model2 = FeatureBasedSelection(100, 'log')
model = MixtureSelection(100, [model1, model2], [1.0, 0.3], optimizer=GreeDi(optimizer1='naive', optimizer2='naive', random_state=0))
model.fit(X_digits)
assert_array_equal(mode... |
class Generator(nn.Module):
def __init__(self, ct1_channels=512, ct2_channels=256, ct3_channels=128, ct4_channels=64, d_channels_in_2=False):
super().__init__()
self.ct1_channels = ct1_channels
self.pheight = 4
self.pwidth = 4
if d_channels_in_2:
self.ct2_channels... |
def test_interpolation_potential_diffinputs_c():
rzpot = potential.interpRZPotential(RZPot=potential.MWPotential, rgrid=(0.01, 2.0, 151), zgrid=(0.0, 0.2, 151), logR=False, interpPot=True, zsym=True, enable_c=True)
rs = numpy.linspace(0.01, 2.0, 20)
zs = numpy.linspace((- 0.2), 0.2, 40)
assert numpy.all... |
class ConvLayer(nn.Sequential):
def __init__(self, in_channels, out_channels, kernel=3, stride=1):
super().__init__()
self.add_module('conv', nn.Conv2d(in_channels, out_channels, kernel_size=kernel, stride=stride, padding=(kernel // 2), bias=False))
self.add_module('norm', nn.BatchNorm2d(out... |
.parametrize('device', list_devices())
def test_knn_search(device):
dtype = o3c.float32
dataset_points = o3c.Tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.1], [0.0, 0.0, 0.2], [0.0, 0.1, 0.0], [0.0, 0.1, 0.1], [0.0, 0.1, 0.2], [0.0, 0.2, 0.0], [0.0, 0.2, 0.1], [0.0, 0.2, 0.2], [0.1, 0.0, 0.0]], dtype=dtype, device=devi... |
def get_unique_smiles(valid_molecules):
unique = set()
for mol in valid_molecules:
unique.add(Chem.MolToSmiles(mol))
return list(unique) |
class CellDETR(nn.Module):
def __init__(self, num_classes: int=1, number_of_query_positions: int=1, hidden_features=128, backbone_channels: Tuple[(Tuple[(int, int)], ...)]=((1, 64), (64, 128), (128, 256), (256, 256)), backbone_block: Type=ResNetBlock, backbone_convolution: Type=conv, backbone_normalization: Type=nn... |
def _make_stage(transformation_module, in_channels, bottleneck_channels, out_channels, block_count, num_groups, stride_in_1x1, first_stride, dilation=1, dcn_config={}):
blocks = []
stride = first_stride
max_dcn_layer = dcn_config.get('max_dcn_layer', 0)
for i in range(block_count):
if (i < (bloc... |
def log_gradient(model, global_step=None):
if tt.arg.log_grad:
for (k, v) in model.named_parameters():
if ('weight' in k):
if (v.grad is not None):
log_scalar(('gradient/' + k), v.grad.norm(), global_step) |
class KMeansTransformerOriginal(object):
def __init__(self, k_fold=None):
self._new_features = []
self._input_columns = []
self._error = None
self._kmeans = None
self._scale = None
self._k_fold = k_fold
def fit(self, X, y):
if self._new_features:
... |
class Similarity(nn.Module):
def __init__(self):
super(Similarity, self).__init__()
def forward(self, g_s, g_t):
return [self.similarity_loss(f_s, f_t) for (f_s, f_t) in zip(g_s, g_t)]
def similarity_loss(self, f_s, f_t):
bsz = f_s.shape[0]
f_s = f_s.view(bsz, (- 1))
... |
def date_generator(doc):
spans = []
i = 0
while (i < len(doc)):
tok = doc[i]
if (tok.lemma_ in (DAYS | DAYS_ABBRV)):
spans.append((i, (i + 1), 'DATE'))
elif (tok.is_digit and re.match('\\d+$', tok.text) and (1920 < int(tok.text) < 2040)):
spans.append((i, (i +... |
class LeakyReluPar(nn.Module):
def forward(self, x, a):
return ((((1.0 - a) / 2.0) * torch.abs(x)) + (((1.0 + a) / 2.0) * x)) |
def get_font(fonts_valid: List[str]=None, font_size: int=15) -> ImageFont:
if (fonts_valid is None):
fonts_valid = ['FreeSerif.ttf', 'FreeSans.ttf', 'Century.ttf', 'Calibri.ttf', 'arial.ttf']
fonts_in_sys = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
fonts_in_sys = sorted(... |
def utf8_visual_to_logical(text):
text_dir = determine_text_direction(text)
bidi = icu_bidi.Bidi()
bidi.inverse = True
bidi.reordering_mode = icu_bidi.UBiDiReorderingMode.UBIDI_REORDER_INVERSE_LIKE_DIRECT
bidi.reordering_options = icu_bidi.UBiDiReorderingOption.UBIDI_OPTION_DEFAULT
bidi.set_para... |
class OPENPOSE_18():
LEFT_LINES = [(2, 3), (3, 4), (2, 8), (8, 9), (9, 10)]
LEFT_POINTS = [2, 3, 4, 8, 9, 10]
RIGHT_LINES = [(5, 6), (6, 7), (5, 11), (11, 12), (12, 13)]
RIGHT_POINTS = [5, 6, 7, 11, 12, 13]
CENTER_LINES = [(16, 14), (14, 0), (0, 15), (15, 17), (0, 1)]
CENTER_BODY = [1, 2, 8, 11,... |
def get_eventpath_byDM(total_list, d, m):
out = []
for item in total_list:
if ((('/' + d) + '/') in item):
if ((('/' + m) + '/') in item):
out.append(item)
assert (len(out) == 1), 'supposed only 1 here'
return out[0] |
class Unet(nn.Module):
def __init__(self, c=4, n=16, dropout=0.5, norm='gn', num_classes=5):
super(Unet, self).__init__()
self.upsample = nn.Upsample(scale_factor=2, mode='trilinear', align_corners=False)
self.convd1 = ConvD(c, n, dropout, norm, first=True)
self.convd2 = ConvD(n, (2 ... |
class DIAPreResUnit(nn.Module):
def __init__(self, in_channels, out_channels, stride, bottleneck, conv1_stride, attention=None):
super(DIAPreResUnit, self).__init__()
self.resize_identity = ((in_channels != out_channels) or (stride != 1))
if bottleneck:
self.body = PreResBottlene... |
class TFAutoModelForNextSentencePrediction():
def __init__(self):
raise EnvironmentError('TFAutoModelForNextSentencePrediction is designed to be instantiated using the `TFAutoModelForNextSentencePrediction.from_pretrained(pretrained_model_name_or_path)` or `TFAutoModelForNextSentencePrediction.from_config(c... |
def generate_training_labels(data_folder: Path, resume):
print(f'Processing label data in {data_folder}')
for city in ['london', 'madrid', 'melbourne']:
data_folder_train_city_labels = (((data_folder / 'train') / city) / 'labels')
data_folder_train_city_labels.mkdir(exist_ok=True, parents=True)
... |
class erf_step(PhaseGenerator):
def help(self):
return 'Step function polynomial using erf(), but only for specific pre-computed values. Argument is n, where n may be 7 or 23'
def generate(self, n):
phi_n7_erf = [1.58019, 0., 0.251897, (- 0.834542), (- 0.834542), 0.251897, 0., 0.]
phi_n... |
def emulate_int8_tensor(w, scale=None, zero_point=None):
if (scale is None):
obs = torch.quantization.observer.MinMaxObserver()
_ = obs(w)
(scale, zero_point) = obs.calculate_qparams()
scale = scale.cuda().type_as(w)
zero_point = zero_point.cuda().type_as(w)
return (quant... |
def lineset_from_pose_graph(pose_graph):
points = []
colors = []
lines = []
cnt = 0
for node in pose_graph.nodes:
pose = np.array(node.pose)
l = 0.1
points.append((pose np.array([0, 0, 0, 1]).T)[:3])
points.append((pose np.array([l, l, (2 * l), 1]).T)[:3])
p... |
class TrainDataset(object):
def __init__(self, batch_size=100):
((x_train, y_train), (x_test, y_test)) = cifar10.load_data()
x_train = (x_train.astype('float32') / 255)
x_test = (x_test.astype('float32') / 255)
x_train_mean = np.mean(x_train, axis=0)
x_train -= x_train_mean
... |
def main():
args = parse_args()
print('Called with args:')
print(args)
if (not torch.cuda.is_available()):
sys.exit('Need a CUDA device to run the code.')
if (args.cuda or (cfg.NUM_GPUS > 0)):
cfg.CUDA = True
else:
raise ValueError('Need Cuda device to run !')
if (arg... |
class GCNModelVAE(Model):
def __init__(self, placeholders, num_features, num_nodes, features_nonzero, **kwargs):
super(GCNModelVAE, self).__init__(**kwargs)
self.inputs = placeholders['features']
self.input_dim = num_features
self.features_nonzero = features_nonzero
self.n_sa... |
class ArchiveImageFolder(ImageFolder):
def __init__(self, archive: str, cache_dir: Optional[str]=None, transform: Optional[Callable]=None, target_transform: Optional[Callable]=None, is_valid_file: Optional[Callable[([str], bool)]]=None, root_in_archive: str='') -> None:
assert (archive.endswith('.tar') or a... |
def to_numpy(tensors):
if isinstance(tensors, (list, tuple)):
return [bkd.to_numpy(tensor) for tensor in tensors]
return bkd.to_numpy(tensors) |
.xfail('env.PYPY', reason='getrefcount is not available')
.parametrize('method', [m.test_memoryview_object, m.test_memoryview_buffer_info])
def test_memoryview_refcount(method):
buf = b'\n\x0b\x0c\r'
ref_before = sys.getrefcount(buf)
view = method(buf)
ref_after = sys.getrefcount(buf)
assert (ref_be... |
def parse_function_fewshot(*metrics, directory='', args=None, end_signal=None):
print(f'Parsing files in {directory}')
outputs = []
file_list = os.listdir(directory)
file_list.sort()
for file in file_list:
if (('log' in file) or ('pt.txt' in file)):
num = 0
way = 'Non... |
def form_word_to_index_dict_from_dataset(word_vec_dict):
word_to_index = {}
next_index_to_assign = 1
for key in sorted(word_vec_dict.keys()):
word_to_index[key] = next_index_to_assign
next_index_to_assign += 1
return word_to_index |
class CovidNet(nn.Module):
def __init__(self, model: str='small', n_classes: int=3):
super(CovidNet, self).__init__()
filters = {'pepx1_1': [56, 56], 'pepx1_2': [56, 56], 'pepx1_3': [56, 56], 'pepx2_1': [56, 112], 'pepx2_2': [112, 112], 'pepx2_3': [112, 112], 'pepx2_4': [112, 112], 'pepx3_1': [112, ... |
class LabelMapUtilTest(tf.test.TestCase):
def _generate_label_map(self, num_classes):
label_map_proto = string_int_label_map_pb2.StringIntLabelMap()
for i in range(1, (num_classes + 1)):
item = label_map_proto.item.add()
item.id = i
item.name = ('label_' + str(i))... |
def track_infer_time(buffer: [int]):
start = time()
(yield)
end = time()
buffer.append((end - start)) |
def main():
all_models = [name for name in dir(models) if callable(getattr(models, name))]
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
parser.add_argument('experiment', nargs='?', default='test')
parser.add_argument('-model', choices=all_models, default='BasicNetBN')
par... |
class SupervisedDataset():
X: pd.DataFrame
y: pd.Series
meta: dict
def serialize(cls, obj):
(_, X_bstream) = BytesParser.serialize(obj.X)
(_, y_bstream) = BytesParser.serialize(obj.y)
(_, meta_bstream) = BytesParser.serialize(obj.meta)
return (X_bstream, y_bstream, meta_b... |
class TestAutoContrast(unittest.TestCase):
def setUp(self):
self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', 'gt_ignore_flags', 'gt_seg_map')
self.results_mask = construct_toy_data(poly2mask=True)
def test_autocontrast(self):
transform = AutoContrast(prob=0.0)
... |
def mahalanobis_metric_fast(p, mu, covi, U):
mean_p = torch.mean(p, dim=0, keepdim=True)
mahalanobis_distances_new = (mean_p - mu).mm(U.mm(U.t())).mm((mean_p - mu).t())
mahalanobis_distances_new = mahalanobis_distances_new.diag().sqrt().expand(p.size(0))
return mahalanobis_distances_new.data |
class IBN(nn.Module):
def __init__(self, planes, ratio=0.5):
super(IBN, self).__init__()
self.half = int((planes * (1 - ratio)))
self.BN = nn.BatchNorm2d(self.half)
self.IN = nn.InstanceNorm2d((planes - self.half), affine=True)
def forward(self, x):
split = torch.split(x,... |
class XLNetTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
padding_side = 'left'
def __init__(self, vocab_file, do_lower_case=False, remove_space=True, keep_ac... |
class TokenKind(object):
_value_map = {}
def __init__(self, value, name):
self.value = value
self.name = name
def __repr__(self):
return ('TokenKind.%s' % (self.name,))
def from_value(value):
result = TokenKind._value_map.get(value, None)
if (result is None):
... |
class Cora(BaseData):
def __init__(self, data_root: Optional[str]=None) -> None:
super().__init__('cora', data_root)
self._content = {'num_classes': 7, 'num_vertices': 2708, 'num_edges': 10858, 'dim_features': 1433, 'features': {'upon': [{'filename': 'features.pkl', 'md5': '05b45e9c38cc95f4fc44b3668... |
def getFeat(I, net, transform):
feat = net(transform(I).unsqueeze(0).cuda())
feat = feat.data.squeeze()
feat = (feat / (torch.sum((feat ** 2), dim=0, keepdim=True).expand(feat.size()) ** 0.5))
return feat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.