polyprobe 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of polyprobe might be problematic. Click here for more details.
- polyprobe/__init__.py +8 -0
- polyprobe/activations.py +353 -0
- polyprobe/architecture_encoders/architecture_encoder.py +71 -0
- polyprobe/architecture_encoders/gqa.py +77 -0
- polyprobe/architecture_encoders/opt.py +51 -0
- polyprobe/architecture_encoders/qwen3_5.py +100 -0
- polyprobe/batching.py +133 -0
- polyprobe/config.py +101 -0
- polyprobe/document.py +138 -0
- polyprobe/evaluation.py +945 -0
- polyprobe/index_tuple_selectors/causal_combinatorial.py +49 -0
- polyprobe/index_tuple_selectors/index_tuple_selector.py +23 -0
- polyprobe/inferrer.py +480 -0
- polyprobe/lm_encoder.py +218 -0
- polyprobe/logging_utils.py +82 -0
- polyprobe/manager.py +607 -0
- polyprobe/model.py +342 -0
- polyprobe/poolers/max.py +23 -0
- polyprobe/poolers/mean.py +34 -0
- polyprobe/poolers/passthrough.py +21 -0
- polyprobe/poolers/pooler.py +88 -0
- polyprobe/probe_components/index_pair.py +368 -0
- polyprobe/probe_components/probe_component.py +92 -0
- polyprobe/probes/linear.py +46 -0
- polyprobe/probes/neural.py +220 -0
- polyprobe/probes/probe.py +164 -0
- polyprobe/py.typed +0 -0
- polyprobe/registry.py +248 -0
- polyprobe/scorers/average_precision.py +27 -0
- polyprobe/scorers/f1.py +24 -0
- polyprobe/scorers/roc-auc.py +28 -0
- polyprobe/scorers/scorer.py +43 -0
- polyprobe/training/config.py +127 -0
- polyprobe/training/dataset_sources/dataset_source.py +142 -0
- polyprobe/training/dataset_sources/ud_dependency_dataset_source.py +517 -0
- polyprobe/training/runner.py +951 -0
- polyprobe/training/training_data.py +180 -0
- polyprobe/training/truthers/direct.py +206 -0
- polyprobe/training/truthers/random.py +63 -0
- polyprobe/training/truthers/subword.py +49 -0
- polyprobe/training/truthers/truther.py +96 -0
- polyprobe/util.py +599 -0
- polyprobe-1.0.0.dist-info/METADATA +63 -0
- polyprobe-1.0.0.dist-info/RECORD +48 -0
- polyprobe-1.0.0.dist-info/WHEEL +5 -0
- polyprobe-1.0.0.dist-info/licenses/LICENSE +73 -0
- polyprobe-1.0.0.dist-info/licenses/LICENSE-CC-BY-4.0 +395 -0
- polyprobe-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import random
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
from conllu import parse
|
|
11
|
+
from conllu.models import TokenList
|
|
12
|
+
|
|
13
|
+
from polyprobe.document import (
|
|
14
|
+
DocumentPiece,
|
|
15
|
+
DocumentPieceList,
|
|
16
|
+
MatchedTrainingToken,
|
|
17
|
+
TrainingLabel,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from .dataset_source import DatasetSource
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
DEFAULT_MAX_TOKENS = 200
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class UDDependencyCausalDatasetSource(DatasetSource):
|
|
28
|
+
"""
|
|
29
|
+
Extracts train/dev/test lists of document pieces from a Universal Dependencies (UD) repository,
|
|
30
|
+
which must already have been cloned to the local machine, and labels them with the
|
|
31
|
+
specified syntactic dependencies.
|
|
32
|
+
|
|
33
|
+
Where a UD repository has separate train, dev and test files corresponding to each requested
|
|
34
|
+
dataset split, the lists of document pieces are extracted from the corresponding files; where
|
|
35
|
+
at least one requested split file is absent, the available files are pooled and new train,
|
|
36
|
+
development and test splits are sampled from the combined data.
|
|
37
|
+
|
|
38
|
+
This dataset source is intended for use with causal language models: it generates training labels
|
|
39
|
+
where the second training token index is never less than the first training token index; the distinction
|
|
40
|
+
between head-first and head-last dependencies is captured by the order.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, lm_encoder: "LMEncoder", seed: int, kwargs: dict[str, Any]): # type: ignore[name-defined]
|
|
44
|
+
"""
|
|
45
|
+
lm_encoder: the LM Encoder instance.
|
|
46
|
+
seed: a seed for selecting sentences and assigning them to the train/eval/test split.
|
|
47
|
+
kwargs: a dictionary of arguments:
|
|
48
|
+
It must contain location(str): the path to the parent directory under which the Universal Dependency repositories have been checked out.
|
|
49
|
+
It may contain max_tokens(int): the maximum number of UD tokens (including multiword-token entries and empty nodes) that a sentence
|
|
50
|
+
may have to be accepted for use by Polyprobe; if no max_tokens is specified, 200 is used as a default value.
|
|
51
|
+
It may contain use_enhanced_ud(bool) (default False): if True, dependencies are taken from the enhanced-UD "deps" column instead of "head"/"deprel".
|
|
52
|
+
Only dependencies whose endpoints map to distinct aligned surface training tokens are retained. Empty nodes and all dependencies involving them are excluded.
|
|
53
|
+
"""
|
|
54
|
+
super().__init__(lm_encoder, seed, kwargs)
|
|
55
|
+
allowed_keys = {"location", "max_tokens", "use_enhanced_ud"}
|
|
56
|
+
if kwargs.keys() - allowed_keys:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
"Only location, max_tokens and use_enhanced_ud are supported "
|
|
59
|
+
"as dataset_source_kwargs keys."
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
if "location" not in kwargs:
|
|
63
|
+
raise ValueError("dataset_source_kwargs must contain an entry 'location'.")
|
|
64
|
+
|
|
65
|
+
location = kwargs["location"]
|
|
66
|
+
max_tokens = kwargs.get("max_tokens", DEFAULT_MAX_TOKENS)
|
|
67
|
+
use_enhanced_ud = kwargs.get("use_enhanced_ud", False)
|
|
68
|
+
|
|
69
|
+
if type(location) is not str:
|
|
70
|
+
raise ValueError("location in dataset_source_kwargs must have type str.")
|
|
71
|
+
if type(max_tokens) is not int:
|
|
72
|
+
raise ValueError("max_tokens in dataset_source_kwargs must have type int.")
|
|
73
|
+
if type(use_enhanced_ud) is not bool:
|
|
74
|
+
raise ValueError(
|
|
75
|
+
"use_enhanced_ud in dataset_source_kwargs must have type bool."
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
self.location = location
|
|
79
|
+
self.max_tokens = max_tokens
|
|
80
|
+
self.use_enhanced_ud = use_enhanced_ud
|
|
81
|
+
|
|
82
|
+
def _get_sentences_from_separate_files(
|
|
83
|
+
self, conllu_file_paths: list[Path], num_sentences: int
|
|
84
|
+
) -> list[TokenList] | None:
|
|
85
|
+
"""Get a specific dataset split from the file(s) for that split."""
|
|
86
|
+
if num_sentences == 0:
|
|
87
|
+
return None
|
|
88
|
+
sentences: list[TokenList] = []
|
|
89
|
+
for conllu_file_path in conllu_file_paths:
|
|
90
|
+
conllu_data = conllu_file_path.read_text(encoding="utf-8")
|
|
91
|
+
sentences.extend(parse(conllu_data))
|
|
92
|
+
sentences = self._filter_sentences_longer_than_max_tokens(sentences)
|
|
93
|
+
rng = random.Random(self.seed)
|
|
94
|
+
rng.shuffle(sentences)
|
|
95
|
+
if len(sentences) < num_sentences:
|
|
96
|
+
raise ValueError(
|
|
97
|
+
f"{conllu_file_paths} contain only {len(sentences)} sentences, but a sample of {num_sentences} was requested."
|
|
98
|
+
)
|
|
99
|
+
return sentences[:num_sentences]
|
|
100
|
+
|
|
101
|
+
def _get_sentences_from_combined_files(
|
|
102
|
+
self,
|
|
103
|
+
conllu_file_paths: list[Path],
|
|
104
|
+
num_sentences_sizes: tuple[int, int, int],
|
|
105
|
+
) -> tuple[list[TokenList] | None, list[TokenList] | None, list[TokenList] | None]:
|
|
106
|
+
"""Get whichever of train, dev and test dataset splits were requested from whatever file or files are available.
|
|
107
|
+
|
|
108
|
+
conllu_file_paths: a list of available CoNLL-U file paths to pool before sampling the requested splits.
|
|
109
|
+
num_sentences_sizes: the requested number of sentences for each of train, dev and test dataset splits,
|
|
110
|
+
with 0 for any split that is not required.
|
|
111
|
+
"""
|
|
112
|
+
return_lists: list[list[TokenList] | None] = []
|
|
113
|
+
sentences: list[TokenList] = []
|
|
114
|
+
for conllu_file_path in conllu_file_paths:
|
|
115
|
+
conllu_data = conllu_file_path.read_text(encoding="utf-8")
|
|
116
|
+
sentences.extend(parse(conllu_data))
|
|
117
|
+
sentences = self._filter_sentences_longer_than_max_tokens(sentences)
|
|
118
|
+
num_all_sentences = sum(num_sentences_sizes)
|
|
119
|
+
if len(sentences) < num_all_sentences:
|
|
120
|
+
raise ValueError(
|
|
121
|
+
f"{[str(cfp) for cfp in conllu_file_paths]} contain only {len(sentences)} sentences, but a total sample of {num_all_sentences} was requested."
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
rng = random.Random(self.seed)
|
|
125
|
+
rng.shuffle(sentences)
|
|
126
|
+
for num_sentences in num_sentences_sizes:
|
|
127
|
+
if num_sentences == 0:
|
|
128
|
+
return_lists.append(None)
|
|
129
|
+
continue
|
|
130
|
+
return_lists.append(sentences[:num_sentences])
|
|
131
|
+
sentences = sentences[num_sentences:]
|
|
132
|
+
return cast(
|
|
133
|
+
tuple[
|
|
134
|
+
list[TokenList] | None,
|
|
135
|
+
list[TokenList] | None,
|
|
136
|
+
list[TokenList] | None,
|
|
137
|
+
],
|
|
138
|
+
tuple(return_lists),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
def _get_first_line_of_license_file(self, repository_path: Path) -> str | None:
|
|
142
|
+
"""Return the first nonblank line of the license file to display in the training or evaluation output
|
|
143
|
+
so that cases where the license is unfriendly/inappropriate are flagged early on.
|
|
144
|
+
"""
|
|
145
|
+
license_path = repository_path / "LICENSE.txt"
|
|
146
|
+
if license_path.exists():
|
|
147
|
+
license_info = license_path.read_text(encoding="utf-8")
|
|
148
|
+
if len(license_info) > 0:
|
|
149
|
+
lines = license_info.splitlines()
|
|
150
|
+
for line in lines:
|
|
151
|
+
if len(line.strip()) > 0:
|
|
152
|
+
return line
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
def _get_document_piece_and_assigned_labels(
|
|
156
|
+
self,
|
|
157
|
+
repository: str,
|
|
158
|
+
sentence: TokenList,
|
|
159
|
+
labels: list[str],
|
|
160
|
+
) -> tuple[DocumentPiece, set[tuple[str, tuple[int, ...]]]] | None:
|
|
161
|
+
"""
|
|
162
|
+
Generates a Polyprobe document piece from a conllu sentence.
|
|
163
|
+
|
|
164
|
+
repository: the name of the UD repository.
|
|
165
|
+
sentence: the conllu sentence.
|
|
166
|
+
labels: the dependency labels to capture.
|
|
167
|
+
|
|
168
|
+
Returns a document piece and a set containing the dependencies and orders found,
|
|
169
|
+
or *None* if the sentence could not be converted or aligned.
|
|
170
|
+
"""
|
|
171
|
+
assigned_training_labels_and_orders: set[tuple[str, tuple[int, ...]]] = set()
|
|
172
|
+
identifier = sentence.metadata.get(
|
|
173
|
+
"sent_id", f"{repository} (no sentence id supplied)"
|
|
174
|
+
)
|
|
175
|
+
sentence_text = sentence.metadata.get("text")
|
|
176
|
+
if sentence_text is None:
|
|
177
|
+
logger.warning(f"No text in metadata, skipping sentence {identifier} ...")
|
|
178
|
+
return None
|
|
179
|
+
piece = self.lm_encoder.create_document_piece(sentence_text, identifier)
|
|
180
|
+
piece.training_tokens = {}
|
|
181
|
+
piece.training_labels = set()
|
|
182
|
+
|
|
183
|
+
token_matching_dict: dict[int, int] = {}
|
|
184
|
+
next_conllu_tok_num = 1
|
|
185
|
+
next_id_to_assign = 0
|
|
186
|
+
cursor = 0
|
|
187
|
+
for tok_idx, tok in enumerate(sentence):
|
|
188
|
+
this_token_matching_dict: dict[int, int] = {}
|
|
189
|
+
tok_id = tok["id"]
|
|
190
|
+
if isinstance(tok_id, int):
|
|
191
|
+
if tok_id < next_conllu_tok_num: # syntactic token within a multiword
|
|
192
|
+
continue
|
|
193
|
+
this_token_matching_dict[tok_id] = next_id_to_assign
|
|
194
|
+
next_conllu_tok_num = tok_id + 1
|
|
195
|
+
elif isinstance(tok_id, tuple) and len(tok_id) == 3:
|
|
196
|
+
start_tok_id, separator, end_tok_id = tok_id
|
|
197
|
+
if (
|
|
198
|
+
separator == "."
|
|
199
|
+
): # Empty nodes have no surface span to align to LM tokens.
|
|
200
|
+
continue
|
|
201
|
+
elif separator == "-":
|
|
202
|
+
# we want to use the multiword token if it has a different surface form
|
|
203
|
+
# from its component syntactic tokens, otherwise ignore it
|
|
204
|
+
concatenated_syntactic_forms = "".join(
|
|
205
|
+
sentence[idx].get("form", "")
|
|
206
|
+
for idx in range(
|
|
207
|
+
tok_idx + 1, tok_idx + 2 + end_tok_id - start_tok_id
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
if tok.get("form") == concatenated_syntactic_forms:
|
|
211
|
+
continue
|
|
212
|
+
next_conllu_tok_num = end_tok_id + 1
|
|
213
|
+
for conllu_tok_num in range(start_tok_id, next_conllu_tok_num):
|
|
214
|
+
this_token_matching_dict[conllu_tok_num] = next_id_to_assign
|
|
215
|
+
else:
|
|
216
|
+
logger.warning(
|
|
217
|
+
f"Invalid multiword ID {tok_id}, skipping sentence {identifier} ..."
|
|
218
|
+
)
|
|
219
|
+
return None
|
|
220
|
+
else:
|
|
221
|
+
logger.warning(
|
|
222
|
+
f"Invalid conllu ID {tok_id}, skipping sentence {identifier} ..."
|
|
223
|
+
)
|
|
224
|
+
return None
|
|
225
|
+
form = tok.get("form")
|
|
226
|
+
if form is None:
|
|
227
|
+
logger.warning(
|
|
228
|
+
f"Could not retrieve form at character {cursor}, skipping sentence {identifier} ..."
|
|
229
|
+
)
|
|
230
|
+
return None
|
|
231
|
+
tok_start = sentence_text.find(form, cursor)
|
|
232
|
+
if tok_start == -1:
|
|
233
|
+
logger.warning(
|
|
234
|
+
f"Could not align token {form!r} after character {cursor}, skipping sentence {identifier} ..."
|
|
235
|
+
)
|
|
236
|
+
return None
|
|
237
|
+
tok_end = tok_start + len(form)
|
|
238
|
+
cursor = tok_end
|
|
239
|
+
|
|
240
|
+
matching_lm_token_idxs: list[int] = []
|
|
241
|
+
for lm_idx, (lm_start, lm_end) in enumerate(piece.lm_offsets):
|
|
242
|
+
if lm_start == lm_end:
|
|
243
|
+
continue
|
|
244
|
+
if max(tok_start, lm_start) < min(tok_end, lm_end):
|
|
245
|
+
matching_lm_token_idxs.append(lm_idx)
|
|
246
|
+
if len(matching_lm_token_idxs) > 0:
|
|
247
|
+
matched_training_token = MatchedTrainingToken(
|
|
248
|
+
next_id_to_assign, (tok_start, tok_end), matching_lm_token_idxs
|
|
249
|
+
)
|
|
250
|
+
piece.training_tokens[next_id_to_assign] = matched_training_token
|
|
251
|
+
token_matching_dict.update(this_token_matching_dict)
|
|
252
|
+
next_id_to_assign += 1
|
|
253
|
+
else:
|
|
254
|
+
logger.warning(
|
|
255
|
+
f"Token {form!r} at offsets ({tok_start}, {tok_end}) "
|
|
256
|
+
f"matched no LM tokens in sentence {identifier}"
|
|
257
|
+
)
|
|
258
|
+
continue
|
|
259
|
+
|
|
260
|
+
for tok in sentence:
|
|
261
|
+
tok_id = tok["id"]
|
|
262
|
+
if not isinstance(tok_id, int):
|
|
263
|
+
continue
|
|
264
|
+
if tok_id not in token_matching_dict:
|
|
265
|
+
logger.warning(
|
|
266
|
+
f"Token ID {tok_id} not found in token_matching_dict in sentence {identifier}, skipping token"
|
|
267
|
+
)
|
|
268
|
+
continue
|
|
269
|
+
if self.use_enhanced_ud:
|
|
270
|
+
dep_tuples: list[tuple[str, int]] = tok.get("deps") or []
|
|
271
|
+
else:
|
|
272
|
+
dep_tuples = [(tok.get("deprel", ""), tok.get("head"))]
|
|
273
|
+
for dep_repr, head_id in dep_tuples:
|
|
274
|
+
dep = dep_repr.split(":")[0]
|
|
275
|
+
if dep in labels:
|
|
276
|
+
if head_id is None or (
|
|
277
|
+
head_id != 0 and head_id not in token_matching_dict
|
|
278
|
+
):
|
|
279
|
+
logger.warning(
|
|
280
|
+
f"Head token ID {head_id} not found in token_matching_dict in sentence {identifier}, skipping token"
|
|
281
|
+
)
|
|
282
|
+
continue
|
|
283
|
+
if head_id == 0: # root
|
|
284
|
+
continue
|
|
285
|
+
polyprobe_tok_id = token_matching_dict[tok_id]
|
|
286
|
+
polyprobe_head_id = token_matching_dict[head_id]
|
|
287
|
+
if polyprobe_head_id < polyprobe_tok_id:
|
|
288
|
+
piece.training_labels.add(
|
|
289
|
+
TrainingLabel(
|
|
290
|
+
name=dep,
|
|
291
|
+
training_token_idxs=(
|
|
292
|
+
polyprobe_head_id,
|
|
293
|
+
polyprobe_tok_id,
|
|
294
|
+
),
|
|
295
|
+
order=(1, 0),
|
|
296
|
+
)
|
|
297
|
+
)
|
|
298
|
+
assigned_training_labels_and_orders.add((dep, (1, 0)))
|
|
299
|
+
elif polyprobe_tok_id < polyprobe_head_id:
|
|
300
|
+
piece.training_labels.add(
|
|
301
|
+
TrainingLabel(
|
|
302
|
+
name=dep,
|
|
303
|
+
training_token_idxs=(
|
|
304
|
+
polyprobe_tok_id,
|
|
305
|
+
polyprobe_head_id,
|
|
306
|
+
),
|
|
307
|
+
order=(0, 1),
|
|
308
|
+
)
|
|
309
|
+
)
|
|
310
|
+
assigned_training_labels_and_orders.add((dep, (0, 1)))
|
|
311
|
+
else:
|
|
312
|
+
# Discard dependencies whose endpoints map to the same training token
|
|
313
|
+
# (e.g. syntactic components merged under a UD multiword token).
|
|
314
|
+
# Distinct training tokens may share LM token indices; those dependencies remain.
|
|
315
|
+
continue
|
|
316
|
+
return piece, assigned_training_labels_and_orders
|
|
317
|
+
|
|
318
|
+
def _get_labelled_document_piece_list(
|
|
319
|
+
self, repository: str, sentences: list[TokenList], labels: list[str]
|
|
320
|
+
) -> DocumentPieceList:
|
|
321
|
+
"""
|
|
322
|
+
Generates a Polyprobe DocumentPieceList object from a list of conllu sentences.
|
|
323
|
+
|
|
324
|
+
repository: the name of the UD repository.
|
|
325
|
+
sentences: the conllu sentences.
|
|
326
|
+
labels: the dependency labels to capture.
|
|
327
|
+
"""
|
|
328
|
+
|
|
329
|
+
pieces: list[DocumentPiece] = []
|
|
330
|
+
assigned_training_labels_and_orders: set[tuple[str, tuple[int, ...]]] = set()
|
|
331
|
+
for sentence in sentences:
|
|
332
|
+
piece_and_assigned_labels = self._get_document_piece_and_assigned_labels(
|
|
333
|
+
repository, sentence, labels
|
|
334
|
+
)
|
|
335
|
+
if piece_and_assigned_labels is None:
|
|
336
|
+
continue
|
|
337
|
+
piece, piece_assigned_training_labels_and_orders = piece_and_assigned_labels
|
|
338
|
+
pieces.append(piece)
|
|
339
|
+
assigned_training_labels_and_orders.update(
|
|
340
|
+
piece_assigned_training_labels_and_orders
|
|
341
|
+
)
|
|
342
|
+
return DocumentPieceList(
|
|
343
|
+
pieces, self.lm_encoder.lm_name, assigned_training_labels_and_orders
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
def get_dataset(
|
|
347
|
+
self,
|
|
348
|
+
repository: str,
|
|
349
|
+
num_train_sentences: int,
|
|
350
|
+
num_dev_sentences: int,
|
|
351
|
+
num_test_sentences: int,
|
|
352
|
+
labels: list[str],
|
|
353
|
+
trained_on_dataset_descriptions: set[tuple[str, str]],
|
|
354
|
+
) -> tuple[
|
|
355
|
+
DocumentPieceList | None,
|
|
356
|
+
DocumentPieceList | None,
|
|
357
|
+
DocumentPieceList | None,
|
|
358
|
+
]:
|
|
359
|
+
"""
|
|
360
|
+
Returns a (train, dev, test) tuple, with None for splits not requested.
|
|
361
|
+
|
|
362
|
+
Requested counts apply to sentences sampled after length filtering.
|
|
363
|
+
Sentences subsequently rejected during conversion are not replaced,
|
|
364
|
+
so returned splits may contain fewer pieces. Pieces with no matching
|
|
365
|
+
labels are retained.
|
|
366
|
+
|
|
367
|
+
repository: the name of the UD repository.
|
|
368
|
+
num_train_sentences: the number of sentences for which to attempt sampling into the train dataset split,
|
|
369
|
+
or *0* if no train dataset split is required.
|
|
370
|
+
num_dev_sentences: the number of sentences for which to attempt sampling into the dev dataset split,
|
|
371
|
+
or *0* if no dev dataset split is required.
|
|
372
|
+
num_test_sentences: the number of sentences for which to attempt sampling into the test dataset split,
|
|
373
|
+
or *0* if no test dataset split is required.
|
|
374
|
+
labels: the dependency labels to capture.
|
|
375
|
+
trained_on_dataset_descriptions: a set of (dataset source, dataset identifier) tuples
|
|
376
|
+
specifying the datasets on which the model being tested was trained. Only
|
|
377
|
+
contains elements when the method is called from *get_test_dataset()*.
|
|
378
|
+
Where an implementation derives train/dev/test splits itself, it must
|
|
379
|
+
ensure that sentences that end up one split on one occasion cannot end up
|
|
380
|
+
in another split on another occasion, and raise an exception if this cannot
|
|
381
|
+
be guaranteed.
|
|
382
|
+
"""
|
|
383
|
+
if "root" in labels:
|
|
384
|
+
raise ValueError("The root relation is not supported.")
|
|
385
|
+
sizes = (
|
|
386
|
+
num_train_sentences,
|
|
387
|
+
num_dev_sentences,
|
|
388
|
+
num_test_sentences,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
if not any(sizes):
|
|
392
|
+
raise ValueError("At least one sentence must be requested.")
|
|
393
|
+
|
|
394
|
+
repository_dir = Path(self.location) / repository
|
|
395
|
+
if not repository_dir.is_dir():
|
|
396
|
+
raise FileNotFoundError(f"{repository_dir} does not exist.")
|
|
397
|
+
|
|
398
|
+
logger.info(
|
|
399
|
+
f"Retrieving Universal Dependencies repository {repository} with max_tokens={self.max_tokens} and use_enhanced_ud={self.use_enhanced_ud}"
|
|
400
|
+
)
|
|
401
|
+
license_info = self._get_first_line_of_license_file(repository_dir)
|
|
402
|
+
if license_info is not None:
|
|
403
|
+
logger.info(f"First line of license file: '{license_info}'")
|
|
404
|
+
|
|
405
|
+
required_file_missing = False
|
|
406
|
+
|
|
407
|
+
def find(split: str, num_sentences: int) -> list[Path]:
|
|
408
|
+
matches = sorted(
|
|
409
|
+
repository_dir.glob(f"*-ud-{split}*conllu"), key=lambda path: path.name
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
if matches:
|
|
413
|
+
return matches
|
|
414
|
+
else:
|
|
415
|
+
if num_sentences > 0:
|
|
416
|
+
nonlocal required_file_missing
|
|
417
|
+
required_file_missing = True
|
|
418
|
+
return []
|
|
419
|
+
|
|
420
|
+
trains = find("train", num_train_sentences)
|
|
421
|
+
devs = find("dev", num_dev_sentences)
|
|
422
|
+
tests = find("test", num_test_sentences)
|
|
423
|
+
|
|
424
|
+
if not trains or not devs or not tests:
|
|
425
|
+
for (
|
|
426
|
+
datasource_name,
|
|
427
|
+
datasource_identifier,
|
|
428
|
+
) in trained_on_dataset_descriptions:
|
|
429
|
+
if (
|
|
430
|
+
datasource_name == type(self).__name__
|
|
431
|
+
and datasource_identifier == repository
|
|
432
|
+
):
|
|
433
|
+
raise ValueError(
|
|
434
|
+
f"The model being tested was trained using {repository}, "
|
|
435
|
+
"which does not contain all three train/dev/test splits, "
|
|
436
|
+
"meaning that Polyprobe derived splits from the existing data. "
|
|
437
|
+
"It is not possible to evaluate the same repository without the "
|
|
438
|
+
"risk of reusing sentences in test that were originally used "
|
|
439
|
+
"in train or dev."
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
if not required_file_missing:
|
|
443
|
+
if num_train_sentences > 0:
|
|
444
|
+
train_sentences = self._get_sentences_from_separate_files(
|
|
445
|
+
trains, num_train_sentences
|
|
446
|
+
)
|
|
447
|
+
else:
|
|
448
|
+
train_sentences = None
|
|
449
|
+
if num_dev_sentences > 0:
|
|
450
|
+
dev_sentences = self._get_sentences_from_separate_files(
|
|
451
|
+
devs, num_dev_sentences
|
|
452
|
+
)
|
|
453
|
+
else:
|
|
454
|
+
dev_sentences = None
|
|
455
|
+
if num_test_sentences > 0:
|
|
456
|
+
test_sentences = self._get_sentences_from_separate_files(
|
|
457
|
+
tests, num_test_sentences
|
|
458
|
+
)
|
|
459
|
+
else:
|
|
460
|
+
test_sentences = None
|
|
461
|
+
|
|
462
|
+
else:
|
|
463
|
+
(
|
|
464
|
+
train_sentences,
|
|
465
|
+
dev_sentences,
|
|
466
|
+
test_sentences,
|
|
467
|
+
) = self._get_sentences_from_combined_files(
|
|
468
|
+
trains + devs + tests,
|
|
469
|
+
(num_train_sentences, num_dev_sentences, num_test_sentences),
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
if train_sentences is not None:
|
|
473
|
+
train_document_piece_list = self._get_labelled_document_piece_list(
|
|
474
|
+
repository, train_sentences, labels
|
|
475
|
+
)
|
|
476
|
+
if len(train_document_piece_list.pieces) == 0:
|
|
477
|
+
raise ValueError(
|
|
478
|
+
f"No train document pieces extracted from {repository}."
|
|
479
|
+
)
|
|
480
|
+
else:
|
|
481
|
+
train_document_piece_list = None
|
|
482
|
+
|
|
483
|
+
if dev_sentences is not None:
|
|
484
|
+
dev_document_piece_list = self._get_labelled_document_piece_list(
|
|
485
|
+
repository, dev_sentences, labels
|
|
486
|
+
)
|
|
487
|
+
if len(dev_document_piece_list.pieces) == 0:
|
|
488
|
+
raise ValueError(f"No dev document pieces extracted from {repository}.")
|
|
489
|
+
else:
|
|
490
|
+
dev_document_piece_list = None
|
|
491
|
+
|
|
492
|
+
if test_sentences is not None:
|
|
493
|
+
test_document_piece_list = self._get_labelled_document_piece_list(
|
|
494
|
+
repository, test_sentences, labels
|
|
495
|
+
)
|
|
496
|
+
if len(test_document_piece_list.pieces) == 0:
|
|
497
|
+
raise ValueError(
|
|
498
|
+
f"No test document pieces extracted from {repository}."
|
|
499
|
+
)
|
|
500
|
+
else:
|
|
501
|
+
test_document_piece_list = None
|
|
502
|
+
return (
|
|
503
|
+
train_document_piece_list,
|
|
504
|
+
dev_document_piece_list,
|
|
505
|
+
test_document_piece_list,
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
def _filter_sentences_longer_than_max_tokens(
|
|
509
|
+
self, sentences: list[TokenList]
|
|
510
|
+
) -> list[TokenList]:
|
|
511
|
+
num_filtered_out = len([s for s in sentences if len(s) > self.max_tokens])
|
|
512
|
+
if num_filtered_out > 0:
|
|
513
|
+
max_len = max(len(s) for s in sentences)
|
|
514
|
+
logger.warning(
|
|
515
|
+
f"Filtered out {num_filtered_out} sentences longer than max_tokens={self.max_tokens}; the longest was {max_len} tokens."
|
|
516
|
+
)
|
|
517
|
+
return [s for s in sentences if len(s) <= self.max_tokens]
|