code stringlengths 101 5.91M |
|---|
def get_mean_period(frequencies, p_floor, p_ceil, max_p_factor):
cumsum = 0
counter = 0
for freq in frequencies:
if validate_frequencies([freq], p_floor, p_ceil, max_p_factor):
cumsum += (1 / freq)
counter += 1
mean_period = ((cumsum / counter) if (counter != 0) else None... |
class Timer():
def __init__(self, name):
self.name = name
def __enter__(self):
self.begin = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.elapsed = (self.end - self.begin)
self.elapsedH = time.gmtime(self.elapsed)
print... |
class ConfiguredInferenceNet(nn.Module):
def __init__(self, vectorizer, article_encoder, intervention_encoder, comparator_encoder, outcome_encoder, cls_layer):
super(ConfiguredInferenceNet, self).__init__()
self.vectorizer = vectorizer
self.article_encoder = article_encoder
self.inte... |
class SparseStage(nn.Module):
def __init__(self, in_channels, channels_per_stage, growth_rate, dropout_rate, do_transition):
super(SparseStage, self).__init__()
self.do_transition = do_transition
if self.do_transition:
self.trans = TransitionBlock(in_channels=in_channels, out_cha... |
def make_delta(base_model_path, target_model_path, delta_path):
print(f'Loading the base model from {base_model_path}')
base = AutoModelForCausalLM.from_pretrained(base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
print(f'Loading the target model from {target_model_path}')
target = Aut... |
def create_region_from_mask(mask, join_labels: tuple):
mask_new = np.zeros_like(mask, dtype=np.uint8)
for l in join_labels:
mask_new[(mask == l)] = 1
return mask_new |
class LinearLASSO(torch.nn.Linear, BaseARD, SparsityStats):
def penalty(self):
return abs(self.weight)
def relevance(self, *, threshold, **kwargs):
with torch.no_grad():
return torch.ge(torch.log((abs(self.weight) + 1e-20)), threshold)
def sparsity(self, *, threshold, **kwargs):
... |
class SqlOption(CommandLineOption):
__depends_on__ = 'sqlalchemy'
arg = 'DB_URL'
arg_description = 'The typical form is: dialect://username::port/database'
def apply(cls, args, run):
run.observers.append(SqlObserver.create(args)) |
.parametrize('id, name, demodata', [pytest.param(1, 'cities', DEMODATA_CITIES, id='demodata_cities'), pytest.param(2, 'countries', DEMODATA_COUNTRIES, id='demodata_countries')])
def test_lookup_data_demo_data(id, name, demodata):
lookup = LookupData(name=name, data=load_data_from_file(demodata))
validation = lo... |
class Adafactor(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class ONNXRTBertDataset():
def __init__(self, model, data_dir, model_name_or_path, max_seq_length=128, do_lower_case=True, task='mrpc', model_type='bert', dynamic_length=False, evaluate=True, transform=None, filter=None):
self.inputs = [inp.name for inp in onnx.load(model).graph.input]
task = task.l... |
class SchemaMapAttentionDecoderOutput(namedtuple('DecoderOutput', ['logits', 'predicted_ids', 'cell_output', 'attention_scores', 'attention_context', 'schema_attention_scores', 'schema_attention_context', 'schema_map_attention_scores', 'schema_map_attention_context'])):
pass |
class Normalize(transforms.Normalize):
def __init__(self, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), inplace=False):
super(Normalize, self).__init__(mean, std, inplace)
def __call__(self, x):
return F.normalize(x, self.mean, self.std, self.inplace) |
def split_data(data: MoleculeDataset, split_type: str='random', sizes: Tuple[(float, float, float)]=(0.8, 0.1, 0.1), seed: int=0, args: Namespace=None, logger: Logger=None) -> Tuple[(MoleculeDataset, MoleculeDataset, MoleculeDataset)]:
assert ((len(sizes) == 3) and (sum(sizes) == 1))
if (args is not None):
... |
class NullEvaluator(DatasetEvaluator):
def reset(self):
return
def process(self, inputs: List[Dict], outputs: Dict):
return
def evaluate(self):
synchronize()
return |
def create_pipeline():
fps = 10
monoResolution = dai.MonoCameraProperties.SensorResolution.THE_720_P
pipeline = dai.Pipeline()
queueNames = []
camRgb = pipeline.create(dai.node.ColorCamera)
left = pipeline.create(dai.node.MonoCamera)
right = pipeline.create(dai.node.MonoCamera)
stereo = ... |
class DownTransition(nn.Module):
def __init__(self, inChans, nConvs, elu, dropout=False):
super(DownTransition, self).__init__()
outChans = (2 * inChans)
self.down_conv = nn.Conv3d(inChans, outChans, kernel_size=2, stride=2)
self.bn1 = torch.nn.BatchNorm3d(outChans)
self.do1 ... |
class FairseqMultiModel(BaseFairseqModel):
def __init__(self, encoders, decoders):
super().__init__()
assert (encoders.keys() == decoders.keys())
self.keys = list(encoders.keys())
for key in self.keys:
assert isinstance(encoders[key], FairseqEncoder)
assert is... |
class AnimateDiffPipeline(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(cls... |
class StreamingEpochBatchIterator(EpochBatchIterating):
def __init__(self, dataset, max_sentences=1, collate_fn=None, epoch=1, num_workers=0, buffer_size=0, timeout=0, persistent_workers=True):
assert isinstance(dataset, torch.utils.data.IterableDataset)
self.dataset = dataset
self.max_sente... |
class HumanoidEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self):
mujoco_env.MujocoEnv.__init__(self, 'humanoid.xml', 5)
utils.EzPickle.__init__(self)
def _get_obs(self):
data = self.sim.data
return np.concatenate([data.qpos.flat[2:], data.qvel.flat, data.cinert.flat, ... |
class CodeVersion():
def __init__(self):
self.versions = {'mdir_git': self.git_head_state('mdir')}
def git_head_state(module_name):
if (not hasattr(sys.modules.get(module_name, None), '__file__')):
return None
try:
git_path = (Path(sys.modules[module_name].__file_... |
def parse_args():
parser = argparse.ArgumentParser(description='mmseg test (and eval) a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--aug-test', action='store_true', help='Use Flip and Multi scale aug'... |
_config
def bsp_small():
cfg = {'learner': {'model': 'LifelongSidetuneNetwork', 'model_kwargs': {'base_class': 'GenericSidetuneNetwork', 'base_kwargs': {'base_kwargs': {'bsp': True, 'period': 3}, 'side_kwargs': {'bsp': True, 'period': 3}}}}} |
class PDTBEval(object):
def __init__(self, task_path, seed=1111):
self.seed = seed
logging.debug('***** Transfer task : PDTB classification, task path: {} *****\n\n'.format(task_path))
train = self.loadFile(os.path.join(task_path, 'train.txt'))
valid = self.loadFile(os.path.join(task... |
class RRS(nn.Module):
def __init__(self, encoder, decoder, dl, **kwargs):
super().__init__()
encoder.vocab_size = dl.dataset.src.tokenizer.vocab_size
self.enc = EncoderModel(encoder)
decoder.vocab_size = dl.dataset.tgt.tokenizer.vocab_size
self.dec = DecoderModel(decoder)
... |
class LIRCMOP3(LIRCMOP1):
def __init__(self, number_of_variables: int=30):
super(LIRCMOP3, self).__init__(number_of_variables)
def number_of_constraints(self) -> int:
return 3
def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution:
x = solution.variables
con... |
def plot_log_csv(log_path):
(log_dir, _) = osp.split(log_path)
dat = np.genfromtxt(log_path, names=True, delimiter=',', autostrip=True)
train_loss = dat['trainloss']
train_loss_sel = (~ np.isnan(train_loss))
train_loss = train_loss[train_loss_sel]
iter_train_loss = dat['iteration'][train_loss_se... |
def parse_args():
parser = argparse.ArgumentParser(description='Train a segmentor')
parser.add_argument('config', help='train config file path')
parser.add_argument('--shape', type=int, nargs='+', default=[2048, 1024], help='input image size')
args = parser.parse_args()
return args |
class _bound_learner(nn.Module):
def __init__(self, point_pred=1, hidden_features=128, im_num=2, ex_num=2):
super().__init__()
self.point_pred = point_pred
self.convolution_mapping_1 = nn.Conv2d(in_channels=128, out_channels=hidden_features, kernel_size=(1, 1), stride=(1, 1), padding=(0, 0),... |
class Policy4Toyota(tf.Module):
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
tf.config.experimental.set_visible_devices([], 'GPU')
def __init__(self, args):
super().__init__()
self.args = args
(obs_dim, act_dim) ... |
def compute_impact_geometry(a: Polygon, b: BaseGeometry) -> (np.ndarray, Point):
assert (not a.touches(b))
if a.contains(b):
impact_point = b.centroid
r_ap = (np.array(impact_point.coords[0]) - np.array(a.centroid.coords[0]))
normal = (r_ap / np.linalg.norm(r_ap))
else:
inter... |
class SimpleTokenizer(Tokenizer):
ALPHA_NUM = '[\\p{L}\\p{N}\\p{M}]+'
NON_WS = '[^\\p{Z}\\p{C}]'
def __init__(self, **kwargs):
self._regexp = regex.compile(('(%s)|(%s)' % (self.ALPHA_NUM, self.NON_WS)), flags=((regex.IGNORECASE + regex.UNICODE) + regex.MULTILINE))
if (len(kwargs.get('annotat... |
def _onnxruntime_checker():
onnxruntime_installed = (not (find_spec('onnxruntime') is None))
onnx_installed = (not (find_spec('onnx') is None))
return (onnxruntime_installed and onnx_installed) |
def load_svhn(data_dir, use_augmentation=False):
test_transform = transforms.Compose([transforms.ToTensor()])
train_transform = test_transform
train_dataset = torchvision.datasets.SVHN(root=data_dir, split='train', download=True, transform=train_transform)
test_dataset = torchvision.datasets.SVHN(root=d... |
def log_parameters(log_file, args, classes):
log_params = {}
for (param_name, param_value) in args.__dict__.items():
if any([param_name.startswith(x) for x in list(classes.keys())]):
continue
log_params[param_name] = param_value
for (name, cls) in classes.items():
if isin... |
_grad()
def n_step_guided_p_sample(model, x, cond, t, guide, scale=0.001, t_stopgrad=0, n_guide_steps=1, scale_grad_by_std=True):
model_log_variance = extract(model.posterior_log_variance_clipped, t, x.shape)
model_std = torch.exp((0.5 * model_log_variance))
model_var = torch.exp(model_log_variance)
for... |
def subprocess_fn(rank, args, temp_dir):
dnnlib.util.Logger(should_flush=True)
if (args.num_gpus > 1):
init_file = os.path.abspath(os.path.join(temp_dir, '.torch_distributed_init'))
if (os.name == 'nt'):
init_method = ('file:///' + init_file.replace('\\', '/'))
torch.dist... |
def display_table(rows, positions):
def display_row(objects, positions):
line = ''
for i in range(len(objects)):
line += str(objects[i])
line = line[:positions[i]]
line += (' ' * (positions[i] - len(line)))
print(line)
for objects in rows:
disp... |
class NezhaForNextSentencePrediction(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def spectral_worker(G):
eigs = eigvalsh(nx.normalized_laplacian_matrix(G).todense())
(spectral_pmf, _) = np.histogram(eigs, bins=200, range=((- 1e-05), 2), density=False)
spectral_pmf = (spectral_pmf / spectral_pmf.sum())
return spectral_pmf |
def show_semantic_scholar_popup(show_popup: bool, user_id):
conn = getDb()
with closing(conn.cursor()) as cur:
sql = 'update users set show_semantic_scholar_popup = %s where user_id = %s'
cur.execute(sql, (show_popup, user_id))
conn.commit() |
def show_heads():
head_names = heads.__all__
numbers = list(range(1, (len(head_names) + 1)))
print(tabulate({'No.': numbers, 'Heads': head_names}, headers='keys')) |
def test_digits_cosine_stochastic():
model = GraphCutSelection(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_almost_... |
def unfreeze_model(model):
for layer in model.layers[(- 20):]:
if (not isinstance(layer, layers.BatchNormalization)):
layer.trainable = True
optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']... |
def process_one_data_item(data_item):
print(data_item)
(_, item_name) = os.path.split(data_item[:(- 1)])
output_fd = os.path.join(output_data_dir, item_name)
os.makedirs(output_fd, exist_ok=True)
os.makedirs(os.path.join(output_fd, 'sample'), exist_ok=True)
smpl = objio.load_obj_data(os.path.joi... |
def quniform(lower: float, upper: float, q: float) -> 'tune.sample.Float':
return tune.quniform(lower, upper, q) |
def test_test_memoryview_from_buffer_nullptr():
if env.PY2:
m.test_memoryview_from_buffer_nullptr()
else:
with pytest.raises(ValueError):
m.test_memoryview_from_buffer_nullptr() |
class TestExampleConfigs():
.parametrize('config_name', list(_CONFIG_LEVELS.keys()))
def testExampleConfigs(self, config_name):
config_module = importlib.import_module(('moog_demos.example_configs.' + config_name))
for level in _CONFIG_LEVELS[config_name]:
config = config_module.get_... |
def conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1):
if could_use_op(input):
return conv2d_gradfix(transpose=False, weight_shape=weight.shape, stride=stride, padding=padding, output_padding=0, dilation=dilation, groups=groups).apply(input, weight, bias)
return F.conv2d(input=... |
class downSample_Generator(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
super(downSample_Generator, self).__init__()
self.convLayer = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, paddin... |
class SpectralNormLoadStateDictPreHook(object):
def __init__(self, fn):
self.fn = fn
def __call__(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
fn = self.fn
version = local_metadata.get('spectral_norm', {}).get((fn.name + '.version'), None)... |
('requests.sessions.Session.request')
def test_get_data(mock_request):
session = eia.EIASession(api_key='DUMMY_KEY')
mock_response = mock.Mock()
mock_response.json.side_effect = [RETURN_VALUE_1, RETURN_VALUE_2]
mock_response.status_code = 200
mock_request.return_value = mock_response
data = sess... |
def get_annotations(fn):
global options
annfn = (path.splitext(fn)[0] + options.annsuffix)
with open(annfn, 'rU') as f:
(textbounds, dict_of_entity, list_of_relns) = parse_textbounds(f)
textbounds = eliminate_overlaps(textbounds, fn)
return (textbounds, dict_of_entity, list_of_relns) |
_ARCH_REGISTRY.register()
class PanopticFPN_baseline(PanopticFPN):
def __init__(self, cfg):
unseen_path = cfg.DATASETS.UNSEEN_LABEL_SET
self.meta = MetadataCatalog.get(cfg.DATASETS.TRAIN[0])
if (unseen_path != ''):
meta = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]).thing_classes
... |
def copy_to_quad_double_syspool(idx, vrblvl=0):
if (vrblvl > 0):
print('in copy_to_quad_double_syspool, idx :', idx)
phc = get_phcfun()
adim = pointer(c_int32(idx))
bbb = pointer(c_int32(0))
ccc = pointer(c_double(0.0))
vrb = c_int32(vrblvl)
if (vrblvl > 0):
print('-> copy_to... |
def group_bleu(inp_group, reference: str) -> dict:
scores = defaultdict(list)
for (idx, inp) in enumerate(inp_group):
bleu_score = bleu_scorer.sentence_score(inp, [reference])
scores['bleu'].append(bleu_score.score)
d = {}
for (k, v) in scores.items():
avg = statistics.mean(v)
... |
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU):
super().__init__()
out_features = (out_features or in_features)
hidden_features = (hidden_features or in_features)
self.fc1 = nn.Linear(in_features, hidden_features)
... |
def test_isotropic_eddington_selfconsist_dehnencore_sigmar_directint():
pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
dfp = eddingtondf(pot=pot)
tol = 0.001
check_sigmar_against_jeans_directint(dfp, pot, tol, rmin=(pot._scale / 10.0), rmax=(pot._scale * 10.0), bins=31)
return None |
def diapreresnet26(**kwargs):
return get_diapreresnet(blocks=26, bottleneck=False, model_name='diapreresnet26', **kwargs) |
def get_train_data(input_shape, output_dim):
if (input_shape == (1,)):
data = np.linspace((- np.pi), np.pi, 1000)
obs = [{'observations': [[x]], 'returns': [get_labels(input_shape, x, output_dim)]} for x in data]
elif (input_shape == (2,)):
x = np.linspace(0, 1, 100)
y = np.linsp... |
def get_parser():
parser = configargparse.ArgumentParser(description='Translate text from speech using a speech translation model on one CPU or GPU', config_file_parser_class=configargparse.YAMLConfigFileParser, formatter_class=configargparse.ArgumentDefaultsHelpFormatter)
parser.add('--config', is_config_file=... |
class DemoLoader(Dataset):
NUM_CLASS = 1
def __init__(self, dataset_dir, transform=None, base_size=512, crop_size=480, suffix='.png'):
super(DemoLoader, self).__init__()
self.transform = transform
self.images = dataset_dir
self.base_size = base_size
self.crop_size = crop_... |
class DreamBoothDataset(Dataset):
def __init__(self, instance_data_root, instance_prompt, tokenizer, class_data_root=None, class_prompt=None, size=512, center_crop=False):
self.size = size
self.center_crop = center_crop
self.tokenizer = tokenizer
self.instance_data_root = Path(instan... |
def float_to_float16(tensor):
min_val = 5.96e-08
max_val = 65504.0
tensor[((tensor > max_val) & (tensor < float('inf')))] = max_val
tensor[((tensor < min_val) & (tensor > 0))] = min_val
tensor[((tensor > (- min_val)) & (tensor < 0))] = (- min_val)
tensor[((tensor < (- max_val)) & (tensor > float... |
def hdbscan(feat, min_samples=10):
import hdbscan
db = hdbscan.HDBSCAN(min_cluster_size=min_samples)
labels_ = db.fit_predict(feat)
return labels_ |
class GraphRewriter(object):
def __init__(self, input_graph, mode, quantized_input_range, fallback_quantization_range=None):
self.input_graph = input_graph
self.nodes_map = self.create_nodes_map(input_graph)
self.output_graph = None
self.mode = mode
self.final_node_renames = ... |
class DeepImage(nn.Module):
def __init__(self, pretrained: bool=True, resnet_architecture: int=18, freeze_n: int=6, head_hidden_dims: Optional[List[int]]=None, head_activation: str='relu', head_dropout: float=0.1, head_batchnorm: bool=False, head_batchnorm_last: bool=False, head_linear_first: bool=False):
s... |
class EfficientNetSqueezeExciteLayer(nn.Module):
def __init__(self, config: EfficientNetConfig, in_dim: int, expand_dim: int, expand: bool=False):
super().__init__()
self.dim = (expand_dim if expand else in_dim)
self.dim_se = max(1, int((in_dim * config.squeeze_expansion_ratio)))
sel... |
_task('speech_commands')
class SpeechCommandsTask(FairseqTask):
def add_args(parser):
parser.add_argument('data', metavar='FILE', help='file prefix for data')
parser.add_argument('--num-classes', type=int, default=(- 1), help='number of classes or regression targets')
parser.add_argument('--... |
def sub_UNK(sent, word_dict):
words = sent.split()
for (i, w) in enumerate(words):
if (w not in word_dict):
words[i] = '<UNK>'
return ' '.join(words) |
def solve(pols, tasks=0, mvfocus=0, precision='d', checkin=True, dictionary_output=False, verbose_level=0):
if checkin:
errmsg = 'The blackbox solver accepts only square systems,'
if (not solve_checkin(pols, errmsg)):
return None
if (tasks < 0):
print('The number of t... |
def _process_image_files(name, filenames, synsets, labels, humans, bboxes, num_shards):
assert (len(filenames) == len(synsets))
assert (len(filenames) == len(labels))
assert (len(filenames) == len(humans))
assert (len(filenames) == len(bboxes))
spacing = np.linspace(0, len(filenames), (FLAGS.num_thr... |
def _malfunction_prob(rate: float) -> float:
if (rate <= 0):
return 0.0
else:
return (1 - np.exp((- rate))) |
def zero_shot_prompt(example: Example) -> str:
'Creates a zero-shot prompt given a single example. Uses the prompt format from this paper on Scalable Oversight: \n
prompt = base_prompt(example)
prompt += f'''
Format your response as follows: "The correct answer is (insert answer here)"'''
return pro... |
class DenseDecoder(tools.Module):
def __init__(self, shape, layers, units, dist='normal', act=tf.nn.elu):
self._shape = shape
self._layers = layers
self._units = units
self._dist = dist
self._act = act
def __call__(self, features):
x = features
for index i... |
def print_progress(prefix, start_time, urls_counter, domain_blacklist_counter, extention_blacklist_counter, short_url_counter, malformed_url_counter, duplicate_url_counter):
string = (prefix + ' | ')
string += 'time elapsed (s): {:.2f} | '.format((time.time() - start_time))
string += 'number of urls: {} | '... |
def hydra_conf_load_from_checkpoint(chkpt_file, cfg):
instance_args = dict()
cfg_mask = list()
for k in cfg.keys():
if (OmegaConf.is_dict(cfg[k]) and ('_target_' in cfg[k])):
instance_args[k] = hydra.utils.instantiate(cfg[k])
else:
cfg_mask += [k]
ModuleType = typ... |
def extract_pattern(message, pattern):
matches = re.findall(pattern, message, re.DOTALL)
for match in matches:
return match.strip()
return None |
def torchify_buffer(buffer_):
if (buffer_ is None):
return
if isinstance(buffer_, np.ndarray):
return torch.from_numpy(buffer_)
elif isinstance(buffer_, torch.Tensor):
return buffer_
contents = tuple((torchify_buffer(b) for b in buffer_))
if (type(buffer_) is tuple):
... |
class ContextAttentionEncoder(nn.Module):
def __init__(self, input_dim: int, dropout: float, with_addnorm: bool, activation: str):
super(ContextAttentionEncoder, self).__init__()
self.with_addnorm = with_addnorm
self.attn = ContextAttention(input_dim, dropout)
if with_addnorm:
... |
class RandomForestRegressorAlgorithm(SklearnTreesEnsembleRegressorAlgorithm):
algorithm_name = 'Random Forest'
algorithm_short_name = 'Random Forest'
def __init__(self, params):
super(RandomForestRegressorAlgorithm, self).__init__(params)
logger.debug('RandomForestRegressorAlgorithm.__init__... |
class UNetMidBlock3DCrossAttn(nn.Module):
def __init__(self, in_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=True, attn_num_head_channels=1, output_s... |
class Edge_NRI(nn.Module):
def __init__(self, in_channels, w_node2edge, num_atoms, device, dropout=0.0):
super(Edge_NRI, self).__init__()
self.dropout = nn.Dropout(dropout)
self.w_node2edge = w_node2edge
self.w_edge2value = nn.Sequential(nn.Linear(in_channels, (in_channels // 2)), nn... |
class ADAINResnetBlock(nn.Module):
def __init__(self, input_nc, output_nc, hidden_nc, feature_nc, nonlinearity=nn.LeakyReLU(), use_spect=False, use_coord=False, learned_shortcut=False):
super(ADAINResnetBlock, self).__init__()
self.learned_shortcut = ((input_nc != output_nc) or learned_shortcut)
... |
class GcnInfomax(nn.Module):
def __init__(self, args: Namespace, gamma=0.1):
super(GcnInfomax, self).__init__()
self.args = args
self.gamma = gamma
self.prior = args.prior
self.features_dim = args.hidden_size
self.embedding_dim = args.gcn_hidden3
self.local_d ... |
def main():
parser = argparse.ArgumentParser(description='PyTorch Object Detection Inference')
parser.add_argument('--config-file', default='/private/home/fmassa/github/detectron.pytorch_v2/configs/e2e_faster_rcnn_R_50_C4_1x_caffe2.yaml', metavar='FILE', help='path to config file')
parser.add_argument('--lo... |
def save_model(state, output_path):
save_path = os.path.join(output_path, f"final_epoch_{state['epoch']}_val_loss_{state['val_loss']}_dice_{state['val_dice_score']}.pth")
logger.info(f'Saving last to{save_path}')
torch.save(state, save_path) |
def convMeanpool(inplanes, outplanes):
sequence = []
sequence += [conv3x3(inplanes, outplanes)]
sequence += [nn.AvgPool2d(kernel_size=2, stride=2)]
return nn.Sequential(*sequence) |
_REGISTRY.register()
class DAEL(TrainerXU):
def __init__(self, cfg):
super().__init__(cfg)
n_domain = cfg.DATALOADER.TRAIN_X.N_DOMAIN
batch_size = cfg.DATALOADER.TRAIN_X.BATCH_SIZE
if (n_domain <= 0):
n_domain = self.dm.num_source_domains
self.split_batch = (batch... |
class ShortestPathFollowerCompat():
def __init__(self, sim: HabitatSim, goal_radius: float, return_one_hot: bool=True):
assert (getattr(sim, 'geodesic_distance', None) is not None), '{} must have a method called geodesic_distance'.format(type(sim).__name__)
self._sim = sim
self._max_delta = ... |
_grad()
def make_convolutional_sample(model, batch_size, vanilla=False, custom_steps=None, eta=1.0):
log = dict()
shape = [batch_size, model.model.diffusion_model.in_channels, model.model.diffusion_model.image_size, model.model.diffusion_model.image_size]
with model.ema_scope('Plotting'):
t0 = time.... |
class FasterRcnnBoxCoderTest(tf.test.TestCase):
def test_get_correct_relative_codes_after_encoding(self):
boxes = [[10.0, 10.0, 20.0, 15.0], [0.2, 0.1, 0.5, 0.4]]
anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]]
expected_rel_codes = [[(- 0.5), (- 0.416666), (- 0.405465), (- 0.18232... |
_module(name='NormedConv2d')
class NormedConv2d(nn.Conv2d):
def __init__(self, *args, tempearture: float=20, power: int=1.0, eps: float=1e-06, norm_over_kernel: bool=False, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.tempearture = tempearture
self.power = power
self.nor... |
def get_flat(sent):
labels = []
for token in sent.tokens:
scopes = token.scope
if (len(scopes) > 0):
label = scopes[(- 1)][(- 1)]
else:
label = 'O'
labels.append(label)
return labels |
def build_attr_dict(attr_triples):
d = dict()
for (e, a, v) in attr_triples:
d.setdefault(e, dict())
d[e][a] = v
return d |
class WhiteSpaceTokenizer(object):
def __init__(self, word_count_path, vocab_size, pad_token='<pad>', bos_token='<s>', eos_token='</s>', unk_token='<unk>', sep_token='<sep>', cls_token='<cls>', mask_token='<mask>', special_token_dict={}):
self.pad_token = pad_token
self.bos_token = bos_token
... |
class UniSpeechConfig(PretrainedConfig):
model_type = 'unispeech'
def __init__(self, vocab_size=32, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout=0.1, activation_dropout=0.1, attention_dropout=0.1, feat_proj_dropout=0.0, feat_quantizer_d... |
class LinearGrad(autograd.Function):
def forward(context, input, weight, bias=None):
context.save_for_backward(input, weight, bias)
output = torch.nn.functional.linear(input, weight, bias)
return output
def backward(context, grad_output):
(input, weight, bias) = context.saved_ten... |
class BasisModel(tf.keras.layers.Layer):
def __init__(self, dimensions, nfunctions, scale, **kwarg):
super(BasisModel, self).__init__(name='attention', **kwarg)
self._degree = nfunctions
self.scale = scale
def build(self, input_shape):
self.centers = np.linspace(0.0, 1.01, self._... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.