code stringlengths 101 5.91M |
|---|
def noise_vector(x, y, z, int_x, int_y, int_z, seed_offset):
vector = _get_vector(int_x, int_y, int_z, seed_offset)
diff_vector = ((x - int_x), (y - int_y), (z - int_z))
return (((vector[0] * diff_vector[0]) + (vector[1] * diff_vector[1])) + (vector[2] * diff_vector[2])) |
class VideoTestVimeo90KDataset(data.Dataset):
def __init__(self, opt):
super(VideoTestVimeo90KDataset, self).__init__()
self.opt = opt
self.cache_data = opt['cache_data']
if self.cache_data:
raise NotImplementedError('cache_data in Vimeo90K-Test dataset is not implemented... |
def ParseLstmDelayString(lstm_delay):
split1 = lstm_delay.split(' ')
lstm_delay_array = []
try:
for i in range(len(split1)):
indexes = [int(x) for x in split1[i].strip().lstrip('[').rstrip(']').strip().split(',')]
if (len(indexes) < 1):
raise ValueError(('inva... |
class MultiLabelField(Field[torch.Tensor]):
_already_warned_namespaces: Set[str] = set()
def __init__(self, labels: Sequence[Union[(str, int)]], label_namespace: str='labels', skip_indexing: bool=False, num_labels: Optional[int]=None) -> None:
self.labels = labels
self._label_namespace = label_n... |
def main():
args = parse_args()
neural_engine_graph = diffusion_utils.neural_engine_init(args.ir_path)
if (args.pipeline == 'text2img'):
dpm = DPMSolverMultistepScheduler.from_pretrained(args.input_model, subfolder='scheduler')
pipe = diffusion_utils.StableDiffusionPipeline.from_pretrained(a... |
class SuperGlueConfig(datasets.BuilderConfig):
def __init__(self, features, data_url, citation, url, label_classes=('False', 'True'), few_shot_url=None, is_few_shot=False, train_path=None, pseudolabels_provided=False, **kwargs):
super(SuperGlueConfig, self).__init__(version=datasets.Version('1.0.3'), **kwar... |
((not torch.cuda.is_available()), 'No gpu available for cuda tests')
class BF16GradScalerTest(unittest.TestCase):
def setUp(self) -> None:
self.x = torch.randn(4, 4).cuda()
self.m = torch.nn.Linear(4, 1).cuda()
kwargs = {'lr': 0.1}
self.o = torch.optim.SGD(self.m.parameters(), **kwar... |
class MultiTaskModel(nn.Module):
def __init__(self, args, pair_encoder, FDS=None):
super(MultiTaskModel, self).__init__()
self.args = args
self.pair_encoder = pair_encoder
self.FDS = FDS
self.start_smooth = args.start_smooth
def build_regressor(self, task, d_inp):
... |
_bpe('bytes')
class Bytes(object):
def __init__(self, *unused):
pass
def add_args(parser):
pass
def encode(x: str) -> str:
encoded = byte_encode(x)
escaped = encoded.replace(SPACE, SPACE_ESCAPE)
return SPACE.join(list(escaped))
def decode(x: str) -> str:
u... |
def train_lower(u0, v0, ka0, kb0, x_minus, x_plus, y_minus, y_plus, lr_x=0.001, lr_k=0.01, max_iter=100, print_info=True):
device = x_minus.device
x_best = torch.zeros(x_minus.shape).to(device)
y_best = torch.zeros(x_minus.shape).to(device)
a_best = torch.zeros(x_minus.shape).to(device)
b_best = tor... |
def fake_env(env):
if hasattr(env, 'step_wait'):
if hasattr(env, 'venv'):
original = env.venv
(child, original) = fake_env(original)
env.venv = child
return (env, original)
else:
return (TestingVecEnv(env.num_envs, env.observation_space, en... |
def save_results(content, save_path, ori_shape):
ori_len = np.prod(ori_shape)
scale = int(np.sqrt((len(content) / ori_len)))
target_size = [int((size * scale)) for size in ori_shape[:2][::(- 1)]]
img = Image.frombytes('RGB', target_size, content, 'raw', 'BGR', 0, 0)
img.save(save_path) |
def expr_to_dict(e):
d = None
if isinstance(e, Var):
d = {'type': 'Var', 'name': e.name, 'primed': e.primed}
elif isinstance(e, Const):
d = {'type': 'Const', 'value': e.value}
else:
d = {'type': 'Op', 'name': e.name, 'args': list(map(expr_to_dict, e.args))}
d['original'] = e.... |
def test_loss():
self = PartA2BboxHead(num_classes=3, seg_in_channels=16, part_in_channels=4, seg_conv_channels=[64, 64], part_conv_channels=[64, 64], merge_conv_channels=[128, 128], down_conv_channels=[128, 256], shared_fc_channels=[256, 512, 512, 512], cls_channels=[256, 256], reg_channels=[256, 256])
cls_sco... |
class API():
def __init__(self, host=None, port=None, name='serving_stream'):
self.name = name
self.host = (host if host else 'localhost')
self.port = (port if port else '6379')
self.db = redis.StrictRedis(host=self.host, port=self.port, db=0)
try:
self.db.xgroup_... |
def contains_sub_symbol(identifier):
if ('`' in identifier):
new_id = identifier
results = re.findall('`[^`]*`', new_id)
for item in results:
new_id = new_id.replace(item, '')
return ('_' in new_id)
return ('_' in identifier) |
def discriminator_wgan_gp(img, dim=64, reuse=True, training=True):
conv_ln_lrelu = partial(conv, normalizer_fn=ln, activation_fn=lrelu, biases_initializer=None)
with tf.variable_scope('discriminator', reuse=reuse):
y = lrelu(conv(img, dim, 5, 2))
y = conv_ln_lrelu(y, (dim * 2), 5, 2)
y =... |
def note_sequence_to_onsets_and_offsets_and_programs(ns: note_seq.NoteSequence) -> Tuple[(Sequence[float], Sequence[NoteEventData])]:
notes = sorted(ns.notes, key=(lambda note: (note.is_drum, note.program, note.pitch)))
times = ([note.end_time for note in notes if (not note.is_drum)] + [note.start_time for note... |
def corrector_absresendgame_set(tol):
from phcpy.phcpy2c3 import py2c_set_value_of_continuation_parameter as set
return set(24, tol) |
def get_anno_ids(anno_path, pic_to_tensor_function, threshold):
pic = Image.open(anno_path)
tensor = pic_to_tensor_function(pic)
values = (tensor.view((- 1)).bincount() > threshold).nonzero().view((- 1)).tolist()
if (0 in values):
values.remove(0)
if (255 in values):
values.remove(25... |
def clean_csv(input_file, output_file):
input_r = open(input_file, 'r').read()
lines = input_r.split('')
print(len(lines))
for line in lines[:10]:
print(line[(- 3):]) |
_module()
class PSENetTargets(PANetTargets):
def __init__(self, shrink_ratio=(1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4), max_shrink=20):
super().__init__(shrink_ratio=shrink_ratio, max_shrink=max_shrink) |
class FlaxStableDiffusionXLPipeline(metaclass=DummyObject):
_backends = ['flax', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['flax', 'transformers'])
def from_pretrai... |
def padded_nonzero(tensor, padding=0):
indices = padded_stack([tensor[i].nonzero().view((- 1)) for i in range(tensor.shape[0])], padding)
return indices |
def read_CR(path, seed=1234):
file_path = os.path.join(path, 'custrev.all')
(data, labels) = read_corpus(file_path)
random.seed(seed)
perm = list(range(len(data)))
random.shuffle(perm)
data = [data[i] for i in perm]
labels = [labels[i] for i in perm]
return (data, labels) |
class SqueezeAndExcitationBlock2D(_SqueezeAndExcitationBlockND):
def __init__(self, in_channels, reduction=16, dimension=2, **kwargs):
super().__init__(in_channels, reduction, dimension, **kwargs)
def _check_input_dim(self, input):
if (input.dim() != 4):
raise ValueError('expected 4D... |
class RoundSTE(torch.autograd.Function):
def forward(ctx, x):
return torch.round(x)
def backward(ctx, grad):
return grad
def reverse(ctx, x):
return ((x + torch.rand_like(x)) - 0.5) |
class AugmentationList(Augmentation):
def __init__(self, augs):
super().__init__()
self.augs = [_transform_to_aug(x) for x in augs]
def __call__(self, aug_input) -> TransformList:
tfms = []
for x in self.augs:
tfm = x(aug_input)
tfms.append(tfm)
re... |
class DiffusionDecoder():
def __init__(self, model: MultinomialDiffusion) -> None:
self.model = model
self.time_steps = model.time_steps
self.residues = model.residues
self.loss_function = DiffusionLoss(model=self.model)
def decode(self, spectra: torch.FloatTensor, spectra_paddin... |
class SpatialPath(BaseModule):
def __init__(self, in_channels=3, num_channels=(64, 64, 64, 128), conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU'), init_cfg=None):
super(SpatialPath, self).__init__(init_cfg=init_cfg)
assert (len(num_channels) == 4), 'Length of input channels ... |
def r_precision(r):
r = (np.asarray(r) != 0)
z = r.nonzero()[0]
if (not z.size):
return 0.0
return np.mean(r[:(z[(- 1)] + 1)]) |
def get_local_path_from_repo_id(repo_id, models_root=os.getenv('HF_HOME')):
if (models_root is None):
invalidInputError(False, errMsg='To use repo_id, you must set environmrnt variable `HF_HOME`.')
(repo_id, model_id) = repo_id.split('/')
cache_dir = os.path.join(models_root, 'diffusers', f'models--... |
def remove_node_by_span(tree, span, label, position, in_place):
nodes = tree.get_nodes('all', span[0], span[1])
nodes = [node for node in nodes if (node.label == label)]
if (len(nodes) <= position):
return (False, 'No node matching {} ({}, {} - {}) found'.format(position, label, *span))
return r... |
class DPM_Solver():
def __init__(self, model_fn, noise_schedule, algorithm_type='dpmsolver++', correcting_x0_fn=None, correcting_xt_fn=None, thresholding_max_val=1.0, dynamic_thresholding_ratio=0.995):
self.model = (lambda x, t: model_fn(x, t.expand(x.shape[0])))
self.noise_schedule = noise_schedule... |
def remove_done_folders(task, folders_to_convert, data_dir, save_dir, store_prediction, store_representation):
rgb_dir = os.path.join(data_dir, 'rgb')
encoding_dir = os.path.join(save_dir, f'{task}_encoding')
decoding_dir = os.path.join(save_dir, f'{task}_decoding')
folders_to_use = set()
for folder... |
def leg_pose_to_motor_angles_with_half_pi_offset_and_safety(leg_pose):
motor_angles = []
for idx in range(4):
swing = leg_pose[(idx * 2)]
extend = leg_pose[((idx * 2) + 1)]
motor_angles.extend(swing_extend_to_motor_angles(idx, swing, extend))
return motor_angles |
def mask_cross_entropy(pred, target, label, reduction='mean', avg_factor=None):
assert ((reduction == 'mean') and (avg_factor is None))
num_rois = pred.size()[0]
inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device)
pred_slice = pred[(inds, label)].squeeze(1)
return F.binary_cross_e... |
class BertPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def create_new_model_like(model_type: str, new_model_patterns: ModelPatterns, add_copied_from: bool=True, frameworks: Optional[List[str]]=None):
model_info = retrieve_info_for_model(model_type, frameworks=frameworks)
model_files = model_info['model_files']
old_model_patterns = model_info['model_patterns']
... |
class EncoderDecoderTests(tf.test.TestCase):
def setUp(self):
super(EncoderDecoderTests, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.batch_size = 2
self.input_depth = 4
self.sequence_length = 10
self.vocab_list = [str(_) for _ in range(10)]
se... |
def main(opt):
logger.setLevel(logging.INFO)
result_root = opt.out_root
result_json_root = osp.join(result_root, 'json')
mkdir_if_missing(result_json_root)
transforms = T.Compose([T.ToTensor(), T.Normalize(opt.im_mean, opt.im_std)])
obs_root = osp.join(opt.data_root, 'obs', opt.split, opt.obid)
... |
def jaccard_simple(annotation, segmentation):
annotation = annotation.astype(np.bool)
segmentation = segmentation.astype(np.bool)
if (np.isclose(np.sum(annotation), 0) and np.isclose(np.sum(segmentation), 0)):
return 1
else:
return (np.sum((annotation & segmentation)) / np.sum((annotatio... |
class ROIPoolingParameter(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _ROIPOOLINGPARAMETER |
class ROIAlignRotated(nn.Module):
def __init__(self, output_size, spatial_scale, sampling_ratio):
super(ROIAlignRotated, self).__init__()
self.output_size = output_size
self.spatial_scale = spatial_scale
self.sampling_ratio = sampling_ratio
def forward(self, input, rois):
... |
def _collate_fn(batch: List[Dict]) -> Tuple[(torch.tensor, str, str)]:
(ims, filenames, bad_images) = ([], [], [])
for b in batch:
im = b['image']
if (im is not None):
ims.append(im)
filenames.append(b['filename'])
else:
bad_images.append(b['filename']... |
def clean_standard_data(standard_record):
def sanitize_sex(sex):
sex = sex.lower()
if (('f' in sex) or ('w' in sex)):
return 'F'
else:
return 'M'
def sanitize_age(age):
for possible_age in age.split(' '):
try:
return int(possibl... |
def process_task(task, token_indexer, vocab):
if (hasattr(task, 'train_data_text') and (task.train_data_text is not None)):
train = process_split(task.train_data_text, token_indexer)
else:
train = None
if (hasattr(task, 'val_data_text') and (task.val_data_text is not None)):
val = pr... |
def extract(fxml):
(sentlist, constlist) = reader(fxml)
sentlist = combine(sentlist, constlist)
fconll = fxml.replace('.xml', '.conll')
writer(sentlist, fconll) |
def _load_shared_library(lib_base_name: str):
(_base_path, _lib_paths) = get_shared_lib_info(lib_base_name=lib_base_name)
if ('GPTNEOX_CPP_LIB' in os.environ):
lib_base_name = os.environ['GPTNEOX_CPP_LIB']
_lib = pathlib.Path(lib_base_name)
_base_path = _lib.parent.resolve()
_lib... |
def test_capture_function_twice(ing):
def foo(something):
pass
assert (ing.captured_functions == [foo])
ing.capture(foo)
assert (ing.captured_functions == [foo]) |
class ExpReduceMaxLROnIteration():
def __init__(self, gamma=1):
self.gamma = gamma
def __call__(self, eta_min, eta_max, iterations):
return (eta_min, (eta_max * (self.gamma ** iterations))) |
class YoloLayer(nn.Module):
def __init__(self, anchor_mask=[], num_classes=0, anchors=[], num_anchors=1, use_cuda=None):
super(YoloLayer, self).__init__()
use_cuda = (torch.cuda.is_available() and (True if (use_cuda is None) else use_cuda))
self.device = torch.device(('cuda' if use_cuda else... |
def get_iou_dataset(model_id, edge_length_threshold=0.1, filled=False, recalc=False):
manager = IouAutoSavingManager(model_id=model_id, edge_length_threshold=edge_length_threshold, filled=filled)
if (not recalc):
if (not os.path.isfile(manager.path)):
recalc = True
else:
... |
def save_rouge_scores(str_scores):
with open('rouge_scores.txt', 'w') as output:
output.write(str_scores) |
def compute_target(answers, ans2label):
answer_count = {}
if (len(answers) == 1):
answer_ = preprocess_answer(answers[0]['answer'])
answer_count[answer_] = 10
else:
for answer in answers:
answer_ = preprocess_answer(answer['answer'])
answer_count[answer_] = (a... |
def sin2_cos2_width_3(width=None, sin_theta=None, cos_theta=None, features=None):
sin_cos_height_width = []
if (features is not None):
sin_cos_height_width = [features['bbox/sin_theta'], features['bbox/cos_theta'], features['bbox/width']]
else:
sin_cos_height_width = [sin_theta, cos_theta, w... |
class Evaluator():
def __init__(self, dataset, tokenizer, batch_size=1, pad_val=1, pad_max=512):
self.dataset = dataset
self.tokenizer = tokenizer
self.batch_size = batch_size
self.pad_val = pad_val
self.pad_max = pad_max
self.dataset = self.dataset.map(self.tokenize_... |
def evaluate(dataset, split, time_data):
print('Evaluate dataset {} in split {} for single stamp supervision'.format(dataset, split))
bz_stages = ('/margin_map_both' + time_data)
recog_path = ((((('./results/' + dataset) + bz_stages) + '_split_') + split) + '/')
ground_truth_path = (('./data/' + dataset... |
class ProgressBar(object):
def __init__(self, task_num=0, bar_width=50, start=True):
self.task_num = task_num
max_bar_width = self._get_max_bar_width()
self.bar_width = (bar_width if (bar_width <= max_bar_width) else max_bar_width)
self.completed = 0
if start:
sel... |
class Searcher(BaseSearcher):
def __init__(self):
super().__init__(name=Path(__file__).stem)
self._repo = config.INSTANCE['publish'][self.name]
def _search(self, query: str) -> SearchResults:
dfs = []
num_results = 0
validator = SqliteFTS5Matcher(query)
paginated_... |
def test_sample_nyu_rgbd_image():
gt_prefix = 'SampleNYURGBDImage'
(gt_data_root, gt_download_dir, gt_extract_dir) = get_test_data_dirs(gt_prefix)
rgbd_image_nyu = o3d.data.SampleNYURGBDImage()
assert Path(gt_download_dir).is_dir()
assert (Path(rgbd_image_nyu.color_path) == (gt_extract_dir / 'NYU_co... |
def accuracy(output, target, topk=(1,)):
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expand_as(pred)).contiguous()
res = []
for k in top... |
_model
def tf_efficientnet_lite1(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet_lite('tf_efficientnet_lite1', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)
return model |
_model
def efficientnet_cc_b0_8e(pretrained=False, **kwargs):
model = _gen_efficientnet_condconv('efficientnet_cc_b0_8e', channel_multiplier=1.0, depth_multiplier=1.0, experts_multiplier=2, pretrained=pretrained, **kwargs)
return model |
def int4a2nbr(data, verbose=False):
if verbose:
print('-> int4a2nbr, data :', data)
dim = len(data)
szd = (4 * dim)
if verbose:
print('-> int4a2nbr size of result :', szd)
result = create_string_buffer(b'', szd)
for k in range(dim):
if (data[k] < 256):
result[... |
def _create_dummy_loader():
loader = dict(type='HardDiskLoader', repeat=1, parser=dict(type='LineStrParser', keys=['file_name', 'text']))
return loader |
def get_ind(data, start):
array_ = []
for i in range(len(data)):
array_.append((i + start))
return array_ |
def eval_train(model, train_loader):
model.eval()
train_loss = 0
correct = 0
with torch.no_grad():
for (data, target) in train_loader:
(data, target) = (data.cuda(), target.cuda())
output = model(data)
train_loss += F.cross_entropy(output, target, size_average... |
class LTOCF1(BasicModel):
def __init__(self, config: dict, dataset: BasicDataset):
super(LTOCF1, self).__init__()
self.config = config
self.dataset: dataloader.BasicDataset = dataset
self.__init_weight()
self.__init_ode()
def __init_weight(self):
self.num_users = ... |
def check_free_port(host, port, verbose=True):
sock = socket.socket()
try:
sock.bind((host, port))
sock.close()
print('host {} on port {} is AVAIL'.format(host, port))
return True
except:
print('host {} on port {} is BUSY'.format(host, port))
sock.close()
... |
def _start_():
seed = args.seed
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
np.set_printoptions(precision=4)
torch.set_printoptions(precision=4)
print()
print('[ARGUMENTS]')
print(args)
print()
return |
def ResNet152Body(net, from_layer, use_pool5=True, use_dilation_conv5=False, **bn_param):
conv_prefix = ''
conv_postfix = ''
bn_prefix = 'bn_'
bn_postfix = ''
scale_prefix = 'scale_'
scale_postfix = ''
ConvBNLayer(net, from_layer, 'conv1', use_bn=True, use_relu=True, num_output=64, kernel_si... |
def test_fixing_values(conf_scope):
cfg = conf_scope({'a': 100})
assert (cfg['a'] == 100)
assert (cfg['composit1'] == 102.0) |
def semnasnet_100(pretrained=False, **kwargs):
model = _gen_mnasnet_a1('semnasnet_100', 1.0, pretrained=pretrained, **kwargs)
return model |
def add_special_tokens_to_vocab(model_dir: Path, separate_vocab=False) -> None:
if separate_vocab:
vocab = load_yaml(find_src_vocab_file(model_dir))
vocab = {k: int(v) for (k, v) in vocab.items()}
num_added = add_to_vocab_(vocab, ['<pad>'])
save_json(vocab, (model_dir / 'vocab.json')... |
def tokenize(refs, cands, no_op=False):
tokenizer = PTBTokenizer()
if no_op:
refs = {idx: [r for r in c_refs] for (idx, c_refs) in enumerate(refs)}
cands = {idx: [c] for (idx, c) in enumerate(cands)}
else:
refs = {idx: [{'caption': r} for r in c_refs] for (idx, c_refs) in enumerate(r... |
class CityscapesSemSegEvaluator(CityscapesEvaluator):
def process(self, inputs, outputs):
from cityscapesscripts.helpers.labels import trainId2label
for (input, output) in zip(inputs, outputs):
file_name = input['file_name']
basename = os.path.splitext(os.path.basename(file_n... |
def ibn_resnet152(**kwargs):
return get_ibnresnet(blocks=152, model_name='ibn_resnet152', **kwargs) |
def _res_shortcut_D_dec(block, layers, **kwargs):
model = ResShortCut_D_Dec(block, layers, **kwargs)
return model |
def read_data(config, data_type, ref, data_filter=None):
data_path = os.path.join(config.data_dir, 'data_{}.json'.format(data_type))
shared_path = os.path.join(config.data_dir, 'shared_{}.json'.format(data_type))
with open(data_path, 'r') as fh:
data = json.load(fh)
with open(shared_path, 'r') a... |
def _add_categories_metadata(dataset_name: str, categories: Dict[(str, Any)]):
meta = MetadataCatalog.get(dataset_name)
meta.categories = {c['id']: c['name'] for c in categories}
logger = logging.getLogger(__name__)
logger.info('Dataset {} categories: {}'.format(dataset_name, categories)) |
class DIV2K(srdata.SRData):
def __init__(self, args, train=True):
super(DIV2K, self).__init__(args, train)
self.repeat = (args.test_every // (args.n_train // args.batch_size))
def _scan(self):
list_hr = []
if self.train:
idx_begin = 0
idx_end = self.args.n... |
def test_nrtr_encoder():
tf_encoder = NRTREncoder()
tf_encoder.init_weights()
tf_encoder.train()
feat = torch.randn(1, 512, 1, 25)
out_enc = tf_encoder(feat)
print('hello', out_enc.size())
assert (out_enc.shape == torch.Size([1, 25, 512])) |
def get_maybe_sharded_checkpoint_filename(filename: str, suffix: str, shard_idx: int, num_shards: int) -> str:
orig_filename = filename
filename = filename.replace('.pt', (suffix + '.pt'))
fsdp_filename = (filename[:(- 3)] + f'-shard{shard_idx}.pt')
model_parallel_filename = (orig_filename[:(- 3)] + f'_... |
def main():
top_widgets = []
for i in range(num_top):
top_widgets.append(ORCWidget(('HF_' + str(i)), [top_button_width_min, top_button_width_pref, top_button_width_max, top_button_height_min, top_button_height_pref, top_button_height_max]))
column = ORCColumn('column', None, window_width, window_hei... |
def resnet152_eca(k_size=[5, 5, 5, 7]):
print('Constructing resnet152_eca......')
model = ResNet(Bottleneck, [3, 8, 36, 3], ECA=k_size)
return model |
class DescriptorCollection(list):
def val_to_description(self, val):
d = self[0]
for d in self:
if d.contains_value(val):
break
return d.adj
def sample(self):
return random.choice(self).sample() |
def _create_input_ids_from_token_ids(token_ids_a, token_ids_b, tokenizer, max_seq_length):
pair = (len(token_ids_b) != 0)
num_special_tokens_to_add = tokenizer.num_special_tokens_to_add(pair=pair)
while ((len(token_ids_a) + len(token_ids_b)) > (max_seq_length - num_special_tokens_to_add)):
if (len(t... |
def crps_minimum(yHat_2d, y_2d):
avg = []
for (i, (yHat_val, y_2d_val)) in enumerate(zip(yHat_2d.flatten(), y_2d.flatten())):
optimal_tau_pll = ((yHat_val - y_2d_val) ** (- 2.0))
result = optimize.minimize(crps_minimization, np.sqrt((1.0 / optimal_tau_pll)), method='L-BFGS-B', args=(y_2d_val, yH... |
def test_runningmeanstd():
import subprocess
subprocess.check_call(['mpirun', '-np', '3', 'python', '-c', 'from baselines.common.mpi_moments import _helper_runningmeanstd; _helper_runningmeanstd()']) |
class ViTMSNConfig(PretrainedConfig):
model_type = 'vit_msn'
def __init__(self, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, initializer_range=0.02, layer_norm_eps=1e-06, image_size=224, patch... |
def test_nonref_iterators():
pairs = m.IntPairs([(1, 2), (3, 4), (0, 5)])
assert (list(pairs.nonref()) == [(1, 2), (3, 4), (0, 5)])
assert (list(pairs.nonref_keys()) == [1, 3, 0])
assert (list(pairs.nonref_values()) == [2, 4, 5]) |
def load_dobldobl_system():
from phcpy.phcpy2c3 import py2c_syscon_number_of_dobldobl_polynomials
from phcpy.phcpy2c3 import py2c_syscon_load_dobldobl_polynomial
dim = py2c_syscon_number_of_dobldobl_polynomials()
result = []
for ind in range(1, (dim + 1)):
result.append(py2c_syscon_load_dobl... |
def header(text, color=0.4, hpad=20, vpad=15):
if isinstance(vpad, (float, int)):
vpad = [vpad, vpad]
if isinstance(hpad, (float, int)):
hpad = [hpad, hpad]
line_height = imgui.core.get_text_line_height()
if isinstance(color, (float, int)):
color = [color, color, color, 1]
im... |
def main():
parser = argparse.ArgumentParser(description='Singing separation Trainer')
parser.add_argument('--use_wandb', type=str2bool, default=False)
parser.add_argument('--entity', type=str, default='your_entity_id')
parser.add_argument('--project', type=str, default='your_project_name')
parser.a... |
class DistilBertTokenizationTest(BertTokenizationTest):
tokenizer_class = DistilBertTokenizer
def get_tokenizer(self, **kwargs):
return DistilBertTokenizer.from_pretrained(self.tmpdirname, **kwargs)
def test_sequence_builders(self):
tokenizer = DistilBertTokenizer.from_pretrained('distilbert... |
def BatchNormClassifier(inputs, labels, scope=None, reuse=None):
with tf.variable_scope(scope, 'BatchNormClassifier', [inputs, labels], reuse=reuse):
inputs = slim.batch_norm(inputs, decay=0.1)
predictions = slim.fully_connected(inputs, 1, activation_fn=tf.sigmoid, scope='fully_connected')
s... |
_model
def resnetblur50(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
default_cfg = default_cfgs['resnetblur50']
model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, aa_layer=BlurPool2d, **kwargs)
model.default_cfg = default_cfg
if pretrained:
load_pr... |
def sortTable(gtruth, pred, scrres, truthlist):
a = list(range(number))
total = list(zip(gtruth, pred, scrres, truthlist))
total = sorted(total, key=(lambda x: x[3]), reverse=True)
srt = sorted(total, key=(lambda x: x[2]), reverse=True)
srt = [(a[i], srt[i][0], srt[i][1], srt[i][2], srt[i][3]) for i... |
class Fourrooms():
def __init__(self):
layout = 'wwwwwwwwwwwww\nw w w\nw w w\nw w\nw w w\nw w w\nww wwww w\nw www www\nw w w\nw w w\nw w\nw w w\nwwwwwwwwwwwww\n'
self.occupancy = np.array([list(map((lambda c: (1 if (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.