-
Notifications
You must be signed in to change notification settings - Fork 618
/
interfaces.py
178 lines (145 loc) 路 5.32 KB
/
interfaces.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import datetime
import logging
import multiprocessing as mp
import sys
import threading
from multiprocessing import synchronize
from typing import TYPE_CHECKING, Any, List, Optional, TypeVar, Union
if sys.version_info >= (3, 8):
from typing import Protocol, runtime_checkable
else:
from typing_extensions import Protocol, runtime_checkable
if TYPE_CHECKING:
from typing import Deque
from wandb.proto.wandb_telemetry_pb2 import TelemetryRecord
from wandb.sdk.interface.interface import FilesDict
from wandb.sdk.internal.settings_static import SettingsStatic
import wandb
TimeStamp = TypeVar("TimeStamp", bound=datetime.datetime)
logger = logging.getLogger(__name__)
class Metric(Protocol):
"""
Base protocol for individual metrics
"""
name: str
# samples: Sequence[Tuple[TimeStamp, Sample]]
samples: "Deque[Any]"
def sample(self) -> None:
... # pragma: no cover
def clear(self) -> None:
... # pragma: no cover
def aggregate(self) -> dict:
... # pragma: no cover
@runtime_checkable
class Asset(Protocol):
"""
Base protocol to encapsulate everything relating to an "Asset"
e.g. CPU, GPU, TPU, Network, I/O etc.
"""
name: str
metrics: List[Metric]
metrics_monitor: "MetricsMonitor"
def __init__(self, *args: Any, **kwargs: Any) -> None:
... # pragma: no cover
@classmethod
def is_available(cls) -> bool:
"""Check if the resource is available"""
... # pragma: no cover
def start(self) -> None:
"""Start monitoring the resource"""
... # pragma: no cover
def finish(self) -> None:
"""finish monitoring the resource"""
... # pragma: no cover
def probe(self) -> dict:
"""Get static information about the resource"""
... # pragma: no cover
class Interface(Protocol):
def publish_stats(self, stats: dict) -> None:
... # pragma: no cover
def _publish_telemetry(self, telemetry: "TelemetryRecord") -> None:
... # pragma: no cover
def publish_files(self, files_dict: "FilesDict") -> None:
... # pragma: no cover
class MetricsMonitor:
"""
Takes care of collecting, sampling, serializing, and publishing a set of metrics.
"""
def __init__(
self,
asset_name: str,
metrics: List[Metric],
interface: Interface,
settings: "SettingsStatic",
shutdown_event: synchronize.Event,
) -> None:
self.metrics = metrics
self.asset_name = asset_name
self._interface = interface
self._process: Optional[Union[mp.Process, threading.Thread]] = None
self._shutdown_event: synchronize.Event = shutdown_event
self.sampling_interval: float = float(
max(
0.1,
settings._stats_sample_rate_seconds,
)
) # seconds
# The number of samples to aggregate (e.g. average or compute max/min etc.)
# before publishing; defaults to 15; valid range: [1:30]
self.samples_to_aggregate: int = min(
30, max(1, settings._stats_samples_to_average)
)
def monitor(self) -> None:
"""Poll the Asset metrics"""
while not self._shutdown_event.is_set():
for _ in range(self.samples_to_aggregate):
for metric in self.metrics:
try:
metric.sample()
except Exception as e:
wandb.termerror(f"Failed to sample metric: {e}", repeat=False)
self._shutdown_event.wait(self.sampling_interval)
if self._shutdown_event.is_set():
break
self.publish()
def aggregate(self) -> dict:
"""Return a dict of metrics"""
aggregated_metrics = {}
for metric in self.metrics:
try:
serialized_metric = metric.aggregate()
aggregated_metrics.update(serialized_metric)
# aggregated_metrics = wandb.util.merge_dicts(
# aggregated_metrics, metric.serialize()
# )
except Exception as e:
wandb.termerror(f"Failed to serialize metric: {e}", repeat=False)
return aggregated_metrics
def publish(self) -> None:
"""Publish the Asset metrics"""
try:
aggregated_metrics = self.aggregate()
if aggregated_metrics:
self._interface.publish_stats(aggregated_metrics)
for metric in self.metrics:
metric.clear()
except Exception as e:
wandb.termerror(f"Failed to publish metrics: {e}", repeat=False)
def start(self) -> None:
if self._process is None and not self._shutdown_event.is_set():
self._process = threading.Thread(
target=self.monitor,
daemon=True,
name=f"{self.asset_name}",
)
self._process.start()
logger.info(f"Started {self._process.name}")
def finish(self) -> None:
if self._process is None:
return None
try:
self._process.join()
logger.info(f"Joined {self._process.name}")
except Exception as e:
logger.warning(f"Failed to join {self._process.name}: {e}")
self._process = None