diffusers-dynamic-offloader 0.1.0rc2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. ddo_native_check.py +44 -0
  2. ddo_vmm_bootstrap.py +142 -0
  3. diffusers_dynamic_offloader/__init__.py +116 -0
  4. diffusers_dynamic_offloader/allocation_diagnostics.py +96 -0
  5. diffusers_dynamic_offloader/auxiliary_sources.py +126 -0
  6. diffusers_dynamic_offloader/backend.py +166 -0
  7. diffusers_dynamic_offloader/device_cache.py +60 -0
  8. diffusers_dynamic_offloader/dynamic_offload.py +3919 -0
  9. diffusers_dynamic_offloader/float8_compile.py +77 -0
  10. diffusers_dynamic_offloader/float8_loading.py +130 -0
  11. diffusers_dynamic_offloader/host_cache.py +101 -0
  12. diffusers_dynamic_offloader/host_memory.py +70 -0
  13. diffusers_dynamic_offloader/linear_convolution.py +105 -0
  14. diffusers_dynamic_offloader/metrics.py +217 -0
  15. diffusers_dynamic_offloader/metrics_journal.py +66 -0
  16. diffusers_dynamic_offloader/operator_diagnostics.py +167 -0
  17. diffusers_dynamic_offloader/profiles.py +495 -0
  18. diffusers_dynamic_offloader/quantized_sources.py +58 -0
  19. diffusers_dynamic_offloader/timing.py +129 -0
  20. diffusers_dynamic_offloader/vmm_model_arena.py +277 -0
  21. diffusers_dynamic_offloader/vmm_weight_store.py +840 -0
  22. diffusers_dynamic_offloader/weight_source_metadata.py +81 -0
  23. diffusers_dynamic_offloader/windows_file_reader.py +106 -0
  24. diffusers_dynamic_offloader-0.1.0rc2.dist-info/METADATA +90 -0
  25. diffusers_dynamic_offloader-0.1.0rc2.dist-info/RECORD +28 -0
  26. diffusers_dynamic_offloader-0.1.0rc2.dist-info/WHEEL +5 -0
  27. diffusers_dynamic_offloader-0.1.0rc2.dist-info/licenses/LICENSE +201 -0
  28. diffusers_dynamic_offloader-0.1.0rc2.dist-info/top_level.txt +3 -0
@@ -0,0 +1,217 @@
1
+ """Stable, runner-neutral reports for Dynamic Offload execution.
2
+
3
+ The library owns the meaning and schema of its telemetry. Hosts may render or
4
+ persist this object, but must not inspect hook state or VMM implementation
5
+ attributes directly.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from copy import deepcopy
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Mapping
13
+
14
+ DYNAMIC_OFFLOAD_METRICS_SCHEMA_VERSION = 1
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class DynamicOffloadMetrics:
19
+ """A serializable snapshot of one DDO component route.
20
+
21
+ ``configuration`` describes the resolved request, ``setup`` captures the
22
+ apply operation, and ``runtime`` is populated from a hook when one exists.
23
+ Values are deliberately ordinary Python data so JSON writers and host
24
+ trackers can consume them without importing DDO internals.
25
+ """
26
+
27
+ route: str
28
+ configuration: Mapping[str, Any] = field(default_factory=dict)
29
+ setup: Mapping[str, Any] = field(default_factory=dict)
30
+ runtime: Mapping[str, Any] = field(default_factory=dict)
31
+
32
+ @property
33
+ def schema_version(self) -> int:
34
+ return DYNAMIC_OFFLOAD_METRICS_SCHEMA_VERSION
35
+
36
+ def as_dict(self) -> dict[str, Any]:
37
+ """Return a detached JSON-ready payload with a versioned schema."""
38
+ return {
39
+ "schema_version": self.schema_version,
40
+ "route": self.route,
41
+ "configuration": deepcopy(dict(self.configuration)),
42
+ "setup": deepcopy(dict(self.setup)),
43
+ "runtime": deepcopy(dict(self.runtime)),
44
+ }
45
+
46
+ def format_profile(self) -> str:
47
+ """Render the compact, stable summary used by ``--show-profile``."""
48
+ lines = [
49
+ "DDO profile",
50
+ f" schema={self.schema_version} route={self.route}",
51
+ ]
52
+ requested = self.configuration.get("dynamic_offload_requested_preset")
53
+ detachment = self.setup.get("auxiliary_source_detachment", {})
54
+ if detachment:
55
+ lines.append(f" auxiliary_source_detachment={detachment['status']} "
56
+ f"copied_bytes={detachment['copied_bytes']} "
57
+ "(CPU ownership only; commit recovery not proven)")
58
+ host_memory = self.setup.get("host_memory", {})
59
+ if host_memory:
60
+ host = host_memory.get("host", {})
61
+ storages = host_memory.get("cpu_storages", {})
62
+ lines.append(f" host_memory={host_memory['status']} phase={host_memory['phase']} "
63
+ f"private_bytes={host.get('process_private_bytes', 'unavailable')} "
64
+ f"cpu_storage_bytes={storages.get('unique_storage_bytes', 'unavailable')} "
65
+ "(phase observation, not a peak or allocation census)")
66
+ host_cache = self.setup.get("host_cache_release", {})
67
+ if host_cache:
68
+ delta = host_cache.get("allocator_bytes_delta")
69
+ lines.append(f" host_cache_release={host_cache['status']} phase={host_cache['phase']} "
70
+ f"allocator_bytes_delta={delta if delta is not None else 'unavailable'}")
71
+ source = self.setup.get("weight_source", {})
72
+ if source:
73
+ lines.append(f" weight_source={source.get('resolver', 'legacy_exact_names')} bound={source.get('bound', 0)} "
74
+ f"available={source.get('available', 0)} rejected={source.get('rejected_storage_groups', 0)} "
75
+ "(source metadata, not native execution support)")
76
+ capacity = self.setup.get("capacity_inspection", {})
77
+ if capacity:
78
+ lines.append(f" component={self.configuration.get('component', 'model')} metadata_only (not execution support)")
79
+ lines.append(f" selected_modules={capacity['selected_module_count']} "
80
+ f"aligned_payload_gib={capacity['selected_aligned_payload_bytes'] / 1024**3:.4f} "
81
+ f"nonselected_gib={capacity['nonselected_unique_parameter_bytes'] / 1024**3:.4f} "
82
+ f"shared_owner_gib={capacity['shared_selected_nonselected_bytes'] / 1024**3:.4f}")
83
+ effective = self.configuration.get("dynamic_offload_effective_preset")
84
+ mode = self.configuration.get("dynamic_offload_execution_mode")
85
+ if requested or effective or mode:
86
+ lines.append(f" preset={requested or 'none'} -> {effective or 'none'} mode={mode or 'none'}")
87
+
88
+ state = self.runtime.get("state", {})
89
+ component = self.runtime.get("component_ownership", {})
90
+ if component:
91
+ lines.append(f" experimental_component_ownership parameters={component['parameter_groups']} "
92
+ f"buffers={component['buffer_groups']} buffer_bytes={component['buffer_bytes']} "
93
+ f"units={component['execution_units']} lookahead={component['lookahead']}")
94
+ if state:
95
+ lines.append(
96
+ " modules="
97
+ f"{state.get('module_count', 0)} patched={state.get('patched_module_count', 0)} "
98
+ f"total_gb={state.get('total_gb', 0):.4f}"
99
+ )
100
+ planner = state.get("planner_decisions", {})
101
+ if "sdnq_pin_parameter_budget_bytes" in planner:
102
+ pinning = state.get("sdnq_parameter_pinning", {})
103
+ lines.append(
104
+ " sdnq_cpu_parameters="
105
+ f"pinned_gib={pinning.get('pinned_gb', 0):.4f} "
106
+ f"unpinned_gib={pinning.get('unpinned_gb', 0):.4f} "
107
+ f"pin_ceiling_gib={planner['sdnq_pin_parameter_budget_bytes'] / 1024**3:.4f} "
108
+ "(setup accounting, not GPU residency)"
109
+ )
110
+ vmm = self.runtime.get("vmm", {})
111
+ if vmm:
112
+ resident_bytes = vmm.get("fast_resident_bytes", vmm.get("arena_resident_bytes", 0))
113
+ materializations = vmm.get("fast_faults", vmm.get("arena_materializations", 0))
114
+ temporary = vmm.get("fast_temporary_tensors", vmm.get("arena_temporary_fallbacks", 0))
115
+ lines.append(
116
+ " vmm="
117
+ f"resident_gb={resident_bytes / 1024**3:.4f} "
118
+ f"materializations={materializations} "
119
+ f"temporary_fallbacks={temporary}"
120
+ )
121
+ timing = self.runtime.get("execution_timing", {})
122
+ allocation = self.runtime.get("allocation_diagnostics", {})
123
+ if allocation:
124
+ lines.append(f" allocation_diagnostics={allocation.get('status', 'unknown')} "
125
+ f"steps={len(allocation.get('steps', []))} "
126
+ "(native host calls, no boundary wait; diagnostic only)")
127
+ for step in allocation.get("steps", []):
128
+ counters = step.get("driver_delta", {})
129
+ values = " ".join(f"{name}_host_s={counters.get(name + '_host_seconds', 0):.6f}"
130
+ for name in ("create", "map", "access", "unmap", "release"))
131
+ for name in ("access_retry_sync", "fault_range"):
132
+ if name + "_host_seconds" in counters:
133
+ values += f" {name}_host_s={counters[name + '_host_seconds']:.6f}"
134
+ if "access_return_not_ready_calls" in counters:
135
+ values += f" access_not_ready_calls={counters['access_return_not_ready_calls']}"
136
+ lines.append(f" allocation_step={step['step_index'] + 1} "
137
+ f"host_submit_s={step['host_submission_seconds']:.6f} {values}")
138
+ operators = self.runtime.get('operator_diagnostics')
139
+ if operators:
140
+ lines.append(f" operator_diagnostics={operators['status']} "
141
+ f"samples={len(operators['samples'])} (sampled profiler; may synchronize; diagnostic only)")
142
+ for sample in operators['samples']:
143
+ lines.append(f" operator_invocation={sample['invocation_index'] + 1} "
144
+ f"host_forward_s={sample['host_forward_seconds']:.6f} "
145
+ f"profiler_stop_s={sample['profiler_stop_seconds']:.6f} "
146
+ f"device_events={sample['device_activity_events']} trace={sample['trace_path']}")
147
+ for category in ('top_host', 'top_device'):
148
+ for row in sample[category][:3]:
149
+ lines.append(f" {category}={row['name']} calls={row['calls']} "
150
+ f"self_host_s={row['self_host_seconds']:.6f} "
151
+ f"self_device_s={row['self_device_seconds']:.6f}")
152
+ pressure_prefix = "fast_source_cache_pressure_observation_"
153
+ if vmm.get(pressure_prefix + "schema_version") == 1:
154
+ reasons = {0: "none", 1: "ram", 2: "commit", 3: "ram_and_commit", 4: "observation_unavailable"}
155
+ reason = reasons.get(vmm.get(pressure_prefix + "last_reason"), "unknown")
156
+ lines.append(
157
+ " source_cache_pressure="
158
+ f"entries={vmm.get(pressure_prefix + 'entries', 0)} "
159
+ f"recoveries={vmm.get(pressure_prefix + 'recoveries', 0)} "
160
+ f"last_reason={reason} "
161
+ f"failed_observations={vmm.get(pressure_prefix + 'failed_observations', 0)}"
162
+ )
163
+ if timing:
164
+ lines.append(f" cuda_timing={timing.get('status', 'unknown')} scope={timing.get('scope', 'unknown')}")
165
+ diagnostic = timing.get("diagnostic_step_wait", {})
166
+ if diagnostic.get("enabled"):
167
+ lines.append(f" diagnostic_step_wait_calls={diagnostic['calls']} "
168
+ f"host_seconds={diagnostic['host_seconds']:.6f} (not a benchmark)")
169
+ if timing.get("status") == "complete":
170
+ lines.append(f" cuda_phase_seconds={timing['phase_seconds']:.6f} tail_seconds={timing['tail_seconds']:.6f}")
171
+ steady = timing.get("steady_state_seconds_per_step")
172
+ if steady is not None:
173
+ lines.append(f" cuda_steady_state_seconds_per_step={steady:.6f}")
174
+ collection = self.runtime.get("completion_collection", {})
175
+ timeline = self.runtime.get("native_timeline", {})
176
+ if timeline:
177
+ lines.append(f" native_timeline={timeline.get('status', 'unknown')} "
178
+ f"samples={len(timeline.get('samples', []))} "
179
+ f"dropped={timeline.get('dropped', 0)} (stream windows, not engine activity)")
180
+ release_seconds = vmm.get("fast_torch_allocator_cache_eviction_sync_seconds")
181
+ memory = []
182
+ for name, label in (("live_mapped_bytes", "live_gib"),
183
+ ("cached_mapped_bytes", "cached_gib")):
184
+ value = vmm.get(f"fast_torch_allocator_{name}")
185
+ if value is not None:
186
+ memory.append(f"{label}={value / 1024**3:.4f}")
187
+ if memory:
188
+ lines.append(" torch_allocator=" + " ".join(memory)
189
+ + " (process ledger snapshot, not GPU total/peak)")
190
+ footprint = []
191
+ for name, label in (("requested", "requested_gib"),
192
+ ("granularity_padding", "padding_gib"),
193
+ ("reuse_excess", "reuse_excess_gib")):
194
+ value = vmm.get(f"fast_torch_allocator_footprint_{name}_bytes")
195
+ if value is not None:
196
+ footprint.append(f"{label}={value / 1024**3:.4f}")
197
+ if footprint:
198
+ lines.append(" torch_allocation_footprint=" + " ".join(footprint)
199
+ + " (atomic live ledger, not GPU total/peak)")
200
+ pool_mapped = vmm.get("fast_torch_allocator_pool_mapped_bytes")
201
+ if pool_mapped is not None:
202
+ pool = []
203
+ for name in ("mapped", "requested", "leased", "available", "pending", "quarantined"):
204
+ value = vmm.get(f"fast_torch_allocator_pool_{name}_bytes")
205
+ if value is not None:
206
+ pool.append(f"{name}_gib={value / 1024**3:.4f}")
207
+ lines.append(" torch_span_pool=" + " ".join(pool)
208
+ + " (unique backing snapshot, not GPU total/peak)")
209
+ if release_seconds is not None:
210
+ lines.append(
211
+ f" torch_cache_eviction_sync_seconds={release_seconds:.6f} "
212
+ f"attempts={vmm.get('fast_torch_allocator_cache_eviction_attempts', 0)} "
213
+ "(process lifetime, host time)"
214
+ )
215
+ if collection.get("status") == "collected":
216
+ lines.append(f" source_tickets={collection['tickets_before']} -> {collection['tickets_after']} (nonblocking collection)")
217
+ return "\n".join(lines)
@@ -0,0 +1,66 @@
1
+ """Opt-in durable partial reports without CUDA timing/completion collection."""
2
+ import json
3
+ import os
4
+ import time
5
+ import uuid
6
+ from pathlib import Path
7
+
8
+
9
+ class DynamicOffloadMetricsJournal:
10
+ """Persist public snapshots; step boundaries do not prove GPU completion.
11
+
12
+ Each record is immutable and separately published. Killing the process may
13
+ leave a temporary file, but cannot corrupt earlier published records. Native
14
+ statistics may contain pending work; the journal never collects or waits.
15
+ """
16
+
17
+ def __init__(self, result, directory, *, enabled=False):
18
+ self.enabled = enabled
19
+ self._result = result if enabled else None
20
+ self._directory = Path(directory) if enabled else None
21
+ self._started = time.perf_counter()
22
+ self._closed = False
23
+
24
+ def __enter__(self):
25
+ if self._closed:
26
+ raise RuntimeError("Metrics journal is closed")
27
+ return self
28
+
29
+ def __exit__(self, *exc):
30
+ self._result = None # Do not retain an unloaded model through diagnostics.
31
+ self._closed = True
32
+
33
+ def record(self, step_index=None):
34
+ """Return the published path, or None when disabled; never replace it."""
35
+ if self._closed:
36
+ raise RuntimeError("Metrics journal is closed")
37
+ if not self.enabled:
38
+ return None
39
+ if step_index is not None and (type(step_index) is not int or step_index < 0):
40
+ raise ValueError("Step index must be a non-negative integer or None")
41
+ name = 'before_denoise.json' if step_index is None else f'step_{step_index:04d}.json'
42
+ target = self._directory / name
43
+ if target.exists():
44
+ raise FileExistsError(target)
45
+ report = self._result.metrics_snapshot(collect_completed=False)
46
+ payload = {
47
+ 'schema_version': 1, 'observation': 'partial_host_step_boundary',
48
+ 'step_index': step_index, 'host_elapsed_seconds': time.perf_counter() - self._started,
49
+ 'gpu_completion_proven': False, 'completion_collection_requested': False,
50
+ 'metrics': report.as_dict(),
51
+ }
52
+ serialized = json.dumps(payload, indent=2, allow_nan=False)
53
+ self._directory.mkdir(parents=True, exist_ok=True)
54
+ temporary = self._directory / (name + '.' + uuid.uuid4().hex + '.tmp')
55
+ with temporary.open('x', encoding='utf-8') as handle:
56
+ handle.write(serialized)
57
+ handle.flush()
58
+ os.fsync(handle.fileno())
59
+ # Windows rename refuses existing destinations. POSIX hard-link creation
60
+ # supplies the same no-replacement, atomic publication guarantee.
61
+ if os.name == 'nt':
62
+ os.rename(temporary, target)
63
+ else:
64
+ os.link(temporary, target)
65
+ temporary.unlink()
66
+ return target
@@ -0,0 +1,167 @@
1
+ """Bounded, opt-in operator tracing; never an allocation or offload policy."""
2
+ from dataclasses import replace
3
+ from pathlib import Path
4
+ from threading import Lock
5
+ from time import perf_counter
6
+
7
+
8
+ _owner = Lock()
9
+
10
+
11
+ class DynamicOffloadOperatorDiagnostics:
12
+ """Profile selected invocations of one module and label its direct children.
13
+
14
+ Profiling may synchronize at start/stop and perturbs submission cadence.
15
+ It cannot establish uninstrumented performance or prove driver paging.
16
+ No input shapes, stacks, memory profiles or model tensors are retained.
17
+ Single-threaded, nonrecursive inference only; no concurrent profiler.
18
+ """
19
+
20
+ def __init__(self, *, enabled=False, module=None, module_path=None,
21
+ invocations=(0, 2), output_dir=None, use_cuda=True):
22
+ self.enabled, self.module, self.module_path = bool(enabled), module, module_path
23
+ self.invocations, self.output_dir = tuple(invocations), output_dir
24
+ self.use_cuda = bool(use_cuda)
25
+ self._used = self._finished = self._failed = False
26
+ self._hooks, self._samples = [], []
27
+ self._profiler = None
28
+ self._count = 0
29
+ self._root_active = False
30
+ self._ranges = {}
31
+ self._owns = False
32
+
33
+ def __enter__(self):
34
+ if self._used:
35
+ raise RuntimeError('Operator diagnostic scopes cannot be reused')
36
+ self._used = True
37
+ if not self.enabled:
38
+ return self
39
+ if (not self.module_path or not self.output_dir or not self.invocations
40
+ or len(self.invocations) > 4
41
+ or any(type(i) is not int or not 0 <= i <= 31 for i in self.invocations)
42
+ or len(set(self.invocations)) != len(self.invocations)):
43
+ raise ValueError('Specify one module path, output directory and 1..4 unique invocation indices in 0..31')
44
+ target = self.module.get_submodule(self.module_path)
45
+ if not _owner.acquire(blocking=False):
46
+ raise RuntimeError('Operator diagnostics are already owned')
47
+ self._owns = True
48
+ try:
49
+ import torch
50
+ self._torch = torch
51
+ self._activities = [torch.profiler.ProfilerActivity.CPU]
52
+ if self.use_cuda:
53
+ if torch.profiler.ProfilerActivity.CUDA not in torch.profiler.supported_activities():
54
+ raise RuntimeError('CUDA operator tracing unavailable; refusing legacy event-timing fallback')
55
+ self._activities.append(torch.profiler.ProfilerActivity.CUDA)
56
+ self._directory = Path(self.output_dir).resolve()
57
+ self._directory.mkdir(parents=True, exist_ok=True)
58
+ for index in self.invocations:
59
+ if (self._directory / f'operators_invocation_{index:02d}.json').exists():
60
+ raise FileExistsError('Operator trace directory already contains a requested capture')
61
+ self._hooks.append(target.register_forward_pre_hook(self._begin))
62
+ self._hooks.append(target.register_forward_hook(self._end, always_call=True))
63
+ for name, child in target.named_children():
64
+ self._hooks.append(child.register_forward_pre_hook(self._child_begin(name)))
65
+ self._hooks.append(child.register_forward_hook(self._child_end(name), always_call=True))
66
+ except BaseException:
67
+ self._remove()
68
+ raise
69
+ return self
70
+
71
+ def _child_begin(self, name):
72
+ def begin(module, args):
73
+ if self._profiler is not None:
74
+ scope = self._torch.profiler.record_function('ddo.forward.' + name)
75
+ scope.__enter__()
76
+ self._ranges.setdefault(name, []).append(scope)
77
+ return begin
78
+
79
+ def _child_end(self, name):
80
+ def end(module, args, output):
81
+ stack = self._ranges.get(name)
82
+ if stack:
83
+ stack.pop().__exit__(None, None, None)
84
+ return end
85
+
86
+ def _begin(self, module, args):
87
+ if self._root_active:
88
+ raise RuntimeError('Recursive/concurrent selected forwards are unsupported')
89
+ self._root_active = True
90
+ index, self._count = self._count, self._count + 1
91
+ if index not in self.invocations:
92
+ return
93
+ self._index = index
94
+ profiler = self._torch.profiler.profile(activities=self._activities,
95
+ record_shapes=False, profile_memory=False, with_stack=False)
96
+ profiler.__enter__()
97
+ self._profiler = profiler
98
+ self._start = perf_counter()
99
+
100
+ def _end(self, module, args, output):
101
+ self._root_active = False
102
+ if self._profiler is None:
103
+ return
104
+ host_forward = perf_counter() - self._start
105
+ profiler, self._profiler = self._profiler, None
106
+ start = perf_counter()
107
+ profiler.__exit__(None, None, None)
108
+ stop_seconds = perf_counter() - start
109
+ path = self._directory / f'operators_invocation_{self._index:02d}.json'
110
+ if path.exists():
111
+ raise FileExistsError(f'Refusing to overwrite operator trace: {path}')
112
+ profiler.export_chrome_trace(str(path))
113
+ rows = [{'name': e.key, 'calls': e.count,
114
+ 'self_host_seconds': e.self_cpu_time_total / 1e6,
115
+ 'host_seconds': e.cpu_time_total / 1e6,
116
+ 'self_device_seconds': e.self_device_time_total / 1e6,
117
+ 'device_seconds': e.device_time_total / 1e6}
118
+ for e in profiler.key_averages()]
119
+ device_events = sum(str(e.device_type).endswith('CUDA') for e in profiler.events())
120
+ self._samples.append({'invocation_index': self._index,
121
+ 'host_forward_seconds': host_forward, 'profiler_stop_seconds': stop_seconds,
122
+ 'trace_path': str(path), 'device_activity_events': device_events,
123
+ 'operator_count': len(rows),
124
+ 'top_host': sorted(rows, key=lambda e: e['self_host_seconds'], reverse=True)[:40],
125
+ 'top_device': sorted(rows, key=lambda e: e['self_device_seconds'], reverse=True)[:40],
126
+ 'child_ranges': [e for e in rows if e['name'].startswith('ddo.forward.')]})
127
+ if self.use_cuda and not device_events:
128
+ raise RuntimeError('Operator capture has no CUDA activity; stop rather than continue an unobservable diagnostic')
129
+
130
+ def _remove(self):
131
+ for hook in self._hooks:
132
+ hook.remove()
133
+ self._hooks.clear()
134
+ self.module = None # A completed diagnostic must not retain the model.
135
+ if self._owns:
136
+ _owner.release()
137
+ self._owns = False
138
+
139
+ def __exit__(self, exc_type, exc_value, traceback):
140
+ self._failed = exc_type is not None
141
+ try:
142
+ if self._profiler is not None:
143
+ profiler, self._profiler = self._profiler, None
144
+ profiler.__exit__(exc_type, exc_value, traceback)
145
+ except BaseException as error:
146
+ self._failed = True
147
+ if exc_value is None:
148
+ raise
149
+ if hasattr(exc_value, 'add_note'):
150
+ exc_value.add_note('Operator profiler cleanup also failed: ' + repr(error))
151
+ finally:
152
+ self._remove()
153
+ self._finished = True
154
+
155
+ def snapshot(self):
156
+ status = 'disabled' if not self.enabled else 'not_finished' if not self._finished else (
157
+ 'failed' if self._failed else 'incomplete' if len(self._samples) != len(self.invocations)
158
+ else 'cuda_activity_unavailable' if self.use_cuda and any(
159
+ not s['device_activity_events'] for s in self._samples) else 'complete')
160
+ return {'schema_version': 1, 'status': status, 'benchmark_eligible': False,
161
+ 'scope': 'selected_forward_operators', 'may_synchronize': True,
162
+ 'use_cuda': self.use_cuda, 'module_path': self.module_path,
163
+ 'requested_invocations': list(self.invocations), 'observed_invocations': self._count,
164
+ 'samples': list(self._samples)}
165
+
166
+ def attach(self, report):
167
+ return replace(report, runtime={**report.runtime, 'operator_diagnostics': self.snapshot()})