code stringlengths 101 5.91M |
|---|
class ResnetGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, norm_layer=InstanceNorm2d, use_dropout=False, n_blocks=9, gpu_ids=[], padding_type='reflect'):
assert (n_blocks >= 0)
super(ResnetGenerator, self).__init__()
self.gpu_ids = gpu_ids
model = [nn.Reflectio... |
class LearningSchedule(object):
def __init__(self, start_schedule, schedule_timesteps, initial_p=1.0, final_p=0.05):
self.initial_p = initial_p
self.final_p = final_p
self.schedule_timesteps = schedule_timesteps
self.start_schedule = start_schedule
def value(self, t):
fra... |
class BasicType(ValueType):
def __init__(self, cur_type):
self.type = cur_type
def to_string(self, value):
return str(value)
def from_string(self, value):
return self.type(value) |
def patch_graph(graph):
for u in graph.nodes():
graph.nodes[u]['label'] = graph.nodes[u]['label'].split('-')[0]
return graph |
class AggregateTransformer(TransformerMixin):
def __init__(self, case_id_col, cat_cols, num_cols, boolean=False, fillna=True):
self.case_id_col = case_id_col
self.cat_cols = cat_cols
self.num_cols = num_cols
self.boolean = boolean
self.fillna = fillna
self.columns = N... |
class TFCamembertForCausalLM(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class MgpstrModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class ChunkTabPreprocessor(TabPreprocessor):
('with_attention', 'for_transformer')
('cat_embed_cols', 'embed_cols')
('scale', 'scale_cont_cols')
('cols_and_bins', 'quantization_setup')
def __init__(self, n_chunks: int, cat_embed_cols: Optional[Union[(List[str], List[Tuple[(str, int)]])]]=None, conti... |
class Actor(nn.Module):
def _distribution(self, obs):
raise NotImplementedError
def _log_prob_from_distribution(self, pi, act):
raise NotImplementedError
def forward(self, obs, act=None):
pi = self._distribution(obs)
logp_a = None
if (act is not None):
log... |
class MaskedLinear(nn.Linear):
def __init__(self, in_features: int, out_features: int, bias: bool=True, mask_init: str='constant', mask_scale: float=0.0, pruning_method: str='topK'):
super(MaskedLinear, self).__init__(in_features=in_features, out_features=out_features, bias=bias)
assert (pruning_met... |
def _load_model(arch_type, backbone, pretrained, progress, num_classes, aux_loss, **kwargs):
if pretrained:
aux_loss = True
kwargs['pretrained_backbone'] = False
model = _segm_model(arch_type, backbone, num_classes, aux_loss, **kwargs)
if pretrained:
_load_weights(model, arch_type, b... |
_cache()
def statcast_pitcher_active_spin(year: int, minP: int=250, _type: str='spin-based') -> pd.DataFrame:
url = f'
res = requests.get(url, timeout=None).content
if (res and ('<html' in res.decode('utf-8'))):
if (_type == 'spin-based'):
warnings.warn(f'Could not get active spin result... |
def setup_agent(cfg: DictConfig, env: Environment) -> Agent:
agent: Agent
if (cfg.agent == 'random'):
random_policy = _setup_random_policy(cfg, env)
agent = RandomAgent(env=env, n_steps=cfg.env.training.n_steps, total_batch_size=cfg.env.training.total_batch_size, random_policy=random_policy)
... |
def test_force_in_10m13kms2():
(vofid, rofid) = (200.0, 8.0)
assert (numpy.fabs((((4.0 * conversion.force_in_10m13kms2(vofid, rofid)) / conversion.force_in_10m13kms2((2.0 * vofid), rofid)) - 1.0)) < (10.0 ** (- 10.0))), 'force_in_10m13kms2 did not work as expected'
assert (numpy.fabs((((0.5 * conversion.for... |
class AttributeMonitor(BaseMonitor):
def __init__(self, attribute_name: str, pre_forward: bool, net: nn.Module, instance: (Any or tuple)=None, function_on_attribute: Callable=(lambda x: x)):
super().__init__()
self.attribute_name = attribute_name
self.function_on_attribute = function_on_attr... |
def create_inception_v3_two_path_mixed_layer(x, id, name='', channel_axis=3, bottleneck_compression=0.5, compression=0.655, has_batch_norm=False, kType=0):
if (name == ''):
name = 'mixed'
interleaved = cai.layers.InterleaveChannels(2, name=(name + '_interleaved'))(x)
a = create_inception_path(last_t... |
class TestLoadCheckpoint(unittest.TestCase):
def setUp(self):
self.args_mock = MagicMock()
self.args_mock.optimizer_overrides = '{}'
self.args_mock.reset_dataloader = False
self.args_mock.reset_meters = False
self.args_mock.reset_optimizer = False
self.patches = {'os.... |
class TestRollout():
def setup_method(self):
self.env = GarageEnv(DummyBoxEnv(obs_dim=(4, 4), action_dim=(2, 2)))
self.policy = DummyPolicy(self.env.spec)
def test_max_path_length(self):
path = utils.rollout(self.env, self.policy, max_path_length=3)
assert (path['observations'].s... |
def get_Future3D_text_annotation(cfg: DictConfig, id: str) -> dict:
form = 'future3d-STMCS'
with open(cfg.data.future3d_json, 'r') as f:
model_info = json.load(f)
id2annot = {el['model_id']: [el['style'], el['theme'], el['material'], el['category'], el['super-category']] for el in model_info}
te... |
class FeatureRectifyModule(nn.Module):
def __init__(self, dim, reduction=1, lambda_c=0.5, lambda_s=0.5):
super(FeatureRectifyModule, self).__init__()
self.lambda_c = lambda_c
self.lambda_s = lambda_s
self.channel_weights = ChannelWeights(dim=dim, reduction=reduction)
self.spa... |
class Cropping1D(ZooKerasLayer):
def __init__(self, cropping=(1, 1), input_shape=None, **kwargs):
super(Cropping1D, self).__init__(None, cropping, (list(input_shape) if input_shape else None), **kwargs) |
class XFUN(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [XFUNConfig(name=f'xfun.{lang}', lang=lang) for lang in _LANG]
tokenizer = AutoTokenizer.from_pretrained('xlm-roberta-base')
def _info(self):
return datasets.DatasetInfo(features=datasets.Features({'id': datasets.Value('string'), 'input_i... |
class GenDiffPOBase(GenFOBase):
def gen_model(self):
if (not hasattr(self, '_gen_model')):
torch.manual_seed(0)
self._gen_model = self.model_class(n_obs_neurons=self.n_obs_neurons, n_hidden_neurons=self.n_hidden_neurons, connection_tensor=self.connection_tensor, n_inducing_points=sel... |
class RepeatedContinuousStratifiedGroupKFold(_RepeatedSplits):
def __init__(self, n_bins, method='binning', n_splits: int=5, n_repeats: int=10, random_state: Optional[Union[(int, RandomState)]]=None):
super().__init__(ContinuousStratifiedGroupKFold, n_bins=n_bins, method=method, n_repeats=n_repeats, random_... |
class FairseqDataset(torch.utils.data.Dataset, EpochListening):
def __getitem__(self, index):
raise NotImplementedError
def __len__(self):
raise NotImplementedError
def collater(self, samples):
raise NotImplementedError
def num_tokens(self, index):
raise NotImplementedErr... |
class Self_Attn(nn.Module):
def __init__(self, in_dim, activation):
super(Self_Attn, self).__init__()
self.chanel_in = in_dim
self.activation = activation
self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=(in_dim // 8), kernel_size=1)
self.key_conv = nn.Conv2d(in_c... |
def do_training(tr: Training, callback: tf.keras.callbacks.Callback, verbose=0):
tr.model_name = ((tr.dataset_name + '_') + str(tr.hyperparameters))
tr.checkpoint_path = os.path.join(models_dir, tr.model_name, 'checkpoints')
tr.log_path = os.path.join(models_dir, tr.model_name, 'logs')
tr.custom_objects... |
class XceptionAligned(nn.Module):
def __init__(self, block_cfg, num_classes=1000, in_chans=3, output_stride=32, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, drop_rate=0.0, global_pool='avg'):
super(XceptionAligned, self).__init__()
self.num_classes = num_classes
self.drop_rate = drop_rate
... |
def main(args):
ray.init(num_cpus=args.num_cpus, memory=(1800 * (1024 ** 2)), object_store_memory=(300 * (1024 ** 2)))
def train_reg(config, reporter):
sys.path.append(BASE_DIR)
from experiments.data_sim import provide_data
(data_train, data_valid, _) = provide_data(dataset=args.dataset,... |
class GAPNormalizer(object):
def __init__(self, vocab_file):
self.vocab_file = vocab_file
self.init_vocabulary()
self.letters = set((string.ascii_letters + '*'))
def init_vocabulary(self):
self.vocabulary = []
with open(self.vocab_file) as f:
for line in f:
... |
def store_in_memory(mmemory, addr, value):
for i in range((addr + 1), (addr + 32)):
if (i in mmemory):
if (not is_undefined(mmemory[i])):
if is_undefined(value):
mmemory[i]['type'] = 'undefined'
continue
obytes = (i - addr)
... |
def test_transformer_head_loss():
s = 256
img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3), 'batch_input_shape': (s, s)}]
train_cfg = dict(assigner=dict(type='HungarianAssigner', cls_cost=dict(type='ClassificationCost', weight=1.0), reg_cost=dict(type='BBoxL1Cost', weight=5.0)... |
def ensure_valid_input(model, tokens, input_names):
print('Ensuring inputs are in correct order')
model_args_name = model.forward.__code__.co_varnames
(model_args, ordered_input_names) = ([], [])
for arg_name in model_args_name[1:]:
if (arg_name in input_names):
ordered_input_names.a... |
class XLMRobertaTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
def __init__(self, vocab_file, bos_token='<... |
def test_action_space():
space = ActionSpace({'move': gym.spaces.Dict({'position': gym.spaces.Discrete(2), 'velocity': gym.spaces.Discrete(3)}), 'move_forward': EmptySpace()})
assert space.contains(space.sample())
assert space.contains({'action': 'move', 'action_args': {'position': 0, 'velocity': 1}})
a... |
def get_dep_adj(passage, tag):
map_passage = {}
word_passage = passage.split()
tags = tag.split()
assert (len(word_passage) == len(tags))
for (position, word) in enumerate(word_passage):
map_passage[position] = word
adj = np.zeros([len(word_passage), len(word_passage)])
str_passage =... |
def fg_mask2d(img_2d, thresh):
mask_map = np.float32((img_2d > thresh))
def getLargestCC(segmentation):
labels = label(segmentation)
assert (labels.max() != 0)
largestCC = (labels == (np.argmax(np.bincount(labels.flat)[1:]) + 1))
return largestCC
if (mask_map.max() < 0.999):
... |
def main():
env = MineCraft()
env.set_render(True)
random_play = False
minecraft_global_setup()
obs = env.reset()
if random_play:
action = np.random.randint(0, env.action_space.n)
else:
input_key = cv2.waitKey(0)
action = env.key_map_to_action[input_key]
while Tru... |
def get_existing_filenames(path_to_file):
f = open(path_to_file, 'r')
filenames = []
for line in f:
line = line.replace('\n', '')
filename = extract_filename_from_url(line)
if (not filename):
print('>>>get_existing_filenames: Empty line extracted.')
continue
... |
def write_results(filename, results, data_type):
if (data_type == 'mot'):
save_format = '{frame},{id},{x1},{y1},{w},{h},1,-1,-1,-1\n'
elif (data_type == 'kitti'):
save_format = '{frame} {id} pedestrian 0 0 -10 {x1} {y1} {x2} {y2} -10 -10 -10 -1000 -1000 -1000 -10\n'
else:
raise Value... |
def gptneox_sample_repetition_penalty(ctx: gptneox_context_p, candidates, last_tokens_data, last_tokens_size: c_int, penalty: c_float):
return _lib.gptneox_sample_repetition_penalty(ctx, candidates, last_tokens_data, last_tokens_size, penalty) |
def train_user_pred(optims, generator, bsize, embed_dim, recom_length, trainSample, validSample, testSample, mode='generator with rec', inner_val_acc_best=None, inner_val_preck_best=None, inner_val_rewd_best=None, inner_loss_best=None, only_rewards=False, n_epochs=10):
outputdir = 'model_output'
outputmodelname... |
class RuleTrimmer():
def __init__(self, quantitative_dataframe):
self.__dataframe = quantitative_dataframe
def transform(self, rules):
copied_rules = [rule.copy() for rule in rules]
trimmed = [self.__trim(rule) for rule in copied_rules]
return trimmed
def __trim(self, rule):
... |
def squared_euclidean_distance(x: Tensor, y: Tensor) -> Tensor:
x_norm = (x ** 2).sum(1).view((- 1), 1)
y_t = torch.transpose(y, 0, 1)
y_norm = (y ** 2).sum(1).view(1, (- 1))
dist = ((x_norm + y_norm) - (2.0 * torch.mm(x, y_t)))
return torch.clamp(dist, 0.0, np.inf) |
_config
def model_lifelong_independent_resnet_taskonomy():
cfg = {'learner': {'model': 'LifelongSidetuneNetwork', 'model_kwargs': {'side_class': 'TaskonomyEncoder', 'side_kwargs': {'eval_only': False, 'normalize_outputs': False}, 'side_weights_path': '/mnt/models/curvature_encoder.dat', 'normalize_pre_transfer': Tr... |
class XLNetTokenizer():
def __init__(self, *args, **kwargs):
requires_sentencepiece(self)
def from_pretrained(self, *args, **kwargs):
requires_sentencepiece(self) |
def get_dataloaders(config: Namespace, train: bool=True) -> Tuple[(DataLoader, DataLoader)]:
if train:
config.return_volumes = False
if (config.percentage != 100):
config.return_volumes = True
slices = get_camcan_slices(config)
if (config.percentage != 100):
i... |
class Arcface(nn.Module):
def __init__(self, in_features, out_features, s=30.0, m=0.3, easy_margin=False, ls_eps=0.0):
super(Arcface, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.m = m
self.ls_eps = ls_eps
se... |
def get_arguments():
parser = ArgumentParser(description='nilm-project')
parser.add_argument('--settings')
parser.add_argument('--appliance')
parser.add_argument('--path')
parser.add_argument('--train', action='store_true')
parser.add_argument('--tune', action='store_true')
parser.add_argume... |
class TensorflowSavedModelModel(TensorflowBaseModel):
def __init__(self, model, **kwargs):
super(TensorflowSavedModelModel, self).__init__(model, **kwargs)
self._auto_trackable = None
def get_all_weight_names(self):
import tensorflow as tf
names = []
for (index, layer) in... |
def get_possible_iterations(logdir, population_i):
possible_iterations = []
checkpoint_path_search_prefix = os.path.join(logdir, '{}{}{}-{}'.format(CHECKPOINT_PATH_PREFIX, CHECKPOINT_PATH_POPULATION_PREFIX, population_i, CHECKPOINT_PATH_ITERATION_PREFIX))
for file in glob.glob((checkpoint_path_search_prefix... |
def test_resnet_backbone():
with pytest.raises(KeyError):
ResNet(20)
with pytest.raises(AssertionError):
ResNet(50, num_stages=0)
with pytest.raises(AssertionError):
dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False)
ResNet(50, dcn=dcn, stage_with_dcn=(True,))
... |
def make_data_creator(refs):
def data_creator(config, batch_size):
return refs
return data_creator |
def read_jsonl(path: str, key: str=None):
data = []
with open(os.path.expanduser(path)) as f:
for line in f:
if (not line):
continue
data.append(json.loads(line))
if (key is not None):
data.sort(key=(lambda x: x[key]))
data = {item[key]: item f... |
def get_real_epoch_or_iter(config):
cfg = mmcv.Config.fromfile(('./configs/' + config))
if (cfg.runner.type == 'EpochBasedRunner'):
epoch = cfg.runner.max_epochs
if (cfg.data.train.type == 'RepeatDataset'):
epoch *= cfg.data.train.times
return epoch
else:
return c... |
def fewShot(paired_sample, n_ways, n_shots, n_unlabel, cnt_query, coco=False, cfg=None, labels=None):
cumsum_idx = np.cumsum(([0] + [((n_shots + n_unlabel) + x) for x in cnt_query]))
class_ids = [paired_sample[cumsum_idx[i]]['basic_class_id'] for i in range(n_ways)]
support_images = [[paired_sample[(cumsum_... |
class ArithExpNode():
def __init__(self, type=None, value=None):
self.type = type
self.value = value
self.opNum = 0
self.cntDiv = 0
self.ArgSet = (0 if (type == 'CONSTANT') else (1 << value))
self.cntMinMax = 0
if (self.type == 'CONSTANT'):
self.cn... |
class SupConResNet(nn.Module):
def __init__(self, name='resnet50', head='mlp', feat_dim=128):
super(SupConResNet, self).__init__()
(model_fun, dim_in) = model_dict[name]
self.encoder = model_fun()
if (head == 'linear'):
self.head = nn.Linear(dim_in, feat_dim)
elif... |
def _test():
import torch
pretrained = False
models = [senet16, senet28, senet40, senet52, senet103, senet154]
for model in models:
net = model(pretrained=pretrained)
net.eval()
weight_count = _calc_width(net)
print('m={}, {}'.format(model.__name__, weight_count))
... |
def proxylessnas_gpu(**kwargs):
return get_proxylessnas(version='gpu', model_name='proxylessnas_gpu', **kwargs) |
_task('speech_to_text')
class SpeechToTextTask(LegacyFairseqTask):
def add_args(cls, parser):
parser.add_argument('data', help='manifest root path')
parser.add_argument('--config-yaml', type=str, default='config.yaml', help='Configuration YAML filename (under manifest root)')
parser.add_argu... |
class DetectionCrop(FeatureTransformer):
def __init__(self, roi_key, normalized=True, bigdl_type='float'):
super(DetectionCrop, self).__init__(bigdl_type, roi_key, normalized) |
def load_outcome_not_last_column_dataset():
data = [['a', 0, 10], ['a', 0, 10000], ['a', 0, 14], ['a', 0, 10], ['a', 0, 10]]
return pd.DataFrame(data, columns=['Categorical', 'Outcome', 'Numerical']) |
class ExperimentRunner(tune.Trainable):
def _setup(self, variant):
set_seed(variant['run_params']['seed'])
self._variant = variant
gpu_options = tf.GPUOptions(allow_growth=True)
session = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
tf.keras.backend.set_session(... |
class ProjectedAdditiveExactGPModel(ExactGPModel):
def __init__(self, train_x, train_y, likelihood, kernel):
if isinstance(kernel, gpytorch.kernels.ScaleKernel):
if (not isinstance(kernel.base_kernel, GeneralizedProjectionKernel)):
raise ValueError('Not an projected additive kern... |
def _grouper(iterable: Iterable[Any], n: int, fillvalue=None) -> Iterator[Tuple[Any]]:
it = iter(iterable)
while True:
values = []
for _ in range(n):
try:
value = next(it)
except StopIteration:
values.extend(([fillvalue] * (n - len(values))... |
_torch
_retrieval
_sentencepiece
class RagTestMixin():
all_model_classes = ((RagModel, RagTokenForGeneration, RagSequenceForGeneration) if (is_torch_available() and is_datasets_available() and is_faiss_available()) else ())
retrieval_vector_size = 32
n_docs = 3
max_combined_length = 16
def setUp(sel... |
def test_simple():
assert (_replace_reactive_atoms('$foo $bar') == 'foo bar')
assert (_replace_reactive_atoms('$foo bar $baz42') == 'foo bar baz42')
assert (_replace_reactive_atoms('$foo $42bar $_baz42') == 'foo 42bar _baz42') |
def test_unregularized_methods(data):
(X, Y, _) = data
latent_dims = 2
methods = [rCCA(latent_dimensions=latent_dims), CCA(latent_dimensions=latent_dims), KCCA(latent_dimensions=latent_dims), PCACCA(latent_dimensions=latent_dims), TCCA(latent_dimensions=latent_dims), KTCCA(latent_dimensions=latent_dims)]
... |
class ArgDef():
def __init__(self):
self.name: str = ''
self.index: int = (- 1)
self.is_optional: bool = False
self.type: set = set()
self.default_value: str = ''
self.description: str = ''
self.case: Argument = None
self.record = {}
self.ignor... |
def get_model_fwk_name(model):
def _is_onnxruntime(model):
from importlib.util import find_spec
try:
so = ort.SessionOptions()
if ((sys.version_info < (3, 11)) and find_spec('onnxruntime_extensions')):
from onnxruntime_extensions import get_library_path
... |
def acquireLock(lock_f='/tmp/lockfile.LOCK'):
import fcntl
locked_file_descriptor = open(lock_f, 'w+')
fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX)
return locked_file_descriptor |
class KernelConv2D(nn.Module):
def __init__(self, kernel_size):
super(KernelConv2D, self).__init__()
assert ((kernel_size % 2) == 1)
self.kernel_size = kernel_size
self.pad = torch.nn.ReplicationPad2d([((kernel_size - 1) // 2), ((kernel_size - 1) // 2), ((kernel_size - 1) // 2), ((ke... |
class MaskedLMOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None |
_registry(operator_type='InnerProduct')
_registry(operator_type='InnerProductGraph')
class InnerProduct(Operator):
def __init__(self):
super().__init__() |
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) |
def fused_leaky_relu(input, bias, negative_slope=0.2, scale=(2 ** 0.5)):
rest_dim = ([1] * ((input.ndim - bias.ndim) - 1))
input = input.cuda()
return (F.leaky_relu((input + bias.view(1, bias.shape[0], *rest_dim)), negative_slope=negative_slope) * scale) |
def test_fit_weighted_2ds(X, w):
X = [x for x in torch.tensor((numpy.array(X) + 1))]
d = [Exponential([2.1, 0.3, 0.1]), Exponential([1.5, 3.1, 2.2])]
model = DenseHMM(distributions=d, edges=[[0.1, 0.8], [0.3, 0.6]], starts=[0.2, 0.8], ends=[0.1, 0.1], max_iter=1)
model.fit(X, sample_weight=w)
d1 = m... |
class Beam(object):
def __init__(self, beam_size, min_time_step, max_time_step, hypotheses, device):
self.beam_size = beam_size
self.min_time_step = min_time_step
self.max_time_step = max_time_step
self.completed_hypotheses = []
self.steps = 0
self.hypotheses = hypoth... |
class FlaxBartDecoderPreTrainedModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def to_json(o):
if isinstance(o, str):
return o
elif isinstance(o, type):
return o.__name__
elif isinstance(o, (list, tuple)):
return [to_json(x) for x in o]
elif isinstance(o, dict):
return {to_json(k): to_json(v) for (k, v) in o.items()}
else:
return o |
class DIML_Indoor(Dataset):
def __init__(self, data_dir_root):
import glob
self.image_files = glob.glob(os.path.join(data_dir_root, 'LR', '*', 'color', '*.png'))
self.depth_files = [r.replace('color', 'depth_filled').replace('_c.png', '_depth_filled.png') for r in self.image_files]
s... |
def load_pretrained_component_from_model(component: Union[(FairseqEncoder, FairseqDecoder)], checkpoint: str):
if (not PathManager.exists(checkpoint)):
raise IOError('Model file not found: {}'.format(checkpoint))
state = load_checkpoint_to_cpu(checkpoint)
if isinstance(component, FairseqEncoder):
... |
class WarmupLinearDecaySchedule():
def __init__(self, warmup_steps, total_steps, learning_rate, min_lr=0.0):
self.warmup_steps = warmup_steps
self.total_steps = total_steps
self.initial_learning_rate = learning_rate
self.min_lr = min_lr
self.decay_steps = max(1.0, (self.total... |
def get_dataset(root_dir, use_line_art=True, include_subfolders=False):
return DatasetFromFolder(root_dir, use_line_art, include_subfolders=include_subfolders) |
class InfBallBounded(DualObject):
def __init__(self, X, epsilon, l=0, u=1):
super(InfBallBounded, self).__init__()
self.epsilon = epsilon
self.l = (X - epsilon).clamp(min=l).view(X.size(0), 1, (- 1))
self.u = (X + epsilon).clamp(max=u).view(X.size(0), 1, (- 1))
n = X[0].numel... |
class Blip2VisionModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class SinkhornDivergence(OptimalTransport):
thre = 0.001
def __init__(self, dist_metric='cosine', eps=0.01, max_iter=5, bp_to_sinkhorn=False):
super().__init__()
self.dist_metric = dist_metric
self.eps = eps
self.max_iter = max_iter
self.bp_to_sinkhorn = bp_to_sinkhorn
... |
def load_person_names(path):
data = []
with open(path, 'r', encoding='utf8') as f:
for line in f:
data.append(line.strip().replace(' ', '_'))
return set(data) |
class SkNetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.global_pool
def get_stages(self):
ret... |
class FacesHQTrain(Dataset):
def __init__(self, size, keys=None, crop_size=None, coord=False):
d1 = CelebAHQTrain(size=size, keys=keys)
d2 = FFHQTrain(size=size, keys=keys)
self.data = ConcatDatasetWithIndex([d1, d2])
self.coord = coord
if (crop_size is not None):
... |
def generate_benchmark_table():
res_root = '../eval/EvaluationResults_ablation_script_new_3'
data_lst = ['CHAMELEON', 'CAMO', 'COD10K']
model_lst = ['-Network_Res2Net_GRA_NCD_GSize_32_32_32']
for i in range(len(model_lst)):
for j in range(len(data_lst)):
txt_path = os.path.join(res_r... |
def test(model):
model.eval()
loss = 0
correct = 0
(pred_list, label_list) = ([], [])
with torch.no_grad():
for (data, label) in test_loader:
(data, label) = (data.cuda(), label.cuda())
label = (label - 1)
out = model_TST(data, label)
pred = ou... |
def color_transfer(source, target, clip=True, preserve_paper=True, mask=None):
source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype('float32')
target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype('float32')
(lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source, mask)
(lMea... |
class ConcatDataset(Dataset):
def __init__(self, datasets):
super(ConcatDataset, self).__init__()
self.datasets = list(datasets)
assert (len(datasets) > 0), 'datasets should not be an empty iterable'
self.cum_sizes = np.cumsum([len(x) for x in self.datasets])
def __len__(self):
... |
def set_param_grad_off(module):
for param in module.parameters():
param.requires_grad = False |
class Test_lpoly(unittest.TestCase):
def test_simple_unitary_from_angles1(self):
phiset = [0]
ualg = LPoly.LAlg.unitary_from_angles(phiset)
print(f'For phiset={phiset}, U={ualg}')
print(f'diagonal poly = {ualg.IPoly}')
assert (ualg.IPoly == LPoly.LPoly([1]))
def test_simp... |
class NoisyTopkErrorRate(TopkErrorRate):
def __init__(self, model, noise=None, k=1):
super().__init__(model, k)
if (not noise):
noise = (lambda x: x)
self.noise = noise
def update(self, inputs, labels):
noisy = self.noise(inputs)
return super().update(noisy, l... |
def inf_generator(iterable):
iterator = iterable.__iter__()
while True:
try:
(yield iterator.__next__())
except StopIteration:
iterator = iterable.__iter__() |
def trans(args):
set_deterministic_pytorch(args)
(model, train_args) = load_trained_model(args.model)
assert isinstance(model, STInterface)
model.trans_args = args
if (args.ngpu == 1):
gpu_id = list(range(args.ngpu))
logging.info(('gpu id: ' + str(gpu_id)))
model.cuda()
w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.