code stringlengths 101 5.91M |
|---|
class BertTokenizer(object):
def __init__(self, vocab_file, do_lower_case=True, max_len=None, never_split=('[UNK]', '[SEP]', '[PAD]', '[CLS]', '[MASK]')):
if (not os.path.isfile(vocab_file)):
raise ValueError("Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretra... |
class TestCornerNet(TestCase):
def setUp(self) -> None:
register_all_modules()
model_cfg = get_detector_cfg('cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py')
backbone = dict(type='ResNet', depth=18, num_stages=4, out_indices=(3,), norm_cfg=dict(type='BN', requires_grad=True), norm... |
class AnchorHeadSemi(AnchorHeadTemplate):
def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, voxel_size, point_cloud_range, predict_boxes_when_training=True):
super().__init__(model_cfg=model_cfg, num_class=num_class, class_names=class_names, grid_size=grid_size, point_cloud_ra... |
def test_recarray(simple_dtype, packed_dtype):
elements = [(False, 0, 0.0, (- 0.0)), (True, 1, 1.5, (- 2.5)), (False, 2, 3.0, (- 5.0))]
for (func, dtype) in [(m.create_rec_simple, simple_dtype), (m.create_rec_packed, packed_dtype)]:
arr = func(0)
assert (arr.dtype == dtype)
assert_equal(... |
def test_check_parameters_minmax_values_float():
x = torch.tensor([1.1, 2.3, 7.8], dtype=torch.float32)
dtypes = [torch.bool]
_check_parameter(x, 'x', min_value=1.0, max_value=24)
assert_raises(ValueError, _check_parameter, x, 'x', min_value=1.2, max_value=24)
assert_raises(ValueError, _check_parame... |
def _gaussian_cross_kernels(q, x, s):
K_qq = _gaussian_kernel(q, q, s)
K_qx = _gaussian_kernel(q, x, s)
K_xx = _gaussian_kernel(x, x, s)
return (K_qq, K_qx, K_xx) |
class SlimmableAlexNet(BaseModule, SlimmableMixin):
input_shape = [None, 3, 256, 256]
def __init__(self, num_classes=10, track_running_stats=True, bn_type='bn', share_affine=True, width_scale=1.0, slimmabe_ratios=None):
super(SlimmableAlexNet, self).__init__()
self._set_slimmabe_ratios(slimmabe_... |
class Attention(att_model.Attention):
def __init__(self, config):
nn.Module.__init__(self)
self.config = config
self.rnn_size = config.rnn_size
self.att_hid_size = config.att_hid_size
mask_params = {'mask_type': self.config.prune_type, 'mask_init_value': self.config.prune_sup... |
class ImbalanceCIFAR100(ImbalanceCIFAR10):
base_folder = 'cifar-100-python'
url = '
filename = 'cifar-100-python.tar.gz'
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [['train', '16019d7e3df5f24257cddd939b257f8d']]
test_list = [['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc']]
meta =... |
def separate_channels(items, n_channels=9, use_note_on_pitch=True):
caches = []
for i in range((n_channels + 1)):
cache = LastCache()
caches.append(cache)
midi_instruments = []
for i in range((n_channels + 1)):
midi_instruments.append(dict())
for (i, ins_items) in enumerate(i... |
class Attention(nn.Module):
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
super().__init__()
inner_dim = (dim_head * heads)
context_dim = default(context_dim, query_dim)
self.scale = (dim_head ** (- 0.5))
self.heads = heads
self.t... |
class ResNet34Fc(nn.Module):
def __init__(self):
super(ResNet34Fc, self).__init__()
model_resnet34 = models.resnet34(pretrained=True)
self.conv1 = model_resnet34.conv1
self.bn1 = model_resnet34.bn1
self.relu = model_resnet34.relu
self.maxpool = model_resnet34.maxpool
... |
class ONNXRuntimeSegmentor(BaseSegmentor):
def __init__(self, onnx_file: str, cfg: Any, device_id: int):
super(ONNXRuntimeSegmentor, self).__init__()
import onnxruntime as ort
ort_custom_op_path = ''
try:
from mmcv.ops import get_onnxruntime_op_path
ort_custom... |
_pipeline_test
_vision
class ImageToTextPipelineTests(unittest.TestCase):
model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING
tf_model_mapping = TF_MODEL_FOR_VISION_2_SEQ_MAPPING
def get_test_pipeline(self, model, tokenizer, processor):
pipe = pipeline('image-to-text', model=model, tokenizer=tokenizer, i... |
def test__find_duplicates_dict_scores_false(cnn):
encoding_map = data_encoding_map()
dict_ret = cnn._find_duplicates_dict(encoding_map, min_similarity_threshold=0.9, scores=False)
assert isinstance(dict_ret['ukbench00002.jpg'], list)
assert (len(dict_ret['ukbench00002.jpg']) == 1)
assert (not isinst... |
def test_clustered_inference():
(n_samples, n_features) = (100, 2000)
support_size = 10
sigma = 5.0
rho = 0.95
n_clusters = 200
margin_size = 5
interior_support = (support_size - margin_size)
extended_support = (support_size + margin_size)
(X_init, y, beta, epsilon) = multivariate_1D... |
def union_bbox(bbox1, bbox2):
return [min(bbox1[0], bbox2[0]), max(bbox1[1], bbox2[1]), min(bbox1[2], bbox2[2]), max(bbox1[3], bbox2[3])] |
def _maybe_create_general_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
def has_annotations(instance: Instance) -> bool:
return ('annotations' in instance)
def has_only_crowd_anotations(instance: Instance) -> bool:
for ann in instance['annotations']:
if (ann.g... |
_module()
class AverageFusion(BaseModule):
def __init__(self, init_cfg=None):
super().__init__(init_cfg)
def forward(self, image_features, events_features):
fusion_features = []
for i in range(len(image_features)):
fusion_features.append(((image_features[i] + events_features[... |
def taubin_filtering():
knot_mesh = o3d.data.KnotMesh()
mesh_in = o3d.io.read_triangle_mesh(knot_mesh.path)
vertices = np.asarray(mesh_in.vertices)
noise = 5
vertices += np.random.uniform(0, noise, size=vertices.shape)
mesh_in.vertices = o3d.utility.Vector3dVector(vertices)
mesh_in.compute_v... |
def network_check(config: ElasticLaunchConfig, entrypoint: Union[(Callable, str, None)], args: List[Any]) -> bool:
config = copy.deepcopy(config)
config.network_check = False
if (not config.run_id):
run_id = str(uuid.uuid4().int)
logger.warning(f'config has no run_id, generated a random run_... |
def double_training_trick(train_Xy, val_Xy, test_Xy, inference_vectorizer):
def double(instances):
ret = []
for inst in instances:
original = inst
ret.append(original)
inst = copy.deepcopy(inst)
(inst['I'], inst['C']) = (original['C'], original['I'])
... |
class StableBaselines3ObservationWrapper(ObservationWrapper):
def __init__(self, env: CityLearnEnv):
assert env.central_agent, 'StableBaselines3ObservationWrapper is compatible only when env.central_agent = True. First set env.central_agent = True to use this wrapper.'
super().__init__(env)
... |
def grad_scale(x, scale):
y = x
y_grad = (x * scale)
return ((y - y_grad).detach() + y_grad) |
class ClassifierHead(nn.Module):
def __init__(self, in_channels=512, out_channels=40):
nn.Module.__init__(self)
self.fc = ME.MinkowskiLinear(in_channels, out_channels, bias=True)
self.glob_pool = ME.MinkowskiGlobalMaxPooling()
def forward(self, x):
return self.fc(self.glob_pool(x... |
_torch
class MakeStudentTester(unittest.TestCase):
_property
def teacher_config(self):
return AutoConfig.from_pretrained(TINY_BART)
def test_valid_t5(self):
(student, *_) = create_student_by_copying_alternating_layers(TINY_T5, tempfile.mkdtemp(), e=1, d=1)
self.assertEqual(student.co... |
def run_speed_benchmark():
if os.path.isfile(SPEED_RUN_PICKLE):
print(f'result file {SPEED_RUN_PICKLE} is already present. skipping data generation.')
return
print('\nSpeed test:')
print('testing {} evenly distributed random polynomials'.format(NR_SAMPLES_SPEED_TEST))
print('average timi... |
class MultiInputDecoder(FairseqDecoder):
def __init__(self, dictionary):
super().__init__(dictionary)
def select_decoder(self, mode, **kwargs):
raise NotImplementedError('Model must implement the select_decoder method')
return (None, kwargs)
def forward(self, prev_output_tokens, enco... |
def _make_ferminets():
(key, ion_pos, _, init_pos, spin_split, ndense_list) = _get_initial_pos_and_hyperparams()
slog_psis = []
for (cyclic_spins, use_det_resnet, determinant_fn_mode, full_det, num_heads, use_transformer) in [(False, False, models.construct.DeterminantFnMode.SIGN_COVARIANCE, False, 1, False... |
class CustomLexer(ExtendedRegexLexer):
name = 'A Lexer for IHeartLA'
functions = ['trace', 'tr', 'vec', 'diag', 'eig', 'conj', 'Re', 'Im', 'inv', 'det', 'svd', 'rank', 'null', 'orth', 'qr', 'sum', '', 'min', 'max', 'argmin', 'argmax', 'sin', 'asin', 'arcsin', 'cos', 'acos', 'arccos', 'tanh', 'cot', 'sec', 'csc'... |
def resize(input, size=None, scale_factor=None, mode='nearest', align_corners=None, warning=True):
if warning:
if ((size is not None) and align_corners):
(input_h, input_w) = tuple((int(x) for x in input.shape[2:]))
(output_h, output_w) = tuple((int(x) for x in size))
if ... |
def main():
if torch.cuda.is_available():
dev = (torch.cuda.device_count() - 1)
print('Running on gpu:{}'.format(dev))
else:
print('Running on cpu')
args = parse()
with open(os.path.join('configs', args.config), 'r') as f:
print('loading config file: {}'.format(os.path.jo... |
class WeightedPascalDetectionEvaluator(ObjectDetectionEvaluator):
def __init__(self, categories, matching_iou_threshold=0.5):
super(WeightedPascalDetectionEvaluator, self).__init__(categories, matching_iou_threshold=matching_iou_threshold, evaluate_corlocs=False, metric_prefix='WeightedPASCAL', use_weighted... |
class MLP_D(nn.Module):
def __init__(self, isize, nz, nc, ndf, ngpu):
super(MLP_D, self).__init__()
self.ngpu = ngpu
main = nn.Sequential(nn.Linear(((nc * isize) * isize), ndf), nn.ReLU(True), nn.Linear(ndf, ndf), nn.ReLU(True), nn.Linear(ndf, ndf), nn.ReLU(True), nn.Linear(ndf, 1))
... |
def download_file(url, dest_folder, fname, overwrite=False):
fpath = os.path.join(dest_folder, fname)
if os.path.isfile(fpath):
if overwrite:
print('Overwriting existing file')
else:
print('File exists, skipping download.')
return
tmp_fpath = (fpath + '.tm... |
def CheckGlobalStatic(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
if (((linenum + 1) < clean_lines.NumLines()) and (not Search('[;({]', line))):
line += clean_lines.elided[(linenum + 1)].strip()
match = Match('((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\\b(.*)'... |
def build_fake_yaml():
fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: x\n outputs: op_to_store\n device: cpu\n evaluation:\n accuracy:\n metric:\n topk: 1\n performance:\n warmup... |
_model
def eca_botnext26ts_256(pretrained=False, **kwargs):
kwargs.setdefault('img_size', 256)
return _create_byoanet('eca_botnext26ts_256', 'eca_botnext26ts', pretrained=pretrained, **kwargs) |
def x_u_split_semi_cifar(labels, num_expand_x, num_expand_u, device_ids, server_idxs):
unlabeled_idx = []
unlabeled_idx_list = []
for id in range(len(device_ids)):
unlabeled_idx = device_ids[id]
exapand_unlabeled = ((num_expand_u // len(device_ids[id])) // len(device_ids))
unlabeled_... |
def ensure_directory(path):
if ((path == '') or (path == '.')):
return
if ((path != None) and (len(path) > 0)):
assert (not op.isfile(path)), '{} is a file'.format(path)
if ((not os.path.exists(path)) and (not op.islink(path))):
try:
os.makedirs(path)
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--workers', type=int, default=10)
parser.add_argument('files', nargs='*', help='input files')
args = parser.parse_args()
seen = set()
with fileinput.input(args.files, mode='rb') as h:
pool = Pool(args.workers)
re... |
class Tagger(object):
def __init__(self):
self._spacy_tagger = spacy.load('en_core_web_sm', disable=['parser', 'ner'])
def tokenize_text(self, text: str):
return [t for t in self._spacy_tagger(text)] |
def test_batting_stats_bref_bad_year() -> None:
with pytest.raises(ValueError):
league_batting_stats.batting_stats_bref('NOT A YEAR') |
def train(train_Xy, n_epochs=4, batch_size=4):
tokenizer = RobertaTokenizer.from_pretrained('allenai/biomed_roberta_base')
model = RobertaForSequenceClassification.from_pretrained('allenai/biomed_roberta_base').to(device=device)
from transformers import AdamW
optimizer = torch.optim.SGD(model.parameters... |
class SppBackbone(nn.Module):
def __init__(self):
super(SppBackbone, self).__init__()
self.inplanes = 32
self.in_conv = nn.Sequential(nn.Conv2d(3, 16, kernel_size=3, padding=1, stride=2, bias=False), nn.BatchNorm2d(16), nn.ReLU(inplace=True), nn.Conv2d(16, 16, kernel_size=3, padding=1, bias=... |
def save_model(model, optimizer, epoch, args):
os.system('mkdir -p {}'.format(args.work_dirs))
if (optimizer is not None):
torch.save({'net': model.state_dict(), 'optim': optimizer.state_dict(), 'epoch': epoch}, os.path.join(args.work_dirs, '{}.pth'.format(epoch)))
else:
torch.save({'net': m... |
class DatasetFolder(VisionDataset):
def __init__(self, root, loader, extensions=None, transform_common=None, transform_parallel=None, target_transform=None, is_valid_file=None):
super(DatasetFolder, self).__init__(root, transform_common=transform_common, transform_parallel=transform_parallel, target_transfo... |
def get_quad_double_solutions(vrblvl=0):
nbrsols = number_quad_double_solutions(vrblvl)
if (vrblvl > 0):
print('number of solutions retrieved :', nbrsols)
result = []
if (nbrsols > 0):
sol = get_next_quad_double_solution(1, vrblvl)
if (vrblvl > 0):
print('the first so... |
def main(Pd_l=[0.0, 0.0]):
Nh_l = [100, 50]
number_of_class = 10
Nout = number_of_class
((X_train, Y_train), (X_test, Y_test)) = Data_func()
model = DNN(X_train.shape[1], Nh_l, Pd_l, Nout)
history = model.fit(X_train, Y_train, epochs=100, batch_size=100, validation_split=0.2)
performace_test... |
class RandomHorizontalFlip(object):
def __init__(self, prob=0.5):
self.prob = prob
def __call__(self, image, target, target2=None):
if (random.random() < self.prob):
image = F.hflip(image)
target = target.transpose(0)
if (not (target2 is None)):
... |
_immediately
def writer(args, finish_queue_lst):
(_, query_id_memmap) = get_embed_memmap(args.query_embedding_dir, args.embedding_dim)
with open(args.output_path, 'w') as outFile:
for qid in query_id_memmap:
score_docid_lst = []
for q in finish_queue_lst:
score_do... |
def main():
is_performance = True
is_int8 = False
output_file = 'benchmark.txt'
sequence_len = 0
iterations = 10
warmup = 5
batch_size = [16, 32]
instance_cores = [[4, 7]]
allocator_mode = [1]
model_list = ['bert_mini_mrpc', 'distilroberta_base_wnli', 'distilbert_base_uncased_sst... |
def gen_latex_table(table):
content = '\\begin{table*}\n'
content += tabulate(table[1:], headers=table[0], tablefmt='latex')
content += '\n\\end{table*}'
return content |
def main(opt, data_root='/data/MOT16/train', det_root=None, seqs=('MOT16-05',), exp_name='demo', save_images=False, save_videos=False, show_image=True):
logger.setLevel(logging.INFO)
result_root = os.path.join(data_root, '..', 'results', exp_name)
mkdir_if_missing(result_root)
data_type = 'mot'
accs... |
def process_sdf(sdf_path, table, progress=True):
supplier = Chem.SDMolSupplier(sdf_path)
molecules = []
fragments = []
linkers = []
out_table = []
uuid = 0
supplier = (tqdm(supplier, total=len(supplier)) if progress else supplier)
for mol in supplier:
mol_name = mol.GetProp('_Nam... |
class DispAgg(nn.Module):
def __init__(self, maxdisp=192):
super(DispAgg, self).__init__()
self.maxdisp = maxdisp
self.LGA3 = LGA3(radius=2)
self.LGA2 = LGA2(radius=2)
self.LGA = LGA(radius=2)
self.softmax = nn.Softmin(dim=1)
self.disparity = DisparityRegressi... |
def parse_args():
parser = argparse.ArgumentParser(description='Analyze Json Log')
subparsers = parser.add_subparsers(dest='task', help='task parser')
add_plot_parser(subparsers)
add_time_parser(subparsers)
args = parser.parse_args()
return args |
def build_model(x, is_training, config):
return backend(spec_frontend(x, is_training, config, 16), is_training, config, 500) |
def convert_y_domain(mpl_plot_bounds, mpl_max_y_bounds):
mpl_y_dom = [mpl_plot_bounds[1], (mpl_plot_bounds[1] + mpl_plot_bounds[3])]
plotting_height = (mpl_max_y_bounds[1] - mpl_max_y_bounds[0])
y0 = ((mpl_y_dom[0] - mpl_max_y_bounds[0]) / plotting_height)
y1 = ((mpl_y_dom[1] - mpl_max_y_bounds[0]) / pl... |
class TestMaskFormer(unittest.TestCase):
def setUp(self):
register_all_modules()
def _create_model_cfg(self):
cfg_path = 'maskformer/maskformer_r50_ms-16xb1-75e_coco.py'
model_cfg = get_detector_cfg(cfg_path)
base_channels = 32
model_cfg.backbone.depth = 18
model_... |
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--input_model', type=str, required=False, default='MRPC.zip')
parser.add_argument('--output_model', type=str, required=True)
parser.add_argument('--max_len', type=int, default=128, help='Maximum length of the sentence pairs')... |
def cat_id_to_desc(cat_id):
if isinstance(cat_id, (list, tuple)):
return tuple((_cat_descs[c] for c in cat_id))
else:
return _cat_descs[cat_id] |
class ResNetAttention(nn.Module):
def __init__(self, label_dim=527, pretrain=True):
super(ResNetAttention, self).__init__()
self.model = torchvision.models.resnet50(pretrained=False)
if (pretrain == False):
print('ResNet50 Model Trained from Scratch (ImageNet Pretraining NOT Used... |
def cross_entropy(outputs, targets, exp=1, size_average=True, eps=1e-05):
out = torch.nn.functional.softmax(outputs)
tar = torch.nn.functional.softmax(targets)
if (exp != 1):
out = out.pow(exp)
out = (out / out.sum(1).view((- 1), 1).expand_as(out))
tar = tar.pow(exp)
tar = (t... |
class PolynomialEncoderTransformer(AutotabularPreprocessingAlgorithm):
def __init__(self, cols=None, random_state: Optional[np.random.RandomState]=None):
self.cols = cols
self.random_state = random_state
def fit(self, X: PIPELINE_DATA_DTYPE, y: Optional[PIPELINE_DATA_DTYPE]=None) -> 'PolynomialE... |
class JointPlayerPolicy(OpenSpielPolicy):
def __init__(self, game, policies):
player_ids = [0, 1]
super(JointPlayerPolicy, self).__init__(game, player_ids)
self._policies = policies
self._obs = {'info_state': [None, None], 'legal_actions': [None, None]}
def action_probabilities(s... |
def entry_test_corrupt(cfg, model_path=''):
model = get_model(cfg)
model.to(DEVICE)
print(model)
if (torch.cuda.device_count() > 1):
model = nn.DataParallel(model)
(optimizer, lr_sched, bnm_sched) = get_optimizer(cfg.EXP.OPTIMIZER, cfg.TRAIN, model)
model = load_model_opt_sched(model, op... |
class ConvType(Enum):
HYPERCUBE = (0, 'HYPERCUBE')
SPATIAL_HYPERCUBE = (1, 'SPATIAL_HYPERCUBE')
SPATIO_TEMPORAL_HYPERCUBE = (2, 'SPATIO_TEMPORAL_HYPERCUBE')
HYPERCROSS = (3, 'HYPERCROSS')
SPATIAL_HYPERCROSS = (4, 'SPATIAL_HYPERCROSS')
SPATIO_TEMPORAL_HYPERCROSS = (5, 'SPATIO_TEMPORAL_HYPERCROSS'... |
def index_select_ND(source: torch.Tensor, index: torch.Tensor) -> torch.Tensor:
index_size = index.size()
suffix_dim = source.size()[1:]
final_size = (index_size + suffix_dim)
target = source.index_select(dim=0, index=index.view((- 1)))
target = target.view(final_size)
return target |
class DefaultConfigs():
def __init__(self, model, server_env=None, dim=2):
self.model = model
self.dim = dim
self.select_prototype_subset = None
self.backbone_path = 'models/i3dbackbone.py'
self.source_dir = os.path.dirname(os.path.realpath(__file__))
self.input_df_na... |
def fine_tune(args):
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from transformers import AdamW, AutoModelForSequenceClassification
train_dataset = load_dataset_from_local(args.train_data_path, args.model_name_or_path)
val_dataset = load_dataset_from_loc... |
def get_formants(waveform, sample_rate):
myformants = estimate_formants_lpc(waveform, sample_rate)
formants_dict = {'f1': myformants[2], 'f2': myformants[3], 'f3': myformants[4], 'f4': myformants[5]}
return formants_dict |
class Sequence(BaseLoader):
def __init__(self, split, name, regex='*.jpg', lmdb_env=None):
super(Sequence, self).__init__(split, osp.join(cfg.PATH.SEQUENCES, name), regex, lmdb_env=lmdb_env) |
def getLabel(d, argres):
lbs = []
for i in range(len(argres)):
lbs.append(d[argres[i]])
return lbs |
class SinCUTModel(CUTModel):
def modify_commandline_options(parser, is_train=True):
parser = CUTModel.modify_commandline_options(parser, is_train)
parser.add_argument('--lambda_R1', type=float, default=1.0, help='weight for the R1 gradient penalty')
parser.add_argument('--lambda_identity', t... |
def get_map(waypoint_tuple_list):
origin_map = np.zeros((6000, 6000, 3), dtype='uint8')
origin_map.fill(255)
origin_map = Image.fromarray(origin_map)
return origin_map |
def rotationx(theta):
return np.array([[1.0, 0.0, 0.0, 0.0], [0.0, np.cos(((theta / 180) * np.pi)), np.sin(((theta / 180) * np.pi)), 0.0], [0.0, (- np.sin(((theta / 180) * np.pi))), np.cos(((theta / 180) * np.pi)), 0.0], [0.0, 0.0, 0.0, 1.0]]) |
class TSP(Environment[State]):
def __init__(self, generator: Optional[Generator]=None, reward_fn: Optional[RewardFn]=None, viewer: Optional[Viewer[State]]=None):
self.generator = (generator or UniformGenerator(num_cities=20))
self.num_cities = self.generator.num_cities
self.reward_fn = (rewa... |
def flatten_and_batch_shift_indices(indices: torch.Tensor, sequence_length: int) -> torch.Tensor:
if ((torch.max(indices) >= sequence_length) or (torch.min(indices) < 0)):
print(f'All elements in indices should be in range (0, {(sequence_length - 1)})')
offsets = (get_range_vector(indices.size(0), get_d... |
class BitGroupNormActivation(nn.GroupNorm):
def __init__(self, config, num_channels, eps=1e-05, affine=True, apply_activation=True):
super(BitGroupNormActivation, self).__init__(config.num_groups, num_channels, eps=eps, affine=affine)
if apply_activation:
self.activation = ACT2FN[config.... |
def _a3_tab2(brd):
return ((((((- 0.0326) * (brd ** 4.0)) + (0.1816 * (brd ** 3.0))) - (0.2943 * (brd ** 2.0))) - (0.6329 * brd)) + 2.3193) |
def test_quadpack():
from galpy.util.quadpack import dblquad
int = dblquad((lambda y, x: ((4.0 * x) * y)), 0.0, 1.0, (lambda z: 0.0), (lambda z: 1.0))
assert (numpy.fabs((int[0] - 1.0)) < int[1]), 'galpy.util.quadpack.dblquad did not work as expected'
return None |
def read_swag_examples(input_file, is_training):
with open(input_file, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
lines = []
for line in reader:
if (sys.version_info[0] == 2):
line = list((unicode(cell, 'utf-8') for cell in line))
lines.append... |
class TestSNNBiasFit(TrainSNN, GenFullyObsSigmoidSNN, TestBase, unittest.TestCase):
def setUp(self):
self.n_neurons = 2
self.n_epochs = 10
self.sample_size = 500
self.length = 50
def preprocess(self):
self.trainable_model.params['kernel_weight'].data = deepcopy(self.gen_m... |
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if ('log_time' in kw):
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int(((te - ts) * 1000))
else:
print(... |
def get_epsilon_sigma_uff(m1, m2):
n1 = m1.GetNumAtoms()
n2 = m2.GetNumAtoms()
(vdw_epsilon, vdw_sigma) = (np.zeros((n1, n2)), np.zeros((n1, n2)))
m_combine = CombineMols(m1, m2)
for i1 in range(n1):
for i2 in range(n2):
param = GetUFFVdWParams(m_combine, i1, (i1 + i2))
... |
class SummarizationDatasetReaderPkl(DatasetReader):
def __init__(self, source_token_indexers: Dict[(str, TokenIndexer)]=None, dir: str=None, lazy: bool=True, single_oracle=True, fix_edu_num=None, trim_sent_oracle: bool=True, vocab_path: str='', save_to: str=None, dbg: bool=False) -> None:
super().__init__(l... |
def main(args):
cfg = setup(args)
model = build_model(cfg)
logger.info('Model:\n{}'.format(model))
if args.eval_only:
DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume)
return do_test(cfg, model)
distributed = (comm.get_world_s... |
_pt_tf_cross_test
_sentencepiece
_tokenizers
class TFPegasusIntegrationTests(unittest.TestCase):
src_text = [PGE_ARTICLE, XSUM_ENTRY_LONGER]
expected_text = ["California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to reduce the risk of wildfires.", 'N-Dubz hav... |
def select_using_loss(batch: Union[(torch.Tensor, torch.Tensor)], batch_idx: int, trainer: 'pl.Trainer', pl_module: 'pl.LightningModule', keep: float=0.5, scale_factor: float=1, loss_fn: Callable=None) -> Tuple[(torch.Tensor, torch.Tensor)]:
INTERPOLATE_MODES = {3: 'linear', 4: 'bilinear', 5: 'trilinear'}
(inpu... |
def adjust_beat_tracked_data(downbeat_fp, midi_obj):
downbeat = get_downbeats(downbeat_fp)
print(downbeat_fp)
tps = (735 * 60)
changed_spb = []
prev = downbeat[0]
bpms = []
for db in downbeat[1:]:
bpm = int(((1 / (db - prev)) * 60))
changed_spb.append((db - prev))
tic... |
class GATConv(nn.Module):
def __init__(self, in_channels: int, out_channels: int, bias: bool=True, use_bn: bool=False, drop_rate: float=0.5, atten_neg_slope: float=0.2, is_last: bool=False):
super().__init__()
self.is_last = is_last
self.bn = (nn.BatchNorm1d(out_channels) if use_bn else None... |
def test_img_self_att():
fake_feature = Variable(torch.randn(16, ((32 * 7) * 7)))
fake_feature = fake_feature.view(16, (- 1), 7, 7)
img_self_attention = ImageSelfAttention(32)
out = img_self_attention(fake_feature)
print(out.size()) |
def normalized_columns_initializer(weights, std=1.0):
out = torch.randn(weights.size())
out *= (std / torch.sqrt(out.pow(2).sum(1).expand_as(out)))
return out |
class TFAutoModelForMaskedLM():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
class EfficientNetV2S(extractor.BaseModule):
def __init__(self, config, name):
super(EfficientNetV2S, self).__init__()
self.name = name
drop_rate = config['dropout']
self.features = timm.create_model('efficientnetv2_s', drop_rate=drop_rate)
self.n_features = 0
def forward... |
_REGISTRY.register()
def build_fcos_resnet_fpn_backbone(cfg, input_shape: ShapeSpec):
if cfg.MODEL.BACKBONE.ANTI_ALIAS:
bottom_up = build_resnet_lpf_backbone(cfg, input_shape)
elif (cfg.MODEL.RESNETS.DEFORM_INTERVAL > 1):
bottom_up = build_resnet_interval_backbone(cfg, input_shape)
elif cfg.... |
class Loader(object):
def __call__(self, model, pattern_config=None):
framework = get_model_fwk_name(model)
if (framework == 'tensorflow'):
if isinstance(model, str):
graph = tf.Graph()
graph_def = tf.compat.v1.GraphDef()
with open(model, '... |
class Trainer(object):
def __init__(self, config, train_data_loader, test_data_loader):
self.config = config
self.train_data_loader = train_data_loader
self.test_data_loader = test_data_loader
self.start_step = 0
self.tensorboard = None
self._build_model()
if ... |
class WhereConditionNode(StmtNode):
def __init__(self, parse_info=None, raw_text=None):
super().__init__(IRNodeType.WhereCondition, parse_info=parse_info, raw_text=raw_text)
self.id = []
self.type = None
self.desc = None
def get_type_dict(self):
ret = {}
for name ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.