code stringlengths 101 5.91M |
|---|
def qrandint(lower: int, upper: int, q: int=1) -> 'tune.sample.Integer':
return tune.qrandint(lower, upper, q) |
class DAIN(nn.Module):
def __init__(self, nclass, model1, model2):
super(DAIN, self).__init__()
self.model1 = model1
self.model2 = model2
self.fc = nn.Linear((512 * 2), nclass)
def forward(self, img, diff_img):
img_f = self.model1.conv1(img)
img_f = self.model1.bn... |
(eq=False)
class DeFeatNet(BaseModel):
num_layers: int
preres: bool
scales: list = range(4)
use_skips: bool = True
n_dims: int = 3
spp_branches: list = None
activation: str = 'relu'
im_pad: int = None
norm: bool = True
def __post_init__(self):
super().__post_init__()
... |
def ReadFileSL(x_axis, tthread, batchInterval, NUM_ITEMS, deposit_ratio, key_skewness, overlap_ratio, abort_ratio, isCyclic, complexity):
(w, h) = (2, len(x_axis))
y = [[] for _ in range(w)]
for NUM_ITEMS in x_axis:
inputEvents = (tthread * batchInterval)
op_gs_path = getPathSL('OPGSA', inpu... |
.parametrize('in_features, out_features, C, a, b, bias, batch_size, use_prototypes', [(in_features, out_features, C, a, b, bias, batch_size, use_prototypes) for in_features in [512] for out_features in [32, 128] for C in [4, 16] for a in [1.0] for b in [0.0] for bias in [True, False] for batch_size in [1, 8] for use_pr... |
def tiny_oshi_zumo_nfsp_dqn_params(env: MultiAgentEnv) -> Dict[(str, Any)]:
return merge_dicts(GRL_DEFAULT_OSHI_ZUMO_TINY_DQN_PARAMS, {'exploration_config': {'epsilon_timesteps': int(.0), 'final_epsilon': 0.001, 'initial_epsilon': 0.06, 'type': ValidActionsEpsilonGreedy}, 'model': merge_dicts(MODEL_DEFAULTS, {'fcne... |
def input_fn_builder(features, seq_length, drop_remainder):
all_unique_ids = []
all_input_ids = []
all_input_mask = []
all_segment_ids = []
all_start_positions = []
all_end_positions = []
for feature in features:
all_unique_ids.append(feature.unique_id)
all_input_ids.append(f... |
def pairwise_operator(codes, method):
pairs = []
for (i, coderi) in enumerate(codes):
for (j, coderj) in enumerate(codes):
if (j > i):
pairs.append(method(coderi, coderj))
return np.mean(pairs) |
def _header_paths():
return ['', 'include', 'include/cuda', 'include/*-linux-gnu', 'extras/CUPTI/include', 'include/cuda/CUPTI', 'local/cuda/extras/CUPTI/include'] |
class TorchvisionNormalize():
def __init__(self, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
self.mean = mean
self.std = std
def __call__(self, img):
imgarr = np.asarray(img)
proc_img = np.empty_like(imgarr, np.float32)
proc_img[(..., 0)] = (((imgarr[(..., 0)]... |
_model
def eca_nfnet_l1(pretrained=False, **kwargs):
return _create_normfreenet('eca_nfnet_l1', pretrained=pretrained, **kwargs) |
def forward_wrapper(model, input, device='cpu'):
if (isinstance(input, dict) or isinstance(input, UserDict)):
if (device == 'cpu'):
output = model(**input)
else:
for inp in input.keys():
input[inp] = (input[inp].to(device) if isinstance(input[inp], torch.Tenso... |
def test_neither_x0_nor_initial_solutions_provided(archive_fixture):
(archive, _) = archive_fixture
with pytest.raises(ValueError):
GaussianEmitter(archive, sigma=1.0) |
def get_doc_cell(func_name):
code = f'show_doc({func_name})'
return get_code_cell(code, True) |
def QImage_from_np(img):
if (img.dtype != np.uint8):
raise ValueError('img should be in np.uint8 format')
(h, w, c) = img.shape
if (c == 1):
fmt = QImage.Format_Grayscale8
elif (c == 3):
fmt = QImage.Format_BGR888
elif (c == 4):
fmt = QImage.Format_ARGB32
else:
... |
class TFLongformerSelfAttention():
def __init__(self, *args, **kwargs):
requires_tf(self) |
def get_logger(root, name=None, debug=True):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s: %(message)s', '%Y-%m-%d %H:%M')
console_handler = logging.StreamHandler()
if debug:
console_handler.setLevel(logging.DEBUG)
else:
... |
def cook_test(test, refparam, eff=None, n=4):
(reflen, refmaxcounts) = (refparam[0], refparam[1])
(testlen, counts) = precook(test, n, True)
result = {}
if (eff == 'closest'):
result['reflen'] = min(((abs((l - testlen)), l) for l in reflen))[1]
else:
result['reflen'] = reflen
res... |
class AntFileSystem(object):
def __init__(self, uri):
raise NotImplementedError
def exists(self, filename):
raise NotImplementedError
def remove(self, filename):
raise NotImplementedError
def stat(self, filename):
raise NotImplementedError
def list_dir(self, dirname):... |
class ResUNetIN101(ResUNet101):
NORM_TYPE = NormType.SPARSE_INSTANCE_NORM
BLOCK = BottleneckIN |
class ResidualConvUnit_custom(nn.Module):
def __init__(self, features, activation, bn):
super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
self.conv2 = nn.Conv2d(feature... |
def modify_space_hw(space, h, w):
if (isinstance(space, gym.spaces.Box) and is_image_space(space)):
shape = list(space.shape)
shape[(- 2)] = h
shape[(- 1)] = w
return gym.spaces.Box(low=0, high=255, shape=shape, dtype=np.uint8)
elif isinstance(space, gym.spaces.Dict):
ret... |
def test(in_dataset, out_dataset, wide, epsilon, temperature):
testsetout = torchvision.datasets.ImageFolder(os.path.expanduser('./data/{}'.format(out_dataset)), transform=transform)
testloaderOut = torch.utils.data.DataLoader(testsetout, batch_size=100, shuffle=False, num_workers=2)
if (in_dataset == 'cifa... |
class BBoxCrop(object):
def __init__(self, padding=0):
if (type(padding) != int):
raise TypeError('padding should be int')
self.padding = padding
def __call__(self, img, bbox):
if (not ((isinstance(bbox, (list, tuple, np.ndarray)) and len(bbox)) == 4)):
raise Type... |
class TFMarianPreTrainedModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class BaseSampler(object):
def __init__(self, max_path_length, min_pool_size, batch_size, store_last_n_paths=10):
self._max_path_length = max_path_length
self._min_pool_size = min_pool_size
self._batch_size = batch_size
self._store_last_n_paths = store_last_n_paths
self._last... |
def eval_argparser():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--dataset_path', type=str, help='Path to dataset')
_add_common_args(arg_parser)
return arg_parser |
def test1():
graph = {('A', 'B'): 3, ('A', 'C'): 3, ('A', 'F'): 5, ('C', 'B'): (- 2), ('C', 'D'): 7, ('C', 'E'): 4, ('D', 'E'): (- 5), ('E', 'F'): (- 1)}
result = shortest_paths('A', graph)
expected = {'A': 0, 'C': 3, 'B': 1, 'E': 5, 'D': 10, 'F': 4}
assert (result == expected) |
class GenericDataloader(DataLoader):
def __init__(self, dataset: Dataset, config: Namespace, shuffle: bool=True, drop_last: bool=False):
super().__init__(dataset, batch_size=config.batch_size, shuffle=shuffle, pin_memory=False, num_workers=config.num_workers, drop_last=False) |
def get_gan_criterion(mode):
if (mode == 'dcgan'):
criterion = GANLoss(dis_loss=nn.BCEWithLogitsLoss(), gen_loss=nn.BCEWithLogitsLoss())
elif (mode == 'lsgan'):
criterion = GANLoss(dis_loss=nn.MSELoss(), gen_loss=nn.MSELoss())
elif (mode == 'hinge'):
def hinge_dis(pre, margin):
... |
def load_reactant_vocab(path_to_json: str) -> typing.List[str]:
with open(path_to_json, 'r') as fo:
d = json.load(fo)
return sorted(list(d.keys()), key=(lambda x: d[x])) |
def clean(embedding_path: str, output_path: str=None, block_size: int=665536):
with open(embedding_path, 'r', encoding='utf8', errors='ignore') as input_file:
with open(output_path, 'w+', encoding='utf8') as output_file:
lines: List[str] = input_file.readlines(block_size)
while lines... |
class PruningMode(Enum):
BASICMAGNITUDE = 'basic_magnitude'
PATTERNLOCK = 'pattern_lock'
GROUPLASSO = 'group_lasso' |
def compare(string1, string2):
if compare_cell(string1[:(len(string1) // 2)], string2[:(len(string2) // 2)]):
if compare_cell(string1[(len(string1) // 2):], string2[(len(string2) // 2):]):
return True
return False |
class TestFilterLearnableParmams(unittest.TestCase):
def test_filter_learnable_params(self) -> None:
boring_model = BoringModel()
large_boring_model = LargeBoringModel()
boring_model_params = list(boring_model.parameters())
filtered_boring_model_params = filter_learnable_params(borin... |
def test_reallocation_f(capture, msg):
with capture:
create_and_destroy(4, 0.5)
assert (msg(capture) == strip_comments('\n noisy new # preallocation needed before invoking placement-new overload\n noisy delete # deallocation of preallocated storage\n noisy new ... |
class RobertaModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class Rescal(BaseModel):
def __init__(self, entity_dict_len, relation_dict_len, embedding_dim, penalty_weight=0.0):
super().__init__(model_name='Rescal', penalty_weight=penalty_weight)
self.entity_dict_len = entity_dict_len
self.relation_dict_len = relation_dict_len
self.embedding_di... |
class DatasetMapper():
def __init__(self, is_train: bool, *, augmentations: List[Union[(T.Augmentation, T.Transform)]], image_format: str, use_instance_mask: bool=False, use_keypoint: bool=False, instance_mask_format: str='polygon', keypoint_hflip_indices: Optional[np.ndarray]=None, precomputed_proposal_topk: Optio... |
class ResamplingDataset(BaseWrapperDataset):
def __init__(self, dataset, weights=None, replace=True, size_ratio=1.0, batch_by_size=True, seed=0, epoch=1):
super().__init__(dataset)
if (weights is None):
self.weights = None
else:
assert (len(weights) == len(dataset))
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data-path', type=str, default='./data')
parser.add_argument('--output-path', type=str, default='./outputs')
parser.add_argument('--output-name', type=str, default='adv_bpda.npy')
parser.add_argument('--defense', type=str, default=... |
def aspect_ratio_rel(im, aspect_ratio):
(im_h, im_w) = im.shape[:2]
im_ar_w = int(round((aspect_ratio * im_w)))
im_ar = cv2.resize(im, dsize=(im_ar_w, im_h))
return im_ar |
def main(args):
dbsn_net = DBSN_Model(in_ch=args.input_channel, out_ch=args.output_channel, mid_ch=args.middle_channel, blindspot_conv_type=args.blindspot_conv_type, blindspot_conv_bias=args.blindspot_conv_bias, br1_block_num=args.br1_block_num, br1_blindspot_conv_ks=args.br1_blindspot_conv_ks, br2_block_num=args.b... |
class FlipGradientBuilder(object):
def __init__(self):
self.num_calls = 0
def __call__(self, x, l=1.0):
grad_name = ('FlipGradient%d' % self.num_calls)
(grad_name)
def _flip_gradients(op, grad):
return [(tf.negative(grad) * l)]
g = tf.get_default_graph()
... |
class PadToMultiple(object):
def __init__(self, multiple, fill=0, padding_mode='constant'):
assert isinstance(multiple, numbers.Number)
assert isinstance(fill, (numbers.Number, str, tuple))
assert (padding_mode in ['constant', 'edge', 'reflect', 'symmetric'])
self.multiple = multiple... |
_register_to_config
class FlaxAutoencoderKL(nn.Module, FlaxModelMixin, ConfigMixin):
in_channels: int = 3
out_channels: int = 3
down_block_types: Tuple[str] = ('DownEncoderBlock2D',)
up_block_types: Tuple[str] = ('UpDecoderBlock2D',)
block_out_channels: Tuple[int] = (64,)
layers_per_block: int =... |
def get_config_group(dataset):
for (group, group_data) in CONFIG_GROUPS.items():
if (dataset in group_data['datasets']):
return group
assert False, f"Dataset `{dataset}' not found" |
class S2VGraph(object):
def __init__(self, g, label, node_tags=None, node_features=None):
self.label = label
self.g = g
self.node_tags = node_tags
self.neighbors = []
self.node_features = 0
self.max_neighbor = 0
self.mean_neighbor = 0 |
def writeMain(output):
if (not (options.gui or options.runner)):
return
output.write(('int %s( int argc, char *argv[] ) {\n' % options.main))
output.write(' int status;\n')
if options.noStaticInit:
output.write(' CxxTest::initialize();\n')
if options.gui:
tester_t = ('CxxTest... |
class DdpCheckpointer(Checkpointer):
def __init__(self, checkpoint_dir: str):
self.checkpoint_dir = checkpoint_dir
self._engine = DdpCheckpointEngine(checkpoint_dir)
def save_checkpoint(self, step, state_dict, path='', storage_type=StorageType.DISK):
if (path == ''):
ckpt_nam... |
def CreateTrgDataLoader(args):
if ((args.set == 'train') or (args.set == 'trainval')):
target_dataset = cityscapesDataSetLabel(args.data_dir_target, args.data_list_target, crop_size=image_sizes['cityscapes'], mean=IMG_MEAN, max_iters=(args.num_steps * args.batch_size), set=args.set)
else:
target... |
def create_mapping(dico):
sorted_items = sorted(dico.items(), key=(lambda x: ((- x[1]), x[0])))
id_to_item = {i: v[0] for (i, v) in enumerate(sorted_items)}
item_to_id = {v: k for (k, v) in id_to_item.items()}
return (item_to_id, id_to_item) |
def load_view_point(pcd, filename):
vis = o3d.visualization.Visualizer()
vis.create_window()
ctr = vis.get_view_control()
param = o3d.io.read_pinhole_camera_parameters(filename)
vis.add_geometry(pcd)
ctr.convert_from_pinhole_camera_parameters(param)
vis.run()
vis.destroy_window() |
class TestAttentionReshape(unittest.TestCase):
def setUpClass(self):
pass
def tearDownClass(self):
pass
def test_attention_reshape_0(self):
graph = Graph()
graph.framework_modeling_config['framework'] = 'onnxruntime'
input_data_node = OPERATORS['Input']()
inpu... |
def find_first_disambig_symbol(symbols: k2.SymbolTable) -> int:
return min((v for (k, v) in symbols._sym2id.items() if k.startswith('#'))) |
def main():
opt = TestOptions().parse()
opt.is_flip = False
opt.batchSize = 1
data_loader = CreateDataLoader(opt)
model = create_model(opt)
web_dir = os.path.join(opt.results_dir, 'test')
webpage = html.HTML(web_dir, 'task {}'.format(opt.exp_name))
for (i, data) in enumerate(islice(data_... |
def main(args):
misc.init_distributed_mode(args)
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
print('{}'.format(args).replace(', ', ',\n'))
device = torch.device(args.device)
seed = (args.seed + misc.get_rank())
torch.manual_seed(seed)
np.random.seed(seed)
cud... |
class AverageMeter(object):
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += (... |
class RandomResize(object):
def __init__(self, min_size, max_size=None):
self.min_size = min_size
if (max_size is None):
max_size = min_size
self.max_size = max_size
def __call__(self, image, target):
size = random.randint(self.min_size, self.max_size)
image =... |
class LinearSelfAttn(nn.Module):
def __init__(self, input_size, dropout=None):
super(LinearSelfAttn, self).__init__()
self.linear = nn.Linear(input_size, 1)
self.dropout = dropout
def forward(self, x, x_mask):
x = self.dropout(x)
x_flat = x.contiguous().view((- 1), x.size... |
def wrn_40_2(conv_layer, linear_layer, init_type, **kwargs):
assert (init_type == 'kaiming_normal'), 'only supporting default init for WRN'
return WideResNet(conv_layer, linear_layer, depth=40, widen_factor=2, **kwargs) |
def generate(*args, method='auto', **kwargs):
if (method == 'auto'):
if (not sf.util.CPLEX_AVAILABLE):
log.info('CPLEX solver not found; falling back to pyomo/bonmin.')
method = 'bonmin'
else:
method = 'cplex'
if (method == 'bonmin'):
return _generate_... |
(scope='session')
def model_architectures():
return [('le_net_mnist', (1, 1, 32, 32)), ('le_net_cifar', (1, 3, 32, 32)), ('resnet18', (1, 3, 128, 128)), ('resnet20', (1, 3, 128, 128)), ('resnet56', (1, 3, 128, 128))] |
def load_adult_income_dataset(only_train=True):
outdirname = 'adult'
zipfilename = (outdirname + '.zip')
urlretrieve(' zipfilename)
with zipfile.ZipFile(zipfilename, 'r') as unzip:
unzip.extractall(outdirname)
raw_data = np.genfromtxt((outdirname + '/adult.data'), delimiter=', ', dtype=str, ... |
class MT5EncoderModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def sharding(config, out_file):
with open(out_file, 'rb') as fr:
captions = pickle.load(fr)
target_dir = config.target_dir
prefix = (((os.path.basename(os.path.splitext(config.caption_pkl_path)[0]) + '.') + config.bert_name) + '.')
for split in ['train', 'val']:
target_path = os.path.joi... |
class TripletLoss(nn.Module):
def __init__(self, margin=0.2):
super(TripletLoss, self).__init__()
self.margin = margin
def forward(self, audio_embeds, text_embeds, labels):
n = audio_embeds.size(0)
sim_a2t = util.cos_sim(audio_embeds, text_embeds)
sim_ap = torch.diag(sim_... |
def normal(in_image):
value_max = np.max(in_image)
value_min = np.min(in_image)
return ((in_image - value_min) / (value_max - value_min)) |
_torch
class MegatronBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = ((MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering,... |
class SuperResIDWE4K3(SuperResIDWEXKX):
def __init__(self, in_channels=None, out_channels=None, stride=None, bottleneck_channels=None, sub_layers=None, no_create=False, **kwargs):
super(SuperResIDWE4K3, self).__init__(in_channels=in_channels, out_channels=out_channels, stride=stride, bottleneck_channels=bot... |
def bilinear_attention(queries, units, num_heads, attns=None, memory=None, seq_len=None, causality=False, scope='Bilinear_Attention', reuse=None, mask=None, return_weights=False, bias=True, dropout=0.0):
with tf.variable_scope(scope, default_name='bilinear_attention', reuse=reuse):
memory_shapes = memory.sh... |
class Interp2xBoundary3dFunction(Function):
def forward(ctx, input, balance_value):
(output, is_boundary) = interp2x_boundary3d.forward(input, balance_value)
return (output, is_boundary)
def backward(ctx, grad_output, grad_boundary):
grad_input = interp2x_boundary3d.backward(grad_output.... |
class Inputs(unittest.TestCase):
def test_m2m100_inputs(self):
with tempfile.TemporaryDirectory() as tmpdirname:
input_path = os.path.join(tmpdirname, 'source.txt')
output_path = os.path.join(tmpdirname, 'target.txt')
with open(os.path.join(tmpdirname, 'source.txt'), 'w',... |
class CALayer(nn.Module):
def __init__(self, channel, reduction=16):
super(CALayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.c1 = ops.BasicBlock(channel, (channel // reduction), 3, 1, 3, 3)
self.c2 = ops.BasicBlock(channel, (channel // reduction), 3, 1, 5, 5)
... |
class AMAZONPOLARITY(AbstractTask):
name = 'amazon_polarity'
metric = [metrics.accuracy]
metric_names = ['accuracy']
split_to_data_split = {'train': 'train', 'validation': 'validation'}
def load_dataset(self, split: int):
train_data_files = {'train': './data/manual/amazon_review_polarity_csv... |
def smoothrange(a=None, b=None, n=10):
def _multiple(v, round=False):
e = floor(log(v, 10))
m = pow(10, e)
f = (v / m)
if (round is True):
(op, x, y, z) = (lt, 1.5, 3.0, 7.0)
if (round is False):
(op, x, y, z) = (le, 1.0, 2.0, 5.0)
if op(f, x):... |
def weights_init(m):
classname = m.__class__.__name__
if (('Linear' in classname) or ('Embedding' == classname)):
print(f'Initializing Module {classname}.')
nn.init.trunc_normal_(m.weight.data, 0.0, 0.02) |
def rx_rm_vlc(host, port, chunk=hl2ss.ChunkSize.RM_VLC, mode=hl2ss.StreamMode.MODE_1, divisor=1, profile=hl2ss.VideoProfile.H265_MAIN, level=hl2ss.H26xLevel.DEFAULT, bitrate=None, options=None, decoded=True):
if (bitrate is None):
bitrate = get_video_codec_default_bitrate(hl2ss.Parameters_RM_VLC.WIDTH, hl2s... |
def test_eval_map():
det_results = [[det_bboxes, det_bboxes], [det_bboxes, det_bboxes]]
labels = np.array([0, 1, 1])
labels_ignore = np.array([0, 1])
gt_info = {'bboxes': gt_bboxes, 'bboxes_ignore': gt_ignore, 'labels': labels, 'labels_ignore': labels_ignore}
annotations = [gt_info, gt_info]
(me... |
def build_client_model(feature_num):
inputs = Input(shape=feature_num)
outputs = Dense(1)(inputs)
return Model(inputs=inputs, outputs=outputs, name='vfl_client_model') |
def run_all(tests, K, M):
benchmarkSize = 0
passed = 0
failed = 0
total = 0
oov = 0
for suite in tests:
(passed, failed, total, oov) = run_suite(suite, passed, failed, total, oov, K, M)
benchmarkSize = (benchmarkSize + ((len(suite[2]) * len(suite[2])) - len(suite[2])))
print(... |
class DMSelfAttentionMLP(snt.AbstractModule):
def __init__(self, kq_dim, v_dim, make_mlp_fn, num_heads=8, concat_heads_output_dim=20, concat=True, residual=False, layer_norm=False, kq_dim_division=False, name='dm_self_attention'):
super(DMSelfAttentionMLP, self).__init__(name=name)
self.kq_dim = kq_... |
def _flash_attn_flops_compute(qkv, cu_seqlens, max_seqlen, dropout_p, softmax_scale=None, causal=False, return_attn_probs=False):
(_, _, nheads, headdim) = qkv.shape
batch_size = (cu_seqlens.shape[0] - 1)
qk_macs = (((batch_size * nheads) * (max_seqlen ** 2)) * headdim)
fake_tensor = torch.zeros([batch_... |
def test_extended_orbital_matrix_ferminet_can_be_constructed():
_make_extended_orbital_matrix_ferminets() |
def get_hoi_output(Image_dets, corre_mat=None):
output_hoi = []
for Image_det in tqdm(Image_dets, desc='trans output into eval format'):
Image_det = json.loads(Image_det)
file_name = Image_det['image_id']
output = {'predictions': [], 'hoi_prediction': [], 'file_name': file_name}
... |
class DataTrainingArguments():
task_name: Optional[str] = field(default='ner', metadata={'help': 'The name of the task (ner, pos...).'})
dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'})
overwrite_cache: bool = field(default=Fa... |
class DocstringStyler(CodeStyler):
def is_no_style_block(self, line):
if (_re_textual_blocks.search(line) is not None):
return False
if (_re_example.search(line) is not None):
return True
return (_re_code_block.search(line) is not None)
def is_comment_or_textual_b... |
def update_version_in_file(fname, version, pattern):
with open(fname, 'r', encoding='utf-8', newline='\n') as f:
code = f.read()
(re_pattern, replace) = REPLACE_PATTERNS[pattern]
replace = replace.replace('VERSION', version)
code = re_pattern.sub(replace, code)
with open(fname, 'w', encoding... |
(version='2.0')
def _split_nodename_and_shape(name):
inputs = []
shapes = {}
name_pattern = '(?:([\\w\\d/\\-\\._:]+)(\\[[\\-\\d,]+\\])?),?'
splits = re.split(name_pattern, name)
for i in range(1, len(splits), 3):
inputs.append((splits[i] + ':0'))
if (splits[(i + 1)] is not None):
... |
class Testmodel(TestCase):
def test_HGF(self):
custom_hgf = HGF(model_type=None).add_input_node(kind='continuous', input_idxs=0).add_input_node(kind='binary', input_idxs=1).add_value_parent(children_idxs=0).add_value_parent(children_idxs=1, additional_parameters={'binary_expected_precision': jnp.nan}).add_v... |
class Linear(nn.Linear):
def __init__(self, in_features: int, out_features: int, output_dim: int, bias: bool=True, layer_config: dict=None) -> None:
super(Linear, self).__init__(in_features, out_features, bias)
self.layer_config = layer_config
if ('options' not in self.layer_config):
... |
class CHeaderNode(Node):
__instance: CHeaderNode = None
intel_intr_includes = '\n#include <emmintrin.h>\n#include <pmmintrin.h>\n#include <tmmintrin.h>\n#include <immintrin.h>\n#include <xmmintrin.h>\n '
math_include = '#include <math.h>\n'
test_include = '\n#ifdef CNN_TEST\n#include <stdio.h>\n#endi... |
('/click/<string:articleId>', methods=['GET'])
def click(articleId):
db.clickArticle(articleId, g.user)
pdf = request.args.get('pdf', False, type=(lambda x: (x.lower() == 'true')))
if pdf:
return redirect((' % articleId))
return redirect((' + articleId)) |
class BinConv2d(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size=(- 1), stride=(- 1), padding=(- 1), dropout=0):
super(BinConv2d, self).__init__()
self.layer_type = 'BinConv2d'
self.kernel_size = kernel_size
self.stride = stride
self.padding = paddi... |
def _resnetv2(layers=(3, 4, 9), **kwargs):
padding_same = kwargs.get('padding_same', True)
if padding_same:
stem_type = 'same'
conv_layer = StdConv2dSame
else:
stem_type = ''
conv_layer = StdConv2d
if len(layers):
backbone = ResNetV2(layers=layers, num_classes=0, ... |
class QHeuristic():
def __init__(self):
pass
def evaluate(self, state: State, action):
raise NotImplementedError |
def train(args, io):
train_loader = DataLoader(ModelNet40(partition='train', num_points=args.num_points, args=(args if args.pw else None)), num_workers=8, batch_size=args.batch_size, shuffle=True, drop_last=True)
test_loader = DataLoader(ModelNet40(partition='test', num_points=args.num_points), num_workers=8, b... |
class DeepLab(nn.Module):
def __init__(self, ch, c1=128, c2=512, factor=2, sync_bn=True, freeze_bn=False):
super(DeepLab, self).__init__()
if (sync_bn == True):
BatchNorm = SynchronizedBatchNorm2d
else:
BatchNorm = nn.BatchNorm2d
self.sr_decoder = Decoder(c1, ... |
def get_subset_data(data_path, indices):
sub_img_list = [0 for _ in indices]
sub_label_list = [0 for _ in indices]
idx_dict = dict()
for (i, idx) in enumerate(indices):
idx_dict[idx] = i
indices_set = set(indices)
with open(data_path, 'r') as f:
for (idx, line) in enumerate(f):
... |
class DataWriter(object):
def __init__(self, args, q):
self.queue = q
self.output_dir = args.output
if (self.output_dir is None):
logger.warning('No output directory')
self.started = False
self.proc = None
return
try:
os.mak... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.