-
Notifications
You must be signed in to change notification settings - Fork 14
added support for text only metrics, and an implementation of hellaswag #7
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
Open
MajoRoth
wants to merge
1
commit into
slp-rl:main
Choose a base branch
from
MajoRoth:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
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,6 @@ | ||
| defaults: | ||
| - default | ||
| - _self_ | ||
|
|
||
| metric_type: hellaswag | ||
| data_path: //reference/hellaswag |
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,74 @@ | ||
| import logging | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
| import json | ||
| import torch | ||
| from pathlib import Path | ||
| from torch.utils.data import DataLoader, Dataset | ||
| from torch.nn.utils.rnn import pad_sequence | ||
| from tqdm import tqdm | ||
| import re | ||
|
|
||
|
|
||
| class HellaSwagDataset(Dataset): | ||
| def __init__(self, path): | ||
| super().__init__() | ||
| self.data = [] | ||
|
|
||
| with open(path, 'r') as file: | ||
| self.data = [json.loads(line) for line in file] | ||
|
|
||
| def __len__(self): | ||
| return len(self.data) | ||
|
|
||
| def __getitem__(self, idx): | ||
| data = self.data[idx] | ||
| positive_index = data['label'] | ||
| ctx = data["ctx_a"] + " " + data["ctx_b"].capitalize() | ||
| query = HellaSwagDataset.preprocess(data["activity_label"] + ": " + ctx) | ||
| endings = [HellaSwagDataset.preprocess(ending) for ending in data['endings']] | ||
| full_sentences = [query + ending for ending in endings] | ||
|
|
||
| return full_sentences[positive_index:] + full_sentences[:positive_index] | ||
|
|
||
| @staticmethod | ||
| def preprocess(text): | ||
| text = text.strip() | ||
| # NOTE: Brackets are artifacts of the WikiHow dataset portion of HellaSwag. | ||
| text = text.replace(" [title]", ". ") | ||
| text = re.sub("\\[.*?\\]", "", text) | ||
| text = text.replace(" ", " ") | ||
| return text | ||
|
|
||
|
|
||
|
|
||
| def textual_metric(model, dataset, used_token_modality, mean_nll: bool=True, | ||
| batch_size: int = 1, num_workers=8, pin_memory=True): | ||
| dl = DataLoader(dataset, batch_size=batch_size ,num_workers=num_workers, pin_memory=pin_memory) | ||
| res_list = [] | ||
|
|
||
| counter = 0 | ||
| for sample_files in tqdm(dl): | ||
| counter +=1 | ||
|
|
||
| with torch.no_grad(): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. there is not need for the |
||
| results = [ | ||
| model.text_log_likelihood(sample, used_token_modality=used_token_modality, mean_nll=mean_nll) | ||
| for sample in sample_files | ||
| ] | ||
|
|
||
| res = (results[0] > torch.stack(results[1:]).max(dim=0).values).int() | ||
| res_list.append(res) | ||
|
|
||
| res_list = torch.cat(res_list) | ||
| return res_list.float().mean().cpu().item() | ||
|
|
||
|
|
||
| def hellaswag(model, data_path, used_token_modality, mean_nll=True, | ||
| batch_size=1, num_workers=8, pin_memory=True): | ||
| dataset = HellaSwagDataset(data_path) | ||
| assert len(dataset) > 0, f"no samples found for {data_path}" | ||
| res = textual_metric(model, dataset, used_token_modality, mean_nll, batch_size, num_workers, pin_memory) | ||
| logging.info(f"HellaSwag: {res:.4f}") | ||
| return {'HellaSwag': res} | ||
|
|
||
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 |
|---|---|---|
|
|
@@ -35,6 +35,19 @@ def log_likelihood(self, wavs: torch.Tensor, lens: Optional[torch.Tensor] = None | |
| ignore_tokens = self.tokeniser.get_ignore_tokens(used_token_modality) | ||
| return self.model.log_likelihood(tokens, mean_nll, ignore_tokens) | ||
|
|
||
| def text_log_likelihood(self, texts: List[str], mean_nll: bool = True, used_token_modality: Optional[str] = None) -> torch.Tensor: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why add text_log_likelihood to a speech lm model? |
||
| """ | ||
| Given a list of texts, calculate the log likelihood for each sample. | ||
| :param texts: A list of strings | ||
| :param mean_nll: whether to take mean instead of sum thus cancelling length bias | ||
| :param used_token_modality: the tokens modality to use | ||
| :return: | ||
| """ | ||
| tokens = self.tokeniser.string_tokenise(texts, return_tensors='pt', padding=True)['input_ids'].to(self.device) | ||
| ignore_tokens = self.tokeniser.get_ignore_tokens(used_token_modality) | ||
| return self.model.log_likelihood(tokens, mean_nll, ignore_tokens) | ||
|
|
||
|
|
||
| def generate(self, wavs: torch.Tensor, lens: Optional[torch.Tensor] = None, used_token_modality: Optional[str] = None, remove_prompt=False, **kwargs) -> List[torch.Tensor]: | ||
| """ | ||
| Given a batch of wavs zero padded, generate the continuation tokens or audio if a vocoder is present | ||
|
|
||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why replace [title] with ".". is this how this metric is normally processed?