python_code
stringlengths
0
187k
repo_name
stringlengths
8
46
file_path
stringlengths
6
135
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/__init__.py
from __future__ import print_function, unicode_literals, division import os import pdb import re import codecs import platform from subprocess import check_output from tempfile import mkdtemp from functools import partial try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser from gehrmann_rouge_opennmt.rouge_baselines.pyrouge.pyrouge.utils import log from gehrmann_rouge_opennmt.rouge_baselines.pyrouge.pyrouge.utils.file_utils import DirectoryProcessor from gehrmann_rouge_opennmt.rouge_baselines.pyrouge.pyrouge.utils.file_utils import verify_dir class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on filename patterns. This class can be used within Python like this: rouge = Rouge155() rouge.system_dir = 'test/systems' rouge.model_dir = 'test/models' # The system filename pattern should contain one group that # matches the document ID. rouge.system_filename_pattern = 'SL.P.10.R.11.SL062003-(\d+).html' # The model filename pattern has '#ID#' as a placeholder for the # document ID. If there are multiple model summaries, pyrouge # will use the provided regex to automatically match them with # the corresponding system summary. Here, [A-Z] matches # multiple model summaries for a given #ID#. rouge.model_filename_pattern = 'SL.P.10.R.[A-Z].SL062003-#ID#.html' rouge_output = rouge.evaluate() print(rouge_output) output_dict = rouge.output_to_dict(rouge_ouput) print(output_dict) -> {'rouge_1_f_score': 0.95652, 'rouge_1_f_score_cb': 0.95652, 'rouge_1_f_score_ce': 0.95652, 'rouge_1_precision': 0.95652, [...] To evaluate multiple systems: rouge = Rouge155() rouge.system_dir = '/PATH/TO/systems' rouge.model_dir = 'PATH/TO/models' for system_id in ['id1', 'id2', 'id3']: rouge.system_filename_pattern = \ 'SL.P/.10.R.{}.SL062003-(\d+).html'.format(system_id) rouge.model_filename_pattern = \ 'SL.P.10.R.[A-Z].SL062003-#ID#.html' rouge_output = rouge.evaluate(system_id) print(rouge_output) """ def __init__(self, rouge_dir=None, rouge_args=None, log_level=None): """ Create a Rouge155 object. rouge_dir: Directory containing Rouge-1.5.5.pl rouge_args: Arguments to pass through to ROUGE if you don't want to use the default pyrouge arguments. """ if log_level is None: self.log = log.get_global_console_logger() else: self.log = log.get_global_console_logger(log_level) self.__set_dir_properties() self._config_file = None self._settings_file = self.__get_config_path() self.__set_rouge_dir(rouge_dir) self.args = self.__clean_rouge_args(rouge_args) self._system_filename_pattern = None self._model_filename_pattern = None def save_home_dir(self): config = ConfigParser() section = 'pyrouge settings' config.add_section(section) config.set(section, 'home_dir', self._home_dir) with open(self._settings_file, 'w') as f: config.write(f) self.log.info("Set ROUGE home directory to {}.".format(self._home_dir)) @property def settings_file(self): """ Path of the setttings file, which stores the ROUGE home dir. """ return self._settings_file @property def bin_path(self): """ The full path of the ROUGE binary (although it's technically a script), i.e. rouge_home_dir/ROUGE-1.5.5.pl """ if self._bin_path is None: raise Exception( "ROUGE path not set. Please set the ROUGE home directory " "and ensure that ROUGE-1.5.5.pl exists in it.") return self._bin_path @property def system_filename_pattern(self): """ The regular expression pattern for matching system summary filenames. The regex string. E.g. "SL.P.10.R.11.SL062003-(\d+).html" will match the system filenames in the SPL2003/system folder of the ROUGE SPL example in the "sample-test" folder. Currently, there is no support for multiple systems. """ return self._system_filename_pattern @system_filename_pattern.setter def system_filename_pattern(self, pattern): self._system_filename_pattern = pattern @property def model_filename_pattern(self): """ The regular expression pattern for matching model summary filenames. The pattern needs to contain the string "#ID#", which is a placeholder for the document ID. E.g. "SL.P.10.R.[A-Z].SL062003-#ID#.html" will match the model filenames in the SPL2003/system folder of the ROUGE SPL example in the "sample-test" folder. "#ID#" is a placeholder for the document ID which has been matched by the "(\d+)" part of the system filename pattern. The different model summaries for a given document ID are matched by the "[A-Z]" part. """ return self._model_filename_pattern @model_filename_pattern.setter def model_filename_pattern(self, pattern): self._model_filename_pattern = pattern @property def config_file(self): return self._config_file @config_file.setter def config_file(self, path): config_dir, _ = os.path.split(path) verify_dir(config_dir, "configuration file") self._config_file = path def split_sentences(self): """ ROUGE requires texts split into sentences. In case the texts are not already split, this method can be used. """ from pyrouge.utils.sentence_splitter import PunktSentenceSplitter self.log.info("Splitting sentences.") ss = PunktSentenceSplitter() sent_split_to_string = lambda s: "\n".join(ss.split(s)) process_func = partial( DirectoryProcessor.process, function=sent_split_to_string) self.__process_summaries(process_func) @staticmethod def convert_summaries_to_rouge_format(input_dir, output_dir): """ Convert all files in input_dir into a format ROUGE understands and saves the files to output_dir. The input files are assumed to be plain text with one sentence per line. input_dir: Path of directory containing the input files. output_dir: Path of directory in which the converted files will be saved. """ DirectoryProcessor.process( input_dir, output_dir, Rouge155.convert_text_to_rouge_format) @staticmethod def convert_text_to_rouge_format(text, title="dummy title"): """ Convert a text to a format ROUGE understands. The text is assumed to contain one sentence per line. text: The text to convert, containg one sentence per line. title: Optional title for the text. The title will appear in the converted file, but doesn't seem to have any other relevance. Returns: The converted text as string. """ sentences = text.split("\n") sent_elems = [ "<a name=\"{i}\">[{i}]</a> <a href=\"#{i}\" id={i}>" "{text}</a>".format(i=i, text=sent) for i, sent in enumerate(sentences, start=1)] html = """<html> <head> <title>{title}</title> </head> <body bgcolor="white"> {elems} </body> </html>""".format(title=title, elems="\n".join(sent_elems)) return html @staticmethod def write_config_static(system_dir, system_filename_pattern, model_dir, model_filename_pattern, config_file_path, system_id=None): """ Write the ROUGE configuration file, which is basically a list of system summary files and their corresponding model summary files. pyrouge uses regular expressions to automatically find the matching model summary files for a given system summary file (cf. docstrings for system_filename_pattern and model_filename_pattern). system_dir: Path of directory containing system summaries. system_filename_pattern: Regex string for matching system summary filenames. model_dir: Path of directory containing model summaries. model_filename_pattern: Regex string for matching model summary filenames. config_file_path: Path of the configuration file. system_id: Optional system ID string which will appear in the ROUGE output. """ system_filenames = [f for f in os.listdir(system_dir)] system_models_tuples = [] system_filename_pattern = re.compile(system_filename_pattern) for system_filename in sorted(system_filenames, key=lambda x: int(x.split('.')[0])): # pdb.set_trace() match = system_filename_pattern.match(system_filename) if match: id = match.groups(0)[0] model_filenames = Rouge155.__get_model_filenames_for_id( id, model_dir, model_filename_pattern) system_models_tuples.append( (system_filename, sorted(model_filenames))) if not system_models_tuples: raise Exception( "Did not find any files matching the pattern {} " "in the system summaries directory {}.".format( system_filename_pattern.pattern, system_dir)) with codecs.open(config_file_path, 'w', encoding='utf-8') as f: f.write('<ROUGE-EVAL version="1.55">') for task_id, (system_filename, model_filenames) in enumerate( system_models_tuples, start=1): eval_string = Rouge155.__get_eval_string( task_id, system_id, system_dir, system_filename, model_dir, model_filenames) f.write(eval_string) f.write("</ROUGE-EVAL>") def write_config(self, config_file_path=None, system_id=None): """ Write the ROUGE configuration file, which is basically a list of system summary files and their matching model summary files. This is a non-static version of write_config_file_static(). config_file_path: Path of the configuration file. system_id: Optional system ID string which will appear in the ROUGE output. """ if not system_id: system_id = 1 if (not config_file_path) or (not self._config_dir): self._config_dir = mkdtemp() config_filename = "rouge_conf.xml" else: config_dir, config_filename = os.path.split(config_file_path) verify_dir(config_dir, "configuration file") self._config_file = os.path.join(self._config_dir, config_filename) Rouge155.write_config_static( self._system_dir, self._system_filename_pattern, self._model_dir, self._model_filename_pattern, self._config_file, system_id) # self.log.info( # "Written ROUGE configuration to {}".format(self._config_file)) def evaluate(self, system_id=1, rouge_args=None): """ Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id: Optional system ID which will be printed in ROUGE's output. Returns: Rouge output as string. """ self.write_config(system_id=system_id) options = self.__get_options(rouge_args) command = [self._bin_path] + options env = os.environ.copy() if hasattr(self, "_home_dir") and self._home_dir: env['ROUGE_EVAL_HOME'] = self._home_dir # self.log.info( # "Running ROUGE with command {}".format(" ".join(command))) rouge_output = check_output(command, env=env).decode("UTF-8") return rouge_output def convert_and_evaluate(self, system_id=1, split_sentences=False, rouge_args=None): """ Convert plain text summaries to ROUGE format and run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. Optionally split texts into sentences in case they aren't already. This is just a convenience method combining convert_summaries_to_rouge_format() and evaluate(). split_sentences: Optional argument specifying if sentences should be split. system_id: Optional system ID which will be printed in ROUGE's output. Returns: ROUGE output as string. """ if split_sentences: self.split_sentences() self.__write_summaries() rouge_output = self.evaluate(system_id, rouge_args) return rouge_output def output_to_dict(self, output, get_each_score): """ Convert the ROUGE output into python dictionary for further processing. """ #0 ROUGE-1 Average_R: 0.02632 (95%-conf.int. 0.02632 - 0.02632) pattern = re.compile( r"(\d+) (ROUGE-\S+) (Average_\w): (\d.\d+) " r"\(95%-conf.int. (\d.\d+) - (\d.\d+)\)") individual_score_pattern = re.compile( r"(\d+) (ROUGE-\S+) Eval (\d+).1 R:(\d.\d+) P:(\d.\d+) F:(\d.\d+)" ) results = {} if get_each_score: results['individual_score_results'] = {} for line in output.split("\n"): match = pattern.match(line) if match: sys_id, rouge_type, measure, result, conf_begin, conf_end = \ match.groups() measure = { 'Average_R': 'recall', 'Average_P': 'precision', 'Average_F': 'f_score' }[measure] rouge_type = rouge_type.lower().replace("-", '_') key = "{}_{}".format(rouge_type, measure) results[key] = float(result) results["{}_cb".format(key)] = float(conf_begin) results["{}_ce".format(key)] = float(conf_end) if get_each_score: individual_score_match = individual_score_pattern.match(line) if individual_score_match: sys_id, rouge_type, eval_id, recall, precision, f_score = individual_score_match.groups() eval_id = int(eval_id) eval_id = eval_id - 1 # IMPORTANT: pyrouge returns doc_ids starting from 1, we want them to start at 0 rouge_type = rouge_type.lower().replace("-", '_') if eval_id not in results['individual_score_results'].keys(): results['individual_score_results'][eval_id] = {} results['individual_score_results'][eval_id][f'{rouge_type}_recall'] = float(recall) results['individual_score_results'][eval_id][f'{rouge_type}_precision'] = float(precision) results['individual_score_results'][eval_id][f'{rouge_type}_f_score'] = float(f_score) return results ################################################################### # Private methods def __set_rouge_dir(self, home_dir=None): """ Verfify presence of ROUGE-1.5.5.pl and data folder, and set those paths. """ if not home_dir: self._home_dir = self.__get_rouge_home_dir_from_settings() else: self._home_dir = home_dir self.save_home_dir() self._bin_path = os.path.join(self._home_dir, 'ROUGE-1.5.5.pl') self.data_dir = os.path.join(self._home_dir, 'data') if not os.path.exists(self._bin_path): raise Exception( "ROUGE binary not found at {}. Please set the " "correct path by running pyrouge_set_rouge_path " "/path/to/rouge/home.".format(self._bin_path)) def __get_rouge_home_dir_from_settings(self): config = ConfigParser() with open(self._settings_file) as f: if hasattr(config, "read_file"): config.read_file(f) else: # use deprecated python 2.x method config.readfp(f) rouge_home_dir = config.get('pyrouge settings', 'home_dir') return rouge_home_dir @staticmethod def __get_eval_string( task_id, system_id, system_dir, system_filename, model_dir, model_filenames): """ ROUGE can evaluate several system summaries for a given text against several model summaries, i.e. there is an m-to-n relation between system and model summaries. The system summaries are listed in the <PEERS> tag and the model summaries in the <MODELS> tag. pyrouge currently only supports one system summary per text, i.e. it assumes a 1-to-n relation between system and model summaries. """ peer_elems = "<P ID=\"{id}\">{name}</P>".format( id=system_id, name=system_filename) model_elems = ["<M ID=\"{id}\">{name}</M>".format( id=chr(65 + i), name=name) for i, name in enumerate(model_filenames)] model_elems = "\n\t\t\t".join(model_elems) eval_string = """ <EVAL ID="{task_id}"> <MODEL-ROOT>{model_root}</MODEL-ROOT> <PEER-ROOT>{peer_root}</PEER-ROOT> <INPUT-FORMAT TYPE="SEE"> </INPUT-FORMAT> <PEERS> {peer_elems} </PEERS> <MODELS> {model_elems} </MODELS> </EVAL> """.format( task_id=task_id, model_root=model_dir, model_elems=model_elems, peer_root=system_dir, peer_elems=peer_elems) return eval_string def __process_summaries(self, process_func): """ Helper method that applies process_func to the files in the system and model folders and saves the resulting files to new system and model folders. """ temp_dir = mkdtemp() new_system_dir = os.path.join(temp_dir, "system") os.mkdir(new_system_dir) new_model_dir = os.path.join(temp_dir, "model") os.mkdir(new_model_dir) # self.log.info( # "Processing summaries. Saving system files to {} and " # "model files to {}.".format(new_system_dir, new_model_dir)) process_func(self._system_dir, new_system_dir) process_func(self._model_dir, new_model_dir) self._system_dir = new_system_dir self._model_dir = new_model_dir def __write_summaries(self): # self.log.info("Writing summaries.") self.__process_summaries(self.convert_summaries_to_rouge_format) @staticmethod def __get_model_filenames_for_id(id, model_dir, model_filenames_pattern): pattern = re.compile(model_filenames_pattern.replace('#ID#', id)) model_filenames = [ f for f in os.listdir(model_dir) if pattern.match(f)] if not model_filenames: raise Exception( "Could not find any model summaries for the system" " summary with ID {}. Specified model filename pattern was: " "{}".format(id, model_filenames_pattern)) return model_filenames def __get_options(self, rouge_args=None): """ Get supplied command line arguments for ROUGE or use default ones. """ if self.args: options = self.args.split() elif rouge_args: options = rouge_args.split() else: options = [ '-e', self._data_dir, '-c', 95, '-2', '-1', '-U', '-r', 1000, '-n', 4, '-w', 1.2, '-a', ] options = list(map(str, options)) options = self.__add_config_option(options) return options def __create_dir_property(self, dir_name, docstring): """ Generate getter and setter for a directory property. """ property_name = "{}_dir".format(dir_name) private_name = "_" + property_name setattr(self, private_name, None) def fget(self): return getattr(self, private_name) def fset(self, path): verify_dir(path, dir_name) setattr(self, private_name, path) p = property(fget=fget, fset=fset, doc=docstring) setattr(self.__class__, property_name, p) def __set_dir_properties(self): """ Automatically generate the properties for directories. """ directories = [ ("home", "The ROUGE home directory."), ("data", "The path of the ROUGE 'data' directory."), ("system", "Path of the directory containing system summaries."), ("model", "Path of the directory containing model summaries."), ] for (dirname, docstring) in directories: self.__create_dir_property(dirname, docstring) def __clean_rouge_args(self, rouge_args): """ Remove enclosing quotation marks, if any. """ if not rouge_args: return quot_mark_pattern = re.compile('"(.+)"') match = quot_mark_pattern.match(rouge_args) if match: cleaned_args = match.group(1) return cleaned_args else: return rouge_args def __add_config_option(self, options): return options + ['-m'] + [self._config_file] def __get_config_path(self): if platform.system() == "Windows": parent_dir = os.getenv("APPDATA") config_dir_name = "pyrouge" elif os.name == "posix": parent_dir = os.path.expanduser("~") config_dir_name = ".pyrouge" else: parent_dir = os.path.dirname(__file__) config_dir_name = "" config_dir = os.path.join(parent_dir, config_dir_name) if not os.path.exists(config_dir): os.makedirs(config_dir) return os.path.join(config_dir, 'settings.ini') if __name__ == "__main__": import argparse from utils.argparsers import rouge_path_parser parser = argparse.ArgumentParser(parents=[rouge_path_parser]) args = parser.parse_args() rouge = Rouge155(args.rouge_home) rouge.save_home_dir()
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/Rouge155.py
# -*- coding: utf-8 -*- # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ROUGe metric implementation. This is a modified and slightly extended verison of https://github.com/miso-belica/sumy/blob/dev/sumy/evaluation/rouge.py. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import itertools import numpy as np #pylint: disable=C0103 def _get_ngrams(n, text): """Calcualtes n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(text[i:i + n])) return ngram_set def _split_into_words(sentences): """Splits multiple sentences into words and flattens the result""" return list(itertools.chain(*[_.split() for _ in sentences])) def _get_word_ngrams(n, sentences): """Calculates word n-grams for multiple sentences. """ assert len(sentences) > 0 assert n > 0 words = _split_into_words(sentences) return _get_ngrams(n, words) def _len_lcs(x, y): """ Returns the length of the Longest Common Subsequence between sequences x and y. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y """ table = _lcs(x, y) n, m = len(x), len(y) return table[n, m] def _lcs(x, y): """ Computes the length of the longest common subsequence (lcs) between two strings. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of words Returns: Table of dictionary of coord and len lcs """ n, m = len(x), len(y) table = dict() for i in range(n + 1): for j in range(m + 1): if i == 0 or j == 0: table[i, j] = 0 elif x[i - 1] == y[j - 1]: table[i, j] = table[i - 1, j - 1] + 1 else: table[i, j] = max(table[i - 1, j], table[i, j - 1]) return table def _recon_lcs(x, y): """ Returns the Longest Subsequence between x and y. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns: sequence: LCS of x and y """ i, j = len(x), len(y) table = _lcs(x, y) def _recon(i, j): """private recon calculation""" if i == 0 or j == 0: return [] elif x[i - 1] == y[j - 1]: return _recon(i - 1, j - 1) + [(x[i - 1], i)] elif table[i - 1, j] > table[i, j - 1]: return _recon(i - 1, j) else: return _recon(i, j - 1) recon_tuple = tuple(map(lambda x: x[0], _recon(i, j))) return recon_tuple def rouge_n(evaluated_sentences, reference_sentences, n=2): """ Computes ROUGE-N of two text collections of sentences. Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/ papers/rouge-working-note-v1.3.1.pdf Args: evaluated_sentences: The sentences that have been picked by the summarizer reference_sentences: The sentences from the referene set n: Size of ngram. Defaults to 2. Returns: A tuple (f1, precision, recall) for ROUGE-N Raises: ValueError: raises exception if a param has len <= 0 """ if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0: raise ValueError("Collections must contain at least 1 sentence.") evaluated_ngrams = _get_word_ngrams(n, evaluated_sentences) reference_ngrams = _get_word_ngrams(n, reference_sentences) reference_count = len(reference_ngrams) evaluated_count = len(evaluated_ngrams) # Gets the overlapping ngrams between evaluated and reference overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams) overlapping_count = len(overlapping_ngrams) # Handle edge case. This isn't mathematically correct, but it's good enough if evaluated_count == 0: precision = 0.0 else: precision = overlapping_count / evaluated_count if reference_count == 0: recall = 0.0 else: recall = overlapping_count / reference_count f1_score = 2.0 * ((precision * recall) / (precision + recall + 1e-8)) # return overlapping_count / reference_count return f1_score, precision, recall def _f_p_r_lcs(llcs, m, n): """ Computes the LCS-based F-measure score Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-working-note-v1.3.1.pdf Args: llcs: Length of LCS m: number of words in reference summary n: number of words in candidate summary Returns: Float. LCS-based F-measure score """ r_lcs = llcs / m p_lcs = llcs / n beta = p_lcs / (r_lcs + 1e-12) num = (1 + (beta**2)) * r_lcs * p_lcs denom = r_lcs + ((beta**2) * p_lcs) f_lcs = num / (denom + 1e-12) return f_lcs, p_lcs, r_lcs def rouge_l_sentence_level(evaluated_sentences, reference_sentences): """ Computes ROUGE-L (sentence level) of two text collections of sentences. http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-working-note-v1.3.1.pdf Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)/n F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs) where: X = reference summary Y = Candidate summary m = length of reference summary n = length of candidate summary Args: evaluated_sentences: The sentences that have been picked by the summarizer reference_sentences: The sentences from the referene set Returns: A float: F_lcs Raises: ValueError: raises exception if a param has len <= 0 """ if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0: raise ValueError("Collections must contain at least 1 sentence.") reference_words = _split_into_words(reference_sentences) evaluated_words = _split_into_words(evaluated_sentences) m = len(reference_words) n = len(evaluated_words) lcs = _len_lcs(evaluated_words, reference_words) return _f_p_r_lcs(lcs, m, n) def _union_lcs(evaluated_sentences, reference_sentence): """ Returns LCS_u(r_i, C) which is the LCS score of the union longest common subsequence between reference sentence ri and candidate summary C. For example if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and c2 = w1 w3 w8 w9 w5, then the longest common subsequence of r_i and c1 is “w1 w2” and the longest common subsequence of r_i and c2 is “w1 w3 w5”. The union longest common subsequence of r_i, c1, and c2 is “w1 w2 w3 w5” and LCS_u(r_i, C) = 4/5. Args: evaluated_sentences: The sentences that have been picked by the summarizer reference_sentence: One of the sentences in the reference summaries Returns: float: LCS_u(r_i, C) ValueError: Raises exception if a param has len <= 0 """ if len(evaluated_sentences) <= 0: raise ValueError("Collections must contain at least 1 sentence.") lcs_union = set() reference_words = _split_into_words([reference_sentence]) combined_lcs_length = 0 for eval_s in evaluated_sentences: evaluated_words = _split_into_words([eval_s]) lcs = set(_recon_lcs(reference_words, evaluated_words)) combined_lcs_length += len(lcs) lcs_union = lcs_union.union(lcs) union_lcs_count = len(lcs_union) union_lcs_value = union_lcs_count / combined_lcs_length return union_lcs_value def rouge_l_summary_level(evaluated_sentences, reference_sentences): """ Computes ROUGE-L (summary level) of two text collections of sentences. http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-working-note-v1.3.1.pdf Calculated according to: R_lcs = SUM(1, u)[LCS<union>(r_i,C)]/m P_lcs = SUM(1, u)[LCS<union>(r_i,C)]/n F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs) where: SUM(i,u) = SUM from i through u u = number of sentences in reference summary C = Candidate summary made up of v sentences m = number of words in reference summary n = number of words in candidate summary Args: evaluated_sentences: The sentences that have been picked by the summarizer reference_sentence: One of the sentences in the reference summaries Returns: A float: F_lcs Raises: ValueError: raises exception if a param has len <= 0 """ if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0: raise ValueError("Collections must contain at least 1 sentence.") # total number of words in reference sentences m = len(_split_into_words(reference_sentences)) # total number of words in evaluated sentences n = len(_split_into_words(evaluated_sentences)) union_lcs_sum_across_all_references = 0 for ref_s in reference_sentences: union_lcs_sum_across_all_references += _union_lcs(evaluated_sentences, ref_s) return _f_p_r_lcs(union_lcs_sum_across_all_references, m, n) def rouge(hypotheses, references): """Calculates average rouge scores for a list of hypotheses and references""" # Filter out hyps that are of 0 length # hyps_and_refs = zip(hypotheses, references) # hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0] # hypotheses, references = zip(*hyps_and_refs) # Calculate ROUGE-1 F1, precision, recall scores rouge_1 = [ rouge_n(hyp, ref, 1) for hyp, ref in zip(hypotheses, references) ] rouge_1_f, rouge_1_p, rouge_1_r = map(np.mean, zip(*rouge_1)) # Calculate ROUGE-2 F1, precision, recall scores rouge_2 = [ rouge_n(hyp, ref, 2) for hyp, ref in zip(hypotheses, references) ] rouge_2_f, rouge_2_p, rouge_2_r = map(np.mean, zip(*rouge_2)) # Calculate ROUGE-L F1, precision, recall scores rouge_l = [ rouge_l_sentence_level(hyp, ref) for hyp, ref in zip(hypotheses, references) ] rouge_l_f, rouge_l_p, rouge_l_r = map(np.mean, zip(*rouge_l)) return { "rouge_1/f_score": rouge_1_f, "rouge_1/r_score": rouge_1_r, "rouge_1/p_score": rouge_1_p, "rouge_2/f_score": rouge_2_f, "rouge_2/r_score": rouge_2_r, "rouge_2/p_score": rouge_2_p, "rouge_l/f_score": rouge_l_f, "rouge_l/r_score": rouge_l_r, "rouge_l/p_score": rouge_l_p, } if __name__ == '__main__': from baseline import split_sentences article = r'''<s> marseille prosecutor says `` so far no videos were used in the crash investigation '' despite media reports . </s> <s> journalists at bild and paris match are `` very confident '' the video clip is real , an editor says . </s> <s> andreas lubitz had informed his lufthansa training school of an episode of severe depression , airline says . </s>''' sents = split_sentences(article) print(sents) print(rouge([sents], [sents]))
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/g_rouge.py
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/__init__.py
from setuptools import setup import os from pyrouge.utils.file_utils import list_files data_files = list_files('pyrouge/tests/data') data_files = [p.replace('pyrouge/tests/', '') for p in data_files] script_files = [os.path.join('bin', s) for s in os.listdir('bin')] setup( name='pyrouge', version='0.1.3', author='Benjamin Heinzerling, Anders Johannsen', author_email='[email protected]', packages=['pyrouge', 'pyrouge.utils', 'pyrouge.tests'], scripts=script_files, #test_suite='pyrouge.test.suite', package_data={'pyrouge.tests': data_files}, url='https://github.com/noutenki/pyrouge', license='LICENSE.txt', description='A Python wrapper for the ROUGE summarization evaluation' ' package.', classifiers=[ 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Text Processing :: Linguistic'], long_description=open('README.rst').read(), )
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/setup.py
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/bin/__init__.py
# from pyrouge.Rouge155 import Rouge155
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/__init__.py
import unittest from pyrouge.tests.Rouge155_test import PyrougeTest loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(loader.loadTestsFromTestCase(PyrougeTest)) unittest.TextTestRunner().run(suite)
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/test.py
from __future__ import print_function, unicode_literals, division import os import re import codecs import platform from subprocess import check_output from tempfile import mkdtemp from functools import partial try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser from pyrouge.utils import log from pyrouge.utils.file_utils import DirectoryProcessor from pyrouge.utils.file_utils import verify_dir class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on filename patterns. This class can be used within Python like this: rouge = Rouge155() rouge.system_dir = 'test/systems' rouge.model_dir = 'test/models' # The system filename pattern should contain one group that # matches the document ID. rouge.system_filename_pattern = 'SL.P.10.R.11.SL062003-(\d+).html' # The model filename pattern has '#ID#' as a placeholder for the # document ID. If there are multiple model summaries, pyrouge # will use the provided regex to automatically match them with # the corresponding system summary. Here, [A-Z] matches # multiple model summaries for a given #ID#. rouge.model_filename_pattern = 'SL.P.10.R.[A-Z].SL062003-#ID#.html' rouge_output = rouge.evaluate() print(rouge_output) output_dict = rouge.output_to_dict(rouge_ouput) print(output_dict) -> {'rouge_1_f_score': 0.95652, 'rouge_1_f_score_cb': 0.95652, 'rouge_1_f_score_ce': 0.95652, 'rouge_1_precision': 0.95652, [...] To evaluate multiple systems: rouge = Rouge155() rouge.system_dir = '/PATH/TO/systems' rouge.model_dir = 'PATH/TO/models' for system_id in ['id1', 'id2', 'id3']: rouge.system_filename_pattern = \ 'SL.P/.10.R.{}.SL062003-(\d+).html'.format(system_id) rouge.model_filename_pattern = \ 'SL.P.10.R.[A-Z].SL062003-#ID#.html' rouge_output = rouge.evaluate(system_id) print(rouge_output) """ def __init__(self, rouge_dir=None, rouge_args=None, log_level=None): """ Create a Rouge155 object. rouge_dir: Directory containing Rouge-1.5.5.pl rouge_args: Arguments to pass through to ROUGE if you don't want to use the default pyrouge arguments. """ if log_level is None: self.log = log.get_global_console_logger() else: self.log = log.get_global_console_logger(log_level) self.__set_dir_properties() self._config_file = None self._settings_file = self.__get_config_path() self.__set_rouge_dir(rouge_dir) self.args = self.__clean_rouge_args(rouge_args) self._system_filename_pattern = None self._model_filename_pattern = None def save_home_dir(self): config = ConfigParser() section = 'pyrouge settings' config.add_section(section) config.set(section, 'home_dir', self._home_dir) with open(self._settings_file, 'w') as f: config.write(f) self.log.info("Set ROUGE home directory to {}.".format(self._home_dir)) @property def settings_file(self): """ Path of the setttings file, which stores the ROUGE home dir. """ return self._settings_file @property def bin_path(self): """ The full path of the ROUGE binary (although it's technically a script), i.e. rouge_home_dir/ROUGE-1.5.5.pl """ if self._bin_path is None: raise Exception( "ROUGE path not set. Please set the ROUGE home directory " "and ensure that ROUGE-1.5.5.pl exists in it.") return self._bin_path @property def system_filename_pattern(self): """ The regular expression pattern for matching system summary filenames. The regex string. E.g. "SL.P.10.R.11.SL062003-(\d+).html" will match the system filenames in the SPL2003/system folder of the ROUGE SPL example in the "sample-test" folder. Currently, there is no support for multiple systems. """ return self._system_filename_pattern @system_filename_pattern.setter def system_filename_pattern(self, pattern): self._system_filename_pattern = pattern @property def model_filename_pattern(self): """ The regular expression pattern for matching model summary filenames. The pattern needs to contain the string "#ID#", which is a placeholder for the document ID. E.g. "SL.P.10.R.[A-Z].SL062003-#ID#.html" will match the model filenames in the SPL2003/system folder of the ROUGE SPL example in the "sample-test" folder. "#ID#" is a placeholder for the document ID which has been matched by the "(\d+)" part of the system filename pattern. The different model summaries for a given document ID are matched by the "[A-Z]" part. """ return self._model_filename_pattern @model_filename_pattern.setter def model_filename_pattern(self, pattern): self._model_filename_pattern = pattern @property def config_file(self): return self._config_file @config_file.setter def config_file(self, path): config_dir, _ = os.path.split(path) verify_dir(config_dir, "configuration file") self._config_file = path def split_sentences(self): """ ROUGE requires texts split into sentences. In case the texts are not already split, this method can be used. """ from pyrouge.utils.sentence_splitter import PunktSentenceSplitter self.log.info("Splitting sentences.") ss = PunktSentenceSplitter() sent_split_to_string = lambda s: "\n".join(ss.split(s)) process_func = partial( DirectoryProcessor.process, function=sent_split_to_string) self.__process_summaries(process_func) @staticmethod def convert_summaries_to_rouge_format(input_dir, output_dir): """ Convert all files in input_dir into a format ROUGE understands and saves the files to output_dir. The input files are assumed to be plain text with one sentence per line. input_dir: Path of directory containing the input files. output_dir: Path of directory in which the converted files will be saved. """ DirectoryProcessor.process( input_dir, output_dir, Rouge155.convert_text_to_rouge_format) @staticmethod def convert_text_to_rouge_format(text, title="dummy title"): """ Convert a text to a format ROUGE understands. The text is assumed to contain one sentence per line. text: The text to convert, containg one sentence per line. title: Optional title for the text. The title will appear in the converted file, but doesn't seem to have any other relevance. Returns: The converted text as string. """ sentences = text.split("\n") sent_elems = [ "<a name=\"{i}\">[{i}]</a> <a href=\"#{i}\" id={i}>" "{text}</a>".format(i=i, text=sent) for i, sent in enumerate(sentences, start=1)] html = """<html> <head> <title>{title}</title> </head> <body bgcolor="white"> {elems} </body> </html>""".format(title=title, elems="\n".join(sent_elems)) return html @staticmethod def write_config_static(system_dir, system_filename_pattern, model_dir, model_filename_pattern, config_file_path, system_id=None): """ Write the ROUGE configuration file, which is basically a list of system summary files and their corresponding model summary files. pyrouge uses regular expressions to automatically find the matching model summary files for a given system summary file (cf. docstrings for system_filename_pattern and model_filename_pattern). system_dir: Path of directory containing system summaries. system_filename_pattern: Regex string for matching system summary filenames. model_dir: Path of directory containing model summaries. model_filename_pattern: Regex string for matching model summary filenames. config_file_path: Path of the configuration file. system_id: Optional system ID string which will appear in the ROUGE output. """ system_filenames = [f for f in os.listdir(system_dir)] system_models_tuples = [] system_filename_pattern = re.compile(system_filename_pattern) for system_filename in sorted(system_filenames): match = system_filename_pattern.match(system_filename) if match: id = match.groups(0)[0] model_filenames = Rouge155.__get_model_filenames_for_id( id, model_dir, model_filename_pattern) system_models_tuples.append( (system_filename, sorted(model_filenames))) if not system_models_tuples: raise Exception( "Did not find any files matching the pattern {} " "in the system summaries directory {}.".format( system_filename_pattern.pattern, system_dir)) with codecs.open(config_file_path, 'w', encoding='utf-8') as f: f.write('<ROUGE-EVAL version="1.55">') for task_id, (system_filename, model_filenames) in enumerate( system_models_tuples, start=1): eval_string = Rouge155.__get_eval_string( task_id, system_id, system_dir, system_filename, model_dir, model_filenames) f.write(eval_string) f.write("</ROUGE-EVAL>") def write_config(self, config_file_path=None, system_id=None): """ Write the ROUGE configuration file, which is basically a list of system summary files and their matching model summary files. This is a non-static version of write_config_file_static(). config_file_path: Path of the configuration file. system_id: Optional system ID string which will appear in the ROUGE output. """ if not system_id: system_id = 1 if (not config_file_path) or (not self._config_dir): self._config_dir = mkdtemp() config_filename = "rouge_conf.xml" else: config_dir, config_filename = os.path.split(config_file_path) verify_dir(config_dir, "configuration file") self._config_file = os.path.join(self._config_dir, config_filename) Rouge155.write_config_static( self._system_dir, self._system_filename_pattern, self._model_dir, self._model_filename_pattern, self._config_file, system_id) self.log.info( "Written ROUGE configuration to {}".format(self._config_file)) def evaluate(self, system_id=1, rouge_args=None): """ Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id: Optional system ID which will be printed in ROUGE's output. Returns: Rouge output as string. """ self.write_config(system_id=system_id) options = self.__get_options(rouge_args) command = [self._bin_path] + options self.log.info( "Running ROUGE with command {}".format(" ".join(command))) rouge_output = check_output(command).decode("UTF-8") return rouge_output def convert_and_evaluate(self, system_id=1, split_sentences=False, rouge_args=None): """ Convert plain text summaries to ROUGE format and run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. Optionally split texts into sentences in case they aren't already. This is just a convenience method combining convert_summaries_to_rouge_format() and evaluate(). split_sentences: Optional argument specifying if sentences should be split. system_id: Optional system ID which will be printed in ROUGE's output. Returns: ROUGE output as string. """ if split_sentences: self.split_sentences() self.__write_summaries() rouge_output = self.evaluate(system_id, rouge_args) # return rouge_output return "" #Pgour DEBUG def output_to_dict(self, output): """ Convert the ROUGE output into python dictionary for further processing. """ #0 ROUGE-1 Average_R: 0.02632 (95%-conf.int. 0.02632 - 0.02632) pattern = re.compile( r"(\d+) (ROUGE-\S+) (Average_\w): (\d.\d+) " r"\(95%-conf.int. (\d.\d+) - (\d.\d+)\)") results = {} for line in output.split("\n"): match = pattern.match(line) if match: sys_id, rouge_type, measure, result, conf_begin, conf_end = \ match.groups() measure = { 'Average_R': 'recall', 'Average_P': 'precision', 'Average_F': 'f_score' }[measure] rouge_type = rouge_type.lower().replace("-", '_') key = "{}_{}".format(rouge_type, measure) results[key] = float(result) results["{}_cb".format(key)] = float(conf_begin) results["{}_ce".format(key)] = float(conf_end) return results ################################################################### # Private methods def __set_rouge_dir(self, home_dir=None): """ Verfify presence of ROUGE-1.5.5.pl and data folder, and set those paths. """ if not home_dir: self._home_dir = self.__get_rouge_home_dir_from_settings() else: self._home_dir = home_dir self.save_home_dir() self._bin_path = os.path.join(self._home_dir, 'ROUGE-1.5.5.pl') self.data_dir = os.path.join(self._home_dir, 'data') if not os.path.exists(self._bin_path): raise Exception( "ROUGE binary not found at {}. Please set the " "correct path by running pyrouge_set_rouge_path " "/path/to/rouge/home.".format(self._bin_path)) def __get_rouge_home_dir_from_settings(self): config = ConfigParser() with open(self._settings_file) as f: if hasattr(config, "read_file"): config.read_file(f) else: # use deprecated python 2.x method config.readfp(f) rouge_home_dir = config.get('pyrouge settings', 'home_dir') return rouge_home_dir @staticmethod def __get_eval_string( task_id, system_id, system_dir, system_filename, model_dir, model_filenames): """ ROUGE can evaluate several system summaries for a given text against several model summaries, i.e. there is an m-to-n relation between system and model summaries. The system summaries are listed in the <PEERS> tag and the model summaries in the <MODELS> tag. pyrouge currently only supports one system summary per text, i.e. it assumes a 1-to-n relation between system and model summaries. """ peer_elems = "<P ID=\"{id}\">{name}</P>".format( id=system_id, name=system_filename) model_elems = ["<M ID=\"{id}\">{name}</M>".format( id=chr(65 + i), name=name) for i, name in enumerate(model_filenames)] model_elems = "\n\t\t\t".join(model_elems) eval_string = """ <EVAL ID="{task_id}"> <MODEL-ROOT>{model_root}</MODEL-ROOT> <PEER-ROOT>{peer_root}</PEER-ROOT> <INPUT-FORMAT TYPE="SEE"> </INPUT-FORMAT> <PEERS> {peer_elems} </PEERS> <MODELS> {model_elems} </MODELS> </EVAL> """.format( task_id=task_id, model_root=model_dir, model_elems=model_elems, peer_root=system_dir, peer_elems=peer_elems) return eval_string def __process_summaries(self, process_func): """ Helper method that applies process_func to the files in the system and model folders and saves the resulting files to new system and model folders. """ temp_dir = mkdtemp() new_system_dir = os.path.join(temp_dir, "system") os.mkdir(new_system_dir) new_model_dir = os.path.join(temp_dir, "model") os.mkdir(new_model_dir) self.log.info( "Processing summaries. Saving system files to {} and " "model files to {}.".format(new_system_dir, new_model_dir)) process_func(self._system_dir, new_system_dir) process_func(self._model_dir, new_model_dir) self._system_dir = new_system_dir self._model_dir = new_model_dir def __write_summaries(self): self.log.info("Writing summaries.") self.__process_summaries(self.convert_summaries_to_rouge_format) @staticmethod def __get_model_filenames_for_id(id, model_dir, model_filenames_pattern): pattern = re.compile(model_filenames_pattern.replace('#ID#', id)) model_filenames = [ f for f in os.listdir(model_dir) if pattern.match(f)] if not model_filenames: raise Exception( "Could not find any model summaries for the system" " summary with ID {}. Specified model filename pattern was: " "{}".format(id, model_filenames_pattern)) return model_filenames def __get_options(self, rouge_args=None): """ Get supplied command line arguments for ROUGE or use default ones. """ if self.args: options = self.args.split() elif rouge_args: options = rouge_args.split() else: options = [ '-m', '-c', 95, '-2', '-1', '-U', '-r', 1000, '-n', 4, '-w', 1.2, '-a', ] options = list(map(str, options)) options = self.__add_config_option(options) return options def __create_dir_property(self, dir_name, docstring): """ Generate getter and setter for a directory property. """ property_name = "{}_dir".format(dir_name) private_name = "_" + property_name setattr(self, private_name, None) def fget(self): return getattr(self, private_name) def fset(self, path): verify_dir(path, dir_name) setattr(self, private_name, path) p = property(fget=fget, fset=fset, doc=docstring) setattr(self.__class__, property_name, p) def __set_dir_properties(self): """ Automatically generate the properties for directories. """ directories = [ ("home", "The ROUGE home directory."), ("data", "The path of the ROUGE 'data' directory."), ("system", "Path of the directory containing system summaries."), ("model", "Path of the directory containing model summaries."), ] for (dirname, docstring) in directories: self.__create_dir_property(dirname, docstring) def __clean_rouge_args(self, rouge_args): """ Remove enclosing quotation marks, if any. """ if not rouge_args: return quot_mark_pattern = re.compile('"(.+)"') match = quot_mark_pattern.match(rouge_args) if match: cleaned_args = match.group(1) return cleaned_args else: return rouge_args def __add_config_option(self, options): return options + ['-e', self._data_dir] + [self._config_file] def __get_config_path(self): if platform.system() == "Windows": parent_dir = os.getenv("APPDATA") config_dir_name = "pyrouge" elif os.name == "posix": parent_dir = os.path.expanduser("~") config_dir_name = ".pyrouge" else: parent_dir = os.path.dirname(__file__) config_dir_name = "" config_dir = os.path.join(parent_dir, config_dir_name) if not os.path.exists(config_dir): os.makedirs(config_dir) return os.path.join(config_dir, 'settings.ini') if __name__ == "__main__": import argparse from utils.argparsers import rouge_path_parser parser = argparse.ArgumentParser(parents=[rouge_path_parser]) args = parser.parse_args() rouge = Rouge155(args.rouge_home) rouge.save_home_dir()
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/Rouge155.py
from __future__ import print_function, unicode_literals, division import unittest import os import re from subprocess import check_output from tempfile import mkdtemp from pyrouge import Rouge155 from pyrouge.utils.file_utils import str_from_file, xml_equal module_path = os.path.dirname(__file__) os.chdir(module_path) add_data_path = lambda p: os.path.join('data', p) check_output_clean = lambda c: check_output(c).decode("UTF-8").strip() class PyrougeTest(unittest.TestCase): def test_paths(self): rouge = Rouge155() def get_home_from_settings(): with open(rouge.settings_file) as f: for line in f.readlines(): if line.startswith("home_dir"): rouge_home = line.split("=")[1].strip() return rouge_home self.assertEqual(rouge.home_dir, get_home_from_settings()) self.assertTrue(os.path.exists(rouge.bin_path)) self.assertTrue(os.path.exists(rouge.data_dir)) wrong_path = "/nonexisting/path/rewafafkljaerearjafankwe3" with self.assertRaises(Exception) as context: rouge.system_dir = wrong_path self.assertEqual( str(context.exception), "Cannot set {} directory because the path {} does not " "exist.".format("system", wrong_path)) right_path = add_data_path("systems") rouge.system_dir = right_path self.assertEqual(rouge.system_dir, right_path) with self.assertRaises(Exception) as context: rouge.model_dir = wrong_path self.assertEqual( str(context.exception), "Cannot set {} directory because the path {} does not " "exist.".format("model", wrong_path)) right_path = add_data_path("models") rouge.model_dir = right_path self.assertEqual(rouge.model_dir, right_path) def test_wrong_system_pattern(self): wrong_regexp = "adfdas454fd" rouge = Rouge155() rouge.system_dir = add_data_path("systems") rouge.model_dir = add_data_path("models") #rouge.system_filename_pattern = "SL.P.10.R.11.SL062003-(\d+).html" rouge.system_filename_pattern = wrong_regexp rouge.model_filename_pattern = "SL.P.10.R.[A-D].SL062003-#ID#.html" with self.assertRaises(Exception) as context: rouge.evaluate() self.assertEqual( str(context.exception), "Did not find any files matching the pattern {} in the system " "summaries directory {}.".format(wrong_regexp, rouge.system_dir)) def test_wrong_model_pattern(self): rouge = Rouge155() rouge.system_dir = add_data_path("systems") rouge.model_dir = add_data_path("models_plain") rouge.system_filename_pattern = "SL.P.10.R.11.SL062003-(\d+).html" rouge.model_filename_pattern = "SL.P.10.R.[A-D].SL062003-#ID#.html" with self.assertRaises(Exception) as context: rouge.evaluate() match_string = ( r"Could not find any model summaries for the system " r"summary with ID " + "(\d+)" + r". Specified model filename " r"pattern was: " + re.escape(rouge.model_filename_pattern)) try: assert_regex = self.assertRegex except AttributeError: assert_regex = self.assertRegexpMatches assert_regex(str(context.exception), re.compile(match_string)) def test_text_conversion(self): rouge = Rouge155() text = str_from_file(add_data_path("spl_test_doc")) html = rouge.convert_text_to_rouge_format(text, "D00000.M.100.A.C") target = str_from_file(add_data_path("spl_test_doc.html")) self.assertEqual(html, target) # only run this test if BeautifulSoup is installed try: from bs4 import BeautifulSoup def test_get_plain_text(self): input_dir = add_data_path("SL2003_models_rouge_format") output_dir = mkdtemp() target_dir = add_data_path("SL2003_models_plain_text") command = ( "pyrouge_convert_rouge_format_to_plain_text " "-i {} -o {}".format(input_dir, output_dir)) check_output(command.split()) filenames = os.listdir(input_dir) for filename in filenames: output_file = os.path.join(output_dir, filename) output = str_from_file(output_file) target_file = os.path.join(target_dir, filename) target = str_from_file(target_file) self.assertEqual(output, target) except ImportError: pass def test_convert_summaries(self): input_dir = add_data_path("SL2003_models_plain_text") output_dir = mkdtemp() target_dir = add_data_path("SL2003_models_rouge_format") command = ( "pyrouge_convert_plain_text_to_rouge_format -i {} -o {}".format( input_dir, output_dir)) check_output(command.split()) filenames = os.listdir(input_dir) for filename in filenames: output_file = os.path.join(output_dir, filename) output = str_from_file(output_file) target_file = os.path.join(target_dir, filename) target = str_from_file(target_file) filename = filename.replace(".html", "") target = target.replace(filename, "dummy title") self.assertEqual(output, target, filename) def test_config_file(self): rouge = Rouge155() rouge.system_dir = add_data_path("systems") rouge.model_dir = add_data_path("models") rouge.system_filename_pattern = "SL.P.10.R.11.SL062003-(\d+).html" rouge.model_filename_pattern = "SL.P.10.R.[A-D].SL062003-#ID#.html" rouge.config_file = add_data_path("config_test.xml") rouge.write_config(system_id=11) self.assertTrue(xml_equal( rouge.config_file, add_data_path("ROUGE-test_11.xml"))) os.remove(rouge.config_file) def test_evaluation(self): rouge = Rouge155() rouge.system_dir = add_data_path("systems") rouge.model_dir = add_data_path("models") rouge.system_filename_pattern = "SL.P.10.R.11.SL062003-(\d+).html" rouge.model_filename_pattern = "SL.P.10.R.[A-D].SL062003-#ID#.html" pyrouge_output = rouge.evaluate(system_id=11).strip() rouge_command = ( "{bin} -e {data} -c 95 -2 -1 -U -r 1000 -n 4 -w 1.2 " "-a -m {xml}".format( bin=rouge.bin_path, data=rouge.data_dir, xml=add_data_path("ROUGE-test_11.xml"))) orig_rouge_output = check_output_clean(rouge_command.split()) self.assertEqual(pyrouge_output, orig_rouge_output) def test_rouge_for_plain_text(self): model_dir = add_data_path("models_plain") system_dir = add_data_path("systems_plain") pyrouge_command = ( "pyrouge_evaluate_plain_text_files -m {} -s {} -sfp " "D(\d+).M.100.T.A -mfp D#ID#.M.100.T.[A-Z] -id 1".format( model_dir, system_dir)) pyrouge_output = check_output_clean(pyrouge_command.split()) rouge = Rouge155() config_file = add_data_path("config_test2.xml") rouge_command = ( "{bin} -e {data} -c 95 -2 -1 -U -r 1000 -n 4 -w 1.2 " "-a -m {xml}".format( bin=rouge.bin_path, data=rouge.data_dir, xml=config_file)) orig_rouge_output = check_output_clean(rouge_command.split()) self.assertEqual(pyrouge_output, orig_rouge_output) def test_write_config(self): system_dir = add_data_path("systems") model_dir = add_data_path("models") system_filename_pattern = "SL.P.10.R.11.SL062003-(\d+).html" model_filename_pattern = "SL.P.10.R.[A-D].SL062003-#ID#.html" config_file = os.path.join(mkdtemp(), "config_test.xml") command = ( "pyrouge_write_config_file -m {m} -s {s} " "-mfp {mfp} -sfp {sfp} -c {c}".format( m=model_dir, s=system_dir, mfp=model_filename_pattern, sfp=system_filename_pattern, c=config_file)) check_output(command.split()) target_xml = add_data_path("config_test.xml") print(config_file, target_xml) self.assertTrue(xml_equal(config_file, target_xml)) def test_options(self): rouge = Rouge155() model_dir = add_data_path("models_plain") system_dir = add_data_path("systems_plain") config_file = add_data_path("config_test2.xml") command_part1 = ( "pyrouge_evaluate_plain_text_files -m {} -s {} -sfp " "D(\d+).M.100.T.A -mfp D#ID#.M.100.T.[A-Z] -id 1 -rargs".format( model_dir, system_dir)) command_part2 = [ "\"-e {data} -c 90 -2 -1 -U -r 1000 -n 2 -w 1.2 " "-a -m {xml}\"".format( data=rouge.data_dir, xml=config_file)] pyrouge_command = command_part1.split() + command_part2 pyrouge_output = check_output_clean(pyrouge_command) rouge_command = ( "{bin} -e {data} -c 90 -2 -1 -U -r 1000 -n 2 -w 1.2 " "-a -m {xml}".format( bin=rouge.bin_path, data=rouge.data_dir, xml=config_file)) orig_rouge_output = check_output_clean(rouge_command.split()) self.assertEqual(pyrouge_output, orig_rouge_output) def main(): unittest.main() if __name__ == "__main__": main()
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/tests/Rouge155_test.py
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/tests/__init__.py
import unittest import pyrouge.test from pyrouge.test.Rouge155_test import PyrougeTest loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(loader.loadTestsFromTestCase(PyrougeTest)) unittest.TextTestRunner().run(suite)
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/tests/__main__.py
from __future__ import print_function, unicode_literals, division from pyrouge.utils import log from pyrouge.utils.string_utils import cleanup from pyrouge.utils.file_utils import DirectoryProcessor class PunktSentenceSplitter: """ Splits sentences using the NLTK Punkt sentence tokenizer. If installed, PunktSentenceSplitter can use the default NLTK data for English, otherwise custom trained data has to be provided. """ def __init__(self, language="en", punkt_data_path=None): self.lang2datapath = {"en": "tokenizers/punkt/english.pickle"} self.log = log.get_global_console_logger() try: import nltk.data except ImportError: self.log.error( "Cannot import NLTK data for the sentence splitter. Please " "check if the 'punkt' NLTK-package is installed correctly.") try: if not punkt_data_path: punkt_data_path = self.lang2datapath[language] self.sent_detector = nltk.data.load(punkt_data_path) except KeyError: self.log.error( "No sentence splitter data for language {}.".format(language)) except: self.log.error( "Could not load sentence splitter data: {}".format( self.lang2datapath[language])) def split(self, text): """Splits text and returns a list of the resulting sentences.""" text = cleanup(text) return self.sent_detector.tokenize(text.strip()) @staticmethod def split_files(input_dir, output_dir, lang="en", punkt_data_path=None): ss = PunktSentenceSplitter(lang, punkt_data_path) DirectoryProcessor.process(input_dir, output_dir, ss.split) if __name__ == '__main__': text = "Punkt knows that the periods in Mr. Smith and Johann S. Bach do " "not mark sentence boundaries. And sometimes sentences can start with " "non-capitalized words. i is a good variable name." ss = PunktSentenceSplitter() print(ss.split(text))
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/sentence_splitter.py
import logging def get_console_logger(name, level=logging.INFO): logFormatter = logging.Formatter( "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") logger = logging.getLogger(name) if not logger.handlers: logger.setLevel(level) ch = logging.StreamHandler() ch.setFormatter(logFormatter) logger.addHandler(ch) return logger def get_global_console_logger(level=logging.INFO): return get_console_logger('global', level)
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/log.py
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/__init__.py
import argparse io_parser = argparse.ArgumentParser(add_help=False) io_parser.add_argument( '-i', '--input-files-dir', help="Path of the directory containing the files to be converted.", type=str, action="store", dest="input_dir", required=True ) io_parser.add_argument( '-o', '--output-files-dir', help="Path of the directory in which the converted files will be saved.", type=str, action="store", dest="output_dir", required=True ) ss_parser = argparse.ArgumentParser(add_help=False) ss_parser.add_argument( '-ss', '--split-sentences', help="ROUGE assumes one sentence per line as default summary format. Use " "this flag to split sentences using NLTK if the summary texts have " "another format.", action="store_true", dest="split_sents" ) rouge_path_parser = argparse.ArgumentParser(add_help=False) rouge_path_parser.add_argument( '-hd', '--home-dir', help="Path of the directory containing ROUGE-1.5.5.pl.", type=str, action="store", dest="rouge_home", required=True ) model_sys_parser = argparse.ArgumentParser(add_help=False) model_sys_parser.add_argument( '-mfp', '--model-fn-pattern', help="Regexp matching model filenames.", type=str, action="store", dest="model_filename_pattern", required=True ) model_sys_parser.add_argument( '-sfp', '--system-fn-pattern', help="Regexp matching system filenames.", type=str, action="store", dest="system_filename_pattern", required=True ) model_sys_parser.add_argument( '-m', '--model-dir', help="Path of the directory containing model summaries.", type=str, action="store", dest="model_dir", required=True ) model_sys_parser.add_argument( '-s', '--system-dir', help="Path of the directory containing system summaries.", type=str, action="store", dest="system_dir", required=True ) model_sys_parser.add_argument( '-id', '--system-id', help="Optional system ID. This is useful when comparing several systems.", action="store", dest="system_id" ) config_parser = argparse.ArgumentParser(add_help=False) config_parser.add_argument( '-c', '--config-file-path', help="Path of configfile to be written, including file name.", type=str, action="store", dest="config_file_path", required=True ) main_parser = argparse.ArgumentParser( parents=[model_sys_parser], add_help=False) main_parser.add_argument( '-hd', '--home-dir', help="Path of the directory containing ROUGE-1.5.5.pl.", type=str, action="store", dest="rouge_home", ) main_parser.add_argument( '-rargs', '--rouge-args', help="Override pyrouge default ROUGE command line options with the " "ROUGE_ARGS string, enclosed in qoutation marks.", type=str, action="store", dest="rouge_args" )
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/argparsers.py
from __future__ import print_function, unicode_literals, division import re def remove_newlines(s): p = re.compile("[\n|\r\n|\n\r]") s = re.sub(p, " ", s) s = remove_extraneous_whitespace(s) return s def remove_extraneous_whitespace(s): p = re.compile("(\s+)") s = re.sub(p, " ", s) return s def cleanup(s): return remove_newlines(s)
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/string_utils.py
from __future__ import print_function, unicode_literals, division import os import re import codecs import logging import xml.etree.ElementTree as et from gehrmann_rouge_opennmt.rouge_baselines.pyrouge.pyrouge.utils import log class DirectoryProcessor: @staticmethod def process(input_dir, output_dir, function): """ Apply function to all files in input_dir and save the resulting ouput files in output_dir. """ if not os.path.exists(output_dir): os.makedirs(output_dir) logger = log.get_global_console_logger(level=logging.INFO) # logger.info("Processing files in {}.".format(input_dir)) input_file_names = os.listdir(input_dir) for input_file_name in input_file_names: # logger.info("Processing {}.".format(input_file_name)) input_file = os.path.join(input_dir, input_file_name) with codecs.open(input_file, "r", encoding="UTF-8") as f: input_string = f.read() output_string = function(input_string) output_file = os.path.join(output_dir, input_file_name) with codecs.open(output_file, "w", encoding="UTF-8") as f: f.write(output_string) # logger.info("Saved processed files to {}.".format(output_dir)) def str_from_file(path): """ Return file contents as string. """ with open(path) as f: s = f.read().strip() return s def xml_equal(xml_file1, xml_file2): """ Parse xml and convert to a canonical string representation so we don't have to worry about semantically meaningless differences """ def canonical(xml_file): # poor man's canonicalization, since we don't want to install # external packages just for unittesting s = et.tostring(et.parse(xml_file).getroot()).decode("UTF-8") s = re.sub("[\n|\t]*", "", s) s = re.sub("\s+", " ", s) s = "".join(sorted(s)).strip() return s return canonical(xml_file1) == canonical(xml_file2) def list_files(dir_path, recursive=True): """ Return a list of files in dir_path. """ for root, dirs, files in os.walk(dir_path): file_list = [os.path.join(root, f) for f in files] if recursive: for dir in dirs: dir = os.path.join(root, dir) file_list.extend(list_files(dir, recursive=True)) return file_list def verify_dir(path, name=None): if name: name_str = "Cannot set {} directory because t".format(name) else: name_str = "T" msg = "{}he path {} does not exist.".format(name_str, path) if not os.path.exists(path): raise Exception(msg)
BARTScore-main
SUM/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/file_utils.py
import math import os from args import pretrain_args import nltk from accelerate import Accelerator from datasets import load_dataset from torch.utils.data.dataloader import DataLoader from tqdm.auto import tqdm from transformers import ( AdamW, DataCollatorForSeq2Seq, get_scheduler, set_seed, ) import time from transformers import BartTokenizer, BartForConditionalGeneration class BART: def __init__(self, checkpoint='facebook/bart-large-cnn'): self.model = BartForConditionalGeneration.from_pretrained(checkpoint) self.tokenizer = BartTokenizer.from_pretrained(checkpoint) self.criterion = None def pretrain(self, args): """ args.seed args.datapath args.max_source_length args.max_target_length args.ignore_pad_token_for_loss """ # Initialize the accelerator. We will let the accelerator handle device placement for us # in this example accelerator = Accelerator() set_seed(args.seed) data_files = { 'train': args.train_file, 'validation': args.validation_file } extension = args.train_file.split('.')[-1] raw_datasets = load_dataset(extension, data_files=data_files) # Preprocessing the datasets # First we tokenize all the texts column_names = raw_datasets['train'].column_names text_column, summary_column = column_names[0], column_names[1] # Temporarily set max_target_length for training padding = False def preprocess_function(examples): inputs = examples[text_column] targets = examples[summary_column] inputs = [inp for inp in inputs] model_inputs = self.tokenizer(inputs, max_length=args.max_source_length, padding=padding, truncation=True) # Setup the tokenizer for targets with self.tokenizer.as_target_tokenizer(): labels = self.tokenizer(targets, max_length=args.max_target_length, padding=padding, truncation=True) # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore # padding in the loss. if padding == "max_length" and args.ignore_pad_token_for_loss: labels["input_ids"] = [ [(l if l != self.tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"] ] model_inputs["labels"] = labels["input_ids"] return model_inputs processed_datasets = raw_datasets.map( preprocess_function, batched=True, remove_columns=column_names, load_from_cache_file=True ) train_dataset = processed_datasets["train"] eval_dataset = processed_datasets["validation"] label_pad_token_id = -100 if args.ignore_pad_token_for_loss else self.tokenizer.pad_token_id data_collator = DataCollatorForSeq2Seq( self.tokenizer, model=self.model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=8 if accelerator.use_fp16 else None, ) train_dataloader = DataLoader( train_dataset, shuffle=True, collate_fn=data_collator, batch_size=args.per_device_train_batch_size ) eval_dataloader = DataLoader(eval_dataset, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size) # Optimizer # Split weights in two groups, one with weight decay and the other not. no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay, }, { "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate) # Prepare everything with our `accelerator`. model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare( self.model, optimizer, train_dataloader, eval_dataloader ) # Note -> the training dataloader needs to be prepared before we grab his length below (cause its length will be # shorter in multiprocess) # Scheduler and math around the number of training steps. num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) if args.max_train_steps is None: args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch else: args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) lr_scheduler = get_scheduler( name=args.lr_scheduler_type, optimizer=optimizer, num_warmup_steps=args.num_warmup_steps, num_training_steps=args.max_train_steps, ) total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps print("***** Running training *****") print(f" Num examples = {len(train_dataset)}") print(f" Num Epochs = {args.num_train_epochs}") print(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") print(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") print(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") print(f" Total optimization steps = {args.max_train_steps}") # Only show the progress bar once on each machine. progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) completed_steps = 0 for epoch in range(args.num_train_epochs): model.train() for step, batch in enumerate(train_dataloader): outputs = model(**batch) loss = outputs.loss loss = loss / args.gradient_accumulation_steps accelerator.backward(loss) if step % args.gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1: optimizer.step() lr_scheduler.step() optimizer.zero_grad() progress_bar.update(1) completed_steps += 1 if args.save_every > 0: if completed_steps % args.save_every == 0: out_dir = f'{args.output_dir}/{completed_steps}' os.makedirs(out_dir, exist_ok=True) accelerator.wait_for_everyone() unwrapped_model = accelerator.unwrap_model(model) unwrapped_model.save_pretrained(out_dir, save_function=accelerator.save) if completed_steps >= args.max_train_steps: break if args.output_dir is not None: accelerator.wait_for_everyone() unwrapped_model = accelerator.unwrap_model(model) unwrapped_model.save_pretrained(args.output_dir, save_function=accelerator.save) if __name__ == '__main__': bart = BART() args = pretrain_args() bart.pretrain(args)
BARTScore-main
train/bart.py
import argparse import os from transformers import SchedulerType def pretrain_args(): parser = argparse.ArgumentParser(description="Finetune a transformers model on a Seq2Seq task") parser.add_argument( "--train_file", type=str, default='data/parabank2.json', help="A csv or a json file containing the training data." ) parser.add_argument( "--validation_file", type=str, default='data/eval.json', help="A csv or a json file containing the validation data." ) parser.add_argument( "--ignore_pad_token_for_loss", type=bool, default=True, help="Whether to ignore the tokens corresponding to " "padded labels in the loss computation or not.", ) parser.add_argument( "--max_source_length", type=int, default=1024, help="The maximum total input sequence length after " "tokenization.Sequences longer than this will be truncated, sequences shorter will be padded.", ) parser.add_argument( "--preprocessing_num_workers", type=int, default=None, help="The number of processes to use for the preprocessing.", ) parser.add_argument( "--overwrite_cache", type=bool, default=False, help="Overwrite the cached training and evaluation sets" ) parser.add_argument( "--max_target_length", type=int, default=1024, help="The maximum total sequence length for target text after " "tokenization. Sequences longer than this will be truncated, sequences shorter will be padded." "during ``evaluate`` and ``predict``.", ) parser.add_argument( "--max_length", type=int, default=1024, help=( "The maximum total input sequence length after tokenization. Sequences longer than this will be truncated," " sequences shorter will be padded if `--pad_to_max_lengh` is passed." ), ) parser.add_argument( "--per_device_train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader.", ) parser.add_argument( "--per_device_eval_batch_size", type=int, default=8, help="Batch size (per device) for the evaluation dataloader.", ) parser.add_argument( "--learning_rate", type=float, default=5e-5, help="Initial learning rate (after the potential warmup period) to use.", ) parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.") parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.") parser.add_argument( "--max_train_steps", type=int, default=None, help="Total number of training steps to perform. If provided, overrides num_train_epochs.", ) parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument( "--lr_scheduler_type", type=SchedulerType, default="linear", help="The scheduler type to use.", choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"], ) parser.add_argument( "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler." ) parser.add_argument("--output_dir", type=str, default='steps', help="Where to store the final model.") parser.add_argument("--save_every", type=int, default=-1, help="To save the model every certain number of steps.") args = parser.parse_args() # Sanity checks if args.train_file is None and args.validation_file is None: raise ValueError("Need either a dataset name or a training/validation file.") else: if args.train_file is not None: extension = args.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if args.validation_file is not None: extension = args.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." if args.output_dir is not None: os.makedirs(args.output_dir, exist_ok=True) # Set seed args.seed = 666 return args
BARTScore-main
train/args.py
import random from collections import namedtuple from typing import List import torch from tqdm import tqdm, trange from transformers import AdamW, get_linear_schedule_with_warmup from models.bart_utils import ShardedBART TextPairData = namedtuple('TextPairData', ['src_text', 'tgt_text']) class BART: def __init__(self, args): self.args = args assert args.gpu in [0, 1, 2, 3, 4] self.device = 'cuda' if args.gpu > 0 else 'cpu' self.src_max_len = args.src_max_len self.tgt_max_len = args.tgt_max_len self.bart = ShardedBART(args) self.optimizer = None self.lr_scheduler = None self.data = [] # Number of optimization performed self.train_steps = 0 def get_optimizer(self, lr, train_steps, warmup_steps, weight_decay, adam_epsilon): no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ {"params": [p for n, p in self.bart.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": weight_decay}, {"params": [p for n, p in self.bart.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0}] self.optimizer = AdamW( optimizer_grouped_parameters, lr=lr, eps=adam_epsilon) self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=warmup_steps, num_training_steps=train_steps) def save_model(self, path): torch.save(self.bart.state_dict(), path) print(f'Model saved in {path}.') def load_model(self, path): self.bart.load_state_dict(torch.load(path, map_location=self.device)) print(f'Model {path} loaded.') def load_data(self, src_texts, tgt_texts): """ Just go through all the data (maybe once), no more preprocessing """ for src_text, tgt_text in tqdm(zip(src_texts, tgt_texts), total=len(src_texts), desc='Loading data...'): self.data.append(TextPairData( src_text=src_text, tgt_text=tgt_text )) print(f'Data size: {len(self.data)}') def train_epoch(self, batch_size): self.bart.shard() self.bart.train() random.shuffle(self.data) for i in trange(0, len(self.data), batch_size, desc='BART Training...'): batch = self.data[i: i + batch_size] self.optimizer.zero_grad() for j in range(0, len(batch)): data = batch[j] src_encoded = self.bart.encode(data.src_text, self.src_max_len) src_tokens = src_encoded['input_ids'] src_attn_mask = src_encoded['attention_mask'] tgt_encoded = self.bart.encode(data.tgt_text, self.tgt_max_len) tgt_tokens = tgt_encoded['input_ids'] tgt_attn_mask = tgt_encoded['attention_mask'] loss = self.bart.forward( input_ids=src_tokens, attention_mask=src_attn_mask, decoder_attention_mask=tgt_attn_mask, labels=tgt_tokens ) loss = loss / batch_size loss.backward() self.optimizer.step() self.train_steps += 1 self.lr_scheduler.step() # Save checkpoint if self.train_steps % 50 == 0: self.save_model(f'{self.args.save_dir}/bart_{self.train_steps}.pth') if self.train_steps == 6000: exit(0) def generate(self, src_sents: List[str]): self.bart.eval() input_ids = self.bart.tokenizer( src_sents, max_length=self.src_max_len, padding=True, truncation=True, return_tensors='pt' )['input_ids'].to(self.device) output = self.bart.generate( input_ids=input_ids, max_length=self.args.gen_max_len, min_length=self.args.gen_min_len, num_beams=self.args.beam, length_penalty=self.args.lenpen, no_repeat_ngram_size=self.args.no_repeat_ngram_size ) hypos = [self.bart.tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False).strip() for g in output] return hypos
BARTScore-main
train/reproduce/bart.py
import jsonlines def read_file_to_list(file_name): lines = [] with open(file_name, 'r', encoding='utf8') as f: for line in f.readlines(): lines.append(line.strip()) return lines def write_list_to_file(list_to_write, filename): out_file = open(filename, 'w') for line in list_to_write: print(line, file=out_file) out_file.flush() out_file.close() def read_jsonlines_to_list(file_name): lines = [] with jsonlines.open(file_name, 'r') as reader: for obj in reader: lines.append(obj) return lines def write_list_to_jsonline(list_to_write, filename): with jsonlines.open(filename, 'w') as writer: writer.write_all(list_to_write)
BARTScore-main
train/reproduce/utils.py
import argparse def finetune_args(): parser = argparse.ArgumentParser(description='Finetune parameters') parser.add_argument('--gpu', default=2, type=int, help='Number of GPU used') parser.add_argument('--src_max_len', default=1024, type=int, help='Max source length') parser.add_argument('--tgt_max_len', default=1024, type=int, help='Max target length') parser.add_argument('--save_dir', default='trained', type=str, help='Where to save model checkpoints') parser.add_argument('--checkpoint', default='facebook/bart-large-cnn', type=str, help='Which checkpoint to load from') parser.add_argument('--n_epochs', default=3, type=int, help='How many epochs to train') parser.add_argument('--lr', default=5e-5, type=float, help='learning rage') parser.add_argument('--weight_decay', default=0.0, type=float, help='weight decay') parser.add_argument('--warmup_steps', default=0, type=int, help='Number of warmup steps') parser.add_argument('--adam_epsilon', default=1e-8, type=float, help='AdamW epsilon') parser.add_argument('--batch_size', default=20, type=int, help='Training batch size') args = parser.parse_args() return args def generate_args(): parser = argparse.ArgumentParser(description='Generation parameters') args = parser.parse_args() return args
BARTScore-main
train/reproduce/args.py
import logging import os import random import torch from args import finetune_args from utils import * from bart import BART logging.disable(logging.WARNING) def set_seed_everywhere(seed, cuda): """ Set seed for reproduce """ random.seed(seed) torch.manual_seed(seed) if cuda: torch.cuda.manual_seed_all(seed) set_seed_everywhere(666, True) def load_data(filepath): """ Json data, {'text': ..., 'summary': ...}""" data = read_jsonlines_to_list(filepath) src_texts, tgt_texts = [], [] for obj in data: src_texts.append(obj.get('text').strip()) tgt_texts.append(obj.get('summary').strip()) return src_texts, tgt_texts def main(args): save_dir = args.save_dir os.makedirs(save_dir, exist_ok=True) bart = BART(args) src_texts, tgt_texts = load_data('data/parabank2.json') bart.load_data(src_texts, tgt_texts) n_epochs = args.n_epochs train_steps = n_epochs * (len(bart.data) // args.batch_size + 1) bart.get_optimizer( lr=args.lr, train_steps=train_steps, warmup_steps=args.warmup_steps, weight_decay=args.weight_decay, adam_epsilon=args.adam_epsilon ) for epoch in range(n_epochs): print(f'On epoch {epoch}') bart.train_epoch(batch_size=args.batch_size) if __name__ == '__main__': args = finetune_args() main(args)
BARTScore-main
train/reproduce/finetune.py
BARTScore-main
train/reproduce/models/__init__.py
import torch import random import torch.nn as nn from transformers import BartTokenizer, BartForConditionalGeneration import torch.nn.functional as F from typing import Optional def move_device(tensor, device): if tensor is None: return None else: tensor = tensor.to(device) return tensor def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min) def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int): """ Shift input ids one token to the right. """ shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() shifted_input_ids[:, 0] = decoder_start_token_id assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." # replace possible -100 values in labels by `pad_token_id` shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) return shifted_input_ids class ShardedBART(nn.Module): def __init__(self, args): super(ShardedBART, self).__init__() self.args = args self.tokenizer = BartTokenizer.from_pretrained(args.checkpoint) self.model = BartForConditionalGeneration.from_pretrained(args.checkpoint) self.device_enc1 = self.device_enc2 = self.device_dec1 = self.device_dec2 = None self.loss_fct = nn.CrossEntropyLoss(ignore_index=self.tokenizer.pad_token_id) def shard(self): """ Shard the model to at most 4 gpus""" assert self.args.gpu > 0 and torch.cuda.is_available() gpu = min(self.args.gpu, 4) if gpu == 4: assert torch.cuda.device_count() >= 4 self.device_enc1 = 'cuda:0' self.device_enc2 = 'cuda:1' self.device_dec1 = 'cuda:2' self.device_dec2 = 'cuda:3' self.cuda() elif gpu == 3: assert torch.cuda.device_count() >= 3 self.device_enc1 = 'cuda:0' self.device_enc2 = 'cuda:1' self.device_dec1 = 'cuda:1' self.device_dec2 = 'cuda:2' elif gpu == 2: assert torch.cuda.device_count() >= 2 self.device_enc1 = self.device_enc2 = 'cuda:0' self.device_dec1 = self.device_dec2 = 'cuda:1' else: self.device_enc1 = self.device_enc2 = self.device_dec1 = self.device_dec2 = 'cuda:0' # Model sharding self.encoder.to(self.device_enc1) self.decoder.to(self.device_dec1) # We further shard the model if needed. encoder_layer_num = len(self.encoder.layers) for i in range(encoder_layer_num): if i >= (encoder_layer_num // 2): self.encoder.layers[i].to(self.device_enc2) decoder_layer_num = len(self.decoder.layers) for i in range(decoder_layer_num): if i >= (decoder_layer_num // 2): self.decoder.layers[i].to(self.device_dec2) # For calculating lm logits self.model.final_logits_bias = move_device( self.model.final_logits_bias, self.device_dec2 ) self.model.model.shared = move_device(self.model.model.shared, self.device_dec2) torch.cuda.empty_cache() print(f'Sharded to {gpu} GPUs.') def encode(self, sentence, max_len): """ Encode text (up to max_length) Example output: { 'input_ids': tensor([[ 0, 713, 16, 1531, 2]]), 'attention_mask': tensor([[1, 1, 1, 1, 1]]) } """ encoded = self.tokenizer([sentence], max_length=max_len, truncation=True, return_tensors='pt') return encoded def forward( self, input_ids=None, attention_mask=None, decoder_attention_mask=None, labels=None, ): decoder_input_ids = shift_tokens_right( labels, self.config.pad_token_id, self.config.decoder_start_token_id ) # Go through encoder hidden_states = forward_encoder( self=self.encoder, input_ids=input_ids, attention_mask=attention_mask ) # Go through decoder hidden_states = forward_decoder( self=self.decoder, input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, encoder_hidden_states=hidden_states, encoder_attention_mask=attention_mask ) lm_logits = self.model.lm_head(hidden_states) + self.model.final_logits_bias masked_lm_loss = self.loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1).to(lm_logits.device)) return masked_lm_loss @property def config(self): return self.model.config @property def encoder(self): return self.model.model.encoder @property def decoder(self): return self.model.model.decoder @property def generate(self): return self.model.generate def forward_encoder( self, input_ids=None, attention_mask=None ): """ Here self is self.encoder""" # retrieve input_ids and inputs_embeds input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]).to(self.embed_tokens.weight.device) inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale embed_pos = self.embed_positions(input_shape) hidden_states = inputs_embeds.to(self.layernorm_embedding.weight.device) \ + embed_pos.to(self.layernorm_embedding.weight.device) hidden_states = self.layernorm_embedding(hidden_states) hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) # expand attention_mask if attention_mask is not None: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype) for idx, encoder_layer in enumerate(self.layers): # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) dropout_probability = random.uniform(0, 1) if self.training and (dropout_probability < self.layerdrop): # skip the layer pass else: layer_outputs = encoder_layer( hidden_states.to(encoder_layer.fc1.weight.device), attention_mask.to(encoder_layer.fc1.weight.device), layer_head_mask=None, output_attentions=False, ) hidden_states = layer_outputs[0] return hidden_states def forward_decoder( self, input_ids=None, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, ): """ Here self is self.decoder """ # retrieve input_ids and inputs_embeds input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]) inputs_embeds = self.embed_tokens(input_ids.to(self.embed_tokens.weight.device)) * self.embed_scale # past_key_values_length past_key_values_length = 0 attention_mask = self._prepare_decoder_attention_mask( attention_mask.to(inputs_embeds.device), input_shape, inputs_embeds, past_key_values_length ) # expand encoder attention mask if encoder_hidden_states is not None and encoder_attention_mask is not None: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]) # embed positions positions = self.embed_positions(input_shape, past_key_values_length) hidden_states = inputs_embeds.to(self.layernorm_embedding.weight.device) \ + positions.to(self.layernorm_embedding.weight.device) hidden_states = self.layernorm_embedding(hidden_states) hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) for idx, decoder_layer in enumerate(self.layers): # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) dropout_probability = random.uniform(0, 1) if self.training and (dropout_probability < self.layerdrop): continue curr_device = decoder_layer.fc1.weight.device layer_outputs = decoder_layer( hidden_states.to(curr_device), attention_mask=attention_mask.to(curr_device), encoder_hidden_states=encoder_hidden_states.to(curr_device), encoder_attention_mask=encoder_attention_mask.to(curr_device), layer_head_mask=None, cross_attn_layer_head_mask=None, past_key_value=None, output_attentions=False, use_cache=False, ) hidden_states = layer_outputs[0] return hidden_states
BARTScore-main
train/reproduce/models/bart_utils.py