code stringlengths 101 5.91M |
|---|
()
_option()
def cli():
logging.getLogger('dgp2widker').setLevel(level=logging.INFO)
logging.getLogger('py4j').setLevel(level=logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('PIL').setLevel(logging.CRI... |
class Scenario(BaseScenario):
def make_world(self):
world = World()
num_agents = 3
num_adversaries = 1
num_landmarks = 2
world.dim_c = 4
world.agents = [CryptoAgent() for i in range(num_agents)]
for (i, agent) in enumerate(world.agents):
agent.name... |
def IsTainted(split_line_of_utt):
return ((len(split_line_of_utt) > 8) and (split_line_of_utt[8] == 'tainted')) |
class ROIBoxHead(torch.nn.Module):
def __init__(self, cfg, in_channels):
super(ROIBoxHead, self).__init__()
self.feature_extractor = make_roi_box_feature_extractor(cfg, in_channels)
self.predictor = make_roi_box_predictor(cfg, self.feature_extractor.out_channels)
self.post_processor ... |
class ModulatedDeformConvPack(ModulatedDeformConv):
_version = 2
def __init__(self, *args, **kwargs):
super(ModulatedDeformConvPack, self).__init__(*args, **kwargs)
self.conv_offset = nn.Conv2d(self.in_channels, (((self.deformable_groups * 3) * self.kernel_size[0]) * self.kernel_size[1]), kernel... |
class SUNRGBDData(object):
def __init__(self, root_path, split='train', use_v1=False):
self.root_dir = root_path
self.split = split
self.split_dir = osp.join(root_path, 'sunrgbd_trainval')
self.classes = ['bed', 'table', 'sofa', 'chair', 'toilet', 'desk', 'dresser', 'night_stand', 'b... |
def rar_wrapper(pde, model, conf):
data = model.data
train = model.train
def wrapper(*args, **kwargs):
total_iter = kwargs['iterations']
(interval, count) = (conf['interval'], conf['count'])
assert ((total_iter % interval) == 0)
kwargs['iterations'] = interval
for i i... |
def diverse_bleu(answers):
div_bleu = 0
m = len(answers)
if (m == 1):
return 0.0
for i in range(m):
for j in range((i + 1), m):
prediction = answers[i][1].lower().split()
ground_truths = [answers[j][1].lower().split()]
div_bleu += compute_bleu([ground_... |
def rotated_feature_align(features, best_rbboxes, spatial_scale=(1 / 8), points=1):
return RotatedFeatureAlignFunction.apply(features, best_rbboxes, spatial_scale, points) |
class Filter2(nn.Module):
def __init__(self, config):
super().__init__()
hidden_size = 512
self.word_vlad = NetVLAD(cluster_size=4, feature_size=hidden_size)
self.ws1 = nn.Linear(hidden_size, hidden_size, bias=True)
self.ws2 = nn.Linear(hidden_size, hidden_size, bias=False)
... |
class SublayerConnection(nn.Module):
def __init__(self, d_model, dropout):
super(SublayerConnection, self).__init__()
self.norm = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x, sublayer):
return (x + self.dropout(sublayer(self.norm(x)))) |
def test_actionAngleTorus_interppot_freqs():
from galpy.actionAngle import actionAngleTorus
from galpy.potential import LogarithmicHaloPotential, interpRZPotential
lp = LogarithmicHaloPotential(normalize=1.0)
ip = interpRZPotential(RZPot=lp, interpPot=True, interpDens=True, interpRforce=True, interpzfor... |
class test_training(unittest.TestCase):
def setUp(self, prevdir=prevdir, training_scripts=training_scripts):
os.chdir(prevdir)
gopen = open('settings.json', 'r')
settings = json.load(gopen)
gopen.close()
settings['default_training_script'] = training_scripts
settings[... |
class ConfigTester(object):
def __init__(self, parent, config_class=None, has_text_modality=True, **kwargs):
self.parent = parent
self.config_class = config_class
self.has_text_modality = has_text_modality
self.inputs_dict = kwargs
def create_and_test_config_common_properties(sel... |
_pipeline_test
class PipelinePadTest(unittest.TestCase):
_torch
def test_pipeline_padding(self):
import torch
items = [{'label': 'label1', 'input_ids': torch.LongTensor([[1, 23, 24, 2]]), 'attention_mask': torch.LongTensor([[0, 1, 1, 0]])}, {'label': 'label2', 'input_ids': torch.LongTensor([[1, ... |
def create_var(tensor, requires_grad=False):
return Variable(tensor, requires_grad=requires_grad) |
class UNet(nn.Module):
def __init__(self, input_dim=1, num_classes=2):
super(UNet, self).__init__()
self.num_classes = num_classes
self.dec1 = UNetDec(input_dim, 64)
self.dec2 = UNetDec(64, 128)
self.dec3 = UNetDec(128, 256)
self.dec4 = UNetDec(256, 512, dropout=True)... |
def gen_final(In, Out):
(yield nn.Conv2d(In, Out, 3, padding=1))
(yield nn.ReLU(inplace=True)) |
def track_progress(func, tasks, bar_width=50, **kwargs):
if isinstance(tasks, tuple):
assert (len(tasks) == 2)
assert isinstance(tasks[0], collections_abc.Iterable)
assert isinstance(tasks[1], int)
task_num = tasks[1]
tasks = tasks[0]
elif isinstance(tasks, collections_ab... |
class MultiLoss(nn.Module):
def __init__(self, *args, dbg=()):
nn.Module.__init__(self)
assert ((len(args) % 2) == 0), 'args must be a list of (float, loss)'
self.weights = []
self.losses = nn.ModuleList()
for i in range((len(args) // 2)):
weight = float(args[((2 ... |
def _compute_num_images_per_worker(cfg: CfgNode) -> int:
num_workers = get_world_size()
images_per_batch = cfg.SOLVER.IMS_PER_BATCH
assert ((images_per_batch % num_workers) == 0), 'SOLVER.IMS_PER_BATCH ({}) must be divisible by the number of workers ({}).'.format(images_per_batch, num_workers)
assert (i... |
def main(args):
cfg = setup(args)
if args.eval_only:
model = Trainer.build_model(cfg)
DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume)
res = Trainer.test(cfg, model)
if cfg.TEST.AUG.ENABLED:
res.update(Trainer... |
def compute_flat_grad(output, inputs, filter_input_ids=set(), retain_graph=False, create_graph=False):
if create_graph:
retain_graph = True
inputs = list(inputs)
params = []
for (i, param) in enumerate(inputs):
if (i not in filter_input_ids):
params.append(param)
grads = ... |
class T5LMTokenizerWrapper(TokenizerWrapper):
def __init__(self, max_seq_length: int, tokenizer: PreTrainedTokenizer, truncate_method: Optional[str]='tail', decoder_max_length: Optional[int]=128, decode_from_pad: Optional[bool]=True, predict_eos_token: Optional[bool]=False, **kwargs):
super().__init__(max_s... |
class ShowProcess():
i = 1
max_steps = 0
max_arrow = 50
def __init__(self, max_steps):
self.max_steps = max_steps
self.i = 1
def show_process(self, i=None):
if (i is not None):
self.i = i
num_arrow = int(((self.i * self.max_arrow) / self.max_steps))
... |
class Conv2dSame(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride):
super().__init__()
padding = self.conv_same_pad(kernel_size, stride)
if (type(padding) is not tuple):
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
... |
def build_densepose_data_filter(cfg: CfgNode):
dp_filter = DensePoseDataFilter(cfg)
return dp_filter |
def parse_config():
parser = argparse.ArgumentParser()
parser.add_argument('--token_vocab', type=str)
parser.add_argument('--concept_vocab', type=str)
parser.add_argument('--predictable_token_vocab', type=str)
parser.add_argument('--token_char_vocab', type=str)
parser.add_argument('--concept_cha... |
def get_data_loader(args):
train_dataset = PPIDataset(mode='train')
valid_dataset = PPIDataset(mode='valid')
test_dataset = PPIDataset(mode='test')
train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, collate_fn=collate, num_workers=4, shuffle=True)
fixed_train_dataloader = DataL... |
def dump_tabular(*args, **kwargs):
if (not _disabled):
wh = kwargs.pop('write_header', None)
if (len(_tabular) > 0):
if _log_tabular_only:
table_printer.print_tabular(_tabular)
else:
for line in tabulate(_tabular).split('\n'):
... |
def _draw_constraint(surface, constraint):
if (isinstance(constraint, pymunk.GrooveJoint) and hasattr(constraint, 'groove_a')):
pv1 = (constraint.a.position + constraint.groove_a)
pv2 = (constraint.a.position + constraint.groove_b)
p1 = to_pygame(pv1, surface)
p2 = to_pygame(pv2, sur... |
class CompressedWriteObjective(CompressedObjective):
__slots__ = ('chi', 'compress_late', 'secondary_weight')
def __init__(self, chi='auto', compress_late=False, secondary_weight=0.001):
self.secondary_weight = secondary_weight
super().__init__(chi=chi, compress_late=compress_late)
def get_c... |
def prepare_rnn(config):
data_config = config['data']
train_config = config['train']
train_data = load_csv(data_config['train_path'])
vocab = CharVocab.from_data(train_data)
if ('load' in config['model']):
print('LOADING')
model = VAE_RNN.load(config['model']['load'])
vocab =... |
class BinPack(Environment[State]):
def __init__(self, generator: Optional[Generator]=None, obs_num_ems: int=40, reward_fn: Optional[RewardFn]=None, normalize_dimensions: bool=True, debug: bool=False, viewer: Optional[Viewer[State]]=None):
self.generator = (generator or RandomGenerator(max_num_items=20, max_... |
class GCNSyntheticPerturb(nn.Module):
def __init__(self, nfeat, nhid, nout, nclass, adj, dropout, beta, edge_additions=False):
super(GCNSyntheticPerturb, self).__init__()
self.adj = adj
self.nclass = nclass
self.beta = beta
self.num_nodes = self.adj.shape[0]
self.edge... |
def pascal_palette():
palette = {(0, 0, 0): 0, (128, 0, 0): 1, (0, 128, 0): 2, (128, 128, 0): 3, (0, 0, 128): 4, (128, 0, 128): 5, (0, 128, 128): 6, (128, 128, 128): 7, (64, 0, 0): 8, (192, 0, 0): 9, (64, 128, 0): 10, (192, 128, 0): 11, (64, 0, 128): 12, (192, 0, 128): 13, (64, 128, 128): 14, (192, 128, 128): 15, (... |
def first_el(x: Any) -> Any:
if is_listy(x):
return first_el(x[0])
if is_dict(x):
return first_el(x[list(x.keys())[0]])
return x |
def embed(*, header='', compile_flags=None, **kwargs):
config = kwargs.get('config')
if (config is None):
config = load_default_config()
config.InteractiveShellEmbed = config.TerminalInteractiveShell
kwargs['config'] = config
using = kwargs.get('using', 'sync')
if using:
... |
class mit_b4(Segformer_b0_b1):
def __init__(self, **kwargs):
super(mit_b4, self).__init__(num_classes=21, patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], d... |
class VoxelBackBone8x(nn.Module):
def __init__(self, model_cfg, input_channels, grid_size, **kwargs):
super().__init__()
self.model_cfg = model_cfg
norm_fn = partial(nn.BatchNorm1d, eps=0.001, momentum=0.01)
self.sparse_shape = (grid_size[::(- 1)] + [1, 0, 0])
self.conv_input... |
def particle_freq(s, tokens=None):
if (tokens == None):
tokens = word_tokenize(s)
pos = pos_tag(tokens)
particles = []
for [token, tag] in pos:
part = map_tag('en-ptb', 'universal', tag)
if (part == 'PRT'):
particles.append(token)
if (len(tokens) == 0):
re... |
def _get_items(split, mode):
file = kr.get_split_file(split, mode)
if ((split == 'benchmark') and (mode == 'test')):
return []
side2cam = {'l': 'image_02', 'r': 'image_03'}
lines = [line.split() for line in io.readlines(file)]
items = [{'seq': line[0].split('/')[0], 'drive': line[0].split('/... |
def _deep_fusion_fc_layers(num_layers, layer_sizes, input_rois, input_weights, fusion_method, l2_weight_decay, keep_prob, num_final_classes, box_rep, is_training):
if (l2_weight_decay > 0):
weights_regularizer = slim.l2_regularizer(l2_weight_decay)
else:
weights_regularizer = None
fusion_lay... |
class gpipe_encoder(nn.Module):
def __init__(self, model_name, **kwargs):
super(gpipe_encoder, self).__init__()
if ('MeSHProbeNet' in model_name):
self.net = MeSHProbeNet_encoder(**kwargs)
elif ('XMLCNN' in model_name):
self.net = XMLCNN_encoder(**kwargs)
elif... |
def gen_fixed_noise(noise, to_save):
gan_gen.eval()
autoencoder.eval()
fake_hidden = gan_gen(noise)
max_indices = autoencoder.generate(fake_hidden, args.maxlen, sample=args.sample)
with open(to_save, 'w') as f:
max_indices = max_indices.data.cpu().numpy()
for idx in max_indices:
... |
def run_seq(cfg, scene, seq):
print(' Start {}'.format(seq))
pcd_names = uio.list_files(osp.join(cfg.dataset_root, scene, seq), '*.ply', alphanum_sort=True)
if (cfg.threads > 1):
from joblib import Parallel, delayed
import multiprocessing
Parallel(n_jobs=cfg.threads)((delayed(comp... |
def save_model(model, optimizer, save_variable_list, args, before_finetune=False):
argparse_dict = vars(args)
with open(os.path.join(args.save_path, ('config.json' if (not before_finetune) else 'config_before.json')), 'w') as fjson:
json.dump(argparse_dict, fjson)
torch.save({**save_variable_list, '... |
def all_reg_init(y, delta_logp):
batch_size = y.shape[0]
return (y, delta_logp, jnp.zeros((batch_size, 1)), jnp.zeros((batch_size, 1)), jnp.zeros((batch_size, 1))) |
.parametrize('method', ['items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'popitem', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues', '__iter__', '__len__'])
def test_not_implemented(method, fbdict):
with pytest.raises(NotImplementedError):
getattr(fbdict, method)() |
def check_risk_budget(riskbudgets, n):
if (riskbudgets is None):
return
if (np.isnan(riskbudgets).sum() > 0):
raise ValueError('Risk budget contains missing values')
if ((np.array(riskbudgets) < 0).sum() > 0):
raise ValueError('Risk budget contains negative values')
if (n != len(... |
class MultiHeadAttention():
def __init__(self, n_head, d_model, dropout, mode=0):
self.mode = mode
self.n_head = n_head
self.d_k = self.d_v = d_k = d_v = (d_model // n_head)
self.dropout = dropout
if (mode == 0):
self.qs_layer = Dense((n_head * d_k), use_bias=Fals... |
def generate_parameter_dict(seed, config, end_time, with_log):
if with_log:
log_orders = True
exchange_log_orders = True
book_freq = 0
else:
log_orders = None
exchange_log_orders = None
book_freq = None
parameters = {'old': {'sha': 'f1968a56fdb55fd7c70be1db052... |
def build_dataset(cfg):
avai_datasets = DATASET_REGISTRY.registered_names()
check_availability(cfg.DATASET.NAME, avai_datasets)
if cfg.VERBOSE:
print('Loading dataset: {}'.format(cfg.DATASET.NAME))
return DATASET_REGISTRY.get(cfg.DATASET.NAME)(cfg) |
class ColorInfo():
def __init__(self):
self.mBaseColor = Color()
self.mIsBaseColorMode = True
self.mColorTableSize = 0
self.mOpacity = 0
self.mRangeMin = 0
self.mRangeMax = 255
self.mGammaCorrection = 1
self.mColorTableList: List[Color] = []
def se... |
class ReassembleBlocks(BaseModule):
def __init__(self, in_channels=768, out_channels=[96, 192, 384, 768], readout_type='ignore', patch_size=16, init_cfg=None):
super(ReassembleBlocks, self).__init__(init_cfg)
assert (readout_type in ['ignore', 'add', 'project'])
self.readout_type = readout_t... |
def copy_etomo_files(src, name, target):
if exists(join(src, (name + 'local.xf'))):
cp(join(src, (name + 'local.xf')), target)
cp(join(src, (name + '.xf')), target)
cp(join(src, 'eraser.com'), target)
cp(join(src, 'ctfcorrection.com'), target)
cp(join(src, 'tilt.com'), target)
cp(join(sr... |
def update_q(detectors_q, cost, r_detector_belief, r_accu_spam_beliefs, remain_reviews, lr1):
for (d, q) in detectors_q.items():
grad_sum = 0
for review in remain_reviews:
grad_sum += ((((- 1) * cost[review]) * r_detector_belief[review][d]) * expit((- r_accu_spam_beliefs[review])))
... |
class TFXGLMForCausalLM(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class SyntheticImagesDdpmCIFAR10(torch.utils.data.Dataset):
def __init__(self, src, labels):
self.src = src
self.labels = np.load(labels)
(self.nddpm, self.nIddpm) = (6002688, 9400000)
def sample_image(self, df, idx):
df.seek((idx * 3072))
image = np.array(np.frombuffer(d... |
class VideoModelGlobalCoordLatent(nn.Module):
def __init__(self, opt):
super(VideoModelGlobalCoordLatent, self).__init__()
self.nr_boxes = opt.num_boxes
self.nr_actions = opt.num_classes
self.nr_frames = opt.num_frames
self.img_feature_dim = opt.img_feature_dim
self.c... |
class Step3_DownloadText():
def __init__(self, GutenbergBookPersistenz: GutenbergBookPersistenz, savePath: str):
self.savePath = savePath
self.GutenbergBookPersistenz = GutenbergBookPersistenz
def run(self):
return DoneMarker(self.savePath).run(self.script)
def script(self):
... |
('/classify_url', methods=['GET'])
def classify_url():
imageurl = flask.request.args.get('imageurl', '')
try:
string_buffer = StringIO.StringIO(urllib.urlopen(imageurl).read())
image = caffe.io.load_image(string_buffer)
except Exception as err:
logging.info('URL Image open error: %s'... |
def string_to_tree(string):
if ((string[0] in IDCS) and (len(string) != 1)):
bracket_stack = []
tree = []
def add_brackets(num):
if (num == 2):
bracket_stack.extend(['}', '{', '}'])
else:
bracket_stack.extend(['}', '{', '}', '{', '}'])
... |
class FrameNetLoader(Loader):
def __init__(self):
super().__init__()
self.frame_set = set()
self.element_set = set()
def _load(self, path):
dataset = {}
sentence = []
frame = []
element = []
with open(path) as f:
for line in f:
... |
def get_Future3D_visual_path(cfg: DictConfig, id: str) -> dict:
path = os.path.join(cfg.data.future3d, id, 'image.jpg')
form = 'future3d-jpg'
return {'path': path, 'format': form} |
class TimeCondition(AbstractCondition):
def __init__(self, time):
super(TimeCondition, self).__init__()
self.time = time
def __call__(self, world, state, actor=None, prev_state=None):
return (state.t <= self.time)
def name(self):
return ('time_condition(%d)' % self.time) |
class TCNForecaster(BasePytorchForecaster):
def __init__(self, past_seq_len, future_seq_len, input_feature_num, output_feature_num, dummy_encoder=False, num_channels=([16] * 3), kernel_size=3, normalization=True, decomposition_kernel_size=0, repo_initialization=True, dropout=0.1, optimizer='Adam', loss='mse', lr=0.... |
def siamese_model():
input1 = (image_size_h_p, image_size_w_p, nchannels)
input2 = (image_size_h_c, image_size_w_c, nchannels)
left_input_P = Input(input1)
right_input_P = Input(input1)
left_input_C = Input(input2)
right_input_C = Input(input2)
convnet_plate = small_vgg(input1)
convnet_c... |
def get_patch_embed(**kwargs) -> nn.Module:
if (kwargs['conv_type'] == 'identity'):
return nn.Identity()
return PatchEmbed(**kwargs) |
class TestTorchOP(unittest.TestCase):
def setUpClass(self):
pass
def tearDownClass(self):
pass
def test_1(self):
n = Net()
example_in = torch.rand(3, 256)
traced_model = torch.jit.trace(n, example_in)
torch.jit.save(traced_model, '{}.pt'.format(file_name))
... |
class SharedParamsModalityHallucinationModel(nn.Module):
def __init__(self, opt):
super(SharedParamsModalityHallucinationModel, self).__init__()
self.opt = opt
self.conv = VGGTruncatedConv(opt)
self.hallucination_classifier = VGGHallucinationClassifier(opt)
self.rgb_classifie... |
def clean_up_tokenization(out_string):
out_string = out_string.replace(' .', '.').replace(' ?', '?').replace(' !', '!').replace(' ,', ',').replace(" ' ", "'").replace(" n't", "n't").replace(" 'm", "'m").replace(' do not', " don't").replace(" 's", "'s").replace(" 've", "'ve").replace(" 're", "'re")
return out_st... |
class FastExecutioner():
def __init__(self, progs, cells):
self.cells = cells
self.progs = progs
self.sortProgs()
def sortProgs(self):
for i in range(len(self.progs)):
self.progs[i] = self.progs[i].topologicalSort()
def execute(self):
maxLen = max([len(e) ... |
def is_video(ext: str):
allowed_exts = ('.mp4', '.webm', '.ogg', '.avi', '.wmv', '.mkv', '.3gp')
return any((ext.endswith(x) for x in allowed_exts)) |
class VGGTransformerModelTest_big(TestFairseqEncoderDecoderModelBase):
def setUp(self):
def override_config(args):
args.transformer_enc_config = '((1024, 16, 4096, True, 0.15, 0.15, 0.15),) * 3'
super().setUp()
extra_args_setter = [vggtransformer_2, override_config]
self.... |
class ShaConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bias=False, activation=(lambda : nn.ReLU(inplace=True)), activate=True, shared_conv=None):
super(ShaConvBlock, self).__init__()
self.activate = activate
if (shared... |
def test_elastic_net_coeffs():
(X, y) = make_classification(random_state=0)
alpha = 2
n_samples = 100
lambda_1 = (1 / (n_samples * alpha))
lambda_2 = (1 / (n_samples * alpha))
coeffs = list()
for penalty in ('elasticnet', 'l1', 'l2'):
if (penalty in ['l1', 'l2']):
lambda_... |
class TFDebertaForQuestionAnswering(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class ADALN1d(nn.Module):
def __init__(self, norm_nc, feature_nc):
super().__init__()
nhidden = 128
use_bias = True
self.mlp_shared = nn.Sequential(nn.Linear(feature_nc, nhidden, bias=use_bias), nn.ReLU())
self.mlp_gamma = nn.Linear(nhidden, norm_nc, bias=use_bias)
se... |
class SharedEncoder(super_sac.nets.Encoder):
def __init__(self, dim):
super().__init__()
self.fc0 = nn.Linear(dim, 128)
self.fc1 = nn.Linear(128, dim)
self._dim = dim
def embedding_dim(self):
return self._dim
def forward(self, obs_dict):
x = F.relu(self.fc0(ob... |
def dummy_raw_polygon_masks(size):
(num_obj, heigt, width) = size
polygons = []
for _ in range(num_obj):
num_points = ((np.random.randint(5) * 2) + 6)
polygons.append([np.random.uniform(0, min(heigt, width), num_points)])
return polygons |
def test_seg_recognizer():
tmp_dir = tempfile.TemporaryDirectory()
dict_file = osp.join(tmp_dir.name, 'fake_chars.txt')
_create_dummy_dict_file(dict_file)
label_convertor = dict(type='SegConvertor', dict_file=dict_file, with_unknown=False)
preprocessor = None
backbone = dict(type='ResNet31OCR', ... |
def check_kappa(kappa):
print(('Checking dim = 2, kappa = %f' % kappa))
vmf_diff = VmfDiff(100, 100)
dim = 2
print(('KL Guu %f' % KL_guu(kappa, dim)))
print(('KL Davidson %f' % KL_davidson(kappa, dim)))
samples = []
for i in range(0, 10000):
result = vmf_diff.sample_cell(torch.tensor... |
class ObjectListDataset(Dataset):
def __init__(self, obj_list_path, exp_dir):
super(ObjectListDataset, self).__init__()
with open(obj_list_path, 'r') as f:
obj_list = json.load(f)
summary_dir = os.path.join(exp_dir, 'summary')
exist_ids = [os.path.splitext(f)[0] for f in ... |
def mol2graph(smiles_batch: List[str], args: Namespace) -> BatchMolGraph:
mol_graphs = []
for smiles in smiles_batch:
if (smiles in SMILES_TO_GRAPH):
mol_graph = SMILES_TO_GRAPH[smiles]
else:
mol_graph = MolGraph(smiles, args)
if (not args.no_cache):
... |
class MBartTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
model_input_names = ['input_ids', 'attention_mask']
prefix_tokens: List[int] = []
suffix_tokens:... |
class ChatMessage(TypedDict):
role: str
content: str
name: Optional[str]
function_call: Optional[Dict] |
def train_model(cfg, model, dataloaders, loss_fns, optimizer, start_epoch=0, num_epochs=250, save_epochs=25, scheduler=None, mlog=None, flog=None):
checkpoint_dir = os.path.join(cfg['saving']['log_dir'], cfg['saving']['save_dir'])
run_kwargs = {'cfg': cfg, 'mlog': mlog, 'flog': flog, 'optimizer': optimizer, 'lo... |
class RandomHorizontalFlip(object):
def __init__(self, p=0.5):
self.p = p
def __call__(self, frames):
if (random.random() < self.p):
out_frames = []
for frame in frames:
out_frames.append(F.hflip(frame))
return out_frames
else:
... |
class NonLocalBlock2D(NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NonLocalBlock2D, self).__init__(in_channels, inter_channels=inter_channels, dimension=2, sub_sample=sub_sample, bn_layer=bn_layer) |
def White_Space_Remove_From_Word(word, filler_string=''):
white_space_removed_word = ''
for w in word.split():
if (w.strip() == ''):
continue
white_space_removed_word += (filler_string + w)
return white_space_removed_word |
def create_temporary_vocab_file(words, counts=None):
vocab_file = tempfile.NamedTemporaryFile()
if (counts is None):
for token in words:
vocab_file.write((token + '\n').encode('utf-8'))
else:
for (token, count) in zip(words, counts):
vocab_file.write('{}\t{}\n'.format... |
def xception_featurize(file):
model = Xception(include_top=True, weights='imagenet')
img_path = file
img = load_img(img_path, target_size=(299, 299))
x = img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
features = model.predict(x)
features = np.ndarray.flatten(feat... |
def loss_G_fn(P, D, options, images, gen_images):
d_gen = D(P.augment_fn(gen_images))
if (options['loss'] == 'nonsat'):
g_loss = F.softplus((- d_gen)).mean()
else:
g_loss = (- d_gen.mean())
return g_loss |
def make_disc_backbones(configs, cfg):
discs = []
for (i, c) in enumerate(configs):
(dim_in, dim_base, max_dim, num_layers, num_strides) = c
discs.append(ProjectionDiscriminator(dim_in=dim_in, dim_base=dim_base, max_dim=max_dim, num_layers=num_layers, num_strides=num_strides, dilate=False, no_ou... |
class MultiCorpusDataset(FairseqDataset):
def __init__(self, datasets: Dict[(str, FairseqDataset)], distribution: List[float], seed: int, sort_indices: bool=False, batch_sample: bool=False, distributed_rank: Optional[int]=None):
super().__init__()
assert isinstance(datasets, OrderedDict)
ass... |
class FlaxXLMRobertaForMultipleChoice(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def OutputCtm(utterance_id, edits_array, ctm_array):
global ctm_edits_out
assert (len(edits_array) == len(ctm_array))
channel = '1'
for i in range(len(edits_array)):
(hyp_word, ref_word) = edits_array[i]
(start_time, duration, hyp_word2, confidence) = ctm_array[i]
if (not (hyp_wo... |
class Subtokenizer(object):
def __init__(self, vocab_file, reserved_tokens=None):
tf.compat.v1.logging.info(('Initializing Subtokenizer from file %s.' % vocab_file))
if (reserved_tokens is None):
reserved_tokens = RESERVED_TOKENS
self.subtoken_list = _load_vocab_file(vocab_file, ... |
class CategoricalMLPModel(MLPModel):
def __init__(self, output_dim, name=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), output_nonlinearity=None, output_w_init=tf.initializers.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.