• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daisytuner / docc / 28760075767

06 Jul 2026 12:22AM UTC coverage: 62.801% (+0.3%) from 62.469%
28760075767

Pull #835

github

web-flow
Merge 90ef94753 into 6cd06aaae
Pull Request #835: [Python] Extends frontend support and adds pylulesh benchmarks

704 of 800 new or added lines in 5 files covered. (88.0%)

4 existing lines in 1 file now uncovered.

40479 of 64456 relevant lines covered (62.8%)

968.2 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.51
/python/docc/python/python_program.py
1
import inspect
4✔
2
import shutil
4✔
3
import textwrap
4✔
4
import ast
4✔
5
import os
4✔
6
import getpass
4✔
7
import hashlib
4✔
8
import ml_dtypes
4✔
9
import numpy as np
4✔
10
from typing import Annotated, get_origin, get_args, Any, Optional
4✔
11

12
from docc.sdfg import (
4✔
13
    Scalar,
14
    PrimitiveType,
15
    Pointer,
16
    Structure,
17
    Array,
18
    Type,
19
    Tensor,
20
    StructuredSDFG,
21
    StructuredSDFGBuilder,
22
)
23
from docc.compiler.docc_program import DoccProgram
4✔
24
from docc.compiler.compiled_sdfg import CompiledSDFG
4✔
25
from docc.python.ast_parser import ASTParser
4✔
26
from docc.python.types import element_type_from_sdfg_type
4✔
27

28

29
def _compile_wrapper(self, output_folder=None):
4✔
30
    """Wrapper to allow StructuredSDFG.compile() to return a CompiledSDFG."""
31
    lib_path = self._compile(output_folder)
×
32
    return CompiledSDFG(lib_path, self)
×
33

34

35
# Monkey-patch StructuredSDFG to add compile method
36
StructuredSDFG.compile = _compile_wrapper
4✔
37

38

39
def _map_python_type(dtype):
4✔
40
    """Map Python/numpy types to SDFG types."""
41
    # If it is already a sdfg Type, return it
42
    if isinstance(dtype, Type):
4✔
43
        return dtype
×
44

45
    # Handle Annotated for Arrays
46
    if get_origin(dtype) is Annotated:
4✔
47
        args = get_args(dtype)
×
48
        base_type = args[0]
×
49
        metadata = args[1:]
×
50

51
        if base_type is np.ndarray:
×
52
            # Convention: Annotated[np.ndarray, shape, dtype]
53
            shape = metadata[0]
×
54
            elem_type = Scalar(PrimitiveType.Double)  # Default
×
55

56
            if len(metadata) > 1:
×
57
                possible_dtype = metadata[1]
×
58
                elem_type = _map_python_type(possible_dtype)
×
59

60
            return Pointer(elem_type)
×
61

62
    # Handle numpy.ndarray[Shape, DType]
63
    if get_origin(dtype) is np.ndarray:
4✔
64
        args = get_args(dtype)
×
65
        # args[0] is shape, args[1] is dtype
66
        if len(args) >= 2:
×
67
            elem_type = _map_python_type(args[1])
×
68
            return Pointer(elem_type)
×
69

70
    # Handle a parametrized numpy dtype generic, e.g. numpy.dtype[numpy.float64]
71
    # (produced by npt.NDArray[RealT] -> ndarray[Any, dtype[float64]]).
72
    if get_origin(dtype) is np.dtype:
4✔
NEW
73
        inner = get_args(dtype)
×
NEW
74
        if inner:
×
NEW
75
            return _map_python_type(inner[0])
×
76

77
    # Simple mapping for python types
78
    if dtype is float or dtype is np.float64:
4✔
79
        return Scalar(PrimitiveType.Double)
4✔
80
    elif dtype is np.float32:
4✔
81
        return Scalar(PrimitiveType.Float)
×
82
    elif dtype is bool or dtype is np.bool_:
4✔
83
        return Scalar(PrimitiveType.Bool)
4✔
84
    elif dtype is int or dtype is np.int64:
4✔
85
        return Scalar(PrimitiveType.Int64)
4✔
86
    elif dtype is np.int32:
×
87
        return Scalar(PrimitiveType.Int32)
×
88
    elif dtype is np.int16:
×
89
        return Scalar(PrimitiveType.Int16)
×
90
    elif dtype is np.int8:
×
91
        return Scalar(PrimitiveType.Int8)
×
92
    elif dtype is np.uint64:
×
93
        return Scalar(PrimitiveType.UInt64)
×
94
    elif dtype is np.uint32:
×
95
        return Scalar(PrimitiveType.UInt32)
×
96
    elif dtype is np.uint16:
×
97
        return Scalar(PrimitiveType.UInt16)
×
98
    elif dtype is np.uint8:
×
99
        return Scalar(PrimitiveType.UInt8)
×
100

101
    # Handle Python classes - map to Structure type
102
    if inspect.isclass(dtype):
×
103
        # Use the class name as the structure name
104
        return Pointer(Structure(dtype.__name__))
×
105

106
    return dtype
×
107

108

109
class PythonProgram(DoccProgram):
4✔
110

111
    def __init__(
4✔
112
        self,
113
        func,
114
        target: str = "none",
115
        category: str = "server",
116
        instrumentation_mode: Optional[str] = None,
117
        capture_args: Optional[bool] = None,
118
        remote_tuning: bool = False,
119
    ):
120
        super().__init__(
4✔
121
            name=func.__name__,
122
            target=target,
123
            category=category,
124
            instrumentation_mode=instrumentation_mode,
125
            capture_args=capture_args,
126
            remote_tuning=remote_tuning,
127
        )
128
        self.func = func
4✔
129
        self._last_structure_member_info = {}
4✔
130

131
    def __call__(self, *args: Any) -> Any:
4✔
132
        # JIT compile and run. CompiledSDFG validates the call mode (numpy /
133
        # cupy / torch) and rejects GPU arrays on non-device-resident artifacts.
134
        compiled = self.compile(*args)
4✔
135
        res = compiled(*args)
4✔
136

137
        # Handle return value conversion based on annotation
138
        sig = inspect.signature(self.func)
4✔
139
        ret_annotation = sig.return_annotation
4✔
140

141
        if ret_annotation is not inspect.Signature.empty:
4✔
142
            if get_origin(ret_annotation) is Annotated:
4✔
143
                type_args = get_args(ret_annotation)
×
144
                if len(type_args) >= 1 and type_args[0] is np.ndarray:
×
145
                    shape = None
×
146
                    if len(type_args) >= 2:
×
147
                        shape = type_args[1]
×
148

149
                    if shape is not None:
×
150
                        try:
×
151
                            return np.ctypeslib.as_array(res, shape=shape)
×
152
                        except Exception:
×
153
                            pass
×
154

155
        # Try to infer return shape from metadata
156
        if hasattr(compiled, "get_return_shape"):
4✔
157
            shape = compiled.get_return_shape(*args)
4✔
158
            if shape is not None:
4✔
159
                try:
×
160
                    return np.ctypeslib.as_array(res, shape=shape)
×
161
                except Exception:
×
162
                    pass
×
163

164
        return res
4✔
165

166
    def compile(
4✔
167
        self,
168
        *args: Any,
169
        output_folder: Optional[str] = None,
170
        instrumentation_mode: Optional[str] = None,
171
        capture_args: Optional[bool] = None,
172
        remote_tuning: Optional[bool] = None,
173
    ) -> CompiledSDFG:
174
        original_output_folder = output_folder
4✔
175

176
        # Resolve options
177
        instrumentation_mode, capture_args, remote_tuning = (
4✔
178
            self._resolve_compile_options(
179
                instrumentation_mode, capture_args, remote_tuning
180
            )
181
        )
182

183
        # 1. Analyze arguments and shapes
184
        arg_types = []
4✔
185
        shape_values = []  # List of unique shape values found
4✔
186
        shape_sources = []  # List of (arg_idx, dim_idx) for each unique shape value
4✔
187

188
        # Mapping from (arg_idx, dim_idx) -> unique_shape_idx
189
        arg_shape_mapping = {}
4✔
190

191
        # First pass: collect scalar integer arguments and their values
192
        sig = inspect.signature(self.func)
4✔
193
        params = list(sig.parameters.items())
4✔
194
        scalar_int_params = {}  # Maps value -> parameter name (first one wins)
4✔
195
        for i, ((name, param), arg) in enumerate(zip(params, args)):
4✔
196
            if isinstance(arg, (int, np.integer)) and not isinstance(
4✔
197
                arg, (bool, np.bool_)
198
            ):
199
                val = int(arg)
4✔
200
                if val not in scalar_int_params:
4✔
201
                    scalar_int_params[val] = name
4✔
202

203
        for i, arg in enumerate(args):
4✔
204
            t = self._infer_type(arg)
4✔
205
            arg_types.append(t)
4✔
206

207
            if isinstance(arg, np.ndarray):
4✔
208
                for dim_idx, dim_val in enumerate(arg.shape):
4✔
209
                    # Check if we've seen this value
210
                    if dim_val in shape_values:
4✔
211
                        # Reuse
212
                        u_idx = shape_values.index(dim_val)
4✔
213
                    else:
214
                        # New
215
                        u_idx = len(shape_values)
4✔
216
                        shape_values.append(dim_val)
4✔
217
                        shape_sources.append((i, dim_idx))
4✔
218

219
                    arg_shape_mapping[(i, dim_idx)] = u_idx
4✔
220

221
        # 2. Signature - include scalar-shape equivalences for correct caching
222
        mapping_sig = sorted(arg_shape_mapping.items())
4✔
223
        type_sig = ", ".join(self._type_to_str(t) for t in arg_types)
4✔
224
        signature = f"{type_sig}|{mapping_sig}"
4✔
225

226
        if output_folder is None:
4✔
227
            source_path = inspect.getsourcefile(self.func)
4✔
228
            hash_input = f"{source_path}|{self.name}|{self.target}|{self.category}|{self.capture_args}|{self.instrumentation_mode}|{signature}".encode(
4✔
229
                "utf-8"
230
            )
231
            stable_id = hashlib.sha256(hash_input).hexdigest()[:16]
4✔
232
            filename = os.path.basename(inspect.getsourcefile(self.func))
4✔
233

234
            docc_tmp = os.environ.get("DOCC_TMP")
4✔
235
            if docc_tmp:
4✔
236
                output_folder = (
×
237
                    f"{docc_tmp}/{filename}-{self.name}-{self.target}-{stable_id}"
238
                )
239
            else:
240
                user = os.getenv("USER")
4✔
241
                if not user:
4✔
242
                    user = getpass.getuser()
4✔
243
                output_folder = f"/tmp/{user}/DOCC/{self.name}-{stable_id}"
4✔
244

245
        if original_output_folder is None and signature in self.cache:
4✔
246
            return self.cache[signature]
4✔
247

248
        # 3. Build SDFG
249
        if os.path.exists(output_folder):
4✔
250
            # Multiple python processes running the same code?
251
            shutil.rmtree(output_folder)
4✔
252
        sdfg, out_args, out_shapes, out_strides = self._build_sdfg(
4✔
253
            arg_types, args, arg_shape_mapping, shape_values
254
        )
255

256
        lib_path = self.sdfg_pipe(
4✔
257
            sdfg, output_folder, instrumentation_mode, capture_args, remote_tuning
258
        )
259

260
        # 4. Create CompiledSDFG
261
        compiled = CompiledSDFG(
4✔
262
            lib_path,
263
            sdfg,
264
            shape_sources,
265
            self._last_structure_member_info,
266
            out_args,
267
            out_shapes,
268
            out_strides,
269
            device_resident=self._device_resident,
270
            device_backend=self._device_backend,
271
            target=self.target,
272
        )
273

274
        # Cache if using default output folder
275
        if original_output_folder is None:
4✔
276
            self.cache[signature] = compiled
4✔
277

278
        return compiled
4✔
279

280
    def to_sdfg(self, *args: Any) -> StructuredSDFG:
4✔
281
        arg_types = [self._infer_type(arg) for arg in args]
×
282

283
        # Build shape mapping
284
        shape_values = []
×
285
        shape_sources = []
×
286
        arg_shape_mapping = {}
×
287

288
        sig = inspect.signature(self.func)
×
289
        params = list(sig.parameters.items())
×
290
        scalar_int_params = {}
×
291
        for i, ((name, param), arg) in enumerate(zip(params, args)):
×
292
            if isinstance(arg, (int, np.integer)) and not isinstance(
×
293
                arg, (bool, np.bool_)
294
            ):
295
                val = int(arg)
×
296
                if val not in scalar_int_params:
×
297
                    scalar_int_params[val] = name
×
298

299
        for i, arg in enumerate(args):
×
300
            if isinstance(arg, np.ndarray):
×
301
                for dim_idx, dim_val in enumerate(arg.shape):
×
302
                    if dim_val in shape_values:
×
303
                        u_idx = shape_values.index(dim_val)
×
304
                    else:
305
                        u_idx = len(shape_values)
×
306
                        shape_values.append(dim_val)
×
307
                        shape_sources.append((i, dim_idx))
×
308
                    arg_shape_mapping[(i, dim_idx)] = u_idx
×
309

310
        sdfg, _, _, _ = self._build_sdfg(
×
311
            arg_types, args, arg_shape_mapping, shape_values
312
        )
313
        return sdfg
×
314

315
    def _convert_inputs(self, args: tuple) -> tuple:
4✔
316
        return args
×
317

318
    def _convert_outputs(self, result: Any, original_args: tuple) -> Any:
4✔
319
        return result
×
320

321
    def _get_signature(self, arg_types):
4✔
322
        return ", ".join(self._type_to_str(t) for t in arg_types)
×
323

324
    def _type_to_str(self, t):
4✔
325
        if isinstance(t, Scalar):
4✔
326
            return f"Scalar({t.primitive_type})"
4✔
327
        elif isinstance(t, Array):
4✔
328
            return f"Array({self._type_to_str(t.element_type)}, {t.num_elements})"
×
329
        elif isinstance(t, Pointer):
4✔
330
            return f"Pointer({self._type_to_str(t.pointee_type)})"
4✔
331
        elif isinstance(t, Structure):
4✔
332
            return f"Structure({t.name})"
4✔
333
        return str(t)
×
334

335
    def _infer_type(self, arg):
4✔
336
        if isinstance(arg, (float, np.float64)):
4✔
337
            return Scalar(PrimitiveType.Double)
4✔
338
        elif isinstance(arg, np.float32):
4✔
339
            return Scalar(PrimitiveType.Float)
4✔
340
        elif isinstance(arg, (bool, np.bool_)):
4✔
341
            return Scalar(PrimitiveType.Bool)
4✔
342
        elif isinstance(arg, (int, np.int64)):
4✔
343
            return Scalar(PrimitiveType.Int64)
4✔
344
        elif isinstance(arg, np.int32):
4✔
345
            return Scalar(PrimitiveType.Int32)
4✔
346
        elif isinstance(arg, np.int16):
4✔
347
            return Scalar(PrimitiveType.Int16)
×
348
        elif isinstance(arg, np.int8):
4✔
349
            return Scalar(PrimitiveType.Int8)
×
350
        elif isinstance(arg, np.uint64):
4✔
351
            return Scalar(PrimitiveType.UInt64)
×
352
        elif isinstance(arg, np.uint32):
4✔
353
            return Scalar(PrimitiveType.UInt32)
×
354
        elif isinstance(arg, np.uint16):
4✔
355
            return Scalar(PrimitiveType.UInt16)
×
356
        elif isinstance(arg, np.uint8):
4✔
357
            return Scalar(PrimitiveType.UInt8)
×
358
        elif isinstance(arg, np.ndarray):
4✔
359
            # Map dtype
360
            if arg.dtype == np.float64:
4✔
361
                elem_type = Scalar(PrimitiveType.Double)
4✔
362
            elif arg.dtype == np.float32:
4✔
363
                elem_type = Scalar(PrimitiveType.Float)
4✔
364
            elif arg.dtype == np.float16:
4✔
365
                elem_type = Scalar(PrimitiveType.Half)
×
366
            elif arg.dtype == ml_dtypes.bfloat16:
4✔
367
                elem_type = Scalar(PrimitiveType.BFloat)
4✔
368
            elif arg.dtype == np.bool_:
4✔
369
                elem_type = Scalar(PrimitiveType.Bool)
4✔
370
            elif arg.dtype == np.int64:
4✔
371
                elem_type = Scalar(PrimitiveType.Int64)
4✔
372
            elif arg.dtype == np.int32:
4✔
373
                elem_type = Scalar(PrimitiveType.Int32)
4✔
374
            elif arg.dtype == np.int16:
×
375
                elem_type = Scalar(PrimitiveType.Int16)
×
376
            elif arg.dtype == np.int8:
×
377
                elem_type = Scalar(PrimitiveType.Int8)
×
378
            elif arg.dtype == np.uint64:
×
379
                elem_type = Scalar(PrimitiveType.UInt64)
×
380
            elif arg.dtype == np.uint32:
×
381
                elem_type = Scalar(PrimitiveType.UInt32)
×
382
            elif arg.dtype == np.uint16:
×
383
                elem_type = Scalar(PrimitiveType.UInt16)
×
384
            elif arg.dtype == np.uint8:
×
385
                elem_type = Scalar(PrimitiveType.UInt8)
×
386
            else:
387
                raise ValueError(f"Unsupported numpy dtype: {arg.dtype}")
×
388

389
            return Pointer(elem_type)
4✔
390
        elif isinstance(arg, str):
4✔
391
            # Explicitly reject strings - they are not supported
392
            raise ValueError(f"Unsupported argument type: {type(arg)}")
4✔
393
        else:
394
            # Check if it's a class instance
395
            if hasattr(arg, "__class__") and not isinstance(arg, type):
4✔
396
                # It's an instance of a class, return pointer to Structure
397
                return Pointer(Structure(arg.__class__.__name__))
4✔
398
            raise ValueError(f"Unsupported argument type: {type(arg)}")
×
399

400
    def _build_sdfg(
4✔
401
        self,
402
        arg_types,
403
        args,
404
        arg_shape_mapping,
405
        shape_values,
406
    ):
407
        sig = inspect.signature(self.func)
4✔
408

409
        # Handle return type - always void for SDFG, output args used for returns
410
        return_type = Scalar(PrimitiveType.Void)
4✔
411
        infer_return_type = True
4✔
412

413
        # Parse return annotation to determine output arguments if possible
414
        explicit_returns = []
4✔
415
        if sig.return_annotation is not inspect.Signature.empty:
4✔
416
            infer_return_type = False
4✔
417

418
            # Helper to normalize annotation to list of types
419
            def normalize_annotation(ann):
4✔
420
                # Handle Tuple[type, ...]
421
                origin = get_origin(ann)
4✔
422
                if origin is tuple:
4✔
423
                    type_args = get_args(ann)
×
424
                    # Tuple[()] or Tuple w/o args
425
                    if not type_args:
×
426
                        return []
×
427
                    # Tuple[int, float]
428
                    if len(type_args) > 0 and type_args[-1] is not Ellipsis:
×
429
                        return [_map_python_type(t) for t in type_args]
×
430
                    # Tuple[int, ...] - not supported for fixed number of returns yet?
431
                    # For now assume fixed tuple
432
                    return [_map_python_type(t) for t in type_args]
×
433
                else:
434
                    return [_map_python_type(ann)]
4✔
435

436
            explicit_returns = normalize_annotation(sig.return_annotation)
4✔
437
            for rt in explicit_returns:
4✔
438
                if not isinstance(rt, Type):
4✔
439
                    # Fallback if map failed (e.g. invalid annotation)
440
                    infer_return_type = True
×
441
                    explicit_returns = []
×
442
                    break
×
443

444
        builder = StructuredSDFGBuilder(f"{self.name}_sdfg", return_type)
4✔
445

446
        # Add pre-defined return arguments if we know them
447
        if not infer_return_type:
4✔
448
            for i, dtype in enumerate(explicit_returns):
4✔
449
                # Scalar -> Pointer(Scalar)
450
                # Array -> Already Pointer(Scalar). Keep it.
451
                arg_type = dtype
4✔
452
                if isinstance(dtype, Scalar):
4✔
453
                    arg_type = Pointer(dtype)
4✔
454

455
                builder.add_container(f"_docc_ret_{i}", arg_type, is_argument=True)
4✔
456

457
        # Register structure types for any class arguments
458
        # Also track member name to index mapping for each structure
459
        structures_to_register = {}
4✔
460
        structure_member_info = {}  # Maps struct_name -> {member_name: (index, type)}
4✔
461
        for i, (arg, dtype) in enumerate(zip(args, arg_types)):
4✔
462
            if isinstance(dtype, Pointer) and dtype.has_pointee_type():
4✔
463
                pointee = dtype.pointee_type
4✔
464
                if isinstance(pointee, Structure):
4✔
465
                    struct_name = pointee.name
4✔
466
                    if struct_name not in structures_to_register:
4✔
467
                        # Get class from arg to introspect members
468
                        if hasattr(arg, "__dict__"):
4✔
469
                            # Use __dict__ to get only instance attributes
470
                            # Sort by name to ensure consistent ordering
471
                            # Note: This alphabetical ordering is used to define the
472
                            # structure layout and must match the order expected by
473
                            # the backend code generation
474
                            member_types = []
4✔
475
                            member_names = []
4✔
476
                            member_shapes = []
4✔
477
                            for attr_name, attr_value in sorted(arg.__dict__.items()):
4✔
478
                                if not attr_name.startswith("_"):
4✔
479
                                    # Infer member type from instance attribute
480
                                    # Check bool before int since bool is subclass of int
481
                                    member_type = None
4✔
482
                                    member_shape = None
4✔
483
                                    if isinstance(attr_value, bool):
4✔
484
                                        member_type = Scalar(PrimitiveType.Bool)
×
485
                                    elif isinstance(attr_value, (int, np.int64)):
4✔
486
                                        member_type = Scalar(PrimitiveType.Int64)
4✔
487
                                    elif isinstance(attr_value, (float, np.float64)):
4✔
488
                                        member_type = Scalar(PrimitiveType.Double)
4✔
489
                                    elif isinstance(attr_value, np.int32):
4✔
490
                                        member_type = Scalar(PrimitiveType.Int32)
×
491
                                    elif isinstance(attr_value, np.float32):
4✔
492
                                        member_type = Scalar(PrimitiveType.Float)
×
493
                                    elif isinstance(attr_value, np.ndarray):
4✔
494
                                        # Array member: stored as a pointer field
495
                                        # (struct-of-arrays). Record the concrete
496
                                        # shape so attribute access can build a
497
                                        # tensor view over the member pointer.
498
                                        member_type = self._infer_type(attr_value)
4✔
499
                                        member_shape = [
4✔
500
                                            str(int(s)) for s in attr_value.shape
501
                                        ]
502
                                    # TODO: Consider using np.integer and np.floating abstract types
503
                                    # for more comprehensive numpy type coverage
504
                                    # TODO: Add support for nested structures
505

506
                                    if member_type is not None:
4✔
507
                                        member_types.append(member_type)
4✔
508
                                        member_names.append(attr_name)
4✔
509
                                        member_shapes.append(member_shape)
4✔
510

511
                            if member_types:
4✔
512
                                structures_to_register[struct_name] = member_types
4✔
513
                                # Build member name to (index, type, shape) mapping.
514
                                # shape is None for scalar members and a list of
515
                                # dimension-size strings for array members.
516
                                structure_member_info[struct_name] = {
4✔
517
                                    name: (idx, mtype, shape)
518
                                    for idx, (name, mtype, shape) in enumerate(
519
                                        zip(member_names, member_types, member_shapes)
520
                                    )
521
                                }
522

523
        # Store structure_member_info for later use in CompiledSDFG
524
        self._last_structure_member_info = structure_member_info
4✔
525

526
        # Register all discovered structures with the builder
527
        for struct_name, member_types in structures_to_register.items():
4✔
528
            builder.add_structure(struct_name, member_types)
4✔
529

530
        # Register arguments
531
        params = list(sig.parameters.items())
4✔
532
        if len(params) != len(arg_types):
4✔
533
            raise ValueError(
×
534
                f"Argument count mismatch: expected {len(params)}, got {len(arg_types)}"
535
            )
536

537
        # Add regular arguments
538
        tensor_table = {}
4✔
539
        for i, ((name, param), dtype, arg) in enumerate(zip(params, arg_types, args)):
4✔
540
            builder.add_container(name, dtype, is_argument=True)
4✔
541

542
            # Store layout information for arrays
543
            if isinstance(arg, np.ndarray):
4✔
544
                element_type = element_type_from_sdfg_type(dtype)
4✔
545

546
                shapes = []
4✔
547
                for dim_idx in range(arg.ndim):
4✔
548
                    dim_val = arg.shape[dim_idx]
4✔
549
                    if dim_val == 1:
4✔
550
                        # Always use literal "1" for size-1 dimensions to enable
551
                        # proper broadcasting detection
552
                        shapes.append("1")
4✔
553
                    else:
554
                        u_idx = arg_shape_mapping[(i, dim_idx)]
4✔
555
                        shapes.append(f"_s{u_idx}")
4✔
556

557
                strides = []
4✔
558
                if arg.flags["C_CONTIGUOUS"]:
4✔
559
                    # Row-major: stride[i] = product of shapes[i+1:]
560
                    for dim_idx in range(arg.ndim):
4✔
561
                        if dim_idx == arg.ndim - 1:
4✔
562
                            strides.append("1")
4✔
563
                        else:
564
                            suffix_shapes = shapes[dim_idx + 1 :]
4✔
565
                            if len(suffix_shapes) == 1:
4✔
566
                                strides.append(suffix_shapes[0])
4✔
567
                            else:
568
                                strides.append("(" + " * ".join(suffix_shapes) + ")")
4✔
569
                elif arg.flags["F_CONTIGUOUS"]:
4✔
570
                    # Column-major: stride[i] = product of shapes[:i]
571
                    for dim_idx in range(arg.ndim):
4✔
572
                        if dim_idx == 0:
4✔
573
                            strides.append("1")
4✔
574
                        else:
575
                            prefix_shapes = shapes[:dim_idx]
4✔
576
                            if len(prefix_shapes) == 1:
4✔
577
                                strides.append(prefix_shapes[0])
4✔
578
                            else:
579
                                strides.append("(" + " * ".join(prefix_shapes) + ")")
4✔
580
                else:
581
                    # Non-contiguous: use actual stride values
582
                    for dim_idx in range(arg.ndim):
4✔
583
                        stride_val = arg.strides[dim_idx] // arg.itemsize
4✔
584
                        strides.append(f"{stride_val}")
4✔
585

586
                offset = "0"
4✔
587
                tensor_table[name] = Tensor(element_type, shapes, strides, offset)
4✔
588

589
            elif isinstance(arg, np.generic):
4✔
590
                # NumPy scalar types (np.float64, np.int32, etc.) should be treated
591
                # as 0-d arrays for type promotion purposes - they trigger full
592
                # promotion, unlike Python literals which adapt to the array dtype
593
                element_type = element_type_from_sdfg_type(dtype)
4✔
594
                tensor_table[name] = Tensor(element_type, [], [], "0")
4✔
595

596
        # Add unified shape arguments only for shapes without scalar equivalents
597
        # and skip size-1 dimensions (they use literal "1" instead)
598
        for i in range(len(shape_values)):
4✔
599
            if shape_values[i] != 1:
4✔
600
                builder.add_container(
4✔
601
                    f"_s{i}", Scalar(PrimitiveType.Int64), is_argument=True
602
                )
603
                builder.add_assumption_lb(f"_s{i}", "1")  # Shapes must be positive
4✔
604
                builder.add_assumption_const(f"_s{i}", True)  # Shapes are constant
4✔
605

606
        # Create symbol table for parser
607
        container_table = {}
4✔
608
        for i, ((name, param), dtype, arg) in enumerate(zip(params, arg_types, args)):
4✔
609
            container_table[name] = dtype
4✔
610

611
        for i in range(len(shape_values)):
4✔
612
            if shape_values[i] != 1:
4✔
613
                container_table[f"_s{i}"] = Scalar(PrimitiveType.Int64)
4✔
614

615
        # Parse AST
616
        source_lines, start_line = inspect.getsourcelines(self.func)
4✔
617
        source = textwrap.dedent("".join(source_lines))
4✔
618
        tree = ast.parse(source)
4✔
619
        ast.increment_lineno(tree, start_line - 1)
4✔
620
        func_def = tree.body[0]
4✔
621

622
        filename = inspect.getsourcefile(self.func)
4✔
623
        function_name = self.func.__name__
4✔
624

625
        # Combine globals with closure variables (closure takes precedence)
626
        combined_globals = dict(self.func.__globals__)
4✔
627
        if self.func.__closure__ is not None and self.func.__code__.co_freevars:
4✔
628
            for name, cell in zip(
4✔
629
                self.func.__code__.co_freevars, self.func.__closure__
630
            ):
631
                combined_globals[name] = cell.cell_contents
4✔
632

633
        parser = ASTParser(
4✔
634
            builder,
635
            tensor_table,
636
            container_table,
637
            filename,
638
            function_name,
639
            infer_return_type=infer_return_type,
640
            globals_dict=combined_globals,
641
            structure_member_info=structure_member_info,
642
        )
643
        for node in func_def.body:
4✔
644
            parser.visit(node)
4✔
645

646
        # Emit hoisted allocations at function entry
647
        parser.memory_handler.emit_allocations()
4✔
648

649
        sdfg = builder.move()
4✔
650
        # Mark return arguments metadata
651
        out_args = []
4✔
652
        for name in sdfg.arguments:
4✔
653
            if name.startswith("_docc_ret_"):
4✔
654
                out_args.append(name)
4✔
655

656
        return (
4✔
657
            sdfg,
658
            out_args,
659
            parser.captured_return_shapes,
660
            parser.captured_return_strides,
661
        )
662

663

664
def native(
4✔
665
    func=None,
666
    *,
667
    target="none",
668
    category="server",
669
    instrumentation_mode=None,
670
    capture_args=None,
671
    remote_tuning=False,
672
):
673
    """Decorator to create a PythonProgram from a Python function.
674

675
    Example:
676
        @native
677
        def my_function(x: np.ndarray) -> np.ndarray:
678
            return x * 2
679

680
        result = my_function(np.array([1.0, 2.0, 3.0]))
681
    """
682
    if func is None:
4✔
683
        return lambda f: PythonProgram(
4✔
684
            f,
685
            target=target,
686
            category=category,
687
            instrumentation_mode=instrumentation_mode,
688
            capture_args=capture_args,
689
            remote_tuning=remote_tuning,
690
        )
691
    return PythonProgram(
4✔
692
        func,
693
        target=target,
694
        category=category,
695
        instrumentation_mode=instrumentation_mode,
696
        capture_args=capture_args,
697
        remote_tuning=remote_tuning,
698
    )
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc