davanstrien HF Staff commited on
Commit
5f0049a
·
verified ·
1 Parent(s): 1f9fa09

Run the ingest worker inside the Space (cpu-upgrade, rw bucket mount, Daily Papers, cap 1500, inherit quants)

Browse files
Files changed (4) hide show
  1. README.md +4 -2
  2. app.py +32 -1
  3. firehose_worker.py +1556 -0
  4. requirements.txt +6 -0
README.md CHANGED
@@ -28,8 +28,10 @@ Follow new Hugging Face Hub models, datasets and arXiv papers by topic, or brows
28
  - A worker follows the Hub and arXiv, skips items without a real card, and scores each item once with
29
  [fastino/GLiNER2.5-Decide](https://huggingface.co/fastino/GLiNER2.5-Decide): one call gives a 0–1 score for each of
30
  48 catalogue topics. It is a small open classifier running on CPU, not an LLM.
31
- - The scores are stored in the bucket `davanstrien/hub-firehose` (private for now), mounted read-only in this Space at
32
- `/data`. The Space runs no model (cpu-basic); it loads the scores into memory and checks for new files every minute.
 
 
33
  - Default thresholds (`cat48-v1.1.json`) are set so each topic tags about as many items as an LLM reference labelling
34
  did on a 750-item sample, with a floor of 0.1.
35
 
 
28
  - A worker follows the Hub and arXiv, skips items without a real card, and scores each item once with
29
  [fastino/GLiNER2.5-Decide](https://huggingface.co/fastino/GLiNER2.5-Decide): one call gives a 0–1 score for each of
30
  48 catalogue topics. It is a small open classifier running on CPU, not an LLM.
31
+ - The scores are stored in the bucket `davanstrien/hub-firehose` (private for now), mounted in this Space at `/data`.
32
+ A background worker process in this Space (cpu-upgrade, CPU only, lower priority than the page) watches the Hub for
33
+ new and updated models and datasets plus HF Daily Papers, checks whether the card changed, and scores changed items
34
+ with GLiNER2.5-Decide. The page loads the scores into memory and picks up new files every 20 s.
35
  - Default thresholds (`cat48-v1.1.json`) are set so each topic tags about as many items as an LLM reference labelling
36
  did on a 750-item sample, with a floor of 0.1.
37
 
app.py CHANGED
@@ -1,7 +1,8 @@
1
  """Topic Feed Lab: browse and follow new Hub items by topic, from precomputed scores (gradio.Server, CPU only).
2
 
3
  Scores come from the private bucket davanstrien/hub-firehose (GLiNER2.5-Decide, 48-topic catalogue cat48-v1),
4
- mounted read-only in the Space at FIREHOSE_DIR (default /data). No model runs in the Space.
 
5
  """
6
  import glob
7
  import json
@@ -221,6 +222,36 @@ threading.Thread(target=refresher, args=(STORE, REFRESH_S), daemon=True).start()
221
  threading.Thread(target=refresher, args=(EVENTS, EVENTS_REFRESH_S), daemon=True).start()
222
 
223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  # ---------------------------------------------------------------- helpers
225
  def thr_vector(thresholds):
226
  th = DEFAULT_THR.copy()
 
1
  """Topic Feed Lab: browse and follow new Hub items by topic, from precomputed scores (gradio.Server, CPU only).
2
 
3
  Scores come from the private bucket davanstrien/hub-firehose (GLiNER2.5-Decide, 48-topic catalogue cat48-v1),
4
+ mounted in the Space at FIREHOSE_DIR (default /data). The page itself runs no model; a background worker process
5
+ (firehose_worker.py, see supervise_worker) scores new Hub items on CPU and writes them to the same bucket.
6
  """
7
  import glob
8
  import json
 
222
  threading.Thread(target=refresher, args=(EVENTS, EVENTS_REFRESH_S), daemon=True).start()
223
 
224
 
225
+ # ---------------------------------------------------------------- in-Space ingest worker
226
+ # The worker (firehose_worker.py) runs GLiNER2.5-Decide on CPU and appends scores to the bucket mounted at DATA.
227
+ # It runs as a child process at lower CPU priority so page requests stay responsive. RUN_WORKER=0 disables it.
228
+ RUN_WORKER = os.environ.get("RUN_WORKER", "1") == "1"
229
+ WORKER_ARGS = ["--out", DATA, "--model-cap", "1500", "--inherit", "quantized", "--sweep-secs", "1800",
230
+ "--sweep-hours", "6", "--canary-secs", "600"]
231
+
232
+
233
+ def supervise_worker():
234
+ import subprocess
235
+ import sys
236
+
237
+ while not os.path.isdir(os.path.join(DATA, "state")):
238
+ print("worker: waiting for the bucket mount at", DATA, flush=True)
239
+ time.sleep(10)
240
+ backoff = 30
241
+ while True:
242
+ started = time.time()
243
+ proc = subprocess.Popen([sys.executable, os.path.join(HERE, "firehose_worker.py"), *WORKER_ARGS],
244
+ preexec_fn=lambda: os.nice(10))
245
+ rc = proc.wait()
246
+ print("worker exited with", rc, flush=True)
247
+ backoff = 30 if time.time() - started > 600 else min(600, backoff * 2)
248
+ time.sleep(backoff)
249
+
250
+
251
+ if RUN_WORKER:
252
+ threading.Thread(target=supervise_worker, daemon=True).start()
253
+
254
+
255
  # ---------------------------------------------------------------- helpers
256
  def thr_vector(thresholds):
257
  th = DEFAULT_THR.copy()
firehose_worker.py ADDED
@@ -0,0 +1,1556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11,<3.14"
3
+ # dependencies = [
4
+ # "gliner2[local]==2.0.0", "protobuf", "sentencepiece", "torch", "numpy", "pyarrow", "pandas",
5
+ # "huggingface_hub", "requests",
6
+ # ]
7
+ # [[tool.uv.index]]
8
+ # name = "pytorch-cpu"
9
+ # url = "https://download.pytorch.org/whl/cpu"
10
+ # explicit = true
11
+ # [tool.uv.sources]
12
+ # torch = { index = "pytorch-cpu" }
13
+ # ///
14
+ """Topic Feed Lab real-time ingest worker (v2). Continues the backfill in the hub-firehose bucket.
15
+
16
+ One long-running process. The bucket is mounted at --out (FUSE: no rename, whole-file writes only).
17
+ Threads:
18
+ hub poller every --poll-secs: list models + datasets sort=lastModified desc down to the cursor (minus
19
+ --overlap-secs), gate each repo on its README (etag, then body hash, then thin/no README), enqueue.
20
+ paper poller HF Daily Papers (today + yesterday) every --daily-secs. Optional (--arxiv-poll, off by default):
21
+ arXiv API cat:cs.* by submittedDate every --arxiv-secs. Dedupe by arXiv id.
22
+ flusher every --flush-secs: item rows, card-hash delta, events, queue snapshot, then cursor. Status 60 s.
23
+ live every --live-secs: state/events/YYYY-MM-DD/HHMM.jsonl (one line per item event, 48 h retention).
24
+ main scorer. CPU: one item per Decide call, fp32. GPU (--device cuda, drain jobs): batch 8, bf16.
25
+ compaction hourly: merge items/date=*/worker-* parts of finished hours into worker-h-<hour>-c<stamp>.parquet;
26
+ compact the gate table when there are > --compact-over deltas.
27
+ drain flag worker_status.json "drain": needed when the backlog lane > --drain-items or the estimated work >
28
+ --drain-secs. A person launches the GPU drain job (--drain-snapshot); the worker does not.
29
+
30
+ Queue: two lanes. "fresh" = first detected within --fresh-max-age of the change, plus Daily Papers; served
31
+ newest-first. "backlog" = catch-up after downtime, arXiv bulk, fresh items that aged out; served FIFO. The
32
+ scheduler takes --fresh-ratio fresh items per backlog item. The queue is saved at every flush
33
+ (state/queue-<stamp>-<job>.parquet) and restored at start, so the cursor follows the listing directly.
34
+
35
+ Outputs (under --out/--dest):
36
+ items/date=YYYY-MM-DD/worker-<YYYYMMDDTHHMM>-<job>-<n>.parquet backfill row schema; scorer = worker | drain |
37
+ inherited
38
+ state/card_hashes-delta-<YYYYMMDDTHHMMSS>-<job>.parquet gate rows changed since the last flush
39
+ state/queue-<stamp>-<job>.parquet queue snapshot (latest 2 kept)
40
+ state/worker_log/date=YYYY-MM-DD/events-<stamp>-<job>.parquet one row per gate decision / score / error
41
+ state/events/YYYY-MM-DD/HHMM.jsonl live event stream for the Space
42
+ state/cursor.json, state/worker_status.json
43
+
44
+ card_hashes merge rule: cursor.json worker.card_hashes_base (default state/card_hashes.parquet), then every
45
+ state/card_hashes-delta-*.parquet whose name stamp is newer than worker.card_hashes_base_stamp, in file-name
46
+ order; keep the last row per (source, id). Status: scored | yaml_only | thin_card | inherited. A same-etag hit
47
+ means "this README was already judged". Deltas written by other processes (a GPU drain job) are picked up at
48
+ each flush, and queued items they scored are dropped.
49
+ """
50
+ import argparse
51
+ import collections
52
+ import datetime as dt
53
+ import glob
54
+ import hashlib
55
+ import html
56
+ import io
57
+ import json
58
+ import os
59
+ import random
60
+ import re
61
+ import resource
62
+ import signal
63
+ import threading
64
+ import time
65
+ import traceback
66
+ import xml.etree.ElementTree as ET
67
+ from concurrent.futures import ThreadPoolExecutor
68
+
69
+ import numpy as np
70
+ import pyarrow as pa
71
+ import pyarrow.compute # noqa: F401 (pa.compute)
72
+ import pyarrow.parquet as pq
73
+ import requests
74
+
75
+ BASE = "fastino/GLiNER2.5-Decide"
76
+ PROMPT = "Which subject areas is this model, dataset or paper substantially about"
77
+ MIN_PROSE = 200
78
+ CAPS = {"model": 3000, "dataset": 800, "paper": 1500}
79
+ UTC = dt.timezone.utc
80
+ HUB = "https://huggingface.co"
81
+
82
+ S, I64, I32, LS = pa.string(), pa.int64(), pa.int32(), pa.list_(pa.string())
83
+ STAGE_SCHEMA = pa.schema([
84
+ ("id", S), ("source", S), ("url", S), ("title", S), ("created_at", S), ("last_modified", S),
85
+ ("readme_etag", S), ("repo_commit", S), ("body_hash", S), ("text_cap", I32), ("text", S), ("text_chars_full", I32),
86
+ ("snippet", S), ("tags", LS), ("author", S), ("likes", I64), ("downloads", I64), ("pipeline_tag", S),
87
+ ("library_name", S), ("license", S), ("gated", S), ("task_categories", LS), ("language", LS),
88
+ ("size_categories", LS), ("authors", S), ("categories", LS), ("upvotes", I64), ("paper_origin", S),
89
+ ])
90
+ ITEM_SCHEMA = pa.schema([f for f in STAGE_SCHEMA if f.name != "text"] + [
91
+ ("scores", pa.list_(pa.float32())), ("catalogue_version", S), ("scored_at", S), ("scorer", S), ("job_id", S)])
92
+ HASH_SCHEMA = pa.schema([("id", S), ("source", S), ("readme_etag", S), ("body_hash", S), ("repo_commit", S),
93
+ ("last_scored_at", S), ("status", S), ("updated_at", S), ("inherited_from", S)])
94
+ QUEUE_SCHEMA = pa.schema([("source", S), ("id", S), ("lane", S), ("first_detected", S), ("detected", S),
95
+ ("row_json", S)])
96
+ EVENT_SCHEMA = pa.schema([("ts", S), ("id", S), ("source", S), ("event", S), ("last_modified", S),
97
+ ("time_detected", S), ("time_scored", S), ("decide_s", pa.float64()), ("text_cap", I32),
98
+ ("text_chars", I32), ("queue_wait_s", pa.float64()), ("detail", S)])
99
+
100
+ # ---- copied from firehose_fetch.py (= topic-feed-space/app.py); keep in sync ----
101
+ AUTO_TAG = re.compile(r"^(region|format|size_categories|library|modality|arxiv|endpoints_compatible|"
102
+ r"text-generation-inference|autotrain_compatible|safetensors|license|base_model|doi|dataset|"
103
+ r"deploy|model-index|co2_eq_emissions)")
104
+
105
+
106
+ def strip_yaml(md):
107
+ return re.sub(r"\A---\n.*?\n---\n", "", md, flags=re.S).strip()
108
+
109
+
110
+ SNIP_SKIP = re.compile(r"^(model card|dataset card|this (model|dataset) card|table of contents|citation|license|"
111
+ r"provide a quick summary|model details|dataset details|usage|how to (use|get started)|users \(both direct|"
112
+ r"use the code below|carbon emissions can be|this modelcard aims|this dataset card aims)", re.I)
113
+
114
+
115
+ def prose_paragraphs(md):
116
+ s = re.sub(r"<!--.*?-->|```.*?```|<(script|style)\b.*?</\1>", " ", md, flags=re.S | re.I)
117
+ s = re.sub(r"\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)", " ", s)
118
+ s = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", s)
119
+ s = re.sub(r"<[^>]+>", " ", s)
120
+ s = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", s)
121
+ s = re.sub(r"https?://\S+", "", s)
122
+ for block in re.split(r"\n\s*\n", s):
123
+ raw = [ln.strip() for ln in block.splitlines() if ln.strip()]
124
+ if len(raw) >= 3 and sum(map(len, raw)) / len(raw) < 40:
125
+ continue
126
+ lines = []
127
+ for line in raw:
128
+ if line.startswith(("#", "|", "---", "===", "***")) or re.fullmatch(r"[-=:|\s]+", line):
129
+ continue
130
+ lines.append(re.sub(r"^(>\s*)+|^([-*+]|\d+\.)\s+", "", line))
131
+ text = html.unescape(re.sub(r"\*\*|__|`|~~|(?<!\w)[*_](?=\S)|(?<=\S)[*_](?!\w)", "", " ".join(lines)))
132
+ text = " ".join(text.split())
133
+ if not text or SNIP_SKIP.match(text) or "More Information Needed" in text:
134
+ continue
135
+ yield text, len(text) >= 40
136
+
137
+
138
+ def clean_snippet(md, limit=300):
139
+ out, short = [], []
140
+ for text, real in prose_paragraphs(md):
141
+ (out if real else short).append(text)
142
+ if sum(len(t) for t in out) >= limit:
143
+ break
144
+ text = " ".join(out) or " ".join(t for t in short if not t.endswith(":"))
145
+ return text if len(text) <= limit else text[:limit].rsplit(" ", 1)[0] + " …"
146
+
147
+
148
+ def prose_len(md, need=MIN_PROSE):
149
+ n = 0
150
+ for text, real in prose_paragraphs(md):
151
+ n += len(text) if real else 0
152
+ if n >= need:
153
+ break
154
+ return n
155
+ # ---- end copy ----
156
+
157
+
158
+ def now():
159
+ return dt.datetime.now(UTC)
160
+
161
+
162
+ def iso(d):
163
+ return d.astimezone(UTC).replace(microsecond=0).isoformat() if d else None
164
+
165
+
166
+ def iso_str(s):
167
+ if not s:
168
+ return None
169
+ d = dt.datetime.fromisoformat(s.replace("Z", "+00:00"))
170
+ return iso(d if d.tzinfo else d.replace(tzinfo=UTC))
171
+
172
+
173
+ def parse_iso(s):
174
+ return dt.datetime.fromisoformat(s.replace("Z", "+00:00")) if s else None
175
+
176
+
177
+ def tag_values(tags, prefix):
178
+ return [t.split(":", 1)[1] for t in tags if t.startswith(prefix + ":")]
179
+
180
+
181
+ def norm(s):
182
+ return " ".join((s or "").split())
183
+
184
+
185
+ def short_authors(a):
186
+ a = norm(a)
187
+ return a if len(a) <= 200 else a[:200].rsplit(",", 1)[0] + ", et al."
188
+
189
+
190
+ def put_bytes(data, path):
191
+ os.makedirs(os.path.dirname(path), exist_ok=True)
192
+ with open(path, "wb") as f:
193
+ f.write(data)
194
+
195
+
196
+ def put_parquet(table, path):
197
+ buf = io.BytesIO()
198
+ pq.write_table(table, buf, compression="zstd")
199
+ put_bytes(buf.getvalue(), path)
200
+
201
+
202
+ def put_json(obj, path):
203
+ put_bytes(json.dumps(obj, indent=1, default=str).encode(), path)
204
+
205
+
206
+ # internal event -> stage in the live stream (state/events/); None = not streamed
207
+ LIVE_STAGE = {"detected": "detected", "enqueued": "queued", "scored": "scored", "skip_same_etag": "skip_unchanged_etag",
208
+ "skip_yaml_only": "skip_yaml_only", "skip_no_readme": "skip_no_readme", "skip_thin_card": "skip_thin_card",
209
+ "skip_private_or_disabled": "skip_private", "superseded_in_queue": "superseded",
210
+ "decide_error": "error", "skip_gate_error": "error", "skip_fetch_error": "error",
211
+ "skip_http401": "skip_no_readme", "skip_http403": "skip_no_readme", "inherited": "inherited",
212
+ "dropped_in_queue": "superseded", "restored": None}
213
+
214
+ CANARY = ("Dataset: canary/robot-arm-demos\nTags: robotics, lerobot, task_categories:robotics\n\n"
215
+ "This dataset contains 1,200 teleoperated demonstrations of a low-cost robot arm picking up household "
216
+ "objects and placing them in a bin. Each episode has two camera views (wrist and top), joint positions, "
217
+ "gripper state and the action sent to the motors at 30 fps. The data was recorded with LeRobot and can be "
218
+ "used to train imitation-learning policies such as ACT or diffusion policy. Episodes are split into train "
219
+ "and validation sets. We also include failed grasps, marked with a success flag, to support research on "
220
+ "recovery behaviour and reward modelling. The license is Apache 2.0.")[:800]
221
+
222
+
223
+ def cpu_diag():
224
+ """Box health: load, CPU affinity, cgroup quota and throttling (cgroup v2 or v1)."""
225
+ d = {"loadavg": [round(x, 2) for x in os.getloadavg()], "affinity": len(os.sched_getaffinity(0))
226
+ if hasattr(os, "sched_getaffinity") else os.cpu_count()}
227
+ ru = resource.getrusage(resource.RUSAGE_SELF)
228
+ d["proc_cpu_s"] = round(ru.ru_utime + ru.ru_stime, 1)
229
+ for path in ("/sys/fs/cgroup/cpu.max", "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"):
230
+ try:
231
+ d["cpu_max"] = open(path).read().strip()
232
+ break
233
+ except OSError:
234
+ pass
235
+ for path in ("/sys/fs/cgroup/cpu.stat", "/sys/fs/cgroup/cpu/cpu.stat"):
236
+ try:
237
+ d["cpu_stat"] = dict(line.split() for line in open(path).read().strip().splitlines())
238
+ break
239
+ except OSError:
240
+ pass
241
+ return d
242
+
243
+
244
+ def log(*a):
245
+ print(f"[{now().strftime('%H:%M:%S')}]", *a, flush=True)
246
+
247
+
248
+ def pct(xs, q):
249
+ return round(float(np.percentile(xs, q)), 2) if len(xs) else None
250
+
251
+
252
+ # ------------------------------------------------------------------ HTTP
253
+ class Http:
254
+ def __init__(self, token):
255
+ self.token = token
256
+ self.local = threading.local()
257
+ self.arxiv_lock = threading.Lock()
258
+ self.arxiv_last = 0.0
259
+
260
+ def s(self):
261
+ s = getattr(self.local, "s", None)
262
+ if s is None:
263
+ s = requests.Session()
264
+ s.headers.update({"Accept-Encoding": "identity", "User-Agent": "Mozilla/5.0 (compatible; topic-feed-lab-worker/0.1)"})
265
+ self.local.s = s
266
+ return s
267
+
268
+ def get(self, url, params=None, auth=True, tries=6, timeout=30, method="GET", allow_redirects=True):
269
+ """Retries 429/5xx/network errors with backoff. Returns the response (any other status) or None."""
270
+ headers = {"Authorization": f"Bearer {self.token}"} if auth and self.token else {}
271
+ for attempt in range(tries):
272
+ try:
273
+ r = self.s().request(method, url, params=params, headers=headers, timeout=timeout,
274
+ allow_redirects=allow_redirects)
275
+ except requests.RequestException as e:
276
+ log("http retry", url[:90], type(e).__name__)
277
+ time.sleep(min(60, 2 ** attempt + random.random()))
278
+ continue
279
+ if r.status_code == 429 or r.status_code >= 500:
280
+ ra = r.headers.get("Retry-After")
281
+ wait = float(ra) if ra and ra.isdigit() else min(60, 2 ** attempt + random.random())
282
+ log("http", r.status_code, url[:90], f"sleep {wait:.0f}s")
283
+ time.sleep(wait)
284
+ continue
285
+ return r
286
+ return None
287
+
288
+ def arxiv(self, params, tries=7):
289
+ """export.arxiv.org with >= 3.1 s between calls. arXiv answers 406/429/503 when it throttles:
290
+ back off 30 s, 60 s, 120 s ... (max 600 s)."""
291
+ for attempt in range(tries):
292
+ with self.arxiv_lock:
293
+ wait = self.arxiv_last + 3.1 - time.time()
294
+ if wait > 0:
295
+ time.sleep(wait)
296
+ try:
297
+ r = self.s().get("https://export.arxiv.org/api/query", params=params, timeout=90)
298
+ except requests.RequestException as e:
299
+ r = None
300
+ log("arxiv retry", type(e).__name__)
301
+ self.arxiv_last = time.time()
302
+ if r is not None and r.status_code == 200:
303
+ self.arxiv_calls = getattr(self, "arxiv_calls", 0) + 1
304
+ return r.content
305
+ self.arxiv_throttled = getattr(self, "arxiv_throttled", 0) + 1
306
+ wait = min(600, 30 * 2 ** attempt)
307
+ log("arxiv", getattr(r, "status_code", "error"), f"backoff {wait}s")
308
+ time.sleep(wait)
309
+ return None
310
+
311
+
312
+ def readme_url(repo, kind):
313
+ return f"{HUB}/{'datasets/' if kind == 'dataset' else ''}{repo}/resolve/main/README.md"
314
+
315
+
316
+ def etag_of(r):
317
+ """Normalised exactly like huggingface_hub.get_hf_file_metadata / firehose_fetch.fetch_readme."""
318
+ h = r.history[0].headers if r.history else r.headers
319
+ e = h.get("X-Linked-Etag") or h.get("ETag")
320
+ return (e.lstrip("W/").strip('"') if e else None), h.get("X-Repo-Commit")
321
+
322
+
323
+ # ------------------------------------------------------------------ worker
324
+ class Worker:
325
+ def __init__(self, args):
326
+ self.a = args
327
+ self.out = args.out
328
+ self.dest = f"{args.out}/{args.dest}"
329
+ self.job_id = os.environ.get("JOB_ID")
330
+ self.sfx = (self.job_id or f"local{os.getpid()}")[-6:]
331
+ self.http = Http(os.environ.get("HF_TOKEN") or self._token())
332
+ self.cat = json.load(open(f"{args.out}/catalogue/cat48-v1.json"))
333
+ self.labels = self.cat["labels"]
334
+ self.lock = threading.RLock()
335
+ self.cv = threading.Condition(self.lock)
336
+ self.stop = threading.Event()
337
+ self.t_start = time.time()
338
+ self.deadline = self.t_start + args.max_minutes * 60 if args.max_minutes else None
339
+ # queue: pending holds the latest item per key; lanes hold keys (a key may sit in both lanes after a
340
+ # promotion; pop() skips keys that are no longer pending).
341
+ # fresh items first detected < --fresh-max-age after their change + Daily Papers; served newest-first
342
+ # backlog catch-up after downtime, arXiv bulk, fresh items that aged out; served FIFO
343
+ # scheduler: --fresh-ratio fresh pops per 1 backlog pop (when both lanes have work)
344
+ self.lanes = {"fresh": collections.deque(), "backlog": collections.deque()}
345
+ self.pending = {}
346
+ self.qcount = collections.Counter() # pending per source (no O(n) scans under the lock)
347
+ self.queue_max = {"total": 0, "hub": 0, "paper": 0}
348
+ self.inflight = []
349
+ self.pop_n = 0
350
+ # outputs buffered until the next flush
351
+ self.rows, self.hash_delta, self.events = [], [], []
352
+ self.file_n = 0
353
+ # counters
354
+ self.counts = collections.defaultdict(lambda: collections.Counter())
355
+ self.recent = collections.deque() # (t, source, event, lat_mod, lat_det, decide_s)
356
+ self.decide = collections.defaultdict(list)
357
+ self.lat_mod = collections.defaultdict(list)
358
+ self.lat_det = collections.defaultdict(list)
359
+ self.errors = collections.deque(maxlen=20)
360
+ self.live = [] # rolling event log for the Space (state/events/), flushed every --live-secs
361
+ self.live_files = {} # minute file path -> lines already in that file
362
+ self.recent_seen = {} # (src, id) -> last_modified already handled (listing overlap)
363
+ self.seen_long = {} # (src, id) -> last_modified seen in the last --sweep-hours (late-appearance sweep)
364
+ self.first_done = {"model": False, "dataset": False, "arxiv": self.a.no_papers or not self.a.arxiv_poll,
365
+ "daily": self.a.no_papers}
366
+ self.canaries = collections.deque(maxlen=200)
367
+ self.model_scores = {} # model id -> scores, for --inherit
368
+ self.load_state()
369
+
370
+ @staticmethod
371
+ def _token():
372
+ try:
373
+ from huggingface_hub import get_token
374
+ return get_token()
375
+ except Exception:
376
+ return None
377
+
378
+ # ---------------- state
379
+ def state_dirs(self):
380
+ """State is read from the bucket root and, with --dest, also from the dest prefix (dest wins)."""
381
+ return [f"{self.out}/state"] + ([f"{self.dest}state"] if self.a.dest else [])
382
+
383
+ def load_state(self):
384
+ t = time.time()
385
+ cp = f"{self.dest}state/cursor.json"
386
+ self.cursor = json.load(open(cp if os.path.exists(cp) else f"{self.out}/state/cursor.json"))
387
+ w = self.cursor.setdefault("worker", {})
388
+ # card-hash gate: base (compacted base if cursor names one) + deltas newer than the base
389
+ base_name = w.get("card_hashes_base") or "card_hashes.parquet"
390
+ base_stamp = w.get("card_hashes_base_stamp", "")
391
+ self.hashes = {}
392
+ for r in pq.read_table(f"{self.out}/state/{base_name}").to_pylist():
393
+ r.setdefault("status", "scored")
394
+ self.hashes[(r["source"], r["id"])] = r
395
+ self.loaded_deltas = set()
396
+ deltas = self.new_deltas(base_stamp)
397
+ for pth in deltas:
398
+ self.merge_delta(pth)
399
+ self.listed_until = {src: parse_iso(self.cursor["sources"][src]["covered_until"]) for src in ("model", "dataset")}
400
+ log(f"STATE cursor model={self.listed_until['model']} dataset={self.listed_until['dataset']}; "
401
+ f"hashes {len(self.hashes)} ({base_name} + {len(deltas)} deltas) in {time.time() - t:.1f}s; "
402
+ f"previous worker runs: {w.get('runs', [])[-3:]}")
403
+ if len(deltas) > self.a.compact_over and not self.a.dest and not self.a.drain_snapshot:
404
+ self.compact_hashes()
405
+ self.restore_queue()
406
+ if self.a.inherit:
407
+ self.load_model_scores()
408
+
409
+ def new_deltas(self, base_stamp=""):
410
+ out = []
411
+ for d in self.state_dirs():
412
+ for pth in glob.glob(f"{d}/card_hashes-delta-*.parquet"):
413
+ stamp = os.path.basename(pth)[len("card_hashes-delta-"):][:15]
414
+ if pth not in self.loaded_deltas and stamp > base_stamp:
415
+ out.append(pth)
416
+ return sorted(out, key=lambda x: os.path.basename(x))
417
+
418
+ def merge_delta(self, pth):
419
+ self.loaded_deltas.add(pth)
420
+ n = 0
421
+ for r in pq.read_table(pth).to_pylist():
422
+ key = (r["source"], r["id"])
423
+ cur = self.hashes.get(key)
424
+ if cur is None or (r.get("updated_at") or "") >= (cur.get("updated_at") or ""):
425
+ self.hashes[key] = r
426
+ n += 1
427
+ return n
428
+
429
+ def reload_foreign_deltas(self):
430
+ """Pick up hash rows written by other processes (e.g. a GPU drain job) and drop queued items they scored."""
431
+ new = self.new_deltas(self.cursor["worker"].get("card_hashes_base_stamp", ""))
432
+ dropped = 0
433
+ for pth in new:
434
+ with self.lock:
435
+ self.merge_delta(pth)
436
+ for key in list(self.pending):
437
+ st = self.hashes.get(key)
438
+ if st and st.get("status") in ("scored", "inherited") and \
439
+ st.get("body_hash") == self.pending[key]["row"]["body_hash"]:
440
+ self.drop_pending(key, "scored_elsewhere")
441
+ dropped += 1
442
+ if new:
443
+ log(f"RELOAD {len(new)} foreign hash deltas; dropped {dropped} queued items scored elsewhere")
444
+
445
+ def compact_hashes(self):
446
+ """Write the merged gate table as a new base file (FUSE: no rename) and point cursor.json at it.
447
+ Old deltas stay (readers ignore deltas older than card_hashes_base_stamp) and can be deleted later."""
448
+ with self.lock:
449
+ stamp = now().strftime("%Y%m%dT%H%M%S")
450
+ rows = list(self.hashes.values())
451
+ merged = [p for p in self.loaded_deltas if os.path.basename(p)[len("card_hashes-delta-"):][:15] <= stamp]
452
+ name = f"card_hashes-base-{stamp}-{self.sfx}.parquet"
453
+ put_parquet(pa.Table.from_pylist(rows, schema=HASH_SCHEMA), f"{self.out}/state/{name}")
454
+ with self.lock:
455
+ w = self.cursor["worker"]
456
+ old_base = w.get("card_hashes_base")
457
+ w["card_hashes_base"], w["card_hashes_base_stamp"] = name, stamp
458
+ put_json(self.cursor, f"{self.dest}state/cursor.json")
459
+ # the deltas now inside the base, and the previous compacted base, are no longer read by anyone
460
+ n = 0
461
+ for pth in merged + ([f"{self.out}/state/{old_base}"] if old_base and old_base.startswith("card_hashes-base-") else []):
462
+ try:
463
+ os.remove(pth)
464
+ n += 1
465
+ except OSError:
466
+ pass
467
+ with self.lock:
468
+ self.loaded_deltas -= set(merged)
469
+ log(f"COMPACT gate table: {len(rows)} rows -> state/{name}; removed {n} merged files")
470
+
471
+ def compact_items(self, min_age_s=600):
472
+ """Merge items/date=*/worker-<YYYYMMDDTHHMM>-*.parquet parts of each finished UTC hour into one file
473
+ worker-h-<YYYYMMDDTHH>-c<stamp>.parquet (plus any earlier compacted file for that hour), then delete the
474
+ parts. FUSE has no rename: the new file is written first, so a reader may see a row twice for up to one
475
+ refresh (readers keep the newest row per (source, id)); a reader listing between write and delete may
476
+ also hit a vanished file once."""
477
+ cur_hour = now().strftime("%Y%m%dT%H")
478
+ groups = collections.defaultdict(list)
479
+ for pth in glob.glob(f"{self.dest}items/date=*/worker-*.parquet"):
480
+ name = os.path.basename(pth)
481
+ hour = name[9:20] if name.startswith("worker-h-") else name[7:18]
482
+ if hour >= cur_hour:
483
+ continue
484
+ try:
485
+ if time.time() - os.path.getmtime(pth) < min_age_s:
486
+ continue
487
+ except OSError:
488
+ continue
489
+ groups[(os.path.dirname(pth), hour)].append(pth)
490
+ n_files = n_rows = n_out = 0
491
+ for (d, hour), paths in sorted(groups.items()):
492
+ if len(paths) < 2 and os.path.basename(paths[0]).startswith("worker-h-"):
493
+ continue
494
+ try:
495
+ tab = pa.concat_tables([pq.read_table(p).cast(ITEM_SCHEMA) for p in sorted(paths)])
496
+ tab = tab.take(pa.compute.sort_indices(tab, sort_keys=[("scored_at", "ascending")]))
497
+ put_parquet(tab, f"{d}/worker-h-{hour}-c{now().strftime('%Y%m%dT%H%M%S')}.parquet")
498
+ for p in paths:
499
+ os.remove(p)
500
+ n_files += len(paths)
501
+ n_rows += tab.num_rows
502
+ n_out += 1
503
+ except Exception as e:
504
+ self.errors.append({"ts": iso(now()), "where": "compact_items", "err": f"{d} {hour}: {e!r}"[:300]})
505
+ if n_files:
506
+ log(f"COMPACT items: {n_files} files -> {n_out} hourly files ({n_rows} rows)")
507
+ self.last_items_compaction = {"at": iso(now()), "files_merged": n_files, "hourly_files": n_out, "rows": n_rows}
508
+
509
+ def queue_snapshots(self):
510
+ return sorted(glob.glob(f"{self.dest}state/queue-*.parquet"), key=os.path.basename)
511
+
512
+ def restore_queue(self):
513
+ snaps = self.queue_snapshots()
514
+ if not snaps:
515
+ return
516
+ n = skip = 0
517
+ for r in pq.read_table(snaps[-1]).to_pylist():
518
+ row = json.loads(r["row_json"])
519
+ key = (r["source"], r["id"])
520
+ st = self.hashes.get(key)
521
+ if st and st.get("body_hash") == row["body_hash"] and st.get("status") in ("scored", "inherited"):
522
+ skip += 1
523
+ continue
524
+ fd = r["first_detected"]
525
+ self.enqueue({"row": row, "detected": r["detected"], "first_detected": fd,
526
+ "first_detected_ts": parse_iso(fd).timestamp(), "lane": r["lane"]}, r["lane"], emit=False)
527
+ n += 1
528
+ log(f"RESTORE queue from {os.path.basename(snaps[-1])}: {n} items ({skip} already scored)")
529
+
530
+ def load_model_scores(self):
531
+ t = time.time()
532
+ files = sorted(glob.glob(f"{self.out}/items/*/*.parquet"))
533
+ for f in files:
534
+ try:
535
+ tab = pq.read_table(f, columns=["id", "source", "scores", "scored_at"]).to_pylist()
536
+ except Exception:
537
+ continue
538
+ for r in tab:
539
+ if r["source"] == "model":
540
+ self.model_scores[r["id"]] = np.array(r["scores"], dtype=np.float32)
541
+ log(f"INHERIT: {len(self.model_scores)} model score vectors from {len(files)} files ({time.time() - t:.0f}s)")
542
+
543
+ # ---------------- events / counters
544
+ def event(self, src, rid, ev, lm=None, detected=None, scored=None, decide_s=None, cap=None, chars=None,
545
+ wait=None, detail=None, top=None):
546
+ t = now()
547
+ stage = LIVE_STAGE.get(ev, ev)
548
+ if stage is not None:
549
+ e = {"t": iso(t), "id": rid, "source": src, "stage": stage, "queue_len": len(self.pending)}
550
+ if ev in ("scored", "inherited"):
551
+ e["decide_ms"] = int((decide_s or 0) * 1000)
552
+ e["top_topics"] = top
553
+ if detail and ev != "scored":
554
+ e["detail"] = detail
555
+ if self.a.live_secs:
556
+ self.live.append(e)
557
+ self.events.append({"ts": iso(t), "id": rid, "source": src, "event": ev, "last_modified": lm,
558
+ "time_detected": detected, "time_scored": scored, "decide_s": decide_s,
559
+ "text_cap": cap, "text_chars": chars, "queue_wait_s": wait, "detail": detail})
560
+ self.counts[src][ev] += 1
561
+ lat_mod = lat_det = None
562
+ if ev in ("scored", "inherited"):
563
+ if lm and src != "paper":
564
+ lat_mod = (parse_iso(scored) - parse_iso(lm)).total_seconds()
565
+ self.lat_mod[src].append(lat_mod)
566
+ lat_det = (parse_iso(scored) - parse_iso(detected)).total_seconds()
567
+ self.lat_det[src].append(lat_det)
568
+ if ev == "scored":
569
+ self.decide[src].append(decide_s)
570
+ self.recent.append((time.time(), src, ev, lat_mod, lat_det, decide_s if ev == "scored" else None))
571
+
572
+ def enqueue(self, item, lane, emit=True):
573
+ """New key: append to the lane, emit 'enqueued'. Known key: replace the item, keep first_detected, emit
574
+ 'superseded_in_queue'; a fresh re-detection of a backlog item promotes it to the fresh lane."""
575
+ key = (item["row"]["source"], item["row"]["id"])
576
+ item.setdefault("first_detected", item["detected"])
577
+ item.setdefault("first_detected_ts", time.time())
578
+ item["lane"] = lane
579
+ with self.cv:
580
+ old = self.pending.get(key)
581
+ if old is not None:
582
+ item["first_detected"], item["first_detected_ts"] = old["first_detected"], old["first_detected_ts"]
583
+ if lane == "fresh" and old["lane"] == "backlog":
584
+ self.lanes["fresh"].append(key)
585
+ else:
586
+ item["lane"] = old["lane"]
587
+ self.pending[key] = item
588
+ if emit:
589
+ self.event(key[0], key[1], "superseded_in_queue", lm=item["row"]["last_modified"])
590
+ return False
591
+ self.pending[key] = item
592
+ self.lanes[lane].append(key)
593
+ self.qcount[key[0]] += 1
594
+ n_paper = self.qcount["paper"]
595
+ n = len(self.pending)
596
+ self.queue_max["total"] = max(self.queue_max["total"], n)
597
+ self.queue_max["hub"] = max(self.queue_max["hub"], n - n_paper)
598
+ self.queue_max["paper"] = max(self.queue_max["paper"], n_paper)
599
+ if emit:
600
+ self.event(key[0], key[1], "enqueued", lm=item["row"]["last_modified"], detected=item["detected"],
601
+ detail=lane)
602
+ self.cv.notify()
603
+ return True
604
+
605
+ def drop_pending(self, key, why):
606
+ item = self.pending.pop(key, None)
607
+ if item is not None:
608
+ self.qcount[key[0]] -= 1
609
+ self.event(key[0], key[1], "dropped_in_queue", lm=item["row"]["last_modified"], detail=why)
610
+
611
+ def _take(self, lane):
612
+ dq = self.lanes[lane]
613
+ while dq:
614
+ key = dq.pop() if lane == "fresh" else dq.popleft()
615
+ item = self.pending.pop(key, None)
616
+ if item is not None:
617
+ self.qcount[key[0]] -= 1
618
+ return item
619
+ return None
620
+
621
+ def pop(self, n=1, timeout=5):
622
+ with self.cv:
623
+ end = time.time() + timeout
624
+ while not self.stop.is_set():
625
+ # age out fresh items (oldest at the left) into the backlog
626
+ cutoff = time.time() - self.a.fresh_max_age
627
+ fresh = self.lanes["fresh"]
628
+ while fresh and (fresh[0] not in self.pending or self.pending[fresh[0]]["first_detected_ts"] < cutoff):
629
+ key = fresh.popleft()
630
+ if key in self.pending:
631
+ self.pending[key]["lane"] = "backlog"
632
+ self.lanes["backlog"].append(key)
633
+ got = []
634
+ while len(got) < n:
635
+ backlog_turn = self.pop_n % (self.a.fresh_ratio + 1) == self.a.fresh_ratio
636
+ order = ("backlog", "fresh") if backlog_turn else ("fresh", "backlog")
637
+ item = self._take(order[0]) or self._take(order[1])
638
+ if item is None:
639
+ break
640
+ self.pop_n += 1
641
+ got.append(item)
642
+ if got:
643
+ self.inflight = got
644
+ return got
645
+ left = end - time.time()
646
+ if left <= 0:
647
+ return []
648
+ self.cv.wait(left)
649
+ return []
650
+
651
+ # ---------------- Hub polling + gating
652
+ EXPAND = {
653
+ "model": ["author", "createdAt", "lastModified", "sha", "tags", "likes", "downloads", "pipeline_tag",
654
+ "library_name", "gated", "private", "disabled", "baseModels"],
655
+ "dataset": ["author", "createdAt", "lastModified", "sha", "tags", "likes", "downloads", "gated", "private",
656
+ "disabled"],
657
+ }
658
+
659
+ def list_since(self, kind, stop_at):
660
+ """Newest-first listing down to stop_at. No silent page cap: after --max-list-pages the caller gets
661
+ truncated=True and must only advance its cursor to the oldest listed item."""
662
+ url = f"{HUB}/api/{kind}s"
663
+ big = stop_at < now() - dt.timedelta(minutes=30)
664
+ params = [("sort", "lastModified"), ("direction", "-1"), ("limit", "1000" if big else "100")] + \
665
+ [("expand[]", f) for f in self.EXPAND[kind]]
666
+ out, pages, truncated = [], 0, False
667
+ while url:
668
+ r = self.http.get(url, params=params, timeout=90)
669
+ if r is None or r.status_code != 200:
670
+ raise RuntimeError(f"listing {kind} failed: {None if r is None else r.status_code}")
671
+ pages += 1
672
+ done = False
673
+ for x in r.json():
674
+ lm = parse_iso(x.get("lastModified"))
675
+ if lm is None:
676
+ continue
677
+ if lm <= stop_at:
678
+ done = True
679
+ break
680
+ out.append(x)
681
+ if done:
682
+ break
683
+ if pages >= self.a.max_list_pages:
684
+ truncated = True
685
+ break
686
+ url, params = r.links.get("next", {}).get("url"), None
687
+ return out, truncated
688
+
689
+ def _inflight_row(self, key):
690
+ for it in self.inflight:
691
+ if (it["row"]["source"], it["row"]["id"]) == key:
692
+ return it["row"]
693
+ return None
694
+
695
+ def gate(self, kind, x, detected):
696
+ """Returns ('enqueue', item) / ('inherited', None) / (skip reason, None). Never raises."""
697
+ rid = x["id"]
698
+ key = (kind, rid)
699
+ try:
700
+ if x.get("private") or x.get("disabled"):
701
+ return "private_or_disabled", None
702
+ stored = self.hashes.get(key)
703
+ with self.lock:
704
+ pend = self.pending.get(key)
705
+ pend_row = pend["row"] if pend else self._inflight_row(key)
706
+ head = self.http.get(readme_url(rid, kind), method="HEAD")
707
+ if head is None:
708
+ return "fetch_error", None
709
+ if head.status_code == 404:
710
+ return "no_readme", None
711
+ if head.status_code != 200:
712
+ return f"http{head.status_code}", None
713
+ etag, _ = etag_of(head)
714
+ if etag and pend_row and pend_row["readme_etag"] == etag:
715
+ return "same_etag", None
716
+ if etag and stored and stored.get("readme_etag") == etag and not pend_row:
717
+ return "same_etag", None
718
+ r = self.http.get(readme_url(rid, kind))
719
+ if r is None:
720
+ return "fetch_error", None
721
+ if r.status_code == 404:
722
+ return "no_readme", None
723
+ if r.status_code != 200:
724
+ return f"http{r.status_code}", None
725
+ md = r.content.decode("utf-8", errors="ignore")
726
+ etag, commit = etag_of(r)
727
+ body = strip_yaml(md)
728
+ bh = hashlib.sha1(body.encode("utf-8")).hexdigest()
729
+ t = iso(now())
730
+ if pend_row and pend_row["body_hash"] == bh:
731
+ with self.lock:
732
+ if key in self.pending:
733
+ self.pending[key]["row"].update(readme_etag=etag, repo_commit=commit or x.get("sha"))
734
+ return "yaml_only", None
735
+ if stored and stored.get("body_hash") == bh:
736
+ with self.lock:
737
+ if key in self.pending: # README went back to the stored body: the queued version is stale
738
+ self.drop_pending(key, "reverted_to_stored")
739
+ new = dict(stored, readme_etag=etag, repo_commit=commit or x.get("sha"), status="yaml_only",
740
+ updated_at=t)
741
+ self.hashes[key] = new
742
+ self.hash_delta.append(new)
743
+ return "yaml_only", None
744
+ if prose_len(body) < MIN_PROSE:
745
+ with self.lock:
746
+ if key in self.pending:
747
+ self.drop_pending(key, "now_thin")
748
+ new = {"id": rid, "source": kind, "readme_etag": etag, "body_hash": bh,
749
+ "repo_commit": commit or x.get("sha"),
750
+ "last_scored_at": stored.get("last_scored_at") if stored else None,
751
+ "status": "thin_card", "updated_at": t}
752
+ self.hashes[key] = new
753
+ self.hash_delta.append(new)
754
+ return "thin_card", None
755
+ row = self.hub_row(kind, x, body, etag, commit, bh)
756
+ if kind == "model" and self.a.inherit and self.try_inherit(x, row, detected):
757
+ return "inherited", None
758
+ return "enqueue", {"row": row, "detected": detected}
759
+ except Exception as e:
760
+ self.errors.append({"ts": iso(now()), "where": f"gate {kind}", "id": rid, "err": repr(e)[:300]})
761
+ return "gate_error", None
762
+
763
+ def try_inherit(self, x, row, detected):
764
+ """Quantized / converted (and, with --inherit adapter, adapter) repos copy the scores of their base model
765
+ when the base is already scored; 'model compression and quantization' is raised to >= 0.9 for quantized."""
766
+ b = x.get("baseModels") or {}
767
+ rel = b.get("relation")
768
+ allowed = {"quantized"} | ({"adapter"} if self.a.inherit == "adapter" else set())
769
+ bases = [m.get("id") for m in b.get("models", []) if m.get("id")]
770
+ if rel not in allowed or len(bases) != 1:
771
+ return False
772
+ base = bases[0]
773
+ with self.lock:
774
+ sc = self.model_scores.get(base)
775
+ if sc is None:
776
+ return False
777
+ sc = sc.copy()
778
+ if rel == "quantized":
779
+ j = self.labels.index("model compression and quantization")
780
+ sc[j] = max(sc[j], 0.9)
781
+ t = iso(now())
782
+ out = {k: row[k] for k in ITEM_SCHEMA.names if k in row}
783
+ out.update(scores=sc.tolist(), catalogue_version=self.cat["catalogue_version"], scored_at=t,
784
+ scorer="inherited", job_id=self.job_id)
785
+ key = (row["source"], row["id"])
786
+ with self.lock:
787
+ self.rows.append(out)
788
+ self.model_scores[row["id"]] = sc
789
+ new = {"id": row["id"], "source": row["source"], "readme_etag": row["readme_etag"],
790
+ "body_hash": row["body_hash"], "repo_commit": row["repo_commit"], "last_scored_at": t,
791
+ "status": "inherited", "updated_at": t, "inherited_from": base}
792
+ self.hashes[key] = new
793
+ self.hash_delta.append(new)
794
+ if key in self.pending:
795
+ self.drop_pending(key, "inherited")
796
+ self.event("model", row["id"], "inherited", lm=row["last_modified"], detected=detected, scored=t,
797
+ decide_s=0.0, detail=f"{rel}:{base}",
798
+ top=[[self.labels[j], round(float(sc[j]), 3)] for j in np.argsort(-sc)[:3]])
799
+ return True
800
+
801
+ def hub_row(self, kind, x, body, etag, commit, bh):
802
+ tags_all = list(x.get("tags") or [])
803
+ tags = [t for t in tags_all if not AUTO_TAG.match(t)][:25]
804
+ head = f"{'Model' if kind == 'model' else 'Dataset'}: {x['id']}"
805
+ full = head + (f"\nTags: {', '.join(tags)}" if tags else "") + f"\n\n{body}"
806
+ cap = self.a.model_cap if kind == "model" else CAPS[kind]
807
+ lic = tag_values(tags_all, "license")
808
+ gated = x.get("gated")
809
+ return {
810
+ "id": x["id"], "source": kind,
811
+ "url": f"{HUB}/{'' if kind == 'model' else 'datasets/'}{x['id']}",
812
+ "title": x["id"], "created_at": iso_str(x.get("createdAt")), "last_modified": iso_str(x["lastModified"]),
813
+ "readme_etag": etag, "repo_commit": commit or x.get("sha"), "body_hash": bh,
814
+ "text_cap": cap, "text": full[:cap], "text_chars_full": len(full), "snippet": clean_snippet(body),
815
+ "tags": tags, "author": x.get("author") or x["id"].split("/")[0], "likes": x.get("likes"),
816
+ "downloads": x.get("downloads"), "pipeline_tag": x.get("pipeline_tag"),
817
+ "library_name": x.get("library_name") or (tag_values(tags_all, "library") or [None])[0],
818
+ "license": lic[0] if lic else None, "gated": str(gated) if gated not in (None, False) else None,
819
+ "task_categories": tag_values(tags_all, "task_categories") or None,
820
+ "language": tag_values(tags_all, "language") or None,
821
+ "size_categories": tag_values(tags_all, "size_categories") or None,
822
+ "authors": None, "categories": None, "upvotes": None, "paper_origin": None,
823
+ }
824
+
825
+ def poll_hub_once(self, pool, sweep=False):
826
+ """sweep=True: re-list the last --sweep-hours and gate only (id, lastModified) pairs never seen. Catches
827
+ repos that appear in the listing late with an older lastModified (e.g. made public after their last
828
+ commit), which a cursor-based poll skips. A sweep never moves the cursor."""
829
+ for kind in ("model", "dataset"):
830
+ t0 = time.time()
831
+ stop_at = now() - dt.timedelta(hours=self.a.sweep_hours) if sweep else \
832
+ self.listed_until[kind] - dt.timedelta(seconds=self.a.overlap_secs)
833
+ try:
834
+ listed, truncated = self.list_since(kind, stop_at)
835
+ except Exception as e:
836
+ self.errors.append({"ts": iso(now()), "where": f"list {kind}", "err": repr(e)[:300]})
837
+ log("LIST ERROR", kind, e)
838
+ continue
839
+ detected = iso(now())
840
+ if sweep:
841
+ new = [x for x in listed if self.seen_long.get((kind, x["id"])) != x["lastModified"]
842
+ and self.recent_seen.get((kind, x["id"])) != x["lastModified"]]
843
+ listed = [] # the cursor does not move on a sweep
844
+ else:
845
+ new = [x for x in listed if self.recent_seen.get((kind, x["id"])) != x["lastModified"]]
846
+ new.reverse() # listing is newest-first; enqueue oldest-first
847
+ res = list(pool.map(lambda x: self.gate(kind, x, detected), new))
848
+ n_enq = n_inh = 0
849
+ fresh_cut = now() - dt.timedelta(seconds=self.a.fresh_max_age)
850
+ with self.lock:
851
+ for x, (reason, item) in zip(new, res):
852
+ lm = iso_str(x["lastModified"])
853
+ self.event(kind, x["id"], "detected", lm=lm, detected=detected, detail="late" if sweep else None)
854
+ if reason == "enqueue":
855
+ lane = "fresh" if parse_iso(lm) >= fresh_cut else "backlog"
856
+ n_enq += self.enqueue(item, lane)
857
+ elif reason == "inherited":
858
+ n_inh += 1
859
+ else:
860
+ self.event(kind, x["id"], f"skip_{reason}", lm=lm, detected=detected)
861
+ if reason not in ("fetch_error", "gate_error") and not reason.startswith("http5"):
862
+ self.recent_seen[(kind, x["id"])] = x["lastModified"]
863
+ self.seen_long[(kind, x["id"])] = x["lastModified"]
864
+ if listed:
865
+ lms = [parse_iso(x["lastModified"]) for x in listed]
866
+ hw = max(lms)
867
+ failed = [parse_iso(x["lastModified"]) for x, (r, _) in zip(new, res)
868
+ if r in ("fetch_error", "gate_error")]
869
+ if failed:
870
+ hw = min(hw, min(failed) - dt.timedelta(seconds=1))
871
+ if truncated:
872
+ # the listing only reaches back to min(lms): record the unseen span as an explicit gap
873
+ # (never skip silently); a separate catch-up job can fill it
874
+ gap = {"source": kind, "from": iso(self.listed_until[kind]), "to": iso(min(lms)),
875
+ "found_at": iso(now())}
876
+ self.cursor["worker"].setdefault("gaps", []).append(gap)
877
+ self.errors.append({"ts": iso(now()), "where": f"list {kind}", "err": f"GAP {gap}"})
878
+ log("LISTING GAP", gap)
879
+ self.listed_until[kind] = max(self.listed_until[kind], hw)
880
+ if not sweep:
881
+ self.first_done[kind] = True
882
+ cut = (self.listed_until[kind] - dt.timedelta(seconds=self.a.overlap_secs * 3))
883
+ for k in [k for k, v in self.recent_seen.items() if k[0] == kind and parse_iso(v) < cut]:
884
+ del self.recent_seen[k]
885
+ if sweep:
886
+ cut = now() - dt.timedelta(hours=self.a.sweep_hours + 1)
887
+ for k in [k for k, v in self.seen_long.items() if k[0] == kind and parse_iso(v) < cut]:
888
+ del self.seen_long[k]
889
+ log(f"{'SWEEP' if sweep else 'POLL'} {kind}: listed {len(listed)}{' TRUNCATED' if truncated else ''} new {len(new)} enqueued "
890
+ f"{n_enq} inherited {n_inh} ({time.time() - t0:.1f}s) queue {len(self.pending)} "
891
+ f"until {self.listed_until[kind]}")
892
+
893
+ def hub_loop(self):
894
+ last_sweep = time.time() # first sweep after one interval (seen_long fills from normal polls)
895
+ with ThreadPoolExecutor(self.a.gate_workers) as pool:
896
+ while not self.stop.is_set():
897
+ t = time.time()
898
+ try:
899
+ self.poll_hub_once(pool)
900
+ if self.a.sweep_secs and time.time() - last_sweep >= self.a.sweep_secs:
901
+ self.poll_hub_once(pool, sweep=True)
902
+ last_sweep = time.time()
903
+ except Exception as e:
904
+ self.errors.append({"ts": iso(now()), "where": "hub_loop", "err": repr(e)[:300]})
905
+ log("HUB LOOP ERROR", traceback.format_exc()[-800:])
906
+ self.stop.wait(max(1, self.a.poll_secs - (time.time() - t)))
907
+
908
+ # ---------------- papers
909
+ def paper_seen(self, pid):
910
+ with self.lock:
911
+ return ("paper", pid) in self.hashes or ("paper", pid) in self.pending or \
912
+ self._inflight_row(("paper", pid)) is not None
913
+
914
+ def paper_row(self, p):
915
+ full = p["title"] + (f"\nCategories: {' '.join(p['categories'])}" if p["categories"] else "") + \
916
+ f"\n\n{p['abstract']}"
917
+ return {
918
+ "id": p["id"], "source": "paper", "url": f"https://arxiv.org/abs/{p['id']}", "title": p["title"],
919
+ "created_at": p["created_at"], "last_modified": p["last_modified"], "readme_etag": None,
920
+ "repo_commit": None, "body_hash": hashlib.sha1(p["abstract"].encode()).hexdigest(),
921
+ "text_cap": CAPS["paper"], "text": full[:CAPS["paper"]], "text_chars_full": len(full),
922
+ "snippet": clean_snippet(p["abstract"]), "tags": p["categories"] or [], "author": None, "likes": None,
923
+ "downloads": None, "pipeline_tag": None, "library_name": None, "license": None, "gated": None,
924
+ "task_categories": None, "language": None, "size_categories": None, "authors": p["authors"],
925
+ "categories": p["categories"], "upvotes": p["upvotes"], "paper_origin": p["paper_origin"],
926
+ }
927
+
928
+ NS = {"a": "http://www.w3.org/2005/Atom", "o": "http://a9.com/-/spec/opensearch/1.1/"}
929
+
930
+ def parse_arxiv(self, content):
931
+ root = ET.fromstring(content)
932
+ total = root.find("o:totalResults", self.NS)
933
+ out = []
934
+ for e in root.findall("a:entry", self.NS):
935
+ aid = e.find("a:id", self.NS).text.rsplit("/abs/", 1)[-1]
936
+ aid = re.sub(r"v\d+$", "", aid)
937
+ names = [a.find("a:name", self.NS).text for a in e.findall("a:author", self.NS)]
938
+ out.append({"id": aid, "title": norm(e.find("a:title", self.NS).text),
939
+ "abstract": norm(e.find("a:summary", self.NS).text),
940
+ "categories": [c.get("term") for c in e.findall("a:category", self.NS)],
941
+ "authors": short_authors(", ".join(n or "" for n in names)),
942
+ "created_at": iso_str(e.find("a:published", self.NS).text)})
943
+ return (int(total.text) if total is not None else None), out
944
+
945
+ def poll_arxiv_once(self, since):
946
+ t0 = time.time()
947
+ q = f"cat:cs.* AND submittedDate:[{since.strftime('%Y%m%d%H%M')} TO {(now() + dt.timedelta(days=1)).strftime('%Y%m%d%H%M')}]"
948
+ start, page, n_new, n_seen, total, empty_retry = 0, 500, 0, 0, None, False
949
+ detected = iso(now())
950
+ ok = True
951
+ while True:
952
+ content = self.http.arxiv({"search_query": q, "sortBy": "submittedDate", "sortOrder": "descending",
953
+ "start": start, "max_results": page})
954
+ if content is None:
955
+ self.errors.append({"ts": iso(now()), "where": "arxiv", "err": f"page start={start} failed"})
956
+ ok = False
957
+ break
958
+ tot, entries = self.parse_arxiv(content)
959
+ total = tot if total is None else total
960
+ if not entries:
961
+ if total and start < total and not empty_retry:
962
+ empty_retry = True # arXiv sometimes returns an empty page; retry once
963
+ continue
964
+ break
965
+ empty_retry = False
966
+ for p in entries:
967
+ if not any(c.startswith("cs.") for c in p["categories"]):
968
+ continue
969
+ if self.paper_seen(p["id"]):
970
+ n_seen += 1
971
+ continue
972
+ p.update(last_modified=p["created_at"], upvotes=None, paper_origin="arxiv")
973
+ with self.lock:
974
+ self.event("paper", p["id"], "detected", lm=p["last_modified"], detected=detected)
975
+ self.enqueue({"row": self.paper_row(p), "detected": detected}, "backlog")
976
+ n_new += 1
977
+ start += len(entries)
978
+ if (total is not None and start >= total) or self.stop.is_set():
979
+ break
980
+ log(f"ARXIV since {since.date()}: total {total} new {n_new} already {n_seen} ({time.time() - t0:.0f}s)")
981
+ return ok
982
+
983
+ def poll_daily_once(self):
984
+ detected = iso(now())
985
+ daily_only = []
986
+ for day in {now().date(), (now() - dt.timedelta(days=1)).date()}:
987
+ r = self.http.get(f"{HUB}/api/daily_papers", params={"date": str(day), "limit": 100}, auth=False)
988
+ if r is None or r.status_code != 200:
989
+ self.errors.append({"ts": iso(now()), "where": "daily", "err": f"{day} {getattr(r, 'status_code', None)}"})
990
+ continue
991
+ for dp in r.json():
992
+ pp = dp["paper"]
993
+ pid = pp["id"]
994
+ key = ("paper", pid)
995
+ with self.lock:
996
+ pend = self.pending.get(key)
997
+ if pend is not None:
998
+ if pend["row"]["paper_origin"] == "arxiv":
999
+ pend["row"]["paper_origin"] = "arxiv+daily"
1000
+ pend["row"]["upvotes"] = pp.get("upvotes")
1001
+ if pend["lane"] == "backlog": # a Daily Paper is "hot": promote it
1002
+ pend["lane"] = "fresh"
1003
+ pend["first_detected_ts"] = time.time()
1004
+ self.lanes["fresh"].append(key)
1005
+ continue
1006
+ if self.paper_seen(pid) or any(d["id"] == pid for d in daily_only):
1007
+ continue
1008
+ names = [a.get("name", "") for a in pp.get("authors", []) if isinstance(a, dict)]
1009
+ daily_only.append({"id": pid, "title": norm(dp.get("title") or pp.get("title")),
1010
+ "abstract": norm(dp.get("summary") or pp.get("summary")), "categories": None,
1011
+ "authors": short_authors(", ".join(names)), "created_at": iso_str(pp.get("publishedAt")),
1012
+ "last_modified": iso_str(pp.get("submittedOnDailyAt") or dp.get("publishedAt")),
1013
+ "upvotes": pp.get("upvotes"), "paper_origin": "daily"})
1014
+ if daily_only:
1015
+ ids = [p["id"] for p in daily_only]
1016
+ content = self.http.arxiv({"id_list": ",".join(ids), "max_results": len(ids)})
1017
+ cats = {}
1018
+ if content:
1019
+ for p in self.parse_arxiv(content)[1]:
1020
+ cats[p["id"]] = p["categories"]
1021
+ for p in daily_only:
1022
+ p["categories"] = cats.get(p["id"]) or None
1023
+ with self.lock:
1024
+ self.event("paper", p["id"], "detected", lm=p["last_modified"], detected=detected)
1025
+ self.enqueue({"row": self.paper_row(p), "detected": detected}, "fresh")
1026
+ log(f"DAILY: {len(daily_only)} new daily-only papers")
1027
+
1028
+ def paper_loop(self):
1029
+ since0 = dt.datetime.fromisoformat(self.a.arxiv_since).replace(tzinfo=UTC)
1030
+ pc = self.cursor["sources"]["paper"]
1031
+ last_arxiv = last_daily = 0.0
1032
+ while not self.stop.is_set():
1033
+ try:
1034
+ if self.a.arxiv_poll and time.time() - last_arxiv >= self.a.arxiv_secs:
1035
+ # first poll of a process: from --arxiv-since (already-scored ids are skipped); later: 4 days
1036
+ since = since0 if not self.first_done["arxiv"] else max(since0, now() - dt.timedelta(days=4))
1037
+ if self.poll_arxiv_once(since):
1038
+ with self.lock:
1039
+ pc["worker_arxiv_since"] = iso(since0)
1040
+ pc["worker_arxiv_polled_at"] = iso(now())
1041
+ self.first_done["arxiv"] = True
1042
+ last_arxiv = time.time()
1043
+ if time.time() - last_daily >= self.a.daily_secs:
1044
+ self.poll_daily_once()
1045
+ with self.lock:
1046
+ pc["worker_daily_polled_at"] = iso(now())
1047
+ self.first_done["daily"] = True
1048
+ last_daily = time.time()
1049
+ except Exception as e:
1050
+ self.errors.append({"ts": iso(now()), "where": "paper_loop", "err": repr(e)[:300]})
1051
+ log("PAPER LOOP ERROR", traceback.format_exc()[-800:])
1052
+ self.stop.wait(30)
1053
+
1054
+ # ---------------- scoring
1055
+ def load_model(self):
1056
+ import torch
1057
+ torch.set_num_threads(self.a.threads)
1058
+ from gliner2 import AutoExtractor
1059
+ t = time.time()
1060
+ self.torch = torch
1061
+ self.device = "cuda" if self.a.device == "auto" and torch.cuda.is_available() else \
1062
+ ("cpu" if self.a.device == "auto" else self.a.device)
1063
+ self.model = AutoExtractor.from_pretrained(BASE)
1064
+ if self.device == "cuda":
1065
+ self.model = self.model.to("cuda")
1066
+ self.model.eval()
1067
+ self.batch = self.a.batch or (8 if self.device == "cuda" else 1)
1068
+ self.task = {"topics": {"labels": self.labels, "multi_label": True, "cls_threshold": 0.0, "prompt": PROMPT}}
1069
+ self.col = {k: j for j, k in enumerate(self.labels)}
1070
+ self.model_load_s = round(time.time() - t, 1)
1071
+ log(f"MODEL loaded in {self.model_load_s}s on {self.device}; torch {torch.__version__} "
1072
+ f"threads {torch.get_num_threads()} batch {self.batch}")
1073
+
1074
+ def score_texts(self, texts):
1075
+ """-> (float32 [n, 48], seconds). GPU: bf16 autocast (as the backfill). CPU: fp32."""
1076
+ t = time.perf_counter()
1077
+ torch = self.torch
1078
+ with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.device == "cuda"):
1079
+ preds = self.model.batch_classify_text(texts, self.task, batch_size=len(texts), include_confidence=True,
1080
+ max_len=None)
1081
+ out = np.zeros((len(texts), len(self.labels)), dtype=np.float32)
1082
+ for i, p in enumerate(preds):
1083
+ for d in (p["topics"] or []):
1084
+ out[i, self.col[d["label"]]] = float(d["confidence"])
1085
+ return out, time.perf_counter() - t
1086
+
1087
+ def score_text(self, text):
1088
+ s, el = self.score_texts([text])
1089
+ return s[0], el
1090
+
1091
+ def score_items(self, items):
1092
+ """Score a batch; on an error (e.g. CUDA OOM) retry in chunks of 2, then 1 (as the backfill did).
1093
+ Returns (scores or None per item, seconds)."""
1094
+ t = time.perf_counter()
1095
+ texts = [it["row"]["text"] for it in items]
1096
+ for bs in dict.fromkeys((len(texts), 2, 1)):
1097
+ try:
1098
+ out = []
1099
+ for k in range(0, len(texts), bs):
1100
+ out.extend(self.score_texts(texts[k:k + bs])[0])
1101
+ return out, time.perf_counter() - t
1102
+ except Exception as e: # includes torch.cuda.OutOfMemoryError
1103
+ log(f"DECIDE retry below bs {bs}: {repr(e)[:120]}")
1104
+ if self.device == "cuda":
1105
+ self.torch.cuda.empty_cache()
1106
+ last = e
1107
+ if len(items) == 1:
1108
+ raise last
1109
+ # bs 1 failed for at least one item: score one by one, None for the failures
1110
+ out = []
1111
+ for tx in texts:
1112
+ try:
1113
+ out.append(self.score_texts([tx])[0][0])
1114
+ except Exception:
1115
+ out.append(None)
1116
+ if self.device == "cuda":
1117
+ self.torch.cuda.empty_cache()
1118
+ return out, time.perf_counter() - t
1119
+
1120
+ def selfcheck(self, n):
1121
+ """Re-score n backfill rows per source and compare with the stored GPU bf16 bs8 scores."""
1122
+ res = {}
1123
+ for src in ("model", "dataset", "paper"):
1124
+ files = sorted(glob.glob(f"{self.out}/work/scored/{src}/*.parquet"))
1125
+ if not files:
1126
+ continue
1127
+ tab = pq.read_table(files[0], columns=["id", "text", "scores"]).slice(0, n).to_pylist()
1128
+ diffs, top_agree, secs = [], 0, []
1129
+ for r in tab:
1130
+ s, el = self.score_text(r["text"])
1131
+ ref = np.array(r["scores"], dtype=np.float32)
1132
+ diffs.append(float(np.abs(s - ref).max()))
1133
+ top_agree += int(np.argmax(s) == np.argmax(ref))
1134
+ secs.append(el)
1135
+ res[src] = {"n": len(tab), "max_abs_diff_p50": pct(diffs, 50), "max_abs_diff_max": round(max(diffs), 4),
1136
+ "top1_agree": top_agree, "decide_s_p50": pct(secs, 50)}
1137
+ log("SELFCHECK", src, json.dumps(res[src]))
1138
+ put_json(res, f"{self.dest}state/worker_selfcheck.json")
1139
+
1140
+ def canary(self):
1141
+ _, el = self.score_text(CANARY)
1142
+ with self.lock:
1143
+ self.canaries.append((iso(now()), round(el, 2)))
1144
+ log(f"CANARY {el:.2f}s")
1145
+
1146
+ def initial_done(self):
1147
+ return all(self.first_done.values())
1148
+
1149
+ def score_loop(self):
1150
+ last_canary = 0.0
1151
+ while not self.stop.is_set():
1152
+ if time.time() - last_canary >= self.a.canary_secs:
1153
+ self.canary()
1154
+ last_canary = time.time()
1155
+ items = self.pop(self.batch)
1156
+ if not items:
1157
+ if self.a.exit_when_empty and self.initial_done() and not self.pending:
1158
+ log("QUEUE EMPTY after the initial polls: stopping (--exit-when-empty)")
1159
+ self.stop.set()
1160
+ continue
1161
+ items.sort(key=lambda it: len(it["row"]["text"]))
1162
+ try:
1163
+ S, el = self.score_items(items)
1164
+ except Exception as e:
1165
+ S, el = [None], 0.0
1166
+ err = repr(e)[:300]
1167
+ else:
1168
+ err = "failed at batch size 1"
1169
+ failed = [it for it, s in zip(items, S) if s is None]
1170
+ if failed:
1171
+ with self.lock:
1172
+ for it in failed:
1173
+ it["attempts"] = it.get("attempts", 0) + 1
1174
+ rid, src = it["row"]["id"], it["row"]["source"]
1175
+ self.errors.append({"ts": iso(now()), "where": "decide", "id": rid, "err": err})
1176
+ self.event(src, rid, "decide_error", lm=it["row"]["last_modified"], detail=err[:200])
1177
+ if it["attempts"] < 3: # requeue at the back of the backlog
1178
+ self.enqueue(it, "backlog", emit=False)
1179
+ else: # give up, but record it (cursor.json worker.failed) so nothing is lost silently
1180
+ fl = self.cursor["worker"].setdefault("failed", [])
1181
+ fl.append({"source": src, "id": rid, "last_modified": it["row"]["last_modified"],
1182
+ "err": err[:200], "at": iso(now())})
1183
+ del fl[:-200]
1184
+ items = [it for it, s in zip(items, S) if s is not None]
1185
+ S = [s for s in S if s is not None]
1186
+ if not items:
1187
+ with self.lock:
1188
+ self.inflight = []
1189
+ continue
1190
+ per = el / len(items)
1191
+ t = iso(now())
1192
+ with self.lock:
1193
+ self.inflight = []
1194
+ for it, s in zip(items, S):
1195
+ row = it["row"]
1196
+ src = row["source"]
1197
+ out = {k: row[k] for k in ITEM_SCHEMA.names if k in row}
1198
+ out.update(scores=s.tolist(), catalogue_version=self.cat["catalogue_version"], scored_at=t,
1199
+ scorer=self.a.scorer_name, job_id=self.job_id)
1200
+ self.rows.append(out)
1201
+ if src == "model" and self.a.inherit:
1202
+ self.model_scores[row["id"]] = s
1203
+ prev = self.hashes.get((src, row["id"]))
1204
+ new = {"id": row["id"], "source": src, "readme_etag": row["readme_etag"],
1205
+ "body_hash": row["body_hash"], "repo_commit": row["repo_commit"], "last_scored_at": t,
1206
+ "status": "scored", "updated_at": t}
1207
+ self.hashes[(src, row["id"])] = new
1208
+ self.hash_delta.append(new)
1209
+ self.event(src, row["id"], "scored", lm=row["last_modified"], detected=it["first_detected"],
1210
+ scored=t, decide_s=round(per, 3), cap=row["text_cap"],
1211
+ chars=min(len(row["text"]), row["text_cap"]),
1212
+ wait=round(time.time() - it["first_detected_ts"] - el, 2),
1213
+ detail=f"{it['lane']}:{'rescore' if prev and prev.get('status') == 'scored' else 'new'}",
1214
+ top=[[self.labels[j], round(float(s[j]), 3)] for j in np.argsort(-s)[:3]])
1215
+ n_scored = sum(c["scored"] for c in self.counts.values())
1216
+ if n_scored % 25 < len(items):
1217
+ log(f"SCORED {n_scored}: last {items[-1]['row']['source']} {items[-1]['row']['id']} {el:.1f}s "
1218
+ f"(batch {len(items)}) queue {len(self.pending)}")
1219
+
1220
+ # ---------------- flush / status
1221
+ def flush(self, final=False):
1222
+ with self.lock:
1223
+ rows, deltas, events = self.rows, self.hash_delta, self.events
1224
+ self.rows, self.hash_delta, self.events = [], [], []
1225
+ snap = [{"source": it["row"]["source"], "id": it["row"]["id"], "lane": it["lane"],
1226
+ "first_detected": it["first_detected"], "detected": it["detected"],
1227
+ "row_json": json.dumps(it["row"], ensure_ascii=False)}
1228
+ for it in list(self.pending.values()) + list(self.inflight)]
1229
+ cov = dict(self.listed_until)
1230
+ stamp = now().strftime("%Y%m%dT%H%M%S")
1231
+ try:
1232
+ by_day = collections.defaultdict(list)
1233
+ for r in rows:
1234
+ by_day[r["last_modified"][:10]].append(r)
1235
+ for day, rs in by_day.items():
1236
+ self.file_n += 1
1237
+ put_parquet(pa.Table.from_pylist(rs, schema=ITEM_SCHEMA),
1238
+ f"{self.dest}items/date={day}/worker-{stamp[:13]}-{self.sfx}-{self.file_n}.parquet")
1239
+ if deltas:
1240
+ pth = f"{self.dest}state/card_hashes-delta-{stamp}-{self.sfx}.parquet"
1241
+ put_parquet(pa.Table.from_pylist(deltas, schema=HASH_SCHEMA), pth)
1242
+ self.loaded_deltas.add(pth)
1243
+ if events:
1244
+ put_parquet(pa.Table.from_pylist(events, schema=EVENT_SCHEMA),
1245
+ f"{self.dest}state/worker_log/date={stamp[:4]}-{stamp[4:6]}-{stamp[6:8]}/events-{stamp}-{self.sfx}.parquet")
1246
+ # queue snapshot: the queue survives a restart, so the cursor can follow the listing directly
1247
+ if not self.a.no_queue_snapshot:
1248
+ put_parquet(pa.Table.from_pylist(snap, schema=QUEUE_SCHEMA),
1249
+ f"{self.dest}state/queue-{stamp}-{self.sfx}.parquet")
1250
+ for old in self.queue_snapshots()[:-2]:
1251
+ try:
1252
+ os.remove(old)
1253
+ except OSError:
1254
+ pass
1255
+ for src in ("model", "dataset"):
1256
+ c = self.cursor["sources"][src]
1257
+ if parse_iso(c["covered_until"]) < cov[src]:
1258
+ c["covered_until"] = iso(cov[src])
1259
+ w = self.cursor.setdefault("worker", {})
1260
+ runs = w.setdefault("runs", [])
1261
+ me = {"job_id": self.job_id, "started_at": iso(dt.datetime.fromtimestamp(self.t_start, UTC)),
1262
+ "last_flush": iso(now()), "model_cap": self.a.model_cap, "dest": self.a.dest,
1263
+ "scorer": self.a.scorer_name, "version": 2}
1264
+ if runs and runs[-1].get("started_at") == me["started_at"]:
1265
+ runs[-1] = me
1266
+ else:
1267
+ runs.append(me)
1268
+ w["card_hashes_merge_rule"] = ("worker.card_hashes_base (default state/card_hashes.parquet), then "
1269
+ "state/card_hashes-delta-*.parquet with a name stamp newer than "
1270
+ "worker.card_hashes_base_stamp, in file-name order; keep the last row per "
1271
+ "(source, id)")
1272
+ w["queue_snapshot"] = "state/queue-<stamp>-<job>.parquet (latest = the queue at the last flush)"
1273
+ if not self.a.no_cursor:
1274
+ put_json(self.cursor, f"{self.dest}state/cursor.json")
1275
+ log(f"FLUSH {len(rows)} rows, {len(deltas)} hash rows, {len(events)} events, queue snapshot {len(snap)}; "
1276
+ f"cursor model {self.cursor['sources']['model']['covered_until']} dataset "
1277
+ f"{self.cursor['sources']['dataset']['covered_until']}{' (final)' if final else ''}")
1278
+ except Exception as e:
1279
+ log("FLUSH ERROR", traceback.format_exc()[-800:])
1280
+ self.errors.append({"ts": iso(now()), "where": "flush", "err": repr(e)[:300]})
1281
+ with self.lock: # put back, retry next flush
1282
+ self.rows = rows + self.rows
1283
+ self.hash_delta = deltas + self.hash_delta
1284
+ self.events = events + self.events
1285
+ if not final:
1286
+ try:
1287
+ self.reload_foreign_deltas()
1288
+ except Exception as e:
1289
+ self.errors.append({"ts": iso(now()), "where": "reload", "err": repr(e)[:300]})
1290
+
1291
+ def oldest_age(self, lane):
1292
+ ts = [self.pending[k]["first_detected_ts"] for k in list(self.lanes[lane])[:50] if k in self.pending]
1293
+ return round(time.time() - min(ts)) if ts else None
1294
+
1295
+ def status(self, final=False):
1296
+ with self.lock:
1297
+ t = time.time()
1298
+ while self.recent and self.recent[0][0] < t - 3600:
1299
+ self.recent.popleft()
1300
+ hour = collections.defaultdict(collections.Counter)
1301
+ lm1, ld1, dc1 = (collections.defaultdict(list) for _ in range(3))
1302
+ for (_, src, ev, lmod, ldet, dec) in self.recent:
1303
+ hour[src][ev] += 1
1304
+ if ev in ("scored", "inherited"):
1305
+ if lmod is not None:
1306
+ lm1[src].append(lmod)
1307
+ ld1[src].append(ldet)
1308
+ if dec is not None:
1309
+ dc1[src].append(dec)
1310
+ per = {}
1311
+ for src in ("model", "dataset", "paper"):
1312
+ c = self.counts[src]
1313
+ per[src] = {
1314
+ "total": {k: v for k, v in sorted(c.items())},
1315
+ "last_hour": {k: v for k, v in sorted(hour[src].items())},
1316
+ "latency_modified_to_scored_s": {"p50": pct(self.lat_mod[src], 50), "p90": pct(self.lat_mod[src], 90),
1317
+ "last_hour_p50": pct(lm1[src], 50), "last_hour_p90": pct(lm1[src], 90)},
1318
+ "latency_detected_to_scored_s": {"p50": pct(self.lat_det[src], 50), "p90": pct(self.lat_det[src], 90),
1319
+ "last_hour_p50": pct(ld1[src], 50), "last_hour_p90": pct(ld1[src], 90)},
1320
+ "decide_s": {"p50": pct(self.decide[src], 50), "p90": pct(self.decide[src], 90),
1321
+ "max": round(max(self.decide[src]), 2) if self.decide[src] else None,
1322
+ "sum": round(sum(self.decide[src]), 1)},
1323
+ "queued": self.qcount[src],
1324
+ }
1325
+ n = len(self.pending)
1326
+ by_lane = collections.Counter(it["lane"] for it in self.pending.values())
1327
+ for lane, dq in self.lanes.items(): # drop stale keys (scored elsewhere / promoted) now and then
1328
+ if len(dq) > 2 * by_lane[lane] + 100:
1329
+ self.lanes[lane] = collections.deque(k for k in dq if k in self.pending
1330
+ and self.pending[k]["lane"] == lane)
1331
+ st = {
1332
+ "updated_at": iso(now()), "job_id": self.job_id, "state": "stopped" if final else "running",
1333
+ "version": 2, "uptime_min": round((t - self.t_start) / 60, 1),
1334
+ "model_load_s": getattr(self, "model_load_s", None), "device": getattr(self, "device", None),
1335
+ "config": {"model_cap": self.a.model_cap, "caps": {**CAPS, "model": self.a.model_cap},
1336
+ "threads": self.a.threads, "batch": getattr(self, "batch", None),
1337
+ "poll_secs": self.a.poll_secs, "fresh_max_age_s": self.a.fresh_max_age,
1338
+ "fresh_ratio": self.a.fresh_ratio, "inherit": self.a.inherit, "dest": self.a.dest},
1339
+ "queue": {"total": n, "hub": n - self.qcount["paper"], "paper": self.qcount["paper"],
1340
+ "by_source": {s: self.qcount[s] for s in ("model", "dataset", "paper")},
1341
+ "fresh_lane": by_lane["fresh"], "backlog_lane": by_lane["backlog"],
1342
+ "oldest_age_s": {"fresh": self.oldest_age("fresh"), "backlog": self.oldest_age("backlog")},
1343
+ "max": self.queue_max, "inflight": [it["row"]["id"] for it in self.inflight]},
1344
+ "cursor": {s: iso(self.listed_until[s]) for s in self.listed_until},
1345
+ "sources": per,
1346
+ "busy_share_last_hour": round(sum(sum(v) for v in dc1.values()) / min(3600, max(1, t - self.t_start)), 3),
1347
+ "errors_total": sum(c.get("decide_error", 0) + c.get("skip_gate_error", 0) + c.get("skip_fetch_error", 0)
1348
+ for c in self.counts.values()) + len(self.errors),
1349
+ "errors_recent": list(self.errors)[-10:],
1350
+ "arxiv_api": {"ok_calls": getattr(self.http, "arxiv_calls", 0),
1351
+ "throttled_or_failed": getattr(self.http, "arxiv_throttled", 0)},
1352
+ "canary_s": list(self.canaries)[-12:],
1353
+ "cpu": self.cpu_now(t),
1354
+ "rss_mb": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024),
1355
+ }
1356
+ st["drain"] = self.drain_info(st)
1357
+ st["items_compaction"] = getattr(self, "last_items_compaction", None)
1358
+ try:
1359
+ put_json(st, f"{self.dest}state/{self.a.status_file}")
1360
+ except Exception as e:
1361
+ log("STATUS ERROR", e)
1362
+ return st
1363
+
1364
+ def cpu_now(self, t):
1365
+ d = cpu_diag()
1366
+ prev = getattr(self, "_cpu_prev", None)
1367
+ if prev:
1368
+ d["proc_cpu_util_since_last"] = round((d["proc_cpu_s"] - prev[1]) / max(1e-6, t - prev[0]), 2)
1369
+ try:
1370
+ d["throttled_usec_since_last"] = int(d["cpu_stat"]["throttled_usec"]) - int(prev[2]["throttled_usec"])
1371
+ except (KeyError, TypeError):
1372
+ pass
1373
+ self._cpu_prev = (t, d["proc_cpu_s"], d.get("cpu_stat"))
1374
+ return d
1375
+
1376
+ def flush_live(self):
1377
+ """Rewrite the current minute's JSONL file(s) with all their lines (FUSE: whole-file writes, no append)."""
1378
+ with self.lock:
1379
+ new, self.live = self.live, []
1380
+ if not new:
1381
+ return
1382
+ by_file = collections.defaultdict(list)
1383
+ for e in new:
1384
+ by_file[f"{self.dest}state/events/{e['t'][:10]}/{e['t'][11:13]}{e['t'][14:16]}.jsonl"].append(e)
1385
+ for path, es in by_file.items():
1386
+ lines = self.live_files.setdefault(path, [])
1387
+ lines.extend(json.dumps(e, ensure_ascii=False) for e in es)
1388
+ try:
1389
+ put_bytes(("\n".join(lines) + "\n").encode(), path)
1390
+ except Exception as ex:
1391
+ log("LIVE ERROR", ex)
1392
+ cut = (now() - dt.timedelta(minutes=2)).strftime("%Y-%m-%d/%H%M")
1393
+ for path in [p for p in self.live_files if p[-21:-6] < cut]:
1394
+ del self.live_files[path]
1395
+
1396
+ def prune_live(self, hours=48):
1397
+ cut = now() - dt.timedelta(hours=hours)
1398
+ n = 0
1399
+ for path in glob.glob(f"{self.dest}state/events/*/*.jsonl"):
1400
+ try:
1401
+ day, hhmm = path.split("/")[-2], path.split("/")[-1][:4]
1402
+ t = dt.datetime.strptime(f"{day} {hhmm}", "%Y-%m-%d %H%M").replace(tzinfo=UTC)
1403
+ if t < cut:
1404
+ os.remove(path)
1405
+ n += 1
1406
+ except (ValueError, OSError):
1407
+ pass
1408
+ for d in glob.glob(f"{self.dest}state/events/*"):
1409
+ try:
1410
+ os.rmdir(d) # only succeeds when empty
1411
+ except OSError:
1412
+ pass
1413
+ if n:
1414
+ log(f"LIVE pruned {n} event files older than {hours} h")
1415
+
1416
+ def live_loop(self):
1417
+ last_prune = 0.0
1418
+ while not self.stop.wait(self.a.live_secs):
1419
+ self.flush_live()
1420
+ if time.time() - last_prune > 3600:
1421
+ self.prune_live(self.a.live_retention_hours)
1422
+ last_prune = time.time()
1423
+
1424
+ DEFAULT_DECIDE = {"model": 6.0, "dataset": 2.5, "paper": 2.5}
1425
+
1426
+ def drain_info(self, st):
1427
+ """Flag only: a person launches the GPU drain job (see README "Drain job")."""
1428
+ q = st["queue"]
1429
+ est = 0.0
1430
+ for src, n in q["by_source"].items():
1431
+ est += n * (st["sources"][src]["decide_s"]["p50"] or self.DEFAULT_DECIDE[src])
1432
+ need = (q["backlog_lane"] > self.a.drain_items or est > self.a.drain_secs) and not self.a.drain_snapshot
1433
+ if need and not getattr(self, "drain_flag_since", None):
1434
+ self.drain_flag_since = iso(now())
1435
+ elif not need:
1436
+ self.drain_flag_since = None
1437
+ return {"needed": need, "since": self.drain_flag_since,
1438
+ "reason": f"backlog {q['backlog_lane']} items, about {est / 60:.0f} min of CPU work" if need else None,
1439
+ "est_work_s": round(est), "backlog_items": q["backlog_lane"],
1440
+ "thresholds": {"items": self.a.drain_items, "work_s": self.a.drain_secs}}
1441
+
1442
+ def flush_loop(self):
1443
+ last_flush = time.time()
1444
+ last_compact = time.time() - self.a.compact_every + 600 # first compaction ~10 min after start
1445
+ while not self.stop.wait(60):
1446
+ if time.time() - last_flush >= self.a.flush_secs:
1447
+ self.flush()
1448
+ last_flush = time.time()
1449
+ if self.a.compact_every and not self.a.drain_snapshot and time.time() - last_compact >= self.a.compact_every:
1450
+ try:
1451
+ self.compact_items()
1452
+ if len(self.loaded_deltas) > self.a.compact_over:
1453
+ self.reload_foreign_deltas()
1454
+ self.compact_hashes()
1455
+ except Exception as e:
1456
+ self.errors.append({"ts": iso(now()), "where": "compaction", "err": repr(e)[:300]})
1457
+ log("COMPACTION ERROR", traceback.format_exc()[-800:])
1458
+ last_compact = time.time()
1459
+ st = self.status()
1460
+ q = st["queue"]
1461
+ log(f"STATUS queue {q['total']} {q['by_source']} fresh {q['fresh_lane']} backlog {q['backlog_lane']} "
1462
+ f"oldest {q['oldest_age_s']} scored "
1463
+ f"{ {s: st['sources'][s]['total'].get('scored', 0) for s in st['sources']} } busy {st['busy_share_last_hour']} "
1464
+ f"load {st['cpu']['loadavg']} util {st['cpu'].get('proc_cpu_util_since_last')}")
1465
+ if self.deadline and time.time() > self.deadline:
1466
+ log("DEADLINE reached: stopping")
1467
+ self.stop.set()
1468
+
1469
+ def run(self):
1470
+ self.load_model()
1471
+ if self.a.selfcheck:
1472
+ self.selfcheck(self.a.selfcheck)
1473
+ threads = [threading.Thread(target=self.flush_loop, daemon=True, name="flush")]
1474
+ if self.a.live_secs:
1475
+ threads.append(threading.Thread(target=self.live_loop, daemon=True, name="live"))
1476
+ if self.a.drain_snapshot:
1477
+ # drain job: score the always-on worker's latest queue snapshot, write rows + hash deltas only
1478
+ # (no polling, no cursor, no queue snapshot, no live stream); the worker drops what we scored
1479
+ self.first_done = {k: True for k in self.first_done}
1480
+ log(f"DRAIN mode: {len(self.pending)} items from the queue snapshot")
1481
+ else:
1482
+ threads.append(threading.Thread(target=self.hub_loop, daemon=True, name="hub"))
1483
+ if not self.a.no_papers:
1484
+ threads.append(threading.Thread(target=self.paper_loop, daemon=True, name="paper"))
1485
+ for th in threads:
1486
+ th.start()
1487
+ try:
1488
+ self.score_loop()
1489
+ finally:
1490
+ self.stop.set()
1491
+ time.sleep(2)
1492
+ self.flush(final=True)
1493
+ self.flush_live()
1494
+ st = self.status(final=True)
1495
+ log("FINAL", json.dumps(st)[:3000])
1496
+
1497
+
1498
+ def main():
1499
+ ap = argparse.ArgumentParser()
1500
+ ap.add_argument("--out", default="/bucket")
1501
+ ap.add_argument("--dest", default="", help="write prefix, e.g. 'smoke-worker/' (state is read from the bucket "
1502
+ "root and from here; here wins)")
1503
+ ap.add_argument("--threads", type=int, default=4)
1504
+ ap.add_argument("--device", default="auto", choices=["auto", "cpu", "cuda"])
1505
+ ap.add_argument("--batch", type=int, default=0, help="items per Decide call (default: 1 on CPU, 8 on GPU)")
1506
+ ap.add_argument("--scorer-name", default="worker", help="'scorer' value in item rows (e.g. 'drain' on GPU)")
1507
+ ap.add_argument("--model-cap", type=int, default=CAPS["model"])
1508
+ ap.add_argument("--poll-secs", type=int, default=60)
1509
+ ap.add_argument("--overlap-secs", type=int, default=300)
1510
+ ap.add_argument("--max-list-pages", type=int, default=2000)
1511
+ ap.add_argument("--sweep-secs", type=int, default=1800, help="late-appearance sweep interval (0 = off)")
1512
+ ap.add_argument("--sweep-hours", type=float, default=6)
1513
+ ap.add_argument("--flush-secs", type=int, default=300)
1514
+ ap.add_argument("--fresh-max-age", type=int, default=900, help="seconds; older items go to the backlog lane")
1515
+ ap.add_argument("--fresh-ratio", type=int, default=4, help="fresh pops per backlog pop")
1516
+ ap.add_argument("--arxiv-poll", action="store_true", help="also poll the arXiv API for all cs.* submissions "
1517
+ "(off by default: papers come from HF Daily Papers)")
1518
+ ap.add_argument("--arxiv-secs", type=int, default=1800)
1519
+ ap.add_argument("--daily-secs", type=int, default=600)
1520
+ ap.add_argument("--arxiv-since", default="2026-09-18")
1521
+ ap.add_argument("--gate-workers", type=int, default=8)
1522
+ ap.add_argument("--max-minutes", type=float, default=0)
1523
+ ap.add_argument("--exit-when-empty", action="store_true", help="drain mode: stop once the initial polls are "
1524
+ "done and the queue is empty")
1525
+ ap.add_argument("--inherit", default="", choices=["", "quantized", "adapter"],
1526
+ help="copy base-model scores for quantized (+adapter) repos whose base is scored")
1527
+ ap.add_argument("--compact-over", type=int, default=200, help="compact the gate table at start above N deltas")
1528
+ ap.add_argument("--no-queue-snapshot", action="store_true")
1529
+ ap.add_argument("--no-cursor", action="store_true", help="do not write cursor.json (side jobs)")
1530
+ ap.add_argument("--selfcheck", type=int, default=0, help="re-score N backfill rows per source first")
1531
+ ap.add_argument("--no-papers", action="store_true")
1532
+ ap.add_argument("--live-secs", type=int, default=20, help="flush the state/events/ JSONL stream this often")
1533
+ ap.add_argument("--live-retention-hours", type=int, default=48)
1534
+ ap.add_argument("--canary-secs", type=int, default=600, help="score a fixed 800-char text this often (box speed)")
1535
+ ap.add_argument("--status-file", default="worker_status.json")
1536
+ ap.add_argument("--compact-every", type=int, default=3600, help="seconds between item/gate compactions (0 = off)")
1537
+ ap.add_argument("--drain-snapshot", action="store_true", help="GPU drain job: score the latest queue snapshot "
1538
+ "and exit (implies --exit-when-empty, --no-cursor, "
1539
+ "--no-queue-snapshot, --live-secs 0)")
1540
+ ap.add_argument("--drain-items", type=int, default=500)
1541
+ ap.add_argument("--drain-secs", type=int, default=1800)
1542
+ args = ap.parse_args()
1543
+ if args.drain_snapshot:
1544
+ args.exit_when_empty = args.no_cursor = args.no_queue_snapshot = True
1545
+ args.live_secs = 0
1546
+ args.inherit = ""
1547
+ args.compact_every = 0
1548
+ if args.status_file == "worker_status.json":
1549
+ args.status_file = "drain_status.json"
1550
+ w = Worker(args)
1551
+ signal.signal(signal.SIGTERM, lambda *_: w.stop.set())
1552
+ w.run()
1553
+
1554
+
1555
+ if __name__ == "__main__":
1556
+ main()
requirements.txt CHANGED
@@ -1,3 +1,9 @@
 
1
  pandas
2
  pyarrow
3
  numpy
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
  pandas
3
  pyarrow
4
  numpy
5
+ torch
6
+ gliner2[local]==2.0.0
7
+ protobuf
8
+ sentencepiece
9
+ requests