code stringlengths 101 5.91M |
|---|
class TorchSumBenchmark(op_bench.TorchBenchmarkBase):
def init(self, M, N):
self.input_one = torch.rand(M, N)
self.set_module_name('sum')
def jit_forward(self, iters):
return torch_sumall(self.input_one, iters) |
def get_pseudo_label_VTM_for_one_segment(args, node2step, step2node, VNM_matched_nodes, wikihow_step_task_occurrence, howto100m_step_task_occurrence):
wikihow_tasks_this_segment = dict()
howto100m_tasks_this_segment = dict()
for node_id in VNM_matched_nodes:
step_ids_this_node = node2step[node_id]
... |
class __DisplMixin():
def displ_item(self, index):
(sample, ann) = (self.__getitem__(index), self.annotation[index])
return OrderedDict({'file': ann['image'], 'label': ann['caption'], 'audio': sample['audio'], 'audio_path': sample['audio_path'], 'caption': sample['caption']}) |
def load_checkpoint(cfg: CheckpointConfig, trainer, **passthrough_args):
reset_optimizer = cfg.reset_optimizer
reset_lr_scheduler = cfg.reset_lr_scheduler
optimizer_overrides = ast.literal_eval(cfg.optimizer_overrides)
reset_meters = cfg.reset_meters
reset_dataloader = cfg.reset_dataloader
if ((... |
class DownloadTestCase(unittest.TestCase):
def test_download_mirror_list(self):
tmp = tempfile.NamedTemporaryFile()
tmp.close()
progress = StringIO()
Download(MirrorList.URL, tmp.name, progress=progress).run()
self.assertEqual(progress.getvalue(), '[]\n')
with open(tm... |
def encode_dataset(dataset, vocab, tokenizer, test=False):
questions = []
sparqls = []
for item in tqdm(dataset):
question = item['question']
questions.append(question)
if (not test):
sparql = item['sparql']
sparqls.append(sparql)
sequences = (questions + ... |
def load_xml_info(gt_file, img_info):
obj = ET.parse(gt_file)
anno_info = []
for image in obj.getroot():
for box in image:
h = box.attrib['height']
w = box.attrib['width']
x = box.attrib['left']
y = box.attrib['top']
segs = box[1].text
... |
def parse_trace(trace_file):
jobs = []
arrival_times = []
with open(trace_file, 'r') as f:
for line in f:
(job_type, command, working_directory, num_steps_arg, needs_data_dir, total_steps, scale_factor, priority_weight, SLO, arrival_time) = line.split('\t')
assert (int(scale_... |
def K0_func(SUK, A, prec=106):
R = RealField(prec)
K0 = R(1)
c3 = c3_func(SUK, prec)
for v_l in SUK.primes():
e_l = v_l.residue_class_degree()
Norm_v_l = v_l.absolute_norm()
c5_l = (c3 / (e_l * R(Norm_v_l).log()))
c8_l = Yu_bound(SUK, v_l, prec)
K0_l = (((2 * c8_l... |
def augment_parser():
sepp.config.set_main_config_path(os.path.expanduser('~/.sepp/upp.config'))
parser = sepp.config.get_parser()
parser.description = 'This script runs the UPP algorithm on set of sequences. A backbone alignment and tree can be given as input. If none is provided, a backbone will be auto... |
def test_nested_function_method():
class TestClass():
some_field: int
def some_method(self, q):
return (q * self.some_field)
obj = TestClass(5)
def nested(a):
return ((a + 1) + obj.some_method(a))
def nfm(a: dace.float64[20]):
return nested(a)
A = np.rando... |
class FCompiler(CCompiler):
distutils_vars = EnvironmentConfig(distutils_section='config_fc', noopt=(None, None, 'noopt', str2bool, False), noarch=(None, None, 'noarch', str2bool, False), debug=(None, None, 'debug', str2bool, False), verbose=(None, None, 'verbose', str2bool, False))
command_vars = EnvironmentCo... |
class Scalar(nn.Module):
def __init__(self, init_value):
super().__init__()
self.constant = nn.Parameter(torch.tensor(init_value, dtype=torch.float32))
def forward(self):
return self.constant |
class RMSNorm(torch.nn.Module):
def __init__(self, hidden_size, eps=1e-05, device=None, dtype=None):
factory_kwargs = {'device': device, 'dtype': dtype}
super().__init__()
self.eps = eps
self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
self.registe... |
def config_init(dataset):
if (dataset == 'mnist'):
return (784, 3000, 10, 0.002, 0.002, 10, 0.9, 0.9, 1, 'sigmoid')
if (dataset == 'reuters10k'):
return (2000, 15, 4, 0.002, 0.002, 5, 0.5, 0.5, 1, 'linear')
if (dataset == 'har'):
return (561, 120, 6, 0.002, 2e-05, 10, 0.9, 0.9, 5, 'l... |
def evaluate_style_transfer(args):
scorer = StyleTransferScorer(align=args.align)
scores = []
for (input_sent, hypo) in zip(open(args.input_sent).readlines(), open(args.hypo).readlines()):
(input_sent, hypo) = (input_sent.strip(), hypo.strip())
if ((input_sent == '') and (hypo == '')):
... |
def count_sgx_standard(pods) -> Tuple[(int, int)]:
(i1, i2) = tee(pods)
(standard_pods, sgx_pods) = (filterfalse(cluster.pod_requests_sgx, i1), filter(cluster.pod_requests_sgx, i2))
return (len(list(standard_pods)), len(list(sgx_pods))) |
class EnvironmentCommand(BaseTransformersCLICommand):
def register_subcommand(parser: ArgumentParser):
download_parser = parser.add_parser('env')
download_parser.set_defaults(func=info_command_factory)
def run(self):
safetensors_version = 'not installed'
if is_safetensors_availab... |
def log_memory_usage(sample_interval: float=1.0, log_individual_devices: bool=False):
directory = '/dev/shm'
if (not os.path.exists(directory)):
directory = tempfile.gettempdir()
tempfile_name = os.path.join(directory, f'memory_usage_{os.getpid()}.prof')
def inner():
import posix
... |
class SUMOActor():
def __init__(self, actor_id: str, traci):
self._state: ActorState = ActorState()
self._actor_id: str = actor_id
self._outdated: bool = True
self.traci = traci
def flag_outdated(self) -> None:
self._outdated = True
def state(self) -> ActorState:
... |
def add_random(df, mode, arch='MLP'):
rules = [2, 4, 8, 16, 32]
encs = [32, 64, 128, 256, 512]
dims = [128, 256, 512, 1024, 2048]
modes = ['last', 'best']
def collapse_metric_worse(prob, rules):
p = np.min(np.sum(prob, axis=0))
cmw = (1 - (rules * p))
return cmw
def colla... |
class TransformerDecoderLayer(nn.Module):
def __init__(self, args, no_encoder_attn=False, add_bias_kv=False, add_zero_attn=False):
super().__init__()
self.embed_dim = args.decoder_embed_dim
self.cross_self_attention = getattr(args, 'cross_self_attention', False)
self.self_attn = self... |
def get_input_list_file(subset, trainsplit):
if (subset == 'train'):
if (trainsplit == 0):
return 'ImageSets/480p/train.txt'
elif (trainsplit == 1):
return 'ImageSets/480p/trainsplit_train.txt'
elif (trainsplit == 2):
return 'ImageSets/480p/trainsplit2_tra... |
class MobileNetV2DeepLabV3Plus(nn.Module):
def __init__(self, config: MobileNetV2Config) -> None:
super().__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(output_size=1)
self.conv_pool = MobileNetV2ConvLayer(config, in_channels=apply_depth_multiplier(config, 320), out_channels=256, kernel_siz... |
class Beamline(object):
def __init__(self, srwl_beamline=None):
self.propagation_options = [{'optical_elements': [], 'propagation_parameters': []}]
if (srwl_beamline is not None):
tolal_elements = max(len(srwl_beamline.arProp), len(srwl_beamline.arOpt))
for ti in range(tolal_... |
def parse_multiprocessing_cli(parser):
parser.add_argument('--nprocs', type=int, default=4, help='Tells us how much processes do we want')
parser.add_argument('--master_port', type=int, default=29500)
parser.add_argument('--verbose_comm', action='store_true')
parser.add_argument('--verbose_comm_from_cmd... |
class SawyerFaucetOpenV1Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'faucet_pos': obs[3:6], 'unused_info': obs[6:]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})
action[... |
def _seg_40():
return [(63824, 'M', u''), (63825, 'M', u''), (63826, 'M', u''), (63827, 'M', u''), (63828, 'M', u''), (63829, 'M', u''), (63830, 'M', u''), (63831, 'M', u''), (63832, 'M', u''), (63833, 'M', u''), (63834, 'M', u''), (63835, 'M', u''), (63836, 'M', u''), (63837, 'M', u''), (63838, 'M', u''), (63839, ... |
class A006530(SloaneSequence):
def __init__(self):
SloaneSequence.__init__(self, offset=1)
def _repr_(self):
return 'Largest prime dividing n (with a(1)=1).'
def _eval(self, n):
if (n == 1):
return ZZ.one()
return max((p for (p, _) in arith.factor(n))) |
def log_stop_time(key: str, weight: float=0.0):
for agg in get_active_aggregators():
agg[key].stop(weight) |
def safe_np_cat(arrays, **kwargs):
if all([(arr.size == 0) for arr in arrays]):
return np.array([])
cat_arrays = [arr for arr in arrays if arr.size]
return np.concatenate(cat_arrays, **kwargs) |
def get_printer(msg):
def printer(tensor):
if (tensor.nelement() == 1):
print(f'{msg} {tensor}')
else:
print(f'{msg} shape: {tensor.shape} max: {tensor.max()} min: {tensor.min()} mean: {tensor.mean()}')
return printer |
class _PyAccess8(PyAccess):
def _post_init(self, *args, **kwargs):
self.pixels = self.image8
def get_pixel(self, x, y):
return self.pixels[y][x]
def set_pixel(self, x, y, color):
try:
self.pixels[y][x] = min(color, 255)
except TypeError:
self.pixels[y]... |
def predict_labels_multi_scale(images, model_options, eval_scales=(1.0,), add_flipped_images=False):
outputs_to_predictions = {output: [] for output in model_options.outputs_to_num_classes}
for (i, image_scale) in enumerate(eval_scales):
with tf.variable_scope(tf.get_variable_scope(), reuse=(True if i e... |
def write_text(_text, _file_path):
f = open(_file_path, 'w')
f.write((_text + '\n'))
f.close() |
class LineProduction(object):
def __init__(self, id=None, type=None):
self.id = id
self.lhs = type |
(scope='module')
def dataframe_only_item_left_pandas():
data_only_item_left = [(1, [0, 0, 0, 0, 2], [19842]), (1, [0, 0, 0, 2, 4], [19842, 19844]), (1, [0, 0, 2, 4, 3], [19842, 19844, 19843]), (1, [0, 2, 4, 3, 5], [19842, 19844, 19843, 19845]), (1, [2, 4, 3, 5, 6], [19842, 19844, 19843, 19845, 19846]), (1, [4, 3, 5... |
def _assert_no_warnings_context(name=None):
__tracebackhide__ = True
with warnings.catch_warnings(record=True) as l:
warnings.simplefilter('always')
(yield)
if (len(l) > 0):
name_str = ((' when calling %s' % name) if (name is not None) else '')
raise AssertionErro... |
class AmazonViewOrderDetails(VirtualFunctionTool):
name = 'AmazonViewOrderDetails'
summary = 'View the details of an order, including shipment and payment information.'
parameters: List[ArgParameter] = [{'name': 'order_id', 'type': 'string', 'description': 'The unique identifier of the order.', 'required': ... |
def build_struc_layers(G, opt1=True, opt2=True, opt3=True, until_layer=None, workers=64):
if opt3:
until_layer = until_layer
else:
until_layer = None
G = struc2vec.Graph(G, False, workers, untilLayer=until_layer)
if opt1:
G.preprocess_neighbors_with_bfs_compact()
else:
... |
class DistributedDataParallel(Module):
def __init__(self, module):
super(DistributedDataParallel, self).__init__()
self.warn_on_half = (True if (dist._backend == dist.dist_backend.GLOO) else False)
self.module = module
self.data_parallel_group = mpu.get_data_parallel_group()
... |
class Widget(Model):
def __init__(self, style=None, data=None):
if (WIDGET_ENV == 'jupyter'):
self._comms = []
self._queue = []
self._viewcount = 0
def handle_remote_set(name, value):
with capture_output(self):
self.prop(name).trigger(value... |
_after(1800)
def run_model(ckpt_path, ckpt_args, has_gpu, custom_tasks=None):
ckpt_save_dir = ckpt_path.parent
model_args = Namespace(**ckpt_args['model_args'])
model_args.moco = False
transform_args = Namespace(**ckpt_args['transform_args'])
data_args = Namespace(**ckpt_args['data_args'])
print... |
(scope='session')
def comm_nccl_opts(request):
if (not request.config.getoption('--test-communicator')):
return None
import nnabla.communicators as C
from nnabla.ext_utils import get_extension_context
try:
from nnabla_ext import cuda
except Exception as e:
raise ImportError('... |
def __plot_client_goodput(args, circuittype, torperf_dbs, tornet_dbs):
if (circuittype == 'onionservice'):
torperf_dbs = []
for tornet_db in tornet_dbs:
tornet_db['data'] = [[((x * (2 ** 20)) / 1000000.0) for x in ds] for ds in tornet_db['dataset']]
for torperf_db in torperf_dbs:
cli... |
def eval_qg(res_dict, gts_dict, not_print=True):
encoder.FLOAT_REPR = (lambda o: format(o, '.4f'))
res = defaultdict((lambda : []))
gts = defaultdict((lambda : []))
for key in gts_dict.keys():
res[key] = [res_dict[key].encode('utf-8')]
gts[key].append(gts_dict[key].encode('utf-8'))
Q... |
def test_sum_add_to_fun():
var1 = optplan.Parameter()
var2 = optplan.Parameter()
var3 = optplan.Parameter()
sum1 = optplan.Sum(functions=[var1, var2])
sum2 = (sum1 + var3)
assert isinstance(sum2, optplan.Sum)
assert (sum2.functions == [var1, var2, var3]) |
def conv1d(input_, output_channels, dilation=1, filter_width=1, causal=False, name='dilated_conv'):
with tf.variable_scope(name):
w = tf.get_variable('w', [1, filter_width, input_.get_shape()[(- 1)], output_channels], initializer=tf.contrib.layers.xavier_initializer_conv2d())
b = tf.get_variable('b'... |
def _requantize(x, multiplier, zero_point, qmin=0, qmax=255, qtype=np.uint8):
qx = ((x * multiplier).round() + zero_point)
qx = np.clip(qx, qmin, qmax).astype(qtype)
return qx |
def test_random_sampler_empty_gt():
assigner = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.empty(0, 4)
gt_labels = torch.empty(0).long(... |
class EvaluationChunk(sqlalchemy_base):
__tablename__ = 'evaluation_chunks'
uuid = sqla.Column(sqla.String, primary_key=True)
creation_time = sqla.Column(sqla.DateTime(timezone=False), server_default=sqla.sql.func.now())
evaluation_uuid = sqla.Column(sqla.String, sqla.ForeignKey('evaluations.uuid'), nul... |
def epoch_wrapup(pl_module: LightningModule, mode: str):
assert (mode in ['train', 'val', 'test'])
value = getattr(pl_module, f'{mode}_loss').compute()
if (mode == 'train'):
pl_module.log(f'{mode}/loss_epoch', value)
getattr(pl_module, f'{mode}_loss').reset()
value = getattr(pl_module, f'{mo... |
def test_raw_tree():
con_sentences = convert_it_vit.read_constituency_sentences(io.StringIO(CON_SAMPLE))
expected_ids = ['#ID=sent_00002', '#ID=sent_00318', '#ID=sent_00589']
expected_trees = ["(ROOT (cp (sp (part negli) (sn (sa (ag ultimi)) (nt anni))) (f (sn (art la) (n dinamica) (spd (partd dei) (sn (n p... |
def test_pi_numpy():
def returnpi(result: dace.float64[1]):
result[0] = math.pi
a = np.random.rand(1)
returnpi(a)
assert np.allclose(a, np.array(math.pi)) |
def BModel2MLIR(bmodel_net: BModel):
with use_backend(bmodel_net.chip) as context:
if isinstance(context, BM1688Context):
coeff = bmodel_net.net[0].parameter[0].coeff_mem
if (coeff and (context.base_addr[0] != context.base_addr[1])):
context.base_addr[1] += len(coeff.... |
def define_E(opt):
netE_cls = find_network_using_name('conv', 'encoder')
return create_network(netE_cls, opt) |
def softmin(input, dim=None, _stacklevel=3):
if (dim is None):
dim = _get_softmax_dim('softmin', input.dim(), _stacklevel)
return (- input.softmax(dim)) |
class ActionDecoder(nn.Module):
def act(self, latent_plan: torch.Tensor, perceptual_emb: torch.Tensor, latent_goal: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
def loss(self, latent_plan: torch.Tensor, perceptual_emb: torch.Tensor, latent_goal: torch.Tensor, actions: torch.Tensor) -> torch.... |
class SetSeedCallback(Callback):
def __init__(self, seed=10, is_DDP=False):
self.seed = seed
self.is_DDP = is_DDP
def on_fit_start(self, trainer, pl_module):
if self.is_DDP:
if (not dist.is_available()):
raise RuntimeError('Requires distributed package to be a... |
def run_inference(args):
if (args.model in ['bridge', 'seq2seq', 'seq2seq.pg']):
sp = EncoderDecoderLFramework(args)
else:
raise NotImplementedError
sp.cuda()
with torch.set_grad_enabled(False):
inference(sp) |
def orderNodeList(nodelist):
newlist = sorted([n for n in nodelist], key=(lambda x: x.eduspan[1]))
return newlist |
class SelecSLS(nn.Module):
def __init__(self, cfg, num_classes=1000, in_chans=3, drop_rate=0.0, global_pool='avg'):
self.num_classes = num_classes
self.drop_rate = drop_rate
super(SelecSLS, self).__init__()
self.stem = conv_bn(in_chans, 32, stride=2)
self.features = Sequentia... |
class ExpandInplaceOperators(EnvTransform):
def visit_InPlaceAssignmentNode(self, node):
lhs = node.lhs
rhs = node.rhs
if lhs.type.is_cpp_class:
return node
if isinstance(lhs, ExprNodes.BufferIndexNode):
return node
env = self.current_env()
def... |
class ATSNmat(SpectralMatrix):
def assemble(self, method):
(test, trial) = (self.testfunction, self.trialfunction)
assert isinstance(test[0], T)
assert isinstance(trial[0], SN)
N = test[0].N
k = np.arange(N, dtype=float)
self._keyscale = 1
def _getkey(j):
... |
def xml_to_treceval(opt, input_file):
overwrite = opt.overwrite
res_file = (os.path.splitext(input_file)[0] + '.treceval')
if os.path.exists(res_file):
if overwrite:
logger.info(('%s exists. Overwrite' % res_file))
else:
logger.info(('%s exists. Use "--overwrite 1" if... |
def convert_f(args):
from .convert import convert
convert(args.files, args.dest_dir, args.verbose) |
def write_dataset(dataset, out_directory, dataset_name):
for (shard, phrases) in zip(SHARDS, dataset):
output_file = os.path.join(out_directory, ('%s.%s.json' % (dataset_name, shard)))
write_list(output_file, phrases) |
.parametrize('nuclide_name', ['Ni-56', 'Fe-52', 'Cr-48'])
def test_activity(gamma_ray_simulation_state, nuclide_name):
nuclide = rd.Nuclide(nuclide_name)
t_half = (nuclide.half_life() * u.s)
decay_constant = (np.log(2) / t_half)
time_delta = (1.0 * u.s)
composition = gamma_ray_simulation_state.compo... |
def _as_pairs(x, ndim, as_index=False):
if (x is None):
return (((None, None),) * ndim)
x = np.array(x)
if as_index:
x = np.round(x).astype(np.intp, copy=False)
if (x.ndim < 3):
if (x.size == 1):
x = x.ravel()
if (as_index and (x < 0)):
rai... |
class GetTestInfoTester(unittest.TestCase):
def test_get_test_to_tester_mapping(self):
bert_test_tester_mapping = get_test_to_tester_mapping(BERT_TEST_FILE)
blip_test_tester_mapping = get_test_to_tester_mapping(BLIP_TEST_FILE)
EXPECTED_BERT_MAPPING = {'BertModelTest': 'BertModelTester'}
... |
def printer(string, quiet=False, debug=False, error=False, **kwargs):
if (debug and (not DEBUG)):
return
if debug:
if sys.stdout.isatty():
out = ('\x1b[1;30mDEBUG: %s\x1b[0m' % string)
else:
out = ('DEBUG: %s' % string)
else:
out = string
if error:... |
class DPRReader(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def _impl(array, container, buffer_key, form_key, id_start, backend, byteorder):
layout = ak.operations.to_layout(array, allow_record=False, primitive_policy='error')
if (backend is not None):
backend = regularize_backend(backend)
return ak._do.to_buffers(layout, container=container, buffer_key=buff... |
def test_util():
rd = RecursiveDefaultDict()
rd['a']['new']['element'] = 'assigned'
Print.set_verbosity(VERBOSITY.VERBOSE)
Print.verbosity_region_begin(VERBOSITY.VERBOSE)
print(Print.style.header('this is a header!'))
Print.warn('This is a warning!')
Print.info('This is an informative messag... |
def PGL_repn(rational_function):
if is_Matrix(rational_function):
return rational_function
K = rational_function.parent()
F = K.base_ring()
if (not K.is_field()):
return matrix(F, 2, [rational_function[1], rational_function[0], 0, 1])
else:
f = rational_function.numerator()
... |
def check_output(n_channels: int, labels: np.ndarray):
n_labels = len(set(labels[(labels >= 0)]))
if ((n_labels > 2) and (n_labels > n_channels)):
raise ValueError('The dimension of the output is too small for the number of labels. Please check the `dims` parameter of your GNN or the `labels` parameter.... |
def test_residual_normalised_score_pipe() -> None:
pipe = Pipeline([('poly', PolynomialFeatures(degree=2)), ('linear', LinearRegression())])
mapie_reg = MapieRegressor(conformity_score=ResidualNormalisedScore(residual_estimator=pipe, split_size=0.2), cv='split', random_state=random_state)
mapie_reg.fit(np.c... |
def ToricCode(P, F):
from sage.combinat.tuple import Tuples
mset = [x for x in F if (x != 0)]
d = len(P[0])
pts = Tuples(mset, d).list()
n = len(pts)
k = len(P)
e = P[0]
B = []
for e in P:
tmpvar = [prod([(t[i] ** e[i]) for i in range(d)]) for t in pts]
B.append(tmpva... |
class TokenBlockDataset(torch.utils.data.Dataset):
def __init__(self, tokens, sizes, block_size, pad, eos, break_mode=None, include_targets=False):
super().__init__()
self.tokens = tokens
self.total_size = len(tokens)
self.pad = pad
self.eos = eos
self.include_targets... |
.parametrize('access', ['ro', 'rw', 'static_ro', 'static_rw'])
def test_property_return_value_policies(access):
if (not access.startswith('static')):
obj = m.TestPropRVP()
else:
obj = m.TestPropRVP
ref = getattr(obj, (access + '_ref'))
assert (ref.value == 1)
ref.value = 2
assert... |
class RandomHorizontalFlip(transforms.RandomHorizontalFlip):
def __init__(self, p=0.5):
super().__init__(p)
self._current_state = None
def forward(self, x):
return self.__call__(x)
def __call__(self, x, state=None):
if (state is None):
self._current_state = (rando... |
class Scorer(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self._updated = False
self._cached_results = {}
def update(self, results):
self._updated = True
def get_loss(self):
pass
def _get_results(self):
return []
def get_results(self, prefix=''... |
class GraphemePhonemeEncoder(text_encoder.TextEncoder):
def __init__(self, vocab_filename=None, vocab_list=None, separator='', num_reserved_ids=text_encoder.NUM_RESERVED_TOKENS):
super(GraphemePhonemeEncoder, self).__init__(num_reserved_ids=num_reserved_ids)
if (vocab_filename and os.path.exists(voc... |
class DateTimeField(Field):
widget = TextInput()
def __init__(self, label=None, validators=None, parse_kwargs=None, display_format='%Y-%m-%d %H:%M', **kwargs):
super(DateTimeField, self).__init__(label, validators, **kwargs)
if (parse_kwargs is None):
parse_kwargs = {}
self.p... |
class Trainer(BaseTrainer):
def __init__(self, model, train_criterion, metrics, optimizer, config, data_loader, valid_data_loader=None, test_data_loader=None, lr_scheduler=None, len_epoch=None, val_criterion=None):
super().__init__(model, train_criterion, metrics, optimizer, config, val_criterion)
s... |
def prune_stupid_effect_conditions(var, val, conditions, effects_on_var):
if (conditions == [[]]):
return False
assert (val in [0, 1])
dual_val = (1 - val)
dual_fact = (var, dual_val)
if (dual_val in effects_on_var):
return False
simplified = False
for condition in conditions... |
def add_common_eval_args(group):
group.add_argument('--path', metavar='FILE', help='path(s) to model file(s), colon separated')
group.add_argument('--remove-bpe', '--post-process', nargs='?', const=' ', default=None, help='remove BPE tokens before scoring (can be set to sentencepiece)')
group.add_argument('... |
class TimmResNetWrapper(nn.Module):
def __init__(self, net):
super().__init__()
self.net = net
def forward(self, x, return_features=True):
x = self.net.forward_features(x)
embedding = self.net.global_pool(x)
if self.net.drop_rate:
embedding = torch.nn.function... |
class DocumentState(object):
def __init__(self, key):
self.doc_key = key
self.sentence_end = []
self.token_end = []
self.tokens = []
self.subtokens = []
self.info = []
self.segments = []
self.subtoken_map = []
self.segment_subtoken_map = []
... |
def debug_print(s, *args):
if DEBUG_LOGGING:
formatted_args = [format_ops(arg) for arg in args]
print(('DEBUG ' + (s % tuple(formatted_args)))) |
class OneHot(TransformBase):
def __init__(self, drop=None, **kwargs):
super().__init__()
if (drop is None):
self.encoder = preprocessing.OneHotEncoder(handle_unknown='ignore', **kwargs)
else:
self.encoder = preprocessing.OneHotEncoder(drop=drop, **kwargs)
def fit(... |
def train():
memory.train()
gnn.train()
node_pred.train()
memory.reset_state()
neighbor_loader.reset_state()
total_loss = 0
label_t = dataset.get_label_time()
total_score = 0
num_label_ts = 0
for batch in tqdm(train_loader):
batch = batch.to(device)
optimizer.zero... |
def register_Ns3Timer_methods(root_module, cls):
cls.add_constructor([param('ns3::Timer const &', 'arg0')])
cls.add_constructor([])
cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')])
cls.add_method('Cancel', 'void', [])
cls.add_method('GetDelay', 'ns3::Time', [], is_const=Tru... |
.parametrize('return_text', ['{"error":"Model [model] is currently loading","estimated_time": [delay]}', '{"error":"Model [model] is currently loading"}', '{"error:}', ''])
.parametrize('image_model', ['CompVis/stable-diffusion-v1-4', 'stabilityai/stable-diffusion-2-1'])
.parametrize('delay', [10, 0])
def test_huggingf... |
def test_int_ineq_constraint(rng, u, geometry):
bounds = rng.random(2)
bounds.sort()
lower_bound = bounds[0]
upper_bound = bounds[1]
int_ineq_constraint_lower = cashocs.InequalityConstraint((u * geometry.dx), lower_bound=lower_bound)
int_ineq_constraint_upper = cashocs.InequalityConstraint((u * ... |
def inference_detector(model, imgs, cfg, device='cuda:0'):
img_transform = ImageTransform(size_divisor=cfg.data.test.size_divisor, **cfg.img_norm_cfg)
model = model.to(device)
model.eval()
if (not isinstance(imgs, list)):
return _inference_single(model, imgs, img_transform, cfg, device)
else... |
def torch_nn_functional_relu(x, inplace=False):
if (not inplace):
raise ValueError("Don't support in-place functional.relu for MetaTensor analysis")
return x |
def test_read_write_set():
sdfg = dace.SDFG('graph')
sdfg.add_array('A', [10], dace.float64)
sdfg.add_array('B', [10], dace.float64)
sdfg.add_array('C', [10], dace.float64)
state = sdfg.add_state('state')
task1 = state.add_tasklet('work1', {'A'}, {'B'}, 'B = A + 1')
task2 = state.add_tasklet... |
.parametrize('simulator', [wn.delayed_impact, wn.credit, wn.hiv, wn.lotka_volterra, wn.opioid, wn.world2, wn.world3, wn.zika], ids=['delayed_impact', 'credit', 'hiv', 'lotka_volterra', 'opioid', 'world2', 'world3', 'zika'])
def test_dynamics_initial_state(simulator):
initial_state = simulator.State()
config = s... |
class ContextGeneratorEval(object):
def __init__(self, context_file):
self.ctxs = []
with open(context_file, 'r') as f:
ctx_pair = []
for line in f:
ctx = line.strip().split()
ctx_pair.append(ctx)
if (len(ctx_pair) == 2):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.