xmc-metrics 1.3.0__tar.gz
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.
- xmc_metrics-1.3.0/PKG-INFO +20 -0
- xmc_metrics-1.3.0/README.md +257 -0
- xmc_metrics-1.3.0/__init__.py +90 -0
- xmc_metrics-1.3.0/_protos/__init__.py +19 -0
- xmc_metrics-1.3.0/_version.py +22 -0
- xmc_metrics-1.3.0/api/protos/metrics/metrics.proto +33 -0
- xmc_metrics-1.3.0/autolog.py +168 -0
- xmc_metrics-1.3.0/buffer.py +218 -0
- xmc_metrics-1.3.0/client.py +265 -0
- xmc_metrics-1.3.0/dist_harvest.py +183 -0
- xmc_metrics-1.3.0/flusher.py +481 -0
- xmc_metrics-1.3.0/integrations/__init__.py +17 -0
- xmc_metrics-1.3.0/integrations/common.py +66 -0
- xmc_metrics-1.3.0/integrations/keras.py +134 -0
- xmc_metrics-1.3.0/integrations/lightning.py +168 -0
- xmc_metrics-1.3.0/network.py +280 -0
- xmc_metrics-1.3.0/py.typed +1 -0
- xmc_metrics-1.3.0/pyproject.toml +72 -0
- xmc_metrics-1.3.0/resilience.py +225 -0
- xmc_metrics-1.3.0/setup.cfg +4 -0
- xmc_metrics-1.3.0/setup.py +146 -0
- xmc_metrics-1.3.0/types.py +133 -0
- xmc_metrics-1.3.0/xmc_metrics.egg-info/PKG-INFO +20 -0
- xmc_metrics-1.3.0/xmc_metrics.egg-info/SOURCES.txt +35 -0
- xmc_metrics-1.3.0/xmc_metrics.egg-info/dependency_links.txt +1 -0
- xmc_metrics-1.3.0/xmc_metrics.egg-info/requires.txt +7 -0
- xmc_metrics-1.3.0/xmc_metrics.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: xmc-metrics
|
|
3
|
+
Version: 1.3.0
|
|
4
|
+
Summary: XMC Python SDK for Metrics Collection & Management
|
|
5
|
+
Author: XMC Team
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Requires-Dist: protobuf<7.0.0,>=5.29.6
|
|
17
|
+
Provides-Extra: keras
|
|
18
|
+
Requires-Dist: keras>=3.0.0; extra == "keras"
|
|
19
|
+
Provides-Extra: lightning
|
|
20
|
+
Requires-Dist: pytorch-lightning>=2.0.0; extra == "lightning"
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
# XMC Python SDK (`xmc`)
|
|
2
|
+
|
|
3
|
+
[](#)
|
|
4
|
+
[](#)
|
|
5
|
+
|
|
6
|
+
The `xmc` Python SDK is a high-throughput, thread-safe metrics ingestion client designed for distributed Machine Learning (ML) workloads (PyTorch, JAX, TensorFlow) running across GKE, Vertex AI, Slurm, and local workstations.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## 📦 Installation
|
|
11
|
+
|
|
12
|
+
The SDK ships as the `xmc-metrics` distribution and is imported as `xmc`. Its only runtime dependency is `protobuf>=5.29.6,<7.0.0`.
|
|
13
|
+
|
|
14
|
+
> [!WARNING]
|
|
15
|
+
> Never run `pip install xmc`: that name on PyPI belongs to an unrelated package.
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
# From a google/xmc checkout (worker images, local development):
|
|
19
|
+
pip install ./sdks/python/xmc
|
|
20
|
+
pip install -e ./sdks/python/xmc # editable
|
|
21
|
+
|
|
22
|
+
# Optional framework integrations:
|
|
23
|
+
pip install "./sdks/python/xmc[keras]"
|
|
24
|
+
pip install "./sdks/python/xmc[lightning]"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Building the package compiles [`api/protos/metrics/metrics.proto`](../../../api/protos/metrics/metrics.proto) into `xmc._protos.metrics_pb2` (see [`setup.py`](setup.py)), so a source install needs the repository's `api/protos/` next to `sdks/`. The sdist bundles that `.proto` and builds anywhere. The build pins `grpcio-tools==1.70.0` and `protobuf==5.29.6`: the generated module refuses to load on a protobuf runtime older than the one that generated it. `grpcio-tools==1.70.0` has no Python 3.14 wheel, so building from source on 3.14 compiles it first; the `xmc-metrics` wheel installs on 3.11–3.14 directly.
|
|
28
|
+
|
|
29
|
+
Editable installs write `_protos/metrics_pb2.py` into the source tree (git-ignored). Bazel builds don't generate it and import the Bazel-generated `api.protos.metrics.metrics_pb2` instead.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 🏗️ Architecture & Thread Boundaries
|
|
34
|
+
|
|
35
|
+
To guarantee zero training loop stall, `xmc` separates the **Training Hot Path** from **Network Serialization & Flushing**.
|
|
36
|
+
|
|
37
|
+
```mermaid
|
|
38
|
+
flowchart TD
|
|
39
|
+
subgraph HotPath["🔥 Training Hot Path (Main Thread)"]
|
|
40
|
+
A["log_metric('loss', val, step)"] --> B["_coerce_float / _coerce_int<br/>(Detaches PyTorch/JAX .item())"]
|
|
41
|
+
B --> C["is_valid_metric_name<br/>(LRU Cached Regex Check)"]
|
|
42
|
+
C --> D["BoundedMetricsBuffer<br/>(Lightweight 4-element Tuple)"]
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
subgraph Flusher["⚡ Background Flusher Thread (Daemon)"]
|
|
46
|
+
D -- Async Pop Batch --> E["harvest_client_metadata<br/>(XID, WU, Exec, Replica)"]
|
|
47
|
+
E --> F["Instantiate Metric Protos<br/>(Float ts ➡️ Microsecond Int64)"]
|
|
48
|
+
F --> G["format_metric_batch_payload<br/>(JSON Array + AIP-127 String IDs)"]
|
|
49
|
+
G --> H["ResilienceStateMachine<br/>(Exponential Backoff & Retries)"]
|
|
50
|
+
H --> I["HTTP Gateway / Transport"]
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
style HotPath fill:#ffebee,stroke:#c62828,stroke-width:2px
|
|
54
|
+
style Flusher fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## 🔄 Sequence Flow Diagram
|
|
60
|
+
|
|
61
|
+
```mermaid
|
|
62
|
+
sequenceDiagram
|
|
63
|
+
autonumber
|
|
64
|
+
actor Trainer as ML Trainer Thread
|
|
65
|
+
participant Buffer as BoundedMetricsBuffer
|
|
66
|
+
participant Worker as MetricsFlusher Daemon
|
|
67
|
+
participant Gateway as XMC Ingestion Gateway
|
|
68
|
+
|
|
69
|
+
Trainer->>Buffer: log_metric("loss", 0.123, step=10)
|
|
70
|
+
Note over Trainer,Buffer: Non-blocking (~80B tuple insertion)
|
|
71
|
+
Trainer->>Buffer: log_metric("accuracy", 0.95, step=10)
|
|
72
|
+
|
|
73
|
+
loop Background Flush Interval (Default: 5s)
|
|
74
|
+
Worker->>Buffer: pop_batch(batch_size=1000)
|
|
75
|
+
Buffer-->>Worker: List of (name, val, step, timestamp_float)
|
|
76
|
+
Worker->>Worker: Convert float ts to microsecond Int64
|
|
77
|
+
Worker->>Worker: Harvest metadata (xid, work_unit_id, execution_id, replica_id)
|
|
78
|
+
Worker->>Worker: Format XMCMetricsBatch JSON Payload
|
|
79
|
+
Worker->>Gateway: HTTP POST /v1/metrics
|
|
80
|
+
Gateway-->>Worker: 200 OK / Success
|
|
81
|
+
end
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 🌐 Metadata Harvesting Hierarchy
|
|
87
|
+
|
|
88
|
+
`harvest_client_metadata()` automatically extracts cluster context for zero-boilerplate logging across orchestrated environments (GKE, Vertex AI, Slurm):
|
|
89
|
+
|
|
90
|
+
```mermaid
|
|
91
|
+
flowchart LR
|
|
92
|
+
Tier1["1. Environment Vars<br/>(XMC_XID, XMC_WORK_UNIT_ID, ...)"] --> Tier2["2. Fail-Closed Early Exit<br/>(Silences telemetry)"]
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
1. **Environment Variables**: Primary source injected by XMC cluster infrastructure (`XMC_XID`, `XMC_WORK_UNIT_ID`, `XMC_EXECUTION_ID`, `XMC_REPLICA_ID`).
|
|
96
|
+
2. **Fail-Closed Missing Configs**: If `XMC_XID`, `XMC_WORK_UNIT_ID`, or `XMC_EXECUTION_ID` are missing, the SDK logs an error and exits the metric flow early (silences ingestion) instead of reverting to arbitrary fallback values. (`XMC_REPLICA_ID` naturally defaults to `"0"` for undiscovered ranks).
|
|
97
|
+
|
|
98
|
+
> [!NOTE]
|
|
99
|
+
> Per **Google AIP-127**, all 64-bit metadata IDs (`xid`, `work_unit_id`, `execution_id`, `replica_id`) are serialized as stringified integers (e.g. `"xid": "482019"`) in the JSON payload to prevent IEEE 754 float precision loss in web UIs.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 🎯 Distributed ML Rank Detection & Silencing
|
|
104
|
+
|
|
105
|
+
In distributed training (`WORLD_SIZE > 1`), logging from every process can saturate network gateways. `xmc` auto-detects process rank:
|
|
106
|
+
|
|
107
|
+
- **Rank 0 (Chief / Driver)**: Actively logs metrics.
|
|
108
|
+
- **Rank > 0 (Workers)**: Automatically silenced unless `log_all_replicas=True`.
|
|
109
|
+
|
|
110
|
+
### Auto-Harvested Rank Variables:
|
|
111
|
+
- **PyTorch Distributed**: `RANK`, `WORLD_SIZE`
|
|
112
|
+
- **JAX Distributed**: `JAX_PROCESS_INDEX`
|
|
113
|
+
- **MPI**: `OMPI_COMM_WORLD_RANK`
|
|
114
|
+
- **Kubernetes / Vertex Jobs**: `JOB_COMPLETION_INDEX`, `XMC_JOB_INDEX`
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## 💻 Quickstart Usage Examples
|
|
119
|
+
|
|
120
|
+
### 1. Basic Single-Process Logging
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
import xmc
|
|
124
|
+
|
|
125
|
+
for step in range(1000):
|
|
126
|
+
loss = train_step()
|
|
127
|
+
xmc.log_metric("train/loss", loss, step=step)
|
|
128
|
+
|
|
129
|
+
# Optional: Ensure buffer is flushed before script exit
|
|
130
|
+
xmc.shutdown()
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### 2. Distributed Training Setup (PyTorch / JAX)
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
import xmc
|
|
137
|
+
|
|
138
|
+
for step in range(1000):
|
|
139
|
+
loss = distributed_train_step()
|
|
140
|
+
# Auto-detects process rank. Rank 0 logs to buffer; non-zero ranks drop locally.
|
|
141
|
+
xmc.log_metric("train/loss", loss, step=step)
|
|
142
|
+
|
|
143
|
+
xmc.shutdown()
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### 3. Opting Into All-Replica Logging
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
import xmc
|
|
150
|
+
|
|
151
|
+
# Initialize the global flusher with log_all_replicas=True to capture metrics from every GPU rank
|
|
152
|
+
xmc.init(log_all_replicas=True)
|
|
153
|
+
|
|
154
|
+
xmc.log_metric("train/loss", loss, step=step)
|
|
155
|
+
xmc.shutdown()
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## ⚡ Framework Integrations & Autologging
|
|
161
|
+
|
|
162
|
+
XMC provides two modes for framework integration: **Automatic Zero-Configuration Autologging (`xmc.autolog()`)** for zero-code-change telemetry, and **Explicit Callbacks & Loggers** for advanced customization.
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
### 1. Automatic Autologging (`xmc.autolog()`) [Recommended]
|
|
167
|
+
|
|
168
|
+
`xmc.autolog()` enables zero-configuration automatic framework patching for Keras (`keras>=3.0.0`) and PyTorch Lightning (`pytorch-lightning>=2.0.0`). When activated, `model.fit()` and `trainer.fit()` automatically log training/evaluation metrics without requiring manually instantiated callbacks or loggers.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
import xmc
|
|
172
|
+
|
|
173
|
+
# Activate automatic framework patching for Keras & PyTorch Lightning
|
|
174
|
+
xmc.autolog()
|
|
175
|
+
|
|
176
|
+
# Keras training automatically logs metrics without adding callbacks manually
|
|
177
|
+
model.fit(x_train, y_train, epochs=5)
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
#### ⚙️ Autologging Disable Knob & Override
|
|
181
|
+
- **Environment Variable**: Set `XMC_DISABLE_AUTOLOG=1` in your environment to safely disable autologging and skip framework patching without modifying code.
|
|
182
|
+
- **Explicit Disable Flag**: Call `xmc.autolog(disable=True)` to explicitly unpatch frameworks and disable autologging.
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
### 2. Explicit & Custom Integrations (Advanced Usage)
|
|
187
|
+
|
|
188
|
+
If you need custom metric prefixes, custom logging frequencies, or explicit `Client` instances, you can use the explicit integration classes directly instead of `xmc.autolog()`.
|
|
189
|
+
|
|
190
|
+
> [!TIP]
|
|
191
|
+
> **Combining `xmc.autolog()` with Explicit Callbacks**: If `xmc.autolog()` is active and an explicit `XmcKerasCallback` or `XmcLogger` is passed to `fit()`, XMC automatically detects the explicit instance and preserves it without adding a duplicate callback or logger.
|
|
192
|
+
|
|
193
|
+
#### 📦 Keras Explicit Callback (`XmcKerasCallback`)
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
import keras
|
|
197
|
+
from xmc.integrations.keras import XmcKerasCallback
|
|
198
|
+
|
|
199
|
+
model = keras.Sequential([...])
|
|
200
|
+
model.compile(optimizer="adam", loss="mse", metrics=["accuracy"])
|
|
201
|
+
|
|
202
|
+
# Attach XmcKerasCallback manually with custom prefix or batch frequency
|
|
203
|
+
model.fit(
|
|
204
|
+
x_train,
|
|
205
|
+
y_train,
|
|
206
|
+
epochs=5,
|
|
207
|
+
callbacks=[XmcKerasCallback(prefix="train/", log_batch_frequency=10)],
|
|
208
|
+
)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
#### 📦 PyTorch Lightning Explicit Logger (`XmcLogger`)
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
import lightning.pytorch as pl
|
|
215
|
+
from xmc.integrations.lightning import XmcLogger
|
|
216
|
+
|
|
217
|
+
# Instantiate XmcLogger with custom experiment name and prefix
|
|
218
|
+
logger = XmcLogger(name="my_experiment", prefix="pl_metrics/")
|
|
219
|
+
trainer = pl.Trainer(logger=logger)
|
|
220
|
+
trainer.fit(model, dataloader)
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
#### 🔒 Guarantees & Operational Characteristics
|
|
224
|
+
- **Strict Decoupled Eager Imports**: Importing from `xmc.integrations.keras` or `xmc.integrations.lightning` validates version constraints eagerly at process startup (<10s fail-fast check). Missing or incompatible dependencies fail immediately before allocating GPU/TPU cluster resources.
|
|
225
|
+
- **Global Optimizer Step Mapping**: Batch and epoch metrics are mapped to the global optimizer iteration count (`model.optimizer.iterations`) to guarantee continuous time-series metrics across epoch boundaries in ClickHouse without step collisions.
|
|
226
|
+
- **Rank-Zero Silencing**: Automatically drops metric logging on worker ranks (`RANK > 0`) during multi-replica distributed training unless explicit multi-replica logging is configured.
|
|
227
|
+
|
|
228
|
+
> [!NOTE]
|
|
229
|
+
> **Legacy Keras 2 Support**: `XmcKerasCallback` requires `keras>=3.0.0`. For legacy Keras 2 (`tf.keras` <= 2.15), use `xmc.log_metric()` directly inside a `LambdaCallback`:
|
|
230
|
+
> ```python
|
|
231
|
+
> from tensorflow.keras.callbacks import LambdaCallback
|
|
232
|
+
> cb = LambdaCallback(on_epoch_end=lambda ep, logs: xmc.log_metric("loss", logs["loss"], step=ep))
|
|
233
|
+
> ```
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## ⚙️ Resilience & Rate-Limited Drop Logging
|
|
238
|
+
|
|
239
|
+
- **Ring Buffer Overflow Protection**: `BoundedMetricsBuffer` defaults to 500,000 metrics (~85MB RAM). If network drops cause buffer overflow, oldest metrics are evicted FIFO.
|
|
240
|
+
- **Rate-Limited Warnings**: Drop warnings are logged at most once every **10 seconds** to prevent log stdout flooding.
|
|
241
|
+
- **Resilience State Machine**: Retries transient network/5xx errors using exponential backoff with jitter while immediately failing fast on terminal client errors (e.g., 400 Bad Request, 422 Unprocessable).
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
## 🧪 Running Tests & Linters
|
|
246
|
+
|
|
247
|
+
```bash
|
|
248
|
+
# Run all Bazel unit tests
|
|
249
|
+
bazel test //sdks/python/...
|
|
250
|
+
|
|
251
|
+
# Build the wheel and sdist (CI installs both via .github/workflows/xmc-metrics-package.yml
|
|
252
|
+
# and runs test/packaging/xmc_metrics_install_test.py against them)
|
|
253
|
+
python3 -m build sdks/python/xmc --outdir /tmp/xmc-metrics-dist
|
|
254
|
+
|
|
255
|
+
# Run pre-commit linters (Ruff, Buildifier, addlicense)
|
|
256
|
+
./.githooks/pre-commit
|
|
257
|
+
```
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""XMC Python SDK package."""
|
|
16
|
+
|
|
17
|
+
from xmc._version import __version__
|
|
18
|
+
from xmc.autolog import autolog
|
|
19
|
+
from xmc.buffer import DEFAULT_CAPACITY, BoundedMetricsBuffer, MetricTuple
|
|
20
|
+
from xmc.client import Client, XMCAPIError, XMCError, XMCNetworkError
|
|
21
|
+
from xmc.dist_harvest import (
|
|
22
|
+
GetReplicaIDAndSilenceStatus,
|
|
23
|
+
get_replica_id_and_silence_status,
|
|
24
|
+
)
|
|
25
|
+
from xmc.flusher import MetricsFlusher
|
|
26
|
+
from xmc.network import HTTPClient, SendResult
|
|
27
|
+
from xmc.resilience import ResilienceState, ResilienceStateMachine
|
|
28
|
+
from xmc.types import Metric, validate_metric
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"autolog",
|
|
32
|
+
"BoundedMetricsBuffer",
|
|
33
|
+
"DEFAULT_CAPACITY",
|
|
34
|
+
"MetricTuple",
|
|
35
|
+
"Client",
|
|
36
|
+
"HTTPClient",
|
|
37
|
+
"MetricsFlusher",
|
|
38
|
+
"Metric",
|
|
39
|
+
"ResilienceState",
|
|
40
|
+
"ResilienceStateMachine",
|
|
41
|
+
"SendResult",
|
|
42
|
+
"XMCError",
|
|
43
|
+
"XMCNetworkError",
|
|
44
|
+
"XMCAPIError",
|
|
45
|
+
"validate_metric",
|
|
46
|
+
"get_replica_id_and_silence_status",
|
|
47
|
+
"GetReplicaIDAndSilenceStatus",
|
|
48
|
+
"__version__",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
_global_flusher: MetricsFlusher | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def init(*args, **kwargs) -> None:
|
|
55
|
+
"""Initializes the global SDK metrics flusher daemon."""
|
|
56
|
+
global _global_flusher
|
|
57
|
+
if _global_flusher is None:
|
|
58
|
+
_global_flusher = MetricsFlusher(client=Client(*args, **kwargs))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def log_metric(name: str, value: float | int, step: int | None = None) -> None:
|
|
62
|
+
"""Logs a metric to the background flusher daemon. Auto-initializes if needed."""
|
|
63
|
+
global _global_flusher
|
|
64
|
+
if _global_flusher is None:
|
|
65
|
+
init()
|
|
66
|
+
assert _global_flusher is not None
|
|
67
|
+
_global_flusher.log_metric(name, value, step)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def log(name: str, value: float | int, step: int | None = None) -> None:
|
|
71
|
+
"""Alias for log_metric."""
|
|
72
|
+
log_metric(name, value, step)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def shutdown() -> None:
|
|
76
|
+
"""Gracefully shuts down the global SDK metrics flusher."""
|
|
77
|
+
global _global_flusher
|
|
78
|
+
if _global_flusher is not None:
|
|
79
|
+
_global_flusher.shutdown()
|
|
80
|
+
_global_flusher = None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
__all__.extend(
|
|
84
|
+
[
|
|
85
|
+
"init",
|
|
86
|
+
"log_metric",
|
|
87
|
+
"log",
|
|
88
|
+
"shutdown",
|
|
89
|
+
]
|
|
90
|
+
)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Protobuf modules generated when the xmc-metrics package is built.
|
|
16
|
+
|
|
17
|
+
setup.py compiles api/protos/metrics/metrics.proto into metrics_pb2.py here. Bazel
|
|
18
|
+
builds do not generate it; xmc.types then imports api.protos.metrics instead.
|
|
19
|
+
"""
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Single source of the xmc-metrics version.
|
|
16
|
+
|
|
17
|
+
pyproject.toml reads it as the distribution version, xmc re-exports it as
|
|
18
|
+
xmc.__version__, and the HTTP clients send it in their User-Agent headers. It lives
|
|
19
|
+
in its own module so those clients can import it without importing xmc/__init__.py.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
__version__ = "1.3.0"
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Copyright 2026 Google LLC
|
|
2
|
+
//
|
|
3
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
// you may not use this file except in compliance with the License.
|
|
5
|
+
// You may obtain a copy of the License at
|
|
6
|
+
//
|
|
7
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
//
|
|
9
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
// See the License for the specific language governing permissions and
|
|
13
|
+
// limitations under the License.
|
|
14
|
+
|
|
15
|
+
syntax = "proto3";
|
|
16
|
+
|
|
17
|
+
package cloud.xmanager.v1;
|
|
18
|
+
|
|
19
|
+
option go_package = "xmanager_cloud/api/protos/metrics;metrics";
|
|
20
|
+
option java_multiple_files = true;
|
|
21
|
+
|
|
22
|
+
// Metric represents a single numeric measurement logged in XMC.
|
|
23
|
+
message Metric {
|
|
24
|
+
int64 xid = 1;
|
|
25
|
+
int64 work_unit_id = 2;
|
|
26
|
+
int64 execution_id = 3;
|
|
27
|
+
string job_name = 4;
|
|
28
|
+
string replica_id = 5;
|
|
29
|
+
string metric_name = 6;
|
|
30
|
+
double metric_value = 7;
|
|
31
|
+
int64 step = 8;
|
|
32
|
+
int64 timestamp = 9; // Timestamp in microseconds
|
|
33
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""XMC Autologging Entrypoint and Framework Patching Module."""
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
import functools
|
|
19
|
+
import inspect
|
|
20
|
+
import logging
|
|
21
|
+
import os
|
|
22
|
+
from collections.abc import Callable
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
_AUTOLOG_DISABLED_ENV = "XMC_DISABLE_AUTOLOG"
|
|
28
|
+
_patched_keras_original_fit: Callable[..., Any] | None = None
|
|
29
|
+
_patched_lightning_original_fit: Callable[..., Any] | None = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def is_autolog_disabled() -> bool:
|
|
33
|
+
"""Checks if autologging is disabled via XMC_DISABLE_AUTOLOG environment variable."""
|
|
34
|
+
return os.environ.get(_AUTOLOG_DISABLED_ENV) == "1"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def patch_keras() -> bool:
|
|
38
|
+
"""Safely patches Keras Model.fit to automatically attach XmcKerasCallback.
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
True if Keras was successfully patched, False otherwise.
|
|
42
|
+
"""
|
|
43
|
+
global _patched_keras_original_fit
|
|
44
|
+
if _patched_keras_original_fit is not None:
|
|
45
|
+
return True
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
import keras
|
|
49
|
+
|
|
50
|
+
from xmc.integrations.keras import XmcKerasCallback
|
|
51
|
+
|
|
52
|
+
original_fit = keras.Model.fit
|
|
53
|
+
sig = inspect.signature(original_fit)
|
|
54
|
+
|
|
55
|
+
@functools.wraps(original_fit)
|
|
56
|
+
def custom_fit(self: Any, *args: Any, **kwargs: Any) -> Any:
|
|
57
|
+
try:
|
|
58
|
+
bound_args = sig.bind(self, *args, **kwargs)
|
|
59
|
+
bound_args.apply_defaults()
|
|
60
|
+
callbacks = bound_args.arguments.get("callbacks", [])
|
|
61
|
+
callbacks_list = list(callbacks) if callbacks else []
|
|
62
|
+
if not any(isinstance(c, XmcKerasCallback) for c in callbacks_list):
|
|
63
|
+
callbacks_list.append(XmcKerasCallback())
|
|
64
|
+
bound_args.arguments["callbacks"] = callbacks_list
|
|
65
|
+
return original_fit(*bound_args.args, **bound_args.kwargs)
|
|
66
|
+
except TypeError:
|
|
67
|
+
return original_fit(self, *args, **kwargs)
|
|
68
|
+
|
|
69
|
+
keras.Model.fit = custom_fit
|
|
70
|
+
_patched_keras_original_fit = original_fit
|
|
71
|
+
return True
|
|
72
|
+
except (ImportError, Exception):
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def unpatch_keras() -> None:
|
|
77
|
+
"""Restores original Keras Model.fit method if patched."""
|
|
78
|
+
global _patched_keras_original_fit
|
|
79
|
+
if _patched_keras_original_fit is not None:
|
|
80
|
+
with contextlib.suppress(Exception):
|
|
81
|
+
import keras
|
|
82
|
+
|
|
83
|
+
keras.Model.fit = _patched_keras_original_fit
|
|
84
|
+
_patched_keras_original_fit = None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def patch_lightning() -> bool:
|
|
88
|
+
"""Safely patches PyTorch Lightning Trainer.fit to automatically attach XmcLogger.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
True if PyTorch Lightning was successfully patched, False otherwise.
|
|
92
|
+
"""
|
|
93
|
+
global _patched_lightning_original_fit
|
|
94
|
+
if _patched_lightning_original_fit is not None:
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
try:
|
|
99
|
+
import lightning.pytorch as pl
|
|
100
|
+
except ImportError:
|
|
101
|
+
import pytorch_lightning as pl
|
|
102
|
+
|
|
103
|
+
from xmc.integrations.lightning import XmcLogger
|
|
104
|
+
|
|
105
|
+
original_fit = pl.Trainer.fit
|
|
106
|
+
|
|
107
|
+
@functools.wraps(original_fit)
|
|
108
|
+
def custom_fit(self: Any, *args: Any, **kwargs: Any) -> Any:
|
|
109
|
+
if hasattr(self, "_loggers"):
|
|
110
|
+
if isinstance(self._loggers, list):
|
|
111
|
+
if not any(isinstance(logger_inst, XmcLogger) for logger_inst in self._loggers):
|
|
112
|
+
self._loggers.append(XmcLogger())
|
|
113
|
+
elif self._loggers is None:
|
|
114
|
+
self._loggers = [XmcLogger()]
|
|
115
|
+
else:
|
|
116
|
+
loggers = getattr(self, "loggers", None)
|
|
117
|
+
if isinstance(loggers, list) and not any(
|
|
118
|
+
isinstance(logger_inst, XmcLogger) for logger_inst in loggers
|
|
119
|
+
):
|
|
120
|
+
loggers.append(XmcLogger())
|
|
121
|
+
return original_fit(self, *args, **kwargs)
|
|
122
|
+
|
|
123
|
+
pl.Trainer.fit = custom_fit
|
|
124
|
+
_patched_lightning_original_fit = original_fit
|
|
125
|
+
return True
|
|
126
|
+
except (ImportError, Exception):
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def unpatch_lightning() -> None:
|
|
131
|
+
"""Restores original PyTorch Lightning Trainer.fit method if patched."""
|
|
132
|
+
global _patched_lightning_original_fit
|
|
133
|
+
if _patched_lightning_original_fit is not None:
|
|
134
|
+
with contextlib.suppress(Exception):
|
|
135
|
+
try:
|
|
136
|
+
import lightning.pytorch as pl
|
|
137
|
+
except ImportError:
|
|
138
|
+
import pytorch_lightning as pl
|
|
139
|
+
|
|
140
|
+
pl.Trainer.fit = _patched_lightning_original_fit
|
|
141
|
+
_patched_lightning_original_fit = None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def unpatch_all() -> None:
|
|
145
|
+
"""Restores all patched framework methods."""
|
|
146
|
+
unpatch_keras()
|
|
147
|
+
unpatch_lightning()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def autolog(disable: bool = False) -> bool:
|
|
151
|
+
"""Activates automatic framework autologging for Keras and PyTorch Lightning.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
disable: If True, explicitly disables autologging and unpatches frameworks.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
True if autologging is active and patched, False if disabled.
|
|
158
|
+
"""
|
|
159
|
+
if disable or is_autolog_disabled():
|
|
160
|
+
logger.info("INFO: xmc: Autologging disabled via XMC_DISABLE_AUTOLOG=1 or disable flag.")
|
|
161
|
+
unpatch_all()
|
|
162
|
+
return False
|
|
163
|
+
|
|
164
|
+
keras_patched = patch_keras()
|
|
165
|
+
lightning_patched = patch_lightning()
|
|
166
|
+
|
|
167
|
+
logger.info("INFO: xmc: Autologging activated...")
|
|
168
|
+
return keras_patched or lightning_patched
|