wafer-cli 0.2.14__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wafer/output.py ADDED
@@ -0,0 +1,248 @@
1
+ """Structured output formatting for CLI commands.
2
+
3
+ Provides JSON and JSONL output formats for machine-readable CLI output.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import re
10
+ from dataclasses import asdict, dataclass, field
11
+ from datetime import UTC, datetime
12
+ from enum import StrEnum
13
+ from typing import TYPE_CHECKING, Any, Literal
14
+
15
+ import typer
16
+
17
+ if TYPE_CHECKING:
18
+ from .evaluate import EvaluateResult
19
+
20
+
21
+ class OutputFormat(StrEnum):
22
+ """Output format for CLI commands."""
23
+
24
+ TEXT = "text" # Human-readable (default)
25
+ JSON = "json" # Single JSON object at end
26
+ JSONL = "jsonl" # Streaming JSON Lines
27
+
28
+
29
+ @dataclass
30
+ class EvalOutput:
31
+ """Structured evaluation result for JSON output."""
32
+
33
+ status: Literal["success", "failure", "error"]
34
+ target: str | None = None
35
+ phase: str | None = None
36
+ correctness: dict[str, Any] | None = None
37
+ benchmark: dict[str, Any] | None = None
38
+ profile: dict[str, Any] | None = None
39
+ error: dict[str, Any] | None = None
40
+ raw_compiler_output: str | None = None
41
+
42
+ def to_json(self, indent: int | None = 2) -> str:
43
+ """Serialize to JSON, excluding None values."""
44
+ data = {k: v for k, v in asdict(self).items() if v is not None}
45
+ return json.dumps(data, indent=indent, default=str)
46
+
47
+
48
+ @dataclass
49
+ class OutputCollector:
50
+ """Collects output events and formats them according to the output format."""
51
+
52
+ format: OutputFormat
53
+ target: str | None = None
54
+ _result: EvalOutput = field(default_factory=lambda: EvalOutput(status="success"))
55
+
56
+ def emit(self, event: str, **data: Any) -> None:
57
+ """Emit an event.
58
+
59
+ For JSONL format, prints immediately. For TEXT, prints human-readable.
60
+ For JSON, events are collected and output at the end.
61
+ """
62
+ if self.format == OutputFormat.JSONL:
63
+ obj = {
64
+ "event": event,
65
+ "timestamp": datetime.now(UTC).isoformat(),
66
+ **data,
67
+ }
68
+ print(json.dumps(obj, default=str), flush=True)
69
+ elif self.format == OutputFormat.TEXT:
70
+ status = data.get("status", "")
71
+ if status:
72
+ typer.echo(f"[wafer] {event}: {status}")
73
+ else:
74
+ typer.echo(f"[wafer] {event}")
75
+
76
+ def set_result(
77
+ self,
78
+ *,
79
+ status: Literal["success", "failure", "error"],
80
+ phase: str | None = None,
81
+ correctness: dict[str, Any] | None = None,
82
+ benchmark: dict[str, Any] | None = None,
83
+ profile: dict[str, Any] | None = None,
84
+ error: dict[str, Any] | None = None,
85
+ raw_compiler_output: str | None = None,
86
+ ) -> None:
87
+ """Set the final result data."""
88
+ self._result = EvalOutput(
89
+ status=status,
90
+ target=self.target,
91
+ phase=phase,
92
+ correctness=correctness,
93
+ benchmark=benchmark,
94
+ profile=profile,
95
+ error=error,
96
+ raw_compiler_output=raw_compiler_output,
97
+ )
98
+
99
+ def set_error(self, phase: str, error_type: str, **details: Any) -> None:
100
+ """Set an error result."""
101
+ self._result.status = "error"
102
+ self._result.phase = phase
103
+ self._result.error = {"type": error_type, **details}
104
+ self._result.target = self.target
105
+
106
+ def finalize(self) -> None:
107
+ """Print final output based on format."""
108
+ if self.format == OutputFormat.JSON:
109
+ print(self._result.to_json())
110
+ elif self.format == OutputFormat.JSONL:
111
+ print(
112
+ json.dumps(
113
+ {
114
+ "event": "completed",
115
+ "timestamp": datetime.now(UTC).isoformat(),
116
+ "result": {k: v for k, v in asdict(self._result).items() if v is not None},
117
+ },
118
+ default=str,
119
+ )
120
+ )
121
+ # TEXT format already printed incrementally
122
+
123
+ def output_text_result(self, result: EvaluateResult) -> None:
124
+ """Print human-readable result summary (TEXT format only)."""
125
+ if self.format != OutputFormat.TEXT:
126
+ return
127
+
128
+ typer.echo("")
129
+ typer.echo("=" * 60)
130
+ # Handle None (correctness not run), True (pass), False (fail)
131
+ if result.all_correct is None:
132
+ status = "OK" # Correctness wasn't checked (e.g., compile-only or prepare-only)
133
+ elif result.all_correct:
134
+ status = "PASS"
135
+ else:
136
+ status = "FAIL"
137
+ typer.echo(f"Result: {status}")
138
+ if result.total_tests > 0:
139
+ score_pct = f"{result.correctness_score:.1%}"
140
+ typer.echo(f"Correctness: {result.passed_tests}/{result.total_tests} ({score_pct})")
141
+ if result.geomean_speedup > 0:
142
+ typer.echo(f"Speedup: {result.geomean_speedup:.2f}x")
143
+ typer.echo("=" * 60)
144
+
145
+ def output_text_error(self, error_message: str) -> None:
146
+ """Print error message (TEXT format only)."""
147
+ if self.format == OutputFormat.TEXT:
148
+ typer.echo(f"Error: {error_message}", err=True)
149
+
150
+
151
+ def format_evaluate_result(result: EvaluateResult, target: str | None = None) -> EvalOutput:
152
+ """Convert EvaluateResult to structured EvalOutput."""
153
+ if not result.success:
154
+ # Error case
155
+ error_info = parse_error_message(result.error_message or "Unknown error")
156
+ return EvalOutput(
157
+ status="error",
158
+ target=target,
159
+ phase=error_info.get("phase", "unknown"),
160
+ error=error_info,
161
+ )
162
+
163
+ if not result.all_correct:
164
+ # Correctness failure
165
+ return EvalOutput(
166
+ status="failure",
167
+ target=target,
168
+ phase="correctness",
169
+ correctness={
170
+ "passed": False,
171
+ "tests_run": result.total_tests,
172
+ "tests_passed": result.passed_tests,
173
+ },
174
+ )
175
+
176
+ # Success
177
+ output = EvalOutput(
178
+ status="success",
179
+ target=target,
180
+ correctness={
181
+ "passed": True,
182
+ "tests_run": result.total_tests,
183
+ "tests_passed": result.passed_tests,
184
+ },
185
+ )
186
+
187
+ if result.geomean_speedup > 0:
188
+ output.benchmark = {"speedup": result.geomean_speedup}
189
+
190
+ return output
191
+
192
+
193
+ def parse_error_message(error_message: str) -> dict[str, Any]:
194
+ """Parse error message to extract structured information."""
195
+ error_info: dict[str, Any] = {"message": error_message}
196
+
197
+ # Try to identify the phase and type from common patterns
198
+ error_lower = error_message.lower()
199
+
200
+ if "compilation" in error_lower or "compile" in error_lower:
201
+ error_info["phase"] = "compilation"
202
+ error_info["type"] = "CompilationError"
203
+ # Try to parse compiler error format: file:line:col: error: message
204
+ parsed = parse_compilation_error(error_message)
205
+ if parsed:
206
+ error_info.update(parsed)
207
+ elif "hsa_status" in error_lower or "memory" in error_lower or "segfault" in error_lower:
208
+ error_info["phase"] = "runtime"
209
+ error_info["type"] = "MemoryViolation"
210
+ elif "timeout" in error_lower:
211
+ error_info["phase"] = "runtime"
212
+ error_info["type"] = "Timeout"
213
+ elif "correctness" in error_lower:
214
+ error_info["phase"] = "correctness"
215
+ error_info["type"] = "CorrectnessError"
216
+ else:
217
+ error_info["phase"] = "unknown"
218
+ error_info["type"] = "UnknownError"
219
+
220
+ return error_info
221
+
222
+
223
+ def parse_compilation_error(raw_output: str) -> dict[str, Any] | None:
224
+ """Extract structured info from compiler error output.
225
+
226
+ Matches patterns like: file.hip:10:14: error: message
227
+ """
228
+ match = re.search(
229
+ r"(?P<file>[\w./]+):(?P<line>\d+):(?P<col>\d+): error: (?P<message>.+)",
230
+ raw_output,
231
+ )
232
+ if match:
233
+ return {
234
+ "file": match.group("file"),
235
+ "line": int(match.group("line")),
236
+ "column": int(match.group("col")),
237
+ "message": match.group("message").strip(),
238
+ }
239
+ return None
240
+
241
+
242
+ def get_output_format(json_flag: bool, jsonl_flag: bool) -> OutputFormat:
243
+ """Determine output format from CLI flags."""
244
+ if jsonl_flag:
245
+ return OutputFormat.JSONL
246
+ if json_flag:
247
+ return OutputFormat.JSON
248
+ return OutputFormat.TEXT
wafer/problems.py ADDED
@@ -0,0 +1,357 @@
1
+ """Problem set management for Wafer CLI.
2
+
3
+ Download and manage kernel optimization problem sets for evaluation.
4
+ Follows the same pattern as corpus.py for consistency.
5
+ """
6
+
7
+ import shutil
8
+ import tarfile
9
+ import tempfile
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Literal
13
+
14
+ import httpx
15
+
16
+ PROBLEMS_CACHE_DIR = Path.home() / ".cache" / "wafer" / "problems"
17
+
18
+ ProblemSetName = Literal["kernelbench", "gpumode"]
19
+
20
+
21
+ @dataclass
22
+ class ProblemSetConfig:
23
+ """Configuration for a downloadable problem set."""
24
+
25
+ name: ProblemSetName
26
+ description: str
27
+ repo: str # GitHub repo in "owner/repo" format
28
+ repo_paths: list[str] # Paths within repo to download
29
+ format_description: str # Brief description of the format
30
+
31
+
32
+ PROBLEM_SETS: dict[ProblemSetName, ProblemSetConfig] = {
33
+ "kernelbench": ProblemSetConfig(
34
+ name="kernelbench",
35
+ description="KernelBench GPU kernel optimization problems (level1-4)",
36
+ repo="ScalingIntelligence/KernelBench",
37
+ repo_paths=["KernelBench"],
38
+ format_description="Class-based: Model/ModelNew with get_inputs/get_init_inputs",
39
+ ),
40
+ "gpumode": ProblemSetConfig(
41
+ name="gpumode",
42
+ description="GPU Mode reference kernels (pmpp, amd, nvidia, bioml)",
43
+ repo="gpu-mode/reference-kernels",
44
+ repo_paths=["problems"],
45
+ format_description="Functional: ref_kernel/custom_kernel with generate_input",
46
+ ),
47
+ }
48
+
49
+
50
+ def _problems_path(name: ProblemSetName) -> Path:
51
+ """Get local path for problem set."""
52
+ return PROBLEMS_CACHE_DIR / name
53
+
54
+
55
+ def _ensure_cache_dir() -> None:
56
+ """Ensure cache directory exists."""
57
+ PROBLEMS_CACHE_DIR.mkdir(parents=True, exist_ok=True)
58
+
59
+
60
+ def _download_github_repo(config: ProblemSetConfig, dest: Path, verbose: bool = True) -> int:
61
+ """Download specific paths from GitHub repo.
62
+
63
+ Args:
64
+ config: Problem set configuration
65
+ dest: Destination directory
66
+ verbose: Print progress
67
+
68
+ Returns:
69
+ Number of files downloaded
70
+ """
71
+ # Fetch tarball from GitHub
72
+ resp = _fetch_github_tarball(config.repo, verbose)
73
+
74
+ # Save to temp file
75
+ with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as tmp:
76
+ tmp.write(resp.content)
77
+ tmp_path = Path(tmp.name)
78
+
79
+ # Extract matching files
80
+ try:
81
+ downloaded = _extract_tarball(tmp_path, dest, config.repo_paths, verbose)
82
+ finally:
83
+ tmp_path.unlink()
84
+
85
+ return downloaded
86
+
87
+
88
+ def _fetch_github_tarball(repo: str, verbose: bool) -> httpx.Response:
89
+ """Fetch tarball from GitHub, trying main then master branch."""
90
+ with httpx.Client(timeout=120.0, follow_redirects=True) as client:
91
+ for branch in ["main", "master"]:
92
+ tarball_url = f"https://api.github.com/repos/{repo}/tarball/{branch}"
93
+ if verbose:
94
+ print(f" Fetching {repo} ({branch} branch)...")
95
+ try:
96
+ resp = client.get(tarball_url)
97
+ resp.raise_for_status()
98
+ return resp
99
+ except httpx.HTTPStatusError:
100
+ if branch == "master":
101
+ raise
102
+ raise RuntimeError(f"Failed to fetch tarball from {repo}") # Should not reach
103
+
104
+
105
+ def _extract_tarball(tmp_path: Path, dest: Path, repo_paths: list[str], verbose: bool) -> int:
106
+ """Extract files from tarball matching repo_paths."""
107
+ downloaded = 0
108
+ with tarfile.open(tmp_path, "r:gz") as tar:
109
+ for member in tar.getmembers():
110
+ if not member.isfile():
111
+ continue
112
+ # Strip the root directory (e.g., "ScalingIntelligence-KernelBench-abc123/")
113
+ rel_path = "/".join(member.name.split("/")[1:])
114
+ if not _matches_repo_paths(rel_path, repo_paths):
115
+ continue
116
+ target = dest / rel_path
117
+ target.parent.mkdir(parents=True, exist_ok=True)
118
+ extracted = tar.extractfile(member)
119
+ if extracted:
120
+ target.write_bytes(extracted.read())
121
+ downloaded += 1
122
+ if verbose and downloaded <= 10:
123
+ print(f" ✓ {rel_path}")
124
+ if verbose and downloaded > 10:
125
+ print(f" ... and {downloaded - 10} more files")
126
+ return downloaded
127
+
128
+
129
+ def _matches_repo_paths(rel_path: str, repo_paths: list[str]) -> bool:
130
+ """Check if rel_path starts with any of the repo_paths."""
131
+ return any(rel_path.startswith(rp) for rp in repo_paths)
132
+
133
+
134
+ def download_problems(name: ProblemSetName, force: bool = False, verbose: bool = True) -> Path:
135
+ """Download a problem set to local cache.
136
+
137
+ Args:
138
+ name: Problem set name
139
+ force: Re-download even if exists
140
+ verbose: Print progress
141
+
142
+ Returns:
143
+ Path to downloaded problem set
144
+
145
+ Raises:
146
+ ValueError: If problem set name is unknown
147
+ httpx.HTTPError: If download fails
148
+ """
149
+ if name not in PROBLEM_SETS:
150
+ raise ValueError(f"Unknown problem set: {name}. Available: {list(PROBLEM_SETS.keys())}")
151
+
152
+ config = PROBLEM_SETS[name]
153
+ dest = _problems_path(name)
154
+
155
+ if dest.exists() and not force:
156
+ if verbose:
157
+ print(f"Problem set '{name}' already exists at {dest}")
158
+ print("Use --force to re-download")
159
+ return dest
160
+
161
+ _ensure_cache_dir()
162
+
163
+ if dest.exists():
164
+ shutil.rmtree(dest)
165
+ dest.mkdir(parents=True)
166
+
167
+ if verbose:
168
+ print(f"Downloading {name}: {config.description}")
169
+
170
+ try:
171
+ count = _download_github_repo(config, dest, verbose)
172
+ except Exception:
173
+ # Clean up partial download so next run doesn't skip with stale cache
174
+ if dest.exists():
175
+ shutil.rmtree(dest)
176
+ raise
177
+
178
+ if verbose:
179
+ print(f"Downloaded {count} files to {dest}")
180
+
181
+ return dest
182
+
183
+
184
+ def get_problems_path(name: ProblemSetName) -> Path | None:
185
+ """Get path to downloaded problem set, or None if not downloaded.
186
+
187
+ Args:
188
+ name: Problem set name
189
+
190
+ Returns:
191
+ Path if downloaded, None otherwise
192
+ """
193
+ if name not in PROBLEM_SETS:
194
+ return None
195
+ path = _problems_path(name)
196
+ return path if path.exists() else None
197
+
198
+
199
+ def list_problem_sets(verbose: bool = True) -> dict[ProblemSetName, bool]:
200
+ """List available problem sets and their download status.
201
+
202
+ Returns:
203
+ Dict of problem set name -> is_downloaded
204
+ """
205
+ result: dict[ProblemSetName, bool] = {}
206
+ for name, config in PROBLEM_SETS.items():
207
+ path = _problems_path(name)
208
+ exists = path.exists()
209
+ result[name] = exists
210
+ if verbose:
211
+ status = "✓" if exists else " "
212
+ print(f"[{status}] {name}: {config.description}")
213
+ print(f" Format: {config.format_description}")
214
+ if exists:
215
+ file_count = sum(1 for _ in path.rglob("*.py") if _.is_file())
216
+ print(f" Location: {path} ({file_count} Python files)")
217
+ return result
218
+
219
+
220
+ def list_problems(name: ProblemSetName, verbose: bool = True) -> list[str]:
221
+ """List available problems in a problem set.
222
+
223
+ Args:
224
+ name: Problem set name
225
+ verbose: Print to stdout
226
+
227
+ Returns:
228
+ List of problem IDs
229
+
230
+ Raises:
231
+ ValueError: If problem set not downloaded
232
+ """
233
+ path = get_problems_path(name)
234
+ if path is None:
235
+ raise ValueError(
236
+ f"Problem set '{name}' is not downloaded. Run:\n wafer evaluate {name} download"
237
+ )
238
+
239
+ if name == "kernelbench":
240
+ problems = _list_kernelbench_problems(path)
241
+ elif name == "gpumode":
242
+ problems = _list_gpumode_problems(path)
243
+ else:
244
+ problems = []
245
+
246
+ if verbose:
247
+ if not problems:
248
+ print(f"No problems found in {name}")
249
+ else:
250
+ print(f"Available problems in {name} ({len(problems)} total):\n")
251
+ for p in problems:
252
+ print(f" {p}")
253
+
254
+ return problems
255
+
256
+
257
+ def _list_kernelbench_problems(path: Path) -> list[str]:
258
+ """List KernelBench problems: level1/1_Name.py format."""
259
+ problems: list[str] = []
260
+ kb_root = path / "KernelBench"
261
+ if not kb_root.exists():
262
+ kb_root = path # In case structure is flat
263
+
264
+ for level_dir in sorted(kb_root.iterdir()):
265
+ if not (level_dir.is_dir() and level_dir.name.startswith("level")):
266
+ continue
267
+ for problem_file in sorted(level_dir.glob("*.py")):
268
+ if problem_file.name.startswith("__"):
269
+ continue
270
+ problem_id = f"{level_dir.name}/{problem_file.stem}"
271
+ problems.append(problem_id)
272
+ return problems
273
+
274
+
275
+ def _list_gpumode_problems(path: Path) -> list[str]:
276
+ """List GPUMode problems: category/problem_name format."""
277
+ problems: list[str] = []
278
+ problems_root = path / "problems"
279
+ if not problems_root.exists():
280
+ problems_root = path
281
+
282
+ for category_dir in sorted(problems_root.iterdir()):
283
+ if not _is_valid_problem_dir(category_dir):
284
+ continue
285
+ for problem_dir in sorted(category_dir.iterdir()):
286
+ if not _is_valid_problem_dir(problem_dir):
287
+ continue
288
+ # Check if it has the expected files
289
+ has_reference = (problem_dir / "reference.py").exists()
290
+ has_task = (problem_dir / "task.yml").exists()
291
+ if has_reference or has_task:
292
+ problem_id = f"{category_dir.name}/{problem_dir.name}"
293
+ problems.append(problem_id)
294
+ return problems
295
+
296
+
297
+ def _is_valid_problem_dir(path: Path) -> bool:
298
+ """Check if path is a valid problem directory (not hidden/special)."""
299
+ return path.is_dir() and not path.name.startswith((".", "_"))
300
+
301
+
302
+ def get_problem_path(name: ProblemSetName, problem_id: str) -> Path | None:
303
+ """Get path to a specific problem.
304
+
305
+ Args:
306
+ name: Problem set name
307
+ problem_id: Problem ID (e.g., "level4/103" or "pmpp/vectoradd_py")
308
+
309
+ Returns:
310
+ Path to problem file/directory, or None if not found
311
+ """
312
+ base_path = get_problems_path(name)
313
+ if base_path is None:
314
+ return None
315
+
316
+ if name == "kernelbench":
317
+ # Parse problem_id like "level4/103" or "level4/103_GroupedQueryAttention"
318
+ parts = problem_id.split("/")
319
+ if len(parts) != 2:
320
+ return None
321
+
322
+ level_str, problem_part = parts
323
+ if not level_str.startswith("level"):
324
+ level_str = f"level{level_str}"
325
+
326
+ kb_root = base_path / "KernelBench"
327
+ if not kb_root.exists():
328
+ kb_root = base_path
329
+
330
+ problem_dir = kb_root / level_str
331
+ if not problem_dir.exists():
332
+ return None
333
+
334
+ # Find matching problem file
335
+ problem_files = list(problem_dir.glob(f"{problem_part}*.py"))
336
+ if not problem_files:
337
+ # Try exact match
338
+ exact = problem_dir / f"{problem_part}.py"
339
+ if exact.exists():
340
+ return exact
341
+ return None
342
+
343
+ return problem_files[0]
344
+
345
+ elif name == "gpumode":
346
+ # Parse problem_id like "pmpp/vectoradd_py"
347
+ problems_root = base_path / "problems"
348
+ if not problems_root.exists():
349
+ problems_root = base_path
350
+
351
+ problem_path = problems_root / problem_id
352
+ if problem_path.exists() and problem_path.is_dir():
353
+ return problem_path
354
+
355
+ return None
356
+
357
+ return None