code stringlengths 101 5.91M |
|---|
def bni_loss(pred, target, noise_var, bucket_centers, bucket_weights):
mse_term = ((F.mse_loss(pred, target, reduction='none') / 2) / noise_var)
num_bucket = bucket_centers.shape[0]
bucket_center = bucket_centers.unsqueeze(0).repeat(pred.shape[0], 1)
bucket_weights = bucket_weights.unsqueeze(0).repeat(p... |
def run_hyper_attn(batch_size, head_size, seq_len, dim, causal, mode, impl='triton', warmup=20, rep=100):
(q, k, v) = get_tensors(batch_size, head_size, seq_len, dim)
block_size = 256
sample_size = 256
cuda = (impl == 'cuda')
attn = HyperAttention(input_dim=dim, block_size=block_size, sample_size=sa... |
def add_plot_parser(subparsers):
parser_plt = subparsers.add_parser('plot_curve', help='parser for plotting curves')
parser_plt.add_argument('json_logs', type=str, nargs='+', help='path of train log in json format')
parser_plt.add_argument('--keys', type=str, nargs='+', default=['bbox_mAP'], help='the metri... |
class INAdaptiveClient(AdaptiveClient):
def init_optimizer(self):
self.optimizer = SGD(self.model.parameters(), lr=INIT_LR, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY)
self.optimizer_scheduler = lr_scheduler.StepLR(self.optimizer, step_size=STEP_SIZE, gamma=(0.5 ** (STEP_SIZE / LR_HALF_LIFE)))
... |
def convert(file):
clip = VideoFileClip(file)
duration = clip.duration
if (duration < 30):
if (file[(- 4):] in ['.mov', '.avi', '.flv', '.wmv']):
filename = (file[0:(- 4)] + '.mp4')
os.system(('ffmpeg -i %s -an %s' % (file, filename)))
os.remove(file)
elif... |
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):
def __init__(self, optimizer, milestones, gamma=0.1, warmup_factor=(1.0 / 3), warmup_iters=5, warmup_method='linear', last_epoch=(- 1)):
if (not (milestones == sorted(milestones))):
raise ValueError('Milestones should be a list of i... |
def run_hps(cfg, uuid):
print(cfg)
argv_plus_hps = sys.argv
script_name = argv_plus_hps[0]
script_name = script_name.replace('.py', '').replace('/', '.')
script_name = (script_name[1:] if script_name.startswith('.') else script_name)
for (hp, hp_range) in flatten(cfg['hps_kwargs']['hp']).items()... |
class CWRU(object):
num_classes = 10
inputchannel = 1
def __init__(self, data_dir, normlizetype):
self.data_dir = data_dir
self.normlizetype = normlizetype
def data_preprare(self, test=False):
list_data = get_files(self.data_dir, test)
if test:
test_dataset = ... |
def diapreresnet1202_cifar10(num_classes=10, **kwargs):
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name='diapreresnet1202_cifar10', **kwargs) |
def torch2onnx(model: SymbolNet, exportable: Union[(str, BytesIO)], verbose=False, dummy_inputs=None, do_constant_folding=False) -> None:
proxy_enabled = model.proxy_enabled
if proxy_enabled:
model.disable_proxy_grad()
if (dummy_inputs is None):
dummy_inputs = [torch.ones(size=svar.shape).un... |
def test_deflate():
pols = ['x**2+y-3;', 'x+0.125*y**2-1.5;']
sols = [((((('t : 1.E+00 0.E+00\n' + 'm : 1\n') + 'the solution for t :\n') + ' x : -3.E+00 0.E+00\n') + ' y : -6.E+00 0.E+00\n') + '== err : 0.000E+00 = rco : 1.965E-01 = res : 0.000E+00 =='), ((((('t : 1.E+00 0.E+00\n' + 'm : 1\n') + '... |
def fetch_requirements(path):
with open(path, 'r') as fd:
return [r.strip() for r in fd.readlines()] |
class WhitespaceTokenizer(object):
def __init__(self, vocab):
self.vocab = vocab
def __call__(self, text):
words = text.split(' ')
spaces = ([True] * len(words))
return Doc(self.vocab, words=words, spaces=spaces) |
def index_to_mask(index, size):
mask = torch.zeros(size, dtype=torch.bool)
mask[index] = 1
return mask |
def train(model, training_data, validation_data, device, opt):
model = model.to(device)
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [{'params': [p for (n, p) in param_optimizer if (not any(((nd in n) for nd in ... |
def batched_index_select(x: torch.Tensor, dim: int, index: torch.LongTensor) -> torch.Tensor:
views = ([x.shape[0]] + [(1 if (i != dim) else (- 1)) for i in range(1, len(x.shape))])
expanse = list(x.shape)
expanse[0] = (- 1)
expanse[dim] = (- 1)
index = index.view(views).expand(expanse)
return t... |
def quaddobl_pade_vector(dim):
result = []
for i in range(1, (dim + 1)):
result.append(quaddobl_pade_coefficients(i))
return result |
def __dice_loss(input: torch.FloatTensor, target: torch.LongTensor, weights: torch.FloatTensor=None, k: int=0, eps: float=0.0001):
n_classes = input.size()[0]
if (weights is not None):
for c in range(n_classes):
intersection = ((input[c] * target[c]) * weights[c]).sum()
union = (... |
_torch
_wandb
class TrainerHyperParameterWandbIntegrationTest(unittest.TestCase):
def setUp(self):
args = TrainingArguments('..')
self.n_epochs = args.num_train_epochs
self.batch_size = args.train_batch_size
def test_hyperparameter_search(self):
class MyTrialShortNamer(TrialShort... |
def preresnet56_cifar10(num_classes=10, **kwargs):
return get_preresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name='preresnet56_cifar10', **kwargs) |
def local_env_settings():
settings = EnvSettings()
settings.davis_dir = ''
settings.got10k_path = ''
settings.got_packed_results_path = ''
settings.got_reports_path = ''
settings.lasot_path = ''
settings.network_path = '/data/zzy/ablation/V9_Swin_mon_02_accu_box_09/ltr/checkpoints/ltr/transt... |
class MSDInitLayer(nn.Module):
def __init__(self, in_channels, out_channels):
super(MSDInitLayer, self).__init__()
self.scale_blocks = MultiOutputSequential()
for (i, out_channels_per_scale) in enumerate(out_channels):
if (i == 0):
self.scale_blocks.add_module('sc... |
def make_folder(folder_name):
if (not os.path.isdir(folder_name)):
os.makedirs(folder_name) |
def render_example(example_id, render_dir, input_dir, output_dir, texture_dir, csv_file, shape, views):
example_in_dir = os.path.join(input_dir, example_id)
example_out_dir = os.path.join(output_dir, example_id)
example_render_dir = os.path.join(render_dir, example_id)
try:
obj = os.path.join(ex... |
class CognateSet():
IDX = 0
def __init__(self):
self._data = defaultdict(set)
self.idx = CognateSet.IDX
CognateSet.IDX += 1
def add(self, lang, *words):
words = [w for w in words if (w != '_')]
if words:
self._data[lang].update(words)
def is_in(self, w... |
class Evaluator(Generic[S], ABC):
def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]:
pass
def evaluate_solution(solution: S, problem: Problem) -> None:
problem.evaluate(solution) |
def rotate_coordination(orig_x, orig_y, orig_d, coordi_rotate_d):
coordi_rotate_d_in_rad = ((coordi_rotate_d * math.pi) / 180)
transformed_x = ((orig_x * math.cos(coordi_rotate_d_in_rad)) + (orig_y * math.sin(coordi_rotate_d_in_rad)))
transformed_y = (((- orig_x) * math.sin(coordi_rotate_d_in_rad)) + (orig_... |
class DisentangleLayer(nn.Module):
def __init__(self, n_latent, in_dim, out_dim, cat=True):
super(DisentangleLayer, self).__init__()
self.g = None
self.n_latent = n_latent
self.n_feat_latent = ((out_dim // self.n_latent) if cat else out_dim)
self.cat = cat
self.linear... |
def extra_hidden_layer(hidden_dim):
return nn.Sequential(nn.Linear(hidden_dim, hidden_dim), nn.ReLU(True)) |
class EarlyStopping():
def __init__(self, steps_to_wait, epsilon=0):
assert (steps_to_wait >= 0)
self.steps_to_wait = steps_to_wait
self.epsilon = epsilon
self.best_loss = float('inf')
self.waited_steps = 0
def should_stop(self, current_loss, current_step):
if ((s... |
class AssignmentNode(TwoAddressNode):
snippet = '{res_var} = {cast}{var1};\n'
def __init__(self, res_var: TreeNode, var1: TreeNode, prev_node: Node=None):
super().__init__(res_var, var1, prev_node)
self.cast = ''
def write_c(self):
res_var: Variable = self.get_node('res_var')
... |
class Bool(Int):
def __init__(self, default=None, prefix=None):
super(Bool, self).__init__(0, 1, default=default, prefix=prefix) |
def build_detection_model(cfg, BBAM=False):
meta_arch = _DETECTION_META_ARCHITECTURES[cfg.MODEL.META_ARCHITECTURE]
return meta_arch(cfg, BBAM=BBAM) |
class MyOtherNewExpectedFlux(MyNewExpectedFlux):
def __init__(self, config):
super().__init__()
pass |
def main():
parser = argparse.ArgumentParser(description='Deep Orientation Estimation')
parser.add_argument('-c', '--config', default=DEFAULT_CONFIG, type=str)
args = parser.parse_args()
config_file = args.config
assert os.path.exists(args.config), 'Config file {} does not exist'.format(args.config)... |
def wait_for_server_started(ip, port, timeout=60):
s = socket.socket()
num_attempts = 0
while True:
if (num_attempts == timeout):
raise TimeoutError('Failed to connect to {} after waiting for {} s'.format((ip, port), timeout))
try:
s.connect((ip, port))
br... |
def validate(val_loader, model, train_labels=None, prefix='Val'):
batch_time = AverageMeter('Time', ':6.3f')
losses_mse = AverageMeter('Loss (MSE)', ':.3f')
losses_l1 = AverageMeter('Loss (L1)', ':.3f')
progress = ProgressMeter(len(val_loader), [batch_time, losses_mse, losses_l1], prefix=f'{prefix}: ')
... |
def ReadFileWithAbort(tthread, batchInterval):
(w, h) = (6, 6)
y = [[0 for x in range(w)] for y in range(h)]
y_sum = [0 for x in range(w)]
inputEvents = (tthread * batchInterval)
gs_path = (FILE_FOLER + '/GSA/threads = {}/totalEvents = {}'.format(tthread, inputEvents))
lines = open(gs_path).read... |
def gen_rosette_code(invocations: list, o_id: int) -> str:
argCount = len(invocations[0][0])
arglist = ' '.join([f's{i}' for i in range(argCount)])
header = f'''#lang rosette
(require rosette/lib/synthax)
(define int32? (bitvector 32))
(define (int32 i) (bv i int32?))
'''
definitions = f'''(define-symbo... |
('Please use `bigdl.chronos.autots.AutoTSEstimator` instead.')
class AutoTSTrainer():
def __init__(self, horizon=1, dt_col='datetime', target_col='value', logs_dir='~/bigdl_automl_logs', extra_features_col=None, search_alg=None, search_alg_params=None, scheduler=None, scheduler_params=None, name='automl'):
... |
def test_microboone_fale_report_numbr():
ref_line = u'[40] MicroBooNE, LAr1-ND, ICARUS-WA104 collaboration, M. Antonello et al., A Proposal for a Three Detector Short-Baseline Neutrino Oscillation Program in the Fermilab Booster Neutrino Beam, 1503.01520.'
res = get_references(ref_line)
references = res[0]
... |
def validate_item_buffer_args(max_length: int, min_length: int, sample_batch_size: int):
validate_sample_batch_size(sample_batch_size, max_length)
validate_min_length(min_length, max_length) |
class PB4D(Instance, ABC):
def __init__(self):
super(PB4D, self).__init__()
self.dst = '/scratch/NFC/OnFlame/BP4D/'
self.src = '/scratch/NFC/BP4D/'
def get_images(self):
images = {}
for actor in sorted(glob((self.get_src() + 'images/*'))):
imgs = sorted(glob(f... |
def gauss_peak(maxpos, width, weight, wgrid):
a = ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid - maxpos) ** 2)) / (width ** 2))))
a -= ((weight / (np.sqrt((2.0 * np.pi)) * width)) * np.exp((((- 0.5) * ((wgrid + maxpos) ** 2)) / (width ** 2))))
return a |
def load_pretrained_weights(model, model_name, load_fc=True, advprop=False):
url_map_ = (url_map_advprop if advprop else url_map)
state_dict = model_zoo.load_url(url_map_[model_name])
model.load_state_dict(state_dict, strict=False) |
def rotation_matrix(axis, theta):
if ((np.abs(axis).sum() < 1e-06) or (np.abs(theta) < 1e-06)):
return np.eye(3)
axis = np.asarray(axis)
axis = (axis / math.sqrt(np.dot(axis, axis)))
a = math.cos((theta / 2.0))
(b, c, d) = ((- axis) * math.sin((theta / 2.0)))
(aa, bb, cc, dd) = ((a * a),... |
def export_entry_point():
import argparse
parser = argparse.ArgumentParser(description='Use this script to export models to a zip file for sharing with others. You can upload the zip file and then either share the url for usage with nnUNet_download_pretrained_model_by_url, or share the zip for usage with nnUNet... |
def reshape_features(features):
input_tensors = {}
for (name, tensor) in features.items():
input_tensors[name] = tf.reshape(tensor, ((- 1), 1))
return input_tensors |
def stop_recording():
global ffmpeg
ffmpeg.stdin.close()
ffmpeg.wait()
ffmpeg = None
return |
def detect_monitor_files(training_dir):
return [os.path.join(training_dir, f) for f in os.listdir(training_dir) if f.startswith((FILE_PREFIX + '.'))] |
def transform_pos(mtx, pos):
t_mtx = (torch.from_numpy(mtx).cuda() if isinstance(mtx, np.ndarray) else mtx)
posw = torch.cat([pos, torch.ones([pos.shape[0], 1]).cuda()], axis=1)
return torch.matmul(posw, t_mtx.t())[(None, ...)] |
def train_model(model, fields, optim, data_type, model_opt, train_part):
train_loss = make_loss_compute(model, fields['tgt'].vocab, opt)
valid_loss = make_loss_compute(model, fields['tgt'].vocab, opt, train=False)
trunc_size = opt.truncated_decoder
shard_size = opt.max_generator_batches
norm_method ... |
class UnetGeneratorShiftTriple(nn.Module):
def __init__(self, input_nc, output_nc, num_downs, opt, innerCos_list, shift_list, mask_global, ngf=64, norm_layer=nn.BatchNorm2d, use_spectral_norm=False):
super(UnetGeneratorShiftTriple, self).__init__()
unet_block = UnetSkipConnectionBlock((ngf * 8), (ng... |
class RandomPerspective(object):
def __init__(self, distortion_scale=0.5, p=0.5, interpolation=Image.BICUBIC):
self.p = p
self.interpolation = interpolation
self.distortion_scale = distortion_scale
def __call__(self, img):
if (not F._is_pil_image(img)):
raise TypeErro... |
class BlipTextModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def load_video(video_path, n_frms=MAX_INT, height=(- 1), width=(- 1), sampling='uniform'):
vr = VideoReader(uri=video_path, height=height, width=width)
vlen = len(vr)
(start, end) = (0, vlen)
n_frms = min(n_frms, vlen)
if (sampling == 'uniform'):
indices = np.arange(start, end, (vlen / n_frm... |
def prepare_doc_data(input_folder, output_folder):
train_input = os.path.join(input_folder, 'training.txt')
validation_input = os.path.join(input_folder, 'validation.txt')
test_input = os.path.join(input_folder, 'test.txt')
(train_label, train_doc) = extract_docs(train_input, output_folder)
(validat... |
class FCConfig(object):
num_scale = 3
scale_step = 1.0375
scale_penalty = 0.9745
scale_lr = 0.59
response_up = 16
windowing = 'cosine'
w_influence = 0.35
exemplar_size = 128
instance_size = 256
score_size = 27
total_stride = 8
context_amount = 0.5
def update(self, new... |
_tokenizers
class GPT2TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = GPT2Tokenizer
rust_tokenizer_class = GPT2TokenizerFast
test_rust_tokenizer = True
from_pretrained_kwargs = {'add_prefix_space': True}
test_seq2seq = False
def setUp(self):
super().setUp()
... |
.register('DetNASNet-RCNN')
def build_detnasnet_fpn_backbone(cfg):
in_channels_stage2 = cfg.MODEL.HNASNET.FILTER_MULTIPLIER
in_channels_list = [(in_channels_stage2 * s) for s in cfg.MODEL.HNASNET.STRIDE_MULTIPLIER[1:]]
in_channels_list = ([0] + in_channels_list)
body = DetNASNet(cfg)
out_channels = ... |
def train(rank, world_size, opt):
torch.manual_seed(0)
setup(rank, world_size, opt.port)
torch.cuda.set_device(rank)
device = torch.device(rank)
curriculum = getattr(curriculums, opt.curriculum)
metadata = curriculums.extract_metadata(curriculum, 0)
fixed_z = z_sampler((25, 256), device='cpu... |
def load_images(images_file_path, batch_size, resize_size=256, is_train=True, crop_size=224, is_cen=False, num_workers=4):
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
if (not is_train):
start_center = (((resize_size - crop_size) - 1) / 2)
transformer =... |
class CutPaste(object):
def __init__(self, transform=True, type='binary'):
self.type = type
if transform:
self.transform = transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1)
else:
self.transform = None
def crop_and_paste_patch(image, pat... |
def get_transformers_submodules():
submodules = []
for (path, directories, files) in os.walk(PATH_TO_TRANSFORMERS):
for folder in directories:
if folder.startswith('_'):
directories.remove(folder)
continue
if (len(list((Path(path) / folder).glob('*... |
def f(x):
dist = space.pairwise_dist(x, space.id.view((- 1), *space.id.shape)).squeeze()
return torch.sin(dist) |
def main(base_model='ise-uiuc/Magicoder-S-DS-6.7B', device='cuda:0', port=8080):
tokenizer = AutoTokenizer.from_pretrained(base_model)
pipeline = transformers.pipeline('text-generation', model=base_model, torch_dtype=torch.float16, device=device)
def evaluate_magicoder(instruction, temperature=1, max_new_to... |
def json_to_dataframe(path: str, layer_name: str, max_C: int=128, prefix: str='') -> pd.DataFrame:
files = glob.glob((path + '/*.json'))
regex = f'{layer_name}_.+\.json'
pattern = re.compile(regex)
files_res = [x for x in files if pattern.search(x)]
dfs = []
for file in files_res:
data =... |
def main():
tf.set_random_seed(10)
with tf.Session() as sess:
rnn_cell = tf.nn.rnn_cell.LSTMCell(10)
initial_state = rnn_cell.zero_state(4, dtype=tf.float32)
inputs = tf.Variable(tf.random_uniform(shape=(4, 30, 100)), name='input')
inputs = tf.identity(inputs, 'input_node')
... |
class TextSearchSolver(object):
def __init__(self, host: str='localhost', port: int=9200, index_name: str='knowledge', field_name: str='body', topn: int=1) -> None:
self.client = Elasticsearch([host], port=port)
print(self.client)
self.fields = [field_name]
self.index_name = index_na... |
def conv1x1_block(in_channels, out_channels, stride=1, padding=0, groups=1, bias=False, use_bn=True, bn_eps=1e-05, activation=(lambda : nn.ReLU(inplace=True))):
return ConvBlock(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=padding, groups=groups, bias=bias, use_bn=use_bn... |
def preprocess_opts(parser):
group = parser.add_argument_group('Data')
group.add_argument('-train_dir', required=True, help='Path to the training data')
group.add_argument('-valid_dir', required=True, help='Path to the validation data')
group.add_argument('-data_type', choices=['concat', 'query', 'hier'... |
def env_from_checkpoint(ckpt_path=None, ckpt_dict=None, env_name=None, render=False, render_offscreen=False, verbose=False, bddl_file_name=None):
ckpt_dict = maybe_dict_from_checkpoint(ckpt_path=ckpt_path, ckpt_dict=ckpt_dict)
env_meta = ckpt_dict['env_metadata']
shape_meta = ckpt_dict['shape_metadata']
... |
def test_call_marginalizevlos():
from galpy.orbit import Orbit
idf = dehnendf(beta=0.0)
pot = [LogarithmicHaloPotential(normalize=1.0), EllipticalDiskPotential(twophio=0.001)]
edf = evolveddiskdf(idf, pot=pot[0], to=(- 10.0))
(R, phi, vT) = (0.8, 0.0, 0.7)
vrs = numpy.linspace((- 1.0), 1.0, 101)... |
class Node():
def __init__(self, prob, symbol, left=None, right=None):
self.prob = prob
self.symbol = symbol
self.left = left
self.right = right
self.code = '' |
class SymbolicEncoder(nn.Module):
def __init__(self, observation_size, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(observation_size, embedding_size)
self.fc2 = nn.Linear(embedding_size, embedding_s... |
class ToyGPT2Model(GPT2Model):
def __init__(self, hidden_size=256, head_num=4, layer_num=3, seq_length=512):
config = GPT2Config()
c_s = f'n_embd={hidden_size},n_head={head_num},n_layer={layer_num},n_positions={seq_length}'
config.update_from_string(c_s)
super().__init__(config)
... |
def build_tracker(name='max_box', *args, **kwargs):
if (name == 'max_box'):
from .max_box_tracker import MaxBoxTracker
tracker = MaxBoxTracker()
else:
raise ValueError(f'{name} is not valid, currently it only supports {VALID_TRACKERS}')
return tracker |
def test_amuse_MiyamotoNagaiPotential():
mp = potential.MiyamotoNagaiPotential(normalize=1.0, a=0.5, b=0.1)
tmax = 4.0
(vo, ro) = (220.0, 8.0)
o = Orbit([1.0, 0.1, 1.1, 0.3, 0.1, 0.4], ro=ro, vo=vo)
run_orbitIntegration_comparison(o, mp, tmax, vo, ro)
return None |
def apply_model_ema_and_restore(model, state=None):
model = _remove_ddp(model)
if (state is None):
state = get_model_ema_state(model)
old_state = EMAState.FromModel(model, state.device)
state.apply_to(model)
(yield old_state)
old_state.apply_to(model) |
def trades_loss(model, x_natural, y, optimizer, device, step_size=0.003, epsilon=0.031, perturb_steps=10, beta=1.0, distance='l_inf'):
criterion_kl = nn.KLDivLoss(size_average=False)
model.eval()
batch_size = len(x_natural)
x_adv = (x_natural.detach() + (0.001 * torch.randn(x_natural.shape).cuda().detac... |
class iCNN(FlowNetwork):
def __init__(self, num_classes=10, k=16):
super().__init__()
self.num_classes = num_classes
self.k = k
self.body = iSequential(RandomPadChannels((k - 3)), *iCoordSelu(k), *iCoordSelu(k), *iCoordSelu(k), NNdownsample(), *iCoordSelu((4 * k)), *iCoordSelu((4 * k... |
class BaselineUNet(nn.Module):
def __init__(self, in_channels, n_cls, n_filters):
super(BaselineUNet, self).__init__()
self.in_channels = in_channels
self.n_cls = (1 if (n_cls == 2) else n_cls)
self.n_filters = n_filters
self.block_1_1_left = BasicConv3d(in_channels, n_filter... |
class meta_ops():
def upload(cls, meta, grid=None, grid_url=None):
grid_id = _api_v2.parse_grid_id_args(grid, grid_url)
payload = {'metadata': json.dumps(meta, cls=utils.PlotlyJSONEncoder)}
api_url = (_api_v2.api_url('grids') + '/{grid_id}'.format(grid_id=grid_id))
res = requests.pat... |
class StrikerEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self):
utils.EzPickle.__init__(self)
self._striked = False
self._min_strike_dist = np.inf
self.strike_threshold = 0.1
mujoco_env.MujocoEnv.__init__(self, 'striker.xml', 5)
def step(self, a):
vec_... |
class TestIMSATLoss(TestCase):
def setUp(self) -> None:
super().setUp()
self.pred_log = torch.randn(200, 10)
def test_multinformation_imsat(self):
criterion = MultualInformaton_IMSAT(mu=1.0)
(MI, _) = criterion(self.pred_log)
assert (MI > 0), f'MI should be aways positive... |
_config
def scratch():
uuid = 'habitat_scratch_map'
cfg = {}
cfg['learner'] = {'perception_network': 'AtariNet'}
cfg['env'] = {'env_specific_kwargs': {'target_dim': 9}, 'transform_fn_pre_aggregation_fn': 'TransformFactory.independent', 'transform_fn_pre_aggregation_kwargs': {'names_to_transforms': {'rgb... |
def run_generate(verbose=True):
parser = argparse.ArgumentParser()
parser.add_argument('model_name', type=str, help='like facebook/bart-large-cnn,t5-base, etc.')
parser.add_argument('input_path', type=str, help='like cnn_dm/test.source')
parser.add_argument('save_path', type=str, help='where to save sum... |
def train(rank, model, criterion, optimizer, scheduler, batch_meter, comm_meter, train_loader_list, test_loader_list, epoch, device, ue_list_epoches, G, user_weight_diff_array):
average_model_weights = copy.deepcopy(model.state_dict())
average_group_model_weights = copy.deepcopy(model.state_dict())
model.tr... |
def train_seco(epoch, train_loader, model, model_ema, contrast, criterion, optimizer, scheduler, args):
model.train()
set_bn_train(model_ema)
batch_time = AverageMeter()
loss_meter = AverageMeter()
timer = mmcv.Timer()
for (idx, (xq, x1, x2, x3, binary_order)) in enumerate(train_loader):
... |
def download_and_prepare(root):
train = STL10(root, split='train', download=True)
test = STL10(root, split='test')
unlabeled = STL10(root, split='unlabeled')
train_dir = osp.join(root, 'train')
test_dir = osp.join(root, 'test')
unlabeled_dir = osp.join(root, 'unlabeled')
extract_and_save_ima... |
class DAGMM(nn.Module):
def __init__(self, feats):
super(DAGMM, self).__init__()
self.name = 'DAGMM'
self.lr = 0.0001
self.beta = 0.01
self.n_feats = feats
self.n_hidden = 16
self.n_latent = 8
self.n_window = 5
self.n = (self.n_feats * self.n_w... |
class nnUNetTrainerV2CascadeFullRes_noConnComp(nnUNetTrainerV2CascadeFullRes):
def setup_DA_params(self):
super().setup_DA_params()
self.data_aug_params['cascade_do_cascade_augmentations'] = True
self.data_aug_params['cascade_random_binary_transform_p'] = 0.4
self.data_aug_params['ca... |
def _manual_inverting(X, rcond=0.001, full_rank=False):
X = np.asarray(X)
(n_samples, n_features) = X.shape
if (n_samples != n_features):
raise ValueError('The matrix is not a square matrix')
(U, s, V) = np.linalg.svd(X, full_matrices=False)
rank = np.sum((s > (rcond * s.max())))
s_inv =... |
class BaseDataLoader():
def __init__(self, config):
self.config = config
self.batch_size = config['data_loader']['batch_size']
self.shuffle = config['data_loader']['shuffle']
self.num_workers = config['data_loader']['workers']
self.batch_idx = 0
def __iter__(self):
... |
def show_feature_map(feature_map, feature_data, i):
feature_map = feature_map.squeeze(0)
unsample = torch.nn.UpsamplingBilinear2d(size=(64, 64))
feature_data = torch.sum(feature_data, 2)
feature_data = unsample(feature_data)
feature_data = np.array(feature_data.cpu())
feature_data = feature_data... |
def pause(interval: float):
backend = plt.rcParams['backend']
if (backend in matplotlib.rcsetup.interactive_bk):
figManager = matplotlib._pylab_helpers.Gcf.get_active()
if (figManager is not None):
canvas = figManager.canvas
if canvas.figure.stale:
canvas.... |
class LegacyFairseqTask(FairseqTask):
def __init__(self, args: Namespace):
self.args = args
self.datasets = {}
self.dataset_to_epoch_iter = {}
def setup_task(cls, args: Namespace, **kwargs):
return cls(args, **kwargs)
def has_sharded_data(self, split):
return (os.path... |
def resnet_v2_block(scope, base_depth, num_units, stride, centered_stride=False):
return resnet_utils.Block(scope, bottleneck, (([{'depth': (base_depth * 4), 'depth_bottleneck': base_depth, 'stride': 1}] * (num_units - 1)) + [{'depth': (base_depth * 4), 'depth_bottleneck': base_depth, 'stride': stride, 'centered_st... |
def test_can_add(state: trajectory_queue.TrajectoryQueueState, fake_transition: chex.ArrayTree, max_length: int, add_batch_size: int, add_sequence_length: int, sample_sequence_length: int) -> None:
fake_batch_sequence = get_fake_batch_sequence(fake_transition, add_batch_size, add_sequence_length)
assert ((max_l... |
_registry(operator_type='PaddingSequence')
class PaddingSequence(Operator):
def __init__(self):
super().__init__()
def set_attr(self, framework, node):
if (framework == 'torch'):
self._attr['dst_shape'] = '-1,1,1,-1'
self._attr['dims'] = 1
self._attr['padding_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.