-
Notifications
You must be signed in to change notification settings - Fork 1.1k
added textual entailment score #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+100
−8
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9873234
add sbert score
shahules786 ca9676f
add relative import
shahules786 8b8507b
add entailment score
shahules786 56a67bf
add relative import
shahules786 fb379f9
add device assigner
shahules786 763bca2
merge main
shahules786 47e830d
fix input type
shahules786 e363a30
change input type
shahules786 a404038
change DEVICE type
shahules786 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
from belar.metrics.base import Evaluation, Metric | ||
from belar.metrics.similarity import * | ||
from belar.metrics.simple import * | ||
from belar.metrics.similarity import SBERTScore | ||
from belar.metrics.similarity import SBERTScore | ||
from belar.metrics.factual import EntailmentScore |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
from __future__ import annotations | ||
|
||
from transformers import AutoTokenizer, AutoModelForSequenceClassification | ||
import typing as t | ||
from dataclasses import dataclass | ||
|
||
from belar.metrics import Metric | ||
from belar.utils import device_check | ||
|
||
|
||
@dataclass | ||
class EntailmentScore(Metric): | ||
""" | ||
Entailment score using ground truth as premise and generated text as hypothesis. | ||
""" | ||
|
||
model_name: str = "typeform/distilbert-base-uncased-mnli" | ||
batch_size: int = 4 | ||
device: t.Literal["cpu", "cuda"] = "cpu" | ||
|
||
def __post_init__(self): | ||
self.device = device_check(self.device) | ||
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) | ||
self.model = AutoModelForSequenceClassification.from_pretrained(self.model_name) | ||
self.model.eval() | ||
self.model.to(self.device) | ||
|
||
model_config = self.model.config.to_dict() | ||
assert model_config.get("id2label") or model_config.get( | ||
"label2id" | ||
), "label-id mapping missing" | ||
if model_config.get("id2label") is None: | ||
self.id2label = {v: k for k, v in model_config.label2id} | ||
else: | ||
self.id2label = model_config["id2label"] | ||
|
||
@property | ||
def name(self): | ||
return "Entailment_score" | ||
|
||
@property | ||
def is_batchable(self): | ||
return True | ||
|
||
def batch_infer(self, inputs: dict): | ||
predictions = [] | ||
input_ids = inputs["input_ids"] | ||
label2id = {value.lower(): key for key, value in self.id2label.items()} | ||
|
||
for idx in range(0, len(input_ids), self.batch_size): | ||
batch_ids = input_ids[idx : idx + self.batch_size] | ||
output = self.model(batch_ids.to(self.device)) | ||
pred = output.logits.softmax(axis=-1).detach().cpu() | ||
predictions.extend(pred[:, label2id["entailment"]].tolist()) | ||
|
||
return predictions | ||
|
||
def score( | ||
self, | ||
ground_truth: t.List[str], | ||
generated_text: t.List[str], | ||
): | ||
""" | ||
ground_truth : premis | ||
generated_text : hypothesis | ||
returns entailement probability score | ||
""" | ||
|
||
encodings = self.tokenizer( | ||
ground_truth, generated_text, truncation=True, return_tensors="pt" | ||
) | ||
|
||
score = self.batch_infer(encodings) | ||
|
||
return score |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import torch | ||
import typing as t | ||
from warnings import warn | ||
|
||
DEVICES = ["cpu", "cuda"] | ||
|
||
|
||
def device_check(device: t.Literal[DEVICES]): | ||
if device == "cuda": | ||
if torch.cuda.is_available(): | ||
device = torch.device("cuda") | ||
else: | ||
warn("cuda not available, using cpu") | ||
elif device == "cpu": | ||
device = torch.device("cpu") | ||
else: | ||
raise ValueError(f"Invalid device {device}") | ||
|
||
return device |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.