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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build data.json for the Gradio Space.
|
| 2 |
+
|
| 3 |
+
Positions: pre-computed 3D embeddings of the `src/transformers/**` source files
|
| 4 |
+
(downloaded from a private HF bucket). Falls back to PCA on the original
|
| 5 |
+
384-dim embeddings if the 3D file is missing.
|
| 6 |
+
Colors: recency-weighted edit score from `git log` on the cloned transformers repo.
|
| 7 |
+
"""
|
| 8 |
+
import datetime as dt
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
import subprocess
|
| 14 |
+
import urllib.error
|
| 15 |
+
import urllib.request
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
ROOT = Path(__file__).parent
|
| 22 |
+
REPO_DIR = ROOT / ".cache" / "transformers"
|
| 23 |
+
|
| 24 |
+
EMBEDDINGS_3D_FILE = ROOT / ".cache" / "transformers-embeddings-src-3d.jsonl"
|
| 25 |
+
EMBEDDINGS_3D_URL = (
|
| 26 |
+
"https://huggingface.co/buckets/the-best-team/data/resolve/"
|
| 27 |
+
"transformers-embeddings-src-3d.jsonl"
|
| 28 |
+
)
|
| 29 |
+
EMBEDDINGS_FILE = ROOT / ".cache" / "transformers-embeddings-src.jsonl"
|
| 30 |
+
EMBEDDINGS_URL = (
|
| 31 |
+
"https://huggingface.co/buckets/the-best-team/data/resolve/"
|
| 32 |
+
"transformers-embeddings-src.jsonl"
|
| 33 |
+
)
|
| 34 |
+
DATA_FILE = ROOT / "data.json"
|
| 35 |
+
|
| 36 |
+
SRC_PREFIX = "src/transformers/"
|
| 37 |
+
HALF_LIFE_SECONDS = 365 * 24 * 3600 # 1 year
|
| 38 |
+
|
| 39 |
+
# Files whose path matches any of these regexes are dropped from the point cloud.
|
| 40 |
+
SKIP_PATH_PATTERNS = [
|
| 41 |
+
re.compile(r"(^|/)__init__\.py$"),
|
| 42 |
+
re.compile(r"(^|/)modeling_.*\.py$"),
|
| 43 |
+
re.compile(r"^src/transformers/cli/transformers\.py$"),
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def is_skipped(path):
|
| 48 |
+
return any(p.search(path) for p in SKIP_PATH_PATTERNS)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run(cmd):
|
| 52 |
+
return subprocess.run(cmd, check=True, capture_output=True, text=True).stdout
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def hf_token():
|
| 56 |
+
p = Path.home() / ".cache" / "huggingface" / "token"
|
| 57 |
+
return p.read_text().strip() if p.exists() else os.environ.get("HF_TOKEN", "")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def download(url, dest):
|
| 61 |
+
if dest.exists():
|
| 62 |
+
return True
|
| 63 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
try:
|
| 65 |
+
req = urllib.request.Request(
|
| 66 |
+
url, headers={"Authorization": f"Bearer {hf_token()}"}
|
| 67 |
+
)
|
| 68 |
+
with urllib.request.urlopen(req) as resp, dest.open("wb") as out:
|
| 69 |
+
out.write(resp.read())
|
| 70 |
+
return True
|
| 71 |
+
except (urllib.error.URLError, urllib.error.HTTPError) as e:
|
| 72 |
+
print(f" download failed for {url}: {e}")
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def load_embeddings_3d():
|
| 77 |
+
"""Primary source: per-file 3D vectors keyed under `reduced_embedding`.
|
| 78 |
+
|
| 79 |
+
Returns ordered (paths, coords) or (None, None) if the file isn't available.
|
| 80 |
+
"""
|
| 81 |
+
if not download(EMBEDDINGS_3D_URL, EMBEDDINGS_3D_FILE):
|
| 82 |
+
return None, None
|
| 83 |
+
paths, vecs = [], []
|
| 84 |
+
with EMBEDDINGS_3D_FILE.open() as f:
|
| 85 |
+
for line in f:
|
| 86 |
+
d = json.loads(line)
|
| 87 |
+
paths.append(SRC_PREFIX + d["path"])
|
| 88 |
+
vecs.append(d["reduced_embedding"])
|
| 89 |
+
return paths, np.asarray(vecs, dtype=np.float64)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def load_embeddings_pca_fallback():
|
| 93 |
+
"""Fallback: load 384-dim embeddings and reduce via PCA."""
|
| 94 |
+
if not download(EMBEDDINGS_URL, EMBEDDINGS_FILE):
|
| 95 |
+
raise RuntimeError("Neither the 3D nor the 384-dim embedding file is available.")
|
| 96 |
+
paths, vecs = [], []
|
| 97 |
+
with EMBEDDINGS_FILE.open() as f:
|
| 98 |
+
for line in f:
|
| 99 |
+
d = json.loads(line)
|
| 100 |
+
paths.append(SRC_PREFIX + d["path"])
|
| 101 |
+
vecs.append(d["embedding"])
|
| 102 |
+
matrix = np.asarray(vecs, dtype=np.float64)
|
| 103 |
+
return paths, pca_3d(matrix)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def pca_3d(matrix):
|
| 107 |
+
"""Project (N, D) → (N, 3) via centered SVD. Scale each axis to roughly unit std."""
|
| 108 |
+
X = matrix - matrix.mean(axis=0, keepdims=True)
|
| 109 |
+
_, _, Vt = np.linalg.svd(X, full_matrices=False)
|
| 110 |
+
proj = X @ Vt[:3].T
|
| 111 |
+
proj /= proj.std(axis=0, keepdims=True) + 1e-12
|
| 112 |
+
return proj
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def load_positions():
|
| 116 |
+
"""Pre-computed 3D embeddings if available, else PCA on the 384-dim file."""
|
| 117 |
+
paths, coords = load_embeddings_3d()
|
| 118 |
+
if paths is not None:
|
| 119 |
+
print(f"Using pre-computed 3D embeddings: {len(paths)} files.")
|
| 120 |
+
return paths, coords
|
| 121 |
+
print("3D embeddings unavailable; falling back to PCA on 384-dim file.")
|
| 122 |
+
return load_embeddings_pca_fallback()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def edit_timelines():
|
| 126 |
+
out = run(
|
| 127 |
+
[
|
| 128 |
+
"git", "-C", str(REPO_DIR),
|
| 129 |
+
"log", "--name-only", "--pretty=format:COMMIT:%ct",
|
| 130 |
+
]
|
| 131 |
+
)
|
| 132 |
+
timelines = defaultdict(list)
|
| 133 |
+
current_ts = None
|
| 134 |
+
for line in out.split("\n"):
|
| 135 |
+
if line.startswith("COMMIT:"):
|
| 136 |
+
current_ts = int(line[len("COMMIT:"):])
|
| 137 |
+
elif line.strip() and current_ts is not None:
|
| 138 |
+
timelines[line.strip()].append(current_ts)
|
| 139 |
+
return timelines
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def recency_weighted_score(timestamps, now_ts):
|
| 143 |
+
"""Sum of exp-decayed edit weights: recent edits weigh more, old ones fade."""
|
| 144 |
+
if not timestamps:
|
| 145 |
+
return 0.0
|
| 146 |
+
return sum(0.5 ** ((now_ts - ts) / HALF_LIFE_SECONDS) for ts in timestamps)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def redness_scores(scores):
|
| 150 |
+
"""Log-compress, min-max normalize, invert so high score → 0 (red)."""
|
| 151 |
+
log_scores = [math.log1p(s) for s in scores]
|
| 152 |
+
lo, hi = min(log_scores), max(log_scores)
|
| 153 |
+
span = (hi - lo) or 1.0
|
| 154 |
+
return [1.0 - (ls - lo) / span for ls in log_scores]
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def main():
|
| 158 |
+
paths, coords = load_positions()
|
| 159 |
+
keep = [i for i, p in enumerate(paths) if not is_skipped(p)]
|
| 160 |
+
if len(keep) < len(paths):
|
| 161 |
+
print(f"Skipping {len(paths) - len(keep)} files via SKIP_PATH_PATTERNS.")
|
| 162 |
+
paths = [paths[i] for i in keep]
|
| 163 |
+
coords = coords[keep]
|
| 164 |
+
print(f"Per-axis std: {coords.std(axis=0)}")
|
| 165 |
+
|
| 166 |
+
timelines = edit_timelines()
|
| 167 |
+
now_ts = int(dt.datetime.now().timestamp())
|
| 168 |
+
|
| 169 |
+
scores, edit_times, hovers = [], [], []
|
| 170 |
+
for p in paths:
|
| 171 |
+
ts_list = timelines.get(p, [])
|
| 172 |
+
scores.append(recency_weighted_score(ts_list, now_ts))
|
| 173 |
+
edit_times.append(ts_list)
|
| 174 |
+
last = dt.date.fromtimestamp(max(ts_list)).isoformat() if ts_list else "never"
|
| 175 |
+
hovers.append(f"{p}<br>edits: {len(ts_list)} (last: {last})")
|
| 176 |
+
|
| 177 |
+
color_values = redness_scores(scores)
|
| 178 |
+
|
| 179 |
+
data = {
|
| 180 |
+
"x": coords[:, 0].tolist(),
|
| 181 |
+
"y": coords[:, 1].tolist(),
|
| 182 |
+
"z": coords[:, 2].tolist(),
|
| 183 |
+
"color": color_values,
|
| 184 |
+
"edit_times": edit_times,
|
| 185 |
+
"hover": hovers,
|
| 186 |
+
}
|
| 187 |
+
DATA_FILE.write_text(json.dumps(data))
|
| 188 |
+
print(
|
| 189 |
+
f"Wrote {DATA_FILE} — {len(paths)} points, "
|
| 190 |
+
f"max recency-weighted score: {max(scores):.2f}"
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if __name__ == "__main__":
|
| 195 |
+
main()
|