code stringlengths 101 5.91M |
|---|
class BaseOptions():
def __init__(self):
self.initialized = False
def initialize(self, parser):
parser.add_argument('--dataroot', required=True, help='path to images (should have subfolders trainA, trainB, valA, valB, etc)')
parser.add_argument('--batch_size', type=int, default=1, help='... |
def urlsafe_b64decode(data):
pad = (b'=' * (4 - (len(data) & 3)))
return base64.urlsafe_b64decode((data + pad)) |
_start_docstrings('RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n also takes care of multi-layer training. ', ROBERTA_START_DOCSTRING)
class DeeRobertaForSequenceClassification(BertPreTrainedModel):
config_class = RobertaConfig
base_model_prefix = 'roberta'
def __init__(self,... |
def val_meta(args, model, val_loader, device):
meta_trained_state = model.state_dict()
val_model = copy.deepcopy(model)
val_psnrs = []
for (img, pose, kinv, bound) in val_loader:
(img, pose, kinv, bound) = (img.to(device), pose.to(device), kinv.to(device), bound.to(device))
(img, pose, k... |
def word_ids_to_sentence(word_ids, vocabulary):
words = [vocabulary[word_id] for word_id in word_ids]
return ' '.join(words) |
_module()
class DAFormerHeadPanopticShared(BaseDecodeHeadPanoptic):
def __init__(self, **kwargs):
super(DAFormerHeadPanopticShared, self).__init__(input_transform='multiple_select', **kwargs)
assert (not self.align_corners)
decoder_params = kwargs['decoder_params']
embed_dims = decod... |
def segment_window_all(x_train, y_train, window_size, n_sensor_val):
window_segments = np.zeros((len(x_train), window_size, n_sensor_val))
labels = np.zeros((len(y_train),))
total_len = len(x_train)
for i in range(total_len):
end = (i + window_size)
if (end > total_len):
pad_... |
def _return_inverse(input, sorted=True, return_inverse=False, return_counts=False, dim=None):
if (not torch.jit.is_scripting()):
if ((type(input) is not Tensor) and has_torch_function((input,))):
return _unique_impl(input, sorted, return_inverse, return_counts, dim)
(output, inverse_indices,... |
def validate_base_url(ctx: click.core.Context, param: click.core.Parameter, raw_value: str) -> str:
try:
netloc = urlparse(raw_value).netloc
except ValueError as exc:
raise click.UsageError(INVALID_BASE_URL_MESSAGE) from exc
if (raw_value and (not netloc)):
raise click.UsageError(INV... |
def get_args():
parser = argparse.ArgumentParser()
massformer_train.add_massformer_train_args(parser)
nn_utils.add_hyperopt_args(parser)
return parser.parse_args() |
def clean_il_hp(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame:
if (output_format not in {'compact', 'standard'}):
raise ValueError(f'output_format {output_format} is invalid. It needs to be... |
class FixedPolicy(Policy):
def __init__(self, env_spec, scripted_actions, agent_infos=None):
super().__init__(env_spec)
if (agent_infos is None):
agent_infos = ([{}] * len(scripted_actions))
self._scripted_actions = scripted_actions
self._agent_infos = agent_infos
... |
def segment_to_example(segment, label):
raw_segment = np.array(segment, dtype=np.float32).reshape((- 1)).tostring()
raw_label = np.array(label, dtype=np.uint8).reshape((- 1)).tostring()
example = tf.train.Example(features=tf.train.Features(feature={'label': bytes_feature(raw_label), 'segment': bytes_feature... |
def _isomorphisms(E, F):
from .ell_generic import is_EllipticCurve
if ((not is_EllipticCurve(E)) or (not is_EllipticCurve(F))):
raise ValueError('arguments are not elliptic curves')
j = E.j_invariant()
if (j != F.j_invariant()):
return
K = E.base_ring()
from sage.rings.polynomial... |
def add_sampler_FID_args(parser):
parser.add_argument('--n_samples', type=int, required=True)
parser.add_argument('--latents_path', type=str) |
def main():
os.system('curl | tar xvzf -')
os.rename('writingPrompts/valid.wp_source', 'writingPrompts/dev.wp_source')
os.rename('writingPrompts/valid.wp_target', 'writingPrompts/dev.wp_target')
save_dir = 'data/wp'
os.makedirs(save_dir, exist_ok=True)
tokenizer = GPT2Tokenizer.from_pretrained(... |
class HallucinationGenerator():
def __init__(self, device):
self._device = device
self._tokenizer = spacy.load('en')
self._parser = spacy.load('en')
self._parser.add_pipe(BeneparComponent('benepar_en3_large'))
self._infiller = BART(init='bart.large').to(self._device)
def ... |
_utils.test()
def test_remove_rwtexture_ndim():
with pytest.raises(ti.TaichiRuntimeError, match='The shape argument for texture is deprecated in v1.6.0, and it is removed in v1.7.0. Please use ndim instead. \\(Note that you no longer need the exact texture size.\\)'):
ti.graph.Arg(ti.graph.ArgKind.RWTEXTURE... |
def dict_to_query(d=dict(), **kwargs):
d = {**d, **kwargs}
return '&'.join([f'`{k}`=="{v}"' for (k, v) in d.items()]) |
def cuda_dummy_step(function_manager: PyCUDAFunctionManager, data_manager: PyCUDADataManager, env_resetter: PyCUDAEnvironmentReset, target: int, step: int):
env_resetter.reset_when_done(data_manager)
step = np.int32(step)
target = np.int32(target)
test_step = function_manager.get_function('testkernel')
... |
def register_Ns3TcpHybla_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::TcpHybla const &', 'sock')])
cls.add_method('Fork', 'ns3::Ptr< ns3::TcpCongestionOps >', [], is_virtual=True)
cls.add_method('GetName', 'std::string', [], is_const=True, is_virtual=True)
cls.... |
class DatasetMapper():
def __init__(self, is_train: bool, *, augmentations: List[Union[(T.Augmentation, T.Transform)]], image_format: str, use_instance_mask: bool=False, use_keypoint: bool=False, instance_mask_format: str='polygon', keypoint_hflip_indices: Optional[np.ndarray]=None, precomputed_proposal_topk: Optio... |
class CommonSenseQAScenario(Scenario):
name = 'commonsenseqa'
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)
insta... |
def splint(a, b, tck, full_output=0):
if isinstance(tck, BSpline):
if (tck.c.ndim > 1):
mesg = 'Calling splint() with BSpline objects with c.ndim > 1 is not recommended. Use BSpline.integrate() instead.'
warnings.warn(mesg, DeprecationWarning)
if (full_output != 0):
... |
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-06):
mu1 = np.atleast_1d(mu1)
mu2 = np.atleast_1d(mu2)
sigma1 = np.atleast_2d(sigma1)
sigma2 = np.atleast_2d(sigma2)
assert (mu1.shape == mu2.shape), 'Training and test mean vectors have different lengths'
assert (sigma1.shape == si... |
_model
def legacy_seresnext101_32x4d(pretrained=False, **kwargs):
model_args = dict(block=SEResNeXtBottleneck, layers=[3, 4, 23, 3], groups=32, reduction=16, **kwargs)
return _create_senet('legacy_seresnext101_32x4d', pretrained, **model_args) |
class EventWriter():
def write(self, **kwargs):
raise NotImplementedError
def close(self):
pass |
_REGISTRY.register()
class Kinetics(torch.utils.data.Dataset):
def __init__(self, cfg, mode, num_retries=10):
assert (mode in ['train', 'val', 'test']), "Split '{}' not supported for Kinetics".format(mode)
self.mode = mode
self.cfg = cfg
self._video_meta = {}
self._num_retrie... |
def main():
for (i, evaluator) in enumerate(benchmarks):
print('\nBenchmark', i, ':')
print(evaluator)
evaluator.evaluate() |
class Combinations_setk(Combinations_msetk):
def _iterator(self, items, n):
for combination in itertools.combinations(items, n):
(yield list(combination))
def _iterator_zero(self):
(yield [])
def __iter__(self):
if (self.k == 0):
return self._iterator_zero()
... |
class Data(Clustering, MetricComparisons):
def __init__(self, coordinates=None, distances=None, maxk=None, verbose=False, njobs=cores, working_memory=1024):
super().__init__(coordinates=coordinates, distances=distances, maxk=maxk, verbose=verbose, njobs=njobs)
def return_ids_kstar_gride(self, initial_id... |
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair', 4, 'For C++11-compatibility, omit template arguments from make_pair OR use pair ... |
class SplitWordsMapperDefaultArgs(Mapper):
def run(self, text: str) -> FieldMap:
return dict(lower=text.lower(), words=text.split()) |
def intersect_sphere(line: ti.template(), sphere: ti.template()):
color1 = vec4(0)
color2 = vec4(0)
dist1 = inf
dist2 = inf
l = (sphere.center - line.pos)
l2 = l.dot(l)
r2 = (sphere.radius * sphere.radius)
tp = l.dot(line.dir)
out_of_sphere = (l2 > r2)
may_have_intersection = Tru... |
def test_case_partial_deepcopy(swagger_20):
operation = APIOperation('/example/path', 'GET', {}, swagger_20)
media_type = 'application/json'
original_case = Case(operation=operation, media_type=media_type, path_parameters={'test': 'test'}, headers={'Content-Type': 'application/json'}, cookies={'TOKEN': 'sec... |
def add_version_to_conv_bias(net, init_net):
bias_count = defaultdict(int)
for op in net._net.op:
if (('Conv' in op.type) and (len(op.input) >= 3)):
bias_count[op.input[2]] += 1
bias_fill_op = {}
for op in init_net._net.op:
if (bias_count[op.output[0]] > 1):
bias_... |
.parametrize('front, reference', [(tf.zeros(shape=(0, 2)), [[0.1, (- 0.65)], [(- 0.7), (- 0.1)]]), (tf.zeros(shape=(0, 3)), [4.0, 4.0, 4.0])])
def test_pareto_hypervolume_indicator_raises_for_empty_front(front: tf.Tensor, reference: list[float]) -> None:
pareto = Pareto(front)
with pytest.raises(ValueError):
... |
def test_merge_full():
instr0 = ExecutedInstruction('foo', 0, 1, 2, 3, 4, 5)
stmt0 = MagicMock()
assert0 = ExecutedAssertion(0, 1, 2, stmt0)
trace0 = ExecutionTrace()
trace0.executed_code_objects.add(0)
trace0.executed_code_objects.add(1)
trace0.executed_predicates[0] = 9
trace0.executed... |
def JH(N, H):
key = ('JH(%s,%s)' % (N, H))
try:
return _get(key)
except ValueError:
from sage.modular.arithgroup.all import GammaH
return _saved(key, GammaH(N, H).modular_abelian_variety()) |
.parametrize('schema, expected', (({'properties': {'a': {'readOnly': True}}}, {'not': {'required': ['a']}}), ({'properties': {'a': {'readOnly': True}}, 'required': ['a']}, {'not': {'required': ['a']}})))
def test_rewrite_read_only(schema, expected):
rewrite_properties(schema, is_read_only)
assert (schema == exp... |
class ResNet_Block(nn.Module):
def __init__(self, in_c, in_o, opt, downsample=None):
super().__init__()
bn_noise1 = LinearNoiseLayer(opt, output_sz=in_c)
bn_noise2 = LinearNoiseLayer(opt, output_sz=in_o)
conv_layer = get_conv_layer(opt)
conv_aa = conv_layer(in_c, in_o, 3, 1, ... |
class TestGaussian():
def test_basic(self):
assert_allclose(windows.gaussian(6, 1.0), [0., 0., 0., 0., 0., 0.])
assert_allclose(windows.gaussian(7, 1.2), [0., 0., 0., 1.0, 0., 0., 0.])
assert_allclose(windows.gaussian(7, 3), [0., 0., 0., 1.0, 0., 0., 0.])
assert_allclose(windows.gaus... |
class AND(sympy.Function):
def eval(cls, x, y):
if (x.is_Boolean and y.is_Boolean):
return (x and y)
def _eval_is_boolean(self):
return True |
.parametrize('checkpoint_path', ['Neural-HMM-Male.ckpt', 'Neural-HMM-Female.ckpt'])
def test_loading_checkpoint(checkpoint_path):
model = TrainingModule.load_from_checkpoint(checkpoint_path)
assert isinstance(model, pl.LightningModule) |
def copy_image_u8_to_rgba8(src: ti.template(), dst: ti.types.ndarray(), num_components: ti.template(), gray_scale: ti.template()):
for (i, j) in ti.ndrange(src.shape[0], src.shape[1]):
px = ti.Vector([0, 0, 0, 255], dt=u32)
if ti.static(gray_scale):
px[0] = px[1] = px[2] = ti.cast(src[(i... |
class BatchNormStats2d(nn.Module):
def __init__(self, num_features, eps=1e-05, decay=0.1):
super(BatchNormStats2d, self).__init__()
self.eps = eps
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', torch.ones(num_features))
sel... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', default='celeba', choices=['celeba', 'lsun'])
parser.add_argument('--url', default='datasets/celeba/celeba-{000000..000007}.tar')
parser.add_argument('--img_size', default=128, type=int)
parser.add_argument('--n_upsampli... |
def _invert_dict(d):
preimages = {}
for (k, v) in d.items():
preimages[v] = (preimages.get(v, []) + [k])
return preimages |
def create_optimizer(model, cfg, print_fn=None):
if (print_fn is None):
print_fn = print
if (cfg.OPTIMIZER.lower() == 'sgd'):
optimizer = torch.optim.SGD(model.parameters(), cfg.INITIAL_LR, cfg.MOMENTUM, weight_decay=cfg.WEIGHT_DECAY, nesterov=cfg.NESTEROV)
print_fn('Using SGD optimizer ... |
def largest_fundamental_disc_with_class_number(h):
h = Integer(h)
if (h <= 0):
return (Integer(0), Integer(0))
try:
(B, c) = watkins_table[h]
return (Integer(B), Integer(c))
except KeyError:
raise NotImplementedError(('largest fundamental discriminant not available for cl... |
class DenseAnnotationsReader(object):
def __init__(self, dense_annotations_jsonpath: str):
with open(dense_annotations_jsonpath, 'r') as visdial_file:
self._visdial_data = json.load(visdial_file)
self._image_ids = [entry['image_id'] for entry in self._visdial_data]
def __len__(se... |
class Configuration():
def __init__(self, config_dict):
with open(klpt.get_data('data/default-options.json'), encoding='utf-8') as options_file:
self.options = json.load(options_file)
self.unknown = None
if ('script' in config_dict):
self.validate_script(config_dict['... |
def register_Ns3TcpOptionSack_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_constructor([param('ns3::TcpOptionSack const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AddSackBlock', 'void', [param('std::pair< ns3::SequenceNumber< unsigned int, int >, ns3::SequenceNumber< un... |
class losses_saver():
def __init__(self, opt):
self.name_list = ['Generator', 'Vgg', 'D_fake', 'D_real', 'LabelMix']
self.opt = opt
self.freq_smooth_loss = opt.freq_smooth_loss
self.freq_save_loss = opt.freq_save_loss
self.losses = dict()
self.cur_estimates = np.zeros... |
def build_datamanager(cfg):
if (cfg.data.type == 'image'):
return ImageDataManager(**imagedata_kwargs(cfg))
else:
return torchreid.data.VideoDataManager(**videodata_kwargs(cfg)) |
def make_optimizer(cfg, model):
logger = logging.getLogger('atss_core.trainer')
params = []
for (key, value) in model.named_parameters():
if (not value.requires_grad):
continue
lr = cfg.SOLVER.BASE_LR
weight_decay = cfg.SOLVER.WEIGHT_DECAY
if ('bias' in key):
... |
class AttrFunctor(object):
def __init__(self, inputs: list=[], attrs: list=[], func=(lambda x: x)):
assert (len(inputs) == len(attrs))
self.inputs = inputs
self.attrs = attrs
self.func = func |
def create_evaluate_result_table(datasource, result_table, metrics):
table_ops.drop_tables([result_table], datasource)
ext_metrics = ['loss']
if isinstance(metrics, list):
ext_metrics.extend(metrics)
fields = [('%s STRING' % m) for m in ext_metrics]
sql = ('CREATE TABLE IF NOT EXISTS %s (%s)... |
def graph_transform_ps(single_gpu_meta_graph_def, worker_id, config, op_library_path=None):
cluster_info = config.resource_info
if (config.communication_config.ps_config.replicate_variables and (not config.sync)):
raise ValueError('replicate_variables is only possible with sync')
ps_device = ('/job:... |
def convert_speaker_meta_keys(speaker_meta):
return {SPEAKER_META_MAP.get(key, key): value for (key, value) in speaker_meta.items()} |
.parametrize('symbol, typ, result', [(sym, dict, dict[(Any, int)]) for sym in InferredSignature._DICT_VALUE_FROM_ARGUMENT_TYPES])
def test_guess_generic_types_dict_value_from_arguments(inferred_signature, symbol, typ, result):
config.configuration.test_creation.negate_type = 0.0
knowledge = UsageTraceNode('ROOT... |
def register_dataset(dataset_data: CocoDatasetInfo, datasets_root: Optional[str]=None):
annotations_fpath = maybe_prepend_base_path(datasets_root, dataset_data.annotations_fpath)
images_root = maybe_prepend_base_path(datasets_root, dataset_data.images_root)
def load_annotations():
return load_coco_j... |
class Encoder(nn.Module):
def __init__(self, input_size, embedding_size, hidden_size, num_layers, p):
super(Encoder, self).__init__()
self.dropout = nn.Dropout(p)
self.hidden_size = hidden_size
self.num_layers = num_layers
self.embedding = nn.Embedding(input_size, embedding_s... |
class BarthezTokenizer():
def __init__(self, *args, **kwargs):
requires_sentencepiece(self)
def from_pretrained(self, *args, **kwargs):
requires_sentencepiece(self) |
_utils.test(require=ti.extension.sparse, exclude=[ti.opengl, ti.gles, ti.vulkan, ti.metal])
def test_dense_dynamic():
n = 128
x = ti.field(ti.i32)
ti.root.dense(ti.i, n).dynamic(ti.j, n, 128).place(x)
def append():
for i in range(n):
for j in range(i):
ti.append(x.par... |
def test_aws_singlepart_zero_bytes():
assert interface_test_framework('aws:us-east-1', f'test-skyplane-{uuid.uuid4()}', False, test_delete_bucket=True, file_size_mb=0) |
def add_sssp_edges_for_op(ssspG, vars, op, index, in_vars, out_vars, binding, split_idx, prev_split_idx=None):
prev_split_idx = (prev_split_idx or split_idx)
layouts = vars.get_valid_unique_layouts(op.name, (tuple(in_vars) + tuple(out_vars)), binding=freeze_dict(binding))
num_layouts = layout_len(layouts)
... |
def adam_init(optimizer):
for pg in optimizer.param_groups:
for p in pg['params']:
state = optimizer.state[p]
if (len(state) == 0):
state['exp_avg'] = torch.zeros_like(p.data, memory_format=torch.preserve_format)
state['exp_avg_sq'] = torch.zeros_like(... |
class ToyText(nn.Module):
def __init__(self, hidden_size):
super(ToyText, self).__init__()
self.relu = nn.ReLU()
self.fc = nn.Linear(512, hidden_size)
def forward(self, text):
out = self.fc(self.relu(text))
return out |
def depth_for_vis(depth, valid_start=0.2, valid_end=1.0):
mask = (depth > 0)
depth_n = depth.astype(np.float)
depth_n[mask] -= depth_n[mask].min()
depth_n[mask] /= (depth_n[mask].max() / (valid_end - valid_start))
depth_n[mask] += valid_start
return depth_n |
def statistics_avg_duration(all_data, data, dialogue_id='Dialogue_ID', StartTime='StartTime', EndTime='EndTime'):
keys = list(set(data[dialogue_id]))
count_dial_time = []
for key in keys:
start_time = all_data[(all_data[dialogue_id] == key)][StartTime]
end_time = all_data[(all_data[dialogue_... |
def test__setup_report_dir_not_required(tmp_path: Path):
path = ((tmp_path / 'foo') / 'bar')
config.configuration.statistics_output.report_dir = path.absolute()
config.configuration.statistics_output.create_coverage_report = False
config.configuration.statistics_output.statistics_backend = config.Statis... |
.entry
def test_train_lm():
with tempfile.TemporaryDirectory() as tmpdir:
data_config = tiny_test_corpus.tiny_corpus_config(tmpdir)
try:
config = train_lm.TrainLmConfig(data=data_config, model=train_lm.Gpt2Config(num_layers=2, num_heads=2, seq_len=32, hidden_dim=32), trainer=train_lm.Tra... |
def worker_function(local_rank, world_size):
print('-I- my local_rank is', local_rank)
import os
os.environ['OMPI_COMM_WORLD_SIZE'] = str(world_size)
os.environ['OMPI_COMM_WORLD_RANK'] = str(local_rank)
os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = str(local_rank)
os.environ['OMPI_UNIVERSE_SIZE'] =... |
.parametrize('condition, cls', [pytest.param('maximum_test_executions', MaxTestExecutionsStoppingCondition), pytest.param('maximum_statement_executions', MaxStatementExecutionsStoppingCondition), pytest.param('maximum_search_time', MaxSearchTimeStoppingCondition), pytest.param('maximum_iterations', MaxIterationsStoppin... |
def get_json_path(data_dir: str, data_type: str, split: str='1.0') -> str:
json_path = f'{data_dir}/visdial_{split}_{data_type}.json'
return json_path |
def IsOperatorWithEngine(op_type, engine):
TriggerLazyImport()
return (C.op_registry_key(op_type, engine) in _REGISTERED_OPERATORS) |
def softmax_kernel(data, *, projection_matrix, is_query, softmax_temp=None, eps=0.0001):
(b, h, _, d) = data.shape
if (softmax_temp is None):
softmax_temp = (1 / math.sqrt(d))
data_normalizer = math.sqrt(softmax_temp)
ratio = (projection_matrix.shape[0] ** (- 0.5))
projection = repeat(projec... |
def maybe_find_symengine_wrapper(build_dir: Path, ext_filename: str) -> T.Optional[Path]:
symengine_wrapper_candidates = list(build_dir.glob(f'symengine_install/**/lib/python{sys.version_info.major}.{sys.version_info.minor}/*-packages/symengine/lib/{ext_filename}'))
if (len(symengine_wrapper_candidates) > 1):
... |
def build_scheduler(config, optimizer, n_iter_per_epoch):
num_steps = int((config.TRAIN.EPOCHS * n_iter_per_epoch))
warmup_steps = int((config.TRAIN.WARMUP_EPOCHS * n_iter_per_epoch))
decay_steps = int((config.TRAIN.LR_SCHEDULER.DECAY_EPOCHS * n_iter_per_epoch))
lr_scheduler = None
if (config.TRAIN.... |
def DM_51_6_1():
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing as AdditiveCyclic
G = AdditiveCyclic(51)
M = [[5, 33, 29, 30, 1], [8, 3, 47, 10, 13], [14, 27, 6, 12, 28], [9, 16, 44, 49, 11], [34, 32, 36, 26, 20]]
Mb = [[0, 0, 0, 0, 0]]
for R in zip(*M):
for i in range(5... |
def aggregate_ids_with_embeddings(q_ids_w_emb: dict, aggregation_mode: str):
if (aggregation_mode == 'avg'):
q_ids_agg_emb = aggregate_emb_avg(q_ids_w_emb)
elif (aggregation_mode == 'sum'):
q_ids_agg_emb = aggregate_emb_sum(q_ids_w_emb)
elif (aggregation_mode == 'max'):
q_ids_agg_emb... |
def load_entity_vocab(data_dir, ignore_bad_title=True, min_ent_count=1):
entity_vocab = {}
bad_title = 0
few_entity = 0
with open(os.path.join(data_dir, 'entity_vocab.txt'), 'r', encoding='utf-8') as f:
for line in f:
(_, entity_id, entity_title, entity_mid, count) = line.strip().spl... |
def findNearbyBroker():
global profile, discoveryURL
nearby = {}
nearby['latitude'] = profile['location']['latitude']
nearby['longitude'] = profile['location']['longitude']
nearby['limit'] = 1
discoveryReq = {}
discoveryReq['entities'] = [{'type': 'IoTBroker', 'isPattern': True}]
discove... |
()
_option(__version__, '--version', '-v', package_name='showyourwork', message='%(version)s')
def main():
pass |
def _variable_with_weight_decay(name, shape, stddev, wd):
var = _variable_on_cpu(name, shape, tf.truncated_normal_initializer(stddev=stddev))
if wd:
weight_decay = tf.mul(tf.nn.l2_loss(var), wd, name='weight_loss')
tf.add_to_collection('losses', weight_decay)
return var |
def load_waveglow(waveglow_path):
waveglow = torch.load(waveglow_path)['model']
waveglow = waveglow.cuda().eval().half()
for k in waveglow.convinv:
k.float()
denoiser = Denoiser(waveglow)
return (waveglow, denoiser) |
def extract_result_build(conf):
buildFolder = os.path.join(PROJECT_CONFIG['build_dir'], conf.build_folder())
xoccFolder = '_x'
if (not os.path.exists(os.path.join(buildFolder, xoccFolder))):
conf.consumption = Consumption(conf, 'no_intermediate', None, None, None, None, None)
return
kern... |
def l2_regularization_loss(variables, weight_decay):
l2_losses = [tf.nn.l2_loss(var) for var in variables]
total_l2_loss = (weight_decay * tf.add_n(l2_losses))
return total_l2_loss |
class Evaluator():
def __call__(self, args: EvaluatorArgs, prev_ckpt_ind=(- 1), num_frames=0):
logger.info('CUDA_VISIBLE_DEVICES: {}'.format(os.environ['CUDA_VISIBLE_DEVICES']))
logger.info('Hostname: {}'.format(socket.gethostname()))
config = get_config(args.exp_config, args.opts)
r... |
def to_grayscale(image, keep_channels=True):
image = tf.image.rgb_to_grayscale(image)
if keep_channels:
image = tf.tile(image, [1, 1, 1, 3])
return image |
def resnet34(**kwargs):
model = PreActivationResNet(PreActivationBasicBlock, [3, 4, 6, 3], **kwargs)
return model |
class Run():
states: list
times: list
def __post_init__(self):
if (len(self.states) != len(self.times)):
msg = 'Input states and times must be the same length! {} \neq {}'
raise ValueError(msg.format(len(self.states), len(self.times)))
def __getitem__(self, time):
... |
def make_sent_dataset():
train_src_file = './para-train.txt'
train_trg_file = './tgt-train.txt'
embedding_file = './glove.840B.300d.txt'
embedding = './embedding.pkl'
word2idx_file = './word2idx.pkl'
word2idx = make_vocab(train_src_file, train_trg_file, word2idx_file, config.vocab_size)
make... |
def test_node2vec_apply():
node2vec = Node2Vec(emb_size=4, node_num=4, multiplicity=2)
x = np.array([[1]])
expected = np.array([[1, 1, 1, 1]])
inp = keras.Input(shape=(1,))
out = node2vec(inp, 'target')
model1 = keras.Model(inputs=inp, outputs=out)
model_weights1 = [np.ones_like(w) for w in ... |
def default_collate(batch):
elem = batch[0]
elem_type = type(elem)
if isinstance(elem, torch.Tensor):
out = None
if (torch.utils.data.get_worker_info() is not None):
numel = sum((x.numel() for x in batch))
storage = elem.storage()._new_shared(numel)
out = ... |
def decorate_args_and_kwargs_to_deivce(func, device):
def to_device_if_tensor(obj):
return (obj.to(device) if isinstance(obj, torch.Tensor) else obj)
def wrapper(*args, **kwargs):
args = [to_device_if_tensor(x) for x in args]
kwargs = {k: to_device_if_tensor(v) for (k, v) in kwargs.items... |
class HallLittlewood(UniqueRepresentation):
def __repr__(self):
return (self._name + (' over %s' % self._sym.base_ring()))
def __init__(self, Sym, t='t'):
self._sym = Sym
self.t = Sym.base_ring()(t)
self._name_suffix = ''
if (str(t) != 't'):
self._name_suffix ... |
class SawyerReachPushPickPlaceEnv(SawyerXYZEnv):
def __init__(self, task_type, full_state_reward=False):
liftThresh = 0.04
goal_low = ((- 0.1), 0.8, 0.05)
goal_high = (0.1, 0.9, 0.3)
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.6, 0.... |
def none_parameters_factory(parameters: Sequence[(JSONMapping | None)], n_outputs: int) -> List[(JSONMapping | None)]:
return ([None] * n_outputs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.