Giter Club home page Giter Club logo

Comments (9)

JohnGiorgi avatar JohnGiorgi commented on June 1, 2024 1

I think I understand what's going on. When we bulk-embed stuff using the AllenNLP predict it is creating Instance objects under the hood (that is what is shown in your screenshot). These objects are actually quite big, and take up a lot of RAM, and eventually crash Colab. I think this problem is mostly solved in allennlp>=2.0.0. I have begun the process of updating DeCLUTR to support allennlp>=2.0.0 but am not done yet.

For now, what if you use the first option mentioned in the notebook (1. As a library: import and initialize an object from this repo, which can be used to embed sentences/paragraphs.). This should be as easy as:

from declutr import Encoder

# This can be a path on disk to a model you have trained yourself OR
# the name of one of our pretrained models.
pretrained_model_or_path = "declutr-small"

text = [
    "A smiling costumed woman is holding an umbrella.",
    "A happy woman in a fairy costume holds an umbrella.",
    "A soccer game with multiple males playing.",
    "Some men are playing a sport.",
]

encoder = Encoder(pretrained_model_or_path, cuda_device=cuda_device)
embeddings = encoder(text, batch_size=32)

Otherwise, you could use the second option ("2. 🤗 Transformers: load our pretrained model with the 🤗 Transformers library."). You might need to wrap some of it up in a function and then call that function in a loop, accumulating embeddings as you go. It would look something like this (note that this is rough and untested):

import torch
from scipy.spatial.distance import cosine

from transformers import AutoModel, AutoTokenizer

# Load the model
tokenizer = AutoTokenizer.from_pretrained("johngiorgi/declutr-small")
model = AutoModel.from_pretrained("johngiorgi/declutr-small")
model = model.to(device)

def embed(tokenizer, model, text):
    inputs = tokenizer(text, padding=True, truncation=True, return_tensors="pt")
    
    # Put the tensors on the GPU, if available
    for name, tensor in inputs.items():
        inputs[name] = tensor.to(model.device)

    # Embed the text
    with torch.no_grad():
        sequence_output, _ = model(**inputs, output_hidden_states=False)

    # Mean pool the token-level embeddings to get sentence-level embeddings
    embeddings = torch.sum(
        sequence_output * inputs["attention_mask"].unsqueeze(-1), dim=1
    ) / torch.clamp(torch.sum(inputs["attention_mask"], dim=1, keepdims=True), min=1e-9)
    embeddings = embeddings.cpu()

    return embeddings

# Could do a list of lists to batch input or implement batching another way
text = [
    ["A smiling costumed woman is holding an umbrella.",
     "A happy woman in a fairy costume holds an umbrella.",
     "A soccer game with multiple males playing.",
     "Some men are playing a sport."]
]
embeddings = []
for batch in text:
    embeddings.append(embed(tokenizer, model, batch))
embeddings = torch.cat(embeddings)

from declutr.

JohnGiorgi avatar JohnGiorgi commented on June 1, 2024

Hi @deven367,

Is it crashing because you use up all the available RAM? VRAM? I am able to create 3.5K 768 dimensional embedding with torch on Colab using either the RAM or VRAM without any issues.

import torch

matrix = torch.rand(3500, 768)  # no crash
# OR, for GPU
# matrix = torch.rand(3500, 768, device=torch.cuda.current_device())

Maybe if you could link a Colab notebook with the minimum amount of code needed to trigger the error I could take a look? Another thing to try would be to use other models to embed your sentences, e.g. Google USE or SBERT. Do these cause Colab to crash?

I suspect this is more of a Colab problem than a DeCLUTR problem but it would be good to confirm.

from declutr.

deven367 avatar deven367 commented on June 1, 2024

https://colab.research.google.com/drive/1zzAciLi8oFHn61ADCt1Z6xzRgG6gMjJw?usp=sharing

Here's the link to my notebook. I haven't made any particular changes. I face this issue while generating embeddings for these files.
https://github.com/deven367/thesis/blob/main/datasets/cleaned_novels/Ulysses_cleaned.txt
https://github.com/deven367/thesis/blob/main/datasets/cleaned_novels/Pride%20and%20Prejudice_cleaned.txt

image

Please do let me know if I am doing something wrong over here.

Thanks!

from declutr.

deven367 avatar deven367 commented on June 1, 2024

Using the enconder function directly did work out. Thanks John! Is there a way to directly use SentEval on already generated embeddings?

from declutr.

JohnGiorgi avatar JohnGiorgi commented on June 1, 2024

Using the enconder function directly did work out. Thanks John!

Great!

Is there a way to directly use SentEval on already generated embedding?

Hmm, not sure what you mean. Take a look at SentEval's documentation. You will need to write a function batcher that takes the input text of the various tasks and returns a vector. We have an example notebook that may be helpful here, and a SentEval script here.

from declutr.

deven367 avatar deven367 commented on June 1, 2024

I mean, I have already saved the embeddings as .npy arrays

from declutr.

JohnGiorgi avatar JohnGiorgi commented on June 1, 2024

It is likely possible. I would take a look at the SentEval docs. It is not something this repo is setup for if that is what you are asking.

from declutr.

deven367 avatar deven367 commented on June 1, 2024

Oh okay! I'll take a look at it. Thank you.

from declutr.

JohnGiorgi avatar JohnGiorgi commented on June 1, 2024

No worries! I think the original issue has been addressed so I will close this. Please re-open this issue or open an additional issue if you get stuck with anything DeCLUTR-specific!

from declutr.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.