code stringlengths 101 5.91M |
|---|
class DirectPlannerSourceOneSided(MulticastDirectPlanner):
def plan(self, jobs: List[TransferJob]) -> TopologyPlan:
src_region_tag = jobs[0].src_iface.region_tag()
dst_region_tags = [iface.region_tag() for iface in jobs[0].dst_ifaces]
for job in jobs[1:]:
assert (job.src_iface.re... |
def generate_online_performance_plot(performances=None, colors=None, xticks=[], xticks_labels=None, yticks=[], yticks_labels=None, m=20000, xlabel='', ylabel='', labels=None, caption=None, fontsize=24, log_scale_x=False, log_scale_y=False, svg=False):
shape = np.shape(performances)
if (colors is None):
... |
class DownstreamExpert(nn.Module):
def __init__(self, upstream_dim, downstream_expert, **kwargs):
super(DownstreamExpert, self).__init__()
self.upstream_dim = upstream_dim
self.datarc = downstream_expert['datarc']
self.modelrc = downstream_expert['modelrc']
idtable = (Path(kw... |
def build_checkpoint_ops(flags):
checkpoint_dir = ('./logs/' + FLAGS.name)
if (not os.path.exists(checkpoint_dir)):
os.mkdir(checkpoint_dir)
saved_op = {}
for var in tf.trainable_variables():
saved_op[var.name] = var
return (tf.train.Saver(var_list=saved_op, max_to_keep=1000), checkp... |
def test_match_entities():
es = IndexSearch()
print(es.match_entities())
query = 'license'
print(es.match_entities(query)) |
class ProcessingReader(Reader):
def __init__(self, reader, processor):
Reader.__init__(self)
self.reader = reader
self.processor = make_processor(processor, reader)
def schema(self):
return self.processor.schema()
def setup_ex(self, init_net, finish_net):
self.reader.... |
.parametrize('array_type', ['array', 'sparse_csr'])
def test_mutual_reachability_graph_inplace(array_type):
rng = np.random.RandomState(0)
X = rng.randn(10, 10)
X = (X.T X)
np.fill_diagonal(X, 0.0)
X = _convert_container(X, array_type)
mr_graph = mutual_reachability_graph(X)
assert (id(mr_g... |
class AcquisitionOnSubspace():
def __init__(self, acq, free_idx, fixed_vals):
self.acq = acq
self.free_idx = free_idx
self.fixed_vals = fixed_vals
def evaluate(self, x: np.ndarray, **kwargs):
x_fixed = ([self.fixed_vals] * len(x))
x_complete = np.hstack((np.vstack(x_fixed... |
def replace_default_birthdate(patient: RawPatient) -> Optional[RawPatient]:
for event in patient.events:
if ((event.concept_id == OMOP_BIRTH) and (event.start == datetime.datetime(1, 1, 1))):
event.start = datetime.datetime(1900, 1, 1)
patient.resort()
return patient |
def var_shape(x):
out = x.get_shape().as_list()
assert all((isinstance(a, int) for a in out)), 'shape function assumes that shape is fully known'
return out |
def test_chunk_ordering_is_correct_with_slow_shards():
class SlowShardSource(ShardedDataset[List[int]]):
def shard_names(self) -> Sequence[str]:
return ['shard_0', 'shard_1']
def open_shard_at_row(self, shard_name: str, row: int) -> Iterator[List[int]]:
max_count = (40 if (sh... |
class NilCoxeterAlgebra(IwahoriHeckeAlgebra.T):
def __init__(self, W, base_ring=QQ, prefix='u'):
self._W = W
self._n = W.n
self._base_ring = base_ring
self._cartan_type = W.cartan_type()
H = IwahoriHeckeAlgebra(W, 0, 0, base_ring=base_ring)
super(IwahoriHeckeAlgebra.T... |
def load_from_npz(file_name: str) -> SparseGraph:
with np.load(file_name, allow_pickle=True) as loader:
loader = dict(loader)
dataset = SparseGraph.from_flat_dict(loader)
return dataset |
def main():
parser = argparse.ArgumentParser('Text Matching task')
parser.add_argument('--model_arch', default='bge', const='bge', nargs='?', choices=['bge'], help='model architecture')
parser.add_argument('--model_name', default='BAAI/bge-large-zh-noinstruct', type=str, help='Transformers model model or pa... |
class GANLoss(nn.Module):
def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor):
super(GANLoss, self).__init__()
self.real_label = target_real_label
self.fake_label = target_fake_label
self.real_label_var = None
self.fake_l... |
class ECDFResult():
cdf: EmpiricalDistributionFunction
sf: EmpiricalDistributionFunction
def __init__(self, q, cdf, sf, n, d):
self.cdf = EmpiricalDistributionFunction(q, cdf, n, d, 'cdf')
self.sf = EmpiricalDistributionFunction(q, sf, n, d, 'sf') |
def test_builtins_cast_return_none():
assert (m.return_none_string() is None)
assert (m.return_none_char() is None)
assert (m.return_none_bool() is None)
assert (m.return_none_int() is None)
assert (m.return_none_float() is None) |
def run_experiment_disk_io(input_config):
experiments = []
experiments.append(analyzer_experiment(instances=1, name='disk-io', experiment_type='disk-io', input_config=input_config, port=8081))
return experiments |
def test_relabel_sequential_signed_overflow():
imax = np.iinfo(np.int32).max
labels = np.array([0, 1, 99, 42, 42], dtype=np.int32)
(output, fw, inv) = relabel_sequential(labels, offset=imax)
reference = np.array([0, imax, (imax + 2), (imax + 1), (imax + 1)], dtype=np.uint32)
assert_array_equal(outpu... |
def dic_of_chars(words_indexes):
lstChars = {}
for word in words_indexes:
for char in word:
if (char not in lstChars):
lstChars[char] = len(lstChars)
lstChars['unk'] = len(lstChars)
return lstChars |
class ErnieModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def _print_select_config(configs, input_func=input):
if (len(configs) == 0):
return None
print('Config files detected in current directory are listed below:')
for (i, config) in enumerate(configs):
print('[{}] - {}'.format((i + 1), config))
key = input_func('Press the config index to loa... |
def mwem_pgm(data, epsilon, delta=0.0, workload=None, rounds=None, maxsize_mb=25, pgm_iters=1000, noise='gaussian', bounded=False, alpha=0.9):
if (workload is None):
workload = list(itertools.combinations(data.domain, 2))
if (rounds is None):
rounds = len(data.domain)
if (noise == 'laplace')... |
class GradleRequirement(Requirement):
def __init__(self):
super().__init__('Gradle 1.10+')
def check(self):
Shell.exec('gradle -version') |
_arg_scope
def resid_unit(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None):
with variable_scope.variable_scope(scope, 'resid_v1', [inputs]) as sc:
depth_in = utils.last_dimension(inputs.get_shape(), min_rank=5)
if (depth == depth_in):
shortcut = resn... |
def load_and_cache_defect_data(args, filename, pool, tokenizer, split_tag, is_sample=False):
cache_fn = os.path.join(args.cache_path, split_tag)
examples = read_examples(filename, args.data_num, args.task)
if is_sample:
examples = random.sample(examples, int((len(examples) * 0.1)))
calc_stats(ex... |
class GroupedNDRange():
def __init__(self, r):
self.r = r
def __iter__(self):
for ind in self.r:
(yield Matrix(list(ind))) |
class AdaptiveAvgPool2d(_AdaptiveAvgPoolNd):
def forward(self, input):
return F.adaptive_avg_pool2d(input, self.output_size) |
(frozen=True)
class Modules():
def create_checkpointer(self, device: str) -> Checkpointer:
modules = {k: v for (k, v) in asdict_without_copy(self).items() if isinstance(v, (nn.Module, torch.optim.Optimizer))}
return Checkpointer(modules=modules, device=device)
def freeze(self) -> None:
f... |
def quantize(model: nn.Module, get_representative_dataset: callable, tpc: TargetPlatformCapabilities, args: dict):
n_iter = math.ceil((int(args[NUM_REPRESENTATIVE_IMAGES]) // int(args[BATCH_SIZE])))
logging.info(f'Running MCT... number of representative images: {args[REPRESENTATIVE_DATASET_FOLDER]}, number of c... |
class CerebrasInt8(CausalInt8Model):
config_name: str = 'cerebras_int8'
def __init__(self, weights_path: Optional[str]=None):
super().__init__(CerebrasInt8Engine.config_name, weights_path) |
def apply_to_all_dispatchers(operation: APIOperation, context: HookContext, hooks: (HookDispatcher | None), strategy: st.SearchStrategy, container: str) -> st.SearchStrategy:
strategy = GLOBAL_HOOK_DISPATCHER.apply_to_container(strategy, container, context)
strategy = operation.schema.hooks.apply_to_container(s... |
class Each(ParseExpression):
def __init__(self, exprs, savelist=True):
super(Each, self).__init__(exprs, savelist)
self.mayReturnEmpty = all((e.mayReturnEmpty for e in self.exprs))
self.skipWhitespace = True
self.initExprGroups = True
def parseImpl(self, instring, loc, doActions=... |
class Module(chainer.Chain):
def __init__(self, dim):
super(Module, self).__init__(x2z=L.Linear(dim, dim), bn=L.BatchNormalization(dim))
def __call__(self, x):
z = self.x2z(x)
z = self.bn(z)
z = F.relu(z)
return z |
def compute_alignment_score(rank_list, src_objects_count, ref_objects_count):
aligned_obj_counts = 0
for idx in range(src_objects_count):
e1_rank_list = list(rank_list[idx].detach().cpu().numpy())
e1_rank_list.remove(idx)
rank_idx = e1_rank_list[0]
if (rank_idx >= src_objects_cou... |
class TestFiller(test_util.TestCase):
def test_filler(self):
net = core.Net('test_filler')
net.Concat(['X0', 'X1', 'X2'], ['concat_out', 'split_info'])
self.assertFalse(workspace.HasBlob('X0'))
input_dim = (30, 20)
workspace.FillRandomNetworkInputs(net, [[input_dim, input_dim... |
def main():
torch.set_num_threads(3)
if (not torch.cuda.is_available()):
logging.info('no gpu device available')
sys.exit(1)
np.random.seed(args.seed)
gpu = (ig_utils.pick_gpu_lowest_memory() if (args.gpu == 'auto') else int(args.gpu))
torch.cuda.set_device(gpu)
cudnn.benchmark =... |
def create_model(model_name, num_classes=1000, pretrained=False, **kwargs):
if ('test_time_pool' in kwargs):
test_time_pool = kwargs.pop('test_time_pool')
else:
test_time_pool = True
if (model_name == 'dpn68'):
model = dpn68(pretrained=pretrained, test_time_pool=test_time_pool, num_c... |
def _invert_nonzero(arr):
arr_inv = arr.copy()
nz = np.nonzero(arr)
arr_inv[nz] = (1 / arr[nz])
return arr_inv |
class ConllEntry():
def __init__(self, id, form, tasks, pos=None, ner_tag=None, srl_tag=None, chunk=None):
self.id = id
self.form = form
self.norm = normalize(form)
self.pos = pos
self.ner_tag = ner_tag
self.srl_tag = srl_tag
self.tasks = tasks
self.ch... |
def test_insert_random_call_no_accessible(test_case_mock):
test_cluster = MagicMock(ModuleTestCluster)
test_cluster.get_random_accessible.return_value = None
test_factory = tf.TestFactory(test_cluster)
assert (not test_factory.insert_random_call(test_case_mock, 0)) |
('/upload')
def upload():
xml_src = request.get_data()
doc = lxml.etree.fromstring(xml_src)
return lxml.etree.tostring(doc) |
def elsa_doc_model(hidden_dim=64, dropout=0.5, mode='train'):
I_en = Input(shape=(nb_maxlen[0], nb_feature[1]), dtype='float32')
en_out = AttentionWeightedAverage()(I_en)
I_ot = Input(shape=(nb_maxlen[1], nb_feature[0]), dtype='float32')
jp_out = AttentionWeightedAverage()(I_ot)
O_to = concatenate([... |
class CatKLLoss(_Loss):
def __init__(self):
super(CatKLLoss, self).__init__()
def forward(self, log_qy, log_py, batch_size=None, unit_average=False):
if (log_qy.dim() > 2):
log_qy = log_qy.squeeze()
qy = torch.exp(log_qy)
y_kl = torch.sum((qy * (log_qy - log_py)), dim... |
class MLP(nn.Module):
def __init__(self, input_dim=2048, embed_dim=768):
super().__init__()
self.proj = nn.Linear(input_dim, embed_dim)
def forward(self, x):
x = x.flatten(2).transpose(1, 2).contiguous()
x = self.proj(x)
return x |
def process(config) -> None:
def parse_param(name_value: str) -> Tuple[(str, str)]:
(name, value) = [x.strip() for x in name_value.split('=')]
return (name, value)
params = (config.param or [])
variables = dict((parse_param(param) for param in params))
engine = TemplateEngine(variables)
... |
def fix_stanford_coref(stanford_json):
true_corefs = {}
for (key, coref) in stanford_json['corefs'].items():
true_coref = []
for entity in coref:
sent_num = (entity['sentNum'] - 1)
start_index = (entity['startIndex'] - 1)
end_index = (entity['endIndex'] - 1)
... |
def loadnpy(filename, N, dtype, mode='r'):
f = np.memmap(filename, mode=mode, dtype=dtype)
M = int((len(f) / N))
print(M, N)
f = f.reshape(M, N)
return f |
def srwl_uti_math_seq_halton(i, base=2):
h = 0
fac = (1.0 / base)
while (i != 0):
digit = (i % base)
h += (digit * fac)
i = ((i - digit) / base)
fac /= base
return h |
def build_nonlinearity(nonlinearity):
if (nonlinearity in NONLINEARITY):
return NONLINEARITY[nonlinearity]()
raise ValueError(('Chosen value of nonlinearity, "%s", not handled' % nonlinearity)) |
def _ensure_tuple(item: Filter) -> ((list | set) | tuple):
if (not isinstance(item, (list, set, tuple))):
return (item,)
return item |
class TestLoadSave(TestLoadSaveBase):
def testLoadSave(self):
self.load_save()
def testRepeatedArgs(self):
dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16]
arrays = [np.random.permutation(6).reshape(2, 3).astype(T) for T i... |
def GetModelAndOptNames():
if (len(sys.argv) < 2):
print('USAGE: main.py [Model]\n')
print('Model options: LCN, one2one, unet2, unet3, conv-deconv etc.')
sys.exit(1)
modelname = sys.argv[1]
return modelname |
def create_model(n_timesteps, n_features, n_outputs, _dff=512, d_model=128, nh=4, dropout_rate=0.2, use_pe=True):
inputs = tf.keras.layers.Input(shape=(n_timesteps, n_features))
(si, _) = SensorAttention(n_filters=128, kernel_size=3, dilation_rate=2)(inputs)
x = tf.keras.layers.Conv1D(d_model, 1, activation... |
def db2velocity(db, db_median=65, vel_10db_low=20, vel_10db_high=30):
if (db <= db_median):
vel = int((80 - ((vel_10db_low * (db_median - db)) / 10)))
else:
vel = int((80 + ((vel_10db_high * (db - db_median)) / 10)))
vel = min(120, max(10, vel))
return vel |
class BertLM(MiniconsLM):
def __init__(self, model_name_or_path, gpu_batch_size=1, gpu_id=0):
super().__init__(model_name_or_path=model_name_or_path, device='cuda', gpu_batch_size=gpu_batch_size, model_type='MaskedLMScorer') |
class SeqAttnMatch(nn.Module):
def __init__(self, input_size, identity=False):
super(SeqAttnMatch, self).__init__()
if (not identity):
self.linear = nn.Linear(input_size, input_size)
else:
self.linear = None
def forward(self, x, y, y_mask):
if self.linear:... |
class FlaskCliRunner(CliRunner):
def __init__(self, app, **kwargs):
self.app = app
super(FlaskCliRunner, self).__init__(**kwargs)
def invoke(self, cli=None, args=None, **kwargs):
if (cli is None):
cli = self.app.cli
if ('obj' not in kwargs):
kwargs['obj'] ... |
def residual_collapsing_fn(first_node: BaseNode, kernel_str: str) -> np.ndarray:
if (first_node.type == Conv2d):
kernel = first_node.get_weights_by_keys(kernel_str)
(Cout, Cin, kH, kW) = kernel.shape
idxH = ((kH - 1) // 2)
idxW = ((kW - 1) // 2)
for i in range(Cout):
... |
class GNN(torch.nn.Module):
def __init__(self, x_dims, y_dims, n_layers=2):
super(GNN, self).__init__()
self.n_layers = n_layers
self.W = torch.nn.Parameter(torch.zeros(x_dims, y_dims))
def forward(self, adj_t, x):
adj_t = sym_norm(adj_t)
for _ in range(self.n_layers):
... |
def parse_args():
parser = argparse.ArgumentParser(description='MMAction2 benchmark a recognizer')
parser.add_argument('config', help='test config file path')
parser.add_argument('--log-interval', default=10, help='interval of logging')
parser.add_argument('--fuse-conv-bn', action='store_true', help='Wh... |
def _array_descr(descriptor):
fields = descriptor.fields
if (fields is None):
subdtype = descriptor.subdtype
if (subdtype is None):
if (descriptor.metadata is None):
return descriptor.str
else:
new = descriptor.metadata.copy()
... |
class GradedModulesWithBasis(GradedModulesCategory):
class ParentMethods():
def degree_negation(self, element):
base_one = self.base_ring().one()
base_minusone = (- base_one)
diag = (lambda x: (base_one if ((self.degree_on_basis(x) % 2) == 0) else base_minusone))
... |
def get_wsl_blob_names(is_training=True):
blob_names = ['im_info']
if is_training:
blob_names += ['cls_labels']
return blob_names |
def upsample_bilinear(input, size=None, scale_factor=None):
warnings.warn('nn.quantized.functional.upsample_bilinear is deprecated. Use nn.quantized.functional.interpolate instead.')
return interpolate(input, size, scale_factor, mode='bilinear', align_corners=True) |
.skip()
def gen_data():
(n_samples, C) = (10, 5)
open_pred = np.random.rand(n_samples)
open_labels = np.random.randint(low=0, high=2, size=(n_samples,))
close_pred = np.random.rand(n_samples, C)
close_labels = np.random.randint(low=0, high=C, size=(n_samples,))
(n_close_samples, C, n_open_sample... |
def test_isotonic_regression_ties_max():
x = [1, 2, 3, 4, 5, 5]
y = [1, 2, 3, 4, 5, 6]
y_true = [1, 2, 3, 4, 5.5, 5.5]
ir = IsotonicRegression()
ir.fit(x, y)
assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y))
assert_array_equal(y_true, ir.fit_transform(x, y)) |
class HFIndexBase(Index):
def __init__(self, vector_size, dataset, index_initialized=False):
self.vector_size = vector_size
self.dataset = dataset
self._index_initialized = index_initialized
self._check_dataset_format(with_index=index_initialized)
dataset.set_format('numpy', ... |
def resolve_egg_link(path):
referenced_paths = non_empty_lines(path)
resolved_paths = (os.path.join(os.path.dirname(path), ref) for ref in referenced_paths)
dist_groups = map(find_distributions, resolved_paths)
return next(dist_groups, ()) |
def advance_iter_and_group_samples(train_iterator, num_samples, max_seq_length):
num_total_tokens = (max_seq_length * num_samples)
samples = defaultdict(list)
i = 0
while (i < num_total_tokens):
tokenized_samples = next(train_iterator)
i += len(tokenized_samples['input_ids'])
sam... |
class Breakpoint():
type: str = None
pattern: re.Pattern = None
def __init__(self, text, cond=None, index=(- 1)) -> None:
self.enabled = True
self.text = text
self.cond = cond
self.index = index
self.hit_conut = 0
self.ignore = 0
def __init_subclass__(cls)... |
def get_out_entities(entity: str, relation: str):
neighbors = set()
query2 = (((('\n PREFIX rdf: < PREFIX rdfs: < PREFIX : < \n SELECT (?x1 AS ?value) WHERE {\n SELECT DISTINCT ?x1 WHERE {\n :' + entity) + ':') + relation) + ' ?x1 . \n FILTER regex(... |
class CaselessKeyword(Keyword):
def __init__(self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS):
super(CaselessKeyword, self).__init__(matchString, identChars, caseless=True)
def parseImpl(self, instring, loc, doActions=True):
if ((instring[loc:(loc + self.matchLen)].upper() == self.ca... |
def match_classes_with_shuffle(views, deranged_classes_ratio, class_datapoints_threshold, shuffle_datapoints, shuffle_each_cluster, return_class_dict=False, add_vid=False, align=False, if_shuffle_each_view=True, if_shuffle_classes=True):
views = categorize_data_view(views, add_vid=add_vid, align=align)
(keys, n... |
def moving_average(x: np.ndarray, n: int=1000):
out = np.cumsum(x, dtype=np.float32)
out[n:] = (out[n:] - out[:(- n)])
return (out[(n - 1):] / n) |
class FileInterface(base.FileInterface):
def __init__(self, glove_dir, glove_size, elmo_options_file, elmo_weights_file, **kwargs):
self._glove_dir = glove_dir
self._glove_size = glove_size
self._elmo_options_file = elmo_options_file
self._elmo_weights_file = elmo_weights_file
... |
def __plot_relay_goodput(args, torperf_dbs, tornet_dbs, net_scale):
for tornet_db in tornet_dbs:
tornet_db['data'] = []
for (i, d) in enumerate(tornet_db['dataset']):
l = [((b / (1024 ** 3)) * 8) for b in d.values()]
tornet_db['data'].append(l)
for torperf_db in torperf_d... |
def imread(filename, new_dims=None):
im = sp.misc.imread(filename)
if (new_dims is None):
return (im / 255.0)
else:
return (imresize(im, new_dims) / 255.0) |
class EphemWheelCache(SimpleWheelCache):
def __init__(self, format_control):
self._temp_dir = TempDirectory(kind='ephem-wheel-cache')
self._temp_dir.create()
super(EphemWheelCache, self).__init__(self._temp_dir.path, format_control)
def cleanup(self):
self._temp_dir.cleanup() |
def get_loss_across_trials(directory: str) -> List[float]:
directories = os.listdir(directory)
valid = filter(operator.methodcaller('isnumeric'), directories)
sorted_valid = sorted(valid, key=int)
return [get_best_loss(directory, trial) for trial in sorted_valid] |
def create_batches(sampler, dataset_files, cache_dir='cache'):
key = Hasher.hash(dataset_files)
if isinstance(sampler.collator, LeftOversCollator):
key += '_segment_collator'
elif isinstance(sampler.collator, PadCollator):
key += '_longformer_collator'
else:
raise NotImplementedE... |
def test_make_with_kwargs():
env = envs.make('test.ArgumentEnv-v0', arg2='override_arg2', arg3='override_arg3')
assert (env.spec.id == 'test.ArgumentEnv-v0')
assert isinstance(env.unwrapped, ArgumentEnv)
assert (env.arg1 == 'arg1')
assert (env.arg2 == 'override_arg2')
assert (env.arg3 == 'overri... |
def create_color_mapper() -> Tuple[(LinearColorMapper, ColorBar)]:
mapper = LinearColorMapper(palette=list(reversed(GREYS256)), low=0, high=1)
colorbar = ColorBar(color_mapper=mapper, major_label_text_font_size='8pt', ticker=BasicTicker(), formatter=NumeralTickFormatter(format='0 %'), label_standoff=10, border_... |
class CommonConfiguration(Configuration):
def __init__(self, *args, warning_suppress=False, **kwargs):
super(CommonConfiguration, self).__init__(*args, **kwargs)
self._warning_suppress = warning_suppress
def __getattr__(self, item):
if (item.startswith('__') and item.endswith('__')):
... |
def test_reverse_sequence():
time_dim = Dim(Tensor('time', [batch_dim], dtype='int32'))
in_dim = Dim(7, name='in')
extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')})
class _Net(rf.Module):
def __call__(self, x: Tensor) -> Tensor:
return... |
def create_right_column(state) -> html.Div:
explanation_views = create_explanation_layout(state, explanation_type='global')
return html.Div(id='right-column-global', children=explanation_views) |
class ZeldaCtrlProblem(ZeldaProblem):
def __init__(self, cfg: Config):
super(ZeldaCtrlProblem, self).__init__(cfg=cfg)
self._max_nearest_enemy = (np.ceil(((self._width / 2) + 1)) * self._height)
self._max_path_length = ((((np.ceil((self._width / 2)) * self._height) + np.floor((self._height /... |
def rotate_bbox(x, y, w, h, angle):
(c, s) = (np.cos(np.radians(angle)), np.sin(np.radians(angle)))
R = np.asarray([[c, s], [(- s), c]])
pts = np.asarray([[((- w) / 2), ((- h) / 2)], [(w / 2), ((- h) / 2)], [(w / 2), (h / 2)], [((- w) / 2), (h / 2)]])
rot_pts = []
for pt in pts:
rot_pts.appe... |
def get_transform(transform_type='default', image_size=32, args=None):
if (transform_type == 'imagenet'):
mean = (0.485, 0.456, 0.406)
std = (0.229, 0.224, 0.225)
interpolation = args.interpolation
crop_pct = args.crop_pct
train_transform = transforms.Compose([transforms.Resi... |
def make_test_data_loader(cfg, datasets):
ims_per_gpu = cfg.TEST.IMS_PER_GPU
test_sampler = torch.utils.data.distributed.DistributedSampler(datasets)
num_workers = cfg.TEST.LOADER_THREADS
collator = BatchCollator((- 1))
data_loader = torch.utils.data.DataLoader(datasets, batch_size=ims_per_gpu, shuf... |
class DeformRoIPoolingPack(DeformRoIPooling):
def __init__(self, spatial_scale, out_size, out_channels, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0, num_offset_fcs=3, deform_fc_channels=1024):
super(DeformRoIPoolingPack, self).__init__(spatial_scale, out_size, out_channels, no_t... |
def merge_log(log_list):
log = dict()
log['total_reward'] = sum([x['total_reward'] for x in log_list])
log['num_episodes'] = sum([x['num_episodes'] for x in log_list])
log['num_steps'] = sum([x['num_steps'] for x in log_list])
log['avg_reward'] = (log['total_reward'] / log['num_episodes'])
log['... |
def do_tojson(eval_ctx, value, indent=None):
policies = eval_ctx.environment.policies
dumper = policies['json.dumps_function']
options = policies['json.dumps_kwargs']
if (indent is not None):
options = dict(options)
options['indent'] = indent
return htmlsafe_json_dumps(value, dumper=... |
def _conv(x, filters, kernel_size, strides=1, normalizer_fn=tf.keras.layers.BatchNormalization, activation_fn=tf.nn.relu6, normalization_op_params=None):
if (activation_fn is None):
raise ValueError('Activation function cannot be None. Use tf.identity instead to better support quantized training.')
if (... |
def _expand_to_minibatch(np_array, batch_size):
print(batch_size)
tiles = ([batch_size] + ([1] * np_array.ndim))
return gen_array_ops.tile(np.expand_dims(np_array, 0), tiles) |
def apply_edits(edits, raw):
if (len(edits) != len(raw)):
((print >> sys.stderr), 'Number of edits is not equal to number of characters')
((print >> sys.stderr), (' word: %s\n edits: %s' % (raw, ', '.join(edits))))
raise AssertionError
labels = [crf_label(raw[i], edits[i]) for i in range... |
def bio_random_split(dataset, frac_train=0.8, frac_valid=0.1, frac_test=0.1, seed=0):
np.testing.assert_almost_equal(((frac_train + frac_valid) + frac_test), 1.0)
num_mols = len(dataset)
random.seed(seed)
all_idx = list(range(num_mols))
random.shuffle(all_idx)
train_idx = all_idx[:int((frac_trai... |
def dict_from_string(string, allow_tuple=False, free_word=False):
if (string is None):
return {}
if isinstance(string, dict):
return string
parser = create_bnf(allow_tuple=allow_tuple, free_word=free_word)
out = {}
for r in parser.parseString(string, parseAll=True):
out.updat... |
class HighLevelAction():
def __init__(self, motion_goals):
self.motion_goals = motion_goals
def _check_valid(self):
for goal in self.motion_goals:
assert (len(goal) == 2)
(pos, orient) = goal
assert (orient in Direction.ALL_DIRECTIONS)
assert (type... |
def ref_norm_normalization(x, p, axis, eps=1e-12):
if (p is None):
p = 2.0
y = x
y = np.abs(y)
y = np.power(y, p)
y = (np.sum(y, axis, keepdims=True) + eps)
y = np.power(y, (1.0 / p))
y = (x / y)
return y |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.