code stringlengths 101 5.91M |
|---|
class Evaluation():
def __init__(self, args):
if (args.dataset == 'coco'):
self.num_classes = 80
if (args.dataset == 'voc'):
self.num_classes = 20
self.num_folds = 4
self.group_class_num = (self.num_classes / 4)
self.batch_size = args.batch_size
... |
def run_tcl_exp(args, config):
stepDict = {1: [int(5000.0), int(5000.0)], 2: [int(10000.0), int(10000.0)], 3: [int(10000.0), int(10000.0)], 4: [int(10000.0), int(10000.0)], 5: [int(10000.0), int(10000.0)]}
data_dim = config.data_dim
n_segments = config.n_segments
n_layers = config.n_layers
n_obs_per... |
def get_coord_values(field_line):
fl_coordinates = field_line.coords
fl_coordinates = check_field_line_alignment(fl_coordinates)
fl_r = (fl_coordinates.radius.value / aconst.R_sun.value)
fl_lon = fl_coordinates.lon.value
fl_lat = fl_coordinates.lat.value
return (fl_r, fl_lon, fl_lat) |
def ReScaleSize_STARE(image, re_size=512):
(w, h) = image.size
max_len = max(w, h)
(new_w, new_h) = (max_len, max_len)
delta_w = (new_w - w)
delta_h = (new_h - h)
padding = ((delta_w // 2), (delta_h // 2), (delta_w - (delta_w // 2)), (delta_h - (delta_h // 2)))
image = ImageOps.expand(image,... |
def quantize_model_(model, size_tracker, layers_to_quantize, block_sizes_config, n_centroids_config, step=0, n_iter=15, eps=1e-06, max_tentatives=100, verbose=True):
quantized_layers = get_layers(model, layers_to_quantize[step])
for layer in quantized_layers:
is_master_process = ((not dist.is_initialize... |
def estimate_latent_channels(extractor, train_loader):
device = next(extractor.parameters()).device
feats = []
i_samples = 0
for (i, normal_img) in enumerate(train_loader):
with torch.no_grad():
feat = extractor(normal_img.to(device))
(b, c) = feat.shape[:2]
feat = fe... |
class ToIterableDataset(data.IterableDataset):
def __init__(self, dataset: data.Dataset, sampler: Sampler, shard_sampler: bool=True, shard_chunk_size: int=1):
assert (not isinstance(dataset, data.IterableDataset)), dataset
assert isinstance(sampler, Sampler), sampler
self.dataset = dataset
... |
_model
def regnetx_016(pretrained=False, **kwargs):
return _create_regnet('regnetx_016', pretrained, **kwargs) |
class ControlNet(ExamplesTestsAccelerate):
def test_controlnet_checkpointing_checkpoints_total_limit(self):
with tempfile.TemporaryDirectory() as tmpdir:
test_args = f'''
examples/controlnet/train_controlnet.py
--pretrained_model_name_or_path=hf-internal-testing/tiny-stab... |
(autouse=True)
def _requests_prevent_post(monkeypatch: MonkeyPatch, thrower: Callable, logging_side_effect: Callable) -> MagicMock:
mock = MagicMock(side_effect=logging_side_effect(f'requests.post', after=thrower))
monkeypatch.setattr(requests, 'post', mock)
return mock |
class Argument():
_support_types = [ArgType.INT, ArgType.STR, ArgType.FLOAT, ArgType.NULL, ArgType.TUPLE, ArgType.LIST, ArgType.BOOL]
_int_values = [(- 1024), (- 16), (- 1), 0, 1, 16, 1024]
_str_values = ['mean', 'sum', 'max', 'zeros', 'reflect', 'circular', 'replicate']
_float_values = [0.0, 1.0, (- 1.... |
def compute_files(user1, user2, file_list, dir_pre, start_num):
match_total = 0
test_total = 0
gold_total = 0
for fi in file_list:
file1 = ((((dir_pre + user1) + '/') + fi) + '.txt')
file2 = ((((dir_pre + user2) + '/') + fi) + '.txt')
if (not os.path.exists(file1)):
p... |
def get_root_dir():
from . import data
abs_dir = os.path.abspath(data.__file__)
return os.path.split(os.path.split(os.path.split(abs_dir)[0])[0])[0] |
def _make_factorized_antisymmetries():
(key, ion_pos, ion_charges, init_pos, spin_split, ndense_list) = _get_initial_pos_and_hyperparams()
compute_input_streams = _get_compute_input_streams(ion_pos)
backflow = _get_backflow(spin_split, ndense_list, cyclic_spins=False, use_transformer=False, num_heads=1)
... |
def test_convert_SyncBN():
cfg = _get_config_module('pointpillars/hv_pointpillars_fpn_sbn-all_4x8_2x_nus-3d.py')
model_cfg = cfg.model
convert_SyncBN(model_cfg)
assert (model_cfg['pts_voxel_encoder']['norm_cfg']['type'] == 'BN1d')
assert (model_cfg['pts_backbone']['norm_cfg']['type'] == 'BN2d')
... |
def get_charge(pid):
abs_pid = abs(pid)
if (pid in [130, 22, 1, 2]):
return 0.0
elif (abs_pid in [11, 13]):
return (- math.copysign(1.0, pid))
elif (abs_pid in [211]):
return math.copysign(1.0, pid)
else:
raise Exception('Unknown pid: ', pid) |
def main(opt, data_root='/data/MOT16/train', det_root=None, seqs=('MOT16-05',), exp_name='demo', save_images=False, save_videos=False, show_image=True):
logger.setLevel(logging.INFO)
result_root = os.path.join('results/mots', exp_name, 'quantitive')
mkdir_if_missing(result_root)
accs = []
n_frame = ... |
class BatchSamplerSafe(Sampler):
def __init__(self, algo, **kwargs):
self.algo = algo
self.experience_replay = []
self.env_interacts_memory = []
self.env_interacts = 0
self.total_env_interacts = 0
self.mean_path_len = 0
self.use_safety_bonus = (self.algo.safet... |
def add_time(temporal_data):
times = np.repeat(np.arange(temporal_data.shape[1]).reshape(1, (- 1), 1), len(temporal_data), 0)
temporal_data = np.concatenate([times, temporal_data], axis=(- 1))
return temporal_data |
class rSoftMax(nn.Module):
def __init__(self, radix, cardinality):
super().__init__()
self.radix = radix
self.cardinality = cardinality
def forward(self, x):
batch = x.size(0)
if (self.radix > 1):
x = x.view(batch, self.cardinality, self.radix, (- 1)).transpos... |
def create_training_images(fn, i):
dest = (path_lr / fn.relative_to(path_hr))
dest.parent.mkdir(parents=True, exist_ok=True)
img = PIL.Image.open(fn).convert('LA').convert('RGB')
img.save(dest) |
def interleave(x, bt):
s = list(x.shape)
res = torch.reshape(torch.transpose(x.reshape(([(- 1), bt] + s[1:])), 1, 0), ([(- 1)] + s[1:]))
return res |
class TorchGate(torch.nn.Module):
_grad()
def __init__(self, sr: int, nonstationary: bool=False, n_std_thresh_stationary: float=1.5, n_thresh_nonstationary: float=1.3, temp_coeff_nonstationary: float=0.1, n_movemean_nonstationary: int=20, prop_decrease: float=1.0, n_fft: int=1024, win_length: bool=None, hop_len... |
def evaluate(encoder, args, batch_trains, classifier, classifiers, eval_sents, domain_encs):
good_sent = bad_sent = good = bad = 0.0
for sent in eval_sents:
(words, golds) = zip(*sent)
probs = [ath(encoder(words, volatile=True)) for ath in classifiers]
outputs = sum(probs)
tags =... |
def evaluate(model, data_loader, device, num_classes):
model.eval()
confmat = utils.ConfusionMatrix(num_classes)
metric_logger = utils.MetricLogger(delimiter=' ')
header = 'Test:'
with torch.no_grad():
for (image, target) in metric_logger.log_every(data_loader, 100, header):
(im... |
def explore(config):
if (config['train_batch_size'] < (config['sgd_minibatch_size'] * 2)):
config['train_batch_size'] = (config['sgd_minibatch_size'] * 2)
if (config['num_sgd_iter'] < 1):
config['num_sgd_iter'] = 1
config['target_delay'] = int(config['target_delay'])
return config |
def count_objects(obj_info_list):
counts = np.zeros((n_class,))
n_frames = np.zeros(n_class)
ped_hist = []
cyc_hist = []
car_hist = []
for obj_info in obj_info_list:
flags = np.zeros(n_class)
counts_in_frame = np.zeros(n_class)
for obj in obj_info:
class_id = ... |
def parse_args():
parser = argparse.ArgumentParser(description=desc, formatter_class=RawTextHelpFormatter)
parser.add_argument('exsum_fn', type=str, metavar='EXSUM_FN')
parser.add_argument('--model-var-name', default='model', type=str)
parser.add_argument('--log-dir', default='logs', type=str)
parse... |
def handle_sentence(model, layer, tokenized_text, tokenized_to_id_indicies, tokenids_chunks):
layer_embeddings = [sentence_encode(tokenids_chunk, model, layer) for tokenids_chunk in tokenids_chunks]
word_embeddings = sentence_to_wordtoken_embeddings(layer_embeddings, tokenized_text, tokenized_to_id_indicies)
... |
class DeepFoolTF():
def __init__(self, input, logits, num_classes: int=10, max_iter: int=100, subsample: int=10) -> None:
self.input = input
self.logits = logits
self.num_classes = num_classes
self.max_iter = max_iter
self.subsample = subsample
def attack(self, inputs: np... |
class PoseEvaluator(Harness):
def _init_validation(self, opt):
self.fixed_depth_scaling = opt.pose_validation_fixed_scaling
self.val_num_log_images = opt.eval_num_images
def evaluate(self):
print('Evaluate pose predictions:', flush=True)
scores = self._run_pose_validation()
... |
def fixed_padding(inputs, kernel_size, dilation):
kernel_size_effective = (kernel_size + ((kernel_size - 1) * (dilation - 1)))
pad_total = (kernel_size_effective - 1)
pad_beg = (pad_total // 2)
pad_end = (pad_total - pad_beg)
padded_inputs = F.pad(inputs, (pad_beg, pad_end, pad_beg, pad_end))
re... |
def calculate_qparams(x, num_bits, flatten_dims=_DEFAULT_FLATTEN, reduce_dim=0, reduce_type='mean', keepdim=False, true_zero=False, per_ch_input=False, quant_mode='maxmin'):
alpha_gaus = {1: 1.24, 2: 1.71, 3: 2.215, 4: 2.55, 5: 2.93, 6: 3.28, 7: 3.61, 8: 3.92}
alpha_gaus_positive = {1: 1.71, 2: 2.215, 3: 2.55, ... |
def print_progress(prefix, start_time, num_docs, num_fixed_text, num_non_english_docs, chars_non_english_docs, num_small_docs, chars_small_docs):
string = (prefix + ' | ')
string += 'elapsed time: {:.2f} | '.format((time.time() - start_time))
string += 'documents: {} | '.format(num_docs)
string += 'fixe... |
_data_params('mnist2usps')
class Mnist2UspsParams(DatasetParams):
num_channels = 3
image_size = 16
mean = 0.5
std = 0.5
num_cls = 10
target_transform = None |
def negative_pearson(y_true, y_predicted, sample_weight=None):
if isinstance(y_true, pd.DataFrame):
y_true = np.array(y_true).ravel()
if isinstance(y_predicted, pd.DataFrame):
y_predicted = np.array(y_predicted).ravel()
return (- np.corrcoef(y_true, y_predicted)[(0, 1)]) |
def _check_parta2_roi_extractor(config, roi_extractor):
assert (config['type'] == roi_extractor.__class__.__name__)
assert (config.roi_layer.out_size == roi_extractor.roi_layer.out_size)
assert (config.roi_layer.max_pts_per_voxel == roi_extractor.roi_layer.max_pts_per_voxel) |
def create_mat():
image_paths = []
image_labels = []
lmdb_output_path = '../../dataset/LMDB/iiit5k_train'
if (not os.path.exists(lmdb_output_path)):
os.mkdir(lmdb_output_path)
root = '../../dataset/IIIT5K'
train_gt = loadmat(os.path.join(root, 'traindata.mat'))
length = train_gt['tra... |
def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer):
P_mask = ([0] * max_seq_length)
A_mask = ([0] * max_seq_length)
B_mask = ([0] * max_seq_length)
if isinstance(example, PaddingInputExample):
return InputFeatures(input_ids=([0] * max_seq_length), input_mask=([0... |
def compute_dice_at_nfpr(preds: np.ndarray, targets: np.ndarray, max_fpr: float=0.05) -> float:
(preds, targets) = (np.array(preds), np.array(targets))
(fpr, _, thresholds) = roc_curve(targets.reshape((- 1)), preds.reshape((- 1)))
t = thresholds[max(0, (fpr.searchsorted(max_fpr, 'right') - 1))]
return c... |
def save_samples(samples, output_dir='copy_task', prefix='train', ext='src', reverse=False):
if (not os.path.exists(output_dir)):
os.makedirs(output_dir)
with open(os.path.join(output_dir, ((prefix + '.') + ext)), mode='w', encoding='utf-8') as f:
for sample in samples:
sample = (sam... |
_SAMPLERS.register_module()
class ClassAwareSampler(Sampler):
def __init__(self, dataset: BaseDataset, seed: Optional[int]=None, num_sample_class: int=1) -> None:
(rank, world_size) = get_dist_info()
self.rank = rank
self.world_size = world_size
self.dataset = dataset
self.ep... |
class VGG_vanilla(nn.Module):
def __init__(self):
super(VGG_vanilla, self).__init__()
self.vgg19_f = vgg19_features(pretrained=True, include_classifier=True, final_maxpool=True, final_relu=True)
self.addons = nn.Linear(((512 * 7) * 7), 200)
def forward(self, x):
x = self.vgg19_f(... |
class ResNet(nn.Module):
def __init__(self, block, layers, att_position, att_dim, GSoP_mode, num_classes=1000):
self.inplanes = 64
self.GSoP_mode = GSoP_mode
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 ... |
def SAL(num_blocks, **kwargs):
(set_res, addf0, init_random, constraint) = common_config(kwargs)
(input_dependent, input_dim, input_dependent_config) = set_input_dependent_config(kwargs)
block_array = []
for nb in range(num_blocks):
if init_random:
(a_aff, b_aff) = numpy.random.randn... |
class MeshgridTest(tf.test.TestCase):
def test_meshgrid_numpy_comparison(self):
x = np.arange(4)
y = np.arange(6)
(exp_xgrid, exp_ygrid) = np.meshgrid(x, y)
(xgrid, ygrid) = ops.meshgrid(x, y)
with self.test_session() as sess:
(xgrid_output, ygrid_output) = sess.r... |
class DistributionalDuelingHeadModel(torch.nn.Module):
def __init__(self, input_size, hidden_sizes, output_size, n_atoms, grad_scale=(2 ** ((- 1) / 2))):
super().__init__()
if isinstance(hidden_sizes, int):
hidden_sizes = [hidden_sizes]
self.advantage_hidden = MlpModel(input_size... |
class BaseFunction():
def __init__(self):
super().__init__()
def forward(self, batch):
pass
def loss(self, batch, loss_function):
pass
def evaluate(self, batch, metrics):
pass
def predict(self, batch):
pass |
def test_no_preprocessing_steps_does_not_change_data(mock_data):
(brain_data, behavior_data, _) = mock_data
views = [brain_data, behavior_data]
preprocessing_steps = [None, None]
mvp = MultiViewPreprocessing(preprocessing_steps)
mvp.fit(views)
transformed_views = mvp.transform(views)
assert ... |
class MocoLoss(nn.Module):
def __init__(self):
super(MocoLoss, self).__init__()
print('Loading MOCO model from path: {}'.format(model_paths['moco']))
self.model = self.__load_model()
self.model.cuda()
self.model.eval()
def __load_model():
import torchvision.models... |
class AutoMatching(nn.Module):
def __init__(self, num_layers, filter_multiplier=8, block_multiplier=2, step=3, cell=cell_level_search.Cell):
super(AutoMatching, self).__init__()
self.cells = nn.ModuleList()
self._num_layers = num_layers
self._step = step
self._block_multiplie... |
def _expand_onehot_labels(labels, label_weights, target_shape, ignore_index):
bin_labels = labels.new_zeros(target_shape)
valid_mask = ((labels >= 0) & (labels != ignore_index))
inds = torch.nonzero(valid_mask, as_tuple=True)
if (inds[0].numel() > 0):
if (labels.dim() == 3):
bin_labe... |
def func(inp, net=None, target=None):
out = net(inp)
loss = torch.nn.functional.nll_loss(out, target=torch.LongTensor([target]))
print(f'Loss: {loss.item()}')
return loss |
(scope='module')
def regression_data():
data = synthetic_regression()
return (data['full']['X'], data['full']['y']) |
class FlaxElectraForCausalLM(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def plot_collision(collision_report: CollisionReport, sim_log: SimLog):
fig = plt.gca().get_figure()
log_entries: Mapping[(PlayerName, LogEntry)] = sim_log.at_interp(collision_report.at_time)
imp_point = collision_report.impact_point.coords[0]
n = (0.2 * collision_report.impact_normal)
plt.plot(*imp... |
def main(args, debug=True):
app = build_app(args.dataset, args.pred_dir, args.video_dir, args.frame_dir, args.flow_dir, args.nms)
app_kwargs = {'debug': debug, 'port': args.port}
if args.public:
app_kwargs['host'] = '0.0.0.0'
app.run(**app_kwargs) |
def format_step(step):
if isinstance(step, str):
return step
s = ''
if (len(step) > 0):
s += 'Training Epoch: {} '.format(step[0])
if (len(step) > 1):
s += 'Training Iteration: {} '.format(step[1])
if (len(step) > 2):
s += 'Validation Iteration: {} '.format(step[2])
... |
_module()
class QualityFocalLoss(nn.Module):
def __init__(self, use_sigmoid=True, beta=2.0, reduction='mean', loss_weight=1.0, activated=False):
super(QualityFocalLoss, self).__init__()
assert (use_sigmoid is True), 'Only sigmoid in QFL supported now.'
self.use_sigmoid = use_sigmoid
... |
class Pose1DTemporalEncoder(nn.Module):
def __init__(self, input_channels, output_channels):
super(Pose1DTemporalEncoder, self).__init__()
self._input_channels = input_channels
self._output_channels = output_channels
self.init_model()
def init_model(self):
self._model = n... |
def parse_args():
parser = argparse.ArgumentParser(description='Finetune 3D CNN from TCG pretrained weights')
parser.add_argument('--cl', type=int, default=16, help='clip length')
parser.add_argument('--model', type=str, default='r3d', help='c3d/r3d/r21d')
parser.add_argument('--dataset', type=str, defa... |
class VATGenerator(object):
def __init__(self, net: nn.Module, xi=1e-06, eplision=10, ip=1) -> None:
super(VATGenerator, self).__init__()
self.xi = xi
self.eps = eplision
self.ip = ip
self.net = net
def _l2_normalize(d: Tensor) -> Tensor:
d_reshaped = d.view(d.sha... |
def preprocess_lm_data(data_dir):
preprocess_parser = options.get_preprocessing_parser()
preprocess_args = preprocess_parser.parse_args(['--only-source', '--trainpref', os.path.join(data_dir, 'train.out'), '--validpref', os.path.join(data_dir, 'valid.out'), '--testpref', os.path.join(data_dir, 'test.out'), '--d... |
def combine_json(dir_list, output_path, shuffle=False):
data = []
for file_path in dir_list:
with open(file_path, 'r') as infile:
cur_data = json.load(infile)
print(file_path, len(cur_data), 'samples')
data = (data + cur_data)
if (shuffle == True):
print('... |
def check_depths():
from nets.profile_func import profile_slimmable_models
print(f'profile model GFLOPs (forward complexity) and size (#param)')
for resnet in [resnet18, resnet34, resnet50]:
model = resnet(track_running_stats=False, bn_type='bn')
model.eval()
print(f'''
model {resnet... |
def model_slim_mha(model, dataloader=None):
from .pattern_analyzer import SelfMHASearcher
from .weight_slim import MHACompression
logger.warning('You are using model slim methods, some attention heads will be removed permanently.')
pa_obj = SelfMHASearcher(model, dataloader)
(layers, _) = pa_obj.sea... |
class DriftingFiniteArmedBernoulliBandit(FiniteArmedBernoulliBandit):
def __init__(self, n_arm, a0=1.0, b0=1.0, gamma=0.01):
self.n_arm = n_arm
self.a0 = a0
self.b0 = b0
self.prior_success = np.array([a0 for a in range(n_arm)])
self.prior_failure = np.array([b0 for a in range... |
def build_save_dataset(corpus_type, fields, opt):
assert (corpus_type in ['train', 'valid'])
if (corpus_type == 'train'):
corpus = opt.train_dir
else:
corpus = opt.valid_dir
dataset = inputters.build_dataset(fields, data_path=corpus, data_type=opt.data_type, seq_length=opt.seq_length, se... |
def iresnet100(pretrained=False, progress=True, **kwargs):
return _iresnet('iresnet100', IBasicBlock, [3, 13, 30, 3], pretrained, progress, **kwargs) |
def get_model_files(model_type: str, frameworks: Optional[List[str]]=None) -> Dict[(str, Union[(Path, List[Path])])]:
module_name = model_type_to_module_name(model_type)
model_module = ((TRANSFORMERS_PATH / 'models') / module_name)
model_files = list(model_module.glob('*.py'))
model_files = filter_frame... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='cifar')
parser.add_argument('--start', type=int, default=0)
parser.add_argument('--end', type=int, default=100)
parser.add_argument('--n_iter', type=int, default=1000)
parser.add_argument('--transf... |
class PathConv(torch.autograd.Function):
def forward(ctx, path_indices, features):
if features.is_cuda:
output = gckn_fast_cuda.path_conv_forward(path_indices, features)
else:
output = gckn_fast_cpu.path_conv_forward(path_indices, features)
ctx.save_for_backward(path_... |
def try_or_nothing(func):
try:
return func()
except Exception as e:
print(type(Exception))
print(e) |
class L1(Loss):
def __init__(self):
self.loss = nn.L1Loss()
def __call__(self, logits, targets, **kwargs):
return self.loss(logits, targets) |
def setup_logger(log_filename: Pathlike, log_level: str='info', use_console: bool=True) -> None:
now = datetime.now()
date_time = now.strftime('%Y-%m-%d-%H-%M-%S')
log_filename = '{}-{}'.format(log_filename, date_time)
os.makedirs(os.path.dirname(log_filename), exist_ok=True)
if (dist.is_available()... |
def cca_decomp(A, B):
assert (A.shape[0] < A.shape[1])
assert (B.shape[0] < B.shape[1])
(evals_a, evecs_a) = np.linalg.eigh((A A.T))
evals_a = ((evals_a + np.abs(evals_a)) / 2)
inv_a = np.array([((1 / np.sqrt(x)) if (x > 0) else 0) for x in evals_a])
(evals_b, evecs_b) = np.linalg.eigh((B B.T)... |
class SubMGroup3d(SparseGroup):
def __init__(self, in_channels, kernel_size, stride=1, padding=0, dilation=1, indice_key=None):
super(SubMGroup3d, self).__init__(3, in_channels, kernel_size, stride, padding, dilation, True, indice_key=indice_key) |
class TrOCRForCausalLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def get_config_overrides(config_class, processors):
config_overrides = {}
tokenizer = None
for processor in processors:
if isinstance(processor, PreTrainedTokenizerFast):
tokenizer = processor
break
elif isinstance(processor, PreTrainedTokenizer):
tokenize... |
def main(params: Params):
rng = np.random.RandomState(1001)
torch.manual_seed(rng.choice())
(molchef_wae, latent_dim, stop_symbol_idx) = load_in_mchef(params.weights_to_use, cuda_details=params.cuda_details, path_molecule_details=params.path_mol_details)
seq_to_smi_list = mt.MapSeqsToReactants()
trs... |
def xdensenet40_2_k36_bc_cifar10(num_classes=10, **kwargs):
return get_xdensenet_cifar(num_classes=num_classes, blocks=40, growth_rate=36, bottleneck=True, model_name='xdensenet40_2_k36_bc_cifar10', **kwargs) |
def AddFinalLayer(config_lines, input, output_dim, ng_affine_options=' param-stddev=0 bias-stddev=0 ', max_change_per_component=1.5, label_delay=None, use_presoftmax_prior_scale=False, prior_scale_file=None, include_log_softmax=True, add_final_sigmoid=False, name_affix=None, objective_type='linear'):
components = c... |
def create_segmentation_file(img_subdir, anns_subdir, output_subdir, dataset_descriptor, metadata_input, object_input, relationship_input, attribute_synsets_input, attribute_dict_file_dir, attribute_dict_file_path, output_json_path, num_workers=20):
obj_data = json.load(open(object_input))
rel_data = json.load(... |
def render_mesh(mesh, mesh_center):
scene = mi.load_dict({'type': 'scene', 'integrator': {'type': 'path'}, 'light': {'type': 'constant', 'radiance': {'type': 'rgb', 'value': 1.0}}, 'sensor': {'type': 'perspective', 'focal_length': '50mm', 'to_world': mi.ScalarTransform4f.look_at(origin=[0, 0, 5], target=mesh_center... |
class LxmertXLayer(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def create_local_var(primary, val, scope, validate_shape, shape, dtype):
shape = (shape if callable(val) else None)
if isinstance(primary, kv_variable_ops.KvVariable):
if (shape is not None):
shape = tensor_shape.as_shape([shape.as_list()[1]])
current_partitioner = get_kv_variable_sc... |
class MNIST(Dataset):
def __str__(self):
return 'MNIST Dataset'
def __init__(self, target_size, dataset_path='./datasets/mnist', train_transforms=None, test_transforms=None):
self.mean = (0.1307,)
self.std = (0.3081,)
self.num_classes = 10
super(MNIST, self).__init__(targ... |
class Logger(object):
def __init__(self, logdir='./log'):
self.writer = SummaryWriter(logdir)
def scalar_summary(self, tag, value, step):
self.writer.add_scalar(tag, value, step)
def scalars_summary(self, tag, dictionary, step):
self.writer.add_scalars(tag, dictionary, step)
def ... |
class _3DUNET_TF_SUT():
def __init__(self, model_path, preprocessed_data_dir, performance_count):
print('Loading TF model...')
graph_def = graph_pb2.GraphDef()
print(model_path)
with open(model_path, 'rb') as f:
graph_def.ParseFromString(f.read())
with tf.Graph().... |
def _create_rdd_x_y(x, y, input_names, output_names, sc):
from tensorflow.python.keras.engine import training_utils
x = training_utils.standardize_input_data(x, input_names, check_batch_axis=False, exception_prefix='input')
y = training_utils.standardize_input_data(y, output_names, shapes=None, check_batch_... |
def test_scrape2(snapshot):
assert (eia_api_v2.scrape('2020-07-10', '2020-07-11').to_csv() == snapshot(name='Output of scrape for July 10th 2020')) |
def clean_up_SPICE(file):
for ext in ['.asc', '.masterlog', '.net', '_run.net', '_run.op.raw', '_run.raw', '1.log']:
os.system(f'rm {file}{ext}') |
def parse_response(response, current_name, user_name, names, action_delim):
response = response.split('REMINDER:')[0].strip()
response = response.split('RULES:')[0].strip()
match = re.search('(NEXT:\\s*([^\\n]+))', response)
name = user_name
if (not match):
logger.warning(f"Didn't generate N... |
def map_to_generation_datapoint(patch: AvgPatch) -> GenerationDatapoint:
n_unfinshed = utils.binary_bool(patch.is_unfinished)
return GenerationDatapoint(gen_time=patch.total_gen_time, n_total=1, n_unique=utils.binary_bool((not patch.is_duplicate)), n_unfinished=n_unfinshed, n_pruned=utils.binary_bool((patch.is_... |
def device_analysis_options(output_dir):
options = model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS.copy()
options['select'] = ['device', 'float_ops', 'micros']
options['order_by'] = 'name'
options['account_type_regexes'] = ['.*']
if output_dir:
options['dump_to_file'] = os.path.join(output... |
class Learner(object):
def __init__(self, params):
params['zeros'] = False
self.agents = {i: get_policy(params, (params['seed'] + (1000 * i))) for i in range(params['num_agents'])}
self.timesteps = 0
self.w_reward = 1
self.w_size = 0
self.dists = 0
self.adam_p... |
def get_ort_model_output(feat, onnx_io='tmp.onnx'):
onnx_model = onnx.load(onnx_io)
onnx.checker.check_model(onnx_model)
session_options = ort.SessionOptions()
if osp.exists(ort_custom_op_path):
session_options.register_custom_ops_library(ort_custom_op_path)
sess = ort.InferenceSession(onnx_... |
def test_try_parse_percentage_column_known() -> None:
assert (postprocessing.try_parse('50', 'CS', known_percentages=['CS']) == 0.5) |
def conv1x1(in_planes: int, out_planes: int, stride: int=1, bias: bool=False) -> nn.Conv2d:
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=bias) |
def double_double_predict_correct(vrblvl=0):
if (vrblvl > 0):
print('in double_double_predict_correct ...')
phc = get_phcfun()
apar = pointer(c_int32(1))
bvrb = pointer(c_int32(vrblvl))
ccc = pointer(c_double(0.0))
vrb = c_int32(vrblvl)
if (vrblvl > 0):
print('-> double_doubl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.