From 64c4d31b1778cbce19ddcf7c2e0ac619523b42b4 Mon Sep 17 00:00:00 2001 From: Raymond Li <15968818+raymondzmc@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:18:52 -0700 Subject: [PATCH] Add DSL: topic model trained on soft labels from a language model DSL (Li et al., ICML 2026) replaces the bag-of-words reconstruction target with the next-token distribution of a small causal language model that is asked for the document's theme, and uses the model's last hidden state as the document representation. - SoftLabelEncoder: an ExternalEncoder that returns the hidden states, and the vocabulary logits from the same forward pass - DSL: a ProdLDA-style autoencoder trained with KL to the soft labels - docs page with citation, model overview rows, tests on a tiny random model --- docs/DSL.md | 90 ++++++++++ docs/model_overview.md | 2 + mkdocs.yml | 1 + tests/test_dsl.py | 40 +++++ turftopic/__init__.py | 2 + turftopic/encoders/__init__.py | 2 + turftopic/encoders/soft_labels.py | 247 ++++++++++++++++++++++++++ turftopic/models/dsl.py | 283 ++++++++++++++++++++++++++++++ 8 files changed, 667 insertions(+) create mode 100644 docs/DSL.md create mode 100644 tests/test_dsl.py create mode 100644 turftopic/encoders/soft_labels.py create mode 100644 turftopic/models/dsl.py diff --git a/docs/DSL.md b/docs/DSL.md new file mode 100644 index 00000000..fd3355cc --- /dev/null +++ b/docs/DSL.md @@ -0,0 +1,90 @@ +# DSL (Distilling Soft Labels) + +DSL (Li et al., 2026) is a way of training neural topic models on targets produced by a small language model, instead of on bag-of-words. + +A causal language model reads each document inside a short prompt that asks for its theme. +The label is never generated. Instead, DSL keeps two things from that single forward pass: + + 1. The next-token distribution at the end of the prompt, restricted to the vocabulary and softened with a temperature. This **soft label** replaces the bag-of-words vector as the reconstruction target. + 2. The last hidden state at the end of the prompt. This replaces sentence embeddings as the document representation. + +Bag-of-words targets can only give weight to words that occur in a document. +A soft label also gives weight to theme words that the document never uses, such as "hockey" for a post about a trade rumour, which matters most for short texts. + +The topic model in Turftopic's implementation is a ProdLDA-style variational autoencoder, and its loss is the KL divergence between the soft label and the reconstruction, plus the usual prior term. +The paper applies the same target to ECRTM and FASTopic as well. + +## Usage + +```python +from turftopic import DSL + +documents = [...] + +model = DSL(20) +doc_topic_matrix = model.fit_transform(documents) +model.print_topics() +``` + +The language model is run once over the corpus. A GPU is recommended for this step; the default teacher has 0.3B parameters. +You can choose another causal language model from the Hugging Face Hub, or configure the teacher yourself: + +```python +from turftopic import DSL +from turftopic.encoders import SoftLabelEncoder + +teacher = SoftLabelEncoder("Qwen/Qwen3.5-0.8B", batch_size=32, max_length=512) +model = DSL(20, encoder=teacher) +``` + +The teacher's outputs can be computed once and reused across models: + +```python +model = DSL(20, encoder=teacher) +model.vectorizer.fit(documents) +logits, hidden_states, _ = teacher.extract(documents, list(model.get_vocab())) + +model.fit(documents, embeddings=hidden_states, logits=logits) +``` + +!!! note + Only vocabulary words that are a single alphabetic token for the language model are part of the soft label. + The default vectorizer keeps the 2000 most frequent non-stop words; phrase vectorizers are not a good fit for this model. + +## Citation + +Please cite the authors of the paper, and Turftopic when using the DSL model: + +```bibtex +@inproceedings{li2026dsltopic, + title = {Improving Topic Modeling by Distilling Soft Labels from Language Models}, + author = {Li, Raymond and Abaskohi, Amirhossein and Li, Chuyuan and Murray, Gabriel and Carenini, Giuseppe}, + booktitle = {Proceedings of the 43rd International Conference on Machine Learning}, + pages = {65815--65836}, + year = {2026}, + volume = {306}, + series = {Proceedings of Machine Learning Research}, + publisher = {PMLR}, + url = {https://proceedings.mlr.press/v306/li26a.html} +} + +@article{ + Kardos2025, + title = {Turftopic: Topic Modelling with Contextual Representations from Sentence Transformers}, + doi = {10.21105/joss.08183}, + url = {https://doi.org/10.21105/joss.08183}, + year = {2025}, + publisher = {The Open Journal}, + volume = {10}, + number = {111}, + pages = {8183}, + author = {Kardos, Márton and Enevoldsen, Kenneth C. and Kostkan, Jan and Kristensen-McLachlan, Ross Deans and Rocca, Roberta}, + journal = {Journal of Open Source Software} +} +``` + +## API Reference + +::: turftopic.models.dsl.DSL + +::: turftopic.encoders.soft_labels.SoftLabelEncoder diff --git a/docs/model_overview.md b/docs/model_overview.md index 0a8c8043..60bd2c62 100644 --- a/docs/model_overview.md +++ b/docs/model_overview.md @@ -28,6 +28,7 @@ It is quite important that you choose the right topic model for your use case. | [vSLDA](vSLDA.md) | Reconstruct token/window/sentence representations using von-Mises components. | Contextual understanding, theoretical correctness | Manual n-topics, Can be slow with too granular representations | | *Neural Models* | | | | | [FASTopic](FASTopic.md) | Neural topic modelling with Dual Semantic-relation Reconstruction | High quality topics and clusters, GPU support | Very slow, Memory hungry, Manual n-topics | +| [DSL](DSL.md) | Autoencoding topic model that reconstructs soft labels from a small language model instead of bag-of-words | Topic-label agreement on short texts, GPU support, Inference over new documents | Needs one language model pass over the corpus, Manual n-topics, Unigram vocabulary | | [AutoEncodingTopicModel](ctm.md) | Discover topics by generating BoW with a variational autoencoder | GPU-support | Slow, Sometimes low quality topics | | *Clustering Models* | | | | | [ClusteringTopicModel](clustering.md) | Embed -> Reduce -> Cluster | Flexible, many featuress | *Highly depends on construction* | @@ -63,6 +64,7 @@ Some models are also capable of being used in a dynamic context, some can be fit | **[GMM](GMM.md)** | :heavy_check_mark: | :x: | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | | **[AutoEncodingTopicModel](ctm.md)** | :heavy_check_mark: | :x: | :x: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | | **[FASTopic](fastopic.md)** | :heavy_check_mark: | :x: | :x: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | +| **[DSL](DSL.md)** | :heavy_check_mark: | :x: | :x: | :x: | :heavy_check_mark: | :x: | :x: | | [C-Top2Vec](clustering.md) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :x: | :heavy_check_mark: | :x: | | **[LDA](LDA.md)** | :heavy_check_mark: | :x: | :x: | :x: | :heavy_check_mark: | :x: | :x: | | **[NMF](NMF.md)** | :heavy_check_mark: | :x: | :x: | :x: | :heavy_check_mark: | :x: | :x: | diff --git a/mkdocs.yml b/mkdocs.yml index 3026a1d8..ce8884fb 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -44,6 +44,7 @@ nav: - Neural Models: - Autoencoding Models (ZeroShotTM & CombinedTM): ctm.md - FASTopic: FASTopic.md + - DSL: DSL.md - Bag-of-words Models: - LDA: LDA.md - NMF: NMF.md diff --git a/tests/test_dsl.py b/tests/test_dsl.py new file mode 100644 index 00000000..c86362bf --- /dev/null +++ b/tests/test_dsl.py @@ -0,0 +1,40 @@ +import numpy as np + +from turftopic import DSL +from turftopic.encoders import SoftLabelEncoder + +DOCS = [ + "the hockey team won the game in overtime last night", + "the senate passed the budget bill after a long debate", + "new graphics card drivers improve game performance on windows", + "the patient was given antibiotics for the infection", +] * 6 + + +def test_dsl_fit_transform_and_export(): + teacher = SoftLabelEncoder( + "sshleifer/tiny-gpt2", batch_size=8, device="cpu" + ) + model = DSL(3, encoder=teacher, n_epochs=2, random_state=0) + doc_topic = model.fit_transform(DOCS) + assert doc_topic.shape == (len(DOCS), 3) + assert np.allclose(doc_topic.sum(1), 1, atol=1e-4) + assert model.components_.shape == (3, len(model.get_vocab())) + assert model.transform(DOCS[:2]).shape == (2, 3) + topic_data = model.prepare_topic_data(DOCS) + assert topic_data.document_topic_matrix.shape == (len(DOCS), 3) + assert len(model.get_top_words()) == 3 + + +def test_dsl_accepts_precomputed_teacher_outputs(): + teacher = SoftLabelEncoder( + "sshleifer/tiny-gpt2", batch_size=8, device="cpu" + ) + model = DSL(3, encoder=teacher, n_epochs=1, random_state=0) + model.vectorizer.fit(DOCS) + logits, hidden, _ = teacher.extract(DOCS, list(model.get_vocab())) + first = model.fit_transform(DOCS, embeddings=hidden, logits=logits) + second = DSL(3, encoder=teacher, n_epochs=1, random_state=0).fit_transform( + DOCS, embeddings=hidden, logits=logits + ) + assert np.allclose(first, second, atol=1e-5) diff --git a/turftopic/__init__.py b/turftopic/__init__.py index 8170fe0d..c5027d31 100644 --- a/turftopic/__init__.py +++ b/turftopic/__init__.py @@ -12,6 +12,7 @@ ) from turftopic.models.cvp import ConceptVectorProjection, LateCVP from turftopic.models.decomp import S3, SemanticSignalSeparation +from turftopic.models.dsl import DSL from turftopic.models.fastopic import FASTopic from turftopic.models.gmm import GMM from turftopic.models.keynmf import KeyNMF @@ -49,4 +50,5 @@ "LDA", "NMF", "LateCVP", + "DSL", ] diff --git a/turftopic/encoders/__init__.py b/turftopic/encoders/__init__.py index 9c89a74c..f52a5298 100644 --- a/turftopic/encoders/__init__.py +++ b/turftopic/encoders/__init__.py @@ -1,6 +1,7 @@ from turftopic.encoders.base import ExternalEncoder from turftopic.encoders.cohere import CohereEmbeddings from turftopic.encoders.openai import OpenAIEmbeddings +from turftopic.encoders.soft_labels import SoftLabelEncoder from turftopic.encoders.voyage import VoyageEmbeddings __all__ = [ @@ -8,4 +9,5 @@ "OpenAIEmbeddings", "VoyageEmbeddings", "ExternalEncoder", + "SoftLabelEncoder", ] diff --git a/turftopic/encoders/soft_labels.py b/turftopic/encoders/soft_labels.py new file mode 100644 index 00000000..611ce954 --- /dev/null +++ b/turftopic/encoders/soft_labels.py @@ -0,0 +1,247 @@ +"""Language-model teacher for soft-label distillation (DSL).""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Iterable, Optional, Sequence + +import numpy as np +import torch + +from turftopic.encoders.base import ExternalEncoder + +DEFAULT_INSTRUCTION = ( + "Generate a label that captures the overall theme of the document below." +) +DEFAULT_TEMPLATE = "{instruction}\n\nDocument: {document}\n\nTopic:" + + +@dataclass +class VocabularyMap: + """How vocabulary words map onto LM tokens.""" + + token_ids: np.ndarray # (n_vocab,) id of the first token of " word" + single_token: np.ndarray # (n_vocab,) bool, the word is exactly one token + + +def map_vocabulary(tokenizer, vocabulary: Sequence[str]) -> VocabularyMap: + """Find the token that starts each vocabulary word when it follows a space. + + Words made of one token are scored exactly. Words made of several tokens are + scored by their first token, which is only an approximation, so `single_token` + marks the words whose score is exact. `soft_labels` leaves the others out. + """ + pieces = [ + tokenizer.encode(f" {word}", add_special_tokens=False) + for word in vocabulary + ] + if any(len(p) == 0 for p in pieces): + raise ValueError("A vocabulary word produced no tokens.") + # SentencePiece tokenizers that emit a stand-alone space token before every word: + # the distinguishing token is then the second one. + first = {p[0] for p in pieces} + offset = ( + 1 + if ( + len(first) == 1 + and len(pieces) > 1 + and all(len(p) > 1 for p in pieces) + ) + else 0 + ) + token_ids = np.array([p[offset] for p in pieces], dtype=np.int64) + single = np.array( + [ + len(p) == offset + 1 and word.isalpha() + for p, word in zip(pieces, vocabulary) + ], + dtype=bool, + ) + return VocabularyMap(token_ids=token_ids, single_token=single) + + +def build_prompts( + documents: Iterable[str], + tokenizer, + instruction: str = DEFAULT_INSTRUCTION, + template: str = DEFAULT_TEMPLATE, + max_length: Optional[int] = None, +) -> list[str]: + """Render one prompt per document; shorten the document if the prompt is too long. + + Truncating the tokenized prompt would cut off its end ("Topic:"), which is the + position we read from, so the document text is shortened instead. + """ + prompts = [] + for document in documents: + prompt = template.format( + instruction=instruction, document=document + ).rstrip() + if max_length is not None: + n_tokens = len(tokenizer.encode(prompt)) + if n_tokens > max_length: + overhead = len( + tokenizer.encode( + template.format( + instruction=instruction, document="" + ).rstrip() + ) + ) + budget = max(max_length - overhead - 2, 1) + doc_ids = tokenizer.encode(document, add_special_tokens=False)[ + :budget + ] + shortened = tokenizer.decode(doc_ids, skip_special_tokens=True) + prompt = template.format( + instruction=instruction, document=shortened + ).rstrip() + prompts.append(prompt) + return prompts + + +class SoftLabelEncoder(ExternalEncoder): + """Causal language model that yields a document embedding and a soft label. + + The document is placed in a prompt that asks for its theme. The embedding is the + last-layer hidden state at the end of the prompt, and the soft label is the + next-token distribution at that position, restricted to a vocabulary. + + Parameters + ---------- + model_name: str, default "baidu/ERNIE-4.5-0.3B-PT" + Any causal language model on the Hugging Face Hub. + instruction: str + Instruction placed before the document. + template: str + Prompt template with `{instruction}` and `{document}`. + batch_size: int, default 16 + Documents per forward pass. + max_length: int, default 512 + Longer prompts have their document shortened (the end of the prompt is kept). + device: str, default None + Defaults to CUDA when available. + """ + + def __init__( + self, + model_name: str = "baidu/ERNIE-4.5-0.3B-PT", + instruction: str = DEFAULT_INSTRUCTION, + template: str = DEFAULT_TEMPLATE, + batch_size: int = 16, + max_length: Optional[int] = 512, + device: Optional[str] = None, + dtype: Optional[torch.dtype] = None, + trust_remote_code: bool = False, + ): + from transformers import AutoModelForCausalLM, AutoTokenizer + + self.model_name = model_name + self.instruction = instruction + self.template = template + self.batch_size = batch_size + self.max_length = max_length + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + self.device = torch.device(device) + if dtype is None: + dtype = ( + torch.bfloat16 if self.device.type == "cuda" else torch.float32 + ) + self.tokenizer = AutoTokenizer.from_pretrained( + model_name, trust_remote_code=trust_remote_code + ) + if self.tokenizer.pad_token_id is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + # Left padding keeps the last real token at position -1 for every row. + self.tokenizer.padding_side = "left" + self.model = ( + AutoModelForCausalLM.from_pretrained( + model_name, + torch_dtype=dtype, + trust_remote_code=trust_remote_code, + ) + .eval() + .to(self.device) + ) + + def encode(self, sentences: Iterable[str]) -> np.ndarray: + """Document embeddings: the last hidden state at the end of the prompt.""" + return self.extract(list(sentences), [])[1] + + @torch.no_grad() + def extract( + self, + documents: Sequence[str], + vocabulary: Sequence[str], + progress=None, + ): + """Return (logits, hidden): arrays of shape (n_docs, n_vocab) and (n_docs, hidden_size).""" + if len(vocabulary): + vocab_map = map_vocabulary(self.tokenizer, vocabulary) + else: + vocab_map = VocabularyMap( + np.zeros(0, dtype=np.int64), np.zeros(0, dtype=bool) + ) + token_ids = torch.as_tensor(vocab_map.token_ids, device=self.device) + prompts = build_prompts( + documents, + self.tokenizer, + self.instruction, + self.template, + self.max_length, + ) + lengths = [len(self.tokenizer.encode(p)) for p in prompts] + order = np.argsort(lengths)[ + ::-1 + ] # longest first: an out-of-memory error shows up at once + logits = np.empty((len(prompts), len(vocabulary)), dtype=np.float32) + hidden = None + for start in range(0, len(order), self.batch_size): + rows = order[start : start + self.batch_size] + batch = self.tokenizer( + [prompts[i] for i in rows], return_tensors="pt", padding=True + ) + batch = { + k: v.to(self.device) + for k, v in batch.items() + if k in ("input_ids", "attention_mask") + } + out = self.model( + **batch, use_cache=False, output_hidden_states=True + ) + last_logits = ( + out.logits[:, -1, :] + .index_select(-1, token_ids) + .float() + .cpu() + .numpy() + ) + last_hidden = out.hidden_states[-1][:, -1, :].float().cpu().numpy() + if hidden is None: + hidden = np.empty( + (len(prompts), last_hidden.shape[-1]), dtype=np.float32 + ) + logits[rows] = last_logits + hidden[rows] = last_hidden + if progress is not None: + progress(min(start + self.batch_size, len(order)), len(order)) + return logits, hidden, vocab_map + + +def soft_labels(logits, temperature=3.0, mask=None): + """softmax(logits / temperature) over the vocabulary, row-wise. + + `mask` (bool, one entry per word) selects the words that take part; the others + get zero. Pass `VocabularyMap.single_token` to keep exactly scored words only. + """ + z = np.asarray(logits, dtype=np.float64) / temperature + if mask is not None and not np.all(mask): + if not np.any(mask): + raise ValueError( + "No vocabulary word is a single alphabetic token for this language model." + ) + z = np.where(np.asarray(mask)[None, :], z, -np.inf) + z = z - z.max(axis=1, keepdims=True) + p = np.exp(z) + p /= p.sum(axis=1, keepdims=True) + return p.astype(np.float32) diff --git a/turftopic/models/dsl.py b/turftopic/models/dsl.py new file mode 100644 index 00000000..a34cae46 --- /dev/null +++ b/turftopic/models/dsl.py @@ -0,0 +1,283 @@ +from typing import Optional, Union + +import numpy as np +import torch +import torch.nn as nn +from rich.console import Console +from sklearn.feature_extraction.text import CountVectorizer + +from turftopic.base import ContextualModel +from turftopic.encoders.soft_labels import ( + SoftLabelEncoder, + map_vocabulary, + soft_labels, +) + + +class _Network(nn.Module): + """ProdLDA-style variational autoencoder over language-model embeddings.""" + + def __init__(self, input_size, vocab_size, n_components, hidden, dropout): + super().__init__() + self.encoder = nn.Sequential( + nn.Linear(input_size, hidden), + nn.Softplus(), + nn.Linear(hidden, hidden), + nn.Softplus(), + nn.Dropout(dropout), + ) + self.f_mu = nn.Linear(hidden, n_components) + self.f_mu_bn = nn.BatchNorm1d(n_components, affine=False) + self.f_sigma = nn.Linear(hidden, n_components) + self.f_sigma_bn = nn.BatchNorm1d(n_components, affine=False) + self.prior_mean = nn.Parameter(torch.zeros(n_components)) + self.prior_variance = nn.Parameter( + torch.full((n_components,), 1.0 - 1.0 / n_components) + ) + self.beta = nn.Parameter( + nn.init.xavier_uniform_(torch.empty(n_components, vocab_size)) + ) + self.beta_bn = nn.BatchNorm1d(vocab_size, affine=False) + self.theta_dropout = nn.Dropout(dropout) + + def encode(self, x): + h = self.encoder(x) + return self.f_mu_bn(self.f_mu(h)), self.f_sigma_bn(self.f_sigma(h)) + + def forward(self, x, temperature): + mu, log_var = self.encode(x) + z = mu + torch.randn_like(mu) * torch.exp(0.5 * log_var) + theta = self.theta_dropout(torch.softmax(z, dim=1)) + word_dist = torch.softmax( + self.beta_bn(theta @ self.beta) / temperature, dim=1 + ) + return word_dist, mu, log_var + + def prior_kl(self, mu, log_var): + var = log_var.exp() + return 0.5 * ( + (var / self.prior_variance).sum(1) + + ((self.prior_mean - mu) ** 2 / self.prior_variance).sum(1) + - mu.shape[1] + + self.prior_variance.log().sum() + - log_var.sum(1) + ) + + +class DSL(ContextualModel): + """Topic model trained by Distilling Soft Labels from a language model + (Li et al., 2026). + + A small causal language model reads each document in a prompt that asks for its + theme. Its next-token distribution over the vocabulary is the reconstruction target + (instead of the bag-of-words), and its last hidden state is the document + representation. The topic model itself is a ProdLDA-style autoencoder. + + ```python + from turftopic import DSL + + corpus: list[str] = ["some text", "more text", ...] + + model = DSL(10).fit(corpus) + model.print_topics() + ``` + + Parameters + ---------- + n_components: int + Number of topics. + encoder: str or SoftLabelEncoder + Causal language model used as the teacher, + ERNIE-4.5-0.3B is the default. + vectorizer: CountVectorizer, default None + Vectorizer used for term extraction. + Defaults to the 2000 most frequent non-stop words. + Only words that are a single alphabetic token for the language model + are part of the soft labels, so unigram vocabularies work best. + temperature: float, default 3.0 + Softmax temperature of the soft labels. + loss_weight: float, default 1000.0 + Weight of the distillation term against the prior term. + hidden: int, default 200 + Units in each of the two encoder layers. + dropout_rate: float, default 0.2 + Dropout in the encoder and on topic proportions. + batch_size: int, default 64 + Batch size. + learning_rate: float, default 2e-3 + Learning rate of Adam. + n_epochs: int, default 100 + Number of training epochs. + random_state: int, default None + Random state for reproducible training. + device: str, default "cpu" + Device to train the topic model on. + """ + + def __init__( + self, + n_components: int, + encoder: Union[SoftLabelEncoder, str] = "baidu/ERNIE-4.5-0.3B-PT", + vectorizer: Optional[CountVectorizer] = None, + temperature: float = 3.0, + loss_weight: float = 1000.0, + hidden: int = 200, + dropout_rate: float = 0.2, + batch_size: int = 64, + learning_rate: float = 2e-3, + n_epochs: int = 100, + random_state: Optional[int] = None, + device: str = "cpu", + trf_kwargs=None, + encode_kwargs=None, + ): + self.n_components = n_components + self.encoder = encoder + self.trf_kwargs = trf_kwargs + self.encode_kwargs = encode_kwargs + self.random_state = random_state + if isinstance(encoder, str): + self.encoder_ = SoftLabelEncoder(encoder, **(trf_kwargs or {})) + self._encoder_preloaded = False + else: + self.encoder_ = encoder + self._encoder_preloaded = True + if vectorizer is None: + self.vectorizer = CountVectorizer( + max_features=2000, + stop_words="english", + token_pattern=r"(?u)\b[a-zA-Z]{3,}\b", + ) + else: + self.vectorizer = vectorizer + self.temperature = temperature + self.loss_weight = loss_weight + self.hidden = hidden + self.dropout_rate = dropout_rate + self.batch_size = batch_size + self.learning_rate = learning_rate + self.n_epochs = n_epochs + self.device = device + + def fit_transform( + self, + raw_documents, + y=None, + embeddings: Optional[np.ndarray] = None, + logits: Optional[np.ndarray] = None, + ) -> np.ndarray: + """Fits the model and returns the document-topic matrix. + + Parameters + ---------- + raw_documents: iterable of str + Documents to fit the model on. + embeddings: ndarray of shape (n_documents, n_dimensions), optional + Precomputed hidden states from the teacher. + logits: ndarray of shape (n_documents, n_vocab), optional + Precomputed teacher logits over the vectorizer's vocabulary. + """ + console = Console() + raw_documents = list(raw_documents) + with console.status("Fitting model") as status: + status.update("Extracting terms.") + self.vectorizer.fit(raw_documents) + vocab = self.get_vocab() + console.log("Term extraction done.") + if embeddings is None or logits is None: + status.update("Running the language model") + logits, embeddings, _ = self.encoder_.extract( + raw_documents, list(vocab) + ) + console.log("Soft labels and embeddings extracted.") + # Words that are not one alphabetic token for the language model + # cannot be scored exactly, and are left out of the target. + scored = map_vocabulary( + self.encoder_.tokenizer, list(vocab) + ).single_token + targets = soft_labels(logits, self.temperature, mask=scored) + if self.random_state is not None: + torch.manual_seed(self.random_state) + self.model = _Network( + embeddings.shape[1], + len(vocab), + self.n_components, + self.hidden, + self.dropout_rate, + ).to(self.device) + optimizer = torch.optim.Adam( + self.model.parameters(), + lr=self.learning_rate, + betas=(0.99, 0.99), + ) + x_all = torch.as_tensor(np.asarray(embeddings)).float() + y_all = torch.as_tensor(targets).float() + generator = torch.Generator() + if self.random_state is not None: + generator.manual_seed(self.random_state) + self.model.train() + for epoch in range(self.n_epochs): + order = torch.randperm(len(x_all), generator=generator) + running, seen = 0.0, 0 + for start in range(0, len(order), self.batch_size): + idx = order[start : start + self.batch_size] + if len(idx) < 2: + continue + x = x_all[idx].to(self.device) + target = y_all[idx].to(self.device).clamp_min(1e-9) + optimizer.zero_grad() + word_dist, mu, log_var = self.model(x, self.temperature) + distill = ( + target * (target / word_dist.clamp_min(1e-9)).log() + ).sum(1) + loss = ( + self.model.prior_kl(mu, log_var) + + self.loss_weight * distill + ).sum() + loss.backward() + optimizer.step() + running += loss.item() + seen += len(idx) + status.update( + f"Fitting model. Epoch [{epoch + 1}/{self.n_epochs}], " + f"loss [{running / max(seen, 1):.2f}]" + ) + self.components_ = self.model.beta.detach().cpu().numpy() + console.log("Model fitting done.") + doc_topic_matrix = self.transform( + raw_documents, embeddings=embeddings + ) + self.top_documents = self.get_top_documents( + raw_documents, document_topic_matrix=doc_topic_matrix + ) + return doc_topic_matrix + + def transform( + self, raw_documents, embeddings: Optional[np.ndarray] = None + ) -> np.ndarray: + """Infers topic proportions of documents. + + Parameters + ---------- + raw_documents: iterable of str + Documents to infer topics for. + embeddings: ndarray of shape (n_documents, n_dimensions), optional + Precomputed hidden states from the teacher. + + Returns + ------- + ndarray of shape (n_documents, n_topics) + Document-topic matrix. + """ + if embeddings is None: + embeddings = self.encoder_.encode(list(raw_documents)) + self.model.eval() + chunks = [] + with torch.no_grad(): + x_all = torch.as_tensor(np.asarray(embeddings)).float() + for start in range(0, len(x_all), 1024): + mu, _ = self.model.encode( + x_all[start : start + 1024].to(self.device) + ) + chunks.append(torch.softmax(mu, dim=1).cpu().numpy()) + return np.concatenate(chunks, axis=0)