UMCU commited on
Commit
0b12ce4
·
verified ·
1 Parent(s): 3f87fc8

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +60 -0
README.md CHANGED
@@ -96,8 +96,68 @@ def reform(features, how='softmax'):
96
  return torch.nn.functional.normalize(features.reshape(1,-1))
97
 
98
  feature_vector = reform(get_feature_vector(text))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
 
100
 
 
101
  ```
102
 
103
 
 
96
  return torch.nn.functional.normalize(features.reshape(1,-1))
97
 
98
  feature_vector = reform(get_feature_vector(text))
99
+ ```
100
+
101
+ or with multiple texts
102
+
103
+ ```python
104
+
105
+ def get_feature_vectors_with_stride(
106
+ texts,
107
+ stride=16,
108
+ max_context_length=128,
109
+ reformer=None
110
+ ):
111
+ """
112
+ Extract one feature vector per document.
113
+
114
+ Long documents are split into overlapping windows.
115
+ Logits from all windows belonging to the same document are averaged.
116
+
117
+ Returns:
118
+ Tensor [n_documents, n_features]
119
+ """
120
+
121
+ inputs = tokenizer(
122
+ texts,
123
+ return_tensors="pt",
124
+ truncation=True,
125
+ max_length=max_context_length,
126
+ stride=stride,
127
+ return_overflowing_tokens=True,
128
+ padding=True,
129
+ )
130
+
131
+ # Maps each generated chunk back to its original document.
132
+ sample_mapping = inputs.pop("overflow_to_sample_mapping")
133
+
134
+ inputs = {
135
+ key: value.to(device)
136
+ for key, value in inputs.items()
137
+ }
138
+
139
+ with torch.no_grad():
140
+ logits = model(**inputs).logits
141
+
142
+ # logits:
143
+ # [n_chunks, n_features]
144
+
145
+ sample_mapping = sample_mapping.to(logits.device)
146
+
147
+ features = []
148
+
149
+ for sample_idx in range(len(texts)):
150
+ mask = sample_mapping == sample_idx
151
+
152
+ # Mean over all windows belonging to this document.
153
+ if reformer is None:
154
+ document_features = logits[mask].mean(dim=0)
155
+ else:
156
+ document_features = reform(logits[mask].mean(dim=0).flatten(), how=reformer)
157
 
158
+ features.append(document_features)
159
 
160
+ return torch.stack(features).cpu()
161
  ```
162
 
163