code stringlengths 101 5.91M |
|---|
def register_Ns3LteRrcSapCarrierFreqEutra_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteRrcSap::CarrierFreqEutra const &', 'arg0')])
cls.add_instance_attribute('dlCarrierFreq', 'uint16_t', is_const=False)
cls.add_instance_attribute('ulCarrierFreq', 'uint16_t', is... |
def build_backbone(cfg):
assert (cfg.MODEL.BACKBONE.CONV_BODY in registry.BACKBONES), 'cfg.MODEL.BACKBONE.CONV_BODY: {} are not registered in registry'.format(cfg.MODEL.BACKBONE.CONV_BODY)
return registry.BACKBONES[cfg.MODEL.BACKBONE.CONV_BODY](cfg) |
def train(args, model, train_sampler, valid_samplers=None, test_samplers=None, rank=0, rel_parts=None, cross_rels=None, barrier=None, client=None):
logs = []
for arg in vars(args):
logging.info('{:20}:{}'.format(arg, getattr(args, arg)))
if (len(args.gpu) > 0):
gpu_id = (args.gpu[(rank % len... |
def parse_argv(parser):
parser.add_argument('--seed', default=123, type=int, help='Random seed.')
parser.add_argument('-d', '--destdir', default='.embeddings/', type=str, help='where to save embeddings.')
parser.add_argument('--embeddings', required=True, help='which embeddings to download') |
class ResNet(nn.Module):
def __init__(self, block, num_blocks, in_channels=1, num_classes=2):
super(ResNet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 =... |
def train_sequential(model, train_loader, val_loader, max_epochs=200, frequency=2, patience=5, model_path='saved_model', full_config_dict={}):
loss_1 = 'CE'
loss_2 = model.loss
print('### Encoder training ###')
model.loss = loss_1
model.no_density = True
(train_losses_1, val_losses_1, train_accu... |
def split_list(array, split_factors):
assert (round(sum(split_factors), 6) == 1), 'split_factors should sum to one'
np.random.shuffle(array)
pivots = [int((len(array) * x)) for x in split_factors]
out = []
indx = 0
for i in pivots:
out.append(array[indx:(i + indx)])
indx = i
... |
def load_db_data_to_data_frame(datasource, select):
conn = db.connect_with_data_source(datasource)
generator = verifier.fetch_samples(conn, select, n=(- 1))
names = generator.field_names
dtypes = []
for dtype in generator.field_types:
if (dtype in ['VARCHAR', 'CHAR', 'TEXT', 'STRING']):
... |
def get_weights_quantizer_for_node(node: BaseNode) -> BaseKerasInferableQuantizer:
if (node.final_weights_quantization_cfg is None):
Logger.critical(f'Can not set quantizer for a node with no final weights quantization configuration')
node_w_qc = node.final_weights_quantization_cfg
weights_quantizat... |
def merge_dict(dicts: Sequence[dict], merge_fn: Callable=(lambda *args: args)) -> dict:
if (len(dicts) == 0):
return dict()
return {key: merge_fn([dict_[key] for dict_ in dicts]) for key in dicts[0].keys()} |
class Struc2Vec():
def __init__(self, graph, walk_length=10, num_walks=100, workers=1, verbose=0, stay_prob=0.3, opt1_reduce_len=True, opt2_reduce_sim_calc=True, opt3_num_layers=None, temp_path='./temp_struc2vec/', reuse=False):
self.graph = graph
(self.idx2node, self.node2idx) = preprocess_nxgraph(... |
class TestNet(nn.Module):
def __init__(self):
super(TestNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3)
self.bn1 = nn.BatchNorm2d(num_features=64)
self.conv2 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3)
self.bn2 = nn... |
class CubicHeckeMatrixRep(Matrix_generic_dense):
_method
def _get_block(self, ind):
representation_type = self.parent()._representation_type
if (not representation_type.is_split()):
return matrix(self)
n = self.parent()._cubic_hecke_algebra.ngens()
s = sum((irr_rep.di... |
def is_None_tensor(recved_tensor):
return ((recved_tensor.size() == torch.Size()) and np.isnan(recved_tensor.item())) |
def got8(all_potential_countries) -> operations.GraphOfOperations:
operations_graph = operations.GraphOfOperations()
sub_texts = operations.Generate(1, 1)
operations_graph.append_operation(sub_texts)
sub_paragraphs = []
for i in range(1, 9):
paragraph_id = f'Paragraph {i}'
sub_text =... |
def multiple_databases():
os.makedirs(DB_PATH)
db_1 = SingleDatabase(db_path=DB_PATH, db_name=f'{DB_NAME}_1', tables={TABLE_NAME: TABLE_DATAFRAME})
db_2 = SingleDatabase(db_path=DB_PATH, db_name=f'{DB_NAME}_2', tables={TABLE_NAME: TABLE_DATAFRAME})
db_3 = SingleDatabase(db_path=DB_PATH, db_name=f'{DB_NA... |
def rename(checkpoint_dir, replace_from, replace_to, add_prefix, dry_run, out_checkpoint_dir):
checkpoint = tf.train.get_checkpoint_state(checkpoint_dir)
with tf.Session() as sess:
for (var_name, _) in tf.contrib.framework.list_variables(checkpoint_dir):
var = tf.contrib.framework.load_varia... |
def update_graphics(board: np.ndarray, game_display, clock, fps: int=1) -> None:
import pygame
n = board.shape[0]
canvas_scale = int(((ctypes.windll.user32.GetSystemMetrics(1) * (16 / 30)) / n))
game_display.fill((255, 255, 255))
for y in range(canvas_scale, ((n + 2) * canvas_scale), canvas_scale):
... |
class T5Stack(T5PreTrainedModel):
def __init__(self, config, embed_tokens=None):
super().__init__(config)
self.embed_tokens = embed_tokens
self.is_decoder = config.is_decoder
self.precomputed_masks = config.precomputed_masks
for i in range(config.num_layers):
self... |
class _QueueWriter(dataio.Writer):
def __init__(self, wrapper):
self._wrapper = wrapper
def setup_ex(self, init_net, exit_net):
exit_net.CloseBlobsQueue([self._wrapper.queue()], 0)
def write_ex(self, fields, local_init_net, local_finish_net, status):
self._wrapper._new_writer(self.sc... |
.parametrize('observation_shape', [(100,), (4, 84, 84), ((100,), (200,))])
.parametrize('q_func_factory', [MeanQFunctionFactory(), QRQFunctionFactory()])
.parametrize('scalers', [None, 'min_max'])
.parametrize('advantage_type', ['mean', 'max'])
.parametrize('weight_type', ['exp', 'binary'])
.parametrize('target_update_... |
def collect_predictions(model, data_configs):
folder = data_configs.get('dir')
testsets = ['bs_full']
for testset in testsets:
data_file = os.path.join(folder, testset[0])
print(f'>>> Evaluating model on test data {data_file}')
data = np.load(data_file)
raw_predictions = mode... |
class Conv3d(_ConvNd):
__doc__ = (('Applies a 3D convolution over an input signal composed of several input\n planes.\n\n In the simplest case, the output value of the layer with input size :math:`(N, C_{in}, D, H, W)`\n and output :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` can be precisely described ... |
def slerp(t, v0, v1, DOT_THRESHOLD=0.9995):
v0_copy = np.copy(v0)
v1_copy = np.copy(v1)
v0 = (v0 / np.linalg.norm(v0))
v1 = (v1 / np.linalg.norm(v1))
dot = np.sum((v0 * v1))
if (np.abs(dot) > DOT_THRESHOLD):
return lerp(t, v0_copy, v1_copy)
theta_0 = np.arccos(dot)
sin_theta_0 = ... |
def get_ttest_args():
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mode', choices=['ttest', 'fisher', 'mcnemar'], default='ttest')
parser.add_argument('-em', '--evaluate_metric', default='acc')
parser.add_argument('-t', '--evaluate_split', default='test')
parser.add_argument('-o',... |
def adaptive_avg_pool3d(input, output_size):
output_size = _list_with_default(output_size, input.size())
return torch._C._nn.adaptive_avg_pool3d(input, output_size) |
def mk_lean_auto_soundness_name(fn_name: str, namespaces: List[ScopedName]):
prefix = 'auto_sound_'
return get_name_in_open_scopes(ScopedName.from_string(fn_name), namespaces, prefix) |
class docVarListEntryType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, term=None):
self.term = term
def factory(*args_, **kwargs_):
if docVarListEntryType.subclass:
return docVarListEntryType.subclass(*args_, **kwargs_)
else:
retu... |
def create_sqlite_connection_provider(db_uri):
uri = urlparse.urlparse(db_uri)
if (uri.scheme != 'sqlite'):
raise ValueError(('Scheme is not sqlite: ' + db_uri))
if uri.netloc:
raise ValueError(('Can not connect to SQLite over network: ' + db_uri))
if (uri.path == ':memory:'):
ra... |
def linear(input_, output_size, scope_name='linear'):
with tf.variable_scope(scope_name):
input_ = tf.reshape(input_, [(- 1), np.prod(input_.get_shape().as_list()[1:])])
output = tf.layers.dense(input_, output_size)
return output |
class FlaxAutoModelForSpeechSeq2Seq(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter< ns3::PbbTlv > > const &', 'o')])
return |
class ResNetPoolingHead(nn.Module):
def __init__(self, pool_size):
super(ResNetPoolingHead, self).__init__()
self.avg_pool = nn.AvgPool2d(pool_size, stride=1)
def forward(self, input):
x = self.avg_pool(input)
x = x.view(x.shape[0], (- 1))
return x |
def hook_avgpool3d(m, x, y):
k = _triple(m.kernel_size)
k = torch.prod(torch.Tensor(k)).item()
flops_per_ele = k
flops = (flops_per_ele * y.numel())
return int(flops) |
def check_load_config(config_class, config_file):
try:
draccus.parse(config_class, config_file, args=[])
except Exception as e:
raise Exception(f'failed to parse {config_file}') from e |
def setup(dirname=None, format_strs=['stdout', 'tensorboard', 'csv'], action=None):
if (dirname is None):
dirname = os.getenv('SISL_LOGDIR')
if (dirname is None):
dirname = osp.join(tempfile.gettempdir(), datetime.datetime.now().strftime('sisl-%Y-%m-%d-%H-%M-%S-%f'))
if (os.path.isdir(dirnam... |
class OrthogonalMatrixGroup_generic(NamedMatrixGroup_generic):
_method
def invariant_bilinear_form(self):
if (self._invariant_form is not None):
return self._invariant_form
from sage.matrix.constructor import identity_matrix
m = identity_matrix(self.base_ring(), self.degree()... |
class SuperCrystals(Category_singleton):
def super_categories(self):
return [Crystals()]
class ParentMethods():
def tensor(self, *crystals, **options):
cartan_type = self.cartan_type()
if any(((c.cartan_type() != cartan_type) for c in crystals)):
raise Val... |
_model
def regnety_008(pretrained=False, **kwargs):
return _regnet('regnety_008', pretrained, **kwargs) |
def plot_results(results, cols, pdffile, num_seen=0, num_anoms=0, plot_sd=False, ylabel=None, legend_loc='lower right', legend_datasets=None, axis_fontsize=20, legend_size=14):
dataset = results[0][0]
dp = DataPlotter(pdfpath=pdffile, rows=1, cols=1)
pl = dp.get_next_plot()
plt.xlim([0, num_seen])
i... |
class OsaBlock(nn.Module):
def __init__(self, in_chs, mid_chs, out_chs, layer_per_block, residual=False, depthwise=False, attn='', norm_layer=BatchNormAct2d):
super(OsaBlock, self).__init__()
self.residual = residual
self.depthwise = depthwise
next_in_chs = in_chs
if (self.de... |
_task_model('contact_prediction', 'onehot')
class ProteinOneHotForContactPrediction(ProteinOneHotAbstractModel):
def __init__(self, config):
super().__init__(config)
self.onehot = ProteinOneHotModel(config)
self.predict = PairwiseContactPredictionHead(config.hidden_size, ignore_index=(- 1))
... |
class _validation_args():
camera_preset: str
coverage: str = field(default='uniform', choices=['exhaustive', 'uniform'])
repeat_cameras: int = 1
every_n_steps: int = 2500
rays_batch_size: int = 8192 |
class PeakSignalToNoiseRatioMetric(Metric):
def __init__(self):
self._metric = None
self._device = get_torch_device()
def __repr__(self):
return 'PeakSignalToNoiseRatioMetric()'
def evaluate_generation(self, adapter_spec: AdapterSpec, request_state: RequestState, metric_service: Metr... |
def R2():
def hermite(n, y):
if (n == 1):
return (2 * y)
if (n == 0):
return 1
return expand((((2 * y) * hermite((n - 1), y)) - ((2 * (n - 1)) * hermite((n - 2), y))))
t1 = clock()
hermite(15, var('y'))
t2 = clock()
return (t2 - t1) |
class Retrain_Autodeeplab(nn.Module):
def __init__(self, args, input_channels=3):
super(Retrain_Autodeeplab, self).__init__()
filter_param_dict = {0: 1, 1: 2, 2: 4, 3: 8}
BatchNorm2d = (ABN if args.use_ABN else NaiveBN)
if (((not args.dist) and args.use_ABN) or (args.dist and args.us... |
def test_ignored_param_warning(line_graph):
walker = UniformRandomWalk(line_graph, n=2, length=3)
with pytest.raises(ValueError, match="cannot specify both 'walker' and 'length'"):
UnsupervisedSampler(line_graph, walker=walker, length=5)
with pytest.raises(ValueError, match="cannot specify both 'wal... |
class Pose2_SE2(Pose2):
def from_tangent(cls, v: T.Sequence[T.Scalar], epsilon: T.Scalar=sf.epsilon()) -> Pose2_SE2:
theta = v[0]
R = Rot2.from_tangent([theta], epsilon=epsilon)
a = ((R.z.imag + (epsilon * sf.sign_no_zero(R.z.imag))) / (theta + (epsilon * sf.sign_no_zero(theta))))
b ... |
def ccs_on_same_gpu_has_path_via_missing_nodes(cur_set, graph, id_to_node_worked_on, prev_topo_sort_id, topo_sort_id, unbroken_stage):
missing_topo_sort_ids = list(range((prev_topo_sort_id + 1), topo_sort_id))
is_ok = True
for missing_topo_sort_id in missing_topo_sort_ids:
if (missing_topo_sort_id n... |
def register_Ns3PhyRxStatsCalculator_methods(root_module, cls):
cls.add_constructor([param('ns3::PhyRxStatsCalculator const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DlPhyReception', 'void', [param('ns3::PhyReceptionStatParameters', 'params')])
cls.add_method('DlPhyReceptionCallback', 'void'... |
def online_learning_self_train(supervision, agent, init_train_data, online_data_loader, train_table, val_data, val_table, test_data, test_table, update_iter, model_save_path, record_save_path, model_renew_fn, max_seq_length=222, num_target_layers=2, detail=False, st_pos=0, end_pos=(- 1), cnt_tot=1, path_db=None, batch_... |
class AttributeObserver(metaclass=ABCMeta):
def __init__(self):
super().__init__()
def update(self, att_val, class_val, weight):
raise NotImplementedError
def probability_of_attribute_value_given_class(self, att_val, class_val):
raise NotImplementedError
def get_best_evaluated_sp... |
class Func_legendre_Q(BuiltinFunction):
def __init__(self):
BuiltinFunction.__init__(self, 'legendre_Q', nargs=2, latex_name='Q', conversions={'maxima': 'legendre_q', 'mathematica': 'LegendreQ', 'maple': 'LegendreQ'})
def _eval_(self, n, x, *args, **kwds):
ret = self._eval_special_values_(n, x)
... |
class ScriptMeta(type):
def __init__(cls, name, bases, attrs):
cls._methods: Dict[(str, Any)] = {}
cls._constants_set = set(getattr(cls, '__constants__', ()))
for base in reversed(bases):
for (k, v) in getattr(base, '_methods', {}).items():
cls._methods[k] = v
... |
def main():
parser = argparse.ArgumentParser(description='Run the Dawid-Skene, Fast Dawid-Skene, the Hybrid, or the Majority Voting Algorithm')
parser.add_argument('--dataset', type=str, required=True, help='Name of the dataset to use')
parser.add_argument('--k', default=0, type=int, required=False, help='N... |
def construct_scheduler(optimizer, cfg: OmegaConf):
scheduler_type = cfg.train.scheduler
decay_factor = cfg.train.scheduler_params.decay_factor
decay_steps = cfg.train.scheduler_params.decay_steps
patience = cfg.train.scheduler_params.patience
warmup_epochs = cfg.train.scheduler_params.warmup_epochs... |
.parametrize('val,true_dist,false_dist', [(True, 0.0, 1.0), (object(), 0.0, inf), (ExecutionTracer(), 0.0, inf), (False, 1.0, 0), ([], 1.0, 0), (set(), 1.0, 0), ({}, 1.0, 0), ((), 1.0, 0), ('', 1.0, 0), (b'', 1.0, 0), (0, 1.0, 0), (['something'], 0.0, 1.0), ({'something'}, 0.0, 1.0), ({'a': 'something'}, 0.0, 1.0), (('... |
class BJJmat(SpectralMatrix):
def assemble(self, method):
(test, trial) = (self.testfunction, self.trialfunction)
assert isinstance(test[0], J)
assert isinstance(trial[0], J)
return {0: get_norm_sq(test[0], trial[0], method)} |
def _print_top_wer_spks(spks_by_wer, file=sys.stdout):
print(('=' * 80), file=file)
print('SPEAKERS WITH HIGHEST WER', file=file)
for dets in spks_by_wer:
print('{speaker} %WER {WER:.2f}'.format(**dets), file=file) |
def get_noise_pred_single(latents, t, context, unet):
noise_pred = unet(latents, t, encoder_hidden_states=context)['sample']
return noise_pred |
def invert(A0, A1, tmp, i0, i1):
return If((Select(A0, i0) > Select(A0, (i0 + 1))), And((tmp == Select(A0, i0)), (A1 == Store(A0, i0, Select(A0, (i0 + 1)))), (A1 == Store(A0, (i0 + 1), tmp))), (A1 == A0)) |
def main(arg):
global best_acc1
data_info = datainfo(logger, arg)
model = create_model(data_info['img_size'], data_info['n_classes'], arg)
n_parameters = sum((p.numel() for p in model.parameters() if p.requires_grad))
print(f'Creating model: {arg.model}')
print(f"Number of params: {format(n_para... |
def get_opparam_converter_with_context(context, opparam_converter: dict):
def wrap(fn):
def outer(cmd):
return fn(context, cmd)
return outer
new_convert = {}
for (k, v) in opparam_converter.items():
new_convert[k] = wrap(v)
return new_convert |
class ChairsData(Data):
URL = '
TRAIN_VAL_URL = '
dirs = ['flying_chairs']
def __init__(self, data_dir, stat_log_dir=None, development=True, fast_dir=None):
super().__init__(data_dir, stat_log_dir, development=development, fast_dir=fast_dir)
def _fetch_if_missing(self):
local_path = ... |
def resnet_fn(input_layer, block_fn, layers, normalization_op_params=None):
norm_activation = norm_activation_builder(normalization_op_params, activation='relu')
inputs = conv2d_fixed_padding(inputs=input_layer, filters=64, kernel_size=7, strides=2)
inputs = tf.identity(inputs, 'initial_conv')
inputs = ... |
def multi_ref(refs, hypos):
(_ref, _hypo) = ([], [])
ref_cnt = 0
assert (len(refs) == len(hypos))
for (rs, hs) in zip(refs, hypos):
a = set()
for h in hs:
s = [sentence_bleu(h, r) for r in rs]
j = np.argmax(s)
_ref.append(rs[j])
_hypo.appen... |
def get_representative_dataset(n_iter):
def representative_dataset():
ds_iter = iter(train_loader)
for _ in range(n_iter):
(yield [next(ds_iter)[0]])
return representative_dataset |
def lr_calc(epoch):
if ((epoch < args.lr_drop_epoch) or (epoch >= (args.lr_drop_epoch + args.lr_rtrn_epochs))):
return (args.lr_decay ** epoch)
else:
return ((args.lr_decay ** epoch) - ((args.lr_decay ** epoch) * (1 - ((epoch - args.lr_drop_epoch) / args.lr_rtrn_epochs)))) |
def test_limit_memory():
limit_memory(2)
expected = (2 * (1024 ** 3))
(soft, hard) = resource.getrlimit(resource.RLIMIT_AS)
assert (expected == soft)
assert (expected == hard) |
def register_Ns3QuicEchoClientHelper_methods(root_module, cls):
cls.add_constructor([param('ns3::QuicEchoClientHelper const &', 'arg0')])
cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port')])
cls.add_constructor([param('ns3::Address', 'addr')])
cls.add_method('Install', 'ns3::App... |
def display_section_name(title: str, separator: str='=', **kwargs: Any) -> None:
message = f' {title} '.center(get_terminal_width(), separator)
kwargs.setdefault('bold', True)
click.secho(message, **kwargs) |
def eval_datasets_flist_reader(flist):
imlist = []
with open(flist, 'r') as rf:
for line in rf.readlines():
(q, r) = line.strip().split(',')
if (q == 'query_id'):
continue
imlist.append((q, r))
return imlist |
class BR(nn.Module):
def __init__(self, nOut, act_name='prelu'):
super().__init__()
self.br = nn.Sequential(nn.BatchNorm2d(nOut), activation_fn(nOut, name=act_name))
def forward(self, x):
return self.br(x) |
_module()
class GlobalContextHead(nn.Module):
def __init__(self, num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_weight=1.0, conv_cfg=None, norm_cfg=None, conv_to_res=False):
super(GlobalContextHead, self).__init__()
self.num_convs = num_convs
self.in_channels = in_... |
def GetClustCf(tspec, *args):
if (type(tspec) == PUNGraph):
return GetClustCf_PUNGraph(tspec, *args)
if (type(tspec) == PUndirNet):
return GetClustCf_PUndirNet(tspec, *args)
if (type(tspec) == PDirNet):
return GetClustCf_PDirNet(tspec, *args)
if (type(tspec) == PNGraph):
... |
def run_test(args):
if (args.config_path is not None):
path = '--config_path'
path_name = args.config_path
else:
path = '--ckpt_path'
path_name = args.ckpt_path
subprocess.run(['python', 'test.py', '--dataset', 'custom', path, path_name, '--phase', 'test', '--together', 'True... |
def test_views_between_maps_work():
def test_inline_reshape_views_work(A: dace.float64[(3, 3)], B: dace.float64[9]):
result = dace.define_local([9], dace.float64)
result[:] = nested_add2(A, B)
result_reshaped = reshape_node(result)
return np.transpose(result_reshaped)
sdfg = test... |
class RegionpropsTableAll():
param_names = ['cache']
params = (False, True)
def setup(self, cache):
try:
from skimage.measure import regionprops_table
except ImportError:
raise NotImplementedError('regionprops_table unavailable')
(self.label_image, self.intens... |
def train(train_loader, model, criterion, optimizer, scheduler, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
model.train()
end = time.time()
for (i, (input, target)) in enumerate(train_loader):
... |
def load_ckpt_base_path_meta_data(search_space):
base_data_directory = '/home/soroush/data/s3'
import os
if ((search_space.get('rl_variant.ckpt_base_path', None) is not None) and (len(search_space['rl_variant.ckpt_base_path']) > 0)):
search_space['rl_variant.ckpt'] = []
for base_path in sear... |
.parametrize('n', [0, 1, 2, 3.2])
.parametrize('alpha', [0.0, 1, np.nan])
.parametrize('x', [1e-06, 2, np.nan])
def test_gegenbauer_nan(n, alpha, x):
nan_gegenbauer = np.isnan(_ufuncs.eval_gegenbauer(n, alpha, x))
nan_arg = np.any(np.isnan([n, alpha, x]))
assert (nan_gegenbauer == nan_arg) |
class _Ops(types.ModuleType):
__file__ = os.path.join(os.path.dirname(__file__), '_ops.py')
def __init__(self):
super(_Ops, self).__init__('torch.ops')
self.loaded_libraries = set()
def __getattr__(self, name):
namespace = _OpNamespace(name)
setattr(self, name, namespace)
... |
def load_class_map(map_or_filename, root=''):
if isinstance(map_or_filename, dict):
assert dict, 'class_map dict must be non-empty'
return map_or_filename
class_map_path = map_or_filename
if (not os.path.exists(class_map_path)):
class_map_path = os.path.join(root, class_map_path)
... |
_cache(maxsize=1000)
def measure_multiple_with_cache_ket(state: Tuple[complex], num_states: int, length_diff: int) -> Tuple[(List[array], List[float])]:
state = array(state)
basis_count = (2 ** num_states)
projectors = ([None] * basis_count)
probabilities = ([0] * basis_count)
for i in range(basis_c... |
.parametrize('seed', [313])
def test_all_gather(seed, comm_nccl_opts):
if (comm_nccl_opts is None):
pytest.skip('Communicator test is disabled. You can turn it on by an option `--test-communicator`.')
if (len(comm_nccl_opts.devices) < 2):
pytest.skip('Communicator test is disabled. Use more than... |
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(nn.Linear(channel, (channel // reduction), bias=False), nn.ReLU(inplace=True), nn.Linear((channel // reduction), channel, bias=... |
def example():
task = MyOwnTask()
env = CausalWorld(task=task, enable_visualization=True)
env.reset()
for _ in range(2000):
for _ in range(10):
(obs, reward, done, info) = env.step(env.action_space.sample())
random_intervention_dict = env.do_single_random_intervention()
e... |
def register_Ns3EpcMmeApplication_methods(root_module, cls):
cls.add_constructor([param('ns3::EpcMmeApplication const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AddBearer', 'uint8_t', [param('uint64_t', 'imsi'), param('ns3::Ptr< ns3::EpcTft >', 'tft'), param('ns3::EpsBearer', 'bearer')])
cls.... |
class GraphHandler(object):
def __init__(self, model):
self.model = model
self.saver = tf.train.Saver(max_to_keep=3)
self.writer = None
def initialize(self, sess):
sess.run(tf.global_variables_initializer())
if (cfg.load_model or (cfg.mode != 'train')):
self.r... |
def _create_table(conn, table):
if (conn.driver == 'mysql'):
stmt = 'CREATE TABLE IF NOT EXISTS {0} (id INT, block TEXT, PRIMARY KEY (id))'.format(table)
elif (conn.driver == 'hive'):
stmt = 'CREATE TABLE IF NOT EXISTS {0} (id INT, block STRING) ROW FORMAT DELIMITED FIELDS TERM... |
class TestNoop():
def test_noop(self):
env = Noop(DummyDiscretePixelEnv(), noop_max=3)
for _ in range(1000):
env.reset()
assert (1 <= env.env.step_called <= 3)
env = Noop(DummyDiscretePixelEnv(), noop_max=10)
for _ in range(1000):
obs = env.reset()... |
def _rel_pos_enc_shift(x: Tensor, axis: Dim, pos_emb_spatial_dim: Dim, hist_dim: Dim) -> Tensor:
batch_dims = x.remaining_dims((axis, pos_emb_spatial_dim))
(x_padded, (pos_emb_spatial_dim_,)) = rf.pad(x, axes=[pos_emb_spatial_dim], padding=[(1, 0)], value=0.0)
x_padded = rf.reshape(x_padded, (axis, pos_emb_... |
class RPNLossComputation(object):
def __init__(self, proposal_matcher, fg_bg_sampler, box_coder):
self.proposal_matcher = proposal_matcher
self.fg_bg_sampler = fg_bg_sampler
self.box_coder = box_coder
def match_targets_to_anchors(self, anchor, target):
match_quality_matrix = boxl... |
_pydub_effect
def strip_silence(seg, silence_len=1000, silence_thresh=(- 16), padding=100):
if (padding > silence_len):
raise InvalidDuration('padding cannot be longer than silence_len')
chunks = split_on_silence(seg, silence_len, silence_thresh, padding)
crossfade = (padding / 2)
if (not len(ch... |
class KipfGCN(torch.nn.Module):
def __init__(self, data, num_class, params):
super(KipfGCN, self).__init__()
self.p = params
self.data = data
self.conv1 = GCNConv(self.data.num_features, self.p.gcn_dim, cached=True)
self.conv2 = GCNConv(self.p.gcn_dim, num_class, cached=True)... |
def main_worker(gpu, ngpus_per_node, args, checkpoint_folder):
args.gpu = gpu
if (args.multiprocessing_distributed and (args.gpu != 0)):
def print_pass(*args):
pass
builtins.print = print_pass
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))
... |
def divide_variable(self, c, i, in_place=False):
if (not in_place):
Q = self.parent()(self.base_ring(), self.dim(), self.coefficients())
Q.divide_variable(c, i, in_place=True)
return Q
tmp = (self[(i, i)] / (c * c))
self[(i, i)] = tmp
for k in range(self.dim()):
if (k != ... |
def DropoutIfTraining(model, blob_in, blob_out, dropout_rate):
if (model.train and (dropout_rate > 0)):
blob_out = model.Dropout(blob_in, blob_out, ratio=dropout_rate, is_test=False)
return blob_out
else:
return blob_in |
def leaky_relu(g, input, negative_slope, inplace=False):
return g.op('LeakyRelu', input, alpha_f=_scalar(negative_slope)) |
class GemmUniversalLauncher():
def __init__(self, operation: 'GemmOperationUniversal', seed: int=2080, interleaved=False, verification=True, profiling=False, warmup_iterations=500, iterations=500, **kwargs) -> None:
self.reduction_operation: ReductionOperation = ReductionOperation(shape=cutlass.MatrixCoord(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.