repo
stringlengths
2
99
file
stringlengths
14
239
code
stringlengths
20
3.99M
file_length
int64
20
3.99M
avg_line_length
float64
9.73
128
max_line_length
int64
11
86.4k
extension_type
stringclasses
1 value
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/codecs/text_codec/tokenize.py
import torch import torch.nn as nn from image_synthesis.modeling.modules.clip.clip import tokenize from image_synthesis.modeling.codecs.base_codec import BaseCodec from image_synthesis.utils.misc import instantiate_from_config class Tokenize(BaseCodec): def __init__(self, context_length:int = 256, ...
3,124
36.202381
104
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/models/conditional_dalle.py
# VQ-Diffusion import torch import math from torch import nn from image_synthesis.utils.misc import instantiate_from_config import time import numpy as np from PIL import Image import os from torch.cuda.amp import autocast class C_DALLE(nn.Module): def __init__( self, *, content_info={'ke...
11,968
40.559028
154
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/models/unconditional_dalle.py
# VQ-Diffusion import torch import math from torch import nn from image_synthesis.utils.misc import instantiate_from_config import time import numpy as np from PIL import Image import os from torch.cuda.amp import autocast class UC_DALLE(nn.Module): def __init__( self, *, content_info={'k...
8,216
35.52
138
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/models/dalle.py
# VQ-Diffusion import torch import math from torch import nn from image_synthesis.utils.misc import instantiate_from_config import time import numpy as np from PIL import Image import os from torch.cuda.amp import autocast class DALLE(nn.Module): def __init__( self, *, content_info={'key'...
14,512
43.246951
154
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/embeddings/class_embedding.py
import torch import torch.nn as nn from .base_embedding import BaseEmbedding class ClassEmbedding(BaseEmbedding): def __init__(self, num_embed=1000, embed_dim=512, identity=False, trainable=True, ): super().__init__() self...
899
26.272727
74
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/embeddings/dalle_mask_image_embedding.py
import torch import torch.nn as nn from .base_embedding import BaseEmbedding class DalleMaskImageEmbedding(BaseEmbedding): def __init__(self, num_embed=8192, spatial_size=[32, 32], # height and with embed_dim=3968, trainable=True, ...
2,507
42.241379
173
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/embeddings/base_embedding.py
import torch from torch import nn class BaseEmbedding(nn.Module): def get_loss(self): return None def forward(self, **kwargs): raise NotImplementedError def train(self, mode=True): self.training = mode if self.trainable and mode: super().train() retur...
507
19.32
49
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/embeddings/clip_text_embedding.py
import torch import torch.nn as nn from image_synthesis.modeling.modules.clip import clip from image_synthesis.modeling.modules.clip import model as clip_model from .base_embedding import BaseEmbedding class CLIPTextEmbedding(BaseEmbedding): def __init__(self, clip_name='ViT-B/32', ...
3,423
37.47191
121
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/utils/misc.py
from numpy.core.fromnumeric import resize from numpy.lib.function_base import kaiser from numpy.lib.npyio import save import torch import random import math from image_synthesis.distributed.distributed import all_reduce, get_world_size def logits_top_k(logits, filter_ratio = 0.5, minimum=1, pad_value=None): logits...
5,282
32.01875
114
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/transformers/diffusion_transformer.py
# VQ-Diffusion import math import torch from torch import nn import torch.nn.functional as F from image_synthesis.utils.misc import instantiate_from_config import numpy as np from einops import rearrange from image_synthesis.distributed.distributed import is_primary, get_rank from inspect import isfunction from torc...
29,919
42.678832
166
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/modeling/transformers/transformer_utils.py
# VQ-Diffusion import math import torch from torch import nn import torch.nn.functional as F from image_synthesis.utils.misc import instantiate_from_config import numpy as np from einops import rearrange from image_synthesis.distributed.distributed import is_primary, get_rank from inspect import isfunction from torc...
30,407
41
131
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/lr_scheduler.py
import numpy as np class LambdaWarmUpCosineScheduler: """ note: use with a base_lr of 1.0 """ def __init__(self, warm_up_steps, lr_min, lr_max, lr_start, max_decay_steps, verbosity_interval=0): self.lr_warm_up_steps = warm_up_steps self.lr_start = lr_start self.lr_min = lr_min ...
1,205
33.457143
114
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/util.py
import os, hashlib import requests from tqdm import tqdm URL_MAP = { "vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1" } CKPT_MAP = { "vgg_lpips": "vgg.pth" } MD5_MAP = { "vgg_lpips": "d507d7349b931f0638a25a48a722f98a" } def download(url, local_path, chunk_size=1024): os....
4,777
29.240506
85
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/util.py
import torch import torch.nn as nn def count_params(model): total_params = sum(p.numel() for p in model.parameters()) return total_params class ActNorm(nn.Module): def __init__(self, num_features, logdet=False, affine=True, allow_reverse_init=False): assert affine super(...
3,847
28.374046
85
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/vqvae/quantize.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch import einsum from einops import rearrange class VectorQuantizer(nn.Module): """ see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py _____________________...
13,259
39.181818
110
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/discriminator/model.py
import functools import torch.nn as nn from image_synthesis.taming.modules.util import ActNorm def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight...
2,566
36.75
116
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/misc/coord.py
import torch class CoordStage(object): def __init__(self, n_embed, down_factor): self.n_embed = n_embed self.down_factor = down_factor def eval(self): return self def encode(self, c): """fake vqmodel interface""" assert 0.0 <= c.min() and c.max() <= 1.0 b,c...
904
27.28125
79
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/diffusionmodules/model.py
# pytorch_diffusion + derived encoder decoder import math import torch import torch.nn as nn import numpy as np def get_timestep_embedding(timesteps, embedding_dim): """ This matches the implementation in Denoising Diffusion Probabilistic Models: From Fairseq. Build sinusoidal embeddings. This mat...
30,221
37.895753
121
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/transformer/mingpt.py
""" taken from: https://github.com/karpathy/minGPT/ GPT model: - the initial stem consists of a combination of token encoding and a positional encoding - the meat of it is a uniform sequence of Transformer blocks - each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block...
15,743
40.10705
140
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/transformer/permuter.py
import torch import torch.nn as nn import numpy as np class AbstractPermuter(nn.Module): def __init__(self, *args, **kwargs): super().__init__() def forward(self, x, reverse=False): raise NotImplementedError class Identity(AbstractPermuter): def __init__(self): super().__init__()...
7,093
27.48996
83
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/losses/lpips.py
"""Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models""" import torch import torch.nn as nn from torchvision import models from collections import namedtuple from image_synthesis.taming.util import get_ckpt_path class LPIPS(nn.Module): # Learned perceptual metric def __...
4,778
38.172131
104
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/losses/segmentation.py
import torch.nn as nn import torch.nn.functional as F class BCELoss(nn.Module): def forward(self, prediction, target): loss = F.binary_cross_entropy_with_logits(prediction,target) return loss, {} class BCELossWithQuant(nn.Module): def __init__(self, codebook_weight=1.): super().__ini...
816
34.521739
82
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/modules/losses/vqperceptual.py
import torch import torch.nn as nn import torch.nn.functional as F from image_synthesis.taming.modules.losses.lpips import LPIPS from image_synthesis.taming.modules.discriminator.model import NLayerDiscriminator, weights_init class DummyLoss(nn.Module): def __init__(self): super().__init__() def adopt_...
6,211
44.343066
113
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/models/vqgan.py
import torch import torch.nn.functional as F import pytorch_lightning as pl from image_synthesis.utils.misc import instantiate_from_config from image_synthesis.taming.modules.diffusionmodules.model import Encoder, Decoder from image_synthesis.taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer fr...
10,554
39.28626
120
py
VQ-Diffusion
VQ-Diffusion-main/image_synthesis/taming/models/cond_transformer.py
import os, math import torch import torch.nn.functional as F import pytorch_lightning as pl from image_synthesis.utils.misc import instantiate_from_config from image_synthesis.taming.modules.util import SOSProvider def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure trai...
15,049
42.75
127
py
VQ-Diffusion
VQ-Diffusion-main/running_command/run_train_ffhq.py
import os string = "python train.py --name ffhq_train --config_file configs/ffhq.yaml --num_node 1 --tensorboard" os.system(string)
135
18.428571
103
py
VQ-Diffusion
VQ-Diffusion-main/running_command/run_tune_coco.py
import os string = "python train.py --name coco_tune --config_file configs/coco_tune.yaml --num_node 1 --tensorboard --load_path OUTPUT/pretrained_model/COCO_pretrained.pth" os.system(string)
195
27
163
py
VQ-Diffusion
VQ-Diffusion-main/running_command/run_train_imagenet.py
import os string = "python train.py --name imagenet_train --config_file configs/imagenet.yaml --num_node 1 --tensorboard" os.system(string)
143
19.571429
111
py
VQ-Diffusion
VQ-Diffusion-main/running_command/run_train_coco.py
import os string = "python train.py --name coco_train --config_file configs/coco.yaml --num_node 1 --tensorboard --load_path OUTPUT/pretrained_model/CC_pretrained.pth" os.system(string)
189
26.142857
157
py
VQ-Diffusion
VQ-Diffusion-main/running_command/run_train_cub.py
import os string = "python train.py --name cub200_train --config_file configs/cub200.yaml --num_node 1 --tensorboard --load_path OUTPUT/pretrained_model/CC_pretrained.pth" os.system(string)
193
26.714286
161
py
Reflect
Reflect-master/mnist_trainer.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags from util.models import MODELS from util.tasks import TASKS FLAGS = flags.FLAGS flags.DEFINE_...
2,498
31.454545
153
py
Reflect
Reflect-master/keras_trainer.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags from util.models import MODELS from util.tasks import TASKS FLAGS = flags.FLAGS flags.DEFINE_...
2,688
34.381579
153
py
Reflect
Reflect-master/util/text_util.py
from collections import Counter import csv import subprocess from util import inflect import pandas as pd from statsmodels.stats.proportion import proportion_confint infl_eng = inflect.engine() dependency_fields = ['sentence', 'orig_sentence', 'pos_sentence', 'subj', 'verb', 'subj_pos', 'has_rel',...
4,707
30.178808
77
py
Reflect
Reflect-master/util/constants.py
pad = '<pad>' unk = '<unk>' bos = '<bos>' eos = '<eos>' pad_idx = 0 unk_idx = 1 bos_idx = 2 eos_idx = 3 all = [pad, unk, bos, eos]
132
11.090909
26
py
Reflect
Reflect-master/util/inflect.py
''' inflect.py: correctly generate plurals, ordinals, indefinite articles; convert numbers to words Copyright (C) 2010 Paul Dyson Based upon the Perl module Lingua::EN::Inflect by Damian Conway. This program is free software: you can redistribute it and/or modify it under the terms o...
94,476
30.273419
106
py
Reflect
Reflect-master/util/models.py
from tf2_models.capnet import Capsule from tf2_models.cnn import VanillaCNN from tf2_models.ff import VanillaFF from tf2_models.ff_resnet import FFResnet from tf2_models.lm_lstm import LmLSTM, LmLSTMSharedEmb, ClassifierLSTM, LmLSTMSharedEmbV2 from tf2_models.lm_transformer import LmGPT2, LmGPT2SharedWeights, Classifie...
1,068
41.76
113
py
Reflect
Reflect-master/util/tasks.py
from tasks.lm1b import Lm1B from tasks.mnist import Mnist, AffNistTask, Svhn, Mnist40 from tasks.smallnorb import SmallNorb from tasks.sst import ClassifySST2, LmSST2 from tasks.sv_agreement import SvAgreementLM, WordSvAgreementLM, WordSvAgreementVP from tasks.wiki import WikiLM TASKS = { 'sv_agreement_lm': SvAgreem...
606
27.904762
82
py
Reflect
Reflect-master/distill/offline_repshare.py
import tensorflow as tf import os from distill.distiller import Distiller from distill.online_distiller import OnlineDistiller from distill.repsim_util import get_reps from tf2_models.train_utils import ExponentialDecayWithWarmpUp from tf2_models.trainer import OPTIMIZER_DIC from tf2_models.utils import camel2snake fro...
6,270
42.248276
128
py
Reflect
Reflect-master/distill/repsim_util.py
import tensorflow as tf import numpy as np def get_reps(outputs, index=1, layer=-1, **kwargs): """ If Model is LSTM: 1: final_rnn_outputs, 2: hidden_activation (for all layers, including input embeddings) reduction: None, "last", "sum" """ logits = outputs[0] outputs = tf.tuple(outputs) rep...
3,444
31.5
110
py
Reflect
Reflect-master/distill/online_distiller.py
import tensorflow as tf import os from distill.distill_util import get_distill_scheduler from distill.distiller import Distiller from tf2_models.train_utils import ExponentialDecayWithWarmpUp from tf2_models.trainer import OPTIMIZER_DIC from tf2_models.utils import camel2snake from inspect import isfunction import num...
9,001
43.127451
132
py
Reflect
Reflect-master/distill/model.py
class Model(object): def apply(self, examples): raise NotImplementedError def update(self, loss): raise NotImplementedError
136
21.833333
29
py
Reflect
Reflect-master/distill/distill_main.py
''' Code to apply the distillation process for a teacher and a student model. Run: python distill/distill_main.py \ --task=word_sv_agreement_vp \ --teacher_exp_name=small_lstm_v4_0.0001_withl2 \ --teacher_model=cl_lstm \ --teacher_config=small_lstm_v4 \ --student_exp_name=distilled0 \ --student_model=cl_gpt2 \ --stude...
5,174
47.820755
136
py
Reflect
Reflect-master/distill/distill_mnist.py
''' Code to apply the distillation process for a teacher and a student model. Run: python distill/distill_main.py \ --task=word_sv_agreement_vp \ --teacher_exp_name=small_lstm_v4_0.0001_withl2 \ --teacher_model=cl_lstm \ --teacher_config=small_lstm_v4 \ --student_exp_name=distilled0 \ --student_model=cl_gpt2 \ --stude...
4,778
47.272727
136
py
Reflect
Reflect-master/distill/distill_util.py
import tensorflow as tf from tf2_models.metrics import distill_loss, sequence_distill_loss @tf.function(experimental_relax_shapes=True) def get_topk_mask(inputs, k): inputs_shape = tf.shape(inputs) inputs_shape = tf.cast(inputs_shape, dtype=tf.int64) values, indices = tf.nn.top_k(inputs, k=k, sorted=False) i...
3,653
35.54
110
py
Reflect
Reflect-master/distill/distiller.py
import tensorflow as tf import os from distill.distill_util import get_distill_scheduler from tf2_models.train_utils import ExponentialDecayWithWarmpUp from tf2_models.trainer import OPTIMIZER_DIC import numpy as np class Distiller(object): ''' Pipeline for offline distillation. ''' def __init__(self, hparams,...
9,284
44.292683
132
py
Reflect
Reflect-master/tf2_models/embedding.py
import tensorflow as tf from tf2_models.common_layers import get_initializer, shape_list class SharedEmbeddings(tf.keras.layers.Layer): """Construct shared token embeddings. """ def __init__(self, vocab_size, hidden_size, initializer_range=None, regularizer=None, **kwargs): super(SharedEmbeddings, self)._...
2,633
38.313433
137
py
Reflect
Reflect-master/tf2_models/lm_transformer.py
import tensorflow as tf from tf2_models.common_layers import get_initializer, shape_list from tf2_models.embedding import SharedEmbeddings from tf2_models.transformer_layers import Block from tf2_models.transformers import * class LmGPT2(tf.keras.Model): def __init__(self, hparams, scope='lm_gpt2', *inputs, **kwargs...
10,814
39.965909
109
py
Reflect
Reflect-master/tf2_models/ff.py
import tensorflow as tf import numpy as np class VanillaFF(tf.keras.models.Sequential): def __init__(self, hparams, scope="cl_vff", *inputs, **kwargs): if 'cl_token' in kwargs: del kwargs['cl_token'] super(VanillaFF, self).__init__() self.scope = scope self.hparams = hparams self.model_n...
3,116
36.107143
92
py
Reflect
Reflect-master/tf2_models/common_layers.py
import tensorflow as tf import numpy as np from tensorflow.python.framework import tensor_shape from tensorflow.python.util import nest def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform ac...
3,398
34.041237
72
py
Reflect
Reflect-master/tf2_models/lm_lstm.py
import absl import tensorflow as tf import numpy as np from tensorboard.compat.tensorflow_stub import tensor_shape from tensorflow.python.util import nest from tf2_models.common_layers import get_initializer from tf2_models.embedding import SharedEmbeddings from tf2_models.utils import create_init_var class LmLSTM(tf...
23,117
47.364017
138
py
Reflect
Reflect-master/tf2_models/transformers.py
import tensorflow as tf from tf2_models.common_layers import get_initializer, shape_list from tf2_models.embedding import SharedEmbeddings from tf2_models.transformer_layers import Block class GPT2(tf.keras.layers.Layer): def __init__(self, hparams, *inputs, **kwargs): super(GPT2, self).__init__(hparams, *input...
16,938
40.619165
113
py
Reflect
Reflect-master/tf2_models/resnet.py
import tensorflow as tf class ResnetBlock(tf.keras.layers.Layer): def __init__(self, filters, kernel_size, activation='relu',*inputs, **kwargs): super(ResnetBlock, self).__init__(*inputs, **kwargs) self.filters = filters self.kernel_size = kernel_size self.activation = activation self.regularizer...
6,572
40.601266
94
py
Reflect
Reflect-master/tf2_models/cnn.py
import tensorflow as tf import numpy as np def max_out(inputs, num_units, axis=None): shape = inputs.get_shape().as_list() if shape[0] is None: shape[0] = -1 if axis is None: # Assume that channel is the last dimension axis = -1 num_channels = shape[axis] if num_channels % num_units: raise Valu...
5,878
38.993197
91
py
Reflect
Reflect-master/tf2_models/utils.py
import tensorflow as tf import re from tensorboard.compat.tensorflow_stub import tensor_shape def camel2snake(name): return name[0].lower() + re.sub(r'(?!^)[A-Z]', lambda x: '_' + x.group(0).lower(), name[1:]) def log_summary(log_value, log_name, summary_scope): """Produce scalar summaries.""" with tf.compat....
884
31.777778
99
py
Reflect
Reflect-master/tf2_models/train_utils.py
import absl import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.keras.optimizer_v2.learning_rate_schedule import LearningRateSchedule from tensorflow.python.ops import math_ops from tensorflow.python.util.tf_export import keras_export from tensorflow_addons.utils import keras_uti...
17,416
40.568019
92
py
Reflect
Reflect-master/tf2_models/transformer_layers.py
import tensorflow as tf from tf2_models.common_layers import get_initializer, shape_list, gelu class Attention(tf.keras.layers.Layer): def __init__(self, hidden_dim, n_ctx, config, regularizer, casual_masking=True, scale=False, **kwargs): super(Attention, self).__init__(**kwargs) self.output_attentions = c...
6,560
35.049451
105
py
Reflect
Reflect-master/tf2_models/ff_resnet.py
import tensorflow as tf class FFResnetBlock(tf.keras.layers.Layer): def __init__(self, filters, kernel_size, activation='relu',*inputs, **kwargs): super(FFResnetBlock, self).__init__(*inputs, **kwargs) self.filters = filters self.kernel_size = kernel_size self.activation = activation self.regular...
6,118
39.256579
96
py
Reflect
Reflect-master/tf2_models/keras_callbacks.py
import tensorflow as tf from tf2_models.utils import log_summary class CheckpointCallback(tf.keras.callbacks.Callback): def __init__(self, manager, ckpt): super(CheckpointCallback, self).__init__() self.manager = manager self.ckpt = ckpt def on_epoch_end(self, epoch, logs=None): self.ckpt.step....
1,859
38.574468
148
py
Reflect
Reflect-master/tf2_models/metrics.py
import tensorflow as tf @tf.function(experimental_relax_shapes=True) def distill_loss(y_true, y_pred, tmp): y_true = tf.cast(tf.squeeze(y_true), dtype=tf.float32) scale_factor = 1.0 / (tmp*tmp) return tf.reduce_mean(tf.compat.v2.nn.softmax_cross_entropy_with_logits(logits=y_pred / tmp, ...
10,276
46.578704
117
py
Reflect
Reflect-master/tf2_models/trainer.py
import tensorflow as tf import os from tf2_models.keras_callbacks import CheckpointCallback, SummaryCallback from tf2_models.train_utils import RectifiedAdam, ExponentialDecayWithWarmpUp OPTIMIZER_DIC = {'adam': tf.keras.optimizers.Adam, 'radam': RectifiedAdam, } class Trainer(object)...
3,931
39.536082
122
py
Reflect
Reflect-master/tfds_data/tal_agreement.py
from collections import Counter import tensorflow as tf import tensorflow_datasets as tfds import os import numpy as np from tensorflow_datasets.core.features.text import Tokenizer from tensorflow_datasets.core.features.text.text_encoder import write_lines_to_file, read_lines_from_file from prep_data.build_dictionary...
8,680
35.020747
106
py
Reflect
Reflect-master/tasks/task.py
import tensorflow as tf from distill.distill_util import get_masked_probs from distill.repsim_util import rep_loss from util import constants class Task(object): def __init__(self, task_params, num_replicas_in_sync=1, builder_cls=None, name='abstract_task', data_dir='data', output_padding=False): self.name = na...
6,704
47.586957
142
py
Reflect
Reflect-master/tasks/sv_agreement.py
import functools from distill.distill_util import DistillLoss, get_probs, SequenceDistillLoss, get_topk_masked_probs, get_masked_probs from tasks.task import Task import tensorflow as tf from tf2_models import metrics from tf2_models.metrics import masked_batch_perplexity, masked_perplexity, \ MaskedSequenceLoss, C...
5,424
44.208333
163
py
Reflect
Reflect-master/tasks/mnist.py
from distill.distill_util import DistillLoss, get_probs from tasks.task import Task import tensorflow as tf import tensorflow_datasets as tfds from tf2_models.metrics import ClassificationLoss from tfds_data.aff_nist import AffNist class Mnist(Task): def __init__(self, task_params, name='mnist', data_dir='mnist_da...
8,663
37.678571
103
py
Reflect
Reflect-master/tasks/evaluations/lm_sv_agreement_eval.py
''' Evaluate word based language models on the subject verb agreement task. Codes adapted from: Example Run: python tasks/evaluations/lm_sv_agreement_eval.py \ --exp_name=lisa_fd4 \ --model_name=lm_gpt2 \ --model_config=very_big_gpt_v10 \ --train_config=adam_slow \ --prefix=offline_pure_distill_2_teacher_lm_lstm_shar...
6,755
36.955056
135
py
Reflect
Reflect-master/notebooks/notebook_utils.py
import tensorflow as tf import numpy as np import os from tqdm import tqdm from util import constants from collections import Counter from util.models import MODELS from util.tasks import TASKS from util.config_util import get_model_params, get_task_params, get_train_params import matplotlib.pyplot as plt import pandas...
10,989
36.508532
153
py
Reflect
Reflect-master/notebooks/calibration_util.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS import tensorflo...
3,258
38.26506
100
py
Reflect
Reflect-master/notebooks/eval_scripts/eval_vp.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS from notebook_ut...
5,193
28.68
139
py
Reflect
Reflect-master/notebooks/eval_scripts/eval_vp-bert.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS from notebook_ut...
19,508
33.962366
137
py
Reflect
Reflect-master/notebooks/eval_scripts/eval_vp-ugpt.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS from notebook_ut...
19,655
33.851064
139
py
Reflect
Reflect-master/notebooks/eval_scripts/eval_vp-lstm.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS from notebook_ut...
7,129
32.009259
139
py
Reflect
Reflect-master/notebooks/eval_scripts/eval_full_sv_cl.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS from notebook_ut...
4,451
29.285714
108
py
Reflect
Reflect-master/notebooks/eval_scripts/eval_lm.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS from notebook_ut...
2,524
28.360465
86
py
Reflect
Reflect-master/notebooks/eval_scripts/eval_full_sv_cl_gpt2.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS from notebook_ut...
4,517
29.322148
108
py
Reflect
Reflect-master/notebooks/eval_scripts/eval_full_sv_cl_bert.py
import os import tensorflow as tf from util import constants from util.config_util import get_model_params, get_task_params, get_train_params from tf2_models.trainer import Trainer from absl import app from absl import flags import numpy as np from util.models import MODELS from util.tasks import TASKS from notebook_ut...
4,447
29.258503
108
py
Reflect
Reflect-master/prep_data/split.py
import sys import os import errno import random from util.text_util import deps_from_tsv, deps_to_tsv def make_splits(fname, expr_dir, prop_train=0.1, prop_valid=0.01): # for reproducibility random.seed(42) print('| read in the data') data = deps_from_tsv(fname) print('| shuffling') random.sh...
947
25.333333
66
py
Reflect
Reflect-master/prep_data/gen_bowman_logic.py
from itertools import chain from itertools import combinations from collections import Counter import random def powerset(iterable): s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) def get_candidate_worlds(num_vars): return powerset(set(range(num_vars))) de...
5,553
28.386243
77
py
Reflect
Reflect-master/prep_data/build_dictionary.py
from util import text_util as utils from util import constants from sys import argv import numpy as np import os def build_and_save_dic(input_file, data_dir): worddict = {} worddict[constants.pad] = constants.pad_idx worddict[constants.unk] = constants.unk_idx worddict[constants.bos] = constants.bos_i...
969
26.714286
51
py
PyKrige
PyKrige-main/setup.py
"""Kriging Toolkit for Python.""" import os import numpy as np from Cython.Build import cythonize from setuptools import Extension, setup # cython extensions CY_MODULES = [ Extension( name=f"pykrige.{ext}", sources=[os.path.join("src", "pykrige", *ext.split(".")) + ".pyx"], include_dirs=[n...
634
27.863636
75
py
PyKrige
PyKrige-main/benchmarks/kriging_benchmarks.py
"""Benchmarks.""" from time import time import numpy as np from pykrige.ok import OrdinaryKriging np.random.seed(19999) VARIOGRAM_MODELS = ["power", "gaussian", "spherical", "exponential", "linear"] BACKENDS = ["vectorized", "loop", "C"] N_MOVING_WINDOW = [None, 10, 50, 100] def make_benchark(n_train, n_test, n_d...
3,473
27.47541
88
py
PyKrige
PyKrige-main/examples/06_exact_values_example_1D.py
""" Exact Values ============ PyKrige demonstration and usage as a non-exact interpolator in 1D. """ import matplotlib.pyplot as plt import numpy as np from pykrige.ok import OrdinaryKriging plt.style.use("ggplot") np.random.seed(42) x = np.linspace(0, 12.5, 50) xpred = np.linspace(0, 12.5, 393) y = np.sin(x) * ...
1,375
21.557377
77
py
PyKrige
PyKrige-main/examples/00_ordinary.py
""" Ordinary Kriging Example ======================== First we will create a 2D dataset together with the associated x, y grids. """ import matplotlib.pyplot as plt import numpy as np import pykrige.kriging_tools as kt from pykrige.ok import OrdinaryKriging data = np.array( [ [0.3, 1.2, 0.47], ...
1,840
30.20339
84
py
PyKrige
PyKrige-main/examples/07_regression_kriging2d.py
""" Regression kriging ------------------ An example of regression kriging """ import sys from sklearn.datasets import fetch_california_housing from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.svm im...
1,368
28.76087
81
py
PyKrige
PyKrige-main/examples/10_classification_kriging2d.py
""" Classification kriging ---------------------- An example of classification kriging """ import sys from sklearn.datasets import fetch_california_housing from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from...
1,566
29.72549
86
py
PyKrige
PyKrige-main/examples/01_universal.py
""" Universal Kriging Example ========================= In this example we apply a regional linear trend to the kriging system. """ import matplotlib.pyplot as plt import numpy as np from pykrige.uk import UniversalKriging data = np.array( [ [0.3, 1.2, 0.47], [1.9, 0.6, 0.56], [1.1, 3.2...
1,475
27.941176
84
py
PyKrige
PyKrige-main/examples/08_krige_cv.py
""" Krige CV -------- Searching for optimal kriging parameters with cross validation """ import numpy as np from sklearn.model_selection import GridSearchCV from pykrige.rk import Krige # 2D Kring param opt param_dict = { "method": ["ordinary", "universal"], "variogram_model": ["linear", "power", "gaussian...
1,951
23.708861
86
py
PyKrige
PyKrige-main/examples/02_kriging3D.py
""" Three-Dimensional Kriging Example ================================= """ import numpy as np from matplotlib import pyplot as plt from pykrige.ok3d import OrdinaryKriging3D from pykrige.uk3d import UniversalKriging3D data = np.array( [ [0.1, 0.1, 0.3, 0.9], [0.2, 0.1, 0.4, 0.8], [0.1, ...
3,514
32.47619
85
py
PyKrige
PyKrige-main/examples/05_kriging_1D.py
""" 1D Kriging ========== An example of 1D kriging with PyKrige """ import matplotlib.pyplot as plt import numpy as np from pykrige import OrdinaryKriging plt.style.use("ggplot") # fmt: off # Data taken from X, y = np.array([ [-5.01, 1.06], [-4.90, 0.92], [-4.82, 0.35], [-4.69, 0.49], [-4.56, 0.52], [-4.5...
2,626
36
79
py
PyKrige
PyKrige-main/examples/04_krige_geometric.py
""" Geometric example ================= A small example script showing the usage of the 'geographic' coordinates type for ordinary kriging on a sphere. """ import numpy as np from matplotlib import pyplot as plt from pykrige.ok import OrdinaryKriging # Make this example reproducible: np.random.seed(89239413) # Gen...
2,636
31.555556
79
py
PyKrige
PyKrige-main/examples/03_gstools_covmodel.py
""" GSTools Interface ================= Example how to use the PyKrige routines with a GSTools CovModel. """ import gstools as gs import numpy as np from matplotlib import pyplot as plt from pykrige.ok import OrdinaryKriging # conditioning data data = np.array( [ [0.3, 1.2, 0.47], [1.9, 0.6, 0.56...
844
23.852941
87
py
PyKrige
PyKrige-main/src/pykrige/ok.py
""" PyKrige ======= Code by Benjamin S. Murphy and the PyKrige Developers bscott.murphy@gmail.com Summary ------- Contains class OrdinaryKriging, which provides easy access to 2D Ordinary Kriging. References ---------- .. [1] P.K. Kitanidis, Introduction to Geostatistcs: Applications in Hydrogeology, (Cambridge ...
42,554
40.679726
88
py
PyKrige
PyKrige-main/src/pykrige/compat_gstools.py
# pylint: disable= invalid-name, unused-import """For GSTools compatibility.""" # gstools try: import gstools as gs GSTOOLS_INSTALLED = True GSTOOLS_VERSION = list(map(int, gs.__version__.split(".")[:2])) except ImportError: gs = None GSTOOLS_INSTALLED = False GSTOOLS_VERSION = None class G...
1,062
27.72973
85
py
PyKrige
PyKrige-main/src/pykrige/uk.py
""" PyKrige ======= Code by Benjamin S. Murphy and the PyKrige Developers bscott.murphy@gmail.com Summary ------- Contains class UniversalKriging, provides greater control over 2D kriging by utilizing drift terms. References ---------- .. [1] P.K. Kitanidis, Introduction to Geostatistcs: Applications in Hydrogeo...
56,799
41.706767
87
py
PyKrige
PyKrige-main/src/pykrige/core.py
""" PyKrige ======= Code by Benjamin S. Murphy and the PyKrige Developers bscott.murphy@gmail.com Summary ------- Methods used by multiple classes. References ---------- [1] P.K. Kitanidis, Introduction to Geostatistcs: Applications in Hydrogeology, (Cambridge University Press, 1997) 272 p. [2] T. Vincenty, Dir...
30,289
33.538198
88
py
PyKrige
PyKrige-main/src/pykrige/uk3d.py
""" PyKrige ======= Code by Benjamin S. Murphy and the PyKrige Developers bscott.murphy@gmail.com Summary ------- Contains class UniversalKriging3D. References ---------- .. [1] P.K. Kitanidis, Introduction to Geostatistcs: Applications in Hydrogeology, (Cambridge University Press, 1997) 272 p. .. [2] N. Cressie...
49,151
41.852659
88
py
PyKrige
PyKrige-main/src/pykrige/ok3d.py
""" PyKrige ======= Code by Benjamin S. Murphy and the PyKrige Developers bscott.murphy@gmail.com Summary ------- Contains class OrdinaryKriging3D. References ---------- .. [1] P.K. Kitanidis, Introduction to Geostatistcs: Applications in Hydrogeology, (Cambridge University Press, 1997) 272 p. .. [2] N. Cressie,...
39,816
41.676313
88
py
PyKrige
PyKrige-main/src/pykrige/rk.py
"""Regression Kriging.""" from pykrige.compat import Krige, check_sklearn_model, validate_sklearn validate_sklearn() from sklearn.metrics import r2_score from sklearn.svm import SVR class RegressionKriging: """ An implementation of Regression-Kriging. As described here: https://en.wikipedia.org/wik...
5,982
30.994652
86
py
PyKrige
PyKrige-main/src/pykrige/variogram_models.py
""" PyKrige ======= Code by Benjamin S. Murphy and the PyKrige Developers bscott.murphy@gmail.com Summary ------- Function definitions for variogram models. In each function, m is a list of defining parameters and d is an array of the distance values at which to calculate the variogram model. References ---------- ....
2,092
24.52439
83
py
PyKrige
PyKrige-main/src/pykrige/ck.py
"""Classification Kriging.""" import numpy as np from pykrige.compat import Krige, check_sklearn_model, validate_sklearn validate_sklearn() from scipy.linalg import helmert from sklearn.metrics import accuracy_score from sklearn.preprocessing import OneHotEncoder from sklearn.svm import SVC class ClassificationKri...
9,458
31.393836
106
py
PyKrige
PyKrige-main/src/pykrige/compat.py
# pylint: disable= invalid-name, unused-import """For compatibility.""" from pykrige.ok import OrdinaryKriging from pykrige.ok3d import OrdinaryKriging3D from pykrige.uk import UniversalKriging from pykrige.uk3d import UniversalKriging3D # sklearn try: # keep train_test_split here for backward compatibility f...
9,889
31.11039
88
py