Esempio n. 1
0
def main():
    parser = argparse.ArgumentParser(
        description=
        """Computes rationale and final class classification scores""",
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument(
        '--data_dir',
        dest='data_dir',
        required=True,
        help='Which directory contains a {train,val,test}.jsonl file?')
    parser.add_argument('--split',
                        dest='split',
                        required=True,
                        help='Which of {train,val,test} are we scoring on?')
    parser.add_argument('--strict',
                        dest='strict',
                        required=False,
                        action='store_true',
                        default=False,
                        help='Do we perform strict scoring?')
    parser.add_argument('--results',
                        dest='results',
                        required=True,
                        help="""Results File
    Contents are expected to be jsonl of:
    {
        "annotation_id": str, required
        # these classifications *must not* overlap
        # these classifications *must not* overlap
        "rationales": List[
            {
                "docid": str, required
                "hard_rationale_predictions": List[{
                    "start_token": int, inclusive, required
                    "end_token": int, exclusive, required
                }], optional,
                # token level classifications, a value must be provided per-token
                # in an ideal world, these correspond to the hard-decoding above.
                "soft_rationale_predictions": List[float], optional.
                # sentence level classifications, a value must be provided for every
                # sentence in each document, or not at all
                "soft_sentence_predictions": List[float], optional.
            }
        ],
        # the classification the model made for the overall classification task
        "classification": str, optional
        # A probability distribution output by the model. We require this to be normalized.
        "classification_scores": Dict[str, float], optional
        # The next two fields are measures for how faithful your model is (the
        # rationales it predicts are in some sense causal of the prediction), and
        # how sufficient they are. We approximate a measure for comprehensiveness by
        # asking that you remove the top k%% of tokens from your documents,
        # running your models again, and reporting the score distribution in the
        # "comprehensiveness_classification_scores" field.
        # We approximate a measure of sufficiency by asking exactly the converse
        # - that you provide model distributions on the removed k%% tokens.
        # 'k' is determined by human rationales, and is documented in our paper.
        # You should determine which of these tokens to remove based on some kind
        # of information about your model: gradient based, attention based, other
        # interpretability measures, etc.
        # scores per class having removed k%% of the data, where k is determined by human comprehensive rationales
        "comprehensiveness_classification_scores": Dict[str, float], optional
        # scores per class having access to only k%% of the data, where k is determined by human comprehensive rationales
        "sufficiency_classification_scores": Dict[str, float], optional
        # the number of tokens required to flip the prediction - see "Is Attention Interpretable" by Serrano and Smith.
        "tokens_to_flip": int, optional
    }
    When providing one of the optional fields, it must be provided for *every* instance.
    The classification, classification_score, and comprehensiveness_classification_scores
    must together be present for every instance or absent for every instance.
    """)
    parser.add_argument('--iou_thresholds',
                        dest='iou_thresholds',
                        required=False,
                        nargs='+',
                        type=float,
                        default=[0.5],
                        help='''Thresholds for IOU scoring.

    These are used for "soft" or partial match scoring of rationale spans.
    A span is considered a match if the size of the intersection of the prediction
    and the annotation, divided by the union of the two spans, is larger than
    the IOU threshold. This score can be computed for arbitrary thresholds.
    ''')
    parser.add_argument('--score_file',
                        dest='score_file',
                        required=False,
                        default=None,
                        help='Where to write results?')
    args = parser.parse_args()
    results = load_jsonl(args.results)
    docids = set(
        chain.from_iterable([rat['docid'] for rat in res['rationales']]
                            for res in results))
    docs = load_flattened_documents(args.data_dir, docids)
    verify_instances(results, docs)
    # load truth
    annotations = annotations_from_jsonl(
        os.path.join(args.data_dir, args.split + '.jsonl'))
    docids |= set(
        chain.from_iterable((ev.docid
                             for ev in chain.from_iterable(ann.evidences))
                            for ann in annotations))

    has_final_predictions = _has_classifications(results)
    scores = dict()
    if args.strict:
        if not args.iou_thresholds:
            raise ValueError(
                "--iou_thresholds must be provided when running strict scoring"
            )
        if not has_final_predictions:
            raise ValueError(
                "We must have a 'classification', 'classification_score', and 'comprehensiveness_classification_score' field in order to perform scoring!"
            )
    # TODO think about offering a sentence level version of these scores.
    if _has_hard_predictions(results):
        truth = list(
            chain.from_iterable(
                Rationale.from_annotation(ann) for ann in annotations))
        pred = list(
            chain.from_iterable(
                Rationale.from_instance(inst) for inst in results))
        if args.iou_thresholds is not None:
            iou_scores = partial_match_score(truth, pred, args.iou_thresholds)
            scores['iou_scores'] = iou_scores
        # NER style scoring
        rationale_level_prf = score_hard_rationale_predictions(truth, pred)
        scores['rationale_prf'] = rationale_level_prf
        token_level_truth = list(
            chain.from_iterable(rat.to_token_level() for rat in truth))
        token_level_pred = list(
            chain.from_iterable(rat.to_token_level() for rat in pred))
        token_level_prf = score_hard_rationale_predictions(
            token_level_truth, token_level_pred)
        scores['token_prf'] = token_level_prf
    else:
        logging.info(
            "No hard predictions detected, skipping rationale scoring")

    if _has_soft_predictions(results):
        flattened_documents = load_flattened_documents(args.data_dir, docids)
        paired_scoring = PositionScoredDocument.from_results(
            results, annotations, flattened_documents, use_tokens=True)
        token_scores = score_soft_tokens(paired_scoring)
        scores['token_soft_metrics'] = token_scores
    else:
        logging.info(
            "No soft predictions detected, skipping rationale scoring")

    if _has_soft_sentence_predictions(results):
        documents = load_documents(args.data_dir, docids)
        paired_scoring = PositionScoredDocument.from_results(results,
                                                             annotations,
                                                             documents,
                                                             use_tokens=False)
        sentence_scores = score_soft_tokens(paired_scoring)
        scores['sentence_soft_metrics'] = sentence_scores
    else:
        logging.info(
            "No sentence level predictions detected, skipping sentence-level diagnostic"
        )

    if has_final_predictions:
        flattened_documents = load_flattened_documents(args.data_dir, docids)
        class_results = score_classifications(results, annotations,
                                              flattened_documents)
        scores['classification_scores'] = class_results
    else:
        logging.info(
            "No classification scores detected, skipping classification")

    pprint.pprint(scores)

    if args.score_file:
        with open(args.score_file, 'w') as of:
            json.dump(scores, of, indent=4, sort_keys=True)
def load_and_cache_examples(args,
                            model_params,
                            tokenizer,
                            evaluate=False,
                            split="train",
                            output_examples=False):
    if args.local_rank not in [-1, 0] and not evaluate:
        torch.distributed.barrier(
        )  # Make sure only the first process in distributed training process the dataset, and the others will use the cache

    # only load one split
    input_file = os.path.join(args.data_dir, split)
    cached_features_file = os.path.join(
        os.path.dirname(input_file), 'cached_{}_{}_{}'.format(
            split,
            list(filter(None,
                        model_params["tokenizer_name"].split('/'))).pop(),
            str(args.max_seq_length)))
    if args.gold_evidence:
        cached_features_file += "_goldevidence"

    if os.path.exists(cached_features_file
                      ) and not args.overwrite_cache and not output_examples:
        logger.info("Loading features from cached file %s",
                    cached_features_file)
        features = torch.load(cached_features_file)
    else:
        logger.info("Creating features from dataset file at %s", input_file)
        dataset = annotations_from_jsonl(
            os.path.join(args.data_dir, split + ".jsonl"))

        docids = set(e.docid
                     for e in chain.from_iterable(
                         chain.from_iterable(
                             map(lambda ann: ann.evidences, chain(dataset)))))
        documents = load_documents(args.data_dir, docids)

        if args.out_domain:
            examples = read_json(args)
        else:
            examples = read_examples(args, model_params, dataset, documents,
                                     split)

        features = convert_examples_to_features(
            args,
            model_params,
            examples=examples,
            tokenizer=tokenizer,
            max_seq_length=args.max_seq_length,
            max_query_length=args.max_query_length,
            is_training=not evaluate)
        if args.local_rank in [-1, 0]:
            logger.info("Saving features into cached file %s",
                        cached_features_file)
            torch.save(features, cached_features_file)

    if args.local_rank == 0 and not evaluate:
        torch.distributed.barrier()

    # Tensorize all features
    all_input_ids = torch.tensor([f.input_ids for f in features],
                                 dtype=torch.long)
    all_input_mask = torch.tensor([f.input_mask for f in features],
                                  dtype=torch.long)
    all_segment_ids = torch.tensor([f.segment_ids for f in features],
                                   dtype=torch.long)
    all_cls_index = torch.tensor([f.cls_index for f in features],
                                 dtype=torch.long)
    all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float)
    all_unique_ids = torch.tensor([f.unique_id for f in features],
                                  dtype=torch.float)

    if evaluate:
        all_example_index = torch.arange(all_input_ids.size(0),
                                         dtype=torch.long)
        tensorized_dataset = TensorDataset(all_input_ids, all_input_mask,
                                           all_segment_ids, all_example_index,
                                           all_cls_index, all_p_mask,
                                           all_unique_ids)
    else:
        all_class_labels = torch.tensor([f.class_label for f in features],
                                        dtype=torch.long)
        all_evidence_labels = torch.tensor(
            [f.evidence_label for f in features], dtype=torch.long)
        tensorized_dataset = TensorDataset(all_input_ids, all_input_mask,
                                           all_segment_ids, all_class_labels,
                                           all_cls_index, all_p_mask,
                                           all_unique_ids, all_evidence_labels)

    if output_examples:
        return tensorized_dataset, examples, features
    return tensorized_dataset, features
from ib_utils import read_examples
import argparse
import json
from itertools import chain
from eraser.rationale_benchmark.utils import load_documents, annotations_from_jsonl
import logging, os

parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', dest='data_dir', required=True)
parser.add_argument('--model_params', dest='model_params', required=True)
parser.add_argument("--split", type=str, default="val")
parser.add_argument("--truncate", default=False, action="store_true")
parser.add_argument("--max_seq_length", default=512, type=int)
parser.add_argument("--max_query_length", default=24, type=int)
parser.add_argument("--max_num_sentences", default=20, type=int)
parser.add_argument("--debug", action="store_true", default=False)
parser.add_argument('--low_resource', action="store_true", default=False)
args = parser.parse_args()

# Parse model args json
with open(args.model_params, 'r') as fp:
    logging.debug(f'Loading model parameters from {args.model_params}')
    model_params = json.load(fp)

dataset = annotations_from_jsonl(
    os.path.join(args.data_dir, args.split + ".jsonl"))
docids = set(e.docid for e in chain.from_iterable(
    chain.from_iterable(map(lambda ann: ann.evidences, chain(dataset)))))
documents = load_documents(args.data_dir, docids)
examples = read_examples(args, model_params, dataset, documents, args.split)