code stringlengths 101 5.91M |
|---|
def create_dataset(trainset_file, devset_file, device, vocab_size=None, embed_type=None, embed_dir=None):
return CoQADataset(trainset_file, devset_file, vocab_size=vocab_size, device=device, embed_type=embed_type, embed_dir=embed_dir) |
def parse_args():
parser = argparse.ArgumentParser('Sample (with beam-search) from the session model')
parser.add_argument('--ignore-unk', action='store_false', help='Disables the generation of unknown words (<unk> tokens)')
parser.add_argument('model_prefix', help='Path to the model prefix (without _model.... |
def lrelu(x, a):
with tf.name_scope('lrelu'):
x = tf.identity(x)
return (((0.5 * (1 + a)) * x) + ((0.5 * (1 - a)) * tf.abs(x))) |
class ActivationStats(HookCallback):
def on_train_begin(self, **kwargs):
super().on_train_begin(**kwargs)
self.stats = []
def hook(self, m: nn.Module, i: Tensors, o: Tensors) -> Tuple[(Rank0Tensor, Rank0Tensor)]:
return (o.mean().item(), o.std().item())
def on_batch_end(self, train, ... |
def main():
print('\nTesting the Pieri homotopies ...\n')
test_pieri()
print('\nTesting the Littlewood-Richardson homotopies ...')
test_lrhom() |
def get_angle(a, b, c):
ang = math.degrees((math.atan2((c[1] - b[1]), (c[0] - b[0])) - math.atan2((a[1] - b[1]), (a[0] - b[0]))))
ang = ((ang + 360) if (ang < 0) else ang)
return (ang if (ang < 180) else (360 - ang)) |
def calc_metrics(tp, p, t, percent=False):
precision = ((tp / p) if p else 0)
recall = ((tp / t) if t else 0)
fb1 = ((((2 * precision) * recall) / (precision + recall)) if (precision + recall) else 0)
if percent:
return ((100 * precision), (100 * recall), (100 * fb1))
else:
return (p... |
def train_dev_test_split(dialogs):
n_dial = len(dialogs)
random.shuffle(dialogs)
dataset = {'train': dialogs[:int((n_dial * 0.8))], 'dev': dialogs[int((n_dial * 0.8)):int((n_dial * 0.9))], 'test': dialogs[int((n_dial * 0.9)):]}
return dataset |
def get_world_size(group):
if use_xla():
assert (group[0] == 'tpu')
my_group = _find_my_group(group[1])
return len(my_group)
elif torch.distributed.is_initialized():
return dist.get_world_size(group=group)
else:
return 1 |
class TestCategoricalLSTMPolicy(TfGraphTestCase):
def test_invalid_env(self):
env = GarageEnv(DummyBoxEnv())
with pytest.raises(ValueError):
CategoricalLSTMPolicy(env_spec=env.spec)
.parametrize('obs_dim, action_dim, hidden_dim, obs_type', [((1,), 1, 4, 'discrete'), ((2,), 2, 4, 'dis... |
def set_weights(full_name, module, fsq_value, hf_weight_path):
hf_weight = access_by_string(module, hf_weight_path)
hf_value = hf_weight.data
if (fsq_value.shape != hf_value.shape):
raise ValueError(f'{full_name} has size {fsq_value.shape}, but {hf_value.shape} was found.')
hf_weight.data = fsq_... |
def pytorch2onnx(config_path, checkpoint_path, input_img, input_shape, opset_version=11, show=False, output_file='tmp.onnx', verify=False, normalize_cfg=None, dataset='coco', test_img=None, do_simplify=False, cfg_options=None):
input_config = {'input_shape': input_shape, 'input_path': input_img, 'normalize_cfg': no... |
class LiftingSurface():
def __init__(self, p: bullet_client.BulletClient, physics_period: float, np_random: np.random.RandomState, uav_id: int, surface_id: int, lifting_unit: np.ndarray, forward_unit: np.ndarray, Cl_alpha_2D: float, chord: float, span: float, flap_to_chord: float, eta: float, alpha_0_base: float, a... |
def add_emerging_index(df, col_name='emerging_index', target_days=[1, 2, 3], n_days_past=3, min_deaths=20, new_deaths=True):
past_cols = df.filter(regex='#Deaths_').columns[(- (n_days_past + 1)):].tolist()
pred_cols = [f'Predicted Deaths {day}-day' for day in target_days]
assert set(pred_cols).issubset(df.c... |
def count_summary(sequence: List[E]) -> str:
return ', '.join(['{}: {}'.format(tag, count) for (tag, count) in Counter(sequence).most_common()]) |
class unet(nn.Module):
def __init__(self, n_classes, n_channels=14, bilinear=True):
super(unet, self).__init__()
self.n_channels = n_channels
self.n_classes = n_classes
self.bilinear = bilinear
self.inc = DoubleConv(n_channels, 64)
self.down1 = Down(64, 128)
s... |
def test_multiple_files_scene_path():
dataset_config = get_config(CFG_MULTI_TEST).DATASET
if (not PointNavDatasetV1.check_config_paths_exist(dataset_config)):
pytest.skip('Test skipped as dataset files are missing.')
scenes = PointNavDatasetV1.get_scenes_to_load(config=dataset_config)
assert (le... |
class GlobalContextTest(unittest.TestCase):
def test_config_master_port(self):
ctx = Context.singleton_instance()
ctx.config_master_port(50001)
self.assertEqual(ctx.master_port, 50001)
os.environ['HOST_PORTS'] = '20000,20001,20002,20003'
ctx.config_master_port(0)
self... |
class GegenbauerPolynomials(torch.nn.Module):
def __init__(self, alpha, n):
super().__init__()
self.alpha = alpha
self.n = n
self.coefficients = self.compute_coefficients()
self.powers = torch.arange(0.0, (self.n + 1.0), dtype=dtype, device=device)
def compute_coefficient... |
.parametrize('bandwidth', [(1.5 / 4), (1 / 8)])
.parametrize('discretization_parameter', [4, 8, 16])
def test_tree_parameters__creation(bandwidth: float, discretization_parameter: int) -> None:
tree_params = TreeParameters.construct(bandwidth=bandwidth, discretization_parameter=discretization_parameter)
assert ... |
def get_logits(args, size, bias, bias_start=0.0, scope=None, mask=None, wd=0.0, input_keep_prob=1.0, is_train=None, func=None, reuse=False):
if (func is None):
func = 'sum'
if (func == 'sum'):
return sum_logits(args, mask=mask, name=scope)
elif (func == 'linear'):
return linear_logit... |
class DFE(nn.Module):
def __init__(self, in_channels, mid_channels):
super().__init__()
self.fe = nn.Sequential(*[DRB(in_channels), DB(in_channels, mid_channels, offset_channels=32)])
def forward(self, x):
out = self.fe(x)
return out |
_HEADS.register('SingleConvRPNHead')
class RPNHead(nn.Module):
def __init__(self, cfg, in_channels, num_anchors):
super(RPNHead, self).__init__()
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
self.cls_logits = nn.Conv2d(in_channels, num_anchors, kernel_s... |
def get_media_info(media_path):
assert os.path.isfile(media_path), f'The media file does not exist: "{media_path}"'
probe = ffmpeg.probe(media_path)
video_stream = next((stream for stream in probe['streams'] if (stream['codec_type'] == 'video')), None)
width = int(video_stream['width'])
height = int... |
class Writer():
def __init__(self, save_dir):
self.save_dir = Path(save_dir)
self.log_mjson_file = None
self.summary_writter = None
self.metrics = []
self._text_current_gstep = (- 1)
self._tb_texts = []
def open(self):
save_dir = self.save_dir
asse... |
def concatenate(*mats: CSXMatrix3d, device=None):
device = (mats[0].device if (device is None) else device)
mat_type = type(mats[0])
mat_h = mats[0].shape[1]
mat_w = mats[0].shape[2]
batch_size = 0
indptr_offset = 0
indices = []
indptr = []
data = []
for mat in mats:
asse... |
class SGDTorch(SGD):
_get_updates_support
def get_updates(self, loss, params):
grads = self.get_gradients(loss, params)
self.updates = [K.update_add(self.iterations, 1)]
lr = self.lr
if (self.initial_decay > 0):
lr *= (1.0 / (1.0 + (self.decay * K.cast(self.iterations... |
def main(opt):
translator = build_translator(opt, report_score=False)
translator.translate(data_path=opt.data, batch_size=opt.batch_size, attn_debug=opt.attn_debug) |
class OpenAIGPTLMHeadModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def mlp_mixer_s32(num_classes: int, image_size: int=224, channels: int=3):
params = dict(patch_size=32, num_layers=8, hidden_dim=512, tokens_hidden_dim=256, channels_hidden_dim=2048)
return MLPMixer(num_classes, image_size, channels, **params) |
def rank_roidb_ratio(roidb):
ratio_large = 2
ratio_small = 0.5
ratio_list = []
for i in range(len(roidb)):
width = roidb[i]['width']
height = roidb[i]['height']
ratio = (width / float(height))
if (ratio > ratio_large):
roidb[i]['need_crop'] = 1
rat... |
class MultiCADopt():
dir_name: str
task_name: str
class MultiCADargs():
n_nodes: int
input_step: int
batch_size: int
dy_dim: int
total_epoch: int
update_every: int
show_graph_every: int
class data_pred():
model: str
mult... |
def linear_attention_normalization(q, k, causal=False):
if (not causal):
return torch.einsum('...nm,...m->...n', q, k.sum(dim=(- 2)))
else:
return torch.einsum('...nm,...nm->...n', q, k.cumsum(dim=(- 2))) |
class TestLossMetric(Metric):
def __init__(self, criterion, train=False):
self.criterion = criterion
self.main_metric_name = 'loss_value'
super().__init__(name='Loss', train=False)
def compute_metric(self, outputs: torch.Tensor, labels: torch.Tensor, top_k=(1,)):
loss = None
... |
.skipif((not baseline_installed), reason='baseline sub-module not installed')
def test_simple_agents():
config_env = habitat.get_config(config_paths=CFG_TEST)
if (not os.path.exists(config_env.SIMULATOR.SCENE)):
pytest.skip('Please download Habitat test data to data folder.')
benchmark = habitat.Ben... |
def hash_clustering(clustering):
clustering = [list(v) for v in clustering]
for i in range(len(clustering)):
clustering[i].sort()
clustering[i] = tuple(clustering[i])
clustering.sort()
return tuple(clustering) |
def lifetime(m, Z):
lm = np.log10(m)
a0 = (3.79 + (0.24 * Z))
a1 = ((- 3.1) - (0.35 * Z))
a2 = (0.74 + (0.11 * Z))
tmp = ((a0 + (a1 * lm)) + ((a2 * lm) * lm))
return np.divide(np.power(10, tmp), 1000) |
def decode_predictions(preds, top_n=5):
assert ((len(preds.shape) == 2) and (preds.shape[1] == 50))
results = []
for pred in preds:
result = zip(TAGS, pred)
result = sorted(result, key=(lambda x: x[1]), reverse=True)
results.append(result[:top_n])
return results |
def get():
print(('Python Interpreter version:%s' % sys.version[:3]))
print(('tensorflow version:%s' % tf.__version__))
print(('numpy version:%s' % np.__version__))
return FLAGS |
class NNModel(JavaTransformer, MLWritable, MLReadable, HasFeaturesCol, HasPredictionCol, HasBatchSize, HasSamplePreprocessing, JavaValue):
def __init__(self, model, feature_preprocessing=None, jvalue=None, bigdl_type='float'):
super(NNModel, self).__init__()
if jvalue:
invalidInputError(... |
class TextModeTestClass(nn.Module):
def __init__(self):
super(TextModeTestClass, self).__init__()
self.word_embed = nn.Embedding(5, 16, padding_idx=0)
self.rnn = nn.LSTM(16, 8, batch_first=True)
self.linear = nn.Linear(8, 1)
def forward(self, X):
embed = self.word_embed(X... |
def update_plot(losses, prefix):
for key in ['loss', 'cls_loss', 'reg_loss']:
plotter.update(f'{prefix}_{key}', losses[key].item()) |
def convnet(input, output, dropout_rate=0.0, input_shape=(1, 28, 28), batch_size=100, l2_rate=0.001, nb_epoch=12, img_rows=28, img_cols=28, nb_filters=64, pool_size=(2, 2), kernel_size=(3, 3), activations='relu', constrain_norm=False):
const = (maxnorm(2) if constrain_norm else None)
state = Convolution2D(nb_fi... |
.script
def hard_mish_jit(x, inplace: bool=False):
return ((0.5 * x) * (x + 2).clamp(min=0, max=2)) |
class Conv1x1Branch(nn.Module):
def __init__(self, in_channels, out_channels):
super(Conv1x1Branch, self).__init__()
self.conv = incept_conv1x1(in_channels=in_channels, out_channels=out_channels)
def forward(self, x):
x = self.conv(x)
return x |
def validate(val_loader, model, criterion, epoch, args, log=None, tf_writer=None, flag='val'):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('', ':6.2f')
model.eval()
all_preds = []
all_targets = []
with torch.no_grad():
end = ti... |
def expand_dims(array, axis):
if is_numpy_array(array):
return np.expand_dims(array, axis)
elif is_torch_tensor(array):
return array.unsqueeze(dim=axis)
elif is_tf_tensor(array):
import tensorflow as tf
return tf.expand_dims(array, axis=axis)
elif is_jax_tensor(array):
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--audio-manifest', '-i', required=True, type=str, help='path to the input manifest.')
parser.add_argument('--output-dir', '-o', required=True, type=str, help='path to the output dir. it will contain files after denoising and vad')
parse... |
def build_model(input_shape, out_dim, activation=tf.keras.layers.LeakyReLU):
filters = 32
def middle_stack(x, activation):
x = _res_block(x, filters=filters, num_blocks=3, strides=2, name='res32', activation=activation)
x = _res_block(x, filters=(filters * 2), num_blocks=3, strides=2, name='res6... |
def main(args):
if (args.dataset == 'mr'):
(train_x, train_y) = dataloader.read_corpus('/data/medg/misc/jindi/nlp/datasets/mr/train.txt')
(test_x, test_y) = dataloader.read_corpus('/data/medg/misc/jindi/nlp/datasets/mr/test.txt')
elif (args.dataset == 'imdb'):
(train_x, train_y) = datalo... |
class MyValDataSet_cls(data.Dataset):
def __init__(self, root_path, root_path_coarsemask, list_path, crop_size=(224, 224)):
self.root_path = root_path
self.root_path_coarsemask = root_path_coarsemask
self.list_path = list_path
(self.crop_h, self.crop_w) = crop_size
self.img_i... |
class TemplateFfdBuilder(builder.ModelBuilder):
def __init__(self, *args, **kwargs):
super(TemplateFfdBuilder, self).__init__(*args, **kwargs)
self._initializer_run = False
def n_ffd_samples(self):
return self.params.get('n_ffd_samples', 16384)
def view_index(self):
return se... |
def tanhtanh_2(x, mu1, mu2, sd):
xn_1 = ((x - mu1) / sd)
xn_2 = ((x - mu2) / sd)
tanh_1 = torch.tanh(xn_1)
tanh_2 = torch.tanh(xn_2)
sech2_1 = (1 - (tanh_1 ** 2))
sech2_2 = (1 - (tanh_2 ** 2))
t = (tanh_1 * tanh_2)
jt = ((1 / sd) * ((tanh_1 * sech2_2) + (sech2_1 * tanh_2)))
jjt = ((1... |
class StableBaselines3Wrapper(Wrapper):
def __init__(self, env: CityLearnEnv):
env = StableBaselines3ActionWrapper(env)
env = StableBaselines3RewardWrapper(env)
env = StableBaselines3ObservationWrapper(env)
super().__init__(env)
self.env: CityLearnEnv |
class TFRoFormerForQuestionAnswering(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def test_fsaf_head_forward():
fsaf_model = fsaf_config()
s = 128
feats = [torch.rand(1, fsaf_model.in_channels, (s // (2 ** (i + 2))), (s // (2 ** (i + 2)))) for i in range(len(fsaf_model.anchor_generator.strides))]
ort_validate(fsaf_model.forward, feats) |
class ResidualBlock(nn.Module):
def __init__(self, in_channels, dilation=1):
super(ResidualBlock, self).__init__()
self.dilation = dilation
self.bn1 = nn.BatchNorm2d(in_channels)
self.relu = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size=(3... |
def training_loss_3rd_item_task_fbne(fbne_data, batch_index, model, sess, train_data, is_training):
train_loss = 0.0
num_batch = (fbne_data.oracle_num_items // setting.batch_size)
for index in batch_index:
(b_target_item, b_k_shot_user, b_second_order_items, b_third_order_users, b_oracle_item_ebd, b... |
def reconstruct_with_dqvae(img, dqvae):
with torch.no_grad():
output = dqvae(img, is_training=False, ret_loss=False)
x_rec = output['x_rec']
return tensor2img(x_rec[0]) |
class TestShortener(unittest.TestCase):
def test_example(self):
text = ' Ilsa, le mechant gardien '
width = 27
shortened = shorten_to_bytes_width(text, width)
self.assertEqual(shortened, ' Ilsa, le mechant [...]')
self.assertLessEqual(len(shortened.encode()), width)
def... |
def test_multi_captured(capfd):
stream = StringIO()
with redirect_stdout(stream):
m.captured_output('a')
m.raw_output('b')
m.captured_output('c')
m.raw_output('d')
(stdout, stderr) = capfd.readouterr()
assert (stdout == 'bd')
assert (stream.getvalue() == 'ac') |
class RNN(nn.Module):
def __init__(self, input_size, embedding_size, hidden_size, num_layers, rnn_type='GRU', dropout=0, output_size=None, output_embedding_size=None, device=torch.device('cpu')):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
... |
def _send_slack(msg):
req = Request(_slack_url)
req.add_header('Content-Type', 'application/json')
urlopen(req, json.dumps({'username': 'tacotron', 'icon_emoji': ':taco:', 'text_jamo': ('*%s*: %s' % (_run_name, msg))}).encode()) |
def require_librosa(test_case):
return unittest.skipUnless(is_librosa_available(), 'test requires librosa')(test_case) |
class SentencePieceModelTokenizer(Tokenizer):
def __init__(self, model_path):
super().__init__()
import sentencepiece as spm
self.model = spm.SentencePieceProcessor()
self.model.Load(model_path)
def split(self, string):
return self.model.EncodeAsPieces(string)
def end... |
class Trainer(DefaultTrainer):
def build_evaluator(cls, cfg: CfgNode, dataset_name, output_folder=None):
if (output_folder is None):
output_folder = os.path.join(cfg.OUTPUT_DIR, 'inference')
evaluators = [COCOEvaluator(dataset_name, cfg, True, output_folder)]
if cfg.MODEL.DENSEPO... |
def plot_rank_corrs(rho, rho_p, tau, tau_p, METRICS, scatter=False, title=''):
(fig, ax) = plt.subplots(2, 2, figsize=(10, 10))
fig.suptitle(title)
if scatter:
(x, y) = ([], [])
for (i, metric) in enumerate(METRICS):
x += (len(rho[metric]) * [i])
y += rho[metric]
... |
def get_kernel_window(kernel: Literal[('gaussian', 'triang', 'laplace')]='gaussian', ks: int=5, sigma: Union[(int, float)]=2) -> List[float]:
half_ks = ((ks - 1) // 2)
if (kernel == 'gaussian'):
base_kernel = ((([0.0] * half_ks) + [1.0]) + ([0.0] * half_ks))
kernel_window = gaussian_filter1d(bas... |
class CategoricalPolicy(nn.Module):
def __init__(self, embedder, recurrent, action_size):
super(CategoricalPolicy, self).__init__()
self.embedder = embedder
self.fc_policy = orthogonal_init(nn.Linear(self.embedder.output_dim, action_size), gain=0.01)
self.fc_value = orthogonal_init(n... |
_torch
_vision
class BeitFeatureExtractionTest(FeatureExtractionSavingTestMixin, unittest.TestCase):
feature_extraction_class = (BeitFeatureExtractor if is_vision_available() else None)
def setUp(self):
self.feature_extract_tester = BeitFeatureExtractionTester(self)
def feat_extract_dict(self):
... |
class PGDAttack(Attack):
__metaclass__ = abc.ABCMeta
def __init__(self, predictor, specification, epsilon, lr=0.1, lr_fn=None, num_steps=20, num_restarts=1, input_bounds=(0.0, 1.0), optimizer_builder=UnrolledGradientDescent):
super(PGDAttack, self).__init__(name='pgd')
self._predictor = predicto... |
.skipif((torch is None), reason='requires torch library')
def test_assert_is_norm_layer():
assert (not mmcv.assert_is_norm_layer(nn.Conv3d(3, 64, 3)))
assert mmcv.assert_is_norm_layer(nn.BatchNorm3d(128))
assert mmcv.assert_is_norm_layer(nn.GroupNorm(8, 64))
assert (not mmcv.assert_is_norm_layer(nn.Sigm... |
class RODDecode_RA(nn.Module):
def __init__(self):
super(RODDecode_RA, self).__init__()
self.convt1 = nn.ConvTranspose3d(in_channels=256, out_channels=128, kernel_size=(4, 6, 6), stride=(2, 2, 2), padding=(1, 2, 2))
self.convt2 = nn.ConvTranspose3d(in_channels=128, out_channels=64, kernel_si... |
class TestCircuitBit(QiskitTestCase):
def test_bit_getitem(self):
qubit = QuantumRegister(1, 'q')[0]
with self.assertWarns(DeprecationWarning):
self.assertEqual(qubit[0], qubit.register)
self.assertEqual(qubit[1], qubit.index)
def test_gate_with_tuples(self):
qr =... |
def query_argname(arg_name):
def index_name(api_name, arg_name):
arg_names = DB[signature_collection].find_one({'api': api_name})['args']
for (idx, name) in enumerate(arg_names):
if (name == arg_name):
return f'parameter:{idx}'
return None
APIs = []
for ap... |
def execute_only_once():
f = inspect.currentframe().f_back
ident = (f.f_code.co_filename, f.f_lineno)
if (ident in _EXECUTE_HISTORY):
return False
_EXECUTE_HISTORY.add(ident)
return True |
def test_DPICT_main(epoch, test_dataloader, model, criterion, quantize_parameters=0, loss_weights=np.array([(1 / 3), (1 / 3), (1 / 3)]), distillation=True):
model.eval()
device = next(model.parameters()).device
loss = []
bpp_loss = []
mse_loss = []
msssim_loss = []
aux_loss = []
psnr = [... |
_config
def exploration():
uuid = 'habitat_exploration'
cfg = {}
cfg['learner'] = {'lr': 0.001, 'perception_network_kwargs': {'n_map_channels': 1, 'use_target': False}}
cfg['env'] = {'env_name': 'Habitat_Exploration', 'transform_fn_pre_aggregation_fn': 'TransformFactory.independent', 'transform_fn_pre_a... |
class MultilingualDatasetManager(object):
def __init__(self, args, lang_pairs, langs, dicts, sampling_method):
super().__init__()
self.args = args
self.seed = args.seed
self.lang_pairs = lang_pairs
self.extra_lang_pairs = (list({p for (_, v) in args.extra_lang_pairs.items() f... |
class ResNet(nn.Module):
__factory = {18: torchvision.models.resnet18, 34: torchvision.models.resnet34, 50: torchvision.models.resnet50, 101: torchvision.models.resnet101, 152: torchvision.models.resnet152}
def __init__(self, depth, ibn_type=None, final_layer='layer3', neck=128, pretrained=True):
super(... |
class Config(object):
def __init__(self, args, labels={}):
self.args = args
self.labels = labels
self.annotation = args.ann_scope
self.annotation_type = args.ann_type
self.input_to_action = {}
if (args.config_file is not None):
for line in open(args.config... |
_model
def gmixer_24_224(pretrained=False, **kwargs):
model_args = dict(patch_size=16, num_blocks=24, embed_dim=384, mlp_ratio=(1.0, 4.0), mlp_layer=GluMlp, act_layer=nn.SiLU, **kwargs)
model = _create_mixer('gmixer_24_224', pretrained=pretrained, **model_args)
return model |
class TestTuningSpaceV2(unittest.TestCase):
def setUp(self) -> None:
self.capability = {'calib': {'calib_sampling_size': [1, 10, 50]}, 'op': deepcopy(op_cap)}
self.op_wise_user_cfg_for_fallback = {'op_name1': {'activation': {'dtype': ['fp32']}, 'weight': {'dtype': ['fp32']}}}
def test_tuning_sam... |
class SchedulerMixin():
config_name = SCHEDULER_CONFIG_NAME
_compatibles = []
has_compatibles = True
def from_pretrained(cls, pretrained_model_name_or_path: Dict[(str, Any)]=None, subfolder: Optional[str]=None, return_unused_kwargs=False, **kwargs):
(config, kwargs, commit_hash) = cls.load_confi... |
class AttentionSaver(Callback):
def __init__(self, output_directory, att_model, training_set):
self._dir = path.join(output_directory, 'attention')
try:
os.mkdir(self._dir)
except FileExistsError:
pass
self._att_model = att_model
idxs = training_set.st... |
class NamedEntityConfig(BaseModel):
text: str = Field(..., description='Text for entity linking or disambiguation.')
spans: Optional[List[Span]] = Field(None, description="\nFor EL: the spans field needs to be set to an empty list. \n\nFor ED: spans should consist of a list of tuples, where each tuple refers to... |
def seenArticle(articles):
conn = getDb()
cur = conn.cursor()
sql = 'UPDATE article_feedback SET seen_web=CURRENT_TIMESTAMP WHERE article_id=%s AND user_id = %s'
cur.executemany(sql, articles)
cur.close()
conn.commit()
return True |
def get_is(args, gen_net: nn.Module, num_img):
gen_net = gen_net.eval()
eval_iter = (num_img // args.eval_batch_size)
img_list = list()
for _ in range(eval_iter):
z = torch.cuda.FloatTensor(np.random.normal(0, 1, (args.eval_batch_size, args.latent_dim)))
gen_imgs = gen_net(z).mul_(127.5)... |
def verify(pols, sols):
from phcpy.solutions import strsol2dict, evaluate
dictsols = [strsol2dict(sol) for sol in sols]
checksum = 0
for sol in dictsols:
sumeval = sum(evaluate(pols, sol))
print(sumeval)
checksum = (checksum + sumeval)
print('the total check sum :', checksum) |
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = torch.nn.Linear(10, 5)
self.fc2 = torch.nn.Linear(5, 10)
self.mm = Matmul()
self.bmm = BatchMatmul()
def forward(self, inp):
x1 = self.fc1(inp)
x2 = self.fc2(x1)
x3... |
class Data2VecVisionForSemanticSegmentation(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class TestOptions(BaseOptions):
def __init__(self):
BaseOptions.__init__(self, print_opt=False)
parser = self.parser
parser.add_argument('--train_config', type=argparse.FileType(mode='r'), required=True, help='config file saved from model training')
parser.add_argument('--partition',... |
class TestBiasCorrection(unittest.TestCase):
def test_bias_correction(self):
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, [1, 224, 224, 3], name='input')
if (tf.version.VERSION <= '2.1.0'):
x = tf.nn.relu(x)
conv_weights = tf.compat.v1.g... |
class Program():
def __init__(self, prog, mul, imgFeats, arities):
self.prog = prog
self.mul = mul
self.imgFeats = imgFeats
self.arities = arities
self.root = Node(None)
def build(self, ind=0):
self.buildInternal(self.root)
def buildInternal(self, cur=None, co... |
def format_row(buffer, environment, results):
buffer_str = BUFFER_STRINGS[buffer]
environment_str = ENVIRONMENT_STRINGS[environment]
highlights = set_highlights(results)
results_str = ' & '.join((format_result(result, h) for (result, h) in zip(results, highlights)))
row = f'''{buffer_str} & {environ... |
def find_max_f1_subtree(tree, span):
return max(((t, span_f1(span, t.span)) for t in tree.subtrees()), key=(lambda p: p[1]))[0] |
class LSTMLatentLevel(LatentLevel):
def __init__(self, level_config):
super(LSTMLatentLevel, self).__init__(level_config)
self._construct(level_config)
def _construct(self, level_config):
if (level_config['inference_config'] is not None):
self.inference_model = LSTMNetwork(le... |
def dataset(metadata_filename, args):
batch_size = args.batch_size
buffer_size = 20000
num_mels = args.num_mels
max_length = 2000
input_dir = os.path.join(os.path.dirname(metadata_filename), 'inputs')
label_dir = os.path.join(os.path.dirname(metadata_filename), 'labels')
with open(metadata_f... |
class Config():
batch_size = 100
original_dim = 784
latent_dim = 40
encoder_arch = [[300, None], [300, None]]
decoder_arch = [[300, None], [300, None]]
number_epochs = 5000
epsilon_std = 1.0
early_stopping_epochs = 100
learning_rate = 0.0002
kl_sample = True
regularization = ... |
def plot_train_history(train_loss_history, val_loss_history, save_dir, save_title):
(fig, ax) = plt.subplots()
time_ = range(len(train_loss_history))
ax.set_xlabel('Epochs')
ax.set_ylabel('BCE Loss')
ax.grid(linestyle='--')
ax.plot(time_, train_loss_history, color='blue', label='train loss')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.