code stringlengths 101 5.91M |
|---|
_module()
class CosineAnnealingMomentumUpdaterHook(MomentumUpdaterHook):
def __init__(self, min_momentum=None, min_momentum_ratio=None, **kwargs):
assert ((min_momentum is None) ^ (min_momentum_ratio is None))
self.min_momentum = min_momentum
self.min_momentum_ratio = min_momentum_ratio
... |
class UnitTest(unittest.TestCase):
def setUp(self) -> None:
device = get_device_type()
if (device != 'cpu'):
self.skipTest('Only test this UT case on Intel CPU.')
plugins['tts']['class'] = TextToSpeech
plugins['tts']['enable'] = True
plugins['asr']['class'] = Audi... |
def main():
for split in splits:
word_table = {c: [] for c in WORD_TABLE_COLUMNS}
split_path = os.path.join(seg_path, (split + '_align'))
speaker_dirs = os.listdir(split_path)
speaker_dirs = list(filter((lambda x: str.isdigit(x)), speaker_dirs))
speaker_dirs.sort(key=(lambda ... |
def simpleperf_abi_dir_names(abi):
simpleperf_dir_names = {'armeabi-v7a': 'arm', 'arm64-v8a': 'arm64'}
return simpleperf_dir_names[abi] |
def advantage(A):
std = ((0.0001 + A.std()) if (len(A) > 0) else 1)
adv = ((A - A.mean()) / std)
adv = adv.detach()
adv[(adv != adv)] = 0
return adv |
def load_wikigold_data(file_name):
with open(file_name, 'r') as f:
instances = json.load(f)
sent_list = list()
labels_list = list()
for instant in instances:
sent = instant['text']
labels = formalize_bio(instant['labels'])
sent_list.append(sent)
labels_list.append... |
def test_categorical_exact_exclude_parents(X):
exclude_parents = ((), (2,), (), (1,))
structure = _categorical_exact(X, exclude_parents=exclude_parents)
assert_tuple_equal(structure, ((), (), (0,), (0, 2)))
structure = _categorical_exact(X, exclude_parents=exclude_parents, max_parents=1)
assert_tupl... |
class MessagePassing(torch.nn.Module):
def __init__(self, aggr='add'):
super(MessagePassing, self).__init__()
self.message_args = inspect.getargspec(self.message)[0][1:]
self.update_args = inspect.getargspec(self.update)[0][2:]
def propagate(self, aggr, edge_index, **kwargs):
ass... |
class Deconvolution2D(KerasLayer):
def __init__(self, nb_filter, nb_row, nb_col, output_shape, init='glorot_uniform', activation=None, border_mode='valid', subsample=(1, 1), dim_ordering='th', W_regularizer=None, b_regularizer=None, bias=True, input_shape=None, **kwargs):
if (border_mode != 'valid'):
... |
def update_scale(qmodel, model, data_distill, graph, bottoms, res, targ_layer, num_epoch=1000):
print('Start updating scale')
writer = SummaryWriter('./tensorboard/exp_{}/'.format(round(time.time())))
qmodel = qmodel.eval().cuda()
model = model.eval().cuda()
for idx in range(len(data_distill)):
... |
_BUILDERS.register_module()
class LearningRateDecayOptimizerConstructor(DefaultOptimizerConstructor):
def add_params(self, params, module, **kwargs):
logger = get_root_logger()
parameter_groups = {}
logger.info(f'self.paramwise_cfg is {self.paramwise_cfg}')
num_layers = (self.paramwi... |
def dino_xcit_medium_24_p16(pretrained=True, **kwargs):
model = torch.hub.load('facebookresearch/xcit:main', 'xcit_medium_24_p16', num_classes=0, **kwargs)
if pretrained:
state_dict = torch.hub.load_state_dict_from_url(url=' map_location='cpu')
model.load_state_dict(state_dict, strict=True)
... |
def make_data_loader(cfg, shuffle_train=True):
train_transforms = build_transforms(cfg, is_train=shuffle_train)
val_transforms = build_transforms(cfg, is_train=False)
num_workers = cfg.DATALOADER.NUM_WORKERS
dataset = BaseImageDataset()
print(cfg.DATASETS.TRAIN)
if isinstance(cfg.DATASETS.TRAIN,... |
class PROBAVDataModule(BaseDataModule):
def __init__(self, root: str='.data/probav', band: str='RED', lr_transform: T.Compose=T.Compose([ToTensor(), ToDtype(torch.float32)]), hr_transform: T.Compose=T.Compose([ToTensor(), ToDtype(torch.float32)]), *args, **kwargs):
super().__init__(*args, **kwargs)
... |
def quaddobl_newton_power_series(pols, lser, idx=1, maxdeg=4, nbr=4, checkin=True, verbose=True):
from phcpy.solver import number_of_symbols
from phcpy.interface import store_quaddobl_system, load_quaddobl_system
from phcpy.phcpy2c3 import py2c_quaddobl_Newton_power_series as newton
from phcpy.phcpy2c3 ... |
class TFLayoutLMv3PreTrainedModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def train(model, train_loaders, optimizer, tokenizer, epoch, global_step, device, scheduler, scaler, config):
model.train()
metric_logger = MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', SmoothedValue(window=1, fmt='{value:.6f}'))
metric_logger.add_meter('temperature', SmoothedValue(window=1... |
def move(nrow):
return np.array([1, (nrow + 1), nrow, (nrow - 1), (- 1), ((- nrow) - 1), (- nrow), ((- nrow) + 1)]) |
_module()
class DetectionTransformer(BaseDetector, metaclass=ABCMeta):
def __init__(self, backbone: ConfigType, neck: OptConfigType=None, encoder: OptConfigType=None, decoder: OptConfigType=None, bbox_head: OptConfigType=None, positional_encoding: OptConfigType=None, num_queries: int=100, train_cfg: OptConfigType=N... |
class SparseLeNet(nn.Module):
def __init__(self, sparsities, sparse_func='reg'):
super(SparseLeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(256, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, ... |
class DCNv2Pooling(nn.Module):
def __init__(self, spatial_scale, pooled_size, output_dim, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0):
super(DCNv2Pooling, self).__init__()
self.spatial_scale = spatial_scale
self.pooled_size = pooled_size
self.output_dim ... |
def dropout(inputs, is_training, scope, keep_prob=0.5, noise_shape=None):
with tf.variable_scope(scope) as sc:
outputs = tf.cond(is_training, (lambda : tf.nn.dropout(inputs, keep_prob, noise_shape)), (lambda : inputs))
return outputs |
def query_point_sampling_complex(draw) -> np.complex:
real_part = draw(float_sampling())
imaginary_part = draw(float_sampling())
query_point = np.complex(real_part, imaginary_part)
return query_point |
def add_words_to_word_vec_dict(word_vec_dict, word_set, dictionary, translations=None):
succeeded_to_find_in_src_list = 0
failed_to_find_in_src_list = 0
for word in word_set:
try:
translation = (word if (translations is None) else translations[word])
word_vec_dict[translation... |
def test_quad_double_syspool(vrblvl=0):
initialize_quad_double_syspool(3, vrblvl)
dim = size_quad_double_syspool(vrblvl)
print('The size of the systems pool :', dim)
pol1 = ['t - 1/3;']
set_quad_double_system(1, pol1, vrblvl)
copy_to_quad_double_syspool(1)
pol2 = ['t - 2/3;']
set_quad_do... |
class PermutationInvariantSolution(Solution):
def __init__(self, n_embeddings=16, proj_dim=32, hidden_size=8):
self.kwargs = {'n_embeddings': n_embeddings, 'proj_dim': proj_dim, 'hidden_size': hidden_size}
self.policy = PermutationInvariantNetwork(n_embeddings=n_embeddings, proj_dim=proj_dim, hidden... |
class PrefetchLoader(object):
def __init__(self, loader):
self.loader = loader
self.stream = torch.cuda.Stream()
def __iter__(self):
loader_it = iter(self.loader)
self.preload(loader_it)
batch = self.next(loader_it)
while (batch is not None):
(yield ba... |
def _kinematics_from_tokens(helper: PredictHelper, instance: str, sample: str) -> KinematicsData:
annotation = helper.get_sample_annotation(instance, sample)
(x, y, _) = annotation['translation']
yaw = quaternion_yaw(Quaternion(annotation['rotation']))
velocity = helper.get_velocity_for_agent(instance, ... |
def parse_results(experiments, save_dir):
log_results = {}
for (exp_name, subdict) in experiments.items():
timestamp = subdict['timestamp']
if timestamp.startswith('TODO'):
log_results[exp_name] = {'timestamp': 'TODO', 'results': {}}
continue
log_path = ((((Path(s... |
def add_pip(src, dst, flags=0):
(x, y, _, _) = switches[(- 1)]
if (src not in wire_downhill):
wire_downhill[src] = set()
wire_downhill[src].add(dst)
if (dst not in wire_uphill):
wire_uphill[dst] = set()
wire_uphill[dst].add(src)
pip_xy[(src, dst)] = (x, y, 0, (len(switches) - 1),... |
class SceneGraphTrainer(DefaultTrainer):
def __init__(self, cfg):
super(SceneGraphTrainer, self).__init__(cfg)
def build_train_loader(cls, cfg):
return build_detection_train_loader(cfg, mapper=SceneGraphDatasetMapper(cfg, True))
def build_test_loader(cls, cfg, dataset_name):
return b... |
def is_rst_docstring(docstring):
if (_re_rst_special_words.search(docstring) is not None):
return True
if (_re_double_backquotes.search(docstring) is not None):
return True
if (_re_rst_example.search(docstring) is not None):
return True
return False |
def Perlin(nrow, specs={}):
size = specs.get('size', 5)
assert (size > 0)
x = y = np.linspace(0, size, nrow)
n = [[noise.pnoise2(i, j, repeatx=size, repeaty=size) for j in y] for i in x]
landscape = (n - np.min(n))
landscape /= landscape.max()
return landscape.ravel() |
def batch_to_device(batch, device='cuda:0'):
vals = [to_device(getattr(batch, field), device) for field in batch._fields]
return type(batch)(*vals) |
def get_optimized_training_schedule(task, optimizer):
if (task in ['C10-CNN1', 'C100-resnet', 'tiny-CNN']):
if ('layca' in optimizer):
lr = ((3 ** (- 5)) if (optimizer in ['Adam_layca', 'SGD_AMom_layca']) else (3 ** (- 3)))
elif ((task in ['C10-CNN1', 'C100-resnet']) and (optimizer == 'S... |
class CityscapesDataset(Pix2pixDataset):
def modify_commandline_options(parser, is_train):
parser = Pix2pixDataset.modify_commandline_options(parser, is_train)
parser.set_defaults(preprocess_mode='fixed')
parser.set_defaults(load_size=512)
parser.set_defaults(crop_size=512)
p... |
def is_syntactic_correct(code):
try:
javalang.parse.parse(code)
return True
except Exception as e:
return False |
def test_digits_cosine_greedi_ll_object():
model = FacilityLocationSelection(100, 'cosine', optimizer=GreeDi(optimizer1='lazy', optimizer2='lazy', random_state=0))
model.fit(X_digits)
assert_array_equal(model.ranking[:30], digits_cosine_greedi_ranking[:30])
assert_array_almost_equal(model.gains[:30], di... |
def set_batch_nodeID(mol_batch, vocab):
tot = 0
for mol_tree in mol_batch:
for node in mol_tree.nodes:
node.idx = tot
node.wid = vocab.get_index(node.smiles)
tot += 1 |
def run_interpretation_summary(x_unvec, y, contrib_sums_D, contrib_sums_D2, contrib_sums, idx_feat_dict, idx_class_dict, icd9_descript_dict, pairs, num_sample, full_out_dir):
from riddle import feature_importance, frequency, ordering
feat_importance_summary = feature_importance.FeatureImportanceSummary(contrib_... |
def paren_colors():
if (color_scheme == 'dark'):
return ['red', 'green', 'cyan', 'magenta', 'yellow']
elif (color_scheme == 'light'):
return ['blue', 'red', 'magenta', 'green', 'cyan']
else:
raise RuntimeError(('Unknown color scheme: %s' % color_scheme)) |
def mobilenetv3_small_w7d20(**kwargs):
return get_mobilenetv3(version='small', width_scale=0.35, model_name='mobilenetv3_small_w7d20', **kwargs) |
def relu_or_hswish(name):
if (name == 'RE'):
return nn.ReLU
elif (name == 'HS'):
return nn.Hardswish
else:
raise IOError(f'{name} does not exist') |
class VTUAVDataset(BaseDataset):
def __init__(self, subset):
super().__init__()
if (subset == 'st'):
self.base_path = os.path.join(self.env_settings.vtuav_path, 'short-term')
elif (subset == 'lt'):
self.base_path = os.path.join(self.env_settings.vtuav_path, 'long-term... |
.parametrize('loss_bbox', [dict(type='L1Loss', loss_weight=1.0), dict(type='GHMR', mu=0.02, bins=10, momentum=0.7, loss_weight=10.0), dict(type='IoULoss', loss_weight=1.0), dict(type='BoundedIoULoss', loss_weight=1.0), dict(type='GIoULoss', loss_weight=1.0), dict(type='DIoULoss', loss_weight=1.0), dict(type='CIoULoss',... |
def convert_to_submission(source_dir, target_dir):
niftis = subfiles(source_dir, join=False, suffix='.nii.gz')
patientids = np.unique([i[:10] for i in niftis])
maybe_mkdir_p(target_dir)
for p in patientids:
files_of_that_patient = subfiles(source_dir, prefix=p, suffix='.nii.gz', join=False)
... |
def tf_model_to_tar(tf_model: Model, run_id: int):
model_name = 'intent-model-{}/1'.format(run_id)
local_tar_name = 'model-{}.tar.gz'.format(run_id)
tf_model.save(filepath=model_name)
with tarfile.open(local_tar_name, mode='w:gz') as _tar:
_tar.add(model_name, recursive=True)
shutil.rmtree(m... |
def checkpoint_dir(trainer: Trainer):
return os.path.join(trainer.logdir, 'br_policy_checkpoints') |
def get_mask(attention, thr_high, thr_low):
mask = attention.new_zeros((attention.size(0), 1, 224, 224)).fill_(255)
mask = mask_fg(mask, attention, thr_high)
mask = mask_bg(mask, attention, thr_low)
return mask |
def save_analysis(chosen_data: list[dict], rejected_data: list[dict], output_dir: Path):
rejected_data = sorted(rejected_data, key=(lambda x: x['reason']))
write_jsonl((output_dir / 'rejected_data.jsonl'), rejected_data)
chosen_data_dict = dict[(str, list[dict])]()
rejected_data_dict = dict[(str, list[d... |
class LikGauss(Likelihood):
def __init__(self, sf=None):
self.sf = sf
def gpml_function(self):
if (self.sf > (- np.Inf)):
return '{}'
else:
return '{}'
def is_thunk(self):
return True
def id(self):
return 'Gauss'
def param_vector(self):... |
_LAYERS.register_module()
class SparseInverseConv2d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, indice_key=None, bias=True):
super(SparseInverseConv2d, self).__init__(2, in_channels, out_channels, kernel_size, bias=bias, inverse=True, indice_key=indice_key) |
def scale_grad(grad):
grad_arr = torch.abs(grad).mean(dim=1).detach().permute(1, 2, 0)
grad_arr /= grad_arr.quantile(0.98)
grad_arr = torch.clamp(grad_arr, 0, 1)
return grad_arr.numpy() |
class FORCESNLPsolver_final_outputs_ctypes(ctypes.Structure):
_fields_ = [('x01', (ctypes.c_double * 17)), ('x02', (ctypes.c_double * 17)), ('x03', (ctypes.c_double * 17)), ('x04', (ctypes.c_double * 17)), ('x05', (ctypes.c_double * 17)), ('x06', (ctypes.c_double * 17)), ('x07', (ctypes.c_double * 17)), ('x08', (ct... |
def get_discriminator(model_config):
discriminator_name = model_config['d_name']
if (discriminator_name == 'no_gan'):
model_d = None
elif (discriminator_name == 'patch_gan'):
model_d = NLayerDiscriminator(n_layers=model_config['d_layers'], norm_layer=get_norm_layer(norm_type=model_config['no... |
class DataTrainingArguments():
label_column_id: int = field(metadata={'help': 'Which column contains the label'})
train_file: str = field(default=None, metadata={'help': 'The path of the training file'})
dev_file: Optional[str] = field(default=None, metadata={'help': 'The path of the development file'})
... |
def validate_and_save(cfg: DictConfig, trainer: Trainer, task: tasks.FairseqTask, epoch_itr, valid_subsets: List[str], end_of_epoch: bool) -> Tuple[(List[Optional[float]], bool)]:
num_updates = trainer.get_num_updates()
max_update = (cfg.optimization.max_update or math.inf)
should_stop = False
if (num_u... |
class RevGrad(Module):
def __init__(self, alpha=1, *args, **kwargs):
super().__init__(*args, **kwargs)
self.alpha = tensor(alpha, requires_grad=False)
def forward(self, input_):
return revgrad(input_, self.alpha) |
class DenseConvBlock():
def __init__(self, growth_rate=64, n_layers=1, bottleneck_factor=1, **kwargs):
n_layers = np.minimum(n_layers, 3)
n_layers = np.maximum(n_layers, 1)
self.dense_conv = DenseConv2D((growth_rate * n_layers), bottleneck_factor)
def call(self, inputs):
return s... |
('/conv', response_model=List[TurnResponse])
def conversational_entity_linking(config: ConversationConfig):
if DEBUG:
return []
return config.response() |
def build_transforms(cfg, mode='train'):
assert (mode in ['train', 'test', 'val'])
min_size = cfg.SCALES[0]
max_size = cfg.SCALES[1]
assert (min_size <= max_size)
if (mode == 'train'):
flip_prob = cfg.TRAIN.FLIP_PROB
elif (mode == 'test'):
flip_prob = cfg.TEST.FLIP_PROB
else:... |
_group.command('get')
('name')
('path', type=click.Path(exists=True, file_okay=False, writable=True, resolve_path=True))
_project(required=True)
def get_sim(name, path, project=None):
from cli.sims import download_sim
try:
output_path = download_sim(name, path, project)
click.echo(f"Downloaded s... |
def fc_elu_layer(name, bottom, output_dim, is_train, bias_term=True, weights_initializer=None, biases_initializer=None, reuse=None, dropout=False, dropout_rate=0.3):
if dropout:
bottom = tf.cond(is_train, (lambda : tf.nn.dropout(bottom, rate=dropout_rate)), (lambda : bottom))
fc = fc_layer(name, bottom,... |
def extract_block(content: str, indent_level: int=0) -> str:
current_object = []
lines = content.split('\n')
end_markers = [')', ']', '}', '"""']
for (idx, line) in enumerate(lines):
if ((idx == 0) and (indent_level > 0) and (not is_empty_line(line)) and (find_indent(line) != indent_level)):
... |
def test_precompute():
settings = dict(feature='mels', samplerate=16000, n_mels=32, fmin=0, fmax=8000, n_fft=512, hop_length=256, augmentations=12)
dir = './pre2'
if os.path.exists(dir):
shutil.rmtree(dir)
workdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/'))
data = ... |
class TestSparseProductCUDA(unittest.TestCase):
def setUpClass(cls):
if (not torch.cuda.is_available()):
raise unittest.SkipTest('No CUDA capable device detected')
def test_single_query(self):
X = torch.randn(1, 1, 1, 32).cuda()
Y = torch.randn(1, 1, 100, 32).cuda()
l... |
def augmentor_sim(cascade_file, save_aug_file):
def calculate_global_time(path):
all_ts = list()
i = 0
with open(path, 'r') as f:
for line in f:
i += 1
last_t = 0
paths = line.strip().split('\t')
paths = paths[2:(- 1... |
def retrofit_eval_fn(original_fn):
def f(model_id, *args, **kwargs):
if ('view_index' in kwargs):
view_index = kwargs['view_index']
if isinstance(view_index, int):
return original_fn(model_id, *args, **kwargs)
else:
del kwargs['view_index']... |
class URL(object):
def __init__(self, string='', method=GET, query={}, **kwargs):
self.__dict__['method'] = method
self.__dict__['_string'] = u(string)
self.__dict__['_parts'] = None
self.__dict__['_headers'] = None
self.__dict__['_redirect'] = None
if isinstance(stri... |
class TrainingSchedule(Callback):
def __init__(self, total_time):
self._total_time = total_time
self._lr = self._get_lr(0.0)
def _get_lr(self, progress):
if (progress > 0.8):
return 0.004
elif (progress > 0.5):
return 0.02
else:
return ... |
class PreResActivation(nn.Module):
def __init__(self, in_channels, bn_affine=True):
super(PreResActivation, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels, affine=bn_affine)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = se... |
def run_multi_process_init_distributed(codes=None, nproc=2, training_script=None, training_script_args=''):
if (codes is not None):
(fd, training_script) = tempfile.mkstemp(suffix='py')
with open(fd, 'w') as f:
f.write(codes)
os.environ['WORLD_SIZE'] = '1'
os.environ['MASTER_PORT... |
_tokenizer('nltk')
class NLTKTokenizer(object):
def __init__(self, source_lang=None, target_lang=None):
try:
from nltk.tokenize import word_tokenize
self.word_tokenize = word_tokenize
except ImportError:
raise ImportError('Please install nltk with: pip install nlt... |
def get_model_list():
ret = requests.post((args.controller_url + '/refresh_all_workers'))
assert (ret.status_code == 200)
ret = requests.post((args.controller_url + '/list_models'))
models = ret.json()['models']
models.sort(key=(lambda x: priority.get(x, x)))
logger.info(f'Models: {models}')
... |
class JobManager(MsfManager):
def list(self):
return self.rpc.call(MsfRpcMethod.JobList)
def stop(self, jobid):
self.rpc.call(MsfRpcMethod.JobStop, [jobid])
def info(self, jobid):
return self.rpc.call(MsfRpcMethod.JobInfo, [jobid])
def info_by_uuid(self, uuid):
return sel... |
def bert_tokenize(sent):
tokens = []
for (i, t) in enumerate(sent):
subtokens = tokenizer.tokenize(t['text'].strip())
for st in subtokens:
tokens.append({'text': t['text'], 'text_with_ws': t['text_with_ws'], 'lemma': t['lemma'], 'sub': st, 'text_id': i})
return tokens |
def loss_game_nfsp_dqn_params(env: MultiAgentEnv) -> Dict[(str, Any)]:
return merge_dicts(GRL_DEFAULT_OSHI_ZUMO_MEDIUM_DQN_PARAMS, {'metrics_smoothing_episodes': 10000, 'exploration_config': {'epsilon_timesteps': int(.0), 'final_epsilon': 0.001, 'initial_epsilon': 0.06, 'type': ValidActionsEpsilonGreedy}, 'model': ... |
def initalizeEnvironment(environment, logger):
if (environment != ''):
db = Database(DB_NAME, DB_HOST, DB_PORT)
' Can be SimpleFog, BitbrainFog // Datacenter '
if (environment != ''):
datacenter = Datacenter(HOSTS_IP, environment)
else:
datacenter = BitbrainFog(HOSTS)
' Can b... |
_model
def cspresnet50w(pretrained=False, **kwargs):
return _create_cspnet('cspresnet50w', pretrained=pretrained, **kwargs) |
def dobldobl_set_solution(nvar, sol, verbose=False):
from phcpy.phcpy2c3 import py2c_padcon_initialize_dobldobl_solution
from phcpy.interface import store_dobldobl_solutions
store_dobldobl_solutions(nvar, [sol])
return py2c_padcon_initialize_dobldobl_solution(1, int(verbose)) |
def drn_d_105(BatchNorm, pretrained=True):
model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 1, 1], arch='D', BatchNorm=BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-105'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrai... |
_module()
class HWFolderMultipleGTDataset(BaseDHDataset):
def __init__(self, lq_folder, gt_folder, pipeline, trans_folder=None, ann_file=None, num_input_frames=None, test_mode=True):
super().__init__(pipeline, test_mode)
self.lq_folder = str(lq_folder)
self.gt_folder = str(gt_folder)
... |
class AutoPipelineForImage2Image(ConfigMixin):
config_name = 'model_index.json'
def __init__(self, *args, **kwargs):
raise EnvironmentError(f'{self.__class__.__name__} is designed to be instantiated using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or `{self.__class__.... |
def load_data(config):
print(('-*-' * 10))
print(f'current data_sign: {config.data_sign}')
if (config.data_sign == 'conll03'):
data_processor = Conll03Processor()
elif (config.data_sign == 'zh_msra'):
data_processor = MSRAProcessor()
elif (config.data_sign == 'zh_onto'):
data... |
class HifiganVocoder():
def __init__(self, vocoder_path, vocoder_cfg_path, use_cuda=True):
with open(vocoder_cfg_path) as f:
cfg = json.load(f)
self.vocoder = CodeHiFiGANVocoder(vocoder_path, cfg).eval()
self.use_cuda = use_cuda
if self.use_cuda:
self.vocoder.... |
class GCN(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = GCNConv(dataset.num_node_features, 16)
self.conv2 = GCNConv(16, dataset.num_classes)
def forward(self, data):
(x, edge_index) = (data.x, data.edge_index)
x = self.conv1(x, edge_index)
... |
def hotpot_biattention(config, is_train, h, u, h_mask=None, u_mask=None, scope=None, tensor_dict=None):
(h_len, u_len) = (tf.shape(h)[2], tf.shape(u)[1])
M = tf.shape(h)[1]
u_aug = tf.tile(tf.expand_dims(u, 1), [1, M, 1, 1])
with tf.variable_scope((scope or 'hotpot_biattention')):
h_dot = tf.squ... |
class MJOPTION(Structure):
_fields_ = [('timestep', c_double), ('apirate', c_double), ('tolerance', c_double), ('impratio', c_double), ('gravity', (c_double * 3)), ('wind', (c_double * 3)), ('magnetic', (c_double * 3)), ('density', c_double), ('viscosity', c_double), ('o_margin', c_double), ('o_solref', (c_double *... |
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
line = line.replace('\\\\', '')
if (line.count('/*') > line.count('*/')):
error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. L... |
def split_to_dir(train_idxes, val_idxes, test_idxes, label_list):
texts = []
with open('data/AAPD/text_all', 'r') as f:
for line in f:
texts.append(line)
def write_text(path, idxes):
with open(path, 'w') as f:
for i in idxes:
f.write(texts[i])
def ... |
class PointSupDatasetMapper():
def __init__(self, is_train: bool, *, augmentations: List[Union[(T.Augmentation, T.Transform)]], image_format: str, sample_points: int=0):
self.is_train = is_train
self.augmentations = T.AugmentationList(augmentations)
self.image_format = image_format
s... |
class PredefinedPromptExtractor(PromptExtractor):
def __init__(self, templates: List[str]):
super().__init__()
self.templates = ['a photo of a {}.', 'This is a photo of a {}', 'There is a {} in the scene', 'There is the {} in the scene', 'a photo of a {} in the scene', 'a photo of a small {}.', 'a p... |
_module()
class CenterNet(SingleStageDetector):
def __init__(self, backbone: ConfigType, neck: ConfigType, bbox_head: ConfigType, train_cfg: OptConfigType=None, test_cfg: OptConfigType=None, data_preprocessor: OptConfigType=None, init_cfg: OptMultiConfig=None) -> None:
super().__init__(backbone=backbone, ne... |
class BasicRFB(nn.Module):
def __init__(self, in_planes, out_planes, stride=1, scale=0.1, visual=1):
super(BasicRFB, self).__init__()
self.scale = scale
self.out_channels = out_planes
inter_planes = (in_planes // 8)
self.branch0 = nn.Sequential(BasicConv(in_planes, (2 * inter... |
class normalize(nn.Module):
def __init__(self):
super(normalize, self).__init__()
def forward(self, x):
x = F.normalize(x, p=2, dim=1)
return x |
class Poisson(Distribution):
def __init__(self, lambdas=None, inertia=0.0, frozen=False, check_data=True):
super().__init__(inertia=inertia, frozen=frozen, check_data=check_data)
self.name = 'Poisson'
self.lambdas = _check_parameter(_cast_as_parameter(lambdas), 'lambdas', min_value=0, ndim=1... |
def _find_conditional_parameters(dim, S):
Sig12Sig22inv = []
cond_var = []
for e in range(dim):
S11 = copy.copy(S[e][e])
S12 = S[e][:]
S12 = np.delete(S12, e)
S21 = S[e][:]
S21 = np.delete(S21, e)
S22 = S[:][:]
S22 = np.delete(S22, e, 0)
S22 = ... |
class TrainerConfigCLAM(_TrainerConfig):
def __init__(self, *, num_splits: int=1, k: int=3, k_start: int=(- 1), k_end: int=(- 1), max_epochs: int=20, lr: float=0.0001, reg: float=1e-05, label_frac: float=1, weighted_sample: bool=False, log_data: bool=False, testing: bool=False, early_stopping: bool=False, subtyping... |
class DCNv2(nn.Module):
def __init__(self, c1, c2, k, s, p, g=1):
super().__init__()
self.dcn = DeformConv2d(c1, c2, k, s, p, groups=g)
self.offset_mask = nn.Conv2d(c2, (((g * 3) * k) * k), k, s, p)
self._init_offset()
def _init_offset(self):
self.offset_mask.weight.data.... |
def _get_sampling_method(training_pars: dict) -> Callable[([List[SentenceEvidence], Dict[(str, List[SentenceEvidence])]], List[SentenceEvidence])]:
if (training_pars['sampling_method'] == 'random'):
sampling_ratio = training_pars['sampling_ratio']
logging.info(f'Setting up random sampling with negat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.