@simplexai/localmodels-linux-x64 0.1.0-dev.55 → 0.1.0-dev.57

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.
Files changed (62) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +61 -55
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_admin.py +337 -0
  5. package/modules/localmodels/bifrost_checks.py +23 -10
  6. package/modules/localmodels/bifrost_config.py +13 -5
  7. package/modules/localmodels/bifrost_models.py +2 -1
  8. package/modules/localmodels/catalog.json +12 -9
  9. package/modules/localmodels/engines.py +24 -1
  10. package/modules/localmodels/gateway_accept.py +4 -3
  11. package/modules/localmodels/gateway_bifrost.py +2 -1
  12. package/modules/localmodels/gateway_cli.py +4 -3
  13. package/modules/localmodels/gateway_server.py +3 -1
  14. package/modules/localmodels/harness.py +2 -2
  15. package/modules/localmodels/hf_repo.py +27 -4
  16. package/modules/localmodels/library_floor.py +3 -1
  17. package/modules/localmodels/library_gateway.py +26 -4
  18. package/modules/localmodels/library_jobs.py +44 -6
  19. package/modules/localmodels/library_kept.py +117 -0
  20. package/modules/localmodels/library_model.py +1 -0
  21. package/modules/localmodels/library_order.py +234 -0
  22. package/modules/localmodels/library_poly.py +20 -16
  23. package/modules/localmodels/library_pricing.py +8 -1
  24. package/modules/localmodels/library_serve.py +9 -3
  25. package/modules/localmodels/library_state.py +12 -2
  26. package/modules/localmodels/library_status.py +2 -0
  27. package/modules/localmodels/llm_rank.py +11 -8
  28. package/modules/localmodels/mirrors.py +464 -0
  29. package/modules/localmodels/recommend.py +2 -2
  30. package/modules/localmodels/records.py +1 -0
  31. package/modules/localmodels/region.py +457 -42
  32. package/modules/localmodels/remote_ops.py +130 -33
  33. package/modules/localmodels/remote_ops_download.py +233 -418
  34. package/modules/localmodels/remote_ops_mirrors.py +290 -0
  35. package/modules/localmodels/remote_ops_ranges.py +447 -0
  36. package/modules/localmodels/runtime-lock.json +19 -19
  37. package/modules/localmodels/runtime_auth.py +2 -1
  38. package/modules/localmodels/runtime_cli.py +1 -1
  39. package/modules/localmodels/runtime_install.py +5 -2
  40. package/modules/localmodels/runtime_io.py +5 -6
  41. package/modules/localmodels/runtime_pi.py +2 -1
  42. package/modules/localmodels/runtime_windows_acl.py +39 -0
  43. package/modules/localmodels/setup_inspection.py +4 -0
  44. package/modules/localmodels/source_byok_probe.py +2 -1
  45. package/modules/localmodels/stack.py +13 -3
  46. package/modules/localmodels/stack_auto.py +38 -5
  47. package/modules/localmodels/stack_cli.py +1 -0
  48. package/modules/localmodels/stack_compose.py +2 -1
  49. package/modules/localmodels/stack_events.py +15 -0
  50. package/modules/localmodels/stack_plan.py +5 -1
  51. package/modules/localmodels/stack_progress.py +30 -5
  52. package/modules/localmodels/stack_run.py +117 -0
  53. package/modules/localmodels/stack_try.py +4 -1
  54. package/modules/localmodels/transport.py +2 -0
  55. package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/METADATA +1 -1
  56. package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/RECORD +58 -52
  57. package/package.json +1 -1
  58. package/tool.json +1 -1
  59. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/WHEEL +0 -0
  60. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/entry_points.txt +0 -0
  61. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/NOTICE +0 -0
  62. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,290 @@
1
+ #!/usr/bin/env python3
2
+ """Mirror prefix tables and URL classification for remote_ops downloads.
3
+
4
+ Part of the remote_ops bundle (transport.BUNDLES): standard library only, Python 3.8+.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import collections
10
+ import json
11
+ import os
12
+ import shutil
13
+ import tarfile
14
+ import time
15
+ import urllib.parse
16
+ import urllib.request
17
+
18
+ try:
19
+ from localmodels import remote_ops
20
+ except ImportError: # run as a bare file from this directory
21
+ import remote_ops # type: ignore[import-not-found,no-redef]
22
+
23
+ RATE_WINDOW_S = 10.0
24
+
25
+
26
+ class Rate:
27
+ """Bytes per second over the last ``window`` seconds of (time, bytes done) samples."""
28
+
29
+ def __init__(self, now: float, done: int, window: float | None = None) -> None:
30
+ self.window = RATE_WINDOW_S if window is None else window
31
+ self.samples: collections.deque[tuple[float, int]] = collections.deque([(now, done)])
32
+
33
+ def add(self, now: float, done: int) -> int:
34
+ while len(self.samples) > 1 and now - self.samples[1][0] >= self.window:
35
+ self.samples.popleft()
36
+ then, before = self.samples[0]
37
+ self.samples.append((now, done))
38
+ return int((done - before) / max(1e-3, now - then))
39
+
40
+
41
+ WEB: tuple[str, ...] = ("http", "https")
42
+ SOURCE_HOSTS: tuple[tuple[str, str], ...] = (
43
+ ("hf-mirror.com", "hf-mirror"),
44
+ ("huggingface.co", "huggingface"),
45
+ ("modelscope.cn", "modelscope"),
46
+ ("npmmirror.com", "npmmirror"),
47
+ ("pypi.tuna.tsinghua.edu.cn", "pypi-tsinghua"),
48
+ ("mirrors.tuna.tsinghua.edu.cn", "tsinghua"),
49
+ ("mirrors.aliyun.com", "aliyun"),
50
+ ("mirrors.ustc.edu.cn", "ustc"),
51
+ ("mirrors.cloud.tencent.com", "tencent"),
52
+ ("repo.huaweicloud.com", "huawei"),
53
+ ("files.pythonhosted.org", "pypi"),
54
+ )
55
+ # Which side of the network each host serves best. A host on neither (GitHub, a LAN registry,
56
+ # a user's own mirror) is neutral: it is never a reason to switch the region.
57
+ GLOBAL_HOSTS: tuple[str, ...] = (
58
+ "huggingface.co",
59
+ "registry.npmjs.org",
60
+ "nodejs.org",
61
+ "files.pythonhosted.org",
62
+ "pypi.org",
63
+ )
64
+ CN_HOSTS: tuple[str, ...] = (
65
+ "hf-mirror.com",
66
+ "modelscope.cn",
67
+ "npmmirror.com",
68
+ "tsinghua.edu.cn",
69
+ "mirrors.aliyun.com",
70
+ "mirrors.ustc.edu.cn",
71
+ "mirrors.cloud.tencent.com",
72
+ "repo.huaweicloud.com",
73
+ )
74
+ # Groups of equivalent URL prefixes serving byte-identical artifacts at the exact same subpath.
75
+ # Any URL matching one prefix in a group automatically gains all other prefixes as candidates.
76
+ MIRROR_GROUPS: tuple[tuple[str, ...], ...] = (
77
+ (
78
+ "https://huggingface.co/",
79
+ "https://hf-mirror.com/",
80
+ ),
81
+ (
82
+ "https://registry.npmjs.org/",
83
+ "https://registry.npmmirror.com/",
84
+ ),
85
+ (
86
+ "https://nodejs.org/dist/",
87
+ "https://cdn.npmmirror.com/binaries/node/",
88
+ "https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/",
89
+ ),
90
+ (
91
+ "https://files.pythonhosted.org/packages/",
92
+ "https://pypi.tuna.tsinghua.edu.cn/packages/",
93
+ "https://mirrors.aliyun.com/pypi/packages/",
94
+ "https://mirrors.ustc.edu.cn/pypi/packages/",
95
+ "https://mirrors.cloud.tencent.com/pypi/packages/",
96
+ "https://repo.huaweicloud.com/repository/pypi/packages/",
97
+ ),
98
+ )
99
+ # Pairwise (global, primary_cn) view for backward-compatible inspection.
100
+ ALTERNATES: tuple[tuple[str, str], ...] = tuple((group[0], group[1]) for group in MIRROR_GROUPS)
101
+ NPM_REGISTRIES: tuple[tuple[str, str], ...] = (
102
+ ("npm", "https://registry.npmjs.org"),
103
+ ("npmmirror", "https://registry.npmmirror.com"),
104
+ )
105
+ # Tie-break order in region cn when two candidates measure the same throughput or are unprobed.
106
+ CN_RANK: dict[str, int] = {
107
+ "modelscope": 1,
108
+ "npmmirror": 1,
109
+ "pypi-tsinghua": 1,
110
+ "tsinghua": 1,
111
+ "aliyun": 1,
112
+ "ustc": 1,
113
+ "tencent": 1,
114
+ "huawei": 1,
115
+ "custom": 2,
116
+ "hf-mirror": 3,
117
+ }
118
+
119
+
120
+ def cn_rank(source: remote_ops.Source) -> int:
121
+ return 0 if remote_ops.non_public(source["url"]) else CN_RANK.get(source["source"], 4)
122
+
123
+
124
+ def _host_in(url: str, domains: tuple[str, ...]) -> bool:
125
+ host = (urllib.parse.urlsplit(url).hostname or "").lower()
126
+ return any(host == d or host.endswith("." + d) for d in domains)
127
+
128
+
129
+ def source_name(url: str) -> str:
130
+ """The public label of a download URL (never the full URL)."""
131
+ for domain, name in SOURCE_HOSTS:
132
+ if _host_in(url, (domain,)):
133
+ return name
134
+ return "custom"
135
+
136
+
137
+ def side(url: str) -> str:
138
+ """``cn``, ``global`` or "" (neutral) for a download URL."""
139
+ return "cn" if _host_in(url, CN_HOSTS) else "global" if _host_in(url, GLOBAL_HOSTS) else ""
140
+
141
+
142
+ def is_web(source: remote_ops.Source) -> bool:
143
+ return urllib.parse.urlsplit(source["url"]).scheme in WEB
144
+
145
+
146
+ def alternates(source: remote_ops.Source) -> list[remote_ops.Source]:
147
+ """Other hosts that serve byte-identical files at the same path."""
148
+ found: list[remote_ops.Source] = []
149
+ seen = {source["url"]}
150
+ for group in MIRROR_GROUPS:
151
+ for here in group:
152
+ if source["url"].startswith(here):
153
+ tail = source["url"][len(here) :]
154
+ for there in group:
155
+ if there == here:
156
+ continue
157
+ url = there + tail
158
+ if url in seen:
159
+ continue
160
+ seen.add(url)
161
+ other: remote_ops.Source = {"source": source_name(url), "url": url}
162
+ if source.get("member"):
163
+ other["member"] = source["member"]
164
+ found.append(other)
165
+ return found
166
+
167
+
168
+ def npm_copies(asset: remote_ops.Archive) -> list[remote_ops.Source]:
169
+ """The npm packages holding a byte-identical copy of ``asset`` (``npm_copy`` in the engine
170
+ and tool locks), on the npm registry and its China mirror; the copy is the package's file of
171
+ the asset's name, and its SHA256 pin is the asset's."""
172
+ copy = asset.get("npm_copy")
173
+ if not copy:
174
+ return []
175
+ name, version = copy["package"], copy["version"]
176
+ tail = f"{name}/-/{name.split('/')[-1]}-{version}.tgz"
177
+ return [
178
+ {"source": label, "url": f"{base}/{tail}", "member": "package/" + asset["name"]}
179
+ for label, base in NPM_REGISTRIES
180
+ ]
181
+
182
+
183
+ def candidates(
184
+ sources: list[remote_ops.Source], region: str | None
185
+ ) -> tuple[list[remote_ops.Source], list[remote_ops.Source]]:
186
+ """(the plan's own sources, the alternates added for the region), without duplicates."""
187
+ own: list[remote_ops.Source] = []
188
+ for s in sources:
189
+ if s.get("url") and all(s["url"] != o["url"] for o in own):
190
+ own.append(s)
191
+ extra: list[remote_ops.Source] = []
192
+ if region in ("cn", "global"):
193
+ for s in own:
194
+ for alt in alternates(s):
195
+ if all(alt["url"] != o["url"] for o in own + extra):
196
+ extra.append(alt)
197
+ return own, extra
198
+
199
+
200
+ NPM_OVERHEAD_BYTES = 4 << 20
201
+
202
+
203
+ def state_path(part: str) -> str:
204
+ return part + ".ranges"
205
+
206
+
207
+ def load_ranges(part: str, size: int) -> list[list[int]] | None:
208
+ try:
209
+ state = json.loads(remote_ops._read(state_path(part)))
210
+ segments = [[int(a), int(b), int(c)] for a, b, c in state["segments"]]
211
+ except (OSError, ValueError, KeyError, TypeError):
212
+ return None
213
+ if state.get("size") != size or not os.path.exists(part) or os.path.getsize(part) != size:
214
+ return None
215
+ if any(not 0 <= start <= done <= end <= size for start, end, done in segments):
216
+ return None
217
+ return segments
218
+
219
+
220
+ def save_ranges(part: str, size: int, segments: list[list[int]]) -> None:
221
+ path = state_path(part)
222
+ remote_ops._write(path + ".tmp", json.dumps({"size": size, "segments": segments}))
223
+ os.replace(path + ".tmp", path)
224
+
225
+
226
+ def kept_bytes(part: str, size: int) -> int:
227
+ """Bytes of ``part`` already downloaded: its ranges record when it has one, else its size."""
228
+ segments = load_ranges(part, size)
229
+ if segments is not None:
230
+ return size - sum(end - done for _, end, done in segments)
231
+ return os.path.getsize(part) if os.path.exists(part) else 0
232
+
233
+
234
+ def discard(part: str) -> None:
235
+ for path in (part, state_path(part)):
236
+ if os.path.exists(path):
237
+ os.remove(path)
238
+
239
+
240
+ def npm_transfer(
241
+ source: remote_ops.Source,
242
+ part: str,
243
+ size: int,
244
+ label: str,
245
+ *,
246
+ overhead: int | None = None,
247
+ ) -> None:
248
+ """Fill ``part`` with the ``member`` file of the npm package at ``source``: the package is
249
+ read in one bounded stream, then only that regular file of exactly ``size`` bytes is taken.
250
+ The caller checks its SHA256 against the asset's pin as for any other source."""
251
+ archive = part + ".npm"
252
+ cap = size + size // 64 + (NPM_OVERHEAD_BYTES if overhead is None else overhead)
253
+ request = urllib.request.Request(source["url"], headers={"User-Agent": "localmodels-deploy"})
254
+ got, start, mark = 0, time.monotonic(), time.monotonic()
255
+ try:
256
+ with urllib.request.urlopen(request, timeout=60) as r, open(archive, "wb") as out:
257
+ while True:
258
+ chunk = r.read(remote_ops._CHUNK)
259
+ if not chunk:
260
+ break
261
+ got += len(chunk)
262
+ if got > cap:
263
+ raise RuntimeError(f"the npm copy of {label} exceeds its size limit")
264
+ out.write(chunk)
265
+ if time.monotonic() - mark >= remote_ops._PROGRESS_EVERY_S:
266
+ mark = time.monotonic()
267
+ remote_ops.emit(
268
+ "progress",
269
+ phase="download",
270
+ file=label,
271
+ done=min(got, size),
272
+ total=size,
273
+ bytes_per_s=int(got / max(1e-3, mark - start)),
274
+ source=source["source"],
275
+ connections=1,
276
+ **remote_ops.step_fields(min(got, size)),
277
+ )
278
+ with tarfile.open(archive) as tar:
279
+ member = tar.getmember(source["member"])
280
+ stream = tar.extractfile(member) if member.isfile() and member.size == size else None
281
+ if stream is None:
282
+ raise RuntimeError(f"the npm copy of {label} does not hold a {size}-byte file")
283
+ discard(state_path(part)) # part is rewritten whole, not resumed
284
+ with stream, open(part, "wb") as out:
285
+ shutil.copyfileobj(stream, out, remote_ops._CHUNK)
286
+ except KeyError:
287
+ raise RuntimeError(f"the npm copy of {label} does not hold {source['member']}") from None
288
+ finally:
289
+ if os.path.exists(archive):
290
+ os.remove(archive)