Comments (9)
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.
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.
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
Please do let me know if I am doing something wrong over here.
Thanks!
from declutr.
Using the enconder function directly did work out. Thanks John! Is there a way to directly use SentEval on already generated embeddings?
from declutr.
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.
I mean, I have already saved the embeddings as .npy arrays
from declutr.
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.
Oh okay! I'll take a look at it. Thank you.
from declutr.
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)
- Cant set up DECLUTR in local AWS linux machine HOT 2
- argument 'lazy' for dataset_reader HOT 2
- Superclass initialization in token embedder HOT 2
- Could not lex the character code 194 HOT 3
- Minimum text length violated despite preprocessing HOT 2
- How to plot the learning curve from the output logs created post training of declutr? HOT 1
- Impact of "shorter" documents (span, number of tokens) for extended pretraining HOT 7
- Installation issue HOT 8
- Wrong training procedure? HOT 6
- Strange issue occuring during Training HOT 2
- load pretrained tf1 model with pytorch HOT 5
- How to integrate a longer sequence model like longformer into declutr architecture HOT 8
- Encoder class breaks for long strings
- can i finetune the model ? HOT 2
- Update DeCLUTR requirements? HOT 5
- How to use a validation dataset when training? HOT 8
- RuntimeError: Error(s) in loading state_dict for DeCLUTR: HOT 2
- Error while encoding HOT 4
- Training with multi gpus HOT 6
- Installation fails in colab notebook HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from declutr.