kymo-logger 0.1.0__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.
- kymo/__init__.py +230 -0
- kymo/__main__.py +91 -0
- kymo/_encode.py +188 -0
- kymo/_run.py +324 -0
- kymo/_sender.py +373 -0
- kymo/_spool.py +158 -0
- kymo/_transport.py +196 -0
- kymo/_util.py +51 -0
- kymo/_version.py +1 -0
- kymo/py.typed +0 -0
- kymo_logger-0.1.0.dist-info/METADATA +165 -0
- kymo_logger-0.1.0.dist-info/RECORD +15 -0
- kymo_logger-0.1.0.dist-info/WHEEL +4 -0
- kymo_logger-0.1.0.dist-info/entry_points.txt +2 -0
- kymo_logger-0.1.0.dist-info/licenses/LICENSE +202 -0
kymo/__init__.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Kymo: a tiny, non-blocking metrics logger for ML training.
|
|
2
|
+
|
|
3
|
+
import kymo
|
|
4
|
+
run = kymo.init(project="llm-pretrain", experiment="7b-lr3e-4", config={"lr": 3e-4})
|
|
5
|
+
for step in range(N):
|
|
6
|
+
run.log({"train/loss": loss, "lr": lr}, step=step)
|
|
7
|
+
run.finish() # optional, also done at exit
|
|
8
|
+
|
|
9
|
+
``log()`` only shallow-copies the dict and appends it to a deque; everything
|
|
10
|
+
else (value conversion, flattening, JSON, gzip, HTTP, retries, disk spool)
|
|
11
|
+
happens on background daemon threads. Nothing in this package raises into
|
|
12
|
+
the training loop.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import atexit
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import socket
|
|
21
|
+
import sys
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
from typing import Any, List, Mapping, Optional, Union
|
|
25
|
+
|
|
26
|
+
from ._run import NoopRun, Run
|
|
27
|
+
from ._util import default_spool_dir, env_bool, env_float, env_str, warn_once
|
|
28
|
+
from ._version import __version__
|
|
29
|
+
|
|
30
|
+
__all__ = ["init", "log", "flush", "finish", "Run", "NoopRun", "__version__"]
|
|
31
|
+
|
|
32
|
+
DEFAULT_HOST = "http://localhost:8080"
|
|
33
|
+
|
|
34
|
+
_lock = threading.Lock()
|
|
35
|
+
_runs: List[Run] = []
|
|
36
|
+
_last: Union[Run, NoopRun, None] = None
|
|
37
|
+
_hooks_installed = False
|
|
38
|
+
_exc_seen = False
|
|
39
|
+
_prev_excepthook = None
|
|
40
|
+
_owner_pid = os.getpid()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_PROJECT_BAD = re.compile(r"[^A-Za-z0-9_.-]")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _clean_project(name: Any) -> str:
|
|
47
|
+
s = str(name or "").strip()
|
|
48
|
+
clean = _PROJECT_BAD.sub("-", s)[:64] or "default"
|
|
49
|
+
if clean != s:
|
|
50
|
+
warn_once(("project-name", s), "project name %r is not [A-Za-z0-9_.-]{1,64}; using %r", s, clean)
|
|
51
|
+
return clean
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _clean_experiment(name: Any) -> str:
|
|
55
|
+
s = str(name).strip() if name is not None else ""
|
|
56
|
+
if not s:
|
|
57
|
+
try:
|
|
58
|
+
hn = socket.gethostname().split(".")[0]
|
|
59
|
+
except Exception:
|
|
60
|
+
hn = "run"
|
|
61
|
+
s = "%s-%s" % (hn, time.strftime("%Y%m%d-%H%M%S"))
|
|
62
|
+
if len(s) > 128:
|
|
63
|
+
warn_once(("exp-name", s), "experiment name longer than 128 chars; truncated")
|
|
64
|
+
s = s[:128]
|
|
65
|
+
return s
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _normalize_host(host: str) -> Optional[str]:
|
|
69
|
+
h = host.strip().rstrip("/")
|
|
70
|
+
if "://" not in h:
|
|
71
|
+
h = "http://" + h
|
|
72
|
+
scheme = h.split("://", 1)[0].lower()
|
|
73
|
+
if scheme not in ("http", "https"):
|
|
74
|
+
return None
|
|
75
|
+
return h
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def init(
|
|
79
|
+
project: str,
|
|
80
|
+
experiment: Optional[str] = None,
|
|
81
|
+
*,
|
|
82
|
+
config: Optional[Mapping[str, Any]] = None,
|
|
83
|
+
api_key: Optional[str] = None,
|
|
84
|
+
host: Optional[str] = None,
|
|
85
|
+
enabled: bool = True,
|
|
86
|
+
offline: Optional[bool] = None,
|
|
87
|
+
flush_interval: float = 1.0,
|
|
88
|
+
max_batch_points: int = 10_000,
|
|
89
|
+
max_memory_bytes: int = 256 * 1024 * 1024,
|
|
90
|
+
) -> Union[Run, NoopRun]:
|
|
91
|
+
"""Start a run and return it (also becomes the target of ``kymo.log``).
|
|
92
|
+
|
|
93
|
+
``api_key`` defaults to ``$KYMO_API_KEY``, ``host`` to ``$KYMO_HOST`` or
|
|
94
|
+
``http://localhost:8080``. Every process that calls ``init`` logs; pass
|
|
95
|
+
``enabled=False`` (e.g. ``enabled=(worker_id == 0)``) to get a no-op run.
|
|
96
|
+
Never raises: on any internal problem a warning is logged and a no-op run
|
|
97
|
+
returned.
|
|
98
|
+
"""
|
|
99
|
+
global _last
|
|
100
|
+
try:
|
|
101
|
+
proj = _clean_project(project)
|
|
102
|
+
exp = _clean_experiment(experiment)
|
|
103
|
+
if env_bool("KYMO_DISABLED"):
|
|
104
|
+
_last = NoopRun(proj, exp, "KYMO_DISABLED")
|
|
105
|
+
return _last
|
|
106
|
+
if not enabled:
|
|
107
|
+
_last = NoopRun(proj, exp, "enabled=False")
|
|
108
|
+
return _last
|
|
109
|
+
|
|
110
|
+
key = api_key if api_key else env_str("KYMO_API_KEY")
|
|
111
|
+
raw_host = host if host else env_str("KYMO_HOST", DEFAULT_HOST)
|
|
112
|
+
base = _normalize_host(raw_host or DEFAULT_HOST)
|
|
113
|
+
off = env_bool("KYMO_OFFLINE") if offline is None else bool(offline)
|
|
114
|
+
if base is None:
|
|
115
|
+
warn_once(("bad-host", raw_host), "KYMO_HOST %r is not an http(s) URL; running offline (spool only)", raw_host)
|
|
116
|
+
base = DEFAULT_HOST
|
|
117
|
+
off = True
|
|
118
|
+
if not key and not off:
|
|
119
|
+
warn_once("no-key", "no API key (set KYMO_API_KEY or pass api_key=); running offline, data is spooled "
|
|
120
|
+
"to disk for `python -m kymo sync`")
|
|
121
|
+
off = True
|
|
122
|
+
|
|
123
|
+
run = Run(
|
|
124
|
+
proj,
|
|
125
|
+
exp,
|
|
126
|
+
config=config,
|
|
127
|
+
api_key=key,
|
|
128
|
+
host=base,
|
|
129
|
+
spool_dir=default_spool_dir(),
|
|
130
|
+
offline=off,
|
|
131
|
+
flush_interval=flush_interval,
|
|
132
|
+
max_batch_points=max_batch_points,
|
|
133
|
+
max_memory_bytes=max_memory_bytes,
|
|
134
|
+
exit_timeout=env_float("KYMO_EXIT_TIMEOUT", 30.0),
|
|
135
|
+
http_timeout=env_float("KYMO_HTTP_TIMEOUT", 60.0),
|
|
136
|
+
)
|
|
137
|
+
with _lock:
|
|
138
|
+
_runs.append(run)
|
|
139
|
+
_install_hooks()
|
|
140
|
+
_last = run
|
|
141
|
+
return run
|
|
142
|
+
except Exception as e:
|
|
143
|
+
warn_once(("init-bug", type(e).__name__), "could not start run (%r); logging disabled", e)
|
|
144
|
+
_last = NoopRun(str(project), str(experiment), "init failed")
|
|
145
|
+
return _last
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def log(data: Mapping[str, Any], step: Optional[int] = None) -> None:
|
|
149
|
+
"""``run.log`` on the most recent run (no-op if there is none)."""
|
|
150
|
+
r = _last
|
|
151
|
+
if r is not None:
|
|
152
|
+
r.log(data, step)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def flush(timeout: Optional[float] = 30.0) -> bool:
|
|
156
|
+
"""Wait until the most recent run's data is acknowledged by the server."""
|
|
157
|
+
r = _last
|
|
158
|
+
return r.flush(timeout) if r is not None else True
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def finish(status: Optional[str] = None, timeout: Optional[float] = None) -> None:
|
|
162
|
+
"""Finish the most recent run."""
|
|
163
|
+
r = _last
|
|
164
|
+
if r is not None:
|
|
165
|
+
r.finish(status, timeout)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# --------------------------------------------------------------------- hooks
|
|
169
|
+
def _excepthook(tp: Any, value: Any, tb: Any) -> None:
|
|
170
|
+
global _exc_seen
|
|
171
|
+
_exc_seen = True
|
|
172
|
+
prev = _prev_excepthook or sys.__excepthook__
|
|
173
|
+
prev(tp, value, tb)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _atexit() -> None:
|
|
177
|
+
if os.getpid() != _owner_pid:
|
|
178
|
+
return # forked child that exits through sys.exit(): not our runs
|
|
179
|
+
with _lock:
|
|
180
|
+
runs = list(_runs)
|
|
181
|
+
_runs.clear()
|
|
182
|
+
if not runs:
|
|
183
|
+
return
|
|
184
|
+
status = "failed" if _exc_seen else "finished"
|
|
185
|
+
timeout = env_float("KYMO_EXIT_TIMEOUT", 30.0)
|
|
186
|
+
deadline = time.monotonic() + timeout
|
|
187
|
+
for r in runs:
|
|
188
|
+
try:
|
|
189
|
+
r.finish(status, timeout=max(0.0, deadline - time.monotonic()))
|
|
190
|
+
except Exception:
|
|
191
|
+
pass
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _install_hooks() -> None:
|
|
195
|
+
global _hooks_installed, _prev_excepthook
|
|
196
|
+
if _hooks_installed:
|
|
197
|
+
return
|
|
198
|
+
_hooks_installed = True
|
|
199
|
+
_prev_excepthook = sys.excepthook
|
|
200
|
+
sys.excepthook = _excepthook
|
|
201
|
+
atexit.register(_atexit)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _after_fork_child() -> None:
|
|
205
|
+
global _lock, _last, _owner_pid, _exc_seen
|
|
206
|
+
_lock = threading.Lock()
|
|
207
|
+
for r in _runs:
|
|
208
|
+
try:
|
|
209
|
+
r._after_fork_child()
|
|
210
|
+
except Exception:
|
|
211
|
+
pass
|
|
212
|
+
_runs.clear()
|
|
213
|
+
_last = None
|
|
214
|
+
_owner_pid = os.getpid()
|
|
215
|
+
_exc_seen = False
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
if hasattr(os, "register_at_fork"):
|
|
219
|
+
os.register_at_fork(after_in_child=_after_fork_child)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _finish_all(timeout: float = 5.0) -> None:
|
|
223
|
+
"""Finish every live run (used by tests)."""
|
|
224
|
+
with _lock:
|
|
225
|
+
runs = list(_runs)
|
|
226
|
+
_runs.clear()
|
|
227
|
+
for r in runs:
|
|
228
|
+
r.finish(timeout=timeout)
|
|
229
|
+
|
|
230
|
+
|
kymo/__main__.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Command line: ``python -m kymo sync`` replays the disk spool."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from typing import List, Optional
|
|
8
|
+
|
|
9
|
+
from . import DEFAULT_HOST, _normalize_host
|
|
10
|
+
from ._sender import AUTH, DROP, GIVEUP, SPLIT, Batch, Sender, split_batch
|
|
11
|
+
from ._spool import Spool
|
|
12
|
+
from ._transport import Transport
|
|
13
|
+
from ._util import default_spool_dir, env_float, env_str
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _sync(args: argparse.Namespace) -> int:
|
|
17
|
+
host = _normalize_host(args.host or env_str("KYMO_HOST", DEFAULT_HOST) or DEFAULT_HOST)
|
|
18
|
+
if host is None:
|
|
19
|
+
print("kymo: invalid host", file=sys.stderr)
|
|
20
|
+
return 2
|
|
21
|
+
key = args.api_key or env_str("KYMO_API_KEY")
|
|
22
|
+
spool = Spool(args.dir or default_spool_dir(), host, key)
|
|
23
|
+
files = spool.pending(all_hosts=args.all_hosts)
|
|
24
|
+
if args.dry_run or not files:
|
|
25
|
+
for f in files:
|
|
26
|
+
print(f)
|
|
27
|
+
print("kymo: %d spooled file(s) in %s for %s" % (len(files), spool.dir, host))
|
|
28
|
+
return 0
|
|
29
|
+
if not key:
|
|
30
|
+
print("kymo: no API key (set KYMO_API_KEY or pass --api-key)", file=sys.stderr)
|
|
31
|
+
return 2
|
|
32
|
+
transport = Transport(host, key, timeout=env_float("KYMO_HTTP_TIMEOUT", 60.0))
|
|
33
|
+
sender = Sender(transport, None, spool, replay=False)
|
|
34
|
+
sender.max_failures = args.max_failures
|
|
35
|
+
sent = dropped = failed = 0
|
|
36
|
+
for path in files:
|
|
37
|
+
got = spool.claim(path)
|
|
38
|
+
if got is None:
|
|
39
|
+
continue
|
|
40
|
+
claimed, body = got
|
|
41
|
+
queue: List[Batch] = [Batch(body, int(body.get("seq") or 0), "replay")]
|
|
42
|
+
ok = True
|
|
43
|
+
while queue:
|
|
44
|
+
b = queue.pop(0)
|
|
45
|
+
res = sender.deliver(b)
|
|
46
|
+
if res == SPLIT:
|
|
47
|
+
halves = split_batch(b)
|
|
48
|
+
if halves:
|
|
49
|
+
queue[:0] = halves
|
|
50
|
+
continue
|
|
51
|
+
if res == DROP:
|
|
52
|
+
dropped += 1
|
|
53
|
+
elif res in (AUTH, GIVEUP):
|
|
54
|
+
ok = False
|
|
55
|
+
break
|
|
56
|
+
if ok:
|
|
57
|
+
Spool.remove(claimed)
|
|
58
|
+
sent += 1
|
|
59
|
+
else:
|
|
60
|
+
Spool.release(claimed)
|
|
61
|
+
failed += 1
|
|
62
|
+
if res == AUTH:
|
|
63
|
+
print("kymo: server rejected the API key; stopping", file=sys.stderr)
|
|
64
|
+
break
|
|
65
|
+
if res == GIVEUP:
|
|
66
|
+
print("kymo: server unreachable; stopping (files kept)", file=sys.stderr)
|
|
67
|
+
break
|
|
68
|
+
transport.close()
|
|
69
|
+
print("kymo: replayed %d file(s) to %s (%d rejected as malformed, %d kept)" % (sent, host, dropped, len(files) - sent))
|
|
70
|
+
return 0 if failed == 0 else 1
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
74
|
+
p = argparse.ArgumentParser(prog="python -m kymo", description="Kymo SDK utilities")
|
|
75
|
+
sub = p.add_subparsers(dest="cmd")
|
|
76
|
+
s = sub.add_parser("sync", help="send spooled (unsent) data to the server")
|
|
77
|
+
s.add_argument("--host", help="server URL (default $KYMO_HOST or %s)" % DEFAULT_HOST)
|
|
78
|
+
s.add_argument("--api-key", help="API token (default $KYMO_API_KEY)")
|
|
79
|
+
s.add_argument("--dir", help="spool directory (default $KYMO_CACHE_DIR or ~/.cache/kymo/spool)")
|
|
80
|
+
s.add_argument("--all-hosts", action="store_true", help="also send files recorded for other hosts to --host")
|
|
81
|
+
s.add_argument("--dry-run", action="store_true", help="only list the files that would be sent")
|
|
82
|
+
s.add_argument("--max-failures", type=int, default=5, help="consecutive network failures before giving up")
|
|
83
|
+
args = p.parse_args(argv)
|
|
84
|
+
if args.cmd == "sync":
|
|
85
|
+
return _sync(args)
|
|
86
|
+
p.print_help()
|
|
87
|
+
return 2
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
if __name__ == "__main__":
|
|
91
|
+
sys.exit(main())
|
kymo/_encode.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Value conversion, flattening and JSON/gzip encoding (background thread only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import zlib
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from typing import Any, Callable, Dict, Tuple
|
|
10
|
+
|
|
11
|
+
_INF = float("inf")
|
|
12
|
+
_I64_MIN = -(2**63)
|
|
13
|
+
_I64_MAX = 2**63 - 1
|
|
14
|
+
GZIP_MIN_BYTES = 4096
|
|
15
|
+
MAX_KEY_BYTES = 256
|
|
16
|
+
_MAX_DEPTH = 32
|
|
17
|
+
|
|
18
|
+
_DROP = object()
|
|
19
|
+
_BAD_KEY_CHARS = re.compile("[\x00-\x1f\x7f-\x9f]")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _float(v: float) -> Any:
|
|
23
|
+
if v - v == 0.0: # finite (inf - inf and nan - nan are nan)
|
|
24
|
+
return v
|
|
25
|
+
if v != v:
|
|
26
|
+
return "NaN"
|
|
27
|
+
return "Infinity" if v > 0 else "-Infinity"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _int(v: int) -> Any:
|
|
31
|
+
if _I64_MIN <= v <= _I64_MAX:
|
|
32
|
+
return v
|
|
33
|
+
try:
|
|
34
|
+
return _float(float(v))
|
|
35
|
+
except OverflowError:
|
|
36
|
+
return _float(_INF if v > 0 else -_INF)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def to_number(v: Any) -> Any:
|
|
40
|
+
"""Convert one metric value to its wire form, or return ``_DROP``.
|
|
41
|
+
|
|
42
|
+
Generic rules, no knowledge of any library: plain numbers and bools, then
|
|
43
|
+
any object whose ``.item()`` returns a number, then anything with
|
|
44
|
+
``__float__``. Calling ``.item()``/``__float__`` may be slow for lazily
|
|
45
|
+
evaluated scalars, so this only ever runs on the background thread.
|
|
46
|
+
"""
|
|
47
|
+
t = type(v)
|
|
48
|
+
if t is float:
|
|
49
|
+
return _float(v)
|
|
50
|
+
if t is bool:
|
|
51
|
+
return 1 if v else 0
|
|
52
|
+
if t is int:
|
|
53
|
+
return _int(v)
|
|
54
|
+
if isinstance(v, (str, bytes, bytearray)) or v is None:
|
|
55
|
+
return _DROP
|
|
56
|
+
if isinstance(v, bool):
|
|
57
|
+
return 1 if v else 0
|
|
58
|
+
if isinstance(v, int):
|
|
59
|
+
return _int(int(v))
|
|
60
|
+
if isinstance(v, float):
|
|
61
|
+
return _float(float(v))
|
|
62
|
+
item = getattr(v, "item", None)
|
|
63
|
+
if item is not None and callable(item):
|
|
64
|
+
try:
|
|
65
|
+
x = item()
|
|
66
|
+
except Exception:
|
|
67
|
+
return _DROP # e.g. a multi-element container
|
|
68
|
+
tx = type(x)
|
|
69
|
+
if tx is bool or isinstance(x, bool):
|
|
70
|
+
return 1 if x else 0
|
|
71
|
+
if tx is int or isinstance(x, int):
|
|
72
|
+
return _int(int(x))
|
|
73
|
+
if tx is float or isinstance(x, float):
|
|
74
|
+
return _float(float(x))
|
|
75
|
+
return _DROP # complex, str, ...
|
|
76
|
+
# Fraction, Decimal and any other object implementing __float__.
|
|
77
|
+
if hasattr(type(v), "__float__"):
|
|
78
|
+
try:
|
|
79
|
+
return _float(float(v))
|
|
80
|
+
except Exception:
|
|
81
|
+
return _DROP
|
|
82
|
+
return _DROP
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def flatten(
|
|
86
|
+
out: Dict[str, Any],
|
|
87
|
+
data: Mapping,
|
|
88
|
+
prefix: str,
|
|
89
|
+
on_drop: Callable[[str, Any], None],
|
|
90
|
+
depth: int = 0,
|
|
91
|
+
) -> None:
|
|
92
|
+
"""Flatten nested mappings into ``out`` with "/" separators, converting values."""
|
|
93
|
+
for k, v in data.items():
|
|
94
|
+
key = prefix + (k if type(k) is str else str(k))
|
|
95
|
+
t = type(v)
|
|
96
|
+
if t is float:
|
|
97
|
+
out[key] = v if v - v == 0.0 else _float(v)
|
|
98
|
+
elif t is int:
|
|
99
|
+
out[key] = _int(v)
|
|
100
|
+
elif t is dict or isinstance(v, Mapping):
|
|
101
|
+
if depth < _MAX_DEPTH:
|
|
102
|
+
flatten(out, v, key + "/", on_drop, depth + 1)
|
|
103
|
+
else:
|
|
104
|
+
r = to_number(v)
|
|
105
|
+
if r is _DROP:
|
|
106
|
+
on_drop(key, v)
|
|
107
|
+
else:
|
|
108
|
+
out[key] = r
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def key_is_valid(key: str) -> bool:
|
|
112
|
+
try:
|
|
113
|
+
n = len(key.encode("utf-8"))
|
|
114
|
+
except UnicodeEncodeError:
|
|
115
|
+
return False
|
|
116
|
+
return 1 <= n <= MAX_KEY_BYTES and _BAD_KEY_CHARS.search(key) is None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def sanitize_json(v: Any, depth: int = 0) -> Any:
|
|
120
|
+
"""Make an arbitrary config value JSON-safe (used for ``config`` only)."""
|
|
121
|
+
if depth > _MAX_DEPTH:
|
|
122
|
+
return str(v)
|
|
123
|
+
t = type(v)
|
|
124
|
+
if v is None or t is str or t is bool:
|
|
125
|
+
return v
|
|
126
|
+
if t is int:
|
|
127
|
+
return v
|
|
128
|
+
if t is float:
|
|
129
|
+
return _float(v)
|
|
130
|
+
if isinstance(v, Mapping):
|
|
131
|
+
return {str(k): sanitize_json(x, depth + 1) for k, x in v.items()}
|
|
132
|
+
if isinstance(v, (list, tuple, set, frozenset)):
|
|
133
|
+
return [sanitize_json(x, depth + 1) for x in v]
|
|
134
|
+
if isinstance(v, bool):
|
|
135
|
+
return bool(v)
|
|
136
|
+
if isinstance(v, int):
|
|
137
|
+
return int(v)
|
|
138
|
+
if isinstance(v, str):
|
|
139
|
+
return str(v)
|
|
140
|
+
r = to_number(v)
|
|
141
|
+
if r is not _DROP:
|
|
142
|
+
return r
|
|
143
|
+
return str(v)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def dumps(obj: Any) -> bytes:
|
|
147
|
+
return json.dumps(obj, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
_point_encoder = json.JSONEncoder(separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode
|
|
151
|
+
|
|
152
|
+
# Bytes fed to zlib per call. Small enough that no single C call holds the GIL for long.
|
|
153
|
+
_GZIP_CHUNK = 64 * 1024
|
|
154
|
+
# Points JSON-encoded per C call.
|
|
155
|
+
_POINT_CHUNK = 64
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _dumps_incremental(obj: Any) -> bytes:
|
|
159
|
+
"""Same bytes as dumps(obj), but built in chunks of points.
|
|
160
|
+
|
|
161
|
+
json.dumps of a whole 250k-value batch is one C call that holds the GIL for tens of
|
|
162
|
+
milliseconds, stalling a pure-Python training thread. Encoding _POINT_CHUNK points per
|
|
163
|
+
call (~0.2 ms each, same total CPU) lets the interpreter switch back to it in between.
|
|
164
|
+
"""
|
|
165
|
+
pts = obj.get("points") if isinstance(obj, dict) else None
|
|
166
|
+
if not pts or len(pts) <= _POINT_CHUNK:
|
|
167
|
+
return dumps(obj)
|
|
168
|
+
head = {k: v for k, v in obj.items() if k != "points"}
|
|
169
|
+
hb = dumps(head) # b"{...}"
|
|
170
|
+
parts = [hb[:-1] + (b',"points":[' if head else b'"points":[')]
|
|
171
|
+
enc = _point_encoder
|
|
172
|
+
for i in range(0, len(pts), _POINT_CHUNK):
|
|
173
|
+
s = enc(pts[i : i + _POINT_CHUNK])[1:-1].encode("utf-8") # strip [ ]
|
|
174
|
+
parts.append(s if i == 0 else b"," + s)
|
|
175
|
+
parts.append(b"]}")
|
|
176
|
+
return b"".join(parts)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def encode_body(obj: Any) -> Tuple[bytes, bool]:
|
|
180
|
+
"""Return (wire bytes, gzipped?)."""
|
|
181
|
+
raw = _dumps_incremental(obj)
|
|
182
|
+
if len(raw) <= GZIP_MIN_BYTES:
|
|
183
|
+
return raw, False
|
|
184
|
+
co = zlib.compressobj(3, zlib.DEFLATED, 31) # wbits=31 -> gzip container, mtime 0
|
|
185
|
+
mv = memoryview(raw)
|
|
186
|
+
out = [co.compress(mv[i : i + _GZIP_CHUNK]) for i in range(0, len(raw), _GZIP_CHUNK)]
|
|
187
|
+
out.append(co.flush())
|
|
188
|
+
return b"".join(out), True
|