code stringlengths 101 5.91M |
|---|
class LayeredModel(ModelBase, metaclass=AutodocABCMeta):
config_class = LayeredModelConfig
def __new__(cls, config: LayeredModelConfig=None, model: ModelBase=None, **kwargs):
original_cls = cls
config = cls._resolve_args(config=config, model=model, **kwargs)
if isinstance(config.model, F... |
('/direct')
def direct():
pattern = request.args.get('pattern')
regex = re.compile(pattern)
return regex.search(text) |
_utils.test()
def test_break_in_static_for_in_non_static_if():
def test_static_loop():
for i in ti.static(range(5)):
x = 0.1
if (x == 0.0):
break
with pytest.raises(ti.TaichiSyntaxError, match='You are trying to `break` a static `for` loop'):
test_static_l... |
def B2Q(uchar):
inside_code = ord(uchar)
if ((inside_code < 32) or (inside_code > 126)):
return uchar
if (inside_code == 32):
inside_code = 12288
else:
inside_code += 65248
return chr(inside_code) |
def test_eval_old_in_new():
param = parametrization.DirectParam((3, 2))
x = problem.Variable(2)
obj = (OldPower(x[0], 2) + x[0])
assert (graph_executor.eval_fun(obj, param) == 12)
np.testing.assert_array_equal(graph_executor.eval_grad(obj, param), [7, 0]) |
class ConformerBlock(nn.Module):
def __init__(self, *, dim, dim_head=64, heads=8, ff_mult=4, conv_expansion_factor=2, conv_kernel_size=31, attn_dropout=0.0, ff_dropout=0.0, conv_dropout=0.0):
super().__init__()
self.ff1 = FeedForward(dim=dim, mult=ff_mult, dropout=ff_dropout)
self.attn = Att... |
def shuffle_choices(x):
choices = sorted([k for k in x if ('choice' in k)])
choices_texts = [x[c] for c in choices]
correct_choice = choices_texts[x['labels']]
random.shuffle(choices_texts)
for (c, ct) in zip(choices, choices_texts):
x[c] = ct
x['labels'] = choices_texts.index(correct_ch... |
def _nntxt_file_loader(ctx, file_loaders, nnp, filename, ext):
if (not ctx.parameter_only):
with get_file_handle_load(nnp, filename, ext) as f:
try:
text_format.Merge(f.read(), ctx.proto)
except:
logger.critical('Failed to read {}.'.format(filename))
... |
def convert_example_to_features(example, max_seq_length, tokenizer, mlm_loss):
tokens_a = example.tokens_a[:max_seq_length]
raw_label = example.raw_label
col_ids = [i for (i, x) in enumerate(tokens_a) if (x == SEP_TOKEN)][:(- 1)]
if (len(col_ids) != len(raw_label)):
print('tokens_a: ', tokens_a)... |
def node_to_text(test, f):
(result, name, reason, time_real) = read_test(test)
if reason:
reason = (' (%s)' % reason)
output = ('%s: Test Suite "%s" (%s)%s\n' % (result, name, time_real, reason))
f.write(output)
for details in test.findall('FailureDetails'):
f.write(' Details:\n')... |
def test_get_max_value_key():
a_dictionary = {1: 10, 2: (- 10), 3: 1000, 4: 100, 5: 1}
key_max = get_max_value_key(a_dictionary)
assert (key_max == 3) |
def parse_code_example(code_lines):
has_doctest = (code_lines[0][:3] in DOCTEST_PROMPTS)
code_samples = []
outputs = []
in_code = True
current_bit = []
for line in code_lines:
if (in_code and has_doctest and (not is_empty_line(line)) and (line[:3] not in DOCTEST_PROMPTS)):
co... |
def unstack_state_dict(state_dict: StateDict, prefix: Optional[str]=None) -> StateDict:
new_dict: StateDict = {}
prefix = apply_prefix(prefix, '')
assert (prefix is not None)
for (k, v) in state_dict.items():
if (k.startswith(prefix) and (v is not None)):
for (i, v_i) in enumerate(v)... |
class AdditiveBlockFunction2(torch.autograd.Function):
def forward(ctx, xin, Fm, Gm, *weights):
assert ((xin.shape[1] % 2) == 0)
ctx.Fm = Fm
ctx.Gm = Gm
with torch.no_grad():
x = xin.detach()
(x1, x2) = torch.chunk(x, 2, dim=1)
(x1, x2) = (x1.conti... |
def dump_current_scores_of_devtest(args, m, xp):
for mode in ['dev', 'test']:
if (mode == 'dev'):
current_data = dev_data
if (mode == 'test'):
current_data = test_data
(scores, accuracy) = (list(), list())
for batch in chunked(current_data, args.test_batch_siz... |
def create_feature_columns() -> Tuple[(list, list, list)]:
(category_feature_columns, dense_feature_columns) = ([], [])
label_feature_columns = []
videoplayseconds = fc.numeric_column('videoplayseconds', default_value=0.0)
u_read_comment_7d_sum = fc.numeric_column('u_read_comment_7d_sum', default_value=... |
def compute_on_dataset(model, data_loader, device, timer=None):
model.eval()
results_dict = {}
cpu_device = torch.device('cpu')
for (_, batch) in enumerate(tqdm(data_loader)):
(images, targets, image_ids) = batch
with torch.no_grad():
if timer:
timer.tic()
... |
class FCOSFPN(nn.Module):
def __init__(self, in_channels=[512, 1024, 2048], out_channels=256):
super(FCOSFPN, self).__init__()
self.prj_3 = nn.Conv2d(in_channels[0], out_channels, kernel_size=1)
self.prj_4 = nn.Conv2d(in_channels[1], out_channels, kernel_size=1)
self.prj_5 = nn.Conv2... |
def add_cb_config(parser):
parser.add_argument('--cb_dimension', default='2D', type=str, choices=('1D', '2D', '6D'), help='Select which dimension to visualize for convergence basin.\n')
parser.add_argument('--save_img', action='store_true', help='Save visualizations.\n')
parser.add_argument('--reset_cb', ac... |
class TransformStack(InvertibleTransformBase):
def __init__(self, transforms, *, check_aligned=True):
super().__init__()
self.transforms = []
for t in transforms:
assert isinstance(t, (TransformBase, dict)), f'Expected all transforms to be instances of TransformBase, or dict, but... |
def resolve_includes(source):
d = os.path.dirname(source)
with open(source) as fid:
lines = []
for line in fid:
m = include_src_re.match(line)
if m:
fn = m.group('name')
if (not os.path.isabs(fn)):
fn = os.path.join(d, f... |
def test_partial_fstring():
N = 5
def fprog_partial():
with dace.tasklet:
i = 2
printf(f'''hi {N} {i}
''')
fprog_partial() |
def get_activations(image_iterator, images, model, verbose=True):
model.eval()
if (not sys.stdout.isatty()):
verbose = False
pred_arr = np.empty((images, FEATURE_DIM))
end = 0
t0 = time.time()
for batch in image_iterator:
if (not isinstance(batch, torch.Tensor)):
batc... |
class Partition1(nn.Module):
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[5]/BertIntermediate[intermediate]/Linear[dense]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[5]/BertOutput[output]/Linear[dense]', 'BertForQuestionAnswering/BertModel[b... |
def load_id_mapping(filename_list, i):
id_map_dict = {}
for filename in filename_list:
f = open(filename, 'r')
while True:
line = f.readline()
if (len(line) == 0):
break
slots = re.split('\\t', line)
old_id = slots[2]
ne... |
def get_device_for_rank(args, rank, local_rank):
nnodes = args.nnodes
ngpus_per_node = get_ngpus_per_node(args)
if hasattr(args, 'stage_to_device_map'):
stage_to_device_map = args.stage_to_device_map
cuda_device_id = stage_to_device_map[rank]
if (nnodes > 1):
for (node_id... |
def create_capsule_markers(marker_ref, oMg, d, l):
from copy import deepcopy
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point
displacment = pin.SE3.Identity()
displacment.translation[2] = (l / 2.0)
oMsphere_1 = (oMg * displacment)
displacment.translation[2] = ((-... |
def resize_and_convert(img, size, resample, quality=100):
img = trans_fn.resize(img, size, resample)
img = trans_fn.center_crop(img, size)
buffer = BytesIO()
img.save(buffer, format='jpeg', quality=quality)
val = buffer.getvalue()
return val |
class Attribute():
def __init__(self, id, subject, attribute, synset):
self.id = id
self.subject = subject
self.attribute = attribute
self.synset = synset
def __str__(self):
return ('%d: %s is %s' % (self.id, self.subject, self.attribute))
def __repr__(self):
... |
class Agent(object):
def feed_context(self, context):
pass
def read(self, inpt):
pass
def write(self):
pass
def choose(self):
pass
def update(self, agree, reward):
pass |
class Integral(Struct):
def __init__(self, name, order=1, coors=None, weights=None, bounds=None, tp_fix=1.0, weight_fix=1.0, symmetric=False):
self.name = name
self.qps = {}
if (coors is None):
self.mode = 'builtin'
else:
self.mode = 'custom'
self.... |
class Writer(object):
def __init__(self, t, location):
self.location = location
self.t = t
def write(self, string):
with self.t.location(*self.location):
sys.stdout.write('\x1b[K')
print(string)
def flush(self):
return |
def _indent_to_level(text: str, level: int) -> str:
return textwrap.indent(text, ((' ' * 4) * level)).lstrip() |
def _get_token_label(utt_char_range, start_char_pos, exclusive_end_char_pos):
end_char_pos = (exclusive_end_char_pos - 1)
slot_at_boundary = True
for (idx, (start, end)) in enumerate(utt_char_range):
if (start <= start_char_pos <= end):
if (start != start_char_pos):
slot_... |
class ParseRc(Action):
def __call__(self, parser, namespace, values, option_string=None):
pars = eval((('{' + values) + '}'))
setattr(namespace, self.dest, pars) |
def validate_point_inside_bounds(x, y, imWidth, imHeight):
if ((x < 0) or (x > imWidth)):
raise Exception(('X value (%s) not valid. Image dimensions: (%s,%s)' % (xmin, imWidth, imHeight)))
if ((y < 0) or (y > imHeight)):
raise Exception(('Y value (%s) not valid. Image dimensions: (%s,%s) Sample... |
def get_spline_knot_values(order):
knot_values = {0: [1], 1: [1], 2: [6, 1], 3: [4, 1], 4: [230, 76, 1], 5: [66, 26, 1]}
return knot_values[order] |
def pwdist_gauss(M1, S1, M2, S2, symmetric=False, return_dmeans=False, nworkers=1, commute=False):
(n1, n2) = (len(M1), len(M2))
if symmetric:
pairs = list(itertools.combinations(range(n1), 2))
else:
pairs = list(itertools.product(range(n1), range(n2)))
D = torch.zeros((n1, n2)).to(devic... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model_name_or_path', type=str, default='bert-base-multilingual-cased')
parser.add_argument('--pooler', type=str, choices=['cls', 'cls_before_pooler', 'avg', 'avg_top2', 'avg_first_last'], default='avg', help='Which pooler to use')
par... |
def eval_step(ood=False, n_evals=10):
model.eval()
total_loss = 0.0
total_acc = 0.0
with torch.no_grad():
for _ in range(n_evals):
(data, label) = data_call(args.batch_size, args.gt_rules, args.data_seed, ood)
data = torch.Tensor(data).to(device)
label = torch... |
def run_metrics(metricObject, args):
metricObject.compute_metrics_per_sequence(**args)
return metricObject |
def _save(f, verts, faces, verts_uv=None, map_file=None, rgb=None, idx=None, double_sided=True, decimal_places: Optional[int]=None):
if (decimal_places is None):
float_str = '%f'
else:
float_str = ('%' + ('.%df' % decimal_places))
lines = ''
(V, D) = verts.shape
for i in range(V):
... |
_module()
class CustomGaussianFocalLoss(nn.Module):
def __init__(self, alpha: float=(- 1), beta: float=4, gamma: float=2, sigmoid_clamp: float=0.0001, ignore_high_fp: float=(- 1.0), reduction='mean', loss_weight=1.0):
super(CustomGaussianFocalLoss, self).__init__()
self.alpha = alpha
self.be... |
def create_attack(attack: str, *args, **kwargs) -> Attack:
if (not any([(attack.lower() == attack_model.__name__.lower()) for attack_model in ATTACK_TYPE.__args__])):
raise ValueError(f'The attack {attack} is not in {ATTACK_TYPE.__args__}')
return globals()[attack](*args, **kwargs) |
def create_dirs(instructions, session_nums, object_names, re_extract):
if (instructions is None):
instructions = ['handoff', 'use']
else:
instructions = instructions.split(',')
if (session_nums is None):
n_sessions = len(dataset_utils.use_data_dirs)
session_nums = ['{:d}'.for... |
class GaussianPrior(Prior):
def __init__(self, size, mean=0, var=1, isotropic=True):
self.size = size
self.mean = mean
self.var = var
self.isotropic = isotropic
self.repr_init()
self.sigma = np.sqrt(var)
self.a = (1 / var)
self.b = (mean / var)
def... |
def is_invertible_module(module_in, test_input_shape, test_input_dtype=torch.float32, atol=1e-06, random_seed=42):
if isinstance(module_in, InvertibleModuleWrapper):
module_in = module_in._fn
if (not hasattr(module_in, 'inverse')):
return False
def _type_check_input_shape(test_input_shape):
... |
def get_option_reward(purchased_options, goal_options):
purchased_options = [normalize_color(o) for o in purchased_options]
goal_options = [normalize_color(o) for o in goal_options]
num_option_matches = 0
for g_option in goal_options:
for p_option in purchased_options:
score = fuzz.t... |
def get_cifar10(data_root, num_labeled, labeled_aug='weak', unlabeled_aug='strong', sample_mode='label_dist', whiten=True, incl_labeled_in_unlabeled=True):
base_dataset = datasets.CIFAR10(data_root, train=True, download=True)
if (num_labeled is None):
num_labeled = len(base_dataset)
if whiten:
... |
class _open_zipfile_reader(_opener):
def __init__(self, name_or_buffer) -> None:
super(_open_zipfile_reader, self).__init__(torch._C.PyTorchFileReader(name_or_buffer)) |
class _unsafe_first_element_pointer(object):
def __init__(self, arr):
self.base = arr
def __array_interface__(self):
i = dict(shape=(), typestr='|V0', data=(self.base.__array_interface__['data'][0], False), strides=(), version=3)
return i |
def pytest_collection_modifyitems(config, items):
if config.getoption('--remote'):
return
skipper = pytest.mark.skip(reason='need --remote option to run')
for item in items:
if ('remote' in item.keywords):
item.add_marker(skipper) |
(name='form_field')
def do_form_field(parser, token):
parts = token.contents.split(' ', 2)
if (len(parts) < 2):
error_text = '%r tag must have the form field name as the first value, followed by optional key="value" attributes.'
raise template.TemplateSyntaxError((error_text % parts[0]))
htm... |
def prepare_data(args, train, return_full_dataset=False):
if (args.root_dir is None):
args.root_dir = dataset_attributes[args.dataset]['root_dir']
if (args.shift_type == 'confounder'):
return prepare_confounder_data(args, train, return_full_dataset)
elif args.shift_type.startswith('label_shi... |
def write_original_conll(fn, conll_original):
with open(fn, 'w') as fh:
for sentence in conll_original:
for entry in sentence[1:]:
fh.write('\t'.join([str(entry.id), entry.form, '_', entry.cpos, entry.pos, '_', str(entry.parent_id), entry.relation, '_', '_']))
fh.... |
class RandomActiveLearningNodeNBA(LearningNodeNBA, RandomActiveLeafClass):
def __init__(self, initial_stats=None, max_features=2, random_state=None):
super().__init__(initial_stats)
self.max_features = max_features
self.feature_indices = np.array([])
self.random_state = random_state
... |
class TestEMAGPU(unittest.TestCase):
def assertTorchAllClose(self, x, y, atol=1e-08, rtol=1e-05, msg=None):
diff = (x.float() - y.float())
diff_norm = torch.norm(diff)
other_norm = torch.norm(y.float())
if (msg is None):
msg = '|input - other| > {} + {} * |other|'.format(... |
class Context(with_metaclass(ContextMeta)):
_legacy_resolve_mode = False
_fast_resolve_mode = False
def __init__(self, environment, parent, name, blocks):
self.parent = parent
self.vars = {}
self.environment = environment
self.eval_ctx = EvalContext(self.environment, name)
... |
class Identity(BaseFunction):
def tf(self, x):
return (tf.identity(x) / self.norm)
def sp(self, x):
return (x / self.norm)
def np(self, x):
return (np.array(x) / self.norm) |
def flat_lstm_cell(input, hx, cx, w_ih, w_hh, b_ih, b_hh):
gates = (((torch.mm(input, w_ih.t()) + torch.mm(hx, w_hh.t())) + b_ih) + b_hh)
(ingate, forgetgate, cellgate, outgate) = gates.chunk(4, 1)
ingate = torch.sigmoid(ingate)
forgetgate = torch.sigmoid(forgetgate)
cellgate = torch.tanh(cellgate)
... |
class TFAutoModelForCausalLM(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def evaluate(model, data):
model.eval()
with torch.no_grad():
logits = model(data)
outs = {}
for key in ['train', 'val', 'test']:
mask = data['{}_mask'.format(key)]
loss = F.nll_loss(logits[mask], data.y[mask]).item()
pred = logits[mask].max(1)[1]
acc = (pred.eq(d... |
class RandomPolicy(SerializablePolicy):
def __init__(self, action_space):
self.action_space = action_space
def get_action(self, *args, **kwargs):
return (self.action_space.sample(), {}) |
class BoundArguments(object):
def __init__(self, signature, arguments):
self.arguments = arguments
self._signature = signature
def signature(self):
return self._signature
def args(self):
args = []
for (param_name, param) in self._signature.parameters.items():
... |
_assert
class Operation(Node):
def __init__(self, opd_ids: List[str], op_type: OperationType, input_types: List[Type], output_types: List[Type], loc_label: LocLabel, attrs: Attributes=None, const: str=None) -> None:
super().__init__()
self.opd_ids = opd_ids
self.op_type = op_type
sel... |
class PerceptualLoss(nn.Module):
def __init__(self, recog_net, input_size=112):
super(PerceptualLoss, self).__init__()
self.recog_net = recog_net
self.preprocess = (lambda x: ((2 * x) - 1))
self.input_size = input_size
def forward(imageA, imageB, M):
imageA = self.preproc... |
class FogPassFilter_conv1(nn.Module):
def __init__(self, inputsize):
super(FogPassFilter_conv1, self).__init__()
self.hidden = nn.Linear(inputsize, (inputsize // 2))
self.hidden2 = nn.Linear((inputsize // 2), (inputsize // 4))
self.output = nn.Linear((inputsize // 4), 64)
sel... |
class PolynomialCameraCal(CameraCal):
NUM_DISTORTION_COEFFS = 3
DEFAULT_MAX_FOV = math.radians(120)
def __init__(self, focal_length: T.Sequence[T.Scalar], principal_point: T.Sequence[T.Scalar], distortion_coeffs: T.Sequence[T.Scalar]=(0.0, 0.0, 0.0), critical_undistorted_radius: T.Scalar=None, max_fov: T.Sc... |
class VGGLoss(tf.keras.Model):
def __init__(self):
super(VGGLoss, self).__init__(name='VGGLoss')
self.vgg = Vgg19()
self.layer_weights = [(1.0 / 32), (1.0 / 16), (1.0 / 8), (1.0 / 4), 1.0]
def call(self, x, y):
x = (((x + 1) / 2) * 255.0)
y = (((y + 1) / 2) * 255.0)
... |
def save_model(model, output_dir, ep_num):
model_to_save = (model.module if hasattr(model, 'module') else model)
model_name = (('model_' + str(ep_num)) + '.bin')
torch.save(model_to_save.state_dict(), os.path.join(output_dir, model_name)) |
class DistEvalHook(_DistEvalHook):
greater_keys = ['mIoU', 'mAcc', 'aAcc']
def __init__(self, *args, by_epoch=False, efficient_test=False, **kwargs):
super().__init__(*args, by_epoch=by_epoch, **kwargs)
self.efficient_test = efficient_test
def _do_evaluate(self, runner):
if self.broa... |
def make_stuff(model):
ret = (lambda : None)
def batch_loss(params, images, y_onehot):
logits = model.apply({'params': params}, images)
return jnp.mean(optax.softmax_cross_entropy(logits=logits, labels=y_onehot))
def batch_num_correct(params, images, y_onehot):
logits = model.apply({... |
.parametrize('backend_name', ['numpy', 'tensorflow', 'pytorch', 'PyTorch'])
def test_backend_no_custom_attributes(backend_name):
pyhf.set_backend(backend_name)
with pytest.raises(AttributeError):
pyhf.tensorlib.nonslotted = True |
class PathSemigroup(UniqueRepresentation, Parent):
Element = QuiverPath
def __classcall__(cls, Q):
Q = Q.copy(immutable=True, weighted=True)
return super().__classcall__(cls, Q)
def __init__(self, Q):
labels = Q.edge_labels()
if (len(set(labels)) != len(labels)):
... |
_HEADS_REGISTRY.register()
class ClasHead(EmbeddingHead):
def forward(self, features, targets=None):
pool_feat = self.pool_layer(features)
neck_feat = self.bottleneck(pool_feat)
neck_feat = neck_feat.view(neck_feat.size(0), (- 1))
if (self.cls_layer.__class__.__name__ == 'Linear'):
... |
class SymmetricTensorDescription():
def __init__(self, element, layout, fill_mode, alignment=1, complex_transform=ComplexTransform.none, side_mode=SideMode.Left):
self.element = element
self.layout = layout
self.fill_mode = fill_mode
self.alignment = alignment
self.complex_tr... |
_cache()
def setup_logger_dist(output=None, distributed_rank=0, *, color=True, name='moco', abbrev_name=None):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.propagate = False
if (abbrev_name is None):
abbrev_name = name
plain_formatter = logging.Formatter('[%(asctime... |
class Warmup(torch.optim.lr_scheduler._LRScheduler):
def __init__(self, optimizer: torch.optim.Optimizer, scheduler: torch.optim.lr_scheduler._LRScheduler, init_lr_ratio: float=0.0, num_epochs: int=5, last_epoch: int=(- 1), iters_per_epoch: int=None):
self.base_scheduler = scheduler
self.warmup_iter... |
def test_cache_different_args():
def test(x):
return (x * x)
a = np.random.rand(2)
b = np.random.rand(3)
ra = test(a)
assert (len(test._cache.cache) == 1)
rb = test(b)
assert (len(test._cache.cache) == 2)
assert np.allclose((a * a), ra)
assert np.allclose((b * b), rb) |
def _sanity_check_tmap(T):
if (not math.isclose(np.sum(T), 1.0, abs_tol=1e-07)):
print('Sum of transport map is ', np.sum(T))
raise Exception('NAN inside Transport MAP. Most likely due to large ground metric values') |
def extract_data(inputs):
assert isinstance(inputs, dict)
new_inputs = {}
for (key, value) in inputs.items():
assert isinstance(value, DataContainer)
data = value.data
if value.cpu_only:
new_inputs[key] = data[0]
else:
device = get_device(data)
... |
def test_Task12AXDataset_deepcopy():
from copy import deepcopy
dataset = Task12AXDataset(num_seqs=10)
dataset = deepcopy(dataset)
dataset.init_seq_order(1)
n = dataset.num_seqs
for i in range(n):
dataset.load_seqs(i, (i + 1))
targets = dataset.get_data(i, 'classes')
print... |
def get_ngpus_per_node(args):
nnodes = args.nnodes
if (not hasattr(args, 'ngpus_per_node')):
if ((args.world_size % nnodes) != 0):
raise NotImplementedError()
ngpus_per_node = ([(args.world_size // nnodes)] * nnodes)
else:
ngpus_per_node = args.ngpus_per_node
assert (... |
class TestIterationLimits():
def setup_method(self):
self.funcalls = 0
def slow_func(self, v):
self.funcalls += 1
(r, t) = (np.sqrt(((v[0] ** 2) + (v[1] ** 2))), np.arctan2(v[0], v[1]))
return (np.sin(((r * 20) + t)) + (r * 0.5))
def test_neldermead_limit(self):
self.... |
class Dim(_DimMixin):
Types = DimTypes
__slots__ = ('name', 'capacity', 'size', 'dyn_size_ext', '_dyn_size_max_value', '_extra')
name: Optional[str]
capacity: Optional[int]
size: Optional[int]
dyn_size_ext: Optional[_t.Tensor]
_dyn_size_max_value: Optional[_t.Tensor]
_extra: Optional[_Di... |
def add_additional_type_casts(func: LeanFunctionInfo, rw_casts: List[str], additional_types: List[CairoType]) -> List[str]:
additional_casts = func.struct_defs.get_lean_type_cast_rec(scope=func.func_scope, cairo_types=additional_types, open_namespaces=func.open_namespaces)
for cast in additional_casts:
... |
def remap_state_dict_hf_gpt_neox(state_dict, config):
def key_mapping_layers(key):
return re.sub('^gpt_neox.', 'transformer.', key)
state_dict = OrderedDict(((key_mapping_layers(k), v) for (k, v) in state_dict.items()))
def key_mapping_emb(key):
return re.sub('^transformer.embed_in.', 'trans... |
def run_nimbix(target, data):
target.write('run_nimbix: all\n')
if ('launch' in data):
if ('cmd_args' in data['launch'][0]):
target.write('\t$(COMMON_REPO)/common/utility/nimbix/run_nimbix.py $(EXECUTABLE) $(CMD_ARGS) $(XSA)\n\n')
else:
target.write('\t$(COMMON_REPO)/common/utili... |
def test_dense_heads_test_attr():
exceptions = ['FeatureAdaption']
all_dense_heads = [m for m in dense_heads.__all__ if (m not in exceptions)]
check_attributes = ['simple_test', 'aug_test', 'simple_test_bboxes', 'simple_test_rpn', 'aug_test_rpn']
table_header = (['head name'] + check_attributes)
tab... |
(frozen=True)
class Return():
name: Optional[str]
type: Type
annotation: Optional[Annotation]
def parse(arg: str) -> 'Return':
name: Optional[str]
if (' ' in arg):
(type_and_annot, name) = arg.rsplit(' ', 1)
else:
type_and_annot = arg
name = No... |
def load_clusters():
topics = []
clusters = os.listdir(args.input_dir)
for cluster_file in clusters:
doc_names_list = []
if (cluster_file == 'metrics.txt'):
continue
print(cluster_file)
full_path = os.path.join(args.input_dir, cluster_file)
with open(full_... |
def main():
args = get_args()
lm = torch.hub.load('pytorch/fairseq', 'transformer_lm.wmt19.en', tokenizer='moses', bpe='fastbpe')
lm.eval().cuda()
if ((args.manifest is None) and (args.prompts_description is None)):
target_ids = None
else:
target_ids = get_target_sequences(args.manif... |
def _seg_42():
return [(64060, 'M', u''), (64061, 'M', u''), (64062, 'M', u''), (64063, 'M', u''), (64064, 'M', u''), (64065, 'M', u''), (64066, 'M', u''), (64067, 'M', u''), (64068, 'M', u''), (64069, 'M', u''), (64070, 'M', u''), (64071, 'M', u''), (64072, 'M', u''), (64073, 'M', u''), (64074, 'M', u''), (64075, ... |
def train_transforms(inp_size, scale):
return transforms.Compose([transforms.RandomResizedCrop(inp_size, scale=scale), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize]) |
class Scorer():
def __init__(self, metrics: Optional[List[str]]=None, custom_metric_funcs: Optional[Mapping[(str, Callable[(..., float)])]]=None, abstain_label: Optional[int]=(- 1)) -> None:
self.metrics: Dict[(str, Callable[(..., float)])]
self.metrics = {}
if metrics:
for metri... |
def test_anntorchdataset_numpy(adata):
adata_manager = generic_setup_adata_manager(adata)
bd = AnnTorchDataset(adata_manager)
for value in bd[1].values():
assert (type(value) == np.ndarray) |
.unit
.convert
.filterwarnings('ignore:.*:astropy.io.fits.verify.VerifyWarning')
def test_line_to_json_ra_dec():
helpers.setup(with_data=True)
in_wcs = WCS(fits.getheader(os.path.join(helpers.TEST_PATH, 'test_image.fits')))
columns = ['id', 'ra', 'dec', 'col1', 'col2']
catalog_assets_path = os.path.join... |
class ScaleLinear(nn.Module):
def __init__(self, dim_in, dim_out, dim_c):
super(ScaleLinear, self).__init__()
self._layer = nn.Linear(dim_in, dim_out)
self._hyper = nn.Linear((1 + dim_c), dim_out)
def forward(self, context, x):
gate = self._hyper(context)
if (x.dim() == 3... |
def test_export_sequence_unexpected_exception(exportable_test_case_with_unexpected_exception, tmp_path):
path = (tmp_path / 'generated_with_unexpected_exception.py')
exporter = export.PyTestChromosomeToAstVisitor()
exportable_test_case_with_unexpected_exception.accept(exporter)
export.save_module_to_fil... |
_cache(maxsize=1)
def query_which_cloud() -> str:
check_exit_code = (lambda cmd: subprocess.call(shlex.split(cmd), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
aws_metadata_url = 'curl -f --connect-timeout 1 --noproxy *
azure_metadata_url = 'curl -f --connect-timeout 1 -H Metadata:true --noproxy ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.