python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
# define the grammar # cf https://docs.google.com/presentation/d/1gzC878kkIgDL015c-kLFXEBc1SAuq_XOsheQowsyIEA/edit?usp=sharing ##### ## define node types class InternalNode(Object): def __init__(self, name): self.name = name self.node_choices = [] self.intern_no...
craftassist-master
acl2020_submission/writeup/figures/acl_tree.py
# 'location', 'move' # 'reference_object', 'spawn' # 'reference_object', 'destroy' # 'schematic', 'dig' # 'reference_object', fill # 'reference_object', 'OtherAction' # 'location', 'OtherAction' # 'target_action_type', 'stop' # 'target_action_type', 'resume' # 'target_action_type', 'undo' LOCATION_RADIO = [ {"text...
craftassist-master
acl2020_submission/annotation_tools/tools/question_flow_for_step_2.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ MAX_WORDS = 30 CSS_SCRIPT = """ <script> var node = document.createElement('style'); """ for j in range(1, 4): for i in range(MAX_WORDS): CSS_SCRIPT += """ if (! "${{word{j}{i}}}") {{ node.innerHTML += '.word{j}{i} {{ dis...
craftassist-master
acl2020_submission/annotation_tools/tools/qualification_tool.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import re def render_q(q, parent_id, show=True, show_siblings=True, sentence_id=""): """Return a fieldset for the given question""" assert "key" in q, "Missing key for q: {}".format(q) q_id = "{}.{}".format(parent_id, q["key"]) r = "" r += ...
craftassist-master
acl2020_submission/annotation_tools/tools/render_questions_tool_1.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ BEFORE = """ <!-- Bootstrap v3.0.3 --> <link href="https://s3.amazonaws.com/mturk-public/bs30/css/bootstrap.min.css" rel="stylesheet" /> <section class="container" id="Other" style="margin-bottom:15px; padding: 10px 10px; font-family: Verdana, Geneva, sans-ser...
craftassist-master
acl2020_submission/annotation_tools/tools/composite_command_tool.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ from collections import Counter, defaultdict import argparse import ast right_answer_count = Counter() wrong_answer_count = Counter() # compile sets of allowed answers allowed_answers = defaultdict(set) command = None def read_gold_set(gold_set): command...
craftassist-master
acl2020_submission/annotation_tools/tools/evaluate_qualification.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ MAX_WORDS = 40 CSS_SCRIPT = """ <script> var node = document.createElement('style'); """ for i in range(MAX_WORDS): CSS_SCRIPT += """ if (! "${{word{i}}}") {{ node.innerHTML += '.word{i} {{ display: none }} ' }} """.format( ...
craftassist-master
acl2020_submission/annotation_tools/tools/annotation_tool_1.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import argparse from annotation_tool_1 import MAX_WORDS def print_csv_format(filename, option_num): if option_num == 1: # level 1 print("command", *["word{}".format(i) for i in range(MAX_WORDS)], sep=",") with open(filename) as f: ...
craftassist-master
acl2020_submission/annotation_tools/tools/construct_input_for_turk.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ MAX_WORDS = 40 CSS_SCRIPT = """ <script> var node = document.createElement('style'); """ for i in range(MAX_WORDS): CSS_SCRIPT += """ if (! "${{word{i}}}") {{ node.innerHTML += '.word{i} {{ display: none }} ' }} """.format( ...
craftassist-master
acl2020_submission/annotation_tools/tools/annotation_tool_2.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ LOCATION_RADIO = [ {"text": "Not specified", "key": None}, { "text": "Represented using word(s) that indicate reference to a location (e.g. 'there', 'here', 'over there' etc)", "key": "coref_resolve_check", "tooltip": "e.g. 'there...
craftassist-master
acl2020_submission/annotation_tools/tools/all_question_flows.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import csv def any_two(a, b, c): return a == b or a == c or b == c with open("Batch_3449808_batch_results.csv", "r") as f: r = csv.DictReader(f) r = [d for d in r] whittled = [ {k: v for k, v in d.items() if (k.startswith("Answer.") or k == ...
craftassist-master
acl2020_submission/annotation_tools/tools/analyze_outputs.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import re def render_q(q, parent_id, show=True, show_siblings=True): """Return a fieldset for the given question""" assert "key" in q, "Missing key for q: {}".format(q) r = "" q_id = "{}.{}".format(parent_id, q["key"]) r += '<fieldset id="{...
craftassist-master
acl2020_submission/annotation_tools/tools/render_questions_tool_2.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ Q_ACTION = { "text": 'What action is being requested? If multiple separate actions are being requested (e.g. "do X and then do Y"), select "Multiple separate actions"', "key": "action_type", "tooltip": "e.g. in 'Make few copies of the cube' it is : 'B...
craftassist-master
acl2020_submission/annotation_tools/tools/question_flow_for_step_1.py
import argparse import functools import json import logging import logging.handlers import os import pickle from os.path import isfile from os.path import join as pjoin from glob import glob from tqdm import tqdm from time import time from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from tran...
craftassist-master
acl2020_submission/model_training_code/train_model.py
import json import numpy as np import random from os.path import isfile, isdir from os.path import join as pjoin import torch from torch.utils.data import Dataset ######### # Node typing: checking the type of a specific sub-tree (dict value) ######### def is_span(val): try: a, (b, c) = val return...
craftassist-master
acl2020_submission/model_training_code/utils_caip.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam, Adagrad from transformers.modeling_bert import BertModel, BertOnlyMLMHead from utils_caip import * # -------------------------- # Transformer-based decoder module for sequence ans span prediction, computes the loss # --...
craftassist-master
acl2020_submission/model_training_code/utils_parsing.py
import json import math import pickle import torch from transformers import AutoModel, AutoTokenizer, BertConfig from utils_parsing import * from utils_caip import * from train_model import * class TTADBertModel(object): def __init__(self, model_dir, data_dir, model_name="caip_test_model"): model_name ...
craftassist-master
acl2020_submission/model_training_code/query_model.py
import sys sys.path.append('/hdd2/dyah/liger/liger') import os import torch import argparse import numpy as np from liger import Liger from flyingsquid_cluster import Flyingsquid_Cluster from core import load_config from utils import evaluate_thresholds, cluster_embeddings import warnings if not sys.warnoptions: ...
liger-main
run_liger.py
import yaml DEGFAULTS = {} def _merge(src, dst): for k, v in src.items(): if k in dst: if isinstance(v, dict): _merge(src[k], dst[k]) else: dst[k] = v def _check_and_update_model_params(config): return def load_config(config_file,defaults = DEGFA...
liger-main
core/config.py
from .config import load_config
liger-main
core/__init__.py
from .utils import evaluate_models, test_model, evaluate_thresholds, cluster_embeddings
liger-main
utils/__init__.py
import numpy as np from sklearn.metrics import precision_recall_fscore_support, accuracy_score from sklearn.cluster import KMeans def evaluate_models(FS_cluster_models, neg_balances_to_try, mode='dev', tune_by='f1'): for i, FS_cluster in enumerate(FS_cluster_models): accs = [] f1s = [] ...
liger-main
utils/utils.py
import numpy as np from sklearn.metrics import pairwise class Liger: def __init__(self): pass def expand_lfs(self, L_train, L_mat, train_embs, mat_embs, thresholds): m = L_mat.shape[1] expanded_L_mat = np.copy(L_mat) dist_from_mat_to_train = pairwise.cosine_similarity( ...
liger-main
liger/liger.py
from .liger import Liger from .flyingsquid_cluster import Flyingsquid_Cluster
liger-main
liger/__init__.py
from flyingsquid.label_model import LabelModel import numpy as np class Flyingsquid_Cluster: def __init__(self, X, mu, T, m_per_task): self.X = X self.mu = mu self.triplet_models = {} self.T = T self.m_per_task = m_per_task self.m = T * m_per_task self.v = T ...
liger-main
liger/flyingsquid_cluster.py
import torch import torch.optim as optim import torch.utils.data from torch.autograd import Variable import numpy as np import argparse import sys, os if sys.version_info[0] < 3: import cPickle as cp else: import _pickle as cp from copy import deepcopy sys.path.append("./models") sys.path.append("./kernels") sy...
lp_rffs-master
run_model.py
import numpy as np import scipy import torch from nystrom import Nystrom from gaussian_exact import GaussianKernel import sys sys.path.append("../utils") from misc_utils import set_random_seed from quantizer import Quantizer import math EPS = 1e-15 class EnsembleNystrom(object): def __init__(self, n_feat, n_learn...
lp_rffs-master
kernels/ensemble_nystrom.py
import numpy as np import scipy import torch from gaussian_exact import GaussianKernel EPS = 1e-15 class Nystrom(object): def __init__(self, n_feat, kernel=None, rand_seed=1): self.n_feat = n_feat self.kernel = kernel self.rand_seed = rand_seed def setup(self, X, n_landmark=None): ''' X is in the shape o...
lp_rffs-master
kernels/nystrom.py
import numpy as np import torch import sys sys.path.append("../utils") from misc_utils import set_random_seed from gaussian_exact import GaussianKernel class RFF(object): def __init__(self, n_feat, n_input_feat, kernel=None, rand_seed=1): self.n_feat = n_feat # number of rff features self.kernel = kernel ...
lp_rffs-master
kernels/rff.py
import numpy as np import torch import sys # class GaussianKernelSpec(object): # def __init__(self, sigma): # self.sigma = sigma class GaussianKernel(object): def __init__(self, sigma): self.sigma = sigma self.dist_func = torch.nn.PairwiseDistance(p=2) def get_kernel_matrix(self, X1, X2, quantize...
lp_rffs-master
kernels/gaussian_exact.py
import numpy as np import torch from gaussian_exact import GaussianKernel from rff import RFF from scipy.linalg import circulant import math class CirculantRFF(RFF): ''' RFF using circulant random projection matrix ''' def __init__(self, n_feat, n_input_feat, kernel=None, rand_seed=1): super(CirculantRFF, ...
lp_rffs-master
kernels/circulant_rff.py
import torch from torch.autograd import Variable import numpy as np from copy import deepcopy import sys sys.path.append("../utils") from misc_utils import delta_approximation def train(args, model, epoch, train_loader, optimizer, quantizer, kernel): train_loss = [] use_cuda = torch.cuda.is_available() and arg...
lp_rffs-master
utils/train_utils.py
import numpy as np import scipy.io as sio import h5py def load_data(path="../../data/census/census"): try: X_train = sio.loadmat(path + "_train_feat.mat") Y_train = sio.loadmat(path + "_train_lab.mat") X_test = sio.loadmat(path + "_heldout_feat.mat") Y_test = sio.loadmat(path + "_heldout_lab.mat") ...
lp_rffs-master
utils/data_loader.py
import numpy as np import torch import math class Quantizer(object): def __init__(self, nbit, min_val, max_val, scale=None, rand_seed=1, use_cuda=False, for_lm_halp=False): self.nbit = nbit self.min_val = min_val self.max_val = max_val if scale == None: if for_lm_halp == False: self.sca...
lp_rffs-master
utils/quantizer.py
import numpy as np from scipy.optimize import minimize import torch # for numerical protection EPS = 1e-20 def set_random_seed(seed): np.random.seed(seed) use_cuda = torch.cuda.is_available() torch.manual_seed(seed) if use_cuda: torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(s...
lp_rffs-master
utils/misc_utils.py
import matplotlib import matplotlib.pyplot as plt #def get_colors(): # prop_cycle = plt.rcParams['axes.prop_cycle'] # colors = prop_cycle.by_key()['color'] # colors_dict = {} # colors_dict["exact"] = colors[0] # colors_dict["fp"] = colors[1] # for idx, nbit in enumerate([1,2,4,8,16,32] ): # colors_dict[str(nb...
lp_rffs-master
utils/plot_utils.py
import torch import numpy as np from torch.autograd import Variable class LogisticRegression(torch.nn.Module): def __init__(self, input_dim, n_class, reg_lambda, dtype="float"): super(LogisticRegression, self).__init__() self.input_dim = input_dim self.n_class = n_class self.reg_lambda = reg_lambda ...
lp_rffs-master
models/logistic_regression.py
import numpy as np import torch import sys sys.path.append("../kernels/") from gaussian_exact import GaussianKernel from rff import RFF from time import time import math class KernelRidgeRegression(object): def __init__(self, kernel, reg_lambda): ''' reg_lambda is the strength of the regression regularizor ...
lp_rffs-master
models/kernel_regressor.py
import torch import numpy as np from torch.autograd import Variable class RidgeRegression(torch.nn.Module): def __init__(self, input_dim, reg_lambda, dtype="float"): super(RidgeRegression, self).__init__() self.input_dim = input_dim self.reg_lambda = reg_lambda self.linear = torch.nn.Linear(self.input_dim, o...
lp_rffs-master
models/ridge_regression.py
babble-master
tutorial/data/__init__.py
from babble import Explanation aliases = { 'spouse': ['spouse', 'wife', 'husband', 'ex-wife', 'ex-husband'], 'family': ['father', 'father', 'mother', 'sister', 'sisters', 'brother', 'brothers', 'son', 'sons', 'daughter', 'daughters', 'grandfather', 'grandmother', 'uncle', 'unc...
babble-master
tutorial/data/sample_explanations.py
import pickle import os import unittest from babble import SemanticParser from test_babble_base import TestBabbleBase import text_explanations class TestBabbleText(TestBabbleBase): @classmethod def setUpClass(cls): cls.sp = SemanticParser(aliases=text_explanations.get_aliases(), ...
babble-master
tests/test_babble_text.py
import pickle import sys import unittest class TestBabbleBase(unittest.TestCase): @classmethod def setUpClass(cls): DATA_FILE = 'tutorial/data/tutorial_data.pkl' with open(DATA_FILE, 'rb') as f: Cs, _ = pickle.load(f) cls.candidate_map = {} for c in Cs[0]: ...
babble-master
tests/test_babble_base.py
from babble import Explanation def get_aliases(): return { 'colors':['red','green','blue'], 'bluebird':['blue','bird','fly'], 'greek':['alpha','beta','gamma'], 'letters':['a','B','C'], 'smalls':['a','b','c','d'], 'spouse':['wife','husband','spouse'] } # Test can...
babble-master
tests/text_explanations.py
import os import unittest from babble import SemanticParser from test_babble_base import TestBabbleBase import core_explanations class TestBabbleCore(TestBabbleBase): @classmethod def setUpClass(cls): cls.sp = SemanticParser(aliases=core_explanations.get_aliases(), be...
babble-master
tests/test_babble_core.py
from babble import Explanation def get_aliases(): return { 'colors':['red','green','blue'], 'bluebird':['blue','bird','fly'], 'greek':['alpha','beta','gamma'], 'letters':['a','B','C'], 'smalls':['a','b','c','d'], 'luckies': [7, 8, 9], 'unluckies': [0, 13, 66]...
babble-master
tests/core_explanations.py
from collections import namedtuple, OrderedDict, defaultdict import numpy as np from metal.contrib.info_extraction.mentions import RelationMention from scipy.sparse import csr_matrix from babble.parsing import Parse from babble.utils import PrintTimer, ProgressBar FilteredParse = namedtuple('FilteredParse', ['parse'...
babble-master
babble/filter_bank.py
from collections import defaultdict, namedtuple import itertools import random import numpy as np from pandas import DataFrame, Series from scipy.sparse import csr_matrix, coo_matrix, lil_matrix import scipy.sparse as sparse from metal.analysis import lf_summary from babble.filter_bank import FilterBank from babble....
babble-master
babble/babbler.py
from .explanation import Explanation from .parsing import Rule, Grammar, Parse, SemanticParser from .filter_bank import FilterBank from .utils import ExplanationIO, link_explanation_candidates from .babbler import Babbler, BabbleStream
babble-master
babble/__init__.py
import random from sklearn.linear_model import LogisticRegression from metal.utils import convert_labels from metal.metrics import metric_score class LogisticRegressionWrapper(object): """A wrapper around scikit-learn's LogisticRegression class The wrapper is necessary both to convert labels from categorica...
babble-master
babble/disc_model.py
import re class Explanation(object): def __init__(self, condition, label, candidate=None, name=None, semantics=None, paraphrase=None): """ Constructs an Explanation object. :param condition: A string explanation that expresses a Boolean condition (e.g., "The se...
babble-master
babble/explanation.py
from collections import Counter, defaultdict import csv import json import os import random import sys from time import time from metal.contrib.info_extraction.mentions import RelationMention from metal.contrib.info_extraction.utils import mark_entities import numpy as np import torch from scipy.sparse import issparse...
babble-master
babble/utils.py
from .core_annotators import annotators, text2int from .core_templates import PrimitiveTemplate from .core_base import core_grammar
babble-master
babble/core/__init__.py
import re from babble.parsing.annotator import Annotator class PunctuationAnnotator(Annotator): def annotate(self, tokens): if len(tokens) == 1: if tokens[0]['pos'] in ["``", "\'\'"] or tokens[0]['word'] in ["'", '"']: return [('$Quote', tokens[0]['word'])] elif tok...
babble-master
babble/core/core_annotators.py
from __future__ import print_function from babble.parsing import Rule, sems0, sems1, sems_in_order, sems_reversed, star def PrimitiveTemplate(seed): X = seed XListStub = X + 'ListStub' XListAnd = X + 'ListAnd' XListOr = X + 'ListOr' XList = X + 'List' XToBool = X + 'ToBool' # f(X) = Bool ...
babble-master
babble/core/core_templates.py
from __future__ import print_function from babble.parsing import ( GrammarMixin, Rule, sems0, sems1, sems_in_order, sems_reversed, flip_dir, star, ) from babble.core.core_templates import PrimitiveTemplate from babble.core.core_annotators import annotators # Rules =====================...
babble-master
babble/core/core_base.py
from collections import namedtuple import re inequalities = { '.lt': lambda x, y: x < y, '.leq': lambda x, y: x <= y, '.eq': lambda x, y: x == y, '.geq': lambda x, y: x >= y, '.gt': lambda x, y: x > y, } class Phrase(object): fields = ['text', 'words', 'char_offsets', 'pos_tags', 'ner_tags', ...
babble-master
babble/text/text_helpers.py
from babble.parsing import Annotator class TokenAnnotator(Annotator): def annotate(self, tokens): # Quotation marks are hard stops to prevent merging of multiple strings if len(tokens) == 1 and tokens[0]['pos'] not in ["``", "\'\'"]: return [('$QueryToken', tokens[0]['word'])] e...
babble-master
babble/text/text_annotators.py
from .text_base import text_grammar from .text_helpers import *
babble-master
babble/text/__init__.py
from babble.parsing import GrammarMixin, Rule, sems0, sems1, sems_in_order, sems_reversed, flip_dir, star from babble.core import PrimitiveTemplate from babble.text.text_helpers import helpers from babble.text.text_annotators import annotators lexical_rules = ( [Rule('$Token', w, 'token') for w in ['token']] + ...
babble-master
babble/text/text_base.py
from .annotator import Annotator from .stopwords import stopword_list from .rule import Rule, sems0, sems1, sems_in_order, sems_reversed, flip_dir, star from .parse import Parse from .grammar import Grammar, GrammarMixin from .parser import SemanticParser
babble-master
babble/parsing/__init__.py
class Annotator: """A base class for annotators.""" def annotate(self, tokens): """Returns a list of pairs, each a category and a semantic representation.""" return []
babble-master
babble/parsing/annotator.py
from __future__ import print_function from collections import defaultdict, namedtuple from itertools import product import re from types import FunctionType from babble.parsing.spacy.spacy_parser import Spacy from babble.parsing.rule import Rule, is_cat, is_optional from babble.parsing.parse import Parse class Gra...
babble-master
babble/parsing/grammar.py
from pandas import DataFrame, Series from metal.contrib.info_extraction.mentions import RelationMention from babble.core import core_grammar, text2int from babble.text import text_grammar from babble.parsing import Grammar, stopword_list from babble.explanation import Explanation class SemanticParser(object): de...
babble-master
babble/parsing/parser.py
from types import FunctionType class Rule(object): """Represents a CFG rule with a semantic attachment.""" def __init__(self, lhs, rhs, sem=None): self.lhs = lhs self.rhs = tuple(rhs.split()) if isinstance(rhs, str) else rhs self.sem = sem self.validate_rule() def __str__(...
babble-master
babble/parsing/rule.py
from __future__ import print_function from collections import Iterable from six import StringIO from babble.parsing.rule import Rule, is_cat class Parse(object): def __init__(self, rule, children, absorbed=0): self.rule = rule self.children = tuple(children[:]) self.semantics = self.compu...
babble-master
babble/parsing/parse.py
stopword_list = [ 'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 'hers', 'herself', 'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'thi...
babble-master
babble/parsing/stopwords.py
import sys class Parser(object): def __init__(self, name, encoding='utf-8'): self.name = name self.encoding = encoding def to_unicode(self, text): ''' Convert char encoding to unicode :param text: :return: ''' if sys.version_info[0] < 3: ...
babble-master
babble/parsing/spacy/parser.py
from collections import defaultdict from .parser import Parser, ParserConnection try: import spacy from spacy.cli import download from spacy import util try: spacy_version=int(spacy.__version__[0]) except: spacy_version=1 except: raise Exception("spaCy not installed. Use `pip i...
babble-master
babble/parsing/spacy/spacy_parser.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import scipy from scipy.optimize import Bounds, LinearConstraint, minimize, SR1 import pdb import math i...
adaptive_scheduling-main
solve_gradient_seq.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import scipy from scipy.optimize import Bounds, LinearConstraint, minimize, SR1 import pdb import math i...
adaptive_scheduling-main
solve_gradient_simple.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import scipy from scipy.optimize import Bounds, LinearConstraint, minimize, SR1 import pdb import mat...
adaptive_scheduling-main
solve_bound.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import math import logging from typing import TYPE_CHECKING, Any, Callable, Optional import torch import torch.optim impor...
adaptive_scheduling-main
adagrad_flex.py
from glob import glob import sys, os import pathlib def print_folder_containing_files(contains=False, root_folder='./', file_regex="*final.json"): # we use this function to search for folders not containing a file with substr in its name paths = glob(root_folder + "/*") print("total subdir ", len(paths)) ...
bert-pretraining-master
src/bert-pretraining/gc_utils.py
import sys, os import glob import json import csv import numpy as np import utils from plot_utils import save_csv_with_error_bar def get_wiki17_wiki18_pred_disagreement_vs_dim(results, dims=[192, 384, 768, 1536, 3072], seeds=[1,2,3]): disagreements_all_dim = [] for dim in dims: disagreements = [] ...
bert-pretraining-master
src/bert-pretraining/analysis.py
import glob import numpy as np import matplotlib.pyplot as plt from matplotlib import rc # rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) ## for Palatino and other serif fonts use: #rc('font',**{'family':'serif','serif':['Palatino']}) rc('text', usetex=True) import plot_utils LABEL_FONT_SIZE = 25 TI...
bert-pretraining-master
src/bert-pretraining/plotting.py
import torch import numpy import numpy as np import _pickle as cp from run_compress import load_dataset_feat def test_ensembling(): # test whether ensemble is doing correctly path = "/dfs/scratch0/zjian/bert-pretraining/src/bert-pretraining/tmp" old_folder = path + "/pretrain_seed_2_dim_192_wiki17" new...
bert-pretraining-master
src/bert-pretraining/scratch.py
import numpy as np import torch import scipy import argparse import sys, os import logging from smallfry import compress import utils NUM_TOL = 1e-6 FEAT_SUBSAMPLE_RATE = 0.1 def read_npy_feature(file): feats = np.load(file) feats = [feats[name] for name in feats.files] return feats def read_npy_label(f...
bert-pretraining-master
src/bert-pretraining/run_compress.py
import os, sys import json from glob import glob import spacy import re import random import math from multiprocessing import Process def get_raw_data_content(f_name): with open(f_name, "r") as f: content = f.readlines() content = [eval(x) for x in content] return content def extract_article_id_name(path): fil...
bert-pretraining-master
src/bert-pretraining/wiki_preprocessing.py
import json import glob import utils import os SCRIPT_FOLDER="../../script" def bert_pretraining_lr_tuning_training(): file_name = SCRIPT_FOLDER + "/0701_bert_pretraining_lr_tuning_training" lrs = [0.000001, 0.00001, 0.0001, 0.001, 0.01] BERT_BASE_DIR = "../../data/bert" tpu_tmp = 'gcloud compute tpus...
bert-pretraining-master
src/bert-pretraining/experiments.py
import tensorflow as tf import torch import numpy as np import sys, os import datetime import logging import pathlib import json import glob import random def set_tensorflow_random_seed(rand_seed): random.seed(rand_seed) np.random.seed(rand_seed) tf.set_random_seed(rand_seed) def set_random_seed(rand_seed...
bert-pretraining-master
src/bert-pretraining/utils.py
import pandas as pd from matplotlib import pyplot as plt import numpy as np import csv import os, sys def std_results_array(results_array): # average list of 1d np array results results_array = [np.reshape(x, x.size) for x in results_array] results = np.vstack(results_array) return np.std(results, axis...
bert-pretraining-master
src/bert-pretraining/plot_utils.py
from setuptools import setup setup(name='halp', version='0.1', description='Code for floating point based halp.', url='https://github.com/HazyResearch/PyTorch_HALP', author='Jian Zhang', author_email='zjian@stanford.edu', license='Apache Version 2', install_requires = ['numpy'...
halp-master
setup.py
halp-master
halp/__init__.py
import torch import torch.nn as nn from torch.nn import ReLU import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.autograd import Function from torch.autograd import Variable import numpy as np from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from halp....
halp-master
halp/layers/relu_layer.py
import torch import numpy as np import torch.nn.functional as F from torch.nn import Parameter from halp.layers.tanh_layer import BitCenterTanh, bit_center_tanh from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from unittest import TestCase from halp.layers.bit_center_layer_test impor...
halp-master
halp/layers/tanh_layer_test.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init from torch.nn.parameter import Parameter from torch.autograd import Function from torch.autograd import Variable import numpy as np from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from ha...
halp-master
halp/layers/cross_entropy.py
import torch import torch.nn as nn import torch.nn.init as init from torch.nn import BatchNorm2d import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.autograd import Function from torch.autograd import Variable import numpy as np from halp.utils.utils import void_cast_func, single_to_half...
halp-master
halp/layers/batch_norm_layer.py
import torch import numpy as np import torch.nn.functional as F from torch.nn import Parameter from halp.layers.sigmoid_layer import BitCenterSigmoid, bit_center_sigmoid from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from unittest import TestCase from halp.layers.bit_center_layer_t...
halp-master
halp/layers/sigmoid_layer_test.py
import torch import numpy as np from torch.nn import Parameter from halp.layers.conv_layer import BitCenterConv2D, bit_center_conv2d from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from unittest import TestCase from halp.utils.utils import set_seed from halp.utils.test_utils import ...
halp-master
halp/layers/conv_layer_test.py
import torch import torch.nn as nn import torch.nn.init as init from torch.nn.parameter import Parameter from torch.autograd import Function from torch.autograd import Variable import numpy as np from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc, void_func import logging import sys lo...
halp-master
halp/layers/bit_center_layer.py
import torch import numpy as np from torch.nn import Parameter from halp.layers.linear_layer import BitCenterLinear, bit_center_linear from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from unittest import TestCase from halp.utils.test_utils import HalpTest from torch.autograd.gradche...
halp-master
halp/layers/linear_layer_test.py
import torch import torch.nn as nn from torch.nn import ReLU import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.nn.modules.utils import _pair from torch.autograd import Function from torch.autograd import Variable import numpy as np from halp.utils.utils import void_cast_func, single_to...
halp-master
halp/layers/pool_layer.py
import torch import torch.nn as nn from torch.nn import Embedding import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.autograd import Function from torch.autograd import Variable import numpy as np from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from ...
halp-master
halp/layers/embedding.py
import torch import torch.nn as nn from torch.nn import Linear import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.autograd import Function from torch.autograd import Variable import numpy as np from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from hal...
halp-master
halp/layers/linear_layer.py
import torch import numpy as np from torch.nn import Parameter from torch.autograd import Variable from halp.layers.cross_entropy import BitCenterCrossEntropy from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from unittest import TestCase from halp.utils.test_utils import HalpTest fro...
halp-master
halp/layers/cross_entropy_test.py
import torch import torch.nn as nn from torch.nn import Tanh import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.autograd import Function import numpy as np from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from halp.layers.bit_center_layer import BitCe...
halp-master
halp/layers/ele_mult.py
halp-master
halp/layers/__init__.py
import torch import numpy as np from torch.nn import Parameter from halp.layers.embedding import BitCenterEmbedding, bit_center_embedding from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from unittest import TestCase from halp.utils.test_utils import HalpTest from torch.autograd.grad...
halp-master
halp/layers/embedding_test.py
import torch import numpy as np from torch.nn import Parameter from halp.layers.batch_norm_layer import BitCenterBatchNorm2D, bit_center_batch_norm2d from halp.utils.utils import void_cast_func, single_to_half_det, single_to_half_stoc from unittest import TestCase from halp.utils.utils import set_seed from halp.utils.t...
halp-master
halp/layers/batch_norm_layer_test.py