code stringlengths 101 5.91M |
|---|
class DiagonalGaussian(Distribution):
def __init__(self, dim):
self._dim = dim
def dim(self):
return self._dim
def kl(self, old_dist_info, new_dist_info):
old_means = old_dist_info['mean']
old_log_stds = old_dist_info['log_std']
new_means = new_dist_info['mean']
... |
def main(argv):
parser = argparse.ArgumentParser(description='Dump dataset or subset of dataset into external HDF dataset')
parser.add_argument('config_file_or_dataset', type=str, help='Config file for RETURNN, or directly the dataset init string')
parser.add_argument('hdf_filename', type=str, help='File na... |
def convert_conv2convsamepadding_model(module, process_group=None, channel_last=False):
mod = module
if isinstance(module, torch.nn.modules.conv._ConvNd):
if isinstance(module.bias, torch.Tensor):
bias = True
else:
bias = False
mod = ops.Conv2dSamePadding(module.i... |
def duplicate_transition_add_input(old_transition, new_transition):
if (isinstance(old_transition.word_in, Iterable) and (len(old_transition.word_in) == 1) and isinstance(new_transition.word_in, Iterable) and (len(new_transition.word_in) == 1)):
old_transition.word_in = [(old_transition.word_in[0] + new_tra... |
class DRIT(object):
def __init__(self, sess, args):
self.model_name = 'DRIT'
self.sess = sess
self.checkpoint_dir = args.checkpoint_dir
self.result_dir = args.result_dir
self.log_dir = args.log_dir
self.sample_dir = args.sample_dir
self.dataset_name = args.dat... |
class HuffmanMMapIndex():
_HDR_MAGIC = b'HUFFIDX\x00\x00'
_VERSION = 1
def writer(cls, path: str, data_len: int):
class _Writer():
def __enter__(self):
self._file = open(path, 'wb')
self._file.write(cls._HDR_MAGIC)
self._file.write(struct.p... |
def _compute_aspect_ratios_voc_dataset(dataset, indices=None):
if (indices is None):
indices = range(len(dataset))
aspect_ratios = []
for i in indices:
(width, height) = Image.open(dataset.images[i]).size
aspect_ratio = (float(width) / float(height))
aspect_ratios.append(aspe... |
def layer_graph_t5_3b_tied_lmheads_512_4_8p_bw12_squad1_pipedream():
return dict(model_type='t5_stateless', model_name_or_path='t5-3b', do_lower_case=False, output_past=False, stateless_tied=True, explicitly_set_dict={'return_dict': False, 'use_cache': False, 'output_only': True, 'output_attentions': False, 'precom... |
def load_from_ckpt(dynamics: Dynamics, optimizer: torch.optim.Optimizer, cfg: DictConfig) -> tuple[(torch.nn.Module, torch.optim.Optimizer, dict)]:
outdir = Path(cfg.get('outdir', os.getcwd()))
if (not (ckpts := list(outdir.joinpath('train', 'checkpoints').rglob('*.tar')))):
raise FileNotFoundError(f'No... |
def test_sag_multiclass_classes():
(X, y) = make_classification(n_samples=10, random_state=0, n_classes=3, n_informative=4)
sag = SAGClassifier()
sag.fit(X, y)
assert (list(sag.classes_) == [0, 1, 2]) |
def add_stats(model):
with tf.variable_scope('stats') as scope:
tf.summary.histogram('linear_outputs', model.linear_outputs)
tf.summary.histogram('linear_targets', model.linear_targets)
tf.summary.histogram('mel_outputs', model.mel_outputs)
tf.summary.histogram('mel_targets', model.m... |
def load_archive(archive_file: str, device=None, weights_file: str=None) -> Archive:
resolved_archive_file = cached_path(archive_file)
if (resolved_archive_file == archive_file):
logger.info(f'loading archive file {archive_file}')
else:
logger.info(f'loading archive file {archive_file} from ... |
def cluster_layout(G, pos_nodes, pos_clusters):
pos = {}
for node in G.nodes():
pos[node] = (pos_nodes[node] + pos_clusters[node])
return pos |
def test_evaluate_coverage(tmpdir):
from skmultiflow.data import SEAGenerator
from skmultiflow.bayes import NaiveBayes
max_samples = 1000
stream = SEAGenerator(random_state=1)
nb = NaiveBayes()
output_file = os.path.join(str(tmpdir), 'prequential_summary.csv')
metrics = ['running_time', 'mod... |
class LRSchedulerFactory(abc.ABC):
def create(self, optimizer: torch.optim.Optimizer) -> torch.optim.lr_scheduler._LRScheduler: |
_module()
class RFP(FPN):
def __init__(self, rfp_steps, rfp_backbone, aspp_out_channels, aspp_dilations=(1, 3, 6, 1), init_cfg=None, **kwargs):
assert (init_cfg is None), 'To prevent abnormal initialization behavior, init_cfg is not allowed to be set'
super().__init__(init_cfg=init_cfg, **kwargs)
... |
def train_step(ds_one, ds_two, f, h, optimizer):
with tf.GradientTape() as tape:
(z1, z2) = (f(ds_one), f(ds_two))
(p1, p2) = (h(z1), h(z2))
loss = ((loss_func(p1, z2) / 2) + (loss_func(p2, z1) / 2))
learnable_params = (f.trainable_variables + h.trainable_variables)
gradients = tape.... |
def test_sub():
var1 = optplan.Parameter()
var2 = optplan.Parameter()
diff = (var2 - var1)
assert isinstance(diff, optplan.Sum) |
def mk_vs_proj_dep_groups(f, name, components):
f.write(' <ItemGroup>\n')
deps = find_all_deps(name, components)
for dep in deps:
dep = get_component(dep)
for cpp in filter((lambda f: f.endswith('.cpp')), os.listdir(dep.src_dir)):
f.write((' <ClCompile Include="%s" />\n' % os... |
def test(encoder, classifier, test_loader, imagenet_loader, args, epoch, tb_logger):
with torch.no_grad():
encoder.eval()
classifier.eval()
top1_webvision = AverageMeter('', ':4.2f')
top5_webvision = AverageMeter('', ':4.2f')
top1_imagenet = AverageMeter('', ':4.2f')
... |
def parse_args():
parser = argparse.ArgumentParser(description='Check cuckoo oracle for the PDFs generated by reverse mimicry.')
parser.add_argument('--var_dir', type=str, help='Variant files directory.', required=True)
return parser.parse_args() |
class EpochBatchIterator(EpochBatchIterating):
def __init__(self, dataset, collate_fn, batch_sampler, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=0):
assert isinstance(dataset, torch.utils.data.Dataset)
self.dataset = dataset
self.collate_fn = collate_fn
self.frozen_batche... |
def noncat_slot_value_match(str_ref_list, str_hyp, use_fuzzy_match):
score = 0.0
for str_ref in str_ref_list:
if (not use_fuzzy_match):
match_score = float((str_ref == str_hyp))
else:
match_score = fuzzy_string_match(str_ref, str_hyp)
score = max(score, match_scor... |
class StructOrUnionScope(Scope):
def __init__(self, name='?'):
Scope.__init__(self, name, None, None)
def declare_var(self, name, type, pos, cname=None, visibility='private', api=0, in_pxd=0, is_cdef=0, allow_pyobject=False, allow_memoryview=False):
if (not cname):
cname = name
... |
def require_pandas(test_case):
return unittest.skipUnless(is_pandas_available(), 'test requires pandas')(test_case) |
class BatchNorm(nn.Module):
def __init__(self, out_channels):
super(BatchNorm, self).__init__()
self.batch_norm = nn.BatchNorm3d(num_features=out_channels)
def forward(self, input):
(x, m) = input
x = self.batch_norm(x)
return (x, m) |
def test_init():
tracer = ExecutionTracer()
tracer.current_thread_identifier = threading.current_thread().ident
tracer.register_code_object(MagicMock(CodeObjectMetaData))
tracer.executed_code_object(0)
trace = tracer.get_trace()
tracer.init_trace()
assert (tracer.get_trace() != trace) |
def test_gimvi_model_library_size():
adata_seq = synthetic_iid()
adata_spatial = synthetic_iid()
GIMVI.setup_anndata(adata_seq, batch_key='batch', labels_key='labels')
GIMVI.setup_anndata(adata_spatial, batch_key='batch', labels_key='labels')
model = GIMVI(adata_seq, adata_spatial, model_library_siz... |
def load_bin(path, fill=0.0):
with open(path, 'rb') as f:
bb = f.read((4 * 4))
v = struct.unpack('4i', bb)
bb = f.read((v[0] * 4))
v = struct.unpack(('%df' % v[0]), bb)
feature = np.full(((feature_dim + feature_ext),), fill, dtype=np.float32)
feature[0:feature_dim] = ... |
def assert_similar(ref, real):
np.testing.assert_equal(len(ref), len(real))
for i in range(len(ref)):
np.testing.assert_allclose(ref[i], real[i], rtol=0.001) |
.parametrize('workers', (1, 2))
def test_connection_error(cli, schema_url, workers, snapshot_cli):
assert (cli.run(schema_url, '--base-url= f'--workers={workers}') == snapshot_cli) |
class InfoSet(object):
def __init__(self, player_position):
self.player_position = player_position
self.player_hand_cards = None
self.num_cards_left_dict = None
self.three_landlord_cards = None
self.card_play_action_seq = None
self.other_hand_cards = None
self... |
def set_blob_potential(implementation):
if (implementation == 'None'):
def default_zero_r_vectors(*args, **kwargs):
return 0
return default_zero
elif (implementation == 'python'):
return calc_blob_potential_python
elif (implementation == 'C++'):
return calc_blob_p... |
def pevaluate(q):
while True:
args = q.get()
if (args is None):
q.task_done()
break
evaluate(*args)
q.task_done() |
class ConvLSTMCell(rnn_cell_impl.RNNCell):
def __init__(self, conv_ndims, input_shape, output_channels, kernel_shape, dilation=1, use_bias=True, skip_connection=False, forget_bias=1.0, initializers=None, name='conv_lstm_cell'):
super(ConvLSTMCell, self).__init__(name=name)
if (conv_ndims != (len(inp... |
class BitBackbone(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def clear_all_gradients(gradient_type=SNodeGradType.ADJOINT):
impl.get_runtime().materialize()
def visit(node):
places = []
for _i in range(node.ptr.get_num_ch()):
ch = node.ptr.get_ch(_i)
if (not ch.is_place()):
visit(SNode(ch))
elif (ch.get_s... |
def list_dir_single(directory):
for (root, dirs, files) in os.walk(directory):
return dirs |
def _convert_when(when):
if isinstance(when, np.ndarray):
return when
try:
return _when_to_num[when]
except (KeyError, TypeError):
return [_when_to_num[x] for x in when] |
def register_Ns3NetDevice_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::em... |
class TextDataset(Dataset):
def __init__(self, fname, vocab, bos=False):
self.path = Path(fname)
self.vocab = vocab
self.bos = bos
self.fnames = sorted(self.path.parent.glob(self.path.name))
if (len(self.fnames) == 0):
raise RuntimeError('{} does not exist.'.forma... |
def register_Ns3FqCoDelQueueDisc_methods(root_module, cls):
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_constructor([])
cls.add_method('SetQuantum', 'void', [param('uint32_t', 'quantum')])
cls.add_method('GetQuantum', 'uint32_t', [], is_const=True)
cls.add_static_attribute... |
def test_block_reduce_sum():
image1 = np.arange((4 * 6)).reshape(4, 6)
out1 = block_reduce(image1, (2, 3))
expected1 = np.array([[24, 42], [96, 114]])
assert_equal(expected1, out1)
image2 = np.arange((5 * 8)).reshape(5, 8)
out2 = block_reduce(image2, (3, 3))
expected2 = np.array([[81, 108, 8... |
class NoBNSecondMomentTest(BaseSecondMomentTest):
def __init__(self, unit_test):
self.i = 0
super().__init__(unit_test, linear_layer=layers.Conv2D)
def create_networks(self):
inputs = layers.Input(shape=self.get_input_shapes()[0][1:])
x = self.linear_layer(1, 1, padding='same', k... |
class TrainedTernaryConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0):
super(TrainedTernaryConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = (kernel_size, kernel_size)
self.... |
class DownBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, drop=0):
super(DownBlock, self).__init__()
padding = int(((kernel_size - 1) / 2))
self.block_conv = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=padding), nn.Dropout2... |
def build_adadelta(model, base_learning_rate, parameters=None, max_gradient_norm=None, allow_lr_injection=False, **kwargs):
adadelta_optimizer = AdadeltaOptimizer(alpha=base_learning_rate, **kwargs)
return _build(model, adadelta_optimizer, max_gradient_norm=max_gradient_norm, allow_lr_injection=allow_lr_injecti... |
class RecordArray(Content):
def __init__(self, contents, recordlookup, length):
assert isinstance(contents, list)
if (len(contents) == 0):
assert isinstance(length, int)
assert (length >= 0)
else:
assert (length is None)
for x in contents:
... |
class ConvNet2D(nn.Module):
def __init__(self, embed_dim, num=50, width=7):
super(ConvNet2D, self).__init__()
self.relu = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d((2 * embed_dim), num, 1)
self.conv2 = nn.Conv2d(num, 1, width, padding=(width // 2))
self.clip()
def forw... |
def main():
p = argparse.ArgumentParser(__doc__.strip())
p.add_argument('range', help=argparse.SUPPRESS)
p.add_argument('-d', '--debug', action='store_true', help='print debug output')
p.add_argument('-n', '--new', action='store_true', help='print debug output')
options = p.parse_args()
try:
... |
def rand_unit_3d():
u = rand_unit_2d()
s = ((ti.random() * 2) - 1)
c = ti.sqrt((1 - (s ** 2)))
return ti.Vector([(c * u[0]), (c * u[1]), s]) |
def fit_model_cv(config_data, model, train_iterator, valid_iterator):
assert (train_iterator.type == 'loader')
nb_epochs = config_data['nb_epochs']
batch_size = config_data['batch_size']
X_train = train_iterator.input_data
y_train = train_iterator.output_data
kf = KFold(n_folds=5, shuffle=True, ... |
def add_ml_lib(name, deps=[], path=None, lib_name=None):
c = MLComponent(name, lib_name, path, deps)
reg_component(name, c) |
class TensorInfo():
def __init__(self):
self.tensor_id = (- 1)
self.shape = None
self.dtype = DataType.UNKNOWN
self.is_const = False
self.gaddr = (- 1)
self.gsize = 0
self.loffset = (- 1)
self.nslice = 0
self.hslice = 0
self.l2addr = 0
... |
def append_path_after_vad(data_folder, id, list):
file = get_path(data_folder, id)
destin_folder = os.path.join(data_folder, 'processed', (id[:5] + id[(- 4)]))
if (not os.path.exists(destin_folder)):
os.makedirs(destin_folder)
if (not os.path.exists(os.path.join(destin_folder, f'{id}.wav'))):
... |
def prepare_const_divs(ctx: LeanGenContext, expr: Expression, to_field: bool) -> List[str]:
hyp_basename = (('h_' + ctx.div_var_basename) + 'c')
const_div_rw = []
for (index, (const_expr, div_const, is_full_expr)) in enumerate(rec_get_const_div_inv(expr, ctx.desc_ctx)):
hyp_name = f'{hyp_basename}{i... |
((not tf), 'no TF')
def test_demo_sprint_interface():
import subprocess
subprocess.check_call(['echo', 'travis_fold:start:test_demo_sprint_interface'])
subprocess.check_call([py, os.path.abspath('demos/demo-sprint-interface.py')], cwd='/')
subprocess.check_call(['echo', 'travis_fold:end:test_demo_sprint... |
class TrainerCallbackForSaving(TrainerCallback):
def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
control.should_save = True |
def setup_for_distributed(is_master):
builtin_print = builtins.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if (is_master or force):
now = datetime.datetime.now().time()
builtin_print('[{}] '.format(now), end='')
builtin_print(*args, **... |
def group_norm(out_channels, affine=True, divisor=1):
out_channels = (out_channels // divisor)
dim_per_gp = (cfg.MODEL.GROUP_NORM.DIM_PER_GP // divisor)
num_groups = (cfg.MODEL.GROUP_NORM.NUM_GROUPS // divisor)
eps = cfg.MODEL.GROUP_NORM.EPSILON
return torch.nn.GroupNorm(get_group_gn(out_channels, d... |
def get_args():
parser = argparse.ArgumentParser()
home = os.path.expanduser('~')
source_dir = os.path.join(home, 'data', 'cnn', 'questions')
target_dir = 'data/cnn'
glove_dir = os.path.join(home, 'data', 'glove')
parser.add_argument('--source_dir', default=source_dir)
parser.add_argument('-... |
def create_stats_table(data_stats=None):
if ((data_stats is None) or (len(data_stats) == 0)):
data = [{'Stats': '', 'Value': ''}]
else:
data = [{'Stats': key, 'Value': value} for (key, value) in data_stats[''].items()]
table = dash_table.DataTable(id='data-stats', data=data, columns=[{'id': ... |
def flags2names(flags):
info = []
for flagname in ['CONTIGUOUS', 'FORTRAN', 'OWNDATA', 'ENSURECOPY', 'ENSUREARRAY', 'ALIGNED', 'NOTSWAPPED', 'WRITEABLE', 'WRITEBACKIFCOPY', 'UPDATEIFCOPY', 'BEHAVED', 'BEHAVED_RO', 'CARRAY', 'FARRAY']:
if (abs(flags) & getattr(wrap, flagname, 0)):
info.append... |
class Hypothesis(object):
def __init__(self, tokens, log_probs, state, attn_dists, p_gens, coverage):
self.tokens = tokens
self.log_probs = log_probs
self.state = state
self.attn_dists = attn_dists
self.p_gens = p_gens
self.coverage = coverage
def extend(self, tok... |
def compute_log_moment(q, sigma, steps, lmbd, verify=False, verbose=False):
moment = compute_a(sigma, q, lmbd, verbose=verbose)
if verify:
mp.dps = 50
moment_a_mp = compute_a_mp(sigma, q, lmbd, verbose=verbose)
moment_b_mp = compute_b_mp(sigma, q, lmbd, verbose=verbose)
np.testin... |
def test_sanity_checks():
with pytest.raises(UsageError, match=filters.ERROR_EMPTY_FILTER):
filters.FilterSet().include() |
def span_overlap(s1, s2):
start = max(s1[0], s2[0])
stop = min(s1[1], s2[1])
if (stop > start):
return (start, stop)
return None |
class DecisionTransformerPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def launch_docker():
os.getcwd()
os.getuid()
snn_dir = os.path.abspath(Path(os.path.dirname(os.path.realpath(__file__))).parent)
dump_dir = os.path.abspath(Path(snn_dir).parent)
parser = argparse.ArgumentParser()
parser.add_argument('--image', type=str, choices=['cpu', 'gpu', 'gpu10'], help='Use... |
class ChatGPT_SP(AbstractChatGPT):
def __init__(self, api_key: str, api_org: (str | None), model_name='gpt-3.5-turbo-0613', *args, **kwargs):
super().__init__(api_key, api_org, model_name, *args, **kwargs)
def prompt(self):
return [{'role': 'user', 'content': 'I want you to act as a text to SQL ... |
def imagenet_preprocess_input(images, labels):
return (tf.keras.applications.mobilenet_v2.preprocess_input(images), labels) |
def generate_meta_info(save_dir, max_node, divide=40):
aa_nas_bench_ss = get_search_spaces('cell', 'nas-bench-201')
archs = CellStructure.gen_all(aa_nas_bench_ss, max_node, False)
print('There are {:} archs vs {:}.'.format(len(archs), (len(aa_nas_bench_ss) ** (((max_node - 1) * max_node) / 2))))
random.... |
class Config():
random_seed: int = 1
min_age: int = 15
start_iter: int = 100
end_iter: int = 200
percent: float = 0.01
harsh_sentence: bool = False
random_sentence_type: bool = False
random_sentence_bias: float = 0.5
consistent_sentence_length: bool = True
mean_sentence_harsh: fl... |
def perform_auto_vertical_scaling(setup_trainer_and_train, config, num_iters=2):
def launch_process(func, kwargs):
p = ProcessWrapper(target=func, kwargs=kwargs)
p.start()
p.join()
if p.exception:
raise p.exception
def set_num_envs_and_train(num_envs, run_config=confi... |
class Transformation(schema_utils.Model):
name = types.StringType()
parametrization = ReferenceType(Parametrization)
parameter_list = types.ListType(types.ModelType(SetParam))
transformation = OptplanPolyModelType(optplan.NodeMetaType.TRANSFORMATION) |
(Output('cytoscape-hover-output', 'children'), Input('cytoscape', 'mouseoverNodeData'))
def hover_graph_node(data):
if (data is None):
return no_update
return f"Node ID: {data['id']}" |
_decorator(0)
def get_fans(html):
cont = public.get_left(html)
if (cont == ''):
return 0
soup = BeautifulSoup(cont, 'lxml')
try:
return int(soup.find_all('strong')[1].get_text())
except Exception:
return 0 |
def filter_clashed_by_priority(chunks: List[tuple], allow_level: int=NESTED):
filtered_chunks = []
for ck in chunks:
if all(((not _is_clashed(ck, ex_ck, allow_level=allow_level)) for ex_ck in filtered_chunks)):
filtered_chunks.append(ck)
return filtered_chunks |
def unzip(zip_path):
zip_files = mmcv.scandir(zip_path, suffix='zip', recursive=False)
import shutil
import zipfile
unzip_folders = []
for zip_file in zip_files:
zip_file = osp.join(zip_path, zip_file)
unzip_folder = zip_file.replace('.zip', '').split('_part')[0]
print(f'Unzi... |
class KleberTreeNode(Element):
def __init__(self, parent_obj, node_weight, dominant_root, parent_node=None):
self.parent_node = parent_node
self.children = []
self.weight = node_weight
self.up_root = dominant_root
Element.__init__(self, parent_obj)
_attribute
def dept... |
def test():
net = MobileNetV2()
x = Variable(torch.randn(2, 3, 32, 32))
y = net(x)
print(y.size()) |
def run(portfolio, executable, sas_file, plan_manager, time, memory):
attributes = get_portfolio_attributes(portfolio)
configs = attributes['CONFIGS']
optimal = attributes['OPTIMAL']
final_config = attributes.get('FINAL_CONFIG')
final_config_builder = attributes.get('FINAL_CONFIG_BUILDER')
if ('... |
class BucketSampler(Sampler):
def __init__(self, num_buckets=10, batch_size=None, seq_len_field_name='seq_len'):
self.num_buckets = num_buckets
self.batch_size = batch_size
self.seq_len_field_name = seq_len_field_name
def set_batch_size(self, batch_size):
self.batch_size = batch_... |
def test_union_float64_datetime64_parameters():
t = UnionType([NumpyType('float64'), NumpyType('datetime64')], {'__array__': 'Something'})
assert (str(parser.parse(str(t))) == str(t)) |
class Func_chebyshev_T(ChebyshevFunction):
def __init__(self):
ChebyshevFunction.__init__(self, 'chebyshev_T', nargs=2, conversions=dict(maxima='chebyshev_t', mathematica='ChebyshevT', sympy='chebyshevt', giac='tchebyshev1'))
def _latex_(self):
return 'T_n'
def _print_latex_(self, n, z):
... |
def make_init_buffer_state(sdfg):
state = sdfg.add_state('init_buffer')
hist_buffer = state.add_array('hist_buffer', (num_bins,), dace.uint32, transient=True, storage=dace.dtypes.StorageType.FPGA_Local)
(entry, exit) = state.add_map('init_map', {'i': '0:num_bins'})
tasklet = state.add_tasklet('zero', {}... |
class _Pooling3D(Layer):
def __init__(self, pool_size=(2, 2, 2), strides=None, padding='valid', data_format=None, **kwargs):
super(_Pooling3D, self).__init__(**kwargs)
if (strides is None):
strides = pool_size
self.pool_size = conv_utils.normalize_tuple(pool_size, 3, 'pool_size')... |
def _run_test_wrapper(root: str, test: str, timeout: float, shared_list: list):
shared_list.append(code_metrics_helper.run_test(root, test, timeout)) |
def convnext_xlarge_config() -> ml_collections.ConfigDict:
configs = convnext_large_config()
configs.dims = [256, 512, 1024, 2048]
return configs |
class DownloadProgressBar(tqdm):
def __init__(self, iterable: (Iterable | None)=None, desc: (str | None)=None, total: ((int | float) | None)=None, leave: (bool | None)=True, file: ((io.TextIOWrapper | io.StringIO) | None)=None, ncols: (int | None)=None, mininterval: (float | None)=0.1, maxinterval: (float | None)=1... |
def test_ByteMaskedArray_NumpyArray():
v2a = ak.contents.bytemaskedarray.ByteMaskedArray(ak.index.Index(np.array([1, 0, 1, 0, 1], np.int8)), ak.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])), valid_when=True)
assert (to_list(ak_from_buffers(*ak_to_buffers(v2a))) == to_list(v2a))
v2... |
class ImgDataset(torch.utils.data.Dataset):
def __init__(self, imgs, labels=None, alb_transform=None):
self.imgs = imgs
self.labels = labels
self.alb_transform = alb_transform
def __getitem__(self, idx):
if (self.alb_transform is not None):
img = self.alb_transform(im... |
class ContinuousGridworld():
def __init__(self, grid_files, switch_grid_every=None, start_pos=(0.0, 0.0), dt=0.1, num_collision_steps=10, grid_kwargs=None, act_noise=0.0):
self.grid_files = grid_files
self.switch_grid_every = switch_grid_every
self.start_pos = start_pos
self.dt = dt
... |
class SingleDiscCond(nn.Module):
def __init__(self, nc=None, ndf=None, start_sz=256, end_sz=8, head=None, patch=False, c_dim=1000, cmap_dim=64, rand_embedding=False):
super().__init__()
self.cmap_dim = cmap_dim
nfc_midas = {4: 512, 8: 512, 16: 256, 32: 128, 64: 64, 128: 64, 256: 32, 512: 16,... |
class TimesformerModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def get_dataloader(logger, args, input_file, is_training, batch_size, num_epochs, tokenizer, index=None):
n_paragraphs = args.n_paragraphs
if ((not is_training) and (',' in n_paragraphs)):
n_paragraphs = n_paragraphs.split(',')[(- 1)]
feature_save_path = input_file.replace('.json', '-{}-{}-{}.pkl'.f... |
def get_corrections(y_pred, y_true):
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
if (len(y_pred.shape) > 1):
y_pred = np.asarray([np.argmax(p) for p in y_pred])
if (len(y_true.shape) > 1):
y_true = np.asarray([np.argmax(p) for p in y_true])
corrections = [i for i in range... |
def find_all_files(root, suffix=None):
res = []
for (root, _, files) in os.walk(root):
for f in files:
if ((suffix is not None) and (not f.endswith(suffix))):
continue
res.append(os.path.join(root, f))
return res |
class Optimizer(object):
def __init__(self, config=None):
self._accumulators = {}
self._global_step = tf.Variable(0.0, trainable=False, name='global_step')
self._config = config
return
def from_optimizer(cls, optimizer):
new_optimizer = cls(config=optimizer._config)
... |
def find_matched_references(collab_attr_list, all_collborators):
matched_ref_dict = {}
previous_collaborator = ''
for collborator_name in all_collborators:
matched_ref_dict[collborator_name.input] = []
for attr in collab_attr_list:
di = {attr: []}
for collab in all_collborators:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.