code stringlengths 101 5.91M |
|---|
def resolve_act_layer(kwargs, default='relu'):
act_name = kwargs.pop('act_layer', default)
if (act_name == 'relu'):
return tf.keras.layers.ReLU
elif (act_name == 'relu6'):
return partial(tf.keras.layers.ReLU, max_value=6.0)
else:
raise NotImplemented |
def fid_calculate_activation_statistics(act):
mu = np.mean(act, axis=0)
sigma = np.cov(act, rowvar=False)
return (mu, sigma) |
class BaseTask(Problem):
def __init__(self, tokenizer, candidate_pool, obj_dim, transform=(lambda x: x), batch_size=1, candidate_weights=None, max_len=None, max_ngram_size=1, allow_len_change=True, **kwargs):
self.op_types = (['sub', 'ins', 'del'] if allow_len_change else ['sub'])
if (max_len is Non... |
class CycleFC(nn.Module):
def __init__(self, in_channels: int, out_channels: int, kernel_size, stride: int=1, padding: int=0, dilation: int=1, groups: int=1, bias: bool=True):
super(CycleFC, self).__init__()
if ((in_channels % groups) != 0):
raise ValueError('in_channels must be divisibl... |
def perm_invert(p):
q = ([None] * len(p))
for (i, j) in enumerate(p):
q[j] = i
return q |
def _suggest_semantic_version(s):
result = s.strip().lower()
for (pat, repl) in _REPLACEMENTS:
result = pat.sub(repl, result)
if (not result):
result = '0.0.0'
m = _NUMERIC_PREFIX.match(result)
if (not m):
prefix = '0.0.0'
suffix = result
else:
prefix = m.... |
def resolve_entity_map(qid, query, el_results, el_extractor):
_delimiter = ';'
if (not (qid in el_results)):
return {}
entity_map = el_results[qid]['entities']
entities = set(entity_map.keys())
for k in entity_map:
v = entity_map[k]['friendly_name']
entity_map[k] = ' '.join(v... |
def save_config(logdir, config):
param_path = os.path.join(logdir, 'params.json')
print(('[*] PARAM path: %s' % param_path))
with open(param_path, 'w') as fp:
json.dump(config.__dict__, fp, indent=4, sort_keys=True) |
def train(args, train_batches, model, tokenizer, evaluator):
t_total = (len(train_batches) * args.train_epochs)
no_decay = ['bias', 'LayerNorm.weight']
head_params = ['coref', 'mention', 'antecedent']
model_decay = [p for (n, p) in model.named_parameters() if ((not any(((hp in n) for hp in head_params))... |
def load_or_extract_features(args, cfg):
if (cfg.MODEL.SPEC.TEXT.TOKENIZER == 'clip'):
tokenizer = SimpleTokenizer()
elif ('hf_' in cfg.MODEL.SPEC.TEXT.TOKENIZER):
tokenizer = HFPTTokenizer(pt_name=cfg.MODEL.SPEC.TEXT.TOKENIZER[3:])
else:
tokenizer = None
feature_file = os.path.j... |
def rand_float(input_shape):
a = np.random.rand(*input_shape)
a = a.astype(np.float32)
return a |
def get_instr_trace_count(instr: LeanPreprocessedCodeElement) -> int:
if isinstance(instr, LeanPreprocessedAddAp):
return 1
if isinstance(instr, LeanPreprocessedAssertEq):
return 1
if (isinstance(instr, LeanPreprocessedConst) or isinstance(instr, LeanPreprocessedNop)):
return 0
c... |
class MulticodeKScheduler(transformers.TrainerCallback):
def __init__(self, k_max, k_min, decay_steps, decay_power=1):
self.k_max = k_max
self.k_min = k_min
self.decay_steps = (decay_steps - 1)
self.decay_power = decay_power
def k_scheduler(self, step):
return int((self.k... |
def buffer_to_bits(buffer):
cmmand_buf = np.frombuffer(buffer, dtype=np.uint8)
return np.unpackbits(cmmand_buf, bitorder='little') |
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-g', '--path', type=str, default='search_targets/default.json')
parser.add_argument('-l', '--large', action='store_true')
args = parser.parse_args()
with open(args.path, 'r') as f:
options = json.load(f)
... |
def main(unused_argv):
(wide_columns, deep_columns) = create_feature_columns()
global total_feature_columns
total_feature_columns = (wide_columns + deep_columns)
estimator = tf.estimator.DNNLinearCombinedClassifier(linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, dnn_hidden_units=F... |
(reuse_venv=True)
def diagnostics(session):
session.install(*requirements_dev)
session.run('python', 'dev/kernel-diagnostics.py', *session.posargs) |
def main(params):
imgs = json.load(open(params['input_json'], 'r'))
itow = json.load(open(params['dict_json'], 'r'))['ix_to_word']
wtoi = {w: i for (i, w) in itow.items()}
imgs = imgs['images']
(ngram_words, ngram_idxs, ref_len) = build_dict(imgs, wtoi, params)
utils.pickle_dump({'document_frequ... |
def pesq_wb(predicted, target, sampling_frequency=16000):
g = torch.manual_seed(1)
wb_pesq = PerceptualEvaluationSpeechQuality(sampling_frequency, 'wb')
return wb_pesq(predicted, target) |
def googlenet_arg_scope(weight_decay=0.0002):
with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay)):
with slim.arg_scope([slim.conv2d], weights_initializer=slim.variance_scaling_initializer(), activation_fn=tf.nn.relu) as sc:
return sc |
def read_file_multi_lab(lab_fp, score_fp, pred_thresh):
chan_lab_d = {}
for line in open(lab_fp):
(chan_id, lab) = line.strip('\n').split('\t')
if (chan_id not in chan_lab_d):
chan_lab_d[chan_id] = set([])
chan_lab_d[chan_id].add(lab.replace(' ', ''))
lab_with_pred_l = []... |
def __is_protected(method_name: str) -> bool:
return (method_name.startswith('_') and (not method_name.startswith('__'))) |
def post_process_hook(out, pb, state, extend=False):
ts = pb.ts
if (ts.step == (ts.n_step - 1)):
(fig, (ax1, ax2)) = plt.subplots(nrows=2)
temperature_image = nm.array(probe_results).squeeze()
m = ax1.imshow(temperature_image.T, origin='lower', aspect='auto')
ax1.set_xlabel('time... |
def sorted_nicely(l):
def convert(text):
return (int(text) if text.isdigit() else text)
def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', key[0])]
return sorted(l, key=alphanum_key) |
def mincut_split_darts(dist_avg, split_num):
assert (split_num == 2), 'always split into 2 groups for darts space (when using gradient to split)'
assert isinstance(dist_avg, np.ndarray)
vertex = [i for i in range(dist_avg.shape[0])]
max_cut = 100000
for subset in chain(*map((lambda x: combinations(v... |
def test_callbacks():
def check(caller, func, user_data):
caller = CALLERS[caller]
func = FUNCS[func]()
user_data = USER_DATAS[user_data]()
if (func is callback_python):
def func2(x):
return func(x, 2.0)
else:
func2 = LowLevelCallable(f... |
def get_node_ratio(history_data, eval_data):
eval_uniq_nodes = set(eval_data['sources']).union(set(eval_data['destinations']))
hist_uniq_nodes = set(history_data['sources']).union(set(history_data['destinations']))
new_nodes = []
for node in eval_uniq_nodes:
if (node not in hist_uniq_nodes):
... |
def test_multi_objective_correctness():
(final_loss, alphas) = multi_cdv.get_descent_vector(losses, gradient)
assert (final_loss.data == ((alphas[0] * loss_1) + (alphas[1] * loss_2)).data)
assert (alphas == alpha_base) |
def Unet_with_inception(input_img, n_filters=16, dropout=0.3, batch_norm=True):
c1 = Conv2D(16, kernel_size=(1, 6), strides=(1, 1), padding='valid')(input_img)
if batch_norm:
c1 = BatchNormalization()(c1)
c1 = Activation('relu')(c1)
c1 = convB(c1, 10, 2, 2)
c1 = convA(c1, 10, batch_norm)
... |
def test_net_on_dataset(args, multi_gpu=False):
dataset = build_dataset(cfg.TEST.DATASETS, is_train=False)
total_timer = Timer()
total_timer.tic()
if multi_gpu:
num_images = len(dataset)
(all_boxes, all_segms, all_parss, all_pscores) = multi_gpu_test_net_on_dataset(args, num_images)
... |
class DeformableDetrModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class HparamsAbsorbing(HparamsBase):
def __init__(self, dataset):
self.loss_type = 'reweighted_elbo'
self.sample_type = 'diffusion'
self.mask_schedule = 'random'
self.total_steps = 256
self.sample_steps = 256
self.attn_pdrop = 0.0
self.embd_pdrop = 0.0
... |
def get_instance_kwargs(args, num_exps, variant):
mode = args.mode
ssh_host = None
gpu_id = args.gpu_id
if (mode == 'local_docker'):
interactive_docker = True
else:
interactive_docker = False
instance_kwargs = dict(mode=mode, ssh_host=ssh_host, use_gpu=(not args.no_gpu), gpu_id=g... |
class Combine(TokenConverter):
def __init__(self, expr, joinString='', adjacent=True):
super(Combine, self).__init__(expr)
if adjacent:
self.leaveWhitespace()
self.adjacent = adjacent
self.skipWhitespace = True
self.joinString = joinString
self.callPrepars... |
class TopologyZooProblem(Problem):
def __init__(self, fname, *, model='gravity', seed=0, scale_factor=1.0, **kwargs):
self._fname = fname
G = Problem._read_graph_graphml(os.path.join(TOPOLOGIES_DIR, 'topology-zoo', fname))
super().__init__(G, model=model, seed=seed, scale_factor=scale_factor... |
class SourceLoc(L.Layer):
def __init__(self, xs, **kwargs):
super(SourceLoc, self).__init__(**kwargs)
self.xs = self.add_weight(name=kwargs.get('name', 'xs'), shape=(len(xs),), trainable=False, initializer=Initializer(xs))
def call(self, x):
return (tf.ones_like(x) * self.xs)
def get... |
def load_lib():
global _tifffile
try:
import tifffile as _tifffile
except ImportError:
from . import _tifffile
return _tifffile |
def test_reduce_mean_dyn_time():
time_dim = Dim(Tensor('time', [batch_dim], dtype='int32'))
in_dim = Dim(7, name='in')
extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')})
class _Net(rf.Module):
def __call__(self, x: Tensor) -> Tensor:
re... |
def _dump_str(v):
if ((sys.version_info < (3,)) and hasattr(v, 'decode') and isinstance(v, str)):
v = v.decode('utf-8')
v = ('%r' % v)
if (v[0] == 'u'):
v = v[1:]
singlequote = v.startswith("'")
if (singlequote or v.startswith('"')):
v = v[1:(- 1)]
if singlequote:
... |
class LambdaWarmUpCosineScheduler():
def __init__(self, warm_up_steps, lr_min, lr_max, lr_start, max_decay_steps, verbosity_interval=0):
self.lr_warm_up_steps = warm_up_steps
self.lr_start = lr_start
self.lr_min = lr_min
self.lr_max = lr_max
self.lr_max_decay_steps = max_deca... |
_processor('clip_image_eval')
class ClipImageEvalProcessor(BlipImageBaseProcessor):
def __init__(self, image_size=224, mean=None, std=None):
super().__init__(mean=mean, std=std)
self.transform = transforms.Compose([transforms.Resize(image_size, interpolation=InterpolationMode.BICUBIC), transforms.Ce... |
.core
def test_hdfs_index_store_exception():
local_warehouse_dir = 'file:///tmp'
with pytest.raises(ValueError, match=f"Can't recognize path {(local_warehouse_dir + '/index_dir')} as HDFS path!"):
HdfsIndexStore(warehouse_dir=local_warehouse_dir, index_dir='index_dir') |
_lr_scheduler('cosine')
class CosineSchedule(FairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
if (len(args.lr) > 1):
raise ValueError('Cannot use a fixed learning rate schedule with cosine. Consider --lr-scheduler=fixed instead.')
warmup... |
def processGuiEvent(_gui):
global fade
while _gui.get_event((ti.GUI.PRESS, ti.GUI.LMB), (ti.GUI.PRESS, ti.GUI.RMB)):
if (_gui.is_pressed(ti.GUI.LMB) and _gui.is_pressed(ti.GUI.RMB)):
for i in range(maxElements):
if ((sources[i].q != 0) and ((sources[i].pos - vec2(*_gui.get_cu... |
class TorchModel(nn.Module):
def __init__(self, config: DeepConfig):
super(TorchModel, self).__init__()
self.config = config
def forward(self, past, past_timestamp, future_timestamp, *args, **kwargs):
raise NotImplementedError
def device(self):
return next(self.parameters()).... |
def selu(x):
with ops.name_scope('elu') as scope:
alpha = 1.
scale = 1.
return (scale * tf.where((x >= 0.0), x, (alpha * tf.nn.elu(x)))) |
class CustomAdamOptimizer(BaseCustomOptimizer):
def __init__(self, beta1=0.9, beta2=0.999, epsilon=1e-08, **kwargs):
super(CustomAdamOptimizer, self).__init__(**kwargs)
self._beta1 = beta1
self._beta2 = beta2
self._epsilon = epsilon
def _prepare(self):
super(CustomAdamOpt... |
def add_confints(df):
df['minconf'] = df.apply((lambda row: confint(row)[0]), axis=1)
df['maxconf'] = df.apply((lambda row: confint(row)[1]), axis=1) |
def generate_subsystem_code(config):
scorep_config = (['scorep-config'] + config)
(return_code, _, _) = scorep.helper.call(scorep_config)
if (return_code != 0):
raise ValueError('given config {} is not supported'.format(scorep_config))
(_, scorep_adapter_init, _) = scorep.helper.call((scorep_con... |
def detoxify(data, use_cuda):
D_scorer = (Detoxify('original', device='cuda') if use_cuda else Detoxify('original'))
(scores, all_scores) = ([], [])
for sample in tqdm(data):
score = D_scorer.predict(sample['output'])
score = {k: float(v) for (k, v) in score.items()}
all_scores.appen... |
_config
def task_finetune_action_recognition_hmdb51():
exp_name = 'finetune_action_recognition_hmdb51'
datasets = ['hmdb51']
loss_names = _loss_names({'openend_vqa': 1})
msrvttqa_label_size = 52
batch_size = 256
max_epoch = 50
max_steps = None
warmup_steps = 0.1
draw_false_text = 15
... |
def _try_load_schema(config: LoaderConfig, first: Loader, second: Loader) -> BaseSchema:
from urllib3.exceptions import InsecureRequestWarning
with warnings.catch_warnings():
warnings.simplefilter('ignore', InsecureRequestWarning)
try:
return first(config)
except SchemaError ... |
def accum_node_fts(encoders, dp: _DataPoint, node_fts: _Array) -> _Array:
is_pointer = (dp.type_ in [_Type.POINTER, _Type.PERMUTATION_POINTER])
if (((dp.location == _Location.NODE) and (not is_pointer)) or ((dp.location == _Location.GRAPH) and (dp.type_ == _Type.POINTER))):
encoding = _encode_inputs(enc... |
class TransferPair():
def __init__(self, src_obj: ObjectStoreObject, dst_objs: Dict[(str, ObjectStoreObject)], dst_key: str):
self.src_obj = src_obj
self.dst_objs = dst_objs
self.dst_key = dst_key |
def _list_unsupported_tensor_ops():
header = '\n\n\nUnsupported Tensor Methods\n\n '
(methods, properties) = _gen_unsupported_methods_properties()
return (((((header + '\n') + methods) + '\n\nUnsupported Tensor Properties\n\n ') + '\n') + properties) |
def conway_diagonal_factor(self, p):
if (p == 2):
species_list = self.conway_species_list_at_2()
else:
species_list = self.conway_species_list_at_odd_prime(p)
diag_factor = QQ(1)
for s in species_list:
if (s == 0):
pass
elif ((s % 2) == 1):
diag_fa... |
def check_format(file_path):
with open(file_path, encoding='UTF-8') as out:
file_content = out.read().strip()
for (i, line) in enumerate(file_content.split('\n')):
(topic_id, tweet_id, score, run_id) = line.strip().split('\t')
if (not _LINE_PATTERN_A.match(('%s\t%s' % (tweet_... |
class GaussianPolicy(nn.Module):
def __init__(self, state_shape, action_shape, hidden_units=(256, 256), hidden_activation=nn.ReLU(inplace=True)):
super().__init__()
self.mlp = MLP(input_dim=state_shape[0], output_dim=hidden_units[(- 1)], hidden_units=hidden_units[:(- 1)], hidden_activation=hidden_ac... |
class Vgg(nn.Module):
def __init__(self, img_size=256, fc_layer=4096, classes=10):
super(Vgg, self).__init__()
self.fc_layer = fc_layer
self.classes = classes
if (img_size == 256):
self.final_size = 8
if (img_size == 96):
self.final_size = 3
if... |
def visualize(state, fname='tests/assets/mahjong/xxx.svg'):
state.save_svg(fname, color_theme='dark') |
class ProgressiveWavLM(nn.Module):
def __init__(self, source, save_path, output_norm=False, freeze=False, freeze_encoder=False, freeze_feature_extractor=False, apply_spec_augment=False, hidden_size=1024, num_layers=1, dropout=0.0, bidirectional=False):
super().__init__()
download_file(_TOKENIZER_URL... |
class E2ESeq2SeqModel(Seq2SeqModel):
def setup(self, data):
self.set_flags()
self.set_data_dependent_params(data)
self.set_embeddings()
self.set_encoder()
self.set_decoder()
def set_data_dependent_params(self, data):
vocabsize = len(data.vocab)
self.set_sr... |
def build_backbone(cfg):
param = dict()
for key in cfg:
if (key == 'type'):
continue
param[key] = cfg[key]
backbone = models.backbone.__dict__[cfg.type](**param)
return backbone |
def get_args_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--cfg', type=str, default='config/config.yml', help='config file path')
parser.add_argument('--load_pretrained', type=int, required=False, help='whether to load pretrained weights for training')
parser.add_argument('--checkpo... |
class typedef(CythonType):
def __init__(self, type, name=None):
self._basetype = type
self.name = name
def __call__(self, *arg):
value = cast(self._basetype, *arg)
return value
def __repr__(self):
return (self.name or str(self._basetype))
__getitem__ = index_type |
def print_successes(succ_traj):
print('\n')
print('Successes: ')
print(succ_traj)
print('\n') |
class CaptionInstructDataset(CaptionDataset):
def __getitem__(self, index):
data = super().__getitem__(index)
if (data != None):
data['text_output'] = data['text_input']
data['text_input'] = self.text_processor('')
return data |
def remove_fc(state_dict):
for key in list(state_dict.keys()):
if key.startswith('fc.'):
del state_dict[key]
return state_dict |
class SpacepyLibFindTests(unittest.TestCase):
def setUp(self):
warnings.simplefilter('always')
def testExists(self):
self.assertTrue(spacepy.lib.have_libspacepy) |
def get_transform(opt, params=None, grayscale=False, method=Image.BICUBIC, convert=True):
transform_list = []
if grayscale:
transform_list.append(transforms.Grayscale(1))
if ('resize' in opt.preprocess):
osize = [opt.load_size, opt.load_size]
transform_list.append(transforms.Resize(o... |
class TestModelClass(BaseModelClass):
def setup_anndata(cls, adata: AnnData, layer: Optional[str]=None, batch_key: Optional[str]=None, labels_key: Optional[str]=None, size_factor_key: Optional[str]=None, categorical_covariate_keys: Optional[list[str]]=None, continuous_covariate_keys: Optional[list[str]]=None, **kwa... |
class PARALoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, score, predicate_one_hot_labels):
entity_mask = predicate_one_hot_labels.sum(dim=1, keepdim=True).repeat_interleave(score.shape[1], dim=1)
entity_mask = (entity_mask > 0).float()
entity_sum = (ent... |
def plot_value_hist(vals, dp):
nbins = 100
mn = np.min(vals)
mx = np.max(vals)
pl = dp.get_next_plot()
(n, bins) = np.histogram(vals, bins=nbins, density=True)
width = (0.7 * (bins[1] - bins[0]))
center = ((bins[:(- 1)] + bins[1:]) / 2)
plt.bar(center, n, align='center', width=width, fac... |
def np_array(tensor):
tensor = tensor.squeeze(0)
tensor = tensor.detach().cpu()
return tensor.numpy() |
def _ipaddress_match(ipname, host_ip):
ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())
return (ip == host_ip) |
def is_integral(dtype: torch.dtype) -> bool:
return (dtype in (torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64)) |
def _maybe_cast_reduce_op_input(g, self):
dtype = self.type().scalarType()
if (dtype is not None):
if ((not sym_help._is_fp(self)) and (not (dtype == 'Long'))):
self = _cast_Long(g, self, False)
return self |
class FreezeGradientsMatchingRegexTest(tf.test.TestCase):
def _create_grads_and_vars(self):
return [(tf.constant(1.0), tf.Variable(1.0, name='FeatureExtractor/InceptionV3/weights')), (tf.constant(2.0), tf.Variable(2.0, name='FeatureExtractor/InceptionV3/biases')), (tf.constant(3.0), tf.Variable(3.0, name='S... |
def test_multidim():
sdfg = dace.SDFG('mapfission_multidim')
sdfg.add_array('A', [2, 3], dace.float64)
state = sdfg.add_state()
(me, mx) = state.add_map('outer', dict(i='0:2', j='0:3'))
nsdfg = dace.SDFG('nested')
nsdfg.add_array('a', [1], dace.float64)
nstate = nsdfg.add_state()
t = nst... |
class TestUtilApproxDividable(unittest.TestCase):
def test_int(self):
self.assertTrue(util.approx_dividable(24, 2, rel_overhead=0, abs_overhead=0))
self.assertTrue(util.approx_dividable(24, 3, rel_overhead=0, abs_overhead=0))
self.assertTrue(util.approx_dividable(24, 4, rel_overhead=0, abs_o... |
def build_conv_layer(cfg, *args, **kwargs):
if (cfg is None):
cfg_ = dict(type='Conv')
else:
assert (isinstance(cfg, dict) and ('type' in cfg))
cfg_ = cfg.copy()
layer_type = cfg_.pop('type')
if (layer_type not in conv_cfg):
raise KeyError('Unrecognized norm type {}'.form... |
class MyModule(nn.Module):
def forward(self, x, y):
x = nn.ReLU()(x)
return MyFunction.apply(x, y) |
def test_slate_ope_performance_using_standard_additive_log():
n_unique_action = 10
len_list = 3
dim_context = 2
reward_type = 'binary'
random_state = 12345
n_rounds = 1000
reward_structure = 'standard_additive'
click_model = None
behavior_policy_function = linear_behavior_policy_logi... |
def register_Ns3LteStatsCalculator_methods(root_module, cls):
cls.add_constructor([param('ns3::LteStatsCalculator const &', 'arg0')])
cls.add_constructor([])
cls.add_method('ExistsCellIdPath', 'bool', [param('std::string', 'path')])
cls.add_method('ExistsImsiPath', 'bool', [param('std::string', 'path')]... |
def deconv3d(norm_type, in_planes, out_planes, num_groups=2):
if (norm_type == 'batch'):
return nn.Sequential(nn.ConvTranspose3d(in_planes, out_planes, kernel_size=4, stride=2, padding=1, bias=True), nn.BatchNorm3d(out_planes), nn.LeakyReLU(0.2, inplace=True))
elif (norm_type == 'group'):
return... |
def get_toxicity_metric_specs() -> List[MetricSpec]:
return [MetricSpec(class_name='helm.benchmark.metrics.toxicity_metrics.ToxicityMetric', args={})] |
def ocp(F, bcs, J, y, u, p, config):
return cashocs.OptimalControlProblem(F, bcs, J, y, u, p, config=config) |
class BaseAssigner(metaclass=ABCMeta):
def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None):
pass |
class GPTNeoForCausalLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class MaxUnpool2d(_MaxUnpoolNd):
kernel_size: _size_2_t
stride: _size_2_t
padding: _size_2_t
def __init__(self, kernel_size: _size_2_t, stride: Optional[_size_2_t]=None, padding: _size_2_t=0) -> None:
super(MaxUnpool2d, self).__init__()
self.kernel_size = _pair(kernel_size)
self.... |
class TFltRect(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
MnX = _swig_property(_snap.TFltRect_MnX_get, _snap.TFltRect_MnX_set)
MnY = _swig_property(_snap.TFltRect_MnY_get, _snap.TFltRect_MnY_set)
MxX = _s... |
class RewardPlusDelay(ValueFunction):
def __init__(self, DELAY_COEFFICIENT: float=0.001, log_dir='../logs/'):
super(RewardPlusDelay, self).__init__(log_dir)
self.DELAY_COEFFICIENT = DELAY_COEFFICIENT
def get_value(self, experiences: List[Experience]) -> List[List[Tuple[(Action, float)]]]:
... |
def _impl(array, fill_value, highlevel, behavior, dtype, including_unknown, attrs):
with HighLevelContext(behavior=behavior, attrs=attrs) as ctx:
(layout, _) = ensure_same_backend(ctx.unwrap(array, primitive_policy='error'), ctx.unwrap(fill_value, primitive_policy='pass-through', string_policy='pass-through... |
class COGS(TypedTextDataset):
URL_BASE = '
SPLT_TYPES = ['train', 'test', 'valid', 'gen']
NAME_MAP = {'valid': 'dev'}
def build_cache(self) -> TypedTextDatasetCache:
types = []
type_list = []
type_map = {}
index_table = {}
in_sentences = []
out_sentences =... |
def df():
folder = dirname(replay.__file__)
res = pd.read_csv(join(folder, '../examples/data/ml1m_ratings.dat'), sep='\t', names=['user_id', 'item_id', 'relevance', 'timestamp']).head(1000)
res = convert2spark(res)
encoder = LabelEncoder([LabelEncodingRule('user_id'), LabelEncodingRule('item_id')])
... |
def main(argv=sys.argv):
(dataset, subset_size, method, subset_file, rest_file) = process_options(argv)
selected_lines = []
if (method == 0):
selected_lines = stratified_selection(dataset, subset_size)
elif (method == 1):
selected_lines = random_selection(dataset, subset_size)
datase... |
class DualMatroid(Matroid):
def __init__(self, matroid):
if (not isinstance(matroid, Matroid)):
raise TypeError('no matroid provided to take dual of.')
self._matroid = matroid
def groundset(self):
return self._matroid.groundset()
def _rank(self, X):
return self._m... |
def map_aa_idx_to_tok_set(msa_sampler):
return set((msa_sampler.model.alphabet.get_tok(idx) for idx in msa_sampler.valid_aa_idx)) |
class DecoderSCAR(nn.Module):
def __init__(self, n_input: int, n_output: int, n_layers: int=2, n_hidden: int=150, use_batch_norm: bool=True, use_layer_norm: bool=False, scale_activation: Literal[('softmax', 'softplus', 'softplus_sp')]='softplus_sp', sparsity: float=0.9):
super().__init__()
self.px_d... |
def build_plugin_layer(cfg, postfix='', **kwargs):
if (not isinstance(cfg, dict)):
raise TypeError('cfg must be a dict')
if ('type' not in cfg):
raise KeyError('the cfg dict must contain the key "type"')
cfg_ = cfg.copy()
layer_type = cfg_.pop('type')
if (layer_type not in PLUGIN_LAY... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.