amberlib 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.
- amberlib/__init__.py +3 -0
- amberlib/cli.py +578 -0
- amberlib/corpus_nll.py +464 -0
- amberlib/cost.py +25 -0
- amberlib/daemon.py +1198 -0
- amberlib/engine.py +696 -0
- amberlib/local_worker.py +394 -0
- amberlib/plugins/__init__.py +18 -0
- amberlib/printed.py +871 -0
- amberlib/telemetry.py +192 -0
- amberlib/verifiers.py +464 -0
- amberlib/worker.py +220 -0
- amberlib/workload.py +69 -0
- amberlib-0.1.0.dist-info/METADATA +195 -0
- amberlib-0.1.0.dist-info/RECORD +19 -0
- amberlib-0.1.0.dist-info/WHEEL +5 -0
- amberlib-0.1.0.dist-info/entry_points.txt +3 -0
- amberlib-0.1.0.dist-info/licenses/LICENSE +21 -0
- amberlib-0.1.0.dist-info/top_level.txt +1 -0
amberlib/__init__.py
ADDED
amberlib/cli.py
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
"""CLI entrypoints for Amber: `amberd` (GPU daemon) and `amber` (model-agnostic agent CLI).
|
|
2
|
+
|
|
3
|
+
Start the GPU daemon (zero models hardcoded):
|
|
4
|
+
amberd --host 0.0.0.0 --port 8765 --serve-port 8000
|
|
5
|
+
|
|
6
|
+
Connect any coding agent:
|
|
7
|
+
export AMBER_URL=http://<gpu-host>:8765
|
|
8
|
+
amber info
|
|
9
|
+
amber deploy ./my_printed_model
|
|
10
|
+
amber telemetry
|
|
11
|
+
amber target --from-telemetry
|
|
12
|
+
amber target --shapes 4096x16:0.8,512x16:0.2
|
|
13
|
+
amber profile --key 1024x4
|
|
14
|
+
amber eval --files cand/kernels.py cand/model.py --name fused_norm
|
|
15
|
+
amber eval --files cand/loader.py --name repack_weights
|
|
16
|
+
amber promote
|
|
17
|
+
amber verify-bench --cmd "python eval_bench.py"
|
|
18
|
+
amber rollback
|
|
19
|
+
amber emit ./dist/specialized_model
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import sys
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from .daemon import AmberDaemon, DaemonClient
|
|
32
|
+
from .printed import EDITABLE_FILES, REQUIRED_FILES, encode_bundle_patch
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _parse_shapes(spec: str) -> dict[str, float]:
|
|
36
|
+
out: dict[str, float] = {}
|
|
37
|
+
for item in spec.split(","):
|
|
38
|
+
item = item.strip()
|
|
39
|
+
if not item:
|
|
40
|
+
continue
|
|
41
|
+
if ":" in item:
|
|
42
|
+
k, v = item.split(":", 1)
|
|
43
|
+
out[k.strip()] = float(v.strip())
|
|
44
|
+
else:
|
|
45
|
+
out[item] = 1.0
|
|
46
|
+
if not out:
|
|
47
|
+
raise SystemExit("--shapes must specify at least one CTXxBATCH[:weight] entry")
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _load_eval_source(patch: Path | None, files: list[Path] | None) -> str:
|
|
52
|
+
if patch is not None and files:
|
|
53
|
+
raise SystemExit("pass either a single patch.py OR --files, not both")
|
|
54
|
+
if files:
|
|
55
|
+
bundle: dict[str, str] = {}
|
|
56
|
+
for fp in files:
|
|
57
|
+
if fp.name not in EDITABLE_FILES:
|
|
58
|
+
raise SystemExit(f"--files entries must be named one of {EDITABLE_FILES}; got {fp.name!r}")
|
|
59
|
+
bundle[fp.name] = fp.read_text()
|
|
60
|
+
return encode_bundle_patch(bundle)
|
|
61
|
+
if patch is None:
|
|
62
|
+
raise SystemExit(
|
|
63
|
+
"eval requires either a patch.py positional argument or --files <loader.py|model.py|kernels.py>"
|
|
64
|
+
)
|
|
65
|
+
return patch.read_text()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _fmt_num(v: Any, signed: bool = False, digits: int = 4) -> str:
|
|
69
|
+
if v is None:
|
|
70
|
+
return "n/a"
|
|
71
|
+
try:
|
|
72
|
+
f = float(v)
|
|
73
|
+
except (TypeError, ValueError):
|
|
74
|
+
return str(v)
|
|
75
|
+
return f"{f:+.{digits}f}" if signed else f"{f:.{digits}f}"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def format_eval_summary(out: dict[str, Any]) -> str:
|
|
79
|
+
"""Concise multi-line verdict summary for humans and agents (safe to tail)."""
|
|
80
|
+
name = out.get("name", "?")
|
|
81
|
+
status = str(out.get("status", "unknown")).upper()
|
|
82
|
+
tier = out.get("reload_tier")
|
|
83
|
+
total_s = out.get("total_seconds")
|
|
84
|
+
meta_parts = []
|
|
85
|
+
if out.get("committed"):
|
|
86
|
+
meta_parts.append("committed")
|
|
87
|
+
if tier:
|
|
88
|
+
meta_parts.append(str(tier))
|
|
89
|
+
if total_s is not None:
|
|
90
|
+
meta_parts.append(f"{float(total_s):.1f}s")
|
|
91
|
+
meta = f" ({', '.join(meta_parts)})" if meta_parts else ""
|
|
92
|
+
lines = [f"[amber eval] {name} -> {status}{meta}"]
|
|
93
|
+
|
|
94
|
+
if out.get("status") == "rejected_stale_base":
|
|
95
|
+
lines.append(
|
|
96
|
+
f" stale base: expected={out.get('expected_base_hash')} current={out.get('current_source_hash')} — run `amber pull`"
|
|
97
|
+
)
|
|
98
|
+
return "\n".join(lines)
|
|
99
|
+
|
|
100
|
+
score_ms = out.get("score_ms")
|
|
101
|
+
if score_ms is not None:
|
|
102
|
+
timings = out.get("timings") or []
|
|
103
|
+
t_str = ", ".join(
|
|
104
|
+
f"{t['key']}={float(t['median_ms']):.3f}ms"
|
|
105
|
+
for t in timings
|
|
106
|
+
if isinstance(t, dict) and "key" in t and "median_ms" in t
|
|
107
|
+
)
|
|
108
|
+
t_part = f" ({t_str})" if t_str else ""
|
|
109
|
+
inc_g = out.get("gain_vs_incumbent_pct")
|
|
110
|
+
base_g = out.get("gain_vs_baseline_pct")
|
|
111
|
+
g_parts = []
|
|
112
|
+
if inc_g is not None:
|
|
113
|
+
g_parts.append(f"vs incumbent: {float(inc_g):+.2f}%")
|
|
114
|
+
if base_g is not None:
|
|
115
|
+
g_parts.append(f"vs baseline: {float(base_g):+.2f}%")
|
|
116
|
+
g_part = (" | " + " | ".join(g_parts)) if g_parts else ""
|
|
117
|
+
lines.append(f" score: {float(score_ms):.3f}ms{t_part}{g_part}")
|
|
118
|
+
elif out.get("incumbent_before_ms") is not None:
|
|
119
|
+
inc_b = float(out["incumbent_before_ms"])
|
|
120
|
+
inc_f = out.get("incumbent_fresh_ms")
|
|
121
|
+
drift = out.get("incumbent_drift_pct")
|
|
122
|
+
extra = (
|
|
123
|
+
f" (fresh={float(inc_f):.3f}ms, drift={float(drift):+.2f}%)"
|
|
124
|
+
if inc_f is not None and drift is not None
|
|
125
|
+
else ""
|
|
126
|
+
)
|
|
127
|
+
lines.append(f" incumbent: {inc_b:.3f}ms{extra}")
|
|
128
|
+
|
|
129
|
+
verdicts = out.get("verdicts") or {}
|
|
130
|
+
tol = verdicts.get("tolerant") or {}
|
|
131
|
+
strict = verdicts.get("strict") or {}
|
|
132
|
+
inc = verdicts.get("incremental") or {}
|
|
133
|
+
limits = tol.get("limits") or {}
|
|
134
|
+
|
|
135
|
+
# Collect top-level failure reasons across search / guard / heldout
|
|
136
|
+
reasons: list[str] = []
|
|
137
|
+
mode = out.get("verify_mode", "tolerant")
|
|
138
|
+
if mode == "strict" and strict and not strict.get("passed", True):
|
|
139
|
+
reasons.append(f"strict_mismatch(max_abs={strict.get('max_abs')})")
|
|
140
|
+
if mode == "incremental" and inc and not inc.get("passed", True):
|
|
141
|
+
reasons.append(f"incremental_mismatch(max_abs={inc.get('max_abs')})")
|
|
142
|
+
if tol.get("failure_reasons"):
|
|
143
|
+
reasons.extend(str(r) for r in tol["failure_reasons"])
|
|
144
|
+
elif tol.get("reason"):
|
|
145
|
+
reasons.append(str(tol["reason"]))
|
|
146
|
+
guard = (verdicts.get("guard") or {}).get("strict" if mode == "strict" else "tolerant") or {}
|
|
147
|
+
if guard and not guard.get("passed", True):
|
|
148
|
+
g_r = guard.get("failure_reasons") or ([guard["reason"]] if guard.get("reason") else ["guard_failed"])
|
|
149
|
+
reasons.extend(f"guard:{r}" for r in g_r)
|
|
150
|
+
hv = out.get("heldout_verdicts")
|
|
151
|
+
if out.get("status") == "rejected_heldout":
|
|
152
|
+
if isinstance(hv, dict) and hv.get("redacted"):
|
|
153
|
+
reasons.append("heldout_failed(redacted)")
|
|
154
|
+
elif isinstance(hv, dict):
|
|
155
|
+
hvg = hv.get(mode if mode in hv else "tolerant") or {}
|
|
156
|
+
h_r = hvg.get("failure_reasons") or ([hvg["reason"]] if hvg.get("reason") else ["heldout_failed"])
|
|
157
|
+
reasons.extend(f"heldout:{r}" for r in h_r)
|
|
158
|
+
if reasons:
|
|
159
|
+
lines.append(" failures: " + "; ".join(reasons))
|
|
160
|
+
|
|
161
|
+
# CorpusNLLVerifier metrics
|
|
162
|
+
if tol.get("full_vocab_exact"):
|
|
163
|
+
agg_lim = limits.get("max_delta_nll_aggregate")
|
|
164
|
+
dom_lim = limits.get("max_delta_nll_per_domain")
|
|
165
|
+
doc_lim = limits.get("max_delta_nll_per_doc")
|
|
166
|
+
lines.append(
|
|
167
|
+
" corpus_nll: "
|
|
168
|
+
f"decode={_fmt_num(tol.get('decode_delta_nll'), signed=True)} (<={agg_lim}) "
|
|
169
|
+
f"prefill={_fmt_num(tol.get('prefill_delta_nll'), signed=True)} (<={agg_lim}) "
|
|
170
|
+
f"domain={_fmt_num(tol.get('worst_domain_delta_nll'), signed=True)} (<={dom_lim}) "
|
|
171
|
+
f"max_doc={_fmt_num(tol.get('max_doc_delta_nll'), signed=True)} (<={doc_lim})"
|
|
172
|
+
)
|
|
173
|
+
p_agg = tol.get("parity_agg_abs_diff")
|
|
174
|
+
p_agg_lim = tol.get("parity_agg_limit", limits.get("parity_agg_limit"))
|
|
175
|
+
p_agg_base = tol.get("parity_agg_baseline", limits.get("parity_agg_baseline"))
|
|
176
|
+
p_agg_margin = limits.get("max_prefill_decode_parity_agg")
|
|
177
|
+
p_doc = tol.get("parity_max_doc_abs_diff")
|
|
178
|
+
p_doc_lim = tol.get("parity_max_doc_limit", limits.get("parity_max_doc_limit"))
|
|
179
|
+
p_doc_base = tol.get("parity_max_doc_baseline", limits.get("parity_max_doc_baseline"))
|
|
180
|
+
p_doc_margin = limits.get("max_prefill_decode_parity_doc")
|
|
181
|
+
agg_rel = f" [base {_fmt_num(p_agg_base)}+{p_agg_margin}]" if p_agg_base is not None else ""
|
|
182
|
+
doc_rel = f" [base {_fmt_num(p_doc_base)}+{p_doc_margin}]" if p_doc_base is not None else ""
|
|
183
|
+
lines.append(
|
|
184
|
+
f" parity: agg={_fmt_num(p_agg)} (<={_fmt_num(p_agg_lim)}{agg_rel}) "
|
|
185
|
+
f"doc={_fmt_num(p_doc)} (<={_fmt_num(p_doc_lim)}{doc_rel})"
|
|
186
|
+
)
|
|
187
|
+
elif tol.get("mean_kl_nats") is not None or tol.get("mean_delta_nll") is not None:
|
|
188
|
+
lines.append(
|
|
189
|
+
" distribution: "
|
|
190
|
+
f"kl={_fmt_num(tol.get('mean_kl_nats'))} (<={limits.get('max_kl_nats')}) "
|
|
191
|
+
f"delta_nll={_fmt_num(tol.get('mean_delta_nll'), signed=True)} (<={limits.get('max_delta_nll')})"
|
|
192
|
+
)
|
|
193
|
+
elif tol.get("max_scaled_err") is not None:
|
|
194
|
+
lines.append(
|
|
195
|
+
f" tolerance: max_scaled_err={_fmt_num(tol.get('max_scaled_err'))} (<={limits.get('max_scaled_err')})"
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
if out.get("error"):
|
|
199
|
+
first_line = str(out["error"]).splitlines()[0][:180]
|
|
200
|
+
lines.append(f" error: {first_line}")
|
|
201
|
+
return "\n".join(lines)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def format_board_summary(entries: list[dict[str, Any]]) -> str:
|
|
205
|
+
"""Compact one-line-per-entry board view with scores, gains, and failure reasons."""
|
|
206
|
+
if not entries:
|
|
207
|
+
return "(board empty)"
|
|
208
|
+
lines = []
|
|
209
|
+
for e in entries:
|
|
210
|
+
eid = e.get("id", "?")
|
|
211
|
+
name = e.get("name", "?")
|
|
212
|
+
status = e.get("status", "?")
|
|
213
|
+
tier = e.get("reload_tier", "fast")
|
|
214
|
+
score = f"{float(e['score_ms']):.3f}ms" if e.get("score_ms") is not None else "-"
|
|
215
|
+
gain = f"{float(e['gain_pct']):+.2f}%" if e.get("gain_pct") is not None else "-"
|
|
216
|
+
timings = e.get("timings_ms") or {}
|
|
217
|
+
t_str = (" [" + ", ".join(f"{k}={float(v):.2f}" for k, v in timings.items()) + "]") if timings else ""
|
|
218
|
+
diag = []
|
|
219
|
+
if e.get("decode_delta_nll") is not None:
|
|
220
|
+
diag.append(f"dNLL={float(e['decode_delta_nll']):+.4f}")
|
|
221
|
+
if e.get("max_doc_delta_nll") is not None:
|
|
222
|
+
diag.append(f"max_doc={float(e['max_doc_delta_nll']):+.4f}")
|
|
223
|
+
if e.get("parity_max_doc_abs_diff") is not None:
|
|
224
|
+
plim = e.get("parity_max_doc_limit")
|
|
225
|
+
p_part = f"p_doc={float(e['parity_max_doc_abs_diff']):.4f}"
|
|
226
|
+
if plim is not None:
|
|
227
|
+
p_part += f"/{float(plim):.4f}"
|
|
228
|
+
diag.append(p_part)
|
|
229
|
+
if e.get("failure_reasons"):
|
|
230
|
+
diag.append("FAIL=" + "; ".join(str(r) for r in e["failure_reasons"]))
|
|
231
|
+
elif e.get("error"):
|
|
232
|
+
diag.append("ERR=" + str(e["error"]).splitlines()[0][:80])
|
|
233
|
+
diag_str = (" | " + " ".join(diag)) if diag else ""
|
|
234
|
+
lines.append(f"#{eid} {name} ({tier}) | {status} | {score}{t_str} ({gain}){diag_str}")
|
|
235
|
+
return "\n".join(lines)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _read_deploy_bundle(pkg_dir: Path) -> dict[str, str]:
|
|
239
|
+
root = pkg_dir.expanduser().resolve()
|
|
240
|
+
missing = [f for f in REQUIRED_FILES if not (root / f).is_file()]
|
|
241
|
+
if missing:
|
|
242
|
+
raise SystemExit(f"deploy package {root} is missing required files: {missing}")
|
|
243
|
+
bundle = {f: (root / f).read_text() for f in REQUIRED_FILES}
|
|
244
|
+
m = json.loads(bundle["manifest.json"])
|
|
245
|
+
cs = m.get("corpus_splits")
|
|
246
|
+
if isinstance(cs, dict):
|
|
247
|
+
m["corpus_splits"] = {
|
|
248
|
+
k: str((root / v).resolve()) if (not Path(v).is_absolute() and (root / v).is_file()) else v
|
|
249
|
+
for k, v in cs.items()
|
|
250
|
+
}
|
|
251
|
+
bundle["manifest.json"] = json.dumps(m, indent=2) + "\n"
|
|
252
|
+
return bundle
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def build_daemon_parser() -> argparse.ArgumentParser:
|
|
256
|
+
p = argparse.ArgumentParser(prog="amberd", description="Amber model-agnostic GPU serving & compiler daemon")
|
|
257
|
+
p.add_argument("--host", default="127.0.0.1")
|
|
258
|
+
p.add_argument("--port", type=int, default=8765, help="Agent control-plane HTTP port (default: 8765)")
|
|
259
|
+
p.add_argument("--serve-port", type=int, default=8000, help="OpenAI serving-plane HTTP port (default: 8000)")
|
|
260
|
+
p.add_argument(
|
|
261
|
+
"--state-dir", type=Path, default=None, help="State/deployments/board directory (default: ~/.amber/state)"
|
|
262
|
+
)
|
|
263
|
+
p.add_argument(
|
|
264
|
+
"--package", type=Path, default=None, help="Optional initial printed package directory to deploy on boot"
|
|
265
|
+
)
|
|
266
|
+
p.add_argument("--token", default=os.environ.get("AMBER_TOKEN"), help="Optional bearer token for control plane")
|
|
267
|
+
p.add_argument(
|
|
268
|
+
"--drift-threshold", type=float, default=0.20, help="L1/TV drift score threshold for needs_optimization"
|
|
269
|
+
)
|
|
270
|
+
p.add_argument("--min-drift-samples", type=int, default=5, help="Minimum requests before drift triggers")
|
|
271
|
+
p.add_argument(
|
|
272
|
+
"--require-base",
|
|
273
|
+
action=argparse.BooleanOptionalAction,
|
|
274
|
+
default=True,
|
|
275
|
+
help="require matching --base source_hash on every eval (default: on; pass --no-require-base to disable)",
|
|
276
|
+
)
|
|
277
|
+
p.add_argument(
|
|
278
|
+
"--redact-heldout",
|
|
279
|
+
action=argparse.BooleanOptionalAction,
|
|
280
|
+
default=True,
|
|
281
|
+
help="redact per-doc heldout metrics in eval responses (default: on; pass --no-redact-heldout to disable)",
|
|
282
|
+
)
|
|
283
|
+
return p
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def main_daemon(argv=None) -> None:
|
|
287
|
+
a = build_daemon_parser().parse_args(argv)
|
|
288
|
+
daemon = AmberDaemon(
|
|
289
|
+
host=a.host,
|
|
290
|
+
control_port=a.port,
|
|
291
|
+
serve_port=a.serve_port,
|
|
292
|
+
state_dir=a.state_dir,
|
|
293
|
+
token=a.token,
|
|
294
|
+
initial_package=a.package,
|
|
295
|
+
drift_threshold=a.drift_threshold,
|
|
296
|
+
min_samples_for_drift=a.min_drift_samples,
|
|
297
|
+
require_base_hash=a.require_base,
|
|
298
|
+
redact_heldout=a.redact_heldout,
|
|
299
|
+
)
|
|
300
|
+
daemon.serve_forever()
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
304
|
+
p = argparse.ArgumentParser(prog="amber", description="Amber model-agnostic agent CLI")
|
|
305
|
+
p.add_argument(
|
|
306
|
+
"--url",
|
|
307
|
+
default=os.environ.get("AMBER_URL", "http://127.0.0.1:8765"),
|
|
308
|
+
help="amberd control URL (default: $AMBER_URL or http://127.0.0.1:8765)",
|
|
309
|
+
)
|
|
310
|
+
p.add_argument(
|
|
311
|
+
"--token", default=os.environ.get("AMBER_TOKEN"), help="optional bearer token (default: $AMBER_TOKEN)"
|
|
312
|
+
)
|
|
313
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
314
|
+
common.add_argument("--url", default=argparse.SUPPRESS)
|
|
315
|
+
common.add_argument("--token", default=argparse.SUPPRESS)
|
|
316
|
+
|
|
317
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
318
|
+
|
|
319
|
+
# Convenience alias: `amber serve` launches amberd directly
|
|
320
|
+
ss = sub.add_parser("serve", parents=[common], help="start amberd (control + serving daemon)")
|
|
321
|
+
ss.add_argument("--host", default="127.0.0.1")
|
|
322
|
+
ss.add_argument("--port", type=int, default=8765)
|
|
323
|
+
ss.add_argument("--serve-port", type=int, default=8000)
|
|
324
|
+
ss.add_argument("--state-dir", type=Path, default=None)
|
|
325
|
+
ss.add_argument("--package", type=Path, default=None)
|
|
326
|
+
ss.add_argument("--drift-threshold", type=float, default=0.20)
|
|
327
|
+
ss.add_argument("--min-drift-samples", type=int, default=5)
|
|
328
|
+
ss.add_argument("--require-base", action=argparse.BooleanOptionalAction, default=True)
|
|
329
|
+
ss.add_argument("--redact-heldout", action=argparse.BooleanOptionalAction, default=True)
|
|
330
|
+
|
|
331
|
+
sub.add_parser("info", parents=[common], help="inspect GPU, environment, active deployment, and drift summary")
|
|
332
|
+
sub.add_parser("status", parents=[common], help="detailed engine, baseline, incumbent, and stack status")
|
|
333
|
+
|
|
334
|
+
st = sub.add_parser(
|
|
335
|
+
"telemetry", parents=[common], help="inspect live serving traffic histogram, latency, and drift"
|
|
336
|
+
)
|
|
337
|
+
st.add_argument("--window", type=float, default=None, help="lookback window in seconds (default: 3600)")
|
|
338
|
+
|
|
339
|
+
sd = sub.add_parser("deploy", parents=[common], help="deploy an agent-printed model package onto amberd")
|
|
340
|
+
sd.add_argument(
|
|
341
|
+
"package_dir",
|
|
342
|
+
type=Path,
|
|
343
|
+
help="local package directory containing manifest.json, loader.py, model.py, kernels.py",
|
|
344
|
+
)
|
|
345
|
+
sd.add_argument("--regime", default=None, help="optional initial regime name from manifest.json")
|
|
346
|
+
sd.add_argument(
|
|
347
|
+
"--remote-path",
|
|
348
|
+
action="store_true",
|
|
349
|
+
help="treat package_dir as a path already on the amberd host instead of uploading files",
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
stg = sub.add_parser(
|
|
353
|
+
"target", parents=[common], help="set active optimization target from telemetry or explicit workload"
|
|
354
|
+
)
|
|
355
|
+
stg.add_argument(
|
|
356
|
+
"--from-telemetry", action="store_true", help="lock target weights to live serving traffic histogram"
|
|
357
|
+
)
|
|
358
|
+
stg.add_argument("--regime", default=None, help="select a named regime from manifest.json")
|
|
359
|
+
stg.add_argument("--shapes", default=None, help="explicit shape weights, e.g. 4096x16:0.8,512x16:0.2")
|
|
360
|
+
stg.add_argument(
|
|
361
|
+
"--workload",
|
|
362
|
+
type=Path,
|
|
363
|
+
default=None,
|
|
364
|
+
help='JSON file with {"weights": {"CTXxBATCH": weight, ...}, "name"?: "..."}',
|
|
365
|
+
)
|
|
366
|
+
stg.add_argument("--name", default=None, help="optional name for this target")
|
|
367
|
+
|
|
368
|
+
sp = sub.add_parser("profile", parents=[common], help="CUDA kernel profile of active incumbent")
|
|
369
|
+
sp.add_argument("--key", default=None, help="shape key, e.g. 1024x4 (default: last key)")
|
|
370
|
+
sp.add_argument("key_pos", nargs="?", default=None, help="same as --key")
|
|
371
|
+
sp.add_argument("--top", type=int, default=10)
|
|
372
|
+
|
|
373
|
+
sb = sub.add_parser("board", parents=[common], help="recent evaluation log")
|
|
374
|
+
sb.add_argument("--limit", type=int, default=20)
|
|
375
|
+
sb.add_argument(
|
|
376
|
+
"--summary", action="store_true", help="print compact one-line-per-eval summary table instead of JSON"
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
spull = sub.add_parser(
|
|
380
|
+
"pull", parents=[common], help="download current winning package files & source_hash to a local directory"
|
|
381
|
+
)
|
|
382
|
+
spull.add_argument("out_dir", type=Path)
|
|
383
|
+
|
|
384
|
+
snotes = sub.add_parser("notes", parents=[common], help="read shared multi-agent collaboration board messages")
|
|
385
|
+
snotes.add_argument("--limit", type=int, default=30)
|
|
386
|
+
snotes.add_argument("--kind", choices=["note", "claim", "finding", "handoff"], default=None)
|
|
387
|
+
|
|
388
|
+
spost = sub.add_parser(
|
|
389
|
+
"post", parents=[common], help="post a claim, finding, handoff, or note to the shared multi-agent board"
|
|
390
|
+
)
|
|
391
|
+
spost.add_argument("message", help="message text for peer agents")
|
|
392
|
+
spost.add_argument("--agent", default="byoa")
|
|
393
|
+
spost.add_argument("--kind", choices=["note", "claim", "finding", "handoff"], default="note")
|
|
394
|
+
spost.add_argument("--tags", default="", help="comma-separated tags, e.g. gdn,loader")
|
|
395
|
+
|
|
396
|
+
se = sub.add_parser("eval", parents=[common], help="evaluate candidate package edits or patch file")
|
|
397
|
+
se.add_argument("patch", nargs="?", type=Path, default=None, help="python file defining apply(ctx) -> restore_fn")
|
|
398
|
+
se.add_argument(
|
|
399
|
+
"--files",
|
|
400
|
+
nargs="+",
|
|
401
|
+
type=Path,
|
|
402
|
+
default=None,
|
|
403
|
+
help="printed-package files to update (loader.py, model.py, kernels.py)",
|
|
404
|
+
)
|
|
405
|
+
se.add_argument("--name", required=True)
|
|
406
|
+
se.add_argument("--hypothesis", default="")
|
|
407
|
+
se.add_argument("--agent", default="byoa")
|
|
408
|
+
se.add_argument(
|
|
409
|
+
"--base",
|
|
410
|
+
default=None,
|
|
411
|
+
help="expected source_hash (auto-read from .amber_base if present; prevents clobbering peer wins)",
|
|
412
|
+
)
|
|
413
|
+
se.add_argument(
|
|
414
|
+
"--mode",
|
|
415
|
+
choices=["tolerant", "incremental", "strict"],
|
|
416
|
+
default="tolerant",
|
|
417
|
+
help="tolerant (default: mean KL / delta-NLL); incremental (tolerant + exact vs incumbent); strict (bit-exact)",
|
|
418
|
+
)
|
|
419
|
+
se.add_argument("--no-commit", action="store_true")
|
|
420
|
+
se.add_argument("--profile", nargs="?", const="last", default=None, help="include per-kernel before/after diff")
|
|
421
|
+
se.add_argument("--replaces", default=None, help="name of a committed patch this candidate supersedes")
|
|
422
|
+
se.add_argument(
|
|
423
|
+
"--summary", action="store_true", help="print only the compact verdict summary to stdout (omits full JSON)"
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
sr = sub.add_parser("revert", parents=[common], help="remove one committed patch from staging stack")
|
|
427
|
+
sr.add_argument("name")
|
|
428
|
+
|
|
429
|
+
sub.add_parser("reset-board", parents=[common], help="clear board and reset staging stack to deployed baseline")
|
|
430
|
+
sub.add_parser("promote", parents=[common], help="atomically promote winning stack to live serving and reset drift")
|
|
431
|
+
sub.add_parser("rollback", parents=[common], help="roll back live serving to previous promoted revision")
|
|
432
|
+
sub.add_parser("restart", parents=[common], help="cleanly reset GPU runtime and replay committed stack")
|
|
433
|
+
|
|
434
|
+
sv = sub.add_parser(
|
|
435
|
+
"verify-bench", parents=[common], help="run an outer benchmark command against live serving plane"
|
|
436
|
+
)
|
|
437
|
+
sv.add_argument(
|
|
438
|
+
"--cmd", dest="bench_cmd", required=True, help="shell command run on amberd host with AMBER_SERVE_URL set"
|
|
439
|
+
)
|
|
440
|
+
sv.add_argument("--timeout", type=int, default=600)
|
|
441
|
+
|
|
442
|
+
sm = sub.add_parser("emit", parents=[common], help="export winning printed package to standalone directory")
|
|
443
|
+
sm.add_argument("out_dir", type=Path)
|
|
444
|
+
|
|
445
|
+
sub.add_parser("stop", parents=[common], help="shut down amberd cleanly")
|
|
446
|
+
return p
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def main(argv=None) -> None:
|
|
450
|
+
p = build_parser()
|
|
451
|
+
a = p.parse_args(argv)
|
|
452
|
+
|
|
453
|
+
if a.cmd == "serve":
|
|
454
|
+
daemon = AmberDaemon(
|
|
455
|
+
host=a.host,
|
|
456
|
+
control_port=a.port,
|
|
457
|
+
serve_port=a.serve_port,
|
|
458
|
+
state_dir=a.state_dir,
|
|
459
|
+
token=a.token,
|
|
460
|
+
initial_package=a.package,
|
|
461
|
+
drift_threshold=a.drift_threshold,
|
|
462
|
+
min_samples_for_drift=a.min_drift_samples,
|
|
463
|
+
require_base_hash=a.require_base,
|
|
464
|
+
redact_heldout=a.redact_heldout,
|
|
465
|
+
)
|
|
466
|
+
daemon.serve_forever()
|
|
467
|
+
return
|
|
468
|
+
|
|
469
|
+
c = DaemonClient(a.url, token=a.token)
|
|
470
|
+
if a.cmd == "info":
|
|
471
|
+
out: Any = c.info()
|
|
472
|
+
elif a.cmd == "status":
|
|
473
|
+
out = c.status()
|
|
474
|
+
elif a.cmd == "telemetry":
|
|
475
|
+
out = c.telemetry(window=a.window)
|
|
476
|
+
elif a.cmd == "deploy":
|
|
477
|
+
if a.remote_path:
|
|
478
|
+
out = c.deploy(package_dir=str(a.package_dir), regime=a.regime)
|
|
479
|
+
else:
|
|
480
|
+
out = c.deploy(files=_read_deploy_bundle(a.package_dir), regime=a.regime)
|
|
481
|
+
elif a.cmd == "target":
|
|
482
|
+
if a.workload is not None:
|
|
483
|
+
blob = json.loads(a.workload.read_text())
|
|
484
|
+
out = c.set_target(weights=blob["weights"], name=a.name or blob.get("name"))
|
|
485
|
+
elif a.shapes is not None:
|
|
486
|
+
out = c.set_target(weights=_parse_shapes(a.shapes), name=a.name)
|
|
487
|
+
elif a.regime is not None:
|
|
488
|
+
out = c.set_target(regime=a.regime)
|
|
489
|
+
elif a.from_telemetry:
|
|
490
|
+
out = c.set_target(from_telemetry=True, name=a.name)
|
|
491
|
+
else:
|
|
492
|
+
raise SystemExit("target requires one of --from-telemetry, --regime, --shapes, or --workload")
|
|
493
|
+
elif a.cmd == "profile":
|
|
494
|
+
out = c.profile(key=a.key or a.key_pos, top=a.top)
|
|
495
|
+
elif a.cmd == "board":
|
|
496
|
+
out = c.board_entries(limit=a.limit)
|
|
497
|
+
elif a.cmd == "pull":
|
|
498
|
+
src = c.get_source()
|
|
499
|
+
dst = a.out_dir.expanduser().resolve()
|
|
500
|
+
dst.mkdir(parents=True, exist_ok=True)
|
|
501
|
+
for fname, content in src["files"].items():
|
|
502
|
+
(dst / fname).write_text(content)
|
|
503
|
+
if src.get("source_hash"):
|
|
504
|
+
(dst / ".amber_base").write_text(str(src["source_hash"]) + "\n")
|
|
505
|
+
out = {
|
|
506
|
+
"pulled_to": str(dst),
|
|
507
|
+
"source_hash": src.get("source_hash"),
|
|
508
|
+
"incumbent_ms": src.get("incumbent_ms"),
|
|
509
|
+
"committed": src.get("committed", []),
|
|
510
|
+
"files": sorted(src["files"].keys()),
|
|
511
|
+
}
|
|
512
|
+
elif a.cmd == "notes":
|
|
513
|
+
out = c.list_notes(limit=a.limit, kind=a.kind)
|
|
514
|
+
elif a.cmd == "post":
|
|
515
|
+
tags = [t.strip() for t in a.tags.split(",") if t.strip()]
|
|
516
|
+
out = c.post_note(a.message, agent=a.agent, kind=a.kind, tags=tags)
|
|
517
|
+
elif a.cmd == "revert":
|
|
518
|
+
out = c.revert(a.name)
|
|
519
|
+
elif a.cmd == "reset-board":
|
|
520
|
+
out = c.reset_board()
|
|
521
|
+
elif a.cmd == "promote":
|
|
522
|
+
out = c.promote()
|
|
523
|
+
elif a.cmd == "rollback":
|
|
524
|
+
out = c.rollback()
|
|
525
|
+
elif a.cmd == "restart":
|
|
526
|
+
out = c.restart()
|
|
527
|
+
elif a.cmd == "verify-bench":
|
|
528
|
+
out = c.verify_bench(a.bench_cmd, timeout_seconds=a.timeout)
|
|
529
|
+
elif a.cmd == "emit":
|
|
530
|
+
out = c.emit(str(a.out_dir))
|
|
531
|
+
elif a.cmd == "stop":
|
|
532
|
+
out = c.shutdown()
|
|
533
|
+
else:
|
|
534
|
+
source = _load_eval_source(a.patch, a.files)
|
|
535
|
+
base_hash = a.base
|
|
536
|
+
if base_hash is None and a.files:
|
|
537
|
+
for fp in a.files:
|
|
538
|
+
bf = fp.parent / ".amber_base"
|
|
539
|
+
if bf.is_file():
|
|
540
|
+
base_hash = bf.read_text().strip() or None
|
|
541
|
+
if base_hash:
|
|
542
|
+
break
|
|
543
|
+
out = c.evaluate(
|
|
544
|
+
a.name,
|
|
545
|
+
source,
|
|
546
|
+
mode=a.mode,
|
|
547
|
+
commit=not a.no_commit,
|
|
548
|
+
agent_id=a.agent,
|
|
549
|
+
hypothesis=a.hypothesis,
|
|
550
|
+
replaces=a.replaces,
|
|
551
|
+
profile=a.profile,
|
|
552
|
+
base_hash=base_hash,
|
|
553
|
+
)
|
|
554
|
+
if out.get("committed") and out.get("source_hash") and a.files:
|
|
555
|
+
bf = a.files[0].parent / ".amber_base"
|
|
556
|
+
if bf.is_file():
|
|
557
|
+
bf.write_text(str(out["source_hash"]) + "\n")
|
|
558
|
+
if a.cmd == "board" and a.summary:
|
|
559
|
+
assert isinstance(out, list)
|
|
560
|
+
print(format_board_summary(out))
|
|
561
|
+
return
|
|
562
|
+
if a.cmd == "eval":
|
|
563
|
+
assert isinstance(out, dict)
|
|
564
|
+
summary_txt = format_eval_summary(out)
|
|
565
|
+
if a.summary:
|
|
566
|
+
print(summary_txt)
|
|
567
|
+
else:
|
|
568
|
+
print(json.dumps(out, indent=2))
|
|
569
|
+
sys.stderr.write(summary_txt + "\n")
|
|
570
|
+
sys.stderr.flush()
|
|
571
|
+
if out.get("status") not in ("accepted", "verified_not_committed"):
|
|
572
|
+
sys.exit(2)
|
|
573
|
+
return
|
|
574
|
+
print(json.dumps(out, indent=2))
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
if __name__ == "__main__":
|
|
578
|
+
main()
|