code stringlengths 101 5.91M |
|---|
def bmm_maybe_select(A, B, index):
if ((A.dtype == th.int64) and (len(A.shape) == 1)):
B = B.view((- 1), B.shape[2])
flatidx = ((index * B.shape[1]) + A)
return B.index_select(0, flatidx)
else:
BB = B.index_select(0, index)
return th.bmm(A.unsqueeze(1), BB).squeeze() |
def test_create_affine_identity_file():
filename = 'facewarper_affine_identity.txt'
directory = os.path.join(tempfile.gettempdir(), 'FaceWarper')
if (not os.path.exists(directory)):
os.makedirs(directory)
filepath = os.path.join(directory, filename)
write_affine_identity(filepath)
return... |
class Bert4WS(Bert4WSFunction, nn.Module):
def __init__(self, vocabulary, embedding_size=768, hidden_dropout_prob=0.1, bert_model='hfl/chinese-roberta-wwm-ext', device=torch.device('cuda')):
super().__init__()
self.vocabulary = vocabulary
self.embedding_size = embedding_size
self.lab... |
class Backbone(nn.Module):
def __init__(self, block, layers, zero_init_residual=False):
super(Backbone, self).__init__()
self.inplanes = 128
self.conv1 = nn.Conv2d(6, 128, kernel_size=7, stride=2, padding=3, groups=2, bias=False)
self.bn1 = nn.BatchNorm2d(128)
self.relu = nn.... |
def set_z3_state(seed=None):
z3.set_param('smt.phase_selection', 5, 'smt.arith.random_initial_value', True, 'smt.random_seed', seed, 'sat.random_seed', seed, 'sat.phase', 'random', 'memory_max_size', (50 * 1024)) |
class MLP_Softmax(nn.Module):
def __init__(self, input_size, embedding_size, output_size, dropout=0):
super(MLP_Softmax, self).__init__()
self.mlp = nn.Sequential(MLP_Plain(input_size, embedding_size, output_size, dropout), nn.Softmax(dim=2))
def forward(self, input):
return self.mlp(inp... |
def inpainting_inference(model, masked_img, mask):
device = next(model.parameters()).device
infer_pipeline = [dict(type='LoadImageFromFile', key='masked_img'), dict(type='LoadMask', mask_mode='file', mask_config=dict()), dict(type='Pad', keys=['masked_img', 'mask'], mode='reflect'), dict(type='Normalize', keys=... |
class MatchingNotFoundError(Exception):
def __init__(self, missingIdsIn1: List[str], missingIdsIn2: List[str], namemissingIdsIn1: str, namemissingIdsIn2: str):
self.missingIdsIn1 = missingIdsIn1
self.missingIdsIn2 = missingIdsIn2
self.namemissingIdsIn1 = namemissingIdsIn1
self.namemi... |
class BottleneckBlock(ResNetBlockBase):
def __init__(self, in_channels, out_channels, *, bottleneck_channels, stride=1, num_groups=1, norm='BN', stride_in_1x1=False, dilation=1, avd=False, avg_down=False, radix=2, bottleneck_width=64):
super().__init__(in_channels, out_channels, stride)
self.avd = (... |
class HfApiLoginTest(HfApiCommonTest):
def test_login_invalid(self):
with self.assertRaises(HTTPError):
self._api.login(username=USER, password='fake')
def test_login_valid(self):
token = self._api.login(username=USER, password=PASS)
self.assertIsInstance(token, str) |
class CSRMatrix3d(CSXMatrix3d):
def __init__(self, inp, shape=None, device=None):
if ((type(inp) == list) and isinstance(inp[0], ssp.spmatrix)):
max_shape = [0, 0]
for s in inp:
max_shape[0] = max(max_shape[0], s.shape[0])
max_shape[1] = max(max_shape[... |
class Metadata():
def __init__(self, name, partition):
self.name = name
self.stems = penn.load.partition(name)[partition]
self.files = [((penn.CACHE_DIR / name) / f'{stem}-audio.npy') for stem in self.stems]
self.frames = [penn.convert.samples_to_frames(len(np.load(file, mmap_mode='r... |
def test_hard_intersection() -> None:
box1 = TFBoxTensor(tf.Variable([[[1, 1], [3, 5]], [[1, 1], [3, 3]]], dtype=tf.float32))
box2 = TFBoxTensor(tf.Variable([[[2, 0], [6, 2]], [[3, 2], [4, 4]]], dtype=tf.float32))
expected = TFHardIntersection()(box1, box2)
res = TFIntersection()(box1, box2)
assert ... |
.timeout(10)
def test_init_with_env_updates():
max_path_length = 16
env = GarageEnv(PointEnv())
policy = FixedPolicy(env.spec, scripted_actions=[env.action_space.sample() for _ in range(max_path_length)])
tasks = SetTaskSampler((lambda : GarageEnv(PointEnv())))
n_workers = 8
workers = WorkerFact... |
class Word2Vec(BaseModule):
def __init__(self, TEXT=None, embedding_dim=50, batch_size=10, n_gram=4, **kwargs):
super(Word2Vec, self).__init__()
self.batch_size = batch_size
self.n_gram = n_gram
self.vocab_size = len(TEXT.itos)
self.embedding_dim = embedding_dim
self.... |
def background_command_waiter(command, popen_object, require_zero_status):
popen_object.communicate()
if (popen_object.returncode is not 0):
str = 'Command exited with status {0}: {1}'.format(popen_object.returncode, command)
if require_zero_status:
logger.error(str)
thre... |
def random_drop_coordinate(grasp_pose, drop_pose, z=0.3):
x_random = random_drop_axis_coordinate(grasp_pose, axis_idx=0, axis_corner=0.43, axis_range=0.3)
y_random = random_drop_axis_coordinate(grasp_pose, axis_idx=1, axis_corner=(- 0.0), axis_range=(- 0.22))
pose_random = kdl.Frame(drop_pose.M, kdl.Vector(... |
class ScribblerDilate128(nn.Module):
def __init__(self, input_nc, output_nc, ngf):
super(ScribblerDilate128, self).__init__()
self.conv = nn.Conv2d
self.batch_norm = nn.BatchNorm2d
self.ngf = ngf
self.res_block = ResidualBlock
self.dilate_block = DilationBlock
... |
class WandBProgressBarWrapper(BaseProgressBar):
def __init__(self, wrapped_bar, wandb_project, run_name=None):
self.wrapped_bar = wrapped_bar
if (wandb is None):
logger.warning('wandb not found, pip install wandb')
return
def __iter__(self):
return iter(self.wrapp... |
def test_pydoc():
import pydoc
import pybind11_tests
assert (pybind11_tests.__name__ == 'pybind11_tests')
assert (pybind11_tests.__doc__ == 'pybind11 test module')
assert pydoc.text.docmodule(pybind11_tests) |
def se_resnet_50(pretrained=False, **kwargs):
model = SENet(Bottleneck, [3, 4, 6, 3], **kwargs)
return model |
def ground_truth_to_binary(ground_truth):
binarized = []
for (i, instance) in enumerate(ground_truth):
instance_labels = []
for (j, token_label) in enumerate(instance):
if (token_label == (- 100)):
instance_labels.append((- 100))
elif (token_label > 0.5):
... |
class FlashSentenceEncoderLayer(nn.Module):
def __init__(self, embedding_dim: int=512, hidden_dim: int=1024, z_dim: int=128, dropout: float=0.0, attention_dropout: float=0.0, hidden_dropout: float=0.0, norm_type: str='layernorm', max_positions: int=1024, export: bool=False) -> None:
super().__init__()
... |
.skipif((sys.platform == 'linux'), reason='This test checks multiprocessing override on non-linux platforms.')
def test_encode_images_num_workers_default_override_on_nonlinux(cnn, mocker):
num_enc_workers = 4
gen_batches_mocker = mocker.patch('imagededup.methods.cnn.CNN._get_cnn_features_batch')
result = cn... |
def configure_dims(params):
env = cached_make_env(params['make_env'])
env.reset()
(obs, _, _, info) = env.step(env.action_space.sample())
dims = {'o': obs['observation'].shape[0], 'u': env.action_space.shape[0], 'g': obs['desired_goal'].shape[0]}
for (key, value) in info.items():
value = np.... |
def wipe_and_exit(config):
if os.path.exists(config.TENSORBOARD_DIR):
print('Removing tensorboard directory...')
shutil.rmtree(config.TENSORBOARD_DIR, ignore_errors=True)
if os.path.exists(config.CHECKPOINT_FOLDER):
print('Removing checkpoint folder...')
shutil.rmtree(config.CHEC... |
class COCO(_COCO):
def __init__(self, annotation_file=None):
if (getattr(pycocotools, '__version__', '0') >= '12.0.2'):
warnings.warn('mmpycocotools is deprecated. Please install official pycocotools by "pip install pycocotools"', UserWarning)
super().__init__(annotation_file=annotation_... |
def load_model_and_data(fname):
dump = torch.load(fname)
data = dt.DataInstructionEmbedding()
data.read_meta_data()
data.load_dataset_params(dump.dataset_params)
return (dump.model, data) |
class MilestonesFinetuning(BaseFinetuning):
def __init__(self, milestones: tuple=(5, 10), train_bn: bool=False):
super().__init__()
self.milestones = milestones
self.train_bn = train_bn
def freeze_before_training(self, pl_module: LightningModule):
self.freeze(modules=pl_module.fe... |
class FakeProvider(BaseProvider):
def get_backend(self, name=None, **kwargs):
backend = self._backends[0]
if name:
filtered_backends = [backend for backend in self._backends if (backend.name() == name)]
if (not filtered_backends):
raise QiskitBackendNotFoundEr... |
def match_xxz(match_dict):
path = '/backup3/jcxu/data/xxz-latent/test.article'
with open(path, 'r') as fd:
lines = fd.read().splitlines()
line_num = len(lines)
output_list = ['' for _ in range(line_num)]
feat_lines = [[] for _ in range(line_num)]
meta_sents = []
for (idx, l) in enume... |
def wrap_sys_argv_cmd(cmd: str, pre):
splits = cmd.split(' ')
el = splits[1:]
pairs = ['{} {}'.format(i, j) for (i, j) in zip(el[::2], el[1::2])]
pro = splits[0]
sep = (' \\\n' + (((len(pre) + len(pro)) + 2) * ' '))
out = sep.join(pairs)
return '{} {} {}'.format(pre, pro, out) |
_registry(operator_type='TransposeBatchMatMul')
class TransposeBatchMatMul(Operator):
def __init__(self):
super().__init__() |
class MrpcProcessor(DataProcessor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(DEPRECATION_WARNING.format('processor'), FutureWarning)
def get_example_from_tensor_dict(self, tensor_dict):
return InputExample(tensor_dict['idx'].numpy(), tensor_dic... |
class StringPool():
def __init__(self):
self.strs = {'': 0}
self.known_id_count = 1
def read_constids(self, file: str):
idx = 1
with open(file, 'r') as f:
for line in f:
l = line.strip()
if (not l.startswith('X(')):
... |
def restore_op():
global tensor_magic_op_supported, raw_tensor_magic_op, torch_op_supported, raw_torch_op, func_op_sopprted, raw_func_op
global tensor_target
for op_name in tensor_magic_op_supported:
setattr(tensor_target, op_name, raw_tensor_magic_op[op_name])
for op_name in torch_op_supported:... |
def parse_args():
parser = argparse.ArgumentParser(description='Print the whole config')
parser.add_argument('config', help='config file path')
parser.add_argument('--save-path', default=None, help='save path of whole config, suffixed with .py, .json or .yml')
parser.add_argument('--cfg-options', nargs=... |
def imgtensor2im(image_tensor, imtype=np.uint8):
image_numpy = inv_normalize(image_tensor).cpu().float().numpy()
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) * 255.0)
if (image_numpy.shape[2] < 3):
image_numpy = np.dstack(([image_numpy] * 3))
return image_numpy.astype(imtype) |
def split_911(amr):
while True:
index = None
for (i, token) in enumerate(amr.tokens):
if (token == '911'):
index = i
break
else:
break
amr.replace_span([index], ['09', '11'], ['CD', 'CD'], ['DATE', 'DATE']) |
def halve_range_str(range_str):
ranges = range_str.split(',')
halved_ranges = []
for r in ranges:
c = [str(max(1, (int(x) // 2))) for x in r.split(':')]
halved_ranges.append(':'.join(c))
return ','.join(halved_ranges) |
def _GenericDiagnoser(short_name, long_name, diagnoses, msg):
for (regex, diagnosis) in diagnoses:
if re.search(regex, msg):
diagnosis = ('%(file)s:%(line)s:' + diagnosis)
for m in _FindAllMatches(regex, msg):
(yield (short_name, long_name, (diagnosis % m.groupdict())... |
def print_model_parameters(model, only_num=True):
print('Model Parameter')
if (not only_num):
for (name, param) in model.named_parameters():
print(name, param.shape, param.requires_grad)
total_num = sum([param.nelement() for param in model.parameters()])
print('Total params num: {}'.... |
def partial_load(pretrained_dict, model, skip_keys=[], log=False):
model_dict = model.state_dict()
filtered_dict = {k: v for (k, v) in pretrained_dict.items() if ((k in model_dict) and (not any([(sk in k) for sk in skip_keys])))}
skipped_keys = [k for k in pretrained_dict if (k not in filtered_dict)]
un... |
class LSUNDataset(Dataset):
def __init__(self, data, transform, size=(32, 32)):
self.data = data
self.size = size
self.transform = transform
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
(image, label) = self.data[idx]
return (TF.resize(... |
class ctx_eval(object):
def __init__(self, module):
self.prev_training_state = get_module_training_state(module)
self.module = module
set_module_training_off(module)
def __enter__(self):
pass
def __exit__(self, *args):
set_module_training_state(self.module, self.prev_... |
_builder('audio_caption')
class AudioCapBuilder(BaseDatasetBuilder):
train_dataset_cls = AudioCaptionEvalDataset
eval_dataset_cls = AudioCaptionEvalDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/clotho/defaults_cap.yaml'}
def build(self):
self.build_processors()
build_info =... |
class SetMinus(AbstractDistribution):
def __init__(self, base, hold_out):
self.base = base
self.hold_out = hold_out
self._keys = base.keys
if (not hold_out.keys.issubset(self._keys)):
raise ValueError('Keys {} of hold_out is not a subset of keys {} of SetMinus base distri... |
def load_cifar100(data_dir, use_augmentation=False):
test_transform = transforms.Compose([transforms.ToTensor()])
if use_augmentation:
train_transform = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(0.5), transforms.RandomRotation(15), transforms.ToTensor()])
... |
def build_errors(options):
s_emb = tensor.matrix('s_emb', dtype='float32')
im_emb = tensor.matrix('im_emb', dtype='float32')
errs = None
if (options['method'] == 'order'):
indices = tensor.arange(s_emb.shape[0])
(errs, _) = theano.map((lambda i, s, im: order_violations(s[i], im, options)... |
class TransformerLanguageModelConfig(FairseqDataclass):
activation_fn: ChoiceEnum(utils.get_available_activation_fns()) = field(default='relu', metadata={'help': 'activation function to use'})
dropout: float = field(default=0.1, metadata={'help': 'dropout probability'})
attention_dropout: float = field(defa... |
def compute_overall_iou(pred, target, num_classes):
shape_ious = []
pred = pred.max(dim=2)[1]
pred_np = pred.cpu().data.numpy()
target_np = target.cpu().data.numpy()
for shape_idx in range(pred.size(0)):
part_ious = []
for part in range(num_classes):
I = np.sum(np.logical... |
class Generator(LearningModule):
def __init__(self, args, dist, nc, z=None, source=None, mode='train', bnkwargs={}, gen_transform=None):
N = self.net = Net(source=source, name='Generator')
self.set_mode(mode)
h_and_weights = dist.embed_data()
bn_use_ave = (mode == 'test')
(se... |
def get_line_style(line):
style = {}
style['alpha'] = line.get_alpha()
if (style['alpha'] is None):
style['alpha'] = 1
style['color'] = color_to_hex(line.get_color())
style['linewidth'] = line.get_linewidth()
style['dasharray'] = get_dasharray(line)
style['zorder'] = line.get_zorder(... |
class InferenceBase(nn.Module):
def __init__(self, input_dim, output_dim, hidden_dim):
super().__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.hidden_dim = hidden_dim
if (not hidden_dim):
self.layer = nn.Sequential(nn.Linear(input_dim, outp... |
def evaluate_svm(train_features, train_labels, test_features, test_labels):
clf = LinearSVC()
clf.fit(train_features, train_labels)
pred = clf.predict(test_features)
return ((np.sum((test_labels == pred)) * 1.0) / pred.shape[0]) |
class ResFCNetBase(ResNetBase):
OUT_PIXEL_DIST = 1
def __init__(self, in_channels, out_channels, config, D=3, **kwargs):
super(ResFCNetBase, self).__init__(in_channels, out_channels, config, D)
def network_initialization(self, in_channels, out_channels, config, D):
net_metadata = self.net_me... |
def extract_archive(file_path, path='.', archive_format='auto'):
if (archive_format is None):
return False
if (archive_format == 'auto'):
archive_format = ['tar', 'zip']
if isinstance(archive_format, str):
archive_format = [archive_format]
for archive_type in archive_format:
... |
def postprocess1(x):
(file_path, util_dir) = x
print(file_path, args.util_dir)
node_utils = NU.from_json(util_dir, 0)
nr = NodeRestore(node_utils)
with open((file_path + '.frame'), 'w', encoding='utf-8') as f:
for amr in nr.restore_file(file_path):
f.write((str(amr) + '\n\n'))
... |
class SupportVectorComponentTest(BaseRegressionComponentTest):
__test__ = True
res = dict()
res['default_boston'] = 0.
res['default_boston_places'] = 2
res['default_boston_iterative'] = None
res['default_boston_sparse'] = 0.
res['default_boston_sparse_places'] = 2
res['default_boston_ite... |
def make_encoder(encoder_type, obs_shape, feature_dim, num_layers, num_filters, output_logits=False):
assert (encoder_type in _AVAILABLE_ENCODERS)
return _AVAILABLE_ENCODERS[encoder_type](obs_shape, feature_dim, num_layers, num_filters, output_logits) |
class Adam(torch.optim.Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False):
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad)
super(Adam, self).__init__(params, defaults)
def step(self, closure=None... |
def shuffle_iterator(iterator: typing.Iterator, queue_size: int) -> typing.Iterable[typing.Any]:
buffer = []
try:
for _ in range(queue_size):
buffer.append(next(iterator))
except StopIteration:
warnings.warn(f'Number of elements in the iterator is less than the queue size (N={que... |
class Continuous(AbstractDistribution):
def __init__(self, key, minval, maxval, dtype='float32'):
self.key = key
self.minval = minval
self.maxval = maxval
self.dtype = dtype
def sample(self, rng=None):
rng = self._get_rng(rng)
out = rng.uniform(low=self.minval, hi... |
def ALDA_loss(ad_out_score, labels_source, softmax_out, weight_type=1, threshold=0.9):
ad_out = torch.sigmoid(ad_out_score)
batch_size = (ad_out.size(0) // 2)
class_num = ad_out.size(1)
labels_source_mask = torch.zeros(batch_size, class_num).to(ad_out.device).scatter_(1, labels_source.unsqueeze(1), 1)
... |
def get_from_cache(url: str, cache_dir=None, force_download=False, proxies=None, etag_timeout=10, resume_download=False, user_agent: Union[(Dict, str, None)]=None, local_files_only=False) -> Optional[str]:
if (cache_dir is None):
cache_dir = TRANSFORMERS_CACHE
if isinstance(cache_dir, Path):
cac... |
class ExperimentPlanner3D_v21_16GB(ExperimentPlanner3D_v21):
def __init__(self, folder_with_cropped_data, preprocessed_output_folder):
super(ExperimentPlanner3D_v21_16GB, self).__init__(folder_with_cropped_data, preprocessed_output_folder)
self.data_identifier = 'nnUNetData_plans_v2.1_16GB'
... |
class DukeMTMCreID(ImageDataset):
dataset_dir = ''
dataset_url = '
def __init__(self, root='', **kwargs):
self.root = osp.abspath(osp.expanduser(root))
self.dataset_dir = osp.join(self.root, self.dataset_dir)
self.download_dataset(self.dataset_dir, self.dataset_url)
self.trai... |
class CAdd(Layer):
def __init__(self, size, bRegularizer=None, bigdl_type='float'):
super(CAdd, self).__init__(None, bigdl_type, size, bRegularizer)
def set_init_method(self, weight_init_method=None, bias_init_method=None):
callBigDlFunc(self.bigdl_type, 'setInitMethod', self.value, weight_init_... |
def precision(input, target):
axes = tuple(range(1, input.dim()))
binary_input = (input > 0.5).float()
true_positives = (binary_input * target).sum(dim=axes)
all_positive_calls = binary_input.sum(dim=axes)
precision = (true_positives / all_positive_calls)
return precision.mean() |
class DownBlock2DTests(UNetBlockTesterMixin, unittest.TestCase):
block_class = DownBlock2D
block_type = 'down'
def test_output(self):
expected_slice = [(- 0.0232), (- 0.9869), 0.8054, (- 0.0637), (- 0.1688), (- 1.4264), 0.447, (- 1.3394), 0.0904]
super().test_output(expected_slice) |
def get_Xy(data, D=12):
X_l = []
y_l = []
N = len(data)
assert (N > D), 'N should be larger than D, where N is len(data)'
for ii in range(((N - D) - 1)):
X_l.append(data[ii:(ii + D)])
y_l.append(data[(ii + D)])
X = np.array(X_l)
X = X.reshape(X.shape[0], X.shape[1], 1)
y ... |
def efficientnet_b6b(in_size=(528, 528), **kwargs):
return get_efficientnet(version='b6', in_size=in_size, tf_mode=True, bn_eps=0.001, model_name='efficientnet_b6b', **kwargs) |
def choose_requirement(primary, secondary):
try:
name = re.split('[!<>=]', primary)[0]
get_distribution(name)
except DistributionNotFound:
return secondary
return str(primary) |
def __main__():
parser = argparse.ArgumentParser(description='BioTorch')
parser.add_argument('--config_file', help='Path to the configuration file')
try:
args = parser.parse_args()
benchmark = Benchmark(args.config_file)
if (benchmark.benchmark_mode == 'training'):
benchm... |
def resize(input, size=None, scale_factor=None, mode='nearest', align_corners=None, warning=True):
if warning:
if ((size is not None) and align_corners):
(input_h, input_w) = tuple((int(x) for x in input.shape[2:]))
(output_h, output_w) = tuple((int(x) for x in size))
if ... |
def train(args, train_dataset, model, tokenizer, criterion):
if (args.local_rank in [(- 1), 0]):
tb_writer = SummaryWriter()
args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu))
train_sampler = (RandomSampler(train_dataset) if (args.local_rank == (- 1)) else DistributedSample... |
def diaresnet50b(**kwargs):
return get_diaresnet(blocks=50, conv1_stride=False, model_name='diaresnet50b', **kwargs) |
_UTILS.register_module()
class PseudoSampler(BaseSampler):
def __init__(self, **kwargs):
pass
def _sample_pos(self, **kwargs):
raise NotImplementedError
def _sample_neg(self, **kwargs):
raise NotImplementedError
def sample(self, assign_result: AssignResult, pred_instances: Instan... |
class TestTransforms(unittest.TestCase):
def setUp(self):
setup_logger()
def test_apply_rotated_boxes(self):
np.random.seed(125)
cfg = get_cfg()
is_train = True
augs = detection_utils.build_augmentation(cfg, is_train)
image = np.random.rand(200, 300)
(imag... |
def _get_pool_dask(n_workers=None, maybe_create=False):
try:
from dask.distributed import get_client
except ImportError:
if (not maybe_create):
return None
else:
raise
try:
client = get_client()
except ValueError:
if (not maybe_create):
... |
class RealmPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
_arg_scope
def dropout(inputs, keep_prob=0.5, noise_shape=None, is_training=True, outputs_collections=None, scope=None, seed=None):
with variable_scope.variable_scope(scope, 'Dropout', [inputs], custom_getter=_model_variable_getter) as sc:
inputs = ops.convert_to_tensor(inputs)
layer = core_layers.D... |
def get_checkpoint_history_callback(outdir, config, dataset, comet_experiment, horovod_enabled, is_hpo_run=False):
callbacks = []
if ((not horovod_enabled) or (hvd.rank() == 0)):
cp_dir = (Path(outdir) / 'weights')
cp_dir.mkdir(parents=True, exist_ok=True)
cp_callback = ModelOptimizerChe... |
def format_hep(citation_elements):
prefixes = ('astro-ph-', 'hep-th-', 'hep-ph-', 'hep-ex-', 'hep-lat-', 'math-ph-')
for el in citation_elements:
if (el['type'] == 'REPORTNUMBER'):
for p in prefixes:
if el['report_num'].startswith(p):
el['report_num'] = ((... |
def translate(input, steps):
x = transform(Image.open(input).convert('RGB')).unsqueeze(0).to(device)
c = E(x)
c_trg = c
for j in range(len(steps)):
step = steps[j]
if (step['type'] == 'latent-guided'):
if (step['seed'] is not None):
torch.manual_seed(step['see... |
def mobilenetv1_w4a4_imagenet(target_platform=None):
target_platform = resolve_target_platform(target_platform)
driver_mode = get_driver_mode()
model_name = 'mobilenetv1-w4a4'
filename = find_bitfile(model_name, target_platform)
if (target_platform in ['ZCU104']):
runtime_weight_dir = find_r... |
def build_pixel_decoder(cfg, input_shape):
name = cfg.MODEL.SEM_SEG_HEAD.PIXEL_DECODER_NAME
model = SEM_SEG_HEADS_REGISTRY.get(name)(cfg, input_shape)
forward_features = getattr(model, 'forward_features', None)
if (not callable(forward_features)):
raise ValueError(f'Only SEM_SEG_HEADS with forwa... |
def main():
np.random.seed(SEED)
run(data_fn=FLAGS.data_fn, prop_missing=FLAGS.prop_missing, max_num_feature=FLAGS.max_num_feature, feature_selection=FLAGS.feature_selection, data_dir=FLAGS.data_dir, out_dir=FLAGS.out_dir) |
def audio_featurize(wavfile):
hop_length = 512
n_fft = 2048
(y, sr) = librosa.load(wavfile)
mfcc = librosa.feature.mfcc(y=y, sr=sr, hop_length=hop_length, n_mfcc=13)
mfcc_delta = librosa.feature.delta(mfcc)
mfcc_features = np.array([np.mean(mfcc[0]), np.std(mfcc[0]), np.amin(mfcc[0]), np.amax(mf... |
class MAESTROProber(bench.ProberForBertSeqLabel):
def __init__(self, cfg):
super().__init__(cfg)
def init_metrics(self):
self.all_metrics = set()
for split in ['train', 'valid', 'test']:
setattr(self, f'{split}_prec', torchmetrics.Precision(task='binary', threshold=self.cfg.f... |
class Writer(object):
def __init__(self, out):
self.out = out
self.indent = 0
def writeln(self, s):
self.out.write(('%s%s\n' % ((' ' * self.indent), s))) |
def create_model(use_selfatt=False, use_fc=False, dropout=None, stage1_weights=False, dataset=None, log_dir=None, test=False, *args):
print('Loading Scratch ResNet 50 Feature Model.')
resnet50 = ResNet(Bottleneck, [3, 4, 6, 3], use_modulatedatt=use_selfatt, use_fc=use_fc, dropout=None)
if (not test):
... |
def plot_partial_trajectory(trajectory, partial_observed_trajectory, mean_trajectory=None):
fig = plt.figure()
plt.plot(partial_observed_trajectory[0], partial_observed_trajectory[1], color='#6ba3ff', label='Observed', linewidth=3.0)
plt.plot(trajectory[0], trajectory[1], '--', color='#ff6a6a', label='Infer... |
class TestSamplingRandomMapIterator(unittest.TestCase, TestCheckpointableIterator):
def setUp(self):
data = list(range(53))
def transform(random: Random, item: int):
return (item + random.random())
seed = 1
random = Random()
random.seed(seed)
self.expected... |
class Contiguous(Layer):
def __init__(self, bigdl_type='float'):
super(Contiguous, self).__init__(None, bigdl_type) |
_grad()
def convert_parlai_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_json_path):
model = torch.load(checkpoint_path, map_location='cpu')
sd = model['model']
cfg = BlenderbotConfig.from_json_file(config_json_path)
m = BlenderbotForConditionalGeneration(cfg)
valid_keys = m.model.sta... |
def graph_ASWTModelComp2():
filename = 'graph_sources/ASWTModel_comp4.txt'
categories = []
aswt_stop = []
standard_stop = []
patient_stop = []
mind_stop = []
aveges_stop = []
with open(filename, 'r') as fh:
r = 0
for line_raw in fh:
line = line_raw.split(',')
... |
_module
class SmoothL1Loss(nn.Module):
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
super(SmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None, re... |
def construct_query_and_database_sets(base_path, runs_folder, folders, pointcloud_fols, filenames, p, output_name):
database_trees = []
test_trees = []
for (folder, filename) in zip(folders, filenames):
print(folder)
df_database = pd.DataFrame(columns=['file', 'northing', 'easting'])
... |
class TransformerEncoderBase(FairseqEncoder):
def __init__(self, cfg, dictionary, embed_tokens, return_fc=False):
self.cfg = cfg
super().__init__(dictionary)
self.register_buffer('version', torch.Tensor([3]))
self.dropout_module = FairseqDropout(cfg.dropout, module_name=module_name_f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.