code stringlengths 101 5.91M |
|---|
class DoubleConv(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.double_conv = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, kernel_size=3, pa... |
class ModuleConverter():
def __init__(self, mode='fa'):
self.mode = mode
def convert(self, module, copy_weights=True, layer_config=None, output_dim=None):
layer_counts = self.count_layers(module)
self.replaced_layers_counts = defaultdict((lambda : 0))
self._replace_layers_recursi... |
def _word_to_index(word, indd):
if (word in indd):
return indd[word]
else:
return len(indd) |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes):
self.inplanes = 128
super(ResNet, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=False)
self.conv2 = conv3x3(64, 64)
self.b... |
class SparseDense(ZooKerasLayer):
def __init__(self, output_dim, init='glorot_uniform', activation=None, W_regularizer=None, b_regularizer=None, backward_start=(- 1), backward_length=(- 1), init_weight=None, init_bias=None, init_grad_weight=None, init_grad_bias=None, bias=True, input_shape=None, **kwargs):
... |
.parametrize('loader_parameters', [{'path_data': [str(Path(__data_testing_dir__, 'microscopy_png'))], 'target_suffix': ['_seg-myelin-manual'], 'extensions': ['.png'], 'roi_params': {'suffix': None, 'slice_filter_roi': None}, 'contrast_params': {'contrast_lst': [], 'balance': {}}, 'slice_axis': 'axial', 'slice_filter_pa... |
def aggregate_equiv(equiv_set, input_vec, predicate_dict, aggregator):
for pair in equiv_set:
aggregator_vec = []
for pred in pair.split(','):
aggregator_vec.append(input_vec[predicate_dict[pred]])
if (aggregator is 'max'):
aggregator_value = np.max(aggregator_vec)
... |
class StickyActionEnv(gym.Wrapper):
def __init__(self, env, p=0.25):
super().__init__(env)
self.p = p
self.last_action = 0
def step(self, action):
if (np.random.uniform() < self.p):
action = self.last_action
self.last_action = action
(obs, reward, done... |
def get_assigned_file(checkpoint_dir, num):
assign_file = os.path.join(checkpoint_dir, '{:d}.tar'.format(num))
return assign_file |
_tf
class TFCoreModelTesterMixin():
model_tester = None
all_model_classes = ()
all_generative_model_classes = ()
test_mismatched_shapes = True
test_resize_embeddings = True
test_head_masking = True
is_encoder_decoder = False
def _prepare_for_class(self, inputs_dict, model_class, return_l... |
_register
class PrunerV2():
def __init__(self, target_sparsity=None, pruning_type=None, pattern=None, op_names=None, excluded_op_names=None, start_step=None, end_step=None, pruning_scope=None, pruning_frequency=None, min_sparsity_ratio_per_op=None, max_sparsity_ratio_per_op=None, sparsity_decay_type=None, pruning_o... |
def prepro_each(args, data_type, start_ratio=0.0, stop_ratio=1.0, out_name='default', in_path=None):
if (args.tokenizer == 'PTB'):
import nltk
sent_tokenize = nltk.sent_tokenize
def word_tokenize(tokens):
return [token.replace("''", '"').replace('``', '"') for token in nltk.word_... |
_module()
class AutoAugment(object):
def __init__(self, policies):
assert (isinstance(policies, list) and (len(policies) > 0)), 'Policies must be a non-empty list.'
for policy in policies:
assert (isinstance(policy, list) and (len(policy) > 0)), 'Each policy in policies must be a non-emp... |
def evaluate():
global DATABASE_VECTORS
global QUERY_VECTORS
global array
with tf.Graph().as_default():
with tf.device(('/gpu:' + str(GPU_INDEX))):
print('In Graph')
query = placeholder_inputs(BATCH_NUM_QUERIES, 1, NUM_POINTS)
positives = placeholder_inputs(BA... |
def error_orders(i, month, day, td, lb_days=5, metric='normalized'):
d0 = date(2020, month, day)
mepis = []
preds = df_county[f'all_deaths_pred_{month}_{day}_ensemble_{horizon}'].values
err = []
for lb in range(lb_days):
d1 = (d0 - timedelta((lb + 1)))
d2 = (d0 - timedelta((lb + td))... |
def main_worker(gpu, ngpus_per_node, args):
global best_acc1
args.gpu = gpu
if (args.multiprocessing_distributed and (args.gpu != 0)):
def print_pass(*args):
pass
builtins.print = print_pass
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))... |
_task('translation', dataclass=TranslationConfig)
class TranslationTask(FairseqTask):
cfg: TranslationConfig
def __init__(self, cfg: TranslationConfig, src_dict, tgt_dict):
super().__init__(cfg)
self.src_dict = src_dict
self.tgt_dict = tgt_dict
def setup_task(cls, cfg: TranslationCon... |
def main(args):
data_path = Path(args.data_path)
output_path = Path(args.out_path)
os.makedirs(str(output_path), exist_ok=True)
for split in ['train', 'val']:
convert(split, data_path, output_path, args.subset_fract) |
def encode(v, **kwargs):
norm = torch.norm(v)
w = v.view((- 1))
t = [time.time()]
signs = torch.sign(w).int()
probs = (torch.abs(w) / norm)
mask = torch.distributions.Bernoulli(probs).sample().byte()
t += [time.time()]
idx = torch.arange(0, len(w))
t += [time.time()]
if v.is_cuda... |
def create_tf_node(op, name, inputs):
from tensorflow.core.framework import node_def_pb2
new_node = node_def_pb2.NodeDef()
new_node.op = op
new_node.name = name
for input_name in inputs:
new_node.input.extend([input_name])
return new_node |
class INItPrClient(ItPrClient):
def init_optimizer(self):
self.optimizer = SGD(self.model.parameters(), lr=INIT_LR, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY)
self.optimizer_scheduler = lr_scheduler.StepLR(self.optimizer, step_size=STEP_SIZE, gamma=(0.5 ** (STEP_SIZE / LR_HALF_LIFE)))
sel... |
def get_args():
cuda_devices = [f'cuda:{i}' for i in range(torch.cuda.device_count())]
parser = argparse.ArgumentParser()
parser.add_argument('-device', type=str, choices=(['auto', 'cpu', 'cuda'] + cuda_devices), default='auto', help='Which device to use')
parser.add_argument('-cpus', type=str, default=... |
class QuaternionToReal(nn.Module):
def __init__(self, in_channels):
super(QuaternionToReal, self).__init__()
self.in_channels = in_channels
def forward(self, x, quat_format=False):
if quat_format:
norm = x.norm()
if (len(norm.shape) == 1):
out = Q(... |
def test_add_end_edge():
d1 = Exponential()
d2 = Gamma()
model = SparseHMM([d1, d2])
model.add_edge(d1, model.end, 0.2)
model.add_edge(d2, model.end, 0.3)
assert_raises(ValueError, model._initialize) |
def evaluate(data_file, model_folder, loss):
test_losses = dict()
dataset = cloud_maps(folder=data_file, input_imgs=4, output_imgs=6, train=False)
test_dl = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, num_workers=2, pin_memory=True)
model_name = 'AA_TransUNet'
model = AA_TransU... |
class BaseDRLAgent(ABC):
def __init__(self, ns: str=None, robot_name: str=None, hyperparameter_path: str=DEFAULT_HYPERPARAMETER, action_space_path: str=DEFAULT_ACTION_SPACE, *args, **kwargs) -> None:
self._is_train_mode = rospy.get_param('/train_mode')
self._ns = ('' if ((ns is None) or (ns == '')) ... |
class SpdSegment():
def __init__(self, segment_xml):
self.spkr = segment_xml.speaker.get_text()
self.start = float(segment_xml.start.get_text())
self.end = float(segment_xml.end.get_text())
self.callsign_list = []
try:
self.callsign_list = list(eval(segment_xml.ca... |
def parse_init(init_file):
with open(init_file, 'r', encoding='utf-8', newline='\n') as f:
lines = f.readlines()
line_index = 0
while ((line_index < len(lines)) and (not lines[line_index].startswith('_import_structure = {'))):
line_index += 1
if (line_index >= len(lines)):
return... |
def train(args, net, device, train_loader, optimizer, epoch, logger):
net.train()
for (batch_idx, (data, target)) in enumerate(train_loader):
start = time()
(data, target) = (data.to(device), target.to(device))
model_fn = (lambda : net(data))
loss_fn = (lambda pred: F.cross_entro... |
def one_line_log(config, cur_step, loss, batch_per_epoch, start_time, validation=False):
s_step = f'Step: {cur_step:<6}'
s_loss = (f'Loss: {loss:<6.4f}' if (not validation) else f'Val loss: {loss:<6.4f}')
s_epoch = f'Epoch: {(cur_step // batch_per_epoch):<4.0f}'
s_mvid = f'Mimg: {((cur_step * config.dat... |
def tanh_tanh2_2(x, mu, sd):
xn = ((x - mu) / sd)
tanh = torch.tanh(xn)
sech2 = (1 - (tanh ** 2))
t = tanh
jt = ((1 / sd) * sech2)
jjt = ((((1 / (sd ** 2)) * (- 2)) * tanh) * sech2)
t2 = (tanh ** 2)
jt2 = ((1 / sd) * ((2 * tanh) * sech2))
jjt2 = ((1 / (sd ** 2)) * ((2 * (sech2 ** 2))... |
class FocalLossBinary(_Loss):
def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alpha: float=0.25, threshold: float=0.5, reduction: str='mean'):
super().__init__()
self.ignore = ignore
if reduced:
self.loss_fn = partial(reduced_focal_loss, gamma=gamma, t... |
def remove_last(tensors, term_bin_weights):
new_tensors = []
for (idx, tensor, weights) in zip(count(), tensors, term_bin_weights):
if (tensor is None):
result = None
elif (weights is None):
result = tensor
else:
n_dimensions = weights.ndim
... |
def search_by_batch(model, beams, mem_dict):
def ready_to_submit(hypotheses):
inp = model.prepare_incremental_input([hyp.seq[(- 1):] for hyp in hypotheses]).cuda()
concat_hyps = dict()
for hyp in hypotheses:
for (k, v) in hyp.state_dict.items():
concat_hyps[k] = (... |
class Flatten(nn.Module):
def forward(self, input):
if (input.dim() > 1):
input = input.view(input.size(0), (- 1))
return input |
def yaw_diff(gt_box: EvalBox, eval_box: EvalBox, period: float=(2 * np.pi)) -> float:
yaw_gt = quaternion_yaw(Quaternion(gt_box.rotation))
yaw_est = quaternion_yaw(Quaternion(eval_box.rotation))
return abs(angle_diff(yaw_gt, yaw_est, period)) |
def build_model1(X_train, y_train, X_valid, y_valid, max_len, max_features, embed_size, embedding_matrix, lr=0.0, lr_d=0.0, spatial_dr=0.0, dense_units=128, conv_size=128, dr=0.2, patience=3, fold_id=1):
file_path = f'best_model_fold_{fold_id}.hdf5'
check_point = ModelCheckpoint(file_path, monitor='val_loss', v... |
def get_synset(t):
from nltk.corpus import wordnet as wn
if (t.endswith('_outdoor') or t.endswith('_indoor')):
t = '_'.join(t.split('_')[:(- 1)])
ss = wn.synsets(t, pos=wn.NOUN)
if ss:
return ss[0]
while ('_' in t):
t = '_'.join(t.split('_'))[:(- 1)]
ss = wn.synsets(t... |
def make_dir(_dir: str) -> None:
if (not exists(_dir)):
try:
os.makedirs(_dir, exist_ok=True)
except FileExistsError:
pass |
def gtzan_path2gt(file_path):
tag = file_path[(file_path.rfind('/') + 1):file_path.rfind('.', 0, (- 4))]
print(tag)
if (tag == 'blues'):
return 0
elif (tag == 'classical'):
return 1
elif (tag == 'country'):
return 2
elif (tag == 'disco'):
return 3
elif (tag ==... |
class UNet(nn.Module):
def __init__(self, in_channels=3, w=4, n_classes=2):
super(UNet, self).__init__()
self.inc = inconv(in_channels, int((16 * w)))
self.down1 = down(int((16 * w)), int((32 * w)))
self.down2 = down(int((32 * w)), int((64 * w)))
self.down3 = down(int((64 * w... |
def _build_corpus(data_path, env_params, sort_dict):
if sort_dict:
corpus_path = os.path.join(data_path, 'corpus_sorted.pt')
else:
corpus_path = os.path.join(data_path, 'corpus.pt')
if os.path.exists(corpus_path):
print('Loading an existing corpus file from {}'.format(corpus_path))
... |
class ImageNet(ImageList):
def __init__(self, root, list_file, memcached, mclient_path):
super(ImageNet, self).__init__(root, list_file, memcached, mclient_path) |
def Sharpness(img, v):
assert (0.1 <= v <= 1.9)
return PIL.ImageEnhance.Sharpness(img).enhance(v) |
_torch
class DataCollatorIntegrationTest(unittest.TestCase):
def setUp(self):
self.tmpdirname = tempfile.mkdtemp()
vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]']
self.vocab_file = os.path.join(self.tmpdirname, 'vocab.txt')
with open(self.vocab_file, 'w', encoding='utf-... |
def test_pr3635_diamond_d0():
o = m.MVD0()
assert (o.b == 1)
assert (o.c == 2)
assert (o.d0 == 3)
assert (o.get_b_b() == 1)
assert (o.get_c_b() == 1)
assert (o.get_d0_b() == 1)
assert (o.get_c_c() == 2)
assert (o.get_d0_c() == 2)
assert (o.get_d0_d0() == 3) |
class TestOptimizersGPU(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
def tearDown(self):
logging.disable(logging.NOTSET)
((not torch.cuda.is_available()), 'test requires a GPU')
def test_flat_grads(self):
with contextlib.redirect_stdout(StringIO()):
... |
def clear_monitor_files(training_dir):
files = detect_monitor_files(training_dir)
if (len(files) == 0):
return
logger.info('Clearing %d monitor files from previous run (because force=True was provided)', len(files))
for file in files:
os.unlink(file) |
def test_modal_analysis_init():
sample_rate = 48000
x = modal_analysis.CQTModalAnalysis(sample_rate)
assert (x.sample_rate == sample_rate) |
class DatasetFactory(object):
def create_dataset(**kwargs):
assert ('name' in kwargs), 'should provide dataset name'
name = kwargs['name']
if ('OTB' in name):
dataset = OTBDataset(**kwargs)
elif ('LaSOT' == name):
dataset = LaSOTDataset(**kwargs)
elif ... |
class PTBReader(BaseTextReader):
def read_line(self, line):
nltk_tree = nltk.Tree.fromstring(line.strip())
s = nltk_tree.leaves()
if self.lowercase:
s = [w.lower() for w in s]
(yield s) |
class PartitionRandomSampler(Sampler):
def __init__(self, partition_start_end_indices):
self.partition_start_end_indices = partition_start_end_indices
partition_end_indices = [end_idx for (_, end_idx) in self.partition_start_end_indices]
self.num_indices = (max(partition_end_indices) + 1)
... |
def plot_alignment(alignment, gs):
(fig, ax) = plt.subplots()
im = ax.imshow(alignment)
fig.colorbar(im)
plt.title('{} Steps'.format(gs))
plt.savefig('{}/alignment_{}k.png'.format(hp.logdir, (gs // 1000)), format='png') |
def remove_seed_setting(code: str) -> str:
return re.sub('torch\\.manual_seed\\(\\S+\\)', '', code) |
def create_ssd_anchors(num_layers=6, min_scale=0.2, max_scale=0.95, aspect_ratios=(1.0, 2.0, 3.0, (1.0 / 2), (1.0 / 3)), base_anchor_size=None, reduce_boxes_in_lowest_layer=True):
if (base_anchor_size is None):
base_anchor_size = [1.0, 1.0]
base_anchor_size = tf.constant(base_anchor_size, dtype=tf.float... |
class MaxPool3d(nn.MaxPool3d):
def forward(self, x):
if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 7))):
out_shape = list(x.shape[:2])
for (i, k, p, s, d) in zip(x.shape[(- 3):], _triple(self.kernel_size), _triple(self.padding), _triple(self.stride), _triple(self... |
_module()
class CustomDataset(Dataset):
CLASSES = None
PALETTE = None
def __init__(self, ann_file, pipeline, classes=None, data_root=None, img_prefix='', seg_prefix=None, seg_suffix='.png', proposal_file=None, test_mode=False, filter_empty_gt=True, file_client_args=dict(backend='disk')):
self.ann_fi... |
def get_spans_and_siblings(tree):
def helper(tr, idx=0, name='root'):
if isinstance(tr, (str, int)):
return (1, [(idx, (idx + 1))], [])
(l_size, l_spans, l_sibs) = helper(tr[0], name='l', idx=idx)
(r_size, r_spans, r_sibs) = helper(tr[1], name='r', idx=(idx + l_size))
siz... |
class ConfGenerator(nn.Module):
def __init__(self, theta):
super(ConfGenerator, self).__init__()
if (not isinstance(theta, (int, float))):
raise TypeError('(int,float) is expected, got {}'.format(type(theta)))
self.theta = theta
def forward(self, estDisp, gtDisp):
if ... |
def array_from_nested_dictionary(nested_dict, array_fn, dtype='float32', square_result=False):
if square_result:
outer_key_indices = inner_key_indices = flattened_nested_key_indices(nested_dict)
else:
(outer_key_indices, inner_key_indices) = nested_key_indices(nested_dict)
n_rows = len(outer... |
def _create_wr_extended_audio(filename, port, mixer_mode, loopback_gain, microphone_gain, profile, level, user):
w = _writer()
w.open(filename)
w.put(_create_header(port, user))
w.put(hl2ss._create_configuration_for_extended_audio(mixer_mode, loopback_gain, microphone_gain, profile, level))
return w |
class LabelClusterUtils():
def __init__(self, dataset):
self._dataset = dataset
self.cluster_split = dataset.cluster_split
self.data_dir = (avod.root_dir() + '/data/label_clusters')
self.clusters = []
self.std_devs = []
def _filter_labels_by_class(obj_labels, classes):
... |
def setup_tictacteo(variation=None):
env = TicTacTeo()
if variation:
env = env.vary(variation)
maintemp = [RuleTemplate(1, True)]
inventedtemp2 = [RuleTemplate(1, True)]
inventedtemp_2extential = [RuleTemplate(2, False)]
invented = Predicate('invented', 2)
invented2 = Predicate('inve... |
class MSVD_Feats_DataLoader(Dataset):
def __init__(self, data_path, features_path, tokenizer, max_words=30, feature_framerate=1.0, max_frames=100, split_type=''):
self.data_path = data_path
self.features_path = features_path
self.feature_dict = pickle.load(open(features_path, 'rb'))
... |
def filecopy(src_path: Union[(Path, str)], dst_path: Union[(Path, str)]) -> None:
src_path = verify_path(src_path)
dst_path = verify_path(dst_path)
log.debug(f'Copying over file from {src_path} to {dst_path}')
shutil.copy(src_path, dst_path) |
def preprocess_data_t5(args):
data = preprocess_data(args)
if (args['ID_name'] == 'sst2'):
def add_prefix_sst2(example):
example['sentence'] = ('sst2 sentence: ' + example['sentence'])
return example
data = data.map(add_prefix_sst2)
elif (args['ID_name'] == 'cola'):
... |
class ELUParameter(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _ELUPARAMETER |
class RevResBottleneck(nn.Module):
def __init__(self, in_channels, out_channels, stride, preactivate, bottleneck_factor=4):
super(RevResBottleneck, self).__init__()
mid_channels = (out_channels // bottleneck_factor)
if preactivate:
self.conv1 = pre_conv1x1_block(in_channels=in_ch... |
class Upsample_unit(nn.Module):
def __init__(self, ind, num_units, in_channels, unit_channels=256, gen_skip=False, gen_cross_conv=False, norm_cfg=dict(type='BN'), out_channels=64):
norm_cfg = cp.deepcopy(norm_cfg)
super().__init__()
self.num_units = num_units
self.norm_cfg = norm_cfg... |
class SelfAttn(MultiHeadAttn):
def __init__(self, dim_in, dim_out, num_heads=8):
super().__init__(dim_in, dim_in, dim_in, dim_out, num_heads)
def forward(self, x, mask=None):
return super().forward(x, x, x, mask=mask) |
def main():
args = parse_args()
in_video = os.path.expanduser(args.in_video)
if (not os.path.exists(in_video)):
raise Exception("Input file/directory doesn't exist: {}".format(in_video))
if os.path.isfile(in_video):
extract_audio(in_video=in_video, out_audio=args.out_audio)
else:
... |
def read_pcd():
files = glob.glob('/home/wang/github/RoBoCar/ROS/pcd/*.pcd')
file_path = []
for file in files:
ts = file.split('/')[7][:(- 4)]
file_path.append(ts)
file_path.sort()
return file_path |
def one_hot(index, classes):
out_idx = torch.arange(classes, device=index.device)
out_idx = torch.unsqueeze(out_idx, 0)
index = torch.unsqueeze(index, (- 1))
return (index == out_idx).float() |
class NeuriR(ConcolicGen):
def __init__(self, opset, record_finder: OpRecordFinder, seed=None, init_fp=False, **kwargs):
BaseGen.__init__(self, opset, seed, **kwargs)
if (seed is not None):
set_z3_state(seed)
self.record_finder = record_finder
self.forward_insert_node(sel... |
def dims_to_shapes(input_dims):
return {key: (tuple([val]) if (val > 0) else tuple()) for (key, val) in input_dims.items()} |
class SmallReactivePolicy():
def __init__(self, observation_space, action_space):
assert (weights_dense1_w.shape == (observation_space.shape[0], 128))
assert (weights_dense2_w.shape == (128, 64))
assert (weights_final_w.shape == (64, action_space.shape[0]))
def act(self, ob):
x =... |
def bpda_strong(x, y, network_ebm, network_clf, config):
transform_raw_to_clf = raw_to_clf(config.structure.dataset)
fmodel = foolbox.PyTorchModel(network_clf, bounds=(0.0, 1.0), preprocessing=foolbox_preprocess(config.structure.dataset))
x = x.to(config.device.ebm_device)
y = y.to(config.device.clf_dev... |
class InputExample():
def __init__(self, paragraph, qa_list, label):
self.paragraph = paragraph
self.qa_list = qa_list
self.label = label |
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, bn_aff=True, shortcut=True, dropRate=0.0):
super(BasicBlock, self).__init__()
self.shortcut = shortcut
self.bn_aff = bn_aff
self.bn1 = nn.BatchNorm2d(in_planes, affine=self.bn_aff)
self.relu1 = nn.... |
class ScoredBoundingBoxVisualizer(object):
def __init__(self, bbox_visualizer_params=None, score_visualizer_params=None, **kwargs):
if (bbox_visualizer_params is None):
bbox_visualizer_params = {}
if (score_visualizer_params is None):
score_visualizer_params = {}
self... |
def accuracy(output, target, topk=(1,)):
(output, target) = (to_torch(output), to_torch(target))
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))
ret = []
for k in topk:
... |
def check_early_stop(trainer, epochs):
end_epoch = trainer.updater.get_iterator('main').epoch
if (end_epoch < (epochs - 1)):
logging.warning((('Hit early stop at epoch ' + str(end_epoch)) + '\nYou can change the patience or set it to 0 to run all epochs')) |
class TestCommutativeCancellation(QiskitTestCase):
def setUp(self):
self.com_pass_ = CommutationAnalysis()
self.pass_ = CommutativeCancellation()
self.pset = self.pass_.property_set = PropertySet()
def test_all_gates(self):
qr = QuantumRegister(2, 'q')
circuit = QuantumCi... |
class MetaIterativeEnvExecutor(object):
def __init__(self, env, meta_batch_size, envs_per_task, max_path_length):
self.envs = np.asarray([copy.deepcopy(env) for _ in range((meta_batch_size * envs_per_task))])
self.ts = np.zeros(len(self.envs), dtype='int')
self.max_path_length = max_path_len... |
def url_to_filename(url, etag=None):
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdigest()
if etag:
etag_bytes = etag.encode('utf-8')
etag_hash = sha256(etag_bytes)
filename += ('.' + etag_hash.hexdigest())
if url.endswith('.h5'):
... |
class ModelCriterionConfig(FairseqDataclass):
loss_weights: Dict[(str, float)] = field(default_factory=dict, metadata={'help': 'weights for the loss terms'})
log_keys: List[str] = field(default_factory=list, metadata={'help': 'additional output keys to log'})
can_sum: bool = True |
.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_forward_equal_with_pytorch_float():
(N, M, D) = (1, 2, 2)
(Lq, L, P) = (2, 2, 2)
shapes = torch.as_tensor([(6, 4), (3, 2)], dtype=torch.long).cuda()
level_start_index = torch.cat((shapes.new_zeros((1,)), shapes.prod(1).cum... |
def ResNet101(nInputChannels=3, os=16, pretrained=False):
model = ResNet(nInputChannels, Bottleneck, [3, 4, 23, 3], os, pretrained=pretrained)
return model |
def get_layers(layer_type):
if (layer_type == 'dense'):
return (nn.Conv2d, nn.Linear)
elif (layer_type == 'subnet'):
return (SubnetConv, SubnetLinear)
else:
raise ValueError('Incorrect layer type') |
def deconv3d(input_, output_shape, k_t=3, k_h=3, k_w=3, d_t=1, d_h=1, d_w=1, padding='SAME', name='deconv3d'):
with tf.variable_scope(name):
w = _variable_with_weight_decay('w', [k_t, k_h, k_h, output_shape[(- 1)], input_.get_shape()[(- 1)]])
deconv = tf.nn.conv3d_transpose(input_, w, output_shape=o... |
class TestFineTuneEpocher(TestCase):
def setUp(self) -> None:
global arch_dict
arch_dict = deepcopy(arch_dict)
super().setUp()
pretrain_datsaet = ACDCDataset(root_dir=DATA_PATH, mode='train', transforms=transform)
self._pretrain_loader = iter(DataLoader(pretrain_datsaet))
... |
def create_decoder(opt):
if (opt.decoder_type == 'AttnDecoderRNN'):
decoder = AttnDecoderRNN(opt.rnn_type, opt.atten_model, opt.embedding_size, opt.hidden_size, opt.num_layers, opt.dropout)
return decoder |
def merge_ans(src, ans):
rst = [(((s + [Constants.SEP_WORD]) + a) + [Constants.SEP_WORD]) for (s, a) in zip(src, ans)]
return rst |
def create_background_tasks():
background_tasks = BackgroundTasks()
background_tasks.add_task(release_model_semaphore)
return background_tasks |
class ViTGraph(nn.Module):
def __init__(self, in_chans=6, num_classes=40, encoder_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=False, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, embed_args={'NAME': 'groupembed', 'num_groups': 256, 'group_size': 32, 'embed_dim': 256, 'subsample': 'fps', 'group... |
def resize_images(scale, verbose=False):
img_dir = './src/hu2013/Data/Lady'
output_dir = './src/hu2013/Data'
names = ['Img1.jpg', 'Img2.jpg', 'Img3.jpg']
for name in names:
img = cv2.imread(os.path.join(img_dir, name))
(height, width, _) = img.shape
img_resize = cv2.resize(img, (... |
def restrict(x):
g = GraphInterface()
vs = g.add_vertex('p', is_input=True)
vout = g.add_vertex('restrict')
vx = g.add_vertex(x, is_output=True)
vp = g.add_vertex('p', is_output=True)
g.add_edge(vs, vout)
g.add_edge(vout, vp)
g.add_edge(vout, vx)
return g |
_registry(operator_type='Flatten')
class Flatten(Operator):
def __init__(self):
super().__init__() |
def max_abs_sum_seg(scores_list, min_length: int=1):
n = len(scores_list[0])
res = ([0] * n)
paths = {}
for s in range(n):
for e in range(s, n):
if ((e - s) >= (min_length - 1)):
scores_list[s][e] = abs(scores_list[s][e])
else:
scores_list[... |
def adjust_and_move_row_and_column_borders(annotations):
row_anns = dict()
col_anns = dict()
for ann in annotations:
if (ann['category'] == 'table_row'):
row_anns[ann['row_nr']] = ann
elif (ann['category'] == 'table_col'):
col_anns[ann['col_nr']] = ann
col_nrs = s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.