code stringlengths 101 5.91M |
|---|
class Encoder_Background(nn.Module):
def __init__(self, num_hiddens, num_residual_layers, num_residual_hiddens, ds_content, T, suf_method='avg_pool'):
super(Encoder_Background, self).__init__()
self._ds_m = ds_content
self._num_hiddens = num_hiddens
self._num_residual_layers = num_re... |
def get_launcher(distributed=False):
num_gpus = (min(2, get_gpu_count()) if distributed else 1)
master_port = os.environ.get('DS_TEST_PORT', DEFAULT_MASTER_PORT)
return f'deepspeed --num_nodes 1 --num_gpus {num_gpus} --master_port {master_port}'.split() |
def load(config):
cls_name = config.model.name
try:
cls = globals()[cls_name]
return cls(config)
except KeyError:
raise Exception('No such model: {}'.format(cls_name)) |
def get_lines_from_clustering(img_edges, mask_extract_contour, mask_plane, mask_number, output_directory, ksize=51):
if (not os.path.exists(output_directory)):
os.mkdir(output_directory)
edge_candidate_clusters = get_edge_candidate_clusters_from_mask(np.copy(img_edges), mask_extract_contour, mask_number... |
def split_corpus(path, shard_size):
with open(path, 'rb') as f:
if (shard_size <= 0):
(yield f.readlines())
else:
while True:
shard = list(islice(f, shard_size))
if (not shard):
break
(yield shard) |
class Dataset():
def __init__(self, root='/home/paul/datasets', dataset='market1501'):
self.dataset = dataset
self.root = root
def train_path(self):
if ((self.dataset == 'market1501') or (self.dataset == 'duke')):
return os.path.join(self.root, self.dataset, 'bounding_box_tra... |
def parse_hypothesis(hyp, char_list):
tokenid_as_list = list(map(int, hyp['yseq'][1:]))
token_as_list = [char_list[idx] for idx in tokenid_as_list]
score = float(hyp['score'])
tokenid = ' '.join([str(idx) for idx in tokenid_as_list])
token = ' '.join(token_as_list)
text = ''.join(token_as_list).... |
def rot_theta(th):
return np.array([[np.cos(th), 0, (- np.sin(th)), 0], [0, 1, 0, 0], [np.sin(th), 0, np.cos(th), 0], [0, 0, 0, 1]], dtype=np.float32) |
def build_lr(input_shape, output_size):
model = Sequential([Flatten(input_shape=input_shape), Dense(output_size), Activation('softmax')])
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model |
def train_one(save_path, config, log_file_dir, index, logfile_level, console_level, device):
if log_file_dir:
logging.basicConfig(filename=log_file_dir.replace('tensorboard', 'programlog'), level=logfile_level)
console = logging.StreamHandler()
console.setLevel(console_level)
logging... |
class BaseGraphMultiLayer(HybridBlock):
def __init__(self, out_units, aggregator_args_list, dropout_rate_list, graph_type='homo', in_units=None, first_embed_units=256, dense_connect=False, every_layer_l2_normalization=False, l2_normalization=False, output_inner_result=False, prefix=None, params=None):
super... |
def floordiv(dividend, divisor, rounding_mode='trunc'):
if _torch_version_div_indexing:
return torch.div(dividend, divisor, rounding_mode=rounding_mode)
else:
return (dividend // divisor) |
class CamembertForMaskedLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class CategoricalParametricDistribution(ParametricDistribution):
def __init__(self, num_actions: int):
postprocessor = IdentityBijector()
super().__init__(param_size=num_actions, postprocessor=postprocessor, event_ndims=0)
def create_dist(self, parameters: chex.Array) -> CategoricalDistribution:... |
class DeviceOptions(Enum):
AUTO = auto()
CPU = auto()
GPU = auto()
XPU = auto()
HPU = auto()
CUDA = auto() |
_task('sentence_ranking')
class SentenceRankingTask(FairseqTask):
def add_args(parser):
parser.add_argument('data', metavar='FILE', help='file prefix for data')
parser.add_argument('--num-classes', type=int, help='number of sentences to be ranked')
parser.add_argument('--init-token', type=in... |
_task('sentence_ranking')
class SentenceRankingTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('data', metavar='FILE', help='file prefix for data')
parser.add_argument('--num-classes', type=int, help='number of sentences to be ranked')
parser.add_argument('--init-token', t... |
class BlockDiagMat():
def __init__(self, A, B):
(self.A, self.B) = (A, B)
def shape(self):
mats = [self.A, self.B]
return (sum([m.shape[0] for m in mats]), sum([m.shape[1] for m in mats]))
def sqrt_dims(self):
mats = [self.A, self.B]
return sum([m.sqrt_dims for m in m... |
class Brightness(object):
def __call__(self, x, magnitude):
return ImageEnhance.Brightness(x).enhance((1 + (magnitude * random.choice([(- 1), 1])))) |
def test_build_global_dist(monkeypatch, tmpdir):
monkeypatch.chdir(MAIN_DIR)
monkeypatch.setenv('PYBIND11_GLOBAL_SDIST', '1')
subprocess.run([sys.executable, '-m', 'build', '--sdist', '--outdir', str(tmpdir)], check=True)
(sdist,) = tmpdir.visit('*.tar.gz')
with tarfile.open(str(sdist), 'r:gz') as t... |
def download_dataset_qm9(datadir, dataname, splits=None, calculate_thermo=True, exclude=True, cleanup=True):
gdb9dir = join(*[datadir, dataname])
os.makedirs(gdb9dir, exist_ok=True)
logging.info('Downloading and processing GDB9 dataset. Output will be in directory: {}.'.format(gdb9dir))
logging.info('Be... |
class P2SROManagerStub(object):
def __init__(self, channel):
self.CheckNumPlayers = channel.unary_unary('/P2SROManager/CheckNumPlayers', request_serializer=p2sro__manager__pb2.NumPlayers.SerializeToString, response_deserializer=p2sro__manager__pb2.Confirmation.FromString)
self.GetManagerMetaData = c... |
def is_tqdm_exists(callbacks):
for callback in callbacks:
if isinstance(callback, TqdmCallback):
return True
return False |
def optimizer_creator(model, config):
return optim.SGD(model.fc.parameters(), lr=config['lr'], momentum=config['momentum']) |
class refNMTModel(nn.Module):
def __init__(self, enc_embedding, dec_embedding, encoder_src, encoder_ref, decoder_ref, decoder, generator, fields):
super(refNMTModel, self).__init__()
self.enc_embedding = enc_embedding
self.dec_embedding = dec_embedding
self.encoder_src = encoder_src
... |
_config
def ilgsn_side_frozen():
cfg = {}
cfg['learner'] = {'model_kwargs': {'base_kwargs': {'perception_unit_kwargs': {'extra_kwargs': {'side_kwargs': {'eval_only': True}}}}}} |
def get_trainer_and_epoch_itr(epoch, epoch_size, num_updates, iterations_in_epoch):
tokens = torch.LongTensor(list(range(epoch_size))).view(1, (- 1))
tokens_ds = data.TokenBlockDataset(tokens, sizes=[tokens.size((- 1))], block_size=1, pad=0, eos=1, include_targets=False)
trainer = mock_trainer(epoch, num_up... |
def star_function(summary_pdf, name_string, abundances, cube, elements_to_trace, gas_reservoir, number_of_models_overplotted):
stars_at_end = 28.0
std = 2.0
dt = (cube['time'][1] - cube['time'][0])
probability = np.log(float(gaussian(cube['stars'][(- 1)], stars_at_end, std)))
if (number_of_models_ov... |
def produce_combinations(array):
arr_len = len(array)
for i in range(arr_len):
combination = (array[0:i] + array[(i + 1):arr_len])
(yield combination) |
def exponential_decay(step, rate, decay_steps, start_step=0):
return (rate ** (max(((step - start_step) + decay_steps), 0) // decay_steps)) |
class LinesMask(Mask):
def __init__(self, config):
super().__init__(config)
mask_file = config.get('filename')
if (mask_file is None):
raise MaskError("Missing argument 'filename' required by LinesMask")
try:
mask = Table.read(mask_file, names=('type', 'wave_m... |
_config
def srl_features():
uuid = 'habitat_alexnet_feature'
cfg = {}
cfg['learner'] = {'perception_network': 'BaseModelAutoEncoder', 'perception_network_kwargs': {'n_map_channels': 1, 'use_target': False}}
cfg['env'] = {'env_specific_kwargs': {'target_dim': 6}, 'transform_fn_pre_aggregation': "\n ... |
class _ProjectorHeadBase(nn.Module):
def __init__(self, *, input_dim: int, output_dim: int, head_type: str, normalize: bool, pool_name='adaptive_avg', spatial_size=(1, 1)):
super().__init__()
self._input_dim = input_dim
self._output_dim = output_dim
assert _check_head_type(head_type=... |
def _get_detector_cfg(fname):
config = _get_config_module(fname)
config.model.class_list = None
model = copy.deepcopy(config.model)
return model |
def get_index(num_domain=2):
index = []
for i in range(num_domain):
for j in range((i + 1), (num_domain + 1)):
index.append((i, j))
return index |
def test_transformer_decoder(num_layers=2, embed_dims=8, num_heads=2, feedforward_channels=8, num_key=10, num_query=5, batch_size=1):
module = TransformerDecoder(num_layers, embed_dims, num_heads, feedforward_channels)
query = torch.rand(num_query, batch_size, embed_dims)
memory = torch.rand(num_key, batch_... |
def librosa_exists():
try:
__import__('librosa')
except ImportError:
return False
else:
return True |
class TestEclipseRetrieval(unittest.TestCase):
def test_hd209458b(self):
def wfc3():
wavelengths = (1e-06 * np.array([1.1279, 1.1467, 1.1655, 1.1843, 1.2031, 1.2218, 1.2406, 1.2594, 1.2782, 1.2969, 1.3157, 1.3345, 1.3533, 1.3721, 1.3908, 1.4096, 1.4284, 1.4472, 1.466, 1.4848, 1.5035, 1.5223, 1.5... |
_pipeline_test
class TQAPipelineTests(unittest.TestCase):
model_mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING
_tensorflow_probability
_pandas
_tf
_torch
def test_small_model_tf(self):
model_id = 'lysandre/tiny-tapas-random-wtq'
model = TFAutoModelForTableQuestionAnswering.... |
class MLPAlgorithm(NNFit):
algorithm_name = 'Neural Network'
algorithm_short_name = 'Neural Network'
def __init__(self, params):
super(MLPAlgorithm, self).__init__(params)
logger.debug('MLPAlgorithm.__init__')
self.max_iters = 1
self.library_version = sklearn.__version__
... |
class VideoModelCoordLatentNL(nn.Module):
def __init__(self, opt):
super(VideoModelCoordLatentNL, self).__init__()
self.nr_boxes = opt.num_boxes
self.nr_actions = opt.num_classes
self.nr_frames = (opt.num_frames // 2)
self.img_feature_dim = opt.img_feature_dim
self.co... |
def get_git_hash(fallback='unknown', digits=None):
if ((digits is not None) and (not isinstance(digits, int))):
raise TypeError('digits must be None or an integer')
try:
out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
sha = out.strip().decode('ascii')
if (digits is not None)... |
def get_condensenet(num_layers, groups=4, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
if (num_layers == 74):
init_block_channels = 16
layers = [4, 6, 8, 10, 8]
growth_rates = [8, 16, 32, 64, 128]
else:
raise ValueError('Unsupported Co... |
class BeamNodeEz(BeamNode):
def __init__(self, prob: float, token_idx: int, prev: List, prev_score: List, min_len: int=10, finished: bool=False) -> None:
super().__init__(prob, token_idx, prev, prev_score, min_len, finished)
self.get_canonical_path()
assert self.all_token_idx
assert ... |
class Gym(object):
def __init__(self, model, train_data, test_data, dev_data, optimizers, logger, models_save_dir):
self.model = model
self.logger = logger
self.train_data = train_data
self.test_data = test_data
self.dev_data = dev_data
self.model_save_dir = models_sa... |
def train(model, train_config):
model = model
train_config = train_config
model_config = model.model_config
global_step_tensor = tf.Variable(0, trainable=False, name='global_step')
max_iterations = train_config.max_iterations
summary_interval = train_config.summary_interval
checkpoint_interv... |
def replace(input_dict, pop_key, new_key, new_value):
output_dict = deepcopy(input_dict)
output_dict.pop(pop_key)
output_dict[new_key] = new_value
return output_dict |
def drn_d_107(pretrained=False, **kwargs):
model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 2, 2], arch='D', **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['drn-d-107']))
return model |
def test_creation_from_zZ():
shape = (3, 1, 5)
z = torch.tensor(np.random.rand(*shape))
Z = (z + torch.tensor(np.random.rand(*shape)))
box = SigmoidBoxTensor.from_zZ(z, Z)
assert (box.z.shape == (3, 1, 5)) |
class Factory():
def __init__(self, latent_dist_name, *args, **kwargs):
self.output_dist = get_net_factory('distribution', latent_dist_name, *args, **kwargs)
assert (self.output_dist is not None), 'Cannot get the distribution'
def __call__(self, input_tensor, gt_tensor):
(input_tensor, i... |
def instantiate_multigpu_model_if_multiple_gpus(training_model):
if (len(cfg.gpus) > 1):
training_model = multi_gpu_model(training_model, len(cfg.gpus))
return training_model |
class InstallSignalHandlerHook(session_run_hook.SessionRunHook):
def __init__(self):
self._signal_fn = signal.getsignal(signal.SIGINT)
def before_run(self, run_context):
signal.signal(signal.SIGINT, signal.SIG_DFL)
def end(self, session):
signal.signal(signal.SIGINT, self._signal_fn) |
def main(opt):
translator = make_translator(opt, report_score=True)
translator.translate(opt.src_dir, opt.src, opt.tgt, opt.doc, opt.batch_size, opt.attn_debug) |
class ScaleLROnPlateau(NamedTuple):
step_size: jnp.ndarray
minimum_loss: jnp.ndarray
steps_without_reduction: jnp.ndarray
max_steps_without_reduction: jnp.ndarray
reduction_factor: jnp.ndarray |
_function('unsqueeze')
class AutogradUnsqueeze(AutogradFunction):
def forward(ctx, input, dim):
ctx.save_for_backward(dim)
return input.unsqueeze(dim)
def backward(ctx, grad_output):
(dim,) = ctx.saved_tensors
return grad_output.squeeze(dim) |
class CompressedStatsTrackerPeak(CompressedStatsTracker):
__slots__ = (CompressedStatsTracker.__slots__ + ('secondary_weight',))
def __init__(self, hg, chi, secondary_weight=0.001):
self.secondary_weight = secondary_weight
super().__init__(hg, chi)
def score(self):
return (math.log2(... |
def main(args, trainqpath, trainrpath, trainlpath, devqpath, devrpath, devlpath, testqpath, testrpath, testlpath, weight_decay=0.0001, lr=0.001):
with open(f'data/src-vocab.pkl', 'rb') as f:
srcv = pickle.load(f)
with open(f'data/tgt-vocab.pkl', 'rb') as f:
tgtv = pickle.load(f)
src_embed = ... |
def read_files(subdirs, module_file):
all_lines = []
for subdir in subdirs:
with open(os.path.join(DATA_SOURCE_DIR, subdir, module_file), 'r') as f:
lines = f.readlines()
print('... read {} lines from {}'.format(len(lines), subdir))
all_lines += lines
return all_lines |
class ShuffledResults(BaseResults):
def __init__(self, random_theta: np.ndarray):
shuffled_theta = np.stack([random_theta, flip_theta_series(random_theta)], axis=1)
super().__init__(theta=shuffled_theta, scores=None, skeletons=None) |
class XGBoostOptuna(object):
def __init__(self, task: str=BINARY_CLASSIFICATION, metric: str='accuracy', random_state=42):
self.task = task
self.seed = random_state
if (metric is None):
self.metric = default_task_metric[task]
else:
self.metric = metric
... |
class BackgroundGenerator(threading.Thread):
def __init__(self, generator, max_prefetch=1):
threading.Thread.__init__(self)
self.queue = Queue.Queue(max_prefetch)
self.generator = generator
self.daemon = True
self.start()
def run(self):
for item in self.generator:... |
def _parse_main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('decls_file')
parser.add_argument('dest_dir')
parser.add_argument('n_workers', type=int)
parser.add_argument('rec_limit', type=int)
parser.add_argument('depth_limit', type=int)
parser.add_argument('... |
def test(flags, num_episodes: int=10):
if (flags.xpid is None):
checkpointpath = './latest/model.tar'
else:
checkpointpath = os.path.expandvars(os.path.expanduser(('%s/%s/%s' % (flags.savedir, flags.xpid, 'model.tar'))))
gym_env = create_env(flags, flags.level_name, 1)
env = environment.... |
class PanopticEvaluator(object):
def __init__(self, ann_file, ann_folder, output_dir='panoptic_eval'):
self.gt_json = ann_file
self.gt_folder = ann_folder
if utils.is_main_process():
if (not os.path.exists(output_dir)):
os.mkdir(output_dir)
self.output_dir... |
def get_igcv3(width_scale, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
init_block_channels = 32
final_block_channels = 1280
layers = [1, 4, 6, 8, 6, 6, 1]
downsample = [0, 1, 1, 1, 0, 1, 0]
channels_per_layers = [16, 24, 32, 64, 96, 160, 320]
from fu... |
def _gen_mobilenet_v2(variant, channel_multiplier=1.0, depth_multiplier=1.0, fix_stem_head=False, pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_c16'], ['ir_r2_k3_s2_e6_c24'], ['ir_r3_k3_s2_e6_c32'], ['ir_r4_k3_s2_e6_c64'], ['ir_r3_k3_s1_e6_c96'], ['ir_r3_k3_s2_e6_c160'], ['ir_r1_k3_s1_e6_c320']]
model_... |
class Seq2SeqLoggingCallback(pl.Callback):
def on_batch_end(self, trainer, pl_module):
lrs = {f'lr_group_{i}': param['lr'] for (i, param) in enumerate(pl_module.trainer.optimizers[0].param_groups)}
pl_module.logger.log_metrics(lrs)
_zero_only
def _write_logs(self, trainer: pl.Trainer, pl_mod... |
class DropColumns(JuTransformer):
def __init__(self, apply_to: ColumnTypesLike, row_select_col_type: Optional[ColumnTypesLike]=None, row_select_vals: Optional[Union[(str, int, list, bool)]]=None):
super().__init__(apply_to=apply_to, needed_types=None, row_select_col_type=row_select_col_type, row_select_vals... |
def predict(X):
token_embeddings = list(map(get_embedding, X))
instr_chain = torch.stack(token_embeddings).unsqueeze(1)
(_, (final_state, _)) = model.instr_rnn(instr_chain, model.get_instr_init())
return model.linear(final_state.squeeze()).squeeze() |
class FSMTForConditionalGeneration(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def get_assassination_result(message: str, answer: str):
match_num = '\\d+'
player_id = []
player_id = re.findall(match_num, (str(message) + str(answer)))
player_id = int(player_id[(- 1)])
return player_id |
class ResultsManager():
_instance = None
log = logging.getLogger('MAIN.RESULTS')
multi_run_res = {}
def __new__(cls, _=None):
if (cls._instance is None):
cls._instance = super(ResultsManager, cls).__new__(cls)
return cls._instance
def __init__(self, metric=''):
if... |
def build_fake_yaml():
fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: x\n outputs: op_to_store\n device: cpu\n evaluation:\n accuracy:\n metric:\n topk: 1\n quantization:\n model_wis... |
class PromptExtractor(nn.Module):
def __init__(self):
super().__init__()
self._buffer_init = False
self.with_trainable_params = False
def init_buffer(self, clip_model):
self._buffer_init = True
def forward(self, noun_list: List[str], clip_model: nn.Module):
raise NotI... |
def levenshtein_similarity(string1, string2):
return (1 - (levenshtein(string1, string2) / float(max(len(string1), len(string2), 1.0)))) |
def randomRotation(imgs, label):
mode = Image.BICUBIC
if (random.random() > 0.8):
random_angle = np.random.randint((- 15), 15)
for i in range(len(imgs)):
imgs[i] = imgs[i].rotate(random_angle, mode)
label = label.rotate(random_angle, mode)
return (imgs, label) |
def test_space__volume(space: Space) -> None:
volume = space.volume()
chex.assert_type(volume, float)
assert (volume == 1.0) |
def setup_seed(seed):
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False |
class Checkpointer(object):
def __init__(self, model, optimizer=None, scheduler=None, save_dir='', ckpt_path=None, save_to_disk=None, logger=None):
self.model = model
self.optimizer = optimizer
self.scheduler = scheduler
self.pretrained_path = ckpt_path
self.finetune = False
... |
def main():
if (not os.path.isdir('./images')):
os.makedirs('./images')
for image_file in glob('valid/*.png'):
print(image_file[6:])
input = image_file
output = (('images/' + image_file[6:(- 4)]) + '.npz')
num_filters = 128
checkpoint_dir = 'models'
compre... |
class SiameseBaseModel(EztorchBaseModule, ABC):
def __init__(self, trunk: DictConfig, optimizer: DictConfig, projector: Optional[DictConfig]=None, predictor: Optional[DictConfig]=None, train_transform: Optional[DictConfig]=None, val_transform: Optional[DictConfig]=None, test_transform: Optional[DictConfig]=None, no... |
(version='2.0')
class SequentialSampler(Sampler):
def __init__(self, dataset, distributed):
self.whole_dataset = dataset
self.distributed = distributed
def __iter__(self):
self.process_rank = 0
self.process_size = 1
if self.distributed:
import horovod.tensorfl... |
def train_baseline(mlp, data, train_batches, test_batches, num_epochs, learning_rate_mlp, device_id=0):
optim = OPTIMIZER(mlp.parameters(), lr=learning_rate_mlp)
criterion = nn.MSELoss()
if torch.cuda.is_available():
criterion = criterion.cuda(device_id)
for epoch in range(num_epochs):
t... |
_torch
class BenchmarkTest(unittest.TestCase):
def check_results_dict_not_empty(self, results):
for model_result in results.values():
for (batch_size, sequence_length) in zip(model_result['bs'], model_result['ss']):
result = model_result['result'][batch_size][sequence_length]
... |
class uniform(BaseInitializer):
def __init__(self, a=(- 0.0), b=1.0):
super(uniform, self).__init__(a=a, b=b)
self.a = a
self.b = b |
class Seq2SeqEncoder(_EncoderBase):
def get_input_dim(self) -> int:
raise NotImplementedError
def get_output_dim(self) -> int:
raise NotImplementedError
def is_bidirectional(self) -> bool:
raise NotImplementedError |
class ConcatFuse(HybridBlock):
def __init__(self, channels=64):
super(ConcatFuse, self).__init__()
self.channels = channels
self.post = nn.HybridSequential(prefix='post')
self.post.add(nn.Conv2D(channels, kernel_size=3, strides=1, padding=1, dilation=1))
self.post.add(nn.Batc... |
def has_key(x, y):
if hasattr(x, 'has_key'):
return x.has_key(y)
else:
return (y in x) |
class FlaxUpsample2D(nn.Module):
in_channels: int
dtype: jnp.dtype = jnp.float32
def setup(self):
self.conv = nn.Conv(self.in_channels, kernel_size=(3, 3), strides=(1, 1), padding=((1, 1), (1, 1)), dtype=self.dtype)
def __call__(self, hidden_states):
(batch, height, width, channels) = hi... |
def ema_loss(x, running_mean, alpha):
t_exp = torch.exp((torch.logsumexp(x, 0) - math.log(x.shape[0]))).detach()
if (running_mean == 0):
running_mean = t_exp
else:
running_mean = ema(t_exp, alpha, running_mean.item())
t_log = EMALoss.apply(x, running_mean)
return (t_log, running_mean... |
def make_predictions(df, model, window):
predictions_list = []
for i in range(len(df)):
row = df.iloc[i]
cur_preds = get_auto_reg_predictions(model, row, window)
predictions_list.append(cur_preds)
df['predicted_deaths'] = predictions_list
return df |
def catx_network_with_dropout_extras() -> Type[CATXHaikuNetwork]:
return CatxNetworkWithDropoutExtras |
class RLAv1_ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(RLAv1_ResNet, self).__init__()
if (norm_layer is None):
... |
def test_Eta_e(white_noise):
a = FeatureSpace(featureList=['Eta_e'])
a = a.calculateFeature(white_noise)
assert ((a.result(method='array') >= 1.9) and (a.result(method='array') <= 2.1)) |
def parse_args():
parser = argparse.ArgumentParser(description='Parse args for training')
parser.add_argument('--script', type=str, help='training script name')
parser.add_argument('--config', type=str, default='baseline', help='yaml configure file name')
parser.add_argument('--save_dir', type=str, help... |
def test_digits_cosine_stochastic():
model = FacilityLocationSelection(100, 'cosine', optimizer='stochastic', random_state=0)
model.fit(X_digits)
assert_array_equal(model.ranking, digits_cosine_stochastic_ranking)
assert_array_almost_equal(model.gains, digits_cosine_stochastic_gains, 4)
assert_array... |
_incremental_state
class FairseqIncrementalDecoder(FairseqDecoder):
def __init__(self, dictionary):
super().__init__(dictionary)
def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs):
raise NotImplementedError
def extract_features(self, prev_output_tokens,... |
def boolean_string(string):
low_string = string.lower()
if (low_string not in {'false', 'true'}):
invalidInputError(False, 'Not a valid boolean string')
return (low_string == 'true') |
def read_heterograph_pyg(raw_dir, add_inverse_edge=False, additional_node_files=[], additional_edge_files=[], binary=False):
if binary:
graph_list = read_binary_heterograph_raw(raw_dir, add_inverse_edge)
else:
graph_list = read_csv_heterograph_raw(raw_dir, add_inverse_edge, additional_node_files... |
def file_len(fname):
with open(fname, 'rb') as f:
for (i, l) in enumerate(f):
pass
return (i + 1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.