code stringlengths 101 5.91M |
|---|
def convert_metadata(old_metadata):
new_metadata = _upgrade_columns_and_keys(old_metadata)
return new_metadata |
def sub_time(time, factor, dt=1, freq=None):
if (factor == 1):
return (time, factor)
elif (factor is not None):
return (ConditionalDimension(name='tsave', parent=time, factor=factor), factor)
else:
return (time, 1) |
def test_instance_header():
header = InstanceHeader(header=['foo', 'bar', 'target'])
assert (header.get_info() == "InstanceHeader: header: ['foo', 'bar', 'target']")
assert (header.get_header_label_at(0) == 'foo')
assert (header.get_header_label_at(4) is None) |
def run_k3mm(device_type: dace.dtypes.DeviceType):
(NI, NJ, NK, NL, NM) = sizes['small']
(A, B, C, D) = initialize(NI, NJ, NK, NL, NM)
if (device_type in {dace.dtypes.DeviceType.CPU, dace.dtypes.DeviceType.GPU}):
sdfg = k3mm_kernel.to_sdfg()
sdfg = auto_optimize(sdfg, device_type)
E ... |
def is_compiler(given, expected):
if (given == expected):
return True
if (len(expected) < len(given)):
return ((given[((len(given) - len(expected)) - 1)] == os.sep) and (given[(len(given) - len(expected)):] == expected))
return False |
def draw_at_coords(ax, coords, attn, img, title, radius=10, target_size=360):
coords = copy.deepcopy(coords)
for i in range(len(coords)):
coords[i] = coords[i][:2]
coords[i][0] = ((coords[i][0] / 27) * target_size)
coords[i][1] = ((coords[i][1] / 27) * target_size)
coords[i] = co... |
def get_t5_sequence_length_from_args(args):
return {'inputs': args.max_seq_length, 'targets': args.answer_max_seq_length} |
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
if (IsBlankLine(line) and (not nesting_state.InNamespaceBody())):
elided = clean_lines.elided
prev_line = elided[(linenum - 1)]
prevbrace = prev_lin... |
def set_lr_injection(lr_injection_value):
workspace.FeedBlob(_LEARNING_RATE_INJECTION, np.array([float(lr_injection_value)], dtype=np.float32)) |
.unit
.cartographer
def test_build_conditional_css():
helpers.setup()
actual_css = c.build_conditional_css(helpers.TEST_PATH)
expected_css = '\n'.join([' <link rel=\'preload\' href=\' as=\'style\' onload=\'this.rel="stylesheet"\'/>', ' <link rel=\'preload\' href=\'css/MarkerCluster.Default.min.css\' ... |
class PytorchTestLogger(unittest.TestCase):
def setUpClass(cls):
Logger.set_log_file('/tmp/')
model = mobilenet_v2(pretrained=True)
core_config = mct.core.CoreConfig(debug_config=mct.core.DebugConfig(analyze_similarity=True))
mct.ptq.pytorch_post_training_quantization_experimental(mo... |
def PositionalEmbeddingMul(num_embeddings: int, embedding_dim: int, padding_idx: int, learned: bool=False):
if learned:
if (padding_idx is not None):
num_embeddings = ((num_embeddings + padding_idx) + 1)
m = LearnedPositionalEmbeddingMul(num_embeddings, embedding_dim, padding_idx)
... |
class MAR(BaseMetric):
def __init__(self, recommendations, config, params, eval_objects):
super().__init__(recommendations, config, params, eval_objects)
self._cutoff = self._evaluation_objects.cutoff
self._relevance = self._evaluation_objects.relevance.binary_relevance
def name():
... |
class ResidualAttention(nn.Module):
def __init__(self, channel=512, num_class=1000, la=0.2):
super().__init__()
self.la = la
self.fc = nn.Conv2d(in_channels=channel, out_channels=num_class, kernel_size=1, stride=1, bias=False)
def forward(self, x):
(b, c, h, w) = x.shape
... |
def NonDecreasingParkingFunctions(n=None):
if (n is None):
return NonDecreasingParkingFunctions_all()
else:
return NonDecreasingParkingFunctions_n(n) |
class WideResnet(nn.Module):
def __init__(self, n_classes, k=1, n=28, low_dim=64, proj=True):
super(WideResnet, self).__init__()
(self.n_layers, self.k) = (n, k)
self.backbone = WideResnetBackbone(k=k, n=n)
self.classifier = nn.Linear((64 * self.k), n_classes, bias=True)
self... |
.parametrize('func,arg,expected_lines', [('explicit_return_none', None, OrderedSet([8])), ('empty_function', None, OrderedSet([11])), ('pass_function', None, OrderedSet([16])), ('only_return_on_branch', True, OrderedSet([20, 21])), ('only_return_on_branch', False, OrderedSet([20])), ('return_on_both_branches', True, Or... |
class EnasCnnModelBuilder(DAGModelBuilder):
def __init__(self, session=None, controller=None, dag_func='EnasConv1DDAG', l1_reg=0.0, l2_reg=0.0, batch_size=None, dag_kwargs=None, *args, **kwargs):
super().__init__(*args, dag_func=dag_func, **kwargs)
self.session = session
self.controller = co... |
def save_plots_for_dataset_model(path_save: Path, optimizer_list=None, epochs=None):
try:
results = get_result_list(results_path=path_save, optimizer_list=optimizer_list)
graph_title = f'{path_save.stem.upper()}'
plots_path = (path_save / 'plots')
plots_path.mkdir(exist_ok=True)
... |
class RandomSideObstacleBreakoutWorld(BreakoutWorld):
side_obstacle_width_range_start = 0
side_obstacle_width_range_end = 20
def reset_world(self):
super(RandomSideObstacleBreakoutWorld, self).reset_world()
self.reset_obstacle()
def reset_obstacle(self):
if hasattr(self, 'obstacl... |
def parse_constants_2002to2014(d):
constants = {}
for line in d.split('\n'):
name = line[:55].rstrip()
val = line[55:77].replace(' ', '').replace('...', '')
val = float(val)
uncert = line[77:99].replace(' ', '').replace('(exact)', '0')
uncert = float(uncert)
units... |
class InvertedResidual(nn.Module):
def __init__(self, cnf: InvertedResidualConfig, bn_norm, se_layer: Callable[(..., nn.Module)]=SqueezeExcitation):
super().__init__()
if (not (1 <= cnf.stride <= 2)):
raise ValueError('illegal stride value')
self.use_res_connect = ((cnf.stride ==... |
def test_verify_compatibility_type_errors():
valid_inducing_variable = construct_basic_inducing_variables([35], input_dim=40)
valid_kernel = construct_basic_kernel([Matern52()])
valid_mean_function = Zero()
with pytest.raises(GPLayerIncompatibilityException):
verify_compatibility(Matern52(), val... |
def recursive_obs_dict_to_spaces_dict(obs):
assert isinstance(obs, dict)
dict_of_spaces = {}
for (k, v) in obs.items():
_v = v
if isinstance(v, list):
_v = np.array(v)
elif isinstance(v, (int, np.integer, float, np.floating)):
_v = np.array([v])
if isi... |
def main(output_dir):
os.makedirs(output_dir, exist_ok=True)
dl_path = snapshot_download(repo_id='biglab/webui-all', repo_type='dataset')
combined_zip_path = os.path.join(output_dir, 'webui-merged.zip')
if (not os.path.exists(combined_zip_path)):
part_paths = sorted(glob.glob(os.path.join(dl_pat... |
def run_episodes(session_list):
work_num = 4
if ((len(session_list) > work_num) and (not (llm_name in (OPENAI_CHAT_MODELS + OPENAI_LLM_MODELS)))):
with ThreadPoolExecutor(max_workers=work_num) as executor:
results = list(executor.map(run_one_session, session_list))
print('Done th... |
def obser_parser(observation, instruction_text):
obs = observation.encode().decode('unicode-escape').encode('latin1').decode('utf-8')
obs = obs.replace('[button]', '[')
obs = obs.replace('[button_]', ']')
if obs.startswith('Instruction:'):
obs = obs.replace(instruction_text, '')
obs = ob... |
def get_mmcls_models():
mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json')
mmcls_urls = load_file(mmcls_json_path)
return mmcls_urls |
class HBFile():
def __init__(self, file, hb_info=None):
self._fid = file
if (hb_info is None):
self._hb_info = HBInfo.from_file(file)
else:
self._hb_info = hb_info
def title(self):
return self._hb_info.title
def key(self):
return self._hb_info.... |
class RendererDecoder(nn.Module):
def __init__(self, im_channels, h_dim, lstm_dim):
super().__init__()
self.decode = nn.Conv2d(lstm_dim, h_dim, 5, stride=1, padding=2)
self.convt = nn.ConvTranspose2d(h_dim, (h_dim * 2), 4, stride=2, padding=1)
self.convt2 = nn.ConvTranspose2d((h_dim ... |
def format_results(runs, title, split_name, step, best_other) -> str:
run_group = lib.common.group(runs, ['transformer.variant'])
variants = {v for (k, v) in init_type_table.items() if (f'transformer.variant_{k}' in run_group)}
rtmp = []
for i in init_order:
if (i not in variants):
c... |
def _remove(file_set, module_base, to_remove):
path = os.path.join(*module_base.split('.'))
for filename in to_remove:
if filename.startswith('.'):
filename = (path + filename)
else:
filename = os.path.join(path, filename)
remove = [filename]
remove.append... |
def prepare_train(save_json_train, save_json_valid, save_json_test=None, split_ratio=[80, 20], win_len=0.02, stride=0.02, seed=12, emovdb_folder=None, esd_folder=None, iemocap_folder=None, jlcorpus_folder=None, ravdess_folder=None):
random.seed(seed)
if (os.path.exists(save_json_train) and os.path.exists(save_j... |
class ModelErrors(object):
def __init__(self, model_name):
self.name = model_name
self.top_1_error_cases = None
self.top_10_error_cases = None |
_utils.test(arch=[ti.cpu, ti.cuda, ti.vulkan], exclude=[vk_on_mac], debug=True)
def test_print_string():
def func(x: ti.i32, y: ti.f32):
print('hello, world! %s %d %f', 233, y)
print('cool', x, 'well', y)
func(666, 233.3)
ti.sync() |
class RE24():
def __init__(self):
self.problem_name = 'RE24'
self.n_objectives = 2
self.n_variables = 2
self.n_constraints = 0
self.n_original_constraints = 4
self.ubound = np.zeros(self.n_variables)
self.lbound = np.zeros(self.n_variables)
self.lbound... |
def save_checkpoint(state, checkpoint, is_best=False, name=None):
if (not os.path.exists(checkpoint)):
print('Checkpoint Directory does not exist! Making directory {}'.format(checkpoint))
os.mkdir(checkpoint)
if is_best:
if (name is not None):
filepath = os.path.join(checkpoi... |
class RangeSampler(Sampler):
def __init__(self, start_ind, end_ind):
self.start_ind = start_ind
self.end_ind = end_ind
def __iter__(self):
indices = torch.arange(self.start_ind, self.end_ind).tolist()
return iter(indices)
def __len__(self):
return (self.end_ind - self... |
class KerasModel(Feedable):
def placeholders(self):
pass
def placeholders_union(cls, models):
phs = []
for model in models:
phs.extend(model.placeholders)
return phs
def output_tensors(self):
pass |
class Array(object):
def __init__(self, typ, dims, intent, obj):
self.type = typ
self.dims = dims
self.intent = intent
self.obj_copy = copy.deepcopy(obj)
self.obj = obj
self.arr = wrap.call(typ.type_num, dims, intent.flags, obj)
assert_(isinstance(self.arr, nd... |
def test_with_sensitive_markers(config):
new_markers = {'new_marker1', 'new_marker2'}
updated_config = config.with_sensitive_markers(*new_markers)
assert (updated_config.sensitive_markers == DEFAULT_SENSITIVE_MARKERS.union(new_markers)) |
class Connection(Base):
src: str
trg: str
fromLane: int
toLane: int
pas: bool = field(default=False)
keepClear: bool = field(default=True)
contPos: float = field(default=(- 1))
visibility: float = field(default=4.5)
speed: float = field(default=(- 1))
shape: List[Tuple[(float, fl... |
def test_run_test_case_chromosome_has_result():
executor = MagicMock()
result = MagicMock()
executor.execute.return_value = result
func = DummyTestCaseChromosomeComputation(executor)
test_case = tcc.TestCaseChromosome(MagicMock())
test_case.changed = False
test_case.set_last_execution_result... |
def main():
opt = get_opt()
print(opt)
print(('Start to train stage: %s, named: %s!' % (opt.stage, opt.name)))
train_dataset = CPDataset(opt)
train_loader = CPDataLoader(opt, train_dataset)
if (not os.path.exists(opt.tensorboard_dir)):
os.makedirs(opt.tensorboard_dir)
board = Summary... |
class Net_purchase(nn.Module):
def __init__(self):
super(Net_purchase, self).__init__()
self.fc1 = nn.Linear(600, 300)
self.fc2 = nn.Linear(300, 50)
self.fc3 = nn.Linear(50, 2)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.rel... |
class ContrastiveLearningDataset():
def __init__(self, root_folder):
self.root_folder = root_folder
def get_simclr_pipeline_transform(size, s=1):
color_jitter = transforms.ColorJitter((0.8 * s), (0.8 * s), (0.8 * s), (0.2 * s))
data_transforms = transforms.Compose([transforms.RandomResiz... |
class Bottleneck_IBN(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, ibn=True):
super(Bottleneck_IBN, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
if ibn:
self.bn1 = IBN(planes)
else:
... |
def convert_loras_to_safeloras(modelmap: Dict[(str, Tuple[(str, Set[str], int)])]={}, outpath='./lora.safetensors'):
convert_loras_to_safeloras_with_embeds(modelmap=modelmap, outpath=outpath) |
class AFLBitmap():
BITMAP_SIZE = 1048576
def __init__(self, bitmap=None):
self.bitmap = np.array(bytearray())
if (bitmap is not None):
if isinstance(bitmap, np.ndarray):
assert (np.sum(np.where((bitmap > 1), 1, 0)) == 0)
self.bitmap = np.array(bitmap, ... |
def removeSinglePoint(data):
newData = []
for stroke in data:
if (len(stroke[0]) > 1):
newData.append(stroke)
return newData |
class ImprovedBCELoss(nn.Module):
def __init__(self, lambda_):
super(ImprovedBCELoss, self).__init__()
self.L = lambda_
def forward(self, s, im):
astype = torch.float
im = im.type(astype)
s = s.type(astype)
weight_1 = ((self.L / torch.sum(im, dim=1, keepdim=True, ... |
.torch
.parametrize('query_ids, scores, unseen_items', [(torch.tensor([0], dtype=torch.long), torch.tensor([0, 1, 2, 3, 4], dtype=torch.float), torch.tensor([False, False, False, True, True], dtype=torch.bool)), (torch.tensor([1], dtype=torch.long), torch.tensor([0, 1, 2, 3, 4], dtype=torch.float), torch.tensor([False,... |
class TestLSTMED(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
set_random_seeds()
self.model = LSTMED(config=LSTMED.config_class(num_epochs=5))
self.dataset = MSL(rootdir=join(rootdir, 'data', 'smap'))
(df, metadata) = self.dataset... |
def reduce_zero(Q, coeffs, offset, exact_form=None):
a = coeffs[int(offset)]
if (a[2] == 0):
return exact_form
Qa = Q[1]
a[0] = (a[0] - ((a[2] * Qa) / 3))
coeffs[int(offset)] = a
if (exact_form is not None):
y = exact_form.parent()(exact_form.parent().base_ring().gen(0))
... |
def fine_tune(data_loader, ifold, meta_m, weights_for_finetune, exp_string):
is_finetune = True
print('finetunning MetaPred model ...')
if (FLAGS.method == 'cnn'):
m2 = finetune.CNN(data_loader, weights_for_finetune, freeze_opt=freeze_opt, is_finetune=is_finetune)
if (FLAGS.method == 'rnn'):
... |
def FetchInt8BlobRealVal(name):
result = C.fetch_blob(StringifyBlobName(name))
assert isinstance(result, tuple), 'You are not fetching an Int8Blob {}. Please use FetchBlob'.format(StringifyBlobName(name))
int8_blob = Int8Tensor(*result)
return ((int8_blob.data.astype(np.int32) - int(int8_blob.zero_point... |
class FairseqModel(FairseqEncoderDecoderModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
utils.deprecation_warning('FairseqModel is deprecated, please use FairseqEncoderDecoderModel or BaseFairseqModel instead', stacklevel=4) |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--task_name', default=None, type=str, required=True, help='The name of the task to train.')
parser.add_argument('--cache_dir', default='', type=str, help='Where do you want to store the pre-trained models downloaded from s3')
parser.add... |
class TestModule(nn.Module):
def __init__(self):
super(TestModule, self).__init__()
self.fc1 = nn.Linear(5, 3)
def forward(self, x):
return (x + 2) |
class TFCamembertForTokenClassification(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def video2segments(infos):
global count
(index, uid, dur) = (infos[0], infos[1], infos[2])
input_path = os.path.join(video_dir, (uid + '.mp4'))
output_uid_dir = os.path.join(output_dir, uid)
if (not os.path.exists(output_uid_dir)):
os.makedirs(output_uid_dir)
assert os.path.exists(input_... |
def get_equal_array_size(xs, ys, ints):
max_size = max(list(map(len, xs)))
for i in range(len(xs)):
xs[i] = np.append(xs[i], (xs[i][(- 1)] * np.ones([(max_size - len(xs[i]))])))
ys[i] = np.append(ys[i], (ys[i][(- 1)] * np.ones([(max_size - len(ys[i]))])))
ints[i] = np.append(ints[i], (in... |
(OperatorDef)
def analyze_op(analyzer, op):
for x in op.input:
analyzer.need_blob(x)
for x in op.output:
analyzer.define_blob(x) |
class FidelityKernel(KernelMatrixBase):
def __init__(self, encoding_circuit: EncodingCircuitBase, executor: Executor, evaluate_duplicates: str='off_diagonal', mit_depol_noise: Union[(str, None)]=None, initial_parameters: Union[(np.ndarray, None)]=None, parameter_seed: Union[(int, None)]=0, regularization: Union[(st... |
def get_loss(pred, label):
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label)
classify_loss = tf.reduce_mean(loss)
tf.summary.scalar('classify loss', classify_loss)
tf.add_to_collection('losses', classify_loss)
return classify_loss |
def convert_by_vocab(vocab, items, max_seq_length=None, blank_id=0, unk_id=1, uncased=True):
output = []
unk_num = 0
for item in items:
if uncased:
item = item.lower()
if (item in vocab):
output.append(vocab[item])
else:
output.append(unk_id)
... |
def _accumulate(iterable, fn=(lambda x, y: (x + y))):
it = iter(iterable)
try:
total = next(it)
except StopIteration:
return
(yield total)
for element in it:
total = fn(total, element)
(yield total) |
class SqueezeExcitation(nn.Module):
def __init__(self, input_channels: int, squeeze_factor: int=4):
super().__init__()
squeeze_channels = _make_divisible((input_channels // squeeze_factor), 8)
self.fc1 = nn.Conv2d(input_channels, squeeze_channels, 1)
self.relu = nn.ReLU(inplace=True)... |
def translate(dx, dy, dz):
return mat4([[1.0, 0.0, 0.0, dx], [0.0, 1.0, 0.0, dy], [0.0, 0.0, 1.0, dz], [0.0, 0.0, 0.0, 1.0]]) |
class TestBatchIterator(object):
def iterator(self):
return ExampleBatchIterator(8)
def test_iterator(self, iterator):
assert (list(iterator) == [0, 1, 2, 3, 4, 5, 6, 7]) |
class PrefetchLoader(object):
def __init__(self, loader):
self.loader = loader
self.stream = torch.cuda.Stream()
def __iter__(self):
loader_it = iter(self.loader)
self.preload(loader_it)
batch = self.next(loader_it)
while (batch is not None):
is_tuple ... |
class _Booleans(_Constraint):
def __init__(self):
super().__init__()
self._constraints = [_InstancesOf(bool), _InstancesOf(np.bool_)]
def is_satisfied_by(self, val):
return any((c.is_satisfied_by(val) for c in self._constraints))
def __str__(self):
return f"{', '.join([str(c)... |
def exec_cmd(cmd):
if isinstance(cmd, str):
cmd = cmd.split(' ')
new_cmd = []
first = True
for e in cmd:
if first:
first = False
new_cmd.append(e)
elif (e != ''):
se = e.split(' ')
if (len(se) > 1):
for e2 in se:
... |
def detect_overflow(var, ctx):
detected = False
if torch.isnan(var).any().item():
detected = True
print(f'{ctx} has nans')
if torch.isinf(var).any().item():
detected = True
print(f'{ctx} has infs')
if 0:
n100 = var[torch.ge(var.abs(), 100)]
if (n100.numel(... |
class PinocchioTestCase(unittest.TestCase):
def assertApprox(self, a, b, eps=1e-06):
return self.assertTrue(isapprox(a, b, eps), ('\n%s\nis not approximately equal to\n%s\nwith precision %f' % (a, b, eps))) |
def _get_experiment_progress(experiment) -> Union[(float, None)]:
if (experiment.status == Status.IN_PROGRESS):
return (experiment.aggregator.round_number / experiment.aggregator.rounds_to_train) |
def get_normalization_norm(func, mean_out, var_out, beta, gamma, constant0, constant1):
nl = []
sub_out = (fork_name(func.input[0]) + '_sub')
n = onnx.helper.make_node('Sub', [func.input[0], mean_out], [sub_out])
nl.append(n)
add_out = (fork_name(func.output[0]) + '_add')
n = onnx.helper.make_no... |
def result2tag(result, turncate):
sentences = []
for (idx, sentence) in enumerate(result):
valid_len = turncate[idx]
words = []
for word in sentence[:valid_len]:
word = word.tolist()
tag = word.index(max(word))
words.append(tag)
sentences.appen... |
class Conv2dAWS(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):
super(Conv2dAWS, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)
self.register_buffer('weight_gamma', torch.on... |
class TestSeq2SeqCollator(unittest.TestCase):
def test_collate(self):
eos_idx = 1
pad_idx = 0
collater = Seq2SeqCollater(feature_index=0, label_index=1, pad_index=pad_idx, eos_index=eos_idx)
frames1 = np.array([[7, 8], [9, 10]])
frames2 = np.array([[1, 2], [3, 4], [5, 6]])
... |
class EggInfoDistribution(BaseInstalledDistribution):
requested = True
shared_locations = {}
def __init__(self, path, env=None):
def set_name_and_version(s, n, v):
s.name = n
s.key = n.lower()
s.version = v
self.path = path
self.dist_path = env
... |
class RandomDomainSampler(Sampler):
def __init__(self, data_source, batch_size, n_domain):
self.data_source = data_source
self.domain_dict = defaultdict(list)
for (i, items) in enumerate(data_source):
camid = items[2]
self.domain_dict[camid].append(i)
self.dom... |
class TestGeomspace(object):
def test_basic(self):
y = geomspace(1, 1000000.0)
assert_((len(y) == 50))
y = geomspace(1, 1000000.0, num=100)
assert_((y[(- 1)] == (10 ** 6)))
y = geomspace(1, 1000000.0, endpoint=False)
assert_((y[(- 1)] < (10 ** 6)))
y = geomspa... |
def debug_print_file(fn):
print(('%s:' % fn))
if (not os.path.exists(fn)):
print('<does not exist>')
return
if os.path.isdir(fn):
print('<dir:>')
pprint(sorted(os.listdir(fn)))
return
print(open(fn).read()) |
def folder2lmdb(dpath, name='train', write_frequency=5000):
directory = osp.expanduser(osp.join(dpath, name))
print(('Loading dataset from %s' % directory))
dataset = ImageFolder(directory, loader=raw_reader)
data_loader = DataLoader(dataset, num_workers=4, collate_fn=(lambda x: x))
lmdb_path = osp.... |
def main():
set_seeds(2020)
args = vars(parser.parse_args())
alphabet = Protein()
cfgs = []
data_cfg = config.DataConfig(args['data_config'])
cfgs.append(data_cfg)
if (args['lm_model_config'] is None):
model_cfg = config.ModelConfig(args['model_config'], input_dim=len(alphabet), num_... |
def generate_bsm_links(graph, node_procs, parsed_args, bsm_naming_func):
cchannels = []
qchannels = []
bsm_nodes = []
for (i, node_pair) in enumerate(graph.edges):
(node1, node2) = node_pair
bsm_name = bsm_naming_func(node1, node2)
bsm_node = {Topology.NAME: bsm_name, Topology.TY... |
def get_out_mask(cfg, pred_mask):
mask_loss_type = cfg.MODEL.CDPN.ROT_HEAD.MASK_LOSS_TYPE
(bs, c, h, w) = pred_mask.shape
if (mask_loss_type == 'L1'):
assert (c == 1), c
mask_max = torch.max(pred_mask.view(bs, (- 1)), dim=(- 1))[0].view(bs, 1, 1, 1)
mask_min = torch.min(pred_mask.vie... |
class OpenAIGPTConfig(PretrainedConfig):
pretrained_config_archive_map = OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP
def __init__(self, vocab_size_or_config_json_file=40478, n_positions=512, n_ctx=512, n_embd=768, n_layer=12, n_head=12, afn='gelu', resid_pdrop=0.1, embd_pdrop=0.1, attn_pdrop=0.1, layer_norm_epsilo... |
def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
xp = array_namespace(cond, *arrays)
if ((f2 is fillvalue is None) or ((f2 is not None) and (fillvalue is not None))):
raise ValueError('Exactly one of `fillvalue` or `f2` must be given.')
args = xp.broadcast_arrays(cond, *arrays)
(cond, a... |
class Reshape(nn.Module):
def __init__(self, *shape: Union[(int, str)]):
super().__init__()
self.shape = shape
def forward(self, x: torch.Tensor):
shape = [(x.shape[int(i)] if isinstance(i, str) else i) for i in self.shape]
return x.reshape(*shape) |
.mpl_image_compare
def test_plot_results_components_no_cls(datadir):
data = json.load(datadir.joinpath('tail_probs_hypotest_results.json').open(encoding='utf-8'))
fig = Figure()
ax = fig.subplots()
brazil_band_collection = brazil.plot_results(data['testmus'], data['results'], test_size=0.05, ax=ax, comp... |
def get_vocabulary(fobj, is_dict=False):
vocab = Counter()
for (i, line) in enumerate(fobj):
if is_dict:
try:
(word, count) = line.strip('\r\n ').split(' ')
except:
print('Failed reading vocabulary file at line {0}: {1}'.format(i, line))
... |
_params({'labels_true': ['array-like'], 'labels_pred': ['array-like'], 'beta': [Interval(Real, 0, None, closed='left')]}, prefer_skip_nested_validation=True)
def v_measure_score(labels_true, labels_pred, *, beta=1.0):
return homogeneity_completeness_v_measure(labels_true, labels_pred, beta=beta)[2] |
def get_word_embedding(sp_output_dir=None):
model = Ner.from_pretrained(sp_output_dir)
tokenizer = BertTokenizer.from_pretrained(sp_output_dir, do_lower_case=args.do_lower_case)
for (name, parameters) in model.named_parameters():
if (name == 'bert.embeddings.word_embeddings.weight'):
ber... |
class SyncBNFunc(Function):
def forward(ctx, in_data, scale_data, shift_data, running_mean, running_var, eps, momentum, training):
if in_data.is_cuda:
ctx.eps = eps
(N, C, H, W) = in_data.size()
in_data = in_data.view(N, C, (- 1))
mean_in = in_data.mean((- 1),... |
class H_Swish(nn.Module):
def forward(self, x):
out = ((x * F.relu6((x + 3), inplace=True)) / 6)
return out |
class set_layer_config():
def __init__(self, scriptable: Optional[bool]=None, exportable: Optional[bool]=None, no_jit: Optional[bool]=None, no_activation_jit: Optional[bool]=None):
global _SCRIPTABLE
global _EXPORTABLE
global _NO_JIT
global _NO_ACTIVATION_JIT
self.prev = (_SC... |
class InpaintGenerator(BaseNetwork):
def __init__(self, init_weights=True):
super(InpaintGenerator, self).__init__()
channel = 256
hidden = 512
stack_num = 8
num_head = 4
kernel_size = (7, 7)
padding = (3, 3)
stride = (3, 3)
output_size = (60, ... |
class TFPegasusForConditionalGeneration():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.