Skip to content

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.

Usage

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:

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:

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:

@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

Bases: 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.

from turftopic import DSL

corpus: list[str] = ["some text", "more text", ...]

model = DSL(10).fit(corpus)
model.print_topics()

Parameters:

Name Type Description Default
n_components int

Number of topics.

required
encoder Union[SoftLabelEncoder, str]

Causal language model used as the teacher, ERNIE-4.5-0.3B is the default.

'baidu/ERNIE-4.5-0.3B-PT'
vectorizer Optional[CountVectorizer]

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.

None
temperature float

Softmax temperature of the soft labels.

3.0
loss_weight float

Weight of the distillation term against the prior term.

1000.0
hidden int

Units in each of the two encoder layers.

200
dropout_rate float

Dropout in the encoder and on topic proportions.

0.2
batch_size int

Batch size.

64
learning_rate float

Learning rate of Adam.

0.002
n_epochs int

Number of training epochs.

100
random_state Optional[int]

Random state for reproducible training.

None
device str

Device to train the topic model on.

'cpu'
Source code in turftopic/models/dsl.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
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)

fit_transform(raw_documents, y=None, embeddings=None, logits=None)

Fits the model and returns the document-topic matrix.

Parameters:

Name Type Description Default
raw_documents

Documents to fit the model on.

required
embeddings Optional[ndarray]

Precomputed hidden states from the teacher.

None
logits Optional[ndarray]

Precomputed teacher logits over the vectorizer's vocabulary.

None
Source code in turftopic/models/dsl.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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

transform(raw_documents, embeddings=None)

Infers topic proportions of documents.

Parameters:

Name Type Description Default
raw_documents

Documents to infer topics for.

required
embeddings Optional[ndarray]

Precomputed hidden states from the teacher.

None

Returns:

Type Description
ndarray of shape (n_documents, n_topics)

Document-topic matrix.

Source code in turftopic/models/dsl.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
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)

turftopic.encoders.soft_labels.SoftLabelEncoder

Bases: 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:

Name Type Description Default
model_name str

Any causal language model on the Hugging Face Hub.

'baidu/ERNIE-4.5-0.3B-PT'
instruction str

Instruction placed before the document.

DEFAULT_INSTRUCTION
template str

Prompt template with {instruction} and {document}.

DEFAULT_TEMPLATE
batch_size int

Documents per forward pass.

16
max_length Optional[int]

Longer prompts have their document shortened (the end of the prompt is kept).

512
device Optional[str]

Defaults to CUDA when available.

None
Source code in turftopic/encoders/soft_labels.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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

encode(sentences)

Document embeddings: the last hidden state at the end of the prompt.

Source code in turftopic/encoders/soft_labels.py
167
168
169
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]

extract(documents, vocabulary, progress=None)

Return (logits, hidden): arrays of shape (n_docs, n_vocab) and (n_docs, hidden_size).

Source code in turftopic/encoders/soft_labels.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
@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