@simplexai/localmodels-linux-x64 0.1.0-dev.56 → 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 (37) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +36 -35
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_admin.py +2 -1
  5. package/modules/localmodels/bifrost_checks.py +11 -8
  6. package/modules/localmodels/bifrost_models.py +2 -1
  7. package/modules/localmodels/catalog.json +10 -8
  8. package/modules/localmodels/gateway_accept.py +4 -3
  9. package/modules/localmodels/gateway_bifrost.py +2 -1
  10. package/modules/localmodels/gateway_cli.py +4 -3
  11. package/modules/localmodels/gateway_server.py +3 -1
  12. package/modules/localmodels/harness.py +2 -2
  13. package/modules/localmodels/hf_repo.py +27 -4
  14. package/modules/localmodels/remote_ops_download.py +36 -261
  15. package/modules/localmodels/remote_ops_ranges.py +447 -0
  16. package/modules/localmodels/runtime_auth.py +2 -1
  17. package/modules/localmodels/runtime_cli.py +1 -1
  18. package/modules/localmodels/runtime_install.py +5 -2
  19. package/modules/localmodels/runtime_io.py +3 -2
  20. package/modules/localmodels/runtime_pi.py +2 -1
  21. package/modules/localmodels/runtime_windows_acl.py +39 -0
  22. package/modules/localmodels/source_byok_probe.py +2 -1
  23. package/modules/localmodels/stack.py +13 -3
  24. package/modules/localmodels/stack_cli.py +1 -0
  25. package/modules/localmodels/stack_events.py +15 -0
  26. package/modules/localmodels/stack_plan.py +5 -1
  27. package/modules/localmodels/stack_progress.py +30 -5
  28. package/modules/localmodels/stack_run.py +117 -0
  29. package/modules/localmodels/transport.py +1 -0
  30. package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/METADATA +1 -1
  31. package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/RECORD +33 -32
  32. package/package.json +1 -1
  33. package/tool.json +1 -1
  34. /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/WHEEL +0 -0
  35. /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/entry_points.txt +0 -0
  36. /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/NOTICE +0 -0
  37. /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -18,14 +18,15 @@ import time
18
18
  import urllib.error
19
19
  import urllib.parse
20
20
  import urllib.request
21
- from typing import Any, Iterator, Tuple
21
+ from typing import Iterator, Tuple
22
22
 
23
23
  try:
24
- from localmodels import remote_ops, remote_ops_mirrors, remote_ops_prepare
24
+ from localmodels import remote_ops, remote_ops_mirrors, remote_ops_prepare, remote_ops_ranges
25
25
  except ImportError: # run as a bare file from this directory
26
26
  import remote_ops # type: ignore[import-not-found,no-redef]
27
27
  import remote_ops_mirrors # type: ignore[import-not-found,no-redef]
28
28
  import remote_ops_prepare # type: ignore[import-not-found,no-redef]
29
+ import remote_ops_ranges # type: ignore[import-not-found,no-redef]
29
30
 
30
31
  _Ranked = Tuple["remote_ops.Source", bool] # a source and whether it serves byte ranges
31
32
 
@@ -186,8 +187,25 @@ CROSS_REGION_PROBE_BPS = 2_000_000
186
187
  SLOW_WINDOW_S = 15.0
187
188
  SLOW_BYTES_PER_S = 256 * 1024
188
189
  SLOW_MIN_REMAINING_S = 30.0
189
- SEGMENTS = 4
190
+ # A file is fetched over up to CONNECTIONS parallel byte ranges of at least MIN_SEGMENT_BYTES
191
+ # each. A connection that finishes its range takes over the second part of the range that will
192
+ # finish last (work stealing), split by the two connections' rates so both end together; a
193
+ # stalled connection loses all of its range. A piece is stolen only when the thief would spend
194
+ # at least STEAL_MIN_S on it, so the extra request (TLS, a Hub redirect) is worth it. Counts come
195
+ # from the 2026-11-24 measurements in docs/local-models/network-download-optimization.md: from
196
+ # China the Hugging Face CDN (also behind hf-mirror) caps each connection near 0.1 MB/s, so 16
197
+ # connections fetch about 16 times as fast; ModelScope reaches the link's ~100 MB/s with 8.
198
+ CONNECTIONS = 8
199
+ SOURCE_CONNECTIONS: dict[str, int] = {"huggingface": 16, "hf-mirror": 16}
190
200
  MIN_SEGMENT_BYTES = 64 << 20
201
+ STEAL_MIN_S = 6.0
202
+ STEAL_MIN_BYTES = 8 << 20 # while no connection's rate is known yet, halve ranges this large
203
+ CLAIM_GRACE_S = 3.0 # a connection's rate is unknown until this long after its first byte
204
+ # A connection with no first byte after this long counts as stalled. The first byte of a Hub
205
+ # range took up to 3 s (a redirect, then TLS to the CDN), so a slow start is not a stall.
206
+ CLAIM_STALL_S = 20.0
207
+ CLAIM_RATE_WINDOW_S = 10.0
208
+ STEAL_POLL_S = 0.5 # how often an idle connection looks for a range to steal
191
209
  ATTEMPTS = 5
192
210
  # A connection's progress moves once per read, so reads stay small: an 8 MiB read at 2-3 MB/s
193
211
  # per connection made the 2 s rate jump in 4 MiB/s steps (often 0). The rate shown is the
@@ -436,10 +454,6 @@ def ordered(
436
454
  yield from _ordered_public(own, public_s, size, label, region, failed, probe_speeds)
437
455
 
438
456
 
439
- class _NoRangeError(Exception):
440
- """The source stopped honouring byte ranges; the next source is tried."""
441
-
442
-
443
457
  class SlowTransferError(RuntimeError):
444
458
  """Sustained transfer throughput dropped below SLOW_BYTES_PER_S; switch to another host."""
445
459
 
@@ -451,147 +465,6 @@ class SlowTransferError(RuntimeError):
451
465
  )
452
466
 
453
467
 
454
- def _split(start: int, end: int) -> list[list[int]]:
455
- """[start, end, done] segments of [start, end): SEGMENTS of them when each gets at least
456
- MIN_SEGMENT_BYTES, fewer otherwise, never none for a non-empty range."""
457
- count = max(1, min(SEGMENTS, (end - start) // MIN_SEGMENT_BYTES))
458
- step = -(-(end - start) // count)
459
- return [[s, min(end, s + step), s] for s in range(start, end, step)]
460
-
461
-
462
- def _resume_ranges(part: str, size: int) -> list[list[int]]:
463
- """The segments still to fetch. A plain .part (a single-connection download of an earlier
464
- version) is a finished prefix; the file is then sized so each range writes in place."""
465
- segments = _load_ranges(part, size)
466
- if segments is None:
467
- have = os.path.getsize(part) if os.path.exists(part) else 0
468
- with open(part, "ab") as out:
469
- out.truncate(size)
470
- segments = _split(have, size) if have < size else []
471
- _save_ranges(part, size, segments)
472
- return segments
473
-
474
-
475
- def _retryable(exc: BaseException) -> bool:
476
- """Permanent HTTP responses (unfollowed redirects such as 308, client errors other than
477
- 408/429) will not turn into the pinned file on retry; move on to the next source at once."""
478
- if isinstance(exc, urllib.error.HTTPError):
479
- return exc.code in (408, 429) or exc.code >= 500
480
- return True
481
-
482
-
483
- class _Transfer:
484
- """Parallel ranged download of one file: each segment resumes from its own ``done`` offset
485
- with retries; ``done`` advances only after the bytes are written, so the saved record never
486
- claims bytes the file lacks."""
487
-
488
- def __init__(
489
- self,
490
- url: str,
491
- part: str,
492
- size: int,
493
- segments: list[list[int]],
494
- *,
495
- attempts: int | None = None,
496
- ) -> None:
497
- self.url, self.part, self.size, self.segments = url, part, size, segments
498
- self.attempts = ATTEMPTS if attempts is None else max(1, attempts)
499
- self.lock, self.io_lock = threading.Lock(), threading.Lock()
500
- self.stop = threading.Event()
501
- self.errors: list[BaseException] = []
502
- self._responses: list[Any] = []
503
-
504
- def _track_response(self, resp: Any) -> None:
505
- with self.lock:
506
- self._responses.append(resp)
507
-
508
- def _untrack_response(self, resp: Any) -> None:
509
- with self.lock:
510
- if resp in self._responses:
511
- self._responses.remove(resp)
512
-
513
- def stop_and_close(self) -> None:
514
- with self.io_lock:
515
- self.stop.set()
516
- with self.lock:
517
- active = list(self._responses)
518
- for resp in active:
519
- for target in (resp, getattr(resp, "fp", None)):
520
- if target is not None:
521
- try:
522
- target.close()
523
- except Exception: # noqa: BLE001
524
- pass
525
-
526
- def remaining(self) -> int:
527
- with self.lock:
528
- return sum(end - done for _, end, done in self.segments)
529
-
530
- def snapshot(self) -> list[list[int]]:
531
- with self.lock:
532
- return [list(s) for s in self.segments]
533
-
534
- def _range(self, segment: list[int]) -> None:
535
- done, end = segment[2], segment[1]
536
- with urllib.request.urlopen(_ranged_request(self.url, done, end), timeout=60) as r:
537
- self._track_response(r)
538
- try:
539
- if self.stop.is_set():
540
- return
541
- if getattr(r, "status", 200) != 206 or not str(
542
- r.headers.get("Content-Range", "")
543
- ).startswith(f"bytes {done}-"):
544
- raise _NoRangeError()
545
- read_fn = getattr(r, "read1", r.read)
546
- with self.io_lock:
547
- if self.stop.is_set():
548
- return
549
- out = open(self.part, "r+b", buffering=0)
550
- with out:
551
- out.seek(done)
552
- while done < end and not self.stop.is_set():
553
- chunk = read_fn(min(READ_BYTES, end - done))
554
- if not chunk:
555
- break
556
- with self.io_lock:
557
- if self.stop.is_set():
558
- break
559
- view = memoryview(chunk)
560
- while view:
561
- view = view[out.write(view) or 0 :]
562
- done += len(chunk)
563
- with self.lock:
564
- segment[2] = done
565
- finally:
566
- self._untrack_response(r)
567
- if done < end and not self.stop.is_set():
568
- raise http.client.IncompleteRead(b"", end - done)
569
-
570
- def worker(self, segment: list[int]) -> None:
571
- attempt = 0
572
- while segment[2] < segment[1] and not self.stop.is_set():
573
- try:
574
- self._range(segment)
575
- except _NoRangeError as exc:
576
- self.fail(exc)
577
- except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
578
- if self.stop.is_set():
579
- return
580
- attempt += 1
581
- if not _retryable(exc) or attempt >= self.attempts:
582
- self.fail(exc)
583
- return
584
- self.stop.wait(min(30, 2**attempt))
585
- except BaseException as exc: # noqa: BLE001 - reported by the main thread
586
- if not self.stop.is_set():
587
- self.fail(exc)
588
-
589
- def fail(self, exc: BaseException) -> None:
590
- with self.lock:
591
- self.errors.append(exc)
592
- self.stop_and_close()
593
-
594
-
595
468
  def transfer(
596
469
  source: remote_ops.Source,
597
470
  part: str,
@@ -606,124 +479,26 @@ def transfer(
606
479
  on failure with the kept ranges saved so the next call (or source) resumes them. A source
607
480
  that turns out not to serve ranges is read once as one plain stream from the start."""
608
481
  if ranged:
609
- job = _Transfer(source["url"], part, size, _resume_ranges(part, size), attempts=attempts)
610
- _run(job, source, label, ranged=True, allow_slow_switch=allow_slow_switch)
611
- if not (job.errors and isinstance(job.errors[0], _NoRangeError)):
612
- _finish(job, label)
482
+ count = remote_ops_ranges.connections_for(source)
483
+ job = remote_ops_ranges._Transfer(
484
+ source["url"],
485
+ part,
486
+ size,
487
+ remote_ops_ranges._resume_ranges(part, size, count),
488
+ attempts=attempts,
489
+ connections=count,
490
+ )
491
+ remote_ops_ranges._run(job, source, label, ranged=True, allow_slow_switch=allow_slow_switch)
492
+ if not (job.errors and isinstance(job.errors[0], remote_ops_ranges._NoRangeError)):
493
+ remote_ops_ranges._finish(job, label)
613
494
  return
614
495
  discard(part)
615
496
  open(part, "wb").close()
616
- job = _Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
617
- _run(job, source, label, ranged=False, allow_slow_switch=allow_slow_switch)
618
- _finish(job, label)
497
+ job = remote_ops_ranges._Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
498
+ remote_ops_ranges._run(job, source, label, ranged=False, allow_slow_switch=allow_slow_switch)
499
+ remote_ops_ranges._finish(job, label)
619
500
 
620
501
 
621
502
  DEFAULT_TRANSFER = transfer
622
503
 
623
-
624
- def _finish(job: _Transfer, label: str) -> None:
625
- if job.errors:
626
- raise job.errors[0]
627
- if job.remaining():
628
- raise RuntimeError(f"{label} download stopped with bytes missing")
629
-
630
-
631
504
  Rate = remote_ops_mirrors.Rate
632
-
633
-
634
- def _run(
635
- job: _Transfer,
636
- source: remote_ops.Source,
637
- label: str,
638
- *,
639
- ranged: bool,
640
- allow_slow_switch: bool = False,
641
- ) -> None:
642
- if ranged:
643
- threads = [
644
- threading.Thread(target=job.worker, args=(s,), daemon=True)
645
- for s in job.segments
646
- if s[2] < s[1]
647
- ]
648
- else:
649
- threads = [threading.Thread(target=_plain, args=(job,), daemon=True)]
650
- for thread in threads:
651
- thread.start()
652
- size = job.size
653
- mark = time.monotonic()
654
- initial_done = size - job.remaining()
655
- meter = Rate(mark, initial_done)
656
- slow_window_start, slow_window_done = mark, initial_done
657
- while True:
658
- alive = [t for t in threads if t.is_alive()] # the connections open during this interval
659
- if not alive:
660
- break
661
- for t in alive:
662
- t.join(timeout=remote_ops._PROGRESS_EVERY_S / len(alive))
663
- now, done = time.monotonic(), size - job.remaining()
664
- if allow_slow_switch and not job.stop.is_set():
665
- window_elapsed = now - slow_window_start
666
- if window_elapsed >= SLOW_WINDOW_S:
667
- window_rate = int((done - slow_window_done) / max(1e-3, window_elapsed))
668
- remaining = max(0, size - done)
669
- near_done = remaining <= SLOW_BYTES_PER_S * SLOW_MIN_REMAINING_S
670
- if window_rate < SLOW_BYTES_PER_S and not near_done:
671
- job.fail(SlowTransferError(window_rate))
672
- break
673
- slow_window_start, slow_window_done = now, done
674
- if now - mark >= remote_ops._PROGRESS_EVERY_S:
675
- remote_ops.emit(
676
- "progress",
677
- phase="download",
678
- file=label,
679
- done=done,
680
- total=size,
681
- bytes_per_s=meter.add(now, done),
682
- source=source["source"],
683
- connections=len(alive),
684
- **remote_ops.step_fields(done),
685
- )
686
- mark = now
687
- if ranged:
688
- _save_ranges(job.part, size, job.snapshot())
689
- if job.errors or any(t.is_alive() for t in threads):
690
- job.stop_and_close()
691
- deadline = time.monotonic() + 2.0
692
- for t in threads:
693
- if t.is_alive():
694
- t.join(timeout=max(0.0, deadline - time.monotonic()))
695
- if ranged:
696
- _save_ranges(job.part, size, job.snapshot())
697
-
698
-
699
- def _plain(job: _Transfer) -> None:
700
- """A single unranged stream (a data: URL or a server without Range support)."""
701
- segment = job.segments[0]
702
- try:
703
- with urllib.request.urlopen(
704
- urllib.request.Request(job.url, headers={"User-Agent": "localmodels-deploy"}),
705
- timeout=60,
706
- ) as r:
707
- job._track_response(r)
708
- try:
709
- with job.io_lock:
710
- if job.stop.is_set():
711
- return
712
- out = open(job.part, "wb")
713
- with out:
714
- read_fn = getattr(r, "read1", r.read)
715
- while not job.stop.is_set():
716
- chunk = read_fn(READ_BYTES)
717
- if not chunk:
718
- break
719
- with job.io_lock:
720
- if job.stop.is_set():
721
- break
722
- out.write(chunk)
723
- with job.lock:
724
- segment[2] = min(segment[1], segment[2] + len(chunk))
725
- finally:
726
- job._untrack_response(r)
727
- except BaseException as exc: # noqa: BLE001 - reported by the main thread
728
- if not job.stop.is_set():
729
- job.fail(exc)