File size: 7,331 Bytes
5fed0fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Pair expansion and management for batch evaluation.



A Pair represents a (solution, problem) combination to evaluate.

"""

import hashlib
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional

from ..models import get_model_prefix, sanitize_problem_name


@dataclass
class Pair:
    """Represents a solution-problem pair for evaluation."""

    solution: str  # Solution identifier (e.g., "gpt5_flash_attn")
    problem: str   # Problem identifier (e.g., "flash_attn")

    @property
    def id(self) -> str:
        """Unique identifier for this pair."""
        return f"{self.solution}:{self.problem}"

    @property
    def safe_name(self) -> str:
        """Filesystem-safe name for this pair."""
        base = f"{self.solution}-{self.problem}"
        digest = hashlib.md5(base.encode("utf-8")).hexdigest()[:8]
        sanitized = _sanitize_name(base)
        suffix = f"-{digest}"
        max_len = 63
        available = max_len - len(suffix)
        trimmed = sanitized[:available].rstrip("-")
        return _sanitize_name(f"{trimmed}{suffix}")

    def __hash__(self):
        return hash(self.id)

    def __eq__(self, other):
        if isinstance(other, Pair):
            return self.id == other.id
        return False


def _sanitize_name(name: str) -> str:
    """Sanitize a name to be a valid cluster/file name."""
    cleaned = []
    valid = "abcdefghijklmnopqrstuvwxyz0123456789-"
    last_dash = False
    for ch in name.lower():
        if ch in valid:
            cleaned.append(ch)
            last_dash = ch == "-"
        else:
            if not last_dash:
                cleaned.append("-")
                last_dash = True
    sanitized = "".join(cleaned).strip("-")
    return sanitized or "job"


# get_model_prefix and sanitize_problem_name imported from ..models


def expand_pairs(

    problems: List[str],

    models: List[str],

    variants: Optional[List[int]] = None,

    *,

    solutions_dir: Optional[Path] = None,

    validate_paths: bool = True,

) -> List[Pair]:
    """

    Expand problems × models × variants into pairs.



    Args:

        problems: List of problem IDs (e.g., ["flash_attn", "cross_entropy"])

        models: List of model names (e.g., ["gpt-5", "claude-sonnet-4-5"])

        variants: List of variant indices (default: [0] for no suffix)

        solutions_dir: Directory containing solutions (for validation)

        validate_paths: Whether to validate solution paths exist



    Returns:

        List of Pair objects

    """
    if variants is None:
        variants = [0]

    pairs: List[Pair] = []

    for problem in problems:
        problem_name = sanitize_problem_name(problem)

        for model in models:
            model_prefix = get_model_prefix(model)

            for variant_idx in variants:
                suffix = "" if variant_idx == 0 else f"_{variant_idx}"
                solution_name = f"{model_prefix}_{problem_name}{suffix}"

                if validate_paths and solutions_dir:
                    solution_path = solutions_dir / solution_name
                    if not solution_path.exists():
                        continue

                pairs.append(Pair(solution=solution_name, problem=problem))

    return pairs


def read_pairs_file(path: Path) -> List[Pair]:
    """

    Read pairs from a pairs file.



    Format: one pair per line as "solution:problem"

    Lines starting with # are comments.

    """
    pairs: List[Pair] = []

    with path.open("r", encoding="utf-8") as f:
        for line in f:
            stripped = line.strip()
            if not stripped or stripped.startswith("#"):
                continue
            if ":" not in stripped:
                raise ValueError(f"Invalid pair line (expected solution:problem): {stripped}")
            solution, problem = stripped.split(":", 1)
            pairs.append(Pair(solution=solution.strip(), problem=problem.strip()))

    return pairs


def read_problems_file(path: Path) -> List[str]:
    """Read problems from a problems file (one per line)."""
    problems: List[str] = []

    with path.open("r", encoding="utf-8") as f:
        for line in f:
            stripped = line.strip()
            if not stripped or stripped.startswith("#"):
                continue
            # Normalize: remove 'research/' prefix if present
            if stripped.startswith("research/"):
                stripped = stripped[len("research/"):]
            problems.append(stripped)

    return problems


def read_models_file(path: Path) -> List[str]:
    """Read models from a models file (one per line)."""
    models: List[str] = []

    with path.open("r", encoding="utf-8") as f:
        for line in f:
            stripped = line.strip()
            if not stripped or stripped.startswith("#"):
                continue
            models.append(stripped)

    return models


def read_variants_file(path: Path) -> List[int]:
    """Read variant indices from a file (one per line)."""
    variants: List[int] = []

    if not path.exists():
        return [0]  # Default: just index 0 (no suffix)

    with path.open("r", encoding="utf-8") as f:
        for line in f:
            stripped = line.strip()
            if not stripped or stripped.startswith("#"):
                continue
            try:
                variants.append(int(stripped))
            except ValueError:
                pass

    return variants if variants else [0]


def read_solution_config(solution_dir: Path) -> Optional[str]:
    """

    Read problem from a solution's config.yaml.



    Returns:

        Problem path (e.g., "flash_attn") or None if not found.

    """
    config_file = solution_dir / "config.yaml"
    if not config_file.exists():
        return None

    try:
        import yaml
        with config_file.open("r", encoding="utf-8") as f:
            config = yaml.safe_load(f)
        if config and isinstance(config, dict):
            return config.get("problem")
    except Exception:
        # Fallback: simple parsing for "problem: value"
        try:
            content = config_file.read_text(encoding="utf-8")
            for line in content.splitlines():
                line = line.strip()
                if line.startswith("problem:"):
                    return line.split(":", 1)[1].strip()
        except Exception:
            pass

    return None


def scan_solutions_dir(solutions_dir: Path) -> List[Pair]:
    """

    Scan solutions directory and build pairs from config.yaml files.



    Args:

        solutions_dir: Path to solutions directory



    Returns:

        List of Pair objects for solutions that have valid config.yaml

    """
    pairs: List[Pair] = []

    if not solutions_dir.is_dir():
        return pairs

    for solution_path in sorted(solutions_dir.iterdir()):
        if not solution_path.is_dir() or solution_path.name.startswith("."):
            continue

        problem = read_solution_config(solution_path)
        if problem:
            pairs.append(Pair(solution=solution_path.name, problem=problem))

    return pairs