cutile 0.0.2

cuTile Rust lets programmers safely author and execute tile kernels directly in Rust.
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
 * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
use cutile;
use cutile::{api::*, tensor::*, tile_kernel::*};
use cutile_compiler::compiler::utils::CompileOptions;
use cutile_compiler::compiler::{CUDATileFunctionCompiler, CUDATileModules};
use cutile_compiler::cuda_tile_runtime_utils::get_gpu_name;
use half::bf16;
use std::sync::Arc;

mod common;

#[cutile::module]
mod type_conversion_ops_module {

    use cutile::core::*;

    #[cutile::entry()]
    fn conversion_ops_kernel<const S: [i32; 1]>(output: &mut Tensor<i64, S>) {
        // Test integer conversion operations
        let x: Tile<i64, S> = load_tile_mut(output);
        // Truncate to i32, then extend back to i64
        let truncated: Tile<i32, S> = trunci(x, overflow::None);
        let extended: Tile<i64, S> = exti(truncated);
        output.store(extended);
    }

    #[cutile::entry()]
    fn ptr_conversion_kernel<const S: [i32; 1]>(output: &mut Tensor<i64, S>) {
        // Test pointer conversion operations
        let x: Tile<i64, S> = load_tile_mut(output);
        // Convert to pointer, cast pointer type, convert back to int
        let ptrs: PointerTile<*mut i64, S> = int_to_ptr(x);
        let ptrs_f32: PointerTile<*mut f32, S> = ptr_to_ptr(ptrs);
        let ptrs_back: PointerTile<*mut i64, S> = ptr_to_ptr(ptrs_f32);
        let ints: Tile<i64, S> = ptr_to_int(ptrs_back);
        output.store(ints);
    }

    #[cutile::entry()]
    fn exti_unsigned_kernel<const S: [i32; 1]>(output: &mut Tensor<i64, S>) {
        // Test integer extension with unsigned types (zero extension)
        // Note: Using i64 tensor but operating on u32 tiles to test unsigned extension
        let x: Tile<i64, S> = load_tile_mut(output);
        // Truncate to u32, then extend back to i64 with unsigned (zero extension)
        let truncated: Tile<u32, S> = trunci(x, overflow::None);
        let extended: Tile<i64, S> = exti(truncated);
        output.store(extended);
    }

    #[cutile::entry()]
    fn bf16_conversion_kernel<const S: [i32; 1]>(output: &mut Tensor<bf16, S>) {
        // Exercises bf16 <-> f32 tile conversion lowering
        let x: Tile<bf16, S> = load_tile_mut(output);
        let upcast: Tile<f32, S> = convert_tile(x);
        let downcast: Tile<bf16, S> = convert_tile(upcast);
        output.store(downcast);
    }

    #[cutile::entry()]
    fn bf16_to_f32_conversion_kernel<const S: [i32; 1]>(
        output: &mut Tensor<f32, S>,
        input: &Tensor<bf16, { [-1] }>,
    ) {
        // Runtime test kernel for bf16 -> f32 tile conversion
        let x: Tile<bf16, S> = load_tile_like(input, output);
        let y: Tile<f32, S> = convert_tile(x);
        output.store(y);
    }

    #[cutile::entry()]
    fn f32_to_bf16_conversion_kernel<const S: [i32; 1]>(
        output: &mut Tensor<bf16, S>,
        input: &Tensor<f32, { [-1] }>,
    ) {
        // Runtime test kernel for f32 -> bf16 tile conversion
        let x: Tile<f32, S> = load_tile_like(input, output);
        let y: Tile<bf16, S> = convert_tile(x);
        output.store(y);
    }

    #[cutile::entry()]
    fn unannotated_load_tile_like_kernel<const S: [i32; 1]>(
        output: &mut Tensor<f32, S>,
        input: &Tensor<f32, { [-1] }>,
    ) {
        let x = load_tile_like(input, output);
        output.store(x);
    }

    #[cutile::entry()]
    fn explicit_conversion_ops_kernel<const S: [i32; 1]>(output: &mut Tensor<f32, S>) {
        let x: Tile<f32, S> = load_tile_mut(output);
        let narrowed: Tile<f16, S> = ftof(x, rounding::NearestEven);
        let widened: Tile<f32, S> = ftof(narrowed, rounding::NearestEven);
        let ints: Tile<i32, S> = ftoi(widened, rounding::Zero);
        let floats: Tile<f32, S> = itof(ints, rounding::NearestEven);
        output.store(floats);
    }
}

use type_conversion_ops_module::__module_ast_self;
use type_conversion_ops_module::bf16_conversion_kernel;
use type_conversion_ops_module::bf16_to_f32_conversion_kernel;
use type_conversion_ops_module::f32_to_bf16_conversion_kernel;

#[test]
fn compile_conversion_ops() -> () {
    common::with_test_stack(|| {
        let modules = CUDATileModules::from_kernel(__module_ast_self())
            .expect("Failed to create CUDATileModules");
        let gpu_name = get_gpu_name(0);
        let compiler = CUDATileFunctionCompiler::new(
            &modules,
            "type_conversion_ops_module",
            "conversion_ops_kernel",
            &[128.to_string()],
            &[("output", &[1])],
            &[],
            &[],
            None,
            gpu_name,
            &CompileOptions::default(),
        )
        .expect("Failed.");
        let module_op_str = compiler.compile().expect("Failed.").to_string();
        println!("\n=== CONVERSION OPS MLIR ===\n{}", module_op_str);

        assert!(
            module_op_str.contains("= trunci"),
            "Expected trunci operation in MLIR output"
        );
        assert!(
            module_op_str.contains("= exti"),
            "Expected exti operation in MLIR output"
        );
        assert!(
            module_op_str.contains("signed"),
            "Expected signedness attribute in exti operation"
        );

        println!("\n✓ trunci and exti operations verified in MLIR output");
    });
}

#[test]
fn compile_ptr_conversion() -> () {
    common::with_test_stack(|| {
        let modules = CUDATileModules::from_kernel(__module_ast_self())
            .expect("Failed to create CUDATileModules");
        let gpu_name = get_gpu_name(0);
        let compiler = CUDATileFunctionCompiler::new(
            &modules,
            "type_conversion_ops_module",
            "ptr_conversion_kernel",
            &[128.to_string()],
            &[("output", &[1])],
            &[],
            &[],
            None,
            gpu_name,
            &CompileOptions::default(),
        )
        .expect("Failed.");
        let module_op_str = compiler.compile().expect("Failed.").to_string();
        println!("\n=== PTR CONVERSION MLIR ===\n{}", module_op_str);

        assert!(
            module_op_str.contains("= int_to_ptr"),
            "Expected int_to_ptr operation in MLIR output"
        );
        assert!(
            module_op_str.contains("= ptr_to_ptr"),
            "Expected ptr_to_ptr operation in MLIR output"
        );
        assert!(
            module_op_str.contains("= ptr_to_int"),
            "Expected ptr_to_int operation in MLIR output"
        );

        println!("\n✓ Pointer conversion operations verified in MLIR output");
    });
}

#[test]
fn compile_exti_unsigned() -> () {
    common::with_test_stack(|| {
        let modules = CUDATileModules::from_kernel(__module_ast_self())
            .expect("Failed to create CUDATileModules");
        let gpu_name = get_gpu_name(0);
        let compiler = CUDATileFunctionCompiler::new(
            &modules,
            "type_conversion_ops_module",
            "exti_unsigned_kernel",
            &[128.to_string()],
            &[("output", &[1])],
            &[],
            &[],
            None,
            gpu_name,
            &CompileOptions::default(),
        )
        .expect("Failed.");
        let module_op_str = compiler.compile().expect("Failed.").to_string();
        println!("\n=== EXTI UNSIGNED MLIR ===\n{}", module_op_str);

        assert!(
            module_op_str.contains("= exti"),
            "Expected exti operation in MLIR output"
        );
        assert!(
            module_op_str.contains("unsigned"),
            "Expected unsigned signedness attribute (zero extension)"
        );

        println!("\n✓ exti with unsigned types (zero extension) verified in MLIR output");
    });
}

#[test]
fn compile_bf16_conversion() -> () {
    common::with_test_stack(|| {
        let modules = CUDATileModules::from_kernel(__module_ast_self())
            .expect("Failed to create CUDATileModules");
        let gpu_name = get_gpu_name(0);
        let compiler = CUDATileFunctionCompiler::new(
            &modules,
            "type_conversion_ops_module",
            "bf16_conversion_kernel",
            &[128.to_string()],
            &[("output", &[1])],
            &[],
            &[],
            None,
            gpu_name,
            &CompileOptions::default(),
        )
        .expect("Failed.");
        let module_op_str = compiler.compile().expect("Failed.").to_string();
        println!("\n=== BF16 CONVERSION MLIR ===\n{}", module_op_str);

        assert!(
            module_op_str.contains("= ftof"),
            "Expected floating-point conversion operation in MLIR output"
        );
        assert!(
            module_op_str.contains("bf16"),
            "Expected bf16 type in MLIR output"
        );
    });
}

#[test]
fn compile_bf16_to_f32_load_tile_like() -> () {
    common::with_test_stack(|| {
        let modules = CUDATileModules::from_kernel(__module_ast_self())
            .expect("Failed to create CUDATileModules");
        let gpu_name = "sm_120".to_string();
        let compiler = CUDATileFunctionCompiler::new(
            &modules,
            "type_conversion_ops_module",
            "bf16_to_f32_conversion_kernel",
            &[128.to_string()],
            &[("output", &[1]), ("input", &[1])],
            &[],
            &[],
            None,
            gpu_name,
            &CompileOptions::default(),
        )
        .expect("Failed.");
        let module_op_str = compiler.compile().expect("Failed.").to_string();
        println!(
            "\n=== BF16 -> F32 LOAD TILE LIKE MLIR ===\n{}",
            module_op_str
        );

        assert!(
            module_op_str.contains("load_view_tko"),
            "Expected load_view_tko operation in MLIR output"
        );
        assert!(
            module_op_str.contains("tile<128xbf16>"),
            "Expected source tile type in MLIR output"
        );
        assert!(
            module_op_str.contains("tile<128xf32>"),
            "Expected converted tile type in MLIR output"
        );
    });
}

#[test]
fn compile_unannotated_load_tile_like() -> () {
    common::with_test_stack(|| {
        let modules = CUDATileModules::from_kernel(__module_ast_self())
            .expect("Failed to create CUDATileModules");
        let gpu_name = "sm_120".to_string();
        let compiler = CUDATileFunctionCompiler::new(
            &modules,
            "type_conversion_ops_module",
            "unannotated_load_tile_like_kernel",
            &[128.to_string()],
            &[("output", &[1]), ("input", &[1])],
            &[],
            &[],
            None,
            gpu_name,
            &CompileOptions::default(),
        )
        .expect("Failed.");
        let module_op_str = compiler.compile().expect("Failed.").to_string();
        println!(
            "\n=== UNANNOTATED LOAD TILE LIKE MLIR ===\n{}",
            module_op_str
        );

        assert!(
            module_op_str.contains("load_view_tko"),
            "Expected load_view_tko operation in MLIR output"
        );
        assert!(
            module_op_str.contains("tile<128xf32>"),
            "Expected statically shaped tile type in MLIR output"
        );
        assert!(
            !module_op_str.contains("-9223372036854775808"),
            "Did not expect dynamic-shape sentinel in load_tile_like result"
        );
    });
}

#[test]
fn compile_explicit_conversion_ops() -> () {
    common::with_test_stack(|| {
        let modules = CUDATileModules::from_kernel(__module_ast_self())
            .expect("Failed to create CUDATileModules");
        let gpu_name = get_gpu_name(0);
        let compiler = CUDATileFunctionCompiler::new(
            &modules,
            "type_conversion_ops_module",
            "explicit_conversion_ops_kernel",
            &[128.to_string()],
            &[("output", &[1])],
            &[],
            &[],
            None,
            gpu_name,
            &CompileOptions::default(),
        )
        .expect("Failed.");
        let module_op_str = compiler.compile().expect("Failed.").to_string();
        println!("\n=== EXPLICIT CONVERSION OPS MLIR ===\n{}", module_op_str);

        assert!(
            module_op_str.matches("= ftof").count() >= 2,
            "Expected two ftof operations in MLIR output"
        );
        assert!(
            module_op_str.contains("= ftoi"),
            "Expected ftoi operation in MLIR output"
        );
        assert!(
            module_op_str.contains("= itof"),
            "Expected itof operation in MLIR output"
        );
    });
}

#[test]
fn execute_bf16_f32_roundtrip() -> () {
    common::with_test_stack(|| {
        let input_host = Arc::new(vec![
            bf16::from_f32(-3.5),
            bf16::from_f32(-1.0),
            bf16::from_f32(-0.0),
            bf16::from_f32(0.0),
            bf16::from_f32(0.125),
            bf16::from_f32(0.1),
            bf16::from_f32(1.1),
            bf16::from_f32(42.0),
        ]);

        let input: Tensor<bf16> = copy_host_vec_to_device(&input_host)
            .sync()
            .expect("Failed.");
        let (result,) = bf16_conversion_kernel(input.partition([4]))
            .sync()
            .expect("Failed.");

        let result_host: Vec<bf16> = result.unpartition().to_host_vec().sync().expect("Failed.");

        // This kernel performs bf16 -> f32 -> bf16, so bf16 bit patterns should round-trip.
        assert_eq!(
            result_host, *input_host,
            "Expected bf16 values to round-trip through f32 conversion"
        );
    });
}

#[test]
fn execute_bf16_to_f32_conversion() -> () {
    common::with_test_stack(|| {
        let input_host = Arc::new(vec![
            bf16::from_f32(-3.5),
            bf16::from_f32(-1.0),
            bf16::from_f32(-0.0),
            bf16::from_f32(0.0),
            bf16::from_f32(0.125),
            bf16::from_f32(0.1),
            bf16::from_f32(1.1),
            bf16::from_f32(42.0),
        ]);

        let input: Tensor<bf16> = copy_host_vec_to_device(&input_host)
            .sync()
            .expect("Failed.");
        let input = Arc::new(input);
        let output: Tensor<f32> = zeros(&[input_host.len()]).sync().expect("Failed.");

        let (result, _) = bf16_to_f32_conversion_kernel(output.partition([4]), input)
            .sync()
            .expect("Failed.");

        let result_host: Vec<f32> = result.unpartition().to_host_vec().sync().expect("Failed.");
        let expected: Vec<f32> = input_host.iter().map(|x| x.to_f32()).collect();

        assert_eq!(
            result_host, expected,
            "Expected bf16->f32 conversion output to match host-side bf16::to_f32"
        );
    });
}

#[test]
fn execute_f32_to_bf16_conversion() -> () {
    common::with_test_stack(|| {
        let input_host = Arc::new(vec![-3.5f32, -1.0, -0.0, 0.0, 0.125, 0.1, 1.1, 42.0]);

        let input: Tensor<f32> = copy_host_vec_to_device(&input_host)
            .sync()
            .expect("Failed.");
        let input = Arc::new(input);
        let output: Tensor<bf16> = zeros(&[input_host.len()]).sync().expect("Failed.");

        let (result, _) = f32_to_bf16_conversion_kernel(output.partition([4]), input)
            .sync()
            .expect("Failed.");

        let result_host: Vec<bf16> = result.unpartition().to_host_vec().sync().expect("Failed.");
        let expected: Vec<bf16> = input_host.iter().map(|x| bf16::from_f32(*x)).collect();

        assert_eq!(
            result_host, expected,
            "Expected f32->bf16 conversion output to match host-side bf16::from_f32"
        );
    });
}