Datasets:
File size: 9,490 Bytes
06c7e2f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | """Ignoring Context Task - Information retrieval with distractors.
Tests the model's ability to extract relevant information while ignoring
irrelevant context. Similar to "needle in a haystack" but simpler.
Format:
[Filler text] KEY FACT [More filler] Question: [Query about KEY FACT]
Answer: [Extracted information]
Example:
Some text here. X = 5. More text here.
Question: What is X?
Answer: 5
This tests selective attention and information retrieval capabilities.
"""
import random
import string
from typing import Dict, List, Optional
from tasks.base_task import BaseTask, TaskConfig
class IgnoringContextTask(BaseTask):
"""
Task testing the ability to extract key information from irrelevant context.
The model must find and extract a variable assignment buried in filler text.
"""
TASK_NAME = "ignoring_context"
def __init__(self, config: TaskConfig, use_generator: bool = False):
"""
Initialize IgnoringContextTask.
Args:
config: TaskConfig with task settings
use_generator: If True, generate synthetic examples with random variables
"""
self.use_generator = use_generator
super().__init__(config)
def _generate_filler_text(self, num_words: int = 5, seed: Optional[int] = None) -> str:
"""Generate random filler text."""
if seed is not None:
random.seed(seed)
# Simple words for filler
filler_words = [
"the", "a", "is", "was", "are", "were", "has", "have", "had",
"today", "yesterday", "tomorrow", "here", "there", "then", "now",
"cat", "dog", "tree", "house", "car", "book", "day", "time",
"good", "bad", "nice", "big", "small", "red", "blue", "green",
"went", "came", "saw", "said", "made", "took", "gave", "found"
]
words = [random.choice(filler_words) for _ in range(num_words)]
return " ".join(words).capitalize() + "."
def generate_example(
self,
variable: Optional[str] = None,
value: Optional[int] = None,
filler_before: int = 5,
filler_after: int = 5,
seed: Optional[int] = None
) -> Dict[str, str]:
"""Generate a single example with a variable assignment buried in context.
Args:
variable: Variable name (e.g., "X"). If None, randomly chosen.
value: Value to assign. If None, random integer 1-20.
filler_before: Number of filler words before the key fact.
filler_after: Number of filler words after the key fact.
seed: Random seed for reproducibility.
Returns:
Dict with input, output, variable, and value.
"""
if seed is not None:
random.seed(seed)
# Generate variable and value if not provided
if variable is None:
variable = random.choice(['X', 'Y', 'Z', 'A', 'B', 'N', 'M'])
if value is None:
value = random.randint(1, 20)
# Generate filler text
before = self._generate_filler_text(filler_before, seed)
after = self._generate_filler_text(filler_after, seed=(seed+1) if seed else None)
# Create the context with embedded fact
context = f"{before} {variable} = {value}. {after}"
question = f"Question: What is {variable}?"
# Combined input
input_str = f"{context}\n{question}"
return {
"input": input_str,
"output": str(value),
"variable": variable,
"value": value,
"context_length": len(context.split())
}
def generate_examples(
self,
num_examples: int,
filler_range: tuple = (3, 8),
seed: Optional[int] = None
) -> List[Dict[str, str]]:
"""Generate multiple examples with varying context lengths.
Args:
num_examples: Number of examples to generate.
filler_range: (min, max) words for filler text.
seed: Random seed for reproducibility.
Returns:
List of example dictionaries.
"""
if seed is not None:
random.seed(seed)
examples = []
for i in range(num_examples):
filler_len = random.randint(*filler_range)
example = self.generate_example(
filler_before=filler_len,
filler_after=filler_len,
seed=(seed + i) if seed else None
)
examples.append(example)
return examples
def get_icl_examples(
self,
num_examples: int = 10,
shuffle: bool = True,
seed: Optional[int] = None,
fresh: bool = True,
filler_range: tuple = (3, 8),
) -> List[Dict[str, str]]:
"""
Return ICL-formatted examples.
If use_generator=True, generates synthetic examples.
Otherwise, uses the standard BaseTask logic with stored data.
Args:
num_examples: Number of examples to return.
shuffle: Whether to shuffle (ignored if use_generator=True).
seed: Random seed for reproducibility.
fresh: Whether to prefer unused examples (ignored if use_generator=True).
filler_range: (min, max) words for filler text in generated examples.
Returns:
List of example dictionaries with 'input' and 'output' keys.
"""
if self.use_generator:
# Generate fresh examples on-the-fly
return self.generate_examples(num_examples, filler_range, seed)
else:
# Use the standard BaseTask logic with stored data
return super().get_icl_examples(
num_examples=num_examples,
shuffle=shuffle,
seed=seed,
fresh=fresh
)
def evaluate(self, predictions: List[str], split: str = "test", **kwargs) -> Dict[str, float]:
"""Evaluate predictions with exact match accuracy."""
ground_truth = self.get_ground_truth(split)
if len(predictions) != len(ground_truth):
raise ValueError(
f"Prediction count ({len(predictions)}) doesn't match "
f"ground truth count ({len(ground_truth)})"
)
# Preprocess predictions
processed_predictions = [self.preprocess_prediction(pred) for pred in predictions]
# Calculate exact match accuracy
correct = sum(
1 for pred, gt in zip(processed_predictions, ground_truth)
if pred.strip() == gt.strip()
)
accuracy = correct / len(ground_truth) if ground_truth else 0.0
return {
"accuracy": accuracy,
"correct": correct,
"total": len(ground_truth)
}
def make_ignoring_context_task(
config: TaskConfig = None,
use_generator: bool = False,
) -> IgnoringContextTask:
"""Factory function to create an IgnoringContextTask.
Args:
config: Optional TaskConfig. If None, creates default config with examples.
use_generator: If True, generate synthetic examples on-the-fly.
Returns:
IgnoringContextTask instance.
"""
if config is None:
if use_generator:
# Minimal config for generator mode
default_examples = [
{
"input": "Some text here. X = 5. More text.\nQuestion: What is X?",
"output": "5"
}
]
else:
# Static examples with varying context lengths
default_examples = [
{
"input": "The cat sat. X = 3. A dog ran.\nQuestion: What is X?",
"output": "3",
"variable": "X",
"value": 3
},
{
"input": "Today was nice and sunny. Y = 7. We went to the park.\nQuestion: What is Y?",
"output": "7",
"variable": "Y",
"value": 7
},
{
"input": "The house is big and blue. Z = 12. Birds were singing.\nQuestion: What is Z?",
"output": "12",
"variable": "Z",
"value": 12
},
{
"input": "A car drove by fast. N = 1. The tree is tall.\nQuestion: What is N?",
"output": "1",
"variable": "N",
"value": 1
},
{
"input": "Books are good to read every day. M = 15. Time goes quickly.\nQuestion: What is M?",
"output": "15",
"variable": "M",
"value": 15
},
]
config = TaskConfig(
name="ignoring_context",
description="Extract key information while ignoring irrelevant context",
data_format="memory",
in_memory_data=default_examples,
num_demonstrations=3,
)
return IgnoringContextTask(config, use_generator=use_generator)
|