• 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

69.14
/python/docc/compiler/docc_program.py
1
from abc import ABC, abstractmethod
4✔
2
import sys
4✔
3
from typing import Any, Dict, Optional
4✔
4
import json
4✔
5
import os
4✔
6
import re
4✔
7

8
from docc.sdfg import StructuredSDFG, TargetOptions
4✔
9
from docc.sdfg._sdfg import (
4✔
10
    _enable_statistics,
11
    _statistics_enabled_by_env,
12
    _statistics_summary,
13
)
14
from docc.compiler.compiled_sdfg import CompiledSDFG
4✔
15
from docc.compiler.target_registry import (
4✔
16
    get_target_schedule_fn,
17
    get_target_compile_fn,
18
    get_target_expand_fn,
19
    register_target_overrides,
20
)
21

22

23
def _parse_docc_debug() -> dict[str, str]:
4✔
24
    debug_env = os.environ.get("DOCC_DEBUG", "")
4✔
25
    debug_dict = {}
4✔
26
    if debug_env:
4✔
27
        for entry in re.split(r"[;:]", debug_env):
×
28
            if not entry:
×
29
                continue
×
30
            parts = entry.split("=", 1)
×
31
            key = parts[0].strip()
×
32
            value = parts[1].strip() if len(parts) > 1 else ""
×
33
            debug_dict[key] = value
×
34
    return debug_dict
4✔
35

36

37
def _is_debug_dump(flags: dict[str, str]) -> bool:
4✔
38
    return "dump" in flags
4✔
39

40

41
def _is_debug_compile(flags: dict[str, str]) -> bool:
4✔
42
    return "build" in flags
4✔
43

44

45
def _get_build_thread_count(flags: dict[str, str]) -> int:
4✔
46
    return int(flags.get("build_threads", "0"))
4✔
47

48

49
class DoccProgram(ABC):
4✔
50

51
    def __init__(
4✔
52
        self,
53
        name: str,
54
        target: str = "none",
55
        category: str = "server",
56
        instrumentation_mode: Optional[str] = None,
57
        capture_args: Optional[bool] = None,
58
        remote_tuning: bool = False,
59
    ):
60
        self.name = name
4✔
61
        self.target = target
4✔
62
        self.category = category
4✔
63
        self.remote_tuning = remote_tuning
4✔
64
        self.last_sdfg: Optional[StructuredSDFG] = None
4✔
65
        self._device_resident: bool = False
4✔
66
        self._device_backend: Optional[str] = None
4✔
67
        self.cache: dict = {}
4✔
68
        debug_flags = _parse_docc_debug()
4✔
69
        self.debug_dump: bool = _is_debug_dump(debug_flags)
4✔
70
        self.debug_build: bool = _is_debug_compile(debug_flags)
4✔
71
        self.build_thread_count: int = _get_build_thread_count(debug_flags)
4✔
72

73
        # Check environment variable DOCC_CI
74
        docc_ci = os.environ.get("DOCC_CI", "")
4✔
75
        if docc_ci:
4✔
76
            if docc_ci == "regions":
×
77
                if instrumentation_mode is None:
×
78
                    instrumentation_mode = "ols"
×
79
            elif docc_ci == "arg-capture":
×
80
                if capture_args is None:
×
81
                    capture_args = True
×
82
            else:
83
                # Full mode (or unknown value treated as full)
84
                if instrumentation_mode is None:
×
85
                    instrumentation_mode = "ols"
×
86
                if capture_args is None:
×
87
                    capture_args = True
×
88

89
        self.instrumentation_mode = instrumentation_mode
4✔
90
        self.capture_args = capture_args
4✔
91

92
    @abstractmethod
4✔
93
    def __call__(self, *args: Any) -> Any:
4✔
94
        pass
×
95

96
    @abstractmethod
4✔
97
    def compile(self, *args: Any, output_folder: Optional[str] = None) -> CompiledSDFG:
4✔
98
        pass
×
99

100
    def _resolve_compile_options(
4✔
101
        self,
102
        instrumentation_mode: Optional[str] = None,
103
        capture_args: Optional[bool] = None,
104
        remote_tuning: Optional[bool] = None,
105
    ) -> tuple[str, bool, bool]:
106
        """Resolve compile-time options, falling back to instance defaults and env vars."""
107
        if instrumentation_mode is None:
4✔
108
            instrumentation_mode = self.instrumentation_mode
4✔
109
        if capture_args is None:
4✔
110
            capture_args = self.capture_args
4✔
111
        if remote_tuning is None:
4✔
112
            remote_tuning = self.remote_tuning
4✔
113

114
        # Check environment variable DOCC_CI
115
        docc_ci = os.environ.get("DOCC_CI", "")
4✔
116
        if docc_ci:
4✔
117
            if docc_ci == "regions":
×
118
                if instrumentation_mode is None:
×
119
                    instrumentation_mode = "ols"
×
120
            elif docc_ci == "arg-capture":
×
121
                if capture_args is None:
×
122
                    capture_args = True
×
123
            else:
124
                # Full mode (or unknown value treated as full)
125
                if instrumentation_mode is None:
×
126
                    instrumentation_mode = "ols"
×
127
                if capture_args is None:
×
128
                    capture_args = True
×
129

130
        # Defaults
131
        if instrumentation_mode is None:
4✔
132
            instrumentation_mode = ""
4✔
133
        if capture_args is None:
4✔
134
            capture_args = False
4✔
135

136
        return instrumentation_mode, capture_args, remote_tuning
4✔
137

138
    def sdfg_pipe(
4✔
139
        self,
140
        sdfg: StructuredSDFG,
141
        output_folder: Optional[str],
142
        instrumentation_mode: str,
143
        capture_args: bool,
144
        remote_tuning: Optional[bool] = None,
145
        reuse_sources: bool = False,
146
    ) -> str:
147

148
        if not reuse_sources and output_folder:
4✔
149
            if self.debug_dump:
4✔
150
                sdfg.dump(output_folder, "py0.parsed", dump_dot=True)
×
151

152
            if not output_folder is None:
4✔
153
                sdfg.output_dir = output_folder
4✔
154

155
            # Enable statistics if envvar is set
156
            if _statistics_enabled_by_env():
4✔
157
                _enable_statistics()
×
158

159
            sdfg.validate()
4✔
160

161
            if remote_tuning is None:
4✔
162
                remote_tuning = self.remote_tuning
×
163

164
            target_options = TargetOptions()
4✔
165
            target_options.target = self.target
4✔
166
            target_options.category = self.category
4✔
167
            target_options.remote_tuning = remote_tuning
4✔
168

169
            # Einsum detection
170
            sdfg.einsum()
4✔
171
            if self.debug_dump:
4✔
172
                sdfg.dump(output_folder, "py1.einsum", dump_dot=True)
×
173

174
            # Tensor targets keep tensor nodes
175
            custom_expand_fn = get_target_expand_fn(self.target)
4✔
176
            if custom_expand_fn is not None:
4✔
177
                custom_expand_fn(sdfg, self.category, {})
4✔
178
            else:
179
                sdfg.expand(target_options)
4✔
180
            if self.debug_dump:
4✔
181
                sdfg.dump(output_folder, "py2.expanded", dump_dot=True)
×
182

183
            # Simplify pipelines
184
            sdfg.simplify()
4✔
185
            if self.debug_dump:
4✔
186
                sdfg.dump(output_folder, "py3.opt", dump_dot=True)
×
187

188
            # Normalization for scheduling
189
            if self.target != "none":
4✔
190
                sdfg.normalize()
4✔
191

192
            if self.debug_dump:
4✔
UNCOV
193
                sdfg.dump(
×
194
                    output_folder,
195
                    "py4.norm",
196
                    dump_dot=True,
197
                )
198

199
            # Schedule if target is specified
200

201
            custom_schedule_fn = get_target_schedule_fn(self.target)
4✔
202
            if custom_schedule_fn is not None:
4✔
203
                custom_schedule_fn(
4✔
204
                    sdfg, self.category, {"remote_tuning": remote_tuning}
205
                )
206
            else:
207
                sdfg.schedule(target_options)
4✔
208

209
            if self.debug_dump or instrumentation_mode or capture_args:
4✔
210
                sdfg.dump(
4✔
211
                    output_folder,
212
                    "py5.post_sched",
213
                    dump_dot=True,
214
                    dump_json=True,
215
                    record_for_instrumentation=True,
216
                )
217

218
        # Promote pointer arguments to device residency when the whole program keeps
219
        # data on device. Communicated explicitly via the pass return value (bool),
220
        # not through SDFG metadata.
221
        self._device_resident = False
4✔
222
        self._device_backend = None
4✔
223
        if self.target in ("cuda", "rocm"):
4✔
224
            if sdfg.promote_device_residency(self.target == "rocm"):
×
225
                self._device_resident = True
×
226
                self._device_backend = self.target
×
227

228
        self.last_sdfg = sdfg
4✔
229

230
        custom_compile_fn = get_target_compile_fn(self.target)
4✔
231
        if custom_compile_fn is not None:
4✔
232
            lib_path = custom_compile_fn(
4✔
233
                sdfg,
234
                output_folder,
235
                instrumentation_mode,
236
                capture_args,
237
                {"debug_build": self.debug_build, "threads": self.build_thread_count},
238
            )
239
        else:
240
            lib_path = sdfg._compile(
4✔
241
                output_folder=output_folder,
242
                target=self.target,
243
                instrumentation_mode=instrumentation_mode,
244
                capture_args=capture_args,
245
                debug_build=self.debug_build,
246
                threads=self.build_thread_count,
247
                reuse_sources=reuse_sources,
248
            )
249

250
        # Dump statistics after compile
251
        if _statistics_enabled_by_env():
4✔
252
            print(_statistics_summary(), file=sys.stderr)
×
253

254
        # Record the device-residency decision in the persisted (py4.norm) SDFG
255
        # metadata. It is computed here (not stored in metadata by the pass) and
256
        # decides host vs device argument marshalling. Binary-reuse paths
257
        # (DOCC_REUSE_BINARIES) load only the cached .so + normalized SDFG and
258
        # never re-run scheduling/promotion, so without this they default to
259
        # host execution and feed host pointers into a device-resident binary
260
        # -> heap corruption / double free.
261
        if output_folder:
4✔
262
            self._persist_device_residency(output_folder, sdfg)
4✔
263

264
        return lib_path
4✔
265

266
    def _persist_device_residency(
4✔
267
        self, output_folder: str, sdfg: StructuredSDFG
268
    ) -> None:
269
        """Stamp the device-residency decision into the persisted SDFG metadata.
270

271
        Patches only the ``metadata`` object of the already-written
272
        ``py4.norm.json`` (the file the reuse path loads), leaving the SDFG
273
        structure and element IDs untouched so instrumentation references stay
274
        valid.
275
        """
276
        json_path = os.path.join(output_folder, f"{sdfg.name}.py4.norm.json")
4✔
277
        try:
4✔
278
            with open(json_path) as f:
4✔
UNCOV
279
                data = json.load(f)
×
UNCOV
280
            metadata = data.setdefault("metadata", {})
×
UNCOV
281
            metadata["device_resident"] = "1" if self._device_resident else "0"
×
UNCOV
282
            metadata["device_backend"] = self._device_backend or ""
×
UNCOV
283
            with open(json_path, "w") as f:
×
UNCOV
284
                json.dump(data, f)
×
285
        except (OSError, ValueError):
4✔
286
            pass
4✔
287

288
    @abstractmethod
4✔
289
    def to_sdfg(self, *args: Any) -> StructuredSDFG:
4✔
290
        pass
×
291

292
    @abstractmethod
4✔
293
    def _convert_inputs(self, args: tuple) -> tuple:
4✔
294
        pass
×
295

296
    @abstractmethod
4✔
297
    def _convert_outputs(self, result: Any, original_args: tuple) -> Any:
4✔
298
        pass
×
299

300
    def _get_cache_key(self, *args: Any) -> str:
4✔
301
        return ""
×
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