File size: 11,786 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
270
271
272
273
274
275
276
277
278
279
280
281
282
"""Simple ICL task implementation with category-based demonstrations."""

from typing import Dict, List, Any
import pandas as pd
from ..base_task import BaseTask, TaskConfig


class SimpleICLTask(BaseTask):
    """Task for simple in-context learning with category-based demonstrations."""
    
    TASK_NAME = "simple_icl"  # Auto-registration name

    # Categories whose correct answer is always exactly one character.
    # Scoring for these is lenient: we extract the first alphabetic char
    # from the model's output so that verbose responses like
    # "The first letter is t." still score correctly.
    SINGLE_CHAR_CATEGORIES = {"first_letter", "last_letter", "uppercase", "lowercase"}

    # Explicit task preamble prepended before the few-shot examples for
    # single-char categories.  The preamble anchors the expected output
    # format so models do not produce verbose completions.
    CATEGORY_PREAMBLES = {
        "first_letter": "# Output only the first letter of each phrase.",
        "last_letter":  "# Output only the last letter of each phrase.",
        "uppercase":    "# Output the uppercase version of each letter.",
        "lowercase":    "# Output the lowercase version of each letter.",
    }

    def __init__(self, config: TaskConfig):
        super().__init__(config)
        
        # Define hardcoded demonstrations for each category
        import string
        import random

        # Build full alphabet demonstrations for completeness.
        # Shuffle with a fixed seed so the 5 shown demos are non-consecutive,
        # which eliminates the "consecutive alphabetic shift" ambiguity that
        # arises when the model always sees a->A, b->B, c->C, d->D, e->E.
        _rng = random.Random(42)
        uppercase_demos = [f"{ch.lower()} -> {ch}" for ch in string.ascii_uppercase]
        _rng.shuffle(uppercase_demos)
        lowercase_demos = [f"{ch} -> {ch.lower()}" for ch in string.ascii_uppercase]
        _rng.shuffle(lowercase_demos)

        self.category_demonstrations = {
            "uppercase": uppercase_demos,
            "lowercase": lowercase_demos,
            "first_letter": [
                "the cat went up the tree -> t",
                "elephants are cool -> e",
                "beautiful morning sunshine -> b",
                "running through the forest -> r",
                "amazing journey ahead -> a",
            ],
            "last_letter": [
                "the cat went up the tree -> e",
                "elephants are cool -> l",
                "beautiful morning sunshine -> e",
                "running through the forest -> t",
                "amazing journey ahead -> d",
            ],
            "translate_eng_fr": [
                "hello -> bonjour",
                "goodbye -> au revoir",
                "thank you -> merci",
                "please -> s'il vous plaît",
                "yes -> oui",
                "cat -> chat",
                "dog -> chien",
                "house -> maison",
                "car -> voiture",
                "book -> livre",
                "flower -> fleur",
                "pen -> stylo",
                "pencil -> crayon",
            ],
            "translate_fr_eng": [
                "bonjour -> hello",
                "au revoir -> goodbye",
                "merci -> thank you",
                "s'il vous plaît -> please",
                "oui -> yes",
                "chat -> cat",
                "chien -> dog",
                "maison -> house",
                "voiture -> car",
                "livre -> book",
                "fleur -> flower",
                "stylo -> pen",
                "crayon -> pencil",
            ],
            "translate_eng_sp": [
                "hello -> hola",
                "goodbye -> adiós",
                "thank you -> gracias",
                "please -> por favor",
                "yes -> sí",
                "cat -> gato",
                "dog -> perro",
                "house -> casa",
                "car -> coche",
                "book -> libro",
                "flower -> flor",
                "pen -> bolígrafo",
                "pencil -> lápiz",
                "flower -> flor",
            ],
            "translate_sp_eng": [
                "hola -> hello",
                "adiós -> goodbye",
                "gracias -> thank you",
                "por favor -> please",
                "sí -> yes",
                "gato -> cat",
                "perro -> dog",
                "casa -> house",
                "coche -> car",
                "libro -> book",
                "flor -> flower",
                "bolígrafo -> pen",
                "lápiz -> pencil",
                "flor -> flower"
            ],
            "present_to_gerund": [
                "run -> running", "swim -> swimming", "walk -> walking",
                "jump -> jumping", "dance -> dancing", "sing -> singing",
                "read -> reading", "write -> writing", "sleep -> sleeping",
            ],
            "singular_to_plural": [
                "cat -> cats", "dog -> dogs", "book -> books", "car -> cars",
                "house -> houses", "child -> children", "mouse -> mice",
            ],
            "country_to_capital": [
                "France -> Paris", "Germany -> Berlin", "Italy -> Rome",
                "Spain -> Madrid", "United Kingdom -> London", "Japan -> Tokyo",
                "Canada -> Ottawa", "Australia -> Canberra",
            ],
            "country_to_currency": [
                "France -> Euro", "United States -> Dollar", "United Kingdom -> Pound",
                "Japan -> Yen", "Canada -> Canadian Dollar", "Australia -> Australian Dollar",
                "India -> Rupee", "China -> Yuan",
            ],
        }
    
    def _load_data(self):
        """Load data from CSV file."""
        import pandas as pd
        
        if self.config.data_path:
            self.data = pd.read_csv(self.config.data_path)
        else:
            # If no data path, create empty DataFrame
            self.data = pd.DataFrame(columns=[self.config.input_column, self.config.output_column])
    
    def _preprocess_for_category(self, prediction: str, category: str) -> str:
        """Return the cleaned prediction for a given category.

        For single-char categories the logic is:
          1. Strip surrounding whitespace and trailing punctuation from the
             first output line.  If that reduces to a single alpha char, return it.
          2. Otherwise scan for the last standalone single letter in the first
             output line (word-boundary on both sides), which handles verbose
             completions such as "The first letter is t." → 't'.
        For all other categories trailing punctuation is stripped from the
        first output line.
        """
        import re
        first_line = prediction.strip().split('\n')[0].strip() if prediction else ""
        if category in self.SINGLE_CHAR_CATEGORIES:
            stripped = first_line.strip('.,!?;:\'"() ')
            if len(stripped) == 1 and stripped.isalpha():
                return stripped
            # Find all standalone single letters; return the last one, which is
            # typically the actual answer in verbose outputs like
            # "The first letter is t."
            matches = re.findall(r'\b([a-zA-Z])\b', first_line)
            if matches:
                return matches[-1]
            return stripped[:1] if stripped else first_line
        return first_line.rstrip('.,!?;:')

    def build_prompt(self, instance: Dict[str, Any], num_shots: int = -1) -> str:
        """Build a prompt with category-specific demonstrations.
        
        Args:
            instance: The instance to build a prompt for
            num_shots: Number of in-context learning examples.
                       Defaults to self.config.num_demonstrations.
        
        Returns:
            Formatted prompt string
        """
        # Use config value when caller did not specify explicitly
        if num_shots < 0:
            num_shots = self.config.num_demonstrations

        category = instance.get('category_name', '')
        
        # Check if we have demonstrations in the config (from in-memory data)
        if (self.config.in_memory_demonstrations and 
            isinstance(self.config.in_memory_demonstrations, dict)):
            demos = self.config.in_memory_demonstrations.get(category, [])
        else:
            # Fallback to hardcoded demonstrations
            demos = self.category_demonstrations.get(category, [])
        
        # Exclude demonstrations that match the current instance input to avoid leaking the test item
        instance_input = instance.get(self.config.input_column, '')
        filtered_demos = []
        for d in demos:
            # Each demo may be formatted like 'input -> output'
            demo_input = d.split('->', 1)[0].strip()
            if demo_input != instance_input:
                filtered_demos.append(d)

        # Limit to num_shots if provided
        if filtered_demos and num_shots > 0:
            demos = filtered_demos[:num_shots]
        else:
            demos = filtered_demos
        
        prompt = ""
        # Prepend an explicit format instruction for single-char categories so
        # models do not produce verbose completions.
        preamble = self.CATEGORY_PREAMBLES.get(category)
        if preamble:
            prompt += f"{preamble}\n"
        if demos:
            for demo in demos:
                prompt += f"{demo}\n"
        
        # Add the current question
        prompt += f"{instance[self.config.input_column]} ->"
        
        return prompt
    
    def evaluate(self, predictions: List[str], split: str = "test", **kwargs) -> Dict[str, float]:
        """Evaluate predictions with exact match accuracy, including per-category metrics."""
        ground_truth = self.get_ground_truth(split)
        task_data = self.get_split(split)
        
        if len(predictions) != len(ground_truth):
            raise ValueError(f"Prediction count ({len(predictions)}) doesn't match ground truth count ({len(ground_truth)})")
        
        # Category-aware preprocessing: single-char tasks extract first letter;
        # other tasks strip trailing punctuation from the first output line.
        processed_predictions = [
            self._preprocess_for_category(pred, item.get('category_name', ''))
            for pred, item in zip(predictions, task_data)
        ]
        
        # Overall accuracy
        correct = sum(1 for pred, gt in zip(processed_predictions, ground_truth) 
                     if pred.lower().strip() == gt.lower().strip())
        accuracy = correct / len(ground_truth)
        
        results = {
            "accuracy": accuracy,
            "correct": correct,
            "total": len(ground_truth)
        }
        
        # Per-category accuracy
        category_stats = {}
        for pred, gt, item in zip(processed_predictions, ground_truth, task_data):
            category = item.get("category_name", "unknown")
            if category not in category_stats:
                category_stats[category] = {"correct": 0, "total": 0}
            
            category_stats[category]["total"] += 1
            if pred.lower().strip() == gt.lower().strip():
                category_stats[category]["correct"] += 1
        
        # Calculate per-category accuracy
        for category, stats in category_stats.items():
            results[f"accuracy_{category}"] = stats["correct"] / stats["total"]
            results[f"correct_{category}"] = stats["correct"]
            results[f"total_{category}"] = stats["total"]
        
        return results