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

daisytuner / docc / 22608361531

28 Feb 2026 02:59PM UTC coverage: 64.42% (+0.005%) from 64.415%
22608361531

push

github

web-flow
Merge pull request #557 from daisytuner/accelerator-dtypes

Accelerator dtypes

22 of 35 new or added lines in 4 files covered. (62.86%)

24472 of 37988 relevant lines covered (64.42%)

386.62 hits per line

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

72.94
/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
from docc.python.target_registry import get_target, is_custom_target
4✔
28

29

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

35

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

39

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

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

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

57
            if len(metadata) > 1:
4✔
58
                possible_dtype = metadata[1]
4✔
59
                elem_type = _map_python_type(possible_dtype)
4✔
60

61
            return Pointer(elem_type)
4✔
62

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

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

95
    # Handle Python classes - map to Structure type
96
    if inspect.isclass(dtype):
×
97
        # Use the class name as the structure name
98
        return Pointer(Structure(dtype.__name__))
×
99

100
    return dtype
×
101

102

103
class PythonProgram(DoccProgram):
4✔
104

105
    def __init__(
4✔
106
        self,
107
        func,
108
        target: str = "none",
109
        category: str = "server",
110
        instrumentation_mode: Optional[str] = None,
111
        capture_args: Optional[bool] = None,
112
        remote_tuning: bool = False,
113
    ):
114
        super().__init__(
4✔
115
            name=func.__name__,
116
            target=target,
117
            category=category,
118
            instrumentation_mode=instrumentation_mode,
119
            capture_args=capture_args,
120
            remote_tuning=remote_tuning,
121
        )
122
        self.func = func
4✔
123
        self._last_structure_member_info = {}
4✔
124

125
    def __call__(self, *args: Any) -> Any:
4✔
126
        # JIT compile and run
127
        compiled = self.compile(*args)
4✔
128
        res = compiled(*args)
4✔
129

130
        # Handle return value conversion based on annotation
131
        sig = inspect.signature(self.func)
4✔
132
        ret_annotation = sig.return_annotation
4✔
133

134
        if ret_annotation is not inspect.Signature.empty:
4✔
135
            if get_origin(ret_annotation) is Annotated:
4✔
136
                type_args = get_args(ret_annotation)
4✔
137
                if len(type_args) >= 1 and type_args[0] is np.ndarray:
4✔
138
                    shape = None
4✔
139
                    if len(type_args) >= 2:
4✔
140
                        shape = type_args[1]
4✔
141

142
                    if shape is not None:
4✔
143
                        try:
4✔
144
                            return np.ctypeslib.as_array(res, shape=shape)
4✔
145
                        except Exception:
×
146
                            pass
×
147

148
        # Try to infer return shape from metadata
149
        if hasattr(compiled, "get_return_shape"):
4✔
150
            shape = compiled.get_return_shape(*args)
4✔
151
            if shape is not None:
4✔
152
                try:
×
153
                    return np.ctypeslib.as_array(res, shape=shape)
×
154
                except Exception:
×
155
                    pass
×
156

157
        return res
4✔
158

159
    def compile(
4✔
160
        self,
161
        *args: Any,
162
        output_folder: Optional[str] = None,
163
        instrumentation_mode: Optional[str] = None,
164
        capture_args: Optional[bool] = None,
165
    ) -> CompiledSDFG:
166
        original_output_folder = output_folder
4✔
167

168
        # Resolve options
169
        if instrumentation_mode is None:
4✔
170
            instrumentation_mode = self.instrumentation_mode
4✔
171
        if capture_args is None:
4✔
172
            capture_args = self.capture_args
4✔
173

174
        # Check environment variable DOCC_CI
175
        docc_ci = os.environ.get("DOCC_CI", "")
4✔
176
        if docc_ci:
4✔
177
            if docc_ci == "regions":
×
178
                if instrumentation_mode is None:
×
179
                    instrumentation_mode = "ols"
×
180
            elif docc_ci == "arg-capture":
×
181
                if capture_args is None:
×
182
                    capture_args = True
×
183
            else:
184
                # Full mode (or unknown value treated as full)
185
                if instrumentation_mode is None:
×
186
                    instrumentation_mode = "ols"
×
187
                if capture_args is None:
×
188
                    capture_args = True
×
189

190
        # Defaults
191
        if instrumentation_mode is None:
4✔
192
            instrumentation_mode = ""
4✔
193
        if capture_args is None:
4✔
194
            capture_args = False
4✔
195

196
        # 1. Analyze arguments and shapes
197
        arg_types = []
4✔
198
        shape_values = []  # List of unique shape values found
4✔
199
        shape_sources = []  # List of (arg_idx, dim_idx) for each unique shape value
4✔
200

201
        # Mapping from (arg_idx, dim_idx) -> unique_shape_idx
202
        arg_shape_mapping = {}
4✔
203

204
        # First pass: collect scalar integer arguments and their values
205
        sig = inspect.signature(self.func)
4✔
206
        params = list(sig.parameters.items())
4✔
207
        scalar_int_params = {}  # Maps value -> parameter name (first one wins)
4✔
208
        for i, ((name, param), arg) in enumerate(zip(params, args)):
4✔
209
            if isinstance(arg, (int, np.integer)) and not isinstance(
4✔
210
                arg, (bool, np.bool_)
211
            ):
212
                val = int(arg)
4✔
213
                if val not in scalar_int_params:
4✔
214
                    scalar_int_params[val] = name
4✔
215

216
        for i, arg in enumerate(args):
4✔
217
            t = self._infer_type(arg)
4✔
218
            arg_types.append(t)
4✔
219

220
            if isinstance(arg, np.ndarray):
4✔
221
                for dim_idx, dim_val in enumerate(arg.shape):
4✔
222
                    # Check if we've seen this value
223
                    if dim_val in shape_values:
4✔
224
                        # Reuse
225
                        u_idx = shape_values.index(dim_val)
4✔
226
                    else:
227
                        # New
228
                        u_idx = len(shape_values)
4✔
229
                        shape_values.append(dim_val)
4✔
230
                        shape_sources.append((i, dim_idx))
4✔
231

232
                    arg_shape_mapping[(i, dim_idx)] = u_idx
4✔
233

234
        # Detect scalar-shape equivalences: which shape indices have a matching scalar param
235
        # Maps unique_shape_idx -> scalar parameter name
236
        shape_to_scalar = {}
4✔
237
        for s_idx, s_val in enumerate(shape_values):
4✔
238
            if s_val in scalar_int_params:
4✔
239
                shape_to_scalar[s_idx] = scalar_int_params[s_val]
4✔
240

241
        # 2. Signature - include scalar-shape equivalences for correct caching
242
        mapping_sig = sorted(arg_shape_mapping.items())
4✔
243
        equiv_sig = sorted(shape_to_scalar.items())
4✔
244
        type_sig = ", ".join(self._type_to_str(t) for t in arg_types)
4✔
245
        signature = f"{type_sig}|{mapping_sig}|{equiv_sig}"
4✔
246

247
        if output_folder is None:
4✔
248
            filename = inspect.getsourcefile(self.func)
4✔
249
            hash_input = f"{filename}|{self.name}|{self.target}|{self.category}|{self.capture_args}|{self.instrumentation_mode}|{signature}".encode(
4✔
250
                "utf-8"
251
            )
252
            stable_id = hashlib.sha256(hash_input).hexdigest()[:16]
4✔
253

254
            docc_tmp = os.environ.get("DOCC_TMP")
4✔
255
            if docc_tmp:
4✔
256
                output_folder = f"{docc_tmp}/{self.name}-{stable_id}"
×
257
            else:
258
                user = os.getenv("USER")
4✔
259
                if not user:
4✔
260
                    user = getpass.getuser()
4✔
261
                output_folder = f"/tmp/{user}/DOCC/{self.name}-{stable_id}"
4✔
262

263
        if original_output_folder is None and signature in self.cache:
4✔
264
            return self.cache[signature]
4✔
265

266
        # 3. Build SDFG
267
        if os.path.exists(output_folder):
4✔
268
            # Multiple python processes running the same code?
269
            shutil.rmtree(output_folder)
4✔
270
        sdfg, out_args, out_shapes, out_strides = self._build_sdfg(
4✔
271
            arg_types, args, arg_shape_mapping, shape_values, shape_to_scalar
272
        )
273
        sdfg.validate()
4✔
274

275
        # Tensor targets keep tensor nodes
276
        if self.target != "onnx":
4✔
277
            sdfg.expand()
4✔
278

279
        # Simplify pipelines
280
        sdfg.simplify()
4✔
281

282
        # Normalization for scheduling
283
        if self.target != "none":
4✔
284
            sdfg.normalize()
4✔
285

286
        sdfg.dump(output_folder)
4✔
287

288
        # Schedule if target is specified
289
        if self.target != "none":
4✔
290
            # Check for custom registered target first
291
            custom_schedule_fn = get_target(self.target)
4✔
292
            if custom_schedule_fn is not None:
4✔
293
                custom_schedule_fn(sdfg, self.category)
×
294
            else:
295
                sdfg.schedule(self.target, self.category, self.remote_tuning)
4✔
296

297
        self.last_sdfg = sdfg
4✔
298

299
        lib_path = sdfg._compile(
4✔
300
            output_folder=output_folder,
301
            target=self.target,
302
            instrumentation_mode=instrumentation_mode,
303
            capture_args=capture_args,
304
        )
305

306
        # Build ONNX model from JSON if target is onnx (after _compile creates the JSON)
307
        if self.target == "onnx":
4✔
308
            from docc.python.targets.onnx_model_builder import convert_json_to_onnx
×
309

310
            onnx_model_path = convert_json_to_onnx(output_folder)
×
311
            if onnx_model_path:
×
312
                print(f"Generated ONNX models: {onnx_model_path}")
×
313

314
        # 5. Create CompiledSDFG
315
        compiled = CompiledSDFG(
4✔
316
            lib_path,
317
            sdfg,
318
            shape_sources,
319
            self._last_structure_member_info,
320
            out_args,
321
            out_shapes,
322
            out_strides,
323
        )
324

325
        # Cache if using default output folder
326
        if original_output_folder is None:
4✔
327
            self.cache[signature] = compiled
4✔
328

329
        return compiled
4✔
330

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

334
        # Build shape mapping
335
        shape_values = []
×
336
        shape_sources = []
×
337
        arg_shape_mapping = {}
×
338

339
        sig = inspect.signature(self.func)
×
340
        params = list(sig.parameters.items())
×
341
        scalar_int_params = {}
×
342
        for i, ((name, param), arg) in enumerate(zip(params, args)):
×
343
            if isinstance(arg, (int, np.integer)) and not isinstance(
×
344
                arg, (bool, np.bool_)
345
            ):
346
                val = int(arg)
×
347
                if val not in scalar_int_params:
×
348
                    scalar_int_params[val] = name
×
349

350
        for i, arg in enumerate(args):
×
351
            if isinstance(arg, np.ndarray):
×
352
                for dim_idx, dim_val in enumerate(arg.shape):
×
353
                    if dim_val in shape_values:
×
354
                        u_idx = shape_values.index(dim_val)
×
355
                    else:
356
                        u_idx = len(shape_values)
×
357
                        shape_values.append(dim_val)
×
358
                        shape_sources.append((i, dim_idx))
×
359
                    arg_shape_mapping[(i, dim_idx)] = u_idx
×
360

361
        shape_to_scalar = {}
×
362
        for s_idx, s_val in enumerate(shape_values):
×
363
            if s_val in scalar_int_params:
×
364
                shape_to_scalar[s_idx] = scalar_int_params[s_val]
×
365

366
        sdfg, _, _, _ = self._build_sdfg(
×
367
            arg_types, args, arg_shape_mapping, shape_values, shape_to_scalar
368
        )
369
        return sdfg
×
370

371
    def _convert_inputs(self, args: tuple) -> tuple:
4✔
372
        return args
×
373

374
    def _convert_outputs(self, result: Any, original_args: tuple) -> Any:
4✔
375
        return result
×
376

377
    def _get_signature(self, arg_types):
4✔
378
        return ", ".join(self._type_to_str(t) for t in arg_types)
×
379

380
    def _type_to_str(self, t):
4✔
381
        if isinstance(t, Scalar):
4✔
382
            return f"Scalar({t.primitive_type})"
4✔
383
        elif isinstance(t, Array):
4✔
384
            return f"Array({self._type_to_str(t.element_type)}, {t.num_elements})"
×
385
        elif isinstance(t, Pointer):
4✔
386
            return f"Pointer({self._type_to_str(t.pointee_type)})"
4✔
387
        elif isinstance(t, Structure):
4✔
388
            return f"Structure({t.name})"
4✔
389
        return str(t)
×
390

391
    def _infer_type(self, arg):
4✔
392
        if isinstance(arg, (float, np.float64)):
4✔
393
            return Scalar(PrimitiveType.Double)
4✔
394
        elif isinstance(arg, np.float32):
4✔
395
            return Scalar(PrimitiveType.Float)
4✔
396
        elif isinstance(arg, (bool, np.bool_)):
4✔
397
            return Scalar(PrimitiveType.Bool)
4✔
398
        elif isinstance(arg, (int, np.int64)):
4✔
399
            return Scalar(PrimitiveType.Int64)
4✔
400
        elif isinstance(arg, np.int32):
4✔
401
            return Scalar(PrimitiveType.Int32)
4✔
402
        elif isinstance(arg, np.int16):
4✔
403
            return Scalar(PrimitiveType.Int16)
×
404
        elif isinstance(arg, np.int8):
4✔
405
            return Scalar(PrimitiveType.Int8)
×
406
        elif isinstance(arg, np.uint64):
4✔
407
            return Scalar(PrimitiveType.UInt64)
×
408
        elif isinstance(arg, np.uint32):
4✔
409
            return Scalar(PrimitiveType.UInt32)
×
410
        elif isinstance(arg, np.uint16):
4✔
411
            return Scalar(PrimitiveType.UInt16)
×
412
        elif isinstance(arg, np.uint8):
4✔
413
            return Scalar(PrimitiveType.UInt8)
×
414
        elif isinstance(arg, np.ndarray):
4✔
415
            # Map dtype
416
            if arg.dtype == np.float64:
4✔
417
                elem_type = Scalar(PrimitiveType.Double)
4✔
418
            elif arg.dtype == np.float32:
4✔
419
                elem_type = Scalar(PrimitiveType.Float)
4✔
420
            elif arg.dtype == np.float16:
4✔
NEW
421
                elem_type = Scalar(PrimitiveType.Half)
×
422
            elif arg.dtype == ml_dtypes.bfloat16:
4✔
423
                elem_type = Scalar(PrimitiveType.BFloat)
4✔
424
            elif arg.dtype == np.bool_:
4✔
425
                elem_type = Scalar(PrimitiveType.Bool)
4✔
426
            elif arg.dtype == np.int64:
4✔
427
                elem_type = Scalar(PrimitiveType.Int64)
4✔
428
            elif arg.dtype == np.int32:
4✔
429
                elem_type = Scalar(PrimitiveType.Int32)
4✔
430
            elif arg.dtype == np.int16:
×
431
                elem_type = Scalar(PrimitiveType.Int16)
×
432
            elif arg.dtype == np.int8:
×
433
                elem_type = Scalar(PrimitiveType.Int8)
×
434
            elif arg.dtype == np.uint64:
×
435
                elem_type = Scalar(PrimitiveType.UInt64)
×
436
            elif arg.dtype == np.uint32:
×
437
                elem_type = Scalar(PrimitiveType.UInt32)
×
438
            elif arg.dtype == np.uint16:
×
439
                elem_type = Scalar(PrimitiveType.UInt16)
×
440
            elif arg.dtype == np.uint8:
×
441
                elem_type = Scalar(PrimitiveType.UInt8)
×
442
            else:
443
                raise ValueError(f"Unsupported numpy dtype: {arg.dtype}")
×
444

445
            return Pointer(elem_type)
4✔
446
        elif isinstance(arg, str):
4✔
447
            # Explicitly reject strings - they are not supported
448
            raise ValueError(f"Unsupported argument type: {type(arg)}")
4✔
449
        else:
450
            # Check if it's a class instance
451
            if hasattr(arg, "__class__") and not isinstance(arg, type):
4✔
452
                # It's an instance of a class, return pointer to Structure
453
                return Pointer(Structure(arg.__class__.__name__))
4✔
454
            raise ValueError(f"Unsupported argument type: {type(arg)}")
×
455

456
    def _build_sdfg(
4✔
457
        self,
458
        arg_types,
459
        args,
460
        arg_shape_mapping,
461
        shape_values,
462
        shape_to_scalar=None,
463
    ):
464
        if shape_to_scalar is None:
4✔
465
            shape_to_scalar = {}
×
466
        sig = inspect.signature(self.func)
4✔
467

468
        # Handle return type - always void for SDFG, output args used for returns
469
        return_type = Scalar(PrimitiveType.Void)
4✔
470
        infer_return_type = True
4✔
471

472
        # Parse return annotation to determine output arguments if possible
473
        explicit_returns = []
4✔
474
        if sig.return_annotation is not inspect.Signature.empty:
4✔
475
            infer_return_type = False
4✔
476

477
            # Helper to normalize annotation to list of types
478
            def normalize_annotation(ann):
4✔
479
                # Handle Tuple[type, ...]
480
                origin = get_origin(ann)
4✔
481
                if origin is tuple:
4✔
482
                    type_args = get_args(ann)
×
483
                    # Tuple[()] or Tuple w/o args
484
                    if not type_args:
×
485
                        return []
×
486
                    # Tuple[int, float]
487
                    if len(type_args) > 0 and type_args[-1] is not Ellipsis:
×
488
                        return [_map_python_type(t) for t in type_args]
×
489
                    # Tuple[int, ...] - not supported for fixed number of returns yet?
490
                    # For now assume fixed tuple
491
                    return [_map_python_type(t) for t in type_args]
×
492
                else:
493
                    return [_map_python_type(ann)]
4✔
494

495
            explicit_returns = normalize_annotation(sig.return_annotation)
4✔
496
            for rt in explicit_returns:
4✔
497
                if not isinstance(rt, Type):
4✔
498
                    # Fallback if map failed (e.g. invalid annotation)
499
                    infer_return_type = True
×
500
                    explicit_returns = []
×
501
                    break
×
502

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

505
        # Add pre-defined return arguments if we know them
506
        if not infer_return_type:
4✔
507
            for i, dtype in enumerate(explicit_returns):
4✔
508
                # Scalar -> Pointer(Scalar)
509
                # Array -> Already Pointer(Scalar). Keep it.
510
                arg_type = dtype
4✔
511
                if isinstance(dtype, Scalar):
4✔
512
                    arg_type = Pointer(dtype)
4✔
513

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

516
        # Register structure types for any class arguments
517
        # Also track member name to index mapping for each structure
518
        structures_to_register = {}
4✔
519
        structure_member_info = {}  # Maps struct_name -> {member_name: (index, type)}
4✔
520
        for i, (arg, dtype) in enumerate(zip(args, arg_types)):
4✔
521
            if isinstance(dtype, Pointer) and dtype.has_pointee_type():
4✔
522
                pointee = dtype.pointee_type
4✔
523
                if isinstance(pointee, Structure):
4✔
524
                    struct_name = pointee.name
4✔
525
                    if struct_name not in structures_to_register:
4✔
526
                        # Get class from arg to introspect members
527
                        if hasattr(arg, "__dict__"):
4✔
528
                            # Use __dict__ to get only instance attributes
529
                            # Sort by name to ensure consistent ordering
530
                            # Note: This alphabetical ordering is used to define the
531
                            # structure layout and must match the order expected by
532
                            # the backend code generation
533
                            member_types = []
4✔
534
                            member_names = []
4✔
535
                            for attr_name, attr_value in sorted(arg.__dict__.items()):
4✔
536
                                if not attr_name.startswith("_"):
4✔
537
                                    # Infer member type from instance attribute
538
                                    # Check bool before int since bool is subclass of int
539
                                    member_type = None
4✔
540
                                    if isinstance(attr_value, bool):
4✔
541
                                        member_type = Scalar(PrimitiveType.Bool)
×
542
                                    elif isinstance(attr_value, (int, np.int64)):
4✔
543
                                        member_type = Scalar(PrimitiveType.Int64)
×
544
                                    elif isinstance(attr_value, (float, np.float64)):
4✔
545
                                        member_type = Scalar(PrimitiveType.Double)
4✔
546
                                    elif isinstance(attr_value, np.int32):
×
547
                                        member_type = Scalar(PrimitiveType.Int32)
×
548
                                    elif isinstance(attr_value, np.float32):
×
549
                                        member_type = Scalar(PrimitiveType.Float)
×
550
                                    # TODO: Consider using np.integer and np.floating abstract types
551
                                    # for more comprehensive numpy type coverage
552
                                    # TODO: Add support for nested structures and arrays
553

554
                                    if member_type is not None:
4✔
555
                                        member_types.append(member_type)
4✔
556
                                        member_names.append(attr_name)
4✔
557

558
                            if member_types:
4✔
559
                                structures_to_register[struct_name] = member_types
4✔
560
                                # Build member name to (index, type) mapping
561
                                structure_member_info[struct_name] = {
4✔
562
                                    name: (idx, mtype)
563
                                    for idx, (name, mtype) in enumerate(
564
                                        zip(member_names, member_types)
565
                                    )
566
                                }
567

568
        # Store structure_member_info for later use in CompiledSDFG
569
        self._last_structure_member_info = structure_member_info
4✔
570

571
        # Register all discovered structures with the builder
572
        for struct_name, member_types in structures_to_register.items():
4✔
573
            builder.add_structure(struct_name, member_types)
4✔
574

575
        # Register arguments
576
        params = list(sig.parameters.items())
4✔
577
        if len(params) != len(arg_types):
4✔
578
            raise ValueError(
×
579
                f"Argument count mismatch: expected {len(params)}, got {len(arg_types)}"
580
            )
581

582
        # Add regular arguments
583
        tensor_table = {}
4✔
584
        for i, ((name, param), dtype, arg) in enumerate(zip(params, arg_types, args)):
4✔
585
            builder.add_container(name, dtype, is_argument=True)
4✔
586

587
            # Store layout information for arrays
588
            if isinstance(arg, np.ndarray):
4✔
589
                element_type = element_type_from_sdfg_type(dtype)
4✔
590

591
                shapes = []
4✔
592
                for dim_idx in range(arg.ndim):
4✔
593
                    dim_val = arg.shape[dim_idx]
4✔
594
                    if dim_val == 1:
4✔
595
                        # Always use literal "1" for size-1 dimensions to enable
596
                        # proper broadcasting detection
597
                        shapes.append("1")
4✔
598
                    else:
599
                        u_idx = arg_shape_mapping[(i, dim_idx)]
4✔
600
                        if u_idx in shape_to_scalar:
4✔
601
                            shapes.append(shape_to_scalar[u_idx])
4✔
602
                        else:
603
                            shapes.append(f"_s{u_idx}")
4✔
604

605
                strides = []
4✔
606
                if arg.flags["C_CONTIGUOUS"]:
4✔
607
                    # Row-major: stride[i] = product of shapes[i+1:]
608
                    for dim_idx in range(arg.ndim):
4✔
609
                        if dim_idx == arg.ndim - 1:
4✔
610
                            strides.append("1")
4✔
611
                        else:
612
                            suffix_shapes = shapes[dim_idx + 1 :]
4✔
613
                            if len(suffix_shapes) == 1:
4✔
614
                                strides.append(suffix_shapes[0])
4✔
615
                            else:
616
                                strides.append("(" + " * ".join(suffix_shapes) + ")")
4✔
617
                elif arg.flags["F_CONTIGUOUS"]:
4✔
618
                    # Column-major: stride[i] = product of shapes[:i]
619
                    for dim_idx in range(arg.ndim):
4✔
620
                        if dim_idx == 0:
4✔
621
                            strides.append("1")
4✔
622
                        else:
623
                            prefix_shapes = shapes[:dim_idx]
4✔
624
                            if len(prefix_shapes) == 1:
4✔
625
                                strides.append(prefix_shapes[0])
4✔
626
                            else:
627
                                strides.append("(" + " * ".join(prefix_shapes) + ")")
4✔
628
                else:
629
                    # Non-contiguous: use actual stride values
630
                    for dim_idx in range(arg.ndim):
4✔
631
                        stride_val = arg.strides[dim_idx] // arg.itemsize
4✔
632
                        strides.append(f"{stride_val}")
4✔
633

634
                offset = "0"
4✔
635
                tensor_table[name] = Tensor(element_type, shapes, strides, offset)
4✔
636

637
        # Add unified shape arguments only for shapes without scalar equivalents
638
        # and skip size-1 dimensions (they use literal "1" instead)
639
        for i in range(len(shape_values)):
4✔
640
            if i not in shape_to_scalar and shape_values[i] != 1:
4✔
641
                builder.add_container(
4✔
642
                    f"_s{i}", Scalar(PrimitiveType.Int64), is_argument=True
643
                )
644

645
        # Create symbol table for parser
646
        container_table = {}
4✔
647
        for i, ((name, param), dtype, arg) in enumerate(zip(params, arg_types, args)):
4✔
648
            container_table[name] = dtype
4✔
649

650
        for i in range(len(shape_values)):
4✔
651
            if i not in shape_to_scalar and shape_values[i] != 1:
4✔
652
                container_table[f"_s{i}"] = Scalar(PrimitiveType.Int64)
4✔
653

654
        # Parse AST
655
        source_lines, start_line = inspect.getsourcelines(self.func)
4✔
656
        source = textwrap.dedent("".join(source_lines))
4✔
657
        tree = ast.parse(source)
4✔
658
        ast.increment_lineno(tree, start_line - 1)
4✔
659
        func_def = tree.body[0]
4✔
660

661
        filename = inspect.getsourcefile(self.func)
4✔
662
        function_name = self.func.__name__
4✔
663

664
        # Combine globals with closure variables (closure takes precedence)
665
        combined_globals = dict(self.func.__globals__)
4✔
666
        if self.func.__closure__ is not None and self.func.__code__.co_freevars:
4✔
667
            for name, cell in zip(
4✔
668
                self.func.__code__.co_freevars, self.func.__closure__
669
            ):
670
                combined_globals[name] = cell.cell_contents
4✔
671

672
        parser = ASTParser(
4✔
673
            builder,
674
            tensor_table,
675
            container_table,
676
            filename,
677
            function_name,
678
            infer_return_type=infer_return_type,
679
            globals_dict=combined_globals,
680
            structure_member_info=structure_member_info,
681
        )
682
        for node in func_def.body:
4✔
683
            parser.visit(node)
4✔
684

685
        # Emit hoisted allocations at function entry
686
        parser.memory_handler.emit_allocations()
4✔
687

688
        sdfg = builder.move()
4✔
689
        # Mark return arguments metadata
690
        out_args = []
4✔
691
        for name in sdfg.arguments:
4✔
692
            if name.startswith("_docc_ret_"):
4✔
693
                out_args.append(name)
4✔
694

695
        return (
4✔
696
            sdfg,
697
            out_args,
698
            parser.captured_return_shapes,
699
            parser.captured_return_strides,
700
        )
701

702

703
def native(
4✔
704
    func=None,
705
    *,
706
    target="none",
707
    category="desktop",
708
    instrumentation_mode=None,
709
    capture_args=None,
710
):
711
    """Decorator to create a PythonProgram from a Python function.
712

713
    Example:
714
        @native
715
        def my_function(x: np.ndarray) -> np.ndarray:
716
            return x * 2
717

718
        result = my_function(np.array([1.0, 2.0, 3.0]))
719
    """
720
    if func is None:
4✔
721
        return lambda f: PythonProgram(
4✔
722
            f,
723
            target=target,
724
            category=category,
725
            instrumentation_mode=instrumentation_mode,
726
            capture_args=capture_args,
727
        )
728
    return PythonProgram(
4✔
729
        func,
730
        target=target,
731
        category=category,
732
        instrumentation_mode=instrumentation_mode,
733
        capture_args=capture_args,
734
    )
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc