kymo-logger 0.1.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.
@@ -0,0 +1,3 @@
1
+ .venv/
2
+ .pytest_cache/
3
+ bench/.bench-spool/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,119 @@
1
+ # NOTES — Python SDK (`sdk/python`, package `kymo`)
2
+
3
+ ## Layout
4
+
5
+ | path | what it does |
6
+ |---|---|
7
+ | `src/kymo/__init__.py` | public API: `init`, `log`, `flush`, `finish`. Also the atexit hook, chained excepthook, fork handler and the `enabled=` switch. |
8
+ | `src/kymo/_run.py` | `Run` (hot-path `log()`, plus the `kymo-collector` thread that converts and batches) and `NoopRun` |
9
+ | `src/kymo/_sender.py` | `Batch`, the memory-capped `Outbox`, and the `kymo-sender` thread (retry, backoff, 413 split, spool replay) |
10
+ | `src/kymo/_transport.py` | keep-alive `http.client` connection, proxy resolution, CONNECT tunnel, proxy basic auth |
11
+ | `src/kymo/_spool.py` | disk spool: atomic writes, claim-by-rename, replay matching |
12
+ | `src/kymo/_encode.py` | flattening, value conversion, JSON/gzip |
13
+ | `src/kymo/__main__.py` | `python -m kymo sync` |
14
+ | `tests/` | pytest suite. `tests/fakes.py` has the fake ingest server, the forwarding/CONNECT proxy and the hanging server. |
15
+ | `bench/bench_log.py` | hot-path benchmark |
16
+
17
+ ## Data flow
18
+
19
+ 1. **Training thread.** `run.log(d, step)` runs `self._push((step, time(), d.copy()))`, where `_push` is the bound `deque.append`. Nothing else happens there. When the run finishes, or in a forked child, `_push` is swapped for a no-op, so the hot path has no flag checks.
20
+ 2. **`kymo-collector`.** Every 50 ms it drains the deque. For each entry it flattens the dict, converts values generically (plain numbers and bools, then `.item()` returning a number, then `__float__`) and validates keys, then appends a point to the current batch. A batch is closed at `flush_interval` (1 s), at `max_batch_points` (10 000 points) or at 250 000 values. Closing a batch JSON-encodes it, gzips it if it is over 4 KiB, and puts it into the outbox. The collector calls `sleep(0)` every 512 entries to release the GIL. `flush()` and `finish()` only *ask* the collector to drain, so `.item()` / `__float__` never run on the caller's thread.
21
+ 3. **Outbox.** A FIFO of encoded batches, capped at `max_memory_bytes` of wire bytes. Batches that overflow the cap go to the spool.
22
+ 4. **`kymo-sender`.**
23
+ * Posts batches one at a time over a single keep-alive connection.
24
+ * If a reused connection turns out to be stale, it reconnects once immediately.
25
+ * When the outbox is empty, it claims spool files that match this host and token and replays them.
26
+
27
+ ## Benchmark (`uv run python bench/bench_log.py`, AMD Ryzen 5 9600X, Linux)
28
+
29
+ Per-call cost of `run.log(d)` for a 10-key flat dict. The fake ingest server runs in a separate process, so the background threads really encode and POST while the loop runs and compete for the GIL. Each figure is the median and minimum over 7 rounds of 200 000 calls.
30
+
31
+ | case | Python 3.14.8 median / min (µs) | Python 3.9.25 median / min (µs) |
32
+ |---|---|---|
33
+ | empty loop | 0.004 / 0.004 | 0.007 / 0.007 |
34
+ | baseline `deque.append((i, time(), d.copy()))` | 0.33 / 0.31 | 0.37 / 0.33 |
35
+ | `run.log(d10, step=i)` | **0.93 / 0.39** | 0.83 / 0.50 |
36
+ | `run.log(d10)` | 0.79 / 0.33 | 0.82 / 0.50 |
37
+ | `run.log(nested, 10 values)` | 0.88 / 0.32 | 1.43 / 0.60 |
38
+ | `kymo.log(d10)` | 1.02 / 0.21 | 0.92 / 0.37 |
39
+
40
+ The target was ≤ 2 µs per call, and it is met.
41
+
42
+ * **Median vs. minimum.** The minimum is the uncontended cost. The gap up to the median is the GIL being held by the background thread while it converts the 200 000 entries just queued.
43
+ * **Background throughput.** About 165k points/s of 10-key points through convert, JSON, gzip, POST and ack on 3.14, and about 67k/s on 3.9.
44
+ * **Hanging server.** In `test_training_thread_never_waits_on_hanging_server`, 100 000 `log()` calls against a server that accepts and never answers take about 0.04 s (0.4 µs per call). `finish(timeout=1)` then returns in about 1 s, and all 100 000 points end up in the spool.
45
+
46
+ ## Deviations and additions to SPEC §3 and §5
47
+
48
+ All of these are backward compatible.
49
+
50
+ ### What the server must accept
51
+
52
+ 1. **Hello request.** `init()` immediately sends a request with `points: []` that carries `status: "running"`, `host` and `config`, so the experiment shows up before the first metric. The final status (`finished` or `failed`) also goes out as its own request with `points: []`. **The server must accept an empty `points` array.**
53
+ 2. **`seq`.** `seq` is per request. When a batch is split after a 413, both halves keep the original `seq` (the field is informational).
54
+
55
+ ### Status codes
56
+
57
+ 3. **Not retried.** 400, 401, 403 and every other 4xx except 407, 408, 413, 425 and 429 cause one warning, and the batch is dropped.
58
+ * After a 401 or 403, the sender stops replaying the spool for the rest of that process. The spool files are kept.
59
+ * 3xx responses are dropped too.
60
+ 4. **Retried.** 407 (proxy auth) is retried with backoff and a warning. It is a proxy problem, not the server rejecting the data.
61
+ 5. **413 split.** A 413 on a single point with many metrics splits the point's metrics dict. A single value that still gets 413 is dropped.
62
+ 6. **Client-side size cap.** Requests are capped at 10 000 points or 250 000 values, well under the server's 1M values / 64 MiB limit, so a 413 should be rare.
63
+
64
+ ### Exit and finishing
65
+
66
+ 7. **Early give-up.** While finishing, the sender gives up after 3 consecutive failures, or as soon as the next backoff would pass the deadline. It then spools the rest instead of always waiting the full `KYMO_EXIT_TIMEOUT` when the server is plainly down.
67
+ * If a request is stuck on a hanging socket, `finish()` returns at the deadline and shuts the socket down.
68
+ * A batch that was still in flight is spooled as well. If the server later commits it, the replay is a harmless duplicate because ingest upserts.
69
+ 8. **Exit status.** `failed` is set only through `sys.excepthook` (uncaught exceptions, including `KeyboardInterrupt`). `sys.exit(1)` does not call the excepthook, so the run is marked `finished`. `Run` can also be used as a context manager (`failed` if the block raises) and has `finish(status=...)`.
70
+
71
+ ### Disk spool
72
+
73
+ 9. **File format.** Each spool file is JSON: `{"kymo_spool":1,"host":…,"token":<sha256(api_key)[:16] | "anon">,"created":…,"body":<ingest body>}`.
74
+ * The file name encodes host and token hashes, so replayers pick their own files without opening them.
75
+ * The token itself is never written to disk.
76
+ * Files from a run without an API key (`anon`) are replayed with whichever key the replayer has.
77
+ * Claiming works by atomic rename to `*.claimed.<pid>`. Claims left by dead PIDs are recovered.
78
+ 10. **No resurrected runs.** A `"status":"running"` is removed from any spooled body. Otherwise a late replay could flip an experiment that has finished back to running.
79
+
80
+ ### Init defaults and validation
81
+
82
+ * **Multi-process: no launcher detection.** No environment variables are inspected to decide who logs; every process that calls `init()` logs. `kymo.init(..., enabled=False)` returns a `NoopRun`. There is no per-process key prefix (updated SPEC §5).
83
+
84
+ 11. **No API key.** If no key is found, kymo warns and runs **offline**, so data goes to the spool instead of being rejected with 401 and lost. An invalid `KYMO_HOST` also forces offline mode.
85
+ 12. **Bad names.** Invalid project names are sanitized (characters outside `[A-Za-z0-9_.-]` become `-`, truncated to 64) with a warning instead of raising. A job that has waited hours in a queue should not die on a typo.
86
+ 13. **Experiment name.** `experiment` is optional and defaults to `<hostname>-<YYYYmmdd-HHMMSS>`. Names are truncated to 128 characters.
87
+
88
+ ### Proxies
89
+
90
+ 14. **`ALL_PROXY` fallback.** `ALL_PROXY` is used when `<scheme>_proxy` is unset. That matches curl and requests; urllib's own `ProxyHandler` ignores it.
91
+ 15. **Proxy schemes.**
92
+ * The connection to the proxy is always plaintext, even for `https://` proxy URLs. This matches urllib.
93
+ * A scheme-less value such as `host:3128` is accepted.
94
+ * SOCKS proxies are unsupported. kymo warns and connects directly.
95
+
96
+ ### Extra environment variables and API
97
+
98
+ 16. **Environment variables.** `KYMO_HTTP_TIMEOUT` (60 s read timeout; connect is 10 s) and `KYMO_CA_BUNDLE` (a custom CA for https; `SSL_CERT_FILE` also works through OpenSSL's defaults).
99
+ 17. **API additions.**
100
+ * `run.flush(timeout) -> bool` and `kymo.flush()` block until everything logged so far is acknowledged.
101
+ * `log()` after `finish()` is a silent no-op.
102
+ * `step` may be any object with `.item()` or `__int__`; it is converted on the background thread.
103
+ 18. **Value conversion.**
104
+ * Ints outside the i64 range are sent as floats.
105
+ * Subclasses of `int`/`float`, objects whose `.item()` returns a number, and anything with `__float__` (`Fraction`, `Decimal`, ...) are accepted. The SDK imports and names no third-party library.
106
+ * Values in `config` that are not finite are encoded as `"NaN"` / `"Infinity"` strings, and objects that can't be serialized are encoded with `str()`.
107
+
108
+ ### Known limits
109
+
110
+ 19. **Memory cap.** The cap counts encoded wire bytes in the outbox, not the raw dicts still waiting in the deque. The deque is unbounded, but the collector drains it every 50 ms.
111
+ 20. **Shallow copy.** `log()` copies only the top-level dict, as the spec says. If a nested dict is mutated after `log()`, the background thread may see the new values.
112
+ 21. **GIL.** The collector holds the GIL while it converts values. It yields every 512 entries, and zlib releases the GIL while compressing. At realistic logging rates (≤ 1000 calls/s) its CPU share is negligible.
113
+
114
+ ## Integration fix: chunked JSON encoding (added during end-to-end testing)
115
+
116
+ `json.dumps` of a whole batch (up to 250k values) is one C call that holds the GIL ~35 ms, which
117
+ stalled a pure-Python training loop by up to 76 ms in the e2e run. `encode_body` now encodes points
118
+ 64 at a time (same total CPU, ~0.2 ms per call, byte-identical output) and feeds gzip in 64 KiB pieces.
119
+ Worst training-thread stall is now ≈ the 5 ms GIL switch interval. Covered by `tests/test_encode_chunked.py`.
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.5
2
+ Name: kymo-logger
3
+ Version: 0.1.0
4
+ Summary: Non-blocking Python logging SDK for the Kymo ML experiment tracker
5
+ Project-URL: Repository, https://github.com/Kelvinlby/kymo
6
+ Project-URL: Issues, https://github.com/Kelvinlby/kymo/issues
7
+ Project-URL: Documentation, https://github.com/Kelvinlby/kymo/tree/main/sdk/python
8
+ Author: Kelvin
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: experiment-tracking,logging,machine-learning,metrics
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+
18
+ # kymo — Python SDK
19
+
20
+ You hand kymo a dict of numbers and it gets them to a [Kymo](https://github.com/Kelvinlby/kymo/blob/main/SPEC.md) server, without slowing down or crashing the loop that produced them.
21
+
22
+ * `run.log()` costs well under a microsecond: it shallow-copies your dict and appends it to a deque. Nothing else happens on your thread.
23
+ * Flattening, value conversion, JSON, gzip, HTTP, retries and the disk spool all run on background daemon threads.
24
+ * Nothing in this package raises into your code. Problems are reported as warnings on the `kymo` logger.
25
+ * There are no runtime dependencies (stdlib only), and it needs Python ≥ 3.9. kymo works with any framework, because it doesn't know about any of them.
26
+
27
+ ```bash
28
+ pip install kymo-logger # or: uv add kymo-logger
29
+ export KYMO_HOST=https://kymo.example.com
30
+ export KYMO_API_KEY=kymo_... # create one in the web UI: Settings → API tokens
31
+ ```
32
+
33
+ The package is published on PyPI as `kymo-logger` (the name `kymo` belongs to an unrelated project); you still `import kymo`. To track unreleased changes on `main` instead, use a git source:
34
+
35
+ ```toml
36
+ [tool.uv.sources]
37
+ kymo-logger = { git = "https://github.com/Kelvinlby/kymo", subdirectory = "sdk/python", branch = "main" }
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```python
43
+ import kymo
44
+
45
+ run = kymo.init(project="llm-pretrain", experiment="lr3e-4", config={"lr": 3e-4, "model": {"d": 4096}})
46
+ for step in range(1000):
47
+ loss = 2.3 / (step + 1)
48
+ run.log({"train/loss": loss, "lr": 3e-4, "eval": {"acc": 0.71, "loss": 2.4}}, step=step)
49
+ run.finish() # optional: also done automatically at exit
50
+ ```
51
+
52
+ * **Keys.** Nested dicts become `/`-separated keys: the dict above logs `train/loss`, `lr`, `eval/acc` and `eval/loss`. The UI groups keys by the part before the first `/`.
53
+ * **Values.**
54
+ * Accepted:
55
+ * ints and floats
56
+ * bools, sent as 0/1
57
+ * NaN and ±Inf, sent as `"NaN"` / `"Infinity"` / `"-Infinity"`
58
+ * any object whose `.item()` returns a number
59
+ * any object with `__float__`
60
+ * Conversion happens later, on the background thread, so a value that is slow to read never blocks you.
61
+ * Strings, `None` and other non-numeric values are dropped, with one warning per key.
62
+ * **`step`** is optional. If you leave it out, it auto-increments (one past the previous step).
63
+ * **`config`** is any JSON-like dict. It is sent once at `init` and shallow-merged into the experiment's config on the server.
64
+ * **Shortcuts.** Module-level `kymo.log(...)`, `kymo.flush()` and `kymo.finish()` act on the most recent run.
65
+ * **Context manager.** `with kymo.init(...) as run:` marks the run `failed` if the block raises. Otherwise, at exit the run is marked `finished`, or `failed` when the interpreter exits because of an uncaught exception.
66
+
67
+ ### Logging from just one process
68
+
69
+ Every process that calls `kymo.init` logs. kymo does not inspect any launcher environment variables. When several workers run the same script, decide yourself who logs:
70
+
71
+ ```python
72
+ run = kymo.init(project="p", experiment="e", enabled=(worker_id == 0))
73
+ run.log({"loss": 1.2}) # a no-op on the other workers; no `if` needed around each call
74
+ ```
75
+
76
+ To log from every worker, give each one its own experiment name or key prefix, e.g. `{f"worker{worker_id}/loss": ...}`.
77
+
78
+ After `os.fork()` the child's inherited runs turn into no-ops. The child can call `kymo.init` again to start its own run.
79
+
80
+ ## Offline use and the disk spool
81
+
82
+ * **Retries.** Network errors, 429 and 5xx are retried with exponential backoff and full jitter (0.5 s doubling to a 60 s cap), honoring `Retry-After`.
83
+ * **No retry.** 400/401/403 are never retried: kymo logs one warning and drops the batch.
84
+ * **413.** The batch is split in half and resent.
85
+ * **Memory, then disk.** Unsent batches stay in memory up to `max_memory_bytes` (256 MiB by default). Beyond that, they spill to the spool directory (`KYMO_CACHE_DIR`).
86
+ * **Exit.** kymo flushes for up to `KYMO_EXIT_TIMEOUT` seconds, then writes whatever is left to the spool.
87
+ * **Replay.** Spooled files are replayed automatically by the next run that uses the same host and token. Replays are idempotent, because the server upserts by `(key, step)`.
88
+
89
+ ```bash
90
+ python -m kymo sync # replay the spool now (uses KYMO_HOST / KYMO_API_KEY)
91
+ python -m kymo sync --dry-run # just list what would be sent; also --dir, --all-hosts, --host, --api-key
92
+ ```
93
+
94
+ On a machine without network access, set `KYMO_OFFLINE=1`; everything goes to the spool. Later, copy the spool directory to a machine that can reach the server and run `python -m kymo sync` there, with `KYMO_CACHE_DIR` pointing at the copy. Without an API key, kymo also runs offline instead of losing data.
95
+
96
+ ## Proxies
97
+
98
+ Proxy settings come from `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` and `NO_PROXY`, in upper or lower case. kymo uses the same rules as `urllib.request.getproxies()` and `proxy_bypass()`; `ALL_PROXY` is used as a fallback.
99
+
100
+ * **Plain http:** requests go through the proxy with an absolute-URI request line.
101
+ * **https:** kymo opens a `CONNECT` tunnel. TLS runs end to end, and the certificate is verified against the real server name.
102
+ * **Credentials:** `http://user:pass@proxy:3128` is sent as `Proxy-Authorization: Basic`. Percent-encode special characters, e.g. `@` → `%40`.
103
+ * **Connections:** both modes keep the connection alive between batches.
104
+ * **SOCKS:** SOCKS proxies are not supported. kymo connects directly and logs a warning.
105
+
106
+ ```bash
107
+ export HTTPS_PROXY=http://alice:s3cr%40t@proxy.corp:3128
108
+ export NO_PROXY=localhost,127.0.0.1,.internal
109
+ ```
110
+
111
+ ## Configuration
112
+
113
+ | env var | default | meaning |
114
+ |---|---|---|
115
+ | `KYMO_API_KEY` | – | API token (`kymo_...`). Without one, the run is offline and spools to disk. |
116
+ | `KYMO_HOST` | `http://localhost:8080` | server URL; a path prefix is allowed |
117
+ | `KYMO_DISABLED` | – | `1` makes everything a no-op |
118
+ | `KYMO_OFFLINE` | – | `1` only spools to disk |
119
+ | `KYMO_CACHE_DIR` | `~/.cache/kymo/spool` | spool directory |
120
+ | `KYMO_EXIT_TIMEOUT` | `30` | seconds to flush at exit before spooling the rest |
121
+ | `KYMO_HTTP_TIMEOUT` | `60` | socket read timeout per request (the connect timeout is 10 s) |
122
+ | `KYMO_CA_BUNDLE` | – | CA file for https (`SSL_CERT_FILE` also works) |
123
+ | `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY` | – | proxies (see above) |
124
+
125
+ `kymo.init` takes these keyword arguments:
126
+
127
+ * `project` and `experiment` (if `experiment` is omitted, it defaults to `<hostname>-<timestamp>`)
128
+ * `config`, `api_key`, `host`
129
+ * `enabled` (default `True`)
130
+ * `offline`
131
+ * `flush_interval` (default 1.0 s)
132
+ * `max_batch_points` (default 10 000)
133
+ * `max_memory_bytes` (default 256 MiB)
134
+
135
+ `log()` takes a *shallow* copy. If you mutate a nested dict right after logging it, the background thread may see the new values.
136
+
137
+ ## No SDK needed
138
+
139
+ The SDK is a convenience. Anything that can send an HTTP POST can log to the ingest endpoint directly. The single-point shorthand puts `metrics` at the top level. `step` is optional; if you leave it out, the server assigns the next step for that experiment.
140
+
141
+ ```bash
142
+ curl -sS https://kymo.example.com/api/v1/ingest \
143
+ -H "Authorization: Bearer $KYMO_API_KEY" -H "Content-Type: application/json" \
144
+ -d '{"project":"p","experiment":"e","metrics":{"loss":1.2}}'
145
+ ```
146
+
147
+ The full form sends many points per request, along with optional config and status:
148
+
149
+ ```bash
150
+ curl -sS https://kymo.example.com/api/v1/ingest \
151
+ -H "Authorization: Bearer $KYMO_API_KEY" -H "Content-Type: application/json" \
152
+ -d '{"project":"p","experiment":"e","config":{"lr":0.0003},"status":"running",
153
+ "points":[{"step":1,"ts":1732400000.1,"metrics":{"train/loss":2.31,"lr":0.0003}},
154
+ {"step":2,"metrics":{"train/loss":2.12,"grad_norm":"NaN"}}]}'
155
+ ```
156
+
157
+ The project and experiment are created automatically. Values are JSON numbers, with `"NaN"` / `"Infinity"` / `"-Infinity"` as strings. You can also gzip the body and send `Content-Encoding: gzip`. A 200 response means the data is durably stored. See SPEC §3 for the details.
158
+
159
+ ## Development
160
+
161
+ ```bash
162
+ cd sdk/python
163
+ uv run --with pytest pytest -q # tests (fake ingest server, proxy and hanging server are in tests/fakes.py)
164
+ uv run python bench/bench_log.py # hot-path benchmark
165
+ ```
@@ -0,0 +1,148 @@
1
+ # kymo — Python SDK
2
+
3
+ You hand kymo a dict of numbers and it gets them to a [Kymo](https://github.com/Kelvinlby/kymo/blob/main/SPEC.md) server, without slowing down or crashing the loop that produced them.
4
+
5
+ * `run.log()` costs well under a microsecond: it shallow-copies your dict and appends it to a deque. Nothing else happens on your thread.
6
+ * Flattening, value conversion, JSON, gzip, HTTP, retries and the disk spool all run on background daemon threads.
7
+ * Nothing in this package raises into your code. Problems are reported as warnings on the `kymo` logger.
8
+ * There are no runtime dependencies (stdlib only), and it needs Python ≥ 3.9. kymo works with any framework, because it doesn't know about any of them.
9
+
10
+ ```bash
11
+ pip install kymo-logger # or: uv add kymo-logger
12
+ export KYMO_HOST=https://kymo.example.com
13
+ export KYMO_API_KEY=kymo_... # create one in the web UI: Settings → API tokens
14
+ ```
15
+
16
+ The package is published on PyPI as `kymo-logger` (the name `kymo` belongs to an unrelated project); you still `import kymo`. To track unreleased changes on `main` instead, use a git source:
17
+
18
+ ```toml
19
+ [tool.uv.sources]
20
+ kymo-logger = { git = "https://github.com/Kelvinlby/kymo", subdirectory = "sdk/python", branch = "main" }
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```python
26
+ import kymo
27
+
28
+ run = kymo.init(project="llm-pretrain", experiment="lr3e-4", config={"lr": 3e-4, "model": {"d": 4096}})
29
+ for step in range(1000):
30
+ loss = 2.3 / (step + 1)
31
+ run.log({"train/loss": loss, "lr": 3e-4, "eval": {"acc": 0.71, "loss": 2.4}}, step=step)
32
+ run.finish() # optional: also done automatically at exit
33
+ ```
34
+
35
+ * **Keys.** Nested dicts become `/`-separated keys: the dict above logs `train/loss`, `lr`, `eval/acc` and `eval/loss`. The UI groups keys by the part before the first `/`.
36
+ * **Values.**
37
+ * Accepted:
38
+ * ints and floats
39
+ * bools, sent as 0/1
40
+ * NaN and ±Inf, sent as `"NaN"` / `"Infinity"` / `"-Infinity"`
41
+ * any object whose `.item()` returns a number
42
+ * any object with `__float__`
43
+ * Conversion happens later, on the background thread, so a value that is slow to read never blocks you.
44
+ * Strings, `None` and other non-numeric values are dropped, with one warning per key.
45
+ * **`step`** is optional. If you leave it out, it auto-increments (one past the previous step).
46
+ * **`config`** is any JSON-like dict. It is sent once at `init` and shallow-merged into the experiment's config on the server.
47
+ * **Shortcuts.** Module-level `kymo.log(...)`, `kymo.flush()` and `kymo.finish()` act on the most recent run.
48
+ * **Context manager.** `with kymo.init(...) as run:` marks the run `failed` if the block raises. Otherwise, at exit the run is marked `finished`, or `failed` when the interpreter exits because of an uncaught exception.
49
+
50
+ ### Logging from just one process
51
+
52
+ Every process that calls `kymo.init` logs. kymo does not inspect any launcher environment variables. When several workers run the same script, decide yourself who logs:
53
+
54
+ ```python
55
+ run = kymo.init(project="p", experiment="e", enabled=(worker_id == 0))
56
+ run.log({"loss": 1.2}) # a no-op on the other workers; no `if` needed around each call
57
+ ```
58
+
59
+ To log from every worker, give each one its own experiment name or key prefix, e.g. `{f"worker{worker_id}/loss": ...}`.
60
+
61
+ After `os.fork()` the child's inherited runs turn into no-ops. The child can call `kymo.init` again to start its own run.
62
+
63
+ ## Offline use and the disk spool
64
+
65
+ * **Retries.** Network errors, 429 and 5xx are retried with exponential backoff and full jitter (0.5 s doubling to a 60 s cap), honoring `Retry-After`.
66
+ * **No retry.** 400/401/403 are never retried: kymo logs one warning and drops the batch.
67
+ * **413.** The batch is split in half and resent.
68
+ * **Memory, then disk.** Unsent batches stay in memory up to `max_memory_bytes` (256 MiB by default). Beyond that, they spill to the spool directory (`KYMO_CACHE_DIR`).
69
+ * **Exit.** kymo flushes for up to `KYMO_EXIT_TIMEOUT` seconds, then writes whatever is left to the spool.
70
+ * **Replay.** Spooled files are replayed automatically by the next run that uses the same host and token. Replays are idempotent, because the server upserts by `(key, step)`.
71
+
72
+ ```bash
73
+ python -m kymo sync # replay the spool now (uses KYMO_HOST / KYMO_API_KEY)
74
+ python -m kymo sync --dry-run # just list what would be sent; also --dir, --all-hosts, --host, --api-key
75
+ ```
76
+
77
+ On a machine without network access, set `KYMO_OFFLINE=1`; everything goes to the spool. Later, copy the spool directory to a machine that can reach the server and run `python -m kymo sync` there, with `KYMO_CACHE_DIR` pointing at the copy. Without an API key, kymo also runs offline instead of losing data.
78
+
79
+ ## Proxies
80
+
81
+ Proxy settings come from `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` and `NO_PROXY`, in upper or lower case. kymo uses the same rules as `urllib.request.getproxies()` and `proxy_bypass()`; `ALL_PROXY` is used as a fallback.
82
+
83
+ * **Plain http:** requests go through the proxy with an absolute-URI request line.
84
+ * **https:** kymo opens a `CONNECT` tunnel. TLS runs end to end, and the certificate is verified against the real server name.
85
+ * **Credentials:** `http://user:pass@proxy:3128` is sent as `Proxy-Authorization: Basic`. Percent-encode special characters, e.g. `@` → `%40`.
86
+ * **Connections:** both modes keep the connection alive between batches.
87
+ * **SOCKS:** SOCKS proxies are not supported. kymo connects directly and logs a warning.
88
+
89
+ ```bash
90
+ export HTTPS_PROXY=http://alice:s3cr%40t@proxy.corp:3128
91
+ export NO_PROXY=localhost,127.0.0.1,.internal
92
+ ```
93
+
94
+ ## Configuration
95
+
96
+ | env var | default | meaning |
97
+ |---|---|---|
98
+ | `KYMO_API_KEY` | – | API token (`kymo_...`). Without one, the run is offline and spools to disk. |
99
+ | `KYMO_HOST` | `http://localhost:8080` | server URL; a path prefix is allowed |
100
+ | `KYMO_DISABLED` | – | `1` makes everything a no-op |
101
+ | `KYMO_OFFLINE` | – | `1` only spools to disk |
102
+ | `KYMO_CACHE_DIR` | `~/.cache/kymo/spool` | spool directory |
103
+ | `KYMO_EXIT_TIMEOUT` | `30` | seconds to flush at exit before spooling the rest |
104
+ | `KYMO_HTTP_TIMEOUT` | `60` | socket read timeout per request (the connect timeout is 10 s) |
105
+ | `KYMO_CA_BUNDLE` | – | CA file for https (`SSL_CERT_FILE` also works) |
106
+ | `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY` | – | proxies (see above) |
107
+
108
+ `kymo.init` takes these keyword arguments:
109
+
110
+ * `project` and `experiment` (if `experiment` is omitted, it defaults to `<hostname>-<timestamp>`)
111
+ * `config`, `api_key`, `host`
112
+ * `enabled` (default `True`)
113
+ * `offline`
114
+ * `flush_interval` (default 1.0 s)
115
+ * `max_batch_points` (default 10 000)
116
+ * `max_memory_bytes` (default 256 MiB)
117
+
118
+ `log()` takes a *shallow* copy. If you mutate a nested dict right after logging it, the background thread may see the new values.
119
+
120
+ ## No SDK needed
121
+
122
+ The SDK is a convenience. Anything that can send an HTTP POST can log to the ingest endpoint directly. The single-point shorthand puts `metrics` at the top level. `step` is optional; if you leave it out, the server assigns the next step for that experiment.
123
+
124
+ ```bash
125
+ curl -sS https://kymo.example.com/api/v1/ingest \
126
+ -H "Authorization: Bearer $KYMO_API_KEY" -H "Content-Type: application/json" \
127
+ -d '{"project":"p","experiment":"e","metrics":{"loss":1.2}}'
128
+ ```
129
+
130
+ The full form sends many points per request, along with optional config and status:
131
+
132
+ ```bash
133
+ curl -sS https://kymo.example.com/api/v1/ingest \
134
+ -H "Authorization: Bearer $KYMO_API_KEY" -H "Content-Type: application/json" \
135
+ -d '{"project":"p","experiment":"e","config":{"lr":0.0003},"status":"running",
136
+ "points":[{"step":1,"ts":1732400000.1,"metrics":{"train/loss":2.31,"lr":0.0003}},
137
+ {"step":2,"metrics":{"train/loss":2.12,"grad_norm":"NaN"}}]}'
138
+ ```
139
+
140
+ The project and experiment are created automatically. Values are JSON numbers, with `"NaN"` / `"Infinity"` / `"-Infinity"` as strings. You can also gzip the body and send `Content-Encoding: gzip`. A 200 response means the data is durably stored. See SPEC §3 for the details.
141
+
142
+ ## Development
143
+
144
+ ```bash
145
+ cd sdk/python
146
+ uv run --with pytest pytest -q # tests (fake ingest server, proxy and hanging server are in tests/fakes.py)
147
+ uv run python bench/bench_log.py # hot-path benchmark
148
+ ```