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

daisytuner / docc / 30626884092

31 Jul 2026 11:23AM UTC coverage: 64.71% (-0.02%) from 64.73%
30626884092

push

github

web-flow
Merge pull request #921 from daisytuner/dump-last-sdfg

uses last SDFG as reference for instrumentation

3 of 3 new or added lines in 1 file covered. (100.0%)

15 existing lines in 2 files now uncovered.

45160 of 69788 relevant lines covered (64.71%)

728.67 hits per line

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

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

13
from docc.sdfg import (
4✔
14
    Scalar,
15
    PrimitiveType,
16
    Pointer,
17
    Structure,
18
    Array,
19
    Type,
20
    Tensor,
21
    StructuredSDFG,
22
    StructuredSDFGBuilder,
23
)
24
from docc.compiler.docc_program import DoccProgram
4✔
25
from docc.compiler.compiled_sdfg import CompiledSDFG
4✔
26
from docc.python.ast_parser import ASTParser
4✔
27
from docc.python.types import element_type_from_sdfg_type
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)
×
49
        base_type = args[0]
×
50
        metadata = args[1:]
×
51

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

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

61
            return Pointer(elem_type)
×
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
    # Handle a parametrized numpy dtype generic, e.g. numpy.dtype[numpy.float64]
72
    # (produced by npt.NDArray[RealT] -> ndarray[Any, dtype[float64]]).
73
    if get_origin(dtype) is np.dtype:
4✔
74
        inner = get_args(dtype)
×
75
        if inner:
×
76
            return _map_python_type(inner[0])
×
77

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

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

107
    return dtype
×
108

109

110
class PythonProgram(DoccProgram):
4✔
111

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

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

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

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

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

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

165
        return res
4✔
166

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

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

184
        # When binary reuse is requested, the build run must persist the
185
        # normalized SDFG (py4.norm.json) so a later run can reload it without
186
        # re-parsing/recompiling. Force the dump if instrumentation/capture
187
        # would not already produce it.
188
        docc_reuse_binaries = os.environ.get("DOCC_REUSE_BINARIES")
4✔
189
        if docc_reuse_binaries and not self.debug_dump:
4✔
190
            self.debug_dump = True
×
191

192
        # 1. Analyze arguments and shapes
193
        arg_types = []
4✔
194
        shape_values = []  # List of unique shape values found
4✔
195
        shape_sources = []  # List of (arg_idx, dim_idx) for each unique shape value
4✔
196

197
        # Mapping from (arg_idx, dim_idx) -> unique_shape_idx
198
        arg_shape_mapping = {}
4✔
199

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

212
        for i, arg in enumerate(args):
4✔
213
            t = self._infer_type(arg)
4✔
214
            arg_types.append(t)
4✔
215

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

228
                    arg_shape_mapping[(i, dim_idx)] = u_idx
4✔
229

230
        # 2. Signature - include scalar-shape equivalences for correct caching
231
        mapping_sig = sorted(arg_shape_mapping.items())
4✔
232
        type_sig = ", ".join(self._type_to_str(t) for t in arg_types)
4✔
233
        signature = f"{type_sig}|{mapping_sig}"
4✔
234

235
        # In-memory cache key: the structural signature plus the resolved compile
236
        # options, so repeated in-process compiles with different
237
        # instrumentation/arg-capture/remote-tuning do not alias to the first
238
        # built binary (the on-disk hash already accounts for these options).
239
        mem_cache_key = (
4✔
240
            f"{signature}|{capture_args}|{instrumentation_mode}|{remote_tuning}"
241
        )
242

243
        if output_folder is None:
4✔
244
            source_path = inspect.getsourcefile(self.func)
4✔
245
            hash_input = f"{source_path}|{self.name}|{self.target}|{self.category}|{capture_args}|{instrumentation_mode}|{remote_tuning}|{signature}".encode(
4✔
246
                "utf-8"
247
            )
248
            stable_id = hashlib.sha256(hash_input).hexdigest()[:16]
4✔
249
            filename = os.path.basename(inspect.getsourcefile(self.func))
4✔
250

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

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

265
        # 3. Reuse a previously built binary if requested and available.
266
        # Structure arguments need per-member layout info that is only produced
267
        # while parsing the kernel, so reuse is limited to plain array/scalar
268
        # kernels; anything else falls through to a full rebuild.
269
        has_struct_args = any(
4✔
270
            isinstance(t, Pointer)
271
            and t.has_pointee_type()
272
            and isinstance(t.pointee_type, Structure)
273
            for t in arg_types
274
        )
275
        if docc_reuse_binaries and not has_struct_args:
4✔
276
            reused = self._try_reuse_binary(output_folder, shape_sources)
×
277
            if reused is not None:
×
278
                if original_output_folder is None:
×
279
                    self.cache[mem_cache_key] = reused
×
280
                return reused
×
281

282
        # 4. Build SDFG
283
        if os.path.exists(output_folder):
4✔
284
            # Multiple python processes running the same code?
285
            shutil.rmtree(output_folder)
4✔
286
        sdfg, out_args, out_shapes, out_strides = self._build_sdfg(
4✔
287
            arg_types, args, arg_shape_mapping, shape_values
288
        )
289

290
        lib_path = self.sdfg_pipe(
4✔
291
            sdfg, output_folder, instrumentation_mode, capture_args, remote_tuning
292
        )
293

294
        # Persist the return-value layout so a later DOCC_REUSE_BINARIES run can
295
        # rebuild the CompiledSDFG without re-parsing the kernel.
296
        if output_folder:
4✔
297
            self._persist_return_layout(output_folder, sdfg, out_shapes, out_strides)
4✔
298

299
        # 5. Create CompiledSDFG
300
        compiled = CompiledSDFG(
4✔
301
            lib_path,
302
            sdfg,
303
            shape_sources,
304
            self._last_structure_member_info,
305
            out_args,
306
            out_shapes,
307
            out_strides,
308
            device_resident=self._device_resident,
309
            device_backend=self._device_backend,
310
            target=self.target,
311
        )
312

313
        # Cache if using default output folder
314
        if original_output_folder is None:
4✔
315
            self.cache[mem_cache_key] = compiled
4✔
316

317
        return compiled
4✔
318

319
    def _persist_return_layout(
4✔
320
        self, output_folder: str, sdfg: StructuredSDFG, out_shapes, out_strides
321
    ) -> None:
322
        """Stamp the return-value layout into the persisted SDFG metadata.
323

324
        The return shapes/strides are discovered while parsing the kernel and
325
        are not otherwise recoverable from the SDFG structure. Persisting them
326
        (into the same ``py4.norm.json`` the reuse path loads) lets a later
327
        ``DOCC_REUSE_BINARIES`` run reconstruct the CompiledSDFG without
328
        re-parsing/recompiling.
329
        """
330
        json_path = os.path.join(output_folder, f"{sdfg.name}.py4.norm.json")
4✔
331
        if not os.path.exists(json_path):
4✔
332
            return
4✔
UNCOV
333
        try:
×
UNCOV
334
            with open(json_path) as f:
×
UNCOV
335
                data = json.load(f)
×
UNCOV
336
            metadata = data.setdefault("metadata", {})
×
UNCOV
337
            metadata["output_shapes"] = json.dumps(out_shapes)
×
UNCOV
338
            metadata["output_strides"] = json.dumps(out_strides)
×
UNCOV
339
            with open(json_path, "w") as f:
×
UNCOV
340
                json.dump(data, f)
×
341
        except (OSError, ValueError):
×
342
            pass
×
343

344
    def _try_reuse_binary(
4✔
345
        self, output_folder: Optional[str], shape_sources
346
    ) -> Optional[CompiledSDFG]:
347
        """Reload a cached ``.so`` + normalized SDFG instead of recompiling.
348

349
        Mirrors the strictness of the pytorch/mlir binary-reuse path: when the
350
        cache directory does not exist yet this returns ``None`` so the caller
351
        performs a first build (no error); but when the directory *does* exist
352
        and a required artifact is missing, it raises ``ValueError`` so a broken
353
        or stale cache surfaces loudly instead of silently recompiling. The
354
        calling convention (device residency) and return-value layout are
355
        restored from the persisted SDFG metadata so arguments are marshalled
356
        exactly as they were at build time.
357
        """
358
        if not output_folder:
×
359
            return None
×
360

361
        # Cache directory absent -> first build. Let the caller build it; this
362
        # is the one case the mlir/pytorch frontends also treat as non-fatal.
363
        if not os.path.exists(output_folder):
×
364
            return None
×
365

366
        sdfg_name = f"{self.name}_sdfg"
×
367
        lib_path = os.path.join(output_folder, f"lib{sdfg_name}.so")
×
368
        json_path = os.path.join(output_folder, f"{sdfg_name}.py4.norm.json")
×
369
        if not os.path.exists(lib_path):
×
370
            raise ValueError(f"Tried reusing binary '{lib_path}' but does not exist")
×
371
        if not os.path.exists(json_path):
×
372
            raise ValueError(f"Tried loading SDFG '{json_path}' but does not exist")
×
373

374
        sdfg = StructuredSDFG.from_file(json_path)
×
375

376
        # Return arguments are recoverable directly from the SDFG signature.
377
        out_args = [name for name in sdfg.arguments if name.startswith("_docc_ret_")]
×
378

379
        # Return-value layout was persisted into the SDFG metadata at build time.
380
        out_shapes = {}
×
381
        out_strides = {}
×
382
        shapes_meta = sdfg.metadata("output_shapes")
×
383
        strides_meta = sdfg.metadata("output_strides")
×
384
        if shapes_meta:
×
385
            try:
×
386
                out_shapes = json.loads(shapes_meta)
×
387
            except ValueError:
×
388
                out_shapes = {}
×
389
        if strides_meta:
×
390
            try:
×
391
                out_strides = json.loads(strides_meta)
×
392
            except ValueError:
×
393
                out_strides = {}
×
394

395
        # Restore the device-residency calling convention chosen at compile time;
396
        # otherwise a device-resident binary would be fed host pointers.
397
        self._device_resident = sdfg.metadata("device_resident") == "1"
×
398
        backend = sdfg.metadata("device_backend")
×
399
        self._device_backend = backend or None
×
400

401
        return CompiledSDFG(
×
402
            lib_path,
403
            sdfg,
404
            shape_sources,
405
            {},
406
            out_args,
407
            out_shapes,
408
            out_strides,
409
            device_resident=self._device_resident,
410
            device_backend=self._device_backend,
411
            target=self.target,
412
        )
413

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

417
        # Build shape mapping
418
        shape_values = []
×
419
        shape_sources = []
×
420
        arg_shape_mapping = {}
×
421

422
        sig = inspect.signature(self.func)
×
423
        params = list(sig.parameters.items())
×
424
        scalar_int_params = {}
×
425
        for i, ((name, param), arg) in enumerate(zip(params, args)):
×
426
            if isinstance(arg, (int, np.integer)) and not isinstance(
×
427
                arg, (bool, np.bool_)
428
            ):
429
                val = int(arg)
×
430
                if val not in scalar_int_params:
×
431
                    scalar_int_params[val] = name
×
432

433
        for i, arg in enumerate(args):
×
434
            if isinstance(arg, np.ndarray):
×
435
                for dim_idx, dim_val in enumerate(arg.shape):
×
436
                    if dim_val in shape_values:
×
437
                        u_idx = shape_values.index(dim_val)
×
438
                    else:
439
                        u_idx = len(shape_values)
×
440
                        shape_values.append(dim_val)
×
441
                        shape_sources.append((i, dim_idx))
×
442
                    arg_shape_mapping[(i, dim_idx)] = u_idx
×
443

444
        sdfg, _, _, _ = self._build_sdfg(
×
445
            arg_types, args, arg_shape_mapping, shape_values
446
        )
447
        return sdfg
×
448

449
    def _convert_inputs(self, args: tuple) -> tuple:
4✔
450
        return args
×
451

452
    def _convert_outputs(self, result: Any, original_args: tuple) -> Any:
4✔
453
        return result
×
454

455
    def _get_signature(self, arg_types):
4✔
456
        return ", ".join(self._type_to_str(t) for t in arg_types)
×
457

458
    def _type_to_str(self, t):
4✔
459
        if isinstance(t, Scalar):
4✔
460
            return f"Scalar({t.primitive_type})"
4✔
461
        elif isinstance(t, Array):
4✔
462
            return f"Array({self._type_to_str(t.element_type)}, {t.num_elements})"
×
463
        elif isinstance(t, Pointer):
4✔
464
            return f"Pointer({self._type_to_str(t.pointee_type)})"
4✔
465
        elif isinstance(t, Structure):
4✔
466
            return f"Structure({t.name})"
4✔
467
        return str(t)
×
468

469
    def _infer_type(self, arg):
4✔
470
        if isinstance(arg, (float, np.float64)):
4✔
471
            return Scalar(PrimitiveType.Double)
4✔
472
        elif isinstance(arg, np.float32):
4✔
473
            return Scalar(PrimitiveType.Float)
4✔
474
        elif isinstance(arg, (bool, np.bool_)):
4✔
475
            return Scalar(PrimitiveType.Bool)
4✔
476
        elif isinstance(arg, (int, np.int64)):
4✔
477
            return Scalar(PrimitiveType.Int64)
4✔
478
        elif isinstance(arg, np.int32):
4✔
479
            return Scalar(PrimitiveType.Int32)
4✔
480
        elif isinstance(arg, np.int16):
4✔
481
            return Scalar(PrimitiveType.Int16)
×
482
        elif isinstance(arg, np.int8):
4✔
483
            return Scalar(PrimitiveType.Int8)
×
484
        elif isinstance(arg, np.uint64):
4✔
485
            return Scalar(PrimitiveType.UInt64)
×
486
        elif isinstance(arg, np.uint32):
4✔
487
            return Scalar(PrimitiveType.UInt32)
×
488
        elif isinstance(arg, np.uint16):
4✔
489
            return Scalar(PrimitiveType.UInt16)
×
490
        elif isinstance(arg, np.uint8):
4✔
491
            return Scalar(PrimitiveType.UInt8)
×
492
        elif isinstance(arg, np.ndarray):
4✔
493
            # Map dtype
494
            if arg.dtype == np.float64:
4✔
495
                elem_type = Scalar(PrimitiveType.Double)
4✔
496
            elif arg.dtype == np.float32:
4✔
497
                elem_type = Scalar(PrimitiveType.Float)
4✔
498
            elif arg.dtype == np.float16:
4✔
499
                elem_type = Scalar(PrimitiveType.Half)
×
500
            elif arg.dtype == ml_dtypes.bfloat16:
4✔
501
                elem_type = Scalar(PrimitiveType.BFloat)
4✔
502
            elif arg.dtype == np.bool_:
4✔
503
                elem_type = Scalar(PrimitiveType.Bool)
4✔
504
            elif arg.dtype == np.int64:
4✔
505
                elem_type = Scalar(PrimitiveType.Int64)
4✔
506
            elif arg.dtype == np.int32:
4✔
507
                elem_type = Scalar(PrimitiveType.Int32)
4✔
508
            elif arg.dtype == np.int16:
×
509
                elem_type = Scalar(PrimitiveType.Int16)
×
510
            elif arg.dtype == np.int8:
×
511
                elem_type = Scalar(PrimitiveType.Int8)
×
512
            elif arg.dtype == np.uint64:
×
513
                elem_type = Scalar(PrimitiveType.UInt64)
×
514
            elif arg.dtype == np.uint32:
×
515
                elem_type = Scalar(PrimitiveType.UInt32)
×
516
            elif arg.dtype == np.uint16:
×
517
                elem_type = Scalar(PrimitiveType.UInt16)
×
518
            elif arg.dtype == np.uint8:
×
519
                elem_type = Scalar(PrimitiveType.UInt8)
×
520
            else:
521
                raise ValueError(f"Unsupported numpy dtype: {arg.dtype}")
×
522

523
            return Pointer(elem_type)
4✔
524
        elif isinstance(arg, str):
4✔
525
            # Explicitly reject strings - they are not supported
526
            raise ValueError(f"Unsupported argument type: {type(arg)}")
4✔
527
        else:
528
            # Check if it's a class instance
529
            if hasattr(arg, "__class__") and not isinstance(arg, type):
4✔
530
                # It's an instance of a class, return pointer to Structure
531
                return Pointer(Structure(arg.__class__.__name__))
4✔
532
            raise ValueError(f"Unsupported argument type: {type(arg)}")
×
533

534
    def _build_sdfg(
4✔
535
        self,
536
        arg_types,
537
        args,
538
        arg_shape_mapping,
539
        shape_values,
540
    ):
541
        sig = inspect.signature(self.func)
4✔
542

543
        # Handle return type - always void for SDFG, output args used for returns
544
        return_type = Scalar(PrimitiveType.Void)
4✔
545
        infer_return_type = True
4✔
546

547
        # Parse return annotation to determine output arguments if possible
548
        explicit_returns = []
4✔
549
        if sig.return_annotation is not inspect.Signature.empty:
4✔
550
            infer_return_type = False
4✔
551

552
            # Helper to normalize annotation to list of types
553
            def normalize_annotation(ann):
4✔
554
                # Handle Tuple[type, ...]
555
                origin = get_origin(ann)
4✔
556
                if origin is tuple:
4✔
557
                    type_args = get_args(ann)
×
558
                    # Tuple[()] or Tuple w/o args
559
                    if not type_args:
×
560
                        return []
×
561
                    # Tuple[int, float]
562
                    if len(type_args) > 0 and type_args[-1] is not Ellipsis:
×
563
                        return [_map_python_type(t) for t in type_args]
×
564
                    # Tuple[int, ...] - not supported for fixed number of returns yet?
565
                    # For now assume fixed tuple
566
                    return [_map_python_type(t) for t in type_args]
×
567
                else:
568
                    return [_map_python_type(ann)]
4✔
569

570
            explicit_returns = normalize_annotation(sig.return_annotation)
4✔
571
            for rt in explicit_returns:
4✔
572
                if not isinstance(rt, Type):
4✔
573
                    # Fallback if map failed (e.g. invalid annotation)
574
                    infer_return_type = True
×
575
                    explicit_returns = []
×
576
                    break
×
577

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

580
        # Add pre-defined return arguments if we know them
581
        if not infer_return_type:
4✔
582
            for i, dtype in enumerate(explicit_returns):
4✔
583
                # Scalar -> Pointer(Scalar)
584
                # Array -> Already Pointer(Scalar). Keep it.
585
                arg_type = dtype
4✔
586
                if isinstance(dtype, Scalar):
4✔
587
                    arg_type = Pointer(dtype)
4✔
588

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

591
        # Register structure types for any class arguments
592
        # Also track member name to index mapping for each structure
593
        structures_to_register = {}
4✔
594
        structure_member_info = {}  # Maps struct_name -> {member_name: (index, type)}
4✔
595
        for i, (arg, dtype) in enumerate(zip(args, arg_types)):
4✔
596
            if isinstance(dtype, Pointer) and dtype.has_pointee_type():
4✔
597
                pointee = dtype.pointee_type
4✔
598
                if isinstance(pointee, Structure):
4✔
599
                    struct_name = pointee.name
4✔
600
                    if struct_name not in structures_to_register:
4✔
601
                        # Get class from arg to introspect members
602
                        if hasattr(arg, "__dict__"):
4✔
603
                            # Use __dict__ to get only instance attributes
604
                            # Sort by name to ensure consistent ordering
605
                            # Note: This alphabetical ordering is used to define the
606
                            # structure layout and must match the order expected by
607
                            # the backend code generation
608
                            member_types = []
4✔
609
                            member_names = []
4✔
610
                            member_shapes = []
4✔
611
                            for attr_name, attr_value in sorted(arg.__dict__.items()):
4✔
612
                                if not attr_name.startswith("_"):
4✔
613
                                    # Infer member type from instance attribute
614
                                    # Check bool before int since bool is subclass of int
615
                                    member_type = None
4✔
616
                                    member_shape = None
4✔
617
                                    if isinstance(attr_value, bool):
4✔
618
                                        member_type = Scalar(PrimitiveType.Bool)
×
619
                                    elif isinstance(attr_value, (int, np.int64)):
4✔
620
                                        member_type = Scalar(PrimitiveType.Int64)
4✔
621
                                    elif isinstance(attr_value, (float, np.float64)):
4✔
622
                                        member_type = Scalar(PrimitiveType.Double)
4✔
623
                                    elif isinstance(attr_value, np.int32):
4✔
624
                                        member_type = Scalar(PrimitiveType.Int32)
×
625
                                    elif isinstance(attr_value, np.float32):
4✔
626
                                        member_type = Scalar(PrimitiveType.Float)
×
627
                                    elif isinstance(attr_value, np.ndarray):
4✔
628
                                        # Array member: stored as a pointer field
629
                                        # (struct-of-arrays). Record the concrete
630
                                        # shape so attribute access can build a
631
                                        # tensor view over the member pointer.
632
                                        member_type = self._infer_type(attr_value)
4✔
633
                                        member_shape = [
4✔
634
                                            str(int(s)) for s in attr_value.shape
635
                                        ]
636
                                    # TODO: Consider using np.integer and np.floating abstract types
637
                                    # for more comprehensive numpy type coverage
638
                                    # TODO: Add support for nested structures
639

640
                                    if member_type is not None:
4✔
641
                                        member_types.append(member_type)
4✔
642
                                        member_names.append(attr_name)
4✔
643
                                        member_shapes.append(member_shape)
4✔
644

645
                            if member_types:
4✔
646
                                structures_to_register[struct_name] = member_types
4✔
647
                                # Build member name to (index, type, shape) mapping.
648
                                # shape is None for scalar members and a list of
649
                                # dimension-size strings for array members.
650
                                structure_member_info[struct_name] = {
4✔
651
                                    name: (idx, mtype, shape)
652
                                    for idx, (name, mtype, shape) in enumerate(
653
                                        zip(member_names, member_types, member_shapes)
654
                                    )
655
                                }
656

657
        # Store structure_member_info for later use in CompiledSDFG
658
        self._last_structure_member_info = structure_member_info
4✔
659

660
        # Register all discovered structures with the builder
661
        for struct_name, member_types in structures_to_register.items():
4✔
662
            builder.add_structure(struct_name, member_types)
4✔
663

664
        # Register arguments
665
        params = list(sig.parameters.items())
4✔
666
        if len(params) != len(arg_types):
4✔
667
            raise ValueError(
×
668
                f"Argument count mismatch: expected {len(params)}, got {len(arg_types)}"
669
            )
670

671
        # Add regular arguments
672
        tensor_table = {}
4✔
673
        for i, ((name, param), dtype, arg) in enumerate(zip(params, arg_types, args)):
4✔
674
            builder.add_container(name, dtype, is_argument=True)
4✔
675

676
            # Store layout information for arrays
677
            if isinstance(arg, np.ndarray):
4✔
678
                element_type = element_type_from_sdfg_type(dtype)
4✔
679

680
                shapes = []
4✔
681
                for dim_idx in range(arg.ndim):
4✔
682
                    dim_val = arg.shape[dim_idx]
4✔
683
                    if dim_val == 1:
4✔
684
                        # Always use literal "1" for size-1 dimensions to enable
685
                        # proper broadcasting detection
686
                        shapes.append("1")
4✔
687
                    else:
688
                        u_idx = arg_shape_mapping[(i, dim_idx)]
4✔
689
                        shapes.append(f"_s{u_idx}")
4✔
690

691
                strides = []
4✔
692
                if arg.flags["C_CONTIGUOUS"]:
4✔
693
                    # Row-major: stride[i] = product of shapes[i+1:]
694
                    for dim_idx in range(arg.ndim):
4✔
695
                        if dim_idx == arg.ndim - 1:
4✔
696
                            strides.append("1")
4✔
697
                        else:
698
                            suffix_shapes = shapes[dim_idx + 1 :]
4✔
699
                            if len(suffix_shapes) == 1:
4✔
700
                                strides.append(suffix_shapes[0])
4✔
701
                            else:
702
                                strides.append("(" + " * ".join(suffix_shapes) + ")")
4✔
703
                elif arg.flags["F_CONTIGUOUS"]:
4✔
704
                    # Column-major: stride[i] = product of shapes[:i]
705
                    for dim_idx in range(arg.ndim):
4✔
706
                        if dim_idx == 0:
4✔
707
                            strides.append("1")
4✔
708
                        else:
709
                            prefix_shapes = shapes[:dim_idx]
4✔
710
                            if len(prefix_shapes) == 1:
4✔
711
                                strides.append(prefix_shapes[0])
4✔
712
                            else:
713
                                strides.append("(" + " * ".join(prefix_shapes) + ")")
4✔
714
                else:
715
                    # Non-contiguous: use actual stride values
716
                    for dim_idx in range(arg.ndim):
4✔
717
                        stride_val = arg.strides[dim_idx] // arg.itemsize
4✔
718
                        strides.append(f"{stride_val}")
4✔
719

720
                offset = "0"
4✔
721
                tensor_table[name] = Tensor(element_type, shapes, strides, offset)
4✔
722

723
            elif isinstance(arg, np.generic):
4✔
724
                # NumPy scalar types (np.float64, np.int32, etc.) should be treated
725
                # as 0-d arrays for type promotion purposes - they trigger full
726
                # promotion, unlike Python literals which adapt to the array dtype
727
                element_type = element_type_from_sdfg_type(dtype)
4✔
728
                tensor_table[name] = Tensor(element_type, [], [], "0")
4✔
729

730
        # Add unified shape arguments only for shapes without scalar equivalents
731
        # and skip size-1 dimensions (they use literal "1" instead)
732
        for i in range(len(shape_values)):
4✔
733
            if shape_values[i] != 1:
4✔
734
                builder.add_container(
4✔
735
                    f"_s{i}", Scalar(PrimitiveType.Int64), is_argument=True
736
                )
737
                builder.add_assumption_lb(f"_s{i}", "1")  # Shapes must be positive
4✔
738
                builder.add_assumption_const(f"_s{i}", True)  # Shapes are constant
4✔
739

740
        # Create symbol table for parser
741
        container_table = {}
4✔
742
        for i, ((name, param), dtype, arg) in enumerate(zip(params, arg_types, args)):
4✔
743
            container_table[name] = dtype
4✔
744

745
        for i in range(len(shape_values)):
4✔
746
            if shape_values[i] != 1:
4✔
747
                container_table[f"_s{i}"] = Scalar(PrimitiveType.Int64)
4✔
748

749
        # Parse AST
750
        source_lines, start_line = inspect.getsourcelines(self.func)
4✔
751
        source = textwrap.dedent("".join(source_lines))
4✔
752
        tree = ast.parse(source)
4✔
753
        ast.increment_lineno(tree, start_line - 1)
4✔
754
        func_def = tree.body[0]
4✔
755

756
        filename = inspect.getsourcefile(self.func)
4✔
757
        function_name = self.func.__name__
4✔
758

759
        # Combine globals with closure variables (closure takes precedence)
760
        combined_globals = dict(self.func.__globals__)
4✔
761
        if self.func.__closure__ is not None and self.func.__code__.co_freevars:
4✔
762
            for name, cell in zip(
4✔
763
                self.func.__code__.co_freevars, self.func.__closure__
764
            ):
765
                combined_globals[name] = cell.cell_contents
4✔
766

767
        parser = ASTParser(
4✔
768
            builder,
769
            tensor_table,
770
            container_table,
771
            filename,
772
            function_name,
773
            infer_return_type=infer_return_type,
774
            globals_dict=combined_globals,
775
            structure_member_info=structure_member_info,
776
        )
777
        for node in func_def.body:
4✔
778
            parser.visit(node)
4✔
779

780
        # Emit hoisted allocations at function entry
781
        parser.memory_handler.emit_allocations()
4✔
782

783
        sdfg = builder.move()
4✔
784
        # Mark return arguments metadata
785
        out_args = []
4✔
786
        for name in sdfg.arguments:
4✔
787
            if name.startswith("_docc_ret_"):
4✔
788
                out_args.append(name)
4✔
789

790
        return (
4✔
791
            sdfg,
792
            out_args,
793
            parser.captured_return_shapes,
794
            parser.captured_return_strides,
795
        )
796

797

798
def native(
4✔
799
    func=None,
800
    *,
801
    target="none",
802
    category="server",
803
    instrumentation_mode=None,
804
    capture_args=None,
805
    remote_tuning=False,
806
):
807
    """Decorator to create a PythonProgram from a Python function.
808

809
    Example:
810
        @native
811
        def my_function(x: np.ndarray) -> np.ndarray:
812
            return x * 2
813

814
        result = my_function(np.array([1.0, 2.0, 3.0]))
815
    """
816
    if func is None:
4✔
817
        return lambda f: PythonProgram(
4✔
818
            f,
819
            target=target,
820
            category=category,
821
            instrumentation_mode=instrumentation_mode,
822
            capture_args=capture_args,
823
            remote_tuning=remote_tuning,
824
        )
825
    return PythonProgram(
4✔
826
        func,
827
        target=target,
828
        category=category,
829
        instrumentation_mode=instrumentation_mode,
830
        capture_args=capture_args,
831
        remote_tuning=remote_tuning,
832
    )
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