code stringlengths 101 5.91M |
|---|
def instance_whitening_loss(f_map, eye, mask_matrix, margin, num_remove_cov):
(f_cor, B) = get_covariance_matrix(f_map, eye=eye)
f_cor_masked = (f_cor * mask_matrix)
off_diag_sum = (torch.sum(torch.abs(f_cor_masked), dim=(1, 2), keepdim=True) - margin)
loss = torch.clamp(torch.div(off_diag_sum, num_remo... |
def prune(spans, T, LAMBDA=0.4):
STOP = int((LAMBDA * T))
sorted_spans = sorted(spans, key=(lambda s: s.si), reverse=True)
nonoverlapping = remove_overlapping(sorted_spans)
pruned_spans = nonoverlapping[:STOP]
spans = sorted(pruned_spans, key=(lambda s: (s.i1, s.i2)))
return spans |
def exposure_meter_BC_vel(JDUTC, expmeterflux, starname='', hip_id=None, ra=None, dec=None, epoch=None, pmra=None, pmdec=None, px=None, rv=None, obsname='', lat=0.0, longi=0.0, alt=0.0, zmeas=0.0, ephemeris='de430', leap_dir=os.path.join(os.path.dirname(__file__), 'data'), leap_update=True, SolSystemTarget=None, Horizo... |
class ImageClassifierCLI(CLI):
def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None:
super().add_arguments_to_parser(parser)
parser.link_arguments('data.num_classes', 'model.num_classes', apply_on='instantiate')
parser.link_arguments('data.image_shape', 'model.image_sha... |
def test_mi_base_return():
n_inst = ConstructorStats.detail_reg_inst()
c1 = m.i801c_b1()
assert (type(c1) is m.I801C)
assert (c1.a == 1)
assert (c1.b == 2)
d1 = m.i801d_b1()
assert (type(d1) is m.I801D)
assert (d1.a == 1)
assert (d1.b == 2)
assert (ConstructorStats.detail_reg_ins... |
def run(args):
if (args.exp_name is None):
exp_layout = collections.OrderedDict([('dicg{}_de_ppo', args.n_gcn_layers), ('atype={}', args.attention_type), ('res={}', bool(args.residual)), ('entcoeff={}', args.ent), ('dim={}', args.dim), ('nagents={}', args.n_agents), ('difficulty={}', args.difficulty), ('cur... |
class FIDInceptionE_2(torchvision.models.inception.InceptionE):
def __init__(self, in_channels):
super(FIDInceptionE_2, self).__init__(in_channels)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch3x3 = self.branch3x3_1(x)
branch3x3 = [self.branch3x3_2a(branch3x3), self.... |
class NaiveModelParallelSplitter():
def __init__(self):
pass
def spread_on_devices(model: torch.nn.Module, devices: Optional[List]=None):
if ((devices is None) and torch.cuda.is_available()):
devices = list(range(torch.cuda.device_count()))
if (len(devices) < 2):
... |
def log_loss_calc(classes, prob_vector, actual_vector, normalize=True, sample_weight=None, pos_class=None):
try:
vector_length = len(actual_vector)
if (sample_weight is None):
sample_weight = ([1] * vector_length)
weight_sum = sum(sample_weight)
if (pos_class is None):
... |
class OverFeatTest(tf.test.TestCase):
def testBuild(self):
batch_size = 5
(height, width) = (231, 231)
num_classes = 1000
with self.test_session():
inputs = tf.random_uniform((batch_size, height, width, 3))
(logits, _) = overfeat.overfeat(inputs, num_classes)
... |
def get_loader(mode, data_root, batch_size, shuffle, num_workers, test_mode=None):
if (mode == 'train'):
is_training = True
else:
is_training = False
dataset = VimeoSepTuplet(data_root, is_training=is_training)
return DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_worker... |
def prev_identical_edge(cur, E, edits):
for e in E:
if ((e[1] == cur[0]) and (edits[e] == edits[cur])):
return e
return None |
def load_lib():
libpath = '/usr/local/lib/libcdf.so'
lib = ctypes.CDLL(libpath)
for funcname in call_dict:
func = getattr(lib, funcname)
args = call_dict[funcname]
func.restype = args[0]
func.argtypes = (None if (len(args) <= 1) else args[1:])
return lib |
def _check_voxceleb_folders(data_folders, splits):
for data_folder in data_folders:
if ('train' in splits):
folder_vox1 = os.path.join(data_folder, 'wav', 'id10001')
folder_vox2 = os.path.join(data_folder, 'wav', 'id00012')
if ((not os.path.exists(folder_vox1)) or (not os... |
.serial
def test_log_multitask_performance_task_id():
lengths = np.array([10, 5, 1, 1])
batch = TrajectoryBatch(EnvSpec(akro.Box(np.array([0.0, 0.0, 0.0]), np.array([1.0, 1.0, 1.0])), akro.Box(np.array([(- 1.0), (- 1.0)]), np.array([0.0, 0.0]))), observations=np.ones((sum(lengths), 3), dtype=np.float32), last_o... |
def butter_lowpass(cutoff, fs, order=5):
nyq = (0.5 * fs)
normal_cutoff = (cutoff / nyq)
(b, a) = butter(order, normal_cutoff, btype='low', analog=False)
return (b, a) |
def simple_separated_format(separator):
return TableFormat(None, None, None, None, headerrow=DataRow('', separator, ''), datarow=DataRow('', separator, ''), padding=0, with_header_hide=None) |
class ProfileResult():
f_times_mean: Dict[(int, float)]
f_times_std: Dict[(int, float)]
b_times_mean: Dict[(int, float)]
b_times_std: Dict[(int, float)]
communication_stats: Dict[(int, Dict[(str, float)])]
nocommf_times_mean: Dict[(int, float)]
nocommf_times_std: Dict[(int, float)]
nocom... |
def false_positive(pred, target, num_classes):
out = []
for i in range(num_classes):
out.append(((pred == i) & (target != i)).sum())
return torch.tensor(out) |
def t5_small_tied_lmhead_4p_bw12_async_squad1():
return dict(model_type='t5_stateless', model_name_or_path='t5-small', do_lower_case=False, output_past=False, output_attentions=False, output_hidden_states=False, explicitly_set_dict={'output_only': True, 'output_attentions': False, 'precomputed_masks': True, 'output... |
(scope='session')
def hypothesis_max_examples():
value = settings().max_examples
return (None if (value == 100) else value) |
class ZeroBaseline(Baseline):
def __init__(self, env_spec):
pass
def get_param_values(self, **kwargs):
return None
def set_param_values(self, val, **kwargs):
pass
def fit(self, paths):
pass
def predict(self, path):
return np.zeros_like(path['rewards'])
def... |
def setup(args):
cfg = get_cfg()
add_deeplab_config(cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
default_setup(cfg, args)
return cfg |
class AggregationCell_3(AggregationCell):
def __init__(self, genotype, steps, multiplier, parse_method, C_in=[256, 32, 768]):
super().__init__(genotype, steps, multiplier, parse_method)
C = 128
self.preprocess0 = nn.Sequential(nn.ReLU(inplace=False), nn.Conv2d(C_in[0], C, kernel_size=1, bias... |
class TestSweepPoly(object):
def test_sweep_poly_quad1(self):
p = np.poly1d([1.0, 0.0, 1.0])
t = np.linspace(0, 3.0, 10000)
phase = waveforms._sweep_poly_phase(t, p)
(tf, f) = compute_frequency(t, phase)
expected = p(tf)
abserr = np.max(np.abs((f - expected)))
... |
def get_atari_median_human_normalized_score(algo_title, env_variant):
normalized_scores = []
algo_entries = find_all({'algo-title': algo_title, 'env-variant': env_variant})
for algo_entry in algo_entries:
if (algo_entry['env-title'][:5] == 'atari'):
score = get_human_normalized_score(alg... |
def _impl(array, axis, keepdims, initial, mask_identity, highlevel, behavior, attrs):
axis = regularize_axis(axis)
with HighLevelContext(behavior=behavior, attrs=attrs) as ctx:
layout = ctx.unwrap(array, allow_record=False, primitive_policy='error')
reducer = ak._reducers.Max(initial)
out = ak._... |
class GPTNeoXLayer(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def transpose(array, axes=None):
if is_numpy_array(array):
return np.transpose(array, axes=axes)
elif is_torch_tensor(array):
return (array.T if (axes is None) else array.permute(*axes))
elif is_tf_tensor(array):
import tensorflow as tf
return tf.transpose(array, perm=axes)
... |
class EntityReviewBucketBatchSampler(Sampler):
def __init__(self, dataset, entity_id, batch_size, pct=1.0):
ids = ['__'.join([entity_id, review_id]) for review_id in dataset.reviews[entity_id]]
if (pct < 1.0):
num_ids = int((len(ids) * pct))
shuffle(ids)
ids = ids... |
def attn_bilinear(lf_input, rt_input, lf_max_len, rt_max_len, dim_att_hidden):
(expand_lf_input, expand_rt_input) = expand_both_dims(lf_input=lf_input, rt_input=rt_input, lf_max_len=lf_max_len, rt_max_len=rt_max_len)
with tf.variable_scope('cross_att_bilinear', reuse=tf.AUTO_REUSE):
w = tf.get_variable(... |
def get_parameter_file_loader():
file_loaders = OrderedDict([('.h5', _h5_parameter_file_loader), ('.protobuf', _pb_parameter_file_loader), ('.nntxt,.prototxt', _nntxt_parameter_file_loader), ('.nnp', _nnp_parameter_file_loader)])
return file_loaders |
class RandomDatasetSampler(Sampler):
def __init__(self, data_source, batch_size, n_dataset):
self.data_source = data_source
self.dataset_dict = defaultdict(list)
for (i, items) in enumerate(data_source):
dsetid = items[3]
self.dataset_dict[dsetid].append(i)
se... |
class ConstantRangeMemlet(MemletPattern):
def can_be_applied(self, expressions, variable_context, node_range, orig_edges):
constant_range = True
for dim in node_range:
for rngelem in dim:
if ((not dtypes.isconstant(rngelem)) and (not isinstance(rngelem, sympy.Number))):
... |
class TaggingTask(task.Task):
__metaclass__ = abc.ABCMeta
def __init__(self, config: configure_finetuning.FinetuningConfig, name, tokenizer, is_token_level):
super(TaggingTask, self).__init__(config, name)
self._tokenizer = tokenizer
self._label_mapping_path = os.path.join(self.config.pr... |
class TestShLexer(unittest.TestCase):
def lex(self, str, *args, **kwargs):
return list(ShLexer(str, *args, **kwargs).lex())
def test_basic(self):
self.assertEqual(self.lex('a|b>c&d<e;f'), ['a', ('|',), 'b', ('>',), 'c', ('&',), 'd', ('<',), 'e', (';',), 'f'])
def test_redirection_tokens(self... |
class BridgeTowerForContrastiveLearning(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class ZeldaProblem(Problem):
_tile_types = ['empty', 'solid', 'player', 'key', 'door', 'bat', 'scorpion', 'spider']
def __init__(self, cfg: Config):
super().__init__(cfg=cfg)
self.path_length = 0
self.path = []
self._prob = {'empty': 0.58, 'solid': 0.3, 'player': 0.02, 'key': 0.0... |
def _maybe_load_yaml(item):
if isinstance(item, six.string_types):
return yaml.load(item)
elif isinstance(item, dict):
return item
else:
raise ValueError('Got {}, expected YAML string or dict', type(item)) |
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.model = torchvision.models.mobilenet_v2(pretrained=True)
self.model.requires_grad_(False)
self.model.classifier[1] = torch.nn.Linear(in_features=1280, out_features=num_classes, bias=True)
def forward(self,... |
def _clean_street(result_dict: Dict[(str, str)], street: str) -> None:
if re.match('\\d+[st|nd|rd|th]', street, flags=re.IGNORECASE):
result_dict['street_name'] = street.lower()
else:
result_dict['street_name'] = street.title() |
def interleave(inter, f, seq, **kwargs):
seq = iter(seq)
try:
f(next(seq), **kwargs)
except StopIteration:
pass
else:
for x in seq:
inter()
f(x, **kwargs) |
def load_entity_vocab(data_dir, ignore_bad_title=True, min_ent_count=1):
entity_vocab = {}
bad_title = 0
few_entity = 0
with open(os.path.join(data_dir, 'entity_vocab.txt'), 'r', encoding='utf-8') as f:
for line in f:
(_, entity_id, entity_title, entity_mid, count) = line.strip().spl... |
def skipIfNoQNNPACK(fn):
reason = 'Quantized operations require QNNPACK.'
if isinstance(fn, type):
if ('qnnpack' not in torch.backends.quantized.supported_engines):
fn.__unittest_skip__ = True
fn.__unittest_skip_why__ = reason
return fn
(fn)
def wrapper(*args, **k... |
def process_checkpoint(in_file, out_file):
checkpoint = torch.load(in_file, map_location='cpu')
if ('optimizer' in checkpoint):
del checkpoint['optimizer']
for key in list(checkpoint['state_dict']):
if key.startswith('ema_'):
checkpoint['state_dict'].pop(key)
if (torch.__vers... |
def dut_cb_event(ed, eventid, exp_meta, exp_meta_lock):
global initial_dr
if (eventid == 'JOINED'):
print('DUT: End device joined')
event_device_joined.set()
elif (eventid == 'REBOOT'):
print('DUT: Reboot successful') |
def orthogonal_procrustes(A, B, check_finite=True):
if check_finite:
A = np.asarray_chkfinite(A)
B = np.asarray_chkfinite(B)
else:
A = np.asanyarray(A)
B = np.asanyarray(B)
if (A.ndim != 2):
raise ValueError(('expected ndim to be 2, but observed %s' % A.ndim))
if ... |
def test_c2st_shape_error():
source_samples = np.random.random(size=(5, 2))
target_samples = np.random.random(size=(5, 3))
with pytest.raises(ShapeError):
computational_utilities.c2st(source_samples, target_samples) |
def intersect_and_union(pred_label, label, num_classes, ignore_index, label_map=dict(), reduce_zero_label=False):
if isinstance(pred_label, str):
pred_label = torch.from_numpy(np.load(pred_label))
else:
pred_label = torch.from_numpy(pred_label)
if isinstance(label, str):
label = torc... |
def _copy_cookie_jar(jar):
if (jar is None):
return None
if hasattr(jar, 'copy'):
return jar.copy()
new_jar = copy.copy(jar)
new_jar.clear()
for cookie in jar:
new_jar.set_cookie(copy.copy(cookie))
return new_jar |
def get_layer_groups_(T_m, m):
return [nn.Sequential(*flatten_model(T_m)), nn.Sequential(*flatten_model(m))] |
def test_multiple_encoded_covariates_totalvi():
adata = synthetic_iid()
adata.obs['cont1'] = np.random.normal(size=(adata.shape[0],))
adata.obs['cont2'] = np.random.normal(size=(adata.shape[0],))
adata.obs['cat1'] = np.random.randint(0, 5, size=(adata.shape[0],))
adata.obs['cat2'] = np.random.randin... |
def _load(plugin):
if (plugin in find_available_plugins(loaded=True)):
return
if (plugin not in plugin_module_name):
raise ValueError(f'Plugin {plugin} not found.')
else:
modname = plugin_module_name[plugin]
plugin_module = __import__(('skimage.io._plugins.' + modname), froml... |
class Decoder(nn.Module):
def __init__(self, num_ch_enc, num_output_channels=3):
super(Decoder, self).__init__()
num_ch_dec = [16, 32, 64, 128, 256]
self.upconv5 = ConvBlock(num_ch_enc[4], num_ch_dec[4])
self.upconv4 = ConvBlock(num_ch_dec[4], num_ch_dec[3])
self.upconv3 = Co... |
def _convert_models_to_fp32(model):
for p in model.parameters():
p.data = p.data.float()
p.grad.data = p.grad.data.float() |
def run_nodistributed(local_rank, func, cfg):
torch.cuda.set_device(local_rank)
cfg.process_rank = local_rank
func(cfg) |
.hypothesis_nested
def test_date_deserializing(testdir):
schema = {'openapi': '3.0.2', 'info': {'title': 'Test', 'description': 'Test', 'version': '0.1.0'}, 'paths': {'/teapot': {'get': {'summary': 'Test', 'parameters': [{'name': 'key', 'in': 'query', 'required': True, 'schema': {'allOf': [{'type': 'string', 'examp... |
def time_logger(func):
def wrapper(*args, **kw):
start_time = time.time()
print(f'Start running {func.__name__} at {get_cur_time()}')
ret = func(*args, **kw)
print(f'Finished running {func.__name__} at {get_cur_time()}, running time = {time2str((time.time() - start_time))}.')
... |
def check_full_copies(overwrite: bool=False):
diffs = []
for (target, source) in FULL_COPIES.items():
with open(source, 'r', encoding='utf-8') as f:
source_code = f.read()
with open(target, 'r', encoding='utf-8') as f:
target_code = f.read()
if (source_code != tar... |
class EmbedDropout(nn.Dropout):
def forward(self, sequences_batch):
ones = sequences_batch.data.new_ones(sequences_batch.shape[0], sequences_batch.shape[(- 1)])
dropout_mask = nn.functional.dropout(ones, self.p, self.training, inplace=False)
return (dropout_mask.unsqueeze(1) * sequences_batc... |
class DataTrainingArguments():
task_name: Optional[str] = field(default=None, metadata={'help': f'The name of the glue task to train on. choices {list(task_to_keys.keys())}'})
dataset_config_name: Optional[str] = field(default=None, metadata={'help': 'The configuration name of the dataset to use (via the datase... |
class _SessionState():
def __init__(self, session, hash_funcs):
self.__dict__['_state'] = {'data': {}, 'hash': None, 'hasher': _CodeHasher(hash_funcs), 'is_rerun': False, 'session': session}
def __call__(self, **kwargs):
for (item, value) in kwargs.items():
if (item not in self._stat... |
def build(x_channels, cond_channels, hparams, is_training):
if isinstance(hparams, str):
hparams = JsonConfig(hparams)
(graph, optim, lrschedule, criterion_dict) = (None, None, None, None)
(cpu, devices) = ('cpu', None)
get_loss = None
graph = Glow(x_channels, cond_channels, hparams)
gra... |
class SparseEdgeConvLayer(MessagePassing):
def __init__(self, in_channels, out_channels, improved=False, cached=False, bias=True, **kwargs):
super(SparseEdgeConvLayer, self).__init__(aggr=cfg.gnn.agg, **kwargs)
self.in_channels = in_channels
self.out_channels = out_channels
self.impr... |
class PredictJointModelStack(ModelStack[SupportsPredictJoint], SupportsPredictJoint):
def predict_joint(self, query_points: TensorType) -> tuple[(TensorType, TensorType)]:
(means, covs) = zip(*[model.predict_joint(query_points) for model in self._models])
return (tf.concat(means, axis=(- 1)), tf.con... |
def validate_dk_cvr(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(cvr.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
def totuple(a):
try:
return tuple((totuple(i) for i in a))
except TypeError:
return a |
def print_timedelta(*args, sep=' '):
global last_time
this_time = time.time()
logger.info('[%7.2f] %s', ((this_time - last_time) * 1000), sep.join(map(str, args)))
last_time = this_time |
def test_div():
var1 = optplan.Parameter()
var2 = optplan.Parameter()
div = (var2 / var1)
assert isinstance(div, optplan.Product) |
class RobustRandomCutForest(BaseModel):
def __init__(self, num_trees=4, shingle_size=4, tree_size=256):
from rrcf import rrcf
self.tree_size = tree_size
self.shingle_size = shingle_size
self.num_trees = num_trees
self.forest = []
for _ in range(self.num_trees):
... |
def register_Ns3TcpSocketFactory_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::TcpSocketFactory const &', 'arg0')])
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
return |
def set_param(torch_layer, weight, bias=None):
assert (torch_layer.weight.shape == weight.shape), '{} layer.weight does not match'.format(torch_layer)
torch_layer.weight = torch.nn.Parameter(weight)
if (bias is not None):
assert (torch_layer.bias.shape == bias.shape), '{} layer.bias does not match'.... |
def quantity_from_str(text):
(value_str, unit_str) = text.split(None, 1)
value = float(value_str)
if (unit_str.strip() == 'log_lsun'):
value = (10 ** (value + np.log10(const.L_sun.cgs.value)))
unit_str = 'erg/s'
unit = u.Unit(unit_str)
if (unit == u.L_sun):
return (value * co... |
def approx(expected, **kwargs):
class boolean_integer():
def __init__(self, value):
self.value = value
def __eq__(self, other):
return (bool(self.value) == bool(other))
def __ne__(self, other):
return (bool(self.value) != bool(other))
if isinstance(exp... |
def get_parameter_groups(model, weight_decay=1e-05, skip_list=(), get_num_layer=None, get_layer_scale=None):
parameter_group_names = {}
parameter_group_vars = {}
for (name, param) in model.named_parameters():
if (not param.requires_grad):
continue
if ((len(param.shape) == 1) or n... |
class Partition26(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/T5Block[15]/T5LayerFF[2]/T5LayerNorm[layer_norm]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[15]/T5LayerFF[2]/T5DenseReluDense[DenseReluDense]/Linear[wi]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[15]/T... |
class TestCabs(object):
def setup(self):
self.olderr = np.seterr(invalid='ignore')
def teardown(self):
np.seterr(**self.olderr)
def test_simple(self):
x = np.array([(1 + 1j), (0 + 2j), (1 + 2j), np.inf, np.nan])
y_r = np.array([np.sqrt(2.0), 2, np.sqrt(5), np.inf, np.nan])
... |
class ResNet(nn.Module):
def __init__(self, arch, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet, self).__init__()
self.name = arch
if (norm_layer is None):
norm_layer = nn... |
class SSIM():
def __init__(self):
self.win_size = None
self.gradient = False
self.data_range = 255
self.multichannel = True
self.gaussian_weights = False
self.full = False
def forward(self, img1, img2):
(img1, img2) = (img1.copy(), img2.copy())
ret... |
def group_chains(chain_list):
chains = []
while len(chain_list):
chain = set(chain_list.pop(0))
ii = 0
while (ii < len(chain_list)):
c1 = sorted(chain_list[ii])
is0 = (c1[0] in chain)
is1 = (c1[1] in chain)
if (is0 and is1):
... |
_utils.test(print_preprocessed_ir=True)
def test_func():
def bar(x):
return ((x * x), (- x))
a = ti.field(ti.i32, shape=(10,))
b = ti.field(ti.i32, shape=(10,))
def foo():
for i in a:
(a[i], b[i]) = bar(i)
foo()
for i in range(10):
assert (a[i] == (i * i))
... |
class GeniaProcessor(QueryNERProcessor):
def get_labels(self):
return ['cell_line', 'cell_type', 'DNA', 'RNA', 'protein', 'O'] |
def tile(imgs, rows=None, cols=None):
if ((rows is None) and (cols is None)):
rows = int(math.sqrt(len(imgs)))
if (rows is None):
rows = (((len(imgs) + cols) - 1) // cols)
else:
cols = (((len(imgs) + rows) - 1) // rows)
diff = ((rows * cols) - len(imgs))
if (diff != 0):
... |
.parametrize('dtype, storage_format', [(ti.f32, 'col_major'), (ti.f32, 'row_major'), (ti.f64, 'col_major'), (ti.f64, 'row_major')])
_utils.test(arch=ti.cpu)
def test_sparse_matrix_subtraction(dtype, storage_format):
n = 8
Abuilder = ti.linalg.SparseMatrixBuilder(n, n, max_num_triplets=100, dtype=dtype, storage_... |
class Indexer(object):
def __init__(self, index_dir):
print('lucene:', lucene.VERSION)
self.index_dir = index_dir
store = SimpleFSDirectory(Paths.get(self.index_dir))
analyzer = LimitTokenCountAnalyzer(StandardAnalyzer(), 1048576)
config = IndexWriterConfig(analyzer)
... |
def draw_rtt_1M(results):
SIZE = (2 ** 20)
results = results[(results[COLUMNS[1]] == SIZE)]
(Latency, STD) = (results[COLUMNS[2]], results[COLUMNS[3]])
plt.figure(figsize=(4, 4))
ind = range(5)
width = 0.8
plt.bar(ind, (Latency * 1000), width, label='usr', color=COLORS, linewidth=10)
plt... |
def test_sort_events(tmp_path: pathlib.Path) -> None:
events = create_events(tmp_path)
sorted_events = events.sort(os.path.join(tmp_path, 'sorted_events'), num_threads=2)
with sorted_events.reader() as reader:
all_sorted_events = list(reader)
assert (sorted(all_sorted_events) == sorted(all_event... |
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
best_filename = (('model_best_' + str(save_name)) + '.pth.tar')
shutil.copyfile(filename, best_filename) |
class NotSupportedError(Exception):
def __init__(self, message):
super().__init__(message) |
def get_charge(molecule):
logger.debug('Entering get_charge()')
return Chem.rdmolops.GetFormalCharge(molecule) |
class OperatorFPExceptionsTest(TestCase):
def test_fp_exception_divbyzero(self):
workspace.blobs['0'] = np.array([0.0], dtype=np.float32)
workspace.blobs['1'] = np.array([1.0], dtype=np.float32)
net = core.Net('test_fp')
net.Div(['1', '0'], 'out')
for throw_if_fp_exceptions i... |
def subsample_dataset(dataset, idxs, absolute=True):
mask = np.zeros(len(dataset)).astype('bool')
if (absolute == True):
mask[idxs] = True
else:
idxs = set(idxs)
mask = np.array([(i in idxs) for i in dataset.uq_idxs])
dataset.samples = [s for (m, s) in zip(mask, dataset.samples) ... |
class ComboMultiStepLR():
def __init__(self, optimizers, base_lr, **kwargs):
self.schedulers = dict()
for (name, opt) in optimizers.items():
self.schedulers[name] = WarmupMultiStepLR(opt, lr=base_lr, **kwargs)
self.last_epoch = 0
def set_batch_size(self, batch_size, lod):
... |
def get_user_input():
model_types = list(auto_module.configuration_auto.MODEL_NAMES_MAPPING.keys())
valid_model_type = False
while (not valid_model_type):
old_model_type = input('What is the model you would like to duplicate? Please provide the lowercase `model_type` (e.g. roberta): ')
if (o... |
('nlu_engine')
class SnipsNLUEngine(ProcessingUnit):
config_type = NLUEngineConfig
def __init__(self, config=None, **shared):
super(SnipsNLUEngine, self).__init__(config, **shared)
self.intent_parsers = []
self.dataset_metadata = None
def default_config(cls):
return None
... |
class CityscapesLabelTool(QtWidgets.QMainWindow):
def __init__(self):
super(CityscapesLabelTool, self).__init__()
configDir = os.path.dirname(__file__)
self.configFile = os.path.join(configDir, 'cityscapesLabelTool.conf')
self.config = configuration()
self.config.load(self.co... |
_test(assert_ii_1=False, intel=False)
def test_type_inference():
sdfg = program.to_sdfg()
sdfg.apply_transformations(FPGATransformSDFG)
f2cOperator = np.array([0, 1, 2, 3], dtype=np.uint32)
rc = np.array([42, 42, 42, 42], dtype=np.float64)
Axf = np.array([0, 2, 4, 6], dtype=np.float64)
x = np.ar... |
class InputBlockDAG(DAG):
def __init__(self, add_output=True, *args, **kwargs):
super().__init__(*args, **kwargs)
assert self.with_input_blocks, '`InputBlockDAG` class only handles `with_input_blocks=True`'
self.added_output_nodes = []
self.add_output = add_output
def _build_dag(... |
class StackedMultiLevelAttentionFusion(tf.keras.layers.Layer):
def __init__(self, filters=256, projection_dim=64, num_repeats=2, min_level=3, max_level=7, backbone_max_level=5, conv_2d_op_params=None, normalization_op_params=None, use_channel_attention=True, **kwargs):
super(StackedMultiLevelAttentionFusion... |
def get_width_manner_node_list(root):
node_list = []
queue = []
if (root is not None):
queue.append(root)
while (len(queue) != 0):
node = queue.pop(0)
node_list.append(node)
if (node.left is not None):
queue.append(node.left)
if (node.right is not None... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.