-
Notifications
You must be signed in to change notification settings - Fork 18
Comment prediction added (CommentCode2Seq) #120
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
malodetz
wants to merge
33
commits into
master
Choose a base branch
from
comment-prediction
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.
Open
Changes from 12 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
628c5e5
Added useful classes
malodetz 1ff1994
Config added
malodetz f8ffa00
Added comment label processing
malodetz 5f39e68
Added wrapper
malodetz 8620414
Update requirements.txt
malodetz 7624d44
Fixing train to use gpu
malodetz fb5fb26
New model with correct decoder
malodetz c4a203b
Fix black
malodetz 6fdee03
Added custom chrf metric
malodetz db70270
Minor updates
malodetz b68cc10
Fix random
malodetz 24c8484
Fixing chrf and f1
malodetz 33db6b5
Preliminary new tokenizer
malodetz dc15cdb
Complete new tokenizer
malodetz 26dd42f
Some fixes
malodetz f6fa424
New vocab size
malodetz e8b677d
Add tokenizer to config
malodetz b1b2e27
Move chrf metric
malodetz e70f96d
Better tokenization
malodetz 5e93981
Implement comment transformer decoder
malodetz 033560c
Greedy decoding for val/test
malodetz c74319f
Small fix
malodetz b1009cd
Some fixes
malodetz 6aff1ed
Logits cut
malodetz c23e20a
Fixed greedy generation
malodetz 37f3db2
Some train changes to fix
malodetz a19e752
Fix train
malodetz e43b664
Сonfig for transformer decoder
malodetz c51f14c
Multiple decoders
malodetz d09dc30
Another config
malodetz 9bfa25c
Add early stop for greedy generation
malodetz b0b7b81
Early generation stop
malodetz 54cb711
Added predictions
malodetz 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,63 @@ | ||
| from argparse import ArgumentParser | ||
| from typing import cast | ||
|
|
||
| import torch | ||
| from commode_utils.common import print_config | ||
| from omegaconf import DictConfig, OmegaConf | ||
| from pytorch_lightning import seed_everything | ||
|
|
||
| from code2seq.data.comment_path_context_data_module import CommentPathContextDataModule | ||
| from code2seq.model.comment_code2seq import CommentCode2Seq | ||
| from code2seq.utils.common import filter_warnings | ||
| from code2seq.utils.test import test | ||
| from code2seq.utils.train import train | ||
|
|
||
|
|
||
| def configure_arg_parser() -> ArgumentParser: | ||
| arg_parser = ArgumentParser() | ||
| arg_parser.add_argument("mode", help="Mode to run script", choices=["train", "test"]) | ||
| arg_parser.add_argument("-c", "--config", help="Path to YAML configuration file", type=str) | ||
| arg_parser.add_argument( | ||
| "-p", "--pretrained", help="Path to pretrained model", type=str, required=False, default=None | ||
| ) | ||
| return arg_parser | ||
|
|
||
|
|
||
| def train_code2seq(config: DictConfig): | ||
| filter_warnings() | ||
|
|
||
| if config.print_config: | ||
| print_config(config, fields=["model", "data", "train", "optimizer"]) | ||
|
|
||
| # Load data module | ||
| data_module = CommentPathContextDataModule(config.data_folder, config.data) | ||
|
|
||
| # Load model | ||
| code2seq = CommentCode2Seq(config.model, config.optimizer, data_module.vocabulary, config.train.teacher_forcing) | ||
|
|
||
| train(code2seq, data_module, config) | ||
|
|
||
|
|
||
| def test_code2seq(model_path: str, config: DictConfig): | ||
| filter_warnings() | ||
|
|
||
| # Load data module | ||
| data_module = CommentPathContextDataModule(config.data_folder, config.data) | ||
|
|
||
| # Load model | ||
| code2seq = CommentCode2Seq.load_from_checkpoint(model_path, map_location=torch.device("cpu")) | ||
|
|
||
| test(code2seq, data_module, config.seed) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| __arg_parser = configure_arg_parser() | ||
| __args = __arg_parser.parse_args() | ||
|
|
||
| __config = cast(DictConfig, OmegaConf.load(__args.config)) | ||
| seed_everything(__config.seed) | ||
| if __args.mode == "train": | ||
| train_code2seq(__config) | ||
| else: | ||
| assert __args.pretrained is not None | ||
| test_code2seq(__args.pretrained, __config) |
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,9 @@ | ||
| from code2seq.data.comment_path_context_dataset import CommentPathContextDataset | ||
| from code2seq.data.path_context_data_module import PathContextDataModule | ||
|
|
||
|
|
||
| class CommentPathContextDataModule(PathContextDataModule): | ||
| def _create_dataset(self, holdout_file: str, random_context: bool) -> CommentPathContextDataset: | ||
| if self._vocabulary is None: | ||
| raise RuntimeError(f"Setup vocabulary before creating data loaders") | ||
| return CommentPathContextDataset(holdout_file, self._config, self._vocabulary, random_context) |
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 @@ | ||
| from typing import Dict, List, Optional | ||
|
|
||
| from transformers import RobertaTokenizerFast | ||
|
|
||
| from code2seq.data.path_context_dataset import PathContextDataset | ||
|
|
||
| tokenizer = RobertaTokenizerFast.from_pretrained("microsoft/codebert-base") | ||
|
|
||
|
|
||
| class CommentPathContextDataset(PathContextDataset): | ||
| @staticmethod | ||
| def tokenize_label(raw_label: str, vocab: Dict[str, int], max_parts: Optional[int]) -> List[int]: | ||
| label_with_spaces = " ".join(raw_label.split(PathContextDataset._separator)) | ||
malodetz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| label_tokens = tokenizer.tokenize(label_with_spaces) | ||
| if max_parts is None: | ||
| max_parts = len(label_tokens) | ||
| label_tokens = [tokenizer.bos_token] + label_tokens[: max_parts - 2] + [tokenizer.eos_token] | ||
| label_tokens += [tokenizer.pad_token] * (max_parts - len(label_tokens)) | ||
malodetz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return tokenizer.convert_tokens_to_ids(label_tokens) | ||
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,84 @@ | ||
| from typing import Dict | ||
|
|
||
| import torch | ||
| from commode_utils.losses import SequenceCrossEntropyLoss | ||
| from commode_utils.metrics import SequentialF1Score | ||
| from commode_utils.modules import LSTMDecoderStep, Decoder | ||
| from omegaconf import DictConfig | ||
| from sacrebleu import CHRF | ||
| from torchmetrics import MetricCollection, Metric | ||
| from transformers import RobertaTokenizerFast | ||
|
|
||
| from code2seq.data.vocabulary import Vocabulary | ||
| from code2seq.model import Code2Seq | ||
|
|
||
|
|
||
| class CommentCode2Seq(Code2Seq): | ||
| def __init__( | ||
| self, | ||
| model_config: DictConfig, | ||
| optimizer_config: DictConfig, | ||
| vocabulary: Vocabulary, | ||
| teacher_forcing: float = 0.0, | ||
| ): | ||
| super().__init__(model_config, optimizer_config, vocabulary, teacher_forcing) | ||
|
|
||
| tokenizer = RobertaTokenizerFast.from_pretrained("microsoft/codebert-base") | ||
|
|
||
| self._pad_idx = tokenizer.pad_token_id | ||
| eos_idx = tokenizer.eos_token_id | ||
| ignore_idx = [tokenizer.bos_token_id, tokenizer.unk_token_id] | ||
| metrics: Dict[str, Metric] = { | ||
| f"{holdout}_f1": SequentialF1Score(pad_idx=self._pad_idx, eos_idx=eos_idx, ignore_idx=ignore_idx) | ||
| for holdout in ["train", "val", "test"] | ||
| } | ||
|
|
||
| # TODO add concatenation and rouge-L metric | ||
| metrics.update({f"{holdout}_chrf": CommentChrF(tokenizer) for holdout in ["val", "test"]}) | ||
| self._metrics = MetricCollection(metrics) | ||
|
|
||
| self._encoder = self._get_encoder(model_config) | ||
| output_size = len(tokenizer.get_vocab()) | ||
| decoder_step = LSTMDecoderStep(model_config, output_size, self._pad_idx) | ||
| self._decoder = Decoder(decoder_step, output_size, tokenizer.eos_token_id, teacher_forcing) | ||
|
|
||
| self._loss = SequenceCrossEntropyLoss(self._pad_idx, reduction="batch-mean") | ||
|
|
||
|
|
||
| class CommentChrF(Metric): | ||
malodetz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| def __init__(self, tokenizer: RobertaTokenizerFast, **kwargs): | ||
| super().__init__(**kwargs) | ||
| self.__tokenizer = tokenizer | ||
| self.__chrf = CHRF() | ||
|
|
||
| # Metric states | ||
| self.add_state("chrf", default=torch.tensor(0, dtype=torch.float), dist_reduce_fx="sum") | ||
| self.add_state("count", default=torch.tensor(0), dist_reduce_fx="sum") | ||
|
|
||
| def update(self, predicted: torch.Tensor, target: torch.Tensor): | ||
| """Calculated ChrF metric on predicted tensor w.r.t. target tensor. | ||
|
|
||
| :param predicted: [pred seq len; batch size] -- tensor with predicted tokens | ||
| :param target: [target seq len; batch size] -- tensor with ground truth tokens | ||
| :return: | ||
| """ | ||
| batch_size = target.shape[1] | ||
| if predicted.shape[1] != batch_size: | ||
| raise ValueError(f"Wrong batch size for prediction (expected: {batch_size}, actual: {predicted.shape[1]})") | ||
|
|
||
| for batch_idx in range(batch_size): | ||
| target_seq = [token.item() for token in target[:, batch_idx]] | ||
| predicted_seq = [token.item() for token in predicted[:, batch_idx]] | ||
|
|
||
| target_str = self.__tokenizer.decode(target_seq, skip_special_tokens=True) | ||
| predicted_str = self.__tokenizer.decode(predicted_seq, skip_special_tokens=True) | ||
|
|
||
| if target_str == "": | ||
| # Empty target string mean that the original string encoded only with <UNK> token | ||
| continue | ||
|
|
||
| self.chrf += self.__chrf.sentence_score(predicted_str, [target_str]).score | ||
| self.count += 1 | ||
|
|
||
| def compute(self) -> torch.Tensor: | ||
| return self.chrf / self.count | ||
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
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,60 @@ | ||
| data_folder: ./dataset | ||
|
|
||
| checkpoint: null | ||
|
|
||
| seed: 7 | ||
| # Training in notebooks (e.g. Google Colab) may crash with too small value | ||
| progress_bar_refresh_rate: 1 | ||
| print_config: true | ||
|
|
||
| wandb: | ||
| project: Code2Seq -- java-med | ||
| group: null | ||
| offline: false | ||
|
|
||
| data: | ||
| num_workers: 4 | ||
|
|
||
| # Each token appears at least 10 times (99.2% coverage) | ||
| labels_count: 1 | ||
| max_label_parts: 256 | ||
| # Each token appears at least 1000 times (99.5% coverage) | ||
| tokens_count: 1 | ||
| max_token_parts: 5 | ||
| path_length: 9 | ||
|
|
||
| max_context: 200 | ||
| random_context: true | ||
|
|
||
| batch_size: 16 | ||
| test_batch_size: 16 | ||
|
|
||
| model: | ||
| # Encoder | ||
| embedding_size: 128 | ||
| encoder_dropout: 0.25 | ||
| encoder_rnn_size: 128 | ||
| use_bi_rnn: true | ||
| rnn_num_layers: 1 | ||
|
|
||
| # Decoder | ||
| decoder_size: 320 | ||
| decoder_num_layers: 1 | ||
| rnn_dropout: 0.5 | ||
|
|
||
| optimizer: | ||
| optimizer: "Momentum" | ||
| nesterov: true | ||
| lr: 0.01 | ||
| weight_decay: 0 | ||
| decay_gamma: 0.95 | ||
|
|
||
| train: | ||
| gpu: 1 | ||
| n_epochs: 100 | ||
| patience: 10 | ||
| clip_norm: 5 | ||
| teacher_forcing: 1.0 | ||
| val_every_epoch: 1 | ||
| save_every_epoch: 1 | ||
| log_every_n_steps: 10 |
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,7 +1,11 @@ | ||
| torch==1.10.0 | ||
| pytorch-lightning==1.5.1 | ||
| torchmetrics==0.6.0 | ||
| tqdm==4.62.3 | ||
| wandb==0.12.6 | ||
| omegaconf==2.1.1 | ||
| commode-utils==0.4.1 | ||
| torch==1.12.0 | ||
| pytorch-lightning==1.6.5 | ||
| torchmetrics==0.9.2 | ||
| tqdm==4.64.0 | ||
| wandb==0.12.21 | ||
| omegaconf==2.2.2 | ||
| commode-utils==0.4.2 | ||
| typing==3.7.4.3 | ||
| transformers==4.20.1 | ||
| setuptools==63.2.0 | ||
| sacrebleu>=2.0.0 |
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.