[cad161]: / tests / training / test_train.py

Download this file

210 lines (175 with data), 6.6 kB

  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
# ruff:noqa:E402
import pytest
try:
import torch.nn
except ImportError:
torch = None
if torch is None:
pytest.skip("torch not installed", allow_module_level=True)
pytest.importorskip("rich")
import shutil
from typing import (
Optional,
Sequence,
Union,
)
import pytest
import spacy.tokenizer
import torch.nn
from confit import Config
from confit.utils.random import set_seed
from spacy.tokens import Doc, Span
from edsnlp.core.registries import registry
from edsnlp.data.converters import AttributesMappingArg, get_current_tokenizer
from edsnlp.metrics.dep_parsing import DependencyParsingMetric
from edsnlp.training.optimizer import LinearSchedule, ScheduledOptimizer
from edsnlp.training.trainer import GenericScorer, train
from edsnlp.utils.span_getters import SpanSetterArg, set_spans
@registry.factory.register("myproject.custom_dict2doc", spacy_compatible=False)
class CustomSampleGenerator:
def __init__(
self,
*,
tokenizer: Optional[spacy.tokenizer.Tokenizer] = None,
name: str = "myproject.custom_dict2doc",
span_setter: SpanSetterArg = {"ents": True, "*": True},
bool_attributes: Union[str, Sequence[str]] = [],
span_attributes: Optional[AttributesMappingArg] = None,
):
self.tokenizer = tokenizer
self.name = name
self.span_setter = span_setter
self.bool_attributes = bool_attributes
self.span_attributes = span_attributes
def __call__(self, obj):
tok = get_current_tokenizer() if self.tokenizer is None else self.tokenizer
doc = tok(obj["note_text"] or "")
doc._.note_id = obj.get("note_id", obj.get("__FILENAME__"))
doc._.note_datetime = obj.get("note_datetime")
spans = []
if self.span_attributes is not None:
for dst in self.span_attributes.values():
if not Span.has_extension(dst):
Span.set_extension(dst, default=None)
for ent in obj.get("entities") or ():
ent = dict(ent)
span = doc.char_span(
ent.pop("start"),
ent.pop("end"),
label=ent.pop("label"),
alignment_mode="expand",
)
for label, value in ent.items():
new_name = (
self.span_attributes.get(label, None)
if self.span_attributes is not None
else label
)
if self.span_attributes is None and not Span.has_extension(new_name):
Span.set_extension(new_name, default=None)
if new_name:
span._.set(new_name, value)
spans.append(span)
set_spans(doc, spans, span_setter=self.span_setter)
for attr in self.bool_attributes:
for span in spans:
if span._.get(attr) is None:
span._.set(attr, False)
return doc
def test_ner_qualif_train_diff_bert(run_in_test_dir, tmp_path):
set_seed(42)
config = Config.from_disk("ner_qlf_diff_bert_config.yml")
shutil.rmtree(tmp_path, ignore_errors=True)
kwargs = Config.resolve(config["train"], registry=registry, root=config)
nlp = train(**kwargs, output_dir=tmp_path, cpu=True)
scorer = GenericScorer(**kwargs["scorer"])
val_data = kwargs["val_data"]
last_scores = scorer(nlp, val_data)
# Check empty doc
nlp("")
assert last_scores["ner"]["micro"]["f"] > 0.4
assert last_scores["qual"]["micro"]["f"] > 0.4
def test_ner_qualif_train_same_bert(run_in_test_dir, tmp_path):
set_seed(42)
config = Config.from_disk("ner_qlf_same_bert_config.yml")
shutil.rmtree(tmp_path, ignore_errors=True)
kwargs = Config.resolve(config["train"], registry=registry, root=config)
nlp = train(**kwargs, output_dir=tmp_path, cpu=True)
scorer = GenericScorer(**kwargs["scorer"])
val_data = kwargs["val_data"]
last_scores = scorer(nlp, val_data)
# Check empty doc
nlp("")
assert last_scores["ner"]["micro"]["f"] > 0.4
assert last_scores["qual"]["micro"]["f"] > 0.4
def test_qualif_train(run_in_test_dir, tmp_path):
set_seed(42)
config = Config.from_disk("qlf_config.yml")
shutil.rmtree(tmp_path, ignore_errors=True)
kwargs = Config.resolve(config["train"], registry=registry, root=config)
nlp = train(**kwargs, output_dir=tmp_path, cpu=True)
scorer = GenericScorer(**kwargs["scorer"])
val_data = kwargs["val_data"]
last_scores = scorer(nlp, val_data)
# Check empty doc
nlp("")
assert last_scores["qual"]["micro"]["f"] >= 0.4
def test_dep_parser_train(run_in_test_dir, tmp_path):
set_seed(42)
config = Config.from_disk("dep_parser_config.yml")
shutil.rmtree(tmp_path, ignore_errors=True)
kwargs = Config.resolve(config["train"], registry=registry, root=config)
nlp = train(**kwargs, output_dir=tmp_path, cpu=True)
scorer = GenericScorer(**kwargs["scorer"])
val_data = list(kwargs["val_data"])
last_scores = scorer(nlp, val_data)
scorer_bis = GenericScorer(parser=DependencyParsingMetric(filter_expr="False"))
# Just to test what happens if the scores indicate 2 roots
val_data_bis = [Doc.from_docs([val_data[0], val_data[0]])]
nlp.pipes.parser.decoding_mode = "mst"
last_scores_bis = scorer_bis(nlp, val_data_bis)
assert last_scores_bis["parser"]["uas"] == 0.0
# Check empty doc
nlp("")
assert last_scores["dep"]["las"] >= 0.4
def test_optimizer():
net = torch.nn.Linear(10, 10)
optim = ScheduledOptimizer(
torch.optim.AdamW,
module=net,
total_steps=10,
groups={
".*": {
"lr": 9e-4,
"schedules": LinearSchedule(
warmup_rate=0.1,
start_value=0,
),
}
},
)
for param in net.parameters():
assert "exp_avg" not in optim.optim.state[param]
optim.initialize()
for param in net.parameters():
assert "exp_avg" in optim.optim.state[param]
lr_values = [optim.optim.param_groups[0]["lr"]]
for i in range(10):
optim.step()
lr_values.append(optim.optim.param_groups[0]["lr"])
# close enough
assert lr_values == pytest.approx(
[
0.0,
0.0009,
0.0008,
0.0007,
0.0006,
0.0005,
0.0004,
0.0003,
0.0002,
0.0001,
0.0,
]
)