BERTopic icon indicating copy to clipboard operation
BERTopic copied to clipboard

Best practices on large datasets

Open nilsblessing opened this issue 4 years ago • 15 comments

Hi all!

I am currently approaching larger amounts of data step by step and have asked myself whether there are any experiences or even best practices in this regard?

Maybe as a preliminary information: I work in an Azure environment (Databricks) and I am more or less free in designing the computing units. Currently I am still working experimentally with Pandas Dataframes, maybe there are already better recommendations here? In terms of data volume, I am currently at around 1,000,000 records, and the trend is upwards. Before I call the fit method (single node cluster with 256GB and 64 cores), I use a GPU instance to generate the embeddings.

Any other tips, improvements or comments on this?

Kind regards, Nils

nilsblessing avatar Apr 01 '22 21:04 nilsblessing

Hi Nils,

I would advise starting with subsets of the data to see how well your environment can handle large amounts of data. Starting with 100,000 records and slowly increasing them.

The following steps typically works well for me when using large datasets:

  • Following along with the memory FAQ here
    • Most notably, making sure min_df is set to at least 10 to prevent generating large sparse matrices
    • Moreover, limiting ngram_range to (1, 2) at most as it is likely to generate a too large vocabulary
  • Embed the documents before training BERTopic to allow for easier parameter tuning
    • Also, save those embeddings using np.save to quickly access the embeddings
    • You can find a bit more about that here
  • You can update the topic representations after training with .update_topics() as it allows you to quickly fine-tune the representations without the need to re-train the model
    • You can find a bit more about that here
  • Lastly, make sure HDBSCAN is the latest version as it has difficulties handling data > 500,000 records if it is not

I might have forgotten a few things but the above are some steps that have worked well for me.

MaartenGr avatar Apr 02 '22 06:04 MaartenGr

Thank you for the valuable advices!

Especially the two options np.save and .update_topics() are a big help for me. 👍

Best regards, Nils

nilsblessing avatar Apr 11 '22 05:04 nilsblessing

Hi Maarten,

With reference to embedding the documents before training BERTopic - I tried following the link posted, but the page does not exist. How would you use fit_transform without embedding the documents every time? This would save me a lot of time, since I need to tune the parameters for my model.

Regards, Francesca

Spekkboom avatar May 24 '22 09:05 Spekkboom

@DieSpekboom It seems that the link indeed has changed with the new release, my apologies. It is now fixed and should work!

In essence, you create the embeddings before training BERTopic and simply supply them to the model:

from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
from bertopic import BERTopic

# Prepare embeddings
docs = fetch_20newsgroups(subset='all',  remove=('headers', 'footers', 'quotes'))['data']
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = sentence_model.encode(docs, show_progress_bar=False)

# Train our topic model using our pre-trained sentence-transformers embeddings
topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs, embeddings)

Thus, whenever you supply embeddings when using fit_transform they will not be calculated again which could save you quite some time.

MaartenGr avatar May 24 '22 13:05 MaartenGr

Thanks @MaartenGr, this works perfectly!

Spekkboom avatar May 24 '22 13:05 Spekkboom

Hi Maarten, great work on bertopic and keybert!

I was wondering if it is possible to call the .fit_transform(docs, embeddings) function but instead of providing the embeddings, I would like to give it the embeddings reduced by UMAP. So something like .fit_transform(docs, umap_reduced)

The idea is that I would like to fine tune the HDBSCAN hyper-parameters without re-reducing the dimension each time. Plus UMAP being stochastic, it can make it difficult to know if the change occurred because of hyper-parameter value change or UMAP reduction being slightly different.

I've been looking in your code and it does not seem to be possible but maybe I've missed it.

Regrads, Etienne

Zzbra avatar Jun 02 '22 15:06 Zzbra

@Zzbra It is a little bit hacky but you can do this by creating a UMAP class that, instead of training on embeddings when running fit it actually returns the embeddings without any changes.

First, we will need to create a class that mimics the behavior of UMAP but instead returns the embeddings as-is:

class EmptyUMAP:
    def fit(self, x, y):
        return self
    
    def transform(self, embeddings):
        return embeddings

Then, we simply pass that class to BERTopic along with the umap_reduced that you generated previously:

from bertopic import BERTopic

# This empty UMAP instance basically does nothing and allows you to pass in 
# UMAP embeddings that you generated previously
empty_umap = EmptyUMAP()
topic_model = BERTopic(umap_model=empty_umap)

# Now, we can pass the umap_embeddings and it will only apply the HDBSCAN->c-TF-IDF steps
# The embedding and dimensionality stages are ignored
topics, probs = topic_model.fit_transform(docs, umap_reduced)

Do note that the easiest solution is to simply assign a random_state as mentioned here. Hope this helps!

MaartenGr avatar Jun 02 '22 19:06 MaartenGr

@MaartenGr MaartenGr Thank you for your answer. That is a smart solution, I did not think of it. Thank you very much!

I have tried using the random state but it slows down computation considerably. Your solution will do the job nicely. Thanks again and have a great day!

Regards, Etienne

Zzbra avatar Jun 03 '22 10:06 Zzbra

Glad to hear that it worked out! I will go ahead and close this issue. Having said, if you want to re-open it, please let me know 😄

MaartenGr avatar Jul 13 '22 08:07 MaartenGr

Suppose a scenario where we have 1 billion documents, so there is no option other than to chunk documents into batches and train a topic model. The maximum number of documents we can load into our machine at a given time is 100k.

Can we also use the online topic modeling for such use cases with large number of documents? How does online topic modeling compare to the approach in which we update the topic representations after training with .update_topics()? It looks to me .update_topics doesn't re-train the model and only slightly modifies the topic representations according to the new documents. Is the online topic modeling approach less accurate than the typical method of loading all documents into memory at once and training on all of them?

erfaneshrati avatar Feb 05 '23 21:02 erfaneshrati

@erfaneshrati With so many documents, it is indeed advised to use online topic modeling as it should scale much better by batching documents. The .update_topics() only updates the topic representations themselves and has no influence on the underlying cluster creation process. As such, it has no direct relationship with online topic modeling and what you are trying to achieve with 1 billion documents.

Is the online topic modeling approach less accurate than the typical method of loading all documents into memory at once and training on all of them?

Online topic modeling uses a different set of algorithms than the default and as such is likely to be quite different from one another. The default, using UMAP and HDBSCAN, often gives great results whereas online topic modeling cannot make use of those models and uses IncrementalPCA and MiniBatchKmeans instead. Other sub-models are possible but there are not many out there that support online functionality. If you do not want to use online topic modeling, then it might be worthwhile to train BERTopic using GPU-accelerated UMAP and HDBSCAN on a subset of the dataset and predict the topics of all others.

MaartenGr avatar Feb 06 '23 10:02 MaartenGr

I run BERTopic on my corpus. Actually every document in the corpus is quite big. What is the default way of handling large document in BERTopic? I mean if every topic is bigger ethan the window size of BERT token.

Tiziano-Pacifico avatar Nov 02 '23 11:11 Tiziano-Pacifico

@Tiziano-Pacifico By default, the large documents will be truncated. That is how the underlying sentence-transformers model handles large documents. It all depends on the embedding model you choose.

MaartenGr avatar Nov 02 '23 12:11 MaartenGr

Hi @MaartenGr, I am processing large datasets (number of docs > 1M), but found that the processing of representation is too slow. With 100K docs, it takes 10mins, but I would like to process 10M docs. These are my representation models:

representation_model = { # "KeyBERT": keybert_model, # "OpenAI": openai_model, # Uncomment if you will use OpenAI "MMR": mmr_model, "POS": pos_model }

Could you advise any suggestions for acceleration? Thanks!

shizhediao avatar Sep 21 '24 23:09 shizhediao

Hi @MaartenGr, I am processing large datasets (number of docs > 1M), but found that the processing of representation is too slow. With 100K docs, it takes 10mins, but I would like to process 10M docs. These are my representation models:

representation_model = {

"KeyBERT": keybert_model,

"OpenAI": openai_model, # Uncomment if you will use OpenAI

"MMR": mmr_model, "POS": pos_model }

Could you advise any suggestions for acceleration? Thanks!

maybe you can change some part into GPU-accelrated ones, for e.g. using

from cuml.cluster import HDBSCAN

yangziyu-620 avatar Mar 05 '25 05:03 yangziyu-620