repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
TayLaNets | TayLaNets-main/examples_taylanets/mnist/tayla_mnist.py | import argparse
import pickle
import time
# Typing functions
from typing import Tuple
from pathlib import Path
# Import JAX and utilities
import jax
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_flatten
from jax import lax
# Haiku for Neural networks
import haiku as hk
# Optax for the o... | 34,476 | 47.21958 | 255 | py |
TayLaNets | TayLaNets-main/examples_taylanets/mnist/jinkelly_mnist.py | """
Neural ODEs on MNIST with no downsampling before ODE, implemented with Haiku.
"""
import argparse
import collections
import os
import pickle
import time
from math import prod
import haiku as hk
import jax
import jax.numpy as jnp
import tensorflow_datasets as tfds
from jax import lax
from jax.config import config
f... | 30,344 | 36.141983 | 293 | py |
TayLaNets | TayLaNets-main/examples_taylanets/vanderpool/learn_dynamics.py | import argparse
import pickle
import time
# Typing functions
from typing import Tuple
from pathlib import Path
# Import JAX and utilities
import jax
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_flatten
from jax import lax
# Haiku for Neural networks
import haiku as hk
# Optax for the o... | 28,251 | 50.74359 | 402 | py |
TayLaNets | TayLaNets-main/examples_taylanets/vanderpool/learn_midpoint.py | import argparse
import pickle
import time
# Typing functions
from typing import Tuple
from pathlib import Path
# Import JAX and utilities
import jax
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_flatten
# Haiku for Neural networks
import haiku as hk
# Optax for the optimization scheme
i... | 23,232 | 47.911579 | 279 | py |
TayLaNets | TayLaNets-main/examples_taylanets/vanderpool/plot_result.py | import argparse
import pickle
import time
from math import prod
# Typing functions
from typing import Tuple
# Import JAX and utilities
import jax
import jax.numpy as jnp
from jax.experimental import jet
from jax.tree_util import tree_flatten
import numpy as np
# Haiku for Neural networks
import haiku as hk
# Optax... | 13,454 | 42.543689 | 134 | py |
TayLaNets | TayLaNets-main/examples_taylanets/vanderpool/generate_sample.py | from jax.config import config
config.update("jax_enable_x64", True)
import yaml
import pickle
# Import JAX
import jax
import jax.numpy as jnp
from jax import grad, vmap, jit
from taylanets.utils import SampleLog, load_data_yaml
from tqdm.auto import tqdm
from scipy.integrate import odeint as scipy_ode
import numpy... | 6,205 | 37.308642 | 176 | py |
TayLaNets | TayLaNets-main/examples_taylanets/ffjord_tabular/tayla_ffjord_tabular.py | import argparse
import pickle
import time
# Typing functions
from typing import Tuple
from pathlib import Path
# Import JAX and utilities
import jax
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_flatten
from jax import lax
from jax.config import config
# Haiku for Neural networks
import ... | 32,551 | 44.211111 | 196 | py |
TayLaNets | TayLaNets-main/examples_taylanets/ffjord_tabular/jinkelly_ffjord_tabular.py | """
FFJORD on Tabular, implemented with Haiku.
"""
import argparse
import collections
import os
import pickle
import sys
import time
import haiku as hk
import jax
import jax.numpy as jnp
from jax import lax
from jax.config import config
from jax.experimental import optimizers
from jax.experimental.jet import jet
from ... | 26,564 | 34.801887 | 259 | py |
TayLaNets | TayLaNets-main/examples_taylanets/stiff_dynamics/learn_dynamics.py | import argparse
import pickle
import time
# Typing functions
from typing import Tuple
from pathlib import Path
# Import JAX and utilities
import jax
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_flatten
from jax import lax
# Haiku for Neural networks
import haiku as hk
# Optax for the o... | 29,250 | 50.955595 | 402 | py |
TayLaNets | TayLaNets-main/examples_taylanets/stiff_dynamics/show_results.py | """ Code source to plot the results associated to
learning the midpoint value
"""
import numpy as np
import matplotlib.pyplot as plt
from tqdm.auto import tqdm
from generate_sample import exact_solution
from learn_midpoint import init_model as known_dyn_init
from learn_dynamics import init_model as unkn_dyn_init
... | 13,426 | 43.906355 | 216 | py |
TayLaNets | TayLaNets-main/examples_taylanets/stiff_dynamics/learn_midpoint.py | import argparse
import pickle
import time
# Typing functions
from typing import Tuple
from pathlib import Path
# Import JAX and utilities
import jax
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_flatten
# Haiku for Neural networks
import haiku as hk
# Optax for the optimization scheme
i... | 24,270 | 48.735656 | 398 | py |
TayLaNets | TayLaNets-main/examples_taylanets/stiff_dynamics/generate_sample.py | from jax.config import config
config.update("jax_enable_x64", True)
import yaml
import pickle
# Import JAX
import jax
import jax.numpy as jnp
from jax import grad, vmap, jit
from taylanets.utils import SampleLog, load_data_yaml
from tqdm.auto import tqdm
from scipy.integrate import odeint as scipy_ode
import numpy... | 7,873 | 37.038647 | 176 | py |
TayLaNets | TayLaNets-main/taylanets/ode.py | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 75,796 | 39.33901 | 121 | py |
TayLaNets | TayLaNets-main/taylanets/utils.py | from collections import namedtuple
# Haiku for Neural networks
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
# Optax for the optimization scheme
import optax
# Yaml and pickle import
import pickle
import yaml
from tqdm.auto import tqdm
suffix = '.pickle'
_INITIALIZER_MAPPING = \
{
'Co... | 16,929 | 44.026596 | 201 | py |
TayLaNets | TayLaNets-main/taylanets/tayla.py | # Import JAX and utilities
import jax
import jax.numpy as jnp
from jax.experimental import jet
from jax.experimental.ode import odeint as jax_odeint
from jax import lax
import math
def taylor_order_n(vector_field_fn, state : jnp.ndarray, order : int):
""" Compute higher-order Taylor expansion and return the high-... | 18,648 | 44.485366 | 154 | py |
KPGT | KPGT-main/src/utils.py | import os
import random
import numpy as np
import torch
import dgl
def set_random_seed(seed=22, n_threads=16):
"""Set random seed.
Parameters
----------
seed : int
Random seed to use
"""
random.seed(seed)
np.random.seed(seed)
dgl.random.seed(seed)
dgl.seed(seed)
torch.m... | 578 | 22.16 | 45 | py |
KPGT | KPGT-main/src/trainer/scheduler.py | from torch.optim.lr_scheduler import _LRScheduler
class PolynomialDecayLR(_LRScheduler):
def __init__(self, optimizer, warmup_updates, tot_updates, lr, end_lr, power, last_epoch=-1, verbose=False):
self.warmup_updates = warmup_updates
self.tot_updates = tot_updates
self.lr = lr
se... | 1,136 | 35.677419 | 112 | py |
KPGT | KPGT-main/src/trainer/evaluator.py | from sklearn.metrics import roc_auc_score, average_precision_score, mean_absolute_error, r2_score
import pandas as pd
import os
import numpy as np
try:
import torch
except ImportError:
torch = None
### Evaluator for graph classification
class Evaluator:
def __init__(self, name, eval_metric, n_tasks, mean=... | 7,860 | 38.109453 | 131 | py |
KPGT | KPGT-main/src/trainer/pretrain_trainer.py | import torch
import numpy as np
from sklearn.metrics import f1_score
class Trainer():
def __init__(self, args, optimizer, lr_scheduler, reg_loss_fn, clf_loss_fn, sl_loss_fn, reg_evaluator, clf_evaluator, result_tracker, summary_writer, device, ddp=False, local_rank=1):
self.args = args
self.optimize... | 5,957 | 63.76087 | 187 | py |
KPGT | KPGT-main/src/trainer/finetune_trainer.py | import torch
import numpy as np
class Trainer():
def __init__(self, args, optimizer, lr_scheduler, loss_fn, evaluator, result_tracker, summary_writer, device, model_name, label_mean=None, label_std=None, ddp=False, local_rank=0):
self.args = args
self.model_name = model_name
self.optimizer =... | 3,482 | 44.233766 | 184 | py |
KPGT | KPGT-main/src/data/pretrain_dataset.py | from torch.utils.data import Dataset
import os
import numpy as np
import scipy.sparse as sps
import torch
import dgl.backend as F
class MoleculeDataset(Dataset):
def __init__(self, root_path):
smiles_path = os.path.join(root_path, "smiles.smi")
fp_path = os.path.join(root_path, "rdkfp1-7_512.npz")
... | 1,509 | 40.944444 | 88 | py |
KPGT | KPGT-main/src/data/collator.py | import dgl
import torch
import numpy as np
from copy import deepcopy
from .featurizer import smiles_to_graph
def preprocess_batch_light(batch_num, batch_num_target, tensor_data):
batch_num = np.concatenate([[0],batch_num],axis=-1)
cs_num = np.cumsum(batch_num)
add_factors = np.concatenate([[cs_num[i]]*batc... | 5,513 | 46.128205 | 167 | py |
KPGT | KPGT-main/src/data/finetune_dataset.py | from torch.utils.data import Dataset
import os
import pandas as pd
import numpy as np
from dgl.data.utils import load_graphs
import torch
import dgl.backend as F
import scipy.sparse as sps
SPLIT_TO_ID = {'train':0, 'val':1, 'test':2}
class MoleculeDataset(Dataset):
def __init__(self, root_path, dataset, dataset_ty... | 3,261 | 42.493333 | 120 | py |
KPGT | KPGT-main/src/data/featurizer.py | import numpy as np
import torch
from rdkit import Chem
import dgl
from dgllife.utils.featurizers import ConcatFeaturizer, bond_type_one_hot, bond_is_conjugated, bond_is_in_ring, bond_stereo_one_hot, atomic_number_one_hot, atom_degree_one_hot, atom_formal_charge, atom_num_radical_electrons_one_hot, atom_hybridization_on... | 15,191 | 47.075949 | 366 | py |
KPGT | KPGT-main/src/model/light.py | import torch
from torch import nn
import dgl
from dgl import function as fn
from dgl.nn.functional import edge_softmax
import numpy as np
from src.data.featurizer import VIRTUAL_ATOM_FEATURE_PLACEHOLDER, VIRTUAL_BOND_FEATURE_PLACEHOLDER
def init_params(module):
if isinstance(module, nn.Linear):
module.wei... | 13,491 | 40.134146 | 160 | py |
KPGT | KPGT-main/scripts/extract_features.py | import torch
from torch.utils.data import DataLoader
import numpy as np
import argparse
import sys
sys.path.append("..")
from src.utils import set_random_seed
from src.data.featurizer import Vocab, N_ATOM_TYPES, N_BOND_TYPES
from src.data.finetune_dataset import MoleculeDataset
from src.data.collator import Collator_... | 2,489 | 39.819672 | 119 | py |
KPGT | KPGT-main/scripts/finetune.py | import sys
sys.path.append('..')
from src.utils import set_random_seed
import argparse
import torch
from torch import nn
from torch.utils.data import DataLoader
from torch.optim import Adam
from torch.nn import MSELoss, BCEWithLogitsLoss
import numpy as np
import random
from src.data.featurizer import Vocab, N_ATOM_TY... | 6,739 | 47.142857 | 307 | py |
KPGT | KPGT-main/scripts/train_kpgt.py | import sys
sys.path.append('..')
from src.utils import set_random_seed
import argparse
import torch
from torch.utils.data import DataLoader
from torch.optim import Adam
from torch.nn import MSELoss, BCEWithLogitsLoss, CrossEntropyLoss
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data.distributed ... | 4,499 | 44.918367 | 230 | py |
KPGT | KPGT-main/scripts/evaluation.py | import sys
sys.path.append('..')
from src.utils import set_random_seed
import argparse
import torch
from torch import nn
from torch.utils.data import DataLoader
import numpy as np
import random
from src.data.featurizer import Vocab, N_ATOM_TYPES, N_BOND_TYPES
from src.data.finetune_dataset import MoleculeDataset
from ... | 6,059 | 45.976744 | 307 | py |
RxnScribe | RxnScribe-main/main.py | import os
import math
import json
import random
import argparse
import numpy as np
import torch
import torch.distributed as dist
import pytorch_lightning as pl
from pytorch_lightning import LightningModule, LightningDataModule
from pytorch_lightning.callbacks import LearningRateMonitor
from pytorch_lightning.strategie... | 17,750 | 47.236413 | 123 | py |
RxnScribe | RxnScribe-main/setup.py | from distutils.core import setup
setup(
name='RxnScribe',
version='1.0',
description='RxnScribe',
author='Yujie Qian',
author_email='yujieq@csail.mit.edu',
url='https://github.com/thomas0809/RxnScribe',
packages=['rxnscribe', 'rxnscribe.inference', 'rxnscribe.pix2seq', 'rxnscribe.transforme... | 924 | 30.896552 | 96 | py |
RxnScribe | RxnScribe-main/predict.py | import argparse
import torch
from rxnscribe import RxnScribe
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', type=str, default=None, required=True)
parser.add_argument('--image_path', type=str, default=None, required=True)
args = parser.parse_args()
device = tor... | 505 | 24.3 | 78 | py |
RxnScribe | RxnScribe-main/rxnscribe/loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class LabelSmoothingLoss(nn.Module):
"""
With label smoothing,
KL-divergence between q_{smoothed ground truth prob.}(w)
and p_{prob. computed by model}(w) is minimized.
"""
def __init__(self, label_smoothing, tgt_vocab_size, ig... | 3,268 | 34.150538 | 95 | py |
RxnScribe | RxnScribe-main/rxnscribe/model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import timm
from .inference import GreedySearch, BeamSearch
from .transformer import TransformerDecoder, Embeddings
class Encoder(nn.Module):
def __init__(self, args, pretrained=False):
super().__init__()
mode... | 10,688 | 39.954023 | 120 | py |
RxnScribe | RxnScribe-main/rxnscribe/dataset.py | import os
import cv2
import copy
import random
import json
import contextlib
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence
from . import transforms as T
from pycocot... | 9,495 | 37.759184 | 113 | py |
RxnScribe | RxnScribe-main/rxnscribe/interface.py | import os
import argparse
from typing import List
import PIL
import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
from .pix2seq import build_pix2seq_model
from .tokenizer import get_tokenizer
from .dataset import make_transforms
from .data import p... | 7,212 | 42.451807 | 117 | py |
RxnScribe | RxnScribe-main/rxnscribe/transforms.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Transforms and data augmentation for both image + bbox.
"""
import random
import math
import PIL
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as F
import numpy as np
def box_cxcywh_to_xyxy(x):
... | 16,371 | 31.809619 | 113 | py |
RxnScribe | RxnScribe-main/rxnscribe/pix2seq/pix2seq.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Pix2Seq model and criterion classes.
"""
import torch
import torch.nn.functional as F
from torch import nn
from .misc import nested_tensor_from_tensor_list
from .backbone import build_backbone
from .transformer import build_transformer
class ... | 3,296 | 40.2125 | 101 | py |
RxnScribe | RxnScribe-main/rxnscribe/pix2seq/misc.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
import os
import subprocess
import time
from collections import defaultdict, deque
import datetime
import pickle
from typing import Optional, List... | 20,490 | 32.869421 | 116 | py |
RxnScribe | RxnScribe-main/rxnscribe/pix2seq/position_encoding.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Various positional encodings for the transformer.
"""
import math
import torch
from torch import nn
from .misc import NestedTensor
class PositionEmbeddingSine(nn.Module):
"""
This is a more standard version of the position embedding, ... | 3,380 | 36.566667 | 105 | py |
RxnScribe | RxnScribe-main/rxnscribe/pix2seq/backbone.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Backbone modules.
"""
from collections import OrderedDict
import torch
import torch.nn.functional as F
import torchvision
from torch import nn
from torchvision.models._utils import IntermediateLayerGetter
from typing import Dict, List
from .mi... | 4,445 | 36.05 | 113 | py |
RxnScribe | RxnScribe-main/rxnscribe/pix2seq/transformer.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Pix2Seq Transformer class.
Copy-paste from torch.nn.Transformer with modifications:
* positional encodings are passed in MHattention
* extra LN at the end of encoder is removed
* decoder returns a stack of activations from all decod... | 14,179 | 37.016086 | 113 | py |
RxnScribe | RxnScribe-main/rxnscribe/pix2seq/attention_layer.py | import torch
import torch.nn as nn
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, dropout=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3)
self.attn_dro... | 1,173 | 30.72973 | 102 | py |
RxnScribe | RxnScribe-main/rxnscribe/inference/decode_strategy.py | import torch
from copy import deepcopy
class DecodeStrategy(object):
def __init__(self, pad, bos, eos, batch_size, parallel_paths, min_length, max_length,
return_attention=False, return_hidden=False):
self.pad = pad
self.bos = bos
self.eos = eos
self.batch_size = ... | 1,843 | 29.229508 | 89 | py |
RxnScribe | RxnScribe-main/rxnscribe/inference/greedy_search.py | import torch
from .decode_strategy import DecodeStrategy
def sample_with_temperature(logits, sampling_temp, keep_topk):
"""Select next tokens randomly from the top k possible next tokens.
Samples from a categorical distribution over the ``keep_topk`` words using
the category probabilities ``logits / samp... | 4,871 | 38.290323 | 98 | py |
RxnScribe | RxnScribe-main/rxnscribe/inference/beam_search.py | import torch
from .decode_strategy import DecodeStrategy
import warnings
class BeamSearch(DecodeStrategy):
"""Generation with beam search.
"""
def __init__(self, pad, bos, eos, batch_size, beam_size, n_best, min_length,
return_attention, max_length):
super(BeamSearch, self).__in... | 8,021 | 38.910448 | 91 | py |
RxnScribe | RxnScribe-main/rxnscribe/transformer/embedding.py | """ Embeddings module """
import math
import warnings
import torch
import torch.nn as nn
from onmt.modules.util_class import Elementwise
class SequenceTooLongError(Exception):
pass
class PositionalEncoding(nn.Module):
"""Sinusoidal positional encoding for non-recurrent neural networks.
Implementation... | 10,055 | 37.528736 | 79 | py |
RxnScribe | RxnScribe-main/rxnscribe/transformer/swin_transformer.py | """ Swin Transformer
A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows`
- https://arxiv.org/pdf/2103.14030
Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below
"""
# --------------------------------------------------------... | 27,970 | 40.255162 | 125 | py |
RxnScribe | RxnScribe-main/rxnscribe/transformer/decoder.py | """
Implementation of "Attention is All You Need" and of
subsequent transformer based architectures
"""
import torch
import torch.nn as nn
from onmt.decoders.decoder import DecoderBase
from onmt.modules import MultiHeadedAttention, AverageAttention
from onmt.modules.position_ffn import PositionwiseFeedForward
from on... | 17,193 | 34.233607 | 110 | py |
SIP | SIP-main/poisson/plot_poisson.py | from phi.torch.flow import *
import pylab
net = u_net(1, 1)
math.seed(999999)
x_gt = CenteredGrid(Noise(batch(batch=128)), 0, x=64, y=64)
y_target = field.solve_linear(field.laplace, x_gt, Solve('CG', 1e-5, 0, x0=x_gt * 0))
net.load_state_dict(torch.load("~/phi/poisson_net/sim_000000/net_GD.pth"))
x_gd = field.nati... | 3,776 | 40.505495 | 96 | py |
SIP | SIP-main/poisson/train_poisson_fno.py | import os
import time
from os.path import expanduser
from phi.torch.flow import *
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
assert TORCH.set_default_device('GPU')
class SpectralConv2d(nn.Module):
def __init__(self, in_channels, out_channels, modes1, modes2):
... | 7,117 | 39.443182 | 215 | py |
SIP | SIP-main/poisson/train_poisson.py | import os
import time
from os.path import expanduser
import torch_kfac
from torch_optimizer import Adahessian
from hessianfree.optimizer import HessianFree
from phi.torch.flow import *
TORCH.set_default_device('GPU')
for seed in range(1):
math.seed(seed)
net = u_net(1, 1)
os.path.exists(expanduser(f"... | 4,705 | 47.020408 | 130 | py |
SIP | SIP-main/heat/train_heat.py | import os
import time
from inv_diffuse import generate_heat_example, inv_diffuse
from phi.torch.flow import *
from os.path import expanduser
from torch_optimizer import Adahessian
from hessianfree.optimizer import HessianFree
math.set_global_precision(64)
assert backend.default_backend().set_default_device('GPU')
... | 4,945 | 51.617021 | 152 | py |
SIP | SIP-main/heat/train_heat_fno.py | """ Fourier Neural Operator (FNO) version
"""
import os
import time
from inv_diffuse import generate_heat_example, inv_diffuse
from phi.torch.flow import *
from os.path import expanduser
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
math.set_global_precision(64)
assert backen... | 7,928 | 41.175532 | 215 | py |
SIP | SIP-main/heat/plot_heat_optim.py | import time
from inv_diffuse import generate_heat_example, inv_diffuse
from phi.torch.flow import *
import pylab
# TORCH.set_default_device('GPU')
math.set_global_precision(64)
viewer = view('x_pg, dx, y, dy, x_gt, x_gd, x_bfgs, y_target', select='batch')
math.seed(0)
x_gt = generate_heat_example(batch(batch=128), s... | 8,746 | 43.176768 | 117 | py |
SIP | SIP-main/fluid/train_fluid.py | from phi.torch.flow import *
from phi.field._field_math import discretize
from phi.vis._vis import record
TORCH.set_default_device('GPU')
math.seed(0)
DOMAIN = dict(x=64, y=64, extrapolation=extrapolation.PERIODIC, bounds=Box(x=128, y=128))
TIME = 2
STEPS = 8
DT = TIME / STEPS
BATCH = batch(batch=64)
def match_los... | 8,980 | 47.284946 | 195 | py |
SIP | SIP-main/fluid/plot_fluid_vis.py | import pylab
from fluid_base import *
net = u_net(2, 2, levels=5, filters=16)
print(f"Parameter count: {parameter_count(net)}")
math.seed(0)
m0, mt, gt, gtv = generate_example()
train_marker_keys = field.stack([m0, mt], dim=channel('keyframe'))
net.load_state_dict(torch.load('~/phi/fluid_v0_net_swirl/Adam/net_16000... | 5,689 | 40.231884 | 104 | py |
SIP | SIP-main/fluid/fluid_base.py | from phi.torch.flow import *
from phi.field._field_math import discretize
from phi.vis._vis import record
TORCH.set_default_device('GPU')
math.seed(0)
DOMAIN = dict(x=64, y=64, extrapolation=extrapolation.PERIODIC, bounds=Box[0:128, 0:128])
TIME = 2
STEPS = 8
DT = TIME / STEPS
BATCH = batch(batch=64)
def match_los... | 4,948 | 48 | 188 | py |
SIP | SIP-main/sin_characterization/newton.py | from phi.flow import math
import torch
@math.jit_compile
def newton_minimization(grad: math.Tensor, hessian: math.Tensor, max_loss_change=None) -> math.Tensor:
"""
Computes a Newton update step that always points towards a minimum of the function.
Args:
grad: Gradient vector.
hessian: Hes... | 7,520 | 53.89781 | 155 | py |
SIP | SIP-main/sin_characterization/train_sin.py | import os
import time
from typing import Optional
from newton import newton_minimization
from phi.torch.flow import *
SEED = 0
OPTIMIZERS = {
'Newton': lambda: optim.Adam(net.parameters(), lr=1e-3 * learning_rate_scale),
'Adam': lambda: optim.Adam(net.parameters(), lr=1e-3 * learning_rate_scale),
'SGD': l... | 5,265 | 40.140625 | 220 | py |
SIP | SIP-main/exp/train_exp.py | from phi.torch.flow import *
TORCH.set_default_device('GPU')
math.seed(0)
BATCH = batch(batch=100)
net = dense_net(1, 1, [16, 64, 16], activation='Sigmoid')
optimizer = optim.SGD(net.parameters(), lr=1e-2)
# optimizer = optim.Adam(net.parameters(), lr=1e-3)
method = vis.control('Adjoint', ('Adjoint', 'Ground Truth', ... | 3,970 | 45.717647 | 144 | py |
SIP | SIP-main/exp/plot_exp.py | from os.path import basename, join
from phi.torch.flow import *
PATHS = [
"~/phi/exp_Sigmoid/Adjoint_000003",
# "~/phi/exp_Sigmoid/Ground Truth",
"~/phi/exp_Sigmoid/Adam",
# "~/phi/exp_Sigmoid/Newton",
# "~/phi/exp_Sigmoid/Newton Damped 0.01",
"~/phi/exp_Sigmoid/Sign",
# "~/phi/exp_Sigmoi... | 2,131 | 28.205479 | 80 | py |
CoQEx | CoQEx-main/coqex/coqex.py | from flask import Flask, render_template, url_for, json, request, jsonify
from flask_cors import CORS, cross_origin
import json
import pprint
import signal
import sys, os
import glob
import traceback
import spacy
import configparser
## set cache directories before loading the predictor module
os.environ['TRANSFORMERS_C... | 5,873 | 34.173653 | 192 | py |
CoQEx | CoQEx-main/coqex/count_prediction/count_contextualization.py | from sentence_transformers import util
def get_cnp_groups(prediction, sorted_data):
"""
return the representative cnp,
group1: cnps with count == prediction
group2: other cnps
"""
cnp_rep, group1, group2 = None, [], []
for cardinal, score, _id, text in sorted_data:
if int(cardinal) == int(prediction):
... | 3,995 | 39.77551 | 123 | py |
conditional_INNs | conditional_INNs-master/mnist_cINN/losses.py | import torch
import numpy as np
from torch.autograd import Variable
import config as c
def MMD(x, y):
xx, yy, xy = torch.mm(x,x.t()), torch.mm(y,y.t()), torch.mm(x,y.t())
rx = (xx.diag().unsqueeze(0).expand_as(xx))
ry = (yy.diag().unsqueeze(0).expand_as(yy))
dxx = rx.t() + rx - 2.*xx
dyy = ry.t(... | 1,023 | 28.257143 | 80 | py |
conditional_INNs | conditional_INNs-master/mnist_cINN/cond_net.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import config as c
import data as color_data
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv = nn.Sequential(
... | 3,131 | 30.959184 | 95 | py |
conditional_INNs | conditional_INNs-master/mnist_cINN/model.py | import torch.optim
import torch.nn as nn
import numpy as np
from FrEIA.framework import *
from FrEIA.modules import *
from extra_modules import *
import data
import config as c
import cond_net
if c.colorize:
nodes = [InputNode(3, *c.img_dims, name='inp')]
else:
nodes = [InputNode(*c.img_dims, name='inp')]
if... | 3,581 | 36.705263 | 135 | py |
conditional_INNs | conditional_INNs-master/mnist_cINN/data.py | import os
from os.path import join, isfile, basename
from time import time
from multiprocessing import Process
from tqdm import tqdm
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset, DataLoader, TensorDataset
import torchvision.transforms as T
import config as c
import torchv... | 1,405 | 35.051282 | 130 | py |
conditional_INNs | conditional_INNs-master/mnist_cINN/eval.py | import sys
import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import torch
from tqdm import tqdm
from torch.nn.functional import avg_pool2d, interpolate
import config as c
import opts
import data
opts.parse(sys.argv)
print('==='*30)
print('Config options:\n')
for v in dir(c):
... | 11,203 | 33.368098 | 119 | py |
conditional_INNs | conditional_INNs-master/mnist_cINN/train.py | #!/usr/bin/env python
import sys
import torch
import torch.nn
import torch.optim
from torch.nn.functional import avg_pool2d, interpolate
from torch.autograd import Variable
import numpy as np
import tqdm
import config as c
import opts
opts.parse(sys.argv)
config_str = ""
config_str += "==="*30 + "\n"
config_str += "C... | 5,006 | 29.162651 | 114 | py |
conditional_INNs | conditional_INNs-master/mnist_cINN/extra_modules.py | from math import exp
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from FrEIA.modules import *
class F_fully_conv(nn.Module):
def __init__(self, in_channels, out_channels, channels_hidden=64, kernel_size=3, leaky_slope=... | 1,664 | 30.415094 | 116 | py |
conditional_INNs | conditional_INNs-master/mnist_cINN/color_mnist_data/color_mnist.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb, rgb_to_hsv
from scipy.ndimage import zoom
from skimage.filters import gaussian
import torch
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as T
import torchvision.datasets
data_dir = '../mnist... | 2,805 | 26.782178 | 100 | py |
conditional_INNs | conditional_INNs-master/colorization_minimal_example/model.py | import torch
import torch.nn as nn
import torch.optim
import FrEIA.framework as Ff
import FrEIA.modules as Fm
ndim_total = 2 * 64 * 64
class CondNet(nn.Module):
'''conditioning network'''
def __init__(self):
super().__init__()
class Flatten(nn.Module):
def __init__(self, *args):
... | 5,661 | 38.594406 | 94 | py |
conditional_INNs | conditional_INNs-master/colorization_minimal_example/data.py | import numpy as np
from skimage import io, color
import torch
from PIL import Image
from torch.utils.data import Dataset, DataLoader, TensorDataset
import torchvision.transforms as T
batch_size = 128
offsets = (47.5, 2.4, 7.4)
scales = (25.6, 11.2, 16.8)
def norm_lab_to_rgb(L, ab, norm=True):
'''given an Nx1xWxH... | 2,479 | 32.972603 | 124 | py |
conditional_INNs | conditional_INNs-master/colorization_minimal_example/eval.py | from os.path import join
import torch
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
from scipy.spatial import distance_matrix
import model
import data
cinn = model.ColorizationCINN(0)
cinn.cuda()
cinn.eval()
state_dict = {k:v for k,v in torch.load('output/lsun_cinn.pt').items() if 'tmp_var... | 2,782 | 30.625 | 106 | py |
conditional_INNs | conditional_INNs-master/colorization_minimal_example/train.py | from time import time
from tqdm import tqdm
import torch
import torch.optim
import numpy as np
import model
import data
cinn = model.ColorizationCINN(1e-3)
cinn.cuda()
scheduler = torch.optim.lr_scheduler.StepLR(cinn.optimizer, 1, gamma=0.1)
N_epochs = 3
t_start = time()
nll_mean = []
print('Epoch\tBatch/Total \tT... | 1,553 | 32.06383 | 97 | py |
conditional_INNs | conditional_INNs-master/colorization_cINN/subnet_coupling.py | from math import exp
import torch
import torch.nn as nn
class subnet_coupling_layer(nn.Module):
def __init__(self, dims_in, dims_c, F_class, subnet, sub_len, F_args={}, clamp=5.):
super().__init__()
channels = dims_in[0][0]
self.ndims = len(dims_in[0])
self.split_len1 = channels //... | 2,321 | 35.857143 | 90 | py |
conditional_INNs | conditional_INNs-master/colorization_cINN/model.py | import warnings
import torch.optim
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from FrEIA.framework import *
from FrEIA.modules import *
from subnet_coupling import *
import data
import config as c
feature_channels = 256
fc_cond_length = 512
n_blocks_fc = 8
outputs = []
conditions = [Co... | 12,161 | 37.487342 | 134 | py |
conditional_INNs | conditional_INNs-master/colorization_cINN/data.py | import sys
import glob
from os.path import join
from multiprocessing import Pool
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, color
from PIL import Image, ImageEnhance
import torch
from torch.utils.data import Dataset, DataLoader, TensorDataset
import torch.nn.functional as F
import torch... | 5,704 | 31.976879 | 144 | py |
conditional_INNs | conditional_INNs-master/colorization_cINN/model_no_cond.py | import torch.optim
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from FrEIA.framework import *
from FrEIA.modules import *
from cbn_layer import *
from subnet_coupling import *
import data
import config as c
n_blocks_fc = 8
outputs = []
conditions = [ConditionNode(1, c.img_dims[0], c.img_d... | 9,387 | 34.161049 | 134 | py |
conditional_INNs | conditional_INNs-master/colorization_cINN/eval.py | #!/usr/bin/env python
'''
Usage: ./eval.py model_checkpoint_file [val_start_index, val_stop_index]
model_checkpoint_file: Path of the checkpoint
optional val_start/stop_index: Only use validation images between these indexes
(Useful for GNU-parallel etc.)
'''
import glob
import... | 20,532 | 34.462867 | 139 | py |
conditional_INNs | conditional_INNs-master/colorization_cINN/feature_net.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
__weights_dict = dict()
def load_weights(weight_file):
if weight_file == None:
return
try:
weights_dict = np.load(weight_file).item()
except:
weights_dict = np.load(weight_file, encoding='bytes')... | 9,641 | 51.118919 | 171 | py |
conditional_INNs | conditional_INNs-master/colorization_cINN/train.py | #!/usr/bin/env python
import sys
import torch
import torch.nn
import torch.optim
from torch.nn.functional import avg_pool2d#, interpolate
from torch.autograd import Variable
import numpy as np
import tqdm
import config as c
if c.no_cond_net:
import model_no_cond as model
else:
import model
import data
impor... | 3,522 | 28.605042 | 101 | py |
conditional_INNs | conditional_INNs-master/mnist_minimal_example/model.py | import torch
import torch.nn as nn
import torch.optim
import FrEIA.framework as Ff
import FrEIA.modules as Fm
ndim_total = 28 * 28
def one_hot(labels, out=None):
'''
Convert LongTensor labels (contains labels 0-9), to a one hot vector.
Can be done in-place using the out-argument (faster, re-use of GPU me... | 1,968 | 30.253968 | 94 | py |
conditional_INNs | conditional_INNs-master/mnist_minimal_example/data.py | import torch
from torch.utils.data import Dataset, DataLoader, TensorDataset
import torchvision.transforms as T
import torchvision.datasets
batch_size = 256
data_mean = 0.128
data_std = 0.305
# amplitude for the noise augmentation
augm_sigma = 0.08
data_dir = 'mnist_data'
def unnormalize(x):
'''go from normaized... | 1,536 | 40.540541 | 124 | py |
conditional_INNs | conditional_INNs-master/mnist_minimal_example/eval.py | import torch
import numpy as np
import matplotlib.pyplot as plt
import model
import data
cinn = model.MNIST_cINN(0)
cinn.cuda()
state_dict = {k:v for k,v in torch.load('output/mnist_cinn.pt').items() if 'tmp_var' not in k}
cinn.load_state_dict(state_dict)
cinn.eval()
def show_samples(label):
'''produces and sho... | 1,355 | 23.214286 | 94 | py |
conditional_INNs | conditional_INNs-master/mnist_minimal_example/train.py | from time import time
from tqdm import tqdm
import torch
import torch.nn
import torch.optim
import numpy as np
import model
import data
cinn = model.MNIST_cINN(5e-4)
cinn.cuda()
scheduler = torch.optim.lr_scheduler.MultiStepLR(cinn.optimizer, milestones=[20, 40], gamma=0.1)
N_epochs = 60
t_start = time()
nll_mean =... | 1,675 | 33.204082 | 97 | py |
bertviz | bertviz-master/setup.py | import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="bertviz",
version="1.4.0",
description="Attention visualizati... | 706 | 29.73913 | 112 | py |
bertviz | bertviz-master/bertviz/model_view.py | import json
import os
import uuid
from IPython.core.display import display, HTML, Javascript
from .util import format_special_chars, format_attention, num_layers, num_heads
def model_view(
attention=None,
tokens=None,
sentence_b_start=None,
prettify_tokens=True,
display_mode=... | 11,267 | 44.072 | 132 | py |
bertviz | bertviz-master/bertviz/util.py | import torch
def format_attention(attention, layers=None, heads=None):
if layers:
attention = [attention[layer_index] for layer_index in layers]
squeezed = []
for layer_attention in attention:
# 1 x num_heads x seq_len x seq_len
if len(layer_attention.shape) != 4:
raise... | 995 | 31.129032 | 118 | py |
bertviz | bertviz-master/bertviz/head_view.py | import json
import os
import uuid
from IPython.core.display import display, HTML, Javascript
from .util import format_special_chars, format_attention, num_layers
def head_view(
attention=None,
tokens=None,
sentence_b_start=None,
prettify_tokens=True,
layer=None,
heads... | 10,699 | 43.957983 | 132 | py |
bertviz | bertviz-master/bertviz/neuron_view.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | 12,114 | 41.508772 | 185 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_utils.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | 47,514 | 50.534707 | 480 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | 66,824 | 52.247012 | 187 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_gpt2.py | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... | 36,835 | 48.245989 | 136 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_openai.py | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... | 34,785 | 47.516039 | 140 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/tokenization_bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | 20,131 | 43.441501 | 183 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/file_utils.py | """
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
import sys
import json
import logging
import os
impor... | 9,100 | 33.604563 | 112 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_transfo_xl.py | # coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | 58,612 | 41.814463 | 157 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_xlnet.py | # coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | 63,906 | 48.387172 | 169 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.