Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK : Generalised robustness metrics Pipeline (logits or predictions or loss values)
NOTE : using the only torch module we have implement below scratch
Problem Statement:
Develop a metrics pipeline using PyTorch for evaluating text generation tasks. The pipeline should calculate:
Perplexity: Measures the inverse probability of generated words in context.
BLEU (Text Generation): Precision for n-gram overlap between generated and reference texts.
ROUGE-L: Longest common subsequence (LCS) overlap with references.
Content Preservation Score: Measures content preservation between generated and reference text.
Distinct-1 and Distinct-2: Diversity metrics for unigram and bigram diversity in generated text.
The metrics should be adaptable to different batch sizes, n-gram counts, and specific requirements in text generation evaluation.
1. Perplexity
Perplexity ((P)) is a measure of the inverse probability of predicted words in context, with lower values indicating better performance (higher probability).
For a batch of text sequences, perplexity is calculated as:
[
P = \exp \left( -\frac{1}{N} \sum_{i=1}^{N} \log p(w_i) \right)
]
where:
(N) is the total number of words in the generated text.
(p(w_i)) is the predicted probability of the (i)-th word in the sequence, given the preceding words.
In PyTorch, this can be implemented by calculating the negative log probability for each word and averaging it across the batch, then taking the exponential.
2. BLEU (Text Generation)
BLEU (Bilingual Evaluation Understudy) score measures n-gram overlap between the generated text and reference text, emphasizing precision. BLEU with n-gram up to (N) can be calculated as:
[
\text{BLEU} = \exp \left( \sum_{n=1}^N w_n \log \text{Precision}_n \right) \times \text{BP}
]
where:
(w_n) are the weights for each n-gram precision (commonly (w_n = \frac{1}{N}) for uniform weighting).
Assistant
(\text{Precision}_n) is the modified precision score for each n-gram.
(\text{BP}) is the brevity penalty, which penalizes short generated sequences compared to the reference, calculated as:
[
\text{BP} =
\begin{cases}
1 & \text{if } c > r \
\exp\left(1 - \frac{r}{c}\right) & \text{if } c \leq r
\end{cases}
]
where (c) is the length of the generated sequence, and (r) is the length of the reference.
3. ROUGE-L
ROUGE-L measures the longest common subsequence (LCS) overlap between generated and reference texts, focusing on recall. It’s defined as:
[
\text{ROUGE-L} = \frac{(1 + \beta^2) \times \text{LCS-precision} \times \text{LCS-recall}}{\text{LCS-precision} + \beta^2 \times \text{LCS-recall}}
]
where:
(\text{LCS-precision} = \frac{\text{LCS length}}{\text{length of generated text}})
(\text{LCS-recall} = \frac{\text{LCS length}}{\text{length of reference text}})
(\beta) is typically set to favor recall over precision, often (\beta = 1) for a balanced F-score.
4. Content Preservation Score
Content preservation is usually computed as a similarity score between generated text and reference text, often based on a semantic similarity measure (e.g., cosine similarity between sentence embeddings) or a term-based metric like Jaccard similarity:
[
\text{Content Preservation Score} = \frac{|G \cap R|}{|G \cup R|}
]
where:
(G) is the set of unique content terms in the generated text.
(R) is the set of unique content terms in the reference text.
Alternatively, if using embeddings, compute cosine similarity as:
[
\text{Cosine Similarity} = \frac{\text{Emb}(G) \cdot \text{Emb}(R)}{|\text{Emb}(G)| \times |\text{Emb}(R)|}
]
where (\text{Emb}(G)) and (\text{Emb}(R)) are the embeddings for generated and reference texts.
5. Distinct-1 and Distinct-2
Distinct-n scores measure diversity by calculating the ratio of unique n-grams to total n-grams in the generated text. This metric is helpful to evaluate the lexical variety in text generation.
For Distinct-1 (unigram diversity) and Distinct-2 (bigram diversity), these are defined as:
[
\text{Distinct-1} = \frac{\text{Unique unigrams in generated text}}{\text{Total unigrams in generated text}}
]
[
\text{Distinct-2} = \frac{\text{Unique bigrams in generated text}}{\text{Total bigrams in generated text}}
]
Higher Distinct scores indicate more diverse and less repetitive text generation.
python
import math
from typing import List, Tuple, Dict
import torch
class MetricsPipeline:
"""
A pipeline for evaluating text generation tasks using various robustness metrics.
"""
def __init__(self):
pass
@staticmethod
def calculate_perplexity(
logits: torch.Tensor, targets: torch.Tensor
) -> float:
"""
Calculate perplexity for a batch of sequences.
Args:
logits (torch.Tensor): Logits output by the model with shape (batch_size, sequence_length, vocab_size).
targets (torch.Tensor): Ground truth tokens with shape (batch_size, sequence_length).
Returns:
float: Perplexity score.
"""
try:
if logits.dim() != 3:
raise ValueError(
"Logits tensor must be 3-dimensional (batch_size, sequence_length, vocab_size)."
)
if targets.dim() != 2:
raise ValueError(
"Targets tensor must be 2-dimensional (batch_size, sequence_length)."
)
if logits.size(0) != targets.size(0) or logits.size(1) != targets.size(1):
raise ValueError(
"Logits and targets must have the same batch size and sequence length."
)
log_probs = torch.log_softmax(logits, dim=-1)
targets = targets.unsqueeze(-1)
selected_log_probs = log_probs.gather(dim=-1, index=targets).squeeze(-1)
negative_log_likelihood = -selected_log_probs
average_nll = negative_log_likelihood.mean().item()
perplexity = math.exp(average_nll)
return perplexity
except Exception as e:
raise RuntimeError(f"Error calculating perplexity: {e}")
@staticmethod
def _get_ngrams(tokens: List[str], n: int) -> List[Tuple[str, ...]]:
"""
Generate n-grams from a list of tokens.
Args:
tokens (List[str]): Tokenized text.
n (int): The 'n' in n-gram.
Returns:
List[Tuple[str, ...]]: List of n-grams.
"""
return [tuple(tokens[i : i + n]) for i in range(len(tokens) - n + 1)]
@staticmethod
def calculate_bleu(
generated: str, reference: str, max_n: int = 4
) -> float:
"""
Calculate BLEU score between generated and reference texts.
Args:
generated (str): Generated text.
reference (str): Reference text.
max_n (int, optional): Maximum n-gram size. Defaults to 4.
Returns:
float: BLEU score.
"""
try:
gen_tokens = generated.strip().split()
ref_tokens = reference.strip().split()
precisions = []
for n in range(1, max_n + 1):
gen_ngrams = MetricsPipeline._get_ngrams(gen_tokens, n)
ref_ngrams = MetricsPipeline._get_ngrams(ref_tokens, n)
gen_counts: Dict[Tuple[str, ...], int] = {}
for ng in gen_ngrams:
gen_counts[ng] = gen_counts.get(ng, 0) + 1
ref_counts: Dict[Tuple[str, ...], int] = {}
for ng in ref_ngrams:
ref_counts[ng] = ref_counts.get(ng, 0) + 1
overlap = {
ng: min(count, ref_counts.get(ng, 0))
for ng, count in gen_counts.items()
}
overlap_count = sum(overlap.values())
total_count = sum(gen_counts.values())
precision = (
overlap_count / total_count if total_count > 0 else 0.0
)
precisions.append(precision)
if min(precisions) == 0:
bleu_score = 0.0
else:
log_precisions = [
math.log(p) if p > 0 else float("-inf")
for p in precisions
]
bleu_score = math.exp(
sum(log_precisions) / max_n
)
# Brevity Penalty
c = len(gen_tokens)
r = len(ref_tokens)
if c > r:
bp = 1
elif c == 0:
bp = 0
else:
bp = math.exp(1 - r / c)
bleu = bleu_score * bp
return bleu
except Exception as e:
raise RuntimeError(f"Error calculating BLEU score: {e}")
@staticmethod
def _lcs_length(x: List[str], y: List[str]) -> int:
"""
Compute the length of the longest common subsequence between two token lists.
Args:
x (List[str]): First token list.
y (List[str]): Second token list.
Returns:
int: Length of the LCS.
"""
m = len(x)
n = len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
if x[i] == y[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
else:
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
return dp[m][n]
@staticmethod
def calculate_rouge_l(
generated: str, reference: str, beta: float = 1.0
) -> float:
"""
Calculate ROUGE-L score between generated and reference texts.
Args:
generated (str): Generated text.
reference (str): Reference text.
beta (float, optional): Weighting factor for recall. Defaults to 1.0.
Returns:
float: ROUGE-L score.
"""
try:
gen_tokens = generated.strip().split()
ref_tokens = reference.strip().split()
lcs = MetricsPipeline._lcs_length(gen_tokens, ref_tokens)
if len(gen_tokens) == 0 or len(ref_tokens) == 0:
return 0.0
precision = lcs / len(gen_tokens)
recall = lcs / len(ref_tokens)
if precision + (beta ** 2) * recall == 0:
return 0.0
rouge_l = (
(1 + beta ** 2) * precision * recall
/ (precision + (beta ** 2) * recall)
)
return rouge_l
except Exception as e:
raise RuntimeError(f"Error calculating ROUGE-L score: {e}")
@staticmethod
def calculate_content_preservation(
generated: str, reference: str
) -> float:
"""
Calculate content preservation score between generated and reference texts using Jaccard similarity.
Args:
generated (str): Generated text.
reference (str): Reference text.
Returns:
float: Content preservation score.
"""
try:
gen_tokens = set(generated.strip().split())
ref_tokens = set(reference.strip().split())
if not gen_tokens and not ref_tokens:
return 1.0
if not gen_tokens or not ref_tokens:
return 0.0
intersection = gen_tokens.intersection(ref_tokens)
union = gen_tokens.union(ref_tokens)
jaccard_similarity = len(intersection) / len(union)
return jaccard_similarity
except Exception as e:
raise RuntimeError(
f"Error calculating content preservation score: {e}"
)
@staticmethod
def calculate_distinct_n(
generated: str, n: int
) -> float:
"""
Calculate Distinct-n score for generated text.
Args:
generated (str): Generated text.
n (int): The 'n' in Distinct-n.
Returns:
float: Distinct-n score.
"""
try:
tokens = generated.strip().split()
ngrams = MetricsPipeline._get_ngrams(tokens, n)
total_ngrams = len(ngrams)
unique_ngrams = len(set(ngrams))
if total_ngrams == 0:
return 0.0
distinct_n = unique_ngrams / total_ngrams
return distinct_n
except Exception as e:
raise RuntimeError(f"Error calculating Distinct-{n} score: {e}")
@staticmethod
def calculate_metrics(
logits: torch.Tensor,
targets: torch.Tensor,
generated_texts: List[str],
reference_texts: List[str],
max_bleu_n: int = 4,
) -> Dict[str, float]:
"""
Calculate all metrics and return a dictionary of results.
Args:
logits (torch.Tensor): Logits output by the model with shape (batch_size, sequence_length, vocab_size).
targets (torch.Tensor): Ground truth tokens with shape (batch_size, sequence_length).
generated_texts (List[str]): List of generated texts.
reference_texts (List[str]): List of reference texts.
max_bleu_n (int, optional): Maximum n-gram size for BLEU. Defaults to 4.
Returns:
Dict[str, float]: Dictionary containing all metric scores.
"""
try:
if not (
len(generated_texts)
== len(reference_texts)
== logits.size(0)
== targets.size(0)
):
raise ValueError(
"Lengths of generated texts, reference texts, logits, and targets must be equal."
)
perplexities = MetricsPipeline.calculate_perplexity(
logits, targets
)
bleu_scores = []
rouge_l_scores = []
content_preservation_scores = []
distinct_1_scores = []
distinct_2_scores = []
for gen, ref in zip(generated_texts, reference_texts):
bleu = MetricsPipeline.calculate_bleu(
gen, ref, max_n=max_bleu_n
)
rouge_l = MetricsPipeline.calculate_rouge_l(gen, ref)
content_preservation = MetricsPipeline.calculate_content_preservation(
gen, ref
)
distinct_1 = MetricsPipeline.calculate_distinct_n(gen, 1)
distinct_2 = MetricsPipeline.calculate_distinct_n(gen, 2)
bleu_scores.append(bleu)
rouge_l_scores.append(rouge_l)
content_preservation_scores.append(content_preservation)
distinct_1_scores.append(distinct_1)
distinct_2_scores.append(distinct_2)
metrics = {
"Perplexity": perplexities,
"BLEU": sum(bleu_scores) / len(bleu_scores)
if bleu_scores
else 0.0,
"ROUGE-L": sum(rouge_l_scores) / len(rouge_l_scores)
if rouge_l_scores
else 0.0,
"Content Preservation": sum(content_preservation_scores)
/ len(content_preservation_scores)
if content_preservation_scores
else 0.0,
"Distinct-1": sum(distinct_1_scores) / len(distinct_1_scores)
if distinct_1_scores
else 0.0,
"Distinct-2": sum(distinct_2_scores) / len(distinct_2_scores)
if distinct_2_scores
else 0.0,
}
return metrics
except Exception as e:
raise RuntimeError(f"Error calculating metrics: {e}")
if __name__ == "__main__":
# Example usage
try:
# Sample logits and targets
batch_size = 2
sequence_length = 5
vocab_size = 10
torch.manual_seed(0)
logits = torch.randn(batch_size, sequence_length, vocab_size)
targets = torch.randint(0, vocab_size, (batch_size, sequence_length))
# Sample generated and reference texts
generated_texts = [
"the cat sat on the mat",
"a quick brown fox jumps over the lazy dog",
]
reference_texts = [
"the cat is sitting on the mat",
"the fast brown fox leaps over the lazy dog",
]
pipeline = MetricsPipeline()
metrics = pipeline.calculate_metrics(
logits, targets, generated_texts, reference_texts
)
print("Metrics:")
for metric, value in metrics.items():
print(f"{metric}: {value:.4f}")
except Exception as error:
print(f"An error occurred: {error}")