code stringlengths 101 5.91M |
|---|
def test_first_non_silent_sample_returns_correct_sample():
waveform = torch.zeros(1000)
waveform[500:] = 1.0
first_non_silent_sample = audio_utils.first_non_silent_sample(waveform, frame_size=100, hop_size=100)
assert (first_non_silent_sample == 500) |
class FiniteBernoulliBanditEpsilonGreedy(Agent):
def __init__(self, n_arm, a0=1, b0=1, epsilon=0.0):
self.n_arm = n_arm
self.epsilon = epsilon
self.prior_success = np.array([a0 for arm in range(n_arm)])
self.prior_failure = np.array([b0 for arm in range(n_arm)])
def set_prior(sel... |
def main(dataset_name, pca, cluster_method, lm_type, document_repr_type, random_state):
save_dict_data = {}
do_pca = (pca != 0)
save_dict_data['dataset_name'] = dataset_name
save_dict_data['pca'] = pca
save_dict_data['cluster_method'] = cluster_method
save_dict_data['lm_type'] = lm_type
save... |
class ViTMAEPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class AutoTokenizer():
def __init__(self):
raise EnvironmentError('AutoTokenizer is designed to be instantiated using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method.')
_list_option_in_docstrings(SLOW_TOKENIZER_MAPPING)
def from_pretrained(cls, pretrained_model_name_or_path... |
def convert_data_to_yaml(data, split, yaml, is_train=True, label=None, feature=None, qd_format=False, label_version=None, feature_version=None):
if qd_format:
info = {'feature': (feature if (feature is not None) else {'data': data, 'split': split, 't': 'feature', 'version': feature_version}), 'hw': {'data':... |
class ImportanceWeightedRiskEstimator(RiskEstimator):
def __init__(self, loss, dataset, *args):
super().__init__(loss)
self.N = len(dataset.test_idxs)
def estimate(self, predictions, observed, acq_weights):
l_i = self.loss(predictions, observed)
M = len(predictions)
R = (... |
class TrajInfo(AttrDict):
_discount = 1
def __init__(self, include_observations=False, **kwargs):
super().__init__(**kwargs)
self._include_observations = include_observations
if self._include_observations:
self.Observations = []
self.Length = 0
self.Return = 0... |
class LZ09_F7(LZ09):
def __init__(self, number_of_variables=10):
super(LZ09_F7, self).__init__(number_of_variables, dtype=3, ltype=21, ptype=21)
self.obj_directions = [self.MINIMIZE, self.MINIMIZE]
self.obj_labels = ['f(x)', 'f(y)']
def number_of_objectives(self) -> int:
return l... |
def time_to_string(time, frame_length):
n = round((time / frame_length))
assert (n >= 0)
return float_to_string((n * frame_length)) |
def test_constantbeta_dehnencore_in_nfw_Qoutofbounds():
if WIN32:
return None
pot = potential.NFWPotential(amp=2.3, a=1.3)
denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
betas = [0.25]
for (beta, dfh) in zip(betas, constantbeta_dfs_dehnencore_in_nfw):
assert numpy.... |
class SearchAlgo(ABC):
def __init__(self, task, world_model, action_agent, logger=None, seed=0, print_log=True, test_every_step=True, depth_limit=None) -> None:
self.task = task
self.world_model = world_model
self.action_agent = action_agent
self.states = []
self.logger = log... |
def main(opt):
loader = BatchLoaderUnk(opt.tokens, opt.data_dir, opt.batch_size, opt.seq_length, opt.max_word_l, opt.n_words, opt.n_chars)
opt.word_vocab_size = min(opt.n_words, len(loader.idx2word))
opt.char_vocab_size = min(opt.n_chars, len(loader.idx2char))
opt.max_word_l = loader.max_word_l
prin... |
def main():
with open('find_rocm_config.py', 'rb') as f:
data = f.read()
compressed = zlib.compress(data)
b64encoded = base64.b64encode(compressed)
with open('find_rocm_config.py.gz.base64', 'wb') as f:
f.write(b64encoded) |
class PathwiseGPR(GPR, PathwiseGPModel):
def __init__(self, *args, paths: AbstractSampler=None, **kwargs):
GPR.__init__(self, *args, **kwargs)
self._paths = paths
def generate_paths(self, num_samples: int, num_bases: int=None, prior: AbstractSampler=None, sample_axis: int=None, **kwargs) -> Comp... |
def count_word_freq():
d = {}
os.chdir('../../data/yelp')
(d, _) = count(d, 'valid.txt')
(d, filtered_sents_test) = count(d, 'test.txt')
sorted_d = sorted(d, key=d.get, reverse=True)
print('Len of trimmed vocab {}'.format(len(sorted_d)))
print('Num of Test samples after trimming {}'.format(l... |
def test_game_2048__get_action_mask(game_2048: Game2048, board: Board) -> None:
action_mask_fn = jax.jit(game_2048._get_action_mask)
action_mask = action_mask_fn(board)
expected_action_mask = jnp.array([False, True, True, True])
assert jnp.array_equal(action_mask, expected_action_mask) |
class TestBoxMode(unittest.TestCase):
def _convert_xy_to_wh(self, x):
return BoxMode.convert(x, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
def _convert_xywha_to_xyxy(self, x):
return BoxMode.convert(x, BoxMode.XYWHA_ABS, BoxMode.XYXY_ABS)
def _convert_xywh_to_xywha(self, x):
return BoxMode.... |
class LPIPSWithDiscriminator(nn.Module):
def __init__(self, disc_start, logvar_init=0.0, kl_weight=1.0, pixelloss_weight=1.0, disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0, perceptual_weight=1.0, use_actnorm=False, disc_conditional=False, disc_loss='hinge'):
super().__init__()
... |
def get_transform(point_cloud, is_training, bn_decay=None, K=3):
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
input_image = tf.expand_dims(point_cloud, (- 1))
net = tf_util.conv2d(input_image, 64, [1, 3], padding='VALID', stride=[1, 1], bn=True, is_training=... |
class AttentionNeuralCDE(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, static_dim=None, adjoint=True, run_backwards=True, sparsemax=False):
super(AttentionNeuralCDE, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.output_dim = output_... |
class VIDLoss(nn.Module):
'Variational Information Distillation for Knowledge Transfer (CVPR 2019),\n code from author:
def __init__(self, num_input_channels, num_mid_channel, num_target_channels, init_pred_var=5.0, eps=1e-05):
super(VIDLoss, self).__init__()
def conv1x1(in_channels, out_cha... |
class TrajectoryGraph(DiGraph):
def add_node(self, timed_state: TimedVehicleState, **attr):
super(TrajectoryGraph, self).add_node(node_for_adding=timed_state, **attr)
def check_node(self, node: TimedVehicleState):
if (node not in self.nodes):
raise ValueError(f'{node} not in graph!')... |
def train_alpha(model):
num_epochs = 100
batch_size = 4
nframes = 8
nframes_val = 32
size = (240, 432)
def image_read(path):
pic = Image.open(path)
transform = tv.transforms.Compose([tv.transforms.Resize(size, interpolation=Image.BILINEAR), tv.transforms.ToTensor(), tv.transforms... |
class SegmentableProperties(bpy.types.PropertyGroup):
category_name: bpy.props.StringProperty(name='Category Name', description='String name of the category.', default='')
category_color: bpy.props.FloatVectorProperty(name='Category Color', subtype='COLOR', description='Category color for segmentation.')
in... |
def create_textset(tokenizer, train_split, dev_split, name, path, bucketing, batch_size):
msg_list = []
if (name.lower() == 'librispeech'):
from dataset.librispeech import LibriTextDataset as Dataset
print('import LibriTextDataset as Dataset')
elif (name.lower() == 'aishell'):
from d... |
def get_lvis_22k_meta():
from .lvis_22k_categories import CATEGORIES
cat_ids = [k['id'] for k in CATEGORIES]
assert ((min(cat_ids) == 1) and (max(cat_ids) == len(cat_ids))), 'Category ids are not in [1, #categories], as expected'
lvis_categories = sorted(CATEGORIES, key=(lambda x: x['id']))
thing_cl... |
def test_save_load_and_predict():
fpath = 'tests/test_model_functioning/test_wd_model'
if (not os.path.exists(fpath)):
os.makedirs(fpath)
model = WideDeep(deeptabular=tabmlp)
trainer = Trainer(model, objective='binary', verbose=0)
trainer.fit(X_tab=X_tab, target=target, batch_size=16)
tr... |
class NpInfoDict(object):
def __init__(self, info_dict, key_type=None, value_type=None):
keys = sorted(list(info_dict.keys()))
self.key_arr = np.array(keys, dtype=key_type)
self.val_arr = np.array([info_dict[k] for k in keys], dtype=value_type)
self._key_idx_map = {k: i for (i, k) in... |
def load_pytorch_state_dict_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False, output_loading_info=False, _prefix=None, tf_to_pt_weight_rename=None):
import tensorflow as tf
from packaging.version import parse
if (parse(tf.__version__) >= parse('2.11.0')):
from keras imp... |
def minify(src_dir: str, dest_dir: str, n: int):
src_dir = Path(src_dir)
dest_dir = Path(dest_dir)
dest_dir.mkdir(exist_ok=True)
for path in src_dir.iterdir():
new = [x.rstrip() for x in list(path.open().readlines())][:n]
dest_path = dest_dir.joinpath(path.name)
print(dest_path)
... |
def running_mean(x, n):
cumsum = np.cumsum(np.insert(x, 0, 0))
return ((cumsum[n:] - cumsum[:(- n)]) / float(n)) |
def getPathGS(algo, inputEvents, tthread, NUM_ITEMS, NUM_ACCESS, key_skewness, window_ratio, window_size, transaction_length, isCyclic, complexity):
return (FILE_FOLER + '/WindowedGrepSum/{}/threads = {}/totalEvents = {}/{}_{}_{}_{}_{}_{}_{}_{}'.format(algo, tthread, inputEvents, NUM_ITEMS, 100, key_skewness, windo... |
class Stem(nn.Sequential):
def __init__(self, in_chs, out_chs, kernel_size=3, stride=4, pool='maxpool', num_rep=3, num_act=None, chs_decay=0.5, layers: LayerFn=None):
super().__init__()
assert (stride in (2, 4))
layers = (layers or LayerFn())
if isinstance(out_chs, (list, tuple)):
... |
def draw_level_failed():
global game_state
failed = bold_font3.render('Level Failed', 1, WHITE)
if ((level.number_of_birds <= 0) and ((time.time() - t2) > 5) and (len(pigs) > 0)):
game_state = 3
rect = pygame.Rect(300, 0, 600, 800)
pygame.draw.rect(screen, BLACK, rect)
screen... |
class Additive(Transform):
def fwd(z: torch.Tensor, mask: torch.Tensor, params) -> Tuple[(torch.Tensor, torch.Tensor)]:
mu = params
z = (z + mu).mul(mask.unsqueeze(2))
logdet = z.new_zeros(z.size(0))
return (z, logdet)
def bwd(z: torch.Tensor, mask: torch.Tensor, params) -> Tuple... |
_materialize('core')
class LeakyReLU(ElementWiseUnaryOp):
in_dtypes = [(i,) for i in DTYPE_GEN_FLOATS]
out_dtypes = [(i,) for i in DTYPE_GEN_FLOATS]
def __init__(self):
'See
super().__init__()
self.negative_slope = 0.01 |
def file_lines_to_list(path):
with open(path) as f:
content = f.readlines()
content = [x.strip() for x in content]
return content |
class NormFreeBlock(nn.Module):
def __init__(self, in_chs, out_chs=None, stride=1, dilation=1, first_dilation=None, alpha=1.0, beta=1.0, bottle_ratio=0.25, group_size=None, ch_div=1, reg=True, extra_conv=False, skipinit=False, attn_layer=None, attn_gain=2.0, act_layer=None, conv_layer=None, drop_path_rate=0.0):
... |
class AssignResult(util_mixins.NiceRepr):
def __init__(self, num_gts, gt_inds, max_overlaps, labels=None):
self.num_gts = num_gts
self.gt_inds = gt_inds
self.max_overlaps = max_overlaps
self.labels = labels
def num_preds(self):
return len(self.gt_inds)
def info(self):... |
def get_nvidia_driver_version(run_lambda):
if (get_platform() == 'darwin'):
cmd = 'kextstat | grep -i cuda'
return run_and_parse_first_match(run_lambda, cmd, 'com[.]nvidia[.]CUDA [(](.*?)[)]')
smi = get_nvidia_smi()
return run_and_parse_first_match(run_lambda, smi, 'Driver Version: (.*?) ') |
def findFileOrThrow(strBasename):
if os.path.isfile(strBasename):
return strBasename
LOCAL_FILE_DIR = ('data' + os.sep)
GLOBAL_FILE_DIR = (((os.path.dirname(os.path.abspath(__file__)) + os.sep) + 'data') + os.sep)
strFilename = (LOCAL_FILE_DIR + strBasename)
if os.path.isfile(strFilename):
... |
def saveAsMat(img, filename, matlab_id, mat_dict=None):
assert (img.ndim in [2, 3, 4])
img_normalized = img.copy()
if (img.ndim == 3):
img_normalized = np.transpose(img_normalized, (1, 2, 0))
elif (img.ndim == 4):
img_normalized = np.transpose(img_normalized, (2, 3, 0, 1))
if (mat_di... |
class cityscapesDataSetStrongWeakAug(data.Dataset):
def __init__(self, data_root, data_list, max_iters=None, num_classes=19, split='train', ignore_label=255, debug=False, cfg=None, logger=None):
self.split = split
self.NUM_CLASS = num_classes
self.data_root = data_root
self.data_list... |
def write_to_gsheets_contact(df, ks_output, sheet_name='Contact Info', service_file='creds.json'):
d = df[ks_output].fillna('')
print('writing to gsheets...')
gc = pygsheets.authorize(service_file=service_file)
sh = gc.open(sheet_name)
wks = sh[0]
wks.update_value('A1', 'Last updated Apr 14')
... |
class FNetForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class AssignResult(util_mixins.NiceRepr):
def __init__(self, num_gts, gt_inds, max_overlaps, labels=None):
self.num_gts = num_gts
self.gt_inds = gt_inds
self.max_overlaps = max_overlaps
self.labels = labels
self._extra_properties = {}
def num_preds(self):
return l... |
class ContextPath(nn.Module):
def __init__(self, norm_layer=nn.BatchNorm2d):
super(ContextPath, self).__init__()
inter_channels = 128
self.global_context = _GlobalAvgPooling(512, inter_channels, norm_layer)
self.arms = nn.ModuleList([AttentionRefinmentModule(512, inter_channels, norm... |
def load_conversations(fileName, lines, fields=['character1ID', 'character2ID', 'movieID', 'utteranceIDs'], delimiter=' +++$+++ '):
conversations = []
with open(fileName, 'r', encoding='iso-8859-1') as f:
for line in f:
values = line.split(delimiter)
convObj = {}
for ... |
def flatten(unflattened, parent_key='', separator='.'):
items = []
for (k, v) in unflattened.items():
if (separator in k):
raise ValueError('Found separator ({}) from key ({})'.format(separator, k))
new_key = (((parent_key + separator) + k) if parent_key else k)
if (isinstanc... |
class IterTimerHook(Hook):
def before_epoch(self, runner):
self.t = time.time()
def before_iter(self, runner):
runner.log_buffer.update({'data_time': (time.time() - self.t)})
def after_iter(self, runner):
runner.log_buffer.update({'time': (time.time() - self.t)})
self.t = tim... |
def feature_cols(column_info):
return ((((column_info['wide_base_cols'] + column_info['wide_cross_cols']) + column_info['indicator_cols']) + column_info['embed_cols']) + column_info['continuous_cols']) |
def load_ade20k(path, max_classes=None, random_state=None):
return {'train': ADE20K(path, 'training', max_classes=max_classes), 'val': ADE20K(path, 'validation', max_classes=max_classes)} |
def seq_linear(linear, x):
(batch, hidden_size, length, _) = x.size()
h = linear(torch.transpose(x, 1, 2).contiguous().view((batch * length), hidden_size))
return torch.transpose(h.view(batch, length, hidden_size, 1), 1, 2) |
def paths(graph, id1, id2, length=4, path=[], _root=True):
if (len(path) >= length):
return []
if (id1 not in graph):
return []
if (id1 == id2):
return [(path + [id1])]
path = (path + [id1])
p = []
s = set(path)
for node in graph[id1].links:
if (node.id not in... |
def start_recording(recording_path, env_name):
unique_id = str(int(time.time()))
screens_dir = os.path.join(recording_path, 'screens', '{}'.format(env_name), unique_id)
trajectories_dir = os.path.join(recording_path, 'trajectories_pressed_buttons', '{}'.format(env_name))
os.makedirs(screens_dir)
os.... |
class TestBoxInstDataPreprocessor(TestCase):
def test_forward(self):
processor = BoxInstDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1])
data = {'inputs': [torch.randint(0, 256, (3, 256, 256))], 'data_samples': [DetDataSample()]}
out_data = processor(data)
(batch_inputs, batch_data_sa... |
class ResNet(nn.Module):
def __init__(self, depth, num_classes=1000):
super(ResNet, self).__init__()
assert (((depth - 2) % 6) == 0), 'depth should be 6n+2'
block = (Bottleneck if (depth >= 44) else BasicBlock)
n = (((depth - 2) // 9) if (depth >= 44) else ((depth - 2) // 6))
... |
class LowerBoundedExponentialLR(_LRScheduler):
def __init__(self, optimizer, gamma, lower_bound, last_epoch=(- 1)):
self.gamma = gamma
self.lower_bound = lower_bound
super(LowerBoundedExponentialLR, self).__init__(optimizer, last_epoch)
def _get_lr(self, base_lr):
lr = (base_lr *... |
class FocalLoss(tf.Module):
def __init__(self, gamma=2.0, alpha=0.25, loss_weight=1.0):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
self.loss_weight = loss_weight
def __call__(self, pred, target, weight=None, avg_factor=None):
pred_sigmoid = tf... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, is_last=False):
super(Bottleneck, self).__init__()
self.is_last = is_last
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(plane... |
def main(_):
if (not FLAGS.dataset_dir):
raise ValueError('You must supply the dataset directory with --dataset_dir')
tf.logging.set_verbosity(tf.logging.INFO)
with tf.Graph().as_default():
deploy_config = model_deploy.DeploymentConfig(num_clones=FLAGS.num_clones, clone_on_cpu=FLAGS.clone_on... |
class T5Config(PretrainedConfig):
model_type = 't5'
keys_to_ignore_at_inference = ['past_key_values']
def __init__(self, vocab_size=32128, d_model=512, d_kv=64, d_ff=2048, num_layers=6, num_decoder_layers=None, num_heads=8, relative_attention_num_buckets=32, dropout_rate=0.1, layer_norm_epsilon=1e-06, initi... |
def _chunked_iterator(i: Iterable, chunk_size: int, drop_last: bool):
chunks = more_itertools.chunked(i, chunk_size)
if drop_last:
return (chunk for chunk in chunks if (len(chunk) == chunk_size))
else:
return chunks |
def train_one_epoch(train_loader, model, criterion, optimizer, epoch, opt, num_train_samples, no_acc_eval=False):
info = {}
losses = AverageMeter('Loss ', ':6.4g')
top1 = AverageMeter(' ', ':6.2f')
top5 = AverageMeter(' ', ':6.2f')
model.train()
lr_scheduler = global_utils.LearningRateScheduler(... |
class Rasterizer(Combinator):
def combine(self, data: List[np.ndarray]) -> np.ndarray:
image_shape = data[0].shape
base_image = np.zeros(image_shape).astype('uint8')
return reduce(add_foreground_to_image, ([base_image] + data)) |
def convHuge(c, **kargs):
return n.LeNet([(128, 3, 3, 1), (128, 4, 4, 1), (256, 3, 3, 1), (256, 4, 4, 1)], [512, 512, c], padding=1, normal=True, bias=False, last_lin=True, **kargs) |
def save_training_logs(results_paths, mlog):
step_num_set = set()
for results_path in results_paths:
print(f'logging {results_path}')
try:
results = read_logs(results_path)
except Exception as e:
print(f'Could not read {results_path}. could be empty', e)
... |
class ACFPN(object):
__shared__ = ['norm_type', 'freeze_norm']
def __init__(self, num_chan=256, min_level=2, max_level=6, spatial_scale=[(1.0 / 32.0), (1.0 / 16.0), (1.0 / 8.0), (1.0 / 4.0)], has_extra_convs=False, norm_type=None, freeze_norm=False, use_c5=True, norm_groups=32):
self.freeze_norm = freez... |
def pattern_registry(pattern_type):
def decorator_pattern(cls):
if (pattern_type in PATTERNS):
raise ValueError('Cannot have two patterns with the same name')
PATTERNS[pattern_type] = cls
return cls
return decorator_pattern |
_canonicalize
_specialize
_optimizer([BernoulliOp])
def replace_bernoulli_op(node):
if (not isinstance(node.op, BernoulliOp)):
return False
prob = node.inputs[0]
noise = node.inputs[1]
samples = (noise < prob).astype(floatX)
return [samples] |
def main():
env = RacecarGymEnv(renders=True, isDiscrete=True)
act = deepq.load('racecar_model.pkl')
print(act)
while True:
(obs, done) = (env.reset(), False)
print('')
print('obs')
print(obs)
episode_rew = 0
while (not done):
env.render()
... |
class TestQubit(QiskitTestCase):
def test_default(self):
qubit = Qubit(1, DriveChannel(2), MeasureChannel(4), AcquireChannel(5), control_channels=[ControlChannel(3)])
self.assertEqual(qubit.drive, DriveChannel(2))
self.assertEqual(qubit.controls[0], ControlChannel(3))
self.assertEqua... |
class CifarResNeXt(nn.Module):
def __init__(self, cardinality, depth, num_classes, widen_factor=4, dropRate=0):
super(CifarResNeXt, self).__init__()
self.cardinality = cardinality
self.depth = depth
self.block_depth = ((self.depth - 2) // 9)
self.widen_factor = widen_factor
... |
def make_json(max_block=1):
with open('conf/rigidcloth/absparse/multi.json', 'r') as f:
config = json.load(f)
cube = config['obstacles'][0]
ground = config['obstacles'][1]
single_length = 0.1
one_dif = (single_length + 0.001)
ini_size = single_length
ini_x = (- 4)
ini_y = (- 4)
... |
def calc_metrics_for_dataset(ctx, metrics, real_data_path, fake_data_path, mirror, resolution, gpus, verbose, use_cache: bool, num_runs: int, seed: int):
dnnlib.util.Logger(should_flush=True)
args = dnnlib.EasyDict(metrics=metrics, num_gpus=gpus, seed=seed, verbose=verbose)
if (not all((metric_main.is_valid... |
def synthesize_audio(model, waveglow, denoiser, inp, lab=None, strength=0.0):
assert (inp.size(0) == 1)
inp = inp.cuda()
if (lab is not None):
lab = torch.LongTensor(1).cuda().fill_(lab)
with torch.no_grad():
(_, mel, _, ali, has_eos) = model.inference(inp, lab, ret_has_eos=True)
... |
class MineNetwork(nn.Module):
def __init__(self, x_dim, z_dim, width, loss='mine', alpha=0.01, method=None):
super().__init__()
self.running_mean = 0
self.loss = loss
self.alpha = alpha
self.method = method
T = Seq(x_dim, z_dim, width)
if (method == 'concat'):... |
def get_tagged_data_for_query(data):
dataset = data['query-split']
if (args.split is not None):
if (str(args.split) == str(dataset)):
dataset = 'test'
else:
dataset = 'train'
for sent_info in data['sentences']:
if (not args.query_split):
dataset = ... |
_start_docstrings('\n CamemBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a\n softmax) e.g. for RocStories/SWAG tasks.\n ', CAMEMBERT_START_DOCSTRING)
class TFCamembertForMultipleChoice(TFRobertaForMultipleChoice):
config_class = CamembertConfig |
def BN(x, phase_BN, scope):
return tf.layers.batch_normalization(x, momentum=0.9, training=phase_BN) |
class COLA(AbstractTask):
name = 'cola'
labels_list = ['0', '1']
metric = [metrics.matthews_corrcoef]
metric_names = ['matthews_correlation']
split_to_data_split = {'train': 'train', 'validation': 'validation', 'test': 'validation'}
def load_dataset(self, split):
return datasets.load_dat... |
def feature_descriptions(max_num_entities):
return {'image': tf.FixedLenFeature((IMAGE_SIZE + [3]), tf.string), 'mask': tf.FixedLenFeature((([max_num_entities] + IMAGE_SIZE) + [1]), tf.string)} |
class MultiHeadAttention(nn.Module):
def __init__(self, hidden_size, num_attention_heads, attention_probs_dropout_prob):
super().__init__()
if ((hidden_size % num_attention_heads) != 0):
raise ValueError(f'The hidden size {(hidden_size,)} is not a multiple of the number of attention head... |
def parse_model_dir(model_dir):
if (model_dir and model_dir.startswith('dbfs:/')):
model_dir = ('/dbfs/' + model_dir[len('dbfs:/'):])
return model_dir |
class AllInOneEnv(gym.Env):
def __init__(self, ns: str, robot_yaml_path: str, settings_yaml_path: str, reward_fnc: str, safe_dist: float=None, goal_radius: float=0.1, max_steps_per_episode=1000, train_mode: bool=True, debug: bool=False, paths: dict=None, drl_server: str=None, evaluation: bool=False, evaluation_epis... |
def outer(vector1, vector2=None):
if (vector2 is None):
vector2 = np.array(vector1).conj()
else:
vector2 = np.array(vector2).conj()
return np.outer(vector1, vector2) |
def apply_lights_manager(args, light_manager):
if (args.lights is None):
return
light_group = 'None'
if (args.lightgroup is not None):
light_group = args.lightgroup
lights = light_manager.get_all_lights(LIGHT_GROUP[light_group][0])
i = 0
while (i < len(args.lights)):
opti... |
class GetLayerName(object):
_name_count = {}
def get(cls, name_prefix):
cnt = cls._name_count.get(name_prefix, 0)
cls._name_count[name_prefix] = (cnt + 1)
return (name_prefix + str(cnt)) |
class Embeeding_Attn(nn.Module):
def __init__(self):
super(Embeeding_Attn, self).__init__()
self.max_len = 3
self.input_dim = 1824
self.hidden_dim = 150
self.bidirectional = True
self.drop_out_rate = 0.5
self.context_vector_size = [parameters['embedding_contex... |
class FeatureAdaption(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, deformable_groups=4):
super(FeatureAdaption, self).__init__()
offset_channels = ((kernel_size * kernel_size) * 2)
self.conv_offset = nn.Conv2d(in_channels, (deformable_groups * offset_channels), 1,... |
def _make_optimizer(args, model):
logger.info(f'Using {args.optim} Optimizer ......')
if (args.optim == 'adam'):
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
elif (args.optim == 'adamw'):
optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight... |
class PegasusXForConditionalGeneration(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def quaddobl_ismember_filter(wsys, gpts, dim, points, rcotol=1e-06, evatol=1e-06, memtol=1e-06, verbose=True, tasks=0):
from phcpy.solutions import diagnostics
result = []
for point in points:
rco = diagnostics(point)[1]
if (rco > rcotol):
(isgood, ismember) = (True, False)
... |
def load_model(model, path):
if isinstance(model, DataParallel):
model.module.load_state_dict(torch.load(path))
else:
model.load_state_dict(torch.load(path)) |
_loss
def quality_focal_loss_tensor_target(pred, target, beta=2.0, activated=False):
assert (pred.size() == target.size())
if activated:
pred_sigmoid = pred
loss_function = F.binary_cross_entropy
else:
pred_sigmoid = pred.sigmoid()
loss_function = F.binary_cross_entropy_with_... |
class KittiDataCountLeftTest(data_testing_lib.BaseVTABDataTest):
def setUp(self):
super(KittiDataCountLeftTest, self).setUp(data_wrapper=kitti.KittiData(task='count_left'), num_classes=16, expected_num_samples=dict(train=6347, val=423, trainval=6770, test=711, train800val200=1000, train800=800, val200=200),... |
(name='load_mock')
def _load_mock(monkeypatch: MonkeyPatch, mock_data_1: pd.DataFrame) -> MagicMock:
load_mock = MagicMock(return_value=mock_data_1)
monkeypatch.setattr(cache.dataframe_utils, 'load_df', load_mock)
return load_mock |
def phc_email(addrs, subject, msg_cont):
import smtplib
from email.mime.text import MIMEText
from phc_config import phcstmp, phcmail, phcmailps
msg = MIMEText(msg_cont)
msg['Subject'] = subject
msg['To'] = addrs
server = smtplib.SMTP(phcstmp)
server.starttls()
server.login(phcmail, p... |
def train_unsupervised(args):
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
if (args.dataset == 'Kitti'):
train_dataset = KittiOdometrySceneflow(root=args.root, npoints=args.npoints, max_bias=args.max_bias)
elif (args.dataset == 'nuscenes'):
scenes_list = './data/nuscenes_trainlist.txt'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.