code stringlengths 101 5.91M |
|---|
def create_dataset(cfg: CfgNode, dataset_cfg: CfgNode, train: bool=True, **kwargs) -> Dataset:
dataset_type = Dataset.registry[dataset_cfg.TYPE]
return dataset_type(cfg, **to_lower(dataset_cfg), train=train, **kwargs) |
def get_result(setup):
result_dict = {}
for dataset in dataset_all:
result_dict[dataset] = {}
sub_result_dict = result_dict[dataset]
basedir = f'{base_output_dir}/{dataset}/{setup}'
for (alg_name, alg_name_long) in algorithm_all.items():
if (alg_name in ['CLIPPretrain... |
def flatten_batch_lists(batch_list, nb_batches):
flat_list = []
for b in range(nb_batches):
flat_list += batch_list[b]
return flat_list |
class MLP_2HL(nn.Module):
def __init__(self, dim_in, dim_hidden1, dim_hidden2, sparse=False, bn=True):
super(MLP_2HL, self).__init__()
self.in_layer = (SpLinear(dim_in, dim_hidden1) if sparse else nn.Linear(dim_in, dim_hidden1))
self.dropout_layer = nn.Dropout(0.0)
self.lrelu = nn.Le... |
class TestGFortranVersions(object):
def test_gfortran_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95')
for (vs, version) in gfortran_version_strings:
v = fc.version_match(vs)
assert_((v == version), (vs, v))
def test_not_gfortran(self):
... |
def test_prefitted_throws_error():
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
st = SelfTrainingClassifier(knn)
with pytest.raises(NotFittedError, match='This SelfTrainingClassifier instance is not fitted yet'):
st.predict(X_train) |
def run_and_return_first_line(run_lambda, command):
(rc, out, _) = run_lambda(command)
if (rc != 0):
return None
return out.split('\n')[0] |
class Partition15(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[21]', 'T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[22]', 'T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[23]', 'T5ForConditionalGeneration/T5Stack[dec... |
def get_random_predictions(train_file, test_file, iterations=1000):
df = pd.read_csv(train_file)
total_label = df['label'].to_numpy()
total_ones = np.sum(total_label)
total_zeros = (len(total_label) - total_ones)
df = pd.read_csv(test_file)
random_label = choices([0, 1], [total_zeros, total_ones... |
class TFRegNetSELayer(tf.keras.layers.Layer):
def __init__(self, in_channels: int, reduced_channels: int, **kwargs):
super().__init__(**kwargs)
self.pooler = tf.keras.layers.GlobalAveragePooling2D(keepdims=True, name='pooler')
self.attention = [tf.keras.layers.Conv2D(filters=reduced_channels... |
def ground_truth_reconstruct_multi(inp, cfg):
with torch.no_grad():
assert hasattr(cfg, 'inference')
step_size_ratio = float(getattr(cfg.inference, 'step_size_ratio', 1))
num_steps = int(getattr(cfg.inference, 'num_steps', 5))
num_points = int(getattr(cfg.inference, 'num_points', inp... |
class RegNetConfig(PretrainedConfig):
model_type = 'regnet'
layer_types = ['x', 'y']
def __init__(self, num_channels=3, embedding_size=32, hidden_sizes=[128, 192, 512, 1088], depths=[2, 6, 12, 2], groups_width=64, layer_type='y', hidden_act='relu', **kwargs):
super().__init__(**kwargs)
if (l... |
class TFRobertaForNaturalQuestionAnswering(TFRobertaPreTrainedModel):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.num_labels = config.num_labels
self.roberta = TFRobertaMainLayer(config, name='roberta')
self.initializer = get_initia... |
def _delta_poly(prec=10):
if (prec <= 0):
raise ValueError('prec must be positive')
v = ([0] * prec)
stop = int((((- 1) + math.sqrt((1 + (8 * prec)))) / 2.0))
values = [(((n * (n + 1)) // 2), ((((- 2) * n) - 1) if (n & 1) else ((2 * n) + 1))) for n in range((stop + 1))]
for (i1, v1) in value... |
class FixedNormal(torch.distributions.Normal):
def log_probs(self, actions):
return super().log_prob(actions).sum((- 1), keepdim=True)
def entrop(self):
return super.entropy().sum((- 1))
def mode(self):
return self.mean |
.parametrize('forest_cls', FORESTS)
def test_fit_int_time(make_whas500, forest_cls):
whas500 = make_whas500(to_numeric=True)
y = whas500.y
y_int = np.empty(y.shape[0], dtype=[(y.dtype.names[0], bool), (y.dtype.names[1], int)])
y_int[:] = y
forest_f = forest_cls(oob_score=True, random_state=2).fit(wh... |
def test_gdb():
global have_gdb
if (have_gdb is not None):
return have_gdb
have_gdb = False
try:
p = subprocess.Popen(['gdb', '-nx', '--version'], stdout=subprocess.PIPE)
except OSError:
gdb_version = None
else:
(stdout, _) = p.communicate()
regex = 'GNU g... |
def main(args):
if (args.num_envs is None):
import multiprocessing as mp
args.num_envs = max((mp.cpu_count() - 1), 1)
merge_args_into_config(args, config)
if (config.gamma < 1.0):
config.clip_target_range = (np.round((- (1 / (1 - config.gamma))), 2), 0.0)
if (config.gamma == 1):
... |
_utils.test()
def test_reduction_non_full_warp():
def test() -> ti.i32:
hit_time = 1
ti.loop_config(block_dim=8)
for i in range(8):
ti.atomic_min(hit_time, 1)
return hit_time
assert (test() == 1) |
class TestCategoryFolderIO(object):
.slow
def test_imdb(self, spacy_nlp_en):
folder_io = CategoryFolderIO(categories=['pos', 'neg'], mapping={'<br />': '\n'}, tokenize_callback=spacy_nlp_en, encoding='utf-8', case_mode='lower')
train_data = folder_io.read('data/imdb/train')
test_data = f... |
class InstanceData(GeneralData):
def __setattr__(self, name, value):
if (name in ('_meta_info_fields', '_data_fields')):
if (not hasattr(self, name)):
super().__setattr__(name, value)
else:
raise AttributeError(f'{name} has been used as a private attri... |
def calculade_fid_no_img(img_i, activations_pred, activations_target, eps=1e-06):
activations_pred = activations_pred.copy()
activations_pred[img_i] = activations_target[img_i]
return calculate_frechet_distance(activations_pred, activations_target, eps=eps) |
def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None, tmp=False):
checkpoint = _load_checkpoint(filename, map_location, logger)
if (not isinstance(checkpoint, dict)):
raise RuntimeError(f'No state_dict found in checkpoint file {filename}')
if ('state_dict' in checkpoint... |
def stream(stream):
if (stream is None):
(yield)
return
src_prev_stream = current_stream()
if (src_prev_stream.device != stream.device):
with device(stream.device):
dst_prev_stream = current_stream()
torch._C._cuda_setStream(stream._cdata)
try:
(yield)
... |
def batchnorm_refusing_node_matchers():
bn_node = NodeOperationMatcher(BatchNorm2d)
source_node = (NodeOperationMatcher(Conv2d) | NodeOperationMatcher(ConvTranspose2d))
return (bn_node, source_node) |
class ComputationCache():
def __init__(self, chromosome, fitness_functions: (list[FitnessFunction] | None)=None, coverage_functions: (list[CoverageFunction] | None)=None, fitness_cache: (dict[(FitnessFunction, float)] | None)=None, is_covered_cache: (dict[(FitnessFunction, bool)] | None)=None, coverage_cache: (dict... |
def show_seg_data(idx, dataset, out_dir, filename, show=False):
example = dataset.prepare_train_data(idx)
points = example['points']._data.numpy()
gt_seg = example['pts_semantic_mask']._data.numpy()
show_seg_result(points, gt_seg.copy(), None, out_dir, filename, np.array(dataset.PALETTE), dataset.ignore... |
def _get_optimizer_state(optimizer):
states = loads(optimizer._updaters[0].get_states(dump_optimizer=False))
result_states = {}
for (state_key, state_tuple) in states.items():
for (state_ind, state) in enumerate(state_tuple):
result_states[f'opt_state__{state_key}__{state_ind}'] = state.... |
def mlp_module(x0, x1):
h1_0 = PF.affine(x0, 100, name='affine1_0')
h1_1 = PF.affine(x1, 100, name='affine1_0')
h1 = F.tanh((h1_0 + h1_1))
h2 = F.tanh(PF.affine(h1, 50, name='affine2'))
y0 = PF.affine(h2, 10, name='affiney_0')
y1 = PF.affine(h2, 10, name='affiney_1')
return (y0, y1) |
def _gen_torch_functional_registered_ops():
ops = ['stft', 'istft', 'lu', 'lu_unpack', 'cdist', 'norm', 'unique', 'unique_consecutive']
return set((getattr(torch.functional, name) for name in ops)) |
def base_axis_1_reshape_with_neg_1(x):
h = PF.convolution(x, 3, (3, 3), pad=(0, 0), name='c1', base_axis=1)
y = F.reshape(h, shape=(1, 18, (- 1)))
return y |
def xchg(locked: dace.int32[1], output: dace.int32[20]):
for i in dace.map[0:20]:
with dace.tasklet:
(l >> locked((- 1), (lambda old, new: new)))
(out >> output[i])
l = 4
out = l |
def adaptive_bins(hist, threshold):
new = hist.copy()
peak = hist.max()
peak_depth = np.where((hist == peak))[0]
delta_hist = np.diff(hist, n=1, axis=0)
left = peak_depth
right = peak_depth
i = np.array([peak_depth[0]])
while 1:
new[[i]] = 0
if (i >= 254):
rig... |
def get_laplacian(adjacency: sparse.csr_matrix) -> sparse.csr_matrix:
weights = adjacency.dot(np.ones(adjacency.shape[0]))
return (sparse.diags(weights) - adjacency) |
def build_global_POI_checkin_graph(df, exclude_user=None):
G = nx.DiGraph()
users = list(set(df['user_id'].to_list()))
if (exclude_user in users):
users.remove(exclude_user)
loop = tqdm(users)
for user_id in loop:
user_df = df[(df['user_id'] == user_id)]
for (i, row) in user_... |
class ProgramGraphNode():
def __init__(self, index: int, offset: int=0, basic_block: (BasicBlock | None)=None, is_artificial: bool=False) -> None:
self._index = index
self._offset = offset
self._basic_block = basic_block
self._is_artificial = is_artificial
self._predicate_id:... |
class DocumentEncoder(nn.Module):
def __init__(self, hidden_dim, char_filters, n_layers=2):
super().__init__()
glove_weights = F.normalize(GLOVE.weights())
turian_weights = F.normalize(TURIAN.weights())
self.glove = nn.Embedding(glove_weights.shape[0], glove_weights.shape[1])
... |
class TensorforceAgent(Agent):
def __init__(self, observation_space, action_space, directory):
self.observation_space = observation_space
self.action_space = action_space
self.directory = directory
self.agent = None
def train(self, env, nb_steps):
try:
print('... |
def maybe_download_and_extract_netflix_data(data_dir, force_overwrite=False):
write_path = os.path.join(data_dir, 'netflix-prize.zip')
zip_url = '
if (not os.path.isfile(write_path)):
os.makedirs(data_dir, exist_ok=True)
print('Zip not downloaded. Downloading now...')
save_zip_data(w... |
def save_md5(files, out_file):
md5_dict = {}
for file in files:
md5_dict[file] = get_md5(file)
save_pkl(md5_dict, out_file) |
class stylegenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, gpu_ids=[], padding_type='reflect', n_downsampling=5, opt=None):
super(stylegenerator, self).__init__()
assert ((type(input_nc) == list) and (len(input_nc) == 3)... |
def main():
parser = argparse.ArgumentParser(prog='skyline', description='Skyline: Interactive Neural Network Performance Profiler, Visualizer, and Debugger for PyTorch')
parser.add_argument('-v', '--version', action='store_true', help='Print the version and exit.')
subparsers = parser.add_subparsers(title=... |
def digits_format(testdir):
module = testdir.make_importable_pyfile(hook='\n import string\n import schemathesis\n from hypothesis import strategies as st\n\n schemathesis.openapi.format(\n "digits",\n st.text(\n min_size=1,\n alphabet=st.characters(\n ... |
class NarrowIEOpenIECombiner(object):
def __init__(self, oie_data_dir, IDF_path, csv_path, SUBWORDUNIT, sp_size, number_of_clusters=50, stemming=False, stopwords=True, SUBWORD_UNIT_COMBINATION='avg', path_to_embeddings=None):
self.oie_data_dir = oie_data_dir
self.csv_path = csv_path
self.num... |
class LieAlgebras(Category_over_base_ring):
_method
def super_categories(self):
return [Modules(self.base_ring())]
class SubcategoryMethods():
def Nilpotent(self):
return self._with_axiom('Nilpotent')
Graded = LazyImport('sage.categories.graded_lie_algebras', 'GradedLieAlgebr... |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('axis', [0, 1, 2, (- 1), (- 2), (- 3)])
.parametrize('n', [3, 5])
def test_top_n_error_forward(seed, axis, n, ctx, func_name):
ishape = [5, 6, 7]
rng = np.random.RandomState(seed)
l_shape = list(ishape)
l_shape[axis] = 1
n... |
_toolkit()
class GoogleHome(FunctionToolkit):
name_for_human = 'Google Home'
description_for_human = 'Toolkit for controlling and managing Google Home devices.'
name_for_model = 'GoogleHome'
description_for_model = 'A toolkit for controlling and managing Google Home devices, enabling users to control sm... |
class RealizationsCategory(RegressiveCovariantConstructionCategory):
_functor_category = 'Realizations' |
def lr_func_steps_with_decay(cur_iter):
ind = get_step_index(cur_iter)
return (cfg.SOLVER.BASE_LR * (cfg.SOLVER.GAMMA ** ind)) |
def get_graph(arr, passable='empty'):
graph = nx.Graph()
(width, height) = arr.shape
size = (width * height)
graph.add_nodes_from(range(size))
for u in range(size):
(ux, uy) = ((u // width), (u % width))
if (arr[(ux, uy)] != passable):
continue
neighbs_xy = [((ux ... |
def MAE(original_path, approximate_path):
with open(original_path, 'r') as fo:
org_line_list = fo.readlines()
with open(approximate_path, 'r') as fa:
app_line_list = fa.readlines()
org = [list(filter((lambda a: (a != ' ')), list(i[:(- 1)]))) for i in org_line_list]
app = [list(filter((la... |
def main():
evaluator = CoQAEvaluator(OPTS.data_file)
if OPTS.human:
print(json.dumps(evaluator.human_performance(), indent=2))
if OPTS.pred_file:
with open(OPTS.pred_file) as f:
pred_data = CoQAEvaluator.preds_to_dict(OPTS.pred_file)
print(json.dumps(evaluator.model_perf... |
class LogisticRegression(GNNModel):
def __init__(self, features, graph_adj, targets, nodes_to_consider, weight_decay, normalize_features):
self.normalize_features = normalize_features
with tf.name_scope('extract_relevant_nodes'):
targets = tf.gather(targets, nodes_to_consider)
su... |
class DataSetIter(BatchIter):
def __init__(self, dataset, batch_size=1, sampler=None, as_numpy=False, num_workers=0, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, batch_sampler=None, max_tokens=2500):
assert isinstance(dataset, DataSet)
if (sampler is not None):
data... |
class Trainer():
def __init__(self, corpus, optimizers, translator, batch_size=2, backbool=False, penalty_tuning=None, cosinealpha=None):
self.corpus = corpus
self.translator = translator
self.optimizers = optimizers
self.batch_size = batch_size
self.backbool = backbool
... |
def register_Ns3Dot11sHwmpRtable_methods(root_module, cls):
cls.add_constructor([param('ns3::dot11s::HwmpRtable const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AddPrecursor', 'void', [param('ns3::Mac48Address', 'destination'), param('uint32_t', 'precursorInterface'), param('ns3::Mac48Address', '... |
def register_Ns3Dot11sIeRann_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
cls.add_constructor([param('ns3::dot11s::IeRann const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DecrementTtl', 'void', [])
cls.add_method('DeserializeInfo... |
def load_multiple_tracker_summaries(tracker_folder, tracker_list, cls):
data = {}
for tracker in tracker_list:
with open(os.path.join(tracker_folder, tracker, (cls + '_summary.txt'))) as f:
keys = next(f).split(' ')
done = False
while (not done):
value... |
class ResNet(nn.Module):
def __init__(self, last_stride, bn_norm, with_ibn, with_se, with_nl, block, layers, non_layers):
self.channel_nums = []
self.inplanes = 64
super().__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = get_... |
def scope_dirname(scope):
slash = scope.rfind('/')
if (slash == (- 1)):
return ''
return scope[:(slash + 1)] |
def test_load():
def fake_condition(memo_info, manager, args):
if (memo_info.state == 'RAW'):
return [memo_info]
else:
return []
def fake_action(memories, args):
return (FakeProtocol('protocol'), [None], [None], [{}])
tl = Timeline()
node = FakeNode('node'... |
_model
def resnest50d_1s4x24d(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
default_cfg = default_cfgs['resnest50d_1s4x24d']
model = ResNet(ResNestBottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, stem_type='deep', stem_width=32, avg_down=True, base_width=24, cardinality=4, bloc... |
def collate_dgl(samples):
(graphs, labels) = map(list, zip(*samples))
batched_graph = dgl.batch(graphs)
if isinstance(labels[0], torch.Tensor):
return (batched_graph, torch.stack(labels))
else:
return (batched_graph, labels) |
def run_test(cfg, model, distributed):
if distributed:
model = model.module
torch.cuda.empty_cache()
iou_types = ('bbox',)
if cfg.MODEL.MASK_ON:
iou_types = (iou_types + ('segm',))
if cfg.MODEL.KEYPOINT_ON:
iou_types = (iou_types + ('keypoints',))
output_folders = ([None]... |
def calc_em_score(answers, prediction):
em = 0
for ans in answers:
ans_ = remove_punctuation(ans['text'])
prediction_ = remove_punctuation(prediction)
if (ans_ == prediction_):
em = 1
break
return em |
(nopython=True, nogil=True)
def gower_distance(r0: np.ndarray, r1: np.ndarray, cat_cols_index: np.ndarray) -> float64:
dist = 0.0
for i in range(len(r0)):
if (isnan(r0[i]) and isnan(r1[i])):
dist += 1
elif (i < cat_cols_index):
dist += fabs((r0[i] - r1[i]))
elif (... |
class TestConjugatePriors(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
np.random.seed(12345)
def test_beta_bernoulli(self):
print()
logger.info((('test_beta_bernoulli\n' + ('-' * 80)) + '\n'))
for theta in [0.21, 0.5, 0.93]:
... |
def process_test_params_for_module(test_params_dict, device, test_instance_class):
module_name = compute_module_name(test_params_dict)
test_params_dict['constructor'] = test_params_dict.get('constructor', getattr(torch.nn, module_name))
test_instance = test_instance_class(**test_params_dict)
assert test... |
def convBlock(numIn, numOut, inputResH, inputResW, net_type, baseWidth, cardinality, stride):
numIn = int(numIn)
numOut = int(numOut)
addTable = ConcatTable()
s_list = []
if (net_type != 'no_preact'):
s_list.append(nn.BatchNorm2d(numIn))
s_list.append(nn.ReLU(True))
conv1 = nn.Co... |
def F(y, u, p, geometry):
return ((dot(grad(y), grad(p)) * geometry.dx) - ((u * p) * geometry.dx)) |
def _get_region(name, regions, bc_name):
try:
region = regions[name]
except IndexError:
msg = ("no region '%s' used in condition %s!" % (name, bc_name))
raise IndexError(msg)
return region |
class GemmOperation():
def __init__(self, gemm_kind, arch, tile_description, A, B, C, element_epilogue, epilogue_functor=EpilogueFunctor.LinearCombination, swizzling_functor=SwizzlingFunctor.Identity8):
self.operation_kind = OperationKind.Gemm
self.arch = arch
self.tile_description = tile_de... |
def run_experiment(method_call=None, batch_tasks=None, exp_prefix='experiment', exp_name=None, log_dir=None, script='garage.experiment.experiment_wrapper', python_command='python', dry=False, env=None, variant=None, force_cpu=False, pre_commands=None, **kwargs):
warnings.warn(DeprecationWarning('run_experiment is d... |
def setup_plot_report_loss_entries(training_type):
if ((training_type == 'classification') or (training_type == 'regression')):
entries = ['main/loss', 'val/main/loss']
elif (training_type == 'multi_regression'):
entries = ['main/loss', 'validation/main/loss', 'main/loss_click', 'validation/main... |
def quantize_model_(model, size_tracker, layers_to_quantize, block_sizes_config, n_centroids_config, step=0, n_iter=15, eps=1e-06, max_tentatives=100, remove_weights=False, verbose=True, state_dict=None):
quantized_layers = get_layers(model, layers_to_quantize[step], remove_weights=remove_weights)
for layer in ... |
def process_coverage():
global ARGS, MAP, FIRST_COVERAGE
while True:
fuzzer_files = []
for fuzzer in get_all_names(False):
fuzzer_files += get_coverage_fuzzer_files(fuzzer)
if fuzzer_files:
random.shuffle(fuzzer_files)
process_coverage_fuzzer_files(fuz... |
class QuantileRegressor(LinearModel, RegressorMixin, BaseEstimator):
_parameter_constraints: dict = {'quantile': [Interval(Real, 0, 1, closed='neither')], 'alpha': [Interval(Real, 0, None, closed='left')], 'fit_intercept': ['boolean'], 'solver': [StrOptions({'highs-ds', 'highs-ipm', 'highs', 'interior-point', 'revi... |
class EarlyStopScheduler(torch.optim.lr_scheduler.ReduceLROnPlateau):
def __init__(self, optimizer, mode='min', factor=0.1, patience=10, verbose=False, threshold=0.0001, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-08):
super().__init__(optimizer, mode=mode, factor=factor, patience=patience, threshold... |
class TrainLmConfig():
data: Union[(LMDatasetConfig, LMMixtureDatasetConfig)] = field(default_factory=LMDatasetConfig)
trainer: TrainerConfig = field(default_factory=TrainerConfig)
model: LmConfig = field(default_factory=Gpt2Config)
optimizer: OptimizerConfig = field(default_factory=OptimizerConfig)
... |
def load_checkpoint(path, device='cpu'):
path = Path(path).expanduser()
is_deepspeed = False
if path.is_dir():
is_deepspeed = True
latest_path = (path / 'latest')
if latest_path.is_file():
with open(latest_path, 'r') as fd:
tag = fd.read().strip()
... |
.pure
def test_two_backward_passes():
def train_step(x1: dace.float32[(10, 5)], x2: dace.float32[5], dy: dace.float32[10]):
x1.requires_grad_()
x2.requires_grad_()
z1 = (x1 + 1)
y1 = np.log(z1)
l1 = np.add.reduce(y1, axis=1)
z2 = (x2 * 2)
y2 = np.log(z2)
... |
def adjust_learning_rate(optimizers, cur_iter, args):
scale_running_lr = ((1.0 - (float(cur_iter) / args.max_iters)) ** args.lr_pow)
args.running_lr_encoder = (args.lr_encoder * scale_running_lr)
args.running_lr_decoder = (args.lr_decoder * scale_running_lr)
(optimizer_encoder, optimizer_decoder) = opti... |
def _unlink_solc(solc_path: Path) -> None:
solc_path.unlink()
if (_get_target_os() == 'windows'):
shutil.rmtree(solc_path.parent) |
class DSConvNetwork(network_base.BaseNetwork):
def __init__(self, inputs, trainable=True, conv_width=1.0):
self.conv_width = conv_width
network_base.BaseNetwork.__init__(self, inputs, trainable)
def setup(self):
self.feed('image').conv(3, 3, 64, 1, 1, name='conv1_1', trainable=False).sep... |
class TFGroupViTTextModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def checkpoint_sequential(functions, segments, input, **kwargs):
preserve = kwargs.pop('preserve_rng_state', True)
if kwargs:
raise ValueError(('Unexpected keyword arguments: ' + ','.join((arg for arg in kwargs))))
def run_function(start, end, functions):
def forward(input):
for ... |
def create_tensor(array: numpy.ndarray) -> Union[(torch.Tensor, numpy.ndarray)]:
if (array.dtype.kind in 'UO'):
return array
if (array.dtype == numpy.uint32):
array = numpy.asarray(array, dtype=numpy.int64)
return torch.tensor(array) |
def unpooling_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, kernel, channel_last=False):
dy = grad_inputs[0]
x0_shape = input_shapes[0]
ctx = nn.get_current_context()
df = UnpoolingDataGrad(ctx, kernel, channel_last)
df.xshape = x0_shape
dx0 = df(dy)
return dx0 |
class CvtSelfAttentionLinearProjection(nn.Module):
def forward(self, hidden_state):
(batch_size, num_channels, height, width) = hidden_state.shape
hidden_size = (height * width)
hidden_state = hidden_state.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
return hidden_sta... |
def planetType(temperature, mass, radius):
if (mass is not np.nan):
sizeType = planetMassType(mass)
elif (radius is not np.nan):
sizeType = planetRadiusType(radius)
else:
return None
return '{0} {1}'.format(planetTempType(temperature), sizeType) |
_utils.test(arch=[ti.opengl, ti.vulkan])
def test_mpm99_aot():
quality = 1
(n_particles, n_grid) = ((9000 * (quality ** 2)), (128 * quality))
(dx, inv_dx) = ((1 / n_grid), float(n_grid))
dt = (0.0001 / quality)
(p_vol, p_rho) = (((dx * 0.5) ** 2), 1)
p_mass = (p_vol * p_rho)
(E, nu) = (1000.... |
class Tokenizer(Registrable):
default_implementation = 'word'
def batch_tokenize(self, texts: List[str]) -> List[List[Token]]:
raise NotImplementedError
def tokenize(self, text: str) -> List[Token]:
raise NotImplementedError |
_task('translation_multi_simple_epoch')
class TranslationMultiSimpleEpochTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('-s', '--source-lang', default=None, metavar='SRC', help='inference source language')
parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET',... |
def get_imagenet_models(config):
super_type = getattr(config, 'super_type', 'basic')
if (super_type == 'basic'):
from .ImageNet_ResNet import ResNet
from .ImageNet_MobileNetV2 import MobileNetV2
if (config.arch == 'resnet'):
return ResNet(config.block_name, config.layers, con... |
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str)
parser.add_argument('--gt_dir', type=str, default='')
parser.add_argument('--sample_dir', type=str, default='')
parser.add_argument('--gpu', type=int, default=0)
parser.add_argument('--batch_size', type=i... |
class CVTArchive(ArchiveBase):
def __init__(self, bins, ranges, seed=None, dtype=np.float64, samples=100000, custom_centroids=None, k_means_kwargs=None, use_kd_tree=False, ckdtree_kwargs=None):
ArchiveBase.__init__(self, storage_dims=(bins,), behavior_dim=len(ranges), seed=seed, dtype=dtype)
ranges ... |
def layer_graph_t5_3b_tied_lmheads_64_4_8p_bw12_async_squad1_mpipe():
return dict(model_type='t5_stateless', model_name_or_path='t5-3b', do_lower_case=False, output_past=False, stateless_tied=True, explicitly_set_dict={'return_dict': False, 'use_cache': False, 'output_only': True, 'output_attentions': False, 'preco... |
class StreetMap():
def __init__(self):
self.scenario = None
self.graph = None
self.route_partition = None
self.lane_graph = None
def reset(self, scenario: BasicScenario):
self.scenario = scenario
self.graph = RoadLaneJunctionGraph(scenario)
self.route_part... |
def build_rpn_head(cfg, input_shape, shadow_object_part=False):
name = cfg.MODEL.RPN.HEAD_NAME
return RPN_HEAD_REGISTRY.get(name)(cfg, input_shape, shadow_object_part) |
def ssd(config, cfg, *args, **kwargs):
weights = config.weights
if (config.im_size == 512):
model = SSD512(config, cfg)
elif (config.im_size == 300):
model = SSD300(config, cfg)
else:
print_error_message('{} image size not supported'.format(config.im_size))
if weights:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.