code stringlengths 101 5.91M |
|---|
def test_resnet_backbone():
with pytest.raises(KeyError):
ResNet(20)
with pytest.raises(AssertionError):
ResNet(50, num_stages=0)
with pytest.raises(AssertionError):
dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False)
ResNet(50, dcn=dcn, stage_with_dcn=(True,))
... |
def _make_divisible(v, divisor=8, min_value=None):
if (min_value is None):
min_value = divisor
new_v = max(min_value, ((int((v + (divisor / 2))) // divisor) * divisor))
if (new_v < (0.9 * v)):
new_v += divisor
return new_v |
class CamVid(BaseDataset):
def __init__(self, root, list_path, num_classes=11, multi_scale=True, flip=True, ignore_label=255, base_size=960, crop_size=(720, 960), scale_factor=16, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], bd_dilate_size=4):
super(CamVid, self).__init__(ignore_label, base_size, ... |
class BeitFeatureExtractor(metaclass=DummyObject):
_backends = ['vision']
def __init__(self, *args, **kwargs):
requires_backends(self, ['vision']) |
class SST2Processor(DataProcessor):
def __init__(self):
super().__init__()
self.labels = ['0', '1']
def get_examples(self, data_dir, split):
path = os.path.join(data_dir, f'{split}.tsv')
examples = []
with open(path, encoding='utf-8') as f:
lines = f.readlines... |
def resnet18small(c, **kargs):
return n.Seq(n.ResNet([2, 2, 2]), n.FFNN([100, c], bias=True, last_lin=False, **kargs)) |
class SelfKnowledgeDistillationLoss(KnowledgeDistillationFramework):
def __init__(self, layer_mappings=[], loss_types=None, loss_weights=None, temperature=1.0, add_origin_loss=False, student_model=None, teacher_model=None):
super(SelfKnowledgeDistillationLoss, self).__init__(student_model=student_model, tea... |
_distributed
class TestAutoTCN(TestCase):
def setUp(self) -> None:
from bigdl.orca import init_orca_context
init_orca_context(cores=8, init_ray_on_spark=True)
def tearDown(self) -> None:
from bigdl.orca import stop_orca_context
stop_orca_context()
_torch
def test_fit_np(s... |
class TestMaskedLanguageModel(unittest.TestCase):
def test_masked_lm(self):
with contextlib.redirect_stdout(StringIO()):
with tempfile.TemporaryDirectory('test_mlm') as data_dir:
create_dummy_data(data_dir)
preprocess_lm_data(data_dir)
train_masked... |
class Enrichment(nn.Module):
def __init__(self, c_in, rate=2):
super(Enrichment, self).__init__()
self.rate = rate
self.relu = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(c_in, 32, 3, stride=1, padding=1)
dilation = ((self.rate * 1) if (self.rate >= 1) else 1)
self.co... |
class MsImageDiscriminator(nn.Module):
def __init__(self, input_dim, opt):
super(MsImageDiscriminator, self).__init__()
self.n_layer = opt.n_layers_D
self.dim = opt.ndf
self.norm = 'none'
self.activ = 'lrelu'
self.num_scales = 3
self.pad_type = 'reflect'
... |
_REGISTRY.register()
def resnet18_stylize(pretrained=False, **kwargs):
model = StylizeResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
pretrain_dict = model_zoo.load_url(model_urls['resnet18'])
model.load_state_dict(pretrain_dict, strict=False)
return model |
def sentence_pairing(sentences: List[str]) -> pandas.DataFrame:
sent_pairs = []
for i in range(len(sentences)):
for j in range(i, len(sentences)):
if (sentences[i] == sentences[j]):
continue
sent_pairs.append([sentences[i], sentences[j]])
return pandas.DataFra... |
def freeze_modules(model, modules):
for (mod, param) in model.named_parameters():
if any((mod.startswith(m) for m in modules)):
logging.info(f'freezing {mod}, it will not be updated.')
param.requires_grad = False
model_params = filter((lambda x: x.requires_grad), model.parameters... |
def quantize(onnx_model_path: Path) -> Path:
import onnx
import onnxruntime
from onnx.onnx_pb import ModelProto
from onnxruntime.quantization import QuantizationMode
from onnxruntime.quantization.onnx_quantizer import ONNXQuantizer
from onnxruntime.quantization.registry import IntegerOpsRegistry... |
def test():
net = resnet18(nn.Conv2d, nn.Linear, 'kaiming_normal')
y = net(torch.randn(1, 3, 32, 32))
print(y.size()) |
def lenet(images):
with tf.variable_scope('LeNet', [images]):
net = tf.layers.conv2d(images, 32, (5, 5), activation=tf.nn.relu, name='conv1')
net = tf.layers.max_pooling2d(net, (2, 2), 2, name='pool1')
net = tf.layers.conv2d(net, 64, (5, 5), activation=tf.nn.relu, name='conv2')
net =... |
_function('conv1d')
class AutogradConv1D(AutogradFunction):
def forward(ctx, input, kernel, padding=0, stride=1):
ctx.save_multiple_for_backward((input, kernel, padding, stride))
return input.conv1d(kernel, padding=padding, stride=stride)
def backward(ctx, grad_output):
(input, kernel, p... |
def get_sbms_model(dataset, args):
(g, features, labels, train_mask, val_mask, test_mask, factor_graphs) = dataset
n_classes = 2
if (args.model_name == 'FactorGNN'):
model = FactorGNNSBMs(g, args.num_layers, args.in_dim, args.num_hidden, args.num_latent, args.in_drop, args.residual, n_classes)
e... |
def register_datasets(datasets_data: Iterable[CocoDatasetInfo], datasets_root: Optional[str]=None) -> None:
for dataset_data in datasets_data:
register_dataset(dataset_data, datasets_root) |
class NeuralChatModel(BaseModel):
def match(self, model_path: str):
return ('neural-chat' in model_path.lower())
def get_default_conv_template(self, model_path: str) -> Conversation:
if ('neural-chat-7b-v2' in model_path.lower()):
return get_conv_template('neural-chat-7b-v2')
... |
def attention_func(self, hidden_states, *args, **kwargs):
shape = hidden_states.shape
return torch.empty(shape, device=_DEVICE) |
def plot_image(img):
img = ((img.permute(0, 2, 3, 1) * 127.5) + 128).clamp(0, 255).to(torch.uint8).detach().cpu().numpy()
pillow_image = Image.fromarray(img[0])
plt.imshow(pillow_image)
plt.show() |
def create_reward_transform(transform_type):
if (transform_type == 'tanh'):
def transform(r):
if torch.is_tensor(r):
return torch.tanh(r)
return math.tanh(r)
elif (transform_type == 'clip'):
def transform(r):
if torch.is_tensor(r):
... |
class CLIPImageProjection(metaclass=DummyObject):
_backends = ['torch', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers'])
def from_pretrained(cls... |
def dataframe_to_deepsurv_ds(df, event_col='Event', time_col='Time'):
e = df[event_col].values.astype(np.int32)
t = df[time_col].values.astype(np.float32)
x_df = df.drop([event_col, time_col], axis=1)
x = x_df.values.astype(np.float32)
return {'x': x, 'e': e, 't': t} |
class feature_extraction(nn.Module):
def __init__(self):
super(feature_extraction, self).__init__()
self.inplanes = 32
self.firstconv = nn.Sequential(convbn(3, 32, 3, 2, 1, 1), nn.ReLU(inplace=True), convbn(32, 32, 3, 1, 1, 1), nn.ReLU(inplace=True), convbn(32, 32, 3, 1, 1, 1), nn.ReLU(inpla... |
def test_film_can_toggle_batch_norm(mocker):
spy_batch_norm_init = mocker.spy(torch.nn.BatchNorm1d, '__init__')
spy_batch_norm_forward = mocker.spy(torch.nn.BatchNorm1d, 'forward')
batch_size = 7
in_channels = 13
seq_len = 37
film_embedding_size = 5
x = torch.testing.make_tensor(batch_size, ... |
class SparseConvolution(SparseModule):
def __init__(self, ndim, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, bias=True, subm=False, output_padding=0, transposed=False, inverse=False, indice_key=None, fused_bn=False):
super(SparseConvolution, self).__init__()
a... |
def _generate_waymo_train_dataset_config():
data_root = 'tests/data/waymo/kitti_format/'
ann_file = 'tests/data/waymo/kitti_format/waymo_infos_train.pkl'
classes = ['Car', 'Pedestrian', 'Cyclist']
pts_prefix = 'velodyne'
point_cloud_range = [(- 74.88), (- 74.88), (- 2), 74.88, 74.88, 4]
file_cli... |
def dev_token_loader2(dev_path, dim=1):
try:
with open(dev_path, 'rb') as f:
elmo_embeds_train = pickle.load(f)
return elmo_embeds_train[dim]
except:
print('error with loading (dev/test) files, retry:')
sys.stdout.flush()
with open((dev_path + '_np.pkl'), 'rb'... |
class IsIn(BaseRule):
def __init__(self, keyword: str):
self.keyword = keyword
def __call__(self, target):
return (self.keyword in target) |
def parse_args():
parser = argparse.ArgumentParser(description='fuse Conv and BN layers in a model')
parser.add_argument('config', help='config file path')
parser.add_argument('checkpoint', help='checkpoint file path')
parser.add_argument('out', help='output path of the converted model')
args = pars... |
class TFCamembertModel():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def add_generation_args(parser):
group = parser.add_argument_group('Generation')
add_common_eval_args(group)
gen_parser_from_dataclass(group, GenerationConfig())
return group |
class DefaultValues(object):
TRAIN_SPEED_RECORD_NUM = 50
SEC_TO_START_AUTOSCALE_WORKER = 90
STEP_TO_ADJUST_WORKER = 200
OPTIMIZED_WORKER_CPU_THRESHOLD = 20
SEC_FOR_STABLE_WORKER_COUNT = 60
SEC_INTERVAL_TO_OPTIMIZE = 300
FACTOR_TO_CUT_PENDING_CPU = 2
FACTOR_TO_CUT_PENDING_MEM = 2
SEC_... |
class DeepFactorizationMachineModel(torch.nn.Module):
def __init__(self, field_dims, embed_dim, mlp_dims, dropout):
super().__init__()
self.linear = FeaturesLinear(field_dims)
self.fm = FactorizationMachine(reduce_sum=True)
self.embedding = FeaturesEmbedding(field_dims, embed_dim)
... |
def create_dataloader(opt):
dataset = find_dataset_using_name(opt.dataset_mode)
instance = dataset()
instance.initialize(opt)
print(('dataset [%s] of size %d was created' % (type(instance).__name__, len(instance))))
dataloader = torch.utils.data.DataLoader(instance, batch_size=opt.batchSize, shuffle... |
def crop_video(video_f, video, crop_path, instanc_size):
video_crop_base_path = join(crop_path, video)
if (not isdir(video_crop_base_path)):
makedirs(video_crop_base_path)
sub_set_base_path = join(lasot_base_path, video_f)
video_base_path = join(sub_set_base_path, video)
gts_path = join(vide... |
def convert_gpt2_checkpoint_to_pytorch(gpt2_checkpoint_path, gpt2_config_file, pytorch_dump_folder_path):
if (gpt2_config_file == ''):
config = GPT2Config()
else:
config = GPT2Config.from_json_file(gpt2_config_file)
model = GPT2Model(config)
load_tf_weights_in_gpt2(model, config, gpt2_ch... |
def main():
display_config()
print('Contructing dataset...')
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
train_dataset = VSR_Dataset(dir=args.train_set, trans=transforms.Compose([RandomCrop(48, args.scale), DataAug(), ToTensor()]))
model_factory = ModelFactory()
model = model_factory.create_mo... |
_ingredient.config
def config():
arch = 'resnet18'
pretrained = True
num_features = 512
dropout = 0.0
norm_layer = None
remap = False
detach = False
normalize = False
set_bn_eval = True
normalize_weight = False |
def test_orbit_setup_lb_uvw_oddunits():
from galpy.orbit import Orbit
o = Orbit([(1.0 * units.rad), ((- 0.25) * units.rad), (3000.0 * units.pc), (((- 30.0) * units.pc) / units.Myr), ((20.0 * units.pc) / units.Myr), ((130.0 * units.pc) / units.Myr)], lb=True, uvw=True)
assert (numpy.fabs((o.ll(quantity=False... |
def _infunc(x, func, gfun, hfun, more_args, epsrel, epsabs):
a = gfun(x)
b = hfun(x)
myargs = ((x,) + more_args)
retval = quad(func, a, b, args=myargs, epsrel=epsrel, epsabs=epsabs)
return retval[0] |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', required=True, choices=['voc', 'coco'], help='Dataset to use')
return parser.parse_args() |
def main(args):
trainer = Trainer(args)
for epoch in range(args.start_epoch, args.epochs):
trainer.training(epoch)
trainer.testing(epoch) |
def _parse_args():
parser = ArgumentParser()
parser.add_argument('--cluster_mode', type=str, default='local', help='The cluster mode, such as local, yarn, standalone or spark-submit.')
parser.add_argument('--master', type=str, default=None, help='The master url, only used when cluster mode is standalone.')
... |
def make_roi_box_predictor(cfg):
func = registry.ROI_BOX_PREDICTOR[cfg.MODEL.ROI_BOX_HEAD.PREDICTOR]
return func(cfg) |
def resize_and_convert(img, size, quality=100):
img = trans_fn.resize(img, size, Image.LANCZOS)
img = trans_fn.center_crop(img, size)
buffer = BytesIO()
img.save(buffer, format='jpeg', quality=quality)
val = buffer.getvalue()
return val |
def get_node_ip():
import socket
import errno
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.8', 80))
node_ip_address = s.getsockname()[0]
except OSError as e:
node_ip_address = '127.0.0.1'
if (e.errno == errno.ENETUNREACH):
tr... |
.parametrize('cfg_file', ['../configs/textrecog/sar/sar_r31_parallel_decoder_academic.py', '../configs/textrecog/abinet/abinet_academic.py', '../configs/textrecog/crnn/crnn_academic_dataset.py', '../configs/textrecog/seg/seg_r31_1by16_fpnocr_academic.py', '../configs/textdet/psenet/psenet_r50_fpnf_600e_icdar2017.py'])
... |
def init_model(args, device, n_gpu, local_rank):
if args.init_model:
model_state_dict = torch.load(args.init_model, map_location='cpu')
else:
model_state_dict = None
cache_dir = (args.cache_dir if args.cache_dir else os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed'))
model ... |
def main(correct, fail=None):
if (fail is not None):
with open(fail, 'r') as f:
test_failures = {l.strip() for l in f.readlines()}
else:
test_failures = None
with open(correct, 'r') as f:
correct_lines = f.readlines()
done_tests = defaultdict(int)
for line in corr... |
class UpSample(nn.Module):
def __init__(self, n_chan, factor=2):
super(UpSample, self).__init__()
out_chan = ((n_chan * factor) * factor)
self.proj = nn.Conv2d(n_chan, out_chan, 1, 1, 0)
self.up = nn.PixelShuffle(factor)
self.init_weight()
def forward(self, x):
fe... |
def masks_union(masks1, masks2):
assert (len(masks1) == len(masks2))
masks_union = ((masks1 + masks2) / 2.0)
return masks_union |
def main():
script_dir = os.path.dirname(os.path.realpath(__file__))
config_file_path = os.path.join(script_dir, 'download_models.json')
download_dir = 'checkpoints'
os.makedirs(download_dir, exist_ok=True)
with open(config_file_path, 'r') as f:
config = json.load(f)
for (url, filename) ... |
def lpips(x: torch.Tensor, y: torch.Tensor, net_type: str='alex', version: str='0.1'):
device = x.device
criterion = LPIPS(net_type, version).to(device)
return criterion(x, y) |
def set_mat(obj: Union[(bpy.types.Object, str)], mat: Union[(bpy.types.Material, str)], recursive: bool=True) -> None:
obj = zpy.objects.verify(obj)
mat = zpy.material.verify(mat)
if hasattr(obj, 'active_material'):
log.debug(f'Setting object {obj.name} material {mat.name}')
obj.active_mater... |
def _get_learningrate(lr, decay):
if (decay is None):
return lr
if (decay[0] == 'inverse time'):
return tf.keras.optimizers.schedules.InverseTimeDecay(lr, decay[1], decay[2])
if (decay[0] == 'cosine'):
return tf.keras.optimizers.schedules.CosineDecay(lr, decay[1], alpha=decay[2])
... |
class Sign2TextTransformerEncoder(FairseqEncoder):
def __init__(self, cfg, feats_type: SignFeatsType, feat_dim: int):
super().__init__(None)
self.num_updates = 0
self.dropout_module = FairseqDropout(p=cfg.dropout, module_name=self.__class__.__name__)
self.embed_scale = math.sqrt(cfg.... |
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--input_model', type=str, required=False, default='tiny-yolov3-11.onnx')
parser.add_argument('--output_model', type=str, required=True)
return parser.parse_args() |
class DreamEnvironment(object):
def __init__(self, abstract_scene_description):
self.description = abstract_scene_description
self.scene_shoppinglists = None
def set_scene_shoppinglist(self, shoppinglist: Type[SceneShoppingList]):
assert isinstance(shoppinglist, SceneShoppingList)
... |
def read_annotations(path: str) -> Tuple[(List[str], List[Dict])]:
results = []
with open(path, 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
try:
header = next(csv_reader, None)
except OSError:
raise OSError(f'Failed to open annotations file ... |
def do_analyze(logdir, base_path=None):
hypes = utils.load_hypes_from_logdir(logdir)
modules = utils.load_modules_from_logdir(logdir)
if (base_path is not None):
hypes['dirs']['base_path'] = base_path
with tf.Graph().as_default():
image_pl = tf.placeholder(tf.float32)
image = tf.... |
def runBody(suite, test):
if isDynamic(suite):
return dynamicRun(suite, test)
else:
return staticRun(suite, test) |
class SynthTextDataLoaderFactory(BaseDataLoader):
def __init__(self, config):
super(SynthTextDataLoaderFactory, self).__init__(config)
dataRoot = self.config['data_loader']['data_dir']
self.workers = self.config['data_loader']['workers']
ds = SynthTextDataset(dataRoot)
(self.... |
class Mean(nn.Module):
def __init__(self, dim, keep_dim=False):
super(Mean, self).__init__()
self.dim = dim
self.keep_dim = keep_dim
def forward(self, input):
return input.mean(self.dim, self.keep_dim) |
def write_data(input_file, output_file, features):
print(input_file)
file_id = (input_file.split('/')[(- 1)].split('.')[(- 3)] if ('.s' in input_file) else input_file.split('/')[(- 1)].split('.')[(- 2)])
file_id = int(file_id)
print(file_id)
(cnf, _) = dimacs_to_cnf(input_file)
(_, r_container) ... |
def _unflatten_params(flat_params, params_example):
unflat_params = []
idx = 0
for (key, param) in params_example.items():
size_param = np.prod(param.shape)
reshaped_param = np.reshape(flat_params[idx:(idx + size_param)], newshape=param.shape)
unflat_params.append((key, reshaped_para... |
def get_arpabet(word, dictionary):
word_arpabet = dictionary.lookup(word)
if (word_arpabet is not None):
return (('{' + word_arpabet[0]) + '}')
else:
return word |
class ActNetwork(nn.Module):
def __init__(self, taskname):
super(ActNetwork, self).__init__()
self.taskname = taskname
self.conv1 = nn.Sequential(nn.Conv2d(in_channels=var_size[taskname]['in_size'], out_channels=16, kernel_size=(1, var_size[taskname]['ker_size'])), nn.BatchNorm2d(16), nn.ReL... |
def mock_wrapper_class() -> Type[Wrapper]:
class MockWrapper(Wrapper[FakeState]):
pass
return MockWrapper |
_module()
class BottomUpAicDataset(BottomUpCocoDataset):
def __init__(self, ann_file, img_prefix, data_cfg, pipeline, test_mode=False):
super(BottomUpCocoDataset, self).__init__(ann_file, img_prefix, data_cfg, pipeline, test_mode=test_mode)
self.ann_info['flip_index'] = [3, 4, 5, 0, 1, 2, 9, 10, 11,... |
def plot_segs(track_segs, cd_scores, xtrack, pred=None, y=None, vabs=None, cbar=True, xticks=True, yticks=True):
cm = LinearSegmentedColormap.from_list(name='orange-blue', colors=[((222 / 255), (85 / 255), (51 / 255)), 'lightgray', ((50 / 255), (129 / 255), (168 / 255))])
if (vabs is None):
vabs = np.ma... |
def test_intersection_with_broadcasting_module2() -> None:
box1 = BoxTensor(torch.tensor([[[[1, 1], [4, 4]], [[2, 2], [5, 5]]]]).float())
assert (box1.box_shape == (1, 2, 2))
box2 = BoxTensor(torch.tensor([[[[3, 3], [7, 6]]], [[[1, 3], [3, 4]]]]).float())
assert (box2.box_shape == (2, 1, 2))
expecte... |
class STSEResUNetIN50(STResUNet50):
NORM_TYPE = NormType.SPARSE_INSTANCE_NORM
BLOCK = SEBottleneckIN |
def get_default_kwargs_q(kwargs_q, layer_type):
default = {'nbits': 4}
if isinstance(layer_type, _Conv2dQ):
default.update({'mode': Qmodes.layer_wise})
elif isinstance(layer_type, _LinearQ):
pass
elif isinstance(layer_type, _ActQ):
pass
else:
assert NotImplementedErro... |
class ModuleSepconv(torch.nn.Module):
def __init__(self):
super(ModuleSepconv, self).__init__()
def forward(self, tensorInput, tensorVertical, tensorHorizontal):
return _FunctionSepconv.apply(tensorInput, tensorVertical, tensorHorizontal) |
_HEADS_REGISTRY.register()
class TridentRes5ROIHeads(Res5ROIHeads):
def __init__(self, cfg, input_shape):
super().__init__(cfg, input_shape)
self.num_branch = cfg.MODEL.TRIDENT.NUM_BRANCH
self.trident_fast = (cfg.MODEL.TRIDENT.TEST_BRANCH_IDX != (- 1))
def forward(self, images, features,... |
def test_statcast_outfielder_jump() -> None:
min_att = 50
result: pd.DataFrame = statcast_outfielder_jump(2019, min_att)
assert (result is not None)
assert (not result.empty)
assert (len(result.columns) == 13)
assert (len(result) > 0)
assert (len(result.loc[(result.n < min_att)]) == 0) |
class CheckpointFunction(t.autograd.Function):
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_tensors = list(args[:length])
ctx.input_params = list(args[length:])
with t.no_grad():
output_tensors = ctx.run_function(*ctx.input_tens... |
class HardtanhDiffSNN(MultivariateDiffThinningAlgorithmMixin, HardtanhActivationMixin, DiffSNNBase):
pass |
class ResNet152FeatModule(nn.Module):
def __init__(self):
super(ResNet152FeatModule, self).__init__()
modules = list(RESNET152_MODEL.children())[:(- 2)]
self.feature_module = nn.Sequential(*modules)
def forward(self, x):
return self.feature_module(x) |
def hotpot_biattention(config, is_train, h, u, h_mask, u_mask, indim, scope=None, tensor_dict=None):
(h_len, u_len) = (tf.shape(h)[1], tf.shape(u)[1])
with tf.variable_scope((scope or 'hotpot_biattention')):
h_dot = tf.squeeze(tf.tile(tf.expand_dims(tf.layers.dense(h, 1), 2), [1, 1, u_len, 1]), axis=(- ... |
class DeepLabHeadV3Plus(nn.Module):
def __init__(self, in_channels, low_level_channels, num_classes, aspp_dilate=[12, 24, 36]):
super(DeepLabHeadV3Plus, self).__init__()
self.project = nn.Sequential(nn.Conv2d(low_level_channels, 48, 1, bias=False), nn.BatchNorm2d(48), nn.ReLU(inplace=True))
... |
def test_d2_skewness(barrel):
skew = barrel.second_derivative_skewness()
assert isinstance(skew, np.ndarray) |
_pipeline_test
class SummarizationPipelineTests(unittest.TestCase, metaclass=PipelineTestCaseMeta):
model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
tf_model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
def get_test_pipeline(self, model, tokenizer, feature_extractor):
summarizer = Summa... |
def require_phonemizer(test_case):
return unittest.skipUnless(is_phonemizer_available(), 'test requires phonemizer')(test_case) |
def parse_int_value(string: str) -> int:
pattern = '\\b\\d+\\b'
integers = [int(num) for num in re.findall(pattern, string)]
return (integers[(- 1)] if (len(integers) > 0) else None) |
def SubnetResNet18(taskcla, nf=32, sparsity=0.5):
return SubnetResNet(SubnetBasicBlock, [2, 2, 2, 2], taskcla, nf, sparsity=sparsity) |
_start_docstrings('Bert Based model to embed queries or document for document retrieval. ', RETRIBERT_START_DOCSTRING)
class RetriBertModel(RetriBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.projection_dim = config.projection_dim
self.bert_query = BertModel(... |
def create_mapping_kernel(kernel_size=7):
kernel_arr = np.zeros(((kernel_size * kernel_size), kernel_size, kernel_size), np.float32)
for h in range(kernel_arr.shape[1]):
for w in range(kernel_arr.shape[2]):
kernel_arr[(((h * kernel_arr.shape[2]) + w), h, w)] = 1.0
kernel_tensor = torch.f... |
class DistMult(BaseModel):
def __init__(self, entity_dict_len, relation_dict_len, embedding_dim, penalty_weight=0.0):
super(DistMult, self).__init__(model_name='DistMult', penalty_weight=penalty_weight)
self.entity_dict_len = entity_dict_len
self.relation_dict_len = relation_dict_len
... |
def get_metamodel(netstr, dim_in, dim_hidden, dim_out, num_layers=4, w0=30.0):
if (netstr == 'siren'):
return MetaSirenNet(dim_in, dim_hidden, dim_out, num_layers, w0=w0, w0_initial=w0)
else:
raise ValueError('no such model exists, mate.') |
def decomp_objective(model, x, K=1, beta=1.0, alpha=0.0, regs=None, components=False):
(qz_x, px_z, zs) = model(x, K)
lpx_z = px_z.log_prob(x).view(*px_z.batch_shape[:2], (- 1)).sum((- 1))
pz = model.pz(*model.pz_params)
kld = kl_divergence(qz_x, pz, samples=zs).sum((- 1))
reg = ((regs(pz.sample(tor... |
class Neural_Engine(Neural_Engine_base):
def accuracy(self, batch_size, seq_len, dataset_name, task_name, data_dir, tokenizer_dir):
log.info('Load dataset ......')
dataset = DataLoader(batch_size, seq_len, dataset_name, task_name, data_dir, tokenizer_dir)
log.info('Load metric ......')
... |
.config
def config():
cub_dir = path.join('data', 'CUB_200_2011')
cub_url = '
images_file = 'images.txt'
train_file = 'train.txt'
test_file = 'test.txt' |
class FlaxKarrasDiffusionSchedulers(Enum):
FlaxDDIMScheduler = 1
FlaxDDPMScheduler = 2
FlaxPNDMScheduler = 3
FlaxLMSDiscreteScheduler = 4
FlaxDPMSolverMultistepScheduler = 5 |
def main() -> None:
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument('source', help='source file or folder')
parser.add_argument('target', help='target ipc file to be saved')
parser.add_argument('--source_type', default=None, choices=['mgf', 'mzml', 'csv... |
def main():
input = np.empty((640, 480), dtype=np.uint8, order='F')
for y in range(480):
for x in range(640):
input[(x, y)] = (x ^ (y + 1))
output = np.empty((640, 480), dtype=np.uint8, order='F')
if False:
(input_buf, output_buf) = (buffer_t(), buffer_t())
for i in r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.