code stringlengths 101 5.91M |
|---|
def skipCUDANonDefaultStreamIf(condition):
def dec(fn):
if getattr(fn, '_do_cuda_non_default_stream', True):
fn._do_cuda_non_default_stream = (not condition)
return fn
return dec |
def simpleCNN2(num_classes=10, norm_layer_type='bn', conv_layer_type='conv2d', linear_layer_type='linear', activation_layer_type='relu'):
return Net_circular_CNN(num_classes=num_classes, norm_layer_type=norm_layer_type, conv_layer_type=conv_layer_type, linear_layer_type=linear_layer_type, activation_layer_type=acti... |
def raise_isinstance_error(variable_name, possible_type, variable):
raise ValueError(f'{variable_name} has to be one of {possible_type}. Got {type(variable)} instead.') |
.parametrize('use_global_model', [True, False])
.parametrize('use_global_init_dataset', [True, False])
.parametrize('num_query_points_per_batch', [1, 2])
def test_bayesian_optimizer_creates_correct_datasets_for_rank3_points(use_global_model: bool, use_global_init_dataset: bool, num_query_points_per_batch: int) -> None:... |
def register_Ns3EpcTftPacketFilter_methods(root_module, cls):
cls.add_constructor([param('ns3::EpcTft::PacketFilter const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Matches', 'bool', [param('ns3::EpcTft::Direction', 'd'), param('ns3::Ipv4Address', 'ra'), param('ns3::Ipv4Address', 'la'), param('ui... |
def dla169(pretrained=None, **kwargs):
Bottleneck.expansion = 2
model = DLA([1, 1, 2, 3, 5, 1], [16, 32, 128, 256, 512, 1024], block=Bottleneck, residual_root=True, **kwargs)
if (pretrained is not None):
model.load_pretrained_model(data='imagenet', name='dla169', hash='0914e092')
return model |
class LiSHT_VGG(nn.Module):
def __init__(self, vgg_name):
super(LiSHT_VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, 100)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), (- 1))
out =... |
class SENet(ImageNetBase):
_KEY_VARIABLE = {'classifier': 'Affine', 'pool': 'AveragePooling', 'lastconv': 'Add2_7_RepeatStart_4[1]', 'lastconv+relu': 'ReLU_25_RepeatStart_4[1]'}
def __init__(self):
self._load_nnp('SENet-154.nnp', 'SENet-154/SENet-154.nnp')
def _input_shape(self):
return (3, ... |
class XLNetConfig(PretrainedConfig):
model_type = 'xlnet'
def __init__(self, vocab_size=32000, d_model=1024, n_layer=24, n_head=16, d_inner=4096, ff_activation='gelu', untie_r=True, attn_type='bi', initializer_range=0.02, layer_norm_eps=1e-12, dropout=0.1, mem_len=512, reuse_len=None, bi_data=False, clamp_len=(... |
def quote_xml(inStr):
s1 = ((isinstance(inStr, str) and inStr) or ('%s' % inStr))
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
return s1 |
def check_build_wheel(hooks, build_sys_requires):
with BuildEnvironment() as env:
try:
env.pip_install(build_sys_requires)
log.info('Installed static build dependencies')
except CalledProcessError:
log.error('Failed to install static build dependencies')
... |
def PrintUsage(message):
sys.stderr.write(_USAGE)
if message:
sys.exit(('\nFATAL ERROR: ' + message))
else:
sys.exit(1) |
def rename(node: goos.ProblemGraphNode, name: str) -> goos.ProblemGraphNode:
return cast(node, type(node), name=name) |
class ExponentialDelaySampler():
max_scale: float = 100.0
min_scale: float = 10.0
random_state: int = None
def __post_init__(self) -> None:
if (self.random_state is None):
raise ValueError('`random_state` must be given')
self.random_ = check_random_state(self.random_state)
... |
class Hypothesis(BaseHypothesis):
def __init__(self, dec_prefix, decoder_states, decoder_input):
BaseHypothesis.__init__(self, dec_prefix)
self.sql = []
self.keyword = None
self.nested_keywords = []
(self.avoid_items, self.confirmed_items) = ([], [])
self.decoder_stat... |
def _dict2sarray(sorts, ctx):
sz = len(sorts)
_names = (Symbol * sz)()
_sorts = (Sort * sz)()
i = 0
for k in sorts:
v = sorts[k]
if z3_debug():
_z3_assert(isinstance(k, str), 'String expected')
_z3_assert(is_sort(v), 'Z3 sort expected')
_names[i] = to_... |
class AbstractEntityDisambiguator(object):
def __init__(self, args):
self.args = args
self.max_features_size = self.args.max_features_size
with open(f'{self.args.database_dir}/wiki_entity_data/type_mappings/wiki/type_vocab_to_wikidataqid.json') as fin:
self.type_vocab_to_typeqid ... |
def dataset_dest_prefix(args, output_prefix, lang):
base = '{}/{}'.format(args.destdir, output_prefix)
if (lang is not None):
lang_part = '.{}-{}.{}'.format(args.source_lang, args.target_lang, lang)
elif args.only_source:
lang_part = ''
else:
lang_part = '.{}-{}'.format(args.sour... |
class ToWeak(object):
def __init__(self, fname):
self.fname = fname
def __call__(self):
return u'\n'.join((unicode(a) for a in self.annotations())).encode(ENC)
def annotations(self):
for line in open(self.fname):
a = Annotation.from_string(line.rstrip('\n').decode(ENC))
... |
class ResNetBottleneck(nn.Module):
expansion = 4
num_conv = 3
def __init__(self, inplanes, planes, stride):
super(ResNetBottleneck, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
self.conv_1x1 = ConvBNReLU(inplanes, planes, 1, 1, 0, Fals... |
_task('multilingual_translation')
class MultilingualTranslationTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('data', metavar='DIR', help='path to data directory')
parser.add_argument('--lang-pairs', default=None, metavar='PAIRS', help='comma-separated list of language pairs (in ... |
def save_graph(net, file_name, graph_name='net', op_only=True):
from caffe2.python import net_drawer
graph = None
ops = net.op
if (not op_only):
graph = net_drawer.GetPydotGraph(ops, graph_name, rankdir='TB')
else:
graph = net_drawer.GetPydotGraphMinimal(ops, graph_name, rankdir='TB'... |
def check_oth(distfn, arg, supp, msg):
npt.assert_allclose(distfn.sf(supp, *arg), (1.0 - distfn.cdf(supp, *arg)), atol=1e-10, rtol=1e-10)
q = np.linspace(0.01, 0.99, 20)
npt.assert_allclose(distfn.isf(q, *arg), distfn.ppf((1.0 - q), *arg), atol=1e-10, rtol=1e-10)
median_sf = distfn.isf(0.5, *arg)
np... |
def get_likelihood_grad_BO(likelihood, mz_hat, tz0_hat):
def A_func(mz_hat):
az = (mz_hat + tz0_hat)
return likelihood.compute_potential_BO(az=az, tz0_hat=tz0_hat)
grad_mz_hat_A = numerical_1st_derivative(mz_hat, A_func, EPSILON)
az = (mz_hat + tz0_hat)
vz = likelihood.compute_backward_v... |
class ReformerModelWithLMHead(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class HalfCheetahDirEnv(HalfCheetahEnv):
def __init__(self, task={}):
self._task = task
self._goal_dir = task.get('direction', 1)
super(HalfCheetahDirEnv, self).__init__()
def step(self, action):
xposbefore = self.sim.data.qpos[0]
self.do_simulation(action, self.frame_ski... |
.parametrize('is_mat', [(True, True), (True, False), (False, True)])
_utils.test()
def test_binary_i(is_mat):
(lhs_is_mat, rhs_is_mat) = is_mat
x = ti.Matrix.field(3, 2, ti.i32, 20)
if lhs_is_mat:
y = ti.Matrix.field(3, 2, ti.i32, ())
else:
y = ti.field(ti.i32, ())
if rhs_is_mat:
... |
def create_master(config):
if config['debug_run_local']:
return create_master_local(config)
else:
return create_master_remote(config) |
class MultiHeadAttention(nn.Module):
def init_weights(layer):
if (type(layer) == nn.Linear):
nn.init.xavier_normal_(layer.weight)
def __init__(self, config, d_model, n_head, attention_mask=None):
super(MultiHeadAttention, self).__init__()
self.config = config
self.d_m... |
def test_record_fields_empty_parameters():
t = RecordType([], [], parameters={'p': [123]})
assert (str(ak.types.from_datashape(str(t), highlevel=False)) == str(t)) |
class OptConfig():
opt_type: str = 'adamW'
base_lr: float = 0.0001
weight_decay: float = 0.0001
betas: List[float] = field(default_factory=(lambda : [0.9, 0.99]))
grad_clip_norm: float = 1.0
sched_type: str = 'cosine'
max_steps: int = 0
min_lr: float = 0.0 |
.parametrize('round_number', range(ROUNDS_TO_TRAIN))
def test_get_tasks_for_collaborator(assigner, task_groups, authorized_cols, round_number):
tasks = assigner.get_tasks_for_collaborator(authorized_cols[0], round_number)
assert (tasks == task_groups[0]['tasks']) |
def get_labeled_episodic_dataloader(dataset_name: str, n_way: int, n_shot: int, support: bool, n_episodes=600, n_query_shot=15, n_epochs=1, augmentation: str=None, image_size: int=None, unlabeled_ratio: int=20, num_workers=2, split_seed=1, episode_seed=0):
(unlabeled, labeled) = get_split_dataset(dataset_name, augm... |
def test_readable_file_size():
size_in_bytes = ((1024 * 1024) * 3.5)
readable_size = readable_file_size(size_in_bytes)
assert (readable_size == '3.50 MB') |
def grep_full_py_identifiers(tokens):
global py_keywords
tokens = list(tokens)
i = 0
while (i < len(tokens)):
(token_type, token) = tokens[i]
i += 1
if (token_type != 'id'):
continue
while (((i + 1) < len(tokens)) and (tokens[i] == ('op', '.')) and (tokens[(i ... |
def find_valid_answer_spans(passage_tokens: List[Token], answer_texts: List[str]) -> List[Tuple[(int, int)]]:
normalized_tokens = [token.text.lower().strip(STRIPPED_CHARACTERS) for token in passage_tokens]
word_positions: Dict[(str, List[int])] = defaultdict(list)
for (i, token) in enumerate(normalized_toke... |
def image_from_paths(paths, shape, is_grayscale=True, seed=None):
filename_queue = tf.train.string_input_producer(list(paths), shuffle=False, seed=seed)
reader = tf.WholeFileReader()
(filename, data) = reader.read(filename_queue)
image = tf.image.decode_png(data, channels=3, dtype=tf.uint8)
if is_gr... |
class MemoryElements():
def __init__(self, elements: Set[ActivationMemoryTensor], total_size: float):
self.elements = elements
self.total_size = total_size
def add_element(self, new_element: ActivationMemoryTensor):
self.elements.add(new_element)
self.total_size += new_element.to... |
class convolution_bilstm(nn.Module):
def __init__(self, args):
super(CNN_BiLSTM, self).__init__()
self.args = args
self.hidden_dim = args.lstm_hidden_dim
self.num_layers = args.lstm_num_layers
V = args.embed_num
D = args.embed_dim
C = args.class_num
se... |
def main(config):
device_ids = range(torch.cuda.device_count())
train_loaders = {}
val_loaders = {}
test_loaders = {}
for dataset_name in config.data.name:
datas = Dataset_wrap_csv(k_fold=config.data.k_fold, use_old_split=True, img_size=config.data.img_size, dataset_name=dataset_name, split_... |
def downward_closure(cliques):
ans = set()
for proj in cliques:
ans.update(powerset(proj))
return list(sorted(ans, key=len)) |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model_name_or_path', default='BAAI/bge-large-zh-noinstruct', type=str)
parser.add_argument('--input_file', default='nli-zh-bge/nli_zh-train.jsonl', type=str)
parser.add_argument('--candidate_pool', default='STS-B/STS-B.train.data'... |
class CommandLineParser():
def join(argv):
raise NotImplementedError
def split(cmd):
raise NotImplementedError |
class TransformerLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
super(TransformerLayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):... |
def evaluate(model, init_dist, sampler, train_loader, val_loader, test_loader, preprocess, device, n_iters, n_samples, steps_per_iter=1, viz_every=100):
model = AISModel(model, init_dist)
model.to(device)
betas = np.linspace(0.0, 1.0, n_iters)
samples = init_dist.sample((n_samples,))
log_w = torch.z... |
class RNNTTrainConfig(TrainConfig):
optimizer: str = 'adam'
init_lr: float = 1e-06
final_lr: float = 1e-06
peak_lr: float = 0.0001
warmup_steps: int = 400
num_epochs: int = 20
reduction: str = 'mean'
label_smoothing: float = 0.1
lr_scheduler: str = 'tri_stage_lr_scheduler' |
class BigMlpNet(nn.Module):
def __init__(self, args):
super(BigMlpNet, self).__init__()
if (args.dataset == 'mnist'):
input_dim = 784
elif (args.dataset.lower() == 'cifar10'):
input_dim = 3072
self.fc1 = nn.Linear(input_dim, args.num_hidden_nodes1, bias=(not a... |
def sample_paths(policy_params, max_samples, max_path_length=np.inf, scope=None):
singleton_pool.run_each(_worker_set_policy_params, ([(policy_params, scope)] * singleton_pool.n_parallel))
return singleton_pool.run_collect(_worker_collect_one_path, threshold=max_samples, args=(max_path_length, scope), show_prog... |
def choose_agent(agent_type=RANDOM):
if (agent_type == RANDOM):
return RandomAgent
elif (agent_type == HUMAN):
return HumanAgent
elif (agent_type == REINFORCE):
return ReinforceAgent |
def _write_yaml_to_memory(yaml: str, path: str='memory://test.yaml'):
with fsspec.open(path, 'w') as f:
f.write(yaml)
return path |
def qlCreateCollider(cloth, target):
objects_before = cmds.ls(assemblies=True)
cmds.select([cloth, target])
mel.eval('qlCreateCollider()')
objects_after = cmds.ls(assemblies=True)
colliders = list((set(objects_after) - set(objects_before)))
colliders = [cmds.rename(cl, ((((cloth + '_') + target)... |
def replace_method(klass, method_name, func):
if (sys.version_info[0] < 3):
m = types.MethodType(func, None, klass)
else:
m = (lambda self, *args, **kw: func(self, *args, **kw))
setattr(klass, method_name, m) |
def package_configurations(target):
kernelsPackaged = 0
for fileName in os.listdir(PROJECT_CONFIG['build_dir']):
try:
conf = Configuration.get_conf(fileName)
except ValueError:
continue
if (conf.target != target):
continue
sourceDir = os.path.j... |
class NNDataflow():
def __init__(self, network, batch_size, resource, cost, map_strategy):
if (not isinstance(network, Network)):
raise TypeError('NNDataflow: network must be a Network instance.')
if (not isinstance(resource, Resource)):
raise TypeError('NNDataflow: resource ... |
class LocalFSAdapter(BaseAdapter):
def send(self, request, stream=None, timeout=None, verify=None, cert=None, proxies=None):
pathname = url_to_path(request.url)
resp = Response()
resp.status_code = 200
resp.url = request.url
try:
stats = os.stat(pathname)
... |
def test_warnings():
olderr = np.seterr(all='raise')
try:
orth.eval_legendre(1, 0)
orth.eval_laguerre(1, 1)
orth.eval_gegenbauer(1, 1, 0)
finally:
np.seterr(**olderr) |
.parametrize('seed', [412])
.parametrize('batch_size', [2, 16])
.parametrize('grid_size', [2, 8])
.parametrize('feature_size', [4])
.parametrize('m, M', [((- 1), 1)])
def test_query_on_triplane_forward_backward(seed, batch_size, grid_size, feature_size, m, M):
nn.clear_parameters()
ctx = get_extension_context('... |
class WindowedMetric(BaseMetric):
def __init__(self, metric_cls, window_size, ignore_nonempty_last=True, **kwargs):
super().__init__()
self.ignore_nonempty_last = ignore_nonempty_last
self.window_size = window_size
self.metric_cls = metric_cls
self.metric = self._init_metric(... |
def train(epoch):
print(('\nEpoch: %d' % epoch))
model.train()
train_loss = 0
correct = 0
total = 0
for (batch_idx, (normal_inputs, anomaly_inputs)) in enumerate(zip(normal_train_loader, anomaly_train_loader)):
inputs = torch.cat([anomaly_inputs, normal_inputs], dim=1)
batch_size... |
class GenericSymbolicSubring(SymbolicRing):
def __init__(self, vars):
super().__init__()
self._vars_ = set(vars)
if (not all((v.is_symbol() for v in self._vars_))):
raise ValueError('Invalid variables: {}'.format(', '.join((str(v) for v in sorted(self._vars_, key=str) if (not v.i... |
def DeepResNext101V3PlusD_OS4(args, num_classes, criterion, criterion_aux):
print('Model : DeepLabv3+, Backbone : resnext-101')
return DeepV3Plus(num_classes, trunk='resnext-101', criterion=criterion, criterion_aux=criterion_aux, variant='D4', skip='m1', args=args) |
def test_function_that_needs_replacement():
def notworking(a: dace.float64[20]):
return np.allclose(a, a)
A = np.random.rand(20)
with dace.config.set_temporary('frontend', 'typed_callbacks_only', value=True):
with pytest.raises(DaceSyntaxError):
notworking(A) |
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
kwargs['groups'] = 32
kwargs['width_per_group'] = 8
return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs) |
class AssertionMinimization(cv.ChromosomeVisitor):
_logger = logging.getLogger(__name__)
def __init__(self):
self._remaining_assertions: OrderedSet[Assertion] = OrderedSet()
self._deleted_assertions: OrderedSet[Assertion] = OrderedSet()
self._checked_line_numbers: OrderedSet[int] = Order... |
class GraphDataset(torch_geometric.data.Dataset):
def __init__(self, sample_files):
super().__init__(root=None, transform=None, pre_transform=None)
self.sample_files = sample_files
def len(self):
return len(self.sample_files)
def process_sample(self, filepath):
(BGFilepath, s... |
def __getattr__(name):
return _sub_module_deprecation(sub_package='linalg', module='special_matrices', private_modules=['_special_matrices'], all=__all__, attribute=name) |
def get_context(dial, turn_id):
context = ''
for (idx, turn) in enumerate(dial['dialogue']):
if (idx <= turn_id):
context += (((' <system>: ' + turn['system_transcript']) + ' <user>: ') + turn['transcript'])
else:
break
return context |
def scheduler_from_config(scheduler_config, optimizer, epoch_length):
assert (scheduler_config['type'] in ('linear', 'step', 'poly', 'multistep'))
params = scheduler_config.getstruct('params')
if (scheduler_config['type'] == 'linear'):
if (scheduler_config['update_mode'] == 'batch'):
cou... |
class AnotherMixin():
def __init_subclass__(cls, custom_parameter, **kwargs):
super().__init_subclass__(**kwargs)
cls.custom_parameter = custom_parameter |
class RandomCurriculum(TrainingCurriculum):
def get_action_flag_and_dataloader_for_epoch(self, dataset, epoch):
return (False, DataLoader(dataset, sampler=self.random_sampler, batch_size=self.train_batch_size, collate_fn=self.random_collate_fn))
def summary(self):
return 'completely random curri... |
def preparse_calculus(code):
new_code = []
last_end = 0
for m in re.finditer(';(\\s*)([^\\W\\d]\\w*) *\\(([^()]+)\\) *= *([^;#=][^;]*)', code):
(ident, func, vars, expr) = m.groups()
stripped_vars = [v.replace(';', '').strip() for v in vars.split(',')]
if any((n.startswith(numeric_li... |
class NSEM_DerivTests(unittest.TestCase):
def test_derivJvec_Z1dr(self):
self.assertTrue(DerivJvecTest(0.01))
def test_derivJvec_Z1d_e(self):
self.assertTrue(DerivJvecTest_1D(0.01)) |
def roberts_pos_diag(image, mask=None):
check_nD(image, 2)
if (image.dtype.kind == 'f'):
float_dtype = _supported_float_type(image.dtype)
image = image.astype(float_dtype, copy=False)
else:
image = img_as_float(image)
result = convolve(image, ROBERTS_PD_WEIGHTS)
return _mask_... |
.skip(reason='Need to wait for changes on scikit-learn (see issue #89)')
def test_grid_search():
(pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers()
kne = KNORAE(pool_classifiers)
params = {'k': [1, 3, 5, 7]}
grid = GridSearchCV(kne, params)
grid.fit(X_dsel, y_dsel)
grid.bes... |
class VGG16_FPN(nn.Module):
def __init__(self, pretrained=True):
super(VGG16_FPN, self).__init__()
vgg = models.vgg16_bn(pretrained=pretrained)
features = list(vgg.features.children())
self.layer1 = nn.Sequential(*features[0:23])
self.layer2 = nn.Sequential(*features[23:33])
... |
class OddManOutEval(PROBINGEval):
def __init__(self, task_path, seed=1111):
task_path = os.path.join(task_path, 'odd_man_out.txt')
PROBINGEval.__init__(self, 'OddManOut', task_path, seed) |
def _create_mask(lengths, stride, like=None, use_gpu=True):
if use_gpu:
mask = (torch.arange(stride).cuda() + 1)
mask = (mask.unsqueeze(0) <= lengths.cuda().unsqueeze((- 1)))
else:
mask = (torch.arange(stride) + 1)
mask = (mask.unsqueeze(0) <= lengths.unsqueeze((- 1)))
if (li... |
def runeval(args):
global ed
try:
prepare_connections()
tasks_left = True
stop_requested = False
task_id = None
retries = 0
while ((not stop_requested) and tasks_left):
task = None
taskq = None
previous_task_id = task_id
... |
def load_mnist():
((x_train, y_train), (x_test, y_test)) = keras.datasets.mnist.load_data()
x_train = (x_train.reshape(x_train.shape[0], (- 1)) / 255)
x_test = (x_test.reshape(x_test.shape[0], (- 1)) / 255)
y_train = keras.utils.to_categorical(y_train, num_classes=10)
y_test = keras.utils.to_categor... |
class RetriBertTokenizer(BertTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
model_input_names = ['attention_mask'] |
def _calculate_integral(inp, baseline, gradients):
gradients = ((gradients[:(- 1)] + gradients[1:]) / 2.0)
avg_grads = np.average(gradients, axis=0)
integrated_grads = ((inp - baseline) * avg_grads)
integrated_grads = np.sum(integrated_grads, axis=(- 1))
return integrated_grads |
def test_different_shape():
A = np.random.rand(20, 3).astype(np.float32)
B = np.random.rand(20, 3).astype(np.float32)
sdfg = make_sdfg([20, 3], [60], '1, 0', '3')
sdfg.simplify()
sdfg(A=A, B=B)
assert all(((not isinstance(node, dace.nodes.NestedSDFG)) for node in sdfg.node(0).nodes()))
expec... |
def test_reassignment_while():
def reassignment_while(a: dace.float64[(3, 3)], b: dace.float64[(3, 3)]) -> dace.float64[(3, 3)]:
out = np.copy(a)
i = 0
while (i < 10):
out = (out - b)
i += 1
return out
A = rng.random((3, 3))
B = rng.random((3, 3))
... |
.parametrize('dtype', [ti.i64, ti.u64, ti.f64])
_utils.test(arch=supported_archs_taichi_ndarray, require=ti.extension.data64)
def test_ndarray_python_scope_read_64bit(dtype):
def run(x: ti.types.ndarray()):
for i in x:
x[i] = (i + ti.i64((2 ** 40)))
n = 4
a = ti.ndarray(dtype, shape=(n,)... |
class Softshrink(Module):
__constants__ = ['lambd']
lambd: float
def __init__(self, lambd: float=0.5) -> None:
super(Softshrink, self).__init__()
self.lambd = lambd
def forward(self, input: Tensor) -> Tensor:
return F.softshrink(input, self.lambd)
def extra_repr(self) -> str:... |
class Xor(Benchmark):
def __init__(self, dimensions=9):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 1.0)] * self.N), ([1.0] * self.N)))
self.global_optimum = [[1.0, (- 1.0), 1.0, (- 1.0), (- 1.0), 1.0, 1.0, (- 1.0), 0.421134]]
self.fglob = 0.9597588
def fun(... |
def gen_autograd_functions_lib(out, autograd_functions, template_path):
gen_autograd_functions(out, autograd_functions, template_path, 'Functions') |
def test_bare_reraise_single_exception():
program = 'def f(x):\n try:\n return 1 / x\n except ZeroDivisionError:\n raise\n'
__assert_found(program, 'ZeroDivisionError') |
class create_model_2(torch.nn.Module):
def __init__(self):
super(create_model_2, self).__init__()
self.conv1 = Conv2d(3, 3, kernel_size=1, stride=1)
self.bn = BatchNorm2d(3)
self.bn = bn_weight_change(self.bn)
self.bn2 = BatchNorm2d(3)
self.bn2 = bn_weight_change(self... |
def _environ_cols_tput(*_):
try:
import shlex
cols = int(subprocess.check_call(shlex.split('tput cols')))
return cols
except:
pass
return None |
def RenderRegion(points, lines, region, filename):
dwg = svgwrite.Drawing(filename, profile='tiny')
for line in lines:
x1 = (1000 - int((((line[0] - region[0]) / (region[2] - region[0])) * 1000)))
y1 = int((((line[1] - region[1]) / (region[3] - region[1])) * 1000))
x2 = (1000 - int((((li... |
class FullHessianUpdateStrategy(HessianUpdateStrategy):
_syr = get_blas_funcs('syr', dtype='d')
_syr2 = get_blas_funcs('syr2', dtype='d')
_symv = get_blas_funcs('symv', dtype='d')
def __init__(self, init_scale='auto'):
self.init_scale = init_scale
self.first_iteration = None
self... |
def remove_punctuation(strs):
return re.sub('[\\s+\\.\\!\\/<>,$%^*(+"\']+|[+!,?~#%......&*()]+', '', strs.strip()) |
.expensive
def test_gcsl_run():
os.environ['WANDB_MODE'] = 'offline'
subprocess.run(lunar_command, check=True) |
def check_positive(input_matrix: Union[(sparse.csr_matrix, np.ndarray)]):
if (not has_positive_entries(input_matrix)):
raise ValueError('Only positive values are expected.') |
def tetrahedralize_vtk_mesh(vtkdata):
tetra = vtk.vtkDataSetTriangleFilter()
if (vtk_version < 6):
tetra.SetInput(vtkdata)
else:
tetra.SetInputData(vtkdata)
tetra.Update()
return tetra.GetOutput() |
def make_list_of_t(ts, check_graph=True, allow_graph=True, ignore_ops=False):
if isinstance(ts, tf_ops.Graph):
if allow_graph:
return get_tensors(ts)
else:
raise TypeError('allow_graph is False: cannot convert a tf.Graph.')
else:
if (not is_iterable(ts)):
... |
def train_model(model, dataset, params, ckpt, ckpt_manager, out_file):
optimizer = tf.keras.optimizers.Adagrad(params['learning_rate'], initial_accumulator_value=params['adagrad_init_acc'], clipnorm=params['max_grad_norm'])
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False, reduction... |
()
('data-path', default='data/ner_conll/en/test.txt')
('checkpoint-model-name', type=str, default='studio-ousia/luke-large-finetuned-conll-2003')
('--model-config-path', type=click.Path(exists=True))
('--checkpoint-tokenizer-name', type=str)
('--batch-size', type=int, default=32)
('--cuda-device', type=int, default=0)... |
def test_beeswarm_input_is_explanation():
with pytest.raises(TypeError, match='beeswarm plot requires an `Explanation` object'):
_ = shap.plots.beeswarm(np.random.randn(20, 5), show=False) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.