weco 0.2.5__tar.gz → 0.2.7__tar.gz
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.
- {weco-0.2.5 → weco-0.2.7}/.github/workflows/lint.yml +10 -7
- {weco-0.2.5 → weco-0.2.7}/.github/workflows/release.yml +2 -2
- {weco-0.2.5 → weco-0.2.7}/.gitignore +2 -0
- {weco-0.2.5 → weco-0.2.7}/PKG-INFO +106 -15
- {weco-0.2.5 → weco-0.2.7}/README.md +104 -13
- weco-0.2.7/examples/cuda/evaluate.py +157 -0
- weco-0.2.7/examples/cuda/guide.md +113 -0
- weco-0.2.7/examples/cuda/optimize.py +44 -0
- {weco-0.2.5/examples/simple-torch → weco-0.2.7/examples/hello-kernel-world}/evaluate.py +32 -17
- {weco-0.2.5/examples/simple-mlx → weco-0.2.7/examples/metal}/evaluate.py +28 -20
- weco-0.2.5/examples/simple-mlx/metal-examples.rst → weco-0.2.7/examples/metal/examples.rst +2 -1
- weco-0.2.7/examples/metal/optimize.py +28 -0
- weco-0.2.7/examples/spaceship-titanic/README.md +93 -0
- weco-0.2.7/examples/spaceship-titanic/baseline.py +27 -0
- weco-0.2.7/examples/spaceship-titanic/evaluate.py +71 -0
- weco-0.2.7/examples/spaceship-titanic/optimize.py +27 -0
- weco-0.2.7/examples/spaceship-titanic/requirements-test.txt +8 -0
- weco-0.2.7/examples/spaceship-titanic/utils.py +56 -0
- weco-0.2.7/examples/triton/evaluate.py +153 -0
- weco-0.2.7/examples/triton/optimize.py +44 -0
- {weco-0.2.5 → weco-0.2.7}/pyproject.toml +2 -2
- {weco-0.2.5 → weco-0.2.7}/weco/__init__.py +1 -1
- {weco-0.2.5 → weco-0.2.7}/weco/cli.py +11 -3
- {weco-0.2.5 → weco-0.2.7}/weco/panels.py +16 -10
- {weco-0.2.5 → weco-0.2.7}/weco.egg-info/PKG-INFO +106 -15
- weco-0.2.7/weco.egg-info/SOURCES.txt +33 -0
- weco-0.2.5/examples/simple-mlx/optimize.py +0 -26
- weco-0.2.5/weco.egg-info/SOURCES.txt +0 -22
- {weco-0.2.5 → weco-0.2.7}/LICENSE +0 -0
- {weco-0.2.5/examples/simple-torch → weco-0.2.7/examples/hello-kernel-world}/optimize.py +0 -0
- {weco-0.2.5 → weco-0.2.7}/setup.cfg +0 -0
- {weco-0.2.5 → weco-0.2.7}/weco/api.py +0 -0
- {weco-0.2.5 → weco-0.2.7}/weco/utils.py +0 -0
- {weco-0.2.5 → weco-0.2.7}/weco.egg-info/dependency_links.txt +0 -0
- {weco-0.2.5 → weco-0.2.7}/weco.egg-info/entry_points.txt +0 -0
- {weco-0.2.5 → weco-0.2.7}/weco.egg-info/requires.txt +0 -0
- {weco-0.2.5 → weco-0.2.7}/weco.egg-info/top_level.txt +0 -0
|
@@ -5,6 +5,7 @@ on:
|
|
|
5
5
|
branches:
|
|
6
6
|
- main
|
|
7
7
|
- dev
|
|
8
|
+
pull_request: # Run on any pull request
|
|
8
9
|
|
|
9
10
|
jobs:
|
|
10
11
|
lint:
|
|
@@ -12,9 +13,7 @@ jobs:
|
|
|
12
13
|
|
|
13
14
|
steps:
|
|
14
15
|
- name: Checkout code
|
|
15
|
-
uses: actions/checkout@
|
|
16
|
-
with:
|
|
17
|
-
ref: ${{ github.head_ref }}
|
|
16
|
+
uses: actions/checkout@v4
|
|
18
17
|
|
|
19
18
|
- name: Set up Python
|
|
20
19
|
uses: actions/setup-python@v3
|
|
@@ -26,15 +25,19 @@ jobs:
|
|
|
26
25
|
python -m pip install --upgrade pip
|
|
27
26
|
pip install ruff
|
|
28
27
|
|
|
29
|
-
- name: Run
|
|
28
|
+
- name: Run Linter (PR Check)
|
|
29
|
+
if: github.event_name == 'pull_request'
|
|
30
30
|
run: |
|
|
31
|
-
ruff check .
|
|
32
|
-
|
|
33
|
-
- name: Run
|
|
31
|
+
ruff check .
|
|
32
|
+
|
|
33
|
+
- name: Run Linter & Formatter (Push)
|
|
34
|
+
if: github.event_name == 'push'
|
|
34
35
|
run: |
|
|
36
|
+
ruff check . --fix
|
|
35
37
|
ruff format .
|
|
36
38
|
|
|
37
39
|
- name: Commit changes
|
|
40
|
+
if: github.event_name == 'push'
|
|
38
41
|
run: |
|
|
39
42
|
git config --local user.email "action@github.com"
|
|
40
43
|
git config --local user.name "GitHub Action"
|
|
@@ -90,7 +90,7 @@ jobs:
|
|
|
90
90
|
GITHUB_TOKEN: ${{ github.token }}
|
|
91
91
|
run: >-
|
|
92
92
|
gh release create
|
|
93
|
-
'v0.2.
|
|
93
|
+
'v0.2.7'
|
|
94
94
|
--repo '${{ github.repository }}'
|
|
95
95
|
--notes ""
|
|
96
96
|
|
|
@@ -102,5 +102,5 @@ jobs:
|
|
|
102
102
|
# sigstore-produced signatures and certificates.
|
|
103
103
|
run: >-
|
|
104
104
|
gh release upload
|
|
105
|
-
'v0.2.
|
|
105
|
+
'v0.2.7' dist/**
|
|
106
106
|
--repo '${{ github.repository }}'
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: weco
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.7
|
|
4
4
|
Summary: Documentation for `weco`, a CLI for using Weco AI's code optimizer.
|
|
5
|
-
Author-email: Weco AI Team <
|
|
5
|
+
Author-email: Weco AI Team <contact@weco.ai>
|
|
6
6
|
License: MIT
|
|
7
7
|
Project-URL: Homepage, https://github.com/WecoAI/weco-cli
|
|
8
8
|
Keywords: AI,Code Optimization,Code Generation
|
|
@@ -99,32 +99,111 @@ Here's how `weco` can be applied to common ML engineering tasks:
|
|
|
99
99
|
|
|
100
100
|
### Examples
|
|
101
101
|
|
|
102
|
-
**Example 1: Optimizing PyTorch operations**
|
|
102
|
+
**Example 1: Optimizing PyTorch simple operations**
|
|
103
103
|
|
|
104
104
|
```bash
|
|
105
|
-
|
|
106
|
-
|
|
105
|
+
cd examples/hello-kernel-world
|
|
106
|
+
pip install torch
|
|
107
|
+
weco --source optimize.py \
|
|
108
|
+
--eval-command "python evaluate.py --solution-path optimize.py --device cpu" \
|
|
107
109
|
--metric speedup \
|
|
108
110
|
--maximize true \
|
|
109
111
|
--steps 15 \
|
|
110
|
-
--model
|
|
112
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
111
113
|
--additional-instructions "Fuse operations in the forward method while ensuring the max float deviation remains small. Maintain the same format of the code."
|
|
112
114
|
```
|
|
113
115
|
|
|
116
|
+
Note that if you have an NVIDIA gpu, change the device to `cuda`. If you are running this on Apple Silicon, set it to `mps`.
|
|
117
|
+
|
|
114
118
|
**Example 2: Optimizing MLX operations with instructions from a file**
|
|
115
119
|
|
|
116
|
-
Sometimes, additional context or instructions are too complex for a single command-line string. You can provide a path to a file containing these instructions.
|
|
120
|
+
Lets optimize a 2D convolution operation in [`mlx`](https://github.com/ml-explore/mlx) using [Metal](https://developer.apple.com/documentation/metal/). Sometimes, additional context or instructions are too complex for a single command-line string. You can provide a path to a file containing these instructions.
|
|
117
121
|
|
|
118
122
|
```bash
|
|
119
|
-
|
|
120
|
-
|
|
123
|
+
cd examples/metal
|
|
124
|
+
pip install mlx
|
|
125
|
+
weco --source optimize.py \
|
|
126
|
+
--eval-command "python evaluate.py --solution-path optimize.py" \
|
|
121
127
|
--metric speedup \
|
|
122
128
|
--maximize true \
|
|
123
129
|
--steps 30 \
|
|
124
|
-
--model
|
|
125
|
-
--additional-instructions examples
|
|
130
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
131
|
+
--additional-instructions examples.rst
|
|
126
132
|
```
|
|
127
133
|
|
|
134
|
+
**Example 3: Level Agnostic Optimization: Causal Self Attention with Triton & CUDA**
|
|
135
|
+
|
|
136
|
+
Given how useful causal multihead self attention is to transformers, we've seen its wide adoption across ML engineering and AI research. Its great to keep things at a high-level (in PyTorch) when doing research, but when moving to production you often need to write highly customized low-level kernels to make things run as fast as they can. The `weco` CLI can optimize kernels across a variety of different abstraction levels and frameworks. Example 2 uses Metal but lets explore two more frameworks:
|
|
137
|
+
|
|
138
|
+
1. [Triton](https://github.com/triton-lang/triton)
|
|
139
|
+
```bash
|
|
140
|
+
cd examples/triton
|
|
141
|
+
pip install torch triton
|
|
142
|
+
weco --source optimize.py \
|
|
143
|
+
--eval-command "python evaluate.py --solution-path optimize.py" \
|
|
144
|
+
--metric speedup \
|
|
145
|
+
--maximize true \
|
|
146
|
+
--steps 30 \
|
|
147
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
148
|
+
--additional-instructions "Use triton to optimize the code while ensuring a small max float diff. Maintain the same code format."
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
2. [CUDA](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html)
|
|
152
|
+
```bash
|
|
153
|
+
cd examples/cuda
|
|
154
|
+
pip install torch
|
|
155
|
+
weco --source optimize.py \
|
|
156
|
+
--eval-command "python evaluate.py --solution-path optimize.py" \
|
|
157
|
+
--metric speedup \
|
|
158
|
+
--maximize true \
|
|
159
|
+
--steps 30 \
|
|
160
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
161
|
+
--additional-instructions guide.md
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
**Example 4: Optimizing a Classification Model**
|
|
165
|
+
|
|
166
|
+
This example demonstrates optimizing a script for a Kaggle competition ([Spaceship Titanic](https://www.kaggle.com/competitions/spaceship-titanic/overview)) to improve classification accuracy. The additional instructions are provided via a separate file (`examples/spaceship-titanic/README.md`).
|
|
167
|
+
|
|
168
|
+
First, install the requirements for the example environment:
|
|
169
|
+
```bash
|
|
170
|
+
pip install -r examples/spaceship-titanic/requirements-test.txt
|
|
171
|
+
```
|
|
172
|
+
And run utility function once to prepare the dataset
|
|
173
|
+
```bash
|
|
174
|
+
python examples/spaceship-titanic/utils.py
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
You should see the following structure at `examples/spaceship-titanic`. You need to prepare the kaggle credentials for downloading the dataset.
|
|
178
|
+
```
|
|
179
|
+
.
|
|
180
|
+
├── baseline.py
|
|
181
|
+
├── evaluate.py
|
|
182
|
+
├── optimize.py
|
|
183
|
+
├── private
|
|
184
|
+
│ └── test.csv
|
|
185
|
+
├── public
|
|
186
|
+
│ ├── sample_submission.csv
|
|
187
|
+
│ ├── test.csv
|
|
188
|
+
│ └── train.csv
|
|
189
|
+
├── README.md
|
|
190
|
+
├── requirements-test.txt
|
|
191
|
+
└── utils.py
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Then, execute the optimization command:
|
|
195
|
+
```bash
|
|
196
|
+
weco --source examples/spaceship-titanic/optimize.py \
|
|
197
|
+
--eval-command "python examples/spaceship-titanic/optimize.py && python examples/spaceship-titanic/evaluate.py" \
|
|
198
|
+
--metric accuracy \
|
|
199
|
+
--maximize true \
|
|
200
|
+
--steps 10 \
|
|
201
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
202
|
+
--additional-instructions examples/spaceship-titanic/README.md
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
*The [baseline.py](examples/spaceship-titanic/baseline.py) is provided as a start point for optimization*
|
|
206
|
+
|
|
128
207
|
---
|
|
129
208
|
|
|
130
209
|
### Command Line Arguments
|
|
@@ -132,16 +211,28 @@ weco --source examples/simple-mlx/optimize.py \
|
|
|
132
211
|
| Argument | Description | Required |
|
|
133
212
|
| :-------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- |
|
|
134
213
|
| `--source` | Path to the source code file that will be optimized (e.g., `optimize.py`). | Yes |
|
|
135
|
-
| `--eval-command` | Command to run for evaluating the code in `--source`. This command should print the target `--metric` and its value to the terminal (stdout/stderr). See note below.
|
|
136
|
-
| `--metric` | The name of the metric you want to optimize (e.g., 'accuracy', 'speedup', 'loss'). This metric name should match what's printed by your `--eval-command`.
|
|
214
|
+
| `--eval-command` | Command to run for evaluating the code in `--source`. This command should print the target `--metric` and its value to the terminal (stdout/stderr). See note below. | Yes |
|
|
215
|
+
| `--metric` | The name of the metric you want to optimize (e.g., 'accuracy', 'speedup', 'loss'). This metric name should match what's printed by your `--eval-command`. | Yes |
|
|
137
216
|
| `--maximize` | Whether to maximize (`true`) or minimize (`false`) the metric. | Yes |
|
|
138
217
|
| `--steps` | Number of optimization steps (LLM iterations) to run. | Yes |
|
|
139
|
-
| `--model` | Model identifier for the LLM to use (e.g., `gpt-4o`, `claude-3.5-sonnet`). Recommended models to try include `o3-mini`, `claude-3-haiku`, and `gemini-2.5-pro-exp-03-25
|
|
140
|
-
| `--additional-instructions` | (Optional) Natural language description of specific instructions OR path to a file containing detailed instructions to guide the LLM.
|
|
218
|
+
| `--model` | Model identifier for the LLM to use (e.g., `gpt-4o`, `claude-3.5-sonnet`). Recommended models to try include `o3-mini`, `claude-3-haiku`, and `gemini-2.5-pro-exp-03-25`.| Yes |
|
|
219
|
+
| `--additional-instructions` | (Optional) Natural language description of specific instructions OR path to a file containing detailed instructions to guide the LLM. | No |
|
|
220
|
+
| `--log-dir` | (Optional) Path to the directory to log intermediate steps and final optimization result. Defaults to `.runs/`. | No |
|
|
141
221
|
|
|
142
222
|
---
|
|
143
223
|
|
|
224
|
+
### Performance & Expectations
|
|
225
|
+
|
|
226
|
+
Weco, powered by the AIDE algorithm, optimizes code iteratively based on your evaluation results. Achieving significant improvements, especially on complex research-level tasks, often requires substantial exploration time.
|
|
227
|
+
|
|
228
|
+
The following plot from the independent [Research Engineering Benchmark (RE-Bench)](https://metr.org/AI_R_D_Evaluation_Report.pdf) report shows the performance of AIDE (the algorithm behind Weco) on challenging ML research engineering tasks over different time budgets.
|
|
229
|
+
<p align="center">
|
|
230
|
+
<img src="https://github.com/user-attachments/assets/ff0e471d-2f50-4e2d-b718-874862f533df" alt="RE-Bench Performance Across Time" width="60%"/>
|
|
231
|
+
</p>
|
|
144
232
|
|
|
233
|
+
As shown, AIDE demonstrates strong performance gains over time, surpassing lower human expert percentiles within hours and continuing to improve. This highlights the potential of evaluation-driven optimization but also indicates that reaching high levels of performance comparable to human experts on difficult benchmarks can take considerable time (tens of hours in this specific benchmark, corresponding to many `--steps` in the Weco CLI). Factor this into your planning when setting the number of `--steps` for your optimization runs.
|
|
234
|
+
|
|
235
|
+
---
|
|
145
236
|
|
|
146
237
|
### Important Note on Evaluation
|
|
147
238
|
|
|
@@ -77,32 +77,111 @@ Here's how `weco` can be applied to common ML engineering tasks:
|
|
|
77
77
|
|
|
78
78
|
### Examples
|
|
79
79
|
|
|
80
|
-
**Example 1: Optimizing PyTorch operations**
|
|
80
|
+
**Example 1: Optimizing PyTorch simple operations**
|
|
81
81
|
|
|
82
82
|
```bash
|
|
83
|
-
|
|
84
|
-
|
|
83
|
+
cd examples/hello-kernel-world
|
|
84
|
+
pip install torch
|
|
85
|
+
weco --source optimize.py \
|
|
86
|
+
--eval-command "python evaluate.py --solution-path optimize.py --device cpu" \
|
|
85
87
|
--metric speedup \
|
|
86
88
|
--maximize true \
|
|
87
89
|
--steps 15 \
|
|
88
|
-
--model
|
|
90
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
89
91
|
--additional-instructions "Fuse operations in the forward method while ensuring the max float deviation remains small. Maintain the same format of the code."
|
|
90
92
|
```
|
|
91
93
|
|
|
94
|
+
Note that if you have an NVIDIA gpu, change the device to `cuda`. If you are running this on Apple Silicon, set it to `mps`.
|
|
95
|
+
|
|
92
96
|
**Example 2: Optimizing MLX operations with instructions from a file**
|
|
93
97
|
|
|
94
|
-
Sometimes, additional context or instructions are too complex for a single command-line string. You can provide a path to a file containing these instructions.
|
|
98
|
+
Lets optimize a 2D convolution operation in [`mlx`](https://github.com/ml-explore/mlx) using [Metal](https://developer.apple.com/documentation/metal/). Sometimes, additional context or instructions are too complex for a single command-line string. You can provide a path to a file containing these instructions.
|
|
95
99
|
|
|
96
100
|
```bash
|
|
97
|
-
|
|
98
|
-
|
|
101
|
+
cd examples/metal
|
|
102
|
+
pip install mlx
|
|
103
|
+
weco --source optimize.py \
|
|
104
|
+
--eval-command "python evaluate.py --solution-path optimize.py" \
|
|
99
105
|
--metric speedup \
|
|
100
106
|
--maximize true \
|
|
101
107
|
--steps 30 \
|
|
102
|
-
--model
|
|
103
|
-
--additional-instructions examples
|
|
108
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
109
|
+
--additional-instructions examples.rst
|
|
104
110
|
```
|
|
105
111
|
|
|
112
|
+
**Example 3: Level Agnostic Optimization: Causal Self Attention with Triton & CUDA**
|
|
113
|
+
|
|
114
|
+
Given how useful causal multihead self attention is to transformers, we've seen its wide adoption across ML engineering and AI research. Its great to keep things at a high-level (in PyTorch) when doing research, but when moving to production you often need to write highly customized low-level kernels to make things run as fast as they can. The `weco` CLI can optimize kernels across a variety of different abstraction levels and frameworks. Example 2 uses Metal but lets explore two more frameworks:
|
|
115
|
+
|
|
116
|
+
1. [Triton](https://github.com/triton-lang/triton)
|
|
117
|
+
```bash
|
|
118
|
+
cd examples/triton
|
|
119
|
+
pip install torch triton
|
|
120
|
+
weco --source optimize.py \
|
|
121
|
+
--eval-command "python evaluate.py --solution-path optimize.py" \
|
|
122
|
+
--metric speedup \
|
|
123
|
+
--maximize true \
|
|
124
|
+
--steps 30 \
|
|
125
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
126
|
+
--additional-instructions "Use triton to optimize the code while ensuring a small max float diff. Maintain the same code format."
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
2. [CUDA](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html)
|
|
130
|
+
```bash
|
|
131
|
+
cd examples/cuda
|
|
132
|
+
pip install torch
|
|
133
|
+
weco --source optimize.py \
|
|
134
|
+
--eval-command "python evaluate.py --solution-path optimize.py" \
|
|
135
|
+
--metric speedup \
|
|
136
|
+
--maximize true \
|
|
137
|
+
--steps 30 \
|
|
138
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
139
|
+
--additional-instructions guide.md
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
**Example 4: Optimizing a Classification Model**
|
|
143
|
+
|
|
144
|
+
This example demonstrates optimizing a script for a Kaggle competition ([Spaceship Titanic](https://www.kaggle.com/competitions/spaceship-titanic/overview)) to improve classification accuracy. The additional instructions are provided via a separate file (`examples/spaceship-titanic/README.md`).
|
|
145
|
+
|
|
146
|
+
First, install the requirements for the example environment:
|
|
147
|
+
```bash
|
|
148
|
+
pip install -r examples/spaceship-titanic/requirements-test.txt
|
|
149
|
+
```
|
|
150
|
+
And run utility function once to prepare the dataset
|
|
151
|
+
```bash
|
|
152
|
+
python examples/spaceship-titanic/utils.py
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
You should see the following structure at `examples/spaceship-titanic`. You need to prepare the kaggle credentials for downloading the dataset.
|
|
156
|
+
```
|
|
157
|
+
.
|
|
158
|
+
├── baseline.py
|
|
159
|
+
├── evaluate.py
|
|
160
|
+
├── optimize.py
|
|
161
|
+
├── private
|
|
162
|
+
│ └── test.csv
|
|
163
|
+
├── public
|
|
164
|
+
│ ├── sample_submission.csv
|
|
165
|
+
│ ├── test.csv
|
|
166
|
+
│ └── train.csv
|
|
167
|
+
├── README.md
|
|
168
|
+
├── requirements-test.txt
|
|
169
|
+
└── utils.py
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Then, execute the optimization command:
|
|
173
|
+
```bash
|
|
174
|
+
weco --source examples/spaceship-titanic/optimize.py \
|
|
175
|
+
--eval-command "python examples/spaceship-titanic/optimize.py && python examples/spaceship-titanic/evaluate.py" \
|
|
176
|
+
--metric accuracy \
|
|
177
|
+
--maximize true \
|
|
178
|
+
--steps 10 \
|
|
179
|
+
--model gemini-2.5-pro-exp-03-25 \
|
|
180
|
+
--additional-instructions examples/spaceship-titanic/README.md
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
*The [baseline.py](examples/spaceship-titanic/baseline.py) is provided as a start point for optimization*
|
|
184
|
+
|
|
106
185
|
---
|
|
107
186
|
|
|
108
187
|
### Command Line Arguments
|
|
@@ -110,16 +189,28 @@ weco --source examples/simple-mlx/optimize.py \
|
|
|
110
189
|
| Argument | Description | Required |
|
|
111
190
|
| :-------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- |
|
|
112
191
|
| `--source` | Path to the source code file that will be optimized (e.g., `optimize.py`). | Yes |
|
|
113
|
-
| `--eval-command` | Command to run for evaluating the code in `--source`. This command should print the target `--metric` and its value to the terminal (stdout/stderr). See note below.
|
|
114
|
-
| `--metric` | The name of the metric you want to optimize (e.g., 'accuracy', 'speedup', 'loss'). This metric name should match what's printed by your `--eval-command`.
|
|
192
|
+
| `--eval-command` | Command to run for evaluating the code in `--source`. This command should print the target `--metric` and its value to the terminal (stdout/stderr). See note below. | Yes |
|
|
193
|
+
| `--metric` | The name of the metric you want to optimize (e.g., 'accuracy', 'speedup', 'loss'). This metric name should match what's printed by your `--eval-command`. | Yes |
|
|
115
194
|
| `--maximize` | Whether to maximize (`true`) or minimize (`false`) the metric. | Yes |
|
|
116
195
|
| `--steps` | Number of optimization steps (LLM iterations) to run. | Yes |
|
|
117
|
-
| `--model` | Model identifier for the LLM to use (e.g., `gpt-4o`, `claude-3.5-sonnet`). Recommended models to try include `o3-mini`, `claude-3-haiku`, and `gemini-2.5-pro-exp-03-25
|
|
118
|
-
| `--additional-instructions` | (Optional) Natural language description of specific instructions OR path to a file containing detailed instructions to guide the LLM.
|
|
196
|
+
| `--model` | Model identifier for the LLM to use (e.g., `gpt-4o`, `claude-3.5-sonnet`). Recommended models to try include `o3-mini`, `claude-3-haiku`, and `gemini-2.5-pro-exp-03-25`.| Yes |
|
|
197
|
+
| `--additional-instructions` | (Optional) Natural language description of specific instructions OR path to a file containing detailed instructions to guide the LLM. | No |
|
|
198
|
+
| `--log-dir` | (Optional) Path to the directory to log intermediate steps and final optimization result. Defaults to `.runs/`. | No |
|
|
119
199
|
|
|
120
200
|
---
|
|
121
201
|
|
|
202
|
+
### Performance & Expectations
|
|
203
|
+
|
|
204
|
+
Weco, powered by the AIDE algorithm, optimizes code iteratively based on your evaluation results. Achieving significant improvements, especially on complex research-level tasks, often requires substantial exploration time.
|
|
205
|
+
|
|
206
|
+
The following plot from the independent [Research Engineering Benchmark (RE-Bench)](https://metr.org/AI_R_D_Evaluation_Report.pdf) report shows the performance of AIDE (the algorithm behind Weco) on challenging ML research engineering tasks over different time budgets.
|
|
207
|
+
<p align="center">
|
|
208
|
+
<img src="https://github.com/user-attachments/assets/ff0e471d-2f50-4e2d-b718-874862f533df" alt="RE-Bench Performance Across Time" width="60%"/>
|
|
209
|
+
</p>
|
|
122
210
|
|
|
211
|
+
As shown, AIDE demonstrates strong performance gains over time, surpassing lower human expert percentiles within hours and continuing to improve. This highlights the potential of evaluation-driven optimization but also indicates that reaching high levels of performance comparable to human experts on difficult benchmarks can take considerable time (tens of hours in this specific benchmark, corresponding to many `--steps` in the Weco CLI). Factor this into your planning when setting the number of `--steps` for your optimization runs.
|
|
212
|
+
|
|
213
|
+
---
|
|
123
214
|
|
|
124
215
|
### Important Note on Evaluation
|
|
125
216
|
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import sys
|
|
3
|
+
import os
|
|
4
|
+
import pathlib
|
|
5
|
+
import importlib
|
|
6
|
+
import traceback
|
|
7
|
+
import torch
|
|
8
|
+
import torch.nn as nn
|
|
9
|
+
import torch.nn.functional as F
|
|
10
|
+
import math
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
########################################################
|
|
14
|
+
# Baseline
|
|
15
|
+
########################################################
|
|
16
|
+
class Model(nn.Module):
|
|
17
|
+
"""
|
|
18
|
+
A vanilla multi-head masked self-attention layer with a projection at the end.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, n_embd, n_head, attn_pdrop, resid_pdrop, max_seqlen):
|
|
22
|
+
super().__init__()
|
|
23
|
+
assert n_embd % n_head == 0
|
|
24
|
+
# key, query, value projections for all heads, but in a batch
|
|
25
|
+
self.c_attn = nn.Linear(n_embd, 3 * n_embd)
|
|
26
|
+
# output projection
|
|
27
|
+
self.c_proj = nn.Linear(n_embd, n_embd)
|
|
28
|
+
# regularization
|
|
29
|
+
self.attn_dropout = nn.Dropout(attn_pdrop)
|
|
30
|
+
self.resid_dropout = nn.Dropout(resid_pdrop)
|
|
31
|
+
# causal mask to ensure that attention is only applied to the left in the input sequence
|
|
32
|
+
self.register_buffer("bias", torch.tril(torch.ones(max_seqlen, max_seqlen)).view(1, 1, max_seqlen, max_seqlen))
|
|
33
|
+
self.n_head = n_head
|
|
34
|
+
self.n_embd = n_embd
|
|
35
|
+
|
|
36
|
+
def forward(self, x):
|
|
37
|
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
|
38
|
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
|
39
|
+
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
|
40
|
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
|
41
|
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
|
42
|
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
|
43
|
+
|
|
44
|
+
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
|
|
45
|
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
|
46
|
+
att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float("-inf"))
|
|
47
|
+
att = F.softmax(att, dim=-1)
|
|
48
|
+
att = self.attn_dropout(att)
|
|
49
|
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
|
50
|
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
|
51
|
+
# output projection
|
|
52
|
+
y = self.resid_dropout(self.c_proj(y))
|
|
53
|
+
return y
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
########################################################
|
|
57
|
+
# Weco Solution
|
|
58
|
+
########################################################
|
|
59
|
+
def load_module_from_path(module_path: str, add_to_sys_modules: bool = False):
|
|
60
|
+
# Clean out all old compiled extensions to prevent namespace collisions during build
|
|
61
|
+
module_path = pathlib.Path(module_path)
|
|
62
|
+
name = module_path.stem
|
|
63
|
+
spec = importlib.util.spec_from_file_location(name, module_path)
|
|
64
|
+
mod = importlib.util.module_from_spec(spec) # type: ignore
|
|
65
|
+
if add_to_sys_modules:
|
|
66
|
+
sys.modules[name] = mod
|
|
67
|
+
spec.loader.exec_module(mod) # type: ignore
|
|
68
|
+
return mod
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
########################################################
|
|
72
|
+
# Benchmark
|
|
73
|
+
########################################################
|
|
74
|
+
os.environ["MAX_JOBS"] = "1" # number of workers for building with ninja
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def get_inputs(batch_size, seq_len, n_embd, device):
|
|
78
|
+
return torch.randn(batch_size, seq_len, n_embd, device=device, dtype=torch.float32)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def bench(f, inputs, n_warmup, n_rep):
|
|
82
|
+
with torch.no_grad():
|
|
83
|
+
# warmup
|
|
84
|
+
for _ in range(n_warmup):
|
|
85
|
+
f(inputs) # noqa
|
|
86
|
+
|
|
87
|
+
# benchmark
|
|
88
|
+
t_avg = 0.0
|
|
89
|
+
for _ in range(n_rep):
|
|
90
|
+
torch.cuda.empty_cache() # Clear cache before timing
|
|
91
|
+
start_time = time.time()
|
|
92
|
+
f(inputs)
|
|
93
|
+
torch.cuda.synchronize() # Wait for all computations to complete
|
|
94
|
+
t_avg += time.time() - start_time
|
|
95
|
+
t_avg /= n_rep * 1e-3
|
|
96
|
+
return t_avg
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
if __name__ == "__main__":
|
|
100
|
+
import argparse
|
|
101
|
+
|
|
102
|
+
parser = argparse.ArgumentParser()
|
|
103
|
+
parser.add_argument("--solution-path", type=str, required=True)
|
|
104
|
+
args = parser.parse_args()
|
|
105
|
+
|
|
106
|
+
# benchmarking parameters
|
|
107
|
+
n_correctness_trials = 10
|
|
108
|
+
n_warmup = 1000
|
|
109
|
+
n_rep = 5000
|
|
110
|
+
|
|
111
|
+
# init parameters
|
|
112
|
+
max_seqlen = 512
|
|
113
|
+
seq_len = 256
|
|
114
|
+
n_embd = 768
|
|
115
|
+
n_head = 8
|
|
116
|
+
# turn off dropout to measure correctness well
|
|
117
|
+
attn_pdrop = 0.0
|
|
118
|
+
resid_pdrop = 0.0
|
|
119
|
+
|
|
120
|
+
# input parameters
|
|
121
|
+
batch_size = 32
|
|
122
|
+
|
|
123
|
+
# load solution module
|
|
124
|
+
try:
|
|
125
|
+
torch.manual_seed(0)
|
|
126
|
+
solution_module = load_module_from_path(args.solution_path, add_to_sys_modules=False)
|
|
127
|
+
solution_model = solution_module.Model(
|
|
128
|
+
n_embd=n_embd, n_head=n_head, attn_pdrop=attn_pdrop, resid_pdrop=resid_pdrop, max_seqlen=max_seqlen
|
|
129
|
+
).to("cuda")
|
|
130
|
+
assert isinstance(solution_model, nn.Module)
|
|
131
|
+
except Exception:
|
|
132
|
+
print(f"Candidate module initialization failed: {traceback.format_exc()}")
|
|
133
|
+
exit(1)
|
|
134
|
+
|
|
135
|
+
torch.manual_seed(0)
|
|
136
|
+
baseline_model = Model(
|
|
137
|
+
n_embd=n_embd, n_head=n_head, attn_pdrop=attn_pdrop, resid_pdrop=resid_pdrop, max_seqlen=max_seqlen
|
|
138
|
+
).to("cuda")
|
|
139
|
+
|
|
140
|
+
# measure correctness
|
|
141
|
+
max_diff_avg = 0
|
|
142
|
+
for _ in range(n_correctness_trials):
|
|
143
|
+
inputs = get_inputs(batch_size=batch_size, seq_len=seq_len, n_embd=n_embd, device="cuda")
|
|
144
|
+
with torch.no_grad():
|
|
145
|
+
baseline_output = baseline_model(inputs)
|
|
146
|
+
optimized_output = solution_model(inputs)
|
|
147
|
+
max_diff_avg += torch.max(torch.abs(optimized_output - baseline_output))
|
|
148
|
+
max_diff_avg /= n_correctness_trials
|
|
149
|
+
print(f"max float diff between values of baseline and optimized model: {max_diff_avg}")
|
|
150
|
+
|
|
151
|
+
# measure performance
|
|
152
|
+
inputs = get_inputs(batch_size=batch_size, seq_len=seq_len, n_embd=n_embd, device="cuda")
|
|
153
|
+
t_avg_baseline = bench(baseline_model, inputs, n_warmup, n_rep)
|
|
154
|
+
print(f"baseline time: {t_avg_baseline:.2f}ms")
|
|
155
|
+
t_avg_optimized = bench(solution_model, inputs, n_warmup, n_rep)
|
|
156
|
+
print(f"optimized time: {t_avg_optimized:.2f}ms")
|
|
157
|
+
print(f"speedup: {t_avg_baseline / t_avg_optimized:.2f}x")
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# Writing In-line CUDA Kernels: 101
|
|
2
|
+
|
|
3
|
+
This document outlines the strategy to improve speedup by writing fused and optimized CUDA kernels using a single-file implementation.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- **Single-File Implementation:** Develop fused CUDA kernels within one file.
|
|
8
|
+
- **No Fallback Implementation:** Do not include any alternative or fallback code.
|
|
9
|
+
- **Simplicity & Readability:** Write simple, easy-to-understand code and include clear comments.
|
|
10
|
+
- **Avoid Templates:** Use plain fused kernel functions without templates.
|
|
11
|
+
- **Multiple Kernels Allowed:** You can define more than one kernel in the file if needed.
|
|
12
|
+
- **Model Class Requirement:** The solution must include a class `Model` (an instance of `nn.Module`), with the main computation in its `forward` method.
|
|
13
|
+
- **Preserve Initialization:** Do not change the initialization of the `Model` class.
|
|
14
|
+
- **Focus on Efficiency:** Concentrate solely on efficient PyTorch and CUDA coding without capturing logs.
|
|
15
|
+
- **Error Handling:** Any terminal output or errors will be reviewed by an LLM for feedback.
|
|
16
|
+
|
|
17
|
+
## GPU Hardware Specifications
|
|
18
|
+
|
|
19
|
+
Here are some details on the hardware you have access to.
|
|
20
|
+
|
|
21
|
+
```json
|
|
22
|
+
{
|
|
23
|
+
"GPU Architecture": "Ampere",
|
|
24
|
+
"GPU Memory": "40GB",
|
|
25
|
+
"Memory Bandwidth": "1935 GB/s",
|
|
26
|
+
"FP64 TFLOPS": "9.7",
|
|
27
|
+
"FP64 Tensor Core TFLOPS": "19.5",
|
|
28
|
+
"FP32 TFLOPS": "19.5",
|
|
29
|
+
"TF32 Tensor Core TFLOPS": "156 (312 with sparsity)",
|
|
30
|
+
"BFLOAT16 Tensore Core TFLOPS": "312 (624 with sparsity)",
|
|
31
|
+
"FP16 Tensor Core TFLOPS": "312 (624 with sparsity)",
|
|
32
|
+
"INT8 Tensor Core TOPS": "624 (1248 with sparsity)",
|
|
33
|
+
"Register File Size": "64K 32-bit registers per SM",
|
|
34
|
+
"Maximum number of registers per thread": "255",
|
|
35
|
+
"Maximum number of thread blocks per SM": "32",
|
|
36
|
+
"Shared memory capacity per SM": "164 KB",
|
|
37
|
+
"Maximum shared memory per thread block": "163 KB"
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Baseline Code
|
|
42
|
+
|
|
43
|
+
The baseline implementation of the `Model` class simply performs an element-wise addition.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import torch
|
|
47
|
+
import torch.nn as nn
|
|
48
|
+
import torch.nn.functional as F
|
|
49
|
+
|
|
50
|
+
class Model(nn.Module):
|
|
51
|
+
def __init__(self) -> None:
|
|
52
|
+
super().__init__()
|
|
53
|
+
|
|
54
|
+
def forward(self, a, b):
|
|
55
|
+
return a + b
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Optimized Code
|
|
59
|
+
|
|
60
|
+
The optimized version employs a custom CUDA kernel for fused element-wise addition. The kernel is defined and compiled inline using PyTorch's `load_inline`.
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import torch
|
|
64
|
+
import torch.nn as nn
|
|
65
|
+
import torch.nn.functional as F
|
|
66
|
+
from torch.utils.cpp_extension import load_inline
|
|
67
|
+
|
|
68
|
+
# Define the custom CUDA kernel for element-wise addition
|
|
69
|
+
elementwise_add_source = '''
|
|
70
|
+
#include <torch/extension.h>
|
|
71
|
+
#include <cuda_runtime.h>
|
|
72
|
+
|
|
73
|
+
// CUDA kernel for element-wise addition
|
|
74
|
+
__global__ void elementwise_add_kernel(const float* a, const float* b, float* out, int size) {
|
|
75
|
+
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
|
76
|
+
if (idx < size) {
|
|
77
|
+
out[idx] = a[idx] + b[idx];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Launch function for the CUDA kernel
|
|
82
|
+
torch::Tensor elementwise_add_cuda(torch::Tensor a, torch::Tensor b) {
|
|
83
|
+
auto size = a.numel();
|
|
84
|
+
auto out = torch::zeros_like(a);
|
|
85
|
+
const int block_size = 256;
|
|
86
|
+
const int num_blocks = (size + block_size - 1) / block_size;
|
|
87
|
+
elementwise_add_kernel<<<num_blocks, block_size>>>(a.data_ptr<float>(), b.data_ptr<float>(), out.data_ptr<float>(), size);
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
'''
|
|
91
|
+
|
|
92
|
+
# C++ function prototype declaration
|
|
93
|
+
elementwise_add_cpp_source = "torch::Tensor elementwise_add_cuda(torch::Tensor a, torch::Tensor b);"
|
|
94
|
+
|
|
95
|
+
# Compile the inline CUDA code for element-wise addition
|
|
96
|
+
elementwise_add = load_inline(
|
|
97
|
+
name="elementwise_add",
|
|
98
|
+
cpp_sources=elementwise_add_cpp_source,
|
|
99
|
+
cuda_sources=elementwise_add_source,
|
|
100
|
+
functions=["elementwise_add_cuda"],
|
|
101
|
+
verbose=True,
|
|
102
|
+
extra_cflags=[""],
|
|
103
|
+
extra_ldflags=[""],
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
class Model(nn.Module):
|
|
107
|
+
def __init__(self) -> None:
|
|
108
|
+
super().__init__()
|
|
109
|
+
self.elementwise_add = elementwise_add
|
|
110
|
+
|
|
111
|
+
def forward(self, a, b):
|
|
112
|
+
return self.elementwise_add.elementwise_add_cuda(a, b)
|
|
113
|
+
```
|