code stringlengths 101 5.91M |
|---|
class BoolQProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_examples(os.path.join(data_dir, 'train.jsonl'), 'train')
def get_dev_examples(self, data_dir):
return self._create_examples(os.path.join(data_dir, 'val.jsonl'), 'dev')
def get_test_examples(self,... |
class WeiboDataAdmin(ReadOnlyModelAdmin):
list_display = ('weibo_id', 'uid', 'create_time', 'weibo_cont', 'repost_num', 'comment_num', 'praise_num')
search_fields = ['weibo_cont', 'weibo_id']
list_per_page = 20 |
def get_pinned_packages():
pkgs = {'NUMPY', 'PANDAS', 'SKLEARN', 'PYTHON'}
pinned = {}
for env_name in pkgs:
key = f'CI_{env_name}_VERSION'
ver = os.environ.get(key, '*')
pinned[key] = ver
return pinned |
def get_test_name_from_whole_path(path: str) -> str:
start = path.rfind('/')
end = path.rfind('.')
assert ((start >= 0) and (end >= 0))
return path[(start + 1):end] |
def get_config():
config = ConfigDict()
config.run = run = ConfigDict()
run.name = 'infty_diff'
run.experiment = 'ffhq_mollified_128'
run.wandb_dir = ''
run.wandb_mode = 'online'
config.data = data = ConfigDict()
data.name = 'ffhq'
data.root_dir = ''
data.img_size = FieldReferenc... |
def _format(val: Any, output_format: str='standard', errors: str='coarse') -> Any:
val = str(val)
if (val in NULL_VALUES):
return [np.nan]
if (not validate_br_cpf(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val}')
error_result = (val if (error... |
def momentum(parameters, gradients, mu, eps):
t = U.create_shared(1)
m = ((1 - (3.0 / (t + 5))) < mu)
mu = ((m * (1 - (3.0 / (t + 5)))) + ((1 - m) * mu))
deltas = [U.create_shared(np.zeros(p.get_value().shape)) for p in parameters]
delta_nexts = [((mu * delta) + (eps * grad)) for (delta, grad) in zi... |
class advanced_model(torch.nn.Module):
def __init__(self):
super(advanced_model, self).__init__()
self.conv1 = Conv2d(3, 3, kernel_size=1, stride=1)
self.bn1 = BatchNorm2d(3)
self.relu1 = ReLU()
self.conv2 = Conv2d(3, 3, kernel_size=1, stride=1)
self.bn2 = BatchNorm2d... |
def _get_build_requires(config_settings):
config_settings = _fix_config(config_settings)
requirements = ['setuptools', 'wheel']
sys.argv = ((sys.argv[:1] + ['egg_info']) + config_settings['--global-option'])
try:
with Distribution.patch():
_run_setup()
except SetupRequirementsErr... |
class _suppress_stdout_stderr(object):
def __init__(self):
self.null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]
self.save_fds = [os.dup(1), os.dup(2)]
def __enter__(self):
os.dup2(self.null_fds[0], 1)
os.dup2(self.null_fds[1], 2)
def __exit__(self, *_):
... |
class UpstreamExpert(nn.Module):
def __init__(self, ckpt: str=None, model_config: str=None, **kwargs):
super().__init__()
self.name = '[Example UpstreamExpert]'
print(f'{self.name} - You can use model_config to construct your customized model: {model_config}')
print(f'{self.name} - Y... |
def parse_ml_domain(ml_domain):
intent_utterances = {}
customer_entities = {}
intent_label_to_api_name = {}
api_name_to_intent_label = {}
for item in ml_domain:
data_type = list(item.keys())[0]
if (data_type == 'mlIntents'):
(intent_set_api_name, intent_utterance_type, in... |
_display_as_base
class _UFuncOutputCastingError(_UFuncCastingError):
def __init__(self, ufunc, casting, from_, to, i):
super().__init__(ufunc, casting, from_, to)
self.out_i = i
def __str__(self):
i_str = ('{} '.format(self.out_i) if (self.ufunc.nout != 1) else '')
return 'Cannot... |
class Train():
def __init__(self, config):
self.batch_size = config.batch_size
self.image_path = config.image_path
self.align_path = config.align_path
self.num_gpus = config.num_gpus
self.ctx = setting_ctx(self.num_gpus)
self.num_workers = config.num_workers
s... |
class LSTMUtteranceEmbedder(nn.Module):
def __init__(self, token_embedder, lstm_dim, max_words):
super(LSTMUtteranceEmbedder, self).__init__()
self._token_embedder = token_embedder
self._bilstm = BidirectionalSourceEncoder(token_embedder.embed_dim, lstm_dim, nn.LSTMCell)
self._embed_... |
def main(arguments):
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', help='directory to save data to', type=str, default='glue_data')
parser.add_argument('--tasks', help='tasks to download data for as a comma separated string', type=str, default='all')
parser.add_argument('--path_to... |
class CompactBilinearPooling(nn.Module):
def __init__(self, input_dim1, input_dim2, output_dim, sum_pool=True):
super().__init__()
self.output_dim = output_dim
self.sum_pool = sum_pool
self.sketch1 = nn.Parameter(self.generate_sketch_matrix(torch.randint(output_dim, size=(input_dim1,... |
class Experiment(ABC, LoggingBase):
def __init__(self, cfg: ExperimentConfig):
super().__init__()
self._config = cfg
self._threads = 1
self._invocations = 1
self._invocation_barrier = Semaphore(self._invocations)
def config(self):
return self._config
def name(... |
class NerServicer(ner_pb2_grpc.NERPredictorServiceServicer):
def __init__(self, batch_predictor):
super(NerServicer, self).__init__()
self.predictor = batch_predictor
def predict(self, request, context):
try:
text = request.document.decode('utf-8')
response = self... |
class LLama2LoraKbitEngine(CausalLoraKbitEngine):
config_name: str = 'llama2_lora_kbit_engine'
def __init__(self, weights_path: Optional[Union[(str, Path)]]=None):
model_name = 'daryl149/llama-2-7b-chat-hf'
super().__init__(model_name=model_name, weights_path=None, target_modules=['q_proj', 'v_p... |
def download_all(path=None):
if (pooch is None):
raise ImportError("Missing optional dependency 'pooch' required for scipy.datasets module. Please use pip or conda to install 'pooch'.")
if (path is None):
path = pooch.os_cache('scipy-data')
for (dataset_name, dataset_hash) in _registry.regis... |
def get_root_logger(logger_name='basicsr', log_level=logging.INFO, log_file=None):
logger = logging.getLogger(logger_name)
if (logger_name in initialized_logger):
return logger
format_str = '%(asctime)s %(levelname)s: %(message)s'
stream_handler = logging.StreamHandler()
stream_handler.setFo... |
def load_genre_dict(fname: str) -> Dict[(str, Any)]:
genre_dict = {}
with open(fname, 'r') as f:
reader = csv.reader(f)
for row in reader:
genre_dict[row[0]] = 1
return genre_dict |
class TorchBenchmarkBase(object):
def __init__(self):
self.user_given_name = None
self._jit_forward = None
self._pass_count = 0
self._num_inputs_require_grads = 0
def _set_backward_test(self, is_backward):
self._is_backward = is_backward
def auto_set(self):
if... |
def test_nested_constants():
def program(A: dace.int64[20]):
i = A[0]
j = (i + 1)
k = (j + 1)
l = (i + k)
A[l] = k
sdfg = program.to_sdfg()
ScalarToSymbolPromotion().apply_pass(sdfg, {})
ConstantPropagation().apply_pass(sdfg, {})
assert (set(sdfg.symbols.keys(... |
def move_cpp_tensors_to_device(cpp_tensor_stmts, device):
return ['{}.to("{}")'.format(tensor_stmt, device) for tensor_stmt in cpp_tensor_stmts] |
def fit_predict(estimator, X):
tic = perf_counter()
if (estimator[(- 1)].__class__.__name__ == 'LocalOutlierFactor'):
estimator.fit(X)
y_pred = estimator[(- 1)].negative_outlier_factor_
else:
y_pred = estimator.fit(X).decision_function(X)
toc = perf_counter()
print(f'Duration... |
class _SetupBuilder(NetBuilder):
INIT = 'init'
EXIT = 'exit'
def __init__(self, type, name=None):
NetBuilder.__init__(self, name)
self.type = type
def setup(self, net):
if (self.type == _SetupBuilder.INIT):
return core.to_execution_step(self)
def exit(self, net):
... |
def auto_adjust_limits(aspect_ratio=0.8):
ax = plt.gca()
ax.autoscale()
ax.relim()
ax.autoscale_view()
(x0, x1) = ax.get_xlim()
(y0, y1) = ax.get_ylim()
ax.set_aspect(((abs((x1 - x0)) / abs((y1 - y0))) * aspect_ratio))
plt.draw() |
def get_win_launcher(type):
launcher_fn = ('%s.exe' % type)
if is_64bit():
launcher_fn = launcher_fn.replace('.', '-64.')
else:
launcher_fn = launcher_fn.replace('.', '-32.')
return resource_string('setuptools', launcher_fn) |
def resnet101(pretrained=False, progress=True, **kwargs):
model = _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
model.fc = nn.Linear(2048, kwargs['num_classes'])
return model |
def param_search_greedy(x, bit_rate, n_bins=200, ratio=0.16):
(xmin, xmax) = (np.min(x), np.max(x))
stepsize = ((xmax - xmin) / np.float32(n_bins))
min_bins = (np.float32(n_bins) * (np.float32(1) - np.float32(ratio)))
(xq, loss) = _compress_uniform_simplified(x, bit_rate, xmin, xmax)
solutions = []
... |
class PolyWarmupSGD(torch.optim.SGD):
def __init__(self, params, lr, weight_decay, warmup_iter=None, max_iter=None, warmup_ratio=None, power=None, **kwargs):
super().__init__(params, lr=lr, momentum=0.9, weight_decay=weight_decay)
self.global_step = 0
self.warmup_iter = warmup_iter
s... |
def interpolation_gb_heuristic(d):
d = copy(d)
I = d['I']
if ((not d.get('other_ordering_opts', False)) and want_interpolation_gb(I)):
d['interpolation_gb'] = True
d['other_ordering_first'] = False
return d |
def popup_button(label, width=0, enabled=True):
if button(label, width, enabled):
imgui.open_popup(label)
opened = imgui.begin_popup(label)
return opened |
class Credential(object):
def __init__(self, username, password):
self.username = username
self.password = password
def __iter__(self):
(yield self.username)
(yield self.password)
def __str__(self):
return ('%(username)s:%(password)s' % vars(self)) |
def __getattr__(name):
return _sub_module_deprecation(sub_package='stats', module='biasedurn', private_modules=['_biasedurn'], all=__all__, attribute=name) |
class Viewer2D(object):
def __init__(self, size=(640, 480), xlim=None, ylim=None):
pygame.init()
screen = pygame.display.set_mode(size)
if (xlim is None):
xlim = (0, size[0])
if (ylim is None):
ylim = (0, size[1])
self._screen = screen
self._xl... |
def load_checkpoint(fpath, model, optimizer=None):
ckpt = torch.load(fpath, map_location='cpu')
if (optimizer is None):
optimizer = ckpt.get('optimizer', None)
else:
optimizer.load_state_dict(ckpt['optimizer'])
epoch = ckpt['epoch']
if ('model' in ckpt):
ckpt = ckpt['model']
... |
class SubtensorBatchedIndex(NativeOpGenBase):
in_info = ({'name': 'x', 'ndim': 3, 'shape': (None, None, None), 'bw_in_var': {'want_inplace': 0}}, {'name': 'idx', 'ndim': 2, 'shape': (None, None), 'gradient': 'disconnected'})
out_info = ({'name': 'y', 'ndim': 2, 'shape': ((0, 0), (0, 1))},)
def grad_input_ma... |
def register_Ns3LteRrcSapRadioResourceConfigCommonSib_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteRrcSap::RadioResourceConfigCommonSib const &', 'arg0')])
cls.add_instance_attribute('pdschConfigCommon', 'ns3::LteRrcSap::PdschConfigCommon', is_const=False)
cls.a... |
def getColorEntry(val, args):
if (not args.colorized):
return ''
if ((not isinstance(val, float)) or math.isnan(val)):
return colors.ENDC
if (val < 0.2):
return colors.RED
elif (val < 0.4):
return colors.YELLOW
elif (val < 0.6):
return colors.BLUE
elif (va... |
def load_data(file_name: str, max_to_load: int=100, filter_dict: Optional[dict]=None) -> List[Dict[(str, Any)]]:
count = 0
data = []
filter_dict = (filter_dict or {})
with gzip.open(file_name) as fin:
for l in fin:
d = json.loads(l)
for (k, v) in filter_dict.items():
... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
super(BasicBlock, self).__init__()
assert (style in ['pytorch', 'caffe'])
self.conv1 = conv3x3(inplanes, planes, stride, dilation)
... |
def npz_dump(args):
npzfile = np.load(args[0])
if ((len(args) == 1) or (args[1] == '--list')):
print('\n'.join(npzfile.files))
exit(0)
if (args[1] in npzfile.files):
d = npzfile[args[1]]
else:
raise ValueError('No {} in {} npz file'.format(args[1], args[0]))
K = 0
... |
def main(N, family):
K0 = FunctionSpace(N, 'Fourier', dtype='d')
SD = FunctionSpace(N, family, bc=(0, 0))
ST = FunctionSpace(N, family)
TD = TensorProductSpace(comm, (K0, SD), axes=(1, 0))
TT = TensorProductSpace(comm, (K0, ST), axes=(1, 0))
VT = VectorSpace(TT)
Q = CompositeSpace([VT, TD])
... |
_GENERATOR_REGISTRY.register()
class RRPN(RPN):
def __init__(self, cfg, input_shape: Dict[(str, ShapeSpec)]):
super().__init__(cfg, input_shape)
self.box2box_transform = Box2BoxTransformRotated(weights=cfg.MODEL.RPN.BBOX_REG_WEIGHTS)
def forward(self, images, features, gt_instances=None):
... |
def face_img_func(key, entry, viewer):
img = entry['img'][0]
assert ((img.ndim == 3) and ((img.shape[0] == 1) or (img.shape[0] == 3)))
img = np.transpose(img, (1, 2, 0))
img = img.copy()
img += 0.5
try:
detection_raw = entry['detection'][0]
detection = (detection_raw > 0.5)
... |
def train(base_model: str='', data_path: str='yahma/alpaca-cleaned', output_dir: str='/common/users/jj635/llama/mycheckpoint/', batch_size: int=128, micro_batch_size: int=4, num_epochs: int=3, learning_rate: float=0.0003, cutoff_len: int=256, val_set_size: int=0, lora_r: int=8, lora_alpha: int=16, lora_dropout: float=0... |
_ordering
class ControlFlowDistance():
def __init__(self, approach_level: int=0, branch_distance: float=0.0) -> None:
assert ((approach_level >= 0) and (branch_distance >= 0.0)), 'Expect approach_level and branch_distance to be non-negative'
self._approach_level = approach_level
self._branch... |
class MinMaxNormalize(Rescale):
def __init__(self, bias=None, scale=None, normalize_bias=True, normalize_scale=True):
super().__init__(bias, scale, normalize_bias, normalize_scale)
def train(self, time_series: TimeSeries):
(bias, scale) = ({}, {})
for (name, var) in time_series.items():
... |
def TetrahedralGraph():
edges = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
pos = {0: (0, 0), 1: (0, 1), 2: (cos(((3.5 * pi) / 3)), sin(((3.5 * pi) / 3))), 3: (cos(((5.5 * pi) / 3)), sin(((5.5 * pi) / 3)))}
return Graph(edges, name='Tetrahedron', pos=pos) |
def main(args):
py_model = registry.get_model(args.model)
py_eval_setting = registry.get_eval_setting(args.eval_setting)
if (args.db and utils.evaluation_completed(py_model, py_eval_setting)):
print(f'Evaluation for {py_model.name} x {py_eval_setting.name} already found. Skipping...')
return... |
def test_get_weekly_info_invalid_date_range():
with TestClient(app) as client:
lower_bound_date = datetime.fromisoformat(LOWER_BOUND_START_DATE).date()
past = (lower_bound_date - timedelta(days=2))
response = client.get(f'/{PREFIX}/weekly_info?begin={past}&end={lower_bound_date}')
as... |
def register_functions(root_module):
module = root_module
register_functions_ns3_FatalImpl(module.add_cpp_namespace('FatalImpl'), root_module)
register_functions_ns3_Hash(module.add_cpp_namespace('Hash'), root_module)
register_functions_ns3_TracedValueCallback(module.add_cpp_namespace('TracedValueCallba... |
class MultirotorClient(VehicleClient, object):
def __init__(self, length_of_simulation, port):
super(MultirotorClient, self).__init__(length_of_simulation, port=port)
def takeoffAsync(self, timeout_sec=20, vehicle_name=''):
return self.client.call_async('takeoff', timeout_sec, vehicle_name)
... |
class KITTIRAWDataset(KITTIDataset):
def __init__(self, *args, **kwargs):
super(KITTIRAWDataset, self).__init__(*args, **kwargs)
def get_image_path(self, folder, frame_index, side):
f_str = '{:010d}{}'.format(frame_index, self.img_ext)
image_path = os.path.join(self.data_path, folder, 'i... |
class BalancedDataParallel(DataParallel):
def __init__(self, gpu0_bsz, *args, **kwargs):
self.gpu0_bsz = gpu0_bsz
super().__init__(*args, **kwargs)
def forward(self, *inputs, **kwargs):
if (not self.device_ids):
return self.module(*inputs, **kwargs)
if (self.gpu0_bsz ... |
def test_boxcox1p_underflow():
x = np.array([1e-15, 1e-306])
lmbda = np.array([1e-306, 1e-18])
y = boxcox1p(x, lmbda)
assert_allclose(y, np.log1p(x), rtol=1e-14) |
def itilbert(x, h, period=None, _cache=_cache):
tmp = asarray(x)
if iscomplexobj(tmp):
return (itilbert(tmp.real, h, period) + (1j * itilbert(tmp.imag, h, period)))
if (period is not None):
h = (((h * 2) * pi) / period)
n = len(x)
omega = _cache.get((n, h))
if (omega is None):
... |
def is_valid(column_names, data):
return pd.Series([(value[0] > 1) for value in data[column_names].to_numpy()]) |
def test_string_sort():
filenames = ['f9.10.png', 'f9.9.png', 'f10.10.png', 'f10.9.png', 'e9.png', 'e10.png', 'em.png']
expected_filenames = ['e9.png', 'e10.png', 'em.png', 'f9.9.png', 'f9.10.png', 'f10.9.png', 'f10.10.png']
sorted_filenames = sorted(filenames, key=alphanumeric_key)
assert_equal(expecte... |
def timezone(zone):
if (zone is None):
raise UnknownTimeZoneError(None)
if (zone.upper() == 'UTC'):
return utc
try:
zone = ascii(zone)
except UnicodeEncodeError:
raise UnknownTimeZoneError(zone)
zone = _case_insensitive_zone_lookup(_unmunge_zone(zone))
if (zone no... |
def test_nn_policy_learner_predict():
n_actions = 2
len_list = 1
context = np.ones((100, 2), dtype=np.float32)
context_test = np.array([i for i in range(10)], dtype=np.float32).reshape(5, 2)
action = np.zeros((100,), dtype=int)
reward = np.ones((100,), dtype=np.float32)
pscore = np.array(([0... |
def sparsestmax(v, rad_in=0, u_in=None):
w = sparsemax(v)
if ((max(w) - min(w)) == 1):
return w
ind = torch.tensor((w > 0)).float()
u = (ind / torch.sum(ind))
if (u_in is None):
rad = rad_in
else:
rad = sqrt(((rad_in ** 2) - torch.sum(((u - u_in) ** 2))))
distance = t... |
_utils.test()
def test_vector_index():
val = ti.field(ti.i32)
n = 4
m = 7
p = 11
ti.root.dense(ti.i, n).dense(ti.j, m).dense(ti.k, p).place(val)
def test():
for i in range(n):
for j in range(m):
for k in range(p):
I = ti.Vector([i, j, k])
... |
def register_Ns3HighLatencyDataTxVectorTag_methods(root_module, cls):
cls.add_constructor([param('ns3::HighLatencyDataTxVectorTag const &', 'arg0')])
cls.add_constructor([])
cls.add_constructor([param('ns3::WifiTxVector', 'dataTxVector')])
cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', '... |
def run_multilingual_pipeline(en_has_dependencies=True, fr_has_dependencies=True, **kwargs):
english_text = 'This is an English sentence.'
english_words = ['This', 'is', 'an', 'English', 'sentence', '.']
english_deps_gold = '\n'.join(("('This', 5, 'nsubj')", "('is', 5, 'cop')", "('an', 5, 'det')", "('Englis... |
def absolute_error_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes):
dy = grad_inputs[0]
x0 = inputs[0]
x1 = inputs[1]
m0 = F.greater_equal(x0, x1)
m1 = (1 - m0)
m0 = no_grad(m0)
m1 = no_grad(m1)
dx0 = (dy * (m0 - m1))
dx1 = (- dx0)
return (dx0, dx1) |
def cholesky(a, lower=False, overwrite_a=False, check_finite=True):
(c, lower) = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=True, check_finite=check_finite)
return c |
def xavier_normal_(tensor, gain=1.0):
(fan_in, fan_out) = _calculate_fan_in_and_fan_out(tensor)
std = (gain * math.sqrt((2.0 / float((fan_in + fan_out)))))
return _no_grad_normal_(tensor, 0.0, std) |
def add_preamble(source: str, name: Path, comment_prefix: str, custom_preamble: str) -> str:
dashes = ('-' * 77)
preamble = (custom_preamble + textwrap.dedent(f'''
{comment_prefix} {dashes}
{comment_prefix} This file was autogenerated by symforce from template:
{comment_prefi... |
.experimental
def test_predict(log, model):
recs = model.predict(log, users=[0, 1, 7], k=1)
assert (recs.filter((sf.col('user_idx') == 0)).count() == 1)
assert (recs.filter((sf.col('user_idx') == 7)).count() == 0)
assert (recs.count() == 2) |
class TFAutoModelForQuestionAnswering(_BaseAutoModelClass):
_model_mapping = TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING |
class FunctionTransformer(TransformerMixin, BaseEstimator):
_parameter_constraints: dict = {'func': [callable, None], 'inverse_func': [callable, None], 'validate': ['boolean'], 'accept_sparse': ['boolean'], 'check_inverse': ['boolean'], 'feature_names_out': [callable, StrOptions({'one-to-one'}), None], 'kw_args': [... |
class BenchmarkSet():
def __init__(self, scenario: str=None, instance: str=None, active_session: bool=True, session: Union[(rt.InferenceSession, None)]=None, multithread: bool=True, check: bool=True, noisy: bool=False):
assert (scenario is not None), 'Please provide a valid scenario.'
self.config = ... |
def test_data_frame_complex():
ak_array_in = ak.Array([(1.1 + 0.1j), (2.2 + 0.2j), (3.3 + 0.3j), (4.4 + 0.4j), (5.5 + 0.5j)])
data_frame = ak.to_rdataframe({'x': ak_array_in})
assert (data_frame.GetColumnType('x') == 'std::complex<double>')
ak_array_out = ak.from_rdataframe(data_frame, columns=('x',))
... |
def train_detector(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None):
cfg = compat_cfg(cfg)
logger = get_root_logger(log_level=cfg.log_level)
use_apex = (cfg.optimizer_config.get('type', None) == 'ApexOptimizerHook')
dataset = (dataset if isinstance(dataset, (list, tuple... |
def cuda_timestamp(sync=False, device=None):
if sync:
torch.cuda.synchronize(device=device)
return time.perf_counter() |
_grad()
def evaluate_performance(model, gallery_loader, query_loader, device, use_gt=False, use_cache=False, use_cbgm=False):
model.eval()
if use_cache:
eval_cache = torch.load('data/eval_cache/eval_cache.pth')
gallery_dets = eval_cache['gallery_dets']
gallery_feats = eval_cache['gallery... |
class ProtobufDetectionModel(torch.nn.Module):
def __init__(self, predict_net, init_net, *, convert_outputs=None):
super().__init__()
self.protobuf_model = ProtobufModel(predict_net, init_net)
self.size_divisibility = get_pb_arg_vali(predict_net, 'size_divisibility', 0)
self.device =... |
def args_parser():
parser = argparse.ArgumentParser(description='Train a model on ENS10')
parser.add_argument('--loss', type=str, default='CRPS', choices=['CRPS', 'L2'], help='Loss function for training (default: CRPS)')
parser.add_argument('--seed', type=int, default=16, help='Torch Seed (default: 16)')
... |
def kl_bern_criterion(x):
KLD = (torch.mul(x, (torch.log((x + 1e-20)) - math.log(0.5))) + torch.mul((1 - x), (torch.log(((1 - x) + 1e-20)) - math.log((1 - 0.5)))))
return KLD.mean() |
def ref_min_max_quantize(x, qr_min, qr_max, ql_min, ql_max, decay, x_min_max, ema, ste_fine_grained, eps, quantize):
if (not quantize):
return x
raxes = tuple([i for (i, s) in enumerate(ql_min.shape) if (s == 1)])
x_min = np.min(x, raxes, keepdims=True)
x_max = np.max(x, raxes, keepdims=True)
... |
def get_d_paretomtl(grads, losses, preference_vectors, pref_idx):
current_weight = preference_vectors[pref_idx]
rest_weights = preference_vectors
w = (rest_weights - current_weight)
gx = torch.matmul(w, (losses / torch.norm(losses)))
idx = (gx > 0)
if (torch.sum(idx) <= 0):
(sol, nd) = M... |
def prepare_examples(all_examples, split='train', max_cell=50, max_row=400, max_table=400):
def chunk_table(table, answer, tid):
if (len(table['text']) == 0):
return None
table_text = [[cell.split()[:max_cell] for cell in row] for row in table['text']]
i_start = (1 if (len(table_... |
class _BasePolynomialNetwork(six.with_metaclass(ABCMeta, _BasePoly)):
def __init__(self, degree=2, loss='squared', n_components=5, beta=1, tol=1e-06, fit_lower='augment', warm_start=False, max_iter=10000, verbose=False, random_state=None):
self.degree = degree
self.loss = loss
self.n_compone... |
def ref_log_det(x):
y = np.zeros(x.shape[0], dtype=np.float32)
for i in range(x.shape[0]):
y[i] = np.linalg.det(x[i])
y = np.abs(y)
y = np.log(y)
return y |
class OptimizerMixin():
__slots__ = ['maxiter', 'verbose']
def __init__(self, **kwargs):
self.maxiter = kwargs.pop('maxiter', 100000)
self.verbose = kwargs.pop('verbose', 0)
if kwargs:
raise exceptions.Unsupported(f'Unsupported kwargs were passed in: {list(kwargs)}.')
def... |
def get_layer_label(layer, rankdir):
if (rankdir in ('TB', 'BT')):
separator = ' '
else:
separator = '\\n'
if ((layer.type == 'Convolution') or (layer.type == 'Deconvolution')):
node_label = ('"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' % (layer.name, separator, layer.type, sep... |
def pad_zeros(A, nrows):
nz = (nrows - A.nrows())
if (nz == 0):
return A
if (nz < 0):
return A.matrix_from_rows(range(nrows))
return A.stack(matrix(ZZ, nz, A.ncols())) |
def get_accuracy(model_repl, param_repl):
acc_1 = []
acc_5 = []
steps = (input_pipeline.get_dataset_info(dataset, 'test')['num_examples'] // batch_size)
for (_, batch) in zip(tqdm.notebook.trange(steps), ds_test.as_numpy_iterator()):
predicted = model_repl(param_repl, batch['image'])
pre... |
(**njit_dict_no_parallel)
def compton_scatter(photon, compton_angle):
comov_direction = angle_aberration_gamma(photon.direction, photon.location, photon.time_current)
orthogonal_vector = get_perpendicular_vector(comov_direction)
new_vector = np.dot(euler_rodrigues(compton_angle, orthogonal_vector), comov_di... |
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstru... |
class classifier32ABN(nn.Module):
def __init__(self, num_classes=10, num_ABN=2, feat_dim=None):
if (feat_dim is None):
feat_dim = 128
super(self.__class__, self).__init__()
self.num_classes = num_classes
self.conv1 = nn.Conv2d(3, 64, 3, 1, 1, bias=False)
self.conv... |
def clean_no_mva(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 b... |
def load_ppr(input_dir='datasets/ppr/papers', dataset='ogbn-papers100M', idx=None, alpha=0.1, eps=0.001, topk=64, ppr_normalization='row', split_desc=None, make_undirected=None, shape=None):
if (input_dir is None):
return (None, None)
dump_suffix = f'{dataset}'
if (split_desc is not None):
d... |
.spark
def test_cluster(long_log_with_features, user_features, tmp_path):
path = (tmp_path / 'cluster').resolve()
dataset = create_dataset(long_log_with_features, user_features)
model = ClusterRec()
model.fit(dataset)
base_pred = model.predict(dataset, 5)
save(model, path)
loaded_model = loa... |
def test_float_assertion(assertion_to_ast_ref):
(assertion_to_ast, ref) = assertion_to_ast_ref
assertion = ass.FloatAssertion(source=ref, value=1.5)
assertion.accept(assertion_to_ast)
assert (__create_source_from_ast(assertion_to_ast.nodes) == 'var_0 = 5\nassert var_0 == pytest.approx(1.5, abs=0.01, rel... |
class MultiheadAttention(nn.Module):
def __init__(self, num_hidden_k):
super(MultiheadAttention, self).__init__()
self.num_hidden_k = num_hidden_k
self.attn_dropout = nn.Dropout(p=0.1)
def forward(self, key, value, query):
attn = t.bmm(query, key.transpose(1, 2))
attn = (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.