File size: 10,948 Bytes
5e4510c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# #!/usr/bin/env python3
# """
# Quick test script to verify MLIR syntax is correct.
# """

# import subprocess
# import tempfile
# from pathlib import Path

# def test_mlir_syntax():
#     """Test the corrected MLIR baseline syntax"""
    
#     baseline_mlir = '''
# #map_q = affine_map<(b, h, s1, s2, d) -> (b, h, s1, d)>
# #map_k = affine_map<(b, h, s1, s2, d) -> (b, h, s2, d)>
# #map_scores = affine_map<(b, h, s1, s2, d) -> (b, h, s1, s2)>
# #map_weights = affine_map<(b, h, s1, s2) -> (b, h, s1, s2)>
# #map_v = affine_map<(b, h, s1, s2, d) -> (b, h, s2, d)>
# #map_out = affine_map<(b, h, s1, s2, d) -> (b, h, s1, d)>

# module {
#   func.func @baseline_attention(
#       %query: tensor<1x8x128x64xf32>,
#       %key: tensor<1x8x128x64xf32>, 
#       %value: tensor<1x8x128x64xf32>
#   ) -> tensor<1x8x128x64xf32> {
    
#     %c0 = arith.constant 0.0 : f32
#     %cst_scale = arith.constant 0.125 : f32
    
#     // Initialize output tensors
#     %scores_init = tensor.empty() : tensor<1x8x128x128xf32>
#     %output_init = tensor.empty() : tensor<1x8x128x64xf32>
    
#     // Compute Q @ K^T (scaled dot-product attention)
#     %attention_scores = linalg.generic {
#       indexing_maps = [#map_q, #map_k, #map_scores],
#       iterator_types = ["parallel", "parallel", "parallel", "parallel", "reduction"]
#     } ins(%query, %key : tensor<1x8x128x64xf32>, tensor<1x8x128x64xf32>) 
#       outs(%scores_init : tensor<1x8x128x128xf32>) {
#     ^bb0(%q: f32, %k: f32, %acc: f32):
#       %prod = arith.mulf %q, %k : f32
#       %scaled = arith.mulf %prod, %cst_scale : f32
#       %sum = arith.addf %acc, %scaled : f32
#       linalg.yield %sum : f32
#     } -> tensor<1x8x128x128xf32>
    
#     // Apply attention weights to values  
#     %attention_output = linalg.generic {
#       indexing_maps = [#map_weights, #map_v, #map_out],
#       iterator_types = ["parallel", "parallel", "parallel", "reduction", "parallel"]
#     } ins(%attention_scores, %value : tensor<1x8x128x128xf32>, tensor<1x8x128x64xf32>) 
#       outs(%output_init : tensor<1x8x128x64xf32>) {
#     ^bb0(%weight: f32, %v: f32, %acc: f32):
#       %weighted = arith.mulf %weight, %v : f32
#       %sum = arith.addf %acc, %weighted : f32
#       linalg.yield %sum : f32
#     } -> tensor<1x8x128x64xf32>
    
#     return %attention_output : tensor<1x8x128x64xf32>
#   }
# }
# '''
    
#     try:
#         # Write MLIR to temporary file
#         with tempfile.NamedTemporaryFile(mode='w', suffix='.mlir', delete=False) as f:
#             f.write(baseline_mlir)
#             temp_file = f.name
        
#         print("πŸ”§ Testing MLIR baseline syntax...")
        
#         # Test basic parsing
#         result = subprocess.run([
#             "mlir-opt", temp_file
#         ], capture_output=True, text=True, timeout=30)
        
#         Path(temp_file).unlink()  # Clean up
        
#         if result.returncode == 0:
#             print("βœ… MLIR baseline syntax is correct!")
#             return True
#         else:
#             print(f"❌ MLIR syntax error: {result.stderr}")
#             return False
            
#     except Exception as e:
#         print(f"❌ Test error: {e}")
#         return False

# def test_tiling_pass():
#     """Test the linalg tiling pass syntax"""
    
#     simple_linalg = '''
# #map = affine_map<(d0, d1) -> (d0, d1)>
# module {
#   func.func @simple_add(%arg0: tensor<128x64xf32>, %arg1: tensor<128x64xf32>) -> tensor<128x64xf32> {
#     %0 = tensor.empty() : tensor<128x64xf32>
#     %1 = linalg.generic {
#       indexing_maps = [#map, #map, #map],
#       iterator_types = ["parallel", "parallel"]
#     } ins(%arg0, %arg1 : tensor<128x64xf32>, tensor<128x64xf32>) 
#       outs(%0 : tensor<128x64xf32>) {
#     ^bb0(%in: f32, %in_1: f32, %out: f32):
#       %2 = arith.addf %in, %in_1 : f32
#       linalg.yield %2 : f32
#     } -> tensor<128x64xf32>
#     return %1 : tensor<128x64xf32>
#   }
# }
# '''
    
#     try:
#         # Write MLIR to temporary file
#         with tempfile.NamedTemporaryFile(mode='w', suffix='.mlir', delete=False) as f:
#             f.write(simple_linalg)
#             temp_file = f.name
        
#         print("\nπŸ”§ Testing linalg tiling pass...")
        
#         # Test tiling with our syntax
#         pipeline = "builtin.module(linalg-tile{linalg-tile-sizes=32,32},canonicalize,cse)"
#         result = subprocess.run([
#             "mlir-opt", temp_file, f"--pass-pipeline={pipeline}"
#         ], capture_output=True, text=True, timeout=30)
        
#         Path(temp_file).unlink()  # Clean up
        
#         if result.returncode == 0:
#             print("βœ… Linalg tiling pass works!")
#             print("Sample output:")
#             print(result.stdout[:500] + "..." if len(result.stdout) > 500 else result.stdout)
#             return True
#         else:
#             print(f"❌ Tiling pass error: {result.stderr}")
#             return False
            
#     except Exception as e:
#         print(f"❌ Test error: {e}")
#         return False

# if __name__ == "__main__":
#     print("πŸš€ Testing MLIR Syntax Corrections\n")
    
#     success1 = test_mlir_syntax()
#     success2 = test_tiling_pass()
    
#     if success1 and success2:
#         print("\nπŸŽ‰ All MLIR syntax tests passed!")
#         print("βœ… Ready to run AlphaEvolve evolution")
#     else:
#         print("\n⚠️ Some tests failed. Check MLIR installation.")
        
#     print("\nπŸ“‹ If tests passed, run:")
#     print("python openevolve-run.py fixed_initial_program.py fixed_evaluator.py --iterations 10")


#!/usr/bin/env python3
"""
Quick test script to verify MLIR syntax is correct.
"""

import subprocess
import tempfile
from pathlib import Path

def test_mlir_syntax():
    """Test the corrected MLIR baseline syntax"""
    
    baseline_mlir = '''
#map_q = affine_map<(b, h, s1, s2, d) -> (b, h, s1, d)>
#map_k = affine_map<(b, h, s1, s2, d) -> (b, h, s2, d)>
#map_scores = affine_map<(b, h, s1, s2, d) -> (b, h, s1, s2)>
#map_weights = affine_map<(b, h, s1, s2) -> (b, h, s1, s2)>
#map_v = affine_map<(b, h, s1, s2, d) -> (b, h, s2, d)>
#map_out = affine_map<(b, h, s1, s2, d) -> (b, h, s1, d)>

module {
  func.func @baseline_attention(
      %query: tensor<1x8x128x64xf32>,
      %key: tensor<1x8x128x64xf32>, 
      %value: tensor<1x8x128x64xf32>
  ) -> tensor<1x8x128x64xf32> {
    
    %c0 = arith.constant 0.0 : f32
    %cst_scale = arith.constant 0.125 : f32
    
    // Initialize output tensors
    %scores_init = tensor.empty() : tensor<1x8x128x128xf32>
    %output_init = tensor.empty() : tensor<1x8x128x64xf32>
    
    // Compute Q @ K^T (scaled dot-product attention)
    %attention_scores = linalg.generic {
      indexing_maps = [#map_q, #map_k, #map_scores],
      iterator_types = ["parallel", "parallel", "parallel", "parallel", "reduction"]
    } ins(%query, %key : tensor<1x8x128x64xf32>, tensor<1x8x128x64xf32>) 
      outs(%scores_init : tensor<1x8x128x128xf32>) {
    ^bb0(%q: f32, %k: f32, %acc: f32):
      %prod = arith.mulf %q, %k : f32
      %scaled = arith.mulf %prod, %cst_scale : f32
      %sum = arith.addf %acc, %scaled : f32
      linalg.yield %sum : f32
    } -> tensor<1x8x128x128xf32>
    
    // Apply attention weights to values  
    %attention_output = linalg.generic {
      indexing_maps = [#map_weights, #map_v, #map_out],
      iterator_types = ["parallel", "parallel", "parallel", "reduction", "parallel"]
    } ins(%attention_scores, %value : tensor<1x8x128x128xf32>, tensor<1x8x128x64xf32>) 
      outs(%output_init : tensor<1x8x128x64xf32>) {
    ^bb0(%weight: f32, %v: f32, %acc: f32):
      %weighted = arith.mulf %weight, %v : f32
      %sum = arith.addf %acc, %weighted : f32
      linalg.yield %sum : f32
    } -> tensor<1x8x128x64xf32>
    
    return %attention_output : tensor<1x8x128x64xf32>
  }
}
'''
    
    try:
        # Write MLIR to temporary file
        with tempfile.NamedTemporaryFile(mode='w', suffix='.mlir', delete=False) as f:
            f.write(baseline_mlir)
            temp_file = f.name
        
        print("πŸ”§ Testing MLIR baseline syntax...")
        
        # Test basic parsing
        result = subprocess.run([
            "mlir-opt", temp_file
        ], capture_output=True, text=True, timeout=30)
        
        Path(temp_file).unlink()  # Clean up
        
        if result.returncode == 0:
            print("βœ… MLIR baseline syntax is correct!")
            return True
        else:
            print(f"❌ MLIR syntax error: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ Test error: {e}")
        return False

def test_tiling_pass():
    """Test the linalg tiling pass syntax"""
    
    simple_linalg = '''
#map = affine_map<(d0, d1) -> (d0, d1)>
module {
  func.func @simple_add(%arg0: tensor<128x64xf32>, %arg1: tensor<128x64xf32>) -> tensor<128x64xf32> {
    %0 = tensor.empty() : tensor<128x64xf32>
    %1 = linalg.generic {
      indexing_maps = [#map, #map, #map],
      iterator_types = ["parallel", "parallel"]
    } ins(%arg0, %arg1 : tensor<128x64xf32>, tensor<128x64xf32>) 
      outs(%0 : tensor<128x64xf32>) {
    ^bb0(%in: f32, %in_1: f32, %out: f32):
      %2 = arith.addf %in, %in_1 : f32
      linalg.yield %2 : f32
    } -> tensor<128x64xf32>
    return %1 : tensor<128x64xf32>
  }
}
'''
    
    try:
        # Write MLIR to temporary file
        with tempfile.NamedTemporaryFile(mode='w', suffix='.mlir', delete=False) as f:
            f.write(simple_linalg)
            temp_file = f.name
        
        print("\nπŸ”§ Testing linalg tiling pass...")
        
        # Test tiling with our syntax
        pipeline = "builtin.module(linalg-tile,canonicalize,cse)"
        result = subprocess.run([
            "mlir-opt", temp_file, f"--pass-pipeline={pipeline}"
        ], capture_output=True, text=True, timeout=30)
        
        Path(temp_file).unlink()  # Clean up
        
        if result.returncode == 0:
            print("βœ… Linalg tiling pass works!")
            print("Sample output:")
            print(result.stdout[:500] + "..." if len(result.stdout) > 500 else result.stdout)
            return True
        else:
            print(f"❌ Tiling pass error: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ Test error: {e}")
        return False

if __name__ == "__main__":
    print("πŸš€ Testing MLIR Syntax Corrections\n")
    
    success1 = test_mlir_syntax()
    success2 = test_tiling_pass()
    
    if success1 and success2:
        print("\nπŸŽ‰ All MLIR syntax tests passed!")
        print("βœ… Ready to run AlphaEvolve evolution")
    else:
        print("\n⚠️ Some tests failed. Check MLIR installation.")
        
    print("\nπŸ“‹ If tests passed, run:")
    print("python openevolve-run.py fixed_initial_program.py fixed_evaluator.py --iterations 10")