ArthurZ HF Staff commited on
Commit
4e10f5a
·
verified ·
1 Parent(s): 55ef2ef

tracker script

Browse files
Files changed (1) hide show
  1. tracker.py +235 -0
tracker.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # dependencies = ["huggingface_hub>=0.35", "requests"]
3
+ # ///
4
+ """Daily radar: transformers-related issues + monkey patches in downstream repos -> static Space.
5
+
6
+ Run: HF_TOKEN=... GITHUB_TOKEN=... uv run tracker.py (DRY=1 to write index.html locally instead of pushing)
7
+ Schedule: hf jobs scheduled uv run daily https://huggingface.co/spaces/$SPACE/resolve/main/tracker.py --secrets HF_TOKEN (GITHUB_TOKEN optional: 3x faster search)
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import subprocess
14
+ import tempfile
15
+ import time
16
+ from collections import defaultdict
17
+ from datetime import date, timedelta
18
+ from html import escape
19
+ from pathlib import Path
20
+
21
+ import requests
22
+ from huggingface_hub import HfApi, InferenceClient, hf_hub_download
23
+
24
+ # Heavy transformers users, ordered by GitHub stars (2026-11). Picked from stars >5k or pypi >300k/month.
25
+ REPOS = [
26
+ "ggml-org/llama.cpp", "vllm-project/vllm", "unslothai/unsloth", "hiyouga/LlamaFactory",
27
+ "deepspeedai/DeepSpeed", "hpcaitech/ColossalAI", "sgl-project/sglang", "huggingface/diffusers",
28
+ "huggingface/lerobot", "huggingface/open-r1", "m-bain/whisperX", "verl-project/verl", "huggingface/peft",
29
+ "huggingface/trl", "kvcache-ai/ktransformers", "huggingface/sentence-transformers", "NVIDIA-NeMo/Automodel",
30
+ "modelscope/ms-swift", "dottxt-ai/outlines", "NVIDIA/TensorRT-LLM", "flairNLP/flair",
31
+ "EleutherAI/lm-evaluation-harness", "axolotl-ai-cloud/axolotl", "FlagOpen/FlagEmbedding",
32
+ "OpenRLHF/OpenRLHF", "huggingface/accelerate", "THUDM/slime", "bitsandbytes-foundation/bitsandbytes",
33
+ "ml-explore/mlx-lm", "arcee-ai/mergekit", "linkedin/Liger-Kernel", "Blaizzy/mlx-vlm",
34
+ "EvolvingLMMs-Lab/lmms-eval", "urchade/GLiNER", "vllm-project/llm-compressor", "allenai/open-instruct",
35
+ "huggingface/optimum", "embeddings-benchmark/mteb", "alibaba/ROLL", "PrimeIntellect-ai/prime-rl",
36
+ "intel/auto-round", "ModelCloud/GPTQModel", "huggingface/optimum-quanto", "unslothai/unsloth-zoo",
37
+ ] # fmt: skip
38
+ SPACE = os.environ.get("SPACE", "ArthurZ/transformers-downstream-tracker")
39
+ MODEL = os.environ.get("MODEL", "Qwen/Qwen3-235B-A22B-Instruct-2507")
40
+ DAYS = int(os.environ.get("DAYS", 2)) # ponytail: overlap between daily runs is fine
41
+ DRY = os.environ.get("DRY") == "1"
42
+
43
+ # ponytail: regex heuristic, catches `transformers.x.y = ...`, `modeling_llama.Foo.forward = ...`, setattr on
44
+ # transformers modules, and `LlamaAttention.forward = ...`. Misses aliased imports; AST pass if that matters.
45
+ PATCH_RE = re.compile(
46
+ r"^\s*(transformers(\.\w+)+|modeling_\w+(\.\w+)+"
47
+ r"|[A-Z]\w*(Attention|MLP|Model|ForCausalLM|DecoderLayer|RMSNorm|PreTrainedModel|Embedding)\w*\.\w+)\s*=[^=]"
48
+ r"|setattr\(\s*(transformers|modeling_)"
49
+ )
50
+ MODEL_CLS = re.compile(
51
+ r"^(?!PreTrainedModel)[A-Z]\w*?(?=(ForCausalLM|ForConditionalGeneration|SdpaAttention|FlashAttention2|Attention"
52
+ r"|MLP|DecoderLayer|RMSNorm|RotaryEmbedding|SparseMoeBlock|Experts|Model)\b)"
53
+ )
54
+
55
+
56
+ def issues():
57
+ # GitHub search, not GH Archive: the public events feed is heavily sampled (~40 of ~650 daily vllm events).
58
+ since = (date.today() - timedelta(days=DAYS)).isoformat()
59
+ headers = {"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"} if "GITHUB_TOKEN" in os.environ else {}
60
+ rows = []
61
+ for i, repo in enumerate(REPOS, 1):
62
+ q = f"repo:{repo} transformers in:title,body,comments updated:>={since}"
63
+ r = requests.get(
64
+ "https://api.github.com/search/issues", params={"q": q, "per_page": 100, "sort": "updated"},
65
+ headers=headers, timeout=60,
66
+ ) # fmt: skip
67
+ if not r.ok: # renamed/private repo shouldn't kill the whole report
68
+ print(f"[{i}/{len(REPOS)}] {repo}: search failed {r.status_code}", flush=True)
69
+ continue
70
+ # ponytail: first 100 most recently updated only; vllm hits the cap, paginate if the tail matters
71
+ items = r.json()["items"]
72
+ rows += [
73
+ {"repo_name": repo, "number": it["number"], "t": it["title"], "b": it["body"], "comments": it["comments"],
74
+ "is_pr": "pull_request" in it}
75
+ for it in items
76
+ ] # fmt: skip
77
+ print(f"[{i}/{len(REPOS)}] {repo}: {len(items)} threads", flush=True)
78
+ time.sleep(2.1 if headers else 6.5) # search API: 30 req/min authenticated, 10 anonymous
79
+ return sorted(rows, key=lambda r: -r["comments"])
80
+
81
+
82
+ def patches():
83
+ found = set()
84
+ for i, repo in enumerate(REPOS, 1):
85
+ with tempfile.TemporaryDirectory() as dst: # one at a time, keeps job disk small
86
+ clone = ["git", "clone", "-q", "--depth", "1", "--filter=blob:limit=1m", f"https://github.com/{repo}", dst]
87
+ if subprocess.run(clone).returncode:
88
+ print(f"[{i}/{len(REPOS)}] {repo}: clone failed", flush=True)
89
+ continue
90
+ files = subprocess.run(["git", "ls-files", "*.py"], cwd=dst, capture_output=True, text=True).stdout
91
+ # key on file + stripped line so line-number churn doesn't count as a new patch
92
+ hits = {
93
+ f"{repo}:{f}: {line.strip()}"
94
+ for f in files.split()
95
+ if "test" not in f and Path(dst, f).exists()
96
+ for line in Path(dst, f).read_text(errors="ignore").splitlines()
97
+ if PATCH_RE.search(line)
98
+ }
99
+ found |= hits
100
+ print(f"[{i}/{len(REPOS)}] {repo}: {len(hits)} patches", flush=True)
101
+ return found
102
+
103
+
104
+ def target(key):
105
+ """`repo:file: modeling_llama.LlamaAttention.forward = f` -> `*Attention.forward` (what transformers symbol is patched)."""
106
+ code = key.split(": ", 1)[1]
107
+ m = re.search(r"setattr\(\s*([\w.]+)\s*,\s*['\"](\w+)", code)
108
+ sym = f"{m[1]}.{m[2]}" if m else code.split("=")[0].strip()
109
+ sym = re.sub(r"^(transformers\.)?(models\.\w+\.)?(\w*modeling_\w+\.?)?", "", sym) or "<module>"
110
+ return MODEL_CLS.sub("*", sym)
111
+
112
+
113
+ def triage(rows):
114
+ """LLM groups threads by root cause and says what transformers should do. Returns list of dicts or None."""
115
+ listing = "\n".join(
116
+ f"- {r['repo_name']}#{r['number']} ({'PR' if r['is_pr'] else 'issue'}, {r['comments']} comments): "
117
+ f"{r['t']}\n {(r['b'] or '')[:300]!r}"
118
+ for r in rows[:200]
119
+ )
120
+ prompt = (
121
+ "You triage downstream breakage for the huggingface/transformers maintainers. Below are recent issues/PRs from "
122
+ "libraries that depend on transformers. Group them by root cause. Drop anything not caused by or about "
123
+ "transformers (env dumps that merely list a version do not count). Reply with ONLY a JSON array, most urgent "
124
+ 'first, items: {"severity": "high|medium|low", "action": "fix in transformers|reply/guide users|watch", '
125
+ '"component": "e.g. tokenizers, generate, from_pretrained, attention, model:<name>, trainer", '
126
+ '"summary": "one line, in transformers terms", "refs": ["owner/repo#N", ...]}\n\n' + listing
127
+ )
128
+ try:
129
+ out = InferenceClient().chat_completion([{"role": "user", "content": prompt}], model=MODEL, max_tokens=4000)
130
+ return json.loads(re.search(r"\[.*\]", out.choices[0].message.content, re.S)[0])
131
+ except Exception as e: # LLM is a nicety; raw table still rendered
132
+ print(f"triage failed: {e}", flush=True)
133
+ return None
134
+
135
+
136
+ def link(ref):
137
+ repo, n = ref.split("#")
138
+ return f'<a href="https://github.com/{repo}/issues/{n}">{escape(ref)}</a>'
139
+
140
+
141
+ def patch_link(key):
142
+ repo, rest = key.split(":", 1)
143
+ f, code = rest.split(": ", 1)
144
+ return f'<a href="https://github.com/{repo}/blob/HEAD/{f}">{escape(repo)}/{escape(f)}</a>', f"<code>{escape(code)}</code>"
145
+
146
+
147
+ def table(head, rows):
148
+ th = "".join(f"<th>{h}</th>" for h in head)
149
+ return f"<table><tr>{th}</tr>" + "".join("<tr>" + "".join(f"<td>{c}</td>" for c in r) + "</tr>" for r in rows) + "</table>"
150
+
151
+
152
+ def render(rows, groups, now, new, gone):
153
+ sev = {"high": "🔴", "medium": "🟠", "low": "⚪"}
154
+ h = [f"<h1>transformers downstream radar · {date.today()}</h1>",
155
+ f"<p>{len(REPOS)} repos · last {DAYS} days of GitHub activity · {len(now)} monkey patches tracked</p>"] # fmt: skip
156
+
157
+ h.append("<h2>Act on these</h2>")
158
+ if groups is not None:
159
+ groups = sorted(groups, key=lambda g: ["high", "medium", "low"].index(g.get("severity", "low")))
160
+ h.append(table(["", "action", "component", "what", "threads"], [
161
+ [sev.get(g.get("severity"), ""), escape(g.get("action", "")), escape(g.get("component", "")),
162
+ escape(g.get("summary", "")), " ".join(link(r) for r in g.get("refs", []) if "#" in r)]
163
+ for g in groups if g.get("action") != "watch"
164
+ ])) # fmt: skip
165
+ h.append(f"<details><summary>All {len(rows)} matching threads</summary>")
166
+ h.append(table(["thread", "comments", "title"], [
167
+ [link(f"{r['repo_name']}#{r['number']}"), r["comments"], escape(r["t"] or "")] for r in rows
168
+ ])) # fmt: skip
169
+ h.append("</details>")
170
+
171
+ h.append(f"<h2>New monkey patches since last run ({len(new)})</h2>")
172
+ h.append("<p>Something changed on their side or ours: check whether a transformers change forced it.</p>")
173
+ h.append(table(["where", "patch"], [patch_link(k) for k in new]) if new else "<p>None.</p>")
174
+ if gone:
175
+ h.append(f"<details><summary>Removed since last run ({len(gone)})</summary>")
176
+ h.append(table(["where", "patch"], [patch_link(k) for k in gone]) + "</details>")
177
+
178
+ by_target = defaultdict(set)
179
+ for k in now:
180
+ by_target[target(k)].add(k.split(":", 1)[0])
181
+ top = sorted(by_target.items(), key=lambda kv: (-len(kv[1]), kv[0]))[:40]
182
+ h.append("<h2>Most-patched transformers internals</h2>")
183
+ h.append("<p>Patched by several repos = missing extension point (kernel hub / attention interface / hook).</p>")
184
+ h.append(table(["symbol", "#repos", "repos"], [
185
+ [f"<code>{escape(t)}</code>", len(rs), ", ".join(r.split("/")[1] for r in sorted(rs))] for t, rs in top
186
+ ])) # fmt: skip
187
+
188
+ threads = defaultdict(int)
189
+ for r in rows:
190
+ threads[r["repo_name"]] += 1
191
+ count = lambda keys, repo: sum(k.startswith(repo + ":") for k in keys)
192
+ h.append("<h2>Per repo</h2>")
193
+ h.append(table(["repo", "threads", "patches", "new patches"], [
194
+ [f'<a href="https://github.com/{r}">{r}</a>', threads[r], count(now, r), count(new, r)] for r in REPOS
195
+ ])) # fmt: skip
196
+ h.append(f"<details><summary>All {len(now)} patches</summary>")
197
+ h.append(table(["where", "patch"], [patch_link(k) for k in sorted(now)]) + "</details>")
198
+
199
+ css = (
200
+ "body{max-width:1200px;margin:auto;padding:1em;font-family:system-ui}table{border-collapse:collapse;width:100%}"
201
+ "td,th{border-bottom:1px solid #ddd;padding:4px 8px;text-align:left;vertical-align:top}code{font-size:85%}"
202
+ )
203
+ return f"<!doctype html><meta charset=utf-8><title>transformers radar</title><style>{css}</style>" + "\n".join(h)
204
+
205
+
206
+ def main():
207
+ rows = issues()
208
+ print(f"{len(rows)} transformers-related threads in last {DAYS}d", flush=True)
209
+ groups = triage(rows) if rows else []
210
+ print(f"triaged into {len(groups) if groups is not None else '?'} groups", flush=True)
211
+ now = patches()
212
+ try:
213
+ before = set(json.load(open(hf_hub_download(SPACE, "patches.json", repo_type="space"))))
214
+ except Exception: # first run: nothing to diff against
215
+ before = now
216
+ new, gone = sorted(now - before), sorted(before - now)
217
+ html = render(rows, groups, now, new, gone)
218
+
219
+ if DRY:
220
+ Path("index.html").write_text(html)
221
+ print("wrote index.html", flush=True)
222
+ return
223
+ api = HfApi()
224
+ api.create_repo(SPACE, repo_type="space", space_sdk="static", exist_ok=True)
225
+ with tempfile.TemporaryDirectory() as tmp:
226
+ Path(tmp, "index.html").write_text(html)
227
+ Path(tmp, "patches.json").write_text(json.dumps(sorted(now), indent=1))
228
+ Path(tmp, "reports").mkdir()
229
+ Path(tmp, f"reports/{date.today()}.json").write_text(json.dumps({"threads": rows, "groups": groups}, indent=1))
230
+ api.upload_folder(folder_path=tmp, repo_id=SPACE, repo_type="space", commit_message=f"radar {date.today()}")
231
+ print(f"pushed https://huggingface.co/spaces/{SPACE}", flush=True)
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()