code stringlengths 101 5.91M |
|---|
_function_from_c_func_and_dispatcher(_multiarray_umath.result_type)
def result_type(*arrays_and_dtypes):
return arrays_and_dtypes |
def is_dist_avail_and_initialized():
global _USE_HVD
global _USE_BPS
if _USE_HVD:
return True
elif _USE_BPS:
return True
if (not dist.is_available()):
return False
if (not dist.is_initialized()):
return False
return True |
class TrackerBase():
def __init__(self):
self._is_tracking = False
def track(self):
self.start_tracking()
try:
(yield self)
finally:
self.stop_tracking()
def start_tracking(self):
self._is_tracking = True
def stop_tracking(self):
se... |
class ParallelWorkersTest(unittest.TestCase):
def testParallelWorkers(self):
workspace.ResetWorkspace()
queue = create_queue()
dummy_worker = create_worker(queue, (lambda worker_id: str(worker_id)))
worker_coordinator = parallel_workers.init_workers(dummy_worker)
worker_coord... |
class ShapeDtypeStruct():
__slots__ = ['shape', 'dtype']
def __init__(self, shape, dtype):
self.shape = shape
self.dtype = dtype |
def decide_download(url):
d = ur.urlopen(url)
size = (int(d.info()['Content-Length']) / GBFACTOR)
if (size > 1):
return (input(('This will download %.2fGB. Will you proceed? (y/N)\n' % size)).lower() == 'y')
else:
return True |
def train(args, trainer, task, epoch_itr):
if (epoch_itr.epoch <= len(args.update_freq)):
update_freq = args.update_freq[(epoch_itr.epoch - 1)]
else:
update_freq = args.update_freq[(- 1)]
itr = epoch_itr.next_epoch_itr(fix_batches_to_gpus=args.fix_batches_to_gpus)
itr = iterators.Grouped... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--csvpath', type=str, required=True, default='./', help='Location to data csv file')
parser.add_argument('--output_dir', type=str, default='./', help='output directory to save model')
parser.add_argument('--n_classes', type=int, default... |
def main(args):
kwargs = {'order': 'NCHW'}
kwargs.update(dict(args.kwargs))
model = ModelHelper(name=args.benchmark_name)
op_type = args.operator
input_name = args.input_name
output_name = args.output_name
iters = int(args.iters)
for i in range(iters):
input_blob_name = (input_na... |
def _update_adamax(p, g, m, u, t, alpha, beta1, beta2, eps):
alpha_t = (alpha / (1.0 - (beta1 ** t)))
m[...] = ((beta1 * m) + ((1 - beta1) * g))
u[...] = np.maximum((beta2 * u), np.abs(g))
p[...] = (p - ((alpha_t * m) / (u + eps))) |
def prune(data, cpnet_vocab_path):
with open(cpnet_vocab_path, 'r', encoding='utf8') as fin:
cpnet_vocab = [l.strip() for l in fin]
prune_data = []
for item in tqdm(data):
qc = item['qc']
prune_qc = []
for c in qc:
if ((c[(- 2):] == 'er') and (c[:(- 2)] in qc)):
... |
class CvtEncoder(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.stages = nn.ModuleList([])
for stage_idx in range(len(config.depth)):
self.stages.append(CvtStage(config, stage_idx))
def forward(self, pixel_values, output_hidden_st... |
def radical_difference_family(K, k, l=1, existence=False, check=True):
v = K.cardinality()
x = K.multiplicative_generator()
e = (k * (k - 1))
if ((l * (v - 1)) % e):
raise ValueError('k (k-1) = {} should be a multiple of l (v-1) ={}'.format((k * (k - 1)), (l * (v - 1))))
t = ((l * (v - 1)) /... |
def mlp_gaussian_policy(x, a, hidden_sizes, activation, output_activation, action_space):
act_dim = a.shape.as_list()[(- 1)]
mu = mlp(x, (list(hidden_sizes) + [act_dim]), activation, output_activation)
log_std = tf.get_variable(name='log_std', initializer=((- 0.5) * np.ones(act_dim, dtype=np.float32)))
... |
_module()
class FSAF(SingleStageDetector):
'Implementation of `FSAF <
def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None):
super(FSAF, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained) |
def make_current_context(device_id=None):
torch.cuda.init()
cuda_driver.init()
if (device_id is None):
context = _get_primary_context_for_current_device()
else:
context = cuda_driver.Device(device_id).retain_primary_context()
context.push()
return context |
def generate_header(m: GfxRuntime140, module_name: str, namespace: str, tcm: Optional[bytes]) -> List[str]:
out = []
out += ['// THIS IS A GENERATED HEADER; PLEASE DO NOT MODIFY.', '#pragma once', '#include <vector>', '#include <string>', '#include <taichi/cpp/taichi.hpp>', '']
if namespace:
out += ... |
def split_file_into_training_and_dev(filename, frac_that_should_be_dev):
assert filename.endswith('traindev.tsv')
new_training_name = (filename[:filename.rfind('traindev.tsv')] + 'train.tsv')
new_dev_name = (filename[:filename.rfind('traindev.tsv')] + 'dev.tsv')
train_f = open(new_training_name, 'w')
... |
class ANY():
def __init__(self, *_types):
self._types = _types
def __eq__(self, other):
return isinstance(other, self._types)
def __repr__(self):
return f"ANY({', '.join((_type.__name__ for _type in self._types))})" |
class Generator(BaseGenerator):
def __init__(self, config, mode, X=None, ADV=None):
super(Generator, self).__init__(config, mode)
self.build_generator(X=X, ADV=ADV)
def generate_random_X(self, shape):
return (np.random.rand(*shape) + 2.0)
def generate_random_ADV(self, shape):
... |
class BeamFixedFree(CompositeBase):
def __init__(self, N, quad='LG', bc=(0, 0, 0, 0), domain=((- 1), 1), padding_factor=1, dealias_direct=False, dtype=float, coordinates=None, **kw):
if isinstance(bc, (tuple, list)):
bc = BoundaryConditions({'left': {'D': bc[0], 'N': bc[1]}, 'right': {'N2': bc[2... |
def get_ref_index(length, sample_length):
if (random.uniform(0, 1) > 0.5):
ref_index = random.sample(range(length), sample_length)
ref_index.sort()
else:
pivot = random.randint(0, (length - sample_length))
ref_index = [(pivot + i) for i in range(sample_length)]
return ref_ind... |
def save_checkpoint(state, is_best, epoch, path='./'):
filename = os.path.join(path, ('checkpoint_%d.pth.tar' % epoch))
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, os.path.join(path, 'model_best.pth.tar')) |
def transform_data(data, supports):
df = data.df.copy()
newdom = {}
for col in data.domain:
support = supports[col]
size = support.sum()
newdom[col] = int(size)
if (size < support.size):
newdom[col] += 1
mapping = {}
idx = 0
for i in range(... |
.parametrize('left, right, expected', ((MutationResult.SUCCESS, MutationResult.SUCCESS, MutationResult.SUCCESS), (MutationResult.FAILURE, MutationResult.SUCCESS, MutationResult.SUCCESS), (MutationResult.SUCCESS, MutationResult.FAILURE, MutationResult.SUCCESS), (MutationResult.FAILURE, MutationResult.FAILURE, MutationRe... |
class GPTJ(CausalModel):
config_name: str = 'gptj'
def __init__(self, weights_path: Optional[str]=None):
super().__init__(GPTJEngine.config_name, weights_path) |
def cross_product(R, names=['X', 'Y', 'Z']):
L = three_dimensional(R, 1, 1, 1, 0, names=names)
L.rename('Lie algebra of RR^3 under cross product over {}'.format(R))
return L |
def convert_LinkProperty(model, prop, kwargs):
kwargs['validators'].append(validators.url())
return get_TextField(kwargs) |
def detokenize(string: str):
(string, exceptions) = mask_special_tokens(string)
tokens = ["'d", "n't", "'ve", "'m", "'re", "'ll", '.', ',', '?', '!', "'s", ')', ':', '-']
for t in tokens:
string = string.replace((' ' + t), t)
string = string.replace('( ', '(')
string = string.replace('gon na... |
def get_polyphonic_ratio(pianoroll, threshold=2):
return (np.sum((np.sum(pianoroll, 1) >= threshold)) / pianoroll.shape[0]) |
(scope='module', autouse=True)
def test_data_csv_png_10():
with generate_csv_png('test.csv', 10, 14) as csvfilename:
(yield csvfilename) |
def ResNeXt_4_20(in_ch=3, in_dim=32):
return ResNeXt(num_blocks=[1, 1, 1], cardinality=4, bottleneck_width=20, in_ch=in_ch, in_dim=in_dim) |
def main():
parser = argparse.ArgumentParser(description='Visual Place Recognition: A Tutorial. Code repository supplementing our paper.')
parser.add_argument('--descriptor', type=str, default='HDC-DELF', choices=['HDC-DELF', 'AlexNet', 'NetVLAD', 'PatchNetVLAD', 'CosPlace', 'EigenPlaces', 'SAD'], help='Select ... |
class AllPoleDigitalFilter(nn.Module):
def __init__(self, filter_order, frame_period, ignore_gain=False):
super(AllPoleDigitalFilter, self).__init__()
self.filter_order = filter_order
self.frame_period = frame_period
self.ignore_gain = ignore_gain
assert (0 <= self.filter_ord... |
def main(pretrained_model_path: str, output_dir: str, train_data: Dict, validation_data: Dict, validation_steps: int=100, trainable_modules: Tuple[str]=('attn1.to_q', 'attn2.to_q', 'attn_temp'), train_batch_size: int=1, max_train_steps: int=500, learning_rate: float=3e-05, scale_lr: bool=False, lr_scheduler: str='const... |
def _process_dataset(name, directory, num_shards, labels_file):
(filenames, texts, labels) = _find_image_files(directory, labels_file)
_process_image_files(name, filenames, texts, labels, num_shards) |
def directedLogContagion(G, A):
return (sum((log((sum(((A[u] == 1) for u in G.outIterator(i))) + 1)) for i in G.nodeIterator() if (A[i] == 1))) + sum((log((sum(((A[u] == 1) for u in G.inIterator(i))) + 1)) for i in G.nodeIterator() if (A[i] == 1)))) |
def check_fit_args(distfn, arg, rvs):
with np.errstate(all='ignore'), suppress_warnings() as sup:
sup.filter(category=DeprecationWarning, message='.*frechet_')
sup.filter(category=RuntimeWarning, message='The shape parameter of the erlang')
sup.filter(category=RuntimeWarning, message='floati... |
def get_max_norm(data, ord=2):
if isinstance(data, csr_matrix):
if (ord == np.inf):
norms = data.data
else:
norms = [np.linalg.norm(data.getrow(row_num).data, ord=ord) for row_num in range(data.shape[0])]
else:
norms = np.linalg.norm(data.data, axis=1, ord=ord)
... |
class OrlikTeraoInvariantAlgebra(FiniteDimensionalInvariantModule):
def __init__(self, R, M, G, action_on_groundset=None, *args, **kwargs):
ordering = kwargs.pop('ordering', None)
OT = OrlikTeraoAlgebra(R, M, ordering)
self._ambient = OT
if (action_on_groundset is None):
... |
def batchnorm_flop_jit(inputs, outputs):
input_shape = get_shape(inputs[0])
assert (2 <= len(input_shape) <= 5)
flop = (prod(input_shape) * 4)
flop_counter = Counter({'batchnorm': flop})
return flop_counter |
('time')
('--start', '-s', metavar='TIMECODE', type=click.STRING, default='0', show_default=True, help='Time in video to begin detecting scenes. TIMECODE can be specified as exact number of frames (-s 100 to start at frame 100), time in seconds followed by s (-s 100s to start at 100 seconds), or a timecode in the forma... |
class SkipDeclarations(object):
def visit_CTypeDefNode(self, node):
return node
def visit_CVarDefNode(self, node):
return node
def visit_CDeclaratorNode(self, node):
return node
def visit_CBaseTypeNode(self, node):
return node
def visit_CEnumDefNode(self, node):
... |
def load_archive(archive_file: str, cuda_device: int=(- 1), overrides: str='') -> Archive:
archive_file = cached_path(archive_file)
tempdir = tempfile.mkdtemp()
logger.info('extracting archive file %s to temp dir %s', archive_file, tempdir)
with tarfile.open(archive_file, 'r:gz') as archive:
arc... |
def register_Ns3Mac16AddressChecker_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::Mac16AddressChecker const &', 'arg0')])
return |
def test_multivariatenormaltril_layer_fails_to_serialilze() -> None:
layer = tfp.layers.MultivariateNormalTriL(1)
with pytest.raises(Exception):
serialized = tf.keras.utils.serialize_keras_object(layer)
tf.keras.utils.deserialize_keras_object(serialized, custom_objects={'MultivariateNormalTriL':... |
class MultiTableMetadata():
METADATA_SPEC_VERSION = 'MULTI_TABLE_V1'
def __init__(self):
self.tables = {}
self.relationships = []
def _validate_missing_relationship_keys(self, parent_table_name, parent_primary_key, child_table_name, child_foreign_key):
parent_table = self.tables.get(... |
_cache(maxsize=1000)
def measure_multiple_with_cache(state: Tuple[complex], basis: Tuple[Tuple[complex]], length_diff: int) -> Tuple[(List[array], List[float])]:
state = array(state)
projectors = ([None] * len(basis))
probabilities = ([0] * len(basis))
for (i, vector) in enumerate(basis):
vector... |
class SiqaScenario(Scenario):
name = 'siqa'
description = 'Benchmark from
tags = ['knowledge', 'multiple_choice']
def get_instances(self, output_path: str) -> List[Instance]:
data_path = os.path.join(output_path, 'data')
ensure_directory_exists(data_path)
ensure_file_downloaded(... |
def triu(A, k=0, format=None):
coo_sparse = (coo_array if isinstance(A, sparray) else coo_matrix)
A = coo_sparse(A, copy=False)
mask = ((A.row + k) <= A.col)
row = A.row[mask]
col = A.col[mask]
data = A.data[mask]
new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype)
ret... |
def load_url(url, model_dir='../../../pretrained', map_location=None):
if (not os.path.exists(model_dir)):
os.makedirs(model_dir)
filename = url.split('/')[(- 1)]
cached_file = os.path.join(model_dir, filename)
if (not os.path.exists(cached_file)):
sys.stderr.write('Downloading: "{}" to ... |
def KL_divergence_std(mu1: Tensor, log_var1: Tensor, mu2: Tensor, log_var2: Tensor):
d1 = MultivariateNormal(mu1, covariance_matrix=torch.diag(log_var1.exp()))
d2 = MultivariateNormal(mu2, covariance_matrix=torch.diag(log_var2.exp()))
return kl_divergence(d2, d1) |
def require_version(requirement: str, hint: Optional[str]=None) -> None:
hint = (f'''
{hint}''' if (hint is not None) else '')
if re.match('^[\\w_\\-\\d]+$', requirement):
(pkg, op, want_ver) = (requirement, None, None)
else:
match = re.findall('^([^!=<>\\s]+)([\\s!=<>]{1,2})(.+)', requireme... |
def train_step(data_iter):
def train_step_fn(images, labels):
with tf.GradientTape() as tape:
cosine = model(images)
loss = loss_fn(labels, cosine)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
... |
.parametrize('ext_name', ext_names)
.parametrize('numpy_type, torch_type', types)
def test_from_dlpack_new(ext_name, numpy_type, torch_type):
ctx = get_extension_context(ext_name)
device_name = ctx.backend[0].split(':')[0]
if (device_name == 'cudnn'):
device_name = 'cuda'
nn.set_default_context(... |
class Network(object):
def __init__(self, scope_name):
self.scope_name = scope_name
def build(self, input):
raise NotImplementedError
def all_vars(self):
return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.scope_name)
def trainable_vars(self):
return tf.get... |
class TransformerSpecPredictionHead(nn.Module):
def __init__(self, config, output_dim, input_dim=None):
super(TransformerSpecPredictionHead, self).__init__()
self.output_dim = output_dim
if (input_dim is None):
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
... |
class InconsistentCandidate(ResolverException):
def __init__(self, candidate, criterion):
super(InconsistentCandidate, self).__init__(candidate, criterion)
self.candidate = candidate
self.criterion = criterion
def __str__(self):
return 'Provided candidate {!r} does not satisfy {}... |
def get_expected_shape(t_shape, granularity):
if (granularity == hessian_common.HessianInfoGranularity.PER_ELEMENT):
return t_shape
elif (granularity == hessian_common.HessianInfoGranularity.PER_TENSOR):
return (1,)
else:
return (t_shape[0],) |
def OpenAUC(open_set_pred_known, open_set_pred_unknown, close_set_pred_class, close_set_labels):
(open_set_pred_known, open_set_pred_unknown, correct) = (open_set_pred_known.tolist(), open_set_pred_unknown.tolist(), (close_set_pred_class == close_set_labels).tolist())
m_x2 = (max(open_set_pred_unknown) + 1e-05)... |
class docLanguageTypeSub(supermod.docLanguageType):
def __init__(self, langid=None, para=None):
supermod.docLanguageType.__init__(self, langid, para) |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--source_file', type=str, help='PGN dir')
parser.add_argument('--output_dir', type=str, help='Output directory')
parser.add_argument('--max_games', default=, type=int, help='Max games to parse')
parsed_args = parser.parse_args... |
class ControlBlock(object):
def __init__(self):
self.children = set()
self.parents = set()
self.positions = set()
self.stats = []
self.gen = {}
self.bounded = set()
self.i_input = 0
self.i_output = 0
self.i_gen = 0
self.i_kill = 0
... |
class ViltProcessor():
def __init__(self, feature_extractor, tokenizer):
if (not isinstance(feature_extractor, ViltFeatureExtractor)):
raise ValueError(f'`feature_extractor` has to be of type {ViltFeatureExtractor.__class__}, but is {type(feature_extractor)}')
if (not isinstance(tokenize... |
_utils.test(arch=[ti.cpu, ti.cuda], debug=True)
def test_ref_atomic():
cur_arch = ti.lang.impl.get_runtime().prog.config().arch
if ((cur_arch == ti.cuda) and (ti.lang.impl.get_cuda_compute_capability() < 70)):
pytest.skip('Skip this test on Pascal (and potentially older) architecture, ask turbo0628/Prot... |
class Conceptual_Caption(RNGDataFlow):
def __init__(self, corpus_path, shuffle=False):
self.shuffle = shuffle
self.num_file = 16
self.name = os.path.join(corpus_path, 'CC_resnet101_faster_rcnn_genome.tsv.%d')
self.infiles = [(self.name % i) for i in range(self.num_file)]
self... |
class Lyric(Base):
_attributes = OrderedDict([('time', int), ('lyric', str)])
def __init__(self, time: int, lyric: str):
self.time = time
self.lyric = lyric |
def create_inputs_for_multiple_axes(rng, axes):
x = (rng.randn(2, 3, 4).astype(np.float32) * 2)
shape_stat = [1 for _ in range(x.ndim)]
for i in range(len(axes)):
shape_stat[axes[i]] = x.shape[axes[i]]
beta = rng.randn(*shape_stat).astype(np.float32)
gamma = rng.randn(*shape_stat).astype(np.... |
def get_world_size():
if (os.environ.get('PMI_SIZE') is not None):
return int((os.environ.get('PMI_SIZE') or 1))
elif (os.environ.get('OMPI_COMM_WORLD_SIZE') is not None):
return int((os.environ.get('OMPI_COMM_WORLD_SIZE') or 1))
else:
return torch.cuda.device_count() |
class TransformerInfo(object):
def __init__(self, info):
self._graph = info.graph
self._scope = info.scope
self._graph_ = info.graph_
self._scope_ = info.scope_
self._transformed_ops = info.transformed_ops
self._transformed_ts = info.transformed_ts
def _get_transf... |
def convert_ua_images_2_videos(image_folder):
folders = glob.glob(os.path.join(image_folder, '*'))
for f in tqdm(folders):
if (not os.path.isdir(f)):
continue
video_name = (f + '.avi')
convert(f, video_name, args.video_fps, 960, 540) |
class TestCMAES(TfGraphTestCase):
def test_cma_es_cartpole(self):
with LocalTFRunner(snapshot_config) as runner:
env = GarageEnv(env_name='CartPole-v1')
policy = CategoricalMLPPolicy(name='policy', env_spec=env.spec, hidden_sizes=(32, 32))
baseline = LinearFeatureBaseline... |
def register_Ns3WimaxConnection_methods(root_module, cls):
cls.add_constructor([param('ns3::WimaxConnection const &', 'arg0')])
cls.add_constructor([param('ns3::Cid', 'cid'), param('ns3::Cid::Type', 'type')])
cls.add_method('ClearFragmentsQueue', 'void', [])
cls.add_method('Dequeue', 'ns3::Ptr< ns3::Pac... |
class MNIST(torchvision.datasets.MNIST):
def __init__(self, root, part, labeled_factors, transform):
super().__init__(root, (part == 'train'), transform=transform, download=True)
if (len(labeled_factors) == 0):
self.has_label = False
self.nclass = []
self.class_fr... |
def load_state_dict(checkpoint_path):
sd = torch.load(checkpoint_path, map_location='cpu')
return sd |
class Eckerle4(Benchmark):
def __init__(self, dimensions=3):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0.0, 1.0, 10.0], [20, 20.0, 600.0]))
self.global_optimum = [[1., 4., 451.]]
self.fglob = 0.
self.a = asarray([0.0001575, 0.0001699, 0.000235, 0.0003102, ... |
def replace_negative_size_with_batch_size(shape, batch_size):
sl = []
for d in shape:
if (d < 0):
sl.append(batch_size)
else:
sl.append(d)
return sl |
class Op2DAddConstCollapsing(common.BaseSubstitution):
def __init__(self, first_node: NodeOperationMatcher, second_node: NodeOperationMatcher, op2d_collapsing_fn: Callable, bias_str: str, use_bias_str: str, layer_name_str: str=None):
super().__init__(matcher_instance=EdgeMatcher(first_node, second_node))
... |
class MultiplexedEnv():
def __init__(self, envs, action_repeat, size=(64, 64), use_goal_idx=False, log_per_goal=False):
self.use_goal_idx = use_goal_idx
self.log_per_goal = log_per_goal
self.envs = envs
self.goals = sum(list((list(range(len(_env.get_goals()))) for _env in self.envs))... |
class TFMinLengthLogitsProcessor(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class Polyhedron_base1(Polyhedron_base0, ConvexSet_closed):
def __hash__(self):
return hash((self.dim(), self.ambient_dim(), self.n_Hrepresentation(), self.n_Vrepresentation(), self.n_equations(), self.n_facets(), self.n_inequalities(), self.n_lines(), self.n_rays(), self.n_vertices()))
def _repr_(self)... |
class DetrForObjectDetection():
def __init__(self, *args, **kwargs):
requires_backends(self, ['timm'])
def from_pretrained(cls, *args, **kwargs):
requires_backends(cls, ['timm']) |
class MCTCTPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_parameters_fixed():
spec = {'channels': [{'name': 'channel', 'samples': [{'name': 'sample', 'data': [10.0], 'modifiers': [{'name': 'unfixed', 'type': 'normfactor', 'data': None}]}, {'name': 'another_sample', 'data': [5.0], 'modifiers': [{'name': 'mypoi', 'type': 'normfactor', 'data': None}]}]}], 'parameter... |
class TestNDArrayArrayFunction(object):
_array_function
def test_method(self):
class Other(object):
__array_function__ = _return_not_implemented
class NoOverrideSub(np.ndarray):
pass
class OverrideSub(np.ndarray):
__array_function__ = _return_not_imple... |
def _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta, gamma=0.0001, tau_min=0.1, tau_max=0.5):
f_k = prev_fs[(- 1)]
f_bar = max(prev_fs)
alpha_p = 1
alpha_m = 1
alpha = 1
while True:
xp = (x_k + (alpha_p * d))
(fp, Fp) = f(xp)
if (fp <= ((f_bar + eta) - ((gamma * (al... |
class RefineGAN(Model):
def __init__(self, sess, config, pretrained, name='RefineGAN', reuse=None):
super().__init__(sess, config, name)
self.pretrained = pretrained
print('[*] Building RefineGAN...')
with tf.variable_scope(name, reuse=reuse) as scope:
self.scope = scope
... |
def register_Ns3Dot11sPeerLinkCloseStart_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
cls.add_method('GetFields', 'ns3::dot11s::PeerLinkCloseStart::PlinkCl... |
class LPIPS(nn.Module):
def __init__(self, net_type: str='alex', version: str='0.1'):
assert (version in ['0.1']), 'v0.1 is only supported now'
super(LPIPS, self).__init__()
self.net = get_network(net_type)
self.lin = LinLayers(self.net.n_channels_list)
self.lin.load_state_di... |
def test_conversion_functions():
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
(young, poisson, bulk) = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array(([lam] * 3))
mu = nm.array(([mu] * 3))
youn... |
def _convert(image, dtype, force_copy=False, uniform=False):
image = np.asarray(image)
dtypeobj_in = image.dtype
if (dtype is np.floating):
dtypeobj_out = np.dtype('float64')
else:
dtypeobj_out = np.dtype(dtype)
dtype_in = dtypeobj_in.type
dtype_out = dtypeobj_out.type
kind_i... |
def bounds_from_last_device(last_device: JaxDevice) -> HardwareMesh:
if hasattr(last_device, 'coords'):
(x, y, z) = last_device.coords
return ((x + 1), (y + 1), (z + 1), (last_device.core_on_chip + 1))
else:
return (jax.host_count(), jax.local_device_count()) |
def save_checkpoint(state, model_dir):
if (jax.host_id() == 0):
state = jax.device_get(jax.tree_map((lambda x: x[0]), state))
step = int(state.step)
checkpoints.save_checkpoint(model_dir, state, step, keep=3) |
def remove_Zrot(pose):
noZ = em2euler(pose[:3].copy())
noZ[2] = 0
pose[:3] = euler2em(noZ).copy()
return pose |
class ActNorm(nn.Module):
def __init__(self, dim: int, scale: float=1.0):
super().__init__()
size = [1, dim]
self.register_parameter('bias', nn.Parameter(torch.zeros(*size)))
self.register_parameter('logs', nn.Parameter(torch.zeros(*size)))
self.dim = dim
self.scale =... |
def conv3d(norm_type, in_planes, out_planes, kernel_size=3, stride=1, num_groups=2):
if (norm_type == 'batch'):
return nn.Sequential(nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=((kernel_size - 1) // 2), bias=True), nn.BatchNorm3d(out_planes), nn.LeakyReLU(0.2, inplace=Tr... |
def main():
parser = argparse.ArgumentParser(description='Link-Prediction PLM/TCL')
parser.add_argument('--device', type=int, default=0)
parser.add_argument('--log_steps', type=int, default=1)
parser.add_argument('--use_node_embedding', action='store_true')
parser.add_argument('--num_layers', type=i... |
def get_uncertainty(models, unlabeled_loader):
models['backbone'].eval()
models['module'].eval()
uncertainty = torch.tensor([]).cuda()
with torch.no_grad():
for (inputs, labels) in unlabeled_loader:
inputs = inputs.cuda()
labels = labels.cuda()
(scores, cons_s... |
def make_pyproject_path(unpacked_source_directory):
path = os.path.join(unpacked_source_directory, 'pyproject.toml')
if (six.PY2 and isinstance(path, six.text_type)):
path = path.encode(sys.getfilesystemencoding())
return path |
def main() -> None:
sim_space = create_sim_space('sim_fg.gds', 'sim_bg.gds')
(obj, monitors) = create_objective(sim_space)
trans_list = create_transformations(obj, monitors, sim_space, cont_iters=100, min_feature=100)
plan = optplan.OptimizationPlan(transformations=trans_list)
problem_graph.run_plan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.