Late Interaction Topic Models
Most topic models in Turftopic represent a corpus on the level of documents. Late interaction or multi-vector topic models are different, as they can make use of embeddings of smaller units of text. We term these units Spans.
Spans can take many forms, and we let the user define, what unit they wish to do their analyses on e.g.:
- The default unit is a token, tokens are determined by the language model that you use to produce embeddings for the topic model (aka the Encoder).
- You can use sliding windows of tokens, these are somewhat larger units, capturing more meaning at once, reducing the number of vectors to be processed.
- Sentences are also a natural boundary for Spans.
- Anything else...
To learn more about Spans, check out the Span extraction page.
Usage Example
You can use a late model in Turftopic very similar to any other model.
There is, however, one big difference: since there are an uneven number of words in documents, it is also very likely that there is an unequal number of spans. This means that we cannot use a regular array without padding or truncation. Turftopic solves this problem with Ragged Arrays. Ragged arrays are expressed as regular Python objects, and all you have to know for now is that, instead of just a single embedding or document-topic matrix, we now pass around both a ragged matrix and the character Offsets of the spans in the document.
In this example we will use vSLDA:
from turftopic import vSLDA
# vSLDA, by default, is a sentence-level topic model
model = vSLDA(
10,
encode_kwargs=dict(show_progress_bar=True),
n_iter=50,
span_extractor="sentence"
)
# The first object is a ragged array of the span-topic proportions
# the second one is a list of (span_start, span_end) tuples for each span in the document
doc_topic, offsets = model.fit_transform(corpus)
model.print_topics()
| Topic ID | Highest Ranking |
|---|---|
| 0 | alt, cobb, tek, vice, edu, bobbe, april, series, alexia, lis |
| 1 | physics, evolution, main, opinions, objective, agreed, scientists, model, petri, cheers |
| 2 | bank, germany, uiuc, access, pay, illinois, programs, straight, cheers, wide |
| 3 | motivated, jews, stalin, imo, wars, cheers, petri, wide, failed, killed |
| 4 | morality, moral, animals, cruel, goal, immoral, actions, society, natural, crime |
| 5 | text, texts, versions, mark, logically, john, language, copies, valid, essentially |
| 6 | islam, qur, rushdie, islamic, muslim, khomeini, muslims, fatwa, quran, secular |
| 7 | jesus, paul, liar, church, christ, young, believed, biblical, existed, believing |
| 8 | military, sell, war, arabia, saudi, figure, water, regards, east, nation |
| 9 | atheism, atheists, atheist, exist, god, belief, gods, faq, existence, faith |
Model Interpretation
Most of the same interpretation utilities are available when it comes to late interaction models as with regular ones. To learn more about those, check out the Interpreting and Visualizing Models page.
Top Spans
So far the only utilities specifically related to late interaction models are top span extraction. Top spans can be printed, or exported in different formats:
model.print_representative_spans(
4, corpus, document_topic_matrix=doc_topic, offsets=offsets
)
model.representative_spans_df(
4, corpus, document_topic_matrix=doc_topic, offsets=offsets
)
model.export_representative_spans(
4, corpus, document_topic_matrix=doc_topic, offsets=offsets, format="markdown"
)
model.export_representative_spans(
4, corpus, document_topic_matrix=doc_topic, offsets=offsets, format="latex"
)
model.export_representative_spans(
4, corpus, document_topic_matrix=doc_topic, offsets=offsets, format="csv"
)
| Span | Score |
|---|---|
| Animals of the same species could kill each other arbitarily, but they don't. | 1.00 |
| In a natural sense, it is not at all immoral to harm another species (as long as it doesn't adversely affect your own, I guess). | 1.00 |
| .. So, only intelligent beings can be moral, even if the bahavior of other beings mimics theirs? | 1.00 |
| Well I agree with you in the sense that they have no "moral" right to inflict these rules, but there is one thing I might add: at the very least, almost everybody wants to avoid pain, and | |
| if that means sacrificing some stuff for a herd morality, then so be it. | 1.00 |
| ... |
API Reference
Abstract Base Class
turftopic.late.LateModel
Bases: ContextualModel, TransformerMixin
Source code in turftopic/late.py
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 | |
pooling = None
class-attribute
instance-attribute
Base class for late interaction (multi-vector) topic models.
Attributes:
| Name | Type | Description |
|---|---|---|
span_extractor |
SpanExtractor or "sentence", default None
|
Object that extracts arbitrary spans from a piece of text. These spans will then be used to pool token embeddings. This could for instance be a SentenceSeparator. |
include_edge_tokens |
bool, default True
|
Indicates whether the tokens on the edges of spans (ones that go over the span boundary) should be included in the span embedding. Ignored when not using a span extractor. |
window_size |
int, default None
|
Size of the sliding window to average tokens over. If None, documents will be represented at a token level. Ignored when span_extractor is not None. |
step_size |
int, default None
|
Step size of the window. If (step_size == None) or (step_size == window_size), then windows are separate. If step_size < window_size, windows will overlap. If step_size > window_size, there will be gaps between the windows. In this case, we throw a warning, as this is probably unintended behaviour. Ignored when span_extractor is not None. |
pooling |
Callable, default None
|
Indicates whether and how to pool document-topic matrices.
If None, multi-vector topic proportions are returned in a ragged array.
If Callable, multiple vectors are averaged with the callable in each document.
You could for example take the mean by specifying |
encode_documents(raw_documents)
Encodes documents into a flat embedding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_documents |
list[str]
|
List of documents. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Document embeddings. |
Source code in turftopic/late.py
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 | |
encode_late(raw_documents)
Encodes spans in all documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_documents |
list[str]
|
List of documents. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
span_embeddings |
list[ndarray]
|
Embeddings for all spans. |
span_offsets |
list[Offsets]
|
Start and end character indices for each span. |
Source code in turftopic/late.py
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 | |
encode_tokens(raw_documents)
Encodes tokens in all documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_documents |
list[str]
|
List of documents. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
token_embeddings |
list[ndarray]
|
Embeddings for all tokens. |
token_offsetes |
list[Offsets]
|
Start and end character indices for each token. |
Source code in turftopic/late.py
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 | |
export_representative_spans(topic_id, raw_documents=None, document_topic_matrix=None, embeddings=None, offsets=None, top_k=10, remove_whitespace=True, format='csv')
Exports representative spans for a given topic in a given format
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_id |
ID of the topic to show spans for. |
required | |
raw_documents |
List of documents. |
None
|
|
document_topic_matrix |
Ragged document topic matrix. |
None
|
|
embeddings |
list[ndarray] | None
|
Ragged embeddings. |
None
|
offsets |
list[Offsets] | None
|
Span offsets. |
None
|
top_k |
int
|
Number of spans to return for each topic. |
10
|
remove_whitespace |
bool
|
Indicates whether unnecessary remove_whitespace should be removed from the returned spans. |
True
|
format |
str
|
Specifies which format should be used. 'csv', 'latex' and 'markdown' are supported. |
'csv'
|
Source code in turftopic/late.py
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 | |
extract_spans(documents, token_offsets=None)
Extracts spans using the model's span_extractor. If span_extractor is None, tokens are returned as the default spans.
Source code in turftopic/late.py
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 | |
fit(raw_documents, y=None, embeddings=None, offsets=None)
Fits model on the given corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_documents |
Documents to fit the model on. |
required | |
y |
Ignored, exists for sklearn compatibility. |
None
|
|
embeddings |
Optional[list[ndarray]]
|
Ragged array of document encodings. |
None
|
offsets |
Optional[Offsets]
|
Character offset for each unit in the document. |
None
|
Source code in turftopic/late.py
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 | |
fit_transform(raw_documents, y=None, embeddings=None, offsets=None)
abstractmethod
Fits model and infers topic importances for each document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_documents |
Documents to fit the model on. |
required | |
y |
Ignored, exists for sklearn compatibility. |
None
|
|
embeddings |
Optional[list[ndarray]]
|
Ragged array of document encodings. |
None
|
offsets |
Optional[Offsets]
|
Character offset for each unit in the document. |
None
|
Returns:
| Type | Description |
|---|---|
(list[ndarray], list[Offsets]) or ndarray
|
Document-topic matrix. If pooling = None, this should be a ragged array with offsets, otherwise a regular matrix. |
Source code in turftopic/late.py
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 | |
flatten_repr(repr)
staticmethod
Flattens ragged array to normal array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repr |
Ragged representation array. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
flat_repr |
ndarray
|
Flattened representation array. |
lengths |
list[int]
|
Length of each document in the corpus. |
Source code in turftopic/late.py
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 | |
get_top_spans(raw_documents=None, document_topic_matrix=None, embeddings=None, offsets=None, top_k=10, remove_whitespace=True)
Returns the top K spans for each topic. If no documents are passed, the function will try to return the top spans saved during training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_documents |
List of documents. |
None
|
|
document_topic_matrix |
Ragged document topic matrix. |
None
|
|
embeddings |
list[ndarray] | None
|
Ragged embeddings. |
None
|
offsets |
list[Offsets] | None
|
Span offsets. |
None
|
top_k |
int
|
Number of spans to return for each topic. |
10
|
remove_whitespace |
bool
|
Indicates whether unnecessary remove_whitespace should be removed from the returned spans. |
True
|
Returns:
| Type | Description |
|---|---|
list[list[str]]
|
List of top K spans for each topic. |
Source code in turftopic/late.py
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 | |
pool(doc_topic_matrix, offsets)
Pools the document topic matrix with the pooling method of the model. If pooling is None, nothing will be done
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc_topic_matrix |
list[ndarray]
|
Ragged doc-topic matrix. |
required |
offsets |
Span offsets. |
required |
Returns:
| Type | Description |
|---|---|
ndarray or RaggedArray
|
If pooling is None, return array and offsets as is, otherwise the pooled document-topic-matrix. |
Source code in turftopic/late.py
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | |
pool_flat(flat_repr, lengths, agg=np.nanmean)
staticmethod
Pools vectors within documents using the agg function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flat_repr |
Flattened document representations. |
required | |
lengths |
Number of tokens in each document. |
required |
Returns:
| Type | Description |
|---|---|
ndarray or sparse array of shape (n_documents, n_dims)
|
Pooled representation for each document. |
Source code in turftopic/late.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | |
pool_spans(token_embeddings, token_offsets, span_offsets, include_edge_tokens=True, normalize_spans=True)
staticmethod
Pools vectors within the specified spans using in a bunch of documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_embeddings |
list[ndarray]
|
Ragged array of token embeddings. |
required |
token_offsets |
list[Offsets]
|
End and start character for each token in each document. |
required |
span_offsets |
list[Offsets]
|
End and start character for each span in each document. |
required |
include_edge_tokens |
bool
|
Indicates whether tokens at the edges of spans should be included in the embeddings. |
True
|
normalize_spans |
bool
|
Indicates whether span embeddings should be L2 normalized. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
span_embeddings |
list[ndarray]
|
Ragged array of each span embedding in each document. |
span_offsets |
list[Offsets]
|
Offsets for the extracted spans. This can differ from the input as empty spans are removed in order to avoid NaNs. |
Source code in turftopic/late.py
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 | |
print_representative_spans(topic_id, raw_documents=None, document_topic_matrix=None, embeddings=None, offsets=None, top_k=10, remove_whitespace=True)
Prints representative spans for a given topic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_id |
ID of the topic to show spans for. |
required | |
raw_documents |
List of documents. |
None
|
|
document_topic_matrix |
Ragged document topic matrix. |
None
|
|
embeddings |
list[ndarray] | None
|
Ragged embeddings. |
None
|
offsets |
list[Offsets] | None
|
Span offsets. |
None
|
top_k |
int
|
Number of spans to return for each topic. |
10
|
remove_whitespace |
bool
|
Indicates whether unnecessary remove_whitespace should be removed from the returned spans. |
True
|
Source code in turftopic/late.py
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 | |
ragged_vectorize(raw_documents, offsets, train_vectorizer=False)
Vectorizes spans in a document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc_topic_matrix |
Ragged doc-topic matrix. |
required | |
offsets |
Offsets
|
Span offsets. |
required |
Returns:
| Type | Description |
|---|---|
list[ndarray]
|
Ragged document-term-matrix. |
Source code in turftopic/late.py
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 | |
representative_spans_df(topic_id, raw_documents=None, document_topic_matrix=None, embeddings=None, offsets=None, top_k=10, remove_whitespace=True)
Produces a DataFrame of representative spans for a given topic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_id |
ID of the topic to show spans for. |
required | |
raw_documents |
List of documents. |
None
|
|
document_topic_matrix |
Ragged document topic matrix. |
None
|
|
embeddings |
list[ndarray] | None
|
Ragged embeddings. |
None
|
offsets |
list[Offsets] | None
|
Span offsets. |
None
|
top_k |
int
|
Number of spans to return for each topic. |
10
|
remove_whitespace |
bool
|
Indicates whether unnecessary remove_whitespace should be removed from the returned spans. |
True
|
Source code in turftopic/late.py
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 | |
unflatten_repr(flat_repr, lengths)
staticmethod
Unflattens flat array to ragged array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flat_repr |
Flattened representation array. |
required | |
lengths |
Length of each document in the corpus. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
repr |
list[ndarray]
|
Ragged representation array. |
Source code in turftopic/late.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
Encoder
turftopic.late.LateSentenceTransformer
Bases: SentenceTransformer
SentenceTransformer model that can produce token and window-level embeddings. Its output can be used by topic models that can use multi-vector document representations.
Warning
This is not checked yet in the library, but we recommend that you use SentenceTransformers that are a) Mean pooled b) L2 Normalized This will guarrantee that the token/window embeddings are in the same embedding space as the documents.
Source code in turftopic/late.py
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 | |
encode_tokens(sentences, **kwargs)
Produces contextual token embeddings over all documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sentences |
list[str]
|
Documents to encode contextually. |
required |
batch_size |
Size of the batch of document to encode at once. |
required | |
show_progress_bar |
Indicates whether a progress bar should be displayed when encoding. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
token_embeddings |
list[ndarray]
|
Embedding matrix of tokens for each document. |
offsets |
list[list[tuple[int, int]]]
|
Start and end character of each token in each document. |
Source code in turftopic/late.py
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 | |
encode_windows(sentences, window_size=50, step_size=40, **kwargs)
Produces contextual embeddings for a sliding window of tokens similar to C-Top2Vec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sentences |
list[str]
|
Documents to encode contextually. |
required |
batch_size |
Size of the batch of document to encode at once. |
required | |
window_size |
int
|
Size of the sliding window. |
50
|
step_size |
int
|
Step size of the window. If step_size < window_size, windows will overlap. If step_size == window_size, then windows are separate. If step_size > window_size, there will be gaps between the windows. In this case, we throw a warning, as this is probably unintended behaviour. |
40
|
show_progress_bar |
Indicates whether a progress bar should be displayed when encoding. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
window_embeddings |
list[ndarray]
|
Embedding matrix of windows for each document. |
offsets |
list[list[tuple[int, int]]]
|
Start and end character of each token in each document. |
Source code in turftopic/late.py
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 | |