hanzo-research 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.
- hanzo_research-0.1.0/.gitignore +82 -0
- hanzo_research-0.1.0/PKG-INFO +56 -0
- hanzo_research-0.1.0/README.md +46 -0
- hanzo_research-0.1.0/hanzo_research/__init__.py +55 -0
- hanzo_research-0.1.0/hanzo_research/client.py +267 -0
- hanzo_research-0.1.0/hanzo_research/provenance.py +70 -0
- hanzo_research-0.1.0/pyproject.toml +19 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# IDE and editor
|
|
2
|
+
.vscode
|
|
3
|
+
.idea
|
|
4
|
+
|
|
5
|
+
# Python
|
|
6
|
+
*.egg-info
|
|
7
|
+
__pycache__
|
|
8
|
+
.mypy_cache
|
|
9
|
+
.pytest_cache
|
|
10
|
+
*.pyc
|
|
11
|
+
.venv
|
|
12
|
+
|
|
13
|
+
# Build
|
|
14
|
+
build/
|
|
15
|
+
dist
|
|
16
|
+
_dev
|
|
17
|
+
|
|
18
|
+
# Environment
|
|
19
|
+
.env
|
|
20
|
+
.envrc
|
|
21
|
+
|
|
22
|
+
# Logs
|
|
23
|
+
.prism.log
|
|
24
|
+
codegen.log
|
|
25
|
+
*.log
|
|
26
|
+
|
|
27
|
+
# Package manager
|
|
28
|
+
Brewfile.lock.json
|
|
29
|
+
|
|
30
|
+
# Agent config files (symlinked from user home)
|
|
31
|
+
LLM.md
|
|
32
|
+
AGENTS.md
|
|
33
|
+
CLAUDE.md
|
|
34
|
+
GEMINI.md
|
|
35
|
+
GROK.md
|
|
36
|
+
QWEN.md
|
|
37
|
+
|
|
38
|
+
# Local databases and state
|
|
39
|
+
.hanzo/*
|
|
40
|
+
# …except the native CI/CD workflows, which are source of truth on
|
|
41
|
+
# git.hanzo.ai. `.hanzo/` is ignored because it also holds local agent
|
|
42
|
+
# scratch; the workflows are not scratch. Without this negation a repo can
|
|
43
|
+
# delete its GitHub workflows and land NO replacement — which is exactly
|
|
44
|
+
# what happened here on the first attempt.
|
|
45
|
+
!.hanzo/workflows/
|
|
46
|
+
.grok/
|
|
47
|
+
|
|
48
|
+
# Documentation build
|
|
49
|
+
docs/.next/
|
|
50
|
+
docs/out/
|
|
51
|
+
docs/node_modules/
|
|
52
|
+
|
|
53
|
+
# Training data and scripts (DO NOT COMMIT)
|
|
54
|
+
training_dataset.jsonl
|
|
55
|
+
scripts/full_extractor.py
|
|
56
|
+
scripts/mega_extractor.py
|
|
57
|
+
scripts/mega_full_extractor.py
|
|
58
|
+
scripts/streaming_extractor.py
|
|
59
|
+
scripts/supplement_extractor.py
|
|
60
|
+
|
|
61
|
+
# Test files at root (experimental)
|
|
62
|
+
test_post_quantum_*.py
|
|
63
|
+
|
|
64
|
+
# Analysis documents (internal)
|
|
65
|
+
HANZO_INNOVATION_OPPORTUNITIES.md
|
|
66
|
+
POST_QUANTUM_CRYPTOGRAPHY_IMPLEMENTATION.md
|
|
67
|
+
|
|
68
|
+
# Experimental cryptography (WIP)
|
|
69
|
+
pkg/hanzo/src/hanzo/cryptography/
|
|
70
|
+
site/
|
|
71
|
+
|
|
72
|
+
# hygiene (untrack node_modules, block common build output)
|
|
73
|
+
node_modules/
|
|
74
|
+
**/node_modules/
|
|
75
|
+
.pnpm-store/
|
|
76
|
+
dist/
|
|
77
|
+
.next/
|
|
78
|
+
coverage/
|
|
79
|
+
playwright-report/
|
|
80
|
+
test-results/
|
|
81
|
+
tmp/
|
|
82
|
+
.DS_Store
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hanzo-research
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hanzo Research SDK — record and query R&D evidence (experiments, attempts, diary artifacts) via /v1/research. Zero-config provenance auto-capture.
|
|
5
|
+
Project-URL: Homepage, https://hanzo.ai
|
|
6
|
+
Author-email: Hanzo AI <dev@hanzo.ai>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# hanzo-research
|
|
12
|
+
|
|
13
|
+
Record and query Hanzo R&D evidence in one import. The ONE way every producer
|
|
14
|
+
(enso-bench benchmarks, hanzo-engine/hanzo-ml kernel-perf, any research project) files
|
|
15
|
+
runs into the unified `/v1/research` plane (HIP-0512) — versioned, append-only,
|
|
16
|
+
idempotent by content, private by default.
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import hanzo_research as research
|
|
20
|
+
|
|
21
|
+
# get/create the experiment; provenance is auto-captured (see below)
|
|
22
|
+
exp = research.experiment("benchmark", "grok-4.5", "gpqa_diamond")
|
|
23
|
+
exp.record("q1", "grok-4.5", {"answer": "A", "correct": True}) # an attempt, idempotent
|
|
24
|
+
exp.snapshot(png_bytes) # a board-snapshot artifact
|
|
25
|
+
exp.report(markdown_text) # a generated-report artifact
|
|
26
|
+
exp.finish(value=94.3) # seal the run
|
|
27
|
+
|
|
28
|
+
rows = research.query(project="enso-bench", kind="benchmark") # read canonical
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Zero-config auto-instrumentation
|
|
32
|
+
|
|
33
|
+
The caller supplies **no** provenance. On `experiment()` the SDK reads the run's
|
|
34
|
+
environment and captures three self-documenting narrative sources, plus machine context:
|
|
35
|
+
|
|
36
|
+
- **the calling code's docstring** — *what this experiment is* (write a normal module
|
|
37
|
+
docstring);
|
|
38
|
+
- **the commit messages since this experiment's last recorded run** — *what changed +
|
|
39
|
+
why* (commit normally);
|
|
40
|
+
- an optional **`note=`** you pass.
|
|
41
|
+
|
|
42
|
+
Plus `git_sha` / `git_branch` / `git_dirty`, `lib_versions`, and host. The project
|
|
43
|
+
self-documents as a side effect of running.
|
|
44
|
+
|
|
45
|
+
## Importer-agnostic, idempotent
|
|
46
|
+
|
|
47
|
+
`ingest(experiments=…, attempts=…)` is one idempotent POST. Any source — a SQLite
|
|
48
|
+
backfill, git history, a kernel-perf campaign — maps its records to stable ids and calls
|
|
49
|
+
it; re-import is a no-op. "Load all research in" is just running importers.
|
|
50
|
+
|
|
51
|
+
## Config
|
|
52
|
+
|
|
53
|
+
`RESEARCH_BASE` (default `https://api.hanzo.ai`), `HANZO_API_KEY` (per-org key →
|
|
54
|
+
Bearer), `RESEARCH_PROJECT`. Uploads are private; public visibility, training, and
|
|
55
|
+
commons rights are each a separate grant. Stdlib only (urllib) — importable in any
|
|
56
|
+
zero-dep harness.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# hanzo-research
|
|
2
|
+
|
|
3
|
+
Record and query Hanzo R&D evidence in one import. The ONE way every producer
|
|
4
|
+
(enso-bench benchmarks, hanzo-engine/hanzo-ml kernel-perf, any research project) files
|
|
5
|
+
runs into the unified `/v1/research` plane (HIP-0512) — versioned, append-only,
|
|
6
|
+
idempotent by content, private by default.
|
|
7
|
+
|
|
8
|
+
```python
|
|
9
|
+
import hanzo_research as research
|
|
10
|
+
|
|
11
|
+
# get/create the experiment; provenance is auto-captured (see below)
|
|
12
|
+
exp = research.experiment("benchmark", "grok-4.5", "gpqa_diamond")
|
|
13
|
+
exp.record("q1", "grok-4.5", {"answer": "A", "correct": True}) # an attempt, idempotent
|
|
14
|
+
exp.snapshot(png_bytes) # a board-snapshot artifact
|
|
15
|
+
exp.report(markdown_text) # a generated-report artifact
|
|
16
|
+
exp.finish(value=94.3) # seal the run
|
|
17
|
+
|
|
18
|
+
rows = research.query(project="enso-bench", kind="benchmark") # read canonical
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Zero-config auto-instrumentation
|
|
22
|
+
|
|
23
|
+
The caller supplies **no** provenance. On `experiment()` the SDK reads the run's
|
|
24
|
+
environment and captures three self-documenting narrative sources, plus machine context:
|
|
25
|
+
|
|
26
|
+
- **the calling code's docstring** — *what this experiment is* (write a normal module
|
|
27
|
+
docstring);
|
|
28
|
+
- **the commit messages since this experiment's last recorded run** — *what changed +
|
|
29
|
+
why* (commit normally);
|
|
30
|
+
- an optional **`note=`** you pass.
|
|
31
|
+
|
|
32
|
+
Plus `git_sha` / `git_branch` / `git_dirty`, `lib_versions`, and host. The project
|
|
33
|
+
self-documents as a side effect of running.
|
|
34
|
+
|
|
35
|
+
## Importer-agnostic, idempotent
|
|
36
|
+
|
|
37
|
+
`ingest(experiments=…, attempts=…)` is one idempotent POST. Any source — a SQLite
|
|
38
|
+
backfill, git history, a kernel-perf campaign — maps its records to stable ids and calls
|
|
39
|
+
it; re-import is a no-op. "Load all research in" is just running importers.
|
|
40
|
+
|
|
41
|
+
## Config
|
|
42
|
+
|
|
43
|
+
`RESEARCH_BASE` (default `https://api.hanzo.ai`), `HANZO_API_KEY` (per-org key →
|
|
44
|
+
Bearer), `RESEARCH_PROJECT`. Uploads are private; public visibility, training, and
|
|
45
|
+
commons rights are each a separate grant. Stdlib only (urllib) — importable in any
|
|
46
|
+
zero-dep harness.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Hanzo Research SDK — record and query R&D evidence in one import.
|
|
2
|
+
|
|
3
|
+
import hanzo_research as research
|
|
4
|
+
|
|
5
|
+
exp = research.experiment("benchmark", "grok-4.5", "gpqa_diamond")
|
|
6
|
+
exp.record("q1", "grok-4.5", {"answer": "A", "correct": True})
|
|
7
|
+
exp.snapshot(png_bytes)
|
|
8
|
+
exp.report(markdown_text)
|
|
9
|
+
exp.finish(value=94.3)
|
|
10
|
+
|
|
11
|
+
rows = research.query(project="enso-bench", kind="benchmark")
|
|
12
|
+
|
|
13
|
+
Zero-config: provenance (git sha/branch + the commit-message narrative since the last
|
|
14
|
+
recorded run, lib versions, host) is auto-captured — the caller supplies none. Records
|
|
15
|
+
mirror to cloud /v1/research (HIP-0512): versioned, append-only, idempotent by content,
|
|
16
|
+
private by default.
|
|
17
|
+
"""
|
|
18
|
+
from .client import Research, Experiment
|
|
19
|
+
|
|
20
|
+
__all__ = ["Research", "Experiment", "experiment", "query", "totals", "configure", "client"]
|
|
21
|
+
|
|
22
|
+
_default = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def configure(**kwargs):
|
|
26
|
+
"""Set the process-wide default client (base, api_key, project, repo, libs)."""
|
|
27
|
+
global _default
|
|
28
|
+
_default = Research(**kwargs)
|
|
29
|
+
return _default
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def client():
|
|
33
|
+
"""The process-wide default client, built from the environment on first use."""
|
|
34
|
+
global _default
|
|
35
|
+
if _default is None:
|
|
36
|
+
_default = Research()
|
|
37
|
+
return _default
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def experiment(kind, subject, task, metric="accuracy", n_total=0, note="",
|
|
41
|
+
hypothesis="", predict=""):
|
|
42
|
+
"""Get/create an experiment handle on the default client. Pass `hypothesis` + `predict`
|
|
43
|
+
to structure it as a falsifiable test that conclude(verdict) can prove or refute."""
|
|
44
|
+
return client().experiment(kind, subject, task, metric=metric, n_total=n_total, note=note,
|
|
45
|
+
hypothesis=hypothesis, predict=predict)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def query(project=None, kind=None, canonical=True):
|
|
49
|
+
"""Read canonical experiments on the default client."""
|
|
50
|
+
return client().query(project=project, kind=kind, canonical=canonical)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def totals(project=None):
|
|
54
|
+
"""Read the headline totals (canonical + retained) on the default client."""
|
|
55
|
+
return client().totals(project=project)
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Hanzo Research SDK — the ONE way every producer records and queries research.
|
|
2
|
+
|
|
3
|
+
Generated-shape from the openapi/research contract, wrapped in a tiny, intuitive,
|
|
4
|
+
ZERO-CONFIG surface so hand-rolling is obviously the worse choice:
|
|
5
|
+
|
|
6
|
+
import hanzo_research as research
|
|
7
|
+
|
|
8
|
+
# A benchmark run — accumulate attempts, seal with the score.
|
|
9
|
+
exp = research.experiment("benchmark", "grok-4.5", "gpqa_diamond") # get/create → handle
|
|
10
|
+
exp.record("q1", "grok-4.5", {"answer": "A", "correct": True}) # an attempt, idempotent
|
|
11
|
+
exp.snapshot(png_bytes) # a board snapshot artifact
|
|
12
|
+
exp.finish(value=94.3) # seal the run (or use `with`)
|
|
13
|
+
|
|
14
|
+
# A kernel-perf run structured as a falsifiable test — state the claim, log what you
|
|
15
|
+
# see, then PROVE or REFUTE it. A refutation is a first-class, durable result.
|
|
16
|
+
k = research.experiment("kernel-perf", "matvec_q4k_f32_blk", "vulkan/6144x2048",
|
|
17
|
+
metric="ratio_vs_hand",
|
|
18
|
+
hypothesis="the DSL f32-direct matvec beats the hand kernel",
|
|
19
|
+
predict="DSL/hand >= 1.0 cold in-engine at the dominant FFN shape")
|
|
20
|
+
k.log("cold in-engine A/B, evo gfx1151, quiet window, 3 runs, bit-exact 2.3e-6")
|
|
21
|
+
k.conclude("proven", because="1.022x at 6144 rows (loses small shapes → gate >=4096)",
|
|
22
|
+
value=1.022) # git sha + lib versions auto-stamped
|
|
23
|
+
|
|
24
|
+
rows = research.query(project="enso-bench", kind="benchmark") # read canonical
|
|
25
|
+
|
|
26
|
+
Auto-instrumentation (the caller supplies NO provenance): on experiment()/finish() the
|
|
27
|
+
SDK reads git sha/branch/dirty, the commit messages SINCE the last recorded run of this
|
|
28
|
+
experiment (the narrative of what changed), the installed lib versions, and the host —
|
|
29
|
+
and weaves them into the record. Research self-documents as a side effect of running.
|
|
30
|
+
|
|
31
|
+
Auth is the per-org key (private-by-default is enforced server-side). Records mirror to
|
|
32
|
+
the cloud /v1/research surface (HIP-0512), which is versioned + append-only + idempotent
|
|
33
|
+
by content, so re-recording the same result is a no-op.
|
|
34
|
+
"""
|
|
35
|
+
import base64
|
|
36
|
+
import hashlib
|
|
37
|
+
import json
|
|
38
|
+
import os
|
|
39
|
+
import urllib.error
|
|
40
|
+
import urllib.parse
|
|
41
|
+
import urllib.request
|
|
42
|
+
|
|
43
|
+
from . import provenance
|
|
44
|
+
|
|
45
|
+
DEFAULT_LIBS = [
|
|
46
|
+
"hanzo-kernel", "hanzo-ml", "hanzo-engine", "hanzo-research",
|
|
47
|
+
"enso-bench", "datasets", "huggingface-hub", "torch", "transformers",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Research:
|
|
52
|
+
"""A configured research client. Base URL, per-org key, and project come from the
|
|
53
|
+
environment by default (HANZO_API_KEY, RESEARCH_BASE, RESEARCH_PROJECT); the repo the
|
|
54
|
+
caller runs in is auto-detected for provenance."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, base=None, api_key=None, project=None, repo=None, libs=None, timeout=120):
|
|
57
|
+
self.base = (base or os.environ.get("RESEARCH_BASE", "https://api.hanzo.ai")).rstrip("/")
|
|
58
|
+
self.api_key = api_key or os.environ.get("HANZO_API_KEY", "")
|
|
59
|
+
self.project = project or os.environ.get("RESEARCH_PROJECT", "default")
|
|
60
|
+
self.repo = repo or provenance.find_repo()
|
|
61
|
+
self.libs = libs if libs is not None else DEFAULT_LIBS
|
|
62
|
+
self.timeout = timeout
|
|
63
|
+
|
|
64
|
+
# ── transport ──────────────────────────────────────────────────────────────
|
|
65
|
+
def _headers(self):
|
|
66
|
+
# Auth is ONLY the per-org key (the gateway mints the validated principal from it).
|
|
67
|
+
# The client NEVER mints X-User-Id/X-Org-Id — that is a cross-tenant forge the
|
|
68
|
+
# gateway strips anyway (SanitizeIdentity); any local/dev bypass belongs SERVER-side
|
|
69
|
+
# behind an explicit unsafe flag, never in the client.
|
|
70
|
+
h = {"Content-Type": "application/json", "X-Project-Id": self.project}
|
|
71
|
+
if self.api_key:
|
|
72
|
+
h["Authorization"] = "Bearer " + self.api_key
|
|
73
|
+
return h
|
|
74
|
+
|
|
75
|
+
def _req(self, method, path, payload=None):
|
|
76
|
+
data = json.dumps(payload).encode() if payload is not None else None
|
|
77
|
+
req = urllib.request.Request(self.base + path, data=data, headers=self._headers(), method=method)
|
|
78
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
|
79
|
+
return json.loads(r.read() or b"{}")
|
|
80
|
+
|
|
81
|
+
# ── low-level surface (mirrors the contract; used by the bulk uploader) ──────
|
|
82
|
+
def ingest(self, experiments=None, attempts=None):
|
|
83
|
+
"""POST a batch of experiments + attempts. Idempotent by content; returns the
|
|
84
|
+
cloud counts (canonical + retained)."""
|
|
85
|
+
return self._req("POST", "/v1/research/experiments",
|
|
86
|
+
{"experiments": experiments or [], "attempts": attempts or []})
|
|
87
|
+
|
|
88
|
+
def artifact(self, art):
|
|
89
|
+
return self._req("POST", "/v1/research/artifacts", art)
|
|
90
|
+
|
|
91
|
+
def grant(self, **g):
|
|
92
|
+
return self._req("POST", "/v1/research/grants", g)
|
|
93
|
+
|
|
94
|
+
# ── ergonomic surface ───────────────────────────────────────────────────────
|
|
95
|
+
def experiment(self, kind, subject, task, metric="accuracy", n_total=0, note="",
|
|
96
|
+
hypothesis="", predict=""):
|
|
97
|
+
"""Get/create the experiment for (kind, subject, task) and return a handle. Auto-
|
|
98
|
+
captures provenance + the self-documenting narrative (the caller's docstring, the
|
|
99
|
+
commit messages since this experiment's last run, and an optional note).
|
|
100
|
+
|
|
101
|
+
Structure it as a falsifiable test: `hypothesis` is the claim under test and
|
|
102
|
+
`predict` is the observation that would confirm it — stated up front so a later
|
|
103
|
+
conclude(verdict) can PROVE or REFUTE it unambiguously. A refutation is a
|
|
104
|
+
first-class result, recorded as clearly as a proof."""
|
|
105
|
+
return Experiment(self, kind, subject, task, metric=metric, n_total=n_total,
|
|
106
|
+
note=note, hypothesis=hypothesis, predict=predict)
|
|
107
|
+
|
|
108
|
+
def query(self, project=None, kind=None, canonical=True):
|
|
109
|
+
"""Read canonical experiments (the answered latest-run view). canonical=False is
|
|
110
|
+
reserved for the full retained-version history (a follow-up endpoint; the retained
|
|
111
|
+
COUNTS are already on /v1/research/totals)."""
|
|
112
|
+
q = []
|
|
113
|
+
if project or self.project:
|
|
114
|
+
q.append("project=" + urllib.parse.quote(project or self.project))
|
|
115
|
+
if kind:
|
|
116
|
+
q.append("kind=" + urllib.parse.quote(kind))
|
|
117
|
+
path = "/v1/research/experiments" + ("?" + "&".join(q) if q else "")
|
|
118
|
+
out = self._req("GET", path)
|
|
119
|
+
return out.get("data", [])
|
|
120
|
+
|
|
121
|
+
def totals(self, project=None):
|
|
122
|
+
path = "/v1/research/totals" + ("?project=" + urllib.parse.quote(project) if project else "")
|
|
123
|
+
return self._req("GET", path)
|
|
124
|
+
|
|
125
|
+
# ── internal ────────────────────────────────────────────────────────────────
|
|
126
|
+
def _last_run_sha(self, exp_id):
|
|
127
|
+
"""The git sha of this experiment's last recorded run, for the since-narrative."""
|
|
128
|
+
try:
|
|
129
|
+
for e in self.query():
|
|
130
|
+
if e.get("id") == exp_id:
|
|
131
|
+
return e.get("git_sha", "")
|
|
132
|
+
except Exception:
|
|
133
|
+
return ""
|
|
134
|
+
return ""
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Experiment:
|
|
138
|
+
"""A handle to one experiment (a run of kind:subject:task). record() files attempts;
|
|
139
|
+
snapshot()/report() file diary artifacts; finish() seals the run with its final
|
|
140
|
+
number + the auto-captured narrative. Usable as a context manager (finish on exit)."""
|
|
141
|
+
|
|
142
|
+
def __init__(self, client, kind, subject, task, metric="accuracy", n_total=0, note="",
|
|
143
|
+
hypothesis="", predict=""):
|
|
144
|
+
self.c = client
|
|
145
|
+
self.kind, self.subject, self.task, self.metric = kind, subject, task, metric
|
|
146
|
+
self.id = f"{kind}:{subject}:{task}"
|
|
147
|
+
self.n_total = n_total
|
|
148
|
+
self._ok = 0
|
|
149
|
+
self._n = 0
|
|
150
|
+
# The falsifiable frame, stated up front so the verdict is unambiguous: the claim
|
|
151
|
+
# under test, and the observation that would confirm it.
|
|
152
|
+
self.hypothesis = hypothesis
|
|
153
|
+
self.predict = predict
|
|
154
|
+
self.verdict = "" # proven | refuted | inconclusive — set by conclude()
|
|
155
|
+
self.because = "" # the reasoning that earns the verdict
|
|
156
|
+
self._log = [] # the running notes/logs that travel with the run
|
|
157
|
+
# Zero-config, self-documenting provenance. THREE narrative sources, captured with
|
|
158
|
+
# nothing asked of the caller: (a) the calling code's docstring — what this
|
|
159
|
+
# experiment IS; (b) the commit messages since this experiment's last recorded run
|
|
160
|
+
# — what changed + why; (c) an optional note. Plus git state, lib versions, host.
|
|
161
|
+
self.prov = provenance.git_state(self.c.repo)
|
|
162
|
+
self.doc = provenance.caller_doc()
|
|
163
|
+
self.note = note
|
|
164
|
+
last = self.c._last_run_sha(self.id)
|
|
165
|
+
self.commits = provenance.commit_narrative(self.c.repo, since_sha=last)
|
|
166
|
+
self.libs = provenance.lib_versions(self.c.libs)
|
|
167
|
+
self.host = provenance.host()
|
|
168
|
+
# Post the run as in-flight so the ops board sees it immediately.
|
|
169
|
+
self._post(status="running", value=0.0)
|
|
170
|
+
|
|
171
|
+
def log(self, text):
|
|
172
|
+
"""Append to the running log — the 'what I saw / thought' trail that travels with
|
|
173
|
+
the run into the record. Chainable. (`note=` on experiment() is the one-shot note;
|
|
174
|
+
log() accumulates the ongoing entries.)"""
|
|
175
|
+
self._log.append(text)
|
|
176
|
+
return self
|
|
177
|
+
|
|
178
|
+
def conclude(self, verdict, because="", value=None):
|
|
179
|
+
"""Seal the experiment with its epistemic VERDICT ∈ {proven, refuted, inconclusive}
|
|
180
|
+
(distinct from execution status) and the reasoning that earns it, then finish the
|
|
181
|
+
run. A refutation is recorded as clearly and durably as a proof — the whole point of
|
|
182
|
+
an evidentiary layer. Returns the sealed record."""
|
|
183
|
+
if verdict not in ("proven", "refuted", "inconclusive"):
|
|
184
|
+
raise ValueError(f"verdict must be proven|refuted|inconclusive, got {verdict!r}")
|
|
185
|
+
self.verdict = verdict
|
|
186
|
+
self.because = because
|
|
187
|
+
return self.finish(value=value)
|
|
188
|
+
|
|
189
|
+
def _post(self, status, value):
|
|
190
|
+
e = {
|
|
191
|
+
"id": self.id, "kind": self.kind, "subject": self.subject, "task": self.task,
|
|
192
|
+
"metric": self.metric, "value": value, "n": self._n, "n_total": self.n_total,
|
|
193
|
+
"status": status, "git_sha": self.prov["git_sha"], "git_branch": self.prov["git_branch"],
|
|
194
|
+
"git_dirty": self.prov["git_dirty"], "lib_versions": self.libs,
|
|
195
|
+
# meta carries the scientific frame + the self-documenting narrative. hypothesis/
|
|
196
|
+
# predict/verdict/because make the run a falsifiable claim with a clear result;
|
|
197
|
+
# verdict is queryable evidence (e.g. every refuted lever) — promoting it to a
|
|
198
|
+
# first-class column is the follow-up, the shape is fixed here.
|
|
199
|
+
"meta": {"doc": self.doc, "commits": self.commits, "note": self.note, "host": self.host,
|
|
200
|
+
"hypothesis": self.hypothesis, "predict": self.predict,
|
|
201
|
+
"verdict": self.verdict, "because": self.because, "log": self._log},
|
|
202
|
+
}
|
|
203
|
+
return self.c.ingest(experiments=[e])
|
|
204
|
+
|
|
205
|
+
def record(self, item, model, result):
|
|
206
|
+
"""File one attempt (idempotent by stable id). `result` is a dict:
|
|
207
|
+
{answer, correct, response?, gold?, source?, status?}."""
|
|
208
|
+
a = {
|
|
209
|
+
"benchmark": self.task, "item": item, "model": model,
|
|
210
|
+
"answer": result.get("answer", ""), "correct": bool(result.get("correct")),
|
|
211
|
+
"response": result.get("response", ""), "gold": result.get("gold", ""),
|
|
212
|
+
"source": result.get("source", "hanzo-measured"), "status": result.get("status", "complete"),
|
|
213
|
+
}
|
|
214
|
+
if a["status"] not in ("faulted", "failed"):
|
|
215
|
+
self._n += 1
|
|
216
|
+
if a["correct"]:
|
|
217
|
+
self._ok += 1
|
|
218
|
+
return self.c.ingest(attempts=[a])
|
|
219
|
+
|
|
220
|
+
def snapshot(self, data, run_id=None):
|
|
221
|
+
"""File a board-snapshot artifact. `data` is the PNG bytes (or a path to the PNG).
|
|
222
|
+
The SDK submits the bytes; the SERVER content-addresses them by sha256."""
|
|
223
|
+
raw = data if isinstance(data, (bytes, bytearray)) else _read_bytes(data)
|
|
224
|
+
return self._artifact("snapshot", raw, run_id)
|
|
225
|
+
|
|
226
|
+
def report(self, data, run_id=None):
|
|
227
|
+
"""File a generated-report artifact — HTML/Markdown TEXT (or bytes)."""
|
|
228
|
+
raw = data if isinstance(data, (bytes, bytearray)) else str(data).encode()
|
|
229
|
+
return self._artifact("report", raw, run_id)
|
|
230
|
+
|
|
231
|
+
def _artifact(self, kind, raw, run_id):
|
|
232
|
+
# Submit the BYTES; the server hashes them and owns the sha256 + ref. The client
|
|
233
|
+
# sha256 travels only so the server can reject a mismatch (a mis-hash or tamper).
|
|
234
|
+
return self.c.artifact({
|
|
235
|
+
"content": base64.b64encode(raw).decode(),
|
|
236
|
+
"sha256": hashlib.sha256(raw).hexdigest(),
|
|
237
|
+
"kind": kind, "run_id": run_id or self.id,
|
|
238
|
+
"git_sha": self.prov["git_sha"], "git_branch": self.prov["git_branch"],
|
|
239
|
+
"git_dirty": self.prov["git_dirty"], "lib_versions": self.libs,
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
def finish(self, value=None):
|
|
243
|
+
"""Seal the run: post the final number (computed from recorded attempts if not
|
|
244
|
+
given) + status complete. A new version supersedes the in-flight one; the prior
|
|
245
|
+
is retained. If a hypothesis was stated but no verdict declared, it defaults to
|
|
246
|
+
`inconclusive` — a finished run never silently reads as a proof."""
|
|
247
|
+
if value is None:
|
|
248
|
+
value = round(100.0 * self._ok / self._n, 2) if self._n else 0.0
|
|
249
|
+
if self.hypothesis and not self.verdict:
|
|
250
|
+
self.verdict = "inconclusive"
|
|
251
|
+
return self._post(status="complete", value=value)
|
|
252
|
+
|
|
253
|
+
def __enter__(self):
|
|
254
|
+
return self
|
|
255
|
+
|
|
256
|
+
def __exit__(self, exc_type, exc, tb):
|
|
257
|
+
# A run that raised is sealed faulted (retained), else complete.
|
|
258
|
+
if exc_type is not None:
|
|
259
|
+
self._post(status="faulted", value=0.0)
|
|
260
|
+
else:
|
|
261
|
+
self.finish()
|
|
262
|
+
return False
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _read_bytes(path):
|
|
266
|
+
with open(path, "rb") as f:
|
|
267
|
+
return f.read()
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Zero-config provenance auto-capture — like OpenTelemetry auto-instrument, for
|
|
2
|
+
experiments. The caller supplies nothing; the SDK reads the run's environment: git
|
|
3
|
+
sha/branch/dirty, the recent COMMIT MESSAGES (the narrative of what changed), the
|
|
4
|
+
installed lib versions, and the host. Import and go.
|
|
5
|
+
"""
|
|
6
|
+
import inspect
|
|
7
|
+
import os
|
|
8
|
+
import socket
|
|
9
|
+
import subprocess
|
|
10
|
+
from importlib import metadata
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _git(repo, *args):
|
|
14
|
+
try:
|
|
15
|
+
return subprocess.check_output(["git", "-C", repo, *args], stderr=subprocess.DEVNULL, text=True).strip()
|
|
16
|
+
except Exception:
|
|
17
|
+
return ""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def git_state(repo):
|
|
21
|
+
"""The producing repo's commit sha, branch, and whether the tree was dirty."""
|
|
22
|
+
return {
|
|
23
|
+
"git_sha": _git(repo, "rev-parse", "HEAD"),
|
|
24
|
+
"git_branch": _git(repo, "rev-parse", "--abbrev-ref", "HEAD"),
|
|
25
|
+
"git_dirty": bool(_git(repo, "status", "--porcelain")),
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def commit_narrative(repo, since_sha="", window=10):
|
|
30
|
+
"""The commit-message narrative — the 'what changed + why' story. Commit subjects
|
|
31
|
+
SINCE the last recorded run's sha when known (`<since>..HEAD`), else the last
|
|
32
|
+
`window` commits. Research self-documents as a side effect of running."""
|
|
33
|
+
rng = f"{since_sha}..HEAD" if since_sha else f"-n{window}"
|
|
34
|
+
raw = _git(repo, "log", rng, "--format=%s") if since_sha else _git(repo, "log", f"-{window}", "--format=%s")
|
|
35
|
+
return [ln for ln in raw.splitlines() if ln.strip()]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def lib_versions(names):
|
|
39
|
+
"""{lib: installed version} for the relevant libs, skipping any not installed."""
|
|
40
|
+
out = {}
|
|
41
|
+
for n in names or []:
|
|
42
|
+
try:
|
|
43
|
+
out[n] = metadata.version(n)
|
|
44
|
+
except Exception:
|
|
45
|
+
pass
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def host():
|
|
50
|
+
"""The box the run executed on — enough to correlate a result to hardware."""
|
|
51
|
+
return {"hostname": socket.gethostname(), "platform": os.uname().sysname if hasattr(os, "uname") else os.name}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def find_repo(start=None):
|
|
55
|
+
"""The git repo the caller runs in (the toplevel), auto-detected from the CWD."""
|
|
56
|
+
start = start or os.getcwd()
|
|
57
|
+
top = _git(start, "rev-parse", "--show-toplevel")
|
|
58
|
+
return top or start
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def caller_doc():
|
|
62
|
+
"""The docstring of the first caller frame OUTSIDE this SDK — 'what this experiment
|
|
63
|
+
is', captured zero-config from the researcher's normal module docstring. Together
|
|
64
|
+
with the commit narrative and an optional note, the project self-documents as a side
|
|
65
|
+
effect of running: write a normal docstring + commit normally, nothing extra."""
|
|
66
|
+
for fr in inspect.stack():
|
|
67
|
+
mod = fr.frame.f_globals.get("__name__", "")
|
|
68
|
+
if not mod.startswith("hanzo_research"):
|
|
69
|
+
return (fr.frame.f_globals.get("__doc__") or "").strip()
|
|
70
|
+
return ""
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "hanzo-research"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Hanzo Research SDK — record and query R&D evidence (experiments, attempts, diary artifacts) via /v1/research. Zero-config provenance auto-capture."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
authors = [{ name = "Hanzo AI", email = "dev@hanzo.ai" }]
|
|
8
|
+
requires-python = ">=3.9"
|
|
9
|
+
dependencies = [] # stdlib only (urllib) — importable in any zero-dep harness
|
|
10
|
+
|
|
11
|
+
[project.urls]
|
|
12
|
+
Homepage = "https://hanzo.ai"
|
|
13
|
+
|
|
14
|
+
[build-system]
|
|
15
|
+
requires = ["hatchling"]
|
|
16
|
+
build-backend = "hatchling.build"
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["hanzo_research"]
|