yhatmodels 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.
- yhatmodels/__init__.py +22 -0
- yhatmodels/account.py +212 -0
- yhatmodels/catalog.py +28 -0
- yhatmodels/cli.py +152 -0
- yhatmodels/errors.py +13 -0
- yhatmodels/hub.py +124 -0
- yhatmodels/licensing.py +79 -0
- yhatmodels/loading.py +31 -0
- yhatmodels/py.typed +0 -0
- yhatmodels/registry.py +44 -0
- yhatmodels/ts/__init__.py +7 -0
- yhatmodels/ts/architectures/__init__.py +7 -0
- yhatmodels/ts/architectures/chakrats_v1.py +331 -0
- yhatmodels/ts/covariates.py +76 -0
- yhatmodels/ts/evaluate.py +360 -0
- yhatmodels/ts/forecaster.py +650 -0
- yhatmodels/ts/plotting.py +218 -0
- yhatmodels/ts/predictor.py +205 -0
- yhatmodels/ts/scaling.py +68 -0
- yhatmodels/ts/tune.py +288 -0
- yhatmodels-0.1.0.dist-info/METADATA +284 -0
- yhatmodels-0.1.0.dist-info/RECORD +26 -0
- yhatmodels-0.1.0.dist-info/WHEEL +4 -0
- yhatmodels-0.1.0.dist-info/entry_points.txt +2 -0
- yhatmodels-0.1.0.dist-info/licenses/LICENSE +175 -0
- yhatmodels-0.1.0.dist-info/licenses/NOTICE +8 -0
yhatmodels/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Copyright (c) 2026 Forum Software, Inc. (YHat Labs). Licensed under the Apache License, Version 2.0.
|
|
2
|
+
"""yhatmodels (YHatModels): open models from YHat Labs, run locally. The hosted models are in the `yhatlabs` client.
|
|
3
|
+
|
|
4
|
+
Each task lives in its own subpackage (yhatmodels.ts: time-series forecasting) and is imported when first used, so
|
|
5
|
+
`import yhatmodels` stays light as tasks are added.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
from yhatmodels.catalog import list_models
|
|
11
|
+
from yhatmodels.licensing import accept_license
|
|
12
|
+
|
|
13
|
+
_LAZY = {"ChakraTS": "yhatmodels.ts", "plot_forecast": "yhatmodels.ts"} # name -> the task module that has it
|
|
14
|
+
__all__ = ["ChakraTS", "__version__", "accept_license", "list_models", "plot_forecast"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def __getattr__(name: str):
|
|
18
|
+
if name in _LAZY:
|
|
19
|
+
import importlib
|
|
20
|
+
|
|
21
|
+
return getattr(importlib.import_module(_LAZY[name]), name)
|
|
22
|
+
raise AttributeError(f"module 'yhatmodels' has no attribute {name!r}")
|
yhatmodels/account.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# Copyright (c) 2026 Forum Software, Inc. (YHat Labs). Licensed under the Apache License, Version 2.0.
|
|
2
|
+
"""The one-time license acceptance for YHat Labs' open models, tied to a yhatlabs.com account.
|
|
3
|
+
|
|
4
|
+
Before the first download of such a model, yhatmodels checks with the YHat Labs API that the person behind a token has
|
|
5
|
+
accepted the model's license. With no token, or one whose account has not accepted it yet, it opens yhatlabs.com in the
|
|
6
|
+
browser (sign in or create an account, accept the license) and receives the token back on a one-off local address; the
|
|
7
|
+
token can also be pasted. It is then kept in ~/.cache/yhatmodels/token. Weights already downloaded are never checked, so
|
|
8
|
+
they work offline.
|
|
9
|
+
|
|
10
|
+
The token (`yhm_...`) only proves the acceptance: it cannot call the paid API. An API key works in its place.
|
|
11
|
+
Environment: YHAT_MODELS_TOKEN (or YHAT_API_KEY) for CI; YHATMODELS_NO_BROWSER=1 to never open a browser;
|
|
12
|
+
YHAT_API_URL and YHAT_SITE_URL to point at a test deployment.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import http.server
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import secrets
|
|
21
|
+
import sys
|
|
22
|
+
import threading
|
|
23
|
+
import urllib.error
|
|
24
|
+
import urllib.parse
|
|
25
|
+
import urllib.request
|
|
26
|
+
import webbrowser
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from yhatmodels.errors import LicenseNotAcceptedError
|
|
30
|
+
|
|
31
|
+
TOKEN_ENV, KEY_ENV, NO_BROWSER_ENV = "YHAT_MODELS_TOKEN", "YHAT_API_KEY", "YHATMODELS_NO_BROWSER"
|
|
32
|
+
WAIT_S = 600 # how long the terminal waits for the browser before giving up
|
|
33
|
+
_accepted: set[str] = set() # licenses confirmed in this process
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def api_url() -> str:
|
|
37
|
+
return os.environ.get("YHAT_API_URL", "https://api.yhatlabs.com").rstrip("/")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def site_url() -> str:
|
|
41
|
+
return os.environ.get("YHAT_SITE_URL", "https://yhatlabs.com").rstrip("/")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def token_file() -> Path:
|
|
45
|
+
return Path(os.environ.get("YHATMODELS_CACHE", Path.home() / ".cache" / "yhatmodels")) / "token"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def license_page(license_id: str, model: str, **extra: str) -> str:
|
|
49
|
+
return f"{site_url()}/models/license?" + urllib.parse.urlencode({"license": license_id, "model": model, **extra})
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def stored_token() -> tuple[str | None, str]:
|
|
53
|
+
"""The token to use and where it came from ("env" or "file"): YHAT_MODELS_TOKEN, YHAT_API_KEY, then the saved one."""
|
|
54
|
+
for env in (TOKEN_ENV, KEY_ENV):
|
|
55
|
+
if v := os.environ.get(env, "").strip():
|
|
56
|
+
return v, "env"
|
|
57
|
+
f = token_file()
|
|
58
|
+
return (f.read_text().strip() or None, "file") if f.is_file() else (None, "file")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def save_token(token: str) -> Path:
|
|
62
|
+
f = token_file()
|
|
63
|
+
f.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
f.write_text(token + "\n")
|
|
65
|
+
f.chmod(0o600)
|
|
66
|
+
return f
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def check(token: str, license_id: str) -> str:
|
|
70
|
+
"""'accepted', 'not_accepted', 'invalid' (unknown or replaced token) or 'unreachable'."""
|
|
71
|
+
req = urllib.request.Request(f"{api_url()}/v1/licenses/{urllib.parse.quote(license_id)}",
|
|
72
|
+
headers={"Authorization": f"Bearer {token}", "User-Agent": "yhatmodels"}) # fmt: skip
|
|
73
|
+
try:
|
|
74
|
+
with urllib.request.urlopen(req, timeout=15) as r:
|
|
75
|
+
return "accepted" if json.load(r).get("accepted") else "not_accepted"
|
|
76
|
+
except urllib.error.HTTPError as e:
|
|
77
|
+
return "invalid" if e.code in (401, 403) else "unreachable"
|
|
78
|
+
except (urllib.error.URLError, OSError, ValueError):
|
|
79
|
+
return "unreachable"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _has_display() -> bool:
|
|
83
|
+
if sys.platform in ("win32", "darwin"):
|
|
84
|
+
return not (os.environ.get("SSH_CONNECTION") and not os.environ.get("DISPLAY"))
|
|
85
|
+
return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _in_notebook() -> bool:
|
|
89
|
+
shell = sys.modules.get("IPython") and getattr(sys.modules["IPython"], "get_ipython", lambda: None)()
|
|
90
|
+
return type(shell).__name__ == "ZMQInteractiveShell"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _callback_server(state: str, done_url: str) -> tuple[http.server.HTTPServer, threading.Event, list[str]]:
|
|
94
|
+
"""A one-off server on 127.0.0.1 that takes the token the license page sends back. `state` ties the answer to this
|
|
95
|
+
request, so another page cannot plant a token."""
|
|
96
|
+
got, event = [], threading.Event()
|
|
97
|
+
|
|
98
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
99
|
+
def do_GET(self) -> None:
|
|
100
|
+
q = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
|
|
101
|
+
ok = q.get("state", [""])[0] == state and bool(q.get("token", [""])[0].strip())
|
|
102
|
+
if ok:
|
|
103
|
+
got.append(q["token"][0].strip())
|
|
104
|
+
event.set()
|
|
105
|
+
self.send_response(302)
|
|
106
|
+
self.send_header("Location", done_url)
|
|
107
|
+
self.end_headers()
|
|
108
|
+
return
|
|
109
|
+
self.send_response(400)
|
|
110
|
+
self.send_header("Content-Type", "text/plain; charset=utf-8")
|
|
111
|
+
self.end_headers()
|
|
112
|
+
self.wfile.write(b"This link does not match the request from your terminal. Run the download again.")
|
|
113
|
+
|
|
114
|
+
def log_message(self, *args: object) -> None:
|
|
115
|
+
pass
|
|
116
|
+
|
|
117
|
+
server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
|
|
118
|
+
threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.2}, daemon=True).start()
|
|
119
|
+
return server, event, got
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _wait(event: threading.Event, got: list[str], paste: bool) -> str | None:
|
|
123
|
+
"""The browser's answer, or a token pasted in the terminal, whichever comes first."""
|
|
124
|
+
if not paste or sys.platform == "win32": # select() on stdin is Unix-only
|
|
125
|
+
return got[0] if event.wait(WAIT_S) else None
|
|
126
|
+
import select
|
|
127
|
+
import time
|
|
128
|
+
|
|
129
|
+
print("Or paste your token here and press Enter: ", end="", flush=True)
|
|
130
|
+
end = time.monotonic() + WAIT_S
|
|
131
|
+
while not event.is_set():
|
|
132
|
+
if time.monotonic() > end:
|
|
133
|
+
print()
|
|
134
|
+
return None
|
|
135
|
+
ready, _, _ = select.select([sys.stdin], [], [], 0.25)
|
|
136
|
+
if ready:
|
|
137
|
+
line = sys.stdin.readline()
|
|
138
|
+
if not line:
|
|
139
|
+
return None
|
|
140
|
+
if line.strip():
|
|
141
|
+
return line.strip()
|
|
142
|
+
print()
|
|
143
|
+
return got[0]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def obtain_token(license_id: str, model: str, intro: str) -> str | None:
|
|
147
|
+
"""A token from the browser or the terminal; None where neither is possible (CI, scripts, no browser allowed)."""
|
|
148
|
+
tty, notebook = sys.stdin.isatty(), _in_notebook()
|
|
149
|
+
if not (tty or notebook):
|
|
150
|
+
return None
|
|
151
|
+
browser = os.environ.get(NO_BROWSER_ENV, "").strip().lower() not in ("1", "true", "yes") and (notebook or _has_display())
|
|
152
|
+
if not browser:
|
|
153
|
+
if not tty:
|
|
154
|
+
return None
|
|
155
|
+
print(f"{intro}\nOpen this page in a browser (sign in or create an account, then accept):\n\n "
|
|
156
|
+
f"{license_page(license_id, model)}\n\nthen paste the token it shows.") # fmt: skip
|
|
157
|
+
try:
|
|
158
|
+
return input("Token: ").strip() or None
|
|
159
|
+
except (EOFError, KeyboardInterrupt):
|
|
160
|
+
return None
|
|
161
|
+
state = secrets.token_urlsafe(16)
|
|
162
|
+
server, event, got = _callback_server(state, license_page(license_id, model, done="1"))
|
|
163
|
+
url = license_page(license_id, model, callback=f"http://127.0.0.1:{server.server_address[1]}/", state=state)
|
|
164
|
+
try:
|
|
165
|
+
print(f"{intro}\nOpening yhatlabs.com in your browser (sign in or create an account, then accept):\n\n {url}\n")
|
|
166
|
+
webbrowser.open(url)
|
|
167
|
+
return _wait(event, got, paste=tty)
|
|
168
|
+
except KeyboardInterrupt:
|
|
169
|
+
return None
|
|
170
|
+
finally:
|
|
171
|
+
server.shutdown()
|
|
172
|
+
server.server_close()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def ensure_license(model: str, license_id: str) -> None:
|
|
176
|
+
"""Make sure the person running this has accepted `license_id` (the license of `model`), asking them once if not."""
|
|
177
|
+
if license_id in _accepted:
|
|
178
|
+
return
|
|
179
|
+
page = license_page(license_id, model)
|
|
180
|
+
token, source = stored_token()
|
|
181
|
+
status = check(token, license_id) if token else "invalid"
|
|
182
|
+
if status == "accepted":
|
|
183
|
+
_accepted.add(license_id)
|
|
184
|
+
return
|
|
185
|
+
if status == "unreachable":
|
|
186
|
+
raise LicenseNotAcceptedError(
|
|
187
|
+
f"Could not reach {api_url()} to check the license of {model} before its first download. Check the "
|
|
188
|
+
"connection and try again; once downloaded, the model works offline."
|
|
189
|
+
)
|
|
190
|
+
if status == "invalid" and token and source == "file":
|
|
191
|
+
token_file().unlink(missing_ok=True) # replaced on the website, or from another deployment
|
|
192
|
+
intro = (f"{model} is free for research, personal use, internal evaluation and competitions under its license. It "
|
|
193
|
+
"needs a one-time acceptance with a yhatlabs.com account before the first download; your data stays on "
|
|
194
|
+
"this machine.") # fmt: skip
|
|
195
|
+
new = obtain_token(license_id, model, intro)
|
|
196
|
+
if new is None:
|
|
197
|
+
why = {"not_accepted": "The account of this token has not accepted it yet.",
|
|
198
|
+
"invalid": "The token is no longer valid." if token else "No token found."}[status] # fmt: skip
|
|
199
|
+
raise LicenseNotAcceptedError(
|
|
200
|
+
f"{model} needs a one-time license acceptance with a yhatlabs.com account before its first download. {why}\n"
|
|
201
|
+
f" 1. Open {page} (sign in or create an account) and accept the license.\n"
|
|
202
|
+
f" 2. Copy the token the page shows and set it: export {TOKEN_ENV}=<token>\n"
|
|
203
|
+
f" (or run `yhatmodels accept-license {model}` in a terminal, which does both)."
|
|
204
|
+
)
|
|
205
|
+
status = check(new, license_id)
|
|
206
|
+
if status != "accepted":
|
|
207
|
+
why = {"invalid": "is not valid", "not_accepted": "belongs to an account that has not accepted the license",
|
|
208
|
+
"unreachable": "could not be checked"}[status] # fmt: skip
|
|
209
|
+
raise LicenseNotAcceptedError(f"That token {why}. Accept the license at {page}, then copy the token it shows.")
|
|
210
|
+
saved = save_token(new)
|
|
211
|
+
_accepted.add(license_id)
|
|
212
|
+
print(f"License accepted. Token saved to {saved}; {model} will download now.")
|
yhatmodels/catalog.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Copyright (c) 2026 Forum Software, Inc. (YHat Labs). Licensed under the Apache License, Version 2.0.
|
|
2
|
+
"""Models released by YHat Labs: the short name, the Hugging Face repository, the task and the weights license.
|
|
3
|
+
|
|
4
|
+
Knowing the license here lets yhatmodels ask for acceptance before any download (for these models, once per person with
|
|
5
|
+
a yhatlabs.com account: yhatmodels.account); a model that is not listed is read from its config.json first.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
MODELS: dict[str, dict[str, str]] = {
|
|
11
|
+
"ChakraTS-OS-10M": {
|
|
12
|
+
"repo": "yhatlabs/ChakraTS-OS-10M",
|
|
13
|
+
"task": "forecasting",
|
|
14
|
+
"license": "chakra-nc-1.0",
|
|
15
|
+
"description": "10.6M-parameter probabilistic time-series forecaster",
|
|
16
|
+
},
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def lookup(model: str) -> dict[str, str] | None:
|
|
21
|
+
"""A catalogued model by its short name or its repository id, with its `name`."""
|
|
22
|
+
name = model if model in MODELS else next((n for n, m in MODELS.items() if m["repo"] == model), None)
|
|
23
|
+
return {"name": name, **MODELS[name]} if name else None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def list_models(task: str | None = None) -> list[dict[str, str]]:
|
|
27
|
+
"""The released models (optionally of one task), each with its name, repository, task, license and description."""
|
|
28
|
+
return [{"name": name, **m} for name, m in MODELS.items() if task is None or m["task"] == task]
|
yhatmodels/cli.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Copyright (c) 2026 Forum Software, Inc. (YHat Labs). Licensed under the Apache License, Version 2.0.
|
|
2
|
+
"""`yhatmodels`: forecast, backtest and fine-tune from the command line, on a CSV or Parquet file in long format (one row
|
|
3
|
+
per series and timestamp). The commands and options follow the YHat Labs SDK's CLI.
|
|
4
|
+
|
|
5
|
+
yhatmodels forecast sales.csv --h 24 --level 80,95 --known price --future future.csv -o fc.csv
|
|
6
|
+
yhatmodels evaluate sales.csv --h 24 --windows 3
|
|
7
|
+
yhatmodels tune sales.csv --h 24 --steps 300 -o my-tuned/
|
|
8
|
+
yhatmodels forecast sales.csv --h 24 --model my-tuned/
|
|
9
|
+
yhatmodels models
|
|
10
|
+
yhatmodels accept-license ChakraTS-OS-10M
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _read(path: str):
|
|
22
|
+
import pandas as pd
|
|
23
|
+
|
|
24
|
+
p = Path(path)
|
|
25
|
+
suffix = p.suffix.lower()
|
|
26
|
+
if suffix in (".parquet", ".pq"):
|
|
27
|
+
return pd.read_parquet(p)
|
|
28
|
+
if suffix in (".tsv", ".tab"):
|
|
29
|
+
return pd.read_csv(p, sep="\t")
|
|
30
|
+
if suffix == ".json":
|
|
31
|
+
return pd.read_json(p)
|
|
32
|
+
return pd.read_csv(p)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _write(df, path: str | None) -> None:
|
|
36
|
+
if path is None:
|
|
37
|
+
df.to_csv(sys.stdout, index=False)
|
|
38
|
+
elif path.lower().endswith((".parquet", ".pq")):
|
|
39
|
+
df.to_parquet(path, index=False)
|
|
40
|
+
else:
|
|
41
|
+
df.to_csv(path, index=False)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _list(s: str | None, kind=str):
|
|
45
|
+
return None if s is None else [kind(x) for x in s.split(",") if x.strip()]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _cols(p: argparse.ArgumentParser) -> None:
|
|
49
|
+
p.add_argument("--known", help="covariate columns known over the next h steps too (comma-separated)")
|
|
50
|
+
p.add_argument("--past", help="covariate columns known only up to now (comma-separated)")
|
|
51
|
+
p.add_argument("--id-col"), p.add_argument("--time-col")
|
|
52
|
+
p.add_argument("--target-col", help="the target column (several, comma-separated, are forecast jointly)")
|
|
53
|
+
p.add_argument("--freq", help="pandas frequency alias (h, D, W-SUN, MS, 15min, ...); inferred when left out")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _model_opts(p: argparse.ArgumentParser) -> None:
|
|
57
|
+
p.add_argument("--model", default="ChakraTS-OS-10M", help="a released model's name, a Hugging Face repo id or a local folder")
|
|
58
|
+
p.add_argument("--device", help="cuda, mps or cpu (default: the best available)")
|
|
59
|
+
p.add_argument("--preset", help="fast or pro (default: the model's own)")
|
|
60
|
+
p.add_argument("--cross-series", nargs="?", type=int, const=16, default=None, metavar="N",
|
|
61
|
+
help="read single-target series without covariates N at a time (default N: 16)") # fmt: skip
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _parser() -> argparse.ArgumentParser:
|
|
65
|
+
ap = argparse.ArgumentParser(prog="yhatmodels", description="Open YHat Labs models, run locally.")
|
|
66
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
67
|
+
f = sub.add_parser("forecast", help="forecast the next h steps of every series")
|
|
68
|
+
f.add_argument("data"), f.add_argument("--h", type=int, required=True)
|
|
69
|
+
f.add_argument("--quantiles", help="levels in (0, 1), comma-separated (default 0.1,0.5,0.9), or 'all'")
|
|
70
|
+
f.add_argument("--level", help="central interval widths in percent, comma-separated (e.g. 80,95)")
|
|
71
|
+
f.add_argument("--future", help="file with the --known columns' values over the next h steps")
|
|
72
|
+
f.add_argument("-o", "--output", help="CSV or Parquet file (default: CSV on stdout)")
|
|
73
|
+
_cols(f), _model_opts(f)
|
|
74
|
+
e = sub.add_parser("evaluate", help="rolling backtest against baselines")
|
|
75
|
+
e.add_argument("data"), e.add_argument("--h", type=int, required=True)
|
|
76
|
+
e.add_argument("--windows", type=int, default=3), e.add_argument("--step", type=int)
|
|
77
|
+
e.add_argument("--metrics", help="comma-separated: mase, sql, wql, mae, rmse, coverage@0.8 (default: all of them)")
|
|
78
|
+
e.add_argument("--baselines", default="seasonal_naive", help="comma-separated: seasonal_naive, naive")
|
|
79
|
+
e.add_argument("--season", type=int, help="seasonal period in steps (default: from the frequency)")
|
|
80
|
+
e.add_argument("-o", "--output", help="file for the per-series, per-window scores")
|
|
81
|
+
_cols(e), _model_opts(e)
|
|
82
|
+
t = sub.add_parser("tune", help="fine-tune the model on your series and save the tuned model")
|
|
83
|
+
t.add_argument("data"), t.add_argument("--h", type=int, required=True)
|
|
84
|
+
t.add_argument("--steps", type=int, default=300), t.add_argument("--seed", type=int, default=0)
|
|
85
|
+
t.add_argument("--season", type=int), t.add_argument("--min-gain", type=float, default=0.02)
|
|
86
|
+
t.add_argument("-o", "--output", required=True, help="folder for the tuned model (load it with --model FOLDER)")
|
|
87
|
+
_cols(t), _model_opts(t)
|
|
88
|
+
sub.add_parser("models", help="the released models, their tasks and licenses")
|
|
89
|
+
a = sub.add_parser(
|
|
90
|
+
"accept-license", help="accept a model's license before its first download (YHat Labs models: with a yhatlabs.com account)"
|
|
91
|
+
)
|
|
92
|
+
a.add_argument("model")
|
|
93
|
+
return ap
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def main(argv: list[str] | None = None) -> int:
|
|
97
|
+
args = _parser().parse_args(argv)
|
|
98
|
+
from yhatmodels.errors import YHatModelsError
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
return _run(args)
|
|
102
|
+
except (YHatModelsError, ValueError, TypeError, OSError) as e: # a mistake in the input or setup: the message, not a traceback
|
|
103
|
+
print(f"yhatmodels: error: {e}", file=sys.stderr)
|
|
104
|
+
return 1
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _run(args) -> int:
|
|
108
|
+
import yhatmodels
|
|
109
|
+
|
|
110
|
+
if args.cmd == "models":
|
|
111
|
+
for m in yhatmodels.list_models():
|
|
112
|
+
print("\t".join(str(m.get(k, "")) for k in ("name", "task", "license", "repo")))
|
|
113
|
+
return 0
|
|
114
|
+
if args.cmd == "accept-license":
|
|
115
|
+
where = yhatmodels.accept_license(args.model)
|
|
116
|
+
print("license accepted" + (f"; recorded in {where}" if where else ""))
|
|
117
|
+
return 0
|
|
118
|
+
data = _read(args.data)
|
|
119
|
+
model = yhatmodels.ChakraTS.from_pretrained(args.model, device=args.device)
|
|
120
|
+
target = _list(args.target_col)
|
|
121
|
+
cols = {"known": _list(args.known), "past": _list(args.past), "id_col": args.id_col, "time_col": args.time_col,
|
|
122
|
+
"target_col": target[0] if target and len(target) == 1 else target, "freq": args.freq} # fmt: skip
|
|
123
|
+
common = {"preset": args.preset, "cross_series": args.cross_series, **cols}
|
|
124
|
+
if args.cmd == "forecast":
|
|
125
|
+
quantiles = "all" if args.quantiles == "all" else _list(args.quantiles, float)
|
|
126
|
+
future = _read(args.future) if args.future else None
|
|
127
|
+
fc = model.forecast(data, args.h, quantiles=quantiles, level=_list(args.level, float), future=future, **common)
|
|
128
|
+
_write(fc, args.output)
|
|
129
|
+
if args.output:
|
|
130
|
+
print(f"wrote {len(fc)} rows to {args.output}", file=sys.stderr)
|
|
131
|
+
return 0
|
|
132
|
+
if args.cmd == "evaluate":
|
|
133
|
+
kw = {"metrics": _list(args.metrics)} if args.metrics else {}
|
|
134
|
+
res = model.evaluate(data, args.h, windows=args.windows, step=args.step, baselines=_list(args.baselines), season=args.season,
|
|
135
|
+
**kw, **common) # fmt: skip
|
|
136
|
+
print(res.summary.to_string(float_format=lambda x: f"{x:.4f}"))
|
|
137
|
+
for w in res.warnings:
|
|
138
|
+
print(f"note: {w}", file=sys.stderr)
|
|
139
|
+
if args.output:
|
|
140
|
+
_write(res.scores, args.output)
|
|
141
|
+
return 0
|
|
142
|
+
tuned = model.tune(data, args.h, steps=args.steps, seed=args.seed, season=args.season, min_gain=args.min_gain, verbose=True, **common)
|
|
143
|
+
print(json.dumps(tuned.report, indent=2))
|
|
144
|
+
if tuned.report and tuned.report.get("used"):
|
|
145
|
+
print(f"saved to {tuned.save(args.output)}; forecast with --model {args.output}")
|
|
146
|
+
else:
|
|
147
|
+
print("not saved: the tune did not beat the pretrained model on your holdout", file=sys.stderr)
|
|
148
|
+
return 0
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
if __name__ == "__main__":
|
|
152
|
+
raise SystemExit(main())
|
yhatmodels/errors.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Copyright (c) 2026 Forum Software, Inc. (YHat Labs). Licensed under the Apache License, Version 2.0.
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class YHatModelsError(Exception):
|
|
5
|
+
"""Base class for yhatmodels errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LicenseNotAcceptedError(YHatModelsError):
|
|
9
|
+
"""The model's license has not been accepted yet (see yhatmodels.accept_license)."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ModelLoadError(YHatModelsError):
|
|
13
|
+
"""A model folder or repository is missing a file, or its config names an architecture yhatmodels does not have."""
|
yhatmodels/hub.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Copyright (c) 2026 Forum Software, Inc. (YHat Labs). Licensed under the Apache License, Version 2.0.
|
|
2
|
+
"""Model files: a local folder, or a Hugging Face repository downloaded once into the Hugging Face cache.
|
|
3
|
+
|
|
4
|
+
A released model is a folder with `config.json` (its task, architecture, network settings, license and inference
|
|
5
|
+
defaults) and its weights: `model.safetensors`, or shards listed in `model.safetensors.index.json` for large models.
|
|
6
|
+
`config.json` may also carry `files` (any other files the model needs, e.g. a tabular model's preprocessor), `sha256`
|
|
7
|
+
(file name -> digest), checked when the model loads, and `requires_yhatmodels`, the oldest yhatmodels that can run it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from yhatmodels.catalog import lookup
|
|
17
|
+
from yhatmodels.errors import ModelLoadError
|
|
18
|
+
from yhatmodels.licensing import ensure_accepted
|
|
19
|
+
|
|
20
|
+
CONFIG, WEIGHTS, INDEX = "config.json", "model.safetensors", "model.safetensors.index.json"
|
|
21
|
+
DOWNLOAD = [CONFIG, "model*.safetensors", INDEX, "LICENSE*", "NOTICE*"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def resolve(model: str | Path, revision: str | None = None, token: str | None = None) -> Path:
|
|
25
|
+
"""A local folder as it is; otherwise a released model's short name or a Hugging Face repo id: the copy already in
|
|
26
|
+
the Hugging Face cache (no network: downloaded before means accepted before), else downloaded after its license has
|
|
27
|
+
been accepted when the license asks for that (yhatmodels.licensing). Returns the folder."""
|
|
28
|
+
path = Path(model).expanduser()
|
|
29
|
+
if path.is_dir():
|
|
30
|
+
if not (path / CONFIG).exists() or not ((path / WEIGHTS).exists() or (path / INDEX).exists()):
|
|
31
|
+
missing = [f for f in (CONFIG, WEIGHTS) if not (path / f).exists()]
|
|
32
|
+
raise ModelLoadError(f"{path} is missing {', '.join(missing)}")
|
|
33
|
+
_check_files(path)
|
|
34
|
+
return path
|
|
35
|
+
from huggingface_hub import snapshot_download
|
|
36
|
+
from huggingface_hub.utils import HFValidationError, RepositoryNotFoundError
|
|
37
|
+
|
|
38
|
+
from yhatmodels.catalog import MODELS
|
|
39
|
+
|
|
40
|
+
what = (f"A model is a released model's name ({', '.join(MODELS)}; yhatmodels.list_models()), a Hugging Face repository "
|
|
41
|
+
"id ('owner/name') or a folder with config.json and the weights.") # fmt: skip
|
|
42
|
+
entry = lookup(str(model))
|
|
43
|
+
name = str(model)
|
|
44
|
+
if not entry and (name.startswith((".", "/", "~", "\\")) or name.count("/") > 1 or "\\" in name):
|
|
45
|
+
raise ModelLoadError(f"{name}: no such folder. {what}")
|
|
46
|
+
repo = entry["repo"] if entry else name
|
|
47
|
+
if (cached := _cached(repo, revision)) is not None:
|
|
48
|
+
return cached
|
|
49
|
+
if entry:
|
|
50
|
+
ensure_accepted(repo, entry["license"]) # known without a network call
|
|
51
|
+
try:
|
|
52
|
+
head = Path(snapshot_download(repo, revision=revision, token=token, allow_patterns=[CONFIG]))
|
|
53
|
+
except (RepositoryNotFoundError, HFValidationError):
|
|
54
|
+
raise ModelLoadError(f"{name} is not a model yhatmodels can find (no such repository, or a private one). {what}") from None
|
|
55
|
+
config = read_config(head)
|
|
56
|
+
if not entry: # another repository: its config.json names the license
|
|
57
|
+
ensure_accepted(repo, config.get("license"))
|
|
58
|
+
folder = Path(snapshot_download(repo, revision=revision, token=token, allow_patterns=[*DOWNLOAD, *config.get("files", [])]))
|
|
59
|
+
_check_files(folder)
|
|
60
|
+
return folder
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _cached(repo: str, revision: str | None) -> Path | None:
|
|
64
|
+
"""The repository's complete copy in the local Hugging Face cache, or None (nothing or part of it there)."""
|
|
65
|
+
from huggingface_hub import snapshot_download
|
|
66
|
+
|
|
67
|
+
try: # only the files we download: newer huggingface_hub calls a snapshot without the card or .gitattributes incomplete
|
|
68
|
+
folder = Path(snapshot_download(repo, revision=revision, local_files_only=True, allow_patterns=DOWNLOAD))
|
|
69
|
+
except (OSError, ValueError): # LocalEntryNotFoundError, IncompleteSnapshotError: not (fully) downloaded; a bad id
|
|
70
|
+
return None
|
|
71
|
+
if not (folder / CONFIG).exists():
|
|
72
|
+
return None
|
|
73
|
+
shards = set(json.loads((folder / INDEX).read_text())["weight_map"].values()) if (folder / INDEX).exists() else {WEIGHTS}
|
|
74
|
+
return folder if all((folder / f).exists() for f in {*shards, *read_config(folder).get("files", [])}) else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _check_files(folder: Path) -> None:
|
|
78
|
+
if missing := [f for f in read_config(folder).get("files", []) if not (folder / f).exists()]:
|
|
79
|
+
raise ModelLoadError(f"{folder} is missing {', '.join(missing)}, which its config.json lists")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def read_config(folder: Path) -> dict:
|
|
83
|
+
return json.loads((folder / CONFIG).read_text())
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def weight_files(folder: Path) -> list[Path]:
|
|
87
|
+
if (folder / WEIGHTS).exists():
|
|
88
|
+
return [folder / WEIGHTS]
|
|
89
|
+
index = json.loads((folder / INDEX).read_text())
|
|
90
|
+
return [folder / name for name in sorted(set(index["weight_map"].values()))]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def load_weights(folder: Path) -> dict:
|
|
94
|
+
from safetensors.torch import load_file
|
|
95
|
+
|
|
96
|
+
state: dict = {}
|
|
97
|
+
for f in weight_files(folder):
|
|
98
|
+
state.update(load_file(f))
|
|
99
|
+
return state
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def verify(folder: Path, config: dict) -> None:
|
|
103
|
+
"""Files listed in config.json's `sha256` must match their digests (a truncated or swapped file fails here)."""
|
|
104
|
+
for name, digest in (config.get("sha256") or {}).items():
|
|
105
|
+
h = hashlib.sha256()
|
|
106
|
+
with open(folder / name, "rb") as f:
|
|
107
|
+
for block in iter(lambda: f.read(1 << 22), b""):
|
|
108
|
+
h.update(block)
|
|
109
|
+
if h.hexdigest() != digest:
|
|
110
|
+
raise ModelLoadError(f"{folder / name} does not match its sha256 in config.json; download it again")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def check_version(config: dict, version: str) -> None:
|
|
114
|
+
need = config.get("requires_yhatmodels")
|
|
115
|
+
if need and _parts(version) < _parts(need):
|
|
116
|
+
raise ModelLoadError(f"this model needs yhatmodels >= {need} (installed: {version}); upgrade with pip install -U yhatmodels")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _parts(v: str) -> tuple[int, ...]:
|
|
120
|
+
out = []
|
|
121
|
+
for p in v.split("+")[0].split("."):
|
|
122
|
+
digits = "".join(ch for ch in p if ch.isdigit())
|
|
123
|
+
out.append(int(digits or 0))
|
|
124
|
+
return tuple(out)
|
yhatmodels/licensing.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Copyright (c) 2026 Forum Software, Inc. (YHat Labs). Licensed under the Apache License, Version 2.0.
|
|
2
|
+
"""Model license acceptance.
|
|
3
|
+
|
|
4
|
+
The `yhatmodels` code is Apache-2.0. Model weights are released under their own license (named in each model's
|
|
5
|
+
`config.json` and model card). Weights under an open license (Apache-2.0, MIT, BSD) download as they are. YHat Labs'
|
|
6
|
+
models under another license (ChakraTS-OS-10M) are accepted once per person with a yhatlabs.com account before the first
|
|
7
|
+
download (yhatmodels.account: the browser opens, or a token in YHAT_MODELS_TOKEN). Other repositories' non-open licenses
|
|
8
|
+
are accepted once per model on this machine: `yhatmodels.accept_license("<repo>")`, or YHATMODELS_ACCEPT_LICENSE=1 (e.g.
|
|
9
|
+
in CI) after reading the license, stored under ~/.cache/yhatmodels/licenses. Weights loaded from a local folder or
|
|
10
|
+
already downloaded are not checked: whoever put them there has already obtained them under their license.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from yhatmodels.catalog import lookup
|
|
21
|
+
from yhatmodels.errors import LicenseNotAcceptedError
|
|
22
|
+
|
|
23
|
+
ENV = "YHATMODELS_ACCEPT_LICENSE"
|
|
24
|
+
OPEN_LICENSES = {"apache-2.0", "mit", "bsd-2-clause", "bsd-3-clause"} # SPDX ids that need no acceptance step
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def needs_acceptance(license_id: str | None) -> bool:
|
|
28
|
+
"""Whether weights under this license need acceptance before download (a missing or unknown license does)."""
|
|
29
|
+
return (license_id or "").strip().lower() not in OPEN_LICENSES
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _store() -> Path:
|
|
33
|
+
return Path(os.environ.get("YHATMODELS_CACHE", Path.home() / ".cache" / "yhatmodels")) / "licenses"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _key(model_id: str) -> str:
|
|
37
|
+
entry = lookup(model_id) # a released model's short name stands for its repository
|
|
38
|
+
return (entry["repo"] if entry else model_id).replace("/", "--")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def license_url(model_id: str) -> str:
|
|
42
|
+
return f"https://huggingface.co/{model_id}/blob/main/LICENSE.md"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def accept_license(model_id: str) -> Path | None:
|
|
46
|
+
"""Accept the license of `model_id` ahead of its first download. A YHat Labs model ("ChakraTS-OS-10M"): the one-time
|
|
47
|
+
acceptance with a yhatlabs.com account (opens the browser); returns the saved token's file, or None when the token
|
|
48
|
+
comes from the environment. Another repository: records here that you have read and accept its license; returns
|
|
49
|
+
the file the acceptance is stored in."""
|
|
50
|
+
entry = lookup(model_id)
|
|
51
|
+
if entry and needs_acceptance(entry["license"]):
|
|
52
|
+
from yhatmodels.account import ensure_license, stored_token, token_file
|
|
53
|
+
|
|
54
|
+
ensure_license(entry["name"], entry["license"])
|
|
55
|
+
return token_file() if stored_token()[1] == "file" else None
|
|
56
|
+
repo = entry["repo"] if entry else model_id
|
|
57
|
+
path = _store() / f"{_key(repo)}.json"
|
|
58
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
path.write_text(json.dumps({"model": repo, "license": license_url(repo), "accepted_at": time.time()}) + "\n")
|
|
60
|
+
return path
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def is_accepted(model_id: str) -> bool:
|
|
64
|
+
return os.environ.get(ENV, "").lower() in ("1", "true", "yes") or (_store() / f"{_key(model_id)}.json").exists()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def ensure_accepted(model_id: str, license_id: str | None = None) -> None:
|
|
68
|
+
if not needs_acceptance(license_id):
|
|
69
|
+
return
|
|
70
|
+
if entry := lookup(model_id):
|
|
71
|
+
from yhatmodels.account import ensure_license
|
|
72
|
+
|
|
73
|
+
ensure_license(entry["name"], entry["license"])
|
|
74
|
+
return
|
|
75
|
+
if not is_accepted(model_id):
|
|
76
|
+
raise LicenseNotAcceptedError(
|
|
77
|
+
f"{model_id} is released under its own license ({license_url(model_id)}). Read it, then accept it once with "
|
|
78
|
+
f'yhatmodels.accept_license("{model_id}") or set {ENV}=1.'
|
|
79
|
+
)
|
yhatmodels/loading.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Copyright (c) 2026 Forum Software, Inc. (YHat Labs). Licensed under the Apache License, Version 2.0.
|
|
2
|
+
"""Loading a released model for a task: its files, then its architecture from the registry, then its weights."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from yhatmodels import __version__, registry
|
|
12
|
+
from yhatmodels.hub import check_version, load_weights, read_config, resolve, verify
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Loaded:
|
|
17
|
+
net: torch.nn.Module # weights loaded strictly, on CPU
|
|
18
|
+
config: dict # config.json
|
|
19
|
+
folder: Path # where its files are (a tabular model's preprocessor, ...)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load(model: str | Path, task: str, revision: str | None = None, token: str | None = None) -> Loaded:
|
|
23
|
+
"""`model` (a released name, a Hugging Face repo id or a folder) for `task`: its network, config and folder."""
|
|
24
|
+
folder = resolve(model, revision, token)
|
|
25
|
+
config = read_config(folder)
|
|
26
|
+
check_version(config, __version__)
|
|
27
|
+
arch = registry.get(config.get("architecture"), task)
|
|
28
|
+
verify(folder, config)
|
|
29
|
+
net = arch.build(config.get("model", {}))
|
|
30
|
+
net.load_state_dict(load_weights(folder))
|
|
31
|
+
return Loaded(net, config, folder)
|
yhatmodels/py.typed
ADDED
|
File without changes
|