File size: 71,396 Bytes
bca5039 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 | from __future__ import annotations
import torch
import numpy as np
from abc import ABC, abstractmethod
from typing import Dict, Union, Tuple, Optional, Callable, Any, List
import warnings
from collections import defaultdict
import datasets
from datasets import load_dataset
# Optional dependencies for spatial indexing
try:
import faiss
FAISS_AVAILABLE = True
except ImportError:
FAISS_AVAILABLE = False
try:
from sklearn.neighbors import NearestNeighbors
SKLEARN_AVAILABLE = True
except ImportError:
SKLEARN_AVAILABLE = False
class SpatialIndex:
"""Spatial indexing for fast similarity search."""
def __init__(self, vectors: np.ndarray, token_ids: List[int], method: str = "auto"):
self.token_ids = np.array(token_ids)
self.method = method
self._index = None
if method == "auto":
if FAISS_AVAILABLE and vectors.shape[0] > 1000:
method = "faiss"
elif SKLEARN_AVAILABLE:
method = "sklearn"
else:
method = "linear"
self._build_index(vectors, method)
def _build_index(self, vectors: np.ndarray, method: str):
if method == "faiss" and FAISS_AVAILABLE:
# L1 distance approximation using L2 index with normalized vectors
vectors_l2 = vectors / (np.linalg.norm(vectors, axis=1, keepdims=True) + 1e-8)
self._index = faiss.IndexFlatIP(vectors_l2.shape[1]) # Inner product for normalized vectors
self._index.add(vectors_l2.astype(np.float32))
self.method = "faiss"
elif method == "sklearn" and SKLEARN_AVAILABLE:
# Use manhattan distance for true L1
self._index = NearestNeighbors(
metric='manhattan',
algorithm='ball_tree',
n_jobs=-1
).fit(vectors)
self.method = "sklearn"
else:
# Fallback to linear search
self._vectors = vectors
self.method = "linear"
def search_radius(self, query_vector: np.ndarray, max_distance: float, max_results: int = 1000) -> Tuple[
List[int], List[float]]:
"""Find all points within max_distance using L1 metric."""
if self.method == "sklearn":
indices = self._index.radius_neighbors([query_vector], radius=max_distance)[1][0]
if len(indices) > max_results:
# Compute actual distances and take closest
distances = np.sum(np.abs(self._vectors[indices] - query_vector), axis=1)
top_k = np.argsort(distances)[:max_results]
indices = indices[top_k]
distances = np.sum(np.abs(self._vectors[indices] - query_vector), axis=1)
return self.token_ids[indices].tolist(), distances.tolist()
elif self.method == "faiss":
# Approximate search using cosine similarity
query_l2 = query_vector / (np.linalg.norm(query_vector) + 1e-8)
similarities, indices = self._index.search(query_l2.reshape(1, -1).astype(np.float32), max_results)
# Filter by converting similarity threshold to approximate distance
threshold_sim = 1.0 - max_distance # rough approximation
mask = similarities[0] >= threshold_sim
return self.token_ids[indices[0][mask]].tolist(), (1.0 - similarities[0][mask]).tolist()
else: # linear
distances = np.sum(np.abs(self._vectors - query_vector), axis=1)
mask = distances <= max_distance
if np.sum(mask) > max_results:
indices = np.argsort(distances)[:max_results]
mask = np.zeros_like(distances, dtype=bool)
mask[indices] = True
return self.token_ids[mask].tolist(), distances[mask].tolist()
class GeometricVocab(ABC):
"""
Optimized geometric vocabulary with spatial indexing and caching.
"""
def __init__(self, dim: int):
self.dim = int(dim)
self._token_to_id: Dict[str, int] = {}
self._id_to_token: Dict[int, str] = {}
self._id_to_vec: Dict[int, np.ndarray] = {}
self._id_to_volume: Dict[int, float] = {}
self._id_to_provenance: Dict[int, dict] = {}
self._valid_token_ids: set[int] = set()
# Optimization caches
self._normalized_cache: Dict[int, np.ndarray] = {}
self._pooled_cache: Dict[int, np.ndarray] = {}
self._spatial_index: Optional[SpatialIndex] = None
self._index_dirty = False
# NEW: Character-level cache for Unicode composition
self._char_cache: Dict[str, np.ndarray] = {}
self._char_lookups_saved = 0 # Statistics
def _invalidate_caches(self):
"""Invalidate caches when vocabulary changes."""
self._normalized_cache.clear()
self._pooled_cache.clear()
self._spatial_index = None
self._index_dirty = True
# Keep char cache across vocabulary changes as characters are stable
def _ensure_spatial_index(self):
"""Build spatial index if needed."""
if self._spatial_index is None or self._index_dirty:
if len(self._valid_token_ids) < 10:
return # Too few tokens for indexing
pooled_vectors = []
token_ids = []
for tid in sorted(self._valid_token_ids):
pooled_vec = self._get_cached_pooled(tid)
if pooled_vec is not None:
pooled_vectors.append(pooled_vec)
token_ids.append(tid)
if pooled_vectors:
self._spatial_index = SpatialIndex(
np.array(pooled_vectors),
token_ids,
method="auto"
)
self._index_dirty = False
def _get_cached_pooled(self, token_id: int) -> Optional[np.ndarray]:
"""Get pooled vector with caching."""
if token_id in self._pooled_cache:
return self._pooled_cache[token_id]
if token_id in self._id_to_vec:
X = self._id_to_vec[token_id]
pooled = X.mean(axis=0)
self._pooled_cache[token_id] = pooled
return pooled
return None
def _get_cached_normalized(self, token_id: int) -> Optional[np.ndarray]:
"""Get L1-normalized pooled vector with caching."""
if token_id in self._normalized_cache:
return self._normalized_cache[token_id]
pooled = self._get_cached_pooled(token_id)
if pooled is not None:
normalized = pooled / (np.abs(pooled).sum() + 1e-8)
self._normalized_cache[token_id] = normalized
return normalized
return None
# --------------------------- abstract surface --------------------
@abstractmethod
def encode(self, token: str, *, return_id: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, int]]:
raise NotImplementedError
@abstractmethod
def get_score(self, token_or_id: Union[str, int]) -> float:
raise NotImplementedError
# --------------------------- basic queries (optimized) -----------------------
def decode(self, token_id: int, fallback: str = "<unk>") -> Optional[str]:
if token_id in self._id_to_token:
return self._id_to_token[token_id]
return fallback if fallback in self._token_to_id else None
def decode_with_provenance(self, token_id: int, fallback: str = "<unk>") -> Tuple[Optional[str], Optional[dict]]:
tok = self.decode(token_id, fallback=fallback)
prov = self._id_to_provenance.get(token_id)
return tok, prov
def provenance(self, token_or_id: Union[str, int]) -> Optional[dict]:
tid = token_or_id if isinstance(token_or_id, int) else self._token_to_id.get(token_or_id)
return self._id_to_provenance.get(tid)
def embedding(self, token_or_id: Union[str, int]) -> Optional[np.ndarray]:
tid = token_or_id if isinstance(token_or_id, int) else self._token_to_id.get(token_or_id)
return self._id_to_vec.get(tid)
def pooled(self, token_or_id: Union[str, int], method: str = "mean") -> Optional[np.ndarray]:
"""Optimized pooled method with character caching"""
# Fast path for single characters
if isinstance(token_or_id, str) and len(token_or_id) == 1:
if token_or_id in self._char_cache:
self._char_lookups_saved += 1
return self._char_cache[token_or_id].copy() # Return copy to prevent mutation
# Regular lookup
tid = token_or_id if isinstance(token_or_id, int) else self._token_to_id.get(token_or_id)
if tid is None:
return None
if method == "mean":
pooled = self._get_cached_pooled(tid)
# Cache single characters for future use
if pooled is not None and isinstance(token_or_id, str) and len(token_or_id) == 1:
self._char_cache[token_or_id] = pooled.copy()
return pooled
# Fallback for other methods
X = self._id_to_vec.get(tid)
if X is None:
return None
if method == "first":
return X[0]
if method == "sum":
return X.sum(axis=0)
raise ValueError(f"Invalid pooling method: {method}")
def pooled_batch(self, tokens: List[Union[str, int]], method: str = "mean") -> List[Optional[np.ndarray]]:
"""Batch pooling with character-level caching for efficiency"""
results = []
for token in tokens:
# Use optimized single pooled method which handles char caching
results.append(self.pooled(token, method))
return results
# --------------------------- optimized similarity ---------------------
def similarity(self, token_a: Union[str, int], token_b: Union[str, int]) -> float:
"""
Optimized L1-normalized directional similarity using cached vectors.
"""
tid_a = token_a if isinstance(token_a, int) else self._token_to_id.get(token_a)
tid_b = token_b if isinstance(token_b, int) else self._token_to_id.get(token_b)
if tid_a is None or tid_b is None:
return -1.0
a_norm = self._get_cached_normalized(tid_a)
b_norm = self._get_cached_normalized(tid_b)
if a_norm is None or b_norm is None:
return -1.0
return float(np.dot(a_norm, b_norm))
def similarity_magnitude(self, token_a: Union[str, int], token_b: Union[str, int]) -> float:
"""
Raw dot-product using cached pooled vectors.
"""
tid_a = token_a if isinstance(token_a, int) else self._token_to_id.get(token_a)
tid_b = token_b if isinstance(token_b, int) else self._token_to_id.get(token_b)
if tid_a is None or tid_b is None:
return -1.0
a = self._get_cached_pooled(tid_a)
b = self._get_cached_pooled(tid_b)
if a is None or b is None:
return -1.0
return float(np.dot(a, b))
# --------------------------- optimized spatial search ---------------------
def extract_band(self, trajectory: np.ndarray, max_angle: float = 0.3, method: str = "pooled") -> Dict[
str, np.ndarray]:
"""
Optimized spatial search using indexing when available.
"""
if trajectory.ndim == 2:
direction = trajectory.mean(0)
else:
direction = trajectory
direction = direction / (np.abs(direction).sum() + 1e-8)
# Try spatial index first
self._ensure_spatial_index()
if self._spatial_index is not None:
try:
# Convert angle threshold to distance threshold (approximation)
max_distance = max_angle * 2.0 # rough conversion
token_ids, distances = self._spatial_index.search_radius(
direction, max_distance, max_results=1000
)
# Refine results with exact L1 similarity check
out: Dict[str, np.ndarray] = {}
for tid in token_ids:
tok = self._id_to_token.get(tid)
if tok is None:
continue
v_norm = self._get_cached_normalized(tid)
if v_norm is not None and float(np.dot(v_norm, direction)) >= 1.0 - max_angle:
out[tok] = self._id_to_vec[tid]
return out
except Exception as e:
warnings.warn(f"Spatial index search failed: {e}, falling back to linear")
# Fallback to linear search
out: Dict[str, np.ndarray] = {}
for tok, tid in self._token_to_id.items():
v_norm = self._get_cached_normalized(tid)
if v_norm is not None and float(np.dot(v_norm, direction)) >= 1.0 - max_angle:
out[tok] = self._id_to_vec[tid]
return out
def find_similar_tokens(self, token: Union[str, int], k: int = 10, min_similarity: float = 0.5) -> List[
Tuple[str, float]]:
"""
Find k most similar tokens using spatial indexing when available.
"""
tid = token if isinstance(token, int) else self._token_to_id.get(token)
if tid is None:
return []
query_vec = self._get_cached_normalized(tid)
if query_vec is None:
return []
self._ensure_spatial_index()
if self._spatial_index is not None:
try:
# Use spatial index for approximate search
max_distance = (1.0 - min_similarity) * 2.0
token_ids, _ = self._spatial_index.search_radius(
query_vec, max_distance, max_results=k * 3 # Get extra for refinement
)
# Compute exact similarities and sort
similarities = []
for tid_cand in token_ids:
if tid_cand == tid: # Skip self
continue
sim = self.similarity(tid, tid_cand)
if sim >= min_similarity:
tok = self._id_to_token.get(tid_cand)
if tok:
similarities.append((tok, sim))
return sorted(similarities, key=lambda x: x[1], reverse=True)[:k]
except Exception as e:
warnings.warn(f"Spatial similarity search failed: {e}, falling back to linear")
# Linear fallback
similarities = []
for tok_cand, tid_cand in self._token_to_id.items():
if tid_cand == tid:
continue
sim = self.similarity(tid, tid_cand)
if sim >= min_similarity:
similarities.append((tok_cand, sim))
return sorted(similarities, key=lambda x: x[1], reverse=True)[:k]
# --------------------------- helpers exposed to callbacks --------
def _helpers(self) -> Dict[str, Callable[..., np.ndarray]]:
def _emb(x):
e = self.embedding(x)
return None if e is None else np.asarray(e, np.float32)
def _poo(x):
p = self.pooled(x)
return None if p is None else np.asarray(p, np.float32)
def _chars(s):
# Use batch pooling for efficiency
return self.pooled_batch(list(s)) if isinstance(s, str) else None
return {"embedding": _emb, "pooled": _poo, "chars_pooled": _chars}
# --------------------------- DEFAULT create_crystal (unicode path) ----
def _default_create_crystal(self, config: dict, callback: Callable[..., np.ndarray]) -> np.ndarray:
"""
Deterministic default when user leaves callback/create_crystal=None.
"""
pool_type = config.get("pool_type") or "unicode"
H = config["helpers"]
token_plain = str(config["data"]["token"])
d = int(config["dim"])
c_uni = self._compose_unicode_center(token_plain, H, pool_type, d)
c_defs = self._compose_wordnet_center(config.get("additional_definitions", []), H, pool_type, d)
if pool_type == "combination":
parts = [v for v in (c_uni, c_defs) if v is not None]
c = np.mean(np.stack(parts, 0), 0) if parts else np.zeros(d, np.float32)
elif pool_type == "wordnet":
c = c_defs if c_defs is not None else np.zeros(d, np.float32)
else:
c = c_uni if c_uni is not None else np.zeros(d, np.float32)
# L1 normalization only
l1 = float(np.abs(c).sum()) + 1e-8
c = c / l1
return self._deterministic_pentachoron(c)
def _default_unicode_callback(self, name: str, **kwargs) -> np.ndarray:
raise NotImplementedError("Default callback is not invoked directly.")
# --------------------------- universal builders (overrideable) ---
def _compose_unicode_center(
self, token_plain: str, H, pool_type: Optional[str], dim: int
) -> Optional[np.ndarray]:
"""
Build a center vector from the token's Unicode characters - OPTIMIZED.
"""
# Use batch pooling for all characters at once
char_list = list(token_plain)
pooled_chars = self.pooled_batch(char_list)
vecs: List[np.ndarray] = []
for pooled_v in pooled_chars:
if pooled_v is None:
continue
v = np.asarray(pooled_v, np.float32)
if v.shape[0] != dim:
raise ValueError(f"Unicode pooled dim mismatch: got {v.shape[0]}, expected {dim}")
vecs.append(v)
if not vecs:
return None
stacked = np.stack(vecs, 0)
if pool_type in (None, "unicode", "mean"):
c = stacked.mean(axis=0)
elif pool_type == "abs":
c = np.abs(stacked).mean(axis=0)
elif pool_type == "dot":
c = stacked.mean(axis=0)
c = c / (np.abs(c).sum() + 1e-8) # L1 normalize
elif pool_type == "mse":
c = (stacked ** 2).mean(axis=0)
elif pool_type == "max":
c = stacked.max(axis=0)
else:
raise ValueError(f"Unsupported pool_type '{pool_type}'")
return c.astype(np.float32, copy=False)
def _compose_wordnet_center(
self, definitions: List[str], H, pool_type: Optional[str], dim: int
) -> Optional[np.ndarray]:
"""Build a center vector from definition text characters - OPTIMIZED."""
# Collect all characters from all definitions
all_chars = []
for text in definitions:
all_chars.extend(list(str(text)))
# Batch lookup
pooled_chars = self.pooled_batch(all_chars)
vecs: List[np.ndarray] = []
for pooled_v in pooled_chars:
if pooled_v is None:
continue
v = np.asarray(pooled_v, np.float32)
if v.shape[0] != dim:
raise ValueError(f"Definition pooled dim mismatch: got {v.shape[0]}, expected {dim}")
vecs.append(v)
if not vecs:
return None
stacked = np.stack(vecs, 0)
if pool_type in (None, "unicode", "mean"):
c = stacked.mean(axis=0)
elif pool_type == "abs":
c = np.abs(stacked).mean(axis=0)
elif pool_type == "dot":
c = stacked.mean(axis=0)
c = c / (np.abs(c).sum() + 1e-8) # L1 normalize
elif pool_type == "mse":
c = (stacked ** 2).mean(axis=0)
elif pool_type == "max":
c = stacked.max(axis=0)
else:
raise ValueError(f"Unsupported pool_type '{pool_type}'")
return c.astype(np.float32, copy=False)
def _deterministic_pentachoron(self, center_vec: np.ndarray) -> np.ndarray:
"""Universal pentachoron inflation (deterministic; overrideable)."""
d = center_vec.shape[0]
proposals = np.stack([
center_vec,
np.roll(center_vec, 1),
np.roll(center_vec, 3) * np.sign(center_vec + 1e-8),
np.roll(center_vec, 7) - center_vec,
np.roll(center_vec, 11) + center_vec,
], 0).astype(np.float32)
# L1 row norms
norms = np.sum(np.abs(proposals), axis=1, keepdims=True) + 1e-8
Q = proposals / norms
# GS orthogonalization with L1 row renorm at each step
for i in range(5):
for j in range(i):
Q[i] -= np.dot(Q[i], Q[j]) * Q[j]
Q[i] /= (np.sum(np.abs(Q[i])) + 1e-8)
gamma = np.array([1.0, 0.9, -0.8, 1.1, 1.2], np.float32)
X = np.zeros((5, d), np.float32)
for i in range(5):
X[i] = center_vec + gamma[i] * Q[i]
return X - X.mean(0, keepdims=True)
# --------------------------- finalize + provenance (overrideable) ----
def _finalize_crystal(self, X: np.ndarray) -> np.ndarray:
X = np.asarray(X, np.float32, order='C') # Ensure C-contiguous
if X.shape != (5, self.dim):
raise ValueError(f"Crystal must be shape (5, {self.dim}); got {X.shape}.")
return X - X.mean(0, keepdims=True)
def _auto_provenance_from_cfg(self, cfg: Dict[str, Any]) -> dict:
token = cfg["data"]["token"]
prov = {
"source": "special/compose",
"token": token,
"pool_type": cfg.get("pool_type") or "unicode",
"components": list(token),
"additional_definitions": list(cfg.get("additional_definitions", [])),
}
if cfg.get("antonyms"):
prov["antonyms"] = list(cfg["antonyms"])
if cfg.get("inversion_formula") is not None:
prov["inversion_formula"] = "user_supplied"
return prov
def _finalize_crystal_and_provenance(
self, product: Union[np.ndarray, Dict[str, Any]], cfg: Dict[str, Any]
) -> Tuple[np.ndarray, dict]:
# ndarray path
if isinstance(product, np.ndarray):
X = self._finalize_crystal(product)
prov = self._auto_provenance_from_cfg(cfg)
return X, prov
# dict path
if not isinstance(product, dict):
raise TypeError(
"create_crystal must return ndarray or dict with {'base':..., 'ops':..., 'provenance':...}.")
base = np.asarray(product["base"], np.float32)
X = base
for op in product.get("ops", []):
name = op.get("name")
if name == "center":
X -= X.mean(0, keepdims=True)
elif name == "scale":
X *= float(op.get("k", 1.0))
elif name == "translate":
t = np.asarray(op.get("t"), np.float32)
if t.shape != (self.dim,):
raise ValueError(f"translate.t must be shape ({self.dim},)")
X = X + t[None, :]
elif name == "normalize_rows":
n = np.sum(np.abs(X), axis=1, keepdims=True) + 1e-8
X = X / n
elif name == "align_to":
v = np.asarray(op.get("v"), np.float32)
if v.shape != (self.dim,):
raise ValueError(f"align_to.v must be shape ({self.dim},)")
v = v / (np.abs(v).sum() + 1e-8)
p = X.mean(0)
p = p / (np.abs(p).sum() + 1e-8)
alpha = float(op.get("alpha", 1.0))
X = X + alpha * (v - p)[None, :]
else:
raise ValueError(f"Unsupported op '{name}'")
prov = dict(product.get("provenance", {})) or self._auto_provenance_from_cfg(cfg)
return self._finalize_crystal(X), prov
# --------------------------- universal manifestation routine ----------
def _manifest_special_tokens(
self,
base_set: Dict[str, int],
create_crystal: Callable[[dict, Callable[..., np.ndarray]], Union[np.ndarray, Dict[str, Any]]],
callback: Optional[Callable[..., np.ndarray]],
create_config: Dict[str, Any],
) -> None:
"""Universal, deterministic manifestor with character pre-caching."""
# NEW: Pre-cache all unique characters that will be needed
unique_chars = set()
for name in base_set.keys():
token_plain = name.strip("<>").strip()
unique_chars.update(token_plain)
print(f"[⚡] Pre-caching {len(unique_chars)} unique characters...")
for ch in unique_chars:
_ = self.pooled(ch) # Trigger caching
helpers = self._helpers()
for name, tid in base_set.items():
# Keep if already present
if tid in self._id_to_vec:
self._token_to_id[name] = tid
self._id_to_token.setdefault(tid, name)
self._valid_token_ids.add(tid)
continue
# Build per-token config
cfg = {
"dim": self.dim,
"pool_type": create_config.get("pool_type", None),
"special_tokens": create_config.get("special_tokens"),
"additional_definitions": create_config.get("additional_definitions", []),
"antonyms": create_config.get("antonyms"),
"inversion_formula": create_config.get("inversion_formula"),
"data": {"token": name.strip("<>").strip(), "token_id": tid, "origin": "special"},
"helpers": helpers,
}
if create_crystal is None:
create_crystal = self._default_create_crystal
product = create_crystal(cfg, callback) if callback is not None else create_crystal(cfg,
self._default_unicode_callback)
X, prov = self._finalize_crystal_and_provenance(product, cfg)
# Register
self._token_to_id[name] = tid
self._id_to_token[tid] = name
self._id_to_vec[tid] = X.astype(np.float32, copy=False, order='C')
self._id_to_provenance[tid] = prov
self._valid_token_ids.add(tid)
self._id_to_volume.setdefault(tid, 1.0)
# Aliases
for alias in (cfg.get("special_tokens") or []):
alias = str(alias)
self._token_to_id[alias] = tid
self._id_to_token.setdefault(tid, alias)
if cfg.get("special_tokens"):
self._id_to_provenance[tid].setdefault("aliases", list(cfg["special_tokens"]))
# Antonyms
antonyms = cfg.get("antonyms") or []
invf = cfg.get("inversion_formula")
if invf:
for anti in antonyms:
if anti in base_set:
anti_id = base_set[anti]
if anti_id not in self._id_to_vec:
X_inv = invf(X, cfg) # must be deterministic
X_inv = self._finalize_crystal(X_inv)
self._token_to_id[anti] = anti_id
self._id_to_token[anti_id] = anti
self._id_to_vec[anti_id] = X_inv.astype(np.float32, copy=False, order='C')
inv_prov = {
"source": "inversion",
"of_token": name,
"of_token_id": tid,
"pool_type": cfg.get("pool_type") or "unicode",
"components": prov.get("components", []),
"additional_definitions": cfg.get("additional_definitions", []),
"ops": ["invert"],
}
self._id_to_provenance[anti_id] = inv_prov
self._valid_token_ids.add(anti_id)
self._id_to_volume.setdefault(anti_id, 1.0)
# Invalidate caches after adding tokens
self._invalidate_caches()
if self._char_lookups_saved > 0:
print(f"[✅] Character cache saved {self._char_lookups_saved} lookups")
# --------------------------- basics -------------------------------
def vocab_size(self) -> int:
return len(self._token_to_id)
def token_to_id(self, token: str) -> Optional[int]:
return self._token_to_id.get(token)
def id_to_token(self, token_id: int) -> Optional[str]:
return self._id_to_token.get(token_id)
def cache_stats(self) -> Dict[str, int]:
"""Get cache statistics."""
return {
"normalized_cache_size": len(self._normalized_cache),
"pooled_cache_size": len(self._pooled_cache),
"char_cache_size": len(self._char_cache),
"char_lookups_saved": self._char_lookups_saved,
"spatial_index_size": len(self._spatial_index.token_ids) if self._spatial_index else 0,
"vocab_size": len(self._valid_token_ids)
}
def clear_caches(self):
"""Clear all caches to free memory."""
self._invalidate_caches()
self._char_cache.clear()
self._char_lookups_saved = 0
from typing import List, Dict, Union, Optional, Tuple, Callable, Any
class PretrainedGeometricVocab(GeometricVocab):
"""
Parquet-backed deterministic vocab with columnar load, duplicate-mean aggregation,
pooled caching, and fast path for flat crystals.
"""
def __init__(
self,
repo_id: str,
dim: int,
*,
subset: str = "unicode",
split: str = "train_100d",
base_set: Optional[Dict[str, int]] = None,
create_config: Optional[Dict[str, Any]] = None,
create_crystal: Optional[Callable[[dict, Callable[..., np.ndarray]], Union[np.ndarray, Dict[str, Any]]]] = None,
callback: Optional[Callable[..., np.ndarray]] = None,
manifest_specials: bool = True,
# perf/robustness knobs
store: str = "full", # "full" | "pooled" | "both"
reshape_order: str = "C",
vertex_count: int = 5,
infer_dim: bool = True,
strict_shapes: bool = False,
# new perf knobs
finalize_mode: str = "post_mean", # "none" | "post_mean"
cache_pooled: bool = True,
streaming=False,
):
super().__init__(dim)
self.repo_id = str(repo_id)
self._id_to_pooled: Dict[int, np.ndarray] = {} # optional pooled cache
# ---------- load split (columnar, minimal columns) ----------
ds = load_dataset(self.repo_id, split=split)
have = set(ds.column_names)
wanted = ["token_id", "token", "crystal", "volume"]
keep = [c for c in wanted if c in have]
drop = [c for c in ds.column_names if c not in keep]
if drop:
ds = ds.remove_columns(drop)
ds = ds.with_format("numpy", columns=keep)
ids = ds["token_id"] if "token_id" in keep else np.array([], dtype=np.int64)
toks = ds["token"] if "token" in keep else np.array([], dtype=object)
cryst= ds["crystal"] if "crystal" in keep else np.array([], dtype=object)
vols = ds["volume"] if "volume" in keep else None
ids = np.asarray(ids).astype(np.int64, copy=False)
toks = np.asarray(toks)
# --------- shape helpers ----------
def _coerce(raw: Any) -> np.ndarray:
X = np.asarray(raw, np.float32)
if X.ndim == 2:
V, D = int(X.shape[0]), int(X.shape[1])
if V != vertex_count:
raise ValueError(f"Crystal has {V} vertices, expected {vertex_count}.")
if D != self.dim:
if infer_dim: self.dim = D
else: raise ValueError(f"Dim mismatch: got {D}, expected {self.dim}.")
return X
if X.ndim == 1:
n = int(X.size)
if n == vertex_count * self.dim:
return np.reshape(X, (vertex_count, self.dim), order=reshape_order)
if infer_dim and n % vertex_count == 0:
self.dim = n // vertex_count
return np.reshape(X, (vertex_count, self.dim), order=reshape_order)
if n == self.dim:
c = X / (np.abs(X).sum() + 1e-8)
return self._deterministic_pentachoron(c)
raise ValueError(f"Unsupported crystal shape {X.shape if isinstance(X, np.ndarray) else type(X)}.")
def _finalize_if_needed(X: np.ndarray) -> np.ndarray:
if finalize_mode == "none":
return np.asarray(X, np.float32, order="C")
elif finalize_mode == "post_mean":
return self._finalize_crystal(X)
else:
raise ValueError(f"finalize_mode must be 'none' or 'post_mean', got {finalize_mode!r}")
vols_f = np.asarray(vols, dtype=np.float32) if vols is not None else None
# ---------- FAST PATH: flat uniform crystals ----------
# Try to stack into (N, L); succeeds when each row is the same length.
fastpath_ok = False
A = None # (N, L) float32
try:
A = np.stack(cryst) # may raise if jagged / object
if A.ndim == 2 and A.dtype != object:
A = A.astype(np.float32, copy=False)
L = A.shape[1]
if L % vertex_count == 0:
# infer or validate D
D = L // vertex_count
if self.dim != D:
if infer_dim:
self.dim = int(D)
else:
raise ValueError(f"Dim mismatch: got D={D}, expected dim={self.dim}.")
fastpath_ok = True
except Exception:
fastpath_ok = False
if fastpath_ok and A is not None and len(ids) > 0:
# reshape to (N, V, D)
V = vertex_count
D = self.dim
A = A.reshape(-1, V, D, order=reshape_order)
# sort by ids and reduceat to mean duplicates in pure NumPy
order = np.argsort(ids, kind="stable")
ids_sorted = ids[order]
A_sorted = A[order]
vols_sorted = vols_f[order] if vols_f is not None else None
uniq_ids, idx, counts = np.unique(ids_sorted, return_index=True, return_counts=True)
sums = np.add.reduceat(A_sorted, idx, axis=0) # (K, V, D)
means = sums / counts[:, None, None] # (K, V, D)
if vols_sorted is not None:
v_sums = np.add.reduceat(vols_sorted, idx)
v_means = v_sums / counts.astype(np.float32)
else:
v_means = np.ones_like(uniq_ids, dtype=np.float32)
# commit maps
self._token_to_id.clear(); self._id_to_token.clear()
self._id_to_vec.clear(); self._id_to_volume.clear(); self._valid_token_ids.clear()
self._id_to_pooled.clear()
# pick a representative token per id: first occurrence in sorted block
toks_sorted = toks[order]
rep_toks = toks_sorted[idx]
for tid, tok, X_mean, v_m in zip(uniq_ids.tolist(), rep_toks.tolist(), means, v_means.tolist()):
# cache pooled BEFORE finalize to preserve signal
if cache_pooled:
self._id_to_pooled[tid] = X_mean.mean(axis=0).astype(np.float32, copy=False)
X_store = _finalize_if_needed(X_mean)
self._token_to_id[str(tok)] = tid
self._id_to_token[tid] = str(tok)
if store in ("full", "both"):
self._id_to_vec[tid] = np.asarray(X_store, np.float32, order="C")
elif store == "pooled":
# store pooled as embedding if desired
self._id_to_vec[tid] = (self._id_to_pooled[tid] if cache_pooled
else X_mean.mean(axis=0).astype(np.float32, copy=False))
self._id_to_volume[tid] = float(v_m)
self._valid_token_ids.add(tid)
else:
# ---------- FALLBACK: per-row coerce + dict mean ----------
ids_int = ids.tolist()
toks_str = [str(x) for x in toks.tolist()]
vols_f = (vols_f.tolist() if vols_f is not None else [1.0] * len(ids_int))
x_sum: Dict[int, np.ndarray] = {}
v_sum: Dict[int, float] = {}
n_cnt: Dict[int, int] = {}
tok_pref: Dict[int, str] = {}
for tid, tok, raw, vol in zip(ids_int, toks_str, cryst, vols_f):
X = _coerce(raw) # [V,D] float32
if tid not in x_sum:
x_sum[tid] = X.astype(np.float32, copy=True)
v_sum[tid] = float(vol)
n_cnt[tid] = 1
tok_pref[tid] = tok
else:
x_sum[tid] += X
v_sum[tid] += float(vol)
n_cnt[tid] += 1
self._token_to_id.clear(); self._id_to_token.clear()
self._id_to_vec.clear(); self._id_to_volume.clear(); self._valid_token_ids.clear()
self._id_to_pooled.clear()
for tid in x_sum.keys(): # order not critical; add sorted(tids) if you need determinism
X_mean = x_sum[tid] / float(n_cnt[tid])
if cache_pooled:
self._id_to_pooled[tid] = X_mean.mean(axis=0).astype(np.float32, copy=False)
X_store = _finalize_if_needed(X_mean)
tok = tok_pref[tid]
vol_m = v_sum[tid] / float(n_cnt[tid])
self._token_to_id[tok] = tid
self._id_to_token[tid] = tok
if store in ("full", "both"):
self._id_to_vec[tid] = np.asarray(X_store, np.float32, order="C")
elif store == "pooled":
self._id_to_vec[tid] = (self._id_to_pooled[tid] if cache_pooled
else X_mean.mean(axis=0).astype(np.float32, copy=False))
self._id_to_volume[tid] = float(vol_m)
self._valid_token_ids.add(tid)
# ---------- specials ----------
if manifest_specials and base_set:
self._manifest_special_tokens(
base_set=base_set,
create_crystal=create_crystal,
callback=callback,
create_config=create_config or {}
)
# -------- override pooled() to use cache (if present) --------
def pooled(self, token_or_id: Union[str, int], method: str = "mean") -> Optional[np.ndarray]:
# Favor cached pooled when available; fallback to base (computes mean)
tid = token_or_id if isinstance(token_or_id, int) else self._token_to_id.get(token_or_id)
if tid is not None and tid in self._id_to_pooled:
return self._id_to_pooled[tid]
return super().pooled(token_or_id, method=method)
# -------- SP-like surface --------
def encode(self, token: str, *, return_id: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, int]]:
tid = self._token_to_id.get(token)
if tid is None:
unk_id = self._token_to_id.get("<unk>")
if unk_id is None:
raise KeyError(f"Token '{token}' not found and '<unk>' missing.")
X = self._id_to_vec[unk_id]
return (X, unk_id) if return_id else X
X = self._id_to_vec[tid]
return (X, tid) if return_id else X
def get_score(self, token_or_id: Union[str, int]) -> float:
tid = token_or_id if isinstance(token_or_id, int) else self._token_to_id.get(token_or_id, None)
if tid is None or tid not in self._valid_token_ids:
return -100.0
vol = self._id_to_volume.get(tid, 1.0)
return float(np.clip(vol / 10.0, 0.01, 1.0))
# -------- Torch cache ----------
def cache(self, tokens: Union[List[str], Dict[str, int]], device: str = "cpu", dtype: torch.dtype = torch.float32):
tok_list = list(tokens.keys()) if isinstance(tokens, dict) else list(tokens)
mats, pooled, keep = [], [], []
for t in tok_list:
X = self.embedding(t)
v = self.pooled(t)
if X is None or v is None:
continue
mats.append(torch.as_tensor(X, dtype=dtype))
pooled.append(torch.as_tensor(v, dtype=dtype))
keep.append(t)
if not mats:
raise ValueError("No valid tokens found in input.")
return {
"tokens": keep,
"crystals": torch.stack(mats, 0).to(device),
"pooled": torch.stack(pooled, 0).to(device),
}
def _coerce_crystal_shape(
self,
raw: Any,
*,
vertex_count: int,
reshape_order: str,
infer_dim: bool,
strict_shapes: bool
) -> np.ndarray:
"""
Accepts raw crystal data and returns [vertex_count, self.dim] float32 C-order.
Acceptable inputs:
- [vertex_count, D]
- [vertex_count * D] (flat) -> reshaped to [vertex_count, D]
- [D] (pooled center) -> converted by deterministic pentachoron (fallback)
"""
X = np.asarray(raw, dtype=np.float32)
# Already [V, D]
if X.ndim == 2:
V, D = int(X.shape[0]), int(X.shape[1])
if V != vertex_count:
if strict_shapes:
raise ValueError(f"Crystal has {V} vertices, expected {vertex_count}.")
# Gentle fallback: attempt to treat rows as vertices if divisible
if V * D % vertex_count == 0 and infer_dim:
# e.g., [10, D] -> try to collapse/average into [5,D]? Not safe.
# Safer: hard error to avoid silent geometry change.
raise ValueError(f"Unexpected vertex rows {V}; refusing to coerce silently.")
else:
raise ValueError(f"Crystal has {V} vertices, expected {vertex_count}.")
# Update dim if needed
if D != self.dim:
if infer_dim:
self.dim = D
else:
raise ValueError(f"Dim mismatch: got D={D}, expected dim={self.dim}.")
# Ensure mean-centered (finalize handles centering)
return X
# Flat [V*D]
if X.ndim == 1:
n = int(X.size)
# Exact match for flat crystal
if n == vertex_count * self.dim:
return np.reshape(X, (vertex_count, self.dim), order=reshape_order)
# Infer D from total length if divisible
if infer_dim and n % vertex_count == 0:
inferred = n // vertex_count
self.dim = int(inferred)
return np.reshape(X, (vertex_count, self.dim), order=reshape_order)
# Pooled [D]: inflate deterministically to [V, D]
if n == self.dim:
c = X / (np.abs(X).sum() + 1e-8) # L1
return self._deterministic_pentachoron(c)
if strict_shapes:
raise ValueError(
f"Cannot coerce crystal of length {n}. "
f"Expected {vertex_count*self.dim} (flat) or {self.dim} (pooled)."
)
# Conservative fallback: treat as pooled center with inferred D if reasonable
if infer_dim and n > 0:
self.dim = n
c = X / (np.abs(X).sum() + 1e-8)
return self._deterministic_pentachoron(c)
raise ValueError(f"Unsupported crystal shape {X.shape} (ndim={X.ndim}).")
# -------- Introspection --------
def describe(self) -> Dict[str, Union[str, int]]:
return {"repo": self.repo_id, "dimension": self.dim, "vocab_size": self.vocab_size()}
from __future__ import annotations
import torch
import numpy as np
from abc import ABC, abstractmethod
from typing import Dict, Union, Tuple, Optional, Callable, Any, List
import warnings
from collections import OrderedDict
import datasets
from datasets import load_dataset
# Global flag for warning suppression
SILENT_MODE = False
def set_silent_mode(silent: bool):
"""Set global silent mode for token synthesis warnings"""
global SILENT_MODE
SILENT_MODE = silent
class LRUCache(OrderedDict):
"""Simple LRU cache implementation"""
def __init__(self, maxsize=128):
super().__init__()
self.maxsize = maxsize
def __getitem__(self, key):
value = super().__getitem__(key)
self.move_to_end(key)
return value
def __setitem__(self, key, value):
if key in self:
self.move_to_end(key)
super().__setitem__(key, value)
if len(self) > self.maxsize:
oldest = next(iter(self))
del self[oldest]
class LazyGeometricVocab(GeometricVocab):
"""
Lazy-loading geometric vocabulary that loads tokens on demand.
Maintains a small working set in memory with LRU eviction.
Supports automatic token synthesis for missing tokens.
"""
def __init__(
self,
repo_id: str,
dim: int,
*,
name: str = "unicode_100d", # Updated default to match new structure
split: str = "train", # Updated default to "train"
stream: bool = True, # Use streaming by default to avoid bulk downloads
base_set: Optional[Dict[str, int]] = None,
create_config: Optional[Dict[str, Any]] = None,
create_crystal: Optional[Callable] = None,
callback: Optional[Callable] = None,
manifest_specials: bool = True,
# Lazy loading parameters
cache_size: int = 1000, # Max tokens to keep in memory
preload_tokens: Optional[List[str]] = None, # Critical tokens to preload
index_cache_path: Optional[str] = None, # Path to save/load index
# Tokenization
tokenizer: Optional[Callable[[str], List[str]]] = None, # Custom tokenizer
# Synthesis settings
silent: bool = False, # Suppress synthesis warnings
# Performance knobs
store: str = "full",
reshape_order: str = "C",
vertex_count: int = 5,
infer_dim: bool = True,
finalize_mode: str = "post_mean",
cache_pooled: bool = True,
):
super().__init__(dim)
self.repo_id = repo_id
self.name = name
self.split = split
self.stream = stream
self.vertex_count = vertex_count
self.reshape_order = reshape_order
self.infer_dim = infer_dim
self.finalize_mode = finalize_mode
self.store = store
self.cache_pooled = cache_pooled
self.silent = silent
# Initialize pooled dictionary that may be missing from parent class
if not hasattr(self, '_id_to_pooled'):
self._id_to_pooled = {}
# For synthesis
self.create_crystal_fn = create_crystal
self.callback_fn = callback
self.create_config = create_config or {}
self._synthesized_tokens: set = set()
self._next_synthetic_id = -1 # Use negative IDs for synthetic tokens
# Tokenizer - default to simple split
self.tokenizer = tokenizer or (lambda s: s.split())
# LRU caches for lazy loading
self._crystal_cache = LRUCache(maxsize=cache_size)
self._pooled_lru = LRUCache(maxsize=cache_size * 2) # Pooled vectors are smaller
# Load dataset but don't fetch data yet
self._dataset = None
self._dataset_stream = None
self._token_index: Dict[str, List[int]] = {} # token -> [row indices]
self._id_index: Dict[int, List[int]] = {} # token_id -> [row indices]
self._row_data: Dict[int, dict] = {} # row -> cached data
# Initialize index
self._build_index(split, name)
# Pre-load base characters for synthesis
self._preload_synthesis_base()
# Preload critical tokens if specified
if preload_tokens:
self._preload(preload_tokens)
# Manifest special tokens
if manifest_specials and base_set:
self._manifest_special_tokens(
base_set=base_set,
create_crystal=create_crystal,
callback=callback,
create_config=create_config or {}
)
def _preload_synthesis_base(self):
"""Pre-load basic ASCII characters needed for synthesis"""
# Essential characters that are commonly used in token synthesis
base_chars = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,!?-_()[]{}:;'\"")
print(f"Pre-loading {len(base_chars)} base characters for synthesis...")
loaded = 0
for char in base_chars:
tid = self._token_to_id.get(char)
if tid:
# Pre-load this character's embedding
if self._load_crystal(tid) is not None:
loaded += 1
print(f"Loaded {loaded} base characters")
def _build_index(self, split: str, name: str):
"""Build token/id index without loading crystal data"""
print(f"Building index for {self.repo_id}/{name}/{split}...")
if self.stream:
try:
# Use streaming to avoid downloading all splits
# Don't specify columns in streaming mode to avoid schema issues
self._dataset_stream = load_dataset(
self.repo_id,
name=name,
split=split,
streaming=True
)
# Build index from streaming dataset
for idx, row in enumerate(self._dataset_stream):
token = str(row["token"])
token_id = int(row["token_id"])
# Token index
if token not in self._token_index:
self._token_index[token] = []
self._token_index[token].append(idx)
# ID index
if token_id not in self._id_index:
self._id_index[token_id] = []
self._id_index[token_id].append(idx)
# Update mappings (use first occurrence)
if token not in self._token_to_id:
self._token_to_id[token] = token_id
self._id_to_token[token_id] = token
self._valid_token_ids.add(token_id)
print(f"Index built (streaming): {len(self._token_index)} unique tokens")
except Exception as e:
print(f"Streaming failed: {e}")
print("Falling back to non-streaming mode...")
self.stream = False
# Recursive call with streaming disabled
self._build_index(split, name)
else:
# Non-streaming mode - load dataset normally
try:
# Try with data_files to load only specific split
data_files = f"data/{name}/{split}-*.parquet"
ds = load_dataset(
self.repo_id,
data_files=data_files,
split="train"
)
except:
# Fallback to normal loading
try:
ds = load_dataset(
self.repo_id,
name=name,
split=split
)
except Exception as e:
print(f"Failed to load dataset: {e}")
raise
# Build indices
for idx, row in enumerate(ds):
token = str(row["token"])
token_id = int(row["token_id"])
# Token index
if token not in self._token_index:
self._token_index[token] = []
self._token_index[token].append(idx)
# ID index
if token_id not in self._id_index:
self._id_index[token_id] = []
self._id_index[token_id].append(idx)
# Update mappings (use first occurrence)
if token not in self._token_to_id:
self._token_to_id[token] = token_id
self._id_to_token[token_id] = token
self._valid_token_ids.add(token_id)
# Store dataset reference (will lazy load full data)
self._dataset = ds
print(f"Index built: {len(self._token_index)} unique tokens")
def _load_row(self, row_idx: int) -> dict:
"""Load a single row from dataset"""
if row_idx in self._row_data:
return self._row_data[row_idx]
# If streaming, need to load the full dataset on first data access
if self.stream and self._dataset is None:
print(f"Loading full dataset for {self.repo_id}/{self.name}/{self.split}...")
try:
# Try with data_files first
data_files = f"data/{self.name}/{self.split}-*.parquet"
self._dataset = load_dataset(
self.repo_id,
data_files=data_files,
split="train"
)
except:
# Fallback to normal loading
self._dataset = load_dataset(
self.repo_id,
name=self.name,
split=self.split
)
if self._dataset is None:
raise RuntimeError("Dataset not initialized")
row = self._dataset[row_idx]
self._row_data[row_idx] = row
return row
def _load_crystal(self, token_id: int) -> Optional[np.ndarray]:
"""Load and aggregate crystal for a token_id"""
if token_id in self._crystal_cache:
return self._crystal_cache[token_id]
if token_id not in self._id_index:
return None
row_indices = self._id_index[token_id]
crystals = []
volumes = []
for idx in row_indices:
row = self._load_row(idx)
# Parse crystal
raw_crystal = row.get("crystal")
if raw_crystal is not None:
X = self._coerce_crystal(raw_crystal)
crystals.append(X)
# Get volume if available
vol = row.get("volume", 1.0)
volumes.append(float(vol))
if not crystals:
return None
# Average multiple occurrences
if len(crystals) == 1:
X_final = crystals[0]
vol_final = volumes[0]
else:
X_final = np.mean(crystals, axis=0)
vol_final = np.mean(volumes)
# Finalize
if self.finalize_mode == "post_mean":
X_final = self._finalize_crystal(X_final)
# Cache based on store mode
if self.store in ("full", "both"):
self._crystal_cache[token_id] = X_final
self._id_to_vec[token_id] = X_final
# Cache pooled if requested
if self.cache_pooled:
pooled = X_final.mean(axis=0)
self._pooled_lru[token_id] = pooled
if token_id not in self._id_to_pooled:
self._id_to_pooled[token_id] = pooled
# Store volume
self._id_to_volume[token_id] = vol_final
return X_final
def _coerce_crystal(self, raw: Any) -> np.ndarray:
"""Convert raw crystal data to proper shape"""
X = np.asarray(raw, dtype=np.float32)
if X.ndim == 2:
V, D = X.shape
if V != self.vertex_count:
raise ValueError(f"Expected {self.vertex_count} vertices, got {V}")
if D != self.dim:
if self.infer_dim:
self.dim = D
else:
raise ValueError(f"Dimension mismatch: {D} vs {self.dim}")
return X
if X.ndim == 1:
n = X.size
if n == self.vertex_count * self.dim:
return X.reshape((self.vertex_count, self.dim), order=self.reshape_order)
if self.infer_dim and n % self.vertex_count == 0:
self.dim = n // self.vertex_count
return X.reshape((self.vertex_count, self.dim), order=self.reshape_order)
if n == self.dim:
# Pooled vector - expand to crystal
c = X / (np.abs(X).sum() + 1e-8)
return self._deterministic_pentachoron(c)
raise ValueError(f"Cannot coerce crystal shape {X.shape}")
def _synthesize_token(self, token: str) -> int:
"""Synthesize a new token embedding on-the-fly with fallback for missing chars."""
# Generate a new ID for synthetic token
tid = self._next_synthetic_id
self._next_synthetic_id -= 1
# Warn user unless silenced
if not self.silent and not SILENT_MODE:
warnings.warn(
f"Token '{token}' synthesized - ensure you synthesize your tokens ahead of time.",
UserWarning,
stacklevel=3
)
# Track as synthesized
self._synthesized_tokens.add(token)
# Try to use character-based synthesis first
try:
# Check if all characters are available
missing_chars = []
for char in token:
if char not in self._token_to_id and char not in self._char_cache:
missing_chars.append(char)
# If missing chars, try to load or synthesize them first
if missing_chars:
for char in missing_chars:
char_tid = self._token_to_id.get(char)
if char_tid:
# Try to load it
self._load_crystal(char_tid)
else:
# Create a simple embedding for this character
self._synthesize_simple_char(char)
# Now try the full synthesis
helpers = self._helpers()
cfg = {
"dim": self.dim,
"pool_type": self.create_config.get("pool_type", "unicode"),
"data": {"token": token, "token_id": tid, "origin": "synthetic"},
"helpers": helpers,
}
if self.create_crystal_fn is not None:
product = self.create_crystal_fn(cfg, self.callback_fn)
else:
product = self._default_create_crystal(cfg, self._default_unicode_callback)
X, prov = self._finalize_crystal_and_provenance(product, cfg)
except Exception as e:
# Fallback to simple random synthesis
print(f"Character-based synthesis failed for '{token}': {e}. Using random synthesis.")
X = self._synthesize_random_crystal(token)
prov = {"source": "synthetic_random", "token": token}
prov["synthetic"] = True
# Register in all maps
self._token_to_id[token] = tid
self._id_to_token[tid] = token
self._id_to_vec[tid] = X.astype(np.float32, copy=False, order='C')
self._id_to_provenance[tid] = prov
self._valid_token_ids.add(tid)
self._id_to_volume[tid] = 1.0
# Cache
self._crystal_cache[tid] = X
if self.cache_pooled:
pooled = X.mean(axis=0)
self._pooled_lru[tid] = pooled
self._id_to_pooled[tid] = pooled
return tid
def _synthesize_simple_char(self, char: str):
"""Create a simple deterministic embedding for a single character"""
import hashlib
# Use character's unicode codepoint for deterministic generation
if len(char) == 1:
seed = ord(char)
else:
seed = int(hashlib.md5(char.encode()).hexdigest()[:8], 16)
np.random.seed(seed)
# Generate a simple vector based on character properties
vec = np.random.randn(self.dim).astype(np.float32)
vec = vec / (np.abs(vec).sum() + 1e-8) # L1 normalize
# Cache it
self._char_cache[char] = vec
def _synthesize_random_crystal(self, token: str) -> np.ndarray:
"""Fallback: create a deterministic random crystal based on token string"""
import hashlib
# Create deterministic seed from token
seed = int(hashlib.md5(token.encode()).hexdigest()[:8], 16)
np.random.seed(seed)
# Generate a random crystal
X = np.random.randn(self.vertex_count, self.dim).astype(np.float32)
X = self._finalize_crystal(X)
return X
def _preload(self, tokens: List[str]):
"""Preload specific tokens into cache"""
print(f"Preloading {len(tokens)} tokens...")
for token in tokens:
tid = self._token_to_id.get(token)
if tid:
self._load_crystal(tid)
# Override base methods to use lazy loading with synthesis
def embedding(self, token_or_id: Union[str, int], generate: bool = False) -> Optional[np.ndarray]:
"""Get embedding, loading if necessary, synthesizing if requested"""
# Handle token ID input
if isinstance(token_or_id, int):
tid = token_or_id
token = self._id_to_token.get(tid)
else:
token = token_or_id
tid = self._token_to_id.get(token)
if tid is not None:
# Check cache first
if tid in self._id_to_vec:
return self._id_to_vec[tid]
# Load on demand
return self._load_crystal(tid)
# Token not found - synthesize if requested
if generate and token is not None:
tid = self._synthesize_token(token)
return self._id_to_vec[tid]
return None
def pooled(self, token_or_id: Union[str, int], method: str = "mean", generate: bool = False) -> Optional[np.ndarray]:
"""Get pooled vector, loading if necessary, synthesizing if requested"""
# Handle token ID input
if isinstance(token_or_id, int):
tid = token_or_id
token = self._id_to_token.get(tid)
else:
token = token_or_id
tid = self._token_to_id.get(token)
if tid is not None:
# Check pooled cache
if tid in self._pooled_lru:
return self._pooled_lru[tid]
if tid in self._id_to_pooled:
return self._id_to_pooled[tid]
# Load crystal and compute pooled
X = self.embedding(tid, generate=False)
if X is not None:
if method == "mean":
pooled = X.mean(axis=0)
self._pooled_lru[tid] = pooled
return pooled
elif method == "first":
return X[0]
elif method == "sum":
return X.sum(axis=0)
else:
raise ValueError(f"Unknown pooling method: {method}")
# Token not found - synthesize if requested
if generate and token is not None:
tid = self._synthesize_token(token)
return self.pooled(tid, method=method, generate=False)
return None
def encode(self, token: str, *, return_id: bool = False, generate: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, int]]:
"""Encode token, loading if necessary, synthesizing if requested"""
tid = self._token_to_id.get(token)
if tid is None:
if generate:
# Synthesize new token
tid = self._synthesize_token(token)
X = self._id_to_vec[tid]
else:
# Fallback to UNK
unk_id = self._token_to_id.get("<unk>")
if unk_id is None:
# No UNK token - try to synthesize if allowed
if generate:
tid = self._synthesize_token(token)
X = self._id_to_vec[tid]
else:
raise KeyError(f"Token '{token}' not found and no <unk> token available")
else:
X = self.embedding(unk_id, generate=False)
tid = unk_id
else:
X = self.embedding(tid, generate=False)
if X is None:
raise RuntimeError(f"Failed to load embedding for token '{token}'")
return (X, tid) if return_id else X
def get_score(self, token_or_id: Union[str, int]) -> float:
"""Get token score"""
tid = token_or_id if isinstance(token_or_id, int) else self._token_to_id.get(token_or_id)
if tid is None or tid not in self._valid_token_ids:
return -100.0
# Load volume if needed
if tid not in self._id_to_volume:
self._load_crystal(tid)
vol = self._id_to_volume.get(tid, 1.0)
return float(np.clip(vol / 10.0, 0.01, 1.0))
def encode_batch(self, tokens: Union[str, List[str]],
*, return_ids: bool = False,
prefetch: bool = True,
generate: bool = False) -> Union[List[np.ndarray], Tuple[List[np.ndarray], List[int]]]:
"""
Encode a batch of tokens efficiently.
Args:
tokens: Either a string (will be tokenized) or list of token strings
return_ids: Whether to return token IDs alongside embeddings
prefetch: Whether to prefetch all tokens before encoding
generate: If True, synthesize missing tokens
Returns:
List of embeddings, optionally with list of token IDs
"""
# Handle string input - tokenize it
if isinstance(tokens, str):
tokens = self.tokenizer(tokens)
if not isinstance(tokens, list):
raise TypeError(f"Expected str or List[str], got {type(tokens)}")
# Track which tokens need synthesis
tokens_to_synthesize = []
if generate:
for token in tokens:
if token not in self._token_to_id:
tokens_to_synthesize.append(token)
# Warn about batch synthesis if needed
if tokens_to_synthesize and not self.silent and not SILENT_MODE:
warnings.warn(
f"{len(tokens_to_synthesize)} tokens synthesized - ensure you synthesize your tokens ahead of time. "
f"Synthesized: {tokens_to_synthesize[:5]}{'...' if len(tokens_to_synthesize) > 5 else ''}",
UserWarning,
stacklevel=2
)
# Prefetch existing tokens if requested
if prefetch:
self._prefetch_batch([t for t in tokens if t in self._token_to_id])
# Encode all tokens
embeddings = []
ids = []
for token in tokens:
if return_ids:
emb, tid = self.encode(token, return_id=True, generate=generate)
embeddings.append(emb)
ids.append(tid)
else:
emb = self.encode(token, return_id=False, generate=generate)
embeddings.append(emb)
return (embeddings, ids) if return_ids else embeddings
def _prefetch_batch(self, tokens: List[str]):
"""
Prefetch a batch of tokens efficiently.
"""
# Collect all token IDs that need loading
tokens_to_load = []
for token in tokens:
tid = self._token_to_id.get(token)
if tid and tid not in self._crystal_cache and tid not in self._id_to_vec:
tokens_to_load.append(tid)
if not tokens_to_load:
return # Everything already cached
# Load crystals for each token
for tid in tokens_to_load:
self._load_crystal(tid)
def cache_stats(self) -> Dict[str, Any]:
"""Get cache statistics"""
stats = super().cache_stats()
stats.update({
"crystal_cache_size": len(self._crystal_cache),
"pooled_lru_size": len(self._pooled_lru),
"rows_cached": len(self._row_data),
"tokens_indexed": len(self._token_index),
"ids_indexed": len(self._id_index),
"synthesized_tokens": len(self._synthesized_tokens),
})
return stats
def evict_from_cache(self, tokens: Optional[List[str]] = None):
"""Manually evict tokens from cache to free memory"""
if tokens is None:
# Clear all caches
self._crystal_cache.clear()
self._pooled_lru.clear()
self._id_to_vec.clear()
self._id_to_pooled.clear()
self._row_data.clear()
else:
# Evict specific tokens
for token in tokens:
tid = self._token_to_id.get(token)
if tid:
self._crystal_cache.pop(tid, None)
self._pooled_lru.pop(tid, None)
self._id_to_vec.pop(tid, None)
self._id_to_pooled.pop(tid, None)
def get_synthesized_tokens(self) -> List[str]:
"""Get list of all tokens that were synthesized at runtime"""
return list(self._synthesized_tokens)
def is_synthesized(self, token: str) -> bool:
"""Check if a token was synthesized at runtime"""
return token in self._synthesized_tokens
# For 100-dimensional embeddings
vocab = LazyGeometricVocab(
repo_id="AbstractPhil/geometric-vocab",
dim=64,
name="unicode_64d", # Specifies the dimension config
split="train", # Now always "train"
stream=False,
cache_size=1024,
silent=False
)
FROZEN_VOCAB = [] |