code stringlengths 101 5.91M |
|---|
def dataloader_creator(cfg):
distributed = cfg.distributed
runner_type = ('EpochBasedRunner' if ('runner' not in cfg) else cfg.runner['type'])
dataset = build_dataset(cfg.data.train)
train_dataloader_default_args = dict(samples_per_gpu=2, workers_per_gpu=0, num_gpus=len(cfg.gpu_ids), dist=distributed, s... |
class UnitDictionary(Dictionary):
def __init__(self, *, n_units, bos='<s>', pad='<pad>', eos='</s>', unk='<unk>', extra_special_symbols=None, clip=False):
self.n_units = n_units
(self.bos_word, self.unk_word, self.pad_word, self.eos_word) = (bos, unk, pad, eos)
self.clip = clip
self.... |
def get_example_inputs(model_name, dataset_name='sst2'):
tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)
dataset = load_dataset(dataset_name, split='validation')
text = (dataset[0]['text'] if (dataset_name == 'lambada') else dataset[0]['sentence'])
example_inputs = tokenizer(text, pad... |
def le_net_cifar(pretrained: bool=False, progress: bool=True, num_classes: int=10, layer_config=None):
print('Converting LeNet CNN CIFAR to {} mode'.format(MODE_STRING))
return create_le_net_biomodel(le_net.le_net_cifar, MODE, layer_config, pretrained, progress, num_classes) |
def map_to_cuda(tensor_dict):
cuda_tensor_dict = {}
for (key, value) in tensor_dict.items():
cuda_tensor_dict[key] = value.cuda()
return cuda_tensor_dict |
def test_orbit_setup_radec_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)], radec=True, uvw=True)
assert (numpy.fabs((o.ra(quantity... |
def display_few_shot_examples():
data_root = '/dccstor/jsdata1/dev/RepMet/notebooks/food_usecase_data'
image_set = ['PRDS_0_192_501_589_885_top.jpg', 'PRDS_0_119_137_523_447_top.jpg', 'PRDS_0_118_208_470_612_top.jpg', 'PRDS_0_571_234_923_608_top.jpg']
nrows = 1
ncols = 4
fig = plt.figure(2)
ff =... |
def prepare_image(pil_image, w=512, h=512):
pil_image = pil_image.resize((w, h), resample=Image.BICUBIC, reducing_gap=1)
arr = np.array(pil_image.convert('RGB'))
arr = ((arr.astype(np.float32) / 127.5) - 1)
arr = np.transpose(arr, [2, 0, 1])
image = torch.from_numpy(arr).unsqueeze(0)
return imag... |
def initialize(worker):
pconns = {}
cconns = {}
ps = {}
for key in chunk_keys:
(pconn, cconn) = Pipe()
(pconns[key], cconns[key]) = (pconn, cconn)
p = Process(target=worker.brain, args=(cconn,))
p.start()
ps[key] = p
for (key, pconn) in pconns.items():
... |
def match_frame_ctrl_input(data_dir, datasets, max_offset, redo_matching=False, remove_zeros=True, policy='autopilot'):
frames = []
for dataset in datasets:
for folder in utils.list_dirs(os.path.join(data_dir, dataset)):
session_dir = os.path.join(data_dir, dataset, folder)
frame... |
class TestDiceLoss(TestCase):
def setUp(self) -> None:
self.predict_logit = torch.randn(10, 3, 256, 256)
self.target = torch.randint(0, 3, (10, 256, 256))
def test_mask_dice(self):
iteration = 10
criterion = ThreeDimDiceLoss()
onehot_pred = logit2one_hot(self.predict_logi... |
(a='double', autosave_time='double', bottleneck=str, component='Component', components=list, dump_index='Py_ssize_t', dump_time=object, dump_times=list, dump_times_a=set, dump_times_t=set, initial_time_step='Py_ssize_t', interaction_name=str, output_filenames=dict, output_filenames_autosave=dict, recompute_t_max='bint'... |
class MetadataCatalog():
_NAME_TO_META = {}
def get(name):
assert len(name)
if (name in MetadataCatalog._NAME_TO_META):
return MetadataCatalog._NAME_TO_META[name]
else:
m = MetadataCatalog._NAME_TO_META[name] = Metadata(name=name)
return m
def list... |
class FlavaPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def get_uniform_density(x_shape):
return FlowDensity(bijection=LogitBijection(x_shape=x_shape).inverse(), prior=UniformDensity(x_shape)) |
def weight_reduce_loss(loss: Tensor, weight: Optional[Tensor]=None, reduction: str='mean', avg_factor: Optional[float]=None) -> Tensor:
if (weight is not None):
loss = (loss * weight)
if (avg_factor is None):
loss = reduce_loss(loss, reduction)
elif (reduction == 'mean'):
eps = torch... |
class LightGCN(BasicModel):
def __init__(self, config: dict, dataset: BasicDataset):
super(LightGCN, self).__init__()
self.config = config
self.dataset: dataloader.BasicDataset = dataset
self.__init_weight()
def __init_weight(self):
self.num_users = self.dataset.n_users
... |
def subquery_range(current, pos, tokens, in_quote=False):
if ((current is not None) and (tokens[pos] == 'SELECT') and (not in_quote)):
return (pos, current[1])
elif ((tokens[pos] == '(') and (not in_quote)):
start = pos
end = (pos + 1)
depth = 1
(in_squote, in_dquote) = (... |
def calculate_ap_py(results):
def cal_iou(rect1, rect2):
lt_x = max(rect1[0], rect2[0])
lt_y = max(rect1[1], rect2[1])
rb_x = min(rect1[2], rect2[2])
rb_y = min(rect1[3], rect2[3])
if ((rb_x > lt_x) and (rb_y > lt_y)):
intersection = ((rb_x - lt_x) * (rb_y - lt_y)... |
def ObservationModel(symbolic, observation_size, belief_size, state_size, embedding_size, activation_function='relu'):
if symbolic:
return SymbolicObservationModel(observation_size, belief_size, state_size, embedding_size, activation_function)
else:
return VisualObservationModel(belief_size, sta... |
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_mode):
label_map = {label: i for (i, label) in enumerate(label_list)}
features = []
for (ex_index, example) in enumerate(examples):
if ((ex_index % 10000) == 0):
logger.info(('Writing example %d of %... |
def _test_feature_extractors(self, extractors, overwrite_cfgs, overwrite_in_channels):
self.assertGreater(len(extractors), 0)
in_channels_default = 64
for (name, builder) in extractors.items():
print('Testing {}...'.format(name))
if (name in overwrite_cfgs):
cfg = load_config(ove... |
def imagenet_det_classes() -> list:
return ['accordion', 'airplane', 'ant', 'antelope', 'apple', 'armadillo', 'artichoke', 'axe', 'baby_bed', 'backpack', 'bagel', 'balance_beam', 'banana', 'band_aid', 'banjo', 'baseball', 'basketball', 'bathing_cap', 'beaker', 'bear', 'bee', 'bell_pepper', 'bench', 'bicycle', 'bind... |
class TransformerLanguageModelConfig(FairseqDataclass):
activation_fn: ChoiceEnum(utils.get_available_activation_fns()) = field(default='relu', metadata={'help': 'activation function to use'})
dropout: float = field(default=0.1, metadata={'help': 'dropout probability'})
attention_dropout: float = field(defa... |
class Whole_Slide_Bag_FP_SAVE(Dataset):
def __init__(self, file_path, wsi, pretrained=False, custom_transforms=None, custom_downsample=1, target_patch_size=(- 1), select_idx=None):
self.pretrained = pretrained
self.wsi = wsi
self.roi_transforms = simple_transforms(pretrained=pretrained)
... |
class DotDict(dict):
def __init__(self, value=None):
if (value is None):
pass
elif isinstance(value, dict):
for key in value:
self.__setitem__(key, value[key])
else:
raise TypeError('expected dict')
def __getitem__(self, key):
v... |
_module()
class TextSnake(TextDetectorMixin, SingleStageTextDetector):
def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None, show_score=False, init_cfg=None):
SingleStageTextDetector.__init__(self, backbone, neck, bbox_head, train_cfg, test_cfg, pretrained, init_cfg)
... |
class Solution(object):
def __init__(self, sol):
if isinstance(sol, str):
self.dict = strsol2dict(sol)
elif isinstance(sol, dict):
self.dict = sol
if ('err' not in self.dict):
self.dict['err'] = 0.0
if ('rco' not in self.dict):
... |
def build_freeimage(args):
path = os.path.join(args.build_path, 'freeimage')
if os.path.exists(path):
return
if PLATFORM_IS_WINDOWS:
url = '
archive_path = os.path.join(args.download_path, 'FreeImage3180Win32Win64.zip')
download_zipfile(url, archive_path, args.build_path, '39... |
def test_add_config_non_dict_raises(ing):
with pytest.raises(TypeError):
ing.add_config(12)
with pytest.raises(TypeError):
ing.add_config(True) |
.ml_cpu_only
_dtypes
_feature_dtypes
_functions
_functions
.parametrize('empty_point_set', [False])
def test_voxel_pooling_grad(ml, pos_dtype, feat_dtype, position_fn, feature_fn, empty_point_set):
rng = np.random.RandomState(123)
N = (0 if empty_point_set else 50)
channels = 4
positions = rng.uniform(0... |
def compile_all():
args = parse_args()
pdf_id2tex_file_name = {}
all_list = os.listdir(args.tex_base_folder)
all_list.sort()
pbar = tqdm.tqdm(all_list)
for base_folder in pbar:
pbar.set_description('Processing {}'.format(base_folder))
folder = os.path.join(args.tex_base_folder, b... |
def test_tolerance_value_effect():
(hash_dict, dist_func) = initialize()
bf = BruteForce(hash_dict, dist_func)
query = '5'
valid_retrievals_2 = bf.search(query, tol=2)
valid_retrievals_3 = bf.search(query, tol=3)
assert (set([i[0] for i in valid_retrievals_2]) != set([i[0] for i in valid_retriev... |
def make_comparable_grid(*batches, nrow):
assert all(((len(batches[0]) == len(batch)) for batch in batches[1:]))
N = len(batches[0])
grids = []
for i in range(0, N, nrow):
rows = [batch[i:(i + nrow)] for batch in batches]
row = torch.cat(rows)
grid = to_grid(row, 'torch', nrow=nr... |
_REGISTRY.register()
class Classification(EvaluatorBase):
def __init__(self, cfg, lab2cname=None, **kwargs):
super().__init__(cfg)
self._lab2cname = lab2cname
self._correct = 0
self._total = 0
self._per_class_res = None
self._y_true = []
self._y_pred = []
... |
def parse_precision(precision, model='bigdl-llm'):
result = match('([a-zA-Z_]+)(\\d+)([a-zA-Z_\\d]*)', precision)
datatype = result.group(1)
bit = int(result.group(2))
if (bit >= 16):
float_map = dict(bf16='bfloat16', fp16='float16', fp32='float32')
return f'dtype={float_map[precision]}'... |
class Logger(logging.Logger):
NAME = 'SingletonLogger'
def get(cls, file_path=None, level='info', colorize=True):
logging.setLoggerClass(cls)
logger = logging.getLogger(cls.NAME)
logging.setLoggerClass(logging.Logger)
logger.setLevel(log_lv[level])
if logger.hasHandlers()... |
def extract_layer(model, layer):
layer = layer.split('.')
module = model
if (hasattr(model, 'module') and (layer[0] != 'module')):
module = model.module
if ((not hasattr(model, 'module')) and (layer[0] == 'module')):
layer = layer[1:]
for l in layer:
if hasattr(module, l):
... |
class FSMTTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = FSMTTokenizer
def setUp(self):
super().setUp()
vocab = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<... |
def q_rnd():
(u, v, w) = np.random.uniform(0.0, 1.0, size=[3])
v *= (2.0 * np.pi)
w *= (2.0 * np.pi)
return np.asarray([(((1.0 - u) ** 0.5) * np.sin(v)), (((1.0 - u) ** 0.5) * np.cos(v)), ((u ** 0.5) * np.sin(w)), ((u ** 0.5) * np.cos(w))], np.float32) |
class Tester(BaseTrainer):
def __init__(self, config, model, data_loader, writer, checkpoint_dir, logger, valid_data_loader=None, test_data_loader=None, metric_ftns=None):
super(Tester, self).__init__(config, data_loader, writer, checkpoint_dir, logger, valid_data_loader=valid_data_loader, test_data_loader=... |
class GraspNetModel():
def __init__(self, opt):
self.opt = opt
self.gpu_ids = opt.gpu_ids
self.is_train = opt.is_train
if (self.gpu_ids and (self.gpu_ids[0] >= torch.cuda.device_count())):
self.gpu_ids[0] = (torch.cuda.device_count() - 1)
self.device = (torch.devi... |
def current_git_hash():
unstaged_changes = False
try:
subprocess.check_output(['git', 'diff-index', '--quiet', 'HEAD', '--'])
except subprocess.CalledProcessError as grepexc:
if (grepexc.returncode == 1):
warnings.warn('Running experiments with unstaged changes.')
uns... |
class SqueezeExcite(nn.Module):
def __init__(self, in_chs, rd_ratio=0.25, rd_channels=None, act_layer=nn.ReLU, gate_layer=nn.Sigmoid, force_act_layer=None, rd_round_fn=None):
super(SqueezeExcite, self).__init__()
if (rd_channels is None):
rd_round_fn = (rd_round_fn or round)
... |
def profile_model(model, cfg):
model.eval()
(B, N, C) = (1, cfg.num_points, 3)
if cfg.variable:
points = torch.randn((B * N), 3).cuda().contiguous()
features = torch.randn((B * N), C).cuda().contiguous()
offset = []
count = 0
for i in range(B):
count += N
... |
def get_default_configuration(network, task, network_trainer, plans_identifier=default_plans_identifier, search_in=(nnunet.__path__[0], 'training', 'network_training'), base_module='nnunet.training.network_training'):
assert (network in ['2d', '3d_lowres', '3d_fullres', '3d_cascade_fullres']), "network can only be ... |
class Pool(object):
_WORKER_AUGSEQ = None
_WORKER_SEED_START = None
def __init__(self, augseq, processes=None, maxtasksperchild=None, seed=None):
assert (Pool._WORKER_AUGSEQ is None), '_WORKER_AUGSEQ was already set when calling Pool.__init__(). Did you try to instantiate a Pool within a Pool?'
... |
def detect_trend_anomaly_arr(y, th_arr):
min_diff = (y - th_arr[0])
max_diff = (y - th_arr[1])
anomaly_indexes = np.logical_or((min_diff < 0), (max_diff > 0))
anomaly_scores = np.zeros_like(y)
anomaly_scores[anomaly_indexes] = 1
return list(set(np.where((anomaly_scores > 0))[0])) |
class CIFAR10ItPrServer(ItPrServer):
def init_test_loader(self):
self.test_loader = get_data_loader(EXP_NAME, data_type='test', batch_size=1000, num_workers=8, pin_memory=True)
def init_clients(self):
rand_perm = torch.randperm(NUM_TRAIN_DATA).tolist()
indices = []
len_slice = (N... |
class Algorithm(torch.nn.Module):
def __init__(self, args):
super(Algorithm, self).__init__()
def update(self, minibatches):
raise NotImplementedError
def predict(self, x):
raise NotImplementedError |
def word_embedding_elmo(sentence: List[str], elmo_model: ElmoEmbedder, remove_stopwords=False, avg_all_layers=True) -> np.ndarray:
if remove_stopwords:
sentence = list(stop_words_filter(sentence))
sentence_vectors = elmo_model.embed_sentence(sentence)
if (not avg_all_layers):
sentence_word_e... |
def print_write(print_str, log_file):
print(*print_str)
if (log_file is None):
return
with open(log_file, 'a') as f:
print(*print_str, file=f) |
class TrainerFactory():
def __init__(self):
self.tfidf_experiments = [ModelType.XGBoost, ModelType.NaiveBayes, ModelType.SVM]
self.sequence_experiments = [ModelType.LSTM, ModelType.BiLSTM, ModelType.TRANSFORMERENCODER]
self.graph_experiments = [ModelType.TreeLSTM, ModelType.GCN, ModelType.GA... |
class ViTHybridImageProcessor(metaclass=DummyObject):
_backends = ['vision']
def __init__(self, *args, **kwargs):
requires_backends(self, ['vision']) |
def parse_args():
parser = argparse.ArgumentParser(description='Test a Visual Grounding network')
parser.add_argument('--gpu_id', help='gpu_id', default=0, type=int)
parser.add_argument('--test_split', help='test_split', default='val', type=str)
parser.add_argument('--batchsize', help='batchsize', defau... |
def fixup_resnet56(**kwargs):
model = FixupResNet(FixupBasicBlock, [9, 9, 9], **kwargs)
return model |
class DummyBoxEnv(DummyEnv):
def __init__(self, random=True, obs_dim=(4,), action_dim=(2,)):
super().__init__(random, obs_dim, action_dim)
def observation_space(self):
return gym.spaces.Box(low=(- 1), high=1, shape=self._obs_dim, dtype=np.float32)
def action_space(self):
return gym.s... |
class DropoutQBits_(torch.autograd.Function):
def forward(ctx, input, probability):
mask = torch.ops.qbits_customop.dropout_fwd(input, probability)
if any(ctx.needs_input_grad[:1]):
ctx.tensors = (mask,)
else:
ctx.tensors = (None,)
return input
def backwar... |
def saveFlags(path, flags):
file = (path + '/FLAGS.txt')
with open(file, 'w') as f:
f.write('\n'.join(flags))
print('FLAGS saved') |
class ResNet_D(nn.Module):
'Discriminator ResNet architecture from
def __init__(self, size=64, nfilter=64, nfilter_max=512, res_ratio=0.1):
super().__init__()
s0 = self.s0 = 4
nf = self.nf = nfilter
nf_max = self.nf_max = nfilter_max
nlayers = int(np.log2((size / s0)))
... |
def generate_data_quad(rows):
x_array = []
y_array = []
while (len(x_array) < rows):
a = float(np.random.randint((- 10), 10))
b = float(np.random.randint((- 10), 10))
c = float(np.random.randint((- 10), 10))
y = [0, 0]
try:
y = [(((- b) + math.sqrt(((b * b... |
class Segformer_b0_b1(nn.Module):
def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=20, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1, norm_layer=partial(nn.LayerNorm, eps=1e-0... |
def get_numpy_image(url_or_filepath):
if ((' in url_or_filepath) or ('www' in url_or_filepath)):
url = url_or_filepath
response = requests.get(url)
pim = PIL.Image.open(BytesIO(response.content))
else:
filepath = url_or_filepath
pim = PIL.Image.open(filepath)
nim = _p... |
def PHC_login(form, phcdb):
import Cookie
error = 0
Folder = ''
Name_First = ''
Status = None
if form.has_key('Signout'):
error = 10
UpdateCookie(form, '', '', error)
elif form.has_key('phcaction'):
(error, usermail, userpwd) = ProcessName(form)
if (not error)... |
def tee_log(file_name):
f = open(file_name, 'w+')
def logger(s):
log(s)
f.write(s)
f.write('\n')
f.flush()
return logger |
def change_default_args(**kwargs):
def layer_wrapper(layer_class):
class DefaultArgLayer(layer_class):
def __init__(self, *args, **kw):
pos_to_kw = get_pos_to_kw_map(layer_class.__init__)
kw_to_pos = {kw: pos for (pos, kw) in pos_to_kw.items()}
for... |
def test_interpolation_grad():
batch_size = 1
feat_dim = 2
m = 4
feats = torch.randn(batch_size, feat_dim, m, requires_grad=True).float().cuda()
def interpolate_func(inputs):
idx = torch.from_numpy(np.array([[[0, 1, 2], [1, 2, 3]]])).int().cuda()
weight = torch.from_numpy(np.array([[... |
class RMSELoss(nn.Module):
def __init__(self, eps=1e-06):
super().__init__()
self.mse = nn.MSELoss()
self.eps = eps
def forward(self, yhat, y):
return torch.sqrt((self.mse(yhat, y) + self.eps)) |
def _generate_common_dataloader(dataloader, framework, distributed=False):
if (not isinstance(dataloader, DataLoader)):
assert (hasattr(dataloader, '__iter__') and hasattr(dataloader, 'batch_size')), 'dataloader must implement __iter__ method and batch_size attribute'
assert (not distributed), 'Plea... |
def print_warning(s):
print((((((TerminalColors.WARNING + '[') + get_time()) + '] WARN ') + str(s)) + TerminalColors.ENDC)) |
def get_cuda_version() -> float:
global VALID_CUDA
if (('CUDA_HOME' not in os.environ) and ('CUDA_PATH' in os.environ)):
os.environ['CUDA_HOME'] = os.environ['CUDA_PATH']
assert ('CUDA_HOME' in os.environ), 'Cannot find the $CUDA_HOME in the environments. Please manually install the CUDA >= 10.1, an... |
def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer, parse_record_fn, dtype=None):
if (dtype is None):
dtype = tf.float32
dataset = dataset.prefetch(buffer_size=batch_size)
if is_training:
dataset = dataset.shuffle(buffer_size=shuffle_buffer)
dataset = dataset.rep... |
class FlatNCE(nn.Module):
def __init__(self, temperature):
self.temperature = temperature
super().__init__()
def forward(self, z_i, z_j):
batch_size = z_i.size(0)
features = torch.cat([z_i, z_j], dim=0)
labels = torch.cat([torch.arange(batch_size) for i in range(2)], dim=... |
class Optimizer():
def __init__(self, archive, emitters):
if (len(emitters) == 0):
raise ValueError('Pass in at least one emitter to the optimizer.')
emitter_ids = set((id(e) for e in emitters))
if (len(emitter_ids) != len(emitters)):
raise ValueError('Not all emitter... |
class Pad(UnaryOpBase):
num_var_param = _pad_num_var_param()
in_dtypes = [(i,) for i in DTYPE_GEN_FLOATS]
out_dtypes = [(i,) for i in DTYPE_GEN_FLOATS]
def __str__(self) -> str:
return f'{self.name()} (padding={list(self.padding_list)})'
def __init__(self, padding_list, pad_t):
super... |
class GMNlayer(MessagePassing):
def __init__(self, in_channels, out_channels, device):
super(GMNlayer, self).__init__(aggr='add')
self.device = device
self.out_channels = out_channels
self.fmessage = nn.Linear((3 * in_channels), out_channels)
self.fnode = torch.nn.GRUCell((2 ... |
class FitInfo():
def __init__(self, guesses_dict):
self.fit_param_names = []
self.all_params = dict()
for key in guesses_dict:
self.all_params[key] = _Param(guesses_dict[key])
def add_uniform_fit_param(self, name, low_lim, high_lim, low_guess=None, high_guess=None):
i... |
def final():
head = []
head.append(('layernorm.weight', 'norm.weight'))
head.append(('layernorm.bias', 'norm.bias'))
head.append(('classifier.weight', 'head.weight'))
head.append(('classifier.bias', 'head.bias'))
return head |
class DownSamplingBlock(nn.Module):
def __init__(self, nIn, nOut):
super().__init__()
self.nIn = nIn
self.nOut = nOut
if (self.nIn < self.nOut):
nConv = (nOut - nIn)
else:
nConv = nOut
self.conv3x3 = Conv(nIn, nConv, kSize=3, stride=2, padding=... |
def dot_product_attention(q, k, v, bias, dropout_rate=0.0, summaries=False, image_shapes=None, name=None):
with tf.variable_scope(name, default_name='dot_product_attention', values=[q, k, v]):
logits = tf.matmul(q, k, transpose_b=True)
if (bias is not None):
logits += bias
weight... |
def get_frame_info(level=2):
caller_frame = inspect.stack()[level]
info = inspect.getframeinfo(caller_frame[0])
return (((info.filename + ':') + str(info.lineno)) + ': ') |
def add_parser_params(parser):
parser.add_argument('--resume', type=str, default=None, help='put the path to resuming file if needed')
parser.add_argument('--checkname', type=str, default=None, help='the name of the checkpoint.')
parser.add_argument('--save_ckpt_steps', type=int, default=500, help='save che... |
def convert_file_size_to_int(size: Union[(int, str)]):
if isinstance(size, int):
return size
if size.upper().endswith('GIB'):
return (int(size[:(- 3)]) * (2 ** 30))
if size.upper().endswith('MIB'):
return (int(size[:(- 3)]) * (2 ** 20))
if size.upper().endswith('KIB'):
re... |
def main():
parser = argparse.ArgumentParser(description='Chainforge command line tool')
subparsers = parser.add_subparsers(dest='serve')
serve_parser = subparsers.add_parser('serve', help='Start Chainforge server')
serve_parser.add_argument('--port', help='The port to run the server on. Defaults to 800... |
def plot_feature(data, label=None, y_range=None, new_fig=True, fig=None):
if new_fig:
fig = plt.figure()
ax = plt.gca()
if (y_range is not None):
ax.set_ylim(y_range)
ax.plot(np.arange(np.shape(data)[0]), data, label=label)
if (label is not None):
ax.legend()
if new_fig:
... |
def log_every_n(lvl, msg, n=1, *, name=None):
(caller_module, key) = _find_caller()
_LOG_COUNTER[key] += 1
if ((n == 1) or ((_LOG_COUNTER[key] % n) == 1)):
logging.getLogger((name or caller_module)).log(lvl, msg) |
def add_args(parser):
parser.add_argument('--num_steps', type=int, default=(10 ** 6), help='Number of steps in training')
parser.add_argument('--transitions_per_step', type=int, default=1, help='env transitions per training step. Defaults to 1, but will need to be set higher for repaly ratios < 1')
... |
('torch.cuda.device_count', return_value=1)
('torch.cuda.set_device')
('torch.distributed.init_process_group')
('subprocess.getoutput', return_value='127.0.0.1')
def test_init_dist(mock_getoutput, mock_dist_init, mock_set_device, mock_device_count):
with pytest.raises(ValueError):
init_dist('invaliad_launch... |
class CrossEntropyLoss(_Loss):
def forward(self, x, y):
assert (x.size() == y.size()), 'input and target must have the same size'
return x.cross_entropy(y, skip_forward=self.skip_forward) |
class PNet(nn.Layer):
def __init__(self):
super(PNet, self).__init__()
self.features = nn.Sequential(OrderedDict([('conv1', nn.Conv2D(3, 10, 3, 1)), ('prelu1', nn.PReLU(10)), ('pool1', nn.MaxPool2D(2, 2, ceil_mode=True)), ('conv2', nn.Conv2D(10, 16, 3, 1)), ('prelu2', nn.PReLU(16)), ('conv3', nn.Con... |
class GraspSamplerGAN(GraspSampler):
def __init__(self, model_scale, pointnet_radius, pointnet_nclusters, latent_size=2, device='cpu'):
super(GraspSamplerGAN, self).__init__(latent_size, device)
self.create_decoder(model_scale, pointnet_radius, pointnet_nclusters, (latent_size + 3))
def sample_l... |
class decoder(nn.Module):
def __init__(self, d=128):
super(decoder, self).__init__()
self.features = nn.Sequential(nn.Conv2d(12, 32, kernel_size=3, padding=1), nn.ELU(inplace=True), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ELU(inplace=True), nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.EL... |
def model2():
f1 = Categorical([[0.23, 0.77]])
f3 = JointCategorical([[0.17, 0.15], [0.4, 0.28]])
f4 = JointCategorical([[0.32, 0.12], [0.08, 0.48]])
f2 = JointCategorical([[[0.1, 0.05, 0.05], [0.15, 0.05, 0.04]], [[0.2, 0.1, 0.05], [0.05, 0.1, 0.06]]])
m1 = Categorical([[0.5, 0.5]])
m2 = Catego... |
def optimizer_kwargs(cfg):
return {'optim': cfg.train.optim, 'lr': cfg.train.lr, 'weight_decay': cfg.train.weight_decay, 'momentum': cfg.sgd.momentum, 'sgd_dampening': cfg.sgd.dampening, 'sgd_nesterov': cfg.sgd.nesterov, 'rmsprop_alpha': cfg.rmsprop.alpha, 'adam_beta1': cfg.adam.beta1, 'adam_beta2': cfg.adam.beta2,... |
def read_data(fname):
lines = [x.strip() for x in open(fname).readlines()]
data = []
label = []
for line in lines:
words = []
tags = []
for pair in line.split(' '):
items = pair.split('/')
words.append(str('/'.join(items[:(- 1)])))
tags.append(... |
.script_launch_mode('subprocess')
def test_automate_training(download_functional_test_files, script_runner):
file_config = Path(__data_testing_dir__, 'automate_training_config.json')
file_config_hyper = Path(__data_testing_dir__, 'automate_training_hyperparameter_opt.json')
__output_dir__ = Path(__tmp_dir__... |
def score_target_hypo(args, a, b, c, lenpen, target_outfile, hypo_outfile, write_hypos, normalize):
print('lenpen', lenpen, 'weight1', a, 'weight2', b, 'weight3', c)
(gen_output_lst, bitext1_lst, bitext2_lst, lm_res_lst) = load_score_files(args)
dict = dictionary.Dictionary()
scorer = scorer = bleu.Scor... |
def log_validation(text_encoder, tokenizer, prior, args, accelerator, weight_dtype, epoch):
logger.info('Running validation... ')
pipeline = AutoPipelineForText2Image.from_pretrained(args.pretrained_decoder_model_name_or_path, prior=accelerator.unwrap_model(prior), prior_text_encoder=accelerator.unwrap_model(te... |
class Wire():
def __init__(self, tile, index):
self.tile = tile
self.index = index
self.data = tile.get_wire_data(index)
def name(self):
return self.data.name
def intent(self):
return self.data.intent
def node(self):
if (self.index not in self.tile.wire_to... |
def train_val_split(dataset, val_frac):
indices = np.arange(len(dataset))
np.random.shuffle(indices)
val_size = int(np.round((len(dataset) * val_frac)))
(train_indices, val_indices) = (indices[val_size:], indices[:val_size])
(train_data, val_data) = (Subset(dataset, train_indices), Subset(dataset, v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.