code stringlengths 101 5.91M |
|---|
class SeekPaginationDef(BaseDef):
type: str = Field('seek', const=True)
max_count: int
limit_key: str
seek_id: str
seek_key: str |
_model
def tf_efficientnet_b1_ns(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet('tf_efficientnet_b1_ns', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)
return model |
def test_get_nan_component_value():
row = pd.Series([np.nan, 2, np.nan, 4], index=['a', 'b', 'c', 'd'])
result = get_nan_component_value(row)
assert (result == 'a, c') |
class PadCollator():
def __init__(self, tokenizer, device, max_segment_len=512):
self.tokenizer = tokenizer
self.device = device
self.max_segment_len = max_segment_len
def __call__(self, batch):
batch = self.tokenizer.pad(batch)
batch['input_ids'] = torch.tensor(batch['in... |
def build_horpn_head(cfg, input_shape):
name = cfg.MODEL.RPN.HEAD_NAME
return HORPN_HEAD_REGISTRY.get(name)(cfg, input_shape) |
class FiniteDimensionalHighestWeightCrystal_TypeE(TensorProductOfCrystals):
def __init__(self, dominant_weight):
self._cartan_type = dominant_weight.parent().cartan_type()
self._highest_weight = dominant_weight
assert dominant_weight.is_dominant()
self.rename()
Parent.__init_... |
def _load_llff_image(idx: int, paths: List[str], data_dir: str, out_h: int, out_w: int) -> torch.Tensor:
f_path = os.path.join(data_dir, paths[idx])
img = Image.open(f_path).convert('RGB')
img = img.resize((out_w, out_h), Image.LANCZOS)
img = pil2tensor(img)
img = img.permute(1, 2, 0)
return img |
class Lark(Serialize):
def __init__(self, grammar, **options):
self.options = LarkOptions(options)
use_regex = self.options.regex
if use_regex:
if regex:
re_module = regex
else:
raise ModuleNotFoundError('`regex` module must be installe... |
def compress_for_output_listing(paths):
will_remove = list(paths)
will_skip = set()
folders = set()
files = set()
for path in will_remove:
if path.endswith('.pyc'):
continue
if (path.endswith('__init__.py') or ('.dist-info' in path)):
folders.add(os.path.dirna... |
class Registry():
def __init__(self, name, build_func=None, parent=None, scope=None):
self._name = name
self._module_dict = dict()
self._children = dict()
self._scope = (self.infer_scope() if (scope is None) else scope)
if (build_func is None):
if (parent is not N... |
def toTensor(G_times):
T = []
for G in G_times:
A = nx.to_numpy_matrix(G)
A = np.resize(A, (100, 100))
A = np.asarray(A)
A.astype(float)
T.append(A)
T = tl.tensor(T)
return T |
def test_build_ket():
keys = [0]
amps = [complex(1), complex(0)]
_ = KetState(amps, keys)
amps = [complex(sqrt((1 / 2))), complex(sqrt((1 / 2)))]
_ = KetState(amps, keys)
amps = [complex(0), complex(1j)]
_ = KetState(amps, keys)
amps = [complex(1), complex(0), complex(0), complex(0)]
... |
def visualize_sr(img, halve=False):
hr_img = Image.open(img, mode='r')
hr_img = hr_img.convert('RGB')
if halve:
hr_img = hr_img.resize((int((hr_img.width / 2)), int((hr_img.height / 2))), Image.LANCZOS)
lr_img = hr_img.resize((int((hr_img.width / 4)), int((hr_img.height / 4))), Image.BICUBIC)
... |
def query_2_kde_sql(query: Query, table: Table):
preds = []
for (col, pred) in query.predicates.items():
if (pred is None):
continue
(op, val) = pred
if is_categorical(table.data[col].dtype):
assert ((op == '=') and (not isinstance(val, tuple))), val
v... |
def test_chain_movement_1(env_two_agents):
env = env_two_agents
env.agents[0].x = 3
env.agents[0].y = 25
env.agents[0].dir = Direction.RIGHT
env.agents[1].x = 4
env.agents[1].y = 25
env.agents[1].dir = Direction.RIGHT
env._recalc_grid()
env.step([Action.FORWARD, Action.FORWARD])
... |
class NoTransformation(TransformationBase):
def __init__(self, parser_path: str, language: str) -> object:
super().__init__(parser_path, language)
if (not os.path.exists(parser_path)):
raise ValueError(f'Language parser does not exist at {parser_path}. Please run `setup.sh` to properly s... |
def batched_boarders_and_data(data_min_size=5, data_max_size=10, examples_min_number=1, examples_max_number=4, example_min_size=1, example_max_size=3, dtype=np.float32, elements=None):
dims_ = st.tuples(st.integers(min_value=data_min_size, max_value=data_max_size), st.integers(min_value=examples_min_number, max_val... |
class BenchMatrixPower(Benchmark):
params = [[0, 1, 2, 3, 8, 9], [1000], [1e-06, 0.001]]
param_names = ['x', 'N', 'density']
def setup(self, x: int, N: int, density: float):
self.A = random(N, N, density=density, format='csr')
def time_matrix_power(self, x: int, N: int, density: float):
... |
class MockClassifier(MLClassifierBase):
def __init__(self):
super(MockClassifier, self).__init__()
def fit(self, X, y):
self.label_count = y.shape[1]
return self
def predict(self, X):
return csr_matrix(np.ones(shape=(X.shape[0], self.label_count), dtype=int)) |
def forward_state(app):
(Output('forward', 'disabled'), Input('forward', 'n_clicks'), Input('forward-N', 'children'))
def callback(click, done):
ctx = dash.callback_context
button_id = [x['prop_id'].split('.')[0] for x in ctx.triggered]
if ('forward-N' in button_id):
return F... |
def unpickle_power_series_ring_v0(base_ring, name, default_prec, sparse):
return PowerSeriesRing(base_ring, name=name, default_prec=default_prec, sparse=sparse) |
class VariableSignature(Signature):
def __init__(self, id_, return_type, name=None):
super(VariableSignature, self).__init__(id_, return_type, 0, name=name)
def __repr__(self):
return ('$%s:%s' % (self.name, self.return_type))
def simple_repr(self):
return self.name
def is_ref(se... |
def generate_induce_artifacts(jpeg_quality_range, scale_factor_range):
assert (len(jpeg_quality_range) == 2)
assert all([(1 <= val <= 100) for val in jpeg_quality_range])
assert (jpeg_quality_range[0] <= jpeg_quality_range[1])
assert (len(scale_factor_range) == 2)
assert all([(0 < val <= 1) for val ... |
class FileWriter():
def __init__(self, xpid: str=None, xp_args: dict=None, rootdir: str='~/palaas'):
if (not xpid):
xpid = '{proc}_{unixtime}'.format(proc=os.getpid(), unixtime=int(time.time()))
self.xpid = xpid
self._tick = 0
if (xp_args is None):
xp_args = {... |
class Model_combination(nn.Module):
def __init__(self, encoder, decoder):
super().__init__()
self.encoder_spec2midi = encoder
self.decoder_spec2midi = decoder
def forward(self, input_spec):
enc_vector = self.encoder_spec2midi(input_spec)
(output_onset_A, output_offset_A, ... |
def make_sdfg(transB: bool, alpha: float, beta: float, implementation: str, dtype) -> dace.SDFG:
sdfg = dace.SDFG(name='CSRMM')
sdfg.add_array('A_val', shape=(NNZ,), dtype=dtype, transient=False)
sdfg.add_array('A_row', shape=((N + 1),), dtype=dace.int32, transient=False)
sdfg.add_array('A_col', shape=(... |
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_mode, cls_token_at_end=False, cls_token='[CLS]', cls_token_segment_id=1, sep_token='[SEP]', sep_token_extra=False, pad_on_left=False, pad_token=0, pad_token_segment_id=0, sequence_a_segment_id=0, sequence_b_segment_id=1, mask_paddi... |
.parametrize('freeze', [True, False])
.parametrize('use_gamma', [True, False])
def test_trainble_config(freeze, use_gamma, flair_lm):
flair_config = FlairConfig(flair_lm=flair_lm, freeze=freeze, use_gamma=use_gamma)
flair_embedder = flair_config.instantiate()
expected_num_trainable_params = 0
if (not fr... |
def _get_random_pose_object_with_tf_posebody(num_keypoints: int, frames_min: int=1, frames_max: int=10) -> Pose:
(tensor, mask, confidence) = _create_random_tensorflow_data(frames_min=frames_min, frames_max=frames_max, num_keypoints=num_keypoints)
masked_tensor = MaskedTensor(tensor=tensor, mask=mask)
body ... |
def attr_acc(gt_box: DetectionBox, pred_box: DetectionBox) -> float:
if (gt_box.attribute_name == ''):
acc = np.nan
else:
acc = float((gt_box.attribute_name == pred_box.attribute_name))
return acc |
def make_plots(statistics_file):
print('\n Make Plots')
with open(statistics_file, 'r') as f:
stats = json.load(f)
output_folder = os.path.split(statistics_file)[0]
FILETYPE = 'eps'
numRows = len(configX)
statNames = ['SSIM $\\uparrow$', 'LPIPS $\\downarrow$']
statTags = ['ssim', 'lp... |
class G2PModel(object):
def __init__(self, params, file_path='', is_training=False):
usr_dir.import_usr_dir(os.path.dirname(os.path.abspath(__file__)))
self.params = params
self.file_path = file_path
if (not os.path.exists(self.params.model_dir)):
os.makedirs(self.params.... |
def SMKernel(Q, input_dim, active_dims=None, variances=None, frequencies=None, lengthscales=None, max_freq=1.0, max_len=1.0, ARD=False):
if (variances is None):
variances = [(1.0 / Q) for _ in range(Q)]
if (frequencies is None):
frequencies = [(np.random.rand(input_dim) * max_freq) for _ in rang... |
class NNEmptyEntityPredictor():
def __init__(self):
self.nlp = spacy.load('en_core_web_lg')
self.ref = self.construct_reference()
self.ref = [(x + (self.nlp(x[0]),)) for x in self.ref]
def construct_reference(self):
dataset = load_json('outputs/grailqa_v1.0_train.json')
e... |
class Dataset(object):
def __init__(self, dataset):
self.K = 3
if (dataset == 'synthetic'):
(seq_list, label_list) = prepare_dataset(self.K)
else:
assert False, 'does not exists dataset: {}.'.format(dataset)
self.L = seq_list[0].shape[0]
(self.seq_list... |
class PAU_VGG(nn.Module):
def __init__(self, vgg_name):
super(PAU_VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, 100)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), (- 1))
out = sel... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, use_norm=True):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inpla... |
def find_group_ends(width, next):
next.next()
bufs = deque()
while True:
event = (yield)
if bufs:
if (event[0] == Doc.GEnd):
(_, buf) = bufs.pop()
buf.append_left((Doc.GBegin, event[1]))
buf.append((Doc.GEnd, event[1]))
... |
def consolidate_scores(cv_results, scores, metric):
if (metric == 'MAPE'):
scores[metric].append(f'{value.mean():.2f} {value.std():.2f}')
else:
scores[metric].append(f'{value.mean():.1f} {value.std():.1f}')
return scores |
def _alg_key(self, algorithm=None, recompute=False):
if recompute:
algorithm = self._get_algorithm(algorithm)
return algorithm |
class SA(nn.Module):
def __init__(self, __C):
super().__init__()
self.mhatt = MHAtt(__C)
self.ffn = FFN(__C)
self.dropout1 = nn.Dropout(__C.DROPOUT_R)
self.norm1 = LayerNorm(__C.HIDDEN_SIZE)
self.dropout2 = nn.Dropout(__C.DROPOUT_R)
self.norm2 = LayerNorm(__C.... |
_HEADS_REGISTRY.register()
class CascadeROIHeads(StandardROIHeads):
def __init__(self, *, box_in_features: List[str], box_pooler: ROIPooler, box_heads: List[nn.Module], box_predictors: List[nn.Module], proposal_matchers: List[Matcher], **kwargs):
assert ('proposal_matcher' not in kwargs), "CascadeROIHeads t... |
class SynonymPerturbation(TextPerturbation):
(frozen=True)
class Description(PerturbationDescription):
prob: float = 0.0
name: str = 'synonym'
FILE_NAME: str = 'wordnet_synonyms.json'
SOURCE_URI: str = '
def __init__(self, prob: float):
self.prob: float = prob
try:
... |
def plot_line(df, x, y, col, row, hue, name, ci=None, hue_order=model_names, title=None, xlabel=None, ylabel=None, marker=None):
g = sns.relplot(data=df, x=x, y=y, col=col, row=row, hue=hue, kind='line', facet_kws={'sharey': False}, hue_order=hue_order, ci=ci, marker=marker)
g.set_titles(title).set_ylabels(ylab... |
def stretch_loss(inp_nf, out_nf, deform, x=None, npoints=1000, dim=3, use_surf_points=False, invert_sampling=False, loss_type='l2', reduction='mean', weights=1, detach_weight=True, use_rejection=False):
if (x is None):
(x, weights) = sample_points(npoints, dim=dim, sample_surf_points=use_surf_points, inp_nf... |
def sgn_committee(K, N, alpha, ensemble_type, p_pos, noise_var):
if isinstance(p_pos, float):
p_pos = ([p_pos] * K)
if ((not isinstance(p_pos, list)) or (len(p_pos) != K)):
raise ValueError(f'p_pos must be a list of length {K}')
priors = [dict(prior_type='binary', p_pos=p) for p in p_pos]
... |
class MemcachedBackend(BaseStorageBackend):
def __init__(self, server_list_cfg, client_cfg, sys_path=None):
if (sys_path is not None):
import sys
sys.path.append(sys_path)
try:
import mc
except ImportError:
raise ImportError('Please install mem... |
def _gen_mobilenet_v3_rw(variant, channel_multiplier=1.0, pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_e1_c16_nre_noskip'], ['ir_r1_k3_s2_e4_c24_nre', 'ir_r1_k3_s1_e3_c24_nre'], ['ir_r3_k5_s2_e3_c40_se0.25_nre'], ['ir_r1_k3_s2_e6_c80', 'ir_r1_k3_s1_e2.5_c80', 'ir_r2_k3_s1_e2.3_c80'], ['ir_r2_k3_s1_e6_c112... |
class SawyerStickPushV1Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'stick_pos': obs[3:6], 'obj_pos': obs[6:(- 3)], 'goal_pos': obs[(- 3):]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_pow'... |
def get_plane_params_in_local(planes, camera_info):
tran = camera_info['position']
rot = camera_info['rotation']
b = planes
a = (np.ones((len(planes), 3)) * tran)
planes_world = ((a + b) - (((a * b).sum(axis=1) / (np.linalg.norm(b, axis=1) ** 2)).reshape((- 1), 1) * b))
end = (quaternion.as_rota... |
def main(args):
all_files = glob.glob((args.file_dir + '/*.json'))
start = time.time()
stats_df = pd.DataFrame()
global_df = pd.DataFrame()
global_user_df = pd.DataFrame()
global_system_df = pd.DataFrame()
print('Reading files')
index = 0
for dialogue_json in all_files:
index... |
class Encoder(object):
def __init__(self, cell_factory, input_size, hidden_size, input_dropout=None, output_dropout=None):
self.cell_factory = cell_factory
self.input_size = input_size
self.hidden_size = hidden_size
self.cell = self.cell_factory(self.hidden_size)
if ((input_d... |
def _insert_value(metadata, name, value):
if (value is None):
return metadata
metadata[name] = value
return metadata |
_method
class RealSet(UniqueRepresentation, Parent, Set_base, Set_boolean_operators, Set_add_sub_operators):
def __classcall__(cls, *args, **kwds):
normalized = kwds.pop('normalized', False)
if normalized:
return UniqueRepresentation.__classcall__(cls, *args, normalized=True)
man... |
class Dropout2d(_DropoutNd):
def forward(self, input: Tensor) -> Tensor:
return F.dropout2d(input, self.p, self.training, self.inplace) |
def raise_duplicate_arg_error(old_arg, new_arg):
raise TypeError((((((('For the `' + new_arg) + '` argument, the layer received both the legacy keyword argument `') + old_arg) + '` and the Keras 2 keyword argument `') + new_arg) + '`. Stick to the latter!')) |
def BModel2MLIR(bmodel_file):
from debugger.atomic_dialect import BModel2MLIR
bmodel = dis.BModel(bmodel_file)
return BModel2MLIR(bmodel) |
def read_test_labels(fin):
label_map = {}
for (line_idx, line) in enumerate(fin):
if isinstance(line, bytes):
line = line.decode('utf-8')
pieces = line.split()
if (len(pieces) < 2):
continue
if (len(pieces) > 2):
raise ValueError(('Unexpected f... |
class TupleConstraintTag(AbstractMetric):
def evaluate_single_no_special_case(self, target: list[list], prediction: list[list]) -> float:
target = map(sorted, target)
prediction = map(sorted, prediction)
target = map(tuple, target)
prediction = map(tuple, prediction)
count_ta... |
def test_functional_operation_exceptions(functional_fx, functional_gx, functional_fxy):
with pytest.raises(TypeError):
a = (functional_fx ** functional_gx) |
def register_Ns3EpcS11SapGtpcMessage_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::EpcS11Sap::GtpcMessage const &', 'arg0')])
cls.add_instance_attribute('teid', 'uint32_t', is_const=False)
return |
def main():
parser = argparse.ArgumentParser(description='OGBL-PPA (MF)')
parser.add_argument('--device', type=int, default=0)
parser.add_argument('--log_steps', type=int, default=1)
parser.add_argument('--num_layers', type=int, default=3)
parser.add_argument('--hidden_channels', type=int, default=2... |
class ProcessorVariant(ABC):
OVERRIDE = False
def process(self, doc):
pass
def bulk_process(self, docs):
return [self.process(doc) for doc in docs] |
class SharedState(Freezable):
def __init__(self, network, spec, num_workers, start_time):
assert isinstance(network, NeuralNetwork)
self.network = network
self.spec = spec
self.num_workers = num_workers
self.multithreaded = (num_workers > 1)
self.start_time = start_ti... |
def complex_model():
random_uniform = initializers.random_uniform(0, 1)
inputs = Input(shape=(224, 224, 3))
x = SeparableConv2D(10, 6, padding='same', name='sep_conv2d1')(inputs)
x = BatchNormalization(gamma_initializer='random_normal', beta_initializer='random_normal', moving_mean_initializer='random_n... |
def main(argv=None):
tf.reset_default_graph()
keep_prob = tf.placeholder(tf.float32, name='keep_probabilty')
image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image')
GTLabel = tf.placeholder(tf.int32, shape=[None, None, None, 1], name='GTLabel')
Net = BuildNetVgg16.BUILD_N... |
class Bottle3d(nn.Module):
def __init__(self, in_channel, pred_dim, chans=64):
super(Bottle3d, self).__init__()
conv3d = []
self.out_chans = [chans, (2 * chans), (4 * chans)]
n_layers = len(self.out_chans)
for i in list(range(n_layers)):
if (i == 0):
... |
_utils.test(arch=[ti.cpu, ti.cuda, ti.vulkan], exclude=[vk_on_mac], debug=True)
def test_print_matrix():
x = ti.Matrix.field(2, 3, dtype=ti.f32, shape=())
y = ti.Vector.field(3, dtype=ti.f32, shape=3)
def func(k: ti.f32):
x[None][(0, 0)] = (- 1.0)
y[2] += 1.0
print('hello', x[None], ... |
class GNNStackStage(nn.Module):
def __init__(self, dim_in, dim_out, num_layers):
super(GNNStackStage, self).__init__()
self.num_layers = num_layers
for i in range(num_layers):
if (cfg.gnn.stage_type == 'skipconcat'):
d_in = (dim_in if (i == 0) else (dim_in + (i * ... |
def cERGM2_subgraph(G):
termdict = dict()
maxterm = max([G.GetIntAttrDatN(i, 'term') for i in G.Nodes()])
maxterm_nodes = [node.GetId() for node in G.Nodes() if (G.GetIntAttrDatN(node, 'term') == maxterm)]
nodes = set(maxterm_nodes)
for i in maxterm_nodes:
termdict[i] = maxterm
newNodes ... |
def export_coreml(model, im, file, prefix=colorstr('CoreML:')):
ct_model = None
try:
check_requirements(('coremltools',))
import coremltools as ct
print(f'''
{prefix} starting export with coremltools {ct.__version__}...''')
f = file.with_suffix('.mlmodel')
model.train()
... |
.experimental
def test_predict_empty_log(log):
model = NeuroMF()
model.fit(log)
model.predict(log.limit(0), 1) |
def save_configuration(config, binding, vars, output_file):
layouts = {'input': ('X', binding['X'].upper()), 'output': ('SB2', binding['SB2'].upper()), 'special_dims': {}, 'algorithms': {}}
for (opname, op) in vars.unmerged_ops.items():
if op.specials:
if ('Implementation' in op.specials):
... |
_dispatch
def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None):
return (Dispatchable(x, np.ndarray),) |
def warp_shfl_up_i32(val: template()):
global_tid = block.global_thread_idx()
WARP_SZ = 32
lane_id = (global_tid % WARP_SZ)
offset_j = 1
n = warp.shfl_up_i32(warp.active_mask(), val, offset_j)
if (lane_id >= offset_j):
val += n
offset_j = 2
n = warp.shfl_up_i32(warp.active_mask()... |
def run_training(model, batcher, sess_context_manager, sv, summary_writer):
tf.logging.info('starting run_training')
with sess_context_manager as sess:
if FLAGS.debug:
sess = tf_debug.LocalCLIDebugWrapperSession(sess)
sess.add_tensor_filter('has_inf_or_nan', tf_debug.has_inf_or_n... |
def preprocess_for_lm_mappable(e: Dict[(str, Any)], tokenizer, header: str=DEFAULT_CONVERSATION_HEADER):
source = e['conversations']
conversation = sentences_to_formatted_conversation(header, source)
conversation_tokenized = _tokenize_fn([conversation], tokenizer)
input_ids = conversation_tokenized['inp... |
def test_ann_assign_supported_type():
a = ann_assign_supported_type()
assert (a.dtype == np.uint16) |
class LmdbBackend(BaseStorageBackend):
def __init__(self, db_paths, client_keys='default', readonly=True, lock=False, readahead=False, **kwargs):
try:
import lmdb
except ImportError:
raise ImportError('Please install lmdb to enable LmdbBackend.')
if isinstance(client_... |
def TemperatureCalibration(*args, **kwargs):
_top_level_deprecation_warning('TemperatureCalibration', 'calibration')
return calibration.TemperatureCalibration(*args, **kwargs) |
def _required_threejs_version():
import os
import sage.env
with open(os.path.join(sage.env.SAGE_EXTCODE, 'threejs', 'threejs-version.txt')) as f:
return f.read().strip() |
def preactresnet18(num_classes=10, dropout=False, stride=1, parallel=False):
return PreActResNet(PreActBlock, [2, 2, 2, 2], 64, num_classes, stride=stride) |
def finder_for_path(path):
result = None
pkgutil.get_importer(path)
loader = sys.path_importer_cache.get(path)
finder = _finder_registry.get(type(loader))
if finder:
module = _dummy_module
module.__file__ = os.path.join(path, '')
module.__loader__ = loader
result = fi... |
def get_valid_stats(args, trainer, stats, saver):
stats['num_updates'] = trainer.get_num_updates()
if hasattr(saver.save_checkpoint, 'best'):
key = 'best_{0}'.format(args.best_checkpoint_metric)
best_function = (max if args.maximize_best_checkpoint_metric else min)
stats[key] = best_func... |
def register_Ns3EpcS1apSap_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::EpcS1apSap const &', 'arg0')])
return |
def get_mIoU(fakes, names, model, device, table_path='datasets/table.txt', data_dir='database/cityscapes', batch_size=1, num_workers=8, num_classes=19, use_tqdm=True):
fakes = torch.cat(fakes, dim=0)
fakes = util.tensor2im(fakes)
mAP = test(fakes, names, model, device, table_path=table_path, data_dir=data_d... |
class Adam(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('Invalid epsilon value: {}'.format... |
class MultipleOutputsMultipleTensorsNet(torch.nn.Module):
def __init__(self):
super(MultipleOutputsMultipleTensorsNet, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 3, kernel_size=1, stride=1)
self.linear = torch.nn.Linear(((3 * 32) * 32), 3)
self.conv2 = torch.nn.Conv2d(3, 3, ker... |
def register_Ns3LteFfrAlgorithm_methods(root_module, cls):
cls.add_constructor([param('ns3::LteFfrAlgorithm const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetDlBandwidth', 'uint8_t', [], is_const=True)
cls.add_method('GetFrCellTypeId', 'uint8_t', [], is_const=True)
cls.add_method('GetLt... |
def get_session_items(session):
items = []
for step in session:
if ('retrieved_items' in step):
items += step['retrieved_items']
return items |
class DownstreamExpert(nn.Module):
def __init__(self, upstream_dim, downstream_expert, expdir, **kwargs):
super(DownstreamExpert, self).__init__()
self.upstream_dim = upstream_dim
self.datarc = downstream_expert['datarc']
self.modelrc = downstream_expert['modelrc']
DATA_ROOT ... |
def load_vox_header(filename):
assert os.path.isfile(filename), ('file not found: %s' % filename)
if filename.endswith('.df'):
f_or_c = 'C'
elif filename.endswith('.sdf'):
f_or_c = 'C'
else:
f_or_c = 'F'
fin = open(filename, 'rb')
s = Vox()
s.dims[0] = struct.unpack('... |
class LabelParameterization(nn.Module):
def __init__(self, n_samples, n_class, init='gaussian', mean=0.0, std=0.0001):
super(LabelParameterization, self).__init__()
self.n_samples = n_samples
self.n_class = n_class
self.init = init
self.s = nn.Parameter(torch.empty(n_samples,... |
def _build_import_library_x86():
(out_exists, out_file) = _check_for_import_lib()
if out_exists:
log.debug('Skip building import library: "%s" exists', out_file)
return
lib_name = ('python%d%d.lib' % tuple(sys.version_info[:2]))
lib_file = os.path.join(sys.prefix, 'libs', lib_name)
i... |
def DistributedDataParallelCPU(*args, **kwargs):
import warnings
warnings.warn('torch.nn.parallel.DistributedDataParallelCPU is deprecated, please use torch.nn.parallel.DistributedDataParallel instead.')
return DistributedDataParallel(*args, **kwargs) |
class Configs(ConfigsTemplate):
def __init__(self, hparams_center, project_name):
super(Configs, self).__init__(hparams_center, project_name)
self['dev_list_file'] = os.path.join(self['processed_dir'], 'dev_list_file.txt')
if ('bert_pretrained_dir' in self):
self['vocab_file'] = ... |
def plot3D(bench, output_filename='plot3D.pdf', step=0.1):
def fn_arg0(ind):
return bench.fn(ind)[0][0]
fig = plt.figure(figsize=((4.0 * golden_ratio), 4.0))
ax = fig.add_subplot(111, projection='3d', azim=(- 19), elev=30, position=[0.25, 0.15, 0.7, 0.7])
X = np.arange(bench.ind_domain[0], bench... |
class TestTuner(unittest.TestCase):
def test_tuner_runs(self):
def eval_config(params):
return 0.5
search_space = {'param1': [0.0, 1.0, 2.0], 'param2': {'range': (10.0, 20.0)}}
tuner = RandomTuner(search_space, eval_config, budget=50) |
def gen_adv(net, eps):
global trainloader
net.eval()
(inputs, targets) = next(trainloader)
(inputs, targets) = (inputs.to(device), targets.to(device))
inputs.requires_grad = True
outputs = net(inputs)
(_, predicted) = torch.max(outputs, 1)
loss = criterion(outputs, targets)
grad = to... |
def subs_all(f, sub, simplify=False):
singleton = False
if (not isinstance(f, (list, tuple))):
f = [f]
singleton = True
if (not isinstance(sub, (list, tuple))):
sub = [sub]
g = []
for ff in f:
for D in sub:
if isinstance(ff, dict):
ff = {k:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.