采用ERNIE计算 Perplexity (PPL)

1.模型准备

ERNIE:ernie-3.0-base-zh

GPT2:gpt2-chinese-cluecorpussmall

请自行下载。

2.代码

2.1 test_ppl.py

# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import json
import numpy as np
from tqdm import tqdm
from evaluate import load

import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer


def load_model(model_id, device):
    if device is not None:
        assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
        if device == "gpu":
            device = "cuda"
    else:
        device = "cuda" if torch.cuda.is_available() else "cpu"

    model = AutoModelForCausalLM.from_pretrained(model_id, is_decoder=True)
    model = model.to(device)
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    return model, tokenizer


def get_ppl_score(predictions):
    """
    参考hugging face 第三方包https://huggingface.co/spaces/evaluate-metric/perplexity/blob/main/perplexity.py
    """
    base_dir = os.path.dirname(os.path.abspath(__file__))
    load_path = os.path.join(base_dir, "./perplexity.py")
    perplexity = load(load_path, module_type="metric")
    results = perplexity.compute(predictions=predictions, model_id=os.path.join(base_dir, "./ernie-3.0-base-zh"), add_start_token=False)
    print("hugging third scource:")
    print(results)


def get_ppl_score2(predictions, device=None):
    """
    参考hugging face官方文档https://huggingface.co/docs/transformers/perplexity
    """
    base_dir = os.path.dirname(os.path.abspath(__file__))
    model, tokenizer = load_model(os.path.join(base_dir, "./ernie-3.0-base-zh"), device)
    encodings = tokenizer(predictions, return_tensors="pt").to(device)

    # max_length = model.config.n_positions
    max_length = 512
    stride = 512
    seq_len = encodings.input_ids.size(1)
    print("seq_len:", seq_len)

    nlls = []
    prev_end_loc = 0
    for begin_loc in tqdm(range(0, seq_len, stride)):
        end_loc = min(begin_loc + max_length, seq_len)
        trg_len = end_loc - prev_end_loc  # may be different from stride on last loop
        print("begin_loc:{}, end_loc:{}, trg_len:{}".format(begin_loc, end_loc, trg_len))
        input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)
        target_ids = input_ids.clone()
        # ERINE 结束符的token_id为-100
        target_ids[:, :-trg_len] = -100
        #print("input_ids:", input_ids)
        #print("target_ids:", target_ids)

        with torch.no_grad():
            outputs = model(input_ids, labels=target_ids)

            # loss is calculated using CrossEntropyLoss which averages over valid labels
            # N.B. the model only calculates loss over trg_len - 1 labels, because it internally shifts the labels
            # to the left by 1.
            neg_log_likelihood = outputs.loss

        nlls.append(neg_log_likelihood)

        prev_end_loc = end_loc
        if end_loc == seq_len:
            break

    average_negative_log_likelihood = torch.stack(nlls).mean()
    ppl = torch.exp(average_negative_log_likelihood)
    print("average_negative_log_likelihood:", average_negative_log_likelihood)
    print("hugging-face ppl of fixed-length:", ppl)


def get_ppl_score3(sentence, device=None):
    """
    利用ernie3.0 encoder计算ppl
    """
    device = "cpu"
    base_dir = os.path.dirname(os.path.abspath(__file__))
    model_id = os.path.join(base_dir, "./ernie-3.0-base-zh")
    model = AutoModelForCausalLM.from_pretrained(model_id)
    model = model.to(device)
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    tokenize_input = tokenizer.tokenize(sentence)
    tensor_input = torch.tensor([tokenizer.convert_tokens_to_ids(tokenize_input)])
    sen_len = len(tokenize_input)
    print("input:", tokenize_input)
    print("input len:", sen_len)
    sentence_loss = 0.

    for i, word in enumerate(tokenize_input):
        # add mask to i-th character of the sentence
        tokenize_input[i] = '[MASK]'
        mask_input = torch.tensor([tokenizer.convert_tokens_to_ids(tokenize_input)])
        #print("mask_input:", mask_input)
        output = model(mask_input)
        #print("output:", output)
        prediction_scores = output[0]
        softmax = nn.Softmax(dim=0)
        ps = softmax(prediction_scores[0, i]).log()
        word_loss = ps[tensor_input[0, i]]
        sentence_loss += word_loss.item()

        tokenize_input[i] = word
    ppl = np.exp(-sentence_loss / sen_len)
    average_negative_log_likelihood = -sentence_loss / sen_len
    print("average negative log-likelihood of a sequence:", average_negative_log_likelihood)
    print("ernie encoder ppl score:", ppl)


def get_ppl_score4(sentence, device=None):
    """
    利用ernie3.0 decoder计算ppl
    """
    device = "cpu"
    base_dir = os.path.dirname(os.path.abspath(__file__))
    model_id = os.path.join(base_dir, "./ernie-3.0-base-zh")
    model = AutoModelForCausalLM.from_pretrained(model_id, is_decoder=True)
    model = model.to(device)
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    # 设置计算add_special_tokens=False ppl结果和第一种相同
    inputs = tokenizer(sentence, padding='max_length', max_length=512, truncation=True, return_tensors="pt")
    #print("inputs:", inputs)
    bs, sl = inputs['input_ids'].size()
    outputs = model(**inputs, labels=inputs['input_ids'])

    logits = outputs[1]
    # Shift so that tokens < n predict n
    shift_logits = logits[:, :-1, :].contiguous()
    shift_labels = inputs['input_ids'][:, 1:].contiguous()
    shift_attentions = inputs['attention_mask'][:, 1:].contiguous()
    """print("shift_logits:", shift_logits.shape)
    print("shift_labels:", shift_labels.shape)
    print("shift_attentions:", shift_attentions.shape)"""
    # Flatten the tokens
    # 去除第一个字符CLS
    loss_fct = CrossEntropyLoss(ignore_index=0, reduction="none")
    loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)).detach().reshape(bs, -1)
    meanloss = loss.sum(1) / shift_attentions.sum(1)

    print("meanloss:", meanloss)
    print("len:", shift_attentions.sum(1))
    ppl = torch.exp(meanloss).numpy().tolist()
    print("ernie decoder ppl score:", ppl)


def get_ppl_score5(predictions, device=None):
    """
    参考hugging face官方文档https://huggingface.co/docs/transformers/perplexity
    """
    device = "cpu"
    base_dir = os.path.dirname(os.path.abspath(__file__))
    model_id = os.path.join(base_dir, "./gpt2-chinese-cluecorpussmall")
    model = AutoModelForCausalLM.from_pretrained(model_id, is_decoder=True)
    model = model.to(device)
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    encodings = tokenizer(predictions, return_tensors="pt").to(device)

    # max_length = model.config.n_positions
    max_length = 512
    stride = 512
    seq_len = encodings.input_ids.size(1)
    print("seq_len:", seq_len)

    nlls = []
    prev_end_loc = 0
    for begin_loc in tqdm(range(0, seq_len, stride)):
        end_loc = min(begin_loc + max_length, seq_len)
        trg_len = end_loc - prev_end_loc  # may be different from stride on last loop
        print("begin_loc:{}, end_loc:{}, trg_len:{}".format(begin_loc, end_loc, trg_len))
        input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)
        target_ids = input_ids.clone()
        # ERINE 结束符的token_id为-100
        target_ids[:, :-trg_len] = -100
        #print("input_ids:", input_ids)
        #print("target_ids:", target_ids)

        with torch.no_grad():
            outputs = model(input_ids, labels=target_ids)

            # loss is calculated using CrossEntropyLoss which averages over valid labels
            # N.B. the model only calculates loss over trg_len - 1 labels, because it internally shifts the labels
            # to the left by 1.
            neg_log_likelihood = outputs.loss

        nlls.append(neg_log_likelihood)

        prev_end_loc = end_loc
        if end_loc == seq_len:
            break

    average_negative_log_likelihood = torch.stack(nlls).mean()
    ppl = torch.exp(average_negative_log_likelihood)
    print("average_negative_log_likelihood:", average_negative_log_likelihood)
    print("hugging-face ppl of fixed-length gpt2 chinese:", ppl)


text = "我不会忘记和你一起奋斗的时光。"

get_ppl_score3(text)
print("
" + "*" * 10)
get_ppl_score([text])
print("
" + "*" * 10)
get_ppl_score2([text])
print("
" + "*" * 10)
get_ppl_score4(text)
print("
" + "*" * 10)
get_ppl_score5(text)

2.2 perplexity.py

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
"""Perplexity Metric."""

import datasets
import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import evaluate
from evaluate import logging


_CITATION = """

"""

_DESCRIPTION = """
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence, calculated with exponent base `e`.

For more information, see https://huggingface.co/docs/transformers/perplexity
"""

_KWARGS_DESCRIPTION = """
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    predictions (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to 'cuda' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = evaluate.load("perplexity", module_type="metric")
        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              add_start_token=False,
        ...                              predictions=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results["mean_perplexity"], 0))
        647.0
        >>> print(round(results["perplexities"][0], 0))
        32.0

    Example 2:
        >>> from datasets import load_dataset
        >>> perplexity = evaluate.load("perplexity", module_type="metric")
        >>> input_texts = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")["text"][:10] # doctest: +SKIP
        >>> input_texts = ▼显示
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              predictions=input_texts)
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results["mean_perplexity"], 2)) # doctest: +SKIP
        576.76
        >>> print(round(results["perplexities"][0], 2)) # doctest: +SKIP
        889.28
"""


@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class Perplexity(evaluate.Metric):
    model = None
    tokenizer = None

    def _info(self):
        return evaluate.MetricInfo(
            module_type="metric",
            description=_DESCRIPTION,
            citation=_CITATION,
            inputs_description=_KWARGS_DESCRIPTION,
            features=datasets.Features(
                {
                    "predictions": datasets.Value("string"),
                }
            ),
            reference_urls=["https://huggingface.co/docs/transformers/perplexity"],
        )

    def load_model(model_id, device):
        if device is not None:
            assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
            if device == "gpu":
                device = "cuda"
        else:
            device = "cuda" if torch.cuda.is_available() else "cpu"
        print("device:", device)
        model = AutoModelForCausalLM.from_pretrained(model_id, is_decoder=True)
        Perplexity.model = model.to(device)
        Perplexity.tokenizer = AutoTokenizer.from_pretrained(model_id)

    def _compute(
        self, predictions, model_id, batch_size: int = 16, add_start_token: bool = True, device=None, max_length=None
    ):
        if Perplexity.model is None:
            Perplexity.load_model(model_id, device)

        model, tokenizer = Perplexity.model, Perplexity.tokenizer
        # if batch_size > 1 (which generally leads to padding being required), and
        # if there is not an already assigned pad_token, assign an existing
        # special token to also be the padding token
        if tokenizer.pad_token is None and batch_size > 1:
            existing_special_tokens = list(tokenizer.special_tokens_map_extended.values())
            # check that the model already has at least one special token defined
            assert (
                len(existing_special_tokens) > 0
            ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
            # assign one of the special tokens to also be the pad token
            tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]})

        if add_start_token and max_length:
            # leave room for <BOS> token to be added:
            assert (
                tokenizer.bos_token is not None
            ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
            max_tokenized_len = max_length - 1
        else:
            max_tokenized_len = max_length

        encodings = tokenizer(
            predictions,
            add_special_tokens=False,
            padding=True,
            truncation=True if max_tokenized_len else False,
            max_length=max_tokenized_len,
            return_tensors="pt",
            return_attention_mask=True,
        ).to(device)

        encoded_texts = encodings["input_ids"]
        attn_masks = encodings["attention_mask"]

        # check that each input is long enough:
        if add_start_token:
            assert torch.all(torch.ge(attn_masks.sum(1), 1)), "Each input text must be at least one token long."
        else:
            assert torch.all(
                torch.ge(attn_masks.sum(1), 2)
            ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

        ppls = []
        loss_fct = CrossEntropyLoss(reduction="none")

        for start_index in logging.tqdm(range(0, len(encoded_texts), batch_size)):
            end_index = min(start_index + batch_size, len(encoded_texts))
            encoded_batch = encoded_texts[start_index:end_index]
            attn_mask = attn_masks[start_index:end_index]

            if add_start_token:
                bos_tokens_tensor = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0)).to(device)
                encoded_batch = torch.cat([bos_tokens_tensor, encoded_batch], dim=1)
                attn_mask = torch.cat(
                    [torch.ones(bos_tokens_tensor.size(), dtype=torch.int64).to(device), attn_mask], dim=1
                )

            labels = encoded_batch

            with torch.no_grad():
                out_logits = model(encoded_batch, attention_mask=attn_mask).logits

            shift_logits = out_logits[..., :-1, :].contiguous()
            shift_labels = labels[..., 1:].contiguous()
            shift_attention_mask_batch = attn_mask[..., 1:].contiguous()
            loss = (loss_fct(shift_logits.transpose(1, 2), shift_labels) * shift_attention_mask_batch).sum(1) / shift_attention_mask_batch.sum(1)
            print("loss:", loss)
            print("len:", shift_attention_mask_batch.sum(1))
            perplexity_batch = torch.exp(loss)

            ppls += perplexity_batch.tolist()

        return {"perplexities": ppls, "mean_perplexity": np.mean(ppls)}

3.执行结果

If you want to use `ErnieForCausalLM` as a standalone, add `is_decoder=True.`
input: ['我', '不', '会', '忘', '记', '和', '你', '一', '起', '奋', '斗', '的', '时', '光', '。']
input len: 15
average negative log-likelihood of a sequence: 6.288467170794805
ernie encoder ppl score: 538.3275321802387

**********
device: cpu
Attempting to cast a BatchEncoding to type None. This is not supported.
loss: tensor([8.9537])
len: tensor([14])
hugging third scource:
{'perplexities': [7736.34619140625], 'mean_perplexity': 7736.34619140625}

**********
Attempting to cast a BatchEncoding to type None. This is not supported.
seq_len: 17
average_negative_log_likelihood: tensor(12.2610)
hugging-face ppl of fixed-length: tensor(211290.0781)

**********
meanloss: tensor([12.2610])
len: tensor([16])
ernie decoder ppl score: [211290.28125]

**********
seq_len: 17
average_negative_log_likelihood: tensor(2.6075)
hugging-face ppl of fixed-length gpt2 chinese: tensor(13.5645)

4. 初步结论

采用gpt2计算的PPL较小,和真实数据分布更相似。