code stringlengths 101 5.91M |
|---|
def distort_color(image, color_ordering=0, fast_mode=True, scope=None, lower=0.75, upper=1.25, hue_max_delta=0.1, brightness_max_delta=(16.0 / 255.0)):
with tf.name_scope(scope, 'distort_color', [image]):
if fast_mode:
if (color_ordering == 0):
image = tf.image.random_brightness(... |
class Factory(BaseFactory):
def pt_defaults_scope_value():
return {'activation_fn': default_activation.current_value, 'batch_normalize': True, 'learned_moments_update_rate': 0.0003, 'variance_epsilon': 0.001, 'scale_after_normalization': True}
default_patch_feature_dim = 8
def __init__(self, recon_d... |
def tokenize_for_cer(text):
tokens = list(filter((lambda tok: (len(tok.strip()) > 0)), list(text)))
return tokens |
def get_padding(kernel_size: int, stride: int=1, dilation: int=1, **_) -> int:
padding = (((stride - 1) + (dilation * (kernel_size - 1))) // 2)
return padding |
def softmax_sample(visit_counts, actions, t):
counts_exp = (np.exp(visit_counts) * (1 / t))
probs = (counts_exp / np.sum(counts_exp, axis=0))
action_idx = np.random.choice(len(actions), p=probs)
return actions[action_idx] |
def test_ext(args, device_id, pt, step):
device = ('cpu' if (args.visible_gpus == '-1') else 'cuda')
if (pt != ''):
test_from = pt
else:
test_from = args.test_from
logger.info(('Loading checkpoint from %s' % test_from))
checkpoint = torch.load(test_from, map_location=(lambda storage,... |
def eval(G, dataset, batch_size, training=True, latents=None, labels=None, ratio=1.0, drange_net=[(- 1), 1], vis_types=None, num=100, grid=None, grid_size=None, step=None, keep_samples=True, num_heads=1, components_num=16, section_size=100):
def prefix(step):
return ('' if (step is None) else '{:06d}_'.form... |
def interpolate_like(input: ty.T, /, other: ty.T, mode: str='nearest', align_corners: bool=False) -> ty.T:
if (mode == 'nearest'):
align_corners = None
return F.interpolate(input, size=other.shape[(- 2):], mode=mode, align_corners=align_corners) |
class GrooveJoint(Constraint):
def __init__(self, a, b, groove_a, groove_b, anchr2):
self._constraint = cp.cpGrooveJointNew(a._body, b._body, groove_a, groove_b, anchr2)
self._ccontents = self._constraint.contents
self._pjc = cp.cast(self._constraint, ct.POINTER(cp.cpGrooveJoint)).contents
... |
def get_tree_starting_at(module, edges):
vertices_seen = [module]
new_edges = [edge for edge in edges if ((edge[0] == module) and (edge[1] != module))]
tree = [module]
while (len(new_edges) > 0):
tree.append(new_edges)
final_vertices = list({edge[1] for edge in new_edges})
vertic... |
class PseudoLabel(Algorithm):
def __init__(self, input_shape, num_classes, num_domains, hparams, algorithm):
super().__init__(input_shape, num_classes, num_domains, hparams)
(self.model, self.optimizer) = self.configure_model_optimizer(algorithm, alpha=hparams['alpha'])
self.beta = hparams['... |
_request
def before_request():
authToken = request.cookies.get('auth')
try:
payload = jwt.decode(authToken, jwtKey, algorithms=['HS256'])
g.user = payload.get('sub', None)
g.email = payload.get('email', None)
g.admin = payload.get('admin', False)
g.inactive = payload.get(... |
_grad()
def distributed_sinkhorn(out):
Q = torch.exp((out / config_model.epsilon)).t()
B = Q.shape[1]
K = Q.shape[0]
sum_Q = torch.sum(Q)
Q /= sum_Q
for it in range(config_model.sinkhorn_iterations):
sum_of_rows = torch.sum(Q, dim=1, keepdim=True)
Q /= sum_of_rows
Q /= K
... |
def train_one_epoch(config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler, loss_scaler):
model.train()
optimizer.zero_grad()
num_steps = len(data_loader)
batch_time = AverageMeter()
loss_meter = AverageMeter()
norm_meter = AverageMeter()
scaler_meter = AverageMeter(... |
def starcoder_tokenize(ctx: c_void_p, prompt: bytes, bos: bool=False) -> List[int]:
n_tokens = c_int(0)
c_tokens = _lib.tokenize_api(ctx, prompt, bos, pointer(n_tokens))
tokens = [c_tokens[i] for i in range(0, n_tokens.value)]
c_free(c_tokens)
return tokens |
class DenseNetDiscrimator(nn.Module):
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False, use_spectral_norm=True):
super(DenseNetDiscrimator, self).__init__()
self.model = densenet121(pretrained=True, use_spectral_norm=use_spectral_norm)
self.use_si... |
def reset_keras(per_process_gpu_memory_fraction=1.0):
sess = K.get_session()
K.clear_session()
sess.close()
gc.collect()
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = per_process_gpu_memory_fraction
config.gpu_options.visible_device_list = '0'
K.set_sessi... |
def conv_l1(x, nb_filters, kernel, stride=(1, 1)):
return Convolution2D(nb_filters, kernel, padding='same', kernel_initializer='he_uniform', kernel_regularizer=l1(0.01), strides=(stride, stride))(x) |
_module()
class DNLHead(FCNHead):
def __init__(self, reduction=2, use_scale=True, mode='embedded_gaussian', temperature=0.05, **kwargs):
super(DNLHead, self).__init__(num_convs=2, **kwargs)
self.reduction = reduction
self.use_scale = use_scale
self.mode = mode
self.temperatur... |
def _set_material(world, pos, player, tunnels, simplex):
(x, y) = pos
simplex = functools.partial(_simplex, simplex)
uniform = world.random.uniform
start = (4 - np.sqrt((((x - player.pos[0]) ** 2) + ((y - player.pos[1]) ** 2))))
start += (2 * simplex(x, y, 8, 3))
start = (1 / (1 + np.exp((- star... |
class BoldMin():
def __init__(self, v, disp):
self.v = float(v)
if isinstance(disp, collections.Callable):
disp = disp(v)
assert isinstance(disp, str)
self.disp = disp
def apply(cls, cols):
vals = []
for (idx, v) in enumerate(cols):
if isin... |
class RandomApply(RandomTransforms):
def __init__(self, transforms, p=0.5):
super(RandomApply, self).__init__(transforms)
self.p = p
def __call__(self, img):
if (self.p < random.random()):
return img
for t in self.transforms:
img = t(img)
return im... |
class MobileBertModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class PolyOneOverXRect(PolyGenerator):
def help(self):
return 'Region of validity is from 1/kappa to 1, and from -1/kappa to -1. Error is epsilon'
def generate(self, degree=6, delta=2, kappa=3, epsilon=0.1, ensure_bounded=True, return_scale=False):
(coefs_invert, scale1) = PolyOneOverX().genera... |
def mobilenet_v2(pretrained=False, progress=True, **kwargs):
model = MobileNetV2(**kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls['mobilenet_v2'], progress=progress)
model.load_state_dict(state_dict)
return model |
_start_docstrings('The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.', CAMEMBERT_START_DOCSTRING)
class TFCamembertModel(TFRobertaModel):
config_class = CamembertConfig |
def concat_images_with_tiled_vector_layer(images, vector, image_shape=None, vector_shape=None):
with K.name_scope('concat_images_with_tiled_vector_layer'):
if (not isinstance(images, list)):
images = [images]
if (vector_shape is None):
vector_shape = K.int_shape(vector)[1:]
... |
def inputs(eval_data):
if (not FLAGS.data_dir):
raise ValueError('Please supply a data_dir')
data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin')
(images, labels) = cifar10_input.inputs(eval_data=eval_data, data_dir=data_dir, batch_size=FLAGS.batch_size)
if FLAGS.use_fp16:
ima... |
class SkipConnectionBlock(nn.Module):
def __init__(self, ngf, sub_ngf, down_block=None, submodule=None, up_block=None, flat_block=None, flat_layers=1, padding_type='reflect', norm_layer=nn.BatchNorm2d, act_layer=nn.ReLU(inplace=True), use_dropout=False):
super(SkipConnectionBlock, self).__init__()
s... |
def deep_speaker_loss(y_true, y_pred):
elements = c.BATCH_SIZE
anchor = y_pred[0:elements]
positive_ex = y_pred[elements:(2 * elements)]
negative_ex = y_pred[(2 * elements):]
sap = batch_cosine_similarity(anchor, positive_ex)
san = batch_cosine_similarity(anchor, negative_ex)
loss = K.maximu... |
class components(Mask):
def build_mask(self):
mask = np.zeros((self.face.shape[0:2] + (1,)), dtype=np.float32)
r_jaw = (self.landmarks[0:9], self.landmarks[17:18])
l_jaw = (self.landmarks[8:17], self.landmarks[26:27])
r_cheek = (self.landmarks[17:20], self.landmarks[8:9])
l_c... |
def optimizer(cfg: ConfigDict) -> optax.OptState:
epoch_size = (cfg.epoch_size if hasattr(cfg, 'epoch_size') else (- 1))
batch_size = minimum_batch_size(cfg)
total_steps = (cfg.epochs * (epoch_size // batch_size))
warmup_steps = cfg.get('warmup_steps', 0)
if (cfg.schedule == 'constant'):
sch... |
class Bottleneck3d(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, use_final_relu=True):
super(Bottleneck3d, self).__init__()
bias = False
self.use_final_relu = use_final_relu
self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=(3, 1, 1)... |
def image_decode(video_path):
frames = []
try:
with Image.open(video_path) as img:
frames.append(np.array(img.convert('RGB')))
except BaseException as e:
raise RuntimeError('Caught "{}" when loading {}'.format(str(e), video_path))
return frames |
_optimizer('adadelta')
class Adadelta(LegacyFairseqOptimizer):
def __init__(self, args, params):
super().__init__(args)
self._optimizer = torch.optim.Adadelta(params, **self.optimizer_config)
def add_args(parser):
parser.add_argument('--adadelta-rho', type=float, default=0.9, metavar='RH... |
def _get_kins_instances_meta():
thing_ids = [k['id'] for k in KINS_CATEGORIES]
thing_colors = [k['color'] for k in KINS_CATEGORIES]
assert (len(thing_ids) == 7), len(thing_ids)
thing_dataset_id_to_contiguous_id = {k: i for (i, k) in enumerate(thing_ids)}
thing_classes = [k['name'] for k in KINS_CATE... |
def windows(*args, **kwargs):
pad = kwargs.pop('pad', 3)
try:
(si, ei) = apwindow.waveregions(args[2], pad=pad, asIndex=True)
except IOError:
try:
(si, ei) = apwindow.waveregions(args[2][:(- 1)], pad=pad, asIndex=True)
except IOError:
raise IOError(('Windows f... |
class __DisplMixin():
def displ_item(self, index):
(sample, ann) = (self.__getitem__(index), self.annotation[index])
return OrderedDict({'file': os.path.basename(ann['image']), 'sentence': ann['sentence'], 'label': ann['label'], 'image': sample['image']}) |
def _test():
import torch
in_size = (480, 480)
aux = True
pretrained = False
models = [(fcn8sd_resnetd50b_voc, 21), (fcn8sd_resnetd101b_voc, 21), (fcn8sd_resnetd50b_coco, 21), (fcn8sd_resnetd101b_coco, 21), (fcn8sd_resnetd50b_ade20k, 150), (fcn8sd_resnetd101b_ade20k, 150), (fcn8sd_resnetd50b_citysca... |
def parse_code(net_code: str):
assert (net_code[1] == 'g')
assert (net_code[(- 1)] == 'f')
nb_gnn_layers = int(net_code[0])
nb_dense_layers = int(net_code[(- 2)])
is_max = (True if (net_code[2] == 'm') else False)
return (nb_gnn_layers, nb_dense_layers, is_max) |
class InvertedResidual(nn.Module):
def __init__(self, inp: int, oup: int, stride: int, expand_ratio: int, norm_layer: Optional[Callable[(..., nn.Module)]]=None) -> None:
super(InvertedResidual, self).__init__()
self.stride = stride
assert (stride in [1, 2])
if (norm_layer is None):
... |
def get_file_list(path, extension=None):
if (extension is None):
file_list = [(path + f) for f in listdir(path) if isfile(join(path, f))]
else:
file_list = [(path + f) for f in listdir(path) if (isfile(join(path, f)) and (splitext(f)[1] == extension))]
file_list = sorted_alphanum(file_list)
... |
def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) |
def test_logistic_regression():
cancer = load_breast_cancer()
(X, y) = (cancer.data, cancer.target)
feature_names = cancer.feature_names
sk_lr = SKLogistic(tol=0.01, random_state=1)
our_lr = LogisticRegression(tol=0.01, feature_names=feature_names, random_state=1)
sk_lr.fit(X, y)
our_lr.fit(... |
def SubsampleAndTraverse(length, num_walks, hyperedges, vertexMemberships, alpha=1.0, beta=0):
walksSAT = []
for hyperedge_index in hyperedges:
hyperedge = hyperedges[hyperedge_index]
walk_vertex = []
curr_vertex = random.choice(hyperedge['members'])
for _ in range(num_walks):
... |
def simxGetJointForce(clientID, jointHandle, operationMode):
force = ct.c_float()
return (c_GetJointForce(clientID, jointHandle, ct.byref(force), operationMode), force.value) |
class HeartEpisodicDataLoader(DataLoader):
def __init__(self, batch_size, data_dir='data/', split='train', shuffle=True, collate_fn=None, num_workers=1, data_name=None, signal_type=None, num_mesh=None, seq_len=None, k_shot=None):
self.dataset = HeartEpisodicDataset(data_dir, data_name, signal_type, num_mesh... |
def main(args):
config = load_config(args)
if isinstance(config, omegaconf.dictconfig.DictConfig):
print(OmegaConf.to_yaml(config))
else:
pp = pprint.PrettyPrinter(indent=4)
pp.print(config)
mmtask = Task.config_task(config)
mmtask.build_model()
test_dataloader = get_data... |
class UNetMotionModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch'])
def from_pretrained(cls, *args, **kwargs):
requires_backends(cls, [... |
def get_help_docs(dic):
docs = []
for (k, v) in dic.iteritems():
doc = inspect.getdoc(v)
comp_doc = (('%s %s' % (v.__name__, doc.rsplit('\n')[0])) if doc else v.__name__)
docs.append(("'%s': %s" % (k, comp_doc)))
return docs |
def get_optimizer_scheduler(net, cfg):
train_cls = getattr(cfg.TRAIN, 'TRAIN_CLS', False)
if train_cls:
print('Only training classification head. Learnable parameters are shown below.')
param_dicts = [{'params': [p for (n, p) in net.named_parameters() if (('cls' in n) and p.requires_grad)]}]
... |
class TSDFEncoder(nn.Module):
def __init__(self, nf_in, nf_per_level, nf_out, use_skip_sparse=True, use_skip_dense=True):
nn.Module.__init__(self)
assert (type(nf_per_level) is list)
data_dim = 3
self.use_skip_sparse = use_skip_sparse
self.use_skip_dense = use_skip_dense
... |
def save_results(results_dict, exp_dir, log=True):
results_file = os.path.join(exp_dir, 'results.json')
save_dict(results_dict, results_file)
if log:
logger = get_logger(log_dir=exp_dir)
results_table_str = dict_to_tabular_str(results_dict)
logger.info(((((('\n' + '\n') + ' ... |
class VanDropPath(nn.Module):
def __init__(self, drop_prob: Optional[float]=None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return drop_path(hidden_states, self.drop_prob, self.training)
def extra_repr(self)... |
class QA_Metric():
def __init__(self, model=None, batch_size=8, max_seq_len=384, use_gpu=True):
if (model is None):
model = QA_Bert()
self.model = model
if (torch.cuda.is_available() and use_gpu):
self.gpu = True
self.model.model.to('cuda')
else:
... |
def get_article_ids_past_seven_days():
with closing(getDb().cursor()) as cur:
sql = 'SELECT article_id FROM articles \n WHERE datestamp > date_sub(now(), INTERVAL 1 WEEK)\n ORDER BY article_id ASC'
cur.execute(sql)
return [x[0] for x in cur.fetchall()] |
def wget(src, filename):
if (run(['wget', src, '-O', filename]).returncode != 0):
raise ValueError('Failed to download', src, 'to', filename) |
class RandomHorizontalFlip(object):
def __call__(self, sample):
(image, label) = (sample['image'], sample['label'])
if (random.random() < 0.5):
image = image.transpose(Image.FLIP_LEFT_RIGHT)
label = label.transpose(Image.FLIP_LEFT_RIGHT)
return {'image': image, 'label... |
class AsyncSumTree(SumTree):
async_ = True
def __init__(self, *args, **kwargs):
self.async_t = mp.RawValue('l', 0)
super().__init__(*args, **kwargs)
def _allocate_tree(self):
self.tree = np_mp_array(((2 ** self.tree_levels) - 1), np.float64)
self.tree.fill(0)
def reset(se... |
def blockdiag_butterfly_project_einsum_simple(M, nblocks1, nblocks2):
(m, n) = M.shape
(k, j) = (nblocks1, nblocks2)
M_permuted_batched = rearrange(M, '(l j) (k i) -> k j l i', k=nblocks1, j=nblocks2)
(U, Vt) = low_rank_project(M_permuted_batched, rank=1)
w1_bfly = rearrange(Vt, 'k j 1 i -> k j i')
... |
def test_digits_cosine_lazy_sparse():
model = SumRedundancySelection(100, 'precomputed', optimizer='lazy')
model.fit(X_digits_cosine_sparse)
assert_array_equal(model.ranking, digits_cosine_ranking)
assert_array_almost_equal(model.gains, digits_cosine_gains, 4) |
def build_fake_yaml():
fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n device: cpu\n quantization:\n model_wise:\n weight:\n granularity: per_tensor\n scheme: sym\n dtype: int8\n ... |
class WeightedLoss(torch.nn.Module):
def __init__(self, loss_fns: List[Union[(Callable, torch.nn.Module)]], weights: Optional[List[float]]=None):
super().__init__()
self.loss_fns = loss_fns
if (weights is None):
weights = ([1.0] * len(loss_fns))
else:
assert (... |
class Timer(object):
def __init__(self):
self.total_time = 0.0
self.calls = 0
self.start_time = 0.0
self.diff = 0.0
self.average_time = 0.0
self.duration = 0.0
def tic(self):
self.start_time = time.time()
def toc(self, average=True):
self.diff ... |
def load_pretrain(model, pretrained_dict):
device = torch.cuda.current_device()
check_keys(model, pretrained_dict)
model.load_state_dict(pretrained_dict, strict=False)
return model |
def train(policy, rollout_worker, evaluator, n_epochs, n_test_rollouts, n_cycles, n_batches, policy_save_interval, save_policies, **kwargs):
rank = MPI.COMM_WORLD.Get_rank()
latest_policy_path = os.path.join(logger.get_dir(), 'policy_latest.pkl')
best_policy_path = os.path.join(logger.get_dir(), 'policy_bes... |
def split_last(x, shape):
shape = list(shape)
assert (shape.count((- 1)) <= 1)
if ((- 1) in shape):
shape[shape.index((- 1))] = int((x.size((- 1)) / (- np.prod(shape))))
return x.view(*x.size()[:(- 1)], *shape) |
def main(args):
os.makedirs(args.output, exist_ok=True)
if args.distributed:
torch.cuda.set_device(args.local_rank)
torch.distributed.init_process_group(backend='nccl', init_method='env://')
cudnn.benchmark = True
logger = setup_logger(output=args.output, distributed_rank=dist.ge... |
class PrecisionRecallCurve(Metric):
def get_pytorch_metric(self) -> 'PyTorchPrecisionRecallCurve':
from bigdl.orca.learn.pytorch import pytorch_metrics
return pytorch_metrics.PrecisionRecallCurve()
def get_name(self) -> str:
return 'PrecisionRecallCurve' |
def test_get_dynamic_voxelnet():
if (not torch.cuda.is_available()):
pytest.skip('test requires GPU and torch+cuda')
dynamic_voxelnet_cfg = _get_model_cfg('dynamic_voxelization/dv_second_secfpn_6x8_80e_kitti-3d-car.py')
self = build_detector(dynamic_voxelnet_cfg).cuda()
points_0 = torch.rand([20... |
def train_model(args):
CEMBED_SIZE = args.CEMBED_SIZE
WEMBED_SIZE = args.WEMBED_SIZE
HIDDEN_SIZE = args.HIDDEN_SIZE
MLP_SIZE = args.MLP_SIZE
SPARSE = args.SPARSE
TIMEOUT = args.TIMEOUT
num_train_files = 0
Us = []
batch_trains = []
if args.train:
train = file_conll(args.tr... |
def build_backbone(args):
position_embedding = build_position_encoding(args)
train_backbone = (args.lr_backbone > 0)
return_interm_layers = (args.masks or (args.num_feature_levels > 1))
if ('resnet' in args.backbone):
backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.... |
def get_shufflenetv2b(width_scale, shuffle_group_first=True, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
init_block_channels = 24
final_block_channels = 1024
layers = [4, 8, 4]
channels_per_layers = [116, 232, 464]
channels = [([ci] * li) for (ci, li) in... |
def compute_lucrativity(setup_horner, setup_naive, eval_horner, eval_naive):
benefit_eval = (eval_naive - eval_horner)
loss_setup = (setup_horner - setup_naive)
return round((loss_setup / benefit_eval)) |
def maybe_download(url, dest):
if (not os.path.exists(dest)):
logger.info('Downloading %s to %s', url, dest)
download(url, dest) |
def wavread(fn):
(fs, data) = wavfile.read(fn)
data = (data.astype(np.float32) / (2 ** 15))
return (data, fs) |
class ModelOutput(OrderedDict):
def __post_init__(self):
class_fields = fields(self)
assert len(class_fields), f'{self.__class__.__name__} has no fields.'
assert all(((field.default is None) for field in class_fields[1:])), f'{self.__class__.__name__} should not have more than one required f... |
_model_architecture('transformer_lm', 'transformer_lm_gpt3_13')
def transformer_lm_gpt3_13(args):
args.decoder_layers = safe_getattr(args, 'decoder_layers', 40)
args.decoder_embed_dim = safe_getattr(args, 'decoder_embed_dim', 5120)
args.decoder_attention_heads = safe_getattr(args, 'decoder_attention_heads',... |
def collect_node_state(h, except_last=False):
retval = []
for i in list(h.keys())[:(- 1)]:
retval.append(h[i])
if (except_last == False):
retval.append(h[list(h.keys())[(- 1)]])
return torch.cat(retval, 0) |
def NN_loss(x, y, dim=0):
dist = pairwise_dist(x, y)
(values, indices) = dist.min(dim=dim)
return values.mean() |
def read_only_json_in_dir(dname, check_inv=False):
f = glob.glob(f'{dname}/*.json')
assert (len(f) == 1), f'json files in {dname}: {f}'
(f,) = f
with open(f) as fin:
ret = json.load(fin)
if check_inv:
assert (ret['nr_inverted'] == 0), f'inverted in {f}'
return ret |
def generate_random_ring_element(size, ring_size=(2 ** 64), device='cpu', **kwargs):
gen = (kwargs['generator'] if ('generator' in kwargs) else None)
rand_element = torch.empty(size=size, dtype=torch.long, device=device).random_((- (ring_size // 2)), to=((ring_size - 1) // 2), generator=gen)
if rand_element... |
def _destination_position(pdf, destination):
pagewidth = pdf.getPage(pdf.getDestinationPageNumber(destination)).cropBox.lowerRight[0]
if ((not destination.left) or (not destination.top)):
raise IncompleteCoordinatesError(destination)
column = ((2 * destination.left) // pagewidth)
return (pdf.get... |
def load_schema(name):
with open(((Path('tests') / 'schemas') / f'{name}.json'), 'r') as f:
return json.load(f) |
class PhysicsOracle(Baseline):
def __call__(self, token) -> Prediction:
(instance, sample) = token.split('_')
kinematics = _kinematics_from_tokens(self.helper, instance, sample)
ground_truth = self.helper.get_future_for_agent(instance, sample, self.sec_from_now, in_agent_frame=False)
... |
def rule(id, r, p):
_checkSettings()
for a in _rules:
if (a.isomorphism(r, 1, labelSettings=_ls) == 1):
r = a
break
else:
_rules.append(r)
f = r.print(p, p)
f = f[0]
fL = outputFile((f + '_L.pdf'))
fK = outputFile((f + '_K.pdf'))
fR = outputFile((f... |
def resize_multiple(img, sizes=(8, 16, 32, 64, 128, 256, 512, 1024), quality=100):
imgs = []
for size in sizes:
imgs.append(resize_and_convert(img, size, quality))
return imgs |
def load_checkpoint(model, checkpoint_path, model_key='model|module|state_dict', strict=True):
state_dict = load_state_dict(checkpoint_path, model_key=model_key)
incompatible_keys = model.load_state_dict(state_dict, strict=strict)
print(incompatible_keys)
return incompatible_keys |
def train(train_generator, train_size, input_num, dims_num):
print('Start Train Job! ')
start = time.time()
inputs = InputLayer(input_shape=(input_num, dims_num), batch_size=batch_size)
layer1 = Conv1D(64, 3, activation='relu')
layer2 = Conv1D(64, 3, activation='relu')
layer3 = Conv1D(128, 3, ac... |
class SEWForCTC(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def data_generator(data, dataloader, entity2idx):
for i in range(len(data)):
data_sample = data[i]
head = entity2idx[data_sample[0].strip()]
question = data_sample[1]
(question_tokenized, attention_mask) = dataloader.tokenize_question(question)
if (type(data_sample[2]) is str... |
class GCN(nn.Module):
def __init__(self, g, in_feats, n_hidden, n_classes, n_layers):
super(GCN, self).__init__()
self.g = g
self.layers = nn.ModuleList()
assert (n_layers >= 2)
self.layers.append(GraphConv(in_feats, n_hidden, allow_zero_in_degree=True))
for i in rang... |
def test_get_model_from_default_config():
ion_pos = jnp.array([[1.0, 2.0, 3.0], [(- 2.0), 3.0, (- 4.0)], [(- 0.5), 0.0, 0.0]])
ion_charges = jnp.array([1.0, 3.0, 2.0])
nelec = jnp.array([4, 3])
def _construct_model(model_type, use_det_resnet=True, determinant_fn_mode=None, explicit_antisym_subtype=None,... |
def test_hourglass_backbone():
with pytest.raises(AssertionError):
HourglassNet(num_stacks=0)
with pytest.raises(AssertionError):
HourglassNet(stage_channels=[256, 256, 384, 384, 384], stage_blocks=[2, 2, 2, 2, 2, 4])
with pytest.raises(AssertionError):
HourglassNet(downsample_times=... |
_module()
class CSRNetDecoder(nn.Module):
def __init__(self, load_weights=False, ratio=4, in_channels=256, num_cls=4, using_bn=False, loss_weight=1.0, size_average=False):
super(CSRNetDecoder, self).__init__()
self.seen = 0
self.backend_feat = [512, 256, 128, 64]
self.backend = make_... |
def get_imagenet_data(size=224):
base_dir = os.path.dirname(__file__)
with open(os.path.join(base_dir, 'images', 'ground_truth_val2012')) as f:
ground_truth_val2012 = {x.split()[0]: int(x.split()[1]) for x in f.readlines() if (len(x.strip()) > 0)}
with open(os.path.join(base_dir, 'images', 'synset_i... |
def getTrainingTestingData(batch_size):
(data, nyu2_train) = loadZipToMem('nyu_data.zip')
transformed_training = depthDatasetMemory(data, nyu2_train, transform=getDefaultTrainTransform())
transformed_testing = depthDatasetMemory(data, nyu2_train, transform=getNoTransform())
return (DataLoader(transforme... |
.parametrize('wide, deeptabular, deeptext, deepimage, X_wide, X_tab, X_text, X_img, target', [(wide, None, None, None, X_wide, None, None, None, target), (None, tabmlp, None, None, None, X_tab, None, None, target), (None, tabresnet, None, None, None, X_tab, None, None, target), (None, tabtransformer, None, None, None, ... |
def save_image(image_numpy, image_path):
image_pil = None
if (image_numpy.shape[2] == 1):
image_numpy = np.reshape(image_numpy, (image_numpy.shape[0], image_numpy.shape[1]))
image_pil = Image.fromarray(image_numpy, 'L')
else:
image_pil = Image.fromarray(image_numpy)
image_pil.sav... |
def write_version_py():
content = "# GENERATED VERSION FILE\n# TIME: {}\n\n__version__ = '{}'\nshort_version = '{}'\nversion_info = ({})\n"
sha = get_hash()
with open('mmdet/VERSION', 'r') as f:
SHORT_VERSION = f.read().strip()
VERSION_INFO = ', '.join(SHORT_VERSION.split('.'))
VERSION = ((S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.