code stringlengths 101 5.91M |
|---|
def standardize_otpmizers_params(optm_dict):
msg = "'optm_dict' must be of type dict. found {}.".format(type(optm_dict))
assert isinstance(optm_dict, dict), msg
new_optm_dict = copy.deepcopy(optm_dict)
loldkeys = list(new_optm_dict.keys())
for k in loldkeys:
if k.startswith('optn'):
... |
class AsyncNextNode(AtomicExprNode):
type = py_object_type
is_temp = 1
def __init__(self, iterator):
AtomicExprNode.__init__(self, iterator.pos)
self.iterator = iterator
def infer_type(self, env):
return py_object_type
def analyse_types(self, env):
return self
def... |
def resnet101(pretrained=True, **kwargs):
model = ResNet3X3(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
print(' pretrained ')
model.load_state_dict(torch.load('./pretrained/resnet101-imagenet.pth', map_location='cpu'))
return model |
def eval_ppl_epoch(args, eval_data, eval_examples, model, tokenizer):
eval_sampler = SequentialSampler(eval_data)
eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size, num_workers=4, pin_memory=True)
logger.info((' ' + '***** Running ppl evaluation *****'))
logg... |
def make_hdf5(model_config, train_config, mode):
if ('hdf5' in model_config['dataset_name']):
raise ValueError('Reading from an HDF5 file which you will probably be about to overwrite! Override this error only if you know what youre doing!')
file_name = '{dataset_name}_{size}_{mode}.hdf5'.format(dataset... |
def use_transformers(sentences=('', '')):
from transformers import BertTokenizer, BertModel
import torch
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0]
input_mask_expanded = attention_mask.unsqueeze((- 1)).expand(token_embeddings.size()).float()
re... |
def test_siblings_policy_negative_examples_3(digraph, features_1d, labels):
policy = SiblingsPolicy(digraph, features_1d, labels)
ground_truth = [False, False, False, True, False, False, True, True]
result = policy.negative_examples('2.1')
assert_array_equal(ground_truth, result) |
class CompaqVisualFCompiler(FCompiler):
compiler_type = 'compaqv'
description = 'DIGITAL or Compaq Visual Fortran Compiler'
version_pattern = '(DIGITAL|Compaq) Visual Fortran Optimizing Compiler Version (?P<version>[^\\s]*).*'
compile_switch = '/compile_only'
object_switch = '/object:'
library_s... |
class NaiveSyncBatchNorm(nn.BatchNorm2d):
def forward(self, input):
if ((get_world_size() == 1) or (not self.training)):
return super().forward(input)
assert (input.shape[0] > 0), 'SyncBatchNorm does not support empty inputs'
C = input.shape[1]
mean = torch.mean(input, di... |
def multi_gpu_test(model, data_loader, tmpdir=None):
model.eval()
results = []
dataset = data_loader.dataset
(rank, world_size) = get_dist_info()
if (rank == 0):
prog_bar = mmcv.ProgressBar(len(dataset))
for (i, data) in enumerate(data_loader):
with torch.no_grad():
r... |
class ModulatedDeformConvFunction(Function):
def forward(ctx, input, offset, mask, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1):
ctx.stride = stride
ctx.padding = padding
ctx.dilation = dilation
ctx.groups = groups
ctx.deformable_groups =... |
def get_language_modeling_adapter_spec() -> AdapterSpec:
return AdapterSpec(method=ADAPT_LANGUAGE_MODELING, instructions='', input_prefix='', input_suffix='', output_prefix='', output_suffix='', max_train_instances=0, num_outputs=1, max_tokens=0, temperature=0.0) |
def main(start_epoch, epochs):
assert torch.cuda.is_available(), NotImplementedError('No cuda available ')
if (not osp.exists('data/')):
os.mkdir('data/')
if (not osp.exists('log/')):
os.mkdir('log/')
args = obtain_evaluate_args()
torch.backends.cudnn.benchmark = True
model_fname... |
class SubData(NamedTuple):
data: Data
batch_size: int
n_id: Tensor
offset: Tensor
count: Tensor
def to(self, *args, **kwargs):
return SubData(self.data.to(*args, **kwargs), self.batch_size, self.n_id, self.offset, self.count) |
def get_bar_order(plot_params):
if plot_params['detailed']:
if plot_params['show_score_diffs']:
bar_order = ['neg_s', 'pos_s', 'neg_s_neg_p', 'neg_s_pos_p', 'pos_s_neg_p', 'pos_s_pos_p']
else:
bar_order = ['neg_s_neg_p', 'neg_s_pos_p', 'pos_s_neg_p', 'pos_s_pos_p']
elif (... |
def _wrapper(args=None):
sys.stderr.write("WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.\nPlease see for advice on fixing the underlying issue.\nTo avoid this problem you can invoke Python with '-m pip' instead of running pip directly.\n")
return main(args) |
class TestSave(TestCase):
def roundtrip(self, x, scaling=1):
with NamedTemporaryFile(suffix='.png') as f:
fname = f.name
imsave(fname, x)
y = imread(fname)
assert_array_almost_equal((x * scaling).astype(np.int32), y)
def test_imsave_roundtrip(self):
dtype = np... |
def from_representation(array: ndarray, kind: str, **kwargs) -> Music:
if (kind.lower() in ('pitch', 'pitch-based')):
return from_pitch_representation(array, **kwargs)
if (kind.lower() in ('pianoroll', 'piano-roll', 'piano roll')):
return from_pianoroll_representation(array, **kwargs)
if (ki... |
def test_random_noise():
results = {}
results['lq'] = np.ones((8, 8, 3)).astype(np.float32)
model = RandomNoise(params=dict(noise_type=['gaussian'], noise_prob=[1], gaussian_sigma=[0, 50], gaussian_gray_noise_prob=1), keys=['lq'])
results = model(results)
assert (results['lq'].shape == (8, 8, 3))
... |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('inplace', [False, True])
def test_div2_double_backward(inplace, seed, ctx, func_name):
from nbla_test_utils import backward_function_tester
rng = np.random.RandomState(seed)
inputs = [rng.randn(2, 3).astype(np.float32), (rng.rand... |
def qspline1d_eval(cj, newx, dx=1.0, x0=0):
newx = ((asarray(newx) - x0) / dx)
res = zeros_like(newx)
if (res.size == 0):
return res
N = len(cj)
cond1 = (newx < 0)
cond2 = (newx > (N - 1))
cond3 = (~ (cond1 | cond2))
res[cond1] = qspline1d_eval(cj, (- newx[cond1]))
res[cond2]... |
def format_code_example(code: str, max_len: int, in_docstring: bool=False):
code_lines = code.split('\n')
idx = 0
while ((idx < len(code_lines)) and is_empty_line(code_lines[idx])):
idx += 1
if (idx >= len(code_lines)):
return ('', '')
indent = find_indent(code_lines[idx])
code_l... |
def parse_filenames(dirname, pattern='*conll'):
for (path, subdirs, files) in os.walk(dirname):
for name in files:
if fnmatch(name, pattern):
(yield os.path.join(path, name)) |
_utils.test()
def test_atomic_xor_expr_evaled():
c = ti.field(ti.i32)
step = 42
ti.root.place(c)
def func():
c[None] = 1023
for i in range(10):
ti.atomic_xor(c[None], (2 ** i))
func()
assert (c[None] == 0) |
def _format(val: Any, output_format: str='standard', errors: str='coarse') -> Any:
val = str(val)
result: Any = []
if (val in NULL_VALUES):
return [np.nan]
if (not validate_nl_btw(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val}')
error_re... |
class WeightNormConv2d(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, init_scale=1.0, polyak_decay=0.9995):
super(WeightNormConv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups)
self.V = se... |
def construct_transduction(example, para_generator, hallu_generator):
para = para_generator.generate(input_text=example['text'])
if (para is None):
return None
hallu = hallu_generator.hallucinate(input_text=para)
if (hallu is None):
return None
return {'text': example['text'], 'para'... |
def test_water_filling():
policy = max_min_fairness_water_filling.MaxMinFairnessWaterFillingPolicyWithPerf(priority_reweighting_policies=None)
worker_types = ['k80', 'p100', 'v100']
cluster_spec = {worker_type: 64 for worker_type in worker_types}
num_jobs = 300
print(('Total number of jobs: %d' % nu... |
def _unique_impl(input: Tensor, sorted: bool=True, return_inverse: bool=False, return_counts: bool=False, dim: Optional[int]=None) -> _unique_impl_out:
if (not torch.jit.is_scripting()):
if ((type(input) is not Tensor) and has_torch_function((input,))):
return handle_torch_function(unique, (inpu... |
def test_RegularArray_NumpyArray():
v2a = ak.contents.regulararray.RegularArray(ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5])), 3)
def f(out, obj):
out[0] = len(obj)
out[1] = obj[0][0]
out[2] = obj[0][1]
out[3] = obj[1][0]
out[4] = obj[1][1]
... |
def vis_with_legend(indir_list, raw_rgb_dir, outdir, raw_gray_dir=None, gt_dir=None, ext='png'):
n_imgs = (1 + len(indir_list))
if raw_gray_dir:
n_imgs += 1
if gt_dir:
n_imgs += 1
mkdir_if_not_exist(outdir)
n_row = 2
n_col = int(round((float(n_imgs) / n_row)))
img_fn_list = o... |
class EigenCAM(BaseCAM):
def __init__(self, model, target_layers, use_cuda=False, reshape_transform=None):
super(EigenCAM, self).__init__(model, target_layers, use_cuda, reshape_transform)
def get_cam_image(self, input_tensor, target_layer, target_category, activations, grads, eigen_smooth):
ret... |
class Inception1d(nn.Module):
def __init__(self, num_classes=2, input_channels=8, kernel_size=40, depth=6, bottleneck_size=32, nb_filters=32, use_residual=True, lin_ftrs_head=None, ps_head=0.5, bn_final_head=False, bn_head=True, act_head='relu', concat_pooling=True):
super().__init__()
assert (kerne... |
def accimage_loader(path):
try:
import accimage
return accimage.Image(path)
except IOError:
return pil_loader(path) |
def gen_web_cov_report(cov_paths, cargs):
genhtml_opts = ''
if cargs.enable_branch_coverage:
genhtml_opts += ' --branch-coverage'
run_cmd((((((cargs.genhtml_path + genhtml_opts) + ' --output-directory ') + cov_paths['web_dir']) + ' ') + cov_paths['lcov_info_final']), cov_paths['log_file'], cargs, LO... |
def get_performance_per_query(per_query_baseline, measure):
diff_per_query = {}
for (query, measurements) in per_query_baseline.items():
diff_per_query.update({query: measurements.get(measure)})
return diff_per_query |
def trieste_deep_gaussian_process(data: Dataset, search_space: SearchSpace, num_layers: int, num_inducing_points: int, learning_rate: float, batch_size: int, epochs: int, fix_noise: bool=False) -> Tuple[(DeepGaussianProcess, Dict[(str, Any)])]:
dgp = build_vanilla_deep_gp(data, search_space, num_layers, num_inducin... |
class PPROutputData(genpy.Message):
_md5sum = '732c0e3ca36f241464f8c445e78a0d0a'
_type = 'quadrotor_msgs/PPROutputData'
_has_header = True
_full_text = "Header header\nuint16 quad_time\nfloat64 des_thrust\nfloat64 des_roll\nfloat64 des_pitch\nfloat64 des_yaw\nfloat64 est_roll\nfloat64 est_pitch\nfloat64... |
def parse_args():
parser = argparse.ArgumentParser(description='Get the FLOPs of a segmentor')
parser.add_argument('config', help='train config file path')
parser.add_argument('--shape', type=int, nargs='+', default=[2048, 1024], help='input image size')
args = parser.parse_args()
return args |
def ground_truth(r):
y = np.empty_like(r)
alpha = (- r[0])
beta = 1.0
y[0] = (- r[0])
for k in range(1, r.shape[0]):
beta *= (1.0 - (alpha * alpha))
alpha = ((- (r[k] + np.dot(np.flip(r[:k]), y[:k]))) / beta)
y[:k] += (alpha * np.flip(y[:k]))
y[k] = alpha
return y |
def resize(image, size, max_size=None):
def get_size_with_aspect_ratio(image_size, size, max_size=None):
(w, h) = image_size
if (max_size is not None):
min_original_size = float(min((w, h)))
max_original_size = float(max((w, h)))
if (((max_original_size / min_orig... |
class TestSequenceGenerator(TestSequenceGeneratorBase):
def setUp(self):
(self.tgt_dict, self.w1, self.w2, src_tokens, src_lengths, self.model) = test_utils.sequence_generator_setup()
self.sample = {'net_input': {'src_tokens': src_tokens, 'src_lengths': src_lengths}}
def test_with_normalization(... |
('/download')
def download():
file = request.args['file']
filepath = '/'.join(file.split('_'))
return send_file(filepath, as_attachment=True) |
def plot_confusion_matrix(cmtx, num_classes, class_names=None, figsize=None):
if ((class_names is None) or (type(class_names) != list)):
class_names = [str(i) for i in range(num_classes)]
figure = plt.figure(figsize=figsize)
plt.imshow(cmtx, interpolation='nearest', cmap=plt.cm.Blues)
plt.title(... |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('epsilon', [0.001, 1])
def test_epsilon_insensitive_loss_forward_backward(seed, ctx, func_name, epsilon):
from nbla_test_utils import function_tester
rng = np.random.RandomState(seed)
inputs = [(rng.randn(2, 3, 4).astype(np.float3... |
def _get_split_ranges(nnp, args, supported_set):
def get_ranges_from_param(split_spec):
ranges = []
for srange in split_spec.split(','):
srange_s = srange.split('-')
if (len(srange_s) == 2):
if (srange_s[0] == ''):
pos_start = 0
... |
def test_container_add():
from sfepy.base.base import Struct, Container
a = Struct(name='a')
b = Struct(name='b')
c1 = Container()
c1 = (c1 + c1)
assert_((c1.names == []))
c1 += Container([a, b])
assert_((c1.names == ['a', 'b']))
c2 = (c1 + c1)
assert_((c2.names == (2 * ['a', 'b'... |
def check_psenac(lamada, w, k):
try:
if ((not isinstance(lamada, int)) or (lamada <= 0)):
raise ValueError('Error, parameter lamada must be an int type and larger than and equal to 0.')
elif ((w > 1) or (w < 0)):
raise ValueError('Error, parameter w must be ranged from 0 to 1... |
def copy_dory_sig():
testdata = relative_file('data/dory-subset.fq.sig')
shutil.copyfile(testdata, 'dory-subset.fq.sig') |
class TestBamfilter(unittest.TestCase):
def test_get_ref_lengths(self):
b = bamfilter.BamFilter(os.path.join(data_dir, 'bamfilter_test_get_ref_lengths.bam'), 'out')
expected = {'ref1': 41, 'ref2': 42, 'ref3': 43}
self.assertEqual(expected, b._get_ref_lengths())
def test_get_contigs_to_us... |
class Unet(nn.Module):
def __init__(self, in_ch, out_ch, nf=3, cond_nf=64, norm_layer=nn.InstanceNorm2d):
super(Unet, self).__init__()
self.downscale = 16
self.in_ch = in_ch
self.out_ch = out_ch
self.nf = nf
self.cond_nf = cond_nf
self.merge_cond_mult = nn.Seq... |
class ReluReplacementTest(SingleLayerReplacementTest):
def __init__(self, unit_test):
super().__init__(unit_test)
def get_debug_config(self):
return mct.core.DebugConfig(network_editor=[EditRule(filter=NodeTypeFilter(torch.nn.ReLU), action=ReplaceLayer(Identity, get_identity_params_from_relu))])... |
class FlaxRobertaPreLayerNormForMaskedLM(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class _TimeZone(datetime.tzinfo):
def __init__(self, offset):
self._offset = offset
def utcoffset(self, dt):
return self._offset
def dst(self, dt):
return None
def tzname(self, dt):
m = (self._offset.total_seconds() // 60)
if (m < 0):
res = '-'
... |
class NumpyType(LayoutBuilderType):
def __init__(self, dtype, parameters):
super().__init__(name=f'ak.lb.Numpy({dtype!r}, parameters={parameters!r})')
self._dtype = dtype
self._init(parameters)
def dtype(self):
return self._dtype
def data(self):
return ak.numba.Growab... |
def test_submodule_trainable_variables():
(trackable_layer, variables, modules, module_variables) = setup_layer_modules_variables()
trainable_attributes = [v for v in (variables + module_variables) if v.trainable]
assert (trackable_layer.trainable_variables == trainable_attributes) |
def get_config_from_folder_or_ckpt(folder: str, ckpt: Dict[(str, Any)]=None) -> Dict[(str, Any)]:
configs = glob.glob(os.path.join(folder, '*.yaml'))
if (len(configs) > 0):
assert (len(configs) <= 1), ('Multiple yaml files with the pretrained model. ' + "MMF doesn't know what to do.")
config_fil... |
_model_architecture('universal_transformer_lm', 'universal_transformer_lm_gpt2_medium')
def transformer_lm_gpt2_medium(args):
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1280)
args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 5120)
args.decoder_layers = getattr(args, 'decod... |
class ControlOutputs(object):
def __init__(self, graph):
if (not isinstance(graph, tf_ops.Graph)):
raise TypeError('Expected a tf.Graph, got: {}'.format(type(graph)))
self._control_outputs = {}
self._graph = graph
self._version = None
self._build()
def update(... |
def add_model_to_main_init(old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, frameworks: Optional[List[str]]=None, with_processing: bool=True):
with open((TRANSFORMERS_PATH / '__init__.py'), 'r', encoding='utf-8') as f:
content = f.read()
lines = content.split('\n')
idx = 0
n... |
def remove_bn_and_dropout(module):
for (child_name, child) in module.named_children():
child_type = str(type(child))
if (('BatchNorm' in child_type) or ('Dropout' in child_type)):
module.__setattr__(child_name, torch.nn.Sequential())
else:
remove_bn_and_dropout(child) |
class BaseDataset(data.Dataset):
def __init__(self):
super(BaseDataset, self).__init__()
def name(self):
return 'BaseDataset'
def initialize(self):
pass |
def compute_dual_line_graph(hypergraph, s=1, singleton_type='grey_out'):
dual_hgraph = hypergraph.dual()
dual_line_graph = convert_to_line_graph(dual_hgraph.incidence_dict, s, singleton_type)
return dual_line_graph |
def order_and_prune_files(file_paths, min_duration, max_duration):
print('Sorting manifests...')
duration_file_paths = [(path, float(subprocess.check_output([('soxi -D "%s"' % path.strip())], shell=True))) for path in file_paths]
if (min_duration and max_duration):
print(('Pruning manifests between ... |
class OrVerifier(Verifier):
def __init__(self, stmt, subverifiers):
self.subs = subverifiers
self.stmt = stmt
def process_precommitment(self, precommitment):
if (precommitment is None):
return
for (index, sub) in enumerate(self.subs):
sub.process_precommit... |
def get_action(a):
if isinstance(a, int):
return a
return (a.item() if (a.shape == [1]) else a) |
class Account():
api_key: str
description: str = ''
emails: List[str] = field(default_factory=list)
groups: List[str] = field(default_factory=list)
is_admin: bool = False
usages: Dict[(str, Dict[(str, Usage)])] = field(default_factory=dict) |
def load_cpnet_vocab(cpnet_vocab_path):
with open(cpnet_vocab_path, 'r', encoding='utf8') as fin:
cpnet_vocab = [l.strip() for l in fin]
cpnet_vocab = [c.replace('_', ' ') for c in cpnet_vocab]
return cpnet_vocab |
def hash_seq(ls):
v = 5381
for x in ls:
v = ((1000003 * v) + hash_obj(x))
v = (v & )
return v |
class Feature_Init():
def get_split_feature(self, split_tuple, parent_sentence, children_sentence_list, boxer_graph):
iLength = boxer_graph.calculate_iLength(parent_sentence, children_sentence_list)
split_pattern = boxer_graph.get_pattern_4_split_candidate(split_tuple)
split_feature = ((spli... |
class GlobalAttention(nn.Module):
def __init__(self, dim, attn_type='dot', include_rnn=True, dropout=0.0):
super(GlobalAttention, self).__init__()
self.dim = dim
self.attn_type = attn_type
self.include_rnn = include_rnn
self.drop = nn.Dropout(dropout)
assert (self.att... |
def get_b32_config():
config = get_b16_config()
config.patches.size = (32, 32)
return config |
def load_data_wikisql(args):
in_dir = args.data_dir
splits = ['train', 'dev', 'test']
schema_graphs = load_schema_graphs_wikisql(in_dir, splits=splits)
dataset = dict()
for split in splits:
dataset[split] = load_data_split_wikisql(in_dir, split, schema_graphs)
dataset['schema'] = schema_... |
.parametrize('dtype', [ti.f32, ti.f64])
def test_cast_default_fp(dtype):
ti.init(default_fp=dtype)
def func(x: int, y: int) -> float:
return (ti.cast(x, float) * float(y))
assert (func(23, 4) == pytest.approx((23.0 * 4.0))) |
class ADGEncoder():
def __init__(self, medium, **kwargs):
self.medium = medium
self.context = kwargs.get('context', None)
self.finish_sent = kwargs.get('finish_sent')
self.precision = kwargs.get('precision')
self.is_sort = kwargs.get('is_sort')
self.clean_up_output = ... |
def register_all_voc_pgt(root):
for (dataset_name, splits_per_dataset) in _PREDEFINED_SPLITS_VOC_PGT.items():
for (key, (image_root, json_file)) in splits_per_dataset.items():
register_coco_instances(key, _get_builtin_metadata(key), (os.path.join(root, json_file) if ('://' not in json_file) else... |
class AssertionViolation(InterpreterError):
_node: Node
_index: int
_reason: Callable[([Any], bool)]
_captures: Iterable[int]
def __init__(self, node: Node, index: int, reason: Callable[([Any], bool)], captures: Iterable[int]):
super().__init__()
self._node = node
self._index... |
class build(_build):
def run(self):
if (RELEASE_DIR is None):
self.execute(_configure_z3, (), msg='Configuring Z3')
self.execute(_build_z3, (), msg='Building Z3')
self.execute(_copy_bins, (), msg='Copying binaries')
_build.run(self) |
def two_stages_kwargs():
return {'first_level_models': [ALSWrap(rank=4), ItemKNN(num_neighbours=4), LightFMWrap(no_components=4)], 'train_splitter': TimeSplitter(time_threshold=0.1), 'use_first_level_models_feat': True, 'second_model_params': {'timeout': 30, 'general_params': {'use_algos': ['lgb']}}, 'num_negatives... |
def cast_tensor_type(inputs, src_type=None, dst_type=None):
assert (dst_type is not None)
if isinstance(inputs, torch.Tensor):
if isinstance(dst_type, torch.device):
if (hasattr(inputs, 'to') and hasattr(inputs, 'device') and ((inputs.device == src_type) or (src_type is None))):
... |
class TemplateNLG(NLG):
def __init__(self, nlg_template_path):
self.nlg_template = read_s3_json('botsim', nlg_template_path)
def generate(self, dialog_state, role):
sentences = []
sentences_slots = []
matched = False
assert ((role == 'agent') or (role == 'user'))
... |
class MyDataset(torch.utils.data.Dataset):
def __init__(self, input_ids, attention_mask, token_type_ids, title_id, hn_title_ids, bert_model):
self.bert_model = bert_model
self.input_ids = input_ids
self.attention_mask = attention_mask
if ('roberta' not in self.bert_model):
... |
def read_depth_png_tf(depth_dir):
depth_dir = depth_dir.numpy().decode('utf-8')
depth = read_depth_png(depth_dir)
return depth |
def test_metric(log, log_to_pred, model):
dataset = create_dataset(log)
model.fit(dataset)
pred_dataset = create_dataset(log.unionByName(log_to_pred))
p_pred_metr_from_init_conf = model.predict_pairs(pairs=log_to_pred.select('user_idx', 'item_idx'), dataset=pred_dataset)
model.similarity_metric = 'c... |
.overload_method(TupleType, '_length_get', inline='always')
def Tuple_length(builder):
if isinstance(builder, TupleType):
def getter(builder):
return len(builder._contents[0])
return getter |
class NoVisualization(object):
def __init__(self, seq_info):
self.frame_idx = seq_info['min_frame_idx']
self.last_idx = seq_info['max_frame_idx']
def set_image(self, image):
pass
def draw_groundtruth(self, track_ids, boxes):
pass
def draw_detections(self, detections):
... |
def walk_files(root, extension):
for (path, dirs, files) in os.walk(root):
for file in files:
if file.endswith(extension):
(yield os.path.join(path, file)) |
def get_arrays(notes, labels, n_tracks, seq_len):
data = {'time': np.zeros((seq_len,), int), 'pitch': np.zeros((seq_len,), int), 'duration': np.zeros((seq_len,), int), 'velocity': np.zeros((seq_len,), int), 'label': np.zeros((seq_len,), int), 'onset_hint': np.zeros((n_tracks,), int), 'pitch_hint': np.zeros((n_track... |
class NTU_Feeder(Dataset):
def __init__(self, phase, path, data_shape, connect_joint, debug, **kwargs):
(_, _, self.T, self.V, self.M) = data_shape
self.conn = connect_joint
label_path = '{}/{}_label.pkl'.format(path, phase)
if os.path.exists(label_path):
with open(label_... |
def test_wordvec_type():
with tempfile.TemporaryDirectory(dir=f'{TEST_WORKING_DIR}/out') as temp_dir:
google_dir = os.path.join(temp_dir, 'google', 'English')
os.makedirs(google_dir)
fake_file = os.path.join(google_dir, 'en.vectors.txt')
fout = open(fake_file, 'w')
fout.close... |
def load_data():
print('loading data...')
dirs = '/miniscratch/mittalsa/data/data'
filename = os.path.join(dirs, 'sort-of-clevr.pickle')
with open(filename, 'rb') as f:
(train_datasets, val_datasets, test_datasets) = pickle.load(f)
ternary_train = []
ternary_val = []
ternary_test = [... |
def rounds_to_string(rounds):
return ((((('\nFAST: ' + str(rounds[0])) + '\nMEDIUM: ') + str(rounds[1])) + '\nEXHAUSTIVE: ') + str(rounds[2])) |
def broadcast_coalesced(tensors, devices, buffer_size=):
return torch._C._broadcast_coalesced(tensors, devices, buffer_size) |
class ContinuousMeanQFunction(ContinuousQFunction):
_encoder: EncoderWithAction
_fc: nn.Linear
def __init__(self, encoder: EncoderWithAction, hidden_size: int):
super().__init__()
self._encoder = encoder
self._fc = nn.Linear(hidden_size, 1)
def forward(self, x: TorchObservation, ... |
def model_with_ann(tmp_path):
nmslib_hnsw_params = NmslibHnswParam(space='negdotprod_sparse', m=10, ef_s=200, ef_c=200, post=0)
return SLIM(0.0, 0.01, seed=42, index_builder=ExecutorNmslibIndexBuilder(index_params=nmslib_hnsw_params, index_store=SharedDiskIndexStore(warehouse_dir=str(tmp_path), index_dir='nmsli... |
class OffsetPlayerSpaceInvadersWorld(SpaceInvadersWorld):
def initial_shield_configuration(self):
return [{'health': 20, 'position': ((self._width // 4), 200)}, {'health': 20, 'position': (((2 * self._width) // 4), 200)}, {'health': 20, 'position': (((3 * self._width) // 4), 200)}]
def initial_player_sh... |
('/<path:path>')
def static_file(path):
if (path in ['stanza-brat.css', 'stanza-brat.js', 'stanza-parseviewer.js', 'loading.gif', 'favicon.png', 'stanza-logo.png']):
return app.send_static_file(path)
elif (path in 'index.html'):
return app.send_static_file('stanza-brat.html')
else:
a... |
_flax
_vision
class FlaxVisionTextDualEncoderIntegrationTest(unittest.TestCase):
def test_inference(self):
model = FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian', logit_scale_init_value=1)
processor = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-itali... |
def worker_init_fn(worker_id):
time_seed = np.array(time.time(), dtype=np.int32)
np.random.seed((time_seed + worker_id)) |
class AbsPosAttentionBase(MultiHeadAttentionBase):
def _attention(self, mask: Optional[torch.Tensor], q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
return self._attention_read(mask, torch.bmm(q, k.transpose(1, 2)), v) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.