python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
import matplotlib.pyplot as plt import numpy as np import scipy.sparse as sparse from metal.utils import convert_labels ############################################################ # Label Matrix Plotting ############################################################ def view_label_matrix(L, colorbar=True): """Display an [n, m] matrix of labels""" L = L.todense() if sparse.issparse(L) else L plt.imshow(L, aspect="auto") plt.title("Label Matrix") if colorbar: labels = sorted(np.unique(np.asarray(L).reshape(-1, 1).squeeze())) boundaries = np.array(labels + [max(labels) + 1]) - 0.5 plt.colorbar(boundaries=boundaries, ticks=labels) plt.show() def view_overlaps(L, self_overlaps=False, normalize=True, colorbar=True): """Display an [m, m] matrix of overlaps""" L = L.todense() if sparse.issparse(L) else L G = _get_overlaps_matrix(L, normalize=normalize) if not self_overlaps: np.fill_diagonal(G, 0) # Zero out self-overlaps plt.imshow(G, aspect="auto") plt.title("Overlaps") if colorbar: plt.colorbar() plt.show() def view_conflicts(L, normalize=True, colorbar=True): """Display an [m, m] matrix of conflicts""" L = L.todense() if sparse.issparse(L) else L C = _get_conflicts_matrix(L, normalize=normalize) plt.imshow(C, aspect="auto") plt.title("Conflicts") if colorbar: plt.colorbar() plt.show() def _get_overlaps_matrix(L, normalize=True): n, m = L.shape X = np.where(L != 0, 1, 0).T G = X @ X.T if normalize: G = G / n return G def _get_conflicts_matrix(L, normalize=True): n, m = L.shape C = np.zeros((m, m)) # Iterate over the pairs of LFs for i in range(m): for j in range(m): # Get the overlapping non-zero indices overlaps = list( set(np.where(L[:, i] != 0)[0]).intersection(np.where(L[:, j] != 0)[0]) ) C[i, j] = np.where(L[overlaps, i] != L[overlaps, j], 1, 0).sum() if normalize: C = C / n return C ############################################################ # Classifier Diagnostics ############################################################ def plot_probabilities_histogram(Y_probs, title=None): """Plot a histogram from a numpy array of probabilities Args: Y_probs: An [n] or [n, 1] np.ndarray of probabilities (floats in [0,1]) """ if Y_probs.ndim > 1: print("Plotting probabilities from the first column of Y_probs") Y_probs = Y_probs[:, 0] plt.hist(Y_probs, bins=20) plt.xlim((0, 1.025)) plt.xlabel("Probability") plt.ylabel("# Predictions") if isinstance(title, str): plt.title(title) plt.show() def plot_predictions_histogram(Y_preds, Y_gold, title=None): """Plot a histogram comparing int predictions vs true labels by class Args: Y_gold: An [n] or [n, 1] np.ndarray of gold labels Y_preds: An [n] or [n, 1] np.ndarray of predicted int labels """ labels = list(set(Y_gold).union(set(Y_preds))) edges = [x - 0.5 for x in range(min(labels), max(labels) + 2)] plt.hist([Y_preds, Y_gold], bins=edges, label=["Predicted", "Gold"]) ax = plt.gca() ax.set_xticks(labels) plt.xlabel("Label") plt.ylabel("# Predictions") plt.legend(loc="upper right") if isinstance(title, str): plt.title(title) plt.show() def plot_calibration_plot(Y_probs, Y_gold, bins=20, title=None): """Plot a histogram of the accuracy for predictions with varying confidences Args: Y_probs: An [n] or [n, 1] np.ndarray of probabilities (floats in [0,1]) Y_gold: An [n] or [n, 1] np.ndarray of gold labels For a well-behaved classifier, the plot should be a U-shape. """ # For now, we only tackle binary classification with categorical labels assert all(Y_gold > 0) assert all(Y_gold <= 2) if Y_probs.ndim > 1: print("Plotting probabilities from the first column of Y_probs") Y_probs = Y_probs[:, 0] Y_preds = convert_labels((Y_probs > 0.5).astype(np.int64), "onezero", "categorical") correct_idxs = Y_preds == Y_gold centers = [] accuracies = [] interval = 1 / bins for i in range(bins + 1): if i == bins: bin_idxs = (interval * i <= Y_probs) * (Y_probs <= 1) else: bin_idxs = (interval * i <= Y_probs) * (Y_probs < interval * (i + 1)) bin_accuracy = sum(bin_idxs * correct_idxs) / sum(bin_idxs) centers.append(interval * (i + 0.5)) accuracies.append(bin_accuracy) # print("Accuracy: ", len(correct_idx) / (1.0 * len(Y_probs))) # Y_p_correct = Y_probs[correct_idx] plt.plot(centers, accuracies) plt.xlim((0, 1.025)) plt.xlabel("Probability") plt.ylabel("Accuracy") if isinstance(title, str): plt.title(title)
metal-master
metal/contrib/visualization/analysis.py
metal-master
metal/contrib/visualization/__init__.py
class Featurizer(object): def fit(self, input): """ Args: input: An iterable of raw data of the appropriate type to be featurized, where input[i] corresponds to item i. """ raise NotImplementedError def transform(self, input): """ Args: input: An iterable of raw data of the appropriate type to be featurized, where input[i] corresponds to item i. Returns: X: A Tensor of features of shape (num_items, ...) """ raise NotImplementedError def fit_transform(self, input, **fit_kwargs): """Execute fit and transform in sequence.""" self.fit(input, **fit_kwargs) X = self.transform(input) return X
metal-master
metal/contrib/featurizers/featurizer.py
metal-master
metal/contrib/featurizers/__init__.py
import itertools from collections import Counter import torch from torch.nn.utils.rnn import pad_sequence from torchtext.vocab import Vocab from metal.contrib.featurizers.featurizer import Featurizer class EmbeddingFeaturizer(Featurizer): """Converts lists of tokens into a padded Tensor of embedding indices.""" def __init__(self, markers=[]): self.specials = markers + ["<pad>"] self.vocab = None def build_vocab(self, counter): raise NotImplementedError def fit(self, sents, **kwargs): """Builds a vocabulary object based on the tokens in the input. Args: sents: A list of lists of tokens (representing sentences) Vocab kwargs include: max_size min_freq specials unk_init """ tokens = list(itertools.chain.from_iterable(sents)) counter = Counter(tokens) self.vocab = self.build_vocab(counter, **kwargs) def transform(self, sents): """Converts lists of tokens into a Tensor of embedding indices. Args: sents: A list of lists of tokens (representing sentences) NOTE: These sentences should already be marked using the mark_entities() helper. Returns: X: A Tensor of shape (num_items, max_seq_len) """ def convert(tokens): return torch.tensor([self.vocab.stoi[t] for t in tokens], dtype=torch.long) if self.vocab is None: raise Exception( "Must run .fit() for .fit_transform() before " "calling .transform()." ) seqs = sorted([convert(s) for s in sents], key=lambda x: -len(x)) X = torch.LongTensor(pad_sequence(seqs, batch_first=True)) return X class TrainableEmbeddingFeaturizer(EmbeddingFeaturizer): def build_vocab(self, counter, **kwargs): return Vocab(counter, specials=self.specials, **kwargs)
metal-master
metal/contrib/featurizers/embedding_featurizer.py
import nltk from sklearn.feature_extraction.text import CountVectorizer from metal.contrib.featurizers.featurizer import Featurizer class RelationNgramFeaturizer(Featurizer): """A featurizer for relations that preprocesses and extracts ngrams This featurizer operates on RelationMention objects Args: anonymize: if True, replace each entity with a single token: "EntityX" where X is the index of the entity in the relation (0 or 1) trim_window: if non-zero, the sentence will be trimmed to this many words before the first entity in the sentence to this many words after the last entity in the sentence. lowercase: if True, convert all tokens to lowercase drop_stopwords: if True, drop all tokens that are stopwords stem: if True, stem all tokens ngram_range: a tuple corresponding to the smallest sized ngrams and largest sized ngrams to be included in the feature set kwargs: keyword arguments to pass on to the CountVectorizer. (See http://scikit-learn.org/stable/modules/generated/sklearn. feature_extraction.text.CountVectorizer.html for full details) Options include max_features, min_df, max_df, etc. """ def __init__( self, anonymize=True, trim_window=5, lowercase=True, drop_stopwords=True, stem=True, ngram_range=(1, 3), **vectorizer_kwargs, ): self.anonymize = anonymize self.lowercase = lowercase self.drop_stopwords = drop_stopwords if drop_stopwords: nltk.download("stopwords") self.stopwords = set(nltk.corpus.stopwords.words("english")) self.trim_window = trim_window self.stem = stem if stem: self.porter = nltk.PorterStemmer() self.vectorizer = CountVectorizer( ngram_range=ngram_range, binary=True, **vectorizer_kwargs ) def preprocess(self, mentions): return [" ".join(self._preprocess(mention)) for mention in mentions] def _preprocess(self, mention): tokens = mention.tokens word_positions = mention.word_positions if self.anonymize: tokens, word_positions = self._anonymize(tokens, word_positions) if self.trim_window: tokens, word_positions = self._trim(tokens, word_positions) if self.lowercase: tokens = self._lowercase(tokens) if self.drop_stopwords: # TODO: update word_positions after stopword removal tokens = self._drop_stopwords(tokens) if self.stem: tokens = self._stem(tokens) return tokens def _anonymize(self, tokens, word_positions): offset = 0 for i, (word_start, word_end) in enumerate(word_positions): word_start -= offset word_end -= offset tokens = tokens[:word_start] + [f"ENTITY_{i}"] + tokens[(word_end + 1) :] word_positions[i] = (word_start, word_start) offset += word_end - word_start return tokens, word_positions def _trim(self, tokens, word_positions): word_starts, word_ends = list(zip(*word_positions)) lb = max(0, min(word_starts) - self.trim_window) ub = min(len(tokens), max(word_ends) + self.trim_window + 1) word_positions = [(wp[0] - lb, wp[1] - lb) for wp in word_positions] return tokens[lb:ub], word_positions def _lowercase(self, tokens): return [t.lower() for t in tokens] def _drop_stopwords(self, tokens): return [t for t in tokens if t not in self.stopwords] def _stem(self, tokens): return [self.porter.stem(t) for t in tokens] def get_feature_names(self): return self.vectorizer.get_feature_names() def fit(self, input): preprocessed = self.preprocess(input) self.vectorizer.fit(preprocessed) def transform(self, input): preprocessed = self.preprocess(input) return self.vectorizer.transform(preprocessed) def fit_transform(self, input): preprocessed = self.preprocess(input) return self.vectorizer.fit_transform(preprocessed)
metal-master
metal/contrib/featurizers/ngram_featurizer.py
import os from collections import Counter import numpy as np import torch from torch.utils.data import Dataset from metal.contrib.info_extraction.utils import mark_entities class SnorkelDataset(Dataset): """ Self-contained wrapper class for Snorkel 0.7 database instance. Suitable for datasets that fit entirely in memory. """ session = None def __init__( self, conn_str, candidate_def, split=0, use_lfs=False, word_dict=None, pretrained_word_dict=None, max_seq_len=125, ): """ Assumes a Snorkel database that is fully instantiated with: - Candidates generated and assigned to train/dev/test splits - Labeling functions are applied and probabilistic labels are generated for train split(s) - Gold labels are stored in the database under 'annotator_name = gold' :param conn_str: :param candidate_def: :param split: :param use_lfs: :param word_dict: :param pretrained_word_dict: :param max_seq_len: """ if os.path.exists(conn_str): os.environ["SNORKELDB"] = "sqlite:///{}".format(conn_str) else: os.environ["SNORKELDB"] = "postgresql:///{}".format(conn_str) print("Connected to {}".format(os.environ["SNORKELDB"])) # defer imports until SNORKELDB is defined to prevent initalizing an empty sqlite instance from snorkel import SnorkelSession from snorkel.models import candidate_subclass, Candidate from snorkel.annotations import load_gold_labels, load_marginals # sqlite3 doesn't support multiple connections, so use a singleton-style connection object if not SnorkelDataset.session: SnorkelDataset.session = SnorkelSession() self.session = SnorkelDataset.session self.class_type = candidate_subclass(*candidate_def) self.cardinality = len(candidate_def[-1]) self.split = split self.max_seq_len = max_seq_len # create markup sequences and labels markers = [ m.format(i) for i in range(self.cardinality) for m in ["~~[[{}", "{}]]~~"] ] self.X = ( self.session.query(Candidate) .filter(Candidate.split == split) .order_by(Candidate.id) .all() ) self.X = [self._mark_entities(x, markers) for x in self.X] # initalize vocabulary self.word_dict = ( self._build_vocab(self.X, markers) if not word_dict else word_dict ) if pretrained_word_dict: # include pretrained embedding terms self._include_pretrained_vocab( pretrained_word_dict, self.session.query(Candidate).all() ) # initalize labels (from either LFs or gold labels) if use_lfs: self.Y = torch.tensor(load_marginals(self.session, split=split).todense()) else: self.Y = load_gold_labels(self.session, annotator_name="gold", split=split) self.Y = [int(y) for y in np.nditer(self.Y.todense())] # remap class labels to not include 0 (reserved by MeTaL) labels = { y: i + 1 for i, y in enumerate(sorted(np.unique(self.Y), reverse=1)) } self.Y = torch.tensor([labels[y] for y in self.Y]) @classmethod def splits( cls, conn_str, candidate_def, word_dict=None, train=0, dev=1, test=2, use_lfs=(0, 0, 0), pretrained_word_dict=None, max_seq_len=125, ): """ Create train/dev/test splits (mapped to split numbers) :param conn_str: :param candidate_def: :param word_dict: :param train: :param dev: :param test: :param use_lfs: :param pretrained_word_dict: :param max_seq_len: :return: """ # initialize word_dict if needed train_set = cls( conn_str, candidate_def, word_dict=word_dict, split=train, use_lfs=use_lfs[train], pretrained_word_dict=pretrained_word_dict, max_seq_len=max_seq_len, ) return ( train_set, cls( conn_str, candidate_def, word_dict=train_set.word_dict, split=dev, use_lfs=use_lfs[dev], max_seq_len=max_seq_len, ), cls( conn_str, candidate_def, word_dict=train_set.word_dict, split=test, use_lfs=use_lfs[test], max_seq_len=max_seq_len, ), ) def _mark_entities(self, c, markers): """ Convert Snorkel candidates to marked up sequences :param c: :param markers: :return: """ sent = c.get_parent().words positions = [ [c[i].get_word_start(), c[i].get_word_end()] for i in range(self.cardinality) ] seq = mark_entities(sent, positions, markers=markers, style="insert") return [w for w in seq if w.strip()] def _include_pretrained_vocab(self, pretrained_word_dict, candidates): """ Include terms available via pretrained embeddings :param pretrained_word_dict: :param candidates: :return: """ terms = Counter() for c in candidates: for w in c.get_parent().words: if w in pretrained_word_dict: terms[w] += 1 list(map(self.word_dict.get, terms)) def _build_vocab(self, sentences, markers=[]): """ Initalize symbol table dictionary :param sentences: :param markers: :return: """ from snorkel.learning.pytorch.rnn.utils import SymbolTable vocab = Counter() for sent in sentences: for w in sent: vocab[w] += 1 word_dict = SymbolTable() list(map(word_dict.get, vocab)) list(map(word_dict.get, markers)) return word_dict def __len__(self): return len(self.X) def __getitem__(self, idx): """ Assume fixed length sequences. Pad or clip all sequences to be max_seq_len. :param idx: :return: """ x = torch.tensor([self.word_dict.lookup(w) for w in self.X[idx]]) if x.size(0) > self.max_seq_len: x = x[..., 0 : min(x.size(0), self.max_seq_len)] else: k = self.max_seq_len - x.size(0) x = torch.cat((x, torch.zeros(k, dtype=torch.long))) return x, self.Y[idx] if __name__ == "__main__": db_conn_str = "cdr.db" candidate_def = ["ChemicalDisease", ["chemical", "disease"]] train, dev, test = SnorkelDataset.splits(db_conn_str, candidate_def) print("[TRAIN] {}".format(len(train))) print("[DEV] {}".format(len(dev))) print("[TEST] {}".format(len(test)))
metal-master
metal/contrib/backends/wrapper.py
metal-master
metal/contrib/backends/__init__.py
metal-master
metal/contrib/info_extraction/__init__.py
def mark_entities(tokens, positions, markers=[], style="insert"): """Adds special markers around tokens at specific positions (e.g., entities) Args: tokens: A list of tokens (the sentence) positions: 1) A list of inclusive ranges (tuples) corresponding to the token ranges of the entities in order. (Assumes each entity has only one corresponding mention.) OR 2) A dict of lists with keys corresponding to mention indices and values corresponding to one or more inclusive ranges corresponding to that mention. (Allows entities to potentially have multiple mentions) markers: A list of strings (length of 2 * the number of entities) to use as markers of the entities. style: Where to apply the markers: 'insert': Insert the markers as new tokens before/after each entity 'concatenate': Prepend/append the markers to the first/last token of each entity If the tokens are going to be input to an LSTM, then it is usually best to use the 'insert' option; 'concatenate' may be better for viewing. Returns: toks: An extended list of tokens with markers around the mentions WARNING: if the marked token set will be used with pretrained embeddings, provide markers that will not result in UNK embeddings! Example: Input: (['The', 'cat', 'sat'], [(1,1)]) Output: ['The', '[[BEGIN0]]', 'cat', '[[END0]]', 'sat'] """ if markers and len(markers) != 2 * len(positions): msg = ( f"Expected len(markers) == 2 * len(positions), " f"but {len(markers)} != {2 * len(positions)}." ) raise ValueError(msg) toks = list(tokens) # markings will be of the form: # [(position, entity_idx), (position, entity_idx), ...] if isinstance(positions, list): markings = [(position, idx) for idx, position in enumerate(positions)] elif isinstance(positions, dict): markings = [] for idx, v in positions.items(): for position in v: markings.append((position, idx)) else: msg = ( f"Argument _positions_ must be a list or dict. " f"Instead, got {type(positions)}" ) raise ValueError(msg) markings = sorted(markings) for i, ((si, ei), idx) in enumerate(markings): if markers: start_marker = markers[2 * idx] end_marker = markers[2 * idx + 1] else: start_marker = f"[[BEGIN{idx}]]" end_marker = f"[[END{idx}]]" if style == "insert": toks.insert(si + 2 * i, start_marker) toks.insert(ei + 2 * (i + 1), end_marker) elif style == "concatenate": toks[si] = start_marker + toks[si] toks[ei] = toks[ei] + end_marker else: raise NotImplementedError return toks
metal-master
metal/contrib/info_extraction/utils.py
import numpy as np class EntityMention(object): """A mention of an entity (span of text) in a document Args: doc_id: a unique identifier for the document text: a single string of text corresponding to the document char_start: the integer offset of the first character in the entity mention char_end: the integer offset of the last character in the entity mention, plus one (so that text[char_start:char_end] returns the full entity). tokens: (optional) a list of tokens corresponding to the text. If None, tokenization on whitespace is the default. char_offsets: (optional) a list of character offsets corresponding to the tokens in tokens. If None, we assume all tokens are separated by a single space. attributes: (optional) additional lists of attributes corresponding to the provided tokens (e.g., pos tags, ner tags, types, etc.) """ def __init__( self, doc_id, text, char_start, char_end, tokens=None, char_offsets=None, mention_id=None, **attributes, ): self.doc_id = doc_id self.text = text self.char_start = int(char_start) self.char_end = int(char_end) self.mention_id = mention_id if mention_id else hash(self) self.entity = text[self.char_start : self.char_end] self.tokens = tokens if tokens is not None else text.split() self.char_offsets = self._get_char_offsets(char_offsets) # Convert exclusive character offsets to inclusive token indices self.word_start = self.char_to_word_idx(self.char_start) self.word_end = self.char_to_word_idx(self.char_end - 1) # Store extra attributes for attr, values in attributes.items(): setattr(self, attr, values) def _get_char_offsets(self, char_offsets): """Store or calculate char_offsets, adding the offset of the doc end""" if char_offsets: char_offsets = char_offsets char_offsets.append(len(self.text)) else: char_offsets = np.zeros(len(self.tokens) + 1) for i, tok in enumerate(self.tokens): # Add 1 to account for the spaces between tokens char_offsets[i + 1] = char_offsets[i] + len(tok) + 1 char_offsets[-1] = len(self.text) return np.array(char_offsets) def word_to_char_idx(self, word_idx): """Converts a word index to a character offset Returns the offset of the first character of the token with the given index. """ return self.char_offsets[word_idx] def char_to_word_idx(self, char_offset): """Converts a character offset to a token index Finds the first index of a True (i.e., the index of the first token that is past the desired token) and subtracts one. """ return np.argmax(self.char_offsets > char_offset) - 1 def get_entity_attrib(self, attrib): attrib_tokens = self.get(attrib, None) return attrib_tokens[self.word_start : self.word_end + 1] @property def words(self): return self.tokens def __repr__(self): return ( f"EntityMention(doc_id={self.doc_id}: '{self.entity}'" f"({self.char_start}:{self.char_end})" ) def __hash__(self): return hash((self.doc_id, self.char_start, self.char_end)) class RelationMention(object): """A mention of a relation between two spans of text (entities) in a doc Args: doc_id: a unique identifier for the document text: a single string of text corresponding to the document entity_positions: a list with two elements, each a tuple of the integer offsets (in characters) of the corresponding entity in the text so that text[char_start:char_end] returns the full entity tokens: (optional) a list of tokens corresponding to the text. If None, tokenization on whitespace is the default. char_offsets: (optional) a list of character offsets corresponding to the tokens in tokens. If None, we assume all tokens are separated by a single space. attributes: (optional) additional lists of attributes corresponding to the provided tokens (e.g., pos tags, ner tags, types, etc.) TODO: There is currently inefficiency in the way each EntityMention in a RelationMention stores all properties of a sentence. Instead, create a Sentence object that each EntityMention points to and store the properties with the sentence. """ def __init__( self, doc_id, text, entity_positions, tokens=None, char_offsets=None, mention_id=None, **attributes, ): self.doc_id = doc_id self.entity_positions = entity_positions self.entities = [ EntityMention(doc_id, text, *cp, tokens, char_offsets, **attributes) for cp in entity_positions ] self.mention_id = mention_id if mention_id else hash(self) @property def text(self): return self.entities[0].text @property def tokens(self): return self.entities[0].tokens @property def words(self): return self.entities[0].tokens @property def word_starts(self): return [e.word_start for e in self.entities] @property def word_ends(self): return [e.word_end for e in self.entities] @property def word_positions(self): return [(e.word_start, e.word_end) for e in self.entities] def get_attr(self, attr): return self.entities[0].get(attr, None) def __getitem__(self, key): return self.entities[key] def __repr__(self): entities = ", ".join( [f'"{e.entity}"({e.char_start}:{e.char_end})' for e in self.entities] ) return f"""RelationMention(doc_id={self.doc_id}: entities=({entities})""" def __hash__(self): return hash((self.doc_id, tuple(self.entity_positions)))
metal-master
metal/contrib/info_extraction/mentions.py
from metal.contrib.modules.sparse_linear_module import SparseLinearModule from metal.end_model import EndModel from metal.utils import recursive_merge_dicts class SparseLogisticRegression(EndModel): """A _sparse_ logistic regression classifier for a single-task problem Args: input_dim: The maximum length of each input (a tensor of integer indices corresponding to one-hot features) output_dim: The cardinality of the classifier padding_idx: If not None, the embedding initialized to 0 so no gradient will pass through it. """ def __init__(self, input_dim, output_dim=2, padding_idx=0, **kwargs): layer_out_dims = [input_dim, output_dim] sparse_linear = SparseLinearModule( vocab_size=input_dim, embed_size=output_dim, padding_idx=padding_idx ) overrides = {"input_batchnorm": False, "input_dropout": 0.0} kwargs = recursive_merge_dicts( kwargs, overrides, misses="insert", verbose=False ) super().__init__(layer_out_dims, head_module=sparse_linear, **kwargs)
metal-master
metal/contrib/baselines/sparse_logreg.py
from .lstm_module import EmbeddingsEncoder, Encoder, LSTMModule from .resnet_cifar10 import ResNetModule from .sparse_linear_module import SparseLinearModule __all__ = [ "LSTMModule", "Encoder", "EmbeddingsEncoder", "ResNetModule", "SparseLinearModule", ]
metal-master
metal/contrib/modules/__init__.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.rnn as rnn_utils from metal.utils import set_seed class Encoder(nn.Module): """The Encoder implements the encode() method, which maps a batch of data to encoded output of dimension [batch_size, max_seq_len, encoded_size] The first argument must be the encoded size of the Encoder output. Args: encoded_size: (int) Output feature dimension of the Encoder """ def __init__(self, encoded_size, verbose=True): super().__init__() self.encoded_size = encoded_size def encode(self, X): """ Args: X: (torch.LongTensor) of shape [batch_size, max_seq_length, encoded_size], with all-0s vectors as padding. """ assert X.shape[-1] == self.encoded_size return X.float() class EmbeddingsEncoder(Encoder): def __init__( self, encoded_size, vocab_size=None, embeddings=None, freeze=False, verbose=True, seed=None, **kwargs, ): """ Args: encoded_size: (in) Output feature dimension of the Encoder, and input feature dimension of the LSTM vocab_size: The size of the vocabulary of the embeddings If embeddings=None, this helps to set the size of the randomly initialized embeddings If embeddings != None, this is used to double check that the provided embeddings have the intended size embeddings: An optional embedding Tensor freeze: If False, allow the embeddings to be updated """ super().__init__(encoded_size) self.verbose = verbose # Load provided embeddings or randomly initialize new ones if embeddings is None: # Note: Need to set seed here for deterministic init if seed is not None: set_seed(seed) self.embeddings = nn.Embedding(vocab_size, encoded_size) if self.verbose: print(f"Using randomly initialized embeddings.") else: self.embeddings = self._load_pretrained(embeddings) if self.verbose: print(f"Using pretrained embeddings.") # Freeze or not self.embeddings.weight.requires_grad = not freeze if self.verbose: print( f"Embeddings shape = ({self.embeddings.num_embeddings}, " f"{self.embeddings.embedding_dim})" ) print(f"The embeddings are {'' if freeze else 'NOT '}FROZEN") def _load_pretrained(self, pretrained): if not pretrained.dim() == 2: msg = ( f"Provided embeddings have shape {pretrained.shape}. " "Expected a 2-dimensional tensor." ) raise ValueError(msg) rows, cols = pretrained.shape embedding = nn.Embedding(num_embeddings=rows, embedding_dim=cols) embedding.weight.data.copy_(pretrained) return embedding def encode(self, X): """ Args: X: (torch.LongTensor) of shape [batch_size, max_seq_length], containing the indices of the embeddings to look up for each item in the batch, or 0 for padding. """ return self.embeddings(X.long()) class CNNEncoder(nn.Module): def encode(self, X): """ Args: X: (torch.LongTensor) of shape [batch_size, max_seq_length, encoded_size], with all-0s vectors as padding. """ raise NotImplementedError() class LSTMModule(nn.Module): """An LSTM-based input module""" def __init__( self, encoded_size, hidden_size, lstm_reduction="max", bidirectional=True, verbose=True, seed=None, lstm_num_layers=1, encoder_class=Encoder, encoder_kwargs={}, **kwargs, ): """ Args: encoder: An Encoder object with encode() method that maps from input sequences to [batch_size, max_seq_len, feature_dim] hidden_size: (int) The size of the hidden layer in the LSTM lstm_reduction: One of ['mean', 'max', 'last', 'attention'] denoting what to return as the output of the LSTMLayer freeze: If False, allow the embeddings to be updated skip_embeddings: If True, directly accept X without using embeddings """ super().__init__() self.output_dim = hidden_size * 2 if bidirectional else hidden_size self.verbose = verbose if seed is not None: set_seed(seed) # Initialize Encoder # Note constructing the Encoder here is helpful for e.g. Tuner, as then # all model params initialized here encoder_kwargs["verbose"] = self.verbose self.encoder = encoder_class(encoded_size, **encoder_kwargs) self.lstm_reduction = lstm_reduction if self.verbose: print(f"Using lstm_reduction = '{lstm_reduction}'") # Create lstm core # NOTE: We only pass explicitly-named kwargs here; can always add more! self.lstm = nn.LSTM( self.encoder.encoded_size, hidden_size, num_layers=lstm_num_layers, batch_first=True, bidirectional=bidirectional, ) if lstm_reduction == "attention": att_size = hidden_size * (self.lstm.bidirectional + 1) att_param = nn.Parameter(torch.FloatTensor(att_size, 1)) nn.init.xavier_normal_(att_param) self.attention_param = att_param def _attention(self, output): # output is of shape (seq_length, hidden_size) score = torch.matmul(output, self.attention_param).squeeze() score = F.softmax(score, dim=0).view(output.size(0), 1) scored_output = output * score condensed_output = torch.sum(scored_output, dim=0) return condensed_output def reset_parameters(self): # Note: Classifier.reset() calls reset_parameters() recursively on all # children, so this method need not reset children modules such as # nn.lstm or nn.Embedding pass def _reduce_output(self, outputs, seq_lengths): """Reduces the output of an LSTM step Args: outputs: (torch.FloatTensor) the hidden state outputs from the lstm, with shape [batch_size, max_seq_length, hidden_size] """ batch_size = outputs.shape[0] reduced = [] # Necessary to iterate over batch because of different sequence lengths for i in range(batch_size): if self.lstm_reduction == "mean": # Average over all non-padding reduced # Use dim=0 because first dimension disappears after indexing reduced.append(outputs[i, : seq_lengths[i], :].mean(dim=0)) elif self.lstm_reduction == "max": # Max-pool over all non-padding reduced # Use dim=0 because first dimension disappears after indexing reduced.append(outputs[i, : seq_lengths[i], :].max(dim=0)[0]) elif self.lstm_reduction == "last": # Take the last output of the sequence (before padding starts) # NOTE: maybe better to take first and last? reduced.append(outputs[i, seq_lengths[i] - 1, :]) elif self.lstm_reduction == "attention": reduced.append(self._attention(outputs[i, : seq_lengths[i], :])) else: msg = ( f"Did not recognize lstm kwarg 'lstm_reduction' == " f"{self.lstm_reduction}" ) raise ValueError(msg) return torch.stack(reduced, dim=0) def forward(self, X): """Applies one step of an lstm (plus reduction) to the input X, which is handled by self.encoder""" # Identify the first non-zero integer from the right (i.e., the length # of the sequence before padding starts). batch_size, max_seq = X.shape[0], X.shape[1] seq_lengths = torch.zeros(batch_size, dtype=torch.long) for i in range(batch_size): for j in range(max_seq - 1, -1, -1): if not torch.all(X[i, j] == 0): seq_lengths[i] = j + 1 break # Sort by length because pack_padded_sequence requires it # Save original order to restore before returning seq_lengths, perm_idx = seq_lengths.sort(0, descending=True) X = X[perm_idx] inv_perm_idx = torch.tensor( [i for i, _ in sorted(enumerate(perm_idx), key=lambda idx: idx[1])], dtype=torch.long, ) # Encode and pack input sequence X_packed = rnn_utils.pack_padded_sequence( self.encoder.encode(X), seq_lengths, batch_first=True ) # Run LSTM outputs, (h_t, c_t) = self.lstm(X_packed) # Unpack and reduce outputs outputs_unpacked, _ = rnn_utils.pad_packed_sequence(outputs, batch_first=True) reduced = self._reduce_output(outputs_unpacked, seq_lengths) return reduced[inv_perm_idx, :]
metal-master
metal/contrib/modules/lstm_module.py
import math import torch import torch.nn as nn class SparseLinearModule(nn.Module): def __init__(self, embed_size, vocab_size, padding_idx=0): super().__init__() self.vocab_size = vocab_size self.padding_idx = padding_idx self.W = nn.Embedding( vocab_size, embed_size, sparse=True, padding_idx=padding_idx ) self.b = nn.Parameter(torch.Tensor(embed_size)) self.reset_parameters() def reset_parameters(self): stdv = 1.0 / math.sqrt(self.vocab_size) self.W.weight.data.uniform_(-stdv, stdv) self.b.data.uniform_(-stdv, stdv) if self.padding_idx is not None: self.W.weight.data[self.padding_idx].fill_(0) def forward(self, X): """Execute sparse linear layer Args: X: an [n, h] torch.LongTensor containing up to h indices of features whose weights should be looked up and used in a sparse linear multiplication. """ return self.W(X).sum(dim=1) + self.b
metal-master
metal/contrib/modules/sparse_linear_module.py
"""ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 """ import torch import torch.nn as nn import torch.nn.functional as F class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d( in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False ) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d( planes, planes, kernel_size=3, stride=1, padding=1, bias=False ) self.bn2 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential( nn.Conv2d( in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False, ), nn.BatchNorm2d(self.expansion * planes), ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = F.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d( planes, planes, kernel_size=3, stride=stride, padding=1, bias=False ) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d( planes, self.expansion * planes, kernel_size=1, bias=False ) self.bn3 = nn.BatchNorm2d(self.expansion * planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential( nn.Conv2d( in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False, ), nn.BatchNorm2d(self.expansion * planes), ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = F.relu(self.bn2(self.conv2(out))) out = self.bn3(self.conv3(out)) out += self.shortcut(x) out = F.relu(out) return out class ResNetModule(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNetModule, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) self.linear = nn.Linear(512 * block.expansion, num_classes) def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.layer1(out) out = self.layer2(out) out = self.layer3(out) out = self.layer4(out) out = F.avg_pool2d(out, 4) out = out.view(out.size(0), -1) out = self.linear(out) return out def ResNet18(): return ResNetModule(BasicBlock, [2, 2, 2, 2]) def ResNet34(): return ResNetModule(BasicBlock, [3, 4, 6, 3]) def ResNet50(): return ResNetModule(Bottleneck, [3, 4, 6, 3]) def ResNet101(): return ResNetModule(Bottleneck, [3, 4, 23, 3]) def ResNet152(): return ResNetModule(Bottleneck, [3, 8, 36, 3]) def test(): net = ResNet18() y = net(torch.randn(1, 3, 32, 32)) print(y.size())
metal-master
metal/contrib/modules/resnet_cifar10.py
from collections import Counter from functools import partial from itertools import chain, product import numpy as np import torch import torch.nn as nn from scipy.sparse import issparse from torch.utils.data import DataLoader from metal.classifier import Classifier from metal.label_model.graph_utils import get_clique_tree from metal.label_model.lm_defaults import lm_default_config from metal.utils import MetalDataset, recursive_merge_dicts class LabelModel(Classifier): """A LabelModel...TBD Args: k: (int) the cardinality of the classifier """ # This class variable is explained in the Classifier class implements_l2 = True def __init__(self, k=2, **kwargs): config = recursive_merge_dicts(lm_default_config, kwargs) super().__init__(k, config) def _check_L(self, L): """Run some basic checks on L.""" # TODO: Take this out? if issparse(L): L = L.todense() # Check for correct values, e.g. warning if in {-1,0,1} if np.any(L < 0): raise ValueError("L must have values in {0,1,...,k}.") def _create_L_ind(self, L): """Convert a label matrix with labels in 0...k to a one-hot format Args: L: An [n,m] scipy.sparse label matrix with values in {0,1,...,k} Returns: L_ind: An [n,m*k] dense np.ndarray with values in {0,1} Note that no column is required for 0 (abstain) labels. """ # TODO: Update LabelModel to keep L variants as sparse matrices # throughout and remove this line. if issparse(L): L = L.todense() L_ind = np.zeros((self.n, self.m * self.k)) for y in range(1, self.k + 1): # A[x::y] slices A starting at x at intervals of y # e.g., np.arange(9)[0::3] == np.array([0,3,6]) L_ind[:, (y - 1) :: self.k] = np.where(L == y, 1, 0) return L_ind def _get_augmented_label_matrix(self, L, higher_order=False): """Returns an augmented version of L where each column is an indicator for whether a certain source or clique of sources voted in a certain pattern. Args: L: An [n,m] scipy.sparse label matrix with values in {0,1,...,k} """ # Create a helper data structure which maps cliques (as tuples of member # sources) --> {start_index, end_index, maximal_cliques}, where # the last value is a set of indices in this data structure self.c_data = {} for i in range(self.m): self.c_data[i] = { "start_index": i * self.k, "end_index": (i + 1) * self.k, "max_cliques": set( [ j for j in self.c_tree.nodes() if i in self.c_tree.node[j]["members"] ] ), } L_ind = self._create_L_ind(L) # Get the higher-order clique statistics based on the clique tree # First, iterate over the maximal cliques (nodes of c_tree) and # separator sets (edges of c_tree) if higher_order: L_aug = np.copy(L_ind) for item in chain(self.c_tree.nodes(), self.c_tree.edges()): if isinstance(item, int): C = self.c_tree.node[item] C_type = "node" elif isinstance(item, tuple): C = self.c_tree[item[0]][item[1]] C_type = "edge" else: raise ValueError(item) members = list(C["members"]) nc = len(members) # If a unary maximal clique, just store its existing index if nc == 1: C["start_index"] = members[0] * self.k C["end_index"] = (members[0] + 1) * self.k # Else add one column for each possible value else: L_C = np.ones((self.n, self.k ** nc)) for i, vals in enumerate(product(range(self.k), repeat=nc)): for j, v in enumerate(vals): L_C[:, i] *= L_ind[:, members[j] * self.k + v] # Add to L_aug and store the indices if L_aug is not None: C["start_index"] = L_aug.shape[1] C["end_index"] = L_aug.shape[1] + L_C.shape[1] L_aug = np.hstack([L_aug, L_C]) else: C["start_index"] = 0 C["end_index"] = L_C.shape[1] L_aug = L_C # Add to self.c_data as well id = tuple(members) if len(members) > 1 else members[0] self.c_data[id] = { "start_index": C["start_index"], "end_index": C["end_index"], "max_cliques": set([item]) if C_type == "node" else set(item), } return L_aug else: return L_ind def _build_mask(self): """Build mask applied to O^{-1}, O for the matrix approx constraint""" self.mask = torch.ones(self.d, self.d).byte() for ci in self.c_data.values(): si, ei = ci["start_index"], ci["end_index"] for cj in self.c_data.values(): sj, ej = cj["start_index"], cj["end_index"] # Check if ci and cj are part of the same maximal clique # If so, mask out their corresponding blocks in O^{-1} if len(ci["max_cliques"].intersection(cj["max_cliques"])) > 0: self.mask[si:ei, sj:ej] = 0 self.mask[sj:ej, si:ei] = 0 def _generate_O(self, L): """Form the overlaps matrix, which is just all the different observed combinations of values of pairs of sources Note that we only include the k non-abstain values of each source, otherwise the model not minimal --> leads to singular matrix """ L_aug = self._get_augmented_label_matrix(L) self.d = L_aug.shape[1] self.O = torch.from_numpy(L_aug.T @ L_aug / self.n).float() def _generate_O_inv(self, L): """Form the *inverse* overlaps matrix""" self._generate_O(L) self.O_inv = torch.from_numpy(np.linalg.inv(self.O.numpy())).float() def _init_params(self): """Initialize the learned params - \mu is the primary learned parameter, where each row corresponds to the probability of a clique C emitting a specific combination of labels, conditioned on different values of Y (for each column); that is: self.mu[i*self.k + j, y] = P(\lambda_i = j | Y = y) and similarly for higher-order cliques. - Z is the inverse form version of \mu. """ train_config = self.config["train_config"] # Initialize mu so as to break basic reflective symmetry # Note that we are given either a single or per-LF initial precision # value, prec_i = P(Y=y|\lf=y), and use: # mu_init = P(\lf=y|Y=y) = P(\lf=y) * prec_i / P(Y=y) # Handle single or per-LF values if isinstance(train_config["prec_init"], (int, float)): prec_init = train_config["prec_init"] * torch.ones(self.m) else: prec_init = torch.from_numpy(train_config["prec_init"]) if prec_init.shape[0] != self.m: raise ValueError(f"prec_init must have shape {self.m}.") # Get the per-value labeling propensities # Note that self.O must have been computed already! lps = torch.diag(self.O).numpy() # TODO: Update for higher-order cliques! self.mu_init = torch.zeros(self.d, self.k) for i in range(self.m): for y in range(self.k): idx = i * self.k + y mu_init = torch.clamp(lps[idx] * prec_init[i] / self.p[y], 0, 1) self.mu_init[idx, y] += mu_init # Initialize randomly based on self.mu_init self.mu = nn.Parameter(self.mu_init.clone() * np.random.random()).float() if self.inv_form: self.Z = nn.Parameter(torch.randn(self.d, self.k)).float() # Build the mask over O^{-1} # TODO: Put this elsewhere? self._build_mask() def get_conditional_probs(self, source=None): """Returns the full conditional probabilities table as a numpy array, where row i*(k+1) + ly is the conditional probabilities of source i emmiting label ly (including abstains 0), conditioned on different values of Y, i.e.: c_probs[i*(k+1) + ly, y] = P(\lambda_i = ly | Y = y) Note that this simply involves inferring the kth row by law of total probability and adding in to mu. If `source` is not None, returns only the corresponding block. """ c_probs = np.zeros((self.m * (self.k + 1), self.k)) mu = self.mu.detach().clone().numpy() for i in range(self.m): # si = self.c_data[(i,)]['start_index'] # ei = self.c_data[(i,)]['end_index'] # mu_i = mu[si:ei, :] mu_i = mu[i * self.k : (i + 1) * self.k, :] c_probs[i * (self.k + 1) + 1 : (i + 1) * (self.k + 1), :] = mu_i # The 0th row (corresponding to abstains) is the difference between # the sums of the other rows and one, by law of total prob c_probs[i * (self.k + 1), :] = 1 - mu_i.sum(axis=0) c_probs = np.clip(c_probs, 0.01, 0.99) if source is not None: return c_probs[source * (self.k + 1) : (source + 1) * (self.k + 1)] else: return c_probs def predict_proba(self, L): """Returns the [n,k] matrix of label probabilities P(Y | \lambda) Args: L: An [n,m] scipy.sparse label matrix with values in {0,1,...,k} """ self._set_constants(L) L_aug = self._get_augmented_label_matrix(L) mu = np.clip(self.mu.detach().clone().numpy(), 0.01, 0.99) # Create a "junction tree mask" over the columns of L_aug / mu if len(self.deps) > 0: jtm = np.zeros(L_aug.shape[1]) # All maximal cliques are +1 for i in self.c_tree.nodes(): node = self.c_tree.node[i] jtm[node["start_index"] : node["end_index"]] = 1 # All separator sets are -1 for i, j in self.c_tree.edges(): edge = self.c_tree[i][j] jtm[edge["start_index"] : edge["end_index"]] = 1 else: jtm = np.ones(L_aug.shape[1]) # Note: We omit abstains, effectively assuming uniform distribution here X = np.exp(L_aug @ np.diag(jtm) @ np.log(mu) + np.log(self.p)) Z = np.tile(X.sum(axis=1).reshape(-1, 1), self.k) return X / Z def get_Q(self): """Get the model's estimate of Q = \mu P \mu^T We can then separately extract \mu subject to additional constraints, e.g. \mu P 1 = diag(O). """ Z = self.Z.detach().clone().numpy() O = self.O.numpy() I_k = np.eye(self.k) return O @ Z @ np.linalg.inv(I_k + Z.T @ O @ Z) @ Z.T @ O # These loss functions get all their data directly from the LabelModel # (for better or worse). The unused *args make these compatible with the # Classifer._train() method which expect loss functions to accept an input. def loss_l2(self, l2=0): """L2 loss centered around mu_init, scaled optionally per-source. In other words, diagonal Tikhonov regularization, ||D(\mu-\mu_{init})||_2^2 where D is diagonal. Args: - l2: A float or np.array representing the per-source regularization strengths to use """ if isinstance(l2, (int, float)): D = l2 * torch.eye(self.d) else: D = torch.diag(torch.from_numpy(l2)) # Note that mu is a matrix and this is the *Frobenius norm* return torch.norm(D @ (self.mu - self.mu_init)) ** 2 def loss_inv_Z(self, *args): return torch.norm((self.O_inv + self.Z @ self.Z.t())[self.mask]) ** 2 def loss_inv_mu(self, *args, l2=0): loss_1 = torch.norm(self.Q - self.mu @ self.P @ self.mu.t()) ** 2 loss_2 = torch.norm(torch.sum(self.mu @ self.P, 1) - torch.diag(self.O)) ** 2 return loss_1 + loss_2 + self.loss_l2(l2=l2) def loss_mu(self, *args, l2=0): loss_1 = torch.norm((self.O - self.mu @ self.P @ self.mu.t())[self.mask]) ** 2 loss_2 = torch.norm(torch.sum(self.mu @ self.P, 1) - torch.diag(self.O)) ** 2 return loss_1 + loss_2 + self.loss_l2(l2=l2) def _set_class_balance(self, class_balance, Y_dev): """Set a prior for the class balance In order of preference: 1) Use user-provided class_balance 2) Estimate balance from Y_dev 3) Assume uniform class distribution """ if class_balance is not None: self.p = np.array(class_balance) elif Y_dev is not None: class_counts = Counter(Y_dev) sorted_counts = np.array([v for k, v in sorted(class_counts.items())]) self.p = sorted_counts / sum(sorted_counts) else: self.p = (1 / self.k) * np.ones(self.k) self.P = torch.diag(torch.from_numpy(self.p)).float() def _set_constants(self, L): self.n, self.m = L.shape self.t = 1 def _set_dependencies(self, deps): nodes = range(self.m) self.deps = deps self.c_tree = get_clique_tree(nodes, deps) def train_model( self, L_train, Y_dev=None, deps=[], class_balance=None, log_writer=None, **kwargs, ): """Train the model (i.e. estimate mu) in one of two ways, depending on whether source dependencies are provided or not: Args: L_train: An [n,m] scipy.sparse matrix with values in {0,1,...,k} corresponding to labels from supervision sources on the training set Y_dev: Target labels for the dev set, for estimating class_balance deps: (list of tuples) known dependencies between supervision sources. If not provided, sources are assumed to be independent. TODO: add automatic dependency-learning code class_balance: (np.array) each class's percentage of the population (1) No dependencies (conditionally independent sources): Estimate mu subject to constraints: (1a) O_{B(i,j)} - (mu P mu.T)_{B(i,j)} = 0, for i != j, where B(i,j) is the block of entries corresponding to sources i,j (1b) np.sum( mu P, 1 ) = diag(O) (2) Source dependencies: - First, estimate Z subject to the inverse form constraint: (2a) O_\Omega + (ZZ.T)_\Omega = 0, \Omega is the deps mask - Then, compute Q = mu P mu.T - Finally, estimate mu subject to mu P mu.T = Q and (1b) """ self.config = recursive_merge_dicts(self.config, kwargs, misses="ignore") train_config = self.config["train_config"] # TODO: Implement logging for label model? if log_writer is not None: raise NotImplementedError("Logging for LabelModel.") # Note that the LabelModel class implements its own (centered) L2 reg. l2 = train_config.get("l2", 0) self._set_class_balance(class_balance, Y_dev) self._set_constants(L_train) self._set_dependencies(deps) self._check_L(L_train) # Whether to take the simple conditionally independent approach, or the # "inverse form" approach for handling dependencies # This flag allows us to eg test the latter even with no deps present self.inv_form = len(self.deps) > 0 # Creating this faux dataset is necessary for now because the LabelModel # loss functions do not accept inputs, but Classifer._train_model() # expects training data to feed to the loss functions. dataset = MetalDataset([0], [0]) train_loader = DataLoader(dataset) if self.inv_form: # Compute O, O^{-1}, and initialize params if self.config["verbose"]: print("Computing O^{-1}...") self._generate_O_inv(L_train) self._init_params() # Estimate Z, compute Q = \mu P \mu^T if self.config["verbose"]: print("Estimating Z...") self._train_model(train_loader, self.loss_inv_Z) self.Q = torch.from_numpy(self.get_Q()).float() # Estimate \mu if self.config["verbose"]: print("Estimating \mu...") self._train_model(train_loader, partial(self.loss_inv_mu, l2=l2)) else: # Compute O and initialize params if self.config["verbose"]: print("Computing O...") self._generate_O(L_train) self._init_params() # Estimate \mu if self.config["verbose"]: print("Estimating \mu...") self._train_model(train_loader, partial(self.loss_mu, l2=l2))
metal-master
metal/label_model/label_model.py
import numpy as np from metal.label_model.label_model import LabelModel class RandomVoter(LabelModel): """ A class that votes randomly among the available labels """ def train_model(self, *args, **kwargs): pass def predict_proba(self, L): """ Args: L: An [n, m] scipy.sparse matrix of labels Returns: output: A [n, k] np.ndarray of probabilistic labels """ n = L.shape[0] Y_p = np.random.rand(n, self.k) Y_p /= Y_p.sum(axis=1).reshape(-1, 1) return Y_p class MajorityClassVoter(RandomVoter): """ A class that places all probability on the majority class based on class balance (and ignoring the label matrix). Note that in the case of ties, non-integer probabilities are possible. """ def train_model(self, balance, *args, **kwargs): """ Args: balance: A 1d arraylike that sums to 1, corresponding to the (possibly estimated) class balance. """ self.balance = np.array(balance) def predict_proba(self, L): n = L.shape[0] Y_p = np.zeros((n, self.k)) max_classes = np.where(self.balance == max(self.balance)) for c in max_classes: Y_p[:, c] = 1.0 Y_p /= Y_p.sum(axis=1).reshape(-1, 1) return Y_p class MajorityLabelVoter(RandomVoter): """ A class that places all probability on the majority label from all non-abstaining LFs for that task. Note that in the case of ties, non-integer probabilities are possible. """ def train_model(self, *args, **kwargs): pass def predict_proba(self, L): L = self._to_numpy(L).astype(int) n, m = L.shape Y_p = np.zeros((n, self.k)) for i in range(n): counts = np.zeros(self.k) for j in range(m): if L[i, j]: counts[L[i, j] - 1] += 1 Y_p[i, :] = np.where(counts == max(counts), 1, 0) Y_p /= Y_p.sum(axis=1).reshape(-1, 1) return Y_p
metal-master
metal/label_model/baselines.py
from itertools import product import numpy as np import torch from torch import nn, optim class ClassBalanceModel(nn.Module): """A model for learning the class balance, P(Y=y), given a subset of LFs which are *conditionally independent*, i.e. \lambda_i \perp \lambda_j | Y, for i != j. Learns the model using a tensor factorization approach. Note: This approach can also be used for estimation of the LabelModel, may want to later refactor and expand this class. """ def __init__(self, k, abstains=True, config=None): super().__init__() self.config = config self.k = k # The cardinality of the true label, Y \in {1,...,k} # Labeling functions output labels in range {k_0,...,k}, and have # cardinality k_lf # If abstains=False, k_0 = 1 ==> k_lf = k # If abstains=True, k_0 = 0 ==> k_lf = k + 1 self.abstains = abstains self.k_0 = 0 if self.abstains else 1 self.k_lf = k + 1 if self.abstains else k # Estimated quantities (np.array) self.cond_probs = None self.class_balance = None def _get_overlaps_tensor(self, L): """Transforms the input label matrix to a three-way overlaps tensor. Args: L: (np.array) An n x m array of LF output labels, in {0,...,k} if self.abstains, else in {1,...,k}, generated by m conditionally independent LFs on n data points Outputs: O: (torch.Tensor) A (m, m, m, k, k, k) tensor of the label-specific empirical overlap rates; that is, O[i,j,k,y1,y2,y3] = P(\lf_i = y1, \lf_j = y2, \lf_k = y3) where this quantity is computed empirically by this function, based on the label matrix L. """ n, m = L.shape # Convert from a (n,m) matrix of ints to a (k_lf, n, m) indicator tensor LY = np.array([np.where(L == y, 1, 0) for y in range(self.k_0, self.k + 1)]) # Form the three-way overlaps matrix O = np.einsum("abc,dbe,fbg->cegadf", LY, LY, LY) / n return torch.from_numpy(O).float() def get_mask(self, m): """Get the mask for the three-way overlaps matrix O, which is 0 when indices i,j,k are not unique""" mask = torch.ones((m, m, m, self.k_lf, self.k_lf, self.k_lf)).byte() for i, j, k in product(range(m), repeat=3): if len(set((i, j, k))) < 3: mask[i, j, k, :, :, :] = 0 return mask @staticmethod def get_loss(O, Q, mask): # Main constraint: match empirical three-way overlaps matrix # (entries O_{ijk} for i != j != k) diffs = (O - torch.einsum("aby,cdy,efy->acebdf", [Q, Q, Q]))[mask] return torch.norm(diffs) ** 2 def train_model(self, L=None, O=None, lr=1, max_iter=1000, verbose=False): # Get overlaps tensor if L provided else use O directly (e.g. for tests) if O is not None: pass elif L is not None: O = self._get_overlaps_tensor(L) else: raise ValueError("L or O required as input.") self.m = O.shape[0] # Compute mask self.mask = self.get_mask(self.m) # Initialize parameters self.Q = nn.Parameter(torch.rand(self.m, self.k_lf, self.k)).float() # Use L-BFGS here # Seems to be a tricky problem for simple 1st order approaches, and # small enough for quasi-Newton... L-BFGS seems to work well here optimizer = optim.LBFGS([self.Q], lr=lr, max_iter=max_iter) # The closure computes the loss def closure(): optimizer.zero_grad() loss = self.get_loss(O, self.Q, self.mask) loss.backward() if verbose: print(f"Loss: {loss.detach():.8f}") return loss # Perform optimizer step optimizer.step(closure) # Recover the class balance # Note that the columns are not necessarily ordered correctly at this # point, since there's a column-wise symmetry remaining q = self.Q.detach().numpy() p_y = np.mean(q.sum(axis=1) ** 3, axis=0) # Resolve remaining col-wise symmetry # We do this by first estimating the conditional probabilities (accs.) # P(\lambda_i = y' | Y = y) of the labeling functions, *then leveraging # the assumption that they are better than random* to resolve col-wise # symmetries here # Note we then store both the estimated conditional probs, and the class # balance # Recover the estimated cond probs: Q = C(P^{1/3}) --> C = Q(P^{-1/3}) cps = q @ np.diag(1 / p_y ** (1 / 3)) # Note: For assessing the order, we only care about the non-abstains if self.k_lf > self.k: cps_na = cps[:, 1:, :] else: cps_na = cps # Re-order cps and p_y using assumption and store np.array values # Note: We take the *most common* ordering vals, counts = np.unique(cps_na.argmax(axis=2), axis=0, return_counts=True) col_order = vals[counts.argmax()] self.class_balance = p_y[col_order] self.cond_probs = cps[:, :, col_order]
metal-master
metal/label_model/class_balance.py
import networkx as nx def get_clique_tree(nodes, edges): """Given a set of int nodes i and edges (i,j), returns an nx.Graph object G which is a clique tree, where: - G.node[i]['members'] contains the set of original nodes in the ith maximal clique - G[i][j]['members'] contains the set of original nodes in the seperator set between maximal cliques i and j Note: This method is currently only implemented for chordal graphs; TODO: add a step to triangulate non-chordal graphs. """ # Form the original graph G1 G1 = nx.Graph() G1.add_nodes_from(nodes) G1.add_edges_from(edges) # Check if graph is chordal # TODO: Add step to triangulate graph if not if not nx.is_chordal(G1): raise NotImplementedError("Graph triangulation not implemented.") # Create maximal clique graph G2 # Each node is a maximal clique C_i # Let w = |C_i \cap C_j|; C_i, C_j have an edge with weight w if w > 0 G2 = nx.Graph() for i, c in enumerate(nx.chordal_graph_cliques(G1)): G2.add_node(i, members=c) for i in G2.nodes: for j in G2.nodes: S = G2.node[i]["members"].intersection(G2.node[j]["members"]) w = len(S) if w > 0: G2.add_edge(i, j, weight=w, members=S) # Return a minimum spanning tree of G2 return nx.minimum_spanning_tree(G2)
metal-master
metal/label_model/graph_utils.py
lm_default_config = { # GENERAL "seed": None, "verbose": True, "show_plots": True, # Device (default GPU) "device": "cpu", # TRAIN "train_config": { # Dataloader "data_loader_config": {"batch_size": 1000, "num_workers": 1}, # Classifier # Class balance (if learn_class_balance=False, fix to class_balance) "learn_class_balance": False, # LF precision initializations / priors (float or np.array) "prec_init": 0.7, # Centered L2 regularization strength (int, float, or np.array) "l2": 0.0, # Optimizer "optimizer_config": { "optimizer": "sgd", "optimizer_common": {"lr": 0.01}, # Optimizer - SGD "sgd_config": {"momentum": 0.9}, }, # Scheduler "lr_scheduler": None, # Train loop "n_epochs": 100, "progress_bar": False, # Logger (see metal/logging/writer.py for descriptions) "logger": True, "logger_config": { "log_unit": "epochs", # ['seconds', 'examples', 'batches', 'epochs'] "log_train_every": 1, # How often train loss is reported "log_train_metrics": ["train/loss"], "log_train_metrics_func": None, "log_valid_every": 0, "log_valid_metrics": [], "log_valid_metrics_func": None, }, # Writer "writer": None, # Checkpointer "checkpoint": False, }, }
metal-master
metal/label_model/lm_defaults.py
from .baselines import MajorityClassVoter, MajorityLabelVoter, RandomVoter from .label_model import LabelModel __all__ = ["MajorityClassVoter", "MajorityLabelVoter", "RandomVoter", "LabelModel"]
metal-master
metal/label_model/__init__.py
import numpy as np def compute_mu(L_aug, Y, k, p): """Given label matrix L_aug and labels Y, compute the true mu params. Args: L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix Y: (np.array int) [n] The true labels in {1,...,k} k: (int) Cardinality p: (np.array float) [k] The class balance """ n, d = L_aug.shape assert Y.shape[0] == n # Compute mu mu = np.zeros((d, k)) for y in range(1, k + 1): L_y = L_aug[Y == y] mu[:, y - 1] = L_y.sum(axis=0) / L_y.shape[0] return mu def compute_covariance(L_aug, Y, k, p): """Given label matrix L_aug and labels Y, compute the covariance. Args: L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix Y: (np.array int) [n] The true labels in {1,...,k} k: (int) Cardinality p: (np.array float) [k] The class balance """ n, d = L_aug.shape assert Y.shape[0] == n mu = compute_mu(L_aug, Y, k, p) return (L_aug.T @ L_aug) / n - mu @ np.diag(p) @ mu.T def compute_inv_covariance(L_aug, Y, k, p): """Given label matrix L and labels Y, compute the covariance. Args: L: (np.array) [n, d] The augmented (indicator) label matrix Y: (np.array int) [n] The true labels in {1,...,k} """ return np.linalg.inv(compute_covariance(L_aug, Y, k, p)) def print_matrix(X, decimals=1): """Pretty printing for numpy matrix X""" for row in np.round(X, decimals=decimals): print(row)
metal-master
metal/label_model/utils.py
import numpy as np from scipy.sparse import issparse from metal.label_model import LabelModel from metal.label_model.lm_defaults import lm_default_config from metal.multitask import MTClassifier from metal.multitask.task_graph import TaskGraph from metal.utils import recursive_merge_dicts class MTLabelModel(MTClassifier, LabelModel): def __init__(self, K=None, task_graph=None, **kwargs): """ Args: K: A t-length list of task cardinalities (overrided by task_graph if task_graph is not None) task_graph: TaskGraph: A TaskGraph which defines a feasible set of task label vectors; overrides K if provided """ config = recursive_merge_dicts(lm_default_config, kwargs) MTClassifier.__init__(self, K, config) if task_graph is None: task_graph = TaskGraph(K) self.task_graph = task_graph # Note: While K is a list of the cardinalities of the tasks, k is the # cardinality of the feasible set. These are always the same for a # single-task model, but rarely the same for a multi-task model. self.k = self.task_graph.k def _set_constants(self, L): self.n, self.m = L[0].shape self.t = len(L) def _check_L(self, L): """Run some basic checks on L.""" # TODO: Take this out? if issparse(L[0]): L = [L_t.todense() for L_t in L] # Check for correct values, e.g. warning if in {-1,0,1} for L_t in L: if np.any(L_t < 0): raise ValueError("L must have values in {0,1,...,k}.") def _create_L_ind(self, L): """Convert T label matrices with labels in 0...K_t to a one-hot format Here we can view e.g. the $(i,j)$ entries of the $T$ label matrices as a _label vector_ emitted by LF j for data point i. Args: L: a T-length list of [n,m] scipy.sparse label matrices with values in {0,1,...,k} Returns: L_ind: An [n,m*k] dense np.ndarray with values in {0,1} Note that no column is required for 0 (abstain) labels. """ # TODO: Update LabelModel to keep L, L_ind, L_aug as sparse matrices # throughout and remove this line. if issparse(L[0]): L = [L_t.todense() for L_t in L] # Make sure converted to numpy here L = self._to_numpy(L) L_ind = np.ones((self.n, self.m * self.k)) for yi, y in enumerate(self.task_graph.feasible_set()): for t in range(self.t): # A[x::y] slices A starting at x at intervals of y # e.g., np.arange(9)[0::3] == np.array([0,3,6]) L_ind[:, yi :: self.k] *= np.where( np.logical_or(L[t] == y[t], L[t] == 0), 1, 0 ) # Set LFs that abstained on all feasible label vectors to all 0s L_ind[:, yi :: self.k] *= np.where(sum(L) != 0, 1, 0) return L_ind def predict_proba(self, L): """Returns the task marginals estimated by the model: a t-length list of [n,k_t] matrices where the (i,j) entry of the sth matrix represents the estimated P((Y_i)_s | \lambda_j(x_i)) Args: L: A t-length list of [n,m] scipy.sparse label matrices with values in {0,1,...,k} """ # First, get the estimated probability distribution over the feasible # set defined by the TaskGraph # This is an [n,k] array, where k = |(feasible set)| Y_pf = LabelModel.predict_proba(self, L) n, k = Y_pf.shape # Now get the per-task marginals # TODO: Make this optional, versus just returning the above Y_p = [np.zeros((n, k_t)) for k_t in self.task_graph.K] for yi, y in enumerate(self.task_graph.feasible_set()): for t in range(self.t): k_t = int(y[t]) Y_p[t][:, k_t - 1] += Y_pf[:, yi] return Y_p
metal-master
metal/multitask/mt_label_model.py
import numpy as np from metal.classifier import Classifier from metal.metrics import metric_score from metal.multitask.utils import MultiXYDataset, MultiYDataset class MTClassifier(Classifier): """Simple abstract base class for a *multi-class* probabilistic classifier. The main contribution of children classes will be an implementation of the predict_proba() method. The relationships between the six predict/score functions are as follows: score score_task | | predict predict_task | (default) | *predict_proba <- predict_task_proba Methods on the left return a list of results for all tasks (including a singleton list if there is only one task). Methods on the right return what would be a single element in the list returned by their counterpart on the left. The method predict_proba() method calculates the probabilistic labels, the predict() method handles tie-breaking, and the score() method calculates metrics based on predictions. Children classes must implement predict_proba so that interactions between tasks are handled correctly in applicable multi-task settings. If it is possible to calculate task probabilities independently, they may also override predict_task_proba for efficiency. Otherwise, predict_task_proba() will default to calling predict_proba and accessing element t. Args: K: (list) A t-length list of cardinalities (ints) for each task """ def __init__(self, K, config): Classifier.__init__(self, None, config) self.multitask = True self.K = K def predict_proba(self, X, **kwargs): """Predicts probabilistic labels for an input X on all tasks Args: X: An appropriate input for the child class of Classifier Returns: A t-length list of [n, K_t] np.ndarrays of probabilistic labels """ raise NotImplementedError def predict(self, X, break_ties="random", return_probs=False, **kwargs): """Predicts int labels for an input X on all tasks Args: X: The input for the predict_proba method break_ties: A tie-breaking policy return_probs: Return the predicted probabilities as well Returns: Y_p: A t-length list of n-dim np.ndarrays of predictions in [1, K_t] [Optionally: Y_s: A t-length list of [n, K_t] np.ndarrays of predicted probabilities] """ Y_s = self.predict_proba(X, **kwargs) self._check(Y_s, typ=list) self._check(Y_s[0], typ=np.ndarray) Y_p = [] for Y_ts in Y_s: Y_tp = self._break_ties(Y_ts, break_ties) Y_p.append(Y_tp.astype(np.int)) if return_probs: return Y_p, Y_s else: return Y_p def score( self, data, metric="accuracy", validation_task=None, reduce="mean", break_ties="random", verbose=True, print_confusion_matrix=False, **kwargs, ): """Scores the predictive performance of the Classifier on all tasks Args: data: either a Pytorch Dataset, DataLoader or tuple supplying (X,Y): X: The input for the predict method Y: A t-length list of [n] or [n, 1] np.ndarrays or torch.Tensors of gold labels in {1,...,K_t} metric: The metric with which to score performance on each task validation_task: int: returns score for specific task number. reduce: How to reduce the scores of multiple tasks: None : return a t-length list of scores 'mean': return the mean score across tasks break_ties: How to break ties when making predictions Returns: scores: A (float) score or a t-length list of such scores if reduce=None """ Y_p, Y, Y_s = self._get_predictions( data, break_ties=break_ties, return_probs=True, **kwargs ) # TODO: Handle multiple metrics... metric_list = metric if isinstance(metric, list) else [metric] if len(metric_list) > 1: raise NotImplementedError( "Multiple metrics for multi-task score() not yet supported." ) metric = metric_list[0] # Return score for task t only. if validation_task is not None: score = metric_score( Y[validation_task], Y_p[validation_task], metric, probs=Y_s[validation_task], ignore_in_gold=[0], ) if verbose: print(f"{metric.capitalize()}: {score:.3f}") return score task_scores = [] for t, Y_tp in enumerate(Y_p): score = metric_score(Y[t], Y_tp, metric, probs=Y_s[t], ignore_in_gold=[0]) task_scores.append(score) # TODO: Other options for reduce, including scoring only certain # primary tasks, and converting to end labels using TaskGraph... if reduce is None: score = task_scores elif reduce == "mean": score = np.mean(task_scores) else: raise Exception(f"Keyword reduce='{reduce}' not recognized.") if verbose: if reduce is None: for t, score_t in enumerate(score): print(f"{metric.capitalize()} (t={t}): {score_t:0.3f}") else: print(f"{metric.capitalize()}: {score:.3f}") return score def score_task(self, X, Y, t=0, metric="accuracy", verbose=True, **kwargs): """Scores the predictive performance of the Classifier on task t Args: X: The input for the predict_task method Y: A [n] or [n, 1] np.ndarray or torch.Tensor of gold labels in {1,...,K_t} t: The task index to score metric: The metric with which to score performance on this task Returns: The (float) score of the Classifier for the specified task and metric """ Y = self._to_numpy(Y) Y_tp = self.predict_task(X, t=t, **kwargs) probs = self.predict_proba(X)[t] score = metric_score( Y[t], Y_tp, metric, ignore_in_gold=[0], probs=probs, **kwargs ) if verbose: print(f"[t={t}] {metric.capitalize()}: {score:.3f}") return score def predict_task(self, X, t=0, break_ties="random", **kwargs): """Predicts int labels for an input X on task t Args: X: The input for the predict_task_proba method t: The task index to predict Returns: An n-dim tensor of int predictions for the specified task """ Y_tp = self.predict_task_proba(X, t=t, **kwargs) Y_tph = self._break_ties(Y_tp, break_ties) return Y_tph def predict_task_proba(self, X, t=0, **kwargs): """Predicts probabilistic labels for an input X on task t Args: X: The input for the predict_proba method t: The task index to predict for which to predict probabilities Returns: An [n, K_t] tensor of predictions for task t NOTE: By default, this method calls predict_proba and extracts element t. If it is possible to predict individual tasks in isolation, however, this method may be overriden for efficiency's sake. """ return self.predict_proba(X, **kwargs)[t] def _create_dataset(self, *data): X, Y = data if isinstance(X, list): return MultiXYDataset(X, Y) else: return MultiYDataset(X, Y) @staticmethod def _to_torch(Z, dtype=None): """Converts a None, list, np.ndarray, or torch.Tensor to torch.Tensor""" if isinstance(Z, list): return [Classifier._to_torch(z, dtype=dtype) for z in Z] else: return Classifier._to_torch(Z) @staticmethod def _to_numpy(Z): """Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray""" if isinstance(Z, list): return [Classifier._to_numpy(z) for z in Z] else: return Classifier._to_numpy(Z) @staticmethod def _stack_batches(X): """Given a list of batches, each consisting of a T-len list of np.ndarrays, stack along the first (batch) axis, returning a T-len list of np.ndarrays.""" return [Classifier._stack_batches(Xt) for Xt in zip(*X)]
metal-master
metal/multitask/mt_classifier.py
import copy from collections import defaultdict import torch import torch.nn as nn import torch.nn.functional as F from metal.end_model import EndModel from metal.end_model.em_defaults import em_default_config from metal.end_model.identity_module import IdentityModule from metal.end_model.loss import SoftCrossEntropyLoss from metal.multitask import MTClassifier from metal.multitask.mt_em_defaults import mt_em_default_config from metal.multitask.task_graph import TaskGraph from metal.utils import recursive_merge_dicts class MTEndModel(MTClassifier, EndModel): """A multi-task discriminative model. Note that when looking up methods, MTEndModel will first search in MTClassifier, followed by EndModel. Args: layer_out_dims: a list of integers corresponding to the output sizes of the layers of your network. The first element is the dimensionality of the input layer, and all other elements dictate the sizes of middle layers. The number of middle layers will be inferred from this list. The output dimensions of the task heads will be inferred from the cardinalities pulled from K or the task_graph. input_modules: (nn.Module) a list of modules that converts the user-provided model inputs to torch.Tensors. Defaults to IdentityModule. middle_modules: (nn.Module) a list of modules to execute between the input_module and task head. Defaults to nn.Linear. head_module: (nn.Module) a module to execute right before the final softmax that outputs a prediction for the task. K: A t-length list of task cardinalities (overrided by task_graph if task_graph is not None) task_graph: TaskGraph: A TaskGraph which defines a feasible set of task label vectors; overrides K """ def __init__( self, layer_out_dims, input_modules=None, middle_modules=None, head_modules=None, K=[], task_graph=None, **kwargs, ): kwargs["layer_out_dims"] = layer_out_dims # kwargs["input_modules"] = input_modules # kwargs["middle_modules"] = middle_modules # kwargs["head_modules"] = head_modules config = recursive_merge_dicts( em_default_config, mt_em_default_config, misses="insert" ) config = recursive_merge_dicts(config, kwargs) MTClassifier.__init__(self, K, config) if task_graph is None: if len(K) == 0: raise ValueError( "You must supply either a list of " "cardinalities (K) or a TaskGraph." ) task_graph = TaskGraph(K) self.task_graph = task_graph self.K = self.task_graph.K # Cardinalities by task self.t = self.task_graph.t # Total number of tasks assert len(self.K) == self.t self._build(input_modules, middle_modules, head_modules) # Show network if self.config["verbose"]: print("\nNetwork architecture:") self._print() print() def _build(self, input_modules, middle_modules, head_modules): """ TBD """ self.input_layer = self._build_input_layer(input_modules) self.middle_layers = self._build_middle_layers(middle_modules) self.heads = self._build_task_heads(head_modules) # Construct loss module reduction = self.config["train_config"]["loss_fn_reduction"] self.criteria = SoftCrossEntropyLoss(reduction=reduction) def _build_input_layer(self, input_modules): if input_modules is None: input_modules = IdentityModule() if isinstance(input_modules, list): input_layer = [ self._make_layer(mod, "input", self.config["input_layer_config"]) for mod in input_modules ] else: output_dim = self.config["layer_out_dims"][0] input_layer = self._make_layer( input_modules, "input", self.config["input_layer_config"], output_dim=output_dim, ) return input_layer def _build_middle_layers(self, middle_modules): layer_out_dims = self.config["layer_out_dims"] num_mid_layers = len(layer_out_dims) - 1 if num_mid_layers == 0: return None middle_layers = nn.ModuleList() for i in range(num_mid_layers): if middle_modules is None: module = nn.Linear(*layer_out_dims[i : i + 2]) layer = self._make_layer( module, "middle", self.config["middle_layer_config"], output_dim=layer_out_dims[i + 1], ) else: module = middle_modules[i] layer = self._make_layer( module, "middle", self.config["middle_layer_config"] ) middle_layers.add_module(f"layer{i+1}", layer) return middle_layers def _build_task_heads(self, head_modules): """Creates and attaches task_heads to the appropriate network layers""" # Make task head layer assignments num_layers = len(self.config["layer_out_dims"]) task_head_layers = self._set_task_head_layers(num_layers) # task_head_layers stores the layer whose output is input to task head t # task_map stores the task heads that appear at each layer self.task_map = defaultdict(list) for t, l in enumerate(task_head_layers): self.task_map[l].append(t) if any(l == 0 for l in task_head_layers) and head_modules is None: raise Exception( "If any task head is being attached to layer 0 " "(the input modules), then you must provide a t-length list of " "head_modules, since the output dimension of each input_module " "cannot be inferred." ) # Construct heads head_dims = [self.K[t] for t in range(self.t)] heads = nn.ModuleList() for t in range(self.t): input_dim = self.config["layer_out_dims"][task_head_layers[t]] if self.config["pass_predictions"]: for p in self.task_graph.parents[t]: input_dim += head_dims[p] output_dim = head_dims[t] if head_modules is None: head = nn.Linear(input_dim, output_dim) elif isinstance(head_modules, list): head = head_modules[t] else: head = copy.deepcopy(head_modules) heads.append(head) return heads def _set_task_head_layers(self, num_layers): head_layers = self.config["task_head_layers"] if isinstance(head_layers, list): task_head_layers = head_layers elif head_layers == "top": task_head_layers = [num_layers - 1] * self.t else: msg = f"Invalid option to 'head_layers' parameter: '{head_layers}'" raise ValueError(msg) # Confirm that the network does not extend beyond the latest task head if max(task_head_layers) < num_layers - 1: unused = num_layers - 1 - max(task_head_layers) msg = ( f"The last {unused} layer(s) of your network have no task " "heads attached to them" ) raise ValueError(msg) # Confirm that parents come b/f children if predictions are passed # between tasks if self.config["pass_predictions"]: for t, l in enumerate(task_head_layers): for p in self.task_graph.parents[t]: if task_head_layers[p] >= l: p_layer = task_head_layers[p] msg = ( f"Task {t}'s layer ({l}) must be larger than its " f"parent task {p}'s layer ({p_layer})" ) raise ValueError(msg) return task_head_layers def _print(self): print("\n--Input Layer--") if isinstance(self.input_layer, list): for mod in self.input_layer: print(mod) else: print(self.input_layer) for t in self.task_map[0]: print(f"(head{t})") print(self.heads[t]) print("\n--Middle Layers--") for i, layer in enumerate(self.middle_layers, start=1): print(f"(layer{i}):") print(layer) for t in self.task_map[i]: print(f"(head{t})") print(self.heads[t]) print() def forward(self, x): """Returns a list of outputs for tasks 0,...t-1 Args: x: a [batch_size, ...] batch from X """ head_outputs = [None] * self.t # Execute input layer if isinstance(self.input_layer, list): # One input_module per task input_outputs = [mod(x) for mod, x in zip(self.input_layer, x)] x = torch.stack(input_outputs, dim=1) # Execute level-0 task heads from their respective input modules for t in self.task_map[0]: head = self.heads[t] head_outputs[t] = head(input_outputs[t]) else: # One input_module for all tasks x = self.input_layer(x) # Execute level-0 task heads from the single input module for t in self.task_map[0]: head = self.heads[t] head_outputs[t] = head(x) # Execute middle layers for i, layer in enumerate(self.middle_layers, start=1): x = layer(x) # Attach level-i task heads from the ith middle module for t in self.task_map[i]: head = self.heads[t] # Optionally include as input the predictions of parent tasks if self.config["pass_predictions"] and bool(self.task_graph.parents[t]): task_input = [x] for p in self.task_graph.parents[t]: task_input.append(head_outputs[p]) task_input = torch.stack(task_input, dim=1) else: task_input = x head_outputs[t] = head(task_input) return head_outputs def _preprocess_Y(self, Y, k=None): """Convert Y to t-length list of probabilistic labels if necessary""" # If not a list, convert to a singleton list if not isinstance(Y, list): if self.t != 1: msg = "For t > 1, Y must be a list of n-dim or [n, K_t] tensors" raise ValueError(msg) Y = [Y] if not len(Y) == self.t: msg = f"Expected Y to be a t-length list (t={self.t}), not {len(Y)}" raise ValueError(msg) return [EndModel._preprocess_Y(self, Y_t, self.K[t]) for t, Y_t in enumerate(Y)] def _get_loss_fn(self): """Returns the loss function to use in the train_model routine""" criteria = self.criteria.to(self.config["device"]) loss_fn = lambda X, Y: sum( criteria(Y_tp, Y_t) for Y_tp, Y_t in zip(self.forward(X), Y) ) return loss_fn def predict_proba(self, X): """Returns a list of t [n, K_t] tensors of probabilistic (float) predictions.""" return [ F.softmax(output, dim=1).data.cpu().numpy() for output in self.forward(X) ] def predict_task_proba(self, X, t): """Returns an n x k matrix of probabilities for each label of task t""" return self.predict_proba(X)[t]
metal-master
metal/multitask/mt_end_model.py
from .mt_classifier import MTClassifier from .mt_end_model import MTEndModel from .mt_label_model import MTLabelModel from .task_graph import TaskGraph, TaskHierarchy from .utils import MultiXYDataset, MultiYDataset __all__ = [ "MultiXYDataset", "MultiYDataset", "TaskGraph", "TaskHierarchy", "MTClassifier", "MTEndModel", "MTLabelModel", ]
metal-master
metal/multitask/__init__.py
import itertools import networkx as nx import numpy as np class TaskGraph(object): """A directed graph defining dependencies between tasks In the MTLabelModel, the TaskGraph is used to define a feasible subset of all t-dimensional label vectors Y = [Y_1,...,Y_t]; for example, in a mutually exclusive hierarchy, an example cannot have multiple non-zero leaf labels. In the MTEndModel, the TaskGraph is optionally used for auto-compilation of an MTL network that attaches task heads at appropriate levels and passes relevant information between tasks. Args: edges: A list of (a,b) tuples meaning a is a parent of b in a tree. cardinalities: A t-length list of integers corresponding to the cardinalities of each task. Defaults to a single binary task. """ def __init__(self, cardinalities=[2], edges=[]): self.K = cardinalities # Cardinalities for each task self.t = len(cardinalities) # Total number of tasks self.edges = edges # Create the graph of tasks self.G = nx.DiGraph() self.G.add_nodes_from(range(self.t)) self.G.add_edges_from(edges) # Pre-compute parents, children, and leaf nodes self.leaf_nodes = [i for i in self.G.nodes() if self.G.out_degree(i) == 0] self.parents = {t: self.get_parent(t) for t in range(self.t)} self.children = {t: self.get_children(t) for t in range(self.t)} # Save the cardinality of the feasible set self.k = len(list(self.feasible_set())) def __eq__(self, other): return self.edges == other.edges and self.K == other.K def get_parent(self, node): return sorted(list(self.G.predecessors(node))) def get_children(self, node): return sorted(list(self.G.successors(node))) def is_feasible(self, y): """Boolean indicator if the given y vector is valid (default: True)""" return True def feasible_set(self): """Iterator over values in feasible set""" for y in itertools.product(*[range(1, k + 1) for k in self.K]): yield np.array(y) class TaskHierarchy(TaskGraph): """A mutually-exclusive task hierarchy (a tree)""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Check that G is a tree if not nx.is_tree(self.G): raise ValueError( f"G is not a tree with edges {self.edges}. " "If a tree is not required, use the generic TaskGraph class." ) def is_feasible(self, y): return y in list(self.feasible_set()) def feasible_set(self): # Every feasible vector corresponds to a leaf node value in # {1, ..., K[t]-1}, with the K[t] value reserved for special "N/A" val if self.t > 1: for t in self.leaf_nodes: for yt in range(1, self.K[t]): # By default set all task labels to "N/A" value to start # The default "N/A" value for each task is the last value y = np.array(self.K) # Traverse up the tree y[t] = yt pt = t while pt > 0: ct = pt pt = list(self.G.predecessors(pt))[0] y[pt] = list(self.G.successors(pt)).index(ct) + 1 yield y # Handle the trivial single-node setting, since technically this is a # hierarchy still... else: for yt in range(self.K[0]): yield np.array([yt + 1])
metal-master
metal/multitask/task_graph.py
import numpy as np from scipy.sparse import issparse from torch.utils.data import Dataset class MultiYDataset(Dataset): """A dataset that group each item in X with its labels for t tasks from Y Args: X: an n-dim iterable of inputs Y: a t-length list of n-dim iterables corresponding to labels for t tasks """ def __init__(self, X, Y): self.X = X self.Y = Y self.t = len(Y) n = len(X) assert np.all([len(Y_t) == n for Y_t in Y]) def __getitem__(self, index): return tuple([self.X[index], [self.Y[t][index] for t in range(self.t)]]) def __len__(self): return len(self.X) class MultiXYDataset(Dataset): """A dataset that groups each item's t inputs from X and t labels from Y Args: X: a t-length list of n-dim iterables corresponding to inputs for t tasks Y: a t-length list of n-dim iterables corresponding to labels for t tasks """ def __init__(self, X, Y): # Need to convert sparse matrices to dense here # TODO: Need to handle sparse matrices better overall; maybe not use # Datasets for them...? if issparse(X[0]): X = [Xt.toarray() for Xt in X] # Check and set data objects self.X = X self.Y = Y self.t = len(Y) self.n = len(X[0]) assert np.all([len(X_t) == self.n for X_t in X]) assert np.all([len(Y_t) == self.n for Y_t in Y]) def __getitem__(self, index): return tuple( [ [self.X[t][index] for t in range(self.t)], [self.Y[t][index] for t in range(self.t)], ] ) def __len__(self): return self.n
metal-master
metal/multitask/utils.py
mt_em_default_config = { "task_head_layers": "top", # Optionally specify the layers that each head should attach to # For single-task settings, this is always 'top' # 'top': connect all heads to the final (top) layer # [list]: specify explicitly the layer for each head "pass_predictions": False, # If True, pass output of parent tasks as additional input to children tasks "train_config": {"validation_scoring_kwargs": {"validation_task": None}}, }
metal-master
metal/multitask/mt_em_defaults.py
import os import torch class Checkpointer(object): def __init__(self, config, verbose=True): """Saves checkpoints as applicable based on a reported metric. Args: checkpoint_runway (int): don't save any checkpoints for the first this many iterations checkpoint_dir (str): the directory for saving checkpoints """ self.best_model_found = None self.best_iteration = None self.best_score = None self.verbose = verbose self.checkpoint_best = config["checkpoint_best"] self.checkpoint_every = config["checkpoint_every"] self.checkpoint_metric = config["checkpoint_metric"] self.checkpoint_metric_mode = config["checkpoint_metric_mode"] self.checkpoint_dir = config["checkpoint_dir"] self.checkpoint_runway = config["checkpoint_runway"] # Create checkpoint directory if necessary if not os.path.exists(self.checkpoint_dir): os.makedirs(self.checkpoint_dir) # Remind about checkpoint runway if self.checkpoint_runway and verbose: print( f"No checkpoints will be saved in the first " f"checkpoint_runway={self.checkpoint_runway} iterations." ) def checkpoint(self, metrics_dict, iteration, model, optimizer, lr_scheduler): # Return early if checkpoint_runway has not been met if self.checkpoint_runway: if iteration < self.checkpoint_runway: return elif iteration == self.checkpoint_runway: print("Checkpoint runway has been met. Checkpointing will now occur.") if ( self.checkpoint_every and iteration > 0 and iteration % self.checkpoint_every == 0 ): # Save the checkpoint regardless of performance score = None state = self.bundle_state(iteration, score, model, optimizer, lr_scheduler) checkpoint_path = f"{self.checkpoint_dir}/model_checkpoint_{iteration}.pth" torch.save(state, checkpoint_path) if self.checkpoint_best and self.checkpoint_metric in metrics_dict: score = metrics_dict[self.checkpoint_metric] if self.is_best(score): if self.verbose: print( f"Saving model at iteration {iteration:.2f} with best " f"({self.checkpoint_metric_mode}) score " f"{self.checkpoint_metric}={score:.3f}" ) self.best_model_found = True self.best_iteration = iteration self.best_score = score # Save the checkpoint, overriding previous best if it exists state = self.bundle_state( iteration, score, model, optimizer, lr_scheduler ) checkpoint_path = f"{self.checkpoint_dir}/best_model.pth" torch.save(state, checkpoint_path) def is_best(self, score): if self.best_score is None: return True elif self.checkpoint_metric_mode == "max": return score > self.best_score elif self.checkpoint_metric_mode == "min": return score < self.best_score else: msg = ( f"Did not recognize checkpoint_metric_mode: " + f"{self.checkpoint_metric_mode}" ) raise ValueError(msg) def bundle_state(self, iteration, score, model, optimizer, lr_scheduler): # Save the state of the best model state = { "iteration": iteration, "model": model.state_dict(), "optimizer": optimizer.state_dict(), "lr_scheduler": lr_scheduler.state_dict() if lr_scheduler else None, "score": score, } if self.best_model_found: state["best_model_found"] = True state["best_iteration"] = self.best_iteration state["best_score"] = self.best_score return state def load_best_model(self, model): if self.best_model_found is None: msg = ( f"Best model was never found. Confirm that your checkpoint_metric " f"({self.checkpoint_metric}) is of the form " f"'[model or task]/[split]/loss' or produced by one of your tasks' " f"Scorers and that checkpoint_metric_mode " f"({self.checkpoint_metric_mode}) is appropriate for the given " f"checkpoint_metric." ) raise Exception(msg) if self.verbose: print( f"Restoring best model from iteration {self.best_iteration:0.2f} " f"with score {self.best_score:.3f}" ) state = torch.load( f"{self.checkpoint_dir}/best_model.pth", map_location=torch.device("cpu"), ) self.best_iteration = state["best_iteration"] self.best_score = state["best_score"] model.load_state_dict(state["model"]) return model def restore(self, destination): state = torch.load(f"{destination}") return state def clean_up(self): if os.path.exists(self.checkpoint_dir): os.system(f"rm -r {self.checkpoint_dir}")
metal-master
metal/logging/checkpointer.py
from .checkpointer import Checkpointer from .logger import Logger, Timer from .tensorboard import TensorBoardWriter from .writer import LogWriter __all__ = ["Checkpointer", "Logger", "LogWriter", "TensorBoardWriter", "Timer"]
metal-master
metal/logging/__init__.py
import time from collections import defaultdict from metal.metrics import METRICS as standard_metric_names, metric_score class Logger(object): """Tracks when it is time to calculate train/valid metrics and logs them""" def __init__(self, config, writer={}, epoch_size=None, verbose=True): # Strip split name from config keys self.config = config self.writer = writer self.verbose = verbose self.log_unit = self.config["log_unit"] self.epoch_size = epoch_size self.example_count = 0 self.example_total = 0 self.unit_count = 0 self.unit_total = 0 self.log_count = 0 # Count how many times logging has occurred # Specific to log_unit == "seconds" self.timer = Timer() if self.log_unit == "seconds" else None # Normalize all target metric names to include split prefix self.log_train_metrics = [ self.add_split_prefix(m, "train") for m in self.config["log_train_metrics"] ] self.log_valid_metrics = [ self.add_split_prefix(m, "valid") for m in self.config["log_valid_metrics"] ] # Calculate how many log_train steps to take per log_valid steps self.valid_every_X = self._calculate_valid_frequency() def check(self, batch_size): """Returns True if the logging frequency has been met.""" self.increment(batch_size) return self.unit_count >= self.config["log_train_every"] def increment(self, batch_size): """Update the total and relative unit counts""" self.example_count += batch_size self.example_total += batch_size if self.log_unit == "seconds": self.unit_count = int(self.timer.elapsed()) self.unit_total = int(self.timer.total_elapsed()) elif self.log_unit == "examples": self.unit_count = self.example_count self.unit_total = self.example_total elif self.log_unit == "batches": self.unit_count += 1 self.unit_total += 1 elif self.log_unit == "epochs": # Track epoch by example count because otherwise we only know when # a new epoch starts, not when an epoch ends if self.example_count >= self.epoch_size: self.unit_count += 1 self.unit_total += 1 else: raise Exception(f"Unrecognized log_unit: {self.log_unit}") def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict): """Add standard and custom metrics to metrics_dict""" # Check whether or not it's time for validation as well self.log_count += 1 log_valid = ( valid_loader is not None and self.valid_every_X and not (self.log_count % self.valid_every_X) ) metrics_dict = {} # Calculate custom metrics if self.config["log_train_metrics_func"] is not None: func = self.config["log_train_metrics_func"] func_list = func if isinstance(func, list) else [func] for func in func_list: metrics_dict = self._calculate_custom_metrics( model, train_loader, func, metrics_dict, split="train" ) if self.config["log_valid_metrics_func"] is not None and log_valid: func = self.config["log_valid_metrics_func"] func_list = func if isinstance(func, list) else [func] for func in func_list: metrics_dict = self._calculate_custom_metrics( model, valid_loader, func, metrics_dict, split="valid" ) # Calculate standard metrics metrics_dict = self._calculate_standard_metrics( model, train_loader, self.log_train_metrics, metrics_dict, "train" ) if log_valid: metrics_dict = self._calculate_standard_metrics( model, valid_loader, self.log_valid_metrics, metrics_dict, "valid" ) return metrics_dict def _calculate_custom_metrics(self, model, data_loader, func, metrics_dict, split): custom_metrics = func(model, data_loader) # Normalize all custom metrics to include split prefix for metric, value in custom_metrics.items(): metric = self.add_split_prefix(metric, split) metrics_dict[metric] = value return metrics_dict def _calculate_standard_metrics( self, model, data_loader, target_metrics, metrics_dict, split ): target_standard_metrics = [] for split_metric in target_metrics: metric = self.remove_split_prefix(split_metric) if metric in standard_metric_names: target_standard_metrics.append(metric) # Only calculate predictions if at least one standard metric requires it if target_standard_metrics: if model.multitask: # For multitask models, use score method for aggregation # This may cause inefficiency if there are multiple desired metrics # and we re-predict for each one. for metric in target_standard_metrics: score = model.score(data_loader, metric, verbose=False) metrics_dict[self.add_split_prefix(metric, split)] = score else: # For singletask models, predict once and use Y_probs/Y_preds # for all metrics calculations Y_preds, Y, Y_probs = model._get_predictions( data_loader, return_probs=True ) for metric in target_standard_metrics: score = metric_score(Y, Y_preds, metric, probs=Y_probs) metrics_dict[self.add_split_prefix(metric, split)] = score return metrics_dict @staticmethod def add_split_prefix(metric, split): """Add split name to metric name if it is not already present The order of metric name components should either be: - task/split/metric in the multitask setting (expand to this from task/metric) - split/metric in the singletask setting (expand to this from metric) """ if f"{split}/" in metric: full_metric = metric else: if "/" in metric: # It has two parts but not split, so must be task/metric task, metric = metric.split("/") full_metric = f"{task}/{split}/{metric}" else: # It has one part but not split, so must be metric full_metric = f"{split}/{metric}" return full_metric @staticmethod def remove_split_prefix(metric): """Remove prefixes from begininng of metric name (e.g., task/split/metric)""" return metric.split("/")[-1] def _calculate_valid_frequency(self): assert isinstance(self.config["log_train_every"], int) if self.config["log_valid_every"]: assert isinstance(self.config["log_valid_every"], int) if ( self.config["log_valid_every"] < self.config["log_train_every"] or self.config["log_valid_every"] % self.config["log_train_every"] ): raise Exception( f"Parameter `log_valid_every` ({self.config['log_valid_every']}) " f"must be a multiple of `log_train_every` " f"({self.config['log_train_every']})." ) return int(self.config["log_valid_every"] / self.config["log_train_every"]) else: return 0 def log(self, metrics_dict): """Print calculated metrics and optionally write to file (json/tb)""" if self.writer: self.write_to_file(metrics_dict) if self.verbose: self.print_to_screen(metrics_dict) self.reset() def print_to_screen(self, metrics_dict): """Print all metrics in metrics_dict to screen""" score_strings = defaultdict(list) for full_name, value in metrics_dict.items(): if full_name.count("/") == 2: task, split, metric = full_name.split("/") elif full_name.count("/") == 1: task = None split, metric = full_name.split("/") else: msg = f"Metric should have form task/split/metric or split/metric, not: {full_name}" raise Exception(msg) if task: metric_name = f"{task}/{metric}" else: metric_name = metric if isinstance(value, float): score_strings[split].append(f"{metric_name}={value:0.3f}") else: score_strings[split].append(f"{metric_name}={value}") header = f"{self.unit_total} {self.log_unit[:3]}" if self.log_unit != "epochs": epochs = self.example_total / self.epoch_size header += f" ({epochs:0.2f} epo)" string = f"[{header}]:" if score_strings["train"]: train_scores = f"{', '.join(score_strings['train'])}" string += f" TRAIN:[{train_scores}]" if score_strings["valid"]: valid_scores = f"{', '.join(score_strings['valid'])}" string += f" VALID:[{valid_scores}]" print(string) def write_to_file(self, metrics_dict): for metric, value in metrics_dict.items(): self.writer.add_scalar(metric, value, self.unit_total) def reset(self): self.unit_count = 0 self.example_count = 0 if self.timer is not None: self.timer.update() class Timer(object): """Computes elapsed time.""" def __init__(self): """Initialize timer""" self.reset() def reset(self): """Reset timer, completely obliterating history""" self.start = time.time() self.update() def update(self): """Update timer with most recent click point""" self.click = time.time() def elapsed(self): """Get time elapsed since last recorded click""" elapsed = time.time() - self.click return elapsed def total_elapsed(self): return time.time() - self.start
metal-master
metal/logging/logger.py
def split_full_metric(full_metric): """Splits a full metric name (split/name or task/split/label/name) into pieces""" pieces = full_metric.split("/") if len(pieces) == 2: # Single-task metric split, name = pieces return split, name elif len(pieces) == 4: # Mmtl metric task, payload, label, name = pieces return task, payload, label, name else: msg = ( f"Required a full metric name (split/name or task/payload/label/name) but " f"instead received: {full_metric}" ) raise Exception(msg)
metal-master
metal/logging/utils.py
import copy import json import os from collections import defaultdict from subprocess import check_output from time import strftime from metal.utils import recursive_transform class LogWriter(object): """Class for writing simple JSON logs at end of runs, with interface for storing per-iter data as well. Config contains: log_dir: (str) The path to the base log directory, or defaults to current working directory. run_dir: (str) The name of the sub-directory, or defaults to the date, strftime("%Y_%m_%d"). run_name: (str) The name of the run + the time, or defaults to the time, strftime("%H_%M_%S). writer_metrics: (list) An optional whitelist of metrics to write, ignoring all others. (If None, write all available metrics). Log is saved to 'log_dir/run_dir/{run_name}_H_M_S.json' """ def __init__( self, log_dir=None, run_dir=None, run_name=None, writer_metrics=[], verbose=True, **kwargs, ): start_date = strftime("%Y_%m_%d") start_time = strftime("%H_%M_%S") # Set logging subdirectory + make sure exists log_dir = log_dir or os.getcwd() run_dir = run_dir or start_date if run_name is not None: run_name = f"{run_name}_{start_time}" else: run_name = start_time self.log_subdir = os.path.join(log_dir, run_dir, run_name) if not os.path.exists(self.log_subdir): os.makedirs(self.log_subdir) # Save other settings self.writer_metrics = writer_metrics self.verbose = verbose # Initialize log # Note we have a separate section for during-run metrics commit = check_output(["git", "rev-parse", "--short", "HEAD"]).strip() self.log_dict = { "start_date": start_date, "start_time": start_time, "commit": str(commit), "config": None, "run_log": defaultdict(list), } def add_scalar(self, name, val, i): # Note: Does not handle deduplication of (name, val) entries w same i if not self.writer_metrics or name in self.write_metrics: if val is not None: val = float(val) self.log_dict["run_log"][name].append((i, val)) return True else: return False def write(self, config=None, metrics=None): self.write_run_log() if config is not None: self.write_config(config) if metrics is not None: self.write_metrics(metrics) def write_log(self): """Dump log output to file""" log_path = os.path.join(self.log_subdir, "log.json") if self.verbose: print(f"Writing log to {log_path}") with open(log_path, "w") as f: json.dump(self.log_dict, f, indent=1) def write_config(self, config, config_name="config"): """Dump config dict to file""" config_path = os.path.join(self.log_subdir, f"{config_name}.json") if self.verbose: print(f"Writing config to {config_path}") with open(config_path, "w") as f: config = self._sanitize_config(config) json.dump(config, f, indent=1) def write_metrics(self, metrics): metrics_path = os.path.join(self.log_subdir, "metrics.json") if self.verbose: print(f"Writing metrics to {metrics_path}") with open(metrics_path, "w") as f: json.dump(metrics, f, indent=1) def close(self): pass def _sanitize_config(self, config): config = copy.deepcopy(config) # Replace individual functions is_func = lambda x: callable(x) replace_with_name = lambda f: str(f) config = recursive_transform(config, is_func, replace_with_name) # Replace lists of functions is_func_list = lambda x: isinstance(x, list) and all(is_func(f) for f in x) replace_with_names = lambda x: [replace_with_name(f) for f in x] config = recursive_transform(config, is_func_list, replace_with_names) return config
metal-master
metal/logging/writer.py
import json import warnings import numpy as np from tensorboardX import SummaryWriter from metal.logging.writer import LogWriter class TensorBoardWriter(LogWriter): """Class for logging to Tensorboard during runs, as well as writing simple JSON logs at end of runs. Stores logs in log_dir/{YYYY}_{MM}_{DD}/{H}_{M}_{S}_run_name.json by default. """ def __init__(self, log_dir=None, run_dir=None, run_name=None, **kwargs): super().__init__(log_dir=log_dir, run_dir=run_dir, run_name=run_name, **kwargs) # Set up TensorBoard summary writer self.tb_writer = SummaryWriter(self.log_subdir, filename_suffix=f".{run_name}") def add_scalar(self, name, val, i): if super().add_scalar(name, val, i): self.tb_writer.add_scalar(name, val, i) def write_config(self, config, *args, **kwargs): config_txt = json.dumps(self._sanitize_config(config), indent=1) self.tb_writer.add_text(tag="config", text_string=config_txt, global_step=0) super().write_config(config, *args, **kwargs) def close(self): self.tb_writer.close()
metal-master
metal/logging/tensorboard.py
metal-master
tests/__init__.py
import os import pickle import unittest import GPUtil from metal.end_model import EndModel from metal.label_model import LabelModel from metal.utils import split_data # Making sure we're using GPU 0 os.environ["CUDA_VISIBLE_DEVICES"] = "0" class GPUTest(unittest.TestCase): @unittest.skipIf( "TRAVIS" in os.environ and os.environ["TRAVIS"] == "true", "Skipping this test on Travis CI.", ) def test_gpustorage(self): # Running basics tutorial problem with open("tutorials/data/basics_tutorial.pkl", "rb") as f: X, Y, L, D = pickle.load(f) Xs, Ys, Ls, Ds = split_data( X, Y, L, D, splits=[0.8, 0.1, 0.1], stratify_by=Y, seed=123 ) label_model = LabelModel(k=2, seed=123) label_model.train_model(Ls[0], Y_dev=Ys[1], n_epochs=500, log_train_every=25) Y_train_ps = label_model.predict_proba(Ls[0]) # Creating a really large end model to use lots of memory end_model = EndModel([1000, 100000, 2], seed=123, device="cuda") # Getting initial GPU storage use initial_gpu_mem = GPUtil.getGPUs()[0].memoryUsed # Training model end_model.train_model( (Xs[0], Y_train_ps), valid_data=(Xs[1], Ys[1]), l2=0.1, batch_size=256, n_epochs=3, log_train_every=1, validation_metric="f1", ) # Final GPU storage use final_gpu_mem = GPUtil.getGPUs()[0].memoryUsed # On a Titan X, this model uses ~ 3 GB of memory gpu_mem_difference = final_gpu_mem - initial_gpu_mem self.assertGreater(gpu_mem_difference, 1000) if __name__ == "__main__": unittest.main()
metal-master
tests/gpu/test_gpu.py
import unittest from collections import Counter import numpy as np import scipy.sparse as sparse import torch from metal.utils import pred_to_prob, rargmax, recursive_merge_dicts, split_data class UtilsTest(unittest.TestCase): def test_rargmax(self): x = np.array([2, 1, 2]) np.random.seed(1) self.assertEqual(sorted(list(set(rargmax(x) for _ in range(10)))), [0, 2]) def test_pred_to_prob(self): x = torch.tensor([1, 2, 2, 1]) target = torch.tensor([[1, 0], [0, 1], [0, 1], [1, 0]]) self.assertTrue( (pred_to_prob(x, 2).float() == target.float()).sum() == torch.prod(torch.tensor(target.shape)) ) def test_recursive_merge_dicts(self): x = {"foo": {"Foo": {"FOO": 1}}, "bar": 2, "baz": 3} y = {"FOO": 4, "bar": 5} z = {"foo": 6} w = recursive_merge_dicts(x, y, verbose=False) self.assertEqual(w["bar"], 5) self.assertEqual(w["foo"]["Foo"]["FOO"], 4) with self.assertRaises(ValueError): recursive_merge_dicts(x, z, verbose=False) def test_split_data(self): N = 1000 K = 4 X = np.arange(0, N) Y = np.random.randint(0, K, size=N).astype(int) # Creates splits of correct size splits = [800, 100, 100] Xs_1 = split_data(X, splits=splits, shuffle=False) for i, count in enumerate(splits): self.assertEqual(len(Xs_1[i]), count) # Accepts floats or ints splits = [0.8, 0.1, 0.1] Xs_2 = split_data(X, splits=splits, shuffle=False) for split in range(len(splits)): self.assertTrue(np.array_equal(Xs_2[split], Xs_1[split])) # Shuffles correctly Xs_3 = split_data(X, splits=splits, shuffle=True, seed=123) self.assertNotEqual(Xs_3[0][0], Xs_2[0][0]) # Indices only splits = [0.8, 0.1, 0.1] Ys = split_data(Y, splits=splits, shuffle=False, index_only=True) self.assertGreater(max(Ys[0]), K) # Handles multiple inputs Xs, Ys = split_data(X, Y, splits=splits, shuffle=True, seed=123) self.assertEqual(Ys[0][0], Y[Xs[0][0]]) # Confirm statification (correct proportion of labels in each split) Ys = split_data(Y, splits=splits, stratify_by=Y, seed=123) counts = [Counter(Y) for Y in Ys] for y in np.unique(Y): ratio0 = counts[0][y] / len(Ys[0]) ratio1 = counts[1][y] / len(Ys[1]) ratio2 = counts[2][y] / len(Ys[2]) self.assertLess(abs(ratio0 - ratio1), 0.05) self.assertLess(abs(ratio0 - ratio2), 0.05) # Handles scipy.sparse matrices Z = sparse.csr_matrix([[1, 0, 1, 2], [0, 3, 0, 3], [1, 2, 3, 4], [5, 4, 3, 2]]) splits = [0.75, 0.25] Zs = split_data(Z, splits=splits, shuffle=True, seed=123) self.assertEqual(Zs[0].shape, (3, 4)) # Handles torch.Tensors W = torch.Tensor([[1, 0, 1, 2], [0, 3, 0, 3], [1, 2, 3, 4], [5, 4, 3, 2]]) splits = [0.75, 0.25] Ws = split_data(W, splits=splits, shuffle=True, seed=123) self.assertEqual(Ws[0].shape, (3, 4)) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/test_utils.py
import unittest import numpy as np import torch from metal.metrics import ( accuracy_score, coverage_score, f1_score, fbeta_score, metric_score, precision_score, recall_score, roc_auc_score, ) class MetricsTest(unittest.TestCase): def test_accuracy_basic(self): gold = [1, 1, 1, 2, 2] pred = [1, 1, 1, 2, 1] score = accuracy_score(gold, pred) self.assertAlmostEqual(score, 0.8) def test_metric_score(self): gold = [1, 1, 1, 2, 2] pred = [1, 1, 1, 2, 1] acc = accuracy_score(gold, pred) met = metric_score(gold, pred, metric="accuracy") self.assertAlmostEqual(acc, met) def test_bad_inputs(self): gold = [1, 1, 1, 2, 2] pred1 = [1, 1, 1, 2, 0.5] pred2 = "1 1 1 2 2" pred3 = np.array([[1, 1, 1, 1, 1], [2, 2, 2, 2, 2]]) self.assertRaises(ValueError, accuracy_score, gold, pred1) self.assertRaises(ValueError, accuracy_score, gold, pred2) self.assertRaises(ValueError, accuracy_score, gold, pred3) def test_array_conversion(self): gold = torch.Tensor([1, 1, 1, 2, 2]) pred = np.array([1.0, 1.0, 1.0, 2.0, 1.0]) score = accuracy_score(gold, pred) self.assertAlmostEqual(score, 0.8) def test_ignores(self): gold = [1, 1, 1, 2, 2] pred = [1, 0, 1, 2, 1] score = accuracy_score(gold, pred) self.assertAlmostEqual(score, 0.6) score = accuracy_score(gold, pred, ignore_in_pred=[0]) self.assertAlmostEqual(score, 0.75) score = accuracy_score(gold, pred, ignore_in_gold=[1]) self.assertAlmostEqual(score, 0.5) score = accuracy_score(gold, pred, ignore_in_gold=[2], ignore_in_pred=[0]) self.assertAlmostEqual(score, 1.0) def test_coverage(self): gold = [1, 1, 1, 1, 2] pred = [0, 0, 1, 1, 1] score = coverage_score(gold, pred) self.assertAlmostEqual(score, 0.6) score = coverage_score(gold, pred, ignore_in_gold=[2]) self.assertAlmostEqual(score, 0.5) def test_precision(self): gold = [1, 1, 1, 2, 2] pred = [0, 0, 1, 1, 2] score = precision_score(gold, pred) self.assertAlmostEqual(score, 0.5) score = precision_score(gold, pred, pos_label=2) self.assertAlmostEqual(score, 1.0) def test_recall(self): gold = [1, 1, 1, 1, 2] pred = [0, 2, 1, 1, 2] score = recall_score(gold, pred) self.assertAlmostEqual(score, 0.5) score = recall_score(gold, pred, pos_label=2) self.assertAlmostEqual(score, 1.0) def test_f1(self): gold = [1, 1, 1, 1, 2] pred = [0, 2, 1, 1, 2] score = f1_score(gold, pred) self.assertAlmostEqual(score, 0.666, places=2) score = f1_score(gold, pred, pos_label=2) self.assertAlmostEqual(score, 0.666, places=2) def test_fbeta(self): gold = [1, 1, 1, 1, 2] pred = [0, 2, 1, 1, 2] pre = precision_score(gold, pred) rec = recall_score(gold, pred) self.assertEqual(pre, fbeta_score(gold, pred, beta=0)) self.assertAlmostEqual(rec, fbeta_score(gold, pred, beta=1000), places=4) def test_roc_auc(self): gold = [1, 1, 2, 2] probs = np.array([[0.9, 0.1], [0.6, 0.4], [0.65, 0.35], [0.2, 0.8]]) score = roc_auc_score(gold, probs) self.assertEqual(score, 0.75) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/test_metrics.py
import unittest import numpy as np import scipy.sparse as sparse from metal.analysis import ( error_buckets, label_conflict, label_coverage, label_overlap, lf_conflicts, lf_coverages, lf_empirical_accuracies, lf_overlaps, ) class AnalysisTest(unittest.TestCase): @classmethod def setUpClass(cls): L = np.array([[1, 0, 1], [1, 3, 2], [0, 0, 0], [0, 0, 2], [0, 1, 2]]) cls.L = sparse.csr_matrix(L) cls.Y = np.array([1, 2, 1, 2, 2]) def test_label_coverage(self): self.assertEqual(label_coverage(self.L), 0.8) def test_label_overlap(self): self.assertEqual(label_overlap(self.L), 0.6) def test_label_conflict(self): self.assertEqual(label_conflict(self.L), 0.4) def test_lf_empirical_accuracies(self): self.assertTrue( np.all(lf_empirical_accuracies(self.L, self.Y) == np.array([0.5, 0, 1])) ) def test_lf_coverages(self): self.assertTrue((lf_coverages(self.L) == np.array([0.4, 0.4, 0.8])).all()) def test_lf_overlaps(self): self.assertTrue((lf_overlaps(self.L) == np.array([0.4, 0.4, 0.6])).all()) def test_lf_conflicts(self): self.assertTrue((lf_conflicts(self.L) == np.array([0.2, 0.4, 0.4])).all()) def test_error_buckets(self): gold = [1, 1, 2, 1, 2] pred = [1, 2, 1, 1, 2] e_buckets = error_buckets(gold, pred) self.assertEqual(e_buckets[1, 1], [0, 3]) self.assertEqual(e_buckets[1, 2], [2]) self.assertEqual(e_buckets[2, 2], [4]) self.assertEqual(e_buckets[2, 1], [1]) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/test_analysis.py
metal-master
tests/metal/__init__.py
metal-master
tests/metal/end_model/__init__.py
import os import unittest import numpy as np import torch import torch.nn as nn from metal.end_model import EndModel, LogisticRegression from metal.end_model.identity_module import IdentityModule from metal.metrics import METRICS class EndModelTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 2000 X = np.random.random((n, 2)) * 2 - 1 Y = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1 X = torch.tensor(X, dtype=torch.float) Y = torch.tensor(Y, dtype=torch.long) Xs = [X[:1000], X[1000:1500], X[1500:]] Ys = [Y[:1000], Y[1000:1500], Y[1500:]] cls.single_problem = (Xs, Ys) def test_logreg(self): em = LogisticRegression(seed=1, input_dim=2, verbose=False) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=False ) score = em.score((Xs[2], Ys[2]), verbose=False) self.assertGreater(score, 0.95) def test_softmax(self): em = LogisticRegression(seed=1, input_dim=2, output_dim=3, verbose=False) Xs, _ = self.single_problem Ys = [] for X in Xs: class1 = X[:, 0] < X[:, 1] class2 = X[:, 0] > X[:, 1] + 0.5 class3 = X[:, 0] > X[:, 1] Y = torch.argmax(torch.stack([class1, class2, class3], dim=1), dim=1) + 1 Ys.append(Y) em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), lr=0.1, n_epochs=10, checkpoint=False, ) score = em.score((Xs[2], Ys[2]), verbose=False) self.assertGreater(score, 0.95) def test_singletask(self): """Test basic single-task end model""" em = EndModel( seed=1, input_batchnorm=False, middle_batchnorm=False, input_dropout=0.0, middle_dropout=0.0, layer_out_dims=[2, 10, 2], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=False ) score = em.score((Xs[2], Ys[2]), verbose=False) self.assertGreater(score, 0.95) def test_singletask_extras(self): """Test batchnorm and dropout""" em = EndModel( seed=1, input_batchnorm=True, middle_batchnorm=True, input_dropout=0.01, middle_dropout=0.01, layer_out_dims=[2, 10, 2], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=False ) score = em.score((Xs[2], Ys[2]), verbose=False) self.assertGreater(score, 0.95) def test_custom_modules(self): """Test custom input/head modules""" input_module = nn.Sequential(IdentityModule(), nn.Linear(2, 10)) middle_modules = [nn.Linear(10, 8), IdentityModule()] head_module = nn.Sequential(nn.Linear(8, 2), IdentityModule()) em = EndModel( seed=1, input_module=input_module, middle_modules=middle_modules, head_module=head_module, layer_out_dims=[10, 8, 8], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, verbose=False, checkpoint=False, show_plots=False, ) score = em.score((Xs[2], Ys[2]), verbose=False) self.assertGreater(score, 0.95) def test_scoring(self): """Test the metrics whole way through""" em = EndModel( seed=1, batchnorm=False, dropout=0.0, layer_out_dims=[2, 10, 2], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=False ) metrics = list(METRICS.keys()) scores = em.score((Xs[2], Ys[2]), metric=metrics, verbose=False) for i, metric in enumerate(metrics): self.assertGreater(scores[i], 0.95) def test_determinism(self): """Test whether training and scoring is deterministic given seed""" em = EndModel( seed=123, batchnorm=True, dropout=0.1, layer_out_dims=[2, 10, 2], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=1, checkpoint=False ) score_1 = em.score((Xs[2], Ys[2]), verbose=False) # Test scoring determinism score_2 = em.score((Xs[2], Ys[2]), verbose=False) self.assertEqual(score_1, score_2) # Test training determinism em_2 = EndModel( seed=123, batchnorm=True, dropout=0.1, layer_out_dims=[2, 10, 2], verbose=False, ) em_2.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=1, checkpoint=False ) score_3 = em_2.score((Xs[2], Ys[2]), verbose=False) self.assertEqual(score_1, score_3) def test_save_and_load(self): """Test basic saving and loading""" em = EndModel( seed=1337, input_batchnorm=False, middle_batchnorm=False, input_dropout=0.0, middle_dropout=0.0, layer_out_dims=[2, 10, 2], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=3, checkpoint=False ) score = em.score((Xs[2], Ys[2]), verbose=False) # Save model SAVE_PATH = "test_save_model.pkl" em.save(SAVE_PATH) # Reload and make sure (a) score and (b) non-buffer, non-Parameter # attributes are the same em_2 = EndModel.load(SAVE_PATH) self.assertEqual(em.seed, em_2.seed) score_2 = em_2.score((Xs[2], Ys[2]), verbose=False) self.assertEqual(score, score_2) # Clean up os.remove(SAVE_PATH) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/end_model/test_end_model.py
import unittest import torch import torch.nn as nn from metal.end_model.loss import SoftCrossEntropyLoss from metal.utils import pred_to_prob class LossTest(unittest.TestCase): @classmethod def setUpClass(cls): torch.manual_seed(1) def test_sce_equals_ce(self): # All correct predictions Y = torch.tensor([1, 2, 3], dtype=torch.long) Y_s = pred_to_prob(Y, k=4).float() sce = SoftCrossEntropyLoss(reduction="none") ce = nn.CrossEntropyLoss(reduction="none") for _ in range(10): Y_ps = torch.rand_like(Y_s) Y_ps = Y_ps / Y_ps.sum(dim=1).reshape(-1, 1) self.assertTrue((sce(Y_ps, Y_s) == ce(Y_ps, Y - 1)).all()) sce = SoftCrossEntropyLoss(reduction="sum") ce = nn.CrossEntropyLoss(reduction="sum") for _ in range(10): Y_ps = torch.rand_like(Y_s) Y_ps = Y_ps / Y_ps.sum(dim=1).reshape(-1, 1) self.assertAlmostEqual( sce(Y_ps, Y_s).numpy(), ce(Y_ps, Y - 1).numpy(), places=5 ) sce = SoftCrossEntropyLoss(reduction="mean") ce = nn.CrossEntropyLoss(reduction="mean") for _ in range(10): Y_ps = torch.rand_like(Y_s) Y_ps = Y_ps / Y_ps.sum(dim=1).reshape(-1, 1) self.assertAlmostEqual( sce(Y_ps, Y_s).numpy(), ce(Y_ps, Y - 1).numpy(), places=5 ) def test_perfect_predictions(self): Y = torch.tensor([1, 2, 3], dtype=torch.long) Y_s = pred_to_prob(Y, k=4) sce = SoftCrossEntropyLoss() # Guess nearly perfectly Y_ps = Y_s.clone().float() Y_ps[Y_ps == 1] = 100 Y_ps[Y_ps == 0] = -100 self.assertAlmostEqual(sce(Y_ps, Y_s).numpy(), 0) def test_prob_labels(self): Y_s = torch.tensor([[0.1, 0.9], [0.5, 0.5]]) Y_ps1 = torch.tensor([[0.1, 0.2], [1.0, 0.0]]) Y_ps2 = torch.tensor([[0.1, 0.3], [1.0, 0.0]]) Y_ps3 = torch.tensor([[0.1, 0.3], [0.0, 1.0]]) sce = SoftCrossEntropyLoss() self.assertLess(sce(Y_ps2, Y_s), sce(Y_ps1, Y_s)) self.assertEqual(sce(Y_ps2, Y_s), sce(Y_ps3, Y_s)) def test_loss_weights(self): # All incorrect predictions Y = torch.tensor([1, 1, 2], dtype=torch.long) Y_s = pred_to_prob(Y, k=3) Y_ps = torch.tensor( [[-100.0, 100.0, -100.0], [-100.0, 100.0, -100.0], [-100.0, 100.0, -100.0]] ) weight1 = torch.tensor([1, 2, 1], dtype=torch.float) weight2 = torch.tensor([10, 20, 10], dtype=torch.float) ce1 = nn.CrossEntropyLoss(weight=weight1, reduction="none") sce1 = SoftCrossEntropyLoss(weight=weight1) sce2 = SoftCrossEntropyLoss(weight=weight2) self.assertAlmostEqual( float(ce1(Y_ps, Y - 1).mean()), float(sce1(Y_ps, Y_s)), places=3 ) self.assertAlmostEqual( float(sce1(Y_ps, Y_s)) * 10, float(sce2(Y_ps, Y_s)), places=3 ) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/end_model/test_loss.py
import unittest from collections import defaultdict import numpy as np import torch import torch.nn as nn from metal.mmtl.data import MmtlDataLoader, MmtlDataset from metal.mmtl.metal_model import MetalModel from metal.mmtl.payload import Payload from metal.mmtl.task import ClassificationTask from metal.mmtl.trainer import MultitaskTrainer from metal.utils import split_data SPLITS = ["train", "valid", "test"] def create_tasks(T): tasks = [] for t in range(T): task_name = f"task{t}" input_module = nn.Sequential(nn.Linear(2, 8), nn.ReLU()) head_module = nn.Linear(8, 2) task = ClassificationTask( name=task_name, input_module=input_module, head_module=head_module ) tasks.append(task) return tasks def create_payloads(N, T, batch_size=1): # Create two instance sets from the same (uniform) distribution, each of which # have labels for the same tasks (classification with respect to parallel # linear boundaries). labels_to_tasks = {f"labelset{t}": f"task{t}" for t in range(T)} payloads = [] for t in range(T): X = np.random.random((N, 2)) * 2 - 1 Y = np.zeros((N, 2)) Y[:, 0] = (X[:, 0] > X[:, 1] + 0.5).astype(int) + 1 Y[:, 1] = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1 uids = list(range(t * N, (t + 1) * N)) X = torch.tensor(X, dtype=torch.float) Y = torch.tensor(Y, dtype=torch.long) uid_lists, Xs, Ys = split_data(uids, X, Y, splits=[0.8, 0.1, 0.1], shuffle=True) for i, split in enumerate(SPLITS): payload_name = f"payload{t}_{split}" X_dict = {"data": Xs[i], "uids": uid_lists[i]} Y_dict = {f"labelset{t}": Ys[i][:, t] for t in range(T)} dataset = MmtlDataset(X_dict, Y_dict) data_loader = MmtlDataLoader(dataset, batch_size=batch_size) payload = Payload(payload_name, data_loader, labels_to_tasks, split) payloads.append(payload) return payloads class MmtlTest(unittest.TestCase): @classmethod def setUpClass(cls): np.random.seed(1) cls.trainer = MultitaskTrainer(verbose=False, lr=0.005) def test_mmtl_singletask(self): """One task with one train payload and one labelset""" N = 600 T = 1 tasks = create_tasks(T) model = MetalModel(tasks, verbose=False) payloads = create_payloads(N, T, batch_size=2) metrics_dict = self.trainer.train_model(model, payloads) self.assertEqual(len(metrics_dict), len(SPLITS) * T) for metric, score in metrics_dict.items(): self.assertGreater(score, 0.9) def test_mmtl_multitask(self): """Two tasks with two train payloads and two labelsets each""" N = 600 T = 2 tasks = create_tasks(T) model = MetalModel(tasks, verbose=False) payloads = create_payloads(N, T, batch_size=2) metrics_dict = self.trainer.train_model(model, payloads, verbose=False) # For 3 payloads, each of 2 tasks each has 2 label sets self.assertEqual(len(metrics_dict), len(SPLITS) * T ** 2) for metric, score in metrics_dict.items(): self.assertGreater(score, 0.9) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/mmtl/test_mmtl.py
import json import unittest from shutil import rmtree import numpy as np import torch from metal.end_model import EndModel from metal.logging import LogWriter from metal.tuners.random_tuner import RandomSearchTuner class RandomSearchModelTunerTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 2000 X = np.random.random((n, 2)) * 2 - 1 Y = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1 X = torch.tensor(X, dtype=torch.float) Y = torch.tensor(Y, dtype=torch.long) Xs = [X[:1000], X[1000:1500], X[1500:]] Ys = [Y[:1000], Y[1000:1500], Y[1500:]] cls.single_problem = (Xs, Ys) def test_config_constant(self): search_space = {"a": 1} tuner = RandomSearchTuner(None, None, seed=123) configs = list( tuner.config_generator(search_space, rng=tuner.rng, max_search=10) ) self.assertEqual(len(configs), 1) def test_config_list(self): search_space = {"a": [1, 2]} tuner = RandomSearchTuner(None, None, seed=123) configs = list( tuner.config_generator(search_space, rng=tuner.rng, max_search=10) ) self.assertEqual(len(configs), 2) def test_config_two_values(self): search_space = {"a": [1], "b": [1, 2, 3]} tuner = RandomSearchTuner(None, None, seed=123) configs = list( tuner.config_generator(search_space, rng=tuner.rng, max_search=10) ) self.assertEqual(len(configs), 3) def test_config_range(self): search_space = {"a": [1], "b": [1, 2, 3], "c": {"range": [1, 10]}} tuner = RandomSearchTuner(None, None, seed=123) configs = list( tuner.config_generator(search_space, rng=tuner.rng, max_search=10) ) self.assertEqual(len(configs), 10) def test_config_unbounded_max_search(self): search_space = {"a": [1], "b": [1, 2, 3], "c": {"range": [1, 10]}} tuner = RandomSearchTuner(None, None, seed=123) configs = list( tuner.config_generator(search_space, rng=tuner.rng, max_search=0) ) self.assertEqual(len(configs), 3) def test_config_log_range(self): search_space = { "a": [1], "b": [1, 2, 3], "c": {"range": [1, 10]}, "d": {"range": [1, 10], "scale": "log"}, } tuner = RandomSearchTuner(None, None, seed=123) configs = list( tuner.config_generator(search_space, rng=tuner.rng, max_search=20) ) self.assertEqual(len(configs), 20) self.assertGreater( np.mean([c["c"] for c in configs]), np.mean([c["d"] for c in configs]) ) def test_tuner_and_logging(self): Xs, Ys = self.single_problem # Set up RandomSearchTuner tuner = RandomSearchTuner(EndModel, log_writer_class=LogWriter) # Run the search init_kwargs = { "seed": 1, "input_batchnorm": False, "middle_batchnorm": False, "layer_out_dims": [2, 10, 2], "verbose": False, "checkpoint": False, } search_space = {"middle_dropout": [0.0, 1.0]} tuner.search( search_space, (Xs[1], Ys[1]), init_kwargs=init_kwargs, train_args=[(Xs[0], Ys[0])], train_kwargs={"n_epochs": 10}, verbose=False, ) # Load the log with open(tuner.report_path, "r") as f: tuner_report = json.load(f) # Confirm that when input dropout = 1.0, score tanks, o/w does well # - Tuner statistics at index 1 has dropout = 1, and 0 at index 0 self.assertLess(tuner_report[1]["score"], 0.65) self.assertGreater(tuner_report[0]["score"], 0.95) # Clean up rmtree(tuner.log_rootdir) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/tuners/test_random_search_tuner.py
metal-master
tests/metal/tuners/__init__.py
import unittest from metal.tuners.hyperband_tuner import HyperbandTuner class HyperbandTunerModelTunerTest(unittest.TestCase): def test_hyperband_schedule_correctness(self): # Test the default schedule that is generated by the hyperband tuner # (which at the moment is budget=200, eta=3) hyperband_tuner = HyperbandTuner( None, hyperband_epochs_budget=200, hyperband_proportion_discard=3, seed=123 ) expected_schedule = [[(9, 2), (3, 8), (1, 26)], [(3, 8), (1, 26)], [(3, 26)]] self.assertEqual(hyperband_tuner.hyperband_schedule, expected_schedule) def test_hyperband_paper_schedule_correctness(self): # Generate the schedule in the hyperband paper # (https://arxiv.org/pdf/1603.06560.pdf) hyperband_tuner = HyperbandTuner( None, hyperband_epochs_budget=1701, hyperband_proportion_discard=3, seed=123 ) # This should generate the exact schedule in the paper. expected_schedule = [ [(81, 1), (27, 3), (9, 9), (3, 27), (1, 81)], [(27, 3), (9, 9), (3, 27), (1, 81)], [(9, 9), (3, 27), (1, 81)], [(6, 27), (2, 81)], [(5, 81)], ] self.assertEqual(hyperband_tuner.hyperband_schedule, expected_schedule) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/tuners/test_hyperband_tuner.py
import numpy as np import torch from metal.end_model import SparseLogisticRegression def test_sparselogreg(self): """Confirm sparse logreg can overfit, works on padded data""" F = 1000 # total number of possible features N = 50 # number of data points S = [10, 100] # range of features per data point X = np.zeros((N, S[1])) for i in range(N): Si = np.random.randint(S[0], S[1]) X[i, :Si] = np.random.randint(F, size=(1, Si)) X = torch.from_numpy(X).long() Y = torch.from_numpy(np.random.randint(1, 3, size=(N,))) em = SparseLogisticRegression(seed=1, input_dim=F, padding_idx=0, verbose=False) em.train_model((X, Y), n_epochs=5, optimizer="sgd", lr=0.0005) self.assertEqual(float(em.network[-1].W.weight.data[0, :].sum()), 0.0) score = em.score((X, Y), verbose=False) self.assertGreater(score, 0.95)
metal-master
tests/metal/contrib/test_baselines.py
import json import unittest from shutil import rmtree import numpy as np import torch from metal.contrib.modules import EmbeddingsEncoder, LSTMModule from metal.end_model import EndModel from metal.logging import LogWriter from metal.tuners.random_tuner import RandomSearchTuner n = 1000 SEQ_LEN = 5 MAX_INT = 8 class LSTMTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed torch.manual_seed(1) np.random.seed(1) def _split_dataset(self, X): return [X[:800], X[800:900], X[900:]] def test_lstm_memorize_first(self): """Confirm that lstm can memorize the first token in a long sequence""" X = torch.randint(1, MAX_INT + 1, (n, SEQ_LEN)).long() Y = X[:, 0] Xs = self._split_dataset(X) Ys = self._split_dataset(Y) embed_size = 4 hidden_size = 10 lstm_module = LSTMModule( embed_size, hidden_size, bidirectional=False, verbose=False, lstm_reduction="attention", encoder_class=EmbeddingsEncoder, encoder_kwargs={"vocab_size": MAX_INT + 1}, ) em = EndModel( k=MAX_INT, input_module=lstm_module, layer_out_dims=[hidden_size, MAX_INT], optimizer="adam", batchnorm=True, seed=1, verbose=False, ) em.train_model((Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=10) score = em.score((Xs[2], Ys[2]), verbose=False) self.assertGreater(score, 0.95) def test_lstm_memorize_marker(self): """Confirm that lstm can return the token that comes after a special marker""" X = torch.randint(1, MAX_INT + 1, (n, SEQ_LEN)).long() Y = torch.zeros(n).long() needles = np.random.randint(1, SEQ_LEN - 1, n) for i in range(n): X[i, needles[i]] = MAX_INT + 1 Y[i] = X[i, needles[i] + 1] Xs = self._split_dataset(X) Ys = self._split_dataset(Y) embed_size = 4 hidden_size = 10 lstm_module = LSTMModule( embed_size, hidden_size, bidirectional=True, verbose=False, lstm_reduction="attention", encoder_class=EmbeddingsEncoder, encoder_kwargs={"vocab_size": MAX_INT + 2}, ) em = EndModel( k=MAX_INT, input_module=lstm_module, layer_out_dims=[hidden_size * 2, MAX_INT], batchnorm=True, seed=1, verbose=False, ) em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=15, verbose=False ) score = em.score((Xs[2], Ys[2]), verbose=False) self.assertGreater(score, 0.95) def test_lstm_embeddings_freeze(self): """Confirm that if embeddings are frozen, they do not change during training""" X = torch.randint(1, MAX_INT + 1, (n, SEQ_LEN)).long() Y = torch.zeros(n).long() needles = np.random.randint(1, SEQ_LEN - 1, n) for i in range(n): X[i, needles[i]] = MAX_INT + 1 Y[i] = X[i, needles[i] + 1] Xs = self._split_dataset(X) Ys = self._split_dataset(Y) embed_size = 4 hidden_size = 10 for freeze_embs in [True, False]: lstm_module = LSTMModule( embed_size, hidden_size, verbose=False, encoder_class=EmbeddingsEncoder, encoder_kwargs={"vocab_size": MAX_INT + 2, "freeze": freeze_embs}, ) em = EndModel( k=MAX_INT, input_module=lstm_module, layer_out_dims=[hidden_size * 2, MAX_INT], verbose=False, ) before = lstm_module.encoder.embeddings.weight.clone() em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=15, verbose=False ) after = lstm_module.encoder.embeddings.weight.clone() if freeze_embs: self.assertEqual(torch.abs(before - after).sum().item(), 0.0) else: self.assertNotEqual(torch.abs(before - after).sum().item(), 0.0) def test_lstm_direct_features(self): """Confirm that lstm can work over features passed in directly (rather than embedded).""" X = torch.randint(1, MAX_INT + 1, (n, SEQ_LEN)).long() Y = X[:, 0] # Convert X to one-hot features Xf = torch.zeros((n, SEQ_LEN, MAX_INT)).long() for i in range(n): for j in range(SEQ_LEN): Xf[i, j, X[i, j] - 1] = 1 X = Xf Xs = self._split_dataset(X) Ys = self._split_dataset(Y) encoded_size = MAX_INT hidden_size = 10 lstm_module = LSTMModule( encoded_size, hidden_size, bidirectional=False, verbose=False, lstm_reduction="attention", ) em = EndModel( k=MAX_INT, input_module=lstm_module, layer_out_dims=[hidden_size, MAX_INT], optimizer="adam", batchnorm=True, seed=1, verbose=False, ) em.train_model((Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=15) score = em.score((Xs[2], Ys[2]), verbose=False) self.assertGreater(score, 0.95) def test_lstm_determinism(self): """Test whether training and scoring is deterministic given seed""" X = torch.randint(1, MAX_INT + 1, (n, SEQ_LEN)).long() Y = torch.zeros(n).long() needles = np.random.randint(1, SEQ_LEN - 1, n) for i in range(n): X[i, needles[i]] = MAX_INT + 1 Y[i] = X[i, needles[i] + 1] Xs = self._split_dataset(X) Ys = self._split_dataset(Y) embed_size = 4 hidden_size = 10 lstm_module = LSTMModule( embed_size, hidden_size, seed=123, bidirectional=True, verbose=False, lstm_reduction="attention", encoder_class=EmbeddingsEncoder, encoder_kwargs={"vocab_size": MAX_INT + 2}, ) em = EndModel( k=MAX_INT, input_module=lstm_module, layer_out_dims=[hidden_size * 2, MAX_INT], batchnorm=True, seed=123, verbose=False, ) em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=2, verbose=False ) score_1 = em.score((Xs[2], Ys[2]), verbose=False) # Test scoring determinism score_2 = em.score((Xs[2], Ys[2]), verbose=False) self.assertEqual(score_1, score_2) # Test training determinism lstm_module_2 = LSTMModule( embed_size, hidden_size, seed=123, bidirectional=True, verbose=False, lstm_reduction="attention", encoder_class=EmbeddingsEncoder, encoder_kwargs={"vocab_size": MAX_INT + 2}, ) em_2 = EndModel( k=MAX_INT, input_module=lstm_module_2, layer_out_dims=[hidden_size * 2, MAX_INT], batchnorm=True, seed=123, verbose=False, ) em_2.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=2, verbose=False ) score_3 = em_2.score((Xs[2], Ys[2]), verbose=False) self.assertEqual(score_1, score_3) def test_tuner_with_lstm(self): """Test basic functionality *and* determinism/seeding of the tuner with a more complex EndModel having an input module""" # From tests/metal/modules/test_lstm.py; TODO: Refactor this n = 1000 SEQ_LEN = 5 MAX_INT = 8 X = torch.randint(1, MAX_INT + 1, (n, SEQ_LEN)).long() Y = torch.zeros(n).long() needles = np.random.randint(1, SEQ_LEN - 1, n) for i in range(n): X[i, needles[i]] = MAX_INT + 1 Y[i] = X[i, needles[i] + 1] Xs = [X[:800], X[800:900], X[900:]] Ys = [Y[:800], Y[800:900], Y[900:]] embed_size = 4 hidden_size = 10 # Set up RandomSearchTuner tuner = RandomSearchTuner( EndModel, module_classes={"input_module": LSTMModule}, log_writer_class=LogWriter, seed=123, ) # EndModel init kwargs init_kwargs = { "seed": 123, "batchnorm": True, "k": MAX_INT, "layer_out_dims": [hidden_size * 2, MAX_INT], "input_batchnorm": True, "verbose": False, } # LSTMModule args & kwargs module_args = {} module_args["input_module"] = (embed_size, hidden_size) module_kwargs = {} module_kwargs["input_module"] = { "seed": 123, "bidirectional": True, "verbose": False, "lstm_reduction": "attention", "encoder_class": EmbeddingsEncoder, "encoder_kwargs": {"vocab_size": MAX_INT + 2}, } # Set up search space # NOTE: No middle layers here, so these should return the same scores! search_space = {"middle_dropout": [0.0, 1.0]} # Run random grid search tuner.search( search_space, (Xs[1], Ys[1]), init_kwargs=init_kwargs, train_args=[(Xs[0], Ys[0])], train_kwargs={"n_epochs": 2}, module_args=module_args, module_kwargs=module_kwargs, verbose=False, ) # Load the log with open(tuner.report_path, "r") as f: tuner_report = json.load(f) # Confirm determinism self.assertEqual(tuner_report[0]["score"], tuner_report[1]["score"]) # Clean up rmtree(tuner.log_rootdir) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/contrib/test_lstm.py
import sys import unittest from itertools import product import numpy as np import torch from metal.label_model.class_balance import ClassBalanceModel sys.path.append("../synthetic") class ClassBalanceModelTest(unittest.TestCase): def _set_seed(self, seed): torch.manual_seed(seed) np.random.seed(seed) def _generate_class_balance(self, k): """Generate class balance""" p_Y = np.random.random(k) p_Y /= p_Y.sum() return p_Y def _generate_cond_probs(self, k, m, bias_diag=True, abstains=False): """Generate conditional probability tables for the m conditionally ind. LFs, such that: cpts[i, y1, y2] = P(\lambda_i = y1 | Y = y2) Args: k: (int) Number of classes m: (int) Number of LFs bias_diag: (bool) If True, adds a bias (proportional to (k-1)) to the diagonal of the randomly generated conditional probability tables, to enforce assumption that LFs are better than random abstains: (bool) Incorporate abstains Outputs: C: (np.array) An (m, k, k) tensor, if abstains=False; or, if abstains=True, (m, k+1, k) """ cpts = [] k_lf = k + 1 if abstains else k for i in range(m): a = np.random.random((k_lf, k)) if bias_diag: if abstains: a[1:, :] += (k - 1) * np.eye(k) else: a += (k - 1) * np.eye(k) cpts.append(a @ np.diag(1 / a.sum(axis=0))) return np.array(cpts) def _generate_L(self, p_Y, C, n, abstains=False): """Generate a label matrix L, with entries in {0,1,...,k} if abstains=True, else in {1,...,k}, given the true class balance, p_Y, and a conditional probabilities table C of m cond. ind. LFs""" k = len(p_Y) m = C.shape[0] # Generate true data labels for n data points Y = np.random.choice(range(1, k + 1), n, p=p_Y) # Generate label matrix L with entries in {0,1,...,k} if abstains=True, # else in {1,...,k} lf_0 = 0 if abstains else 1 L = np.zeros((n, m)) for i, y in enumerate(Y): for j in range(m): L[i, j] = np.random.choice(range(lf_0, k + 1), p=C[j, :, y - 1]) return L def _test_model(self, model, p_Y, C, O=None, L=None, tol=1e-3, verbose=True): model.train_model(O=O, L=L) if verbose: print(f"True class balance: {p_Y}") print(f"Estimated class balance: {model.class_balance}") self.assertLess(np.mean(np.abs(p_Y - model.class_balance)), tol) self.assertLess(np.mean(np.abs(C - model.cond_probs)), tol) def _test_class_balance_estimation(self, k, m, abstains=False, verbose=True): model = ClassBalanceModel(k, abstains=abstains) p_Y = self._generate_class_balance(k) C = self._generate_cond_probs(k, m, bias_diag=True, abstains=abstains) # Compute O; mask out diagonal entries mask = model.get_mask(m) O = np.einsum("aby,cdy,efy,y->acebdf", C, C, C, p_Y) O = torch.from_numpy(O).float() O[1 - mask] = 0 # Test recovery of the class balance self._test_model(model, p_Y, C, O=O) def _test_class_balance_estimation_noisy( self, k, m, n, abstains=False, verbose=True ): model = ClassBalanceModel(k, abstains=abstains) p_Y = self._generate_class_balance(k) C = self._generate_cond_probs(k, m, bias_diag=True, abstains=abstains) # Generate label matrix L L = self._generate_L(p_Y, C, n, abstains=abstains) # Test recovery of the class balance self._test_model(model, p_Y, C, L=L, tol=1e-2) def test_class_balance_estimation_2(self): self._set_seed(123) self._test_class_balance_estimation(2, 25) def test_class_balance_estimation_3(self): self._set_seed(123) self._test_class_balance_estimation(3, 25) # Note: This should pass! However, commented out because too slow... # def test_class_balance_estimation_5(self): # self._set_seed(123) # self._test_class_balance_estimation(5, 25) def test_class_balance_estimation_2_abstains(self): self._set_seed(123) self._test_class_balance_estimation(2, 25, abstains=True) def test_class_balance_estimation_2_noisy(self): self._set_seed(123) self._test_class_balance_estimation_noisy(2, 25, 10000, abstains=True) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/label_model/test_class_balance.py
import sys import unittest import numpy as np from metal.label_model.baselines import MajorityLabelVoter from metal.label_model.label_model import LabelModel from synthetic.generate import SingleTaskTreeDepsGenerator sys.path.append("../synthetic") # TODO: Put in tests for LabelModel baselines again! class LabelModelTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.n_iters = 1 cls.n = 10000 cls.m = 10 cls.k = 2 def _test_label_model(self, data, test_acc=True): label_model = LabelModel(k=data.k, verbose=False) label_model.train_model( data.L, deps=data.E, class_balance=data.p, n_epochs=1000, log_train_every=200, ) # Test parameter estimation error c_probs_est = label_model.get_conditional_probs() err = np.mean(np.abs(data.c_probs - c_probs_est)) self.assertLess(err, 0.025) # Test label prediction accuracy if test_acc: score = label_model.score((data.L, data.Y), verbose=False) self.assertGreater(score, 0.95) # Test against baseline mv = MajorityLabelVoter() mv_score = mv.score((data.L, data.Y), verbose=False) self.assertGreater(score, mv_score) def test_no_deps(self): for seed in range(self.n_iters): np.random.seed(seed) data = SingleTaskTreeDepsGenerator(self.n, self.m, k=self.k, edge_prob=0.0) self._test_label_model(data) def test_augmented_L_construction(self): # 5 LFs: a triangle, a connected edge to it, and a singleton source n = 3 m = 5 k = 2 E = [(0, 1), (1, 2), (2, 0), (0, 3)] L = np.array([[1, 1, 1, 2, 1], [1, 2, 2, 1, 0], [1, 1, 1, 1, 0]]) lm = LabelModel(k=k, verbose=False) lm._set_constants(L) lm._set_dependencies(E) L_aug = lm._get_augmented_label_matrix(L, higher_order=True) # Should have 22 columns: # - 5 * 2 = 10 for the sources # - 8 + 4 for the 3- and 2-clique resp. --> = 22 self.assertEqual(L_aug.shape, (3, 22)) # Same as above but minus 2 abstains = 19 total nonzero entries self.assertEqual(L_aug.sum(), 19) # Next, check the singleton entries for i in range(n): for j in range(m): if L[i, j] > 0: self.assertEqual(L_aug[i, j * k + L[i, j] - 1], 1) # Finally, check the clique entries # Triangle clique self.assertEqual(len(lm.c_tree.node[1]["members"]), 3) j = lm.c_tree.node[1]["start_index"] self.assertEqual(L_aug[0, j], 1) self.assertEqual(L_aug[1, j + 3], 1) self.assertEqual(L_aug[2, j], 1) # Binary clique self.assertEqual(len(lm.c_tree.node[2]["members"]), 2) j = lm.c_tree.node[2]["start_index"] self.assertEqual(L_aug[0, j + 1], 1) self.assertEqual(L_aug[1, j], 1) self.assertEqual(L_aug[2, j], 1) def test_with_deps(self): for seed in range(self.n_iters): np.random.seed(seed) data = SingleTaskTreeDepsGenerator(self.n, self.m, k=self.k, edge_prob=1.0) self._test_label_model(data, test_acc=False) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/label_model/test_label_model.py
metal-master
tests/metal/label_model/__init__.py
metal-master
tests/metal/multitask/__init__.py
import unittest from metal.multitask.task_graph import TaskGraph class TaskGraphTest(unittest.TestCase): def test_binary_tree(self): cardinalities = [2, 2, 2] edges = [(0, 1), (0, 2)] tg = TaskGraph(cardinalities, edges) self.assertTrue(tg.parents[0] == []) self.assertTrue(tg.parents[1] == [0]) self.assertTrue(tg.parents[2] == [0]) self.assertTrue(tg.children[0] == [1, 2]) self.assertTrue(tg.children[1] == []) self.assertTrue(tg.children[2] == []) def test_nonbinary_tree(self): cardinalities = [3, 2, 2, 2] edges = [(0, 1), (0, 2), (0, 3)] tg = TaskGraph(cardinalities, edges) self.assertTrue(tg.parents[1] == [0]) self.assertTrue(tg.children[0] == [1, 2, 3]) def test_binary_tree_depth3(self): cardinalities = [2, 2, 2, 2, 2, 2, 2] edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)] tg = TaskGraph(cardinalities, edges) self.assertTrue(tg.parents[1] == [0]) self.assertTrue(tg.children[1] == [3, 4]) def test_unbalanced_tree(self): cardinalities = [2, 2, 2] edges = [(0, 1), (1, 2)] tg = TaskGraph(cardinalities, edges) self.assertTrue(tg.parents[1] == [0]) self.assertTrue(tg.children[1] == [2]) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/multitask/test_task_graph.py
import sys import unittest import numpy as np from metal.multitask import MTLabelModel from synthetic.generate import HierarchicalMultiTaskTreeDepsGenerator sys.path.append("../synthetic") class MTLabelModelTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.n_iters = 1 cls.n = 10000 cls.m = 10 def _test_label_model(self, data, test_acc=True): label_model = MTLabelModel(task_graph=data.task_graph, verbose=False) label_model.train_model( data.L, deps=data.E, class_balance=data.p, n_epochs=1000 ) # Test parameter estimation error c_probs_est = label_model.get_conditional_probs() err = np.mean(np.abs(data.c_probs - c_probs_est)) self.assertLess(err, 0.025) # Test label prediction accuracy if test_acc: acc = label_model.score((data.L, data.Y)) self.assertGreater(acc, 0.95) def test_multitask(self): for seed in range(self.n_iters): np.random.seed(seed) data = HierarchicalMultiTaskTreeDepsGenerator(self.n, self.m, edge_prob=0.0) self._test_label_model(data, test_acc=True) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/multitask/test_mt_label_model.py
import unittest import numpy as np import torch import torch.nn as nn from metal.end_model.identity_module import IdentityModule from metal.metrics import METRICS from metal.multitask import MTEndModel from metal.multitask.task_graph import TaskGraph, TaskHierarchy class MTEndModelTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 1200 X = np.random.random((n, 2)) * 2 - 1 Y = np.zeros((n, 2)) Y[:, 0] = (X[:, 0] > X[:, 1] + 0.5).astype(int) + 1 Y[:, 1] = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1 X = torch.tensor(X, dtype=torch.float) Xs = [X[:1000], X[1000:1100], X[1100:]] Ys = [ [Y[:1000, 0], Y[:1000, 1]], [Y[1000:1100, 0], Y[1000:1100, 1]], [Y[1100:, 0], Y[1100:, 1]], ] cls.Xs = Xs cls.Ys = Ys def test_multitask_top(self): """Attach all task heads to the top layer""" edges = [] cards = [2, 2] tg = TaskGraph(cards, edges) em = MTEndModel( layer_out_dims=[2, 8, 4], task_graph=tg, seed=1, verbose=False, task_head_layers="top", ) top_layer = len(em.config["layer_out_dims"]) - 1 self.assertEqual(len(em.task_map[top_layer]), em.t) em.train_model( (self.Xs[0], self.Ys[0]), valid_data=(self.Xs[1], self.Ys[1]), verbose=False, n_epochs=10, checkpoint=False, ) score = em.score((self.Xs[2], self.Ys[2]), reduce="mean", verbose=False) self.assertGreater(score, 0.95) def test_multitask_custom_attachments(self): """Attach the task heads at user-specified layers""" edges = [(0, 1)] cards = [2, 2] tg = TaskHierarchy(cards, edges) em = MTEndModel( layer_out_dims=[2, 8, 4], task_graph=tg, seed=1, verbose=False, task_head_layers=[1, 2], ) self.assertEqual(em.task_map[1][0], 0) self.assertEqual(em.task_map[2][0], 1) em.train_model( (self.Xs[0], self.Ys[0]), valid_data=(self.Xs[1], self.Ys[1]), verbose=False, n_epochs=10, checkpoint=False, ) score = em.score((self.Xs[2], self.Ys[2]), reduce="mean", verbose=False) self.assertGreater(score, 0.95) def test_multitask_two_modules(self): """Accept a different representation for each task""" edges = [] cards = [2, 2] tg = TaskGraph(cards, edges) em = MTEndModel( layer_out_dims=[2, 8, 4], task_graph=tg, seed=1, verbose=False, input_modules=[IdentityModule(), IdentityModule()], task_head_layers="top", ) Xs = [] for i, X in enumerate(self.Xs): Xs.append([X[:, 0], X[:, 1]]) em.train_model( (Xs[0], self.Ys[0]), valid_data=(Xs[1], self.Ys[1]), verbose=False, n_epochs=10, checkpoint=False, ) score = em.score((Xs[2], self.Ys[2]), reduce="mean", verbose=False) self.assertGreater(score, 0.95) def test_multitask_custom_heads(self): """Accept a different representation for each task""" edges = [] cards = [2, 2] tg = TaskGraph(cards, edges) em = MTEndModel( layer_out_dims=[2, 8, 4], task_graph=tg, seed=1, verbose=False, head_modules=[nn.Linear(8, 2), nn.Linear(4, 2)], task_head_layers=[1, 2], ) em.train_model( (self.Xs[0], self.Ys[0]), valid_data=(self.Xs[1], self.Ys[1]), verbose=False, n_epochs=10, checkpoint=False, ) score = em.score((self.Xs[2], self.Ys[2]), reduce="mean", verbose=False) self.assertGreater(score, 0.95) def test_scoring(self): edges = [(0, 1)] cards = [2, 2] tg = TaskHierarchy(cards, edges) em = MTEndModel(layer_out_dims=[2, 8, 4], task_graph=tg, seed=1, verbose=False) em.train_model( (self.Xs[0], self.Ys[0]), valid_data=(self.Xs[1], self.Ys[1]), verbose=False, n_epochs=3, checkpoint=False, validation_task=0, ) tasks = [0, 1] for metric in METRICS: all_scores = em.score( (self.Xs[2], self.Ys[2]), metric=metric, reduce=None, verbose=False ) task_specific_scores_score_method = [ em.score( (self.Xs[2], self.Ys[2]), metric=metric, validation_task=task, verbose=False, ) for task in tasks ] task_specific_scores_score_task_method = [ em.score_task( self.Xs[2], self.Ys[2], t=task, metric=metric, verbose=False ) for task in tasks ] for i in range(len(tasks)): self.assertEqual( all_scores[i], task_specific_scores_score_method[i], task_specific_scores_score_task_method[i], ) if __name__ == "__main__": unittest.main()
metal-master
tests/metal/multitask/test_mt_end_model.py
import json import os import unittest from shutil import rmtree import numpy as np import torch from metal.end_model import EndModel class LogWriterTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 2000 X = np.random.random((n, 2)) * 2 - 1 Y = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1 X = torch.tensor(X, dtype=torch.float) Y = torch.tensor(Y, dtype=torch.long) Xs = [X[:1000], X[1000:1500], X[1500:]] Ys = [Y[:1000], Y[1000:1500], Y[1500:]] cls.single_problem = (Xs, Ys) cls.log_dir = "tests/logs/" @classmethod def tearDownClass(cls): print("TODO: Confirm that this is deleting logs directory") # Clean up rmtree(cls.log_dir) def test_logwriter(self): """Test the basic LogWriter class""" writer_kwargs = { "log_dir": self.log_dir, "run_dir": "test_dir", "run_name": "test", } em = EndModel( seed=1, input_batchnorm=False, middle_batchnorm=False, input_dropout=0.0, middle_dropout=0.0, layer_out_dims=[2, 10, 2], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=7, checkpoint=False, writer="json", **writer_kwargs, ) # Load the log with open(em.writer.log_path, "r") as f: log_dict = json.load(f) self.assertEqual(log_dict["config"]["train_config"]["n_epochs"], 7) self.assertEqual(len(log_dict["run_log"]["train/loss"]), 7) def test_tensorboard(self): """Test the TensorBoardWriter class""" pass # log_dir = os.path.join(self.log_dir, "tensorboard") # writer_kwargs = {"log_dir": log_dir, "run_dir": "test_dir", "run_name": "test"} # em = EndModel( # seed=1, # input_batchnorm=False, # middle_batchnorm=False, # input_dropout=0.0, # middle_dropout=0.0, # layer_out_dims=[2, 10, 2], # verbose=False, # ) # Xs, Ys = self.single_problem # em.train_model( # (Xs[0], Ys[0]), # valid_data=(Xs[1], Ys[1]), # n_epochs=2, # checkpoint=False, # writer="tensorboard", # **writer_kwargs, # ) # # Load the log # with open(em.writer.log_path, "r") as f: # pass # # Confirm that the event file was written # self.assertTrue(False)
metal-master
tests/metal/logging/test_writer.py
import copy import os import unittest from shutil import rmtree import numpy as np import torch from metal.end_model import EndModel class CheckpointerTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 2000 X = np.random.random((n, 2)) * 2 - 1 Y = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1 X = torch.tensor(X, dtype=torch.float) Y = torch.tensor(Y, dtype=torch.long) Xs = [X[:1000], X[1000:1500], X[1500:]] Ys = [Y[:1000], Y[1000:1500], Y[1500:]] cls.single_problem = (Xs, Ys) cls.checkpoint_dir = "tests/checkpoints/" @classmethod def tearDownClass(cls): print("TODO: Confirm this is deleting checkpoint directory") rmtree(cls.checkpoint_dir) def test_checkpointing(self): """Confirm that different checkpoints are being saved with checkpoint_every on""" em = EndModel( seed=1, batchnorm=False, dropout=0.0, layer_out_dims=[2, 10, 2], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=True, checkpoint_every=1, ) test_model = copy.deepcopy(em.state_dict()) new_model = torch.load("checkpoints/model_checkpoint_4.pth") self.assertFalse( torch.all( torch.eq( test_model["network.1.0.weight"], new_model["model"]["network.1.0.weight"], ) ) ) new_model = torch.load("checkpoints/model_checkpoint_5.pth") self.assertTrue( torch.all( torch.eq( test_model["network.1.0.weight"], new_model["model"]["network.1.0.weight"], ) ) ) def test_resume_training(self): """Confirm that a checkpoint can be saved and reloaded without throwing error""" em = EndModel( seed=1, batchnorm=False, dropout=0.0, layer_out_dims=[2, 10, 2], verbose=False, ) Xs, Ys = self.single_problem em.train_model( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=True, checkpoint_every=1, ) em.resume_training( (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), model_path="checkpoints/model_checkpoint_2.pth", ) def test_checkpoint_metric(self): """Confirm that a non-standard checkpoint_metric can be used""" pass def test_checkpoint_metric_mode(self): """Confirm that metric_mode is used properly""" pass def test_checkpoint_runway(self): """Confirm that no checkpoints are saved the first checkpoint_runway iters""" pass
metal-master
tests/metal/logging/test_checkpointer.py
import unittest import numpy as np import torch class LoggerTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 2000 X = np.random.random((n, 2)) * 2 - 1 Y = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1 X = torch.tensor(X, dtype=torch.float) Y = torch.tensor(Y, dtype=torch.long) Xs = [X[:1000], X[1000:1500], X[1500:]] Ys = [Y[:1000], Y[1000:1500], Y[1500:]] cls.single_problem = (Xs, Ys) def test_seconds(self): pass def test_examples(self): pass def test_batches(self): pass def test_epochs(self): pass def test_tqdm(self): """Confirm that nothing breaks with tqdm on or off""" pass def test_train_metrics(self): """Confirm non-default train metrics can be passed""" pass def test_valid_metrics(self): """Confirm non-default valid metrics can be passed""" pass def test_custom_metrics(self): """Confirm custom metrics can be passed""" pass def test_label_model_logger(self): """Confirm that logger works at a basic level with LabelModel"""
metal-master
tests/metal/logging/test_logger.py
metal-master
tests/synthetic/__init__.py
metal-master
tests/travis/__init__.py
import unittest import numpy as np class TravisTest(unittest.TestCase): def test_sanity(self): self.assertTrue(1 + 1 == 2) # Confirm import of third-party package also works self.assertTrue(int(np.array([1]) + np.array([1])) == 2) if __name__ == "__main__": unittest.main()
metal-master
tests/travis/test_travis.py
from collections import defaultdict import numpy as np import torch from numpy.random import choice, random from scipy.sparse import csr_matrix from metal.multitask.task_graph import TaskHierarchy from synthetic.words1k import vocab1k def singletask_synthetic(n, m, k, **kwargs): data = SingleTaskTreeDepsGenerator(n, m, k, **kwargs) L = data.L Y = data.Y deps = data.E bags, D = gaussian_bags_of_words(Y, vocab1k, **kwargs) X = bags_to_counts(bags, len(vocab1k)) return D, L, X, Y, deps ################################################################################ # Helpers ################################################################################ def logistic_fn(x): return 1 / (1 + np.exp(-x)) def choose_other_label(k, y): """Given a cardinality k and true label y, return random value in {1,...,k} \ {y}.""" return choice(list(set(range(1, k + 1)) - set([y]))) def indpm(x, y): """Plus-minus indicator function""" return 1 if x == y else -1 ################################################################################ # Single-task (Ls and Ys) ################################################################################ class SingleTaskTreeDepsGenerator(object): """Generates a synthetic single-task L and Y matrix with dependencies Args: n: (int) The number of data points m: (int) The number of labeling sources k: (int) The cardinality of the classification task class_balance: (np.array) each class's percentage of the population theta_range: (tuple) The min and max possible values for theta, the class conditional accuracy for each labeling source edge_prob: edge density in the graph of correlations between sources theta_edge_range: The min and max possible values for theta_edge, the strength of correlation between correlated sources The labeling functions have class-conditional accuracies, and class-unconditional pairwise correlations forming a tree-structured graph. Note that k = the # of true classes; thus source labels are in {0,1,...,k} because they include abstains. """ def __init__( self, n, m, k=2, class_balance=None, theta_range=(0, 1.5), edge_prob=0.0, theta_edge_range=(-1, 1), **kwargs ): self.n = n self.m = m self.k = k # Generate correlation structure: edges self.E, parents dict self.parent self._generate_edges(edge_prob) # Generate class-conditional LF & edge parameters, stored in self.theta self._generate_params(theta_range, theta_edge_range) # Generate class balance self.p if class_balance is None: self.p = np.full(k, 1 / k) else: self.p = class_balance # Generate the true labels self.Y and label matrix self.L self._generate_label_matrix() # Compute the conditional clique probabilities self._get_conditional_probs() # Correct output type self.L = csr_matrix(self.L, dtype=np.int) def _generate_edges(self, edge_prob): """Generate a random tree-structured dependency graph based on a specified edge probability. Also create helper data struct mapping child -> parent. """ self.E, self.parent = [], {} for i in range(self.m): if random() < edge_prob and i > 0: p_i = choice(i) self.E.append((p_i, i)) self.parent[i] = p_i def _generate_params(self, theta_range, theta_edge_range): self.theta = defaultdict(float) for i in range(self.m): t_min, t_max = min(theta_range), max(theta_range) self.theta[i] = (t_max - t_min) * random(self.k + 1) + t_min # Choose random weights for the edges te_min, te_max = min(theta_edge_range), max(theta_edge_range) for (i, j) in self.E: w_ij = (te_max - te_min) * random() + te_min self.theta[(i, j)] = w_ij self.theta[(j, i)] = w_ij def _P(self, i, li, j, lj, y): return np.exp( self.theta[i][y] * indpm(li, y) + self.theta[(i, j)] * indpm(li, lj) ) def P_conditional(self, i, li, j, lj, y): """Compute the conditional probability P_\theta(li | lj, y) = Z^{-1} exp( theta_{i|y} \indpm{ \lambda_i = Y } + \theta_{i,j} \indpm{ \lambda_i = \lambda_j } ) In other words, compute the conditional probability that LF i outputs li given that LF j output lj, and Y = y, parameterized by - a class-conditional LF accuracy parameter \theta_{i|y} - a symmetric LF correlation paramter \theta_{i,j} """ Z = np.sum([self._P(i, _li, j, lj, y) for _li in range(self.k + 1)]) return self._P(i, li, j, lj, y) / Z def _generate_label_matrix(self): """Generate an [n,m] label matrix with entries in {0,...,k}""" self.L = np.zeros((self.n, self.m)) self.Y = np.zeros(self.n, dtype=np.int64) for i in range(self.n): y = choice(self.k, p=self.p) + 1 # Note that y \in {1,...,k} self.Y[i] = y for j in range(self.m): p_j = self.parent.get(j, 0) prob_y = self.P_conditional(j, y, p_j, self.L[i, p_j], y) prob_0 = self.P_conditional(j, 0, p_j, self.L[i, p_j], y) p = np.ones(self.k + 1) * (1 - prob_y - prob_0) / (self.k - 1) p[0] = prob_0 p[y] = prob_y self.L[i, j] = choice(self.k + 1, p=p) def _get_conditional_probs(self): """Compute the true clique conditional probabilities P(\lC | Y) by counting given L, Y; we'll use this as ground truth to compare to. Note that this generates an attribute, self.c_probs, that has the same definition as returned by `LabelModel.get_conditional_probs`. TODO: Can compute these exactly if we want to implement that. """ # TODO: Extend to higher-order cliques again self.c_probs = np.zeros((self.m * (self.k + 1), self.k)) for y in range(1, self.k + 1): Ly = self.L[self.Y == y] for ly in range(self.k + 1): self.c_probs[ly :: (self.k + 1), y - 1] = ( np.where(Ly == ly, 1, 0).sum(axis=0) / Ly.shape[0] ) class HierarchicalMultiTaskTreeDepsGenerator(SingleTaskTreeDepsGenerator): def __init__( self, n, m, theta_range=(0, 1.5), edge_prob=0.0, theta_edge_range=(-1, 1), cardinalities=[2, 3, 3], edges=[(0, 1), (0, 2)], ): self.task_graph = TaskHierarchy(cardinalities, edges) fs = list(self.task_graph.feasible_set()) super().__init__( n, m, k=len(fs), theta_range=theta_range, edge_prob=edge_prob, theta_edge_range=theta_edge_range, ) L_mt = [np.zeros((self.n, self.m)) for _ in range(self.task_graph.t)] for i in range(self.n): for j in range(self.m): if self.L[i, j] > 0: y = fs[int(self.L[i, j]) - 1] for s in range(self.task_graph.t): L_mt[s][i, j] = y[s] self.L = list(map(csr_matrix, L_mt)) # Convert Y to a t-length list of n-length vectors self.Y = [ np.array([fs[y - 1] for y in self.Y]).T[t] for t in range(self.task_graph.t) ] ################################################################################ # Generating Xs and Ds ################################################################################ def gaussian_bags_of_words(Y, vocab=vocab1k, sigma=1, bag_size=[25, 50], **kwargs): """ Generate Gaussian bags of words based on label assignments Args: Y: np.array of true labels sigma: (float) the standard deviation of the Gaussian distributions bag_size: (list) the min and max length of bags of words Returns: X: (Tensor) a tensor of indices representing tokens D: (list) a list of sentences (strings) The sentences are conditionally independent, given a label. Note that technically we use a half-normal distribution here because we take the absolute value of the normal distribution. Example: TBD """ def make_distribution(sigma, num_words): p = abs(np.random.normal(0, sigma, num_words)) return p / sum(p) num_words = len(vocab) word_dists = {y: make_distribution(sigma, num_words) for y in set(Y)} bag_sizes = np.random.choice(range(min(bag_size), max(bag_size)), len(Y)) X = [] items = [] for i, (y, length) in enumerate(zip(Y, bag_sizes)): x = torch.from_numpy(np.random.choice(num_words, length, p=word_dists[y])) X.append(x) items.append(" ".join(vocab[j] for j in x)) return X, items def bags_to_counts(bags, vocab_size): X = torch.zeros(len(bags), vocab_size, dtype=torch.float) for i, bag in enumerate(bags): for word in bag: X[i, word] += 1 return X
metal-master
synthetic/generate.py
metal-master
synthetic/__init__.py
vocab1k = [ "a", "ability", "able", "about", "above", "accept", "according", "account", "across", "act", "action", "activity", "actually", "add", "address", "administration", "admit", "adult", "affect", "after", "again", "against", "age", "agency", "agent", "ago", "agree", "agreement", "ahead", "air", "all", "allow", "almost", "alone", "along", "already", "also", "although", "always", "american", "among", "amount", "analysis", "and", "animal", "another", "answer", "any", "anyone", "anything", "appear", "apply", "approach", "area", "argue", "arm", "around", "arrive", "art", "article", "artist", "as", "ask", "assume", "at", "attack", "attention", "attorney", "audience", "author", "authority", "available", "avoid", "away", "baby", "back", "bad", "bag", "ball", "bank", "bar", "base", "be", "beat", "beautiful", "because", "become", "bed", "before", "begin", "behavior", "behind", "believe", "benefit", "best", "better", "between", "beyond", "big", "bill", "billion", "bit", "black", "blood", "blue", "board", "body", "book", "born", "both", "box", "boy", "break", "bring", "brother", "budget", "build", "building", "business", "but", "buy", "by", "call", "camera", "campaign", "can", "cancer", "candidate", "capital", "car", "card", "care", "career", "carry", "case", "catch", "cause", "cell", "center", "central", "century", "certain", "certainly", "chair", "challenge", "chance", "change", "character", "charge", "check", "child", "choice", "choose", "church", "citizen", "city", "civil", "claim", "class", "clear", "clearly", "close", "coach", "cold", "collection", "college", "color", "come", "commercial", "common", "community", "company", "compare", "computer", "concern", "condition", "conference", "congress", "consider", "consumer", "contain", "continue", "control", "cost", "could", "country", "couple", "course", "court", "cover", "create", "crime", "cultural", "culture", "cup", "current", "customer", "cut", "dark", "data", "daughter", "day", "dead", "deal", "death", "debate", "decade", "decide", "decision", "deep", "defense", "degree", "democrat", "democratic", "describe", "design", "despite", "detail", "determine", "develop", "development", "die", "difference", "different", "difficult", "dinner", "direction", "director", "discover", "discuss", "discussion", "disease", "do", "doctor", "dog", "door", "down", "draw", "dream", "drive", "drop", "drug", "during", "each", "early", "east", "easy", "eat", "economic", "economy", "edge", "education", "effect", "effort", "eight", "either", "election", "else", "employee", "end", "energy", "enjoy", "enough", "enter", "entire", "environment", "environmental", "especially", "establish", "even", "evening", "event", "ever", "every", "everybody", "everyone", "everything", "evidence", "exactly", "example", "executive", "exist", "expect", "experience", "expert", "explain", "eye", "face", "fact", "factor", "fail", "fall", "family", "far", "fast", "father", "fear", "federal", "feel", "feeling", "few", "field", "fight", "figure", "fill", "film", "final", "finally", "financial", "find", "fine", "finger", "finish", "fire", "firm", "first", "fish", "five", "floor", "fly", "focus", "follow", "food", "foot", "for", "force", "foreign", "forget", "form", "former", "forward", "four", "free", "friend", "from", "front", "full", "fund", "future", "game", "garden", "gas", "general", "generation", "get", "girl", "give", "glass", "go", "goal", "good", "government", "great", "green", "ground", "group", "grow", "growth", "guess", "gun", "guy", "hair", "half", "hand", "hang", "happen", "happy", "hard", "have", "he", "head", "health", "hear", "heart", "heat", "heavy", "help", "her", "here", "herself", "high", "him", "himself", "his", "history", "hit", "hold", "home", "hope", "hospital", "hot", "hotel", "hour", "house", "how", "however", "huge", "human", "hundred", "husband", "i", "idea", "identify", "if", "image", "imagine", "impact", "important", "improve", "in", "include", "including", "increase", "indeed", "indicate", "individual", "industry", "information", "inside", "instead", "institution", "interest", "interesting", "international", "interview", "into", "investment", "involve", "issue", "it", "item", "its", "itself", "job", "join", "just", "keep", "key", "kid", "kill", "kind", "kitchen", "know", "knowledge", "land", "language", "large", "last", "late", "later", "laugh", "law", "lawyer", "lay", "lead", "leader", "learn", "least", "leave", "left", "leg", "legal", "less", "let", "letter", "level", "lie", "life", "light", "like", "likely", "line", "list", "listen", "little", "live", "local", "long", "look", "lose", "loss", "lot", "love", "low", "machine", "magazine", "main", "maintain", "major", "majority", "make", "man", "manage", "management", "manager", "many", "market", "marriage", "material", "matter", "may", "maybe", "me", "mean", "measure", "media", "medical", "meet", "meeting", "member", "memory", "mention", "message", "method", "middle", "might", "military", "million", "mind", "minute", "miss", "mission", "model", "modern", "moment", "money", "month", "more", "morning", "most", "mother", "mouth", "move", "movement", "movie", "mr", "mrs", "much", "music", "must", "my", "myself", "name", "nation", "national", "natural", "nature", "near", "nearly", "necessary", "need", "network", "never", "new", "news", "newspaper", "next", "nice", "night", "no", "none", "nor", "north", "not", "note", "nothing", "notice", "now", "n't", "number", "occur", "of", "off", "offer", "office", "officer", "official", "often", "oh", "oil", "ok", "old", "on", "once", "one", "only", "onto", "open", "operation", "opportunity", "option", "or", "order", "organization", "other", "others", "our", "out", "outside", "over", "own", "owner", "page", "pain", "painting", "paper", "parent", "part", "participant", "particular", "particularly", "partner", "party", "pass", "past", "patient", "pattern", "pay", "peace", "people", "per", "perform", "performance", "perhaps", "period", "person", "personal", "phone", "physical", "pick", "picture", "piece", "place", "plan", "plant", "play", "player", "pm", "point", "police", "policy", "political", "politics", "poor", "popular", "population", "position", "positive", "possible", "power", "practice", "prepare", "present", "president", "pressure", "pretty", "prevent", "price", "private", "probably", "problem", "process", "produce", "product", "production", "professional", "professor", "program", "project", "property", "protect", "prove", "provide", "public", "pull", "purpose", "push", "put", "quality", "question", "quickly", "quite", "race", "radio", "raise", "range", "rate", "rather", "reach", "read", "ready", "real", "reality", "realize", "really", "reason", "receive", "recent", "recently", "recognize", "record", "red", "reduce", "reflect", "region", "relate", "relationship", "religious", "remain", "remember", "remove", "report", "represent", "republican", "require", "research", "resource", "respond", "response", "responsibility", "rest", "result", "return", "reveal", "rich", "right", "rise", "risk", "road", "rock", "role", "room", "rule", "run", "safe", "same", "save", "say", "scene", "school", "science", "scientist", "score", "sea", "season", "seat", "second", "section", "security", "see", "seek", "seem", "sell", "send", "senior", "sense", "series", "serious", "serve", "service", "set", "seven", "several", "sex", "sexual", "shake", "share", "she", "shoot", "short", "shot", "should", "shoulder", "show", "side", "sign", "significant", "similar", "simple", "simply", "since", "sing", "single", "sister", "sit", "site", "situation", "six", "size", "skill", "skin", "small", "smile", "so", "social", "society", "soldier", "some", "somebody", "someone", "something", "sometimes", "son", "song", "soon", "sort", "sound", "source", "south", "southern", "space", "speak", "special", "specific", "speech", "spend", "sport", "spring", "staff", "stage", "stand", "standard", "star", "start", "state", "statement", "station", "stay", "step", "still", "stock", "stop", "store", "story", "strategy", "street", "strong", "structure", "student", "study", "stuff", "style", "subject", "success", "successful", "such", "suddenly", "suffer", "suggest", "summer", "support", "sure", "surface", "system", "table", "take", "talk", "task", "tax", "teach", "teacher", "team", "technology", "television", "tell", "ten", "tend", "term", "test", "than", "thank", "that", "the", "their", "them", "themselves", "then", "theory", "there", "these", "they", "thing", "think", "third", "this", "those", "though", "thought", "thousand", "threat", "three", "through", "throughout", "throw", "thus", "time", "to", "today", "together", "tonight", "too", "top", "total", "tough", "toward", "town", "trade", "traditional", "training", "travel", "treat", "treatment", "tree", "trial", "trip", "trouble", "true", "truth", "try", "turn", "tv", "two", "type", "under", "understand", "unit", "until", "up", "upon", "us", "use", "usually", "value", "various", "very", "victim", "view", "violence", "visit", "voice", "vote", "wait", "walk", "wall", "want", "war", "watch", "water", "way", "we", "weapon", "wear", "week", "weight", "well", "west", "western", "what", "whatever", "when", "where", "whether", "which", "while", "white", "who", "whole", "whom", "whose", "why", "wide", "wife", "will", "win", "wind", "window", "wish", "with", "within", "without", "woman", "wonder", "word", "work", "worker", "world", "worry", "would", "write", "writer", "wrong", "yard", "yeah", "year", "yes", "yet", "you", "young", "your", "yourself", ]
metal-master
synthetic/words1k.py
""" This tutorial script runs a simple ResNet to classify the CIFAR-10 dataset using MeTaL. The purpose of this particular tutorial is to demonstrate how a standard machine learning task can be run using MeTaL utilities. Running this script with settings in run_CIFAR_Tutorial.sh should give performance on the order of 92-93% dev set accuracy, which is comparable to the performance numbers presented in the pytorch-cifar repo (https://github.com/kuangliu/pytorch-cifar). Note that as in the pytorch-cifar repo, the dev and test set are the same. This is not generally the case! Running this script with default parameters should recover ~88% accuracy after 10 epochs. """ import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.utils.data.dataloader as dataloader from torch.autograd import Variable from torch.utils.data import Dataset from torchvision import transforms from torchvision.datasets import CIFAR10 # from torchvision.models import resnet import metal.contrib.modules.resnet_cifar10 as resnet from metal import EndModel from metal.utils import convert_labels # Checking to see if cuda is available for GPU use cuda = torch.cuda.is_available() # Parsing command line arguments parser = argparse.ArgumentParser(description="Training CIFAR 10") parser.add_argument( "--epochs", default=10, type=int, help="number of total epochs to run" ) parser.add_argument( "-b", "--batch-size", default=128, type=int, help="mini-batch size (default: 10)" ) parser.add_argument( "--lr", "--learning-rate", default=0.001, type=float, help="initial learning rate" ) parser.add_argument("--momentum", default=0.9, type=float, help="momentum") parser.add_argument( "--weight-decay", "--wd", default=1e-4, type=float, help="weight decay (default: 1e-4)", ) # Setting up dataset to adjust CIFAR indices to one-index, # per MeTaL convention class MetalCIFARDataset(Dataset): """A dataset that group each item in X with it label from Y Args: X: an n-dim iterable of items Y: a torch.Tensor of labels This may be predicted (int) labels [n] or probabilistic (float) labels [n, k] """ def __init__(self, dataset): self.dataset = dataset def __getitem__(self, index): x, y = self.dataset[index] # convert to metal form y += 1 return tuple([x, y]) def __len__(self): return len(self.dataset) def train_model(): global args args = parser.parse_args() # Set up transformations for incoming data transform_train = transforms.Compose( [ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ] ) transform_test = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ] ) # Create datasets and data loaders trainset = CIFAR10( root="./data", train=True, download=True, transform=transform_train ) train_loader = dataloader.DataLoader( MetalCIFARDataset(trainset), batch_size=args.batch_size, shuffle=True, num_workers=2, ) testset = CIFAR10( root="./data", train=False, download=True, transform=transform_test ) test_loader = dataloader.DataLoader( MetalCIFARDataset(testset), batch_size=args.batch_size, shuffle=False, num_workers=2, ) # Defining classes in CIFAR-10 in order classes = ( "plane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck", ) # Define input encoder model = resnet.ResNet18() encode_dim = 512 # Define end model. Note that in MeTaL we supply the encoding dimension # to enable auto-compilation of a multi-task end model. This abstraction # is required here, even in the single task case. See the default end # model config file for all possible options. end_model = EndModel( [encode_dim, len(classes)], input_module=model, seed=123, device="cuda" if cuda else "cpu", skip_head=True, input_relu=False, input_batchnorm=False, middle_relu=False, middle_batchnorm=False, ) # Train end model end_model.train_model( train_data=train_loader, valid_data=test_loader, l2=args.weight_decay, lr=args.lr, n_epochs=args.epochs, log_train_every=1, validation_metric="accuracy", ) # Test end model end_model.score(test_loader, metric=["accuracy", "precision", "recall", "f1"]) if __name__ == "__main__": train_model()
metal-master
tutorials/CIFAR_Tutorial.py
mongoose-master
mongoose_reformer/__init__.py
import random import math import numpy as np import torch import argparse import time import os from reformer_lib.reformer_pytorch import ReformerLM,ReformerLM_tune from reformer_lib.generative_tools import TrainingWrapper from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP try: # from apex.parallel import DistributedDataParallel as DDP from apex.fp16_utils import * from apex import optimizers from apex.multi_tensor_apply import multi_tensor_applier except ImportError: raise ImportError("This code requires APEX") seed=17 torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. np.random.seed(seed) # Numpy module. random.seed(seed) # Python random module. torch.manual_seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default="synthetic") parser.add_argument('--seq_len', type=int, default=1024) parser.add_argument('--min_seq_len', type=int, default=4) parser.add_argument('--ntokens', type=int, default=16) parser.add_argument('--emsize', type=int, default=256) parser.add_argument('--nhid', type=int, default=256) parser.add_argument('--nlayers', type=int, default=2) parser.add_argument('--nhead', type=int, default=4) parser.add_argument('--bucket_size_list', nargs='+', type=int, default=[64, 64]) parser.add_argument('--n_hashes_list', nargs='+', type=int, default=[1, 1]) parser.add_argument('--attn_type_list', nargs='+', default=['triplet', 'triplet']) parser.add_argument('--dropout', type=float, default=0.05) parser.add_argument('--batch_size', type=int, default=16) parser.add_argument('--full_attn_thres', type=int, default=0) parser.add_argument('--lr_main', type=float, default=1e-3) parser.add_argument('--lr_tri', type=float, default=1e-3) parser.add_argument('--tri_alpha', type=float, default=1.0) parser.add_argument('--use_full_attn', action='store_true') parser.add_argument('--log', action='store_false') parser.add_argument('--epochs', type=int, default=30) parser.add_argument('--train_batches', type=int, default=5000) parser.add_argument('--eval_batches', type=int, default=500) parser.add_argument('--print_loss', type=int, default=500) parser.add_argument('--note', type=str, default='') parser.add_argument('--scheduler_hashes', type=int, default=10) parser.add_argument('--thresh', type=float, default=0.01) parser.add_argument('--local_rank', type=int, default=0) GRADIENT_ACCUMULATE_EVERY = 1 args = parser.parse_args() args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 args.gpu = 0 args.world_size = 1 if args.distributed: rank = int(os.environ['RANK']) num_gpus = torch.cuda.device_count() gpu_id = rank % num_gpus torch.cuda.set_device(gpu_id) # args.gpu = args.local_rank # torch.cuda.set_device(args.gpu) torch.distributed.init_process_group(backend='nccl') args.world_size = torch.distributed.get_world_size() # generating Tensorboard writer if args.log and args.local_rank==0: log_dir = "./log_paper/{}".format(args.dataset) log_file = log_dir + "/{}_bucket{}_hash{}_seq{}_bz{}_token{}_lr{}_alpha{}_layer{}_note{}.txt".format( '_'.join(args.attn_type_list), '_'.join(str(x) for x in args.bucket_size_list), '_'.join(str(x) for x in args.n_hashes_list), args.seq_len, args.batch_size, args.ntokens, args.lr_tri, args.tri_alpha, args.nlayers, args.note) os.makedirs(log_dir, exist_ok=True) print("args: ", args, file=open(log_file, "a")) print("args: ", args) run_file = "./run_paper/{}/{}_bucket{}_hash{}_seq{}_bz{}_token{}_lr{}_alpha{}_layer{}_note{}".format(args.dataset, '_'.join(args.attn_type_list),'_'.join(str(x) for x in args.bucket_size_list),'_'.join(str(x) for x in args.n_hashes_list), args.seq_len, args.batch_size, args.ntokens, args.lr_tri, args.tri_alpha, args.nlayers, args.note) writer = SummaryWriter(run_file) def save_model(model, optimizer, name, iteration): with open(os.path.join('synthetic', 'model_' + name + '_' + str(iteration) + '.pt'), 'wb') as f: torch.save(model.state_dict(), f) with open(os.path.join('synthetic', 'optimizer_' + name + '_' + str(iteration) + '.pt'), 'wb') as f: torch.save(optimizer.state_dict(), f) def _pad_to_multiple_of(x, y, axis): """Pads x to multiple of y on the given axis.""" pad_len = np.ceil(x.shape[axis] / float(y)) * y pad_widths = [(0, 0)] * len(x.shape) pad_widths[axis] = (0, int(pad_len - x.shape[axis])) return np.pad(x, pad_widths, mode='constant', constant_values=x.dtype.type(0)) def sequence_copy_inputs( vocab_size, batch_size, train_length, eval_min_length, eval_max_length, reverse=False, pad_to_multiple=32): """Inputs for the sequence copy problem: 0w0w for w in [1..vocab_size-1]*. Args: vocab_size: how many symbols to use. batch_size: how large are the batches. train_length: maximum length of w for training. eval_min_length: minimum length of w for eval. eval_max_length : maximum length of w for eval. reverse: bool (optional, false by default): reverse the second sequence. pad_to_multiple: int, pad length to be multiple of this number. Returns: trax.inputs.Inputs """ def random_minibatches(length_list): """Generate a stream of random mini-batches.""" while True: length = random.choice(length_list) assert length % 2 == 0 w_length = (length // 2) - 1 w = np.random.randint(low=1, high=vocab_size - 1, size=(batch_size, w_length)) zero = np.zeros([batch_size, 1], np.int32) loss_weights = np.concatenate([np.zeros((batch_size, w_length + 2)), np.ones((batch_size, w_length))], axis=1) if reverse: x = np.concatenate([zero, w, zero, np.flip(w, axis=1)], axis=1) else: x = np.concatenate([zero, w, zero, w], axis=1) x = torch.Tensor(_pad_to_multiple_of(x, pad_to_multiple, 1)).cuda().long() loss_weights = torch.Tensor(_pad_to_multiple_of(loss_weights, pad_to_multiple, 1)).cuda().long() yield (x,x,loss_weights) # Here inputs and targets are the same. train_lengths = [2 * (i + 2) for i in range(train_length - 1)] eval_lengths = [2 * (i + 1) for i in range(eval_min_length, eval_max_length)] train_stream = lambda _: random_minibatches(train_lengths) eval_stream = lambda _: random_minibatches(eval_lengths) return train_stream(None), eval_stream(None) def train(model, train_loader, epoch): model.train() # Turn on the train mode total_loss = 0. start_time = time.time() for batch in range(args.train_batches): for __ in range(GRADIENT_ACCUMULATE_EVERY): data, target, loss_mask = next(train_loader) if 'triplet' in args.attn_type_list: loss = model(data, loss_weight=loss_mask, return_loss=True, calc_triplet=True) tri_loss = model.net.net.get_triplet_loss() if tri_loss != 0.0: tri_loss.backward() model.net.net.clear_triplet_loss() else: loss = model(data, loss_weight=loss_mask, return_loss=True, calc_triplet=False) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5) optimizer_main.step() optimizer_main.zero_grad() if 'triplet' in args.attn_type_list: optimizer_tri.step() optimizer_tri.zero_grad() total_loss += loss.item() log_interval = args.print_loss if batch % log_interval == 0 and batch > 0: cur_loss = total_loss / log_interval elapsed = time.time() - start_time if args.local_rank==0: print('| epoch {:3d} | {:5d}/{:5d} batches | ' 'lr {:02.5f} | ms/batch {:5.2f} | ' 'loss {:5.2f} | ppl {:8.2f}'.format( epoch, batch, args.train_batches , args.lr_main, elapsed * 1000 / log_interval, cur_loss, math.exp(cur_loss))) if args.log and args.local_rank==0: print('| epoch {:3d} | {:5d}/{:5d} batches | ' 'lr {:02.5f} | ms/batch {:5.2f} | ' 'loss {:5.2f} | ppl {:8.2f}'.format( epoch, batch, args.train_batches , args.lr_main, elapsed * 1000 / log_interval, cur_loss, math.exp(cur_loss)), file = open(log_file, "a")) total_loss = 0 if args.log and args.local_rank==0: writer.add_scalar('Loss/train', cur_loss, epoch*args.train_batches+batch) writer.add_scalar('Loss/train_pp', math.exp(cur_loss), epoch*args.train_batches+batch) start_time = time.time() def evaluate(eval_model, data_source, data_batches, epoch): eval_model.eval() # Turn on the evaluation mode total_loss = 0. counter = 0 with torch.no_grad(): for i in range(data_batches): data, target, loss_mask = next(data_source) loss = eval_model(data, loss_weight=loss_mask, return_loss=True, calc_triplet=False) valid_token = torch.sum(loss_mask) total_loss += valid_token*loss.item() counter += valid_token return total_loss / counter if __name__ == "__main__": train_loader, eval_loader = sequence_copy_inputs(args.ntokens, args.batch_size, args.seq_len//2, args.min_seq_len, args.seq_len//2) model = ReformerLM_tune( dim=args.nhid, emb_dim=args.emsize, depth=args.nlayers, max_seq_len=args.seq_len, num_tokens=args.ntokens, heads=args.nhead, bucket_size_list=args.bucket_size_list, fixed_position_emb=True, n_hashes_list=args.n_hashes_list, ff_chunks=1, ff_mult=1, attn_chunks=1, layer_dropout=0., ff_dropout=args.dropout, post_attn_dropout=args.dropout, lsh_dropout=args.dropout, weight_tie=False, causal=True, n_local_attn_heads=0, use_full_attn=args.use_full_attn, # set this to true for comparison with full attention reverse_thres=9999999999, full_attn_thres=args.full_attn_thres, num_mem_kv=0, attn_type_list=args.attn_type_list, store_stats=args.log, pkm_num_keys=0, ) model = TrainingWrapper(model) model.cuda() params_1 = [] params_2 = [] for name, p in model.named_parameters(): if 'rotation' in name: params_2.append(p) else: params_1.append(p) if 'triplet' in args.attn_type_list: optimizer_main = torch.optim.Adam(params_1, lr=args.lr_main) optimizer_tri = torch.optim.Adam(params_2, lr=args.lr_tri) else: optimizer_main = torch.optim.Adam(model.parameters(), lr=args.lr_main) if args.distributed: global ddp_model model = DDP(model, device_ids=[args.local_rank], output_device=args.local_rank) ddp_model = model for epoch in range(0, args.epochs): epoch_start_time = time.time() train(model, train_loader, epoch) val_loss = evaluate(model, eval_loader, args.print_loss, epoch) if args.log and args.local_rank==0: writer.add_scalar('Loss/val', val_loss, epoch) writer.add_scalar('Loss/val_pp', math.exp(val_loss), epoch) print('-' * 89) print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | ' 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time), val_loss, math.exp(val_loss))) print('-' * 89) if args.log and args.local_rank==0: print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | ' 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time), val_loss, math.exp(val_loss)), file=open(log_file, "a")) if args.log: writer.close()
mongoose-master
mongoose_reformer/train_reformer.py
from functools import partial import torch from torch import nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence from reformer_lib.reformer_pytorch import ReformerLM,ReformerLM_tune from reformer_lib.autopadder import Autopadder def top_p(logits, thres = 0.9): sorted_logits, sorted_indices = torch.sort(logits, descending=True) cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) sorted_indices_to_remove = cum_probs > (1 - thres) sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone() sorted_indices_to_remove[:, 0] = 0 sorted_logits[sorted_indices_to_remove] = float('-inf') return sorted_logits.scatter(1, sorted_indices, sorted_logits) def top_k(logits, thres = 0.9): k = int((1 - thres) * logits.shape[-1]) val, ind = torch.topk(logits, k) probs = torch.full_like(logits, float('-inf')) probs.scatter_(1, ind, val) return probs class TrainingWrapper(nn.Module): def __init__(self, net, ignore_index = -100, pad_value = 0): super().__init__() assert isinstance(net, ReformerLM) or isinstance(net, ReformerLM_tune), 'generative trainer wrapper can only accept ReformerLM class' self.pad_value = pad_value self.ignore_index = ignore_index self.net = Autopadder(net) self.max_seq_len = net.max_seq_len @torch.no_grad() def generate(self, start_tokens, seq_len, eos_token = None, temperature = 1., filter_logits_fn = top_k, filter_thres = 0.9, **kwargs): was_training = self.net.training num_dims = len(start_tokens.shape) if num_dims == 1: start_tokens = start_tokens[None, :] b, t = start_tokens.shape self.net.eval() out = start_tokens input_mask = kwargs.pop('input_mask', None) if input_mask is None: input_mask = torch.full_like(out, True, dtype=torch.bool, device=out.device) for _ in range(seq_len): x = out[:, -self.max_seq_len:] input_mask = input_mask[:, -self.max_seq_len:] logits = self.net(x, input_mask=input_mask, **kwargs)[:, -1, :] filtered_logits = filter_logits_fn(logits, thres = filter_thres) probs = F.softmax(filtered_logits / temperature, dim=-1) sample = torch.multinomial(probs, 1) out = torch.cat((out, sample), dim=-1) input_mask = F.pad(input_mask, (0, 1), value=True) if eos_token is not None and (sample == eos_token).all(): break out = out[:, t:] if num_dims == 1: out = out.squeeze(0) self.net.train(was_training) return out def forward(self, x, loss_weight=None, return_loss=False, **kwargs): pad = partial(pad_sequence, batch_first = True, padding_value = self.pad_value) if not return_loss: if not isinstance(x, torch.Tensor): x = pad(x) return self.net(x, **kwargs) if isinstance(x, torch.Tensor): xi = x[:, :-1] xo = x[:, 1:] else: xi = pad(list(map(lambda t: t[:-1], x))) xo = pad(list(map(lambda t: t[1:], x))) out = self.net(xi, **kwargs) if loss_weight != None: num_token = torch.sum(loss_weight) masked_loss = loss_weight[:, 1:] * F.cross_entropy(out.transpose(1, 2), xo, reduction='none', ignore_index = self.ignore_index) loss = torch.sum(masked_loss) / num_token else: loss = F.cross_entropy(out.transpose(1, 2), xo, ignore_index = self.ignore_index) return loss
mongoose-master
mongoose_reformer/reformer_lib/generative_tools.py
import math import torch from torch import nn import torch.nn.functional as F from reformer_lib.reformer_pytorch import Reformer, ReformerLM, LSHSelfAttention,ReformerLM_tune,Reformer_tune def pad_to_multiple(tensor, seqlen, multiple, dim=-1): m = seqlen / multiple if m.is_integer(): return tensor remainder = math.ceil(m) * multiple - seqlen pad_offset = (0,) * (-1 - dim) * 2 return F.pad(tensor, (*pad_offset, 0, remainder), value=0) class Autopadder(nn.Module): def __init__(self, net): super().__init__() assert isinstance(net, (Reformer, ReformerLM, LSHSelfAttention,ReformerLM_tune,Reformer_tune)), 'only modules LSHSelfAttention, Reformer, ReformerLM accepted' self.net = net reformer = net.reformer if isinstance(net, (ReformerLM,ReformerLM_tune)) else net self.pad_dim = -1 if isinstance(net, (ReformerLM,ReformerLM_tune)) else -2 if isinstance(net, (ReformerLM_tune,Reformer_tune)): self.bucket_size = reformer.bucket_size_list[0] else: self.bucket_size = reformer.bucket_size self.num_mem_kv = reformer.num_mem_kv self.full_attn_thres = reformer.full_attn_thres def forward(self, x, **kwargs): b, t, m, device = *x.shape[:2], self.num_mem_kv, x.device keys = kwargs.get('keys') input_mask = kwargs.get('input_mask') input_attn_mask = kwargs.get('input_attn_mask') k_len = 0 if keys is None else keys.shape[1] seqlen = t + m + k_len if seqlen > self.full_attn_thres: if input_mask is None: input_mask = torch.full_like(x, True, device=x.device, dtype=torch.bool) x = pad_to_multiple(x, seqlen, self.bucket_size * 2, dim=self.pad_dim) if input_mask is not None: new_mask = F.pad(input_mask, (0, x.shape[1] - input_mask.shape[1]), value=False) kwargs.update(input_mask=new_mask) if input_attn_mask is not None: offset = x.shape[1] - input_attn_mask.shape[1] new_mask = F.pad(input_attn_mask, (0, offset, 0, offset), value=False) kwargs.update(input_attn_mask=new_mask) out = self.net(x, **kwargs) return out[:, 0:t]
mongoose-master
mongoose_reformer/reformer_lib/autopadder.py
import re from torch import nn from reformer_lib.reformer_pytorch import ReformerLM from reformer_lib.generative_tools import TrainingWrapper ENC_PREFIX = 'enc_' DEC_PREFIX = 'dec_' def group_dict_by_key(cond, d): return_val = [dict(),dict()] for key in d.keys(): match = bool(cond(key)) ind = int(not match) return_val[ind][key] = d[key] return (*return_val,) def string_begins_with(prefix, str): return bool(re.match(f'^{prefix}', str)) def group_by_key_prefix(prefix, d): return group_dict_by_key(lambda x: string_begins_with(prefix, x), d) def group_by_key_prefix_and_remove_prefix(prefix, d): kwargs_with_prefix, kwargs = group_dict_by_key(lambda x: string_begins_with(prefix, x), d) kwargs_without_prefix = dict(map(lambda x: (x[0][len(prefix):], x[1]), tuple(kwargs_with_prefix.items()))) return kwargs_without_prefix, kwargs def extract_enc_dec_kwargs(kwargs): enc_kwargs, kwargs = group_by_key_prefix_and_remove_prefix(ENC_PREFIX, kwargs) dec_kwargs, kwargs = group_by_key_prefix_and_remove_prefix(DEC_PREFIX, kwargs) return enc_kwargs, dec_kwargs, kwargs def extract_and_set_enc_dec_kwargs(kwargs): enc_kwargs, dec_kwargs, kwargs = extract_enc_dec_kwargs(kwargs) if 'input_mask' in enc_kwargs: dec_kwargs.setdefault('context_mask', enc_kwargs['input_mask']) return enc_kwargs, dec_kwargs, kwargs class ReformerEncDec(nn.Module): def __init__(self, dim, ignore_index = -100, pad_value = 0, **kwargs): super().__init__() enc_kwargs, dec_kwargs, _ = extract_enc_dec_kwargs(kwargs) assert 'return_embedding' not in enc_kwargs, 'you cannot manually set the return embeddings flag for the encoder' assert 'dim' not in dec_kwargs and 'dim' not in enc_kwargs, 'you must set the dim for both encoder and decoder' enc_kwargs['dim'] = dec_kwargs['dim'] = dim enc_kwargs['return_embeddings'] = True dec_kwargs['causal'] = True enc_kwargs.setdefault('bucket_size', 64) dec_kwargs.setdefault('bucket_size', enc_kwargs['bucket_size'] * 2) enc = ReformerLM(**enc_kwargs) dec = ReformerLM(**dec_kwargs) self.enc = TrainingWrapper(enc, ignore_index = ignore_index, pad_value = pad_value) self.dec = TrainingWrapper(dec, ignore_index = ignore_index, pad_value = pad_value) def generate(self, seq_in, seq_out_start, seq_len, **kwargs): enc_kwargs, dec_kwargs, kwargs = extract_and_set_enc_dec_kwargs(kwargs) enc_keys = self.enc(seq_in, **enc_kwargs) return self.dec.generate(seq_out_start, seq_len, keys = enc_keys, **{**dec_kwargs, **kwargs}) def forward(self, seq_in, seq_out, return_loss = False, **kwargs): enc_kwargs, dec_kwargs, kwargs = extract_and_set_enc_dec_kwargs(kwargs) enc_keys = self.enc(seq_in, **enc_kwargs) return self.dec(seq_out, return_loss = return_loss, keys = enc_keys, **dec_kwargs)
mongoose-master
mongoose_reformer/reformer_lib/reformer_enc_dec.py
import torch import torch.nn as nn from torch.autograd.function import Function from torch.utils.checkpoint import get_device_states, set_device_states # following example for saving and setting rng here https://pytorch.org/docs/stable/_modules/torch/utils/checkpoint.html class Deterministic(nn.Module): def __init__(self, net): super().__init__() self.net = net self.cpu_state = None self.cuda_in_fwd = None self.gpu_devices = None self.gpu_states = None def record_rng(self, *args): self.cpu_state = torch.get_rng_state() if torch.cuda._initialized: self.cuda_in_fwd = True self.gpu_devices, self.gpu_states = get_device_states(*args) def forward(self, *args, record_rng = False, set_rng = False, **kwargs): if record_rng: self.record_rng(*args) if not set_rng: return self.net(*args, **kwargs) rng_devices = [] if self.cuda_in_fwd: rng_devices = self.gpu_devices with torch.random.fork_rng(devices=rng_devices, enabled=True): torch.set_rng_state(self.cpu_state) if self.cuda_in_fwd: set_device_states(self.gpu_devices, self.gpu_states) return self.net(*args, **kwargs) # heavily inspired by https://github.com/RobinBruegger/RevTorch/blob/master/revtorch/revtorch.py # once multi-GPU is confirmed working, refactor and send PR back to source class ReversibleBlock(nn.Module): def __init__(self, f, g, depth=None, send_signal = False): super().__init__() self.f = Deterministic(f) self.g = Deterministic(g) self.depth = depth self.send_signal = send_signal def forward(self, x, f_args = {}, g_args = {}): x1, x2 = torch.chunk(x, 2, dim=2) y1, y2 = None, None if self.send_signal: f_args['_reverse'] = g_args['_reverse'] = False f_args['_depth'] = g_args['_depth'] = self.depth with torch.no_grad(): y1 = x1 + self.f(x2, record_rng=self.training, **f_args) y2 = x2 + self.g(y1, record_rng=self.training, **g_args) return torch.cat([y1, y2], dim=2) def backward_pass(self, y, dy, f_args = {}, g_args = {}): y1, y2 = torch.chunk(y, 2, dim=2) del y dy1, dy2 = torch.chunk(dy, 2, dim=2) del dy if self.send_signal: f_args['_reverse'] = g_args['_reverse'] = True f_args['_depth'] = g_args['_depth'] = self.depth with torch.enable_grad(): y1.requires_grad = True gy1 = self.g(y1, set_rng=True, **g_args) torch.autograd.backward(gy1, dy2) with torch.no_grad(): x2 = y2 - gy1 del y2, gy1 dx1 = dy1 + y1.grad del dy1 y1.grad = None with torch.enable_grad(): x2.requires_grad = True fx2 = self.f(x2, set_rng=True, **f_args) torch.autograd.backward(fx2, dx1, retain_graph=True) with torch.no_grad(): x1 = y1 - fx2 del y1, fx2 dx2 = dy2 + x2.grad del dy2 x2.grad = None x = torch.cat([x1, x2.detach()], dim=2) dx = torch.cat([dx1, dx2], dim=2) return x, dx class IrreversibleBlock(nn.Module): def __init__(self, f, g): super().__init__() self.f = f self.g = g def forward(self, x, f_args, g_args): x1, x2 = torch.chunk(x, 2, dim=2) y1 = x1 + self.f(x2, **f_args) y2 = x2 + self.g(y1, **g_args) return torch.cat([y1, y2], dim=2) class _ReversibleFunction(Function): @staticmethod def forward(ctx, x, blocks, kwargs): ctx.kwargs = kwargs for block in blocks: x = block(x, **kwargs) ctx.y = x.detach() ctx.blocks = blocks return x @staticmethod def backward(ctx, dy): y = ctx.y kwargs = ctx.kwargs for block in ctx.blocks[::-1]: y, dy = block.backward_pass(y, dy, **kwargs) return dy, None, None class ReversibleSequence(nn.Module): def __init__(self, blocks, layer_dropout = 0., reverse_thres = 0, send_signal = False): super().__init__() self.layer_dropout = layer_dropout self.reverse_thres = reverse_thres self.blocks = nn.ModuleList([ReversibleBlock(f, g, depth, send_signal) for depth, (f, g) in enumerate(blocks)]) self.irrev_blocks = nn.ModuleList([IrreversibleBlock(f=f, g=g) for f, g in blocks]) def forward(self, x, arg_route = (True, True), **kwargs): reverse = x.shape[1] > self.reverse_thres blocks = self.blocks if reverse else self.irrev_blocks if self.training and self.layer_dropout > 0: to_drop = torch.empty(len(self.blocks)).uniform_(0, 1) < self.layer_dropout blocks = [block for block, drop in zip(self.blocks, to_drop) if not drop] blocks = self.blocks[:1] if len(blocks) == 0 else blocks f_args, g_args = map(lambda route: kwargs if route else {}, arg_route) block_kwargs = {'f_args': f_args, 'g_args': g_args} if not reverse: for block in blocks: x = block(x, **block_kwargs) return x return _ReversibleFunction.apply(x, blocks, block_kwargs)
mongoose-master
mongoose_reformer/reformer_lib/reversible.py
from torch import nn from reformer_lib import LSHAttention, LSHSelfAttention from collections import defaultdict class Recorder(nn.Module): def __init__(self, net): super().__init__() self.iter = 0 self.recordings = defaultdict(list) self.net = net self.on = True self.ejected = False def eject(self): self.ejected = True self.clear() self.unwire() return self.net def wire(self): for module in self.net.modules(): if isinstance(module, LSHAttention): module._return_attn = True if isinstance(module, LSHSelfAttention): module.callback = self.record def unwire(self): for module in self.net.modules(): if isinstance(module, LSHAttention): module._return_attn = False if isinstance(module, LSHSelfAttention): module.callback = None def turn_on(self): self.on = True def turn_off(self): self.on = False def clear(self): del self.recordings self.recordings = defaultdict(list) self.iter = 0 def record(self, attn, buckets): if not self.on: return data = {'attn': attn.detach().cpu(), 'buckets': buckets.detach().cpu()} self.recordings[self.iter].append(data) def forward(self, x, **kwargs): assert not self.ejected, 'Recorder has already been ejected and disposed' if self.on: self.wire() out = self.net(x, **kwargs) self.iter += 1 self.unwire() return out
mongoose-master
mongoose_reformer/reformer_lib/recorder.py
from reformer_lib.reformer_pytorch import LSHAttention, LSHSelfAttention, Reformer, ReformerLM from reformer_lib.reformer_enc_dec import ReformerEncDec from reformer_lib.recorder import Recorder from reformer_lib.autopadder import Autopadder
mongoose-master
mongoose_reformer/reformer_lib/__init__.py
import torch from mongoose_slide.slide_lib.simHash import SimHash class Scheduler: def __init__(self, data, D, k=1, l=10, thresh=0.01): self.thresh_hash = SimHash(D, k, l) self.hash_codes = self.thresh_hash.hash(data) self.thresh = thresh def detect_change(self, updated_data): check = self.thresh_hash.hash(updated_data) distance = check - self.hash_codes if torch.sum(torch.abs(distance)) > self.thresh*distance.numel(): self.hash_codes = check return True else: return False
mongoose-master
mongoose_reformer/reformer_lib/scheduler.py
import math import torch import torch.nn as nn from torch.nn import Identity import torch.nn.functional as F from torch.autograd import Function from functools import partial, reduce, wraps from itertools import chain from operator import mul from local_attention import LocalAttention from axial_positional_embedding import AxialPositionalEmbedding from product_key_memory import PKM from reformer_lib.reversible import ReversibleSequence from reformer_lib.scheduler import Scheduler from torch.nn.init import xavier_uniform_ from torch.nn.init import constant_ from torch.nn.init import xavier_normal_ # constants TOKEN_SELF_ATTN_VALUE = -5e4 # carefully set for half precision to work # helper fns def sort_key_val(t1, t2, dim=-1): values, indices = t1.sort(dim=dim) t2 = t2.expand_as(t1) return values, t2.gather(dim, indices), indices def batched_index_select(values, indices): last_dim = values.shape[-1] return values.gather(1, indices[:, :, None].expand(-1, -1, last_dim)) def process_inputs_chunk(fn, chunks=1, dim=0): def inner_fn(*args, **kwargs): keys, values, len_args = kwargs.keys(), kwargs.values(), len(args) chunked_args = list(zip(*map(lambda x: x.chunk(chunks, dim=dim), list(args) + list(values)))) all_args = map(lambda x: (x[:len_args], dict(zip(keys, x[len_args:]))), chunked_args) outputs = [fn(*c_args, **c_kwargs) for c_args, c_kwargs in all_args] # return tuple(map(lambda x: torch.cat(x, dim=dim), zip(*outputs))) def cat_fn(x): if x[0] is not None: return torch.cat(x, dim=dim) else: return None return tuple(map(cat_fn, zip(*outputs))) return inner_fn def chunked_sum(tensor, chunks=1): *orig_size, last_dim = tensor.shape tensor = tensor.reshape(-1, last_dim) summed_tensors = [c.sum(dim=-1) for c in tensor.chunk(chunks, dim=0)] return torch.cat(summed_tensors, dim=0).reshape(orig_size) def default(val, default_val): return default_val if val is None else val def cast_tuple(x): return x if isinstance(x, tuple) else (x,) def max_neg_value(tensor): return -torch.finfo(tensor.dtype).max def cache_fn(f): cache = None @wraps(f) def cached_fn(*args, **kwargs): nonlocal cache if cache is not None: return cache cache = f(*args, **kwargs) return cache return cached_fn def cosine_similarity(x1, x2, dim=1, eps=1e-6): r"""Returns cosine similarity between x1 and x2, computed along dim. Args: x1 (Variable): First input. x2 (Variable): Second input (of size matching x1). dim (int, optional): Dimension of vectors. Default: 1 eps (float, optional): Small value to avoid division by zero. Default: 1e-8 Shape: - Input: :math:`(\ast_1, D, \ast_2)` where D is at position `dim`. - Output: :math:`(\ast_1, \ast_2)` where 1 is at position `dim`. """ w1 = torch.norm(x1 + eps, 2, dim, keepdim=True) w2 = torch.norm(x2 + eps, 2, dim, keepdim=True) x1 /= w1.clamp(min=eps) x2 /= w2.clamp(min=eps) w12 = torch.sum(x1 * x2, dim) return w12.squeeze() def cache_method_decorator(cache_attr, cache_namespace, reexecute=False): def inner_fn(fn): @wraps(fn) def wrapper(self, *args, key_namespace=None, fetch=False, set_cache=True, **kwargs): namespace_str = str(default(key_namespace, '')) _cache = getattr(self, cache_attr) _keyname = f'{cache_namespace}:{namespace_str}' if fetch: val = _cache[_keyname] if reexecute: fn(self, *args, **kwargs) else: val = fn(self, *args, **kwargs) if set_cache: setattr(self, cache_attr, {**_cache, **{_keyname: val}}) return val return wrapper return inner_fn def expand_dim(dim, k, t): t = t.unsqueeze(dim) expand_shape = [-1] * len(t.shape) expand_shape[dim] = k return t.expand(*expand_shape) def merge_dims(ind_from, ind_to, tensor): shape = list(tensor.shape) arr_slice = slice(ind_from, ind_to + 1) shape[arr_slice] = [reduce(mul, shape[arr_slice])] return tensor.reshape(*shape) def split_at_index(dim, index, t): pre_slices = (slice(None),) * dim l = (*pre_slices, slice(None, index)) r = (*pre_slices, slice(index, None)) return t[l], t[r] # helper classes class MatrixMultiply(nn.Module): def __init__(self, tensor, transpose=False, normalize=False): super().__init__() self.tensor = tensor self.transpose = transpose self.normalize = normalize def forward(self, x): tensor = self.tensor if self.normalize: tensor = F.normalize(tensor, dim=-1) if self.transpose: tensor = tensor.t() return x @ tensor class ReZero(nn.Module): def __init__(self, fn): super().__init__() self.g = nn.Parameter(torch.zeros(1)) self.fn = fn def forward(self, x, **kwargs): return self.fn(x, **kwargs) * self.g class ScaleNorm(nn.Module): def __init__(self, dim, eps=1e-5): super().__init__() self.g = nn.Parameter(torch.ones(1)) self.eps = eps def forward(self, x): n = torch.norm(x, dim=-1, keepdim=True).clamp(min=self.eps) return x / n * self.g class PreNorm(nn.Module): def __init__(self, norm_class, dim, fn): super().__init__() self.norm = norm_class(dim) self.fn = fn def forward(self, x, **kwargs): x = self.norm(x) return self.fn(x, **kwargs) class Chunk(nn.Module): def __init__(self, chunks, fn, along_dim=-1): super().__init__() self.dim = along_dim self.chunks = chunks self.fn = fn def forward(self, x, **kwargs): if self.chunks == 1: return self.fn(x, **kwargs) chunks = x.chunk(self.chunks, dim=self.dim) return torch.cat([self.fn(c, **kwargs) for c in chunks], dim=self.dim) # LSH attention as described in https://openreview.net/pdf?id=rkgNKkHtvB # adapted from trax, stripped to what paper said needed to work # namely that buckets need to be at least 64 with 8 rounds of hashing # https://github.com/google/trax/blob/master/trax/layers/research/efficient_attention.py#L442 # + class LSHAttention(nn.Module): def __init__(self, dropout=0., bucket_size=64, n_hashes=8, causal=False, allow_duplicate_attention=True, attend_across_buckets=True, rehash_each_round=True, drop_for_hash_rate=0.0, random_rotations_per_head=False, return_attn=False, store_stats=False): super().__init__() if dropout >= 1.0: raise ValueError('Dropout rates must be lower than 1.') self.dropout = nn.Dropout(dropout) self.dropout_for_hash = nn.Dropout(drop_for_hash_rate) # self.rotations = nn.Linear(64, 128, bias=False) assert rehash_each_round or allow_duplicate_attention, ( 'The setting {allow_duplicate_attention=False, rehash_each_round=False}' ' is not implemented.') self.causal = causal self.bucket_size = bucket_size self.n_hashes = n_hashes self._allow_duplicate_attention = allow_duplicate_attention self._attend_across_buckets = attend_across_buckets self._rehash_each_round = rehash_each_round self._random_rotations_per_head = random_rotations_per_head # will expend extra computation to return attention matrix self._return_attn = return_attn # cache buckets for reversible network, reported by authors to make Reformer work at depth self._cache = {} self.store_stats = store_stats self.mean_dp = 0.0 self.stat_count = 0 # @cache_method_decorator('_cache', 'buckets', reexecute=True) def hash_vectors(self, n_buckets, vecs, rotations=None): batch_size = vecs.shape[0] device = vecs.device # See https://arxiv.org/pdf/1509.02897.pdf # We sample a different random rotation for each round of hashing to # decrease the probability of hash misses. assert n_buckets % 2 == 0 rot_size = n_buckets rotations_shape = ( batch_size if self._random_rotations_per_head else 1, vecs.shape[-1], self.n_hashes if self._rehash_each_round else 1, rot_size // 2) # add rotations # random_rotations = torch.randn(rotations_shape, dtype=vecs.dtype, device=device).expand(batch_size, -1, -1, -1) if rotations is None: random_rotations = torch.randn(rotations_shape, dtype=vecs.dtype, device=device).expand(batch_size, -1, -1, -1) else: if rotations.size(-1) == rotations_shape[-1]: random_rotations = rotations elif rotations.size(-1) < rotations_shape[-1]: complement_shape = ( batch_size if self._random_rotations_per_head else 1, vecs.shape[-1], self.n_hashes if self._rehash_each_round else 1, rot_size // 2 - rotations.size(-1)) tmp = torch.randn(complement_shape, dtype=vecs.dtype, device=device).expand(batch_size, -1, -1, -1) random_rotations = torch.cat([rotations, tmp], dim=-1) else: random_rotations = rotations[:, :, :, torch.randperm(rotations.size(-1))[:rotations_shape[-1]]] dropped_vecs = self.dropout_for_hash(vecs) rotated_vecs = torch.einsum('btf,bfhi->bhti', dropped_vecs, random_rotations) if self._rehash_each_round: rotated_vecs = torch.cat([rotated_vecs, -rotated_vecs], dim=-1) buckets = torch.argmax(rotated_vecs, dim=-1) # buckets is now (self.n_hashes, seqlen). Next we add offsets so that # bucket numbers from different hashing rounds don't overlap. offsets = torch.arange(self.n_hashes, device=device) offsets = torch.reshape(offsets * n_buckets, (1, -1, 1)) buckets = torch.reshape(buckets + offsets, (batch_size, -1,)) else: rotated_vecs = torch.cat([rotated_vecs, -rotated_vecs], dim=-1) # In this configuration, we map each item to the top self.n_hashes buckets rotated_vecs = torch.squeeze(rotated_vecs, 0) bucket_range = torch.arange(rotated_vecs.shape[-1], device=device) bucket_range = torch.reshape(bucket_range, (1, -1)) bucket_range = bucket_range.expand_as(rotated_vecs.shape) _, buckets = sort_key_val(rotated_vecs, bucket_range, dim=-1) buckets = buckets[:, -self.n_hashes:] h, *_ = buckets.shape buckets = torch.reshape(buckets.permute((*_, h)), (-1,)) return buckets def forward(self, qk, v, query_len=None, input_mask=None, input_attn_mask=None, rotations=None, triplet_examples=False, **kwargs): batch_size, seqlen, dim, device = *qk.shape, qk.device query_len = default(query_len, seqlen) is_reverse = kwargs.pop('_reverse', False) depth = kwargs.pop('_depth', None) assert seqlen % ( self.bucket_size * 2) == 0, f'Sequence length ({seqlen}) needs to be divisible by target bucket size x 2 - {self.bucket_size * 2}' n_buckets = seqlen // self.bucket_size # buckets = self.hash_vectors(n_buckets, qk, key_namespace=depth, fetch=is_reverse, set_cache=self.training) # add customized rotations # buckets = self.hash_vectors(n_buckets, qk, key_namespace=depth, fetch=is_reverse, set_cache=self.training, rotations=rotations) buckets = self.hash_vectors(n_buckets, qk, rotations=rotations) max_idxs = buckets.reshape(batch_size, -1, seqlen) # We use the same vector as both a query and a key. assert int(buckets.shape[1]) == self.n_hashes * seqlen total_hashes = self.n_hashes ticker = torch.arange(total_hashes * seqlen, device=device).unsqueeze(0).expand_as(buckets) buckets_and_t = seqlen * buckets + (ticker % seqlen) buckets_and_t = buckets_and_t.detach() # Hash-based sort ("s" at the start of variable names means "sorted") sbuckets_and_t, sticker, indices = sort_key_val(buckets_and_t, ticker, dim=-1) _, undo_sort = sticker.sort(dim=-1) del ticker sbuckets_and_t = sbuckets_and_t.detach() sticker = sticker.detach() undo_sort = undo_sort.detach() st = (sticker % seqlen) sqk = batched_index_select(qk, st) sv = batched_index_select(v, st) # Split off a "bin" axis so that attention only occurs within chunks. chunk_size = total_hashes * n_buckets bq_t = bkv_t = torch.reshape(st, (batch_size, chunk_size, -1)) bqk = torch.reshape(sqk, (batch_size, chunk_size, -1, dim)) bv = torch.reshape(sv, (batch_size, chunk_size, -1, dim)) # Hashing operates on unit-length vectors. Unnormalized query vectors are # fine because they effectively provide a learnable temperature for the # attention softmax, but normalizing keys is needed so that similarity for # the purposes of attention correctly corresponds to hash locality. bq = bqk bk = F.normalize(bqk, p=2, dim=-1).type_as(bq) # Allow each chunk to attend within itself, and also one chunk back. Chunk # boundaries might occur in the middle of a sequence of items from the # same bucket, so this increases the chances of attending to relevant items. def look_one_back(x): x_extra = torch.cat([x[:, -1:, ...], x[:, :-1, ...]], dim=1) return torch.cat([x, x_extra], dim=2) bk = look_one_back(bk) bv = look_one_back(bv) bkv_t = look_one_back(bkv_t) # Dot-product attention. dots = torch.einsum('bhie,bhje->bhij', bq, bk) * (dim ** -0.5) if triplet_examples: min_samples = dots.argmin(dim=-1).detach() masked_value = max_neg_value(dots) # Mask for post qk attention logits of the input sequence if input_attn_mask is not None: input_attn_mask = F.pad(input_attn_mask, (0, seqlen - input_attn_mask.shape[-1], 0, seqlen - input_attn_mask.shape[-2]), value=True) dot_attn_indices = ((bq_t * seqlen)[:, :, :, None] + bkv_t[:, :, None, :]) input_attn_mask = input_attn_mask.reshape(batch_size, -1) dot_attn_indices = dot_attn_indices.reshape(batch_size, -1) mask = input_attn_mask.gather(1, dot_attn_indices).reshape_as(dots) dots.masked_fill_(~mask, masked_value) del mask # Input mask for padding in variable lengthed sequences if input_mask is not None: input_mask = F.pad(input_mask, (0, seqlen - input_mask.shape[1]), value=True) mq = input_mask.gather(1, st).reshape((batch_size, chunk_size, -1)) mkv = look_one_back(mq) mask = mq[:, :, :, None] * mkv[:, :, None, :] dots.masked_fill_(~mask, masked_value) del mask # Causal masking if self.causal: mask = bq_t[:, :, :, None] < bkv_t[:, :, None, :] if seqlen > query_len: mask = mask & (bkv_t[:, :, None, :] < query_len) dots.masked_fill_(mask, masked_value) del mask # Mask out attention to self except when no other targets are available. self_mask = bq_t[:, :, :, None] == bkv_t[:, :, None, :] dots.masked_fill_(self_mask, TOKEN_SELF_ATTN_VALUE) del self_mask # Mask out attention to other hash buckets. if not self._attend_across_buckets: bq_buckets = bkv_buckets = torch.reshape(sbuckets_and_t // seqlen, (batch_size, chunk_size, -1)) bkv_buckets = look_one_back(bkv_buckets) bucket_mask = bq_buckets[:, :, :, None] != bkv_buckets[:, :, None, :] dots.masked_fill_(bucket_mask, masked_value) del bucket_mask # Don't double-count query-key pairs across multiple rounds of hashing. # There are two possible strategies here. (1) The default is to count how # many times a query-key pair is repeated, and to lower its log-prob # correspondingly at each repetition. (2) When hard_k is set, the code # instead masks all but the first occurence of each query-key pair. if not self._allow_duplicate_attention: locs1 = undo_sort // bq_t.shape[-1] locs2 = (locs1 + 1) % chunk_size if not self._attend_across_buckets: locs1 = buckets * chunk_size + locs1 locs2 = buckets * chunk_size + locs2 locs = torch.cat([ torch.reshape(locs1, (batch_size, total_hashes, seqlen)), torch.reshape(locs2, (batch_size, total_hashes, seqlen)), ], 1).permute((0, 2, 1)) slocs = batched_index_select(locs, st) b_locs = torch.reshape(slocs, (batch_size, chunk_size, -1, 2 * total_hashes)) b_locs1 = b_locs[:, :, :, None, :total_hashes] bq_locs = b_locs1.expand(b_locs.shape[:3] + (2, total_hashes)) bq_locs = torch.reshape(bq_locs, b_locs.shape) bkv_locs = look_one_back(b_locs) dup_counts = (bq_locs[:, :, :, None, :] == bkv_locs[:, :, None, :, :]) # for memory considerations, chunk summation of last dimension for counting duplicates dup_counts = chunked_sum(dup_counts, chunks=(total_hashes * batch_size)) dup_counts = dup_counts.detach() assert dup_counts.shape == dots.shape dots = dots - torch.log(dup_counts + 1e-9) del dup_counts with torch.no_grad(): if self.store_stats: computed_mean = dots.detach() mean = torch.mean(computed_mean[computed_mean > TOKEN_SELF_ATTN_VALUE + 1]) self.mean_dp = mean.item() self.stat_count += 1 # Softmax. dots_logsumexp = torch.logsumexp(dots, dim=-1, keepdim=True) dots = torch.exp(dots - dots_logsumexp).type_as(dots) dropped_dots = self.dropout(dots) bo = torch.einsum('buij,buje->buie', dropped_dots, bv) so = torch.reshape(bo, (batch_size, -1, dim)) slogits = torch.reshape(dots_logsumexp, (batch_size, -1,)) # compute pos/neg examples if triplet_examples: with torch.no_grad(): max_samples = dots.argmax(dim=-1) max_ind = torch.gather(bkv_t, -1, max_samples).view_as(st) min_ind = torch.gather(bkv_t, -1, min_samples).view_as(st) pos_vectors = batched_index_select(qk, max_ind).detach() neg_vectors = batched_index_select(qk, min_ind).detach() else: pos_vectors = None neg_vectors = None # unsort logits o = batched_index_select(so, undo_sort) logits = slogits.gather(1, undo_sort) o = torch.reshape(o, (batch_size, total_hashes, seqlen, dim)) logits = torch.reshape(logits, (batch_size, total_hashes, seqlen, 1)) if query_len != seqlen: query_slice = (slice(None), slice(None), slice(0, query_len)) o, logits = o[query_slice], logits[query_slice] probs = torch.exp(logits - torch.logsumexp(logits, dim=1, keepdim=True)) out = torch.sum(o * probs, dim=1) attn = torch.empty(0, device=device) # return unsorted attention weights if self._return_attn: attn_unsort = ((bq_t * seqlen)[:, :, :, None] + bkv_t[:, :, None, :]) attn_unsort = attn_unsort.view(batch_size * total_hashes, -1).long() unsorted_dots = torch.zeros(batch_size * total_hashes, seqlen * seqlen, device=device) unsorted_dots.scatter_add_(1, attn_unsort, dots.view_as(attn_unsort)) del attn_unsort unsorted_dots = unsorted_dots.reshape(batch_size, total_hashes, seqlen, seqlen) attn = torch.sum(unsorted_dots[:, :, 0:query_len, :] * probs, dim=1) # return output, attention matrix, and bucket distribution return out, attn, buckets, sqk.detach(), pos_vectors, neg_vectors # customized training for hash functions class TripletLSHAttention(LSHAttention): def __init__(self, alpha=1.0, # triplet loss margin dim=512, # embedding dimension seq_len=1024, heads=8, # attention heads dropout=0., bucket_size=64, n_hashes=8, causal=False, allow_duplicate_attention=True, attend_across_buckets=True, rehash_each_round=True, drop_for_hash_rate=0.0, random_rotations_per_head=False, return_attn=False, triplet_chunks=None, store_stats=False ): super().__init__(dropout=dropout, bucket_size=bucket_size, n_hashes=n_hashes, causal=causal, allow_duplicate_attention=allow_duplicate_attention, attend_across_buckets=attend_across_buckets, rehash_each_round=rehash_each_round, drop_for_hash_rate=drop_for_hash_rate, random_rotations_per_head=random_rotations_per_head, return_attn=return_attn, store_stats=store_stats) self.alpha = alpha self.seq_len = seq_len self.heads = heads n_buckets = self.seq_len // bucket_size # buckets_dim = n_buckets // 2 buckets_dim = n_buckets if self._rehash_each_round: buckets_dim *= n_hashes self.rotations = nn.Linear(dim // self.heads, buckets_dim, bias=False) # number of chunks to split up computation of pos/neg examples for triplet loss self.triplet_chunks = default(triplet_chunks, dim) def reset_rotations(self): self.rotations.reset_parameters() def extract_rotations(self, batch_size): n_buckets = self.seq_len // self.bucket_size rotations = self.rotations.weight.t().detach() # dim x (buckets * n_hashes / 2) # rotations = rotations[:, torch.randperm(rotations.size(-1))[:rotations.size(-1) // 2]] rotations = torch.reshape(rotations, (-1, self.n_hashes, n_buckets)) rotations = rotations.unsqueeze(0).expand(batch_size, -1, -1, -1) return rotations def triplet_forward(self, x, # input p, # positive example n, # negative example ): ''' Given inputs, positive and negative examples, compute the triplet loss given by cosine similarity ''' x = x.detach() p = p.detach() n = n.detach() emb_x = self.rotations(x) emb_p = self.rotations(p) emb_n = self.rotations(n) # cosine similarity sim_xp = F.cosine_similarity(emb_x, emb_p, dim=-1, eps=1e-6) sim_xn = F.cosine_similarity(emb_x, emb_n, dim=-1, eps=1e-6) # distance in radians # dis_xp = 1 - torch.acos(sim_xp)/pi # dis_xn = 1 - torch.acos(sim_xn)/pi dis_xp = 1 - sim_xp dis_xn = 1 - sim_xn triplet_loss = dis_xp - dis_xn + self.alpha triplet_loss = torch.mean(torch.max(triplet_loss, torch.zeros(triplet_loss.size()).to(x.device))) if torch.isnan(triplet_loss): print("nan!") return triplet_loss def forward(self, qk, v, query_len=None, input_mask=None, printgrad=False, triplet_examples=False, **kwargs): batch_size, seqlen, dim = qk.shape n_buckets = self.seq_len // self.bucket_size rotations = self.extract_rotations(batch_size) # self.rotations.reset_parameters() out, attn, buckets, emb_x, pos, neg = super().forward(qk, v, query_len=query_len, input_mask=input_mask, rotations=rotations, printgrad=printgrad, triplet_examples=triplet_examples) return out, attn, buckets, emb_x, pos, neg # simple full attention class FullQKAttention(nn.Module): def __init__(self, causal=False, dropout=0.): super().__init__() self.causal = causal self.dropout = nn.Dropout(dropout) self.attn = None def forward(self, qk, v, query_len=None, input_mask=None, input_attn_mask=None, **kwargs): b, seq_len, dim = qk.shape query_len = default(query_len, seq_len) t = query_len q = qk[:, 0:query_len] qk = F.normalize(qk, 2, dim=-1).type_as(q) dot = torch.einsum('bie,bje->bij', q, qk) * (dim ** -0.5) # qk attention requires tokens not attend to self i = torch.arange(t) dot[:, i, i] = TOKEN_SELF_ATTN_VALUE masked_value = max_neg_value(dot) # Input mask for padding in variable lengthed sequences if input_mask is not None: mask = input_mask[:, 0:query_len, None] * input_mask[:, None, :] mask = F.pad(mask, (0, seq_len - mask.shape[-1]), value=True) dot.masked_fill_(~mask, masked_value) # Mask for post qk attention logits of the input sequence if input_attn_mask is not None: input_attn_mask = F.pad(input_attn_mask, (0, seq_len - input_attn_mask.shape[-1]), value=True) dot.masked_fill_(~input_attn_mask, masked_value) if self.causal: i, j = torch.triu_indices(t, t, 1) dot[:, i, j] = masked_value dot = dot.softmax(dim=-1) self.attn = dot.detach() dot = self.dropout(dot) out = torch.einsum('bij,bje->bie', dot, v) return out, dot, torch.empty(0), None, None, None class LSHSelfAttention(nn.Module): def __init__(self, dim, heads=8, bucket_size=64, n_hashes=8, causal=False, dim_head=None, attn_chunks=1, random_rotations_per_head=False, attend_across_buckets=True, allow_duplicate_attention=True, num_mem_kv=0, one_value_head=False, use_full_attn=False, full_attn_thres=None, return_attn=False, post_attn_dropout=0., dropout=0., n_local_attn_heads=0, attn_type='lsh', max_seq_len=None, alpha=1.0, triplet_chunks=None, scheduler_hashes=10, thresh=0.01, **kwargs): super().__init__() assert dim_head or (dim % heads) == 0, 'dimensions must be divisible by number of heads' assert n_local_attn_heads < heads, 'local attention heads must be less than number of heads' dim_head = default(dim_head, dim // heads) dim_heads = dim_head * heads self.dim = dim self.heads = heads self.dim_head = dim_head self.attn_chunks = default(attn_chunks, 1) self.v_head_repeats = (heads if one_value_head else 1) v_dim = dim_heads // self.v_head_repeats self.toqk = nn.Linear(dim, dim_heads, bias=False) self.tov = nn.Linear(dim, v_dim, bias=False) self.to_out = nn.Linear(dim_heads, dim) self.bucket_size = bucket_size self.attn_type = attn_type if self.attn_type == 'triplet': self.lsh_attn = TripletLSHAttention(alpha=alpha, dim=self.dim, seq_len=max_seq_len, heads=self.heads, bucket_size=bucket_size, n_hashes=n_hashes, causal=causal, random_rotations_per_head=random_rotations_per_head, attend_across_buckets=attend_across_buckets, allow_duplicate_attention=allow_duplicate_attention, return_attn=return_attn, triplet_chunks=triplet_chunks, **kwargs) # init scheduler self.scheduler = Scheduler(self.toqk.weight, dim, scheduler_hashes, 1, thresh) else: self.lsh_attn = LSHAttention(bucket_size=bucket_size, n_hashes=n_hashes, causal=causal, random_rotations_per_head=random_rotations_per_head, attend_across_buckets=attend_across_buckets, allow_duplicate_attention=allow_duplicate_attention, return_attn=return_attn, dropout=dropout, **kwargs) self.full_attn = FullQKAttention(causal=causal, dropout=dropout) self.post_attn_dropout = nn.Dropout(post_attn_dropout) self.use_full_attn = use_full_attn self.full_attn_thres = default(full_attn_thres, bucket_size) self.num_mem_kv = num_mem_kv self.mem_kv = nn.Parameter(torch.randn(1, num_mem_kv, dim, requires_grad=True)) if num_mem_kv > 0 else None self.n_local_attn_heads = n_local_attn_heads self.local_attn = LocalAttention(window_size=bucket_size * 2, causal=causal, dropout=dropout, shared_qk=True, look_forward=(1 if not causal else 0)) self.callback = None self.attn = None self.triplet_loss = 0.0 self._reset_parameters() def _reset_parameters(self): # if self._qkv_same_embed_dim: xavier_uniform_(self.toqk.weight) xavier_uniform_(self.tov.weight) xavier_uniform_(self.to_out.weight) def forward(self, x, keys=None, input_mask=None, input_attn_mask=None, context_mask=None, calc_triplet=False, **kwargs): device, dtype = x.device, x.dtype b, t, e, h, dh, m, l_h = *x.shape, self.heads, self.dim_head, self.num_mem_kv, self.n_local_attn_heads mem_kv = default(self.mem_kv, torch.empty(b, 0, e, dtype=dtype, device=device)) mem = mem_kv.expand(-1, m, -1) keys = default(keys, torch.empty(b, 0, e, dtype=dtype, device=device)) c = keys.shape[1] kv_len = t + m + c use_full_attn = self.use_full_attn or kv_len <= self.full_attn_thres x = torch.cat((x, mem, keys), dim=1) qk = self.toqk(x) v = self.tov(x) v = v.repeat(1, 1, self.v_head_repeats) def merge_heads(v): return v.view(b, kv_len, h, -1).transpose(1, 2) def split_heads(v): return v.view(b, h, t, -1).transpose(1, 2).contiguous() merge_batch_and_heads = partial(merge_dims, 0, 1) qk, v = map(merge_heads, (qk, v)) has_local = l_h > 0 lsh_h = h - l_h split_index_fn = partial(split_at_index, 1, l_h) (lqk, qk), (lv, v) = map(split_index_fn, (qk, v)) lqk, qk, lv, v = map(merge_batch_and_heads, (lqk, qk, lv, v)) masks = {} if input_mask is not None or context_mask is not None: default_mask = torch.tensor([True], device=device) i_mask = default(input_mask, default_mask.expand(b, t)) m_mask = default_mask.expand(b, m) c_mask = default(context_mask, default_mask.expand(b, c)) mask = torch.cat((i_mask, m_mask, c_mask), dim=1) mask = merge_batch_and_heads(expand_dim(1, lsh_h, mask)) masks['input_mask'] = mask if input_attn_mask is not None: input_attn_mask = merge_batch_and_heads(expand_dim(1, lsh_h, input_attn_mask)) masks['input_attn_mask'] = input_attn_mask attn_fn = self.lsh_attn if not use_full_attn else self.full_attn # update rotations if calc_triplet: if not self.scheduler.detect_change(self.toqk.weight): calc_triplet = False return_triplet_examples = (self.attn_type in ['triplet', 'simhash']) and calc_triplet and not use_full_attn partial_attn_fn = partial(attn_fn, query_len=t, input_mask=input_mask, triplet_examples=return_triplet_examples) attn_fn_in_chunks = process_inputs_chunk(partial_attn_fn, chunks=self.attn_chunks) out, attn, buckets, emb_x, pos, neg = attn_fn_in_chunks(qk, v, **masks) if self.callback is not None: self.callback(attn.reshape(b, lsh_h, t, -1), buckets.reshape(b, lsh_h, -1)) if return_triplet_examples: def chunked_loss(fn, *args, chunks=1, dim=0): chunked_inputs = list(map(lambda x: x.chunk(chunks, dim=dim), args)) outputs = [fn(*inputs) for inputs in zip(*chunked_inputs)] return sum(outputs) triplet_loss = chunked_loss(self.lsh_attn.triplet_forward, emb_x, pos, neg, chunks=self.attn_chunks, dim=1) if self.triplet_loss is None: self.triplet_loss = triplet_loss else: self.triplet_loss += triplet_loss if has_local: lqk, lv = lqk[:, :t], lv[:, :t] local_out = self.local_attn(lqk, lqk, lv, input_mask=input_mask) local_out = local_out.reshape(b, l_h, t, -1) out = out.reshape(b, lsh_h, t, -1) out = torch.cat((local_out, out), dim=1) out = split_heads(out).view(b, t, -1) self.attn = out.detach() out = self.to_out(out) return self.post_attn_dropout(out) # feed forward class GELU_(nn.Module): def forward(self, x): return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) GELU = nn.GELU if hasattr(nn, 'GELU') else GELU_ class FeedForward(nn.Module): def __init__(self, dim, mult=4, dropout=0., activation=None, glu=False): super().__init__() activation = default(activation, GELU) self.glu = glu self.w1 = nn.Linear(dim, dim * mult * (2 if glu else 1)) self.act = activation() self.dropout = nn.Dropout(dropout) self.w2 = nn.Linear(dim * mult, dim) def forward(self, x, **kwargs): if not self.glu: x = self.w1(x) x = self.act(x) else: x, v = self.w1(x).chunk(2, dim=-1) x = self.act(x) * v x = self.dropout(x) x = self.w2(x) return x # positional embeddings class AbsolutePositionalEmbedding(nn.Module): def __init__(self, dim, max_seq_len): super().__init__() self.emb = nn.Embedding(max_seq_len, dim) def forward(self, x): t = torch.arange(x.shape[1], device=x.device) return self.emb(t) class FixedPositionalEmbedding(nn.Module): def __init__(self, dim): super().__init__() inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim)) self.register_buffer('inv_freq', inv_freq) def forward(self, x): t = torch.arange(x.shape[1], device=x.device).type_as(self.inv_freq) sinusoid_inp = torch.einsum("i,j->ij", t, self.inv_freq) emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1) return emb[None, :, :] class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): x = x + self.pe[:x.size(0), :] return self.dropout(x) # reformer lm class Reformer_tune(nn.Module): def __init__(self, dim, depth, max_seq_len, heads=8, dim_head=None, bucket_size_list=[], n_hashes_list=[], ff_chunks=100, attn_chunks=None, causal=False, weight_tie=False, lsh_dropout=0., ff_dropout=0., ff_activation=None, ff_mult=4, ff_glu=False, post_attn_dropout=0., layer_dropout=0., lsh_attend_across_buckets=True, lsh_allow_duplicate_attention=True, random_rotations_per_head=False, twin_attention=False, use_scale_norm=False, use_rezero=False, use_full_attn=False, full_attn_thres=0, reverse_thres=0, num_mem_kv=0, one_value_head=False, n_local_attn_heads=0, pkm_layers=tuple(), pkm_num_keys=128, attn_type_list=[], store_stats=False, scheduler_hashes=10, thresh=0.01): super().__init__() self.dim = dim self.depth = depth assert len(bucket_size_list) == depth assert len(n_hashes_list) == depth assert len(attn_type_list) == depth self.bucket_size_list = bucket_size_list self.num_mem_kv = num_mem_kv self.twin_attention = twin_attention self.full_attn_thres = full_attn_thres get_ff = lambda: Chunk(ff_chunks, FeedForward(dim, dropout=ff_dropout, activation=ff_activation, mult=ff_mult, glu=ff_glu), along_dim=-2) get_pkm = lambda: PKM(dim, num_keys=pkm_num_keys) if weight_tie: get_attn = lambda: LSHSelfAttention(dim, heads, bucket_size_list[0], n_hashes_list[0], causal=causal, dim_head=dim_head, dropout=lsh_dropout, post_attn_dropout=post_attn_dropout, attn_chunks=attn_chunks, allow_duplicate_attention=lsh_allow_duplicate_attention, attend_across_buckets=lsh_attend_across_buckets, random_rotations_per_head=random_rotations_per_head, num_mem_kv=num_mem_kv, use_full_attn=use_full_attn, full_attn_thres=full_attn_thres, one_value_head=one_value_head, n_local_attn_heads=n_local_attn_heads, max_seq_len=max_seq_len, attn_type=attn_type_list[0], store_stats=store_stats, scheduler_hashes=scheduler_hashes, thresh=thresh) get_attn, get_ff, get_pkm = map(cache_fn, (get_attn, get_ff, get_pkm)) blocks = [] norm_type = ScaleNorm if use_scale_norm else nn.LayerNorm residual_fn_wrapper = ReZero if use_rezero else partial(PreNorm, norm_type, dim) for ind in range(depth): layer_num = ind + 1 use_pkm = layer_num in cast_tuple(pkm_layers) parallel_net = None attn = LSHSelfAttention(dim, heads, bucket_size_list[ind], n_hashes_list[ind], causal=causal, dim_head=dim_head, dropout=lsh_dropout, post_attn_dropout=post_attn_dropout, attn_chunks=attn_chunks, allow_duplicate_attention=lsh_allow_duplicate_attention, attend_across_buckets=lsh_attend_across_buckets, random_rotations_per_head=random_rotations_per_head, num_mem_kv=num_mem_kv, use_full_attn=use_full_attn, full_attn_thres=full_attn_thres, one_value_head=one_value_head, n_local_attn_heads=n_local_attn_heads, max_seq_len=max_seq_len, attn_type=attn_type_list[ind], store_stats=store_stats , scheduler_hashes=scheduler_hashes, thresh=thresh) if use_pkm: parallel_net = get_pkm() elif twin_attention: parallel_net = get_attn() else: parallel_net = get_ff() f = residual_fn_wrapper(attn) g = residual_fn_wrapper(parallel_net) blocks.append(nn.ModuleList([f, g])) self.layers = ReversibleSequence(nn.ModuleList(blocks), layer_dropout=layer_dropout, reverse_thres=reverse_thres, send_signal=True) self.layer_modules = list(chain(*[[m[0], m[1]] for m in blocks])) def forward(self, x, **kwargs): x = torch.cat([x, x], dim=-1) arg_route = (True, self.twin_attention) x = self.layers(x, arg_route=arg_route, **kwargs) return torch.stack(x.chunk(2, dim=-1)).mean(dim=0) # reformer lm class Reformer(nn.Module): def __init__(self, dim, depth, max_seq_len, heads=8, dim_head=None, bucket_size=64, n_hashes=8, ff_chunks=100, attn_chunks=None, causal=False, weight_tie=False, lsh_dropout=0., ff_dropout=0., ff_activation=None, ff_mult=4, ff_glu=False, post_attn_dropout=0., layer_dropout=0., lsh_attend_across_buckets=True, lsh_allow_duplicate_attention=True, random_rotations_per_head=False, twin_attention=False, use_scale_norm=False, use_rezero=False, use_full_attn=False, full_attn_thres=0, reverse_thres=0, num_mem_kv=0, one_value_head=False, n_local_attn_heads=0, pkm_layers=tuple(), pkm_num_keys=128, attn_type='lsh', store_stats=False): super().__init__() self.dim = dim self.depth = depth self.bucket_size = bucket_size self.num_mem_kv = num_mem_kv self.twin_attention = twin_attention self.full_attn_thres = full_attn_thres get_attn = lambda: LSHSelfAttention(dim, heads, bucket_size, n_hashes, causal=causal, dim_head=dim_head, dropout=lsh_dropout, post_attn_dropout=post_attn_dropout, attn_chunks=attn_chunks, allow_duplicate_attention=lsh_allow_duplicate_attention, attend_across_buckets=lsh_attend_across_buckets, random_rotations_per_head=random_rotations_per_head, num_mem_kv=num_mem_kv, use_full_attn=use_full_attn, full_attn_thres=full_attn_thres, one_value_head=one_value_head, n_local_attn_heads=n_local_attn_heads, max_seq_len=max_seq_len, attn_type=attn_type, store_stats=store_stats) get_ff = lambda: Chunk(ff_chunks, FeedForward(dim, dropout=ff_dropout, activation=ff_activation, mult=ff_mult, glu=ff_glu), along_dim=-2) get_pkm = lambda: PKM(dim, num_keys=pkm_num_keys) if weight_tie: get_attn, get_ff, get_pkm = map(cache_fn, (get_attn, get_ff, get_pkm)) blocks = [] norm_type = ScaleNorm if use_scale_norm else nn.LayerNorm residual_fn_wrapper = ReZero if use_rezero else partial(PreNorm, norm_type, dim) for ind in range(depth): layer_num = ind + 1 use_pkm = layer_num in cast_tuple(pkm_layers) parallel_net = None attn = get_attn() if use_pkm: parallel_net = get_pkm() elif twin_attention: parallel_net = get_attn() else: parallel_net = get_ff() f = residual_fn_wrapper(attn) g = residual_fn_wrapper(parallel_net) blocks.append(nn.ModuleList([f, g])) self.layers = ReversibleSequence(nn.ModuleList(blocks), layer_dropout=layer_dropout, reverse_thres=reverse_thres, send_signal=True) self.layer_modules = list(chain(*[[m[0], m[1]] for m in blocks])) def forward(self, x, **kwargs): x = torch.cat([x, x], dim=-1) arg_route = (True, self.twin_attention) x = self.layers(x, arg_route=arg_route, **kwargs) return torch.stack(x.chunk(2, dim=-1)).mean(dim=0) class ReformerLM_tune(nn.Module): def __init__(self, num_tokens, dim, depth, max_seq_len, heads=8, dim_head=None, bucket_size_list=[], n_hashes_list=[], ff_chunks=100, attn_chunks=1, causal=False, weight_tie=False, lsh_dropout=0., ff_dropout=0., ff_mult=4, ff_activation=None, ff_glu=False, post_attn_dropout=0., layer_dropout=0., random_rotations_per_head=False, twin_attention=False, use_scale_norm=False, use_rezero=False, use_full_attn=False, full_attn_thres=0, reverse_thres=0, num_mem_kv=0, one_value_head=False, emb_dim=None, return_embeddings=False, weight_tie_embedding=False, fixed_position_emb=False, absolute_position_emb=False, axial_position_shape=None, n_local_attn_heads=0, pkm_layers=tuple(), pkm_num_keys=128, attn_type_list=[], store_stats=False, scheduler_hashes=10, thresh=0.01): super().__init__() emb_dim = default(emb_dim, dim) self.max_seq_len = max_seq_len self.token_emb = nn.Embedding(num_tokens, emb_dim) self.to_model_dim = Identity() if emb_dim == dim else nn.Linear(emb_dim, dim) if absolute_position_emb: # self.pos_emb = PositionalEncoding(emb_dim, layer_dropout, max_seq_len) self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) elif fixed_position_emb: self.pos_emb = FixedPositionalEmbedding(emb_dim) else: axial_position_shape = default(axial_position_shape, (max_seq_len // bucket_size_list[0], bucket_size_list[0])) self.pos_emb = AxialPositionalEmbedding(emb_dim, axial_position_shape) self.reformer = Reformer_tune(dim, depth, max_seq_len, heads=heads, dim_head=dim_head, bucket_size_list=bucket_size_list, n_hashes_list=n_hashes_list, ff_chunks=ff_chunks, attn_chunks=attn_chunks, causal=causal, weight_tie=weight_tie, lsh_dropout=lsh_dropout, ff_mult=ff_mult, ff_activation=ff_activation, ff_glu=ff_glu, ff_dropout=ff_dropout, post_attn_dropout=0., layer_dropout=layer_dropout, random_rotations_per_head=random_rotations_per_head, twin_attention=twin_attention, use_scale_norm=use_scale_norm, use_rezero=use_rezero, use_full_attn=use_full_attn, full_attn_thres=full_attn_thres, reverse_thres=reverse_thres, num_mem_kv=num_mem_kv, one_value_head=one_value_head, n_local_attn_heads=n_local_attn_heads, pkm_layers=pkm_layers, pkm_num_keys=pkm_num_keys, attn_type_list=attn_type_list, store_stats=store_stats, scheduler_hashes=scheduler_hashes, thresh=thresh) if return_embeddings: self.out = Identity() return self.out = nn.Sequential( nn.Linear(dim, emb_dim) if emb_dim != dim else Identity(), nn.Linear(emb_dim, num_tokens) if not weight_tie_embedding else MatrixMultiply(self.token_emb.weight, transpose=True, normalize=True) ) self.init_weights() def init_weights(self): initrange = 0.1 self.token_emb.weight.data.uniform_(-initrange, initrange) self.out[1].bias.data.zero_() self.out[1].weight.data.uniform_(-initrange, initrange) def forward(self, x, **kwargs): x = self.token_emb(x) x = x + self.pos_emb(x).type_as(x) # x = self.pos_emb(x) x = self.to_model_dim(x) x = self.reformer(x, **kwargs) return self.out(x) def clear_non_rotation_gradients(self): # clear gradients from triplet loss for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn g = self.reformer.layer_modules[(2 * i) + 1].fn # only zero out toqk, tov, and to_out # leave gradients of rotations f.toqk.zero_grad() f.tov.zero_grad() f.to_out.zero_grad() g.zero_grad() def get_triplet_loss(self): total = 0 for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn if f.triplet_loss is not None: total += f.triplet_loss return total def update_simhash(self): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn attn_fn = f.lsh_attn if hasattr(attn_fn, 'simhash'): attn_fn.update_simhash() def reset_triplet(self): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn attn_fn = f.lsh_attn if hasattr(attn_fn, 'rotations'): attn_fn.reset_rotations() def get_statistics(self, batch_size): means = [] for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn attn_fn = f.lsh_attn means.append(attn_fn.mean_dp / attn_fn.stat_count) attn_fn.mean_dp = 0.0 attn_fn.stat_count = 0 return means def set_alpha(self, alpha): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn attn_fn = f.lsh_attn if hasattr(attn_fn, 'alpha'): attn_fn.alpha = alpha def clear_triplet_loss(self): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn if f.triplet_loss is not None: f.triplet_loss = None def save_triplet_params(self, prefix): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn weight = f.lsh_attn.rotations.weight torch.save(weight, prefix + '%d.pt' % i) class ReformerLM(nn.Module): def __init__(self, num_tokens, dim, depth, max_seq_len, heads=8, dim_head=None, bucket_size=64, n_hashes=4, ff_chunks=100, attn_chunks=1, causal=False, weight_tie=False, lsh_dropout=0., ff_dropout=0., ff_mult=4, ff_activation=None, ff_glu=False, post_attn_dropout=0., layer_dropout=0., random_rotations_per_head=False, twin_attention=False, use_scale_norm=False, use_rezero=False, use_full_attn=False, full_attn_thres=0, reverse_thres=0, num_mem_kv=0, one_value_head=False, emb_dim=None, return_embeddings=False, weight_tie_embedding=False, fixed_position_emb=False, absolute_position_emb=False, axial_position_shape=None, n_local_attn_heads=0, pkm_layers=tuple(), pkm_num_keys=128, attn_type='lsh', store_stats=False): super().__init__() emb_dim = default(emb_dim, dim) self.max_seq_len = max_seq_len self.token_emb = nn.Embedding(num_tokens, emb_dim) self.to_model_dim = Identity() if emb_dim == dim else nn.Linear(emb_dim, dim) if absolute_position_emb: # self.pos_emb = PositionalEncoding(emb_dim, layer_dropout, max_seq_len) self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) elif fixed_position_emb: self.pos_emb = FixedPositionalEmbedding(emb_dim) else: axial_position_shape = default(axial_position_shape, (max_seq_len // bucket_size, bucket_size)) self.pos_emb = AxialPositionalEmbedding(emb_dim, axial_position_shape) self.reformer = Reformer(dim, depth, max_seq_len, heads=heads, dim_head=dim_head, bucket_size=bucket_size, n_hashes=n_hashes, ff_chunks=ff_chunks, attn_chunks=attn_chunks, causal=causal, weight_tie=weight_tie, lsh_dropout=lsh_dropout, ff_mult=ff_mult, ff_activation=ff_activation, ff_glu=ff_glu, ff_dropout=ff_dropout, post_attn_dropout=0., layer_dropout=layer_dropout, random_rotations_per_head=random_rotations_per_head, twin_attention=twin_attention, use_scale_norm=use_scale_norm, use_rezero=use_rezero, use_full_attn=use_full_attn, full_attn_thres=full_attn_thres, reverse_thres=reverse_thres, num_mem_kv=num_mem_kv, one_value_head=one_value_head, n_local_attn_heads=n_local_attn_heads, pkm_layers=pkm_layers, pkm_num_keys=pkm_num_keys, attn_type=attn_type, store_stats=store_stats) if return_embeddings: self.out = Identity() return self.out = nn.Sequential( nn.Linear(dim, emb_dim) if emb_dim != dim else Identity(), nn.Linear(emb_dim, num_tokens) if not weight_tie_embedding else MatrixMultiply(self.token_emb.weight, transpose=True, normalize=True) ) self.init_weights() def init_weights(self): initrange = 0.1 self.token_emb.weight.data.uniform_(-initrange, initrange) self.out[1].bias.data.zero_() self.out[1].weight.data.uniform_(-initrange, initrange) def forward(self, x, **kwargs): x = self.token_emb(x) x = x + self.pos_emb(x).type_as(x) # x = self.pos_emb(x) x = self.to_model_dim(x) x = self.reformer(x, **kwargs) return self.out(x) def clear_non_rotation_gradients(self): # clear gradients from triplet loss for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn g = self.reformer.layer_modules[(2 * i) + 1].fn # only zero out toqk, tov, and to_out # leave gradients of rotations f.toqk.zero_grad() f.tov.zero_grad() f.to_out.zero_grad() g.zero_grad() def get_triplet_loss(self): total = 0 for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn if f.triplet_loss is not None: total += f.triplet_loss return total def update_simhash(self): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn attn_fn = f.lsh_attn if hasattr(attn_fn, 'simhash'): attn_fn.update_simhash() def reset_triplet(self): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn attn_fn = f.lsh_attn if hasattr(attn_fn, 'rotations'): attn_fn.reset_rotations() def set_alpha(self, alpha): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn attn_fn = f.lsh_attn if hasattr(attn_fn, 'alpha'): attn_fn.alpha = alpha def get_statistics(self, batch_size): means = [] for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn attn_fn = f.lsh_attn means.append(attn_fn.mean_dp / attn_fn.stat_count) attn_fn.mean_dp = 0.0 attn_fn.stat_count = 0 return means def clear_triplet_loss(self): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn if f.triplet_loss is not None: f.triplet_loss = None def save_triplet_params(self, prefix): for i in range(len(self.reformer.layer_modules) // 2): f = self.reformer.layer_modules[2 * i].fn weight = f.lsh_attn.rotations.weight torch.save(weight, prefix + '%d.pt' % i)
mongoose-master
mongoose_reformer/reformer_lib/reformer_pytorch.py
mongoose-master
mongoose_slide/__init__.py
import os import sys import numpy as np import torch from torch.utils.data import Dataset, DataLoader class MultiLabelDataset(Dataset): def __init__(self, filename): self.build(filename) def build(self, filename): with open(filename) as f: metadata = f.readline().split() self.N = int(metadata[0]) self.D = int(metadata[1]) self.L = int(metadata[2]) self.max_L = 0 self.max_D = 0 self.data = list() for idx in range(self.N): items = f.readline().split() labels = [int(x) for x in items[0].split(",")] self.max_L = max(self.max_L, len(labels)) ids = list() for fdx in range(1, len(items), 1): fid, fv = items[fdx].split(":") ids.append( int(fid) ) self.max_D = max(self.max_D, len(ids)) self.data.append( [torch.from_numpy(np.asarray(x)) for x in [labels, ids]] ) if idx % 100000 == 0: print(idx) def pad(self, item, width, value): result = torch.zeros(width).long() result.fill_(value) result[:len(item)] = item return result def __len__(self): return self.N def __getitem__(self, idx): labels, data = self.data[idx] return self.pad(labels, self.max_L, -1), self.pad(data, self.max_D, self.D) class ValidDataset(Dataset): def __init__(self, filename): self.build(filename) def build(self, filename): with open(filename) as f: metadata = f.readline().split() self.N = int(int(metadata[0]) * 0.025) #self.N = int(metadata[0]) self.D = int(metadata[1]) self.L = int(metadata[2]) self.max_L = 0 self.max_D = 0 self.data = list() for idx in range(self.N): items = f.readline().split() labels = [int(x) for x in items[0].split(",")] self.max_L = max(self.max_L, len(labels)) ids = list() for fdx in range(1, len(items), 1): fid, fv = items[fdx].split(":") ids.append( int(fid) ) self.max_D = max(self.max_D, len(ids)) self.data.append( [torch.from_numpy(np.asarray(x)) for x in [labels, ids]] ) if idx % 100000 == 0: print(idx) def pad(self, item, width, value): result = torch.zeros(width).long() result.fill_(value) result[:len(item)] = item return result def __len__(self): return self.N def __getitem__(self, idx): labels, data = self.data[idx] return self.pad(labels, self.max_L, -1), self.pad(data, self.max_D, self.D)
mongoose-master
mongoose_slide/slide_lib/lazy_parser.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from mongoose_slide.slide_lib.simHash import SimHash from mongoose_slide.slide_lib.lsh import LSH import time use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") class LSHSoftmax(nn.Module): def __init__(self, N, D, K, L, freq): super(LSHSoftmax, self).__init__() self.D = D self.N = N self.K = K self.L = L # Rebuild Settings self.freq = freq self.count = 0 self.sample_size = 0 self.lsh = LSH(SimHash(D, K, L), K, L) self.params = nn.Linear(D, N) self.init_weights(self.params.weight, self.params.bias) def init_weights(self, weight, bias): initrange = 0.05 weight.data.uniform_(-initrange, initrange) bias.data.fill_(0) def build(self, lsh): # lsh.stats() lsh.clear() lsh.insert_multi(self.params.weight.to(device).data, self.N) def sampled(self, inputs, labels, debug=False): if self.lsh.count % self.freq == 0: print("RESET HASH!!!") self.build(self.lsh) # self.lsh.stats() # Query LSH Database t1 = time.time() N, D = inputs.size() # sid = self.lsh.query_multi(inputs.data, N) sid, hashcode = self.lsh.query_multi(inputs.data, N) # print("sid length",len(sid)) # print("sid",sid) sampled_ip = 0 sampled_cos = 0 if debug: product_list = [] dif_list = [] cos_list = [] for idex, h in enumerate(hashcode): d = inputs[idex] sid_debug = self.lsh.query_fp(h) if len(sid_debug) > 0: retrieved = Variable(torch.from_numpy(np.asarray(list(sid_debug))), requires_grad=False).to( device).long() random_sample_ids = torch.randint(0, self.N, (int(len(sid_debug)),)).to(device) random_weights = F.embedding(random_sample_ids, self.params.weight, sparse=True) random_product = random_weights.matmul(d.t()).t() random_cos = (1 - torch.acos( F.cosine_similarity(d.repeat(1, random_weights.size()[0]).view(random_weights.size()[0], -1), random_weights)) / 3.141592653) weights = F.embedding(retrieved, self.params.weight, sparse=True) product = weights.matmul(d.t()).t() cos = (1 - torch.acos( F.cosine_similarity(d.repeat(1, weights.size()[0]).view(weights.size()[0], -1), weights)) / 3.141592653) cos_list += [torch.mean(cos).item() - torch.mean(random_cos).item()] product_list += [torch.mean(product).item()] dif_list += [torch.mean(product).item() - torch.mean(random_product).item()] # print("mean of product_list", torch.mean( torch.from_numpy( np.asarray( product_list)))) print("mean of sampe - random ", torch.mean(torch.from_numpy(np.asarray(dif_list)))) print("mean of sampe - random cos", torch.mean(torch.from_numpy(np.asarray(cos_list)))) # print("retrieved size: ", len(sid)) sampled_ip = torch.mean(torch.from_numpy(np.asarray(dif_list))) sampled_cos = torch.mean(torch.from_numpy(np.asarray(cos_list))) sid_list, target_matrix = self.lsh.multi_label(labels.data.cpu().numpy(), sid) new_targets = Variable(torch.from_numpy(target_matrix)).to(device) sample_ids = Variable(torch.from_numpy(np.asarray(sid_list, dtype=np.int64)), requires_grad=False).to(device) sample_size = sample_ids.size(0) self.lsh.sample_size += sample_size self.lsh.count += 1 # print(sample_size) # gather sample ids - weights and frequencies t1 = time.time() sample_weights = F.embedding(sample_ids, self.params.weight, sparse=True) sample_bias = self.params.bias[sample_ids] sample_logits = sample_weights.matmul(inputs.t()).t() + sample_bias # self.lsh.stats() return sample_logits, new_targets, sample_size, sampled_ip, sampled_cos def forward(self, inputs, labels, debug=False): if self.training: return self.sampled(inputs, labels, debug) else: logits = torch.matmul(inputs, self.params.weight.t()) + self.params.bias return logits
mongoose-master
mongoose_slide/slide_lib/lsh_softmax.py
import torch from mongoose_slide.slide_lib.cupy_kernel import cupyKernel import numpy as np use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") kernel = ''' extern "C" __global__ void fingerprint(const float* src, const int k, const int L, long* fp) { // product (N x kL bits) -> Column-Major Order // const int L = gridDim.y; // const int k = blockDim.x; int offset = (k * L * blockIdx.x) + (k * blockIdx.y + threadIdx.x); long value = (threadIdx.x >= k || src[offset] <= 0) ? 0 : 1; value <<= threadIdx.x; for (int offset = warpSize/2; offset > 0; offset /= 2) { value |= __shfl_down_sync(0xFFFFFFFF, value, offset, 32); } if(!threadIdx.x) { int fp_offset = L * blockIdx.x + blockIdx.y; fp[fp_offset] = value; } } ''' class SimHash: def __init__(self, d_, k_, L_, weights=None,seed_=8191): self.d = d_ self.k = k_ self.L = L_ self.fp = cupyKernel(kernel, "fingerprint") if weights is None: self.rp = SimHash.generate(d_, k_, L_, seed_) else: self.rp = SimHash.generate_from_weight(weights) # def generate_from_weight(weights): # #print("generated from triplet weight") # return weights.to(device) # def generate(d, k, L, seed): # return torch.randn(d, k*L).to(device) def generate_from_weight(weights): #print("generated from triplet weight") matrix = weights positive = torch.gt(matrix, 0).int() negative = (matrix < 0.0).int() result = (positive - negative).float() #return result.cpu() return result.to(device) def generate(d, k, L, seed): print("random generate hash table weight") rand_gen = np.random.RandomState(seed) matrix = rand_gen.randn(d, k*L) positive = np.greater_equal(matrix, 0.0) negative = np.less(matrix, 0.0) result = positive.astype(np.float32) - negative.astype(np.float32) return torch.from_numpy(result).to(device) # def generate_from_list(srp_list): # matrices = [item.rp for item in srp_list] # return torch.cat(matrices, dim=1) def hash(self, data, transpose=False): N, D = data.size() srp = torch.matmul(data.to(device), self.rp) #print("srp", srp) result = self.fingerprint(srp, N) #print("result", result) if transpose: result = torch.t(result) return result # def hash(self, data, transpose=False): # N, D = data.size() # srp = torch.matmul(data, self.rp) # positive = torch.gt(srp, 0).int() # negative = (srp < 0.0).int() # srp = (positive - negative).float() # result = self.fingerprint(srp, N) # if transpose: # result = torch.t(result) # return result def fingerprint(self, srp, N): result = torch.zeros(N, self.L).long().to(device) self.fp(grid=(N,self.L,1), block=(32,1,1), args=[srp.data_ptr(), self.k, self.L, result.data_ptr()], strm=torch.cuda.current_stream().cuda_stream) return result.int()
mongoose-master
mongoose_slide/slide_lib/simHash.py
mongoose-master
mongoose_slide/slide_lib/__init__.py
import collections import os import sys import math import random import numpy as np import numpy.random import scipy as sp import scipy.stats import torch import os from clsh import pyLSH # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 # os.environ["CUDA_VISIBLE_DEVICES"]=config.gpu use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") class LSH: def __init__(self, func_, K_, L_, threads_= 8): self.func = func_ self.K = K_ self.L = L_ self.lsh_ = pyLSH(self.K, self.L, threads_) self.sample_size = 0 self.count = 0 def setSimHash(self, func_): self.func = func_ def resetLSH(self, func_): self.func = func_ self.clear() def stats(self): avg_size = self.sample_size // max(self.count, 1) print("hashtable avg_size", avg_size) self.sample_size = 0 self.count = 0 return avg_size def remove_insert(self, item_id, old_item, new_fp): old_fp = self.func.hash(old_item).int().cpu().numpy() self.lsh_.remove(np.squeeze(old_fp), item_id) self.lsh_.insert(new_fp, item_id) def insert(self, item_id, item): fp = self.func.hash(item).int().cpu().numpy() self.lsh_.insert(np.squeeze(fp), item_id) def insert_fp(self, item_id, fp): self.lsh_.insert(np.squeeze(fp), item_id) def insert_multi(self, items, N): fp = self.func.hash(items).int().cpu().numpy() # print("lsh new: fp", fp) self.lsh_.insert_multi(fp, N) def query(self, item): fp = np.ascontiguousarray(self.func.hash(item).int().cpu()) return self.lsh_.query(np.squeeze(fp)) def query_fp(self, fp): fp = np.ascontiguousarray(fp) return self.lsh_.query(fp) def query_multi(self, items, N): #fp = np.ascontiguousarray(self.func.hash(items, transpose=True).int().cpu()) fp = np.ascontiguousarray(self.func.hash(items, transpose=False).int().cpu()) return self.lsh_.query_multi(fp, N), fp def query_multi_mask(self, item, M, N): fp = self.func.hash(item).int().cpu().numpy() #print("query_multi_mask", fp) mask = torch.zeros(M, N, dtype=torch.float32) # mask_L = torch.zeros(M, self.L, N,dtype=torch.float32) self.lsh_.query_multi_mask(fp, mask.numpy(), M, N) # self.lsh_.query_multi_mask_L(fp, mask.numpy(), mask_L.numpy(), M, N) return mask.to(device), fp def accidental_match(self, labels, samples, N): self.lsh_.accidental_match(labels, samples, N) def multi_label(self, labels, samples): return self.lsh_.multi_label(labels, samples) def multi_label_nonunion(self, labels, mask): return self.lsh_.multi_label_nonunion(labels, mask) # def query_remove_matrix(self, items, labels, total_size): # # for each data sample, query lsh data structure, remove accidental hit # # find maximum number of samples # # create matrix and pad appropriately # batch_size, D = items.size() # fp = self.func.hash(items).int().cpu().numpy() # result, total_count = self.lsh_.query_matrix(fp, labels.cpu().numpy(), batch_size, total_size) # batch_size, ssize = result.shape # self.sample_size += total_count # self.count += batch_size # return result def query_remove_matrix(self, items, labels, total_size): # for each data sample, query lsh data structure, remove accidental hit # find maximum number of samples # create matrix and pad appropriately batch_size, D = items.size() fp = self.func.hash(items).int().cpu().numpy() result, total_count = self.lsh_.query_matrix(fp, labels, batch_size, total_size) batch_size, ssize = result.shape self.sample_size += total_count self.count += batch_size return result,fp def query_remove(self, item, label): fp = self.func.hash(item).int().cpu().numpy() result = self.lsh_.query(np.squeeze(fp)) if label in result: result.remove(label) self.sample_size += len(result) self.count += 1 return list(result) def print_stats(self): print("in lsh new") return self.lsh_.print_stats() def clear(self): self.lsh_.clear()
mongoose-master
mongoose_slide/slide_lib/lsh.py
import cupy as cp from cupy.cuda import function from cupy.cuda import device from pynvrtc.compiler import Program from collections import namedtuple # CUDA Stream Stream = namedtuple('Stream', ['ptr']) class cupyKernel: def __init__(self, kernel, func_name): self.kernel = kernel self.title = func_name + ".cu" self.func_name = func_name self.compiled = False def get_compute_arch(): return "compute_{0}".format(device.Device().compute_capability) def compile(self): # Create program program = Program(self.kernel, self.title) # Compile program arch = "-arch={0}".format(cupyKernel.get_compute_arch()) ptx = program.compile([arch]) # Load Program m = function.Module() m.load(bytes(ptx.encode())) # Get Function Pointer self.func = m.get_function(self.func_name) self.compiled = True def __call__(self, grid, block, args, strm): if not self.compiled: self.compile() # Run Function self.func(grid, block, args, stream=Stream(ptr=strm))
mongoose-master
mongoose_slide/slide_lib/cupy_kernel.py
import numpy as np import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.utils.data import Dataset from mongoose_slide.slide_lib.simHash import SimHash from mongoose_slide.slide_lib.lsh import LSH use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") np.random.seed(1234) torch.manual_seed(1234) class LSHSampledLayer(nn.Module): def __init__(self, hash_weight, layer_size, K, L, num_class): super(LSHSampledLayer, self).__init__() self.D = layer_size self.K = K self.L = L self.num_class = num_class self.hash_weight = hash_weight self.store_query = True # last layer self.params = nn.Linear(layer_size, num_class) self.params.bias = nn.Parameter(torch.Tensor(num_class, 1)) self.init_weights(self.params.weight, self.params.bias) # construct lsh using triplet weight self.lsh = None self.initializeLSH() self.count = 0 self.sample_size = 0 self.thresh_hash = SimHash(self.D+1, 1, self.L) self.thresh = 0.3 self.hashcodes = self.thresh_hash.hash(torch.cat((self.params.weight, self.params.bias), dim = 1)) for name in self.backward_timer_names: self.backward_timer[name] = [] for name in self.forward_timer_names: self.forward_timer[name] = [] def initializeLSH(self): self.lsh = LSH( SimHash(self.D+1, self.K, self.L, self.hash_weight), self.K, self.L ) weight_tolsh = torch.cat( (self.params.weight, self.params.bias), dim = 1) self.lsh.insert_multi(weight_tolsh.to(device).data, self.num_class ) def setSimHash(self, seed, hashweight = None): print("update simhash") if(hashweight!=None): self.lsh.setSimHash( SimHash(self.D+1, self.K, self.L, hashweight ) ) def rebuild(self): weight_tolsh = torch.cat((self.params.weight, self.params.bias), dim=1) check = self.thresh_hash.hash(weight_tolsh) distance = check - self.hashcodes if torch.sum(torch.abs(distance))>self.thresh*distance.numel(): print("Rebuild LSH") self.lsh.clear() #include bias self.lsh.insert_multi(weight_tolsh.to(device).data, self.num_class ) self.hashcodes = check else: print("No need") def init_weights(self, weight, bias): initrange = 0.05 weight.data.uniform_(-initrange, initrange) bias.data.fill_(0) # bias.require_gradient = False def train_forward(self, x, y, triplet_flag, debug=False): '''weight normalization''' N, D = x.size() # sid, hashcode = self.lsh.query_multi(x.data, N) query_tolsh = torch.cat( (x, torch.ones(N).unsqueeze(dim = 1).to(device)), dim = 1 ) sid, hashcode = self.lsh.query_multi(query_tolsh.data, N) sampled_ip = 0 sampled_cos = 0 sizes = 0 retrieved_size = sizes * 1.0 / N # add y sid_list, target_matrix = self.lsh.multi_label(y.data.cpu().numpy(), sid) new_targets = Variable(torch.from_numpy(target_matrix)).to(device) sample_ids = Variable(torch.from_numpy(np.asarray(sid_list, dtype=np.int64)), requires_grad=False).to(device) sample_size = sample_ids.size(0) # print("sample size", sample_size) sample_weights = F.embedding(sample_ids, self.params.weight, sparse=True) sample_bias = self.params.bias.squeeze()[sample_ids] sample_product = sample_weights.matmul(x.t()).t() sample_logits = sample_product + sample_bias self.lsh.sample_size += sample_size weight_pair = {} return sample_logits, new_targets, sample_size, retrieved_size, weight_pair, hashcode, sampled_ip, sampled_cos def forward(self, x, y, triplet_flag, debug): if self.training: # self.speed_test(x, y) return self.train_forward(x, y, triplet_flag, debug) else: return torch.matmul(x, self.params.weight.t()) + self.params.bias.squeeze() class Net(nn.Module): def __init__(self, input_size, output_size, layer_size, hash_weight, K, L): super(Net, self).__init__() stdv = 1. / math.sqrt(input_size) self.input_size = input_size self.output_size = output_size self.layer_size = layer_size self.fc = nn.Embedding(self.input_size + 1, 128, padding_idx=input_size, sparse=True) self.bias = nn.Parameter(torch.Tensor(layer_size)) self.bias.data.uniform_(-stdv, stdv) self.lshLayer = LSHSampledLayer(hash_weight, layer_size, K, L, output_size) def forward(self, x, y, triplet_flag, debug): emb = torch.sum(self.fc(x), dim=1) emb = emb / torch.norm(emb, dim=1, keepdim=True) query = F.relu(emb + self.bias) return self.lshLayer.forward(query, y, triplet_flag, debug) def forward_full(self, x, y, t1, t2): with torch.no_grad(): N,d = x.size() emb = torch.sum(self.fc(x), dim=1) emb = emb / torch.norm(emb, dim=1, keepdim=True) query = F.relu(emb + self.bias) product = torch.matmul(query, self.lshLayer.params.weight.t()) t1 = 0.001 t2 = 0.5 t1_th = int(self.output_size * (1 - t1) ) # positive inner product rank t2_th = int(self.output_size * (1 - t2) ) # negative inner product rank t1_ip = torch.mean( torch.kthvalue(product, t1_th )[0]).item() t1_ip = max(0.0, t1_ip) t2_ip = torch.mean( torch.kthvalue(product, t2_th )[0]).item() #ip threshold mask ip_t1_mask = product > t1_ip ip_t2_mask = product < t2_ip query = torch.cat( (query.data, torch.ones(N).unsqueeze(dim = 1).to(device)), dim = 1 ) retrieved, _ = self.lshLayer.lsh.query_multi_mask(query, N, self.output_size) retrieved = retrieved.bool() positive_mask = ip_t1_mask & (~retrieved) negative_mask = ip_t2_mask & retrieved num_negative = torch.sum(negative_mask).item() num_positive = torch.sum(positive_mask).item() row, column = torch.where(positive_mask == 1) p_arc = query[row].detach() p_pos = torch.cat( (self.lshLayer.params.weight[column], self.lshLayer.params.bias[column]), dim = 1).detach() assert p_arc.size()[0]==p_pos.size()[0] assert p_arc.size()[1]==p_pos.size()[1] row, column = torch.where(negative_mask == 1) n_arc = query[row].detach() n_neg = torch.cat( (self.lshLayer.params.weight[column], self.lshLayer.params.bias[column]), dim = 1).detach() assert n_arc.size()[0]==n_neg.size()[0] assert n_arc.size()[1]==n_neg.size()[1] #down sample size = min(num_negative, num_positive) if(num_positive < num_negative): random_perm = torch.randperm(num_negative) permute_id=random_perm[: int(num_positive)] n_arc = n_arc[permute_id] n_neg = n_neg[permute_id] num_negative = n_arc.size()[0] else: random_perm = torch.randperm(num_positive) permute_id=random_perm[:int(num_negative)] p_arc = p_arc[permute_id] p_pos = p_pos[permute_id] num_positive = p_arc.size()[0] return p_arc,p_pos,n_arc,n_neg,num_negative class MultiLabelDataset(Dataset): def __init__(self, filename): self.build(filename) def build(self, filename): with open(filename) as f: metadata = f.readline().split() self.N = int(metadata[0]) self.D = int(metadata[1]) self.L = int(metadata[2]) self.max_L = 0 self.max_D = 0 self.data = list() for idx in range(self.N): items = f.readline().split() labels = [int(x) for x in items[0].split(",")] self.max_L = max(self.max_L, len(labels)) ids = list() # fvs = list() for fdx in range(1, len(items), 1): fid, fv = items[fdx].split(":") ids.append(int(fid)) # fvs.append( float(fv) ) self.max_D = max(self.max_D, len(ids)) self.data.append([torch.from_numpy(np.asarray(x)) for x in [labels, ids]]) # if idx % 100000 == 0: # print(idx) def pad(self, item, width, value): result = torch.zeros(width).long() result.fill_(value) result[:len(item)] = item return result def __len__(self): return self.N def __getitem__(self, idx): labels, idxs = self.data[idx] return self.pad(labels, self.max_L, -1), self.pad(idxs, self.max_D, self.D)
mongoose-master
mongoose_slide/slide_lib/network.py
import torch import torch.nn as nn import torch.nn.functional as F use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") class TripletNet(nn.Module): def __init__(self, margin, K, L, layer_size): super(TripletNet, self).__init__() self.K = K self.L = L self.dense1 = nn.Linear(layer_size, K*L) self.init_weights(self.dense1.weight, self.dense1.bias) self.dense1.bias.requires_grad = False self.margin = margin self.device = device def init_weights(self, weight, bias): weight.data.normal_(0,1) bias.data.fill_(0) def forward(self, arc, pair, label): emb_arc = self.dense1(arc) emb_pair = self.dense1(pair) # embedding chunk - L1 emb_arc_chunk = torch.cat(torch.chunk(emb_arc, self.L, dim = 1 )) emb_pair_chunk = torch.cat(torch.chunk(emb_pair, self.L, dim = 1 )) label_chunk = label.repeat(self.L) assert emb_arc_chunk.size()==emb_pair_chunk.size() assert emb_arc_chunk.size()[0]==label_chunk.size()[0] beta = 1 alpha = 0.5 emb_arc_chunk = torch.tanh( beta * emb_arc_chunk) emb_pair_chunk = torch.tanh( beta * emb_pair_chunk) # agree_x_p = torch.mean( ((emb_arc_chunk > 0) == (emb_pair_chunk > 0 ))[label_chunk==1].float() ) # agree_x_n = torch.mean( ((emb_arc_chunk > 0) == (emb_pair_chunk > 0 ))[label_chunk==0].float() ) # # print("\nagree_x_p", agree_x_p) # print("agree_x_n", agree_x_n) output = torch.sum(emb_arc_chunk * emb_pair_chunk, dim= 1) assert output.size()==label_chunk.size() output_loss = F.binary_cross_entropy(F.sigmoid(output), label_chunk) # reg_loss=torch.mean(torch.norm(self.dense1.weight,dim=1)) # loss = output_loss+0.05*reg_loss loss = output_loss return loss
mongoose-master
mongoose_slide/slide_lib/triplet_network.py
import math import torch from torch.optim import Optimizer class Adam(Optimizer): """Implements Adam algorithm. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-5, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(Adam, self).__init__(params, defaults) def __setstate__(self, state): super(Adam, self).__setstate__(state) for group in self.param_groups: group.setdefault('amsgrad', False) def dense(self, p, grad, group): amsgrad = group['amsgrad'] state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if amsgrad: # Maintains max of all exp. moving avg. of sq. grad. values state['max_exp_avg_sq'] = torch.zeros_like(p.data) exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] beta1, beta2 = group['betas'] if amsgrad: max_exp_avg_sq = state['max_exp_avg_sq'] state['step'] += 1 if group['weight_decay'] != 0: grad = grad.add(group['weight_decay'], p.data) # Decay the first and second moment running average coefficient exp_avg.mul_(beta1).add_(1 - beta1, grad) exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) if amsgrad: # Maintains the maximum of all 2nd moment running avg. till now torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq) # Use the max. for normalizing running avg. of gradient denom = max_exp_avg_sq.sqrt().add_(group['eps']) else: denom = exp_avg_sq.sqrt().add_(group['eps']) bias_correction1 = 1 - beta1 ** state['step'] bias_correction2 = 1 - beta2 ** state['step'] step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1 p.data.addcdiv_(-step_size, exp_avg, denom) def sparse(self, p, grad, group): state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) state['step'] += 1 grad = grad.coalesce() # the update is non-linear so indices must be unique grad_indices = grad._indices() grad_values = grad._values() size = grad.size() exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] beta1, beta2 = group['betas'] def make_sparse(values): constructor = grad.new if grad_indices.dim() == 0 or values.dim() == 0: return constructor().resize_as_(grad) return constructor(grad_indices, values, size) # Decay the first and second moment running average coefficient # old <- b * old + (1 - b) * new <==> old += (1 - b) * (new - old) old_exp_avg_values = exp_avg.sparse_mask(grad)._values() exp_avg_update_values = grad_values.sub(old_exp_avg_values).mul_(1 - beta1) exp_avg.add_(make_sparse(exp_avg_update_values)) old_exp_avg_sq_values = exp_avg_sq.sparse_mask(grad)._values() exp_avg_sq_update_values = grad_values.pow(2).sub_(old_exp_avg_sq_values).mul_(1 - beta2) exp_avg_sq.add_(make_sparse(exp_avg_sq_update_values)) # Dense addition again is intended, avoiding another sparse_mask numer = exp_avg_update_values.add_(old_exp_avg_values) exp_avg_sq_update_values.add_(old_exp_avg_sq_values) denom = exp_avg_sq_update_values.sqrt_().add_(group['eps']) del exp_avg_update_values, exp_avg_sq_update_values bias_correction1 = 1 - beta1 ** state['step'] bias_correction2 = 1 - beta2 ** state['step'] step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1 p.data.add_(make_sparse(-step_size * numer.div_(denom))) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: self.sparse(p, grad, group) else: self.dense(p, grad, group) return loss
mongoose-master
mongoose_slide/slide_lib/adam_base.py
from setuptools import setup from setuptools.extension import Extension from Cython.Build import cythonize import numpy setup(name="clsh", ext_modules=cythonize(Extension( "clsh", # the extension name sources=["clsh.pyx", "LSH.cpp"], # the Cython source and additional C++ source files language="c++", # generate and compile C++ code include_dirs=[numpy.get_include()], extra_compile_args=["-std=c++11"] )))
mongoose-master
lsh_lib/setup.py
import torch from cupy_kernel import cupyKernel import numpy as np kernel = ''' extern "C" __global__ void fingerprint(const float* src, const int k, const int L, long* fp) { // product (N x kL bits) -> Column-Major Order // const int L = gridDim.y; // const int k = blockDim.x; int offset = (k * L * blockIdx.x) + (k * blockIdx.y + threadIdx.x); long value = (threadIdx.x >= k || src[offset] <= 0) ? 0 : 1; value <<= threadIdx.x; for (int offset = warpSize/2; offset > 0; offset /= 2) { value |= __shfl_down(value, offset); } if(!threadIdx.x) { int fp_offset = L * blockIdx.x + blockIdx.y; fp[fp_offset] = value; } } ''' class SimHash: def __init__(self, d_, k_, L_, seed_=8191, srp_list=None): self.d = d_ self.k = k_ self.L = L_ self.fp = cupyKernel(kernel, "fingerprint") if srp_list is None: self.rp = SimHash.generate(d_, k_, L_, seed_) else: self.rp = SimHash.generate_from_list(srp_list) def generate_from_list(srp_list): matrices = [item.rp for item in srp_list] return torch.cat(matrices, dim=1) def generate(d, k, L, seed): rand_gen = np.random.RandomState(seed) matrix = rand_gen.randn(d, k*L) positive = np.greater_equal(matrix, 0.0) negative = np.less(matrix, 0.0) result = positive.astype(np.float32) - negative.astype(np.float32) return torch.from_numpy(result).cuda() def hash(self, data, transpose=False): N, D = data.size() srp = torch.matmul(data, self.rp) result = self.fingerprint(srp, N) if transpose: result = torch.t(result) return result def fingerprint(self, srp, N): result = torch.zeros(N, self.L).long().cuda() self.fp(grid=(N,self.L,1), block=(32,1,1), args=[srp.data_ptr(), self.k, self.L, result.data_ptr()], strm=torch.cuda.current_stream().cuda_stream) return result
mongoose-master
lsh_lib/matrix_simhash.py
import torch import query_mul class QueryMulFn(torch.autograd.Function): """C = A @ B where A and B are dense matrices, but the output C is sparse, specified by CSR format """ @staticmethod def forward(ctx, A, B, rowPtrC, colIdxC): # Ensure that A and B are contiguous in the column-major format, to avoid copying twice in backward A_cont = A.detach().t().contiguous().t() # Have to detach otherwise torch.autograd complains B_cont = B.detach().t().contiguous().t() ctx.save_for_backward(A_cont, B_cont, rowPtrC, colIdxC) valC = query_mul.constrained_gemm(A_cont, B_cont, rowPtrC, colIdxC) return valC @staticmethod def backward(ctx, grad): A_cont, B_cont, rowPtrC, colIdxC = ctx.saved_tensors grad_A, grad_B = None, None if ctx.needs_input_grad[0]: grad_A = query_mul.csrmm(grad, rowPtrC, colIdxC, B_cont, A_cont.shape[0], False, True) if ctx.needs_input_grad[1]: grad_B = query_mul.csrmm(grad, rowPtrC, colIdxC, A_cont, B_cont.shape[1], True, False).t() return grad_A, grad_B, None, None query_mul_fn = QueryMulFn.apply
mongoose-master
lsh_lib/query_mul_interface.py
import io import os import sys from distutils.util import convert_path from shutil import rmtree from setuptools import Command, find_packages, setup main_ns = {} ver_path = convert_path("domino/version.py") with open(ver_path) as ver_file: exec(ver_file.read(), main_ns) # Package meta-data. NAME = "domino" DESCRIPTION = "" URL = "" EMAIL = "eyuboglu@stanford.edu" AUTHOR = "https://github.com/HazyResearch/domino" REQUIRES_PYTHON = ">=3.7.0" VERSION = main_ns["__version__"] with open("README.md", "r") as fh: long_description = fh.read() REQUIRED = [ "meerkat-ml", "pandas", "numpy>=1.18.0", "tqdm>=4.49.0", # TODO: support scikit-learn 1.0.0 "scikit-learn==0.24.2", "ipywidgets", "seaborn", "torch", ] EXTRAS = { "dev": [ "black==21.5b0", "isort>=5.7.0", "autoflake", "flake8>=3.8.4", "mypy>=0.9", "docformatter>=1.4", "pytest-cov>=2.10.1", "sphinx-rtd-theme>=0.5.1", "nbsphinx>=0.8.0", "recommonmark>=0.7.1", "parameterized", "pre-commit>=2.9.3", "sphinx-autobuild", "sphinx-panels", "jupyter-sphinx", "pydata-sphinx-theme", ], "text": ["transformers", "nltk"], "eval": ["pytorch-lightning", "dcbench"], "bit": ["torchvision"], "clip": ["ftfy", "regex"], } # The rest you shouldn't have to touch too much :) # ------------------------------------------------ # Except, perhaps the License and Trove Classifiers! # If you do change the License, remember to change the Trove Classifier for that! here = os.path.abspath(os.path.dirname(__file__)) # Import the README and use it as the long-description. # Note: this will only work if 'README.md' is present in your MANIFEST.in file! try: with io.open(os.path.join(here, "README.md"), encoding="utf-8") as f: long_description = "\n" + f.read() except FileNotFoundError: long_description = DESCRIPTION # Load the package's __version__.py module as a dictionary. about = {} if not VERSION: project_slug = NAME.lower().replace("-", "_").replace(" ", "_") with open(os.path.join(here, project_slug, "__version__.py")) as f: exec(f.read(), about) else: about["__version__"] = VERSION class UploadCommand(Command): """Support setup.py upload.""" description = "Build and publish the package." user_options = [] @staticmethod def status(s): """Prints things in bold.""" print("\033[1m{0}\033[0m".format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status("Removing previous builds…") rmtree(os.path.join(here, "dist")) except OSError: pass self.status("Building Source and Wheel (universal) distribution…") os.system("{0} setup.py sdist bdist_wheel --universal".format(sys.executable)) self.status("Uploading the package to PyPI via Twine…") os.system("twine upload dist/*") self.status("Pushing git tags…") os.system("git tag v{0}".format(about["__version__"])) os.system("git push --tags") sys.exit() # Where the magic happens: setup( name=NAME, version=about["__version__"], description=DESCRIPTION, long_description=long_description, long_description_content_type="text/markdown", author=AUTHOR, author_email=EMAIL, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"]), # If your package is a single module, use this instead of 'packages': # py_modules=['mypackage'], # entry_points={ # 'console_scripts': ['mycli=mymodule:cli'], # }, install_requires=REQUIRED, extras_require=EXTRAS, include_package_data=True, license="Apache 2.0", classifiers=[ # Trove classifiers # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], # $ setup.py publish support. cmdclass={ "upload": UploadCommand, }, )
domino-main
setup.py
__version__ = "0.1.5"
domino-main
domino/version.py
import functools from typing import Any, List, Optional, Sequence from fvcore.common.registry import Registry as _Registry from tabulate import tabulate class Registry(_Registry): """Extension of fvcore's registry that supports aliases.""" _ALIAS_KEYWORDS = ("_aliases", "_ALIASES") def __init__(self, name: str): super().__init__(name=name) self._metadata_map = {} @functools.lru_cache(maxsize=128) def get(self, name: str, *args, **kwargs) -> Any: ret = self._obj_map.get(name) if ret is None: raise KeyError( "No object named '{}' found in '{}' registry!".format(name, self._name) ) return ret(*args, **kwargs) def _get_aliases(self, obj_func_or_class): for kw in self._ALIAS_KEYWORDS: if hasattr(obj_func_or_class, kw): return getattr(obj_func_or_class, kw) return [] def register( self, obj: object = None, aliases: Sequence[str] = None ) -> Optional[object]: if obj is None: # used as a decorator def deco(func_or_class: object, aliases=None) -> object: name = func_or_class.__name__ # pyre-ignore self._do_register(name, func_or_class) if aliases is None: aliases = self._get_aliases(func_or_class) if not isinstance(aliases, (list, tuple, set)): aliases = [aliases] for alias in aliases: self._do_register(alias, func_or_class) return func_or_class kwargs = {"aliases": aliases} if any(v is not None for v in kwargs.values()): return functools.partial(deco, **kwargs) else: return deco name = obj.__name__ # pyre-ignore self._do_register(name, obj) if aliases is None: aliases = self._get_aliases(obj) for alias in aliases: self._do_register(alias, obj) def _do_register(self, name: str, obj: Any, **kwargs) -> None: self._metadata_map[name] = {"name": name, "description": obj.__doc__, **kwargs} return super()._do_register(name, obj) @property def names(self) -> List[str]: return list(self._obj_map.keys()) def __repr__(self) -> str: table = tabulate(self._metadata_map.values(), tablefmt="fancy_grid") return "Registry of {}:\n".format(self._name) + table def __str__(self) -> str: return self.__repr__()
domino-main
domino/registry.py
from ._embed import embed, encoders from ._slice.abstract import Slicer from ._slice.mixture import MixtureSlicer, DominoSlicer from ._slice.spotlight import SpotlightSlicer from ._slice.barlow import BarlowSlicer from ._slice.multiaccuracy import MultiaccuracySlicer from ._slice.mlp import MLPSlicer from ._slice.fused import FusedSlicer from ._slice.abstract import Slicer from ._describe.generate import generate_candidate_descriptions from ._describe.abstract import Describer from ._describe.mean import MeanDescriber from ._describe.corr import CorrDescriber from ._describe import describe from .main import discover from .gui import explore __all__ = [ "DominoSlicer", "MixtureSlicer", "MLPSlicer", "SpotlightSlicer", "BarlowSlicer", "MultiaccuracySlicer", "FusedSlicer", "Slicer", "Describer", "MeanDescriber", "CorrDescriber", "embed", "encoders", "explore", "describe", "discover", "generate_candidate_descriptions", ]
domino-main
domino/__init__.py
from dataclasses import dataclass from functools import reduce, wraps from inspect import getcallargs from typing import Collection, Mapping import pandas as pd import torch import numpy as np from typing import List import meerkat as mk def unpack_args(data: mk.DataPanel, *args): if any(map(lambda x: isinstance(x, str), args)) and data is None: raise ValueError("If args are strings, `data` must be provided.") new_args = [] for arg in args: if isinstance(arg, str): arg = data[arg] if isinstance(arg, mk.AbstractColumn): # this is necessary because torch.tensor() of a NumpyArrayColumn is very # slow and I don't want implementers to have to deal with casing on this arg = arg.data new_args.append(arg) return new_args def convert_to_numpy(*args): """Convert Torch tensors and Pandas Series to numpy arrays.""" new_args = [] for arg in args: if torch.is_tensor(arg): new_args.append(arg.numpy()) elif isinstance(arg, pd.Series): new_args.append(arg.values) elif isinstance(arg, List): new_args.append(np.array(arg)) else: new_args.append(arg) return tuple(new_args) def convert_to_torch(*args): new_args = [] for arg in args: if isinstance(arg, (np.ndarray, pd.Series, List)): new_args.append(torch.tensor(arg)) else: new_args.append(arg) return tuple(new_args) def nested_getattr(obj, attr, *args): """Get a nested property from an object. # noqa: E501 Source: https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-subobjects-chained-properties """ return reduce(lambda o, a: getattr(o, a, *args), [obj] + attr.split(".")) @dataclass class VariableColumn: variable_name: str def resolve(self, args_dict: dict): path = self.variable_name.split(".") obj = args_dict[path[0]] if len(path) > 1: return nested_getattr(obj, ".".join(path[1:])) return obj def requires_columns(dp_arg: str, columns: Collection[str]): def _requires(fn: callable): @wraps(fn) def _wrapper(*args, aliases: Mapping[str, str] = None, **kwargs): args_dict = getcallargs(fn, *args, **kwargs) if "kwargs" in args_dict: args_dict.update(args_dict.pop("kwargs")) dp = args_dict[dp_arg] if aliases is not None: dp = dp.view() for column, alias in aliases.items(): dp[column] = dp[alias] # resolve variable columns resolved_cols = [ (col.resolve(args_dict) if isinstance(col, VariableColumn) else col) for col in columns ] missing_cols = [col for col in resolved_cols if col not in dp] if len(missing_cols) > 0: raise ValueError( f"DataPanel passed to `{fn.__qualname__}` at argument `{dp_arg}` " f"is missing required columns `{missing_cols}`." ) args_dict[dp_arg] = dp return fn(**args_dict) return _wrapper return _requires
domino-main
domino/utils.py
from typing import Dict, Union, Tuple, List from domino._describe.abstract import Describer from domino.utils import unpack_args import meerkat as mk import numpy as np from ._slice.abstract import Slicer from ._slice.mixture import MixtureSlicer from ._embed import embed from ._describe.abstract import Describer from ._describe.mean import MeanDescriber def discover( data: Union[dict, mk.DataPanel] = None, embeddings: Union[str, np.ndarray] = "embedding", targets: Union[str, np.ndarray] = "target", pred_probs: Union[str, np.ndarray] = "pred_probs", losses: Union[str, np.ndarray] = "loss", split: Union[str, np.ndarray] = "split", slicer: Slicer = None, describer: Describer = None, ) -> Tuple[np.ndarray, List[Dict]]: embeddings, targets, pred_probs, losses, split = unpack_args( data, embeddings, targets, pred_probs, losses, split ) if embeddings is None: raise NotImplementedError if slicer is None: # provide a simple default slicer if none is provided slicer = MixtureSlicer( n_slices=5, y_log_likelihood_weight=10, y_hat_log_likelihood_weight=10, ) train_mask = (split != "test") slicer.fit( targets=targets[train_mask] if targets is not None else None, pred_probs=pred_probs[train_mask] if pred_probs is not None else None, losses=losses[train_mask] if losses is not None else None, embeddings=embeddings[train_mask] if embeddings is not None else None, ) test_mask = ~train_mask slices = slicer.predict_proba( targets=None, pred_probs=None, #losses=losses[test_mask], embeddings=embeddings[test_mask] if embeddings is not None else None, ) if describer is None: raise NotImplementedError descriptions = describer.describe( embeddings=embeddings[test_mask], targets=None, slices=slices ) return slices, descriptions
domino-main
domino/main.py
from typing import List, Union import ipywidgets as widgets import matplotlib.pyplot as plt import meerkat as mk import numpy as np import pandas as pd import seaborn as sns from IPython.display import display from domino.utils import unpack_args from ._describe import describe def explore( data: mk.DataPanel = None, embeddings: Union[str, np.ndarray] = "embedding", targets: Union[str, np.ndarray] = "target", pred_probs: Union[str, np.ndarray] = "pred_prob", slices: Union[str, np.ndarray] = "slices", text: mk.DataPanel = None, text_embeddings: Union[str, np.ndarray] = "embedding", phrase: Union[str, np.ndarray] = "output_phrase", ) -> None: """Creates a IPyWidget GUI for exploring discovered slices. The GUI includes two sections: (1) The first section displays data visualizations summarizing the model predictions and accuracy stratified by slice. (2) The second section displays a table (i.e. Meerkat DataPanel) of the data examples most representative of each slice. The DataPanel passed to ``data`` should include columns for embeddings, targets, pred_probs and slices. Any additional columns will be included in the visualization in section (2). .. caution:: This GUI works best in the original Jupyter Notebook, and may not work properly in a Jupyter Lab or VSCode environment. Args: data (mk.DataPanel, optional): A `Meerkat DataPanel` with columns for embeddings, targets, and prediction probabilities. The names of the columns can be specified with the ``embeddings``, ``targets``, and ``pred_probs`` arguments. Defaults to None. embeddings (Union[str, np.ndarray], optional): The name of a column in ``data`` holding embeddings. If ``data`` is ``None``, then an np.ndarray of shape (n_samples, dimension of embedding). Defaults to "embedding". targets (Union[str, np.ndarray], optional): The name of a column in ``data`` holding class labels. If ``data`` is ``None``, then an np.ndarray of shape (n_samples,). Defaults to "target". pred_probs (Union[str, np.ndarray], optional): The name of a column in ``data`` holding model predictions (can either be "soft" probability scores or "hard" 1-hot encoded predictions). If ``data`` is ``None``, then an np.ndarray of shape (n_samples, n_classes) or (n_samples,) in the binary case. Defaults to "pred_probs". slices (str, optional): The name of The name of a column in ``data`` holding discovered slices. If ``data`` is ``None``, then an np.ndarray of shape (num_examples, num_slices). Defaults to "slices". text (str, optional): A `Meerkat DataPanel` with columns for text phrases and their embeddings. The names of the columns can be specified with the ``text_embeddings`` and ``phrase`` arguments. Defaults to None. text_embeddings (Union[str, np.ndarray], optional): The name of a colum in ``text`` holding embeddings. If ``text`` is ``None``, then an np.ndarray of shape (n_phrases, dimension of embedding). Defaults to "embedding". phrase (Union[str, np.ndarray], optional): The name of a column in ``text`` holding text phrases. If ``text`` is ``None``, then an np.ndarray of shape (n_phrases,). Defaults to "output_phrase". Examples -------- .. code-block:: python :name: Example: from domino import explore, DominoSDM dp = ... # prepare the dataset as a Meerkat DataPanel # split dataset valid_dp = dp.lz[dp["split"] == "valid"] test_dp = dp.lz[dp["split"] == "test"] domino = DominoSDM() domino.fit(data=valid_dp) test_dp["slices"] = domino.transform( data=test_dp, embeddings="emb", targets="target", pred_probs="probs" ) explore(data=test_dp) """ embeddings, targets, pred_probs, slices = unpack_args( data, embeddings, targets, pred_probs, slices ) if data is None: dp = mk.DataPanel( { "embeddings": embeddings, "targets": targets, "pred_probs": pred_probs, "domino_slices": slices, } ) else: dp = data if isinstance(data, mk.DataPanel) else mk.DataPanel(data) plot_output = widgets.Output() # define functions for generating visualizations def plot_slice(slice_idx, slice_threshold: float): # TODO (Sabri): Support a confusion matrix for the multiclass case. with plot_output: plot_df = pd.DataFrame( { "in-slice": slices[:, slice_idx] > slice_threshold, "pred_probs": pred_probs[:, 1].numpy() if len(pred_probs.shape) == 2 else pred_probs, "target": targets, } ) g = sns.displot( data=plot_df, hue="in-slice", x="pred_probs", col="target", aspect=1.7, height=2, facet_kws={"sharey": False}, hue_order=[False, True], palette=["#bdbdbd", "#2396f3"], stat="percent", common_norm=False, bins=20, ) g.set_axis_labels("Model's output probability", "% of examples") for target in np.unique(targets): in_slice = np.sum( (slices[:, slice_idx] > slice_threshold) & (targets == target) ) g.axes[0, int(target)].set_title( f"target={target} \n (# of examples in-slice={in_slice})" ) plot_output.clear_output(wait=True) plt.show() description_output = widgets.Output() def show_descriptions(slice_idx: int, slice_threshold: float): description_output.clear_output(wait=False) if text is not None: description_dp = describe( data=dp, embeddings=embeddings, targets=targets, slices=slices, slice_idx=slice_idx, text=text, text_embeddings=text_embeddings, phrases=phrase, slice_threshold=slice_threshold, ) with description_output: display(description_dp[(-description_dp["score"]).argsort()[:5]]) dp_output = widgets.Output() def show_dp( slice_idx, page_idx: int, page_size: int, columns: List[str], slice_threshold: float, ): mk.config.display.max_rows = page_size dp_output.clear_output(wait=False) num_examples_in_slice = np.sum(slices[:, slice_idx] > slice_threshold) with dp_output: display( dp.lz[ (-slices[:, slice_idx]).argsort()[ page_size * page_idx : min( page_size * (page_idx + 1), num_examples_in_slice ) ] ][list(columns)] ) # Create widgets slice_idx_widget = widgets.Dropdown( value=1, options=list(range(slices.shape[-1])), description="Slice", layout=widgets.Layout(width="150px"), ) slice_threshold_widget = widgets.FloatSlider( value=0.5, min=0, max=1.0, step=0.025, description="Slice Inclusion Threshold", disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format=".3f", style={"description_width": "initial"}, ) # TODO(Sabri): Add a widget for the # of examples in the slice at the current # threshold. It will have to be linked with the threshold widget above. column_selector = widgets.SelectMultiple( options=dp.columns, value=dp.columns, description="Columns", disabled=False ) page_size_widget = widgets.RadioButtons( options=[10, 25, 50], description="Page size" ) page_idx_widget = widgets.BoundedIntText( value=0, min=0, max=10, step=1, description="Page", disabled=False, readout=True, readout_format="d", layout=widgets.Layout(width="150px"), ) # Establish interactions between widgets and the visualization functions widgets.interactive( show_descriptions, slice_idx=slice_idx_widget, slice_threshold=slice_threshold_widget, ) widgets.interactive( show_dp, slice_idx=slice_idx_widget, columns=column_selector, page_idx=page_idx_widget, page_size=page_size_widget, slice_threshold=slice_threshold_widget, ) widgets.interactive( plot_slice, slice_idx=slice_idx_widget, slice_threshold=slice_threshold_widget, ) # Layout and display the widgets display( widgets.HBox( [ widgets.HTML(value="<p><strong> Domino Slice Explorer </strong></p>"), slice_idx_widget, ] ) ) display(slice_threshold_widget) display(plot_output) display( widgets.VBox( [ widgets.HTML( value=( "<p> <strong> Natural language descriptions of the slice: " "</strong> </p>" ) ), description_output, ] ) ) display( widgets.HBox( [ widgets.VBox( [ widgets.HTML( value=( "<style>p{word-wrap: break-word}</style> <p>" + "Select multiple columns with <em>cmd-click</em>." + " </p>" ) ), column_selector, ] ), widgets.VBox([page_idx_widget, page_size_widget]), ], ) ) display( widgets.VBox( [ widgets.HTML( value=( "<p> <strong> Examples in the slice, ranked by likelihood: " "</strong> </p>" ) ), dp_output, ] ) ) # To actually run the functions `plot_slice` and `show_dp` we need update the value # of one of the widgets. slice_idx_widget.value = 0
domino-main
domino/gui.py
from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Dict, Union import meerkat as mk import numpy as np import torch.nn as nn from sklearn.base import BaseEstimator @dataclass class Config: pass class Describer(ABC, BaseEstimator): def __init__(self): super().__init__() self.config = Config() @abstractmethod def describe( embeddings: Union[str, np.ndarray] = "embedding", targets: Union[str, np.ndarray] = "target", slices: Union[str, np.ndarray] = "slices", ): raise NotImplementedError def get_params(self) -> Dict[str, Any]: """ Get the parameters of this slicer. Returns a dictionary mapping from the names of the parameters (as they are defined in the ``__init__``) to their values. Returns: Dict[str, Any]: A dictionary of parameters. """ return self.config.__dict__ def set_params(self, **params): raise ValueError( f"Slicer of type {self.__class__.__name__} does not support `set_params`." ) def to(self, device: Union[str, int]): if device != "cpu": raise ValueError(f"Slicer of type {type(self)} does not support GPU.") # by default this is a no-op, but subclasses can override
domino-main
domino/_describe/abstract.py
from typing import Union import meerkat as mk import numpy as np import torch from scipy.stats import mode, pearsonr from .abstract import Describer from ..utils import convert_to_torch, unpack_args class CorrDescriber(Describer): """ Args: text (str, optional): A `Meerkat DataPanel` with columns for text phrases and their embeddings. The names of the columns can be specified with the ``text_embeddings`` and ``phrase`` arguments. Defaults to None. text_embeddings (Union[str, np.ndarray], optional): The name of a colum in ``text`` holding embeddings. If ``text`` is ``None``, then an np.ndarray of shape (n_phrases, dimension of embedding). Defaults to "embedding". phrase (Union[str, np.ndarray], optional): The name of a column in ``text`` holding text phrases. If ``text`` is ``None``, then an np.ndarray of shape (n_phrases,). Defaults to "output_phrase". slice_idx (int, optional): The index of the slice to describe. Defaults to 0. slice_threshold (float, optional): The probability threshold for inclusion in the slice. Defaults to 0.5. """ def __init__( self, data: mk.DataPanel = None, embeddings: Union[str, np.ndarray] = "embedding", candidates: Union[str, np.ndarray] = "candidates", slice_threshold: float = 0.5, n_descriptions: int = 10, ): super().__init__() embeddings, candidates = unpack_args(data, embeddings, candidates) self.candidates = candidates self.candidate_embeddings = embeddings self.config.slice_threshold = slice_threshold self.config.n_descriptions = n_descriptions def describe( self, data: mk.DataPanel = None, embeddings: Union[str, np.ndarray] = "embedding", targets: Union[str, np.ndarray] = "target", slices: Union[str, np.ndarray] = "slices", ): embeddings, targets, slices = unpack_args(data, embeddings, targets, slices) img_embs, slices, text_embs = convert_to_torch( embeddings, slices, self.candidate_embeddings ) with torch.no_grad(): text_scores = torch.matmul(img_embs.to(0), text_embs.to(0).T) r = batched_pearsonr( x=text_scores.to(torch.float).T, y=slices.to(torch.float).to(0).T ) result = [] for pred_slice_idx in range(r.shape[-1]): slice_scores = r[:, pred_slice_idx].cpu().detach().numpy() idxs = np.argsort(-slice_scores)[:10] result.append( [ { "pred_slice_idx": pred_slice_idx, "scores": slice_scores[idx], "corr": slice_scores[idx], "text": self.candidates[idx], } for idx in idxs ] ) return result @torch.no_grad() def batched_pearsonr(x, y, batch_first=True): if len(x.shape) - len(y.shape) == 1: y = y.unsqueeze(-1) centered_x = x - x.mean(dim=1, keepdim=True) centered_y = y - y.mean(dim=1, keepdim=True) covariance = centered_x @ centered_y.T # x_batch x y_batch bessel_corrected_covariance = covariance / (x.shape[1] - 1) x_std = x.std(dim=1, keepdim=True) y_std = y.std(dim=1, keepdim=True) std = x_std @ y_std.T corr = bessel_corrected_covariance / std return corr
domino-main
domino/_describe/corr.py