Skip to content

fix: respect top_n_words in MMR fallback and surface its warning - #2552

Open
tintape wants to merge 1 commit into
MaartenGr:masterfrom
tintape:fix/mmr-fallback-top-n-words
Open

tintape wants to merge 1 commit into
MaartenGr:masterfrom
tintape:fix/mmr-fallback-top-n-words

Conversation

@tintape

@tintape tintape commented Oct 23, 2026

Copy link
Copy Markdown

What does this PR do?

Fixes #2323. Root-cause analysis: #2323 (comment)

When BERTopic is fitted with precomputed embeddings and no embedding_model, MaximalMarginalRelevance cannot run and falls back to the c-TF-IDF words. Two things went wrong in that fallback:

  1. Too many words. _extract_words_per_topic passes at least 30 candidate words to representation models (max(self.top_n_words, 30)), and the fallback returned them untruncated. That is why update_topics with MMR gave 30+ words regardless of top_n_words.
  2. Invisible warning. The fallback used warnings.warn(...), which raises a UserWarning. _bertopic.py sets warnings.filterwarnings("ignore", category=UserWarning) at import time, so the warning never showed up. This explains why it "should fire a warning, but in my tests it doesn't". The message also lacked a space (instantiatedwith).

Changes

  • Truncate the fallback output to self.top_n_words, the same way the regular MMR path limits its output.
  • Log the warning through MyLogger, like the other warnings in the package (_utils.py, backend/_utils.py), so the module-level filter no longer hides it. Fix the wording.
  • Add tests/test_representation/test_mmr.py, a fast regression test with no model or dataset downloads.

Before / after (precomputed embeddings, update_topics(docs, representation_model=MaximalMarginalRelevance())):

words per topic warning shown
master 30 no
this PR 10 yes

I left the global UserWarning filter in _bertopic.py untouched because it seems deliberate. Note that it also hides UserWarnings from user code after import bertopic. Happy to open a separate issue if you'd like to revisit it, or to adjust the approach here.

Before submitting

When BERTopic has no embedding_model (e.g. precomputed embeddings were
passed), MaximalMarginalRelevance returned the 30 c-TF-IDF candidates
untruncated, and its warnings.warn() was suppressed by the module-level
UserWarning filter in _bertopic.py.

Truncate the fallback to top_n_words and log through MyLogger, matching
the other warnings in the package.

Fixes MaartenGr#2323

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Representation has >=30 terms when using MMR to update topics if pre-calculated embeddings are used

1 participant