code stringlengths 101 5.91M |
|---|
_loss
def mse_loss_with_gmof(pred, target, sigma):
loss = F.mse_loss(pred, target, reduction='none')
loss = gmof(loss, sigma)
return loss |
def bench_group(model_list, bench_name, bench_group, bench_args):
print_stderr('Benchmarking {}s...'.format(bench_name))
nn_results = bench(get_nn_runners(*model_list), bench_group, **bench_args)
print_stderr('')
return nn_results |
def define_env(env):
def models_by_organization():
schema = read_schema(SCHEMA_CLASSIC_YAML_FILENAME)
result = defaultdict(list)
name_to_model_object = {}
for model_object in ALL_MODELS:
name_to_model_object[model_object.name] = model_object
for model_field in sch... |
class MLPEBM_cat(nn.Module):
def __init__(self, nin, n_proj, n_cat=256, nint=256, nout=1):
super().__init__()
self.proj = nn.Linear(n_cat, n_proj)
self.n_proj = n_proj
self.net = mlp_ebm((nin * n_proj), nint, nout=nout)
def forward(self, x):
xr = x.view((x.size(0) * x.siz... |
def validate(opt, val_loader, model, epoch, mode, split):
print('Validate {} {}...'.format(mode, split))
(img_embs, cap_embs) = encode_finetune_data(model, val_loader, opt.no_context, opt.no_image, opt.log_step, logging.info)
((r1, r5, r10, medr, meanr), (rank, top1)) = i2t_finetune(img_embs, cap_embs, meas... |
def build(session_file):
logger.info('Gathering frequency statistics ...')
freq_dict = collections.Counter()
train_file = open(session_file, 'r')
for (num, line) in enumerate(train_file):
if ((num % 1000) == 0):
logger.info('{} sessions / {} queries'.format(num, len(freq_dict)))
... |
class HiddenConf(object):
def __init__(self, name, parent_build=None, filters=None):
self.name = name
self.parent_build = parent_build
self.filters = filters
def gen_workflow_job(self, phase):
return {self.gen_build_name(phase): {'requires': [self.parent_build.gen_build_name('bui... |
def run_prequential_supervised(stream, learner, max_samples, n_wait, y_expected=None):
stream.restart()
y_pred = np.zeros((max_samples // n_wait), dtype=np.int)
y_true = np.zeros((max_samples // n_wait), dtype=np.int)
j = 0
for i in range(max_samples):
(X, y) = stream.next_sample()
i... |
def rand_like(g, self, dtype, layout=None, device=None, pin_memory=False, memory_format=None):
dtype = sym_help._get_const(dtype, 'i', 'dtype')
if (dtype is None):
dtype = 6
return g.op('RandomUniformLike', self, dtype_i=sym_help.scalar_type_to_onnx[dtype]) |
def download_and_extract(root: Path, info: DownloadInfo) -> None:
root.mkdir(parents=True, exist_ok=True)
downloaded_file_path = (root / info.url.split('/')[(- 1)])
if downloaded_file_path.exists():
logger.info('Existing dataset archive found. Skipping download stage.')
else:
logger.info... |
def interpret_args():
parser = argparse.ArgumentParser()
parser.add_argument('--raw_train_filename', type=str, default='../atis_data/data/resplit/processed/train_with_tables.pkl')
parser.add_argument('--raw_dev_filename', type=str, default='../atis_data/data/resplit/processed/dev_with_tables.pkl')
parse... |
(scope='module')
def predict_sorted_dict():
converted_dict = {}
for (user, item, score) in recs_data:
converted_dict.setdefault(user, [])
converted_dict[user].append((item, score))
for (user, items) in converted_dict.items():
items = sorted(items, key=(lambda x: x[1]), reverse=True)
... |
class GCN(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, num_layers, dropout):
super(GCN, self).__init__()
self.convs = torch.nn.ModuleList()
self.convs.append(GCNConv(in_channels, hidden_channels, cached=True))
self.bns = torch.nn.ModuleList()
... |
def set_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
cudnn.deterministic = True
cudnn.benchmark = False |
class AutoModelForMultipleChoice():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class BackboneTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = AttrDict(trial_context.get_hparams())
self.last_epoch = 0
self.download_directory = self.download_data_from_s3()
dataset_hypers = {'s... |
class TestParent3(UniqueRepresentation, Parent):
def __init__(self):
from sage.categories.sets_cat import Sets
Parent.__init__(self, category=Sets())
class Element(ElementWrapper):
pass |
def hits_at_k(examples, scores, all_answers, verbose=False):
assert (len(examples) == scores.shape[0])
dummy_mask = [DUMMY_ENTITY_ID, NO_OP_ENTITY_ID]
for (i, example) in enumerate(examples):
(e1, e2, r) = example
e2_multi = (list(all_answers[e1][r]) + dummy_mask)
target_score = scor... |
def shape_list(x):
x = tf.convert_to_tensor(x)
if (x.get_shape().dims is None):
return tf.shape(x)
static = x.get_shape().as_list()
shape = tf.shape(x)
ret = []
for i in range(len(static)):
dim = static[i]
if (dim is None):
dim = shape[i]
ret.append(di... |
def main(config):
device = torch.device(('cuda' if config.is_gpu else 'cpu'))
print(('using ' + str(device)))
model_motion = slowfast()
model_motion = model_motion.to(device)
model = UGC_BVQA_model.resnet50(pretrained=False)
model = torch.nn.DataParallel(model)
model = model.to(device=device... |
class PSAMask(nn.Module):
def __init__(self, psa_type, mask_size=None):
super(PSAMask, self).__init__()
assert (psa_type in ['collect', 'distribute'])
if (psa_type == 'collect'):
psa_type_enum = 0
else:
psa_type_enum = 1
self.psa_type_enum = psa_type_e... |
class Modulator(nn.Module):
def __init__(self, dim_in, dim_hidden, num_layers):
super().__init__()
self.layers = nn.ModuleList([])
for ind in range(num_layers):
is_first = (ind == 0)
dim = (dim_in if is_first else (dim_hidden + dim_in))
self.layers.append(... |
class OutputTransition(nn.Module):
def __init__(self, inChans, elu, nll):
super(OutputTransition, self).__init__()
self.conv1 = nn.Conv3d(inChans, 2, kernel_size=5, padding=2)
self.bn1 = nn.InstanceNorm3d(2)
self.conv2 = nn.Conv3d(2, 2, kernel_size=1)
self.relu1 = ELUCons(elu... |
def test_nested_globals():
def instantiated_global2(A):
A[cfg.q] = cfg.cloned.p
A = np.random.rand(10)
reg_A = np.copy(A)
reg_A[cfg.q] = cfg.cloned.p
instantiated_global2(A)
assert np.allclose(A, reg_A) |
def efficientnet_b8(pretrained=False, **kwargs):
model = _gen_efficientnet('efficientnet_b8', channel_multiplier=2.2, depth_multiplier=3.6, pretrained=pretrained, **kwargs)
return model |
def make_dataset(dir):
images = []
assert os.path.isdir(dir), ('%s is not a valid directory' % dir)
new_root = './fashion_data'
if (not os.path.exists(new_root)):
os.mkdir(new_root)
train_root = './fashion_data/train'
if (not os.path.exists(train_root)):
os.mkdir(train_root)
... |
def quadratic_residues(n):
n = abs(int(n))
return sorted(set((ZZ(((a * a) % n)) for a in range(((n // 2) + 1))))) |
def hipify(project_directory, show_detailed=False, extensions=('.cu', '.cuh', '.c', '.cc', '.cpp', '.h', '.in', '.hpp'), output_directory='', includes=(), extra_files=(), out_of_place_only=False, ignores=(), show_progress=True, hip_clang_launch=False, is_pytorch_extension=False, clean_ctx=None):
if (project_directo... |
def snip_download(outfolder='data/downloaded', start=0, end=2313, dl_dedup_set=True):
metadata_dir = os.path.join(outfolder, 'metadata')
dedup_set_path = os.path.join(outfolder, 'is_dup_mlp_1024_128_gelu_snn_2layer_notext.npy')
os.makedirs(metadata_dir, exist_ok=True)
if dl_dedup_set:
print('dow... |
_utils.test(require=ti.extension.sparse, exclude=ti.metal)
def test_chain_compare():
a = ti.field(ti.i32)
ti.root.dynamic(ti.i, 256).place(a)
b = ti.field(ti.i32, shape=())
c = ti.field(ti.i32, shape=())
d = ti.field(ti.i32, shape=())
def func():
b[None] = 2
c[None] = 3
d... |
class TrackingAnything():
def __init__(self, sam_checkpoint, cutie_checkpoint, propainter_checkpoint, raft_checkpoint, flow_completion_checkpoint, args):
self.args = args
self.samcontroler = SamControler(sam_checkpoint, args.sam_model_type, args.device)
self.cutie = BaseTracker(cutie_checkpo... |
class Clipart(general_dataset):
def __init__(self, root='data/meta-dataset/clipart', mode='test', backbone_name='resnet12', transform=None):
assert (mode in ['train', 'val', 'test'])
self.mode = mode
(_, train_process, val_process) = load(backbone_name, jit=False)
if ((mode == 'val')... |
def get_model_parallel_group():
global _USE_MEGATRON
if _USE_MEGATRON:
from fairseq.model_parallel.megatron import mpu
return mpu.get_model_parallel_group()
else:
return None |
def main():
if (len(sys.argv) != 1):
usage(os.path.basename(sys.argv[0]))
(m, bipartite_graph) = read_bipartite_matrix(sys.stdin)
general_graph = bipartite_to_adjmatrix(m, bipartite_graph)
for i in xrange(len(general_graph)):
for j in xrange(len(general_graph)):
if general_gr... |
def get_default_tokenizer():
default_vocab_path = pkg_resources.resource_filename('rxnfp', 'models/transformers/bert_ft_10k_25s/vocab.txt')
return SmilesTokenizer(default_vocab_path, do_lower_case=False) |
class GeneratorMLP(nn.Module):
def __init__(self, output_dim):
super(GeneratorMLP, self).__init__()
self.hidden_dim = 256
self.model = nn.Sequential(nn.Linear(256, 512), nn.LeakyReLU(0.2, inplace=True), nn.Linear(512, 1024), nn.LeakyReLU(0.2, inplace=True), nn.Linear(1024, (args.n_timesteps ... |
def test_initializing_example_background_knowledge_2():
(train, _) = load_toy_cancer()
_bk = Background(modes=train.modes, line_search=True, recursion=True, number_of_clauses=8, number_of_cycles=10)
assert (_bk.modes == train.modes)
_capture = str(_bk)
assert ('setParam: nodeSize=2.' in _capture)
... |
(repr=False)
class UndefinedContentType(FailureContext):
content_type: str
defined_content_types: list[str]
message: str
title: str = 'Undocumented Content-Type'
type: str = 'undefined_content_type' |
def _auxiliary_random_forest_word(n, k):
from sage.misc.prandom import shuffle
w = (([0] * (((3 * n) + (2 * k)) - 3)) + ([1] * n))
shuffle(w)
partial_sum = 0
min_value = 0
min_pos = 0
for (i, x) in enumerate(w):
if x:
partial_sum += 3
else:
partial_sum... |
def run_task(v):
env = normalize(CartpoleEnv())
policy = GaussianMLPPolicy(env_spec=env.spec, hidden_sizes=(32, 32))
baseline = LinearFeatureBaseline(env_spec=env.spec)
algo = TRPO(env=env, policy=policy, baseline=baseline, batch_size=4000, max_path_length=100, n_itr=40, discount=0.99, step_size=v['step... |
def _test_quantitatively(sdfg):
graph = sdfg.nodes()[0]
A = np.random.rand(N.get()).astype(np.float64)
B = np.random.rand(N.get()).astype(np.float64)
C1 = np.random.rand(N.get()).astype(np.float64)
C2 = np.random.rand(N.get()).astype(np.float64)
D1 = np.random.rand(N.get()).astype(np.float64)
... |
def get_subject_label(subject_list, label_name):
label = {}
with open(os.path.join(save_path, 'ABIDE_pcp/Phenotypic_V1_0b_preprocessed1.csv')) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (row['subject'] in subject_list):
label[row['subject']] = ... |
def random_word(tokens, tokenizer):
output_label = []
for (i, token) in enumerate(tokens):
prob = random.random()
if ((token != '[CLS]') and (token != '[SEP]') and (token != SEP_TOKEN) and (prob < 0.15)):
prob /= 0.15
if (prob < 0.8):
tokens[i] = '[MASK]'
... |
def log_add(x, y):
if (x == NEG_INF):
return y
elif (y == NEG_INF):
return x
else:
if (y <= x):
d = (y - x)
r = x
else:
d = (x - y)
r = y
return (r + log1pexp(d)) |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('inshape, kernel, out_channels, pad, stride, dilation, group, deformable_group, with_bias', [((2, 4, 6, 6), (3, 2), 4, (0, 0), (1, 1), (1, 1), 2, 2, True), ((2, 2, 5, 7), (3, 3), 2, (1, 1), (1, 2), (2, 1), 1, 1, True), ((2, 2, 5, 7), (3, 3), ... |
def get_embeddings(input_dim, instance, feature_extractor):
if (len(instance.shape) > 1):
features = []
for data in instance:
with no_grad():
x = Variable(from_numpy(data))
feature = feature_extractor(x.view((- 1), input_dim).float()).data.numpy()
... |
def test_conv2d(default_implementation, sdfg_name, use_cpp_dispatcher):
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(1, 4, 3)
self.conv2 = nn.Conv2d(4, 4, 3)
def forward(self, x):
x = F.relu(self.conv... |
class MultiscaleData(Data):
def __init__(self, x=None, edge_index=None, edge_attr=None, y=None, pos=None, normal=None, face=None, **kwargs):
super(MultiscaleData, self).__init__(x=x, edge_index=edge_index, edge_attr=edge_attr, y=y, pos=pos, normal=normal, face=face, **kwargs)
def __inc__(self, key, valu... |
def is_bio_scheme(all_tags):
for tag in all_tags:
if (tag in EMPTY_OR_O_TAG):
continue
elif ((len(tag) > 2) and (tag[:2] in ('B-', 'I-', 'B_', 'I_'))):
continue
else:
return False
return True |
class EarlyStopping():
def __init__(self, patience=7):
self.reset(patience)
def __call__(self, val_loss):
score = (- val_loss)
if (self.best_score is None):
self.best_score = score
elif (score < self.best_score):
self.counter += 1
if (self.coun... |
class LongT5Config(PretrainedConfig):
model_type = 'longt5'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__(self, vocab_size=32128, d_model=512, d_kv=64, d_ff=2048, num_layers... |
class AutoModelForAudioXVector(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_char():
a = ak.highlevel.Array(np.array([ord(x) for x in 'hey there'], dtype=np.uint8), check_valid=True)
a = ak.with_parameter(a, '__array__', 'char')
assert (str(a) == str([ord(c) for c in 'hey there']))
assert (ak.to_list(a) == 'hey there') |
def _join_measurements(join, left_measurements, right_measurements):
joined_measurements = _join_items(join, left_measurements, right_measurements)
if (join == 'none'):
common_measurements = {meas['name'] for meas in left_measurements}.intersection((meas['name'] for meas in right_measurements))
... |
.parametrize('seed', [313])
def test_function_context(seed):
rng = np.random.RandomState(313)
xd = rng.randn(2, 3)
x = nn.Variable.from_numpy_array(xd)
ctx1 = nn.Context(backend=['cpu:float'], array_class='CpuCachedArray', device_id='1')
with nn.context_scope(ctx1):
y = F.relu(x)
ctx0 = ... |
def Manifold(dim: int, name: Optional[str], latex_name: Optional[str]=None, field: str='real', structure: Optional[str]=None, start_index: int=0, **extra_kwds) -> Union[(TopologicalManifold, DifferentiableManifold)]:
from sage.rings.infinity import infinity
from sage.manifolds.differentiable.manifold import Dif... |
def FFT_selection(vio_nodes, dist_matrix, k=10):
assert (k > 1), 'invalid k'
if (len(vio_nodes) <= 1):
return vio_nodes
chosen = [np.random.randint(len(vio_nodes))]
dist_map = dict()
max_dist = p = 0
for i in range(len(vio_nodes)):
if (i != chosen[(- 1)]):
dist = dist... |
def add_arguments(parser=None):
if (parser is None):
parser = argparse.ArgumentParser(('Script to ' + help))
parser.add_argument('file', help='path to input particle file')
parser.add_argument('-o', '--output', help='path to output directory')
parser.add_argument('--format', dest='_from', choice... |
def visualize(state_list, env_name, num_steps):
env = envs.create(env_name=env_name, episode_length=num_steps)
visual_states = []
for i in range(state_list.qp.ang.shape[0]):
qp_state = brax.QP(np.array(state_list.qp.pos[(i, 0)]), np.array(state_list.qp.rot[(i, 0)]), np.array(state_list.qp.vel[(i, 0)... |
def download_image_from_url_test(url):
basename = os.path.basename(url)
filename = os.path.join(storage_dir, 'test', basename)
download_file(url, filename) |
def lisp_to_nested_expression(lisp_string: str) -> List:
stack: List = []
current_expression: List = []
tokens = lisp_string.split()
for token in tokens:
while (token[0] == '('):
nested_expression: List = []
current_expression.append(nested_expression)
stack.a... |
def save_npy(data, save_name='op', save_dir='.'):
return mx.symbol.Custom(data=data, save_name=save_name, save_dir=save_dir, op_type='save_npy') |
def find_ufunc(behavior: (Mapping | None), signature: tuple) -> (UfuncLike | None):
if all(((s is not None) for s in signature)):
behavior = overlay_behavior(behavior)
if all((isinstance(x, str) for x in signature)):
return behavior.get(signature)
else:
for (key, cust... |
class MXMNet(nn.Module):
def __init__(self, config: Config, num_spherical=7, num_radial=6, envelope_exponent=5):
super(MXMNet, self).__init__()
self.dim = config.dim
self.n_layer = config.n_layer
self.cutoff = config.cutoff
self.embeddings = nn.Parameter(torch.ones((5, self.d... |
def main(args):
dss = []
for dataset_path in args.dataset:
dataset = load_dataset(dataset_path, split='train', data_files='*.arrow')
dss.append(dataset)
ds = concatenate_datasets(dss)
ds = ds.shuffle()
ds.save_to_disk(args.output_folder) |
def weights_init_G(m):
if (m.__class__.__name__.find('Conv') != (- 1)):
nn.init.xavier_normal_(m.weight, 0.1)
if hasattr(m.bias, 'data'):
m.bias.data.fill_(0) |
class TagToken(ElementSetToken):
def __init__(self, tag, classes=None):
super(TagToken, self).__init__(classes)
self._tag = tag
def _execute(self, env):
tag_matches = [elem for elem in env.elements if ((self._tag == elem.tag) and self._class_match(elem))]
return ElementSet(tag_ma... |
class LegacyFairseqCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(task=task)
self.args = args
utils.deprecation_warning('Criterions should take explicit arguments instead of an argparse.Namespace object, please update your criterion by extending FairseqCriterio... |
def calculate_CLs(bkgonly_json, signal_patch_json):
workspace = pyhf.workspace.Workspace(bkgonly_json)
model = workspace.model(measurement_name=None, patches=[signal_patch_json], modifier_settings={'normsys': {'interpcode': 'code4'}, 'histosys': {'interpcode': 'code4p'}})
result = pyhf.infer.hypotest(1.0, w... |
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):
channel_axis = (1 if (K.image_data_format() == 'channels_first') else (- 1))
filters = int((filters * alpha))
x = ZeroPadding2D(padding=(1, 1), name='conv1_pad')(inputs)
x = Conv2D(filters, kernel, padding='valid', use_bias=False, s... |
def test_success_remove_option_type():
array = ak.Array(ak.contents.ListOffsetArray(ak.index.Index64(np.array([1, 3], dtype=np.int64)), ak.contents.ListOffsetArray(ak.index.Index64(np.array([0, 2, 2, 3], dtype=np.int64)), ak.contents.NumpyArray(np.array([0, 1, 2], dtype=np.int64)))), check_valid=True)
index = a... |
('/index.html')
def read_index():
return render_template(AUTOMATIC_HTML_FILE, server_debug_mode=server_debug_mode) |
class TestNeighSampler(unittest.TestCase):
def setUp(self) -> None:
self.adjacency = test_graph()
self.n = self.adjacency.shape[0]
def test_uni_node_sampler(self):
uni_sampler = UniformNeighborSampler(sample_size=2)
sampled_adj = uni_sampler(self.adjacency)
self.assertTru... |
def Convolutional_Block(inputs, shortcut, num_filters, name, is_training):
print(('-' * 20))
print('Convolutional Block', str(num_filters), name)
print(('-' * 20))
with tf.variable_scope(((('conv_block_' + str(num_filters)) + '_') + name)):
for i in range(2):
with tf.variable_scope((... |
class KeywordsOper():
def get_search_keywords(cls):
return db_session.query(KeyWords.keyword, KeyWords.id).filter(text('enable=1')).all()
_commit_decorator
def set_useless_keyword(cls, keyword):
search_word = db_session.query(KeyWords).filter((KeyWords.keyword == keyword)).first()
se... |
class clear_and_catch_warnings(warnings.catch_warnings):
class_modules = ()
def __init__(self, record=False, modules=()):
self.modules = set(modules).union(self.class_modules)
self._warnreg_copies = {}
super(clear_and_catch_warnings, self).__init__(record=record)
def __enter__(self):... |
def random_simplicial_complex(level=1, p=0.5):
n = randint(2, (4 * level))
dim = randint(1, n)
return RandomComplex(n, dim, p) |
def register_Ns3CallbackImpl__Void_Unsigned_long_Unsigned_short_Unsigned_short_Ns3UeManagerState_Ns3UeManagerState_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, unsigned long, unsigned short, unsigned short, ns3::UeMan... |
def test_legal_action():
board = make_test_boad()
playable_dice = jnp.array([3, 2, (- 1), (- 1)], dtype=jnp.int32)
expected_legal_action_mask: jnp.ndarray = jnp.zeros((6 * 26), dtype=jnp.bool_)
expected_legal_action_mask = expected_legal_action_mask.at[((6 * (19 + 2)) + 3)].set(True)
expected_legal_... |
class XLMTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = XLMTokenizer
test_rust_tokenizer = False
def setUp(self):
super().setUp()
vocab = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>'... |
def arguments(func: FunctionSchema, *, method: bool=False) -> Sequence[CppArgument]:
return list(map(argument, group_arguments(func, method=method))) |
def FormsSpace(analytic_type, group=3, base_ring=ZZ, k=QQ(0), ep=None):
from .space import canonical_parameters
(group, base_ring, k, ep, n) = canonical_parameters(group, base_ring, k, ep)
from .analytic_type import AnalyticType
AT = AnalyticType()
analytic_type = AT(analytic_type)
if (analytic_... |
def create_extra_val_loader(args, dataset, val_input_transform, target_transform, val_sampler):
if (dataset == 'cityscapes'):
val_set = cityscapes.CityScapes('fine', 'val', 0, transform=val_input_transform, target_transform=target_transform, cv_split=args.cv, image_in=args.image_in)
elif (dataset == 'bd... |
def VDCNN9KMaxPool(num_classes=5, shortcut=False, bias=False):
return VDCNN(KMaxPoolBlock, blocks=[1, 1, 1, 1], filters=[64, 128, 256, 512], num_classes=num_classes, shortcut=shortcut, bias=bias) |
def nullspace_RR(n=300, min=0, max=10, system='sage'):
if (system == 'sage'):
from sage.rings.real_mpfr import RR
A = random_matrix(ZZ, (n + 1), n, x=min, y=(max + 1)).change_ring(RR)
t = cputime()
v = A.kernel()
return cputime(t)
elif (system == 'magma'):
code = ... |
def gp():
global _gp
if (_gp is None):
_gp = Gp(script_subdirectory='buzzard')
_gp.read('DimensionSk.g')
_gp.read('genusn.g')
_gp.read('Tpprog.g')
return _gp |
def setup_logger(args):
os.makedirs(os.path.join(args.logdir, args.name), exist_ok=True)
logging.config.dictConfig({'version': 1, 'disable_existing_loggers': False, 'formatters': {'standard': {'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'}}, 'handlers': {'stderr': {'level': 'INFO', 'formatter': ... |
_numpy_output(non_zero=True, check_dtype=True)
def test_ufunc_remainder_ss(A: dace.int32[10], B: dace.int32[10]):
return np.remainder(A, B) |
class CalvinEnv(PlayTableSimEnv):
def __init__(self, tasks: dict={}, **kwargs):
self.max_episode_steps = kwargs.pop('max_episode_steps')
self.reward_norm = kwargs.pop('reward_norm')
[kwargs.pop(key) for key in ['id', 'screen_size', 'action_repeat', 'frame_stack', 'absorbing_state', 'pixel_ob... |
_utils.test(require=ti.extension.assertion, debug=True)
def test_skip_grad_replaced():
N = 16
x = ti.field(dtype=ti.f32, shape=N, needs_grad=True)
loss = ti.field(dtype=ti.f32, shape=(), needs_grad=True)
b = ti.field(dtype=ti.f32, shape=(), needs_grad=True)
def kernel_1():
loss[None] = (x[1]... |
def pad_list(list_: List, pad_element: Any, pad_to_length: int) -> List:
return (list_ + [pad_element for _ in range((pad_to_length - len(list_)))]) |
def display(d):
img = draw_keypoints((d['image'][(..., 0)] * 255), np.where(d['keypoint_map']), (0, 255, 0))
draw_overlay(img, np.logical_not(d['valid_mask']))
return img |
def export_digraph(booster, tree_index=0, out_file=None):
if (not isinstance(booster, BaseBoostedRelationalModel)):
raise TypeError('booster must inherit from BaseBoostedRelationalModel.')
dotfiles = booster._dotfiles
if (not (0 <= tree_index < len(dotfiles))):
raise IndexError('tree_index i... |
class EnsemblePredictor(object):
def __init__(self, config_path, model_args, data_args, gpu_ids, device, logger=None):
(task2models, aggregation_fn) = self.get_config(config_path)
self.task2models = task2models
self.aggregation_fn = aggregation_fn
self.model_args = model_args
... |
def test_download_not_repeated():
with tempfile.TemporaryDirectory(dir=TEST_WORKING_DIR) as test_dir:
stanza.download('en', model_dir=test_dir, processors='tokenize', package='combined')
assert (sorted(os.listdir(test_dir)) == ['en', 'resources.json'])
en_dir = os.path.join(test_dir, 'en')
... |
def main(args, config):
utils.init_distributed_mode(args)
device = torch.device(args.gpu)
seed = (args.seed + utils.get_rank())
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
cudnn.benchmark = True
cudnn.deterministic = True
print('Creating dataset')
datasets = [c... |
def get_paraphrase_prompt(gpt3, prompt, ent_tuple):
assert (get_n_ents(prompt) == len(ent_tuple))
ent_tuple = [ent.lower() for ent in ent_tuple]
sent = get_sent(prompt=prompt, ent_tuple=ent_tuple)
for _ in range(5):
raw_response = gpt3.call(prompt=f'''paraphrase:
{sent}
''')
para_sent = ... |
def test_coefficient_tracker_can_shift_weighted_sampled_based_on_configured_transition_period():
with mock.patch('obp.simulator.coefficient_drifter.sample_random_uniform_coefficients', MockCoefSample().fake_sample):
drifter = CoefficientDrifter(drift_interval=4, transition_period=2, transition_type='weighte... |
class LinearCameraCal(object):
__slots__ = ['data']
if T.TYPE_CHECKING:
data = []
def __init__(self, focal_length, principal_point):
self.data = []
if isinstance(focal_length, numpy.ndarray):
if (focal_length.shape in [(2, 1), (1, 2)]):
focal_length = foca... |
def label_smoothing_log_loss(pred, labels, smoothing=0.0):
n_class = pred.shape[(- 1)]
one_hot = torch.zeros_like(pred)
one_hot[labels] = 1.0
one_hot = ((one_hot * (1 - smoothing)) + (((1 - one_hot) * smoothing) / (n_class - 1)))
loss = (- (one_hot * pred).sum(dim=(- 1)).mean())
return loss |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.