code stringlengths 101 5.91M |
|---|
def set_memory_limit_in_bytes(parser, args, component):
param = (component + '_memory_limit')
limit = getattr(args, param)
if (limit is not None):
setattr(args, param, _get_memory_limit_in_bytes(limit, parser)) |
def setup(handler):
handler._logger.print('Force loading the entire cache: images, depths and cameras')
loader = handler._data_loader
adapter = loader.adapter
elements = [*adapter.split['train'][:loader.split_limits['train']], *adapter.split['test'][:loader.split_limits['test']]]
nr_views = adapter.... |
def test_issue78():
def _get_identifier(sql):
p = sqlparse.parse(sql)[0]
return p.tokens[2]
results = (('get_name', 'z'), ('get_real_name', 'y'), ('get_parent_name', 'x'), ('get_alias', 'z'), ('get_typecast', 'text'))
variants = ('select x.y::text as z from foo', 'select x.y::text as "z" fro... |
class TrafficSigns(torch.utils.data.Dataset):
def __init__(self, root, train=True, transform=None, download=False):
self.root = os.path.expanduser(root)
self.transform = transform
self.filename = 'traffic_signs_dataset.zip'
self.url = '
fpath = os.path.join(root, self.filenam... |
def assert_requests_call(case: Case):
with pytest.raises((requests.exceptions.ConnectionError, urllib3.exceptions.NewConnectionError, CheckFailed)):
case.call(base_url=' timeout=0.001) |
class Test_Link_Regression(object):
d = 100
d_out = 10
clip_limits = (0, 1)
def test_ip(self):
(x_src, x_dst) = make_orthonormal_vectors(self.d)
expected = np.dot(x_src, x_dst)
x_src = tf.constant(x_src, shape=(1, self.d), dtype='float64')
x_dst = tf.constant(x_dst, shape... |
class Sequential(Model):
def __init__(self, layers=None, name=None):
self.layers = []
self.model = None
self.inputs = []
self.outputs = []
self._trainable = True
self._initial_weights = None
self.inbound_nodes = []
self.outbound_nodes = []
self... |
def normalize_speaker(speaker):
speaker = speaker.replace('-', '_')
speaker = speaker.replace('#', '_')
speaker = speaker.replace('__', '_1_')
speaker = speaker.replace('speaker1', 'speaker')
speaker = speaker.replace('108730', '1_08730')
speaker = speaker.replace('', '08730_1123')
speaker =... |
class DynamicNet(object):
def __init__(self, c0, lr):
self.models = []
self.c0 = c0
self.lr = lr
self.boost_rate = nn.Parameter(torch.tensor(lr, requires_grad=True, device='cuda'))
def add(self, model):
self.models.append(model)
def parameters(self):
params = ... |
class Decoder_SPEC2MIDI(nn.Module):
def __init__(self, n_frame, n_bin, n_note, n_velocity, hid_dim, n_layers, n_heads, pf_dim, dropout, device):
super().__init__()
self.device = device
self.n_note = n_note
self.n_frame = n_frame
self.n_velocity = n_velocity
self.n_bin... |
def prediction_stat(outputs, labels, n_classes):
lbl = labels.data
valid = (lbl < n_classes)
classwise_pixel_acc = []
classwise_gtpixels = []
classwise_predpixels = []
for output in outputs:
(_, pred) = output.data.max(dim=1)
for m in range(n_classes):
mask1 = (lbl ==... |
def test_bad_wires():
dh = 1.0
nx = 12
ny = 12
hx = [(dh, nx)]
hy = [(dh, ny)]
mesh = TensorMesh([hx, hy], 'CN')
actv = np.ones(len(mesh), dtype=bool)
wires = maps.Wires(('m1', mesh.nC), ('m2', (mesh.nC - 2)), ('m3', (mesh.nC - 3)))
with pytest.raises(ValueError):
regularizat... |
def sqrt_poly(f):
if (not f.is_monic()):
raise ValueError('f must be monic')
try:
return prod([(g ** Integer((e / Integer(2)))) for (g, e) in f.factor()])
except TypeError:
raise ValueError('f must be a perfect square') |
def find_benchmark(benchmark: str, path: str):
benchmarks_dir = os.path.join(PROJECT_DIR, path)
benchmark_path = find(benchmark, benchmarks_dir)
return benchmark_path |
def find_text_idx(sentence):
for (idx, line) in enumerate(sentence):
if line.startswith('# text'):
return idx
return (- 1) |
def get_optimizer(params, name, **kwargs):
if (name == 'adam'):
from torch.optim import Adam
return Adam(params, **kwargs)
elif (name == 'adamw'):
from torch.optim import AdamW
return AdamW(params, **kwargs)
else:
raise NotImplementedError(name) |
class TranslationDataset(CachedDataset2):
source_file_prefix = 'source'
target_file_prefix = 'target'
main_source_data_key = 'data'
main_target_data_key = 'classes'
def __init__(self, path, file_postfix, source_postfix='', target_postfix='', source_only=False, search_without_reference=False, unknown... |
def NMTCriterion(vocabSize):
weight = torch.ones(vocabSize)
weight[onmt.Constants.PAD] = 0
crit = nn.NLLLoss(weight, size_average=False)
if opt.gpus:
crit.cuda()
return crit |
.parametrize('hidden_size,sparse_feature_num', [((8,), 2)])
def test_ONN(hidden_size, sparse_feature_num):
model_name = 'ONN'
sample_size = SAMPLE_SIZE
(x, y, feature_columns) = get_test_data(sample_size, sparse_feature_num=sparse_feature_num, dense_feature_num=sparse_feature_num, hash_flag=True)
model ... |
def test_control_bfgs(ocp):
ocp.solve(algorithm='bfgs', rtol=0.01, atol=0.0, max_iter=7)
assert (ocp.solver.relative_norm <= ocp.solver.rtol) |
class Dataset():
def __init__(self, name, path, min_length=None, max_length=None, args=None):
self.name = name
if ((args is not None) and hasattr(args, 'data_dir')):
path = os.path.join(args.data_dir, path)
self.vec = pickle.load(open(path, 'rb'))
(X, Xt) = (self.vec.seq_... |
class ConvModule(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, padding=0):
super(ConvModule, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, bias=False)
self.bn = nn.BatchNorm2d(out_channels, eps=0.001, mo... |
class MeatOffGrill(Task):
def init_task(self) -> None:
self._steak = Shape('steak')
self._chicken = Shape('chicken')
self._success_sensor = ProximitySensor('success')
self.register_graspable_objects([self._chicken, self._steak])
self._w1 = Dummy('waypoint1')
self._w1z... |
def alexnet():
model = ModelHelper(name='r', arg_scope={'order': 'NCHW', 'is_test': True})
conv1 = brew.conv(model, 'data', 'conv1', 3, 64, 11, ('XavierFill', {}), ('ConstantFill', {}), stride=4, pad=2)
relu1 = brew.relu(model, conv1, 'conv1')
pool1 = brew.max_pool(model, relu1, 'pool1', kernel=3, strid... |
def find_use(arg: Any, node: Node) -> bool:
if isinstance(arg, (tuple, list)):
return any((find_use(elem, node) for elem in arg))
elif isinstance(arg, dict):
return any((find_use(v, node) for (k, v) in arg.items()))
elif isinstance(arg, slice):
return any([find_use(arg.start, node), ... |
def test_CE():
reset_seed(0, check_cudnn=False)
for weighted in [True, False]:
instance = CE()
announce_msg('Testing {}'.format(instance))
announce_msg('weighted: {}'.format(weighted))
cuda = 0
DEVICE = torch.device(('cuda:{}'.format(cuda) if torch.cuda.is_available() els... |
class ParamSpec(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _PARAMSPEC |
def wrap_array(array, stride):
offsets = []
for x in range(int((array.__len__() / stride))):
offsets.append((x * stride))
offsets.append(array.__len__())
return ListOffsetArray(offsets, array) |
def deepfashion_name_parse(f, mode='train'):
if (mode == 'train'):
data_type = 'train'
elif (mode == 'val'):
data_type = 'gallery'
elif (mode == 'test'):
data_type = 'query'
lines = txt_parse(f)
num_train = 0
result = []
for line in lines:
if (line[0:4] != 'im... |
def test_download_none():
with tempfile.TemporaryDirectory(dir=TEST_WORKING_DIR) as test_dir:
stanza.download('it', model_dir=test_dir, processors='tokenize', package='combined')
stanza.download('it', model_dir=test_dir, processors='tokenize', package='vit')
it_dir = os.path.join(test_dir, '... |
_args('v', 'i')
def contiguous(g, input, memory_format):
if (memory_format > 2):
raise RuntimeError('onnx memory_format support is not implemented')
return input |
.register_model(TupleType)
class TupleModel(numba.extending.models.StructModel):
def __init__(self, dmm, fe_type):
members = [('contents', fe_type.contents)]
super().__init__(dmm, fe_type, members) |
class GumbelQuantizer(nn.Module):
def __init__(self, codebook_size, emb_dim, num_hiddens, straight_through=False, kl_weight=0.0005, temp_init=1.0):
super().__init__()
self.codebook_size = codebook_size
self.emb_dim = emb_dim
self.straight_through = straight_through
self.tempe... |
_task('text_to_table_task')
class TextToDataTranslationTask(TranslationTask):
def __init__(self, args, src_dict, tgt_dict):
super().__init__(args, src_dict, tgt_dict)
start_split_token = args.split_token.strip()
space_split_token = (' ' + start_split_token)
newline_token = args.newli... |
def make_is_save(options):
class IsSave(Struct):
def __init__(self, save_times):
if is_sequence(save_times):
save_times = nm.asarray(save_times)
self.save_times0 = save_times
self.reset()
def reset(self, ts=None):
self.ilast = 0
... |
def pretrained_model_config_and_tokenizer(model_type: str, model_name_or_path: str, config_name: str='', tokenizer_name: str='', do_lower_case: bool=False, cache_dir: str='', stateless_tied=False, do_resize_token_embedding=True, explicitly_set_dict={}, **config_kw):
(config_class, model_class, tokenizer_class) = MO... |
class DeepmindMathDataset(torch.utils.data.Dataset):
VERSION = 8
vocabulary: framework.data_structures.CharVocabulary = None
raw_data = {}
index = {}
DIFFICULTIES = ['easy', 'medium', 'hard']
def lock(self) -> framework.utils.LockFile:
return framework.utils.LockFile(os.path.join(self.ca... |
class MSRVTTQADataModule(BaseDataModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def dataset_cls(self):
return MSRVTTQADataset
def dataset_name(self):
return 'msrvttqa'
def setup(self, stage):
super().setup(stage)
self.answer2id = s... |
def substep_p2g(x: ti.types.ndarray(ndim=1), v: ti.types.ndarray(ndim=1), C: ti.types.ndarray(ndim=1), J: ti.types.ndarray(ndim=1), grid_v: ti.types.ndarray(ndim=2), grid_m: ti.types.ndarray(ndim=2)):
for p in x:
Xp = (x[p] / dx)
base = int((Xp - 0.5))
fx = (Xp - base)
w = [(0.5 * ((... |
def test_add_loss():
tl = Timeline()
photon = Photon('', tl, encoding_type={'name': 'single_atom'})
assert (photon.loss == 0)
photon.add_loss(0.5)
assert (photon.loss == 0.5)
photon.add_loss(0.5)
assert (photon.loss == 0.75) |
class DDIMSampler(object):
def __init__(self, model, schedule='linear', **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def register_buffer(self, name, attr):
if (type(attr) == torch.Tensor):
... |
def register_Ns3LteUeCcmRrcSapProviderLcsConfig_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteUeCcmRrcSapProvider::LcsConfig const &', 'arg0')])
cls.add_instance_attribute('componentCarrierId', 'uint8_t', is_const=False)
cls.add_instance_attribute('lcConfig', 'ns... |
class DiscreteEncoder(EncoderBase):
def __init__(self):
super(DiscreteEncoder, self).__init__()
def fit(self, df, targets, configurations):
self.reset()
for target in targets:
for (method, parameter) in configurations:
nbins = parameter['nbins']
... |
class DegenerateMetricParal(DegenerateMetric, TensorFieldParal):
def __init__(self, vector_field_module, name, signature=None, latex_name=None):
TensorFieldParal.__init__(self, vector_field_module, (0, 2), name=name, latex_name=latex_name, sym=(0, 1))
ndim = self._ambient_domain.dimension()
... |
def test_hash_collisions():
X = [list('Thequickbrownfoxjumped')]
Xt = FeatureHasher(alternate_sign=True, n_features=1, input_type='string').fit_transform(X)
assert (abs(Xt.data[0]) < len(X[0]))
Xt = FeatureHasher(alternate_sign=False, n_features=1, input_type='string').fit_transform(X)
assert (Xt.da... |
class ContrastCLIPBottleneckEnt(AbstractCLIPBottleneck):
def __init__(self, feature_dim, num_classes, num_domains, hparams, pretrained, idx2class):
super(ContrastCLIPBottleneckEnt, self).__init__(feature_dim, num_classes, num_domains, hparams, pretrained, idx2class, DiscreteEntropyBottleneck, use_clip_contr... |
class Batch():
def __init__(self, src=None, trg=None, dec=None):
(self.src, self.trg, self.dec) = (src, trg, dec) |
def get_dependent_dists(dists, dist):
if (dist not in dists):
raise DistlibException(('given distribution %r is not a member of the list' % dist.name))
graph = make_graph(dists)
dep = [dist]
todo = graph.reverse_list[dist]
while todo:
d = todo.pop()
dep.append(d)
for ... |
class ChoiceStateVarLayer(LayerBase):
layer_class = 'choice_state_var'
def __init__(self, beam_size, search=NotSpecified, input_type='prob', prob_scale=1.0, base_beam_score_scale=1.0, random_sample_scale=0.0, length_normalization=True, custom_score_combine=None, source_beam_sizes=None, scheduled_sampling=False,... |
_testing
def test_random_arith(level=MAX_LEVEL, trials=1):
i = 0
for x in random_rings(level):
print(('survived %s tests' % i))
i += 1
print(x)
a = x.random_element()
b = x.random_element()
print(a, b)
print(((((a * b) + a) - b) + 1))
if (i >= tria... |
class TokenizerUtilsTest(unittest.TestCase):
def check_tokenizer_from_pretrained(self, tokenizer_class):
s3_models = list(tokenizer_class.max_model_input_sizes.keys())
for model_name in s3_models[:1]:
tokenizer = tokenizer_class.from_pretrained(model_name)
self.assertIsNotNon... |
def drop_not_type_specific_keywords(schema: Schema, new_type: str) -> None:
keywords = TYPE_SPECIFIC_KEYS.get(new_type, ())
for keyword in tuple(schema):
if ((keyword not in keywords) and (keyword not in ANY_TYPE_KEYS)):
schema.pop(keyword, None) |
def retry_on_connect_failures(func=None, connect_errors=ADDRESS_IN_USE):
if (func is None):
return partial(retry_on_connect_failures, connect_errors=connect_errors)
(func)
def wrapper(*args, **kwargs):
tries_remaining = 10
while True:
try:
return func(*arg... |
def test_valarray(doc):
lst = m.cast_valarray()
assert (lst == [1, 4, 9])
assert m.load_valarray(lst)
assert (doc(m.cast_valarray) == 'cast_valarray() -> List[int]')
assert (doc(m.load_valarray) == 'load_valarray(arg0: List[int]) -> bool') |
.parametrize('dtype', ((np.float64, np.float32), np.float64, None, 'numeric'))
.parametrize('bool_dtype', ('bool', 'boolean'))
def test_check_dataframe_mixed_float_dtypes(dtype, bool_dtype):
if (bool_dtype == 'boolean'):
pd = importorskip('pandas', minversion='1.0')
else:
pd = importorskip('pand... |
def pad_vocabulary(math):
if (math == 'fp16'):
pad_vocab = 8
elif (math == 'fp32'):
pad_vocab = 1
return pad_vocab |
class TestGIL():
def setup_method(self):
self.messages = []
def log(self, message):
self.messages.append(message)
def make_worker_thread(self, target, args):
log = self.log
class WorkerThread(threading.Thread):
def run(self):
log('interpolation sta... |
class GPTQAccuracyTest(GPTQBaseTest):
def get_gptq_config(self):
return GradientPTQConfig(5, optimizer=torch.optim.Adam([torch.Tensor([])], lr=0.0001), optimizer_rest=torch.optim.Adam([torch.Tensor([])], lr=0.0001), loss=multiple_tensors_mse_loss, train_bias=True, rounding_type=self.rounding_type, use_hessi... |
class SquadExample(object):
def __init__(self, qas_id, question_text, doc_tokens, orig_answer_text=None, start_position=None, end_position=None, is_impossible=None):
self.qas_id = qas_id
self.question_text = question_text
self.doc_tokens = doc_tokens
self.orig_answer_text = orig_answ... |
class NotANumber(Constant):
def __init__(self, name='NaN'):
conversions = dict(matlab='NaN')
Constant.__init__(self, name, conversions=conversions)
def __float__(self):
return float('nan')
def _mpfr_(self, R):
return R('NaN')
def _real_double_(self, R):
return R.N... |
def _format(val: Any, output_format: str='standard', errors: str='coarse') -> Any:
val = str(val)
result: Any = []
if (val in NULL_VALUES):
return [np.nan]
if (not validate_pe_ruc(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val}')
error_re... |
def get_labeled_dataloader(dataset_name: str, augmentation: str, batch_size: int, image_size: int=None, siamese=False, unlabeled_ratio: int=20, num_workers=2, shuffle=True, drop_last=False, split_seed=1):
(unlabeled, labeled) = get_split_dataloader(dataset_name, augmentation, batch_size, image_size, siamese=siamese... |
class PDAG(nx.DiGraph):
def __init__(self, directed_ebunch=[], undirected_ebunch=[], latents=[]):
super(PDAG, self).__init__(((directed_ebunch + undirected_ebunch) + [(Y, X) for (X, Y) in undirected_ebunch]))
self.latents = set(latents)
self.directed_edges = set(directed_ebunch)
self... |
def symbol2number48(symbol):
order = 0
char_list = list(symbol)
if (('o' in char_list) or ('' in char_list)):
order = 4
elif (('#' in char_list) and ('5' in char_list)):
order = 3
elif (('m' in char_list) and ('j' not in char_list)):
order = 2
else:
order = 1
... |
def _nb_nodes(feedback: _Feedback, is_chunked) -> int:
for inp in feedback.features.inputs:
if (inp.location in [_Location.NODE, _Location.EDGE]):
if is_chunked:
return inp.data.shape[2]
else:
return inp.data.shape[1]
assert False |
class FrameSelectionStrategy(Enum):
RANDOM_K = 'random_k'
FIRST_K = 'first_k'
LAST_K = 'last_k'
ALL = 'all' |
class MNASNet(TorchVisionModel):
def __init__(self, tasks, model_args):
super(MNASNet, self).__init__(models.mnasnet1_0, tasks, model_args) |
def enable_hooks(args: argparse.Namespace) -> List[int]:
registered = []
if args.sequential:
def make_sequential(sdfg: dace.SDFG):
for sd in sdfg.all_sdfgs_recursive():
sd.openmp_sections = False
for (n, _) in sdfg.all_nodes_recursive():
if isinsta... |
class PreconditionFailed(HTTPException):
code = 412
description = 'The precondition on the request for the URL failed positive evaluation.' |
class MissingOverleafCredentials(OverleafException):
def __init__(self, **kwargs):
message = 'Overleaf credentials `OVERLEAF_EMAIL` and/or `OVERLEAF_PASSWORD` not found. These should be set as both environment variables and GitHub repository secrets.'
super().__init__(message, level=kwargs.get('leve... |
def LF_contact_covid(s):
rgx = '\\b(known\\s)*(contact(s)*)(\\s)*(with|w\\/)*(\\s)*(known|confirmed)*(\\s)*(coronavirus|covid|covid\\s19|covid-19|covid(\\s)*\\+)(\\scontact)*\\b'
trigger = match_regex(rgx, s)
if (not trigger):
return ABSTAIN
return (EXPOSURE if (not is_negated(trigger)) else NO_... |
class ProjectivePlaneCurve_field(ProjectivePlaneCurve, ProjectiveCurve_field):
_point = ProjectivePlaneCurvePoint_field
def arithmetic_genus(self):
if (not self.is_irreducible()):
raise TypeError('this curve must be irreducible')
d = self.defining_polynomial().total_degree()
... |
class NumberFieldStructure(UniqueRepresentation):
def __init__(self, other):
self.other = other
def create_structure(self, field):
raise NotImplementedError |
def memlet_check_parameters(memlet, volume, dynamic, subsets):
if (memlet.volume != volume):
raise RuntimeError('Expected volume of {}, got {}'.format(volume, memlet.volume))
elif (dynamic and (not memlet.dynamic)):
raise RuntimeError('Expected dynamic volume, got static')
elif (memlet.dynam... |
def semantic_unit_segment(tag_seq):
(tag_item_lists, seg_pointers) = ([], [])
for (idx, tag_item) in enumerate(tag_seq):
if (tag_item[0] != OUTSIDE):
tag_item_lists.append(tag_item)
seg_pointers.append(idx)
return (tag_item_lists, seg_pointers) |
def load_checkpoint(model, optimizer, model_dir, map_location=None, step=None):
path = os.path.join(model_dir, 'model_checkpoint')
if (step is not None):
path += '-{:08d}'.format(step)
if os.path.exists(path):
print(('Loading model from %s' % path))
checkpoint = torch.load(path, map_... |
class EntityMention(Mention):
def __init__(self, doc_id, sent_id, tokens_numbers, tokens, mention_str, head_text, head_lemma, is_singleton, is_continuous, coref_chain, mention_type):
super(EntityMention, self).__init__(doc_id, sent_id, tokens_numbers, tokens, mention_str, head_text, head_lemma, is_singleton... |
def _trim_arity(func, maxargs=2):
if (func in singleArgBuiltins):
return (lambda s, l, t: func(t))
limit = [0]
foundArity = [False]
def extract_stack(limit=0):
offset = (- 2)
frame_summary = traceback.extract_stack(limit=(((- offset) + limit) - 1))[offset]
return [(frame_... |
def create_reverse_dependency_tree():
cache = {}
all_modules = (list(PATH_TO_TRANFORMERS.glob('**/*.py')) + list(PATH_TO_TESTS.glob('**/*.py')))
all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules]
edges = [(dep, mod) for mod in all_modules for dep in get_module_dependencies(mod, ca... |
def normalize(a):
ma = np.max(a)
mi = np.min(a)
assert (ma > mi)
a = ((a - mi) / (ma - mi))
return a |
def create_temp_with_dir():
tmpdir = tempfile.mkdtemp()
(yield tmpdir)
rmtree(tmpdir, ignore_errors=True) |
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytorch_dump_path):
config = BertConfig.from_json_file(bert_config_file)
print('Building PyTorch model from configuration: {}'.format(str(config)))
model = BertForPreTraining(config)
load_tf_weights_in_bert(model, config, tf_chec... |
class Func_legendre_P(GinacFunction):
def __init__(self):
BuiltinFunction.__init__(self, 'legendre_P', nargs=2, latex_name='P', conversions={'maxima': 'legendre_p', 'mathematica': 'LegendreP', 'maple': 'LegendreP', 'giac': 'legendre'}) |
def make_spec(vnnlib_filename, onnx_filename):
(num_inputs, num_outputs, inp_dtype) = get_num_inputs_outputs(onnx_filename)
vnnlib_spec = read_vnnlib_simple(vnnlib_filename, num_inputs, num_outputs)
rv = []
for (box, spec_list) in vnnlib_spec:
if (len(spec_list) == 1):
(mat, rhs) = s... |
def test_unique_objects_after_inlining(empty_open_api_3_schema):
empty_open_api_3_schema['paths'] = {'/test': {'post': {'requestBody': {'content': {'application/json': {'schema': {'$ref': '#/components/schemas/step5'}}}}, 'responses': {'default': {'description': 'Success'}}}}}
empty_open_api_3_schema['component... |
class FastestDetNeck(nn.Module):
def __init__(self, in_channels=[512, 1024, 2048], out_channels=96):
super(FastestDetNeck, self).__init__()
self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
self.avg_pool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
self.SPP = SPP(sum(... |
.parametrize('sql', ['select verrrylongcolumn from foo', 'select "verrrylongcolumn" from "foo"'])
def test_truncate_strings_doesnt_truncate_identifiers(sql):
formatted = sqlparse.format(sql, truncate_strings=2)
assert (formatted == sql) |
.parametrize('observation_shape', [(4,), ((4,), (8,)), (3, 84, 84)])
def test_get_shape_from_observation(observation_shape: Shape) -> None:
observation = create_observation(observation_shape)
assert (tuple(get_shape_from_observation(observation)) == observation_shape) |
def locate_app(script_info, module_name, app_name, raise_if_not_found=True):
__traceback_hide__ = True
try:
__import__(module_name)
except ImportError:
if sys.exc_info()[(- 1)].tb_next:
raise NoAppException('While importing "{name}", an ImportError was raised:\n\n{tb}'.format(nam... |
def data_iterator_csv_dataset(uri, batch_size, shuffle=False, rng=None, use_thread=True, normalize=True, with_memory_cache=True, with_file_cache=True, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[], stop_exhausted=False):
ds = CsvDataSource(uri, shuffle=shuffle, rng=rng, normalize=normalize)
r... |
def TorchGELUPattern(patterns: list):
gelu_input = OuterNode()
div_tensor = OuterNode(is_tensor=True)
add_tensor = OuterNode(tensor_value=1)
mul_tensor = OuterNode(tensor_value=0.5)
_div = PatternNode('Div', [gelu_input, div_tensor])
_erf = PatternNode('Erf', [_div])
_add = PatternNode('Add'... |
def register_Ns3PhyTxStatsCalculator_methods(root_module, cls):
cls.add_constructor([param('ns3::PhyTxStatsCalculator const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DlPhyTransmission', 'void', [param('ns3::PhyTransmissionStatParameters', 'params')])
cls.add_method('DlPhyTransmissionCallback... |
def plot_spk_cur_mem_spk(spk_in, syn_rec, mem_rec, spk_rec, title):
(fig, ax) = plt.subplots(4, figsize=(8, 7), sharex=True, gridspec_kw={'height_ratios': [0.4, 1, 1, 0.4]})
splt.raster(spk_in, ax[0], s=400, c='black', marker='|')
ax[0].set_ylabel('Input Spikes')
ax[0].set_title('Synaptic Conductance-ba... |
class IRBlock(nn.Module):
expansion: int = 1
def __init__(self, in_ch: int, out_ch: int, s: int=1, downsample: Optional[nn.Module]=None) -> None:
super().__init__()
self.bn0 = nn.BatchNorm2d(in_ch)
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, s, 1, bias=False)
self.bn1 = nn.BatchNorm... |
def sample_machine_instructions(machine_instructions, n):
return random.sample(machine_instructions, min(n, len(machine_instructions))) |
class CrossAttention(nn.Module):
def __init__(self, dim: int, nhead: int, dropout: float=0.0, batch_first: bool=True, add_pe_to_qkv: List[bool]=[True, True, False], residual: bool=True, norm: bool=True):
super().__init__()
self.cross_attn = nn.MultiheadAttention(dim, nhead, dropout=dropout, batch_fi... |
def test_zero_crop():
arr = np.arange(45).reshape(9, 5)
out = crop(arr, 0)
assert (out.shape == (9, 5)) |
def from_pretrained(model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', archive_map=None, **kwargs):
from fairseq import checkpoint_utils, file_utils
if (archive_map is not None):
if (model_name_or_path in archive_map):
model_name_or_path = archive_map[model_name_or_path]
... |
def log(spark):
date = datetime(2019, 1, 1)
return spark.createDataFrame(data=[[0, 0, date, 1.0], [1, 0, date, 1.0], [2, 1, date, 2.0], [2, 1, date, 2.0], [1, 1, date, 2.0], [2, 2, date, 2.0], [0, 2, date, 2.0]], schema=get_schema('user_idx', 'item_idx', 'timestamp', 'relevance')) |
def test_lstm_tree_forward(pretrain_file):
model = build_model(pretrain_file, '--num_tree_lstm_layers', '1', '--constituency_composition', 'tree_lstm')
run_forward_checks(model)
model = build_model(pretrain_file, '--num_tree_lstm_layers', '2', '--constituency_composition', 'tree_lstm')
run_forward_check... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.