Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions docs/DSL.md
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions docs/model_overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -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* |
Expand Down Expand Up @@ -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: |
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 40 additions & 0 deletions tests/test_dsl.py
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 2 additions & 0 deletions turftopic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -49,4 +50,5 @@
"LDA",
"NMF",
"LateCVP",
"DSL",
]
2 changes: 2 additions & 0 deletions turftopic/encoders/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
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__ = [
"CohereEmbeddings",
"OpenAIEmbeddings",
"VoyageEmbeddings",
"ExternalEncoder",
"SoftLabelEncoder",
]
Loading
Loading