code stringlengths 101 5.91M |
|---|
(signature, parallel=True, cache=True, nogil=False)
def weighted_average_product_PxP_C(config1, config2, weights, q1, q2):
B = config1.shape[0]
M = config1.shape[1]
N = config2.shape[1]
out = np.zeros((M, N, q1, q2), dtype=curr_float)
for m in prange(M):
for n in prange(N):
for b... |
def _graphsLoad(gs: List[Graph], add: bool) -> List[Graph]:
us = _unwrap(gs)
res = [_graphLoad(a, name=None, add=add) for a in us]
return res |
def unflatten(arr, shape):
size = np.prod(shape)
head = ((np.uint64(arr[:size]) << 32) | np.uint64(arr[size:(2 * size)]))
return (np.reshape(head, shape), (arr[(2 * size):], ())) |
def generate_pretrained_model():
((x_train, y_train), (x_test, y_test)) = cifar10.load_data()
input_shape = x_train.shape[1:]
x_train = (x_train.astype('float32') / 255)
x_test = (x_test.astype('float32') / 255)
x_train_mean = np.mean(x_train, axis=0)
x_train -= x_train_mean
x_test -= x_trai... |
def _find_quantized_op_num(module, op_qcfgs, prefix='', op_count=0):
for (name_tmp, child_tmp) in module.named_children():
op_name = (((prefix + '.') + name_tmp) if (prefix != '') else name_tmp)
if ((op_name in op_qcfgs.keys()) and (type(child_tmp) != torch.quantization.QuantStub)):
op_c... |
class AdditiveKernels(KernelBase):
def __init__(self, k1, k2):
super().__init__()
self.k1 = k1
self.k2 = k2
def __call__(self, x, y):
return (self.k1(x, y) + self.k2(x, y)) |
def num_prompts(data):
pmts = set()
for row in data:
pmts.add(((row[2] + row[3]) + row[4]))
return len(pmts) |
class Object3d(BEVBox3D):
def __init__(self, center, size, yaw, name, box):
super().__init__(center, size, yaw, name, (- 1.0))
self.occlusion = box['occlusion']
self.quaternion = box['quaternion']
self.coords_3d = box['3d_coord']
self.coords_2d = box['2d_coord']
def gener... |
def points_to_bev(points, voxel_size, coors_range, with_reflectivity=False, density_norm_num=16, max_voxels=40000):
if (not isinstance(voxel_size, np.ndarray)):
voxel_size = np.array(voxel_size, dtype=points.dtype)
if (not isinstance(coors_range, np.ndarray)):
coors_range = np.array(coors_range,... |
def sigmoid_2(x, mu, sd):
xn = ((x - mu) / sd)
sig = torch.sigmoid(xn)
s = sig
js = (((1 / sd) * sig) * (1 - sig))
jjs = ((((1 / (sd ** 2)) * sig) * (1 - sig)) * (1 - (2 * sig)))
return (s, js, jjs) |
def generate_random_targets(labels: Tensor, num_classes: int) -> Tensor:
random = torch.rand(len(labels), num_classes, device=labels.device, dtype=torch.float)
random.scatter_(1, labels.unsqueeze((- 1)), 0)
return random.argmax(1) |
def get_local_size() -> int:
if (not dist.is_available()):
return 1
if (not dist.is_initialized()):
return 1
return dist.get_world_size(group=LOCAL_PROCESS_GROUP) |
class Prior(nn.Module):
def __init__(self):
super().__init__()
def sample(self, **kwargs):
raise NotImplementedError
def log_p(self, input, **kwargs):
return self.forward(z)
def forward(self, input, **kwargs):
raise NotImplementedError
def __str__(self):
raise... |
class Server(ABC):
def __init__(self, config, network_config, model, test_loader, seed, optimizer_class: Type, optimizer_params: dict, use_adaptive, use_evaluate=True, lr_scheduler_class=None, lr_scheduler_params=None, control=None, control_scheduler=None, resume=False, init_time_offset=0.0):
self.config = ... |
def equishwidth(elem, spec, specerr, refspec=None):
if (refspec is None):
refspec = numpy.zeros_like(spec)
win = read(elem, apStarWavegrid=True)
(startindxs, endindxs) = waveregions(elem, asIndex=True, pad=0)
lams = apStarWavegrid()
startlams = lams[startindxs]
endlams = lams[endindxs]
... |
class PyrBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride):
super(PyrBlock, self).__init__()
self.conv1 = pre_conv3x3_block(in_channels=in_channels, out_channels=out_channels, stride=stride, activate=False)
self.conv2 = pre_conv3x3_block(in_channels=out_channels, out_ch... |
class BasicBlock(nn.Module):
def __init__(self, in_chs, out_chs, kernel_size=3, stride=1, dilation=(1, 1), group_size=None, bottle_ratio=1.0, downsample='avg', linear_out=False, layers: LayerFn=None, drop_block=None, drop_path_rate=0.0):
super(BasicBlock, self).__init__()
layers = (layers or LayerFn... |
(scope='module')
def simple_dtype():
ld = np.dtype('longdouble')
return np.dtype({'names': ['bool_', 'uint_', 'float_', 'ldbl_'], 'formats': ['?', 'u4', 'f4', f'f{ld.itemsize}'], 'offsets': [0, 4, 8, (16 if (ld.alignment > 4) else 12)]}) |
class EsmModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def matthews_corrcoef(predictions, targets) -> dict:
return {'matthews_correlation': (100 * sklearn.metrics.matthews_corrcoef(targets, predictions))} |
class CosineSchedule(FairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
if (len(args.lr) > 1):
raise ValueError('Cannot use a fixed learning rate schedule with cosine. Consider --lr-scheduler=fixed instead.')
warmup_end_lr = args.max_lr
... |
class FocalLoss(nn.Module):
def __init__(self, gamma=0, size_average=True):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.size_average = size_average
def forward(self, input, target):
target = target.view((- 1), 1)
logpt = F.log_softmax(input, dim=1)
l... |
class CNNEncoder(BaseEncoder):
def __init__(self, latent_dimensions: int, feature_size: Iterable, variational: bool=False, channels: tuple=None, kernel_sizes: tuple=None, strides: tuple=None, paddings: tuple=None, activation=nn.LeakyReLU(), dropout=0):
super(CNNEncoder, self).__init__(latent_dimensions, var... |
class ShuffleNetV2(nn.Module):
def __init__(self, stages_repeats, stages_out_channels, num_classes=1000):
super(ShuffleNetV2, self).__init__()
if (len(stages_repeats) != 3):
raise ValueError('expected stages_repeats as list of 3 positive ints')
if (len(stages_out_channels) != 5):... |
class Sentiment(_Sentiment):
def load(self, path=None):
_Sentiment.load(self, path)
if (not path):
for (w, pos) in list(dict.items(self)):
if ('JJ' in pos):
if w.endswith('y'):
w = (w[:(- 1)] + 'i')
if w.ends... |
((_HAS_VIDEO_OPT is False), "Didn't compile with ffmpeg")
class TestVideo(unittest.TestCase):
_SKIP
((av is None), 'PyAV unavailable')
def test_read_video_tensor(self):
torchvision.set_video_backend('pyav')
for (test_video, config) in test_videos.items():
full_path = os.path.join... |
def TestFlag(flag, test_val, default_val):
env_var = ('GTEST_' + flag.upper())
SetEnvVar(env_var, test_val)
AssertEq(test_val, GetFlag(flag))
SetEnvVar(env_var, None)
AssertEq(default_val, GetFlag(flag)) |
def _run_tensor_parallel_optimization(num_nodes=1, num_devices_per_node=2):
torch.manual_seed(42)
model_context = create_model_context()
parallel_optimization = TensorParallelOptimization(shard_planner='base', num_nodes=num_nodes, num_devices_per_node=num_devices_per_node, tracer_backend='meta_fx', prop_mod... |
class TestReproducibility(unittest.TestCase):
def _test_reproducibility(self, name, extra_flags=None, delta=0.0001, resume_checkpoint='checkpoint1.pt', max_epoch=3):
if (extra_flags is None):
extra_flags = []
with tempfile.TemporaryDirectory(name) as data_dir:
with self.asser... |
def post_processing_function(examples, features, predictions, stage='eval'):
predictions = postprocess_qa_predictions(examples=examples, features=features, predictions=predictions, version_2_with_negative=args.version_2_with_negative, n_best_size=args.n_best_size, max_answer_length=args.max_answer_length, null_scor... |
def replace_tags_board(board_san):
board_san = board_san.split(' ')[0]
board_san = board_san.replace('2', '11')
board_san = board_san.replace('3', '111')
board_san = board_san.replace('4', '1111')
board_san = board_san.replace('5', '11111')
board_san = board_san.replace('6', '111111')
board_... |
class Joint(xmlr.Object):
TYPES = ['unknown', 'revolute', 'continuous', 'prismatic', 'floating', 'planar', 'fixed']
def __init__(self, name=None, parent=None, child=None, joint_type=None, axis=None, origin=None, limit=None, dynamics=None, safety_controller=None, calibration=None, mimic=None, hardwareInterface=N... |
def evaluate(model):
from neural_compressor.model import Model
from neural_compressor import Metric
model = Model(model)
input_tensor = model.input_tensor
output_tensor = (model.output_tensor if (len(model.output_tensor) > 1) else model.output_tensor[0])
iteration = (- 1)
if (FLAGS.benchmark... |
def average_gradients(tower_grads):
average_grads = []
for grad_and_vars in zip(*tower_grads):
grads = []
for (g, _) in grad_and_vars:
expanded_g = tf.expand_dims(g, 0)
grads.append(expanded_g)
grad = tf.concat(0, grads)
grad = tf.reduce_mean(grad, 0)
... |
_sentencepiece
_tokenizers
class TestMarian_EN_DE_More(MarianIntegrationTest):
def test_forward(self):
(src, tgt) = (['I am a small frog'], ['Ich bin ein kleiner Frosch.'])
expected_ids = [38, 121, 14, 697, 38848, 0]
model_inputs: dict = self.tokenizer.prepare_seq2seq_batch(src, tgt_texts=tg... |
_REGISTRY.register()
def build_mnv2_backbone(cfg, input_shape):
out_features = cfg.MODEL.RESNETS.OUT_FEATURES
out_feature_channels = {'res2': 24, 'res3': 32, 'res4': 96, 'res5': 320}
out_feature_strides = {'res2': 4, 'res3': 8, 'res4': 16, 'res5': 32}
model = MobileNetV2(cfg)
model._out_features = o... |
def test_double_double_syspool(vrblvl=0):
initialize_double_double_syspool(3, vrblvl)
dim = size_double_double_syspool(vrblvl)
print('The size of the systems pool :', dim)
pol1 = ['t - 1/3;']
set_double_double_system(1, pol1, vrblvl)
copy_to_double_double_syspool(1)
pol2 = ['t - 2/3;']
s... |
def main(args):
in_dir = os.path.join(args.in_dir, args.exp, args.custom_dir)
out_dir = os.path.join(args.out_dir, args.exp, args.custom_dir)
os.makedirs(out_dir, exist_ok=True)
exp_util.clear_dir(out_dir)
logger = exp_util.get_logger(os.path.join(out_dir, 'log.txt'))
logger.info(args)
logge... |
def vgg16_bn_128(pretrained=False, **kwargs):
model = VGG(make_layers(cfg['D_128'], batch_norm=True), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg16_bn']))
return model |
def grid_search(model_constructor, train_data, dev_data, config, acc_priors, balance_priors, epochs, label_to_ix):
best_p = float('-inf')
best_r = float('-inf')
best_f1 = float('-inf')
best_params = None
best_acc_prior = None
best_balance_prior = None
for acc_prior in acc_priors:
for... |
def get_wavelength_from_header(hdr):
if (('CRVAL1' and ('CRPIX1' in hdr.keys())) and (('CDELT1' in hdr.keys()) or ('CD1_1' in hdr.keys()))):
if ('CD1_1' in hdr.keys()):
cdelt = hdr['CD1_1']
else:
cdelt = hdr['CDELT1']
crval = hdr['CRVAL1']
crpix = hdr['CRPIX1'... |
def change_label(tree, new_label, span=None, cur_label=None, in_place=True):
if ((span is None) and (cur_label is None)):
return change_label_by_node(tree, new_label, in_place)
elif ((span is not None) and (cur_label is not None)):
return change_label_by_span(tree, new_label, span, cur_label, in... |
def worker_init_fn(worker_id, num_workers, rank, seed):
worker_seed = (((num_workers * rank) + worker_id) + seed)
np.random.seed(worker_seed)
random.seed(worker_seed)
torch.manual_seed(worker_seed) |
class SolutionInstance():
def __init__(self, objVal, X, Y, W, H, solNo):
self.X = X
self.Y = Y
self.W = W
self.H = H
self.objVal = objVal
self.solNo = solNo |
class GraphIR():
vars: Dict[(str, AbsTensor)] = field(default_factory=dict)
insts: List[InstIR] = field(default_factory=list)
def __str__(self) -> str:
ret = ''
for inst in self.insts:
ret += f'''{inst}
'''
return ret
def pretty(self) -> str:
inst_remap = {ins... |
def get_model(outputs, width, height, scale, n_patches, patch_size, reg):
x_in = Input(shape=(height, width, 3))
x_high = ImageLinearTransform()(x_in)
x_high = ImagePan(horizontally=True, vertically=True)(x_high)
x_low = ResizeImages((int((height * scale)), int((width * scale))))(x_high)
(features, ... |
def transferFileToHdfsPath(sourcepath, targetpath):
hdfspath = targetpath
targetdir = os.path.dirname(targetpath)
os.system('/opt/hadoop/latest/bin/hdfs dfs -mkdir -p {}'.format(targetdir))
result = os.system('/opt/hadoop/latest/bin/hdfs dfs -copyFromLocal -f {} {}'.format(sourcepath, hdfspath))
if ... |
def get_model_fwk_name(model):
onnx = LazyImport('onnx')
tf = LazyImport('tensorflow')
torch = LazyImport('torch')
def _is_onnxruntime(model):
if isinstance(model, str):
try:
graph = onnx.load(model)
assert (len(graph.graph.node) != 0)
exce... |
def dynamic_import_st(module, backend):
model_class = dynamic_import(module, predefined_st.get(backend, dict()))
assert issubclass(model_class, STInterface), f'{module} does not implement STInterface'
return model_class |
def resnet50(pretrained=False, **kwargs):
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(torch.load(os.path.join(models_dir, model_name['resnet50'])))
return model |
def im_detect_bbox(model, images, target_scale, target_max_size, device, rois=None):
transform = T.Compose([T.Resize(target_scale, target_max_size), T.ToTensor(), T.Normalize(mean=cfg.INPUT.PIXEL_MEAN, std=cfg.INPUT.PIXEL_STD, to_bgr255=cfg.INPUT.TO_BGR255)])
t_images = []
t_rois = []
for (image, roi) i... |
def prepare_img(image, label, num_classes):
if (args.data_set == 'Imagenet'):
image = tf.image.resize(image, [224, 224])
elif (args.data_set == 'Cifar10'):
image = tf.image.resize(image, [32, 32])
label = tf.squeeze(label)
label = tf.one_hot(label, num_classes)
return (image, label) |
class BaseARD(torch.nn.Module):
def penalty(self):
raise NotImplementedError('Derived classes must compute their own penalty.')
def relevance(self, **kwargs):
raise NotImplementedError('Derived classes must implement a float mask of relevant coefficients.') |
def require_set_backend():
assert (backend is not None), 'distributed backend is not set. Please call `distributed_utils.set_backend_from_args` at the start of your script' |
def presnet152(pretrained=False, **kwargs):
return presnet(Bottleneck, [3, 8, 36, 3], 'presnet152', pre=pretrained, **kwargs) |
def inference_multi_modality_detector(model, pcd, image, ann_file):
cfg = model.cfg
device = next(model.parameters()).device
test_pipeline = deepcopy(cfg.data.test.pipeline)
test_pipeline = Compose(test_pipeline)
(box_type_3d, box_mode_3d) = get_box_type(cfg.data.test.box_type_3d)
data_infos = m... |
def main():
args = get_args()
task_name = 'Task043_BraTS2019'
downloaded_data_dir = args.downloaded_data_dir
target_base = join(nnUNet_raw_data, task_name)
target_imagesTr = join(target_base, 'imagesTr')
target_imagesVal = join(target_base, 'imagesVal')
target_imagesTs = join(target_base, 'i... |
def statcast_date_range(start: date, stop: date, step: int, verbose: bool=True) -> Iterator[Tuple[(date, date)]]:
low = start
while (low <= stop):
date_span = (low.replace(month=3, day=15), low.replace(month=11, day=15))
(season_start, season_end) = STATCAST_VALID_DATES.get(low.year, date_span)
... |
class RunningSampleData():
index: int
session_id: int
session: Session
asyncio_task: asyncio.Task
def __init__(self, index, session_id, session, task):
self.index = index
self.session_id = session_id
self.session = session
self.asyncio_task = task |
class EnvironmentCommand(BaseTransformersCLICommand):
def register_subcommand(parser: ArgumentParser):
download_parser = parser.add_parser('env')
download_parser.set_defaults(func=info_command_factory)
def run(self):
pt_version = 'not installed'
pt_cuda_available = 'NA'
i... |
class Nlvr2PairedDataset(DetectFeatTxtTokDataset):
def __init__(self, txt_db, img_db, use_img_type=True):
assert isinstance(txt_db, TxtTokLmdb)
assert isinstance(img_db, DetectFeatLmdb)
self.txt_db = txt_db
self.img_db = img_db
(txt_lens, self.ids) = get_ids_and_lens(txt_db)
... |
class Collator():
def __init__(self, image_size, url_label, text_label, image_label, name, channels):
self.url_label = url_label
self.text_label = text_label
self.image_label = image_label
self.download = (url_label is not None)
self.name = name
self.channels = channe... |
def collect_annotations(files, dataset, nproc=1):
assert isinstance(files, list)
assert isinstance(dataset, str)
assert dataset
assert isinstance(nproc, int)
load_img_info_with_dataset = partial(load_img_info, dataset=dataset)
if (nproc > 1):
images = mmcv.track_parallel_progress(load_im... |
def atari_learn(env, args, num_timesteps):
logdir = os.path.join('data', args.exp_name)
num_iterations = (float(num_timesteps) / 4.0)
def stopping_criterion(env):
return (get_wrapper_by_name(env, 'Monitor').get_total_steps() >= num_timesteps)
optimizer_spec = OptimizerSpec(constructor=optim.Adam... |
class TileExtraData(BBAStruct):
name_prefix: IdString
tile_x: int
tile_y: int
sites: list[SiteInst] = field(default_factory=list)
def serialise_lists(self, context: str, bba: BBAWriter):
for (i, site) in enumerate(self.sites):
site.serialise_lists(f'{context}_si{i}', bba)
... |
def get_averaged_groupby(df, groupby, plot_column):
return df.groupby(groupby)[plot_column].apply(np.mean) |
def export_model(input_model, output_model):
print('\nexport model...')
model = onnx.load(input_model)
model = version_converter.convert_version(model, 14)
onnx.save_model(model, output_model) |
class VAE(Model):
def __init__(self, args):
super(VAE, self).__init__(args)
if (self.args.dataset_name == 'freyfaces'):
h_size = 210
elif (self.args.dataset_name == 'cifar10'):
h_size = 384
else:
h_size = 294
self.q_z2_layers = nn.Sequentia... |
def add_dataset_config(cfg):
_C = cfg
_C.MODEL.ROI_HEADS.NUM_OUTPUT_CLASSES = 80
_C.MODEL.ROI_HEADS.EMBEDDINGS_PATH = ''
_C.MODEL.ROI_HEADS.EMBEDDINGS_PATH_COCO = ''
_C.MODEL.ROI_HEADS.LINGUAL_MATRIX_THRESHOLD = 0.05
_C.MODEL.ROI_HEADS.MASK_NUM_CLASSES = 80
_C.MODEL.FREEZE_LAYERS = CN()
... |
class AttnSkipUpBlock2DTests(UNetBlockTesterMixin, unittest.TestCase):
block_class = AttnSkipUpBlock2D
block_type = 'up'
def dummy_input(self):
return super().get_dummy_input(include_res_hidden_states_tuple=True)
def test_output(self):
expected_slice = [0.0361, 0.0617, 0.2787, (- 0.035),... |
class PreActResNet(nn.Module):
def __init__(self, num_classes: int=10, depth: int=18, width: int=0, activation_fn: nn.Module=nn.ReLU, mean: Union[(Tuple[(float, ...)], float)]=CIFAR10_MEAN, std: Union[(Tuple[(float, ...)], float)]=CIFAR10_STD, padding: int=0, num_input_channels: int=3):
super().__init__()
... |
def to_bigdl_optim_method(optimizer):
optimizer = optimizer.lower()
if (optimizer == 'adagrad'):
return Adagrad(learningrate=0.01)
elif (optimizer == 'sgd'):
return SGD(learningrate=0.01)
elif (optimizer == 'adam'):
return Adam()
elif (optimizer == 'rmsprop'):
return ... |
def build_and_train(slot_affinity_code, log_dir, run_ID, config_key):
affinity = affinity_from_code(slot_affinity_code)
config = configs[config_key]
variant = load_variant(log_dir)
config = update_config(config, variant)
sampler = AsyncCpuSampler(EnvCls=gym_make, env_kwargs=config['env'], CollectorC... |
def mkdir_p(path):
try:
os.makedirs(os.path.abspath(path))
except OSError as exc:
if ((exc.errno == errno.EEXIST) and os.path.isdir(path)):
pass
else:
raise |
def check_all_inits():
failures = []
for (root, _, files) in os.walk(PATH_TO_TRANSFORMERS):
if ('__init__.py' in files):
fname = os.path.join(root, '__init__.py')
objects = parse_init(fname)
if (objects is not None):
errors = analyze_results(*objects)
... |
_module()
class WIDERFaceDataset(XMLDataset):
CLASSES = ('face',)
PALETTE = [(0, 255, 0)]
def __init__(self, **kwargs):
super(WIDERFaceDataset, self).__init__(**kwargs)
def load_annotations(self, ann_file):
data_infos = []
img_ids = mmcv.list_from_file(ann_file)
for img_i... |
class CategoricalMLPRegressor(StochasticRegressor):
def __init__(self, input_shape, output_dim, name='CategoricalMLPRegressor', hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), output_n... |
def find_all_best_thresh(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans):
(best_exact, exact_thresh) = find_best_thresh(preds, exact_raw, na_probs, qid_to_has_ans)
(best_f1, f1_thresh) = find_best_thresh(preds, f1_raw, na_probs, qid_to_has_ans)
main_eval['best_exact'] = best_exact
main_ev... |
class EMAML():
def __init__(self, dim_input, dim_output, dim_hidden=32, num_layers=4, num_particles=2, max_test_step=5):
self.dim_input = dim_input
self.dim_output = dim_output
self.dim_hidden = dim_hidden
self.num_layers = num_layers
self.num_particles = num_particles
... |
def is_trained(cfg: NamespaceMap, stage: str, is_force_retrain: bool=False) -> bool:
pretrained_path = Path(cfg.paths.pretrained.save)
filename = BEST_CHECKPOINT.format(stage=stage)
if (is_force_retrain and (pretrained_path / filename).is_file()):
results_path = Path(cfg.paths.results)
ckpt_... |
class ORTModel():
def __init__(self, model: Union[(str, os.PathLike)], compute_metrics: Optional[Callable[([EvalPrediction], Dict)]]=None, label_names: Optional[List[str]]=None):
self.compute_metrics = compute_metrics
self.label_names = (['labels'] if (label_names is None) else label_names)
... |
class ResLayer(Sequential):
def __init__(self, block, inplanes, planes, num_blocks, stride=1, dilation=1, avg_down=False, conv_cfg=None, norm_cfg=dict(type='BN'), multi_grid=None, contract_dilation=False, **kwargs):
self.block = block
downsample = None
if ((stride != 1) or (inplanes != (plan... |
def save_blip_diffusion_model(model, args):
qformer = get_qformer(model)
qformer.eval()
text_encoder = ContextCLIPTextModel.from_pretrained('runwayml/stable-diffusion-v1-5', subfolder='text_encoder')
vae = AutoencoderKL.from_pretrained('runwayml/stable-diffusion-v1-5', subfolder='vae')
unet = UNet2D... |
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(((16 * 5) * 5), 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
... |
def zscore_from_pval(pval, one_minus_pval=None, distrib='norm'):
if (distrib == 'norm'):
zscore = norm.isf(pval)
if (one_minus_pval is not None):
ind = (pval > 0.5)
zscore[ind] = norm.ppf(one_minus_pval[ind])
zscore = _replace_infinity(zscore, replace_val=40, method='plus... |
class Cell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev, SE=False):
super(Cell, self).__init__()
print(C_prev_prev, C_prev, C)
self.se_layer = None
if reduction_prev:
self.preprocess0 = FactorizedReduce(C_prev_prev, C)
... |
def dump_topset(topset: Dict[(str, OpConfig)], path: PathLike):
OmegaConf.save({'topset': topset}, path) |
_builder('msvd_caption')
class MSVDCapBuilder(BaseDatasetBuilder):
train_dataset_cls = VideoCaptionDataset
eval_dataset_cls = VideoCaptionEvalDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/msvd/defaults_cap.yaml'} |
class Triple():
def __init__(self, s, p, o):
self.s = s
self.o = o
self.p = p |
def last_zero_init(m):
if isinstance(m, nn.Sequential):
constant_init(m[(- 1)], val=0)
m[(- 1)].inited = True
else:
constant_init(m, val=0)
m.inited = True |
def rlagru_resnet101_eca(rla_channel=32, k_size=[5, 5, 5, 7]):
print('Constructing rlagru_resnet101_eca......')
model = RLAgru_ResNet(RLA_Bottleneck, [3, 4, 23, 3], rla_channel=rla_channel, ECA=k_size)
return model |
def read_image_RGB(img_path):
got_img = False
if (not osp.exists(img_path)):
raise IOError('{} does not exist'.format(img_path))
while (not got_img):
try:
img = Image.open(img_path).convert('RGB')
got_img = True
except IOError:
print("IOError incur... |
def main(args):
if args.kitti_to_yolo_labels:
from utils.utils import kitti_labels_to_yolo
kitti_labels_to_yolo(args.kitti_to_yolo_labels)
exit()
cudnn.benchmark = True
start_time = datetime.now()
log.info(' NEW RUN ')
log.info(f"Running: {' '.join(sys.argv)}")
log.info('... |
def make_gsm_loss_evaluator(cfg):
loss_evaluators = dict()
loss_weights = dict()
if ('l1_loss' in cfg.model.losses):
l1_loss_evaluator = make_sll_loss_evaluator(cfg)
loss_evaluators['l1_loss'] = l1_loss_evaluator
loss_weights['l1_loss'] = cfg.model.losses.l1_loss.weight
if ('gerf... |
class TrainingInterface():
def __init__(self, device, model, parallel, log_path_mng, data_loaders, summary_writers, opt_scheduler, param_scheduler, n_epoch, **kwargs):
self.model = model
self.model.device = device
if parallel:
self.model = nn.DataParallel(self.model)
self... |
class DenseProjection(nn.Module):
def __init__(self, in_channels, nr, scale, up=True, bottleneck=True):
super(DenseProjection, self).__init__()
if bottleneck:
self.bottleneck = nn.Sequential(*[nn.Conv2d(in_channels, nr, 1), nn.PReLU(nr)])
inter_channels = nr
else:
... |
def main():
parser = argparse.ArgumentParser(description='Supplement dataset')
parser.add_argument('--data', type=str, required=True, help='Block data file to use (e.g. inputs/data/time_skylake.data')
parser.add_argument('--embedding', type=str, required=True, help='Token embedding file to use (e.g. inputs/... |
class BaseNetwork(nn.Module):
def __init__(self):
super(BaseNetwork, self).__init__()
def modify_commandline_options(parser, is_train):
return parser
def print_network(self):
if isinstance(self, list):
self = self[0]
num_params = 0
for param in self.parame... |
def get_final_path(closed, goal_node):
(reversed_x, reversed_y, reversed_yaw) = (list(reversed(goal_node.x_list)), list(reversed(goal_node.y_list)), list(reversed(goal_node.yaw_list)))
direction = list(reversed(goal_node.directions))
nid = goal_node.parent_index
final_cost = goal_node.cost
while nid... |
class FasterRCNNResnetV1FeatureExtractor(faster_rcnn_meta_arch.FasterRCNNFeatureExtractor):
def __init__(self, architecture, resnet_model, is_training, first_stage_features_stride, reuse_weights=None, weight_decay=0.0):
if ((first_stage_features_stride != 8) and (first_stage_features_stride != 16)):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.