Create a compute_metrics function with the required parameters.
(tokenizer, args, metric)
| 1 | import numpy as np |
| 2 | |
| 3 | def create_compute_metrics_function(tokenizer, args, metric): |
| 4 | """Create a compute_metrics function with the required parameters.""" |
| 5 | |
| 6 | task_to_labels = { |
| 7 | 'cola': ['unacceptable', 'acceptable'], |
| 8 | 'sst2': ['negative', 'positive'], |
| 9 | 'mrpc': ['not_equivalent', 'equivalent'], |
| 10 | 'qqp': ['not_duplicate', 'duplicate'], |
| 11 | 'stsb': None, # Regression task |
| 12 | 'mnli': ['entailment', 'neutral', 'contradiction'], |
| 13 | 'qnli': ['entailment', 'not_entailment'], |
| 14 | 'rte': ['entailment', 'not_entailment'], |
| 15 | 'wnli': ['not_entailment', 'entailment'] |
| 16 | } |
| 17 | |
| 18 | def compute_metrics(eval_preds): |
| 19 | preds, labels = eval_preds |
| 20 | |
| 21 | # Convert predictions to numpy array and get the first element if it's a tuple |
| 22 | if isinstance(preds, tuple): |
| 23 | preds = preds[0] |
| 24 | |
| 25 | # Ensure preds is a numpy array |
| 26 | preds = np.array(preds) |
| 27 | |
| 28 | # Handle multi-dimensional arrays (e.g., from beam search) |
| 29 | if len(preds.shape) > 2: |
| 30 | preds = preds.reshape(-1, preds.shape[-1]) |
| 31 | |
| 32 | # Convert to list of lists if necessary |
| 33 | if isinstance(preds[0], np.ndarray): |
| 34 | preds = [pred.tolist() for pred in preds] |
| 35 | |
| 36 | try: |
| 37 | # Decode predictions |
| 38 | decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) |
| 39 | # Clean up decoded predictions (remove extra whitespace) |
| 40 | decoded_preds = [pred.strip() for pred in decoded_preds] |
| 41 | |
| 42 | if args.task == 'stsb': |
| 43 | # Convert string predictions to float for regression task |
| 44 | # Handle potential formatting issues |
| 45 | decoded_preds = [float(pred.replace(',', '.')) if pred.strip() else 0.0 |
| 46 | for pred in decoded_preds] |
| 47 | else: |
| 48 | # Convert string predictions to label indices for classification tasks |
| 49 | label_list = task_to_labels[args.task] |
| 50 | decoded_preds = [label_list.index(pred) if pred in label_list |
| 51 | else 0 for pred in decoded_preds] |
| 52 | |
| 53 | # Handle labels |
| 54 | if labels is not None: |
| 55 | # Replace -100 with pad token |
| 56 | labels = np.where(labels != -100, labels, tokenizer.pad_token_id) |
| 57 | |
| 58 | # Convert labels to list of lists if necessary |
| 59 | if isinstance(labels[0], np.ndarray): |
| 60 | labels = [label.tolist() for label in labels] |
nothing calls this directly
no outgoing calls
no test coverage detected