Skip to content

Fix find_topics crash when search_term is a list of strings - #2553

Closed
sebastianbreguel wants to merge 2 commits into
MaartenGr:masterfrom
sebastianbreguel:fix/find-topics-list-input
Closed

sebastianbreguel wants to merge 2 commits into
MaartenGr:masterfrom
sebastianbreguel:fix/find-topics-list-input

Conversation

@sebastianbreguel

Copy link
Copy Markdown

Reopens #2479 (closed by mistake), rebased onto current master.

What does this PR do?

Fixes #2475
Fixes #2392

BERTopic.find_topics(search_term) crashes with IndexError when search_term is a single-element list, and silently misbehaves with two-element lists.

Root cause

find_topics always wrapped search_term in an extra list before passing it to _extract_embeddings:

search_embedding = self._extract_embeddings([search_term], method="word", verbose=False).flatten()

When the user passed a list, this produced a nested list (e.g. [["car"]]). sentence-transformers' tokenizer then interpreted the inner list as a text-pair, raising IndexError on text_tuple[1] for length-1 inputs and silently producing wrong embeddings for length-2 inputs (it appears to "work" for length ≥ 3 only by accident).

Changes

  • Resolve search_term to a flat list of strings: a string becomes a single-element list (preserving prior behavior); a list is passed through unchanged.
  • Embed all terms and average the resulting vectors into a single query embedding before computing cosine similarity. Averaging is the standard centroid-search semantics for multi-term queries.
  • Explicitly raise ValueError on empty input instead of silently returning NaN similarities from np.mean over zero rows.
  • Widen the type hint to str | List[str] | None and document the list semantics in the docstring.

Tests

  • New test_find_topics_with_list parametrized over ["car"] and ["car", "vehicle"] across two fixture models — would have caught this bug.
  • New test_find_topics_empty_list_raises covers the empty-list guard.
  • Existing test_find_topics continues to pass (string input is unchanged).

All find_topics tests pass locally and ruff check / ruff format --check are clean.

Before submitting

  • This PR fixes a typo or improves the docs (if yes, ignore all other checks!).
  • Did you read the contributor guideline?
  • Was this discussed/approved via a Github issue? Please add a link to it if that's the case.
  • Did you make sure to update the documentation with your changes (if applicable)?
  • Did you write any new necessary tests?

Closes #2475, closes #2392

find_topics() always wrapped search_term in an extra list before passing it
to the embedder, so a list input became a nested list. sentence-transformers
then interpreted the inner list as a text-pair, raising IndexError for a
single-element list and silently producing wrong embeddings for length-2
lists.

Resolve search_term to a flat list of strings (string -> single-element list,
list -> as-is), embed all terms, and average the resulting vectors into a
single query embedding. Empty lists now raise ValueError explicitly instead
of silently returning NaN similarities.

Adds a regression test covering single- and multi-element list inputs across
fixture models, plus a test for the empty-list ValueError.
@sebastianbreguel

Copy link
Copy Markdown
Author

The red CI here is flaky, and it comes from the Python 3.10 job, not from this change.

I ran the same code twice, and the reduced_topic_model fixture came out different each time:

Run Commit 3.10 result Topics in reduced_topic_model
41165165183 4efe643 3 failed 7
41171928774 e3daa94 (empty commit) 1 failed 9

The other versions show as failed because fail-fast cancelled them. In the second run, 3.14 finished and passed.

None of the failing tests touch find_topics:

  • test_barchart[reduced_topic_model] and test_barchart_outlier[reduced_topic_model] expect exactly 8 topics, and got 7.
  • test_topic_reduction[10-reduced_topic_model] asks for 10 topics on a model that has fewer. reduce_topics then crashes at bertopic/_bertopic.py:4806 with IndexError: index 57 is out of bounds for axis 1 with size 9.

The fixture is built in tests/test_bertopic.py, the 5th test in the run, before any test this PR adds. Locally, the full suite passes on macOS (278 passed). On Linux in Docker, with the same package versions as the failing CI run, test_full_model and test_bar.py pass on both master and this branch. #2539 makes a similar change and hit the same 3 failures, also only on 3.10.

My guess, which I haven't proven: the 3.10 runner computes the embeddings with tiny numeric differences, and that flips HDBSCAN's automatic reduction between 7 and 9 topics.

Two things fall out of this, both separate from this PR:

  1. The == 8 in test_bar.py is brittle against nr_topics="auto".
  2. reduce_topics(nr_topics=n) crashes when n is larger than the current number of topics (seen with 10 on models with 7 and 9). I'd expect it to keep the model unchanged. I'm happy to open a separate PR for that.

Could you re-run the 3.10 job? I don't have permission to.

@sebastianbreguel

Copy link
Copy Markdown
Author

@MaartenGr could you review this?

@MaartenGr

Copy link
Copy Markdown
Owner

@sebastianbreguel Thank you for the PR. Note that there is a v1.0 version in the works where this is going to be fixed: https://github.com/MaartenGr/BERTopic/releases

@sebastianbreguel

Copy link
Copy Markdown
Author

Thanks @MaartenGr, I see v1.0 already takes a list of search terms and averages them the same way. Closing this in favor of v1.0.

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.

find_topics(topic) crashes if topic is a 1-element list List index out of range in find_topics when called with a list of 1 string

2 participants