code stringlengths 101 5.91M |
|---|
class AddNewModelLikeCommand(BaseTransformersCLICommand):
def register_subcommand(parser: ArgumentParser):
add_new_model_like_parser = parser.add_parser('add-new-model-like')
add_new_model_like_parser.add_argument('--config_file', type=str, help='A file with all the information for this model creati... |
class ComparableSampler(Sampler[ComparableT], Generic[ComparableT]):
def __lt__(self, other: Union[(ComparableT, 'ComparableSampler')]) -> bool:
if isinstance(other, ComparableSampler):
return super().__lt__(other)
if (self.value is None):
raise ValueError('`self.value` is No... |
def test_alias_delay_initialization1(capture):
class B(m.A):
def __init__(self):
super().__init__()
def f(self):
print('In python f()')
with capture:
a = m.A()
m.call_f(a)
del a
pytest.gc_collect()
assert (capture == 'A.f()')
with c... |
def read_issia_ground_truth(camera_id, dataset_path):
assert ((camera_id >= 1) and (camera_id <= 6))
dataset_path = os.path.expanduser(dataset_path)
annotation_path = os.path.join(dataset_path, 'Annotation Files')
annotation_file = (('Film Role-0 ID-' + str(camera_id)) + ' T-0 m00s00-026-m00s01-020.xgtf... |
class IRNode(object):
def __init__(self, node_type=None, parent=None, parse_info=None, raw_text=None):
super().__init__()
self.node_type = node_type
self.la_type = None
self.parent = None
self.set_parent(parent)
self.parse_info = parse_info
self.raw_text = raw... |
class TestPPOPendulumLSTM(TfGraphTestCase):
.mujoco_long
def test_ppo_pendulum_lstm(self):
with LocalTFRunner(snapshot_config) as runner:
env = GarageEnv(normalize(gym.make('InvertedDoublePendulum-v2')))
lstm_policy = GaussianLSTMPolicy(env_spec=env.spec)
baseline = G... |
class DataTrainingArguments():
lang: Optional[str] = field(default=None, metadata={'help': 'Language id for summarization.'})
dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'})
dataset_config_name: Optional[str] = field(default=... |
def main_worker(gpu, ngpus_per_node, args):
global best_acc1
args.gpu = gpu
if (args.multiprocessing_distributed and (args.gpu != 0)):
def print_pass(*args):
pass
builtins.print = print_pass
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))... |
def dump_file(*dps):
for dp in dps:
if (len(dp) != 2):
print(('issue:' + str(dp)))
continue
dfile = open(dp[1], 'wb')
cp.dump(dp[0], dfile)
dfile.close()
print('dump file done.') |
class MetaMonkey(torch.nn.Module):
def __init__(self, net):
super().__init__()
self.net = net
self.parameters = OrderedDict(net.named_parameters())
def forward(self, inputs, parameters=None):
if (parameters is None):
return self.net(inputs)
param_gen = iter(pa... |
def xgboost_eval_metric_accuracy(preds, dtrain):
target = dtrain.get_label()
weight = dtrain.get_weight()
if (len(weight) == 0):
weight = None
return ('accuracy', negative_accuracy(target, preds, weight)) |
class convnext_large(nn.Module):
def __init__(self, pretrained=True):
super().__init__()
self.convnext = timm.create_model('convnext_large', pretrained=pretrained)
def forward(self, x, data=None, layer=2):
x = self.convnext.stem(x)
x = self.convnext.stages[0](x)
x = self.... |
def create_data_info_service(port, pool_size=10):
server = grpc.server(futures.ThreadPoolExecutor(max_workers=pool_size))
data_info_servicer = DataInfoServicer()
coworker_pb2_grpc.add_DataInfoServiceServicer_to_server(data_info_servicer, server)
server.add_insecure_port('[::]:{}'.format(port))
logge... |
class EmptyModule(nn.Module):
def __init__(self):
super(EmptyModule, self).__init__()
def forward(self, x):
return x |
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = (out_features or in_features)
hidden_features = (hidden_features or in_features)
self.fc1 = nn.Linear(in_features, hidden_fea... |
def create_file_symlink(file1, file2):
try:
if g_pathmgr.exists(file2):
g_pathmgr.rm(file2)
g_pathmgr.symlink(file1, file2)
except Exception as e:
logging.info(f'Could NOT create symlink. Error: {e}') |
def update_models(opt, epoch, modelG, modelD, dataset_warp):
if (epoch > opt.niter):
modelG.module.update_learning_rate(epoch, 'G')
modelD.module.update_learning_rate(epoch, 'D')
if ((epoch % opt.niter_step) == 0):
dataset_warp.dataset.update_training_batch((epoch // opt.niter_step))
... |
class LZ09_F5(LZ09):
def __init__(self, number_of_variables=30):
super(LZ09_F5, self).__init__(number_of_variables, dtype=1, ltype=26, ptype=21)
self.obj_directions = [self.MINIMIZE, self.MINIMIZE]
self.obj_labels = ['f(x)', 'f(y)']
def number_of_objectives(self) -> int:
return l... |
def delexicalise(utt, dictionary):
for (key, val) in dictionary:
utt = ((' ' + utt) + ' ').replace(((' ' + key) + ' '), ((' ' + val) + ' '))
utt = utt[1:(- 1)]
return utt |
def main():
import argparse
import cv2
parser = argparse.ArgumentParser()
parser.add_argument('dataset_loader', type=str)
parser.add_argument('dataset_path', type=str)
parser.add_argument('--video_name', type=str)
parser.add_argument('--random_seed', type=int, help='Optional random seed for ... |
def measure_model(model, x):
global count_ops, count_params
count_ops = 0
count_params = 0
def should_measure(x):
return (is_leaf(x) or is_pruned(x))
def modify_forward(model):
for child in model.children():
if should_measure(child):
def new_forward(m):
... |
def switch_pool(input, pooling_switches, name=None):
pooled_shape = get_shape(pooling_switches)
batch_size = pooled_shape[0]
element_num = np.prod(pooled_shape[1:])
assert (get_shape(input)[0] == batch_size), 'mismatched batch_size'
global_base = np.reshape((np.array(range(batch_size)) * element_num... |
class ERFNet(nn.Module):
def __init__(self, num_classes, opt):
super().__init__()
self.encoder = Encoder(num_classes)
self.decoder = Decoder(num_classes)
if (opt.weights_init == 'pretrained'):
path_getter = gp.GetPath()
checkpoint_path = path_getter.get_checkp... |
def test_dtype(simple_dtype):
from sys import byteorder
e = ('<' if (byteorder == 'little') else '>')
assert ([x.replace(' ', '') for x in m.print_dtypes()] == [simple_dtype_fmt(), packed_dtype_fmt(), f"[('a',{simple_dtype_fmt()}),('b',{packed_dtype_fmt()})]", partial_dtype_fmt(), partial_nested_fmt(), "[('... |
def get_device(device=None):
if (device is None):
if torch.cuda.is_available():
device = 'cuda'
torch.set_default_tensor_type('torch.cuda.FloatTensor')
else:
device = 'cpu'
elif (device == 'cuda'):
if torch.cuda.is_available():
device = 'cu... |
class ToyModel(nn.Module):
def __init__(self, in_features=16, out_features=4, num_linears=8):
super().__init__()
self.first_linear = nn.Linear(in_features, out_features)
self.linears = torch.nn.ModuleList([nn.Linear(out_features, out_features) for _ in range((num_linears - 1))])
def forw... |
def assign_pos_tag_for_bpe(src_path: str, bpe_path: str, trg_path: str) -> None:
src_file = open(src_path, 'r', encoding='utf-8')
bpe_file = open(bpe_path, 'r', encoding='utf-8')
trg_file = open(trg_path, 'w', encoding='utf-8')
for (src_pos_line, bpe_line) in zip(src_file.readlines(), bpe_file.readlines... |
def resnet50_fc512_efdmix12_a0d1(num_classes, loss='softmax', pretrained=True, **kwargs):
model = ResNet(num_classes=num_classes, loss=loss, block=Bottleneck, layers=[3, 4, 6, 3], last_stride=1, fc_dims=[512], dropout_p=None, efdmix_layers=['layer1', 'layer2'], efdmix_alpha=0.1, **kwargs)
if pretrained:
... |
def browse_weights(weights_dir, model='generator'):
exit = False
while (exit is False):
weights = np.sort(os.listdir(weights_dir))[::(- 1)]
print_sel = dict(zip(np.arange(len(weights)), weights))
for k in print_sel.keys():
logger_message = '{item_n}: {item} \n'.format(item_n=... |
def lowecase_list_of_sentences(sentences):
sentences_lowercased = [s.lower() for s in sentences]
return sentences_lowercased |
class IIDIsotropicGaussianUVLoss(nn.Module):
def __init__(self, sigma_lower_bound: float):
super(IIDIsotropicGaussianUVLoss, self).__init__()
self.sigma_lower_bound = sigma_lower_bound
self.log2pi = math.log((2 * math.pi))
def forward(self, u: torch.Tensor, v: torch.Tensor, sigma_u: torc... |
def compute_metrics(eval_preds):
(preds, labels) = eval_preds
if isinstance(preds, tuple):
preds = preds[0]
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
labels = np.where((labels != (- 100)), labels, tokenizer.pad_token_id)
decoded_labels = tokenizer.batch_decode(l... |
class statm_loss(nn.Module):
def __init__(self):
super(statm_loss, self).__init__()
def forward(self, x, y):
x = x.view(x.size(0), x.size(1), (- 1))
y = y.view(y.size(0), y.size(1), (- 1))
x_mean = x.mean(dim=2)
y_mean = y.mean(dim=2)
mean_gap = (x_mean - y_mean).... |
def warn(msg, *args):
if (MIN_LEVEL <= WARN):
print(colorize(('%s: %s' % ('WARN', (msg % args))), 'yellow')) |
def all_metrics(results, test):
ndcg_ = defaultdict(list)
predictions_per_user = defaultdict((lambda : defaultdict(list)))
predictions_per_sensitive_attr = defaultdict((lambda : defaultdict(list)))
metrics_per_user = defaultdict(list)
metrics_per_sensitive_attr = defaultdict(list)
model = ('LR' ... |
('connect', namespace='/tms')
def ws_conn():
c = db.incr('user_count')
socketio.emit('msg', {'count': c}, namespace='/tms') |
class ExperimentNfS(ExperimentOTB):
def __init__(self, root_dir, fps=240, result_dir='results', report_dir='reports'):
self.dataset = NfS(root_dir, fps)
self.result_dir = os.path.join(result_dir, ('NfS/%d' % fps))
self.report_dir = os.path.join(report_dir, ('NfS/%d' % fps))
self.nbin... |
def test_digits_approximate():
model = FeatureBasedSelection(100, 'sqrt', optimizer='approximate-lazy')
model.fit(X_digits, sample_cost=X_digits_costs)
assert_array_equal(model.ranking, digits_approx_ranking)
assert_array_almost_equal(model.gains, digits_approx_gains, 4)
assert_less_equal(sum(X_digi... |
_task('multilingual_masked_lm')
class MultiLingualMaskedLMTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('data', help='colon separated path to data directories list, will be iterated upon during epochs in round-robin manner')
parser.add_argument('--sam... |
def heatmap_generation(image, kernel_size):
kernel = gaussian_kernel(kernel_size)
map = scipy.signal.convolve(image, kernel, mode='same')
return rescale_values_array(map) |
class Normalization(nn.Module):
def __init__(self, mean, std):
super(Normalization, self).__init__()
self.mean = mean.view((- 1), 1, 1)
self.std = std.view((- 1), 1, 1)
def forward(self, input):
return ((input - self.mean) / self.std) |
class NaiveAssassin(NaiveAgent):
def __init__(self, id: int, name: str, config: AvalonBasicConfig, side: int=0, role_name: str='Assassin', role: int=7, sides: List[int]=None, **configs):
assert (role == 7)
super().__init__(id=id, name=name, config=config, side=side, role=role, sides=sides)
async... |
def reduce_feat_size(feat_size, stride=2):
return (None if (feat_size is None) else tuple([(s // stride) for s in feat_size])) |
def randn_tensor(shape: Union[(Tuple, List)], generator: Optional[Union[(List['torch.Generator'], 'torch.Generator')]]=None, device: Optional['torch.device']=None, dtype: Optional['torch.dtype']=None, layout: Optional['torch.layout']=None):
rand_device = device
batch_size = shape[0]
layout = (layout or torc... |
class TensorType(ExplicitEnum):
PYTORCH = 'pt'
TENSORFLOW = 'tf'
NUMPY = 'np'
JAX = 'jax' |
def main(args):
torch.manual_seed(3)
np.random.seed(2)
random.seed(2)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
if (args.dataset in ['ppi', 'reddit']):
data = load_data(args)
g = data.g
train_mask = g.ndata['train_mask']
val_... |
class Finetuner(object):
def __init__(self, args, model, teacher, train_loader, test_loader):
self.args = args
self.model = model
self.teacher = teacher
self.train_loader = train_loader
self.test_loader = test_loader
self.init_models()
def init_models(self):
... |
class SparseTransformerSentenceEncoder(TransformerSentenceEncoder):
def __init__(self, padding_idx: int, vocab_size: int, num_encoder_layers: int=6, embedding_dim: int=768, ffn_embedding_dim: int=3072, num_attention_heads: int=8, dropout: float=0.1, attention_dropout: float=0.1, activation_dropout: float=0.1, max_s... |
class XconfigFastLstmLayer(XconfigLayerBase):
def __init__(self, first_token, key_to_value, prev_names=None):
assert (first_token in ['fast-lstm-layer', 'fast-lstm-batchnorm-layer'])
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
sel... |
def iresgroup50(pretrained=False, **kwargs):
model = iResGroup(ResGroupBlock, [3, 4, 6, 3], **kwargs)
if pretrained:
os.makedirs(default_cache_path, exist_ok=True)
model.load_state_dict(torch.load(download_from_url(model_urls['iresgroup50'], root=default_cache_path)))
return model |
def run_test(cfg, model, distributed):
if distributed:
model = model.module
torch.cuda.empty_cache()
iou_types = ('bbox',)
if cfg.MODEL.MASK_ON:
iou_types = (iou_types + ('segm',))
if cfg.MODEL.KEYPOINT_ON:
iou_types = (iou_types + ('keypoints',))
output_folders = ([None]... |
def find_lora_modules(model: peft.LoraModel) -> Dict[(str, peft.tuners.lora.LoraLayer)]:
modules: Dict[(str, peft.tuners.lora.LoraLayer)] = {}
key_list = [key for (key, _) in model.model.named_modules() if ('lora' not in key)]
for key in key_list:
try:
(_parent, target, _target_name) = p... |
class VGG19(torch.nn.Module):
def __init__(self):
super(VGG19, self).__init__()
features = models.vgg19(pretrained=True).features
self.relu1_1 = torch.nn.Sequential()
self.relu1_2 = torch.nn.Sequential()
self.relu2_1 = torch.nn.Sequential()
self.relu2_2 = torch.nn.Seq... |
def can_convert_to_int(string):
try:
int(string)
return True
except ValueError:
return False |
def require_wandb(test_case):
if (not is_wandb_available()):
return unittest.skip('test requires wandb')(test_case)
else:
return test_case |
def pm_uniform_withCP(local_sub_patch_radius):
def random_neighbor_withCP_uniform(patch, coords, dims, structN2Vmask=None):
vals = []
for coord in zip(*coords):
(sub_patch, _, _) = get_subpatch(patch, coord, local_sub_patch_radius)
rand_coords = [np.random.randint(0, s) for s... |
def _get_sparsity(tsr):
total = tsr.numel()
nnz = tsr.nonzero().size(0)
return (nnz / total) |
(sample=sampled_from([((4, 5, 10), (1, 5, 10), (4, 5, 10)), ((4, 1, 10), (1, 5, 10), (4, 5, 10)), ((4, 5, 10), (4, 2, 10), RuntimeError), ((4, 5, 10), (10,), (4, 5, 10)), ((4, 5, 10), (5,), RuntimeError)]))
def test_logsumexp2_manual_broadcasting(sample):
(t1_shape, t2_shape, res_shape) = sample
if (res_shape =... |
def _split_list(a: list, n: int):
(k, m) = divmod(len(a), n)
return [a[((i * k) + min(i, m)):(((i + 1) * k) + min((i + 1), m))] for i in range(n)] |
class Statistics():
def __init__(self, args):
self.best_mrr = 0
self.best_ndcg = 0
self.best_metrics = None
self.best_epoch = 0
self.metrics = defaultdict(int)
self.metrics['num_samples'] = 0
self.mail_message = ''
self.step = 0
self.mod_flag =... |
def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, init_gain: float=0, verbose: int=0, **kwargs):
d... |
class EfficientDetResizeCrop(Augmentation):
def __init__(self, size, scale, interp=Image.BILINEAR):
super().__init__()
self.target_size = (size, size)
self.scale = scale
self.interp = interp
def get_transform(self, img):
scale_factor = np.random.uniform(*self.scale)
... |
def crossdomain_mixhm(m):
if (type(m) == MixHistogram):
m.update_mix_method('crossdomain') |
class GPStructRunner():
def __init__(self, data_dir, n_inputs, mu_ranks, covs, bin_cov, lr=0.01, n_epoch=15, decay=None, batch_size=None, preprocess_op=None, te_preprocess_op=None, log_dir=None, save_dir=None, model_dir=None, load_model=False, print_freq=None, num_threads=1):
self.data_dir = data_dir
... |
.parametrize('loader_parameters', [{'path_data': [str(Path(__data_testing_dir__, 'microscopy_png'))], 'target_suffix': ['_seg-myelin-manual'], 'extensions': ['.png'], 'roi_params': {'suffix': None, 'slice_filter_roi': None}, 'contrast_params': {'contrast_lst': [], 'balance': {}}, 'slice_axis': 'axial', 'slice_filter_pa... |
def make_beitl16_384(pretrained, use_readout='ignore', hooks=(5, 11, 17, 23)):
model = timm.create_model('beit_large_patch16_384', pretrained=pretrained)
return _make_beit_backbone(model, features=[256, 512, 1024, 1024], hooks=hooks, vit_features=1024, use_readout=use_readout) |
class Robot(xmlr.Object):
def __init__(self, name=None):
self.aggregate_init()
self.name = name
self.joints = []
self.links = []
self.materials = []
self.gazebos = []
self.transmissions = []
self.joint_map = {}
self.link_map = {}
self.p... |
class Network(Assembly):
_class_label = '<net>'
def __init__(self, name=None):
super(Network, self).__init__(name=name)
self._monitors = OrderedDict()
self._learners = OrderedDict()
self._pipline = None
self._backend: Backend = None
self._forward_build = False
... |
def load_state_dict(checkpoint_path, use_ema=False):
if (checkpoint_path and os.path.isfile(checkpoint_path)):
checkpoint = torch.load(checkpoint_path, map_location='cpu')
state_dict_key = 'state_dict'
if isinstance(checkpoint, dict):
if (use_ema and ('state_dict_ema' in checkpoi... |
def create_all_memmaps(dataset_nums, proportions, num_train, num_val, num_test):
intent_file_paths = [f'{file_path}_intent_pose.npy' for file_path in dataset_nums]
shufflers = [np.random.permutation(np.load(path).shape[0]) for path in intent_file_paths]
image_history_file_paths = [f'{file_path}_image_histor... |
def cast_lora_weight(model, dtype=torch.bfloat16):
for (name, module) in model.named_modules():
if isinstance(module, LowBitLinear):
module.compute_dtype = dtype
if isinstance(module, LoraLayer):
module = module.to(dtype)
if isinstance(module, BF16Linear):
... |
def test_dispatch_issue(msg):
class PyClass1(m.DispatchIssue):
def dispatch(self):
return 'Yay..'
class PyClass2(m.DispatchIssue):
def dispatch(self):
with pytest.raises(RuntimeError) as excinfo:
super(PyClass2, self).dispatch()
assert (msg(exc... |
def train_net(net_id, net, train_dataloader, test_dataloader, epochs, lr, args_optimizer, device='cpu'):
logger.info(('Training network %s' % str(net_id)))
train_acc = compute_accuracy(net, train_dataloader, device=device)
(test_acc, conf_matrix) = compute_accuracy(net, test_dataloader, get_confusion_matrix... |
def get_power_spectral_density_matrix(xs: ComplexTensor, mask: torch.Tensor, normalization=True, eps: float=1e-15) -> ComplexTensor:
psd_Y = FC.einsum('...ct,...et->...tce', [xs, xs.conj()])
mask = mask.mean(dim=(- 2))
if normalization:
mask = (mask / (mask.sum(dim=(- 1), keepdim=True) + eps))
p... |
def GetDotNodeName(name_string, is_component=False):
node_name_string = re.sub('-', 'hyphen', name_string)
node_name_string = re.sub('\\.', '_dot_', node_name_string)
if is_component:
node_name_string += (node_name_string.strip() + '_component')
return {'label': name_string, 'node': node_name_st... |
class MNISTDataModule(LightningDataModule):
def __init__(self, data_dir: str='data/', train_val_test_split: Tuple[(int, int, int)]=(55000, 5000, 10000), batch_size: int=64, num_workers: int=0, pin_memory: bool=False):
super().__init__()
self.data_dir = data_dir
self.train_val_test_split = tr... |
def calc_2dsplinecoeffs_c(array2d):
out = copy.copy(array2d)
out = numpy.require(out, dtype=numpy.float64, requirements=['C', 'W'])
ndarrayFlags = ('C_CONTIGUOUS', 'WRITEABLE')
interppotential_calc_2dsplinecoeffs = _lib.samples_to_coefficients
interppotential_calc_2dsplinecoeffs.argtypes = [ndpointe... |
def multicolorline(x, y, cvals, ax, vmin=(- 90), vmax=90):
import cmasher as cmr
import matplotlib.colors as mcolors
from matplotlib.collections import LineCollection
points = np.array([x, y]).T.reshape((- 1), 1, 2)
segments = np.concatenate([points[:(- 1)], points[1:]], axis=1)
norm = plt.Norma... |
class TemplateArg(object):
def __init__(self, parameter):
parts = splitParts(parameter)
self.name = Template.parse(parts[0])
if (len(parts) > 1):
self.default = Template.parse(parts[1])
else:
self.default = None
def __str__(self):
if self.default:
... |
class PaperClassifier1(nn.Module):
def __init__(self, in_dim, hid_dim_1, hid_dim_2, out_dim, norm, act, dropout=0.5):
super(PaperClassifier1, self).__init__()
no_norm = (lambda x, dim: x)
if (norm == 'weight'):
norm_layer = weight_norm
elif (norm == 'batch'):
... |
class TFPreTrainedModel():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
class MEKF_MA(Optimizer):
def __init__(self, params, dim_out, p0=0.01, lbd=1, sigma_r=None, sigma_q=0, lr=1, miu_v=0, miu_p=0, k_p=1, R_decay=False, R_decay_step=1000000):
if (sigma_r is None):
sigma_r = max(lbd, 0)
self._check_format(dim_out, p0, lbd, sigma_r, sigma_q, lr, miu_v, miu_p,... |
def resdropresnet20_cifar10(classes=10, **kwargs):
return get_resdropresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name='resdropresnet20_cifar10', **kwargs) |
def compute_skip_echo_len(model_name, conv, prompt):
model_name = model_name.lower()
if ('chatglm' in model_name):
skip_echo_len = (len(conv.messages[(- 2)][1]) + 1)
elif ('dolly-v2' in model_name):
special_toks = ['### Instruction:', '### Response:', '### End']
skip_echo_len = len(p... |
def auto_wrap(module: nn.Module, auto_wrap_policy: Optional[Callable]=None, **kwargs: Any) -> nn.Module:
if ConfigAutoWrap.in_autowrap_context:
(wrapped_module, remainder) = ConfigAutoWrap.recursive_wrap(module, auto_wrap_policy=auto_wrap_policy, **kwargs)
return wrapped_module
return module |
def random_odd(key: chex.PRNGKey, max_val: int) -> chex.Array:
return ((jax.random.randint(key, (), 0, (max_val // 2)) * 2) + 1) |
def register_annotations_from_source(source: str, filename: str) -> Set[str]:
regisered_modules = set()
for node in ast.parse(source).body:
if (not isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.Expr, ast.Str))):
continue
for module in (get_modules_from_decorators(getattr(node,... |
class FPNSegmentationHead2(nn.Module):
def __init__(self, in_dim, out_dim, decode_intermediate_input=True, hidden_dim=256, shortcut_dims=[24, 32, 96, 1280], align_corners=True):
super().__init__()
self.align_corners = align_corners
self.decode_intermediate_input = decode_intermediate_input
... |
def ResidualTabularWPrior(num_classes, dim_in, coupling_layers, k, means_r=1.0, cov_std=1.0, nperlayer=1, acc=0.9):
device = torch.device('cuda')
inv_cov_std = (torch.ones((num_classes,), device=device) / cov_std)
model = TabularResidualFlow(in_dim=dim_in, hidden_dim=k, num_per_block=coupling_layers)
di... |
def clf_video():
m = Classifier(cls_model_path)
video_path = './data/video/123.mp4'
result = m.classify_video(video_path)
metadata_info = result['metadata']
preds_info = result['preds']
print('# metadata -------')
for (k, v) in metadata_info.items():
print(k, v)
print('# preds --... |
def init_pipe_distributed(rank, world_size):
seed_everything()
if (not torch.distributed.is_initialized()):
os.environ['LOCAL_RANK'] = str(rank)
os.environ['RANK'] = str(rank)
os.environ['WORLD_SIZE'] = str(world_size)
os.environ['NPROC_PER_NODE'] = str(world_size)
if tor... |
def get_variant_spec_image(universe, domain, task, policy, algorithm, *args, **kwargs):
variant_spec = get_variant_spec_base(universe, domain, task, policy, algorithm, *args, **kwargs)
if (('image' in task.lower()) or ('image' in domain.lower())):
preprocessor_params = {'type': 'convnet_preprocessor', '... |
def get_data(name: str, data_type, transform=None, target_transform=None, user_list=None):
dataset = get_config_by_name(name)
if (dataset == femnist):
assert (data_type in ['train', 'test'])
if (transform is None):
transform = transforms.Compose([transforms.ToTensor()])
if (t... |
class JumanjiToGymWrapper(gym.Env):
_gym_disable_underscore_compat: ClassVar[bool] = True
def __init__(self, env: Environment, seed: int=0, backend: Optional[str]=None):
self._env = env
self.metadata: Dict[(str, str)] = {}
self._key = jax.random.PRNGKey(seed)
self.backend = backe... |
def get_codegen(parser_type):
if (parser_type not in _codegen_dict):
if (parser_type == ParserTypeEnum.LATEX):
gen = CodeGenLatex()
elif (parser_type == ParserTypeEnum.NUMPY):
gen = CodeGenNumpy()
elif (parser_type == ParserTypeEnum.EIGEN):
gen = CodeGenEi... |
class ActorWatcher(NodeWatcher):
def __init__(self, job_name, namespace):
self._job_name = job_name
self._namespace = namespace
self._ray_client = RayClient.singleton_instance(job_name, namespace)
self.event_queue = RayEventQueue.singleton_instance()
def watch(self):
whil... |
def plot_attentions(attention: np.ndarray, src_seq, word: str, effective_doc_len):
(num_layer, num_heads, len_att) = attention.shape
trim_src_seq = src_seq[:len_att]
data_for_timestep = []
for layer_idx in range(num_layer):
one_layer_attn = attention[layer_idx]
row_data = []
for ... |
def generate(text_list, attention_list, latex_file, color='red', rescale_value=False):
assert (len(text_list) == len(attention_list))
if rescale_value:
attention_list = rescale(attention_list)
word_num = len(text_list)
text_list = clean_word(text_list)
with open(latex_file, 'w') as f:
... |
class LDMTextToImagePipeline(metaclass=DummyObject):
_backends = ['torch', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers'])
def from_pretrained(... |
class DynamicMemory(torch.nn.Module):
'Based on
def __init__(self, nb_slots=4, memory_size=300, bidirectional=False, **kwargs):
super(DynamicMemory, self).__init__()
self.cell = DynamicMemoryCell(nb_slots, memory_size)
self.bidirectional = bidirectional
def forward(self, inputs, len... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.