|
| 1 | +import itertools |
| 2 | +import warnings |
| 3 | +from typing import Iterable, Union |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +import torch |
| 7 | +from sentence_transformers import SentenceTransformer |
| 8 | +from sklearn.preprocessing import normalize |
| 9 | +from tokenizers import Tokenizer |
| 10 | +from tqdm import trange |
| 11 | + |
| 12 | + |
| 13 | +def is_contextual(encoder): |
| 14 | + return hasattr(encoder, "encode_tokens") |
| 15 | + |
| 16 | + |
| 17 | +Offsets = list[tuple[int, int]] |
| 18 | +Lengths = list[int] |
| 19 | + |
| 20 | + |
| 21 | +def flatten_embeddings( |
| 22 | + embeddings: list[np.ndarray], |
| 23 | +) -> tuple[np.ndarray, Lengths]: |
| 24 | + """Flattens ragged array to normal array. |
| 25 | +
|
| 26 | + Parameters |
| 27 | + ---------- |
| 28 | + embeddings: list[ndarray] |
| 29 | + Ragged embedding array. |
| 30 | +
|
| 31 | + Returns |
| 32 | + ------- |
| 33 | + flat_embeddings: ndarray |
| 34 | + Flattened embedding array. |
| 35 | + lengths: list[int] |
| 36 | + Length of each document in the corpus. |
| 37 | + """ |
| 38 | + lengths = [emb.shape[0] for emb in embeddings] |
| 39 | + return np.concatenate(embeddings, axis=0), lengths |
| 40 | + |
| 41 | + |
| 42 | +def unflatten_embeddings( |
| 43 | + flat_embeddings: np.ndarray, lengths: Lengths |
| 44 | +) -> list[np.ndarray]: |
| 45 | + """Unflattens flat array to ragged array. |
| 46 | +
|
| 47 | + Parameters |
| 48 | + ---------- |
| 49 | + flat_embeddings: ndarray |
| 50 | + Flattened embedding array. |
| 51 | + lengths: list[int] |
| 52 | + Length of each document in the corpus. |
| 53 | +
|
| 54 | + Returns |
| 55 | + ------- |
| 56 | + embeddings: list[ndarray] |
| 57 | + Ragged embedding array. |
| 58 | +
|
| 59 | + """ |
| 60 | + embeddings = [] |
| 61 | + start_index = 0 |
| 62 | + for length in lengths: |
| 63 | + embeddings.append(flat_embeddings[start_index:length]) |
| 64 | + start_index += length |
| 65 | + return embeddings |
| 66 | + |
| 67 | + |
| 68 | +class ContextTransformer(SentenceTransformer): |
| 69 | + def encode( |
| 70 | + self, sentences: Union[str, list[str], np.ndarray], *args, **kwargs |
| 71 | + ): |
| 72 | + warnings.warn( |
| 73 | + "Encoder is contextual but topic model is not using contextual embeddings. Perhaps you wanted to use another topic model." |
| 74 | + ) |
| 75 | + return super().encode(sentences, *args, **kwargs) |
| 76 | + |
| 77 | + def _encode_tokens( |
| 78 | + self, |
| 79 | + texts, |
| 80 | + batch_size=32, |
| 81 | + show_progress_bar=True, |
| 82 | + ) -> tuple[list[np.ndarray], list[Offsets]]: |
| 83 | + """ |
| 84 | + Returns |
| 85 | + ------- |
| 86 | + token_embeddings: list[np.ndarray] |
| 87 | + Embedding matrix of tokens for each document. |
| 88 | + offsets: list[list[tuple[int, int]]] |
| 89 | + Start and end character of each token in each document. |
| 90 | + """ |
| 91 | + token_embeddings = [] |
| 92 | + offsets = [] |
| 93 | + tokenizer = Tokenizer.from_pretrained(self.model_card_data.base_model) |
| 94 | + for start_index in trange( |
| 95 | + 0, |
| 96 | + len(texts), |
| 97 | + batch_size, |
| 98 | + disable=not show_progress_bar, |
| 99 | + desc="Encoding tokens...", |
| 100 | + ): |
| 101 | + batch = texts[start_index : start_index + batch_size] |
| 102 | + features = self.tokenize(batch) |
| 103 | + with torch.no_grad(): |
| 104 | + output_features = self.forward(features) |
| 105 | + n_tokens = output_features["attention_mask"].sum(axis=1) |
| 106 | + # Find first nonzero elements in each document |
| 107 | + # The document could be padded from the left, so we have to watch out for this. |
| 108 | + start_token = torch.argmax( |
| 109 | + (output_features["attention_mask"] > 0).to(torch.long), axis=1 |
| 110 | + ) |
| 111 | + end_token = start_token + n_tokens |
| 112 | + for i_doc in range(len(batch)): |
| 113 | + _token_embeddings = output_features["token_embeddings"][ |
| 114 | + i_doc, start_token[i_doc] : end_token[i_doc], : |
| 115 | + ].numpy(force=True) |
| 116 | + _offsets = tokenizer.encode(batch[i_doc]).offsets |
| 117 | + token_embeddings.append(_token_embeddings) |
| 118 | + offsets.append(_offsets) |
| 119 | + return token_embeddings, offsets |
| 120 | + |
| 121 | + def encode_tokens( |
| 122 | + self, |
| 123 | + sentences: list[str], |
| 124 | + batch_size: int = 32, |
| 125 | + show_progress_bar: bool = True, |
| 126 | + ): |
| 127 | + """Produces contextual token embeddings over all documents. |
| 128 | +
|
| 129 | + Parameters |
| 130 | + ---------- |
| 131 | + sentences: list[str] |
| 132 | + Documents to encode contextually. |
| 133 | + batch_size: int, default 32 |
| 134 | + Size of the batch of document to encode at once. |
| 135 | + show_progress_bar: bool, default True |
| 136 | + Indicates whether a progress bar should be displayed when encoding. |
| 137 | +
|
| 138 | + Returns |
| 139 | + ------- |
| 140 | + token_embeddings: list[np.ndarray] |
| 141 | + Embedding matrix of tokens for each document. |
| 142 | + offsets: list[list[tuple[int, int]]] |
| 143 | + Start and end character of each token in each document. |
| 144 | + """ |
| 145 | + # This is needed because the above implementation does not normalize embeddings, |
| 146 | + # which normally happens to document embeddings. |
| 147 | + token_embeddings, offsets = self._encode_tokens( |
| 148 | + sentences, |
| 149 | + batch_size=batch_size, |
| 150 | + show_progress_bar=show_progress_bar, |
| 151 | + ) |
| 152 | + token_embeddings = [normalize(emb) for emb in token_embeddings] |
| 153 | + return token_embeddings, offsets |
| 154 | + |
| 155 | + def encode_windows( |
| 156 | + self, |
| 157 | + sentences: list[str], |
| 158 | + batch_size: int = 32, |
| 159 | + window_size: int = 50, |
| 160 | + step_size: int = 40, |
| 161 | + show_progress_bar: bool = True, |
| 162 | + ): |
| 163 | + """Produces contextual embeddings for a sliding window of tokens similar to C-Top2Vec. |
| 164 | +
|
| 165 | + Parameters |
| 166 | + ---------- |
| 167 | + sentences: list[str] |
| 168 | + Documents to encode contextually. |
| 169 | + batch_size: int, default 32 |
| 170 | + Size of the batch of document to encode at once. |
| 171 | + window_size: int, default 50 |
| 172 | + Size of the sliding window. |
| 173 | + step_size: int, default 40 |
| 174 | + Step size of the window. |
| 175 | + If step_size < window_size, windows will overlap. |
| 176 | + If step_size == window_size, then windows are separate. |
| 177 | + If step_size > window_size, there will be gaps between the windows. |
| 178 | + In this case, we throw a warning, as this is probably unintended behaviour. |
| 179 | + show_progress_bar: bool, default True |
| 180 | + Indicates whether a progress bar should be displayed when encoding. |
| 181 | +
|
| 182 | + Returns |
| 183 | + ------- |
| 184 | + window_embeddings: list[np.ndarray] |
| 185 | + Embedding matrix of windows for each document. |
| 186 | + offsets: list[list[tuple[int, int]]] |
| 187 | + Start and end character of each token in each document. |
| 188 | + """ |
| 189 | + token_embeddings, token_offsets = self._encode_tokens( |
| 190 | + sentences, |
| 191 | + batch_size=batch_size, |
| 192 | + show_progress_bar=show_progress_bar, |
| 193 | + ) |
| 194 | + window_embeddings = [] |
| 195 | + window_offsets = [] |
| 196 | + for emb, offs in zip(token_embeddings, token_offsets): |
| 197 | + _offsets = [] |
| 198 | + _embeddings = [] |
| 199 | + for start_index in trange(0, len(emb), step_size): |
| 200 | + end_index = start_index + window_size |
| 201 | + window_emb = np.mean(emb[start_index:end_index], axis=0) |
| 202 | + _embeddings.append(window_emb) |
| 203 | + _offsets.append((offs[start_index][0], offs[end_index][1])) |
| 204 | + window_embeddings.append(normalize(np.stack(_embeddings))) |
| 205 | + window_offsets.append(_offsets) |
| 206 | + return window_embeddings, window_offsets |
0 commit comments