code stringlengths 101 5.91M |
|---|
_utils.test(debug=True)
def test_adjoint_checkbit_place_grad():
x = ti.field(float)
y = ti.field(float)
ti.root.place(x, x.grad, y)
def test():
x[None] = 1
with ti.ad.Tape(loss=x, validation=True):
test()
assert x.snode.ptr.has_adjoint_checkbit()
assert (not y.snode.ptr.has_a... |
class ArcSoftmax(Linear):
def forward(self, logits, targets):
index = torch.where((targets != (- 1)))[0]
m_hot = torch.zeros(index.size()[0], logits.size()[1], device=logits.device, dtype=logits.dtype)
m_hot.scatter_(1, targets[(index, None)], self.m)
logits.acos_()
logits[in... |
def test_inlinepp_in_unroll():
ctr = 11
def stateful(i):
nonlocal ctr
ctr += 1
return (ctr + i)
def tester(a: dace.float64[3]):
for i in dace.unroll(range(3)):
a[i] = dace.inline(stateful(i))
sdfg = tester.to_sdfg()
assert _find_in_tasklet(sdfg, '12')
... |
def load_vocabulary(fn):
vocabulary = set()
with open(fn) as f:
for line in f:
vocabulary.add(line.strip())
return vocabulary |
.parametrize('dtype, storage_format', [(ti.f32, 'col_major'), (ti.f32, 'row_major'), (ti.f64, 'col_major'), (ti.f64, 'row_major')])
_utils.test(arch=ti.cpu)
def test_sparse_matrix_builder(dtype, storage_format):
n = 8
Abuilder = ti.linalg.SparseMatrixBuilder(n, n, max_num_triplets=100, dtype=dtype, storage_form... |
class TrainState(object):
def __init__(self, optimizer, lr_scheduler, step, nnet=None, nnet_ema=None):
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
self.step = step
self.nnet = nnet
self.nnet_ema = nnet_ema
def ema_update(self, rate=0.9999):
if (sel... |
_model
def tresnet_l_448(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
default_cfg = default_cfgs['tresnet_l_448']
model = TResNet(layers=[4, 5, 18, 3], num_classes=num_classes, in_chans=in_chans, width_factor=1.2, **kwargs)
model.default_cfg = default_cfg
if pretrained:
load_pretra... |
def relaxed_average(var_name_suffix, rx_step):
relaxed_vars = []
for l in xrange(rx_step):
with tf.variable_scope(('RX%d' % l), reuse=True):
try:
relaxed_vars.append(tf.get_variable(var_name_suffix))
except ValueError:
pass
dsum = tf.add_n(rela... |
class Inception(nn.Module):
def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes):
super(Inception, self).__init__()
self.b1 = nn.Sequential(nn.Conv2d(in_planes, n1x1, kernel_size=1), nn.BatchNorm2d(n1x1), Elliott())
self.b2 = nn.Sequential(nn.Conv2d(in_planes, n3x3r... |
def swap_word(new_words):
random_idx_1 = random.randint(0, (len(new_words) - 1))
random_idx_2 = random_idx_1
counter = 0
while (random_idx_2 == random_idx_1):
random_idx_2 = random.randint(0, (len(new_words) - 1))
counter += 1
if (counter > 3):
return new_words
(n... |
class EFDTInactiveLearningNodeMC(InactiveLearningNodeMC):
def __init__(self, initial_stats=None):
super().__init__(initial_stats)
def count_nodes():
return np.array([0, 1]) |
class SegmentMap(object):
def __init__(self):
self.map_entries = []
def load(self, path):
open_fun = (gzip.open if path.endswith('.gz') else open)
with open_fun(path, 'rb') as f:
for (event, elem) in ET.iterparse(f, events=('start',)):
if (elem.tag == 'map-ite... |
class IdentityMessage(torch.nn.Module):
def __init__(self, raw_msg_dim: int, memory_dim: int, time_dim: int):
super().__init__()
self.out_channels = ((raw_msg_dim + (2 * memory_dim)) + time_dim)
def forward(self, z_src: Tensor, z_dst: Tensor, raw_msg: Tensor, t_enc: Tensor):
return torch... |
def test_get_init_seq_string_seed_lowercase(esm_sampler_fixture):
sampler = esm_sampler_fixture
out = sampler.get_init_seq('aa', 5, 1)
expected = [[32, 5, 5, 33, 33, 33]]
assert (out.tolist() == expected) |
def text(string):
if isinstance(string, Doc):
return string
if isinstance(string, str):
return _Text(string)
return prepr(string) |
class Generator(object):
__metaclass__ = ABCMeta
def init_history(self):
pass
def get_next(self, history):
pass
def stop_or_not(self, history):
pass
def max_context_size(self):
raise NotImplementedError
def truncate_history(self, history):
if (len(history)... |
def collect_hidden_states(trained_model, data: List[str], word2vec, i2p, pr=None):
trained_model.eval()
states = []
labels = []
inputs = []
outputs = []
genders = []
dataset = Dataset(data, word2vec)
gen = torch.utils.data.DataLoader(dataset, batch_size=1, drop_last=False, shuffle=False)... |
_torch
class EfficientFormerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = ((EfficientFormerModel, EfficientFormerForImageClassificationWithTeacher, EfficientFormerForImageClassification) if is_torch_available() else ())
pipeline_model_mapping = ({'feature-extraction': ... |
def validate_arguments(func, args, kwargs, drop_extra=True):
parser = _parse_signature(func)
(args, kwargs, missing, extra, extra_positional) = parser(args, kwargs)[:5]
if missing:
raise ArgumentValidationError(tuple(missing))
elif ((extra or extra_positional) and (not drop_extra)):
rais... |
def traverse_net(max_node):
aa_nas_bench_ss = get_search_spaces('cell', 'nats-bench')
archs = CellStructure.gen_all(aa_nas_bench_ss, max_node, False)
print('There are {:} archs vs {:}.'.format(len(archs), (len(aa_nas_bench_ss) ** (((max_node - 1) * max_node) / 2))))
random.seed(88)
random.shuffle(ar... |
class ConvRNNBlock(nn.Module):
def __init__(self, batch_size, in_channels, shape, num_filter, kernel_size):
super(ConvRNNBlock, self).__init__()
self.conv_rnn = ConvRNN(in_channels, shape, num_filter, kernel_size)
self.conv = TimeDistributed(nn.Conv2d((2 * num_filter), num_filter, kernel_siz... |
_args('v', 'v', 'v', 'is', 'is', 'is', 'i')
def conv3d(g, input, weight, bias, stride, padding, dilation, groups):
return _convolution(g, input, weight, bias, stride, padding, dilation, False, (), groups, None, None, None, None) |
def _skip_pytest_case_requiring_pooch(data_filename):
if ('PYTEST_CURRENT_TEST' in os.environ):
import pytest
pytest.skip(f'Unable to download {data_filename}', allow_module_level=True) |
()
def plus_test_with_type_name_assertion() -> tc.TestCase:
cluster = generate_test_cluster('tests.fixtures.linecoverage.plus')
transformer = AstToTestCaseTransformer(cluster, False, EmptyConstantProvider())
transformer.visit(ast.parse('def test_case_0():\n int_0 = 42\n plus_0 = module_0.Plus()\n i... |
def _subset_has_indirection(subset, pvisitor: 'ProgramVisitor'=None):
for dim in subset:
if (not isinstance(dim, tuple)):
dim = [dim]
for r in dim:
if (not symbolic.issymbolic(r)):
continue
if symbolic.contains_sympy_functions(r):
r... |
class GenieModelForClassification(GenieModel):
def _init_common(self, args, tasks, **kwargs):
self.args = args
num_labels = 0
if (args.num_labels is not None):
num_labels = args.num_labels
else:
for task in tasks:
if hasattr(task, 'num_labels')... |
def get_tables_with_alias(schema, toks):
tables = scan_alias(toks)
for key in schema:
assert (key not in tables), 'Alias {} has the same name in table'.format(key)
tables[key] = key
return tables |
def main(args):
inpFile = args.src
output_File = args.dst
f = open(inpFile)
lines = f.readlines()
f.close()
nLines = len(lines)
cur = 0
data = dict()
while (cur < nLines):
line = lines[cur].rstrip()
components = line.split(' ')
obj = {}
if (components[... |
def _rev_from_version(version):
p = version.rfind('-')
if (p < 0):
_simple_validate_commit_rev(version)
return version
rev = version[(p + 1):]
_simple_validate_commit_rev(rev)
return rev |
class CDF(MutableMapping, spacepy.datamodel.MetaMixin):
backward = False
def __init__(self, pathname, masterpath=None, create=None, readonly=None, encoding='utf-8'):
if (masterpath is not None):
if (create is False):
raise ValueError('Cannot specify a master CDF without creat... |
def argparser():
parser = argparse.ArgumentParser(description='PyTorch Handwriting Synthesis Model')
parser.add_argument('--hidden_size', type=int, default=400)
parser.add_argument('--n_layers', type=int, default=3)
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--ste... |
class BiFPN(Backbone):
def __init__(self, bottom_up, in_features, out_channels, num_top_levels, num_repeats, norm=''):
super(BiFPN, self).__init__()
assert isinstance(bottom_up, Backbone)
self.bottom_up = BackboneWithTopLevels(bottom_up, out_channels, num_top_levels, norm)
bottom_up_... |
def remove_ignore_keys_(state_dict):
ignore_keys = ['decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'decoder.embed_positions._float_tensor']
for k in ignore_keys:
state_dict.pop(k, None) |
class BetaPrime(ReferenceDistribution):
def __init__(self, *, a, b):
super().__init__(a=a, b=b)
def _support(self, **kwargs):
return (mp.zero, mp.inf)
def _logpdf(self, x, a, b):
return ((((a - mp.one) * mp.log(x)) - ((a + b) * mp.log1p(x))) - mp.log(mp.beta(a, b)))
def _pdf(self... |
def GenCircle(tspec, *args):
if (tspec == PUNGraph):
return GenCircle_PUNGraph(*args)
if (tspec == PUndirNet):
return GenCircle_PUndirNet(*args)
if (tspec == PDirNet):
return GenCircle_PDirNet(*args)
if (tspec == PNGraph):
return GenCircle_PNGraph(*args)
if (tspec == ... |
def download_pretrained_model(model_name, *args, **kwargs):
import omegaconf
from mmf.utils.configuration import get_mmf_env, load_yaml
from omegaconf import OmegaConf
model_zoo = load_yaml(get_mmf_env(key='model_zoo'))
OmegaConf.set_struct(model_zoo, True)
OmegaConf.set_readonly(model_zoo, True... |
def _get_edge_loc_dp(x: List[float], min_feature: float=0) -> np.ndarray:
func = (lambda a, b: ((a - b) ** 2))
max_val = len(x)
divisions = 5
max_k = ((divisions * len(x)) + 1)
x = np.array(x)
zero_value = np.cumsum(func(x, 0))
one_value = np.cumsum(func(x, 1))
zero_value = ([0] + zero_v... |
class LSTM(object):
def __init__(self, config, inputs, labels, lengths, infer=False):
self._inputs = inputs
self._labels = labels
self._lengths = lengths
self._model_type = config.model_type
if infer:
config.batch_size = 1
outputs = self._inputs
wi... |
def group_df_by_time(tdf, freq_str='1D', offset_value=0, offset_unit='hours', add_starting_location=False, dtformat='%Y-%m-%d %H:%M:%S'):
df = tdf.sort_values([constants.DATETIME])
offset = pd.Timedelta(offset_value, offset_unit)
t_init = pd.to_datetime(df[constants.DATETIME].min().date())
t_end = (pd.t... |
class Encoder(nn.Module):
def __init__(self, input_resolutions: List[List[int]], latent_size: int, activation: str):
super(Encoder, self).__init__()
self._input_resolutions = input_resolutions
self._latent_size = latent_size
self._activation = activation
def build(self):
... |
class ErnieMLMCriterion(paddle.nn.Layer):
def __init__(self):
super(ErnieMLMCriterion, self).__init__()
def forward(self, prediction_scores, masked_lm_labels, masked_lm_scale=1.0, weights=None):
masked_lm_labels = paddle.reshape(masked_lm_labels, shape=[(- 1), 1])
with paddle.static.amp.... |
class TestDSWrapperAndDSModier():
def test_initialization(self):
output_path = os.path.join(base_ds, (ds_name + '#{}'.format(modifier_name)))
output_images_path = os.path.join(output_path, 'images')
ds_wrapper = DSWrapper(data_path=data_path)
assert (ds_wrapper.data_path == data_path... |
def _stft(y):
if hp.use_lws:
return _lws_processor(hp).stft(y).T
else:
return librosa.stft(y=y, n_fft=hp.n_fft, hop_length=get_hop_size(), win_length=hp.win_size) |
def generate_graph_args_builder(graph: sr.Graph) -> List[str]:
out = []
out += [f'struct ComputeGraph_{graph.name} : public ti::ComputeGraph {{', f' explicit ComputeGraph_{graph.name}(TiRuntime runtime, TiComputeGraph graph) :', ' ti::ComputeGraph(runtime, graph) {', f' args_.resize({len(graph.args)});',... |
class StmtBuilder(Builder):
augassign_map = {ast.Add: '+', ast.Sub: '-', ast.Mult: '*', ast.Div: '/', ast.Mod: '%'}
def build_Expr(ctx, stmt):
value = stmt.value
if (value.__class__.__name__ == 'Str'):
return None
else:
return ExprStmt(build_expr(ctx, value))
... |
class PositionalEncoding(torch.nn.Module):
def __init__(self, num_freqs=6, d_in=3, freq_factor=np.pi, include_input=True):
super().__init__()
self.num_freqs = num_freqs
self.d_in = d_in
self.freqs = (freq_factor * (2.0 ** torch.arange(0, num_freqs)))
self.d_out = ((self.num_f... |
class SAGE(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, num_layers, dropout):
super(SAGE, self).__init__()
self.convs = torch.nn.ModuleList()
self.convs.append(SAGEConv(in_channels, hidden_channels))
for _ in range((num_layers - 2)):
se... |
def simulate_from_network_attr(arclist_filename, param_func_list, labels, theta, binattr_filename=None, contattr_filename=None, catattr_filename=None, sampler_func=basicALAAMsampler, numSamples=100, iterationInStep=None, burnIn=None):
assert (len(param_func_list) == len(labels))
G = Graph(arclist_filename, bina... |
def test_the_cat_api_evaluator():
label = "curl -X GET '
context_dir = f'data/the_cat_api/v0'
generator = RagGenerator(client_name='openai', model_name='text-curie-001', context_dir=context_dir, max_output_token=256, top_k_api=3, top_k_example=3, query_template='Task: {query} (Answer in code only)\nActions:... |
def evaluate(in_channels, out_channels, kernel_size, data_shape: tuple, input_to_constant: bool, execute_cpu_dace: bool=False, queue=None):
ptmodel = Model(in_channels, out_channels, kernel_size, input_to_constant)
x = torch.rand(data_shape)
torch_output = ptmodel(x)
dace_model = DaceModule(ptmodel, dum... |
class OpTreeValue(OpTreeLeafBase):
def __init__(self, value: float) -> None:
self.value = value
def __str__(self) -> str:
return str(self.value)
def __eq__(self, other) -> bool:
if isinstance(other, OpTreeValue):
return (self.value == other.value)
def copy(self):
... |
_module()
class TransferalPerceptualLoss(nn.Module):
def __init__(self, loss_weight=1.0, use_attention=True, criterion='mse'):
super().__init__()
self.use_attention = use_attention
self.loss_weight = loss_weight
criterion = criterion.lower()
if (criterion == 'l1'):
... |
def random_color_jitter(image, p=1.0, impl='simclrv2'):
def _transform(image):
color_jitter_t = functools.partial(color_jitter, strength=0.2, impl=impl)
image = random_apply(color_jitter_t, p=0.8, x=image)
return random_apply(to_grayscale, p=0.2, x=image)
return random_apply(_transform, ... |
class NonNeg(Constraint):
def __call__(self, w):
w *= K.cast(K.greater_equal(w, 0.0), K.floatx())
return w |
def prepare_env(cfg):
fix_random_seed(cfg.BASIC.SEED)
cudnn.benchmark = cfg.CUDNN.BENCHMARK
cudnn.deterministic = cfg.CUDNN.DETERMINISTIC
cudnn.enabled = cfg.CUDNN.ENABLE
if cfg.BASIC.BACKUP_CODES:
backup_dir = os.path.join(cfg.BASIC.SAVE_DIR, 'backup')
rm(backup_dir)
backup_... |
_datapipe('_dataframes_shuffle', enable_df_api_tracing=True)
class ShuffleDataFramesPipe(DFIterDataPipe):
def __init__(self, source_datapipe):
self.source_datapipe = source_datapipe
if (not WITH_PANDAS):
Exception('DataFrames prototype requires pandas to function')
def __iter__(self)... |
class DecoderLayer(nn.Module):
def __init__(self, d_model, heads, dropout=0.1):
super().__init__()
self.norm_1 = Norm(d_model)
self.norm_2 = Norm(d_model)
self.norm_3 = Norm(d_model)
self.dropout_1 = nn.Dropout(dropout)
self.dropout_2 = nn.Dropout(dropout)
sel... |
class Doctype(object):
def __init__(self, root_node, name, public_id, system_id):
self.root_node = root_node
self.name = name
self.public_id = public_id
self.system_id = system_id
self.text = None
self.tail = None
def getnext(self):
return self.root_node.c... |
class ClapTextConfig(PretrainedConfig):
model_type = 'clap_text_model'
def __init__(self, vocab_size=50265, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=514, type_vocab... |
def GetQuasiSequenceOrder1(ProteinSequence, maxlag=30, weight=0.1, distancematrix={}):
rightpart = 0.0
for i in range(maxlag):
rightpart = (rightpart + GetSequenceOrderCouplingNumber(ProteinSequence, (i + 1), distancematrix))
AAC = GetAAComposition(ProteinSequence)
result = {}
temp = (1 + (w... |
class ManualConvLinearQATModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.qconfig = torch.quantization.get_default_qat_qconfig('qnnpack')
self.quant = QuantStub()
self.dequant = DeQuantStub()
self.conv = torch.nn.Conv2d(3, 1, kernel_size=3).to(dtype=torch.f... |
def load_result(filename_list):
predict_dict = {}
gt_dict = {}
for i in range(len(filename_list)):
f = open(filename_list[i], 'r')
idx = re.findall('\\d+', filename_list[i])
id_map_dict = load_id_mapping(['../Data_process/Trivia_dataset/trivia_title_cont.tsv'], int(idx[0]))
f... |
def saturation(A, proof=True, p=0, max_dets=5):
r = A.rank()
if (A.is_square() and (r == A.nrows())):
return identity_matrix(ZZ, r)
if (A.nrows() > r):
P = []
while (len(P) < r):
P = matrix_integer_dense_hnf.probable_pivot_rows(A)
A = A.matrix_from_rows(P)
A =... |
def aggregate_similarity(similarity_matrix_chunk, aggregation_method='mean'):
if (aggregation_method == 'max'):
return similarity_matrix_chunk.max(dim=1)[0]
elif (aggregation_method == 'sum'):
return similarity_matrix_chunk.sum(dim=1)
elif (aggregation_method == 'mean'):
return simil... |
def labeled_comprehension(input, labels, index, func, out_dtype, default, pass_positions=False):
as_scalar = numpy.isscalar(index)
input = numpy.asarray(input)
if pass_positions:
positions = numpy.arange(input.size).reshape(input.shape)
if (labels is None):
if (index is not None):
... |
.operations('failure')
def test_explicit_example_failure_output(testdir, cli, openapi3_base_url, snapshot_cli):
schema = {'openapi': '3.0.0', 'info': {'title': 'Sample API', 'description': 'API description in Markdown.', 'version': '1.0.0'}, 'paths': {'/failure': {'get': {'parameters': [{'in': 'query', 'name': 'key... |
def ll_heuristic(d):
d = copy(d)
I = d['I']
if (('llfirstonthefly' not in d) and ('llfirst' not in d)):
hint = ll_is_good(I)
if hint:
d[hint] = True
return d |
def test_write_statistics_no_backend():
config.configuration.statistics_output.statistics_backend = None
statistics = stat._SearchStatistics()
assert (not statistics.write_statistics()) |
def test_get_tasks(collaborator_mock):
results = (['task_name'], 0, 0, True)
collaborator_mock.client.get_tasks = mock.Mock(return_value=results)
(tasks, round_number, sleep_time, time_to_quit) = collaborator_mock.get_tasks()
assert (results == (tasks, round_number, sleep_time, time_to_quit)) |
class WarmMultiStepLR(lr_scheduler.MultiStepLR):
def __init__(self, optimizer, milestones, gamma=0.1, last_epoch=(- 1), linear=1, warmup=5):
self.linear = max(linear, 1)
self.warmup = warmup
super().__init__(optimizer, milestones, gamma=gamma, last_epoch=last_epoch)
def get_lr(self):
... |
def find_sublist(a, b):
for l in range(len(a)):
if (a[l:(l + len(b))] == b):
return l
return None |
class YouRM(dspy.Retrieve):
def __init__(self, ydc_api_key=None, k=3):
super().__init__(k=k)
if ((not ydc_api_key) and (not os.environ.get('YDC_API_KEY'))):
raise RuntimeError('You must supply ydc_api_key or set environment variable YDC_API_KEY')
elif ydc_api_key:
sel... |
class UnmaskedLookup(ContentLookup):
CONTENT = 0
def tolookup(cls, layout, positions):
pos = len(positions)
positions.append(None)
positions[(pos + cls.CONTENT)] = tolookup(layout.content, positions)
return pos
def tolayout(self, lookup, pos, fields):
content = self.c... |
def make_pca_scorers(caller):
caller.train_scorer = (lambda _, __: caller.estimator.explained_variance_ratio_.sum())
caller.test_scorer = (lambda _, __: explained_variance_ratio(caller.estimator.transform(caller.X_val), caller.X_val)) |
_utils.test(debug=True)
def test_assign_chained_involve_self():
def foo():
a = 1
b = 1
a = b = (a + b)
assert (a == 2)
assert (b == 2)
foo() |
class NPA(nn.Module):
def __init__(self, input_dim=128, hidden_dim=128, attn_dim=256, fc_dim=512, num_layers=1, question_num=QUESTION_NUM[ARGS.dataset_name], dropout=0.0):
super().__init__()
self._hidden_dim = hidden_dim
self._num_layers = num_layers
self._question_num = question_num... |
class AlignedBottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, base_width=64, cardinality=1, stride=1, dilation=1, radix=1, downsample=None, stride_3x3=False, conv='Conv2d', norm='BN', ctx=''):
super(AlignedBottleneck, self).__init__()
D = int(math.floor((planes * (base_w... |
class BaseDataset(Dataset):
def __init__(self, root_path='', transform=None, target_transform=None, stage='train'):
super(BaseDataset, self).__init__()
self.root_path = root_path
self.transform = transform
self.target_transform = target_transform
self.stage = stage
se... |
def test_illegal_batch_size(foundation_cache):
stanza.Pipeline('en', model_dir=TEST_MODELS_DIR, processors='tokenize,pos', constituency_batch_size='zzz', foundation_cache=foundation_cache)
with pytest.raises(ValueError):
stanza.Pipeline('en', model_dir=TEST_MODELS_DIR, processors='tokenize,pos,constitue... |
class DataModuleFromConfig(pl.LightningDataModule):
def __init__(self, batch_size, train=None, validation=None, test=None, predict=None, wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False, shuffle_val_dataloader=False):
super().__init__()
self.batch_size = batch_size
... |
def skeleton_discovery(data, alpha, indep_test, stable=True, background_knowledge=None, verbose=False, show_progress=True):
assert (type(data) == np.ndarray)
assert (0 < alpha < 1)
no_of_var = data.shape[1]
cg = CausalGraph(no_of_var)
cg.set_ind_test(indep_test)
cg.data_hash_key = hash(str(data)... |
class SawyerReachWallV2Policy(Policy):
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'puck_pos': obs[3:6], 'goal_pos': obs[9:], 'unused_info': obs[6:9]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})
action... |
class ModelCatalogHandler(PathHandler):
PREFIX = 'catalog://'
def _get_supported_prefixes(self):
return [self.PREFIX]
def _get_local_path(self, path):
logger = logging.getLogger(__name__)
catalog_path = ModelCatalog.get(path[len(self.PREFIX):])
logger.info('Catalog entry {} p... |
class MyDataset(data.Dataset):
def __init__(self, images, labels, ids, timestep):
self.images = images
self.labels = labels
self.ids = ids
self.timestep = timestep
def __getitem__(self, index):
(img, target) = (self.images[index], self.labels[index])
return (img, ... |
def pos_reg(w, lambda_pos, filter_len):
location_lambda = (K.cast(K.concatenate([K.arange((filter_len / 2), stop=0, step=(- 1)), K.arange(start=1, stop=((filter_len / 2) + 1))]), 'float32') * (lambda_pos / (filter_len / 2)))
location_penalty = K.sum((location_lambda * K.sum(K.abs(w), axis=(0, 2, 3))))
retur... |
class PolymakeAbstract(ExtraTabCompletion, Interface):
def __init__(self, seed=None):
Interface.__init__(self, 'polymake')
self._seed = seed
self.__tab_completion = {}
_method
def version(self):
return self.get('$Polymake::Version')
def __reduce__(self):
return (r... |
def lambda_B_calc(classes, table, TOP, POP):
try:
result = 0
length = POP
maxresponse = max(list(TOP.values()))
for i in classes:
result += max(list(table[i].values()))
result = ((result - maxresponse) / (length - maxresponse))
return result
except Exc... |
def read_text(file: Path) -> str:
src_file = ('-'.join(str(file).split('-')[:(- 1)]) + '.trans.txt')
idx = file.stem.replace('.flac', '')
with open(src_file, 'r') as fp:
for line in fp:
if (idx == line.split(' ')[0]):
return line[:(- 1)].split(' ', 1)[1]
logger.warnin... |
class Wav2Vec2ConformerConfig(PretrainedConfig):
model_type = 'wav2vec2-conformer'
def __init__(self, vocab_size=None, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout=0.1, activation_dropout=0.1, attention_dropout=0.1, feat_proj_dropout=0.... |
_model
def selecsls60(pretrained=False, **kwargs):
return _create_model('selecsls60', pretrained, kwargs) |
class EmitGemmUniversalInstance3x():
def __init__(self, operation_suffix=''):
self.operation_suffix = operation_suffix
self.includes = ['cutlass/cutlass.h', 'cute/tensor.hpp', 'cute/atom/mma_atom.hpp', 'cutlass/numeric_types.h', 'cutlass/gemm/kernel/gemm_universal.hpp', 'cutlass/gemm/collective/coll... |
_spec_function('synthetic_efficiency')
def get_synthetic_efficiency_spec(num_prompt_tokens: Optional[int]=None, num_output_tokens: Optional[int]=None, tokenizer: Optional[str]=None, random: Optional[str]=None) -> RunSpec:
scenario_spec = ScenarioSpec(class_name='helm.benchmark.scenarios.synthetic_efficiency_scenari... |
class _MeshHandler():
def __init__(self, db: database.Database, form_handler: _forms.ShapeFormHandler, a_priori_tester: mesh_testing.APrioriMeshTester, a_posteriori_tester: mesh_testing.IntersectionTester) -> None:
self.db = weakref.proxy(db)
self.form_handler = form_handler
self.a_priori_te... |
def get_span_mask(start_ids, end_ids, max_len):
tmp = torch.arange(max_len, device=start_ids.device).unsqueeze(0).expand(start_ids.shape[0], (- 1))
batch_start_ids = start_ids.unsqueeze(1).expand_as(tmp)
batch_end_ids = end_ids.unsqueeze(1).expand_as(tmp)
mask = ((tmp >= batch_start_ids).float() * (tmp ... |
def getname(sent):
mid_sent = []
for word in sent.split():
mid_sent.extend(cln_word(word))
curr_name = 'Someone'
other_name = 'Someone'
for word in mid_sent:
arr = re.findall('\\w*:\\w*', word)
if (len(arr) == 1):
curr_name = getspe(word)
other_name = ... |
class HalfCauchy(TransformedDistribution):
arg_constraints = {'scale': constraints.positive}
support = constraints.positive
has_rsample = True
def __init__(self, scale, validate_args=None):
super(HalfCauchy, self).__init__(Cauchy(0, scale), AbsTransform(), validate_args=validate_args)
def sc... |
def dense_bn_relu(units):
return tf.keras.Sequential([tf.keras.layers.Dense(units, use_bias=False, kernel_regularizer=tf.keras.regularizers.l2(0.0001)), tf.keras.layers.BatchNormalization(center=True, scale=True), tf.keras.layers.ReLU()]) |
def _list_with_default(out_size: List[int], defaults: List[int]) -> List[int]:
if isinstance(out_size, int):
return out_size
if (len(defaults) <= len(out_size)):
raise ValueError('Input dimension should be at least {}'.format((len(out_size) + 1)))
return [(v if (v is not None) else d) for (v... |
def test_record_dict_1():
text = '{"1": int64}'
parsedtype = ak.types.from_datashape(text, highlevel=False)
assert isinstance(parsedtype, ak.types.RecordType)
assert (str(parsedtype) == text) |
def time_it(func):
def wrapper(*args, **kwargs):
start = time.time()
print(f'Start {func.__name__}')
output = func(*args, **kwargs)
end = time.time()
print(f'End {func.__name__}. Elapsed {(end - start)} seconds')
return output
return wrapper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.