-
Notifications
You must be signed in to change notification settings - Fork 318
[code_review] Integrate ML filter for the generated comments #5077
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
ArezouAmini
wants to merge
6
commits into
mozilla:master
Choose a base branch
from
ArezouAmini:master
base: master
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.
+179
−1
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b53a07f
[code_review] Integrate ML filter for the generated comments
ArezouAmini 7b6534e
Merge branch 'mozilla:master' into master
ArezouAmini 71d4c52
Lint changes
ArezouAmini 0d8f8e4
Merge branch 'master' of https://github.com/ArezouA/bugbug
ArezouAmini d6bb64d
Fix lint errors
ArezouAmini 3d8a24f
Modify model saving
ArezouAmini 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 |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| from abc import ABC, abstractmethod | ||
| from pathlib import Path | ||
|
|
||
| import torch | ||
| from datasets import Dataset | ||
| from torch.nn.functional import softmax | ||
| from transformers import ( | ||
| AutoTokenizer, | ||
| ModernBertForSequenceClassification, | ||
| Trainer, | ||
| TrainingArguments, | ||
| set_seed, | ||
| ) | ||
|
|
||
|
|
||
| class FineTuneMLClassifer(ABC): | ||
| def __init__(self, model_path, seed=42): | ||
| self.model = ModernBertForSequenceClassification.from_pretrained( | ||
| model_path, device_map=self.device, attn_implementation="sdpa" | ||
| ) | ||
| self.tokenizer = AutoTokenizer.from_pretrained( | ||
| model_path, device_map=self.device | ||
| ) | ||
| self.seed = seed | ||
| self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | ||
|
|
||
| def _tokenize(self, batch): | ||
| return self.tokenizer( | ||
| batch["comment"], | ||
| padding=True, | ||
| truncation=True, | ||
| return_tensors="pt", | ||
| ) | ||
|
|
||
| def fit(self, inputs, labels, tmpdir): | ||
| set_seed(self.seed) | ||
|
|
||
| train_dataset = Dataset.from_dict( | ||
| { | ||
| "comment": inputs, | ||
| "label": labels, | ||
| } | ||
| ) | ||
|
|
||
| train_dataset = train_dataset.map( | ||
| self._tokenize, batched=True, remove_columns=["comment"] | ||
| ) | ||
|
|
||
| training_args = TrainingArguments( | ||
| # Required parameter: | ||
| output_dir=None, | ||
| # Optional training parameters: | ||
| num_train_epochs=30, | ||
| per_device_train_batch_size=128, | ||
| warmup_steps=500, | ||
| learning_rate=5e-5, | ||
| optim="adamw_torch", | ||
| # lr_scheduler_type="constant", | ||
| # warmup_ratio=0.1, | ||
| bf16=True, | ||
| eval_steps=0, | ||
| save_strategy="no", | ||
| save_steps=100, | ||
| save_total_limit=2, | ||
| logging_steps=10, | ||
| logging_strategy="epoch", | ||
| report_to="none", | ||
| seed=self.seed, | ||
| use_cpu=True if self.device == "cpu" else False, | ||
| ) | ||
| trainer = Trainer( | ||
| model=self.model, | ||
| args=training_args, | ||
| tokenizer=self.tokenizer, | ||
| train_dataset=train_dataset, | ||
| eval_dataset=None, | ||
| ) | ||
|
|
||
| trainer.train() | ||
| self.model.save_pretrained(save_directory=tmpdir) | ||
| self.tokenizer.save_pretrained(save_directory=tmpdir) | ||
|
|
||
| def predict(self, inputs): | ||
| self.model.to(self.device).eval() | ||
|
|
||
| input = self.tokenizer( | ||
| inputs, padding=True, truncation=True, return_tensors="pt" | ||
| ).to(self.device) | ||
|
|
||
| with torch.no_grad(): | ||
| logits = self.model(**input).logits | ||
| probs = softmax(logits, dim=1)[:, 0] | ||
| probs = probs.detach().cpu().numpy() | ||
| return probs | ||
|
|
||
| @abstractmethod | ||
| def save(self, tmpdir: Path): ... | ||
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,17 @@ | ||
| from abc import ABC, abstractmethod | ||
| from typing import Any | ||
|
|
||
|
|
||
| class MLCommentFilter(ABC): | ||
| def __init__(self, *args, **kwargs) -> None: | ||
| super().__init__(*args, **kwargs) | ||
|
|
||
| @abstractmethod | ||
| def query_ml_filter(self, comments, *args, **kwargs) -> Any: ... | ||
|
|
||
|
|
||
| ml_comment_filters = {} | ||
|
|
||
|
|
||
| def register_ml_comment_filters(name, cls): | ||
| ml_comment_filters[name] = cls |
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,51 @@ | ||
| from abc import ABC, abstractmethod | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| from sklearn.metrics import recall_score | ||
|
|
||
|
|
||
| class Trainer(ABC): | ||
| def __init__( | ||
| self, | ||
| min_recall: float = 0.9, | ||
| thr_metric: str = "acceptance_rate", | ||
| tmpdir: Path = Path(""), | ||
| ): | ||
| self.min_recall = min_recall | ||
| self.thr_metric = thr_metric | ||
| self.tmpdir = tmpdir | ||
|
|
||
| @abstractmethod | ||
| def train_test_split(self, data, test_size=0.5, random_split=True): ... | ||
|
Member
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. What should the data look like? I do not see the method used anywhere! |
||
|
|
||
| def _fit(self, model): | ||
| model.fit(self.train_inputs, self.train_labels, self.tmpdir) | ||
| return model.predict(self.val_inputs) | ||
|
|
||
| def train(self, model): | ||
| probs = self._fit(model) | ||
| thresholds_results = {} | ||
| for thr in np.arange(0, 1.01, 0.01): | ||
| preds = np.where(probs >= thr, 0, 1) | ||
| recalls = recall_score(self.val_labels, preds, average=None) | ||
| acceptance_rate = sum( | ||
| [1 for pred, label in zip(preds, self.val_labels) if pred and label] | ||
| ) / sum(preds) | ||
| thresholds_results[thr] = { | ||
| "recall_accept": recalls[1], | ||
| "gmean": np.sqrt(recalls[0] * recalls[1]), | ||
| "acceptance_rate": acceptance_rate, | ||
| } | ||
| # Select threshold based on minimum accept recall and max acceptance_rate/gmean | ||
| thresholds_results = { | ||
| thr: metrics | ||
| for thr, metrics in thresholds_results.items() | ||
| if metrics["recall_accept"] >= self.min_recall | ||
| } | ||
| thresholds_results = sorted( | ||
| thresholds_results.items(), | ||
| key=lambda x: x[1][f"{self.thr_metric}"], | ||
| reverse=True, | ||
| ) | ||
| return thresholds_results[0][0] | ||
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
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.
I think some of the dependencies are not in the
requirements.json.