code stringlengths 101 5.91M |
|---|
class DistModule(nn.Module):
def __init__(self, module, bn_method=0):
super(DistModule, self).__init__()
self.module = module
self.bn_method = bn_method
if (get_world_size() > 1):
broadcast_params(self.module)
else:
self.bn_method = 0
def forward(s... |
class ControlServicer(object):
def Start(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Stop(self, request, context):
context.set_code(grpc.StatusCode... |
class FlaxRobertaForTokenClassification(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def preprocess_blur_grayscale(net_preproc_fn, blur_radius=None, blur_prob=1.0, jitter=True):
preproc_fn = prepare_image_fn(jitter=jitter)
transform_list = [preproc_fn]
if ((blur_radius is not None) and (blur_prob > 0)):
transform_list.append(transforms.Lambda(generate_random_blur(blur_radius, blur_p... |
def check_gcc_function_attribute_with_intrinsics(cmd, attribute, name, code, include):
cmd._check_compiler()
body = (textwrap.dedent('\n #include<%s>\n int %s %s(void)\n {\n %s;\n return 0;\n }\n\n int\n main()\n {\n return 0;\n ... |
def drop_connect(x, drop_connect_rate, training):
if (not training):
return x
keep_prob = (1.0 - drop_connect_rate)
batch_size = x.shape[0]
random_tensor = keep_prob
random_tensor += torch.rand([batch_size, 1, 1, 1], dtype=x.dtype, device=x.device)
binary_mask = torch.floor(random_tensor... |
class TrainingArguments(transformers.TrainingArguments):
wandb_project: str = field(default=constants.WANDB_PROJECT)
cache_dir: Optional[str] = field(default=constants.DEFAULT_CACHE_DIR)
flash_attn: bool = field(default=False)
optim: str = field(default='adamw_torch')
truncate_tokens: Optional[List[... |
class AgentGroup(object):
def __init__(self, *agents, allow_duplicate_agents=False):
self.agents = agents
self.n = len(self.agents)
self.reset()
if (not all(((a0 is not a1) for (a0, a1) in itertools.combinations(agents, 2)))):
assert allow_duplicate_agents, 'All agents sh... |
def _get_ps_env(ps_info, config):
try:
parallax_log_level = os.environ['PARALLAX_LOG_LEVEL']
except:
parallax_log_level = logging.INFO
env = {'CUDA_VISIBLE_DEVICES': ','.join((str(gpuid) for gpuid in ps_info['gpus'])), 'PARALLAX_LOG_LEVEL': parallax_log_level, 'PARALLAX_RESOURCE_INFO': seria... |
def test_inout_connector_validation_success_2():
sdfg = dace.SDFG('test_inout_connector_validation_success_2')
sdfg.add_array('A', [1], dace.int32)
nsdfg_0 = dace.SDFG('nested_sdfg_0')
nsdfg_0.add_array('B', [1], dace.int32)
nsdfg_1 = dace.SDFG('nested_sdfg_1')
nsdfg_1.add_array('C', [1], dace.i... |
_pattern(torch.nn.modules.conv.Conv2d)
_pattern((torch.nn.ReLU, torch.nn.modules.conv.Conv2d))
_pattern((torch.nn.modules.batchnorm.BatchNorm2d, torch.nn.modules.conv.Conv2d))
_pattern((torch.nn.ReLU, (torch.nn.modules.batchnorm.BatchNorm2d, torch.nn.modules.conv.Conv2d)))
class ConvNormRelu(MinMaxObserver):
def __... |
def plot_legislative_allinOne():
fname = 'datasets/USLegis_processed/LegisEdgelist.txt'
G_times = USLegis_loader.load_legis_temporarl_edgelist(fname)
LAD = [3, 7]
label_sets = []
label_sets.append(LAD)
graph_name = 'USLegislative'
normal_util.all_in_one_compare(G_times, graph_name, label_set... |
class DensePoseDataPointsVisualizer(object):
def __init__(self, densepose_data_to_value_fn=None, cmap=cv2.COLORMAP_PARULA, **kwargs):
self.points_visualizer = PointsVisualizer()
self.densepose_data_to_value_fn = densepose_data_to_value_fn
self.cmap = cmap
def visualize(self, image_bgr: I... |
(Output('clustering-loglines', 'children'), [Input('cluster-hist', 'clickData')])
def update_logline_list(data):
if (len(data) > 0):
cluster_label = data['points'][0]['label']
df = log_clustering.get_loglines(cluster_label)
columns = [{'name': c, 'id': c} for c in df.columns]
return ... |
def trace_model(model, batch_size=256, device=torch.device('cpu')):
model.eval()
image_size = model.visual.image_size
example_images = torch.ones((batch_size, 3, image_size, image_size), device=device)
example_text = torch.zeros((batch_size, model.context_length), dtype=torch.int, device=device)
mod... |
class CliffordAlgebraIndices(UniqueRepresentation, Parent):
def __init__(self, Qdim):
self._nbits = Qdim
self._cardinality = (2 ** Qdim)
category = FiniteEnumeratedSets().Facade()
Parent.__init__(self, category=category, facade=True)
def _element_constructor_(self, x):
if... |
def exclude_test_and_train_images(kitti_dir, exclude_lists_dir, exclude_target_dir, remove=False):
to_move = []
def exclude_from_seq(day_name, seq_str, image, view, distance=10):
seq_dir_rel = os.path.join(day_name, seq_str, view, 'data')
seq_dir_abs = os.path.join(kitti_dir, seq_dir_rel)
... |
def proc(filename):
(tar, prd) = filename
tar_img = utils.load_img(tar)
prd_img = utils.load_img(prd)
PSNR = utils.calculate_psnr(tar_img, prd_img)
return PSNR |
class FullyConnectedLayer(Module):
def __init__(self, config, input_dim, output_dim, dropout_prob):
super(FullyConnectedLayer, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.dropout_prob = dropout_prob
self.dense = Linear(self.input_dim, self.ou... |
class ScanLengthResplit(torch.utils.data.Dataset):
in_sentences = []
out_sentences = []
index_table = {}
URL = '
def _load_dataset(self, cache_dir: str):
if ScanLengthResplit.in_sentences:
return
os.makedirs(cache_dir, exist_ok=True)
cache_file = os.path.join(cach... |
def test_max_three_scalars():
with goos.OptimizationPlan() as plan:
x = goos.Variable(2)
y = goos.Variable(3)
w = goos.Variable(1)
z = goos.max(x, y, w)
assert (z.get() == 3)
assert (z.get_grad([x])[0] == 0)
assert (z.get_grad([y])[0] == 1)
assert (z.g... |
(scope='session')
def atomic_data_fname(tardis_ref_path):
atomic_data_fname = ((tardis_ref_path / 'atom_data') / 'kurucz_cd23_chianti_H_He.h5')
atom_data_missing_str = f'{atomic_data_fname} atomic datafiles does not seem to exist'
if (not atomic_data_fname.exists()):
pytest.exit(atom_data_missing_st... |
def prepare_batch_inputs_qfvs(data, config, eval=False):
if (not eval):
(features, mask, seg_len, concept1_GT, concept2_GT, mask_GT, oracle_summary_GT, src_txt_1, src_txt_2, src_txt_mask_1, src_txt_mask_2, saliency_pos_labels_1, saliency_pos_labels_2, saliency_pos_labels_oracle) = (data['features'][0], data... |
def get_info(path):
info = torchaudio.info(path)
if hasattr(info, 'num_frames'):
return Info(info.num_frames, info.sample_rate, info.num_channels)
else:
siginfo = info[0]
return Info((siginfo.length // siginfo.channels), siginfo.rate, siginfo.channels) |
_numpy_output()
def test_transpose_axes2(A: dace.float32[(10, 5, 3, 2)]):
return np.transpose(A, axes=[3, 0, 2]) |
def low_memory_matrix_op(func, x, y, x_split_axis, y_split_axis, x_num_splits, y_num_splits, verbose=False, aligned=True):
if verbose:
import sys
import time
printed = False
st = time.time()
last_time = time.time()
mat = [[] for _ in range(x_num_splits)]
for (i, part_... |
def register_codecs():
def policy_encode(policy: jmp.Policy):
def name(dtype):
if hasattr(dtype, 'name'):
return dtype.name
elif hasattr(dtype, 'dtype'):
return name(dtype.dtype)
out = f'compute={name(policy.compute_dtype)},params={name(policy.... |
def get_modifier(mention):
head_span_in_mention = spans.Span((mention.attributes['head_span'].begin - mention.span.begin), (mention.attributes['head_span'].end - mention.span.begin))
modifiers = set()
for (index, (token, pos)) in enumerate(zip(mention.attributes['tokens'], mention.attributes['pos'])):
... |
def update_processor_add_transformer(resources, lang, current_processors, processor, transformer):
if (processor not in current_processors):
return
new_model = current_processors[processor].replace('_charlm', ('_' + transformer)).replace('_nocharlm', ('_' + transformer))
if (new_model in resources[l... |
def test_spec_format():
import h5py
quantities = ['ArealMass', 'ChristodoulouMass', 'CoordCenterInertial', 'DimensionfulInertialSpin', 'DimensionfulInertialSpinMag', 'chiInertial', 'chiMagInertial']
with contextlib.redirect_stdout(None):
catalog = sxs.load('catalog')
selected = catalog.select_fi... |
class AutoModelForQuestionAnswering():
def __init__(self):
raise EnvironmentError('AutoModelForQuestionAnswering is designed to be instantiated using the `AutoModelForQuestionAnswering.from_pretrained(pretrained_model_name_or_path)` or `AutoModelForQuestionAnswering.from_config(config)` methods.')
_list... |
def test_UnmaskedArray_NumpyArray():
v2a = ak.contents.unmaskedarray.UnmaskedArray(ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3])))
def f(out, obj):
out[0] = len(obj)
out[1] = (obj[1] if (obj[1] is not None) else 999.0)
out[2] = (obj[3] if (obj[3] is not None) else 999.... |
def register_Ns3Icmpv6NS_methods(root_module, cls):
cls.add_constructor([param('ns3::Icmpv6NS const &', 'arg0')])
cls.add_constructor([param('ns3::Ipv6Address', 'target')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
c... |
def generate_cpu_cuda_to_methods() -> Tuple[(str, str, str)]:
cpu = f'''
{tab}def cpu(self):
{dtab}return cpu(self)
'''
cuda = [f'{tab}def cuda(self, device=None):', f'''return cuda(self, device=device)
''']
to = [f'{tab}def to(self, *args, **kwargs):', 'return to(self, *args, **kwargs)']
return (cpu, f... |
def resize_img(raw_img):
(w, h) = raw_img.size
scaling_factor = (240 / w)
resized_image = raw_img.resize((int((w * scaling_factor)), int((h * scaling_factor))))
return resized_image |
def plotly_plot(df, extra_df=None):
(traces, index) = ([], 0)
color_list = plotly.colors.qualitative.Dark24
for i in range(df.shape[1]):
v = df[[df.columns[i]]]
color = color_list[(index % len(color_list))]
traces.append(go.Scatter(name=f'{df.columns[i]}', x=v.index, y=v.values.flatt... |
def _compute_lwork(routine, *args, **kwargs):
dtype = getattr(routine, 'dtype', None)
int_dtype = getattr(routine, 'int_dtype', None)
ret = routine(*args, **kwargs)
if (ret[(- 1)] != 0):
raise ValueError(('Internal work array size computation failed: %d' % (ret[(- 1)],)))
if (len(ret) == 2):... |
def load_histology_shard(shard_num, collaborator_count, categorical=False, channels_last=False, **kwargs):
(img_rows, img_cols) = (150, 150)
num_classes = 8
((X_train, y_train), (X_valid, y_valid)) = _load_raw_datashards(shard_num, collaborator_count)
if channels_last:
X_train = X_train.reshape(... |
class Dataset(object):
__metaclass__ = ABCMeta
def __init__(self, name, subset):
assert (subset in self.available_subsets()), self.available_subsets()
self.name = name
self.subset = subset
def num_classes(self):
pass
def num_examples_per_epoch(self):
pass
def ... |
def draw_bbox(img, bboxes, c=(255, 0, 255)):
for bbox in bboxes:
color = COLORS[int(bbox[5])]
cv2.rectangle(img, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2, lineType=cv2.LINE_AA)
ct = [((bbox[0] + bbox[2]) / 2), ((bbox[1] + bbox[3]) / 2)]
txt = '{}'.format(i... |
class SelectAlternatives(object):
def __init__(self, system, gold, fields='eid'):
self.system = system
self.gold = gold
self.fields = (fields.split(',') if (fields != '*') else '*')
def _get_key(self, candidate):
if (self.fields == '*'):
return (candidate.eid, candida... |
class XmodPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_defaultdict_config():
lang_configs = defaultdict((lambda : dict(processors='tokenize')))
run_multilingual_pipeline(en_has_dependencies=False, fr_has_dependencies=False, lang_configs=lang_configs)
lang_configs = defaultdict((lambda : dict(processors='tokenize')))
lang_configs['en'] = {'processor... |
def test():
index = ak.Array(ak.contents.ListOffsetArray(ak.index.Index64([0, 3, 5]), ak.contents.NumpyArray(np.array([True, False, False, True, True, False, False], dtype=np.bool_))))
array = ak.Array([[0, 1, 2], [3, 4]])
result = array[index]
assert (result.tolist() == [[0], [3, 4]]) |
def ud_scores(gold_conllu_file, system_conllu_file):
try:
gold_ud = ud_eval.load_conllu_file(gold_conllu_file)
except UDError as e:
raise UDError(('Could not read %s' % gold_conllu_file)) from e
try:
system_ud = ud_eval.load_conllu_file(system_conllu_file)
except UDError as e:
... |
_function_dispatch(_fftn_dispatcher)
def ifft2(a, s=None, axes=((- 2), (- 1)), norm=None):
return _raw_fftnd(a, s, axes, ifft, norm) |
def test_aposteriori():
(pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers()
rng = np.random.RandomState(123456)
a_posteriori = APosteriori(pool_classifiers, random_state=rng)
a_posteriori.fit(X_dsel, y_dsel)
assert np.isclose(a_posteriori.score(X_test, y_test), 0.) |
class GroupOp(Operation):
def __init__(self, opd_id: str, op_type: OperationType, ops: List[Operation], attrs: Attributes, input_types: List[Type], output_types: List[Type], loc_label: LocLabel) -> None:
assert isinstance(opd_id, str)
assert (':' not in opd_id)
if (len(output_types) == 1):
... |
class ConvReLU3d(nnq.Conv3d):
_FLOAT_MODULE = torch.nn.intrinsic.ConvReLU3d
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros'):
assert (padding_mode != 'reflect'), 'Conv3d does not support reflection padding'
sup... |
def SVD_perSlice(G_times, directed=True, num_eigen=6, top=True, max_size=500):
Temporal_eigenvalues = []
activity_vecs = []
counter = 0
for G in G_times:
if (len(G) < max_size):
for i in range(len(G), max_size):
G.add_node(((- 1) * i))
if directed:
... |
def original_fid(F):
return (((F ** 2) + (((1 - F) / 3) ** 2)) / (((F ** 2) + (((2 * F) * (1 - F)) / 3)) + (5 * (((1 - F) / 3) ** 2)))) |
class GenerationMsgType(Enum):
NEGOTIATE = auto()
NEGOTIATE_ACK = auto()
MEAS_RES = auto() |
class BaseDataset(Dataset):
def __init__(self, vis_processor=None, text_processor=None, vis_root=None, ann_paths=[]):
self.vis_root = vis_root
self.annotation = []
for ann_path in ann_paths:
self.annotation.extend(json.load(open(ann_path, 'r'))['annotations'])
self.vis_pr... |
def _eval_func_get_epoch(self: LayerBase, **_kwargs) -> tf.Tensor:
run_opts = self.network.get_root_network().get_run_opts()
def _py_func_get_epoch() -> int:
return run_opts['epoch']
(epoch,) = tf_compat.v1.py_func(_py_func_get_epoch, [], [tf.int32], stateful=True)
assert isinstance(epoch, tf.Te... |
def splint(xa, ya, y2a, n, x):
klo = 0
khi = (n - 1)
while ((khi - klo) > 1):
k = ((khi + klo) >> 1)
if (xa[k] > x):
khi = k
else:
klo = k
h = (xa[khi] - xa[klo])
if (h == 0):
print('Bad xa input to routine splint')
return 1e309
a =... |
def convert_to_string(data):
if isinstance(data, bytes):
return data.decode('utf-8')
elif isinstance(data, list):
return [convert_to_string(d) for d in data]
else:
return data |
def merge_csvs(ins, out):
count = 0
with open(out, 'a+') as out_f:
for in_file in sorted(ins):
with open(in_file, 'r') as in_f:
for line in in_f:
out_f.write(line)
count += 1
return count |
def test_propagate_strict():
strict_sdfg = propagate_strict.to_sdfg(simplify=True)
assert (len(list(strict_sdfg.all_sdfgs_recursive())) == 1)
non_strict_sdfg = propagate_strict.to_sdfg(simplify=False)
assert (len(list(non_strict_sdfg.all_sdfgs_recursive())) > 1) |
class CudaError(RuntimeError):
def __init__(self, code):
msg = cudart().cudaGetErrorString(code).decode('utf-8')
super(CudaError, self).__init__('{0} ({1})'.format(msg, code)) |
class AlproBaseDataset(Dataset):
def __init__(self, datalist, tokenizer, img_lmdb_dir, img_db_type='lmdb', fps=3, num_frm=3, frm_sampling_strategy='rand', max_img_size=(- 1), max_txt_len=20):
self.fps = fps
self.num_frm = num_frm
self.frm_sampling_strategy = frm_sampling_strategy
sel... |
()
('--batch_size', type=int, default=4000)
_experiment
def trpo_cubecrash(ctxt=None, seed=1, batch_size=4000):
set_seed(seed)
with LocalTFRunner(ctxt) as runner:
env = GarageEnv(normalize(gym.make('CubeCrash-v0')))
policy = CategoricalCNNPolicy(env_spec=env.spec, filters=((32, (8, 8)), (64, (4,... |
def multiple_databases():
os.makedirs(DB_PATH)
_ = SingleDatabase(db_path=DB_PATH, db_name=f'{DB_NAME}_1', tables={TABLE_NAME: TABLE_DATAFRAME})
_ = SingleDatabase(db_path=DB_PATH, db_name=f'{DB_NAME}_2', tables={TABLE_NAME: TABLE_DATAFRAME})
_ = SingleDatabase(db_path=DB_PATH, db_name=f'{DB_NAME}_3', t... |
def maxp(cg, priority=3, background_knowledge=None):
assert (priority in [0, 1, 2, 3, 4])
cg_new = deepcopy(cg)
UC_dict = {}
UT = [(i, j, k) for (i, j, k) in cg_new.find_unshielded_triples() if (i < k)]
for (x, y, z) in UT:
if ((background_knowledge is not None) and (background_knowledge.is_... |
def default_regression_model(num_anchors, pyramid_feature_size=256, regression_feature_size=256, name='regression_submodel'):
options = {'kernel_size': 3, 'strides': 1, 'padding': 'same', 'kernel_initializer': keras.initializers.normal(mean=0.0, stddev=0.01, seed=None), 'bias_initializer': 'zeros'}
inputs = ker... |
.parametrize('reference', [0.0, [0.0], [[0.0]]])
def test_pareto_hypervolume_indicator_raises_for_reference_with_invalid_shape(reference: SequenceN[float]) -> None:
pareto = Pareto(tf.constant([[(- 1.0), (- 0.6)], [(- 0.8), (- 0.7)], [(- 0.6), (- 1.1)]]))
with pytest.raises(TF_DEBUGGING_ERROR_TYPES):
pa... |
def masked_loss(loss_fn, pred, data, mask):
return (loss_fn(pred, data.expand_as(pred), reduction='none') * mask) |
class LoggingBackend(GenericBackend):
def __init__(self, backend, printing=True, doctest=None, test_method=None, base_ring=None):
self._backend = backend
self._printing = printing
self._doctest = doctest
self._test_method = test_method
self._base_ring = base_ring
def __ge... |
class SymmetricGraphPreProcessingLayer(Layer):
def __init__(self, num_of_nodes, **kwargs):
self.output_dims = (num_of_nodes, num_of_nodes)
super().__init__(**kwargs)
def build(self, input_shape):
super().build(input_shape)
def call(self, adj):
adj_T = tf.transpose(adj)
... |
def test_process_predictions_zeros(example_diversity_ones_zeros):
(y, y_pred_ones, y_pred_zeros) = example_diversity_ones_zeros
(N00, N10, N01, N11) = _process_predictions(y, y_pred_zeros, y_pred_zeros)
assert ((N00 == (6.0 / 15.0)) and (N11 == (9.0 / 15.0)) and (N01 == 0.0) and (N10 == 0.0)) |
def debug(env, obs, agent_info):
try:
import matplotlib.pyplot as plt
except ImportError as e:
print('could not import matplotlib')
global ax1
global ax2
if (ax1 is None):
(_, (ax1, ax2)) = plt.subplots(1, 2)
subgoal_seq = agent_info['subgoal_seq']
planned_action_seq ... |
def resize_output(t, height, width, channels):
return tf.image.resize_bilinear(t, [height, width]) |
def test_1d_1d_different_dtypes_stride_trick():
data = np.array([101], dtype=np.int64)
array = np.lib.stride_tricks.as_strided(data, (40,), strides=(0,))
container = {'node0-data': array}
form = '\n {\n "class": "NumpyArray",\n "primitive": "int32",\n "form_key": ... |
class AssertNoJIT():
def __enter__(self):
import os
enabled = os.environ.get('PYTORCH_JIT', 1)
assert (not enabled)
def __exit__(self, *args, **kwargs):
pass |
def add_lsh_self_attention_layer(d, input, output, inside_rec_layer=True, past_only=None, time_axis=None, *, num_heads=8, num_rounds=1, key_dim=64, value_dim=64, dropout=0.0, num_hashes, chunk_size, chunks_before=None, chunks_after=None, ff_init=("variance_scaling_initializer(mode='fan_in', distribution='uniform', scal... |
def get_norm(norm, out_channels, num_gn_groups=32):
if isinstance(norm, str):
if (len(norm) == 0):
return None
norm = {'BN': BatchNorm2d, 'SyncBN': (NaiveSyncBatchNorm if (env.TORCH_VERSION <= (1, 5)) else nn.SyncBatchNorm), 'FrozenBN': FrozenBatchNorm2d, 'GN': (lambda channels: nn.Group... |
def test_case146():
url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert')
headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata145), headers=headers)
print(r.conten... |
def get_all_data(pairs, n_objs):
text = {}
for (src, tgt) in pairs:
pair = f'{src}-{tgt}'
cmd = f'sacrebleu -t wmt19 -l {pair} --echo src'.split()
src_lines = subprocess.run(cmd, stdout=subprocess.PIPE).stdout.decode('utf-8').splitlines()
cmd = f'sacrebleu -t wmt19 -l {pair} --ec... |
def divide_int_str_attributes(files, attrs):
(str_attr, int_attr) = ([], [])
for a in attrs:
if (a == 'n'):
if (a not in int_attr):
int_attr.append(a)
for i in files:
with open(i, 'r') as f:
columns = f.readline()[:(- 1)].split(',')
... |
def validate(opt, val_loader, model):
(img_embs, cap_embs) = encode_data(model, val_loader, opt.log_step, logging.info)
(r1, r5, r10, medr, meanr) = i2t(img_embs, cap_embs, measure=opt.measure)
logging.info(('Image to text: %.1f, %.1f, %.1f, %.1f, %.1f' % (r1, r5, r10, medr, meanr)))
(r1i, r5i, r10i, me... |
(ignore_result=True)
def execute_user_task():
seeds = SeedidsOper.get_seed_ids()
if seeds:
for seed in seeds:
app.send_task('tasks.user.crawl_person_infos', args=(seed.uid,), queue='user_crawler', routing_key='for_user_info') |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('upstream', help='The upstream name. E.g. wav2vec2')
parser.add_argument('problem', help='The problem module. E.g. s3prl.problem.SuperbSID')
parser.add_argument('dataset_root', help='The dataset root of your problem.')
parser.a... |
class MSMT17(BaseImageDataset):
dataset_dir = 'msmt17'
def __init__(self, root='/home/haoluo/data', verbose=True, **kwargs):
super(MSMT17, self).__init__()
self.dataset_dir = osp.join(root, self.dataset_dir)
self.train_dir = osp.join(self.dataset_dir, 'MSMT17_V2/mask_train_v2')
s... |
class AttnConnector(nn.Module):
def __init__(self, rnn_cell, query_size, key_size, content_size, output_size, attn_size):
super(AttnConnector, self).__init__()
self.query_embed = nn.Linear(query_size, attn_size)
self.key_embed = nn.Linear(key_size, attn_size)
self.attn_w = nn.Linear(... |
_native_function
def compute_declaration_yaml(f: NativeFunction) -> object:
(returns, name_to_field_name) = compute_returns_yaml(f)
kwarg_only_set = set((a.name for a in f.func.kwarg_only_arguments))
out_arg_set = set((a.name for a in f.func.out_arguments))
cpp_args = cpp.arguments(f.func)
arguments... |
class ResNetDecoder(Generator):
def __init__(self, in_channels, out_channels, n_channels=64, res_blocks=4, n_upsample=2, normalization=nn.InstanceNorm2d, activation=None, bias=True, gaussian_upsample=True):
super(ResNetDecoder, self).__init__()
self.in_channels = in_channels
self.out_channel... |
def load_fields_from_vocab(vocab, data_type='text'):
vocab = dict(vocab)
n_src_features = len(collect_features(vocab, 'src'))
n_tgt_features = len(collect_features(vocab, 'tgt'))
fields = get_fields(data_type, n_src_features, n_tgt_features)
for (k, v) in vocab.items():
v.stoi = defaultdict(... |
.parametrize('action_dist, estimated_rewards_by_reg_model, description', invalid_input_of_create_estimator_inputs)
def test_meta_create_estimator_inputs_using_invalid_input_data(action_dist, estimated_rewards_by_reg_model, description: str, synthetic_bandit_feedback: BanditFeedback) -> None:
ope_ = OffPolicyEvaluat... |
def load_tf_weights_in_bert_generation(*args, **kwargs):
requires_backends(load_tf_weights_in_bert_generation, ['torch']) |
def tensor_size_bytes(tensor):
if ((tensor is None) or (not tensor.is_cuda)):
return 0
return (tensor.numel() * tensor.element_size()) |
class AverageMeter(object):
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += ... |
def _observe(state: State, player_id: Array) -> Array:
board: Array = state._board
playable_dice_count_vec: Array = _to_playable_dice_count(state._playable_dice)
return jax.lax.cond((player_id == state.current_player), (lambda : jnp.concatenate((board, playable_dice_count_vec), axis=None)), (lambda : jnp.co... |
def traverse_dir(root_dir, extension=('mid', 'MID', 'midi'), amount=None, str_=None, is_pure=False, verbose=False, is_sort=False, is_ext=True):
if verbose:
print('[*] Scanning...')
file_list = []
cnt = 0
for (root, _, files) in os.walk(root_dir):
for file in files:
if file.en... |
def register_Ns3CallbackImplBase_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True)
cls.add_method('IsEqual', 'bool', [param('ns3::Pt... |
class ImageNetDataNP():
def __init__(self, folder_path):
test_data = np.load(os.path.join(folder_path, 'imagenet_test_data.npy'))
test_labels = np.load(os.path.join(folder_path, 'imagenet_test_labels.npy'))
self.test_data = test_data
self.test_labels = test_labels |
def read_fasta_sequence(numeric, fasta_file):
first_char = fasta_file.read(1)
if (first_char == ''):
return ['', '']
elif (first_char == '>'):
line = ''
else:
line = first_char
line = (line + fasta_file.readline())
words = line.split()
if (len(words) == 0):
sy... |
def infer(env, agent, **kwargs):
obs = env.reset()
dones = False
total_reward_weights = 0
while (not dones):
(action, _) = agent.predict(obs)
(obs, rewards, dones, info) = env.step(action)
total_reward_weights += rewards
if dones:
break
show_state(env,... |
def get_task_configuration(config) -> List:
if hasattr(config, 'sub_task'):
mode = '{} {}'.format(config.task, config.sub_task)
else:
mode = config.task
requested_configurations = [task_config() for task_config in TaskConfiguration.__subclasses__() if (task_config.mode() == mode)]
if (le... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--encoder-json', help='path to encoder.json')
parser.add_argument('--vocab-bpe', type=str, help='path to vocab.bpe')
parser.add_argument('--inputs', nargs='+', default=['-'], help='input files to filter/encode')
parser.add_argument(... |
def confidence_interval(data: ArrayLike, func: Callable[([ArrayLike], NDArray)]=np.mean, size: int=1000, ci: int=95, seed: Optional[int]=None) -> float:
bs_replicates = bootstrap(data, func=func, n_boot=size, seed=seed)
p = ((50 - (ci / 2)), (50 + (ci / 2)))
bounds = np.nanpercentile(bs_replicates, p)
r... |
def small_bn_opp_resnet(image, test=False, w_bias=False, channel_last=False, name='bn-graph-ref', dims=2):
kernel = ((3,) * dims)
pool_kernel = ((2,) * dims)
pad = ((1,) * dims)
h = image
h /= 255.0
axes = get_channel_axes(h, channel_last, dims)
h = PF.batch_normalization(h, axes=axes, batch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.