code stringlengths 101 5.91M |
|---|
class LmdbDataset(Dataset):
def __init__(self, root, opt, mode='train'):
self.root = root
skip = 0
self.opt = opt
self.mode = mode
self.env = lmdb.open(root, max_readers=32, readonly=True, lock=False, readahead=False, meminit=False)
if (not self.env):
prin... |
def find_nearest_training(question, n_results=10):
q_rep = embed_questions_for_retrieval([question], qar_tokenizer, qar_model)
(D, I) = eli5_train_q_index.search(q_rep, n_results)
nn_examples = [eli5_train[int(i)] for i in I[0]]
return nn_examples |
def tokenize(impressions, tokenizer):
new_impressions = []
print('\nTokenizing report impressions. All reports are cut off at 512 tokens.')
for i in tqdm(range(impressions.shape[0])):
tokenized_imp = tokenizer.tokenize(impressions.iloc[i])
if tokenized_imp:
res = tokenizer.encode... |
class VAE(BaseHModel):
def __init__(self, args):
super(VAE, self).__init__(args)
def create_model(self, args):
if (args.dataset_name == 'freyfaces'):
self.h_size = 210
elif ((args.dataset_name == 'cifar10') or (args.dataset_name == 'svhn')):
self.h_size = 384
... |
def get_feature_names(quantized_features):
feature_names = ['source_identity']
for x in quantized_features:
split = x.split('_')
if ('source' in split):
continue
else:
feat = '_'.join(split[:(- 1)])
if (feat not in feature_names):
featu... |
def all_reduce_multigpu(tensor_list, op=reduce_op.SUM, group=group.WORLD):
assert (torch.distributed.deprecated._initialized == _INITIALIZED_PG), 'collective only supported in process-group mode'
return torch._C._dist_all_reduce_multigpu(tensor_list, op, group) |
class BaseUnsField(BaseAnnDataField):
_attr_name = _constants._ADATA_ATTRS.UNS
def __init__(self, registry_key: str, uns_key: Optional[str], required: bool=True) -> None:
super().__init__()
if (required and (uns_key is None)):
raise ValueError('`uns_key` cannot be `None` if `required... |
class get_numpy_include():
def __str__(self):
import numpy
return numpy.get_include() |
def _word_accuracy(label_file, pred_file):
with codecs.getreader('utf-8')(tf.gfile.GFile(label_file, 'r')) as label_fh:
with codecs.getreader('utf-8')(tf.gfile.GFile(pred_file, 'r')) as pred_fh:
(total_acc, total_count) = (0.0, 0.0)
for sentence in label_fh:
labels = ... |
class objectnet(iData):
use_path = True
train_trsf = build_transform(True, None)
test_trsf = build_transform(False, None)
common_trsf = []
class_order = np.arange(200).tolist()
def download_data(self):
train_dir = './data/objectnet/train/'
test_dir = './data/objectnet/test/'
... |
class MSRVTTQADataset(BaseDataset):
def __init__(self, *args, split='', **kwargs):
assert (split in ['train', 'val', 'test'])
self.split = split
self.metadata = None
self.ans_lab_dict = None
if (split == 'train'):
names = ['msrvtt_qa_train']
elif (split ==... |
class SICEValidation(SICE):
def __init__(self, dir_data, **kwargs):
super().__init__(dir_data, split='val', **kwargs)
self.transforms = tf.Compose([CenterCrop(size=self.crop_size), ImageToLDMTensor()]) |
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
cls.add_method('HasNext', 'bool', [], is_const=True)... |
def RudinBall():
return UniqueSimplicialComplex([[1, 9, 2, 5], [1, 10, 2, 5], [1, 10, 5, 11], [1, 10, 7, 11], [1, 13, 5, 11], [1, 13, 7, 11], [2, 10, 3, 6], [2, 11, 3, 6], [2, 11, 6, 12], [2, 11, 8, 12], [2, 14, 6, 12], [2, 14, 8, 12], [3, 11, 4, 7], [3, 12, 4, 7], [3, 12, 5, 9], [3, 12, 7, 9], [3, 13, 5, 9], [3, 1... |
def _Workspace_fetch_int8_blob(ws, name):
result = ws.fetch_blob(name)
assert isinstance(result, tuple), 'You are not fetching an Int8Blob {}. Please use fetch_blob'.format(StringifyBlobName(name))
return Int8Tensor(*result) |
def cleanse_nans_from_metrics(metrics, test_name, selector_name):
metrics['removed_steps'] = pd.DataFrame.from_dict(metrics.ply_where((X.name == test_name)).apply((lambda x: np.array(x['steps'])[np.isnan(x['values'])]), axis=1))
removed_steps = metrics.ply_where((X.name == test_name))
removed_steps = dict(z... |
class Generator(object):
def pack_msg(speaker, utt, **kwargs):
resp = {k: v for (k, v) in kwargs.items()}
resp['speaker'] = speaker
resp['utt'] = utt
return resp
def pprint(dialogs, in_json, domain_spec, output_file=None):
f = (sys.stdout if (output_file is None) else ope... |
def perform_val(model, HEAD1, HEAD_test1, cfg, feature_dim, pair_a, pair_b):
(test_lb2idxs, test_idx2lb) = read_meta(cfg.test_data['label_path'])
test_inst_num = len(test_idx2lb)
model.eval()
HEAD1.eval()
HEAD_test1.eval()
for (k, v) in cfg.model['kwargs'].items():
setattr(cfg.test_data,... |
class TestUnmaskOp(serial.SerializedTestCase):
(N=st.integers(min_value=2, max_value=20), dtype=st.sampled_from([np.bool_, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.float16, np.float32, np.float64]), **hu.gcs)
def test(self, N, dtype, gc, dc):
if (dtype is np.bool_):
all... |
def TStrUtil_SplitSentences(ChA, SentenceV):
return _snap.TStrUtil_SplitSentences(ChA, SentenceV) |
class Path(object):
def db_root_dir(database):
if (database == 'pascal'):
return '/path/to/PASCAL/VOC2012'
elif (database == 'sbd'):
return '/path/to/SBD/'
else:
print('Database {} not available.'.format(database))
raise NotImplementedError
... |
def _validate_pruning_amount_init(amount):
if (not isinstance(amount, numbers.Real)):
raise TypeError('Invalid type for amount: {}. Must be int or float.'.format(amount))
if ((isinstance(amount, numbers.Integral) and (amount < 0)) or ((not isinstance(amount, numbers.Integral)) and ((float(amount) > 1.0)... |
def register_Ns3LteMacSapProviderTransmitPduParameters_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteMacSapProvider::TransmitPduParameters const &', 'arg0')])
cls.add_instance_attribute('componentCarrierId', 'uint8_t', is_const=False)
cls.add_instance_attribute('... |
def main(hparams):
torch.backends.cudnn.deterministic = True
random.seed(hparams.seed)
torch.manual_seed(hparams.seed)
torch.cuda.manual_seed(hparams.seed)
np.random.seed(hparams.seed)
model = AffWild2VA(hparams)
if hparams.fusion_checkpoint:
checkpoint = torch.load(hparams.fusion_ch... |
class LFHImportanceMetric(BaseImportanceMetric):
def __init__(self, graph: Graph, representative_data_gen: Callable, fw_impl: PruningFrameworkImplementation, pruning_config: PruningConfig, fw_info: FrameworkInfo):
self.float_graph = graph
self.representative_data_gen = representative_data_gen
... |
def identity_block(input_tensor, kernel_size, filters, stage, block, dilation=1):
(filters1, filters2, filters3) = filters
if (K.image_data_format() == 'channels_last'):
bn_axis = 3
else:
bn_axis = 1
conv_name_base = ((('res' + str(stage)) + block) + '_branch')
bn_name_base = ((('bn'... |
def readable_size(n):
sizes = ['K', 'M', 'G']
fmt = ''
size = n
for (i, s) in enumerate(sizes):
nn = (n / (1000 ** (i + 1)))
if (nn >= 1):
size = nn
fmt = sizes[i]
else:
break
return ('%.2f%s' % (size, fmt)) |
class TestBleuMetricSpec(TestTextMetricSpec):
def test_bleu(self):
metric_spec = BleuMetricSpec({})
return self._test_metric_spec(metric_spec=metric_spec, hyps=['A B C D E F', 'A B C D E F'], refs=['A B C D E F', 'A B A D E F'], expected_scores=[100.0, 69.19]) |
def random_selection(dataset, subset_size):
l = sum((1 for line in open(dataset, 'r')))
return sorted(random.sample(xrange(l), subset_size)) |
class MLP_train():
def __init__(self, net, epochs=10, optimizer='Adam', momentum=0.9, lr=0.001, num_labels=3):
assert (optimizer in ['Adam', 'SGD'])
self.lr = lr
self.net = net
self.epochs = epochs
self.momentum = momentum
self.criterion = nn.CrossEntropyLoss()
... |
class PopREO(BaseMetric):
def __init__(self, recommendations, config, params, eval_objects):
super().__init__(recommendations, config, params, eval_objects)
self._cutoff = self._evaluation_objects.cutoff
self._relevance = self._evaluation_objects.relevance.binary_relevance
self._shor... |
def check_yaml_vs_script(hparam_file, script_file):
print(('Checking %s...' % hparam_file))
if (not os.path.exists(hparam_file)):
print(('File %s not found!' % (hparam_file,)))
return False
if (not os.path.exists(script_file)):
print(('File %s not found!' % (script_file,)))
r... |
class FormDataParser(object):
def __init__(self, stream_factory=None, charset='utf-8', errors='replace', max_form_memory_size=None, max_content_length=None, cls=None, silent=True):
if (stream_factory is None):
stream_factory = default_stream_factory
self.stream_factory = stream_factory
... |
def skip_backend(backend):
try:
return backend.__ua_cache__['skip']
except AttributeError:
backend.__ua_cache__ = {}
except KeyError:
pass
ctx = _SkipBackendContext(backend)
backend.__ua_cache__['skip'] = ctx
return ctx |
class BiasParameter(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _BIASPARAMETER |
class GConvLSTM(torch.nn.Module):
def __init__(self, in_channels: int, out_channels: int, K: int=7, normalization: str='sym', id: int=(- 1), bias: bool=True):
super(GConvLSTM, self).__init__()
assert (id >= 0), 'kwarg id is required.'
self.in_channels = in_channels
self.out_channels ... |
def main(arguments):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-c', help='Path to the file containing the parameters for the experiment', type=str, default='temp_cfg/0.json')
args = parser.parse_args(arguments)
cfg_... |
class ResNet101(nn.Module):
def __init__(self, n_inputs=12, numCls=17):
super().__init__()
resnet = models.resnet101(pretrained=False)
self.conv1 = nn.Conv2d(n_inputs, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
self.encoder = nn.Sequential(self.conv1, resnet.b... |
(scope='session')
def all_filenames(root_data_dir) -> list[Path]:
all_filenames = []
for d in ((root_data_dir / _d) for _d in _dirnames):
all_filenames += [(d / fname) for fname in d.iterdir()]
return all_filenames |
def check_EZ(EZ0, EZ, S):
EZsum = (EZ0 + EZ.sum(axis=(1, 3)))
if (not np.allclose(S, EZsum)):
print('_check_Z failed. Zsum does not add up to S!')
import pdb
pdb.set_trace() |
def train_printer():
print(f'Epoch {epoch}, Iteration {iter_counter}')
print(f'Train Set Loss: {loss_hist[counter]:.2f}')
print(f'Test Set Loss: {test_loss_hist[counter]:.2f}')
print_batch_accuracy(data, targets, train=True)
print_batch_accuracy(test_data, test_targets, train=False)
print('\n') |
class ParamViewer():
def __init__(self, shape, par_map, par_selection):
default_backend = pyhf.default_backend
batch_size = (shape[0] if (len(shape) > 1) else None)
fullsize = default_backend.product(default_backend.astensor(shape))
flat_indices = default_backend.astensor(range(int(f... |
_processor('blip2_image_eval')
class Blip2ImageEvalProcessor(BlipImageBaseProcessor):
def __init__(self, image_size=224, mean=None, std=None, do_normalize=True):
super().__init__(mean=mean, std=std, do_normalize=do_normalize)
self.transform = transforms.Compose([transforms.Resize((image_size, image_... |
def generate_module_content_repr(m: GfxRuntime140, module_name: str, cgraph_kernel_names: Set[str]) -> List[str]:
out = []
if module_name:
module_name = f'AotModule_{module_name}'
else:
module_name = 'AotModule'
out += [f'struct {module_name} : public ti::AotModule {{', f' explicit {mod... |
def quantize_weights_op(quant_scale, max_value):
ops = [v.assign(quantize(v, quant_scale, float(max_value))) for v in tf.trainable_variables()]
return tf.group(*ops) |
class Polygon(Element):
def __init__(self, LP, Priority=1, elevation=254, normdir=2, coordsystem=0):
Element.__init__(self, 'Polygon', Priority=str(Pr), Elevation=str(elevation), NormDir=str(normdir), CoordSystem=str(coordsystem))
for P in LP:
V = Vertex(x=P[0], y=P[1])
self.... |
def _unique1d(ar, return_index=False, return_inverse=False, return_counts=False):
ar = np.asanyarray(ar).flatten()
optional_indices = (return_index or return_inverse)
if optional_indices:
perm = ar.argsort(kind=('mergesort' if return_index else 'quicksort'))
aux = ar[perm]
else:
... |
def simCreateTexture(fileName, options):
handle = lib.simCreateTexture(fileName.encode('ascii'), options, ffi.NULL, ffi.NULL, ffi.NULL, 0, ffi.NULL, ffi.NULL, ffi.NULL)
_check_return(handle)
return handle |
def _test_classification_loader():
loader_ins = TimeSeriesLoader('classification', root='/meladyfs/newyork/nanx/Datasets/PSML')
(train_loader, test_loader) = loader_ins.load(batch_size=32, shuffle=True)
print(f'train_loader: {len(train_loader)}')
for i in train_loader:
(feature, label) = i
... |
class BasicIterativeMethod(ProjectedGradientDescent):
attack_params = ProjectedGradientDescent.attack_params
def __init__(self, classifier, norm=np.inf, eps=0.3, eps_step=0.1, max_iter=100, targeted=False, batch_size=1, distribution=None):
super(BasicIterativeMethod, self).__init__(classifier, norm=norm... |
def remove_file(f_list):
f_list = (f_list if isinstance(f_list, list) else [f_list])
for f_name in f_list:
silent_remove(f_name) |
def main():
target = 'AD'
bl = Baseline(target)
(X, y) = bl.load_data()
bl.get_classifiers(X, y) |
class ContinueStatNode(StatNode):
child_attrs = []
is_terminator = True
def analyse_expressions(self, env):
return self
def generate_execution_code(self, code):
if (not code.continue_label):
error(self.pos, 'continue statement not inside loop')
return
code... |
def test_crf():
batch_size = 10
step = 20
tag_dim = 5
emissions = torch.randn(batch_size, step, tag_dim)
tag_ids = torch.randint(0, tag_dim, (batch_size, step))
seq_lens = torch.randint(1, step, (batch_size,))
mask = (torch.arange(step).unsqueeze(0).expand(batch_size, (- 1)) >= seq_lens.unsq... |
def unpack_and_unpad(lstm_out, reorder):
(unpacked, sizes) = pad_packed_sequence(lstm_out, batch_first=True)
unpadded = [unpacked[idx][:val] for (idx, val) in enumerate(sizes)]
regrouped = [unpadded[idx] for idx in reorder]
return regrouped |
def cvsecs(*args):
if (len(args) == 1):
return float(args[0])
elif (len(args) == 2):
return ((60 * float(args[0])) + float(args[1]))
elif (len(args) == 3):
return (((3600 * float(args[0])) + (60 * float(args[1]))) + float(args[2])) |
def generate_job(throughputs, reference_worker_type='v100', rng=None, job_id=None, fixed_job_duration=None, generate_multi_gpu_jobs=False, generate_multi_priority_jobs=False, run_dir=None, scale_factor_generator_func=_generate_scale_factor, duration_generator_func=_generate_duration, scale_factor_rng=None, duration_rng... |
def check_resume(opt, resume_iter):
if opt['path']['resume_state']:
networks = [key for key in opt.keys() if key.startswith('network_')]
flag_pretrain = False
for network in networks:
if (opt['path'].get(f'pretrain_{network}') is not None):
flag_pretrain = True
... |
def main():
args = parseArgs()
if (args.metric == 'fid'):
metric = FID()
elif (args.metric == 'ssim'):
metric = SSIM()
if (args.model in ['neural_style_transfer', 'fast_neural_style_transfer']):
data_path_real = os.path.join(args.output_path, 'real')
data_path_fake = os.p... |
class Repository(Common):
def __init__(self, base_dir='.', log_level=Log.error):
self.set_base_dir(base_dir)
self.LogLevel = log_level
DEFAULT_DIR_MODE = 504
DEFAULT_HOSTS_CONF_MODE = 416
def secure_check(self, path, ref_mode):
if (os.path.exists(path) == False):
if (... |
class AppContext(object):
def __init__(self, app):
self.app = app
self.url_adapter = app.create_url_adapter(None)
self.g = app.app_ctx_globals_class()
self._refcnt = 0
def push(self):
self._refcnt += 1
if hasattr(sys, 'exc_clear'):
sys.exc_clear()
... |
def run_worker(factory, to_worker, to_sampler, worker_number, agent, env):
to_sampler.cancel_join_thread()
setproctitle.setproctitle(('worker:' + setproctitle.getproctitle()))
inner_worker = factory(worker_number)
inner_worker.update_agent(cloudpickle.loads(agent))
inner_worker.update_env(env)
v... |
def save_gt_instance(path, gt_inst, nyu_id=None):
if (nyu_id is not None):
sem = (gt_inst // 1000)
ignore = (sem == 0)
ins = (gt_inst % 1000)
nyu_id = np.array(nyu_id)
sem = nyu_id[(sem - 1)]
sem[ignore] = 0
gt_inst = ((sem * 1000) + ins)
np.savetxt(path, ... |
def overall_jaccard_index_calc(jaccard_list):
try:
jaccard_sum = sum(jaccard_list)
jaccard_mean = (jaccard_sum / len(jaccard_list))
return (jaccard_sum, jaccard_mean)
except Exception:
return 'None' |
def isAcidic(mol):
if (nAcidicGroup(mol) > nBasicGroup(mol)):
return 1
else:
return 0 |
class DebertaTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, do_lo... |
def load_flax_weights_in_pytorch_model(pt_model, flax_state):
try:
import torch
except ImportError:
logger.error('Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see and for installation instructions.')
raise
is_type_bf16 = flatten_dict(jax... |
class build_scripts(old_build_scripts):
def generate_scripts(self, scripts):
new_scripts = []
func_scripts = []
for script in scripts:
if is_string(script):
new_scripts.append(script)
else:
func_scripts.append(script)
if (not fu... |
def build_constrained_ellipsoidal_problem():
var = Variable(2)
x_var = var[0]
y_var = var[1]
obj = ((((x_var ** 2) + (2 * (y_var ** 2))) - (5 * y_var)) - ((2 * x_var) * y_var))
cons_ineq = [((y_var - x_var) + 1)]
opt = OptimizationProblem(obj, cons_ineq=cons_ineq)
param = DirectParam(np.arra... |
class TestCellPrecision():
def instance(self):
return CellPrecisionTag()
def test_no_matching_cells(self, instance):
target = [['a', 'b'], ['c', 'd']]
prediction = [['x', 'y'], ['z', 'w']]
result = instance.evaluate_single_test_metric(target, prediction)
assert (result ==... |
def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):
(c, lower) = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False, check_finite=check_finite)
return (c, lower) |
class ResetTags(Tagger):
def tag(self, document, ngrams=6, stopwords=[]):
document.annotations = {i: {} for i in range(len(document.sentences))} |
def standardConvection(rhs, u_dealias, u_hat, K, VFSp, FSTp, FCTp, work, mat, la):
rhs[:] = 0
U = u_dealias
Uc = work[(U, 1, True)]
Uc2 = work[(U, 2, True)]
dudx = project(Dx(u_hat[0], 0, 1), FSTp).backward()
dvdx = project(Dx(u_hat[1], 0, 1), FCTp).backward()
dwdx = project(Dx(u_hat[2], 0, ... |
class TFAlbertForSequenceClassification(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def bspline(x, n):
ax = (- abs(asarray(x)))
(funclist, condfuncs) = _bspline_piecefunctions(n)
condlist = [func(ax) for func in condfuncs]
return piecewise(ax, condlist, funclist) |
def test_reset(stopping_condition):
stopping_condition.after_search_iteration(None)
stopping_condition.reset()
assert (stopping_condition.current_value() == 0) |
def resnet50(pretrained=False, **kwargs):
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
print('Loading pretrained Resnet 50 weights.')
return model |
def find_all(filter_dict):
if (not filter_dict):
return entries
filtered_entries = []
for entry in entries:
is_match = True
for (k, v) in filter_dict.items():
if ((k not in entry) or (entry[k] != v)):
is_match = False
break
if is_ma... |
def percent_good_pts(x_fake, means, threshold):
count = 0
counts = np.zeros(len(means))
visited = set()
for point in x_fake:
minimum = 0
diff_minimum = [.0, .0]
for (i, mean) in enumerate(means):
diff = np.abs((point - mean))
if np.all((diff < threshold)):... |
def is_past_tense(c, verb_window='left'):
past_tense = set(['VBD', 'VBN'])
btw = list(get_between_tokens(c, attrib='pos_tags', case_sensitive=True))
return (True if past_tense.intersection(btw) else False) |
def average_checkpoints(inputs):
params_dict = collections.OrderedDict()
params_keys = None
new_state = None
num_models = len(inputs)
for fpath in inputs:
with PathManager.open(fpath, 'rb') as f:
state = torch.load(f, map_location=(lambda s, _: torch.serialization.default_restore... |
def getidperobject(object_name, id_env, id_mapping):
object_name = object_name.lower().replace(' ex', '_')
cont_object = 0
for (elem, id_en) in id_mapping.items():
if (id_en == int(id_env)):
if (object_name == 'door'):
raise ValueError
return int(elem[1])
... |
.parametrize('observation_shape', [(100,)])
.parametrize('batch_size', [32])
def test_min_max_observation_scaler(observation_shape: Sequence[int], batch_size: int) -> None:
shape = (batch_size, *observation_shape)
observations = np.random.random(shape).astype('f4')
maximum = observations.max(axis=0)
min... |
class CsBbox3d(CsObject):
def __init__(self):
CsObject.__init__(self, CsObjectType.BBOX3D)
self.bbox_2d = None
self.center = []
self.dims = []
self.rotation = []
self.instanceId = (- 1)
self.label = ''
self.score = (- 1.0)
def __str__(self):
... |
def get_task_dataset(data, args):
nentity = len(np.unique(data['train']['edge_index'].reshape((- 1))))
nrelation = len(np.unique(data['train']['edge_type']))
train_triples = np.stack((data['train']['edge_index'][0], data['train']['edge_type'], data['train']['edge_index'][1])).T
valid_triples = np.stack(... |
def function_factory(name, nargs=0, latex_name=None, conversions=None, evalf_params_first=True, eval_func=None, evalf_func=None, conjugate_func=None, real_part_func=None, imag_part_func=None, derivative_func=None, tderivative_func=None, power_func=None, series_func=None, print_func=None, print_latex_func=None):
cla... |
.cpublas
def test_openblas_compiles():
A = np.random.rand(2, 3)
B = np.random.rand(3, 4)
C = np.random.rand(2, 4)
blas.default_implementation = 'OpenBLAS'
def prog(A, B, C):
C[:] = (A B)
prog(A, B, C) |
class DMA_nonzero_reg(atomic_reg):
OP_NAME = 'DMA_nonzero'
_fields_ = [('intr_en', ctypes.c_uint64, 1), ('stride_enable', ctypes.c_uint64, 1), ('nchw_copy', ctypes.c_uint64, 1), ('cmd_short', ctypes.c_uint64, 1), ('reserved', ctypes.c_uint64, 1), ('reserved', ctypes.c_uint64, 4), ('reserved', ctypes.c_uint64, 2... |
def tok2int_list(src_list, tokenizer, max_seq_length, max_seq_size=(- 1)):
inp_padding = list()
msk_padding = list()
seg_padding = list()
for (step, sent) in enumerate(src_list):
(input_ids, input_mask, input_seg) = tok2int_sent(sent, tokenizer, max_seq_length)
inp_padding.append(input_i... |
def test_tensordot_1():
def tensordot_1(A: dace.float32[(3, 3, 3, 3, 3, 3)], B: dace.float32[(3, 3, 3, 3, 3, 3)]):
return np.tensordot(A, B, axes=([0, 3], [4, 2]))
A = np.arange((3 ** 6), dtype=np.float32).reshape(3, 3, 3, 3, 3, 3)
B = np.arange((3 ** 6), dtype=np.float32).reshape(3, 3, 3, 3, 3, 3)
... |
def foo(sleep=False):
print('Hello world.')
if sleep:
pointless_sleep()
baz()
print('Good by.') |
_INGREDIENT.capture
def build_model(graph_adj, node_features, labels, dataset_indices_placeholder, train_feed, trainval_feed, val_feed, test_feed, weight_decay, normalize_features, num_layers, hidden_size, num_kernels, r, dropout_prob, alt_opt):
dropout = tf.placeholder(dtype=tf.float32, shape=[])
train_feed[dr... |
def test_keyword_args_and_generalized_unpacking():
def f(*args, **kwargs):
return (args, kwargs)
assert (m.test_tuple_unpacking(f) == (('positional', 1, 2, 3, 4, 5, 6), {}))
assert (m.test_dict_unpacking(f) == (('positional', 1), {'key': 'value', 'a': 1, 'b': 2}))
assert (m.test_keyword_args(f) ... |
class VariationalWarpEncoder(CriticModelMixin, StochasticActorModelMixin, BaseModel):
def __init__(self, batch_of_users, heldout_batch, input_dim=None, evaluation_metric='NDCG', batch_size=500, lr_actor=0.001, lr_critic=0.0001, lr_ac=2e-06, ac_reg_loss_scaler=0.0, actor_reg_loss_scaler=0.0001, **kwargs):
lo... |
def slice_list(in_list, lens):
if (not isinstance(lens, list)):
raise TypeError('"indices" must be a list of integers')
elif (sum(lens) != len(in_list)):
raise ValueError('sum of lens and list length does not match: {} != {}'.format(sum(lens), len(in_list)))
out_list = []
idx = 0
for... |
def fix_rows(table: str, prefix: str, root: str, target_root: str, all_concepts: Dict[(str, Any)], child: str) -> None:
try:
source_path = os.path.join(root, table, child)
target_path = os.path.join(target_root, table, child)
with io.TextIOWrapper(zstandard.ZstdDecompressor().stream_reader(o... |
class OperatorTests(unittest.TestCase):
def setUp(self):
rng = np.random.RandomState(42)
Cluster.global_rng = rng
Genotype.global_rng = rng
setattr(Cluster, 'num_dims', 2)
setattr(Cluster, 'initial_mean_upper', 1.0)
setattr(Cluster, 'initial_cov_upper', 0.5)
c... |
def mse_loss(f_1, f_2):
feat_1 = f_1.dense()
(N, C, D, H, W) = feat_1.shape
feat_1 = feat_1.view(N, (C * D), H, W)
feat_2 = f_2.dense().view(N, (C * D), H, W)
return (F.mse_loss(feat_1, feat_2.detach(), reduction='sum') / (f_2.features.shape[0] * 10)) |
def get_algorithm(config, expl_path_collector, eval_path_collector):
algorithm = TorchMBRLAlgorithm(trainer=config['trainer'], exploration_policy=config['exploration_policy'], model_trainer=config['model_trainer'], exploration_env=config['exploration_env'], evaluation_env=config['evaluation_env'], replay_buffer=con... |
class PeriodMapping(SageObject):
def __init__(self, modsym, A):
self.__modsym = modsym
self.__domain = modsym.ambient_module()
self.__A = A
A.set_immutable()
def modular_symbols_space(self):
return self.__modsym
def __call__(self, x):
if isinstance(x, FreeModu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.