API Reference¶
triadic_head¶
triadic_head
¶
triadic-head — Drop-in triadic projection head for any HuggingFace transformer.
Adds interpretable prime-factor semantic signatures to language models at zero language cost. A single linear layer (n_embd -> n_bits) produces discrete prime composites that enable exact algebraic operations: subsumption, composition, analogy, and gap analysis.
Quick start
from triadic_head import TriadicWrapper
model = TriadicWrapper("gpt2", n_bits=64) sigs = model.encode(["king", "queen", "dog"]) result = model.compare("king", "queen")
Algebra Module¶
Pure Python module with zero external dependencies. Provides exact algebraic operations on prime-factor signatures.
triadic_head.algebra
¶
Prime-factor algebra for neurosymbolic semantic operations.
Provides exact algebraic operations (subsumption, composition, gap analysis) on prime-factor signatures — things impossible with cosine similarity.
Zero external dependencies.
PrimeMapper
¶
Maps continuous projections (tanh outputs in [-1, 1]) to composite prime integers.
Each bit position is assigned a unique prime. If projection[i] > 0, prime[i] is included in the composite product.
Example
projections = [0.5, -0.2, 0.8, 0.1] (4 bits) primes = [2, 3, 5, 7 ] composite = 2 * 5 * 7 = 70 (bits 0, 2, 3 are positive)
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
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 | |
encode(projections) -> int
¶
Convert projection values to a composite prime integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
projections
|
sequence of floats (tanh outputs in [-1, 1]) or a 1D tensor. |
required |
Returns:
| Type | Description |
|---|---|
int
|
int — composite prime product. |
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | |
get_bits(projections) -> List[int]
¶
Return binary bit pattern from projections.
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
110 111 112 | |
explain(composite: int) -> Dict
¶
Decompose a composite into its constituent prime factors.
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
similarity(a: int, b: int) -> float
¶
Jaccard similarity over prime factor sets.
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
130 131 132 | |
TriadicValidator
¶
Verifies semantic relationships using prime-factor algebra.
Three operations IMPOSSIBLE with cosine similarity
- Subsumption — Does concept A contain all features of B?
- Composition — Create a concept with features of A and B.
- Gap Analysis — Exactly WHICH features differ between A and B?
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
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 | |
subsumes(a: int, b: int) -> bool
staticmethod
¶
Does concept A contain ALL semantic features of B? (A % B == 0)
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
149 150 151 152 153 154 | |
compose(*concepts: int) -> int
staticmethod
¶
Combine features from multiple concepts (LCM).
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
156 157 158 159 160 161 162 | |
explain_gap(a: int, b: int) -> Dict
staticmethod
¶
Explain exactly WHY two concepts differ.
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
similarity(a: int, b: int) -> float
staticmethod
¶
Jaccard similarity over prime factor sets. Range: [0.0, 1.0].
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
181 182 183 184 185 186 187 188 189 | |
analogy(a: int, b: int, c: int) -> int
staticmethod
¶
Analogy: A is to B as C is to ?
Computes the transformation from A->B (factors removed/added), then applies it to C to find D.
D = (C / GCD(C, only_in_a)) * only_in_b where only_in_a = A/GCD(A,B) and only_in_b = B/GCD(A,B)
Two steps: (1) remove A-specific factors from C, (2) add B-specific.
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
sieve_primes(limit: int) -> List[int]
¶
Return all primes up to limit via Sieve of Eratosthenes.
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
18 19 20 21 22 23 24 25 26 27 28 | |
nth_prime(n: int) -> int
¶
Return the nth prime (1-indexed: nth_prime(1) = 2).
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
34 35 36 37 38 39 40 41 42 43 44 45 | |
prime_factors(n: int) -> List[int]
¶
Return sorted list of unique prime factors of n.
Source code in triadic-head-src/triadic-head/triadic_head/algebra.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
Wrapper Module¶
PyTorch wrapper for HuggingFace transformers. Adds a triadic projection head to any causal language model.
triadic_head.wrapper
¶
TriadicWrapper — Drop-in triadic projection head for any HuggingFace transformer.
Usage
from triadic_head import TriadicWrapper
model = TriadicWrapper("gpt2", n_bits=64) model.freeze_backbone()
... train phase 1 (triadic head only) ...¶
model.unfreeze_last_n(2)
... train phase 2 (joint optimization) ...¶
sigs = model.encode(["king", "queen", "dog"]) model.compare("king", "queen") # -> 0.89
TriadicHead
¶
Bases: Module
Single linear projection: hidden_states -> tanh -> n_bits continuous values.
This is the only new parameter added to the backbone model. For GPT-2 (768D, 64 bits): 768 * 64 = 49,152 parameters.
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
forward(hidden_states: torch.Tensor) -> torch.Tensor
¶
(B, T, n_embd) -> (B, T, n_bits) in [-1, 1].
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
113 114 115 | |
TriadicWrapper
¶
Bases: Module
Wraps any HuggingFace causal LM with a triadic projection head.
The wrapper adds a single linear layer (n_embd -> n_bits) that produces discrete prime-factor signatures alongside normal language model outputs. Training uses a multi-component triadic loss that transfers semantic structure from the model's own embeddings to the triadic head.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Union[str, Module]
|
HuggingFace model instance or model name string (e.g. "gpt2"). |
required |
n_bits
|
int
|
Number of triadic bits (default 64). Each bit maps to a prime. |
64
|
align_mode
|
str
|
Alignment loss type — "mse", "rank", or "infonce". Use "infonce" for pre-trained models, "mse" for from-scratch. |
'infonce'
|
device
|
Optional[str]
|
Device to place model on (auto-detected if None). |
None
|
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
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 | |
config(**kwargs) -> Dict
¶
View or update model configuration.
Call with no arguments to view current config. Pass keyword arguments to update:
model.config(align_mode='rank', n_bits=32)
Changeable settings
align_mode: 'mse' | 'rank' | 'infonce'
Read-only (shown but not changeable): n_bits, n_embd, backbone, block_size, triadic_params, total_params
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
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 | |
freeze_backbone()
¶
Freeze entire backbone. Only triadic head receives gradients.
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
207 208 209 210 211 212 | |
unfreeze_last_n(n: int = 2)
¶
Unfreeze the last N transformer layers + final layer norm.
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
214 215 216 217 218 219 220 221 222 223 | |
unfreeze_all()
¶
Unfreeze everything.
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
225 226 227 228 | |
forward(input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None)
¶
Forward pass through backbone + triadic head.
Returns:
| Name | Type | Description |
|---|---|---|
logits |
(B, T, vocab_size) |
|
triadic_proj |
(B, T, n_bits) in [-1, 1] |
|
lang_loss |
scalar or None |
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
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 | |
triadic_loss(triadic_proj: torch.Tensor, input_ids: Optional[torch.Tensor] = None, alpha: float = 0.05, entropy_weight: float = 1.0, align_weight: float = 5.0, align_mode: Optional[str] = None) -> torch.Tensor
¶
Compute multi-component triadic loss.
Components
- Diversity — each bit should fire ~50% of the time.
- Contrastive — different sequences should produce different signatures.
- Entropy — prevent dead bits (bits stuck at +1 or -1).
- Embedding alignment — transfer semantic structure from embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
triadic_proj
|
Tensor
|
(B, T, n_bits) from forward(). |
required |
input_ids
|
Optional[Tensor]
|
(B, T) needed for alignment loss. |
None
|
alpha
|
float
|
Weight of total triadic loss (default 0.05, DO NOT exceed 0.10). |
0.05
|
entropy_weight
|
float
|
Weight for entropy term (default 1.0). |
1.0
|
align_weight
|
float
|
Weight for alignment term (default 5.0). |
5.0
|
align_mode
|
Optional[str]
|
Override self.align_mode for this call. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Weighted triadic loss scalar (already multiplied by alpha). |
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
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 | |
encode(texts: Union[str, List[str]], tokenizer=None) -> Dict[str, dict]
¶
Encode text(s) to prime-factor signatures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
texts
|
Union[str, List[str]]
|
Single string or list of strings. |
required |
tokenizer
|
HuggingFace tokenizer. If None, uses AutoTokenizer matching the backbone model. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, dict]
|
Dict mapping each text to: - 'composite': int (prime product) - 'bits': List[int] (binary pattern) - 'projection': List[float] (raw tanh values) - 'n_active': int (number of active bits) |
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
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 | |
compare(text_a: str, text_b: str, tokenizer=None) -> Dict
¶
Compare two texts using prime-factor algebra.
Returns:
| Type | Description |
|---|---|
Dict
|
Dict with 'similarity', 'shared_factors', 'only_in_a', 'only_in_b'. |
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 | |
validate(tokenizer=None, word_groups: Optional[Dict[str, List[str]]] = None, verbose: bool = True, training_steps: int = 0) -> Dict
¶
Run diagnostic checks to verify triadic head training quality.
Checks
- Diversity — are signatures unique? (>75% = PASS)
- Active bits — are enough bits firing? (15-85% = PASS)
- Semantic ordering — related words more similar than unrelated? (gap > 0 = PASS)
- Random baseline — is the gap significantly above what random bits would produce?
Also provides per-group breakdown so you can see which semantic categories the model handles well and which need more training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
HuggingFace tokenizer (auto-loaded if None). |
None
|
|
word_groups
|
Optional[Dict[str, List[str]]]
|
Custom word groups to test, e.g. {"animals": ["dog", "cat"], "colors": ["red", "blue"]}. Uses built-in groups if None. |
None
|
verbose
|
bool
|
Print results to console. |
True
|
training_steps
|
int
|
Total training steps completed (for guidance messages). |
0
|
Returns:
| Type | Description |
|---|---|
Dict
|
Dict with check results, per-group breakdown, random baseline, |
Dict
|
overall PASS/FAIL, config snapshot, and all signatures. |
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
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 | |
explore(words: List[str], tokenizer=None, top_k: int = 0, threshold: Optional[float] = None, show_factors: bool = False, verbose: bool = True) -> Dict
¶
Full audit of relationships between words with similarity matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
words
|
List[str]
|
List of words/phrases to compare. |
required |
tokenizer
|
HuggingFace tokenizer (auto-loaded if None). |
None
|
|
top_k
|
int
|
Show only top-K and bottom-K pairs (0 = show ALL pairs). |
0
|
threshold
|
Optional[float]
|
If set, flag pairs above this similarity for review. |
None
|
show_factors
|
bool
|
Show shared/unique prime factors for every pair. |
False
|
verbose
|
bool
|
Print results to console. |
True
|
Returns:
| Type | Description |
|---|---|
Dict
|
Dict with similarity matrix, ranked pairs, signatures, and flagged pairs. |
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
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 | |
generate(input_ids, max_new_tokens=100, temperature=0.7, top_k=50)
¶
Autoregressive text generation.
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 | |
triadic_params() -> int
¶
Number of parameters in the triadic head only.
Source code in triadic-head-src/triadic-head/triadic_head/wrapper.py
1043 1044 1045 | |