Upload folder using huggingface_hub
Browse files- README.md +12 -0
- config.json +30 -0
- configuration_borg.py +22 -0
- eval/__init__.py +0 -0
- eval/conll18_ud_eval.py +432 -0
- modeling_borg.py +25 -0
- pipeline.py +239 -0
- pytorch_model.bin +3 -0
- requirements.txt +8 -0
- src/__init__.py +1 -0
- src/config.py +117 -0
- src/data/__init__.py +1 -0
- src/data/conllu.py +220 -0
- src/data/dataset.py +610 -0
- src/models/__init__.py +1 -0
- src/models/base.py +100 -0
- src/models/checkpoints.py +131 -0
- src/models/evaluation.py +52 -0
- src/models/inference.py +129 -0
- src/models/lemmatizer.py +515 -0
- src/models/mwt.py +424 -0
- src/models/parser.py +692 -0
- src/models/tagger.py +314 -0
- src/models/tokenizer.py +414 -0
- src/pipeline/__init__.py +1 -0
- src/pipeline/hf/__init__.py +5 -0
- src/pipeline/hf/config.json +22 -0
- src/pipeline/hf/configuration_borg.py +22 -0
- src/pipeline/hf/export.py +114 -0
- src/pipeline/hf/modeling_borg.py +25 -0
- src/pipeline/hf/pipeline.py +239 -0
- src/pipeline/pipeline.py +163 -0
README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Borg Cube
|
| 2 |
+
|
| 3 |
+
This repository contains the borg-cube pipeline configuration and runtime code, but not its component weights. Publish each component to a model repository named by appending `-<component>` to this repository ID (for example, `racai-ai/mixed-tokenizer`). The pipeline downloads the listed components at runtime. Pass `adapter_variant` to select repositories with an additional suffix, such as `racai/borg-tokenizer-combined`; omit it for default repositories. Its custom pipeline code is loaded by Transformers; review it before enabling `trust_remote_code`.
|
| 4 |
+
|
| 5 |
+
Install the dependencies listed in `requirements.txt`, then run:
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
from transformers import pipeline
|
| 9 |
+
|
| 10 |
+
nlp = pipeline(model="your-username/your-nlp-repo", trust_remote_code=True, adapter_variant='combined')
|
| 11 |
+
result = nlp("Your input text here")
|
| 12 |
+
```
|
config.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"BorgHFModel"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_borg.BorgHFConfig",
|
| 7 |
+
"AutoModel": "modeling_borg.BorgHFModel"
|
| 8 |
+
},
|
| 9 |
+
"borg_config": {},
|
| 10 |
+
"checkpoint": "best",
|
| 11 |
+
"components": [
|
| 12 |
+
"tokenizer",
|
| 13 |
+
"mwt",
|
| 14 |
+
"tagger",
|
| 15 |
+
"parser",
|
| 16 |
+
"lemmatizer"
|
| 17 |
+
],
|
| 18 |
+
"custom_pipelines": {
|
| 19 |
+
"borg-cube": {
|
| 20 |
+
"impl": "pipeline.BorgHFPipeline",
|
| 21 |
+
"pt": [
|
| 22 |
+
"AutoModel"
|
| 23 |
+
],
|
| 24 |
+
"tf": []
|
| 25 |
+
}
|
| 26 |
+
},
|
| 27 |
+
"dtype": "float32",
|
| 28 |
+
"model_type": "borg_cube",
|
| 29 |
+
"transformers_version": "4.57.6"
|
| 30 |
+
}
|
configuration_borg.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face configuration for exported borg-cube pipelines."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import Any, Dict, List, Optional
|
| 5 |
+
|
| 6 |
+
from transformers import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class BorgHFConfig(PretrainedConfig):
|
| 10 |
+
model_type = "borg_cube"
|
| 11 |
+
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
borg_config: Optional[Dict[str, Any]] = None,
|
| 15 |
+
components: Optional[List[str]] = None,
|
| 16 |
+
checkpoint: str = "best",
|
| 17 |
+
**kwargs,
|
| 18 |
+
):
|
| 19 |
+
super().__init__(**kwargs)
|
| 20 |
+
self.borg_config = borg_config or {}
|
| 21 |
+
self.components = components if components is not None else []
|
| 22 |
+
self.checkpoint = checkpoint
|
eval/__init__.py
ADDED
|
File without changes
|
eval/conll18_ud_eval.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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#!/usr/bin/env python3
|
| 2 |
+
"""UD evaluation script (CoNLL 2018 shared task evaluation).
|
| 3 |
+
|
| 4 |
+
Computes:
|
| 5 |
+
Tokens, Sentences, Words, UPOS, XPOS, FEATS, UAS, LAS, MLAS, BLEX, LEMMA
|
| 6 |
+
|
| 7 |
+
Usage (standalone)::
|
| 8 |
+
|
| 9 |
+
python conll18_ud_eval.py gold.conllu system.conllu
|
| 10 |
+
|
| 11 |
+
Usage (as module)::
|
| 12 |
+
|
| 13 |
+
from eval.conll18_ud_eval import evaluate
|
| 14 |
+
metrics = evaluate("gold.conllu", "system.conllu")
|
| 15 |
+
print(metrics["LAS"])
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import sys
|
| 21 |
+
import unicodedata
|
| 22 |
+
from collections import Counter
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
from typing import Dict, Iterator, List, Optional, Tuple
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
# Data structures
|
| 29 |
+
# ---------------------------------------------------------------------------
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class UDWord:
|
| 33 |
+
"""A single (non-MWT, non-empty) token in a UD sentence."""
|
| 34 |
+
form: str
|
| 35 |
+
lemma: str
|
| 36 |
+
upos: str
|
| 37 |
+
xpos: str
|
| 38 |
+
feats: str
|
| 39 |
+
head: int
|
| 40 |
+
deprel: str
|
| 41 |
+
deps: str
|
| 42 |
+
misc: str
|
| 43 |
+
# Span in the raw reconstructed text (character offsets)
|
| 44 |
+
span_start: int = 0
|
| 45 |
+
span_end: int = 0
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class UDSentence:
|
| 50 |
+
words: List[UDWord]
|
| 51 |
+
text: Optional[str] # sent_text from # text = comment
|
| 52 |
+
token_forms: Optional[List[str]] = None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class EvalResult:
|
| 57 |
+
precision: float
|
| 58 |
+
recall: float
|
| 59 |
+
f1: float
|
| 60 |
+
aligned_count: int
|
| 61 |
+
gold_count: int
|
| 62 |
+
system_count: int
|
| 63 |
+
|
| 64 |
+
def __str__(self) -> str:
|
| 65 |
+
return f"P={self.precision:.2%} R={self.recall:.2%} F1={self.f1:.2%}"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---------------------------------------------------------------------------
|
| 69 |
+
# CoNLL-U reading
|
| 70 |
+
# ---------------------------------------------------------------------------
|
| 71 |
+
|
| 72 |
+
def _is_mwt(id_str: str) -> bool:
|
| 73 |
+
return "-" in id_str
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _is_empty(id_str: str) -> bool:
|
| 77 |
+
return "." in id_str
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _load_conllu(path: str) -> List[UDSentence]:
|
| 81 |
+
sentences: List[UDSentence] = []
|
| 82 |
+
words: List[UDWord] = []
|
| 83 |
+
token_forms: List[str] = []
|
| 84 |
+
multiword_end = 0
|
| 85 |
+
sent_text: Optional[str] = None
|
| 86 |
+
|
| 87 |
+
with open(path, encoding="utf-8") as fh:
|
| 88 |
+
for raw_line in fh:
|
| 89 |
+
line = raw_line.rstrip("\n")
|
| 90 |
+
if line.startswith("# text ="):
|
| 91 |
+
sent_text = line[len("# text ="):].strip()
|
| 92 |
+
elif line.startswith("#"):
|
| 93 |
+
continue
|
| 94 |
+
elif line == "":
|
| 95 |
+
if words:
|
| 96 |
+
sentences.append(UDSentence(words=words, text=sent_text, token_forms=token_forms))
|
| 97 |
+
words = []
|
| 98 |
+
token_forms = []
|
| 99 |
+
multiword_end = 0
|
| 100 |
+
sent_text = None
|
| 101 |
+
else:
|
| 102 |
+
cols = line.split("\t")
|
| 103 |
+
if len(cols) != 10:
|
| 104 |
+
continue
|
| 105 |
+
id_str = cols[0]
|
| 106 |
+
if _is_empty(id_str):
|
| 107 |
+
continue
|
| 108 |
+
if _is_mwt(id_str):
|
| 109 |
+
token_forms.append(cols[1])
|
| 110 |
+
multiword_end = int(id_str.split("-", 1)[1])
|
| 111 |
+
continue
|
| 112 |
+
if int(id_str) > multiword_end:
|
| 113 |
+
token_forms.append(cols[1])
|
| 114 |
+
head = int(cols[6]) if cols[6] != "_" else 0
|
| 115 |
+
words.append(UDWord(
|
| 116 |
+
form=cols[1],
|
| 117 |
+
lemma=cols[2],
|
| 118 |
+
upos=cols[3],
|
| 119 |
+
xpos=cols[4],
|
| 120 |
+
feats=cols[5],
|
| 121 |
+
head=head,
|
| 122 |
+
deprel=cols[7],
|
| 123 |
+
deps=cols[8],
|
| 124 |
+
misc=cols[9],
|
| 125 |
+
))
|
| 126 |
+
|
| 127 |
+
if words:
|
| 128 |
+
sentences.append(UDSentence(words=words, text=sent_text, token_forms=token_forms))
|
| 129 |
+
|
| 130 |
+
return sentences
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# ---------------------------------------------------------------------------
|
| 134 |
+
# Alignment
|
| 135 |
+
# ---------------------------------------------------------------------------
|
| 136 |
+
|
| 137 |
+
def _normalize(text: str) -> str:
|
| 138 |
+
"""Unicode NFC normalization for character-level alignment."""
|
| 139 |
+
return unicodedata.normalize("NFC", text)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _build_char_sequence(sentences: List[UDSentence]) -> Tuple[str, List[Tuple[int, int]]]:
|
| 143 |
+
"""Build concatenated text and word spans."""
|
| 144 |
+
chars: List[str] = []
|
| 145 |
+
spans: List[Tuple[int, int]] = []
|
| 146 |
+
|
| 147 |
+
for sent in sentences:
|
| 148 |
+
for word in sent.words:
|
| 149 |
+
start = len(chars)
|
| 150 |
+
chars.extend(_normalize(word.form))
|
| 151 |
+
end = len(chars)
|
| 152 |
+
spans.append((start, end))
|
| 153 |
+
|
| 154 |
+
return "".join(chars), spans
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _build_surface_sequence(
|
| 158 |
+
sentences: List[UDSentence],
|
| 159 |
+
) -> Tuple[str, List[Tuple[int, int]], List[Tuple[int, int]]]:
|
| 160 |
+
"""Build surface-token and sentence spans without Unicode Zs spaces."""
|
| 161 |
+
chars: List[str] = []
|
| 162 |
+
token_spans: List[Tuple[int, int]] = []
|
| 163 |
+
sentence_spans: List[Tuple[int, int]] = []
|
| 164 |
+
for sentence in sentences:
|
| 165 |
+
start = len(chars)
|
| 166 |
+
forms = sentence.token_forms
|
| 167 |
+
if forms is None:
|
| 168 |
+
forms = [word.form for word in sentence.words]
|
| 169 |
+
for form in forms:
|
| 170 |
+
token_start = len(chars)
|
| 171 |
+
chars.extend(char for char in form if unicodedata.category(char) != "Zs")
|
| 172 |
+
if len(chars) == token_start:
|
| 173 |
+
raise ValueError("There is an empty FORM in the CoNLL-U file")
|
| 174 |
+
token_spans.append((token_start, len(chars)))
|
| 175 |
+
sentence_spans.append((start, len(chars)))
|
| 176 |
+
return "".join(chars), token_spans, sentence_spans
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _align_spans(
|
| 180 |
+
gold_spans: List[Tuple[int, int]],
|
| 181 |
+
sys_spans: List[Tuple[int, int]],
|
| 182 |
+
gold_text: str,
|
| 183 |
+
sys_text: str,
|
| 184 |
+
) -> List[Optional[int]]:
|
| 185 |
+
"""Align gold word spans to system word spans by character offsets.
|
| 186 |
+
|
| 187 |
+
Returns a list of length len(gold_spans) where each entry is either
|
| 188 |
+
an index into sys_spans (exact match) or None.
|
| 189 |
+
"""
|
| 190 |
+
sys_span_set: Dict[Tuple[int, int], int] = {sp: i for i, sp in enumerate(sys_spans)}
|
| 191 |
+
alignment: List[Optional[int]] = []
|
| 192 |
+
for span in gold_spans:
|
| 193 |
+
alignment.append(sys_span_set.get(span))
|
| 194 |
+
return alignment
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# ---------------------------------------------------------------------------
|
| 198 |
+
# Evaluation logic
|
| 199 |
+
# ---------------------------------------------------------------------------
|
| 200 |
+
|
| 201 |
+
def _feats_intersect(gold_feats: str, sys_feats: str) -> int:
|
| 202 |
+
"""Number of feature key=value pairs in common."""
|
| 203 |
+
if gold_feats == "_" and sys_feats == "_":
|
| 204 |
+
return 1 # both empty — counts as agreement
|
| 205 |
+
if gold_feats == "_" or sys_feats == "_":
|
| 206 |
+
return 0
|
| 207 |
+
g = set(gold_feats.split("|"))
|
| 208 |
+
s = set(sys_feats.split("|"))
|
| 209 |
+
return len(g & s)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _sentence_starts(sentences: List[UDSentence]) -> List[int]:
|
| 213 |
+
"""For each flattened word (across all sentences), the global index of
|
| 214 |
+
the first word in that word's own sentence.
|
| 215 |
+
|
| 216 |
+
``UDWord.head`` is a 1-based index that is only meaningful *within its
|
| 217 |
+
own sentence* (0 means the virtual ROOT). To compare a gold head with a
|
| 218 |
+
system head we first need to translate both into global positions in
|
| 219 |
+
the respective flattened word list.
|
| 220 |
+
"""
|
| 221 |
+
starts: List[int] = []
|
| 222 |
+
pos = 0
|
| 223 |
+
for sent in sentences:
|
| 224 |
+
starts.extend([pos] * len(sent.words))
|
| 225 |
+
pos += len(sent.words)
|
| 226 |
+
return starts
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _resolve_head_global(head: int, sent_start: int) -> int:
|
| 230 |
+
"""Translate a sentence-relative head index into a global word index.
|
| 231 |
+
|
| 232 |
+
Returns ``-1`` as a sentinel for the virtual ROOT (head == 0).
|
| 233 |
+
"""
|
| 234 |
+
if head == 0:
|
| 235 |
+
return -1
|
| 236 |
+
return sent_start + head - 1
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _mlas_correct(g: UDWord, s: UDWord, heads_match: bool) -> bool:
|
| 240 |
+
"""MLAS: LAS + UPOS + FEATS on both dep and head."""
|
| 241 |
+
return (
|
| 242 |
+
heads_match
|
| 243 |
+
and g.deprel.lower() == s.deprel.lower()
|
| 244 |
+
and g.upos == s.upos
|
| 245 |
+
and g.feats == s.feats
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _blex_correct(g: UDWord, s: UDWord, heads_match: bool) -> bool:
|
| 250 |
+
"""BLEX: LAS + LEMMA."""
|
| 251 |
+
return (
|
| 252 |
+
heads_match
|
| 253 |
+
and g.deprel.lower() == s.deprel.lower()
|
| 254 |
+
and g.lemma.lower() == s.lemma.lower()
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def evaluate(gold_file: str, system_file: str) -> Dict[str, EvalResult]:
|
| 259 |
+
"""Evaluate *system_file* against *gold_file*.
|
| 260 |
+
|
| 261 |
+
Returns a dict mapping metric name → EvalResult.
|
| 262 |
+
"""
|
| 263 |
+
gold_sents = _load_conllu(gold_file)
|
| 264 |
+
sys_sents = _load_conllu(system_file)
|
| 265 |
+
|
| 266 |
+
gold_surface_text, gold_token_spans, gold_sentence_spans = _build_surface_sequence(gold_sents)
|
| 267 |
+
sys_surface_text, sys_token_spans, sys_sentence_spans = _build_surface_sequence(sys_sents)
|
| 268 |
+
if gold_surface_text != sys_surface_text:
|
| 269 |
+
raise ValueError("The concatenation of tokens in gold file and in system file differ!")
|
| 270 |
+
|
| 271 |
+
gold_text, gold_spans = _build_char_sequence(gold_sents)
|
| 272 |
+
sys_text, sys_spans = _build_char_sequence(sys_sents)
|
| 273 |
+
|
| 274 |
+
alignment = _align_spans(gold_spans, sys_spans, gold_text, sys_text)
|
| 275 |
+
|
| 276 |
+
# Flatten word lists
|
| 277 |
+
gold_words = [w for s in gold_sents for w in s.words]
|
| 278 |
+
sys_words = [w for s in sys_sents for w in s.words]
|
| 279 |
+
|
| 280 |
+
n_gold = len(gold_words)
|
| 281 |
+
n_sys = len(sys_words)
|
| 282 |
+
|
| 283 |
+
# Per-word global sentence-start offsets, used to translate the
|
| 284 |
+
# sentence-relative `head` index into a position in the flattened word
|
| 285 |
+
# list (see `_resolve_head_global`).
|
| 286 |
+
gold_sent_starts = _sentence_starts(gold_sents)
|
| 287 |
+
sys_sent_starts = _sentence_starts(sys_sents)
|
| 288 |
+
|
| 289 |
+
# Per-metric counters
|
| 290 |
+
counts: Dict[str, int] = Counter()
|
| 291 |
+
|
| 292 |
+
for g_idx, (g_word, sys_idx) in enumerate(zip(gold_words, alignment)):
|
| 293 |
+
if sys_idx is None:
|
| 294 |
+
continue
|
| 295 |
+
s_word = sys_words[sys_idx]
|
| 296 |
+
|
| 297 |
+
# UPOS
|
| 298 |
+
if g_word.upos == s_word.upos:
|
| 299 |
+
counts["UPOS_correct"] += 1
|
| 300 |
+
|
| 301 |
+
# XPOS
|
| 302 |
+
if g_word.xpos == s_word.xpos:
|
| 303 |
+
counts["XPOS_correct"] += 1
|
| 304 |
+
|
| 305 |
+
# FEATS
|
| 306 |
+
if g_word.feats == s_word.feats:
|
| 307 |
+
counts["FEATS_correct"] += 1
|
| 308 |
+
|
| 309 |
+
# LEMMA
|
| 310 |
+
if g_word.lemma.lower() == s_word.lemma.lower():
|
| 311 |
+
counts["LEMMA_correct"] += 1
|
| 312 |
+
|
| 313 |
+
# Resolve each word's head through the alignment rather than
|
| 314 |
+
# comparing raw sentence-relative indices: `head` is only
|
| 315 |
+
# meaningful within its own sentence, so whenever gold/system
|
| 316 |
+
# token counts differ (e.g. a contraction segmented differently),
|
| 317 |
+
# raw indices drift out of sync even for otherwise-correct arcs.
|
| 318 |
+
# Instead, map the gold word's head to the *word* it points to,
|
| 319 |
+
# find that word's aligned system word, and check whether the
|
| 320 |
+
# system word's own head points to that same aligned word.
|
| 321 |
+
gold_head_global = _resolve_head_global(g_word.head, gold_sent_starts[g_idx])
|
| 322 |
+
gold_head_target_sys = (
|
| 323 |
+
-1 if gold_head_global == -1 else alignment[gold_head_global]
|
| 324 |
+
)
|
| 325 |
+
sys_head_value = _resolve_head_global(s_word.head, sys_sent_starts[sys_idx])
|
| 326 |
+
heads_match = (
|
| 327 |
+
gold_head_target_sys is not None and gold_head_target_sys == sys_head_value
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
# UAS (head)
|
| 331 |
+
if heads_match:
|
| 332 |
+
counts["UAS_correct"] += 1
|
| 333 |
+
|
| 334 |
+
# LAS (head + deprel, case-insensitive deprel)
|
| 335 |
+
if heads_match and g_word.deprel.lower() == s_word.deprel.lower():
|
| 336 |
+
counts["LAS_correct"] += 1
|
| 337 |
+
|
| 338 |
+
# MLAS: LAS + UPOS + FEATS
|
| 339 |
+
if _mlas_correct(g_word, s_word, heads_match):
|
| 340 |
+
counts["MLAS_correct"] += 1
|
| 341 |
+
|
| 342 |
+
# BLEX: LAS + LEMMA
|
| 343 |
+
if _blex_correct(g_word, s_word, heads_match):
|
| 344 |
+
counts["BLEX_correct"] += 1
|
| 345 |
+
|
| 346 |
+
def make_result(correct_key: str) -> EvalResult:
|
| 347 |
+
correct = counts.get(correct_key, 0)
|
| 348 |
+
p = correct / max(n_sys, 1)
|
| 349 |
+
r = correct / max(n_gold, 1)
|
| 350 |
+
f1 = 2 * p * r / max(p + r, 1e-12)
|
| 351 |
+
return EvalResult(
|
| 352 |
+
precision=p, recall=r, f1=f1,
|
| 353 |
+
aligned_count=correct, gold_count=n_gold, system_count=n_sys,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# Sentence-level
|
| 357 |
+
n_gold_sent = len(gold_sents)
|
| 358 |
+
n_sys_sent = len(sys_sents)
|
| 359 |
+
sys_sentence_span_set = set(sys_sentence_spans)
|
| 360 |
+
sent_correct = sum(span in sys_sentence_span_set for span in gold_sentence_spans)
|
| 361 |
+
|
| 362 |
+
n_gold_tokens = len(gold_token_spans)
|
| 363 |
+
n_sys_tokens = len(sys_token_spans)
|
| 364 |
+
sys_token_span_set = set(sys_token_spans)
|
| 365 |
+
token_correct = sum(span in sys_token_span_set for span in gold_token_spans)
|
| 366 |
+
|
| 367 |
+
results: Dict[str, EvalResult] = {
|
| 368 |
+
"Tokens": EvalResult(
|
| 369 |
+
precision=token_correct / max(n_sys_tokens, 1),
|
| 370 |
+
recall=token_correct / max(n_gold_tokens, 1),
|
| 371 |
+
f1=2 * token_correct / max(n_gold_tokens + n_sys_tokens, 1),
|
| 372 |
+
aligned_count=token_correct,
|
| 373 |
+
gold_count=n_gold_tokens,
|
| 374 |
+
system_count=n_sys_tokens,
|
| 375 |
+
),
|
| 376 |
+
"Sentences": EvalResult(
|
| 377 |
+
precision=sent_correct / max(n_sys_sent, 1),
|
| 378 |
+
recall=sent_correct / max(n_gold_sent, 1),
|
| 379 |
+
f1=2 * sent_correct / max(n_gold_sent + n_sys_sent, 1),
|
| 380 |
+
aligned_count=sent_correct,
|
| 381 |
+
gold_count=n_gold_sent,
|
| 382 |
+
system_count=n_sys_sent,
|
| 383 |
+
),
|
| 384 |
+
"UPOS": make_result("UPOS_correct"),
|
| 385 |
+
"XPOS": make_result("XPOS_correct"),
|
| 386 |
+
"FEATS": make_result("FEATS_correct"),
|
| 387 |
+
"LEMMA": make_result("LEMMA_correct"),
|
| 388 |
+
"UAS": make_result("UAS_correct"),
|
| 389 |
+
"LAS": make_result("LAS_correct"),
|
| 390 |
+
"MLAS": make_result("MLAS_correct"),
|
| 391 |
+
"BLEX": make_result("BLEX_correct"),
|
| 392 |
+
}
|
| 393 |
+
return results
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
# ---------------------------------------------------------------------------
|
| 397 |
+
# Standalone CLI
|
| 398 |
+
# ---------------------------------------------------------------------------
|
| 399 |
+
|
| 400 |
+
def _print_results(results: Dict[str, EvalResult]) -> None:
|
| 401 |
+
metrics_order = ["Tokens", "Sentences", "UPOS", "XPOS", "FEATS", "LEMMA", "UAS", "LAS", "MLAS", "BLEX"]
|
| 402 |
+
print(f"{'Metric':<12} {'Precision':>10} {'Recall':>10} {'F1':>10} {'Gold':>8} {'System':>8}")
|
| 403 |
+
print("-" * 62)
|
| 404 |
+
for name in metrics_order:
|
| 405 |
+
if name not in results:
|
| 406 |
+
continue
|
| 407 |
+
r = results[name]
|
| 408 |
+
print(
|
| 409 |
+
f"{name:<12} {r.precision:>10.2%} {r.recall:>10.2%} {r.f1:>10.2%}"
|
| 410 |
+
f" {r.gold_count:>8} {r.system_count:>8}"
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def main(argv=None) -> None:
|
| 415 |
+
parser = argparse.ArgumentParser(
|
| 416 |
+
description="CoNLL-U UD evaluation (CoNLL 2018 style)"
|
| 417 |
+
)
|
| 418 |
+
parser.add_argument("gold_file", help="Gold CoNLL-U file")
|
| 419 |
+
parser.add_argument("system_file", help="System CoNLL-U file")
|
| 420 |
+
parser.add_argument("--quiet", action="store_true", help="Only print LAS F1")
|
| 421 |
+
args = parser.parse_args(argv)
|
| 422 |
+
|
| 423 |
+
results = evaluate(args.gold_file, args.system_file)
|
| 424 |
+
|
| 425 |
+
if args.quiet:
|
| 426 |
+
print(f"LAS: {results['LAS'].f1:.4f}")
|
| 427 |
+
else:
|
| 428 |
+
_print_results(results)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
if __name__ == "__main__":
|
| 432 |
+
main()
|
modeling_borg.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lightweight AutoModel used to load a custom borg-cube pipeline from the Hub."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import PreTrainedModel
|
| 8 |
+
|
| 9 |
+
from .configuration_borg import BorgHFConfig
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class BorgHFModel(PreTrainedModel):
|
| 13 |
+
config_class = BorgHFConfig
|
| 14 |
+
base_model_prefix = "borg_cube"
|
| 15 |
+
|
| 16 |
+
def __init__(self, config: BorgHFConfig):
|
| 17 |
+
super().__init__(config)
|
| 18 |
+
self.register_buffer("_pipeline_marker", torch.zeros(1))
|
| 19 |
+
self.post_init()
|
| 20 |
+
|
| 21 |
+
def forward(self, *args: Any, **kwargs: Any):
|
| 22 |
+
raise RuntimeError(
|
| 23 |
+
"BorgHFModel is a Hub loading marker; inference runs through "
|
| 24 |
+
"the registered BorgHFPipeline."
|
| 25 |
+
)
|
pipeline.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transformers Pipeline adapter for borg-cube checkpoints."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Dict, List, Optional, Sequence
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import snapshot_download
|
| 10 |
+
from transformers.pipelines import Pipeline
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_COMPONENTS = ("tokenizer", "mwt", "tagger", "parser", "lemmatizer")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _read_component(path: Path) -> str:
|
| 17 |
+
with (path / "borg_config.json").open(encoding="utf-8") as source:
|
| 18 |
+
component = json.load(source).get("component")
|
| 19 |
+
if component not in _COMPONENTS:
|
| 20 |
+
raise ValueError(f"Checkpoint at {str(path)!r} has an invalid component")
|
| 21 |
+
return component
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _discover_checkpoints(
|
| 25 |
+
model_path: Path,
|
| 26 |
+
components: Sequence[str],
|
| 27 |
+
checkpoint: str,
|
| 28 |
+
) -> Dict[str, Path]:
|
| 29 |
+
if not model_path.is_dir():
|
| 30 |
+
raise FileNotFoundError(f"Borg model directory not found: {model_path}")
|
| 31 |
+
|
| 32 |
+
direct_config = model_path / "borg_config.json"
|
| 33 |
+
if direct_config.is_file():
|
| 34 |
+
component = _read_component(model_path)
|
| 35 |
+
if component not in components:
|
| 36 |
+
raise ValueError(
|
| 37 |
+
f"The checkpoint contains {component!r}, which is not in components"
|
| 38 |
+
)
|
| 39 |
+
return {component: model_path}
|
| 40 |
+
|
| 41 |
+
if model_path.name in _COMPONENTS:
|
| 42 |
+
checkpoint_path = model_path / checkpoint
|
| 43 |
+
if (checkpoint_path / "borg_config.json").is_file():
|
| 44 |
+
return {model_path.name: checkpoint_path}
|
| 45 |
+
|
| 46 |
+
found: Dict[str, Path] = {}
|
| 47 |
+
for component in components:
|
| 48 |
+
component_path = model_path / component
|
| 49 |
+
if (component_path / "borg_config.json").is_file():
|
| 50 |
+
found[component] = component_path
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
checkpoint_path = component_path / checkpoint
|
| 54 |
+
if (checkpoint_path / "borg_config.json").is_file():
|
| 55 |
+
found[component] = checkpoint_path
|
| 56 |
+
|
| 57 |
+
if not found:
|
| 58 |
+
raise FileNotFoundError(
|
| 59 |
+
f"No {checkpoint!r} Borg checkpoints found under {model_path}"
|
| 60 |
+
)
|
| 61 |
+
return found
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _load_config(path: Path):
|
| 65 |
+
from src.config import BorgConfig
|
| 66 |
+
|
| 67 |
+
with (path / "borg_config.json").open(encoding="utf-8") as source:
|
| 68 |
+
return BorgConfig.from_dict(json.load(source))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _sentence_to_dict(sentence) -> Dict[str, Any]:
|
| 72 |
+
return {
|
| 73 |
+
"comments": list(sentence.comments),
|
| 74 |
+
"tokens": [
|
| 75 |
+
{
|
| 76 |
+
"id": token.id,
|
| 77 |
+
"form": token.form,
|
| 78 |
+
"lemma": token.lemma,
|
| 79 |
+
"upos": token.upos,
|
| 80 |
+
"xpos": token.xpos,
|
| 81 |
+
"feats": token.feats_str(),
|
| 82 |
+
"head": token.head,
|
| 83 |
+
"deprel": token.deprel,
|
| 84 |
+
"deps": token.deps,
|
| 85 |
+
"misc": token.misc,
|
| 86 |
+
"space_after": token.space_after,
|
| 87 |
+
"is_mwt": token.is_mwt,
|
| 88 |
+
}
|
| 89 |
+
for token in sentence.tokens
|
| 90 |
+
],
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class _PassthroughTokenizer:
|
| 95 |
+
pad_token_id = 0
|
| 96 |
+
padding_side = "right"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _repository_path(model) -> Path:
|
| 100 |
+
model_id = getattr(model.config, "_name_or_path", None)
|
| 101 |
+
if not model_id:
|
| 102 |
+
raise ValueError("The Borg model config does not identify its Hub repository")
|
| 103 |
+
|
| 104 |
+
path = Path(model_id).expanduser()
|
| 105 |
+
if path.is_dir():
|
| 106 |
+
return path
|
| 107 |
+
return Path(
|
| 108 |
+
snapshot_download(
|
| 109 |
+
model_id,
|
| 110 |
+
revision=getattr(model.config, "_commit_hash", None),
|
| 111 |
+
)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _runtime_device(config, device) -> Any:
|
| 116 |
+
import torch
|
| 117 |
+
|
| 118 |
+
if device is not None:
|
| 119 |
+
if isinstance(device, int):
|
| 120 |
+
config.device = "cpu" if device < 0 else f"cuda:{device}"
|
| 121 |
+
else:
|
| 122 |
+
config.device = str(device)
|
| 123 |
+
return torch.device(config.resolve_device())
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _adapter_repo_id(base_repo_id: str, component: str, variant: Optional[str]) -> str:
|
| 127 |
+
if variant is None:
|
| 128 |
+
return f"{base_repo_id}-{component}"
|
| 129 |
+
if (
|
| 130 |
+
not isinstance(variant, str)
|
| 131 |
+
or not variant
|
| 132 |
+
or variant.strip() != variant
|
| 133 |
+
or "/" in variant
|
| 134 |
+
or "\\" in variant
|
| 135 |
+
):
|
| 136 |
+
raise ValueError("adapter_variant must be a non-empty repository name suffix")
|
| 137 |
+
return f"{base_repo_id}-{component}-{variant}"
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _load_engine(model, device, adapter_variant: Optional[str] = None):
|
| 141 |
+
repo_path = _repository_path(model)
|
| 142 |
+
repo_string = str(repo_path)
|
| 143 |
+
if repo_string not in sys.path:
|
| 144 |
+
sys.path.insert(0, repo_string)
|
| 145 |
+
|
| 146 |
+
from src.config import BorgConfig
|
| 147 |
+
from src.pipeline.pipeline import BorgPipeline
|
| 148 |
+
|
| 149 |
+
adapter_checkpoints = []
|
| 150 |
+
for component in model.config.components:
|
| 151 |
+
adapter_repo_id = _adapter_repo_id(
|
| 152 |
+
model.config._name_or_path,
|
| 153 |
+
component,
|
| 154 |
+
adapter_variant,
|
| 155 |
+
)
|
| 156 |
+
adapter_repo_path = Path(snapshot_download(adapter_repo_id))
|
| 157 |
+
checkpoint_path = adapter_repo_path / model.config.checkpoint
|
| 158 |
+
if not (checkpoint_path / "borg_config.json").is_file():
|
| 159 |
+
if not (adapter_repo_path / "borg_config.json").is_file():
|
| 160 |
+
raise FileNotFoundError(
|
| 161 |
+
f"Repository {adapter_repo_id!r} has no "
|
| 162 |
+
f"{model.config.checkpoint!r} checkpoint for {component!r}"
|
| 163 |
+
)
|
| 164 |
+
checkpoint_path = adapter_repo_path
|
| 165 |
+
adapter_checkpoints.append((component, checkpoint_path))
|
| 166 |
+
|
| 167 |
+
if not adapter_checkpoints:
|
| 168 |
+
raise ValueError("The Borg pipeline config does not list any adapters")
|
| 169 |
+
|
| 170 |
+
if model.config.borg_config:
|
| 171 |
+
config = BorgConfig.from_dict(model.config.borg_config)
|
| 172 |
+
else:
|
| 173 |
+
config = _load_config(adapter_checkpoints[0][1])
|
| 174 |
+
runtime_device = _runtime_device(config, device)
|
| 175 |
+
engine = BorgPipeline(config)
|
| 176 |
+
for component, checkpoint_path in adapter_checkpoints:
|
| 177 |
+
engine.load_component(component, str(checkpoint_path))
|
| 178 |
+
|
| 179 |
+
return engine, runtime_device
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class BorgHFPipeline(Pipeline):
|
| 183 |
+
"""Hub-loadable pipeline for complete borg-cube checkpoints."""
|
| 184 |
+
|
| 185 |
+
def __init__(
|
| 186 |
+
self,
|
| 187 |
+
model,
|
| 188 |
+
tokenizer=None,
|
| 189 |
+
framework: Optional[str] = None,
|
| 190 |
+
task: str = "borg-cube",
|
| 191 |
+
device=None,
|
| 192 |
+
adapter_variant: Optional[str] = None,
|
| 193 |
+
**kwargs,
|
| 194 |
+
):
|
| 195 |
+
self.engine, runtime_device = _load_engine(
|
| 196 |
+
model,
|
| 197 |
+
device,
|
| 198 |
+
adapter_variant=adapter_variant,
|
| 199 |
+
)
|
| 200 |
+
super().__init__(
|
| 201 |
+
model=model,
|
| 202 |
+
tokenizer=(
|
| 203 |
+
tokenizer if tokenizer is not None else _PassthroughTokenizer()
|
| 204 |
+
),
|
| 205 |
+
framework=framework or "pt",
|
| 206 |
+
task=task,
|
| 207 |
+
device=runtime_device,
|
| 208 |
+
**kwargs,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def _sanitize_parameters(self, show_progress: bool = False, **kwargs):
|
| 212 |
+
if kwargs:
|
| 213 |
+
raise TypeError(
|
| 214 |
+
f"Unexpected pipeline parameters: {', '.join(sorted(kwargs))}"
|
| 215 |
+
)
|
| 216 |
+
return {}, {"show_progress": show_progress}, {}
|
| 217 |
+
|
| 218 |
+
def preprocess(self, input_: Any, **preprocess_parameters) -> Dict[str, Any]:
|
| 219 |
+
if not isinstance(input_, str):
|
| 220 |
+
raise TypeError("BorgHFPipeline inputs must be strings")
|
| 221 |
+
return {"text": input_}
|
| 222 |
+
|
| 223 |
+
def _forward(self, input_tensors: Dict[str, Any], show_progress: bool = False):
|
| 224 |
+
texts = input_tensors["text"]
|
| 225 |
+
if isinstance(texts, str):
|
| 226 |
+
texts = [texts]
|
| 227 |
+
return {
|
| 228 |
+
"sentences": [
|
| 229 |
+
self.engine.process(text, show_progress=show_progress)
|
| 230 |
+
for text in texts
|
| 231 |
+
]
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
def postprocess(self, model_outputs: Any) -> List[Dict[str, Any]]:
|
| 235 |
+
if isinstance(model_outputs, dict):
|
| 236 |
+
sentences = model_outputs["sentences"][0]
|
| 237 |
+
else:
|
| 238 |
+
sentences = model_outputs
|
| 239 |
+
return [_sentence_to_dict(sentence) for sentence in sentences]
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e2dec11a5a1cf3e740cd391ae859edf5a91e07deabc29c44f86594abace4ae54
|
| 3 |
+
size 1619
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.0.0
|
| 2 |
+
transformers>=4.35.0
|
| 3 |
+
huggingface_hub>=0.19.0
|
| 4 |
+
adapters>=0.1.1
|
| 5 |
+
numpy>=1.24.0
|
| 6 |
+
tqdm>=4.65.0
|
| 7 |
+
sentencepiece>=0.1.99
|
| 8 |
+
protobuf>=3.20.0
|
src/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""src package for borg-cube NLP pipeline."""
|
src/config.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration dataclass for borg-cube."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from typing import Any, Dict, List, Mapping
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
_WARNED_BFLOAT16_FALLBACKS: set[str] = set()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@lru_cache(maxsize=None)
|
| 16 |
+
def _supports_bfloat16(device: str) -> bool:
|
| 17 |
+
target = torch.device(device)
|
| 18 |
+
if target.type == "cuda":
|
| 19 |
+
if not torch.cuda.is_available():
|
| 20 |
+
return False
|
| 21 |
+
try:
|
| 22 |
+
with torch.cuda.device(target):
|
| 23 |
+
return torch.cuda.is_bf16_supported()
|
| 24 |
+
except (RuntimeError, TypeError):
|
| 25 |
+
return False
|
| 26 |
+
|
| 27 |
+
if target.type == "mps" and not torch.backends.mps.is_available():
|
| 28 |
+
return False
|
| 29 |
+
if target.type not in ("cpu", "mps", "xpu"):
|
| 30 |
+
return False
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
values = torch.ones((2, 2), device=target)
|
| 34 |
+
with torch.autocast(device_type=target.type, dtype=torch.bfloat16):
|
| 35 |
+
result = values @ values
|
| 36 |
+
return result.dtype is torch.bfloat16
|
| 37 |
+
except (AttributeError, NotImplementedError, RuntimeError, TypeError):
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class BorgConfig:
|
| 43 |
+
model_name: str = "microsoft/deberta-v3-large"
|
| 44 |
+
max_seq_length: int = 512
|
| 45 |
+
batch_size: int = 16
|
| 46 |
+
learning_rate: float = 2e-4
|
| 47 |
+
num_epochs: int = 10
|
| 48 |
+
warmup_ratio: float = 0
|
| 49 |
+
adapter_reduction_factor: int = 16
|
| 50 |
+
seed: int = 42
|
| 51 |
+
lang: str = "en"
|
| 52 |
+
dtype: torch.dtype = torch.bfloat16
|
| 53 |
+
device: str = "auto" # "auto", "cpu", "cuda"
|
| 54 |
+
components: List[str] = field(
|
| 55 |
+
default_factory=lambda: ["tokenizer", "tagger", "parser", "lemmatizer"]
|
| 56 |
+
)
|
| 57 |
+
eval_batch_size: int = 32
|
| 58 |
+
|
| 59 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 60 |
+
"""Return checkpoint metadata with a JSON-compatible dtype."""
|
| 61 |
+
values = dict(self.__dict__)
|
| 62 |
+
values["dtype"] = str(self.dtype)
|
| 63 |
+
return values
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def from_dict(cls, values: Mapping[str, Any]) -> "BorgConfig":
|
| 67 |
+
"""Restore checkpoint metadata, including its PyTorch dtype."""
|
| 68 |
+
fields = {k: v for k, v in values.items() if k in cls.__dataclass_fields__}
|
| 69 |
+
if "dtype" in fields:
|
| 70 |
+
dtype = fields["dtype"]
|
| 71 |
+
if isinstance(dtype, str):
|
| 72 |
+
name = dtype[len("torch."):] if dtype.startswith("torch.") else dtype
|
| 73 |
+
dtype = getattr(torch, name, None)
|
| 74 |
+
if not isinstance(dtype, torch.dtype):
|
| 75 |
+
raise ValueError(f"Invalid checkpoint dtype: {fields['dtype']!r}")
|
| 76 |
+
fields["dtype"] = dtype
|
| 77 |
+
return cls(**fields)
|
| 78 |
+
|
| 79 |
+
def resolve_device(self) -> str:
|
| 80 |
+
if self.device == "auto":
|
| 81 |
+
if torch.cuda.is_available():
|
| 82 |
+
return "cuda"
|
| 83 |
+
if torch.backends.mps.is_available():
|
| 84 |
+
return "mps"
|
| 85 |
+
return "cpu"
|
| 86 |
+
return self.device
|
| 87 |
+
|
| 88 |
+
def resolve_dtype(self, device: str | None = None) -> torch.dtype:
|
| 89 |
+
"""Resolve the requested dtype for a runtime device."""
|
| 90 |
+
runtime_device = device or self.resolve_device()
|
| 91 |
+
if self.dtype is not torch.bfloat16 or _supports_bfloat16(runtime_device):
|
| 92 |
+
return self.dtype
|
| 93 |
+
|
| 94 |
+
if runtime_device not in _WARNED_BFLOAT16_FALLBACKS:
|
| 95 |
+
warnings.warn(
|
| 96 |
+
f"Device {runtime_device!r} does not support bfloat16 autocast; "
|
| 97 |
+
"using float32 for this run. BorgConfig.dtype remains bfloat16.",
|
| 98 |
+
RuntimeWarning,
|
| 99 |
+
stacklevel=2,
|
| 100 |
+
)
|
| 101 |
+
_WARNED_BFLOAT16_FALLBACKS.add(runtime_device)
|
| 102 |
+
return torch.float32
|
| 103 |
+
|
| 104 |
+
def autocast_context(self, device: str | None = None):
|
| 105 |
+
"""Create an autocast context using a dtype supported by the runtime device."""
|
| 106 |
+
runtime_device = device or self.resolve_device()
|
| 107 |
+
device_type = torch.device(runtime_device).type
|
| 108 |
+
dtype = self.resolve_dtype(runtime_device)
|
| 109 |
+
enabled = (
|
| 110 |
+
device_type in ("cuda", "cpu", "mps", "xpu")
|
| 111 |
+
and dtype in (torch.float16, torch.bfloat16)
|
| 112 |
+
)
|
| 113 |
+
return torch.autocast(
|
| 114 |
+
device_type=device_type,
|
| 115 |
+
dtype=dtype,
|
| 116 |
+
enabled=enabled,
|
| 117 |
+
)
|
src/data/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""src.data package."""
|
src/data/conllu.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CoNLL-U reader and writer.
|
| 2 |
+
|
| 3 |
+
Supports:
|
| 4 |
+
- Regular tokens (integer IDs)
|
| 5 |
+
- Multi-word tokens (range IDs like "1-2")
|
| 6 |
+
- Empty nodes (decimal IDs like "1.1")
|
| 7 |
+
- FEATS as dict
|
| 8 |
+
- Sentence-level comments
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
import os
|
| 14 |
+
from dataclasses import dataclass, field
|
| 15 |
+
from typing import Dict, List, Optional, Union
|
| 16 |
+
|
| 17 |
+
from tqdm import tqdm
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class Token:
|
| 22 |
+
id: Union[int, str] # int for regular; "1-2" for MWT; "1.1" for empty
|
| 23 |
+
form: str
|
| 24 |
+
lemma: str = "_"
|
| 25 |
+
upos: str = "_"
|
| 26 |
+
xpos: str = "_"
|
| 27 |
+
feats: Union[Dict[str, str], str] = "_" # parsed dict or "_"
|
| 28 |
+
head: Optional[int] = None # None when not set
|
| 29 |
+
deprel: str = "_"
|
| 30 |
+
deps: str = "_"
|
| 31 |
+
misc: str = "_"
|
| 32 |
+
space_after: bool = True
|
| 33 |
+
is_mwt: bool = False
|
| 34 |
+
|
| 35 |
+
# Convenience helpers
|
| 36 |
+
def is_multiword(self) -> bool:
|
| 37 |
+
return isinstance(self.id, str) and "-" in str(self.id)
|
| 38 |
+
|
| 39 |
+
def is_empty(self) -> bool:
|
| 40 |
+
return isinstance(self.id, str) and "." in str(self.id)
|
| 41 |
+
|
| 42 |
+
def feats_str(self) -> str:
|
| 43 |
+
if isinstance(self.feats, dict):
|
| 44 |
+
if not self.feats:
|
| 45 |
+
return "_"
|
| 46 |
+
return "|".join(f"{k}={v}" for k, v in sorted(self.feats.items()))
|
| 47 |
+
return self.feats if self.feats else "_"
|
| 48 |
+
|
| 49 |
+
def __str__(self) -> str:
|
| 50 |
+
head_str = str(self.head) if self.head is not None else "_"
|
| 51 |
+
|
| 52 |
+
# Handle SpaceAfter in misc column: only write SpaceAfter=No
|
| 53 |
+
misc_val = self.misc if self.misc != "_" else ""
|
| 54 |
+
if not self.space_after:
|
| 55 |
+
space_attr = "SpaceAfter=No"
|
| 56 |
+
if misc_val:
|
| 57 |
+
misc_final = f"{misc_val},{space_attr}" if "," not in misc_val else f"{misc_val},{space_attr}"
|
| 58 |
+
else:
|
| 59 |
+
misc_final = space_attr
|
| 60 |
+
else:
|
| 61 |
+
misc_final = misc_val
|
| 62 |
+
|
| 63 |
+
return "\t".join([
|
| 64 |
+
str(self.id),
|
| 65 |
+
self.form,
|
| 66 |
+
self.lemma,
|
| 67 |
+
self.upos,
|
| 68 |
+
self.xpos,
|
| 69 |
+
self.feats_str(),
|
| 70 |
+
head_str,
|
| 71 |
+
self.deprel,
|
| 72 |
+
self.deps,
|
| 73 |
+
misc_final,
|
| 74 |
+
])
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@dataclass
|
| 78 |
+
class Sentence:
|
| 79 |
+
tokens: List[Token] = field(default_factory=list)
|
| 80 |
+
comments: List[str] = field(default_factory=list)
|
| 81 |
+
|
| 82 |
+
def regular_tokens(self) -> List[Token]:
|
| 83 |
+
"""Return only regular (non-MWT, non-empty) tokens."""
|
| 84 |
+
return [t for t in self.tokens if not t.is_multiword() and not t.is_empty()]
|
| 85 |
+
|
| 86 |
+
def surface_tokens(self) -> List[Token]:
|
| 87 |
+
"""Return surface tokens, excluding MWT components and empty nodes."""
|
| 88 |
+
tokens: List[Token] = []
|
| 89 |
+
multiword_end = 0
|
| 90 |
+
for token in self.tokens:
|
| 91 |
+
if token.is_empty():
|
| 92 |
+
continue
|
| 93 |
+
if token.is_multiword():
|
| 94 |
+
multiword_end = int(str(token.id).split("-", 1)[1])
|
| 95 |
+
tokens.append(token)
|
| 96 |
+
elif int(token.id) > multiword_end:
|
| 97 |
+
tokens.append(token)
|
| 98 |
+
return tokens
|
| 99 |
+
|
| 100 |
+
def __repr__(self) -> str:
|
| 101 |
+
words = " ".join(t.form for t in self.regular_tokens())
|
| 102 |
+
return f"<Sentence: {words!r}>"
|
| 103 |
+
|
| 104 |
+
def __str__(self) -> str:
|
| 105 |
+
lines = list(self.comments)
|
| 106 |
+
lines.extend(str(t) for t in self.tokens)
|
| 107 |
+
lines.append("")
|
| 108 |
+
return "\n".join(lines)
|
| 109 |
+
|
| 110 |
+
def to_conllu(self) -> str:
|
| 111 |
+
return str(self)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ---------------------------------------------------------------------------
|
| 115 |
+
# Parsing helpers
|
| 116 |
+
# ---------------------------------------------------------------------------
|
| 117 |
+
|
| 118 |
+
def _parse_feats(feats_str: str) -> Union[Dict[str, str], str]:
|
| 119 |
+
if feats_str in ("_", ""):
|
| 120 |
+
return "_"
|
| 121 |
+
feats: Dict[str, str] = {}
|
| 122 |
+
for part in feats_str.split("|"):
|
| 123 |
+
if "=" in part:
|
| 124 |
+
k, v = part.split("=", 1)
|
| 125 |
+
feats[k] = v
|
| 126 |
+
else:
|
| 127 |
+
feats[part] = ""
|
| 128 |
+
return feats
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _parse_id(id_str: str) -> Union[int, str]:
|
| 132 |
+
"""Return int for simple IDs, str for ranges and decimals."""
|
| 133 |
+
if re.match(r"^\d+$", id_str):
|
| 134 |
+
return int(id_str)
|
| 135 |
+
return id_str
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _parse_head(head_str: str) -> Optional[int]:
|
| 139 |
+
if head_str == "_":
|
| 140 |
+
return None
|
| 141 |
+
try:
|
| 142 |
+
return int(head_str)
|
| 143 |
+
except ValueError:
|
| 144 |
+
return None
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ---------------------------------------------------------------------------
|
| 148 |
+
# Public API
|
| 149 |
+
# ---------------------------------------------------------------------------
|
| 150 |
+
|
| 151 |
+
def read_conllu(path: str, *, show_progress: bool = False) -> List[Sentence]:
|
| 152 |
+
"""Read a CoNLL-U file and return a list of Sentence objects."""
|
| 153 |
+
sentences: List[Sentence] = []
|
| 154 |
+
current_tokens: List[Token] = []
|
| 155 |
+
current_comments: List[str] = []
|
| 156 |
+
|
| 157 |
+
with open(path, encoding="utf-8", newline="") as fh:
|
| 158 |
+
progress = tqdm(
|
| 159 |
+
total=os.path.getsize(path),
|
| 160 |
+
desc=f"Loading {os.path.basename(path)}",
|
| 161 |
+
unit="B",
|
| 162 |
+
unit_scale=True,
|
| 163 |
+
disable=not show_progress,
|
| 164 |
+
)
|
| 165 |
+
try:
|
| 166 |
+
for raw_line in fh:
|
| 167 |
+
progress.update(len(raw_line.encode("utf-8")))
|
| 168 |
+
line = raw_line.rstrip("\r\n")
|
| 169 |
+
if line.startswith("#"):
|
| 170 |
+
current_comments.append(line)
|
| 171 |
+
elif line == "":
|
| 172 |
+
if current_tokens:
|
| 173 |
+
sentences.append(Sentence(tokens=current_tokens, comments=current_comments))
|
| 174 |
+
current_tokens = []
|
| 175 |
+
current_comments = []
|
| 176 |
+
else:
|
| 177 |
+
parts = line.split("\t")
|
| 178 |
+
if len(parts) != 10:
|
| 179 |
+
continue # skip malformed lines
|
| 180 |
+
|
| 181 |
+
misc = parts[9]
|
| 182 |
+
space_after = True
|
| 183 |
+
if "SpaceAfter=No" in misc:
|
| 184 |
+
space_after = False
|
| 185 |
+
elif "SpaceAfter=Yes" in misc:
|
| 186 |
+
space_after = True
|
| 187 |
+
|
| 188 |
+
tok = Token(
|
| 189 |
+
id=_parse_id(parts[0]),
|
| 190 |
+
form=parts[1],
|
| 191 |
+
lemma=parts[2],
|
| 192 |
+
upos=parts[3],
|
| 193 |
+
xpos=parts[4],
|
| 194 |
+
feats=_parse_feats(parts[5]),
|
| 195 |
+
head=_parse_head(parts[6]),
|
| 196 |
+
deprel=parts[7],
|
| 197 |
+
deps=parts[8],
|
| 198 |
+
misc=misc,
|
| 199 |
+
space_after=space_after,
|
| 200 |
+
)
|
| 201 |
+
current_tokens.append(tok)
|
| 202 |
+
finally:
|
| 203 |
+
progress.close()
|
| 204 |
+
|
| 205 |
+
# Handle file without trailing newline
|
| 206 |
+
if current_tokens:
|
| 207 |
+
sentences.append(Sentence(tokens=current_tokens, comments=current_comments))
|
| 208 |
+
|
| 209 |
+
return sentences
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def write_conllu(sentences: List[Sentence], path: str) -> None:
|
| 213 |
+
"""Write a list of Sentence objects to a CoNLL-U file."""
|
| 214 |
+
with open(path, "w", encoding="utf-8") as fh:
|
| 215 |
+
for sent in sentences:
|
| 216 |
+
for comment in sent.comments:
|
| 217 |
+
fh.write(comment + "\n")
|
| 218 |
+
for token in sent.tokens:
|
| 219 |
+
fh.write(str(token) + "\n")
|
| 220 |
+
fh.write("\n")
|
src/data/dataset.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PyTorch Dataset classes for each pipeline component."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import Dict, List, Optional, Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils.data import Dataset
|
| 8 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
from src.data.conllu import Sentence, Token
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# ---------------------------------------------------------------------------
|
| 14 |
+
# Helpers
|
| 15 |
+
# ---------------------------------------------------------------------------
|
| 16 |
+
|
| 17 |
+
def _load_tokenizer(name: str):
|
| 18 |
+
from transformers import AutoTokenizer
|
| 19 |
+
|
| 20 |
+
return AutoTokenizer.from_pretrained(name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _build_vocab(items: List[str], initial_vocab: Optional[Dict[str, int]] = None) -> Dict[str, int]:
|
| 24 |
+
vocab = initial_vocab.copy() if initial_vocab is not None else {"<PAD>": 0, "<UNK>": 1}
|
| 25 |
+
for item in sorted(set(items)):
|
| 26 |
+
if item not in vocab:
|
| 27 |
+
vocab[item] = len(vocab)
|
| 28 |
+
return vocab
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _feats_to_str(token: Token) -> str:
|
| 32 |
+
return token.feats_str() if hasattr(token, "feats_str") else str(token.feats)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# ---------------------------------------------------------------------------
|
| 36 |
+
# Tokenizer dataset
|
| 37 |
+
# ---------------------------------------------------------------------------
|
| 38 |
+
|
| 39 |
+
class TokenizerDataset(Dataset):
|
| 40 |
+
"""Character-level dataset for sentence/token boundary detection."""
|
| 41 |
+
|
| 42 |
+
CONTINUATION = 0
|
| 43 |
+
TOKEN_START = 1
|
| 44 |
+
SENTENCE_START = 2
|
| 45 |
+
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
sentences: List[Sentence],
|
| 49 |
+
hf_tokenizer_name: str,
|
| 50 |
+
max_length: int = 512,
|
| 51 |
+
show_progress: bool = False,
|
| 52 |
+
):
|
| 53 |
+
self.max_length = max_length
|
| 54 |
+
self.hf_tok = AutoTokenizer.from_pretrained(hf_tokenizer_name)
|
| 55 |
+
self.examples: List[Tuple[str, List[int]]] = []
|
| 56 |
+
self._build_examples(sentences, show_progress=show_progress)
|
| 57 |
+
|
| 58 |
+
def collate_fn(self, batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
|
| 59 |
+
padding_values = {
|
| 60 |
+
"input_ids": self.hf_tok.pad_token_id,
|
| 61 |
+
"attention_mask": 0,
|
| 62 |
+
"labels": -100,
|
| 63 |
+
"mwt_labels": -100,
|
| 64 |
+
}
|
| 65 |
+
return {
|
| 66 |
+
key: pad_sequence(
|
| 67 |
+
[example[key] for example in batch],
|
| 68 |
+
batch_first=True,
|
| 69 |
+
padding_value=padding_value,
|
| 70 |
+
)
|
| 71 |
+
for key, padding_value in padding_values.items()
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
def _build_examples(self, sentences: List[Sentence], *, show_progress: bool = False) -> None:
|
| 75 |
+
chars: List[str] = []
|
| 76 |
+
labels: List[int] = []
|
| 77 |
+
mwt_labels: List[int] = []
|
| 78 |
+
|
| 79 |
+
def flush():
|
| 80 |
+
if chars:
|
| 81 |
+
self.examples.append(("".join(chars), list(labels), list(mwt_labels)))
|
| 82 |
+
chars.clear()
|
| 83 |
+
labels.clear()
|
| 84 |
+
mwt_labels.clear()
|
| 85 |
+
|
| 86 |
+
for sent in tqdm(
|
| 87 |
+
sentences,
|
| 88 |
+
desc="Preparing tokenizer data",
|
| 89 |
+
unit="sentences",
|
| 90 |
+
disable=not show_progress,
|
| 91 |
+
):
|
| 92 |
+
tokens = sent.surface_tokens()
|
| 93 |
+
if not tokens:
|
| 94 |
+
continue
|
| 95 |
+
sentence_text = ""
|
| 96 |
+
sentence_labels: List[int] = []
|
| 97 |
+
sentence_mwt_labels: List[int] = []
|
| 98 |
+
for tok_idx, tok in enumerate(tokens):
|
| 99 |
+
form = tok.form
|
| 100 |
+
for char_idx, ch in enumerate(form):
|
| 101 |
+
if tok_idx == 0 and char_idx == 0:
|
| 102 |
+
lbl = self.SENTENCE_START
|
| 103 |
+
elif char_idx == 0:
|
| 104 |
+
lbl = self.TOKEN_START
|
| 105 |
+
else:
|
| 106 |
+
lbl = self.CONTINUATION
|
| 107 |
+
sentence_text += ch
|
| 108 |
+
sentence_labels.append(lbl)
|
| 109 |
+
sentence_mwt_labels.append(
|
| 110 |
+
int(tok.is_multiword()) if char_idx == 0 else -100
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Handle SpaceAfter: add actual whitespace from the Token if available
|
| 114 |
+
if tok_idx < len(tokens) - 1:
|
| 115 |
+
if tok.space_after:
|
| 116 |
+
sentence_text += " "
|
| 117 |
+
sentence_labels.append(self.CONTINUATION)
|
| 118 |
+
sentence_mwt_labels.append(-100)
|
| 119 |
+
else:
|
| 120 |
+
# No space between tokens (e.g. "don't" -> "do", "'t")
|
| 121 |
+
pass
|
| 122 |
+
elif tok.space_after:
|
| 123 |
+
# Trailing space at the end of the sentence
|
| 124 |
+
sentence_text += " "
|
| 125 |
+
sentence_labels.append(self.CONTINUATION)
|
| 126 |
+
sentence_mwt_labels.append(-100)
|
| 127 |
+
|
| 128 |
+
# Check if adding this sentence exceeds limit; flush first if so.
|
| 129 |
+
if len(chars) + len(sentence_text) > self.max_length and chars:
|
| 130 |
+
flush()
|
| 131 |
+
chars.extend(sentence_text)
|
| 132 |
+
labels.extend(sentence_labels)
|
| 133 |
+
mwt_labels.extend(sentence_mwt_labels)
|
| 134 |
+
|
| 135 |
+
flush()
|
| 136 |
+
|
| 137 |
+
def __len__(self) -> int:
|
| 138 |
+
return len(self.examples)
|
| 139 |
+
|
| 140 |
+
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
|
| 141 |
+
text, char_labels, char_mwt_labels = self.examples[idx]
|
| 142 |
+
encoding = self.hf_tok(
|
| 143 |
+
text,
|
| 144 |
+
return_offsets_mapping=True,
|
| 145 |
+
max_length=self.max_length,
|
| 146 |
+
truncation=True,
|
| 147 |
+
padding=False,
|
| 148 |
+
return_tensors="pt",
|
| 149 |
+
)
|
| 150 |
+
offset_mapping = encoding.pop("offset_mapping").squeeze(0) # (seq_len, 2)
|
| 151 |
+
input_ids = encoding["input_ids"].squeeze(0)
|
| 152 |
+
attention_mask = encoding["attention_mask"].squeeze(0)
|
| 153 |
+
token_type_ids = encoding.get("token_type_ids", torch.zeros_like(input_ids))
|
| 154 |
+
if isinstance(token_type_ids, torch.Tensor) and token_type_ids.dim() > 1:
|
| 155 |
+
token_type_ids = token_type_ids.squeeze(0)
|
| 156 |
+
|
| 157 |
+
seq_len = input_ids.size(0)
|
| 158 |
+
aligned_labels = torch.zeros(seq_len, dtype=torch.long)
|
| 159 |
+
aligned_mwt_labels = torch.full((seq_len,), -100, dtype=torch.long)
|
| 160 |
+
|
| 161 |
+
for i, (start, end) in enumerate(offset_mapping.tolist()):
|
| 162 |
+
if start == 0 and end == 0:
|
| 163 |
+
aligned_labels[i] = -100 # special token — ignored
|
| 164 |
+
else:
|
| 165 |
+
# Use the label of the first character of this sub-word.
|
| 166 |
+
# Some tokenizers (e.g. SentencePiece-based ones used by
|
| 167 |
+
# DeBERTa-v3) include the leading whitespace in the offset
|
| 168 |
+
# span of a sub-word that starts a new word. Skip past any
|
| 169 |
+
# such leading whitespace so we don't pick up the space
|
| 170 |
+
# character's CONTINUATION label instead of the real
|
| 171 |
+
# TOKEN_START/SENTENCE_START label of the word.
|
| 172 |
+
char_idx = start
|
| 173 |
+
while char_idx < end and char_idx < len(text) and text[char_idx].isspace():
|
| 174 |
+
char_idx += 1
|
| 175 |
+
if char_idx < len(char_labels):
|
| 176 |
+
aligned_labels[i] = char_labels[char_idx]
|
| 177 |
+
aligned_mwt_labels[i] = char_mwt_labels[char_idx]
|
| 178 |
+
else:
|
| 179 |
+
aligned_labels[i] = self.CONTINUATION
|
| 180 |
+
|
| 181 |
+
return {
|
| 182 |
+
"input_ids": input_ids,
|
| 183 |
+
"attention_mask": attention_mask,
|
| 184 |
+
"labels": aligned_labels,
|
| 185 |
+
"mwt_labels": aligned_mwt_labels,
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ---------------------------------------------------------------------------
|
| 190 |
+
# Tagger dataset
|
| 191 |
+
# ---------------------------------------------------------------------------
|
| 192 |
+
|
| 193 |
+
class TaggerDataset(Dataset):
|
| 194 |
+
"""Token-level dataset for UPOS/XPOS/FEATS tagging."""
|
| 195 |
+
|
| 196 |
+
def __init__(
|
| 197 |
+
self,
|
| 198 |
+
sentences: List[Sentence],
|
| 199 |
+
hf_tokenizer_name: str,
|
| 200 |
+
max_length: int = 512,
|
| 201 |
+
upos_vocab: Optional[Dict[str, int]] = None,
|
| 202 |
+
xpos_vocab: Optional[Dict[str, int]] = None,
|
| 203 |
+
feats_vocab: Optional[Dict[str, int]] = None,
|
| 204 |
+
):
|
| 205 |
+
self.hf_tok = _load_tokenizer(hf_tokenizer_name)
|
| 206 |
+
self.max_length = max_length
|
| 207 |
+
|
| 208 |
+
all_upos = [t.upos for s in sentences for t in s.regular_tokens()]
|
| 209 |
+
all_xpos = [t.xpos for s in sentences for t in s.regular_tokens()]
|
| 210 |
+
all_feats = [_feats_to_str(t) for s in sentences for t in s.regular_tokens()]
|
| 211 |
+
|
| 212 |
+
self.upos_vocab = upos_vocab or _build_vocab(all_upos)
|
| 213 |
+
self.xpos_vocab = xpos_vocab or _build_vocab(all_xpos)
|
| 214 |
+
self.feats_vocab = feats_vocab or _build_vocab(all_feats)
|
| 215 |
+
|
| 216 |
+
self.sentences = sentences
|
| 217 |
+
|
| 218 |
+
def __len__(self) -> int:
|
| 219 |
+
return len(self.sentences)
|
| 220 |
+
|
| 221 |
+
def collate_fn(self, batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
|
| 222 |
+
"""Right-pad tagger examples to the longest sequence in this batch."""
|
| 223 |
+
padding_values = {
|
| 224 |
+
"input_ids": self.hf_tok.pad_token_id,
|
| 225 |
+
"attention_mask": 0,
|
| 226 |
+
"upos_labels": -100,
|
| 227 |
+
"xpos_labels": -100,
|
| 228 |
+
"feats_labels": -100,
|
| 229 |
+
}
|
| 230 |
+
return {
|
| 231 |
+
key: pad_sequence(
|
| 232 |
+
[example[key] for example in batch],
|
| 233 |
+
batch_first=True,
|
| 234 |
+
padding_value=padding_value,
|
| 235 |
+
)
|
| 236 |
+
for key, padding_value in padding_values.items()
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
|
| 240 |
+
sent = self.sentences[idx]
|
| 241 |
+
tokens = sent.regular_tokens()
|
| 242 |
+
forms = [t.form for t in tokens]
|
| 243 |
+
|
| 244 |
+
encoding = self.hf_tok(
|
| 245 |
+
forms,
|
| 246 |
+
is_split_into_words=True,
|
| 247 |
+
max_length=self.max_length,
|
| 248 |
+
truncation=True,
|
| 249 |
+
padding=False,
|
| 250 |
+
return_tensors="pt",
|
| 251 |
+
)
|
| 252 |
+
input_ids = encoding["input_ids"].squeeze(0)
|
| 253 |
+
attention_mask = encoding["attention_mask"].squeeze(0)
|
| 254 |
+
word_ids = encoding.word_ids(batch_index=0)
|
| 255 |
+
|
| 256 |
+
seq_len = input_ids.size(0)
|
| 257 |
+
upos_labels = torch.full((seq_len,), -100, dtype=torch.long)
|
| 258 |
+
xpos_labels = torch.full((seq_len,), -100, dtype=torch.long)
|
| 259 |
+
feats_labels = torch.full((seq_len,), -100, dtype=torch.long)
|
| 260 |
+
|
| 261 |
+
seen_words = set()
|
| 262 |
+
for i, word_id in enumerate(word_ids):
|
| 263 |
+
if word_id is None or word_id in seen_words:
|
| 264 |
+
continue
|
| 265 |
+
seen_words.add(word_id)
|
| 266 |
+
if word_id < len(tokens):
|
| 267 |
+
tok = tokens[word_id]
|
| 268 |
+
upos_labels[i] = self.upos_vocab.get(tok.upos, self.upos_vocab["<UNK>"])
|
| 269 |
+
xpos_labels[i] = self.xpos_vocab.get(tok.xpos, self.xpos_vocab["<UNK>"])
|
| 270 |
+
feats_labels[i] = self.feats_vocab.get(
|
| 271 |
+
_feats_to_str(tok), self.feats_vocab["<UNK>"]
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
return {
|
| 275 |
+
"input_ids": input_ids,
|
| 276 |
+
"attention_mask": attention_mask,
|
| 277 |
+
"upos_labels": upos_labels,
|
| 278 |
+
"xpos_labels": xpos_labels,
|
| 279 |
+
"feats_labels": feats_labels,
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# ---------------------------------------------------------------------------
|
| 284 |
+
# Parser dataset
|
| 285 |
+
# ---------------------------------------------------------------------------
|
| 286 |
+
|
| 287 |
+
class ParserDataset(Dataset):
|
| 288 |
+
"""Token-level dataset for dependency parsing (HEAD + DEPREL)."""
|
| 289 |
+
|
| 290 |
+
def __init__(
|
| 291 |
+
self,
|
| 292 |
+
sentences: List[Sentence],
|
| 293 |
+
hf_tokenizer_name: str,
|
| 294 |
+
max_length: int = 512,
|
| 295 |
+
deprel_vocab: Optional[Dict[str, int]] = None,
|
| 296 |
+
):
|
| 297 |
+
self.hf_tok = _load_tokenizer(hf_tokenizer_name)
|
| 298 |
+
self.max_length = max_length
|
| 299 |
+
|
| 300 |
+
all_deprels = [t.deprel for s in sentences for t in s.regular_tokens()]
|
| 301 |
+
self.deprel_vocab = deprel_vocab or _build_vocab(all_deprels)
|
| 302 |
+
self.sentences = sentences
|
| 303 |
+
self.hf_tok.padding_side = "right"
|
| 304 |
+
|
| 305 |
+
def __len__(self) -> int:
|
| 306 |
+
return len(self.sentences)
|
| 307 |
+
|
| 308 |
+
def collate_fn(self, batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
|
| 309 |
+
"""Right-pad parser examples to the longest sequence in this batch."""
|
| 310 |
+
padding_values = {
|
| 311 |
+
"input_ids": self.hf_tok.pad_token_id,
|
| 312 |
+
"attention_mask": 0,
|
| 313 |
+
"head_labels": -100,
|
| 314 |
+
"deprel_labels": -100,
|
| 315 |
+
}
|
| 316 |
+
return {
|
| 317 |
+
key: pad_sequence(
|
| 318 |
+
[example[key] for example in batch],
|
| 319 |
+
batch_first=True,
|
| 320 |
+
padding_value=padding_value,
|
| 321 |
+
)
|
| 322 |
+
for key, padding_value in padding_values.items()
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
|
| 327 |
+
sent = self.sentences[idx]
|
| 328 |
+
tokens = sent.regular_tokens()
|
| 329 |
+
forms = [t.form for t in tokens]
|
| 330 |
+
|
| 331 |
+
encoding = self.hf_tok(
|
| 332 |
+
forms,
|
| 333 |
+
is_split_into_words=True,
|
| 334 |
+
max_length=self.max_length,
|
| 335 |
+
truncation=True,
|
| 336 |
+
padding=False,
|
| 337 |
+
return_tensors="pt",
|
| 338 |
+
)
|
| 339 |
+
input_ids = encoding["input_ids"].squeeze(0)
|
| 340 |
+
attention_mask = encoding["attention_mask"].squeeze(0)
|
| 341 |
+
word_ids = encoding.word_ids(batch_index=0)
|
| 342 |
+
|
| 343 |
+
seq_len = input_ids.size(0)
|
| 344 |
+
head_labels = torch.full((seq_len,), -100, dtype=torch.long)
|
| 345 |
+
deprel_labels = torch.full((seq_len,), -100, dtype=torch.long)
|
| 346 |
+
|
| 347 |
+
# Map word-id -> first sub-word position. The arc classifier scores
|
| 348 |
+
# pairs of *sequence positions* (not word indices), and position 0
|
| 349 |
+
# (the CLS token) stands in for the virtual ROOT node. Gold
|
| 350 |
+
# ``tok.head`` values are 1-based CoNLL-U word indices (0 == ROOT),
|
| 351 |
+
# so they must be translated into sequence positions before being
|
| 352 |
+
# used as classification targets — otherwise the labels are
|
| 353 |
+
# meaningless whenever any word is split into multiple sub-words.
|
| 354 |
+
word_positions: Dict[int, int] = {}
|
| 355 |
+
for i, word_id in enumerate(word_ids):
|
| 356 |
+
if word_id is not None and word_id not in word_positions:
|
| 357 |
+
word_positions[word_id] = i
|
| 358 |
+
|
| 359 |
+
seen_words = set()
|
| 360 |
+
for i, word_id in enumerate(word_ids):
|
| 361 |
+
if word_id is None or word_id in seen_words:
|
| 362 |
+
continue
|
| 363 |
+
seen_words.add(word_id)
|
| 364 |
+
if word_id < len(tokens):
|
| 365 |
+
tok = tokens[word_id]
|
| 366 |
+
head_pos: Optional[int] = None
|
| 367 |
+
if tok.head is None:
|
| 368 |
+
# Unknown head (e.g. malformed CoNLL-U data) -> leave
|
| 369 |
+
# the label ignored (-100) rather than silently
|
| 370 |
+
# injecting a ROOT target, same treatment as the
|
| 371 |
+
# truncated-head case below.
|
| 372 |
+
pass
|
| 373 |
+
elif tok.head == 0:
|
| 374 |
+
head_pos = 0 # ROOT -> CLS position
|
| 375 |
+
else:
|
| 376 |
+
# `tok.head` is the gold token's 1-based CoNLL-U index
|
| 377 |
+
# into `tokens` (`regular_tokens()`), and `word_id`
|
| 378 |
+
# (from `encoding.word_ids()`, single-example call) is
|
| 379 |
+
# the matching 0-based index into that same
|
| 380 |
+
# `forms`/`tokens` list passed to
|
| 381 |
+
# `is_split_into_words=True` — so `tok.head - 1` is
|
| 382 |
+
# exactly the `word_id` of the head token. The head
|
| 383 |
+
# word may have been truncated out of the sequence
|
| 384 |
+
# (max_length); in that case there's no valid target
|
| 385 |
+
# position, so leave the label ignored (-100) instead
|
| 386 |
+
# of silently mislabeling it as ROOT.
|
| 387 |
+
head_pos = word_positions.get(tok.head - 1)
|
| 388 |
+
if head_pos is not None:
|
| 389 |
+
head_labels[i] = head_pos
|
| 390 |
+
deprel_labels[i] = self.deprel_vocab.get(
|
| 391 |
+
tok.deprel, self.deprel_vocab["<UNK>"]
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
return {
|
| 395 |
+
"input_ids": input_ids,
|
| 396 |
+
"attention_mask": attention_mask,
|
| 397 |
+
"head_labels": head_labels,
|
| 398 |
+
"deprel_labels": deprel_labels,
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class LemmatizerDataset(Dataset):
|
| 403 |
+
"""Token-level dataset for lemmatization via edit scripts."""
|
| 404 |
+
|
| 405 |
+
def __init__(
|
| 406 |
+
self,
|
| 407 |
+
sentences: List[Sentence],
|
| 408 |
+
hf_tokenizer_name: str,
|
| 409 |
+
max_length: int = 512,
|
| 410 |
+
upos_vocab: Optional[Dict[str, int]] = None,
|
| 411 |
+
input_vocab: Optional[Dict[str, int]] = None,
|
| 412 |
+
output_vocab: Optional[Dict[str, int]] = None
|
| 413 |
+
):
|
| 414 |
+
self.hf_tok = _load_tokenizer(hf_tokenizer_name)
|
| 415 |
+
self.max_length = max_length
|
| 416 |
+
|
| 417 |
+
all_upos = [t.upos for s in sentences for t in s.regular_tokens()]
|
| 418 |
+
self.upos_vocab = upos_vocab or _build_vocab(all_upos)
|
| 419 |
+
|
| 420 |
+
all_input_chars = [c for s in sentences for t in s.regular_tokens() for c in t.form]
|
| 421 |
+
all_output_chars = [c for s in sentences for t in s.regular_tokens() for c in t.lemma]
|
| 422 |
+
|
| 423 |
+
self.input_vocab = input_vocab or _build_vocab(all_input_chars, initial_vocab={"<PAD>": 0, "<UNK>": 1, "<SOS>": 2, "<EOS>": 3})
|
| 424 |
+
self.output_vocab = output_vocab or _build_vocab(all_output_chars, initial_vocab={"<PAD>": 0, "<UNK>": 1, "<SOS>": 2, "<EOS>": 3})
|
| 425 |
+
self.sentences = sentences
|
| 426 |
+
|
| 427 |
+
def __len__(self) -> int:
|
| 428 |
+
return len(self.sentences)
|
| 429 |
+
|
| 430 |
+
def collate_fn(self, batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
|
| 431 |
+
"""Right-pad lemmatizer examples to the longest sequence in this batch."""
|
| 432 |
+
padding_values = {
|
| 433 |
+
"input_ids": self.hf_tok.pad_token_id,
|
| 434 |
+
"attention_mask": 0,
|
| 435 |
+
"upos_ids": 0,
|
| 436 |
+
"input_char_ids": torch.tensor([[0]]),
|
| 437 |
+
"output_char_ids": torch.tensor([[-100]]),
|
| 438 |
+
}
|
| 439 |
+
output={}
|
| 440 |
+
for key, padding_value in padding_values.items():
|
| 441 |
+
if key=="input_char_ids" or key=="output_char_ids":
|
| 442 |
+
max_len = max(len(example[key][0]) for example in batch)
|
| 443 |
+
padded_sequences = []
|
| 444 |
+
for example in batch:
|
| 445 |
+
seq = torch.cat([e.unsqueeze(0) for e in example[key]])
|
| 446 |
+
pad_length = max_len - seq.shape[1]
|
| 447 |
+
padded_seq = torch.cat([seq, torch.full((seq.shape[0], pad_length), padding_value[0][0], dtype=torch.long)], dim=1)
|
| 448 |
+
padded_sequences.append(padded_seq)
|
| 449 |
+
|
| 450 |
+
max_sentence_len=max(seq.shape[0] for seq in padded_sequences)
|
| 451 |
+
repadded_seqs=[]
|
| 452 |
+
for seq in padded_sequences:
|
| 453 |
+
if seq.shape[0]<max_sentence_len:
|
| 454 |
+
pad_length=max_sentence_len-seq.shape[0]
|
| 455 |
+
padded_seq=torch.cat([seq, torch.full((pad_length, seq.shape[1]), padding_value[0][0], dtype=torch.long)], dim=0)
|
| 456 |
+
repadded_seqs.append(padded_seq)
|
| 457 |
+
else:
|
| 458 |
+
repadded_seqs.append(seq)
|
| 459 |
+
|
| 460 |
+
output[key]= torch.stack(repadded_seqs, dim=0)
|
| 461 |
+
else:
|
| 462 |
+
output[key] = pad_sequence(
|
| 463 |
+
[example[key] for example in batch],
|
| 464 |
+
batch_first=True,
|
| 465 |
+
padding_value=padding_value,
|
| 466 |
+
)
|
| 467 |
+
return output
|
| 468 |
+
|
| 469 |
+
def encode_chars(self, word_list: List[str], vocab: Dict[str, int]) -> torch.Tensor:
|
| 470 |
+
"""Encode a string of characters into a tensor of input IDs."""
|
| 471 |
+
char_ids_list = []
|
| 472 |
+
for text in word_list:
|
| 473 |
+
char_ids = [vocab.get('<SOS>')]+[vocab.get(c, vocab["<UNK>"]) for c in text]+[vocab.get('<EOS>')]
|
| 474 |
+
char_ids_list.append(char_ids)
|
| 475 |
+
max_len = max(len(ids) for ids in char_ids_list)
|
| 476 |
+
for i in range(len(char_ids_list)):
|
| 477 |
+
char_ids_list[i] += [vocab.get('<PAD>')] * (max_len - len(char_ids_list[i]))
|
| 478 |
+
return torch.tensor(char_ids_list, dtype=torch.long)
|
| 479 |
+
|
| 480 |
+
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
|
| 481 |
+
sent = self.sentences[idx]
|
| 482 |
+
tokens = sent.regular_tokens()
|
| 483 |
+
forms = [t.form for t in tokens]
|
| 484 |
+
encoding = self.hf_tok(
|
| 485 |
+
forms,
|
| 486 |
+
is_split_into_words=True,
|
| 487 |
+
max_length=self.max_length,
|
| 488 |
+
truncation=True,
|
| 489 |
+
padding=False,
|
| 490 |
+
return_tensors="pt",
|
| 491 |
+
)
|
| 492 |
+
input_ids = encoding["input_ids"].squeeze(0)
|
| 493 |
+
attention_mask = encoding["attention_mask"].squeeze(0)
|
| 494 |
+
word_ids = encoding.word_ids(batch_index=0)
|
| 495 |
+
|
| 496 |
+
seq_len = input_ids.size(0)
|
| 497 |
+
upos_ids = torch.zeros(seq_len, dtype=torch.long)
|
| 498 |
+
all_words=[t.form for t in tokens]+['']
|
| 499 |
+
all_lemmas=[t.lemma for t in tokens]+['']
|
| 500 |
+
input_encoded = self.encode_chars(all_words, self.input_vocab)
|
| 501 |
+
output_encoded = self.encode_chars(all_lemmas, self.output_vocab)
|
| 502 |
+
input_char_ids = []
|
| 503 |
+
output_char_ids = []
|
| 504 |
+
seen_words = set()
|
| 505 |
+
for i, word_id in enumerate(word_ids):
|
| 506 |
+
if word_id is None:
|
| 507 |
+
continue
|
| 508 |
+
tok = tokens[word_id] if word_id < len(tokens) else None
|
| 509 |
+
if tok is not None:
|
| 510 |
+
upos_ids[i] = self.upos_vocab.get(tok.upos, self.upos_vocab["<UNK>"])
|
| 511 |
+
if word_id not in seen_words and tok is not None:
|
| 512 |
+
seen_words.add(word_id)
|
| 513 |
+
input_char_ids.append(input_encoded[word_id])
|
| 514 |
+
output_char_ids.append(output_encoded[word_id])
|
| 515 |
+
else:
|
| 516 |
+
input_char_ids.append(input_encoded[-1])
|
| 517 |
+
output_char_ids.append(output_encoded[-1])
|
| 518 |
+
|
| 519 |
+
return {
|
| 520 |
+
"input_ids": input_ids,
|
| 521 |
+
"attention_mask": attention_mask,
|
| 522 |
+
"upos_ids": upos_ids,
|
| 523 |
+
"input_char_ids": input_char_ids,
|
| 524 |
+
"output_char_ids": output_char_ids
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
class MWTDataset(Dataset):
|
| 529 |
+
"""Character-level source/expansion pairs for gold MWT tokens only."""
|
| 530 |
+
|
| 531 |
+
def __init__(
|
| 532 |
+
self,
|
| 533 |
+
sentences: List[Sentence],
|
| 534 |
+
output_vocab: Optional[Dict[str, int]] = None,
|
| 535 |
+
input_vocab: Optional[Dict[str, int]] = None,
|
| 536 |
+
):
|
| 537 |
+
self.examples = [
|
| 538 |
+
(token.form, targets[token.id])
|
| 539 |
+
for sentence in sentences
|
| 540 |
+
for targets in [self._expansion_targets(sentence)]
|
| 541 |
+
for token in sentence.surface_tokens()
|
| 542 |
+
if token.is_multiword() and token.id in targets
|
| 543 |
+
]
|
| 544 |
+
self.input_vocab = input_vocab or _build_vocab(
|
| 545 |
+
[char for form, _ in self.examples for char in form],
|
| 546 |
+
initial_vocab={"<PAD>": 0, "<UNK>": 1, "<SOS>": 2, "<EOS>": 3},
|
| 547 |
+
)
|
| 548 |
+
target_chars = [
|
| 549 |
+
char
|
| 550 |
+
for _, expansion in self.examples
|
| 551 |
+
for char in expansion
|
| 552 |
+
]
|
| 553 |
+
self.output_vocab = output_vocab or _build_vocab(
|
| 554 |
+
target_chars,
|
| 555 |
+
initial_vocab={"<PAD>": 0, "<UNK>": 1, "<SOS>": 2, "<EOS>": 3},
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
@staticmethod
|
| 559 |
+
def _expansion_targets(sentence: Sentence) -> Dict[int | str, str]:
|
| 560 |
+
targets = {}
|
| 561 |
+
regular_tokens = sentence.regular_tokens()
|
| 562 |
+
for token in sentence.tokens:
|
| 563 |
+
if not token.is_multiword():
|
| 564 |
+
continue
|
| 565 |
+
try:
|
| 566 |
+
start, end = map(int, str(token.id).split("-", 1))
|
| 567 |
+
except ValueError:
|
| 568 |
+
continue
|
| 569 |
+
components = [
|
| 570 |
+
part.form
|
| 571 |
+
for part in regular_tokens
|
| 572 |
+
if isinstance(part.id, int) and start <= part.id <= end
|
| 573 |
+
]
|
| 574 |
+
if len(components) >= 2:
|
| 575 |
+
targets[token.id] = " ".join(components)
|
| 576 |
+
return targets
|
| 577 |
+
|
| 578 |
+
def __len__(self) -> int:
|
| 579 |
+
return len(self.examples)
|
| 580 |
+
|
| 581 |
+
def __getitem__(self, index: int) -> Dict[str, torch.Tensor]:
|
| 582 |
+
form, expansion = self.examples[index]
|
| 583 |
+
return {
|
| 584 |
+
"input_char_ids": self.encode_chars(form, self.input_vocab),
|
| 585 |
+
"output_char_ids": self.encode_chars(expansion, self.output_vocab),
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
@staticmethod
|
| 589 |
+
def encode_chars(text: str, vocab: Dict[str, int]) -> torch.Tensor:
|
| 590 |
+
return torch.tensor(
|
| 591 |
+
[vocab["<SOS>"], *(vocab.get(char, vocab["<UNK>"]) for char in text), vocab["<EOS>"]],
|
| 592 |
+
dtype=torch.long,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
def collate_fn(
|
| 596 |
+
self,
|
| 597 |
+
batch: List[Dict[str, torch.Tensor]],
|
| 598 |
+
) -> Dict[str, torch.Tensor]:
|
| 599 |
+
return {
|
| 600 |
+
"input_char_ids": pad_sequence(
|
| 601 |
+
[example["input_char_ids"] for example in batch],
|
| 602 |
+
batch_first=True,
|
| 603 |
+
padding_value=0,
|
| 604 |
+
),
|
| 605 |
+
"output_char_ids": pad_sequence(
|
| 606 |
+
[example["output_char_ids"] for example in batch],
|
| 607 |
+
batch_first=True,
|
| 608 |
+
padding_value=-100,
|
| 609 |
+
),
|
| 610 |
+
}
|
src/models/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""src.models package."""
|
src/models/base.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base model: DeBERTa-v3 + adapter framework."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from typing import Any, Dict, Optional
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
|
| 11 |
+
from src.config import BorgConfig
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BorgBaseModel(nn.Module):
|
| 15 |
+
"""Wraps a DeBERTa-v3 encoder with a task-specific Pfeiffer adapter."""
|
| 16 |
+
|
| 17 |
+
def __init__(self, config: BorgConfig, component: str):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.config = config
|
| 20 |
+
self.component = component
|
| 21 |
+
|
| 22 |
+
from transformers import AutoModel, AutoTokenizer
|
| 23 |
+
import adapters
|
| 24 |
+
|
| 25 |
+
self.hf_tokenizer = AutoTokenizer.from_pretrained(config.model_name)
|
| 26 |
+
self.encoder = AutoModel.from_pretrained(
|
| 27 |
+
config.model_name,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
adapters.init(self.encoder)
|
| 31 |
+
pfeiffer_cfg = adapters.SeqBnConfig(reduction_factor=6)
|
| 32 |
+
self.encoder.add_adapter(component, config=pfeiffer_cfg)
|
| 33 |
+
self.encoder.set_active_adapters(component)
|
| 34 |
+
self.encoder.train_adapter(component)
|
| 35 |
+
|
| 36 |
+
self.hidden_size: int = self.encoder.config.hidden_size
|
| 37 |
+
|
| 38 |
+
# ------------------------------------------------------------------
|
| 39 |
+
def encode(
|
| 40 |
+
self,
|
| 41 |
+
input_ids: torch.Tensor,
|
| 42 |
+
attention_mask: torch.Tensor,
|
| 43 |
+
**kwargs,
|
| 44 |
+
) -> torch.Tensor:
|
| 45 |
+
"""Return last-hidden-state from the encoder."""
|
| 46 |
+
outputs = self.encoder(
|
| 47 |
+
input_ids=input_ids,
|
| 48 |
+
attention_mask=attention_mask,
|
| 49 |
+
**kwargs,
|
| 50 |
+
)
|
| 51 |
+
return outputs.last_hidden_state # (batch, seq, hidden)
|
| 52 |
+
|
| 53 |
+
# ------------------------------------------------------------------
|
| 54 |
+
def save(self, path: str) -> None:
|
| 55 |
+
"""Save model weights and extra metadata to *path* (directory)."""
|
| 56 |
+
os.makedirs(path, exist_ok=True)
|
| 57 |
+
# Save adapter weights
|
| 58 |
+
self.encoder.save_adapter(os.path.join(path, "adapter"), self.component)
|
| 59 |
+
# Save extra heads / vocab stored by subclasses
|
| 60 |
+
extras = self._get_extras()
|
| 61 |
+
if extras:
|
| 62 |
+
torch.save(extras, os.path.join(path, "extras.pt"))
|
| 63 |
+
# Save config
|
| 64 |
+
cfg_dict = self.config.to_dict()
|
| 65 |
+
cfg_dict["component"] = self.component
|
| 66 |
+
with open(os.path.join(path, "borg_config.json"), "w") as f:
|
| 67 |
+
json.dump(cfg_dict, f, indent=2)
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
def load(cls, path: str, config: Optional[BorgConfig] = None) -> "BorgBaseModel":
|
| 71 |
+
"""Load a saved model from *path*."""
|
| 72 |
+
with open(os.path.join(path, "borg_config.json")) as f:
|
| 73 |
+
cfg_dict = json.load(f)
|
| 74 |
+
component = cfg_dict.pop("component")
|
| 75 |
+
if config is None:
|
| 76 |
+
config = BorgConfig.from_dict(cfg_dict)
|
| 77 |
+
|
| 78 |
+
obj = cls.__new__(cls)
|
| 79 |
+
BorgBaseModel.__init__(obj, config, component)
|
| 80 |
+
|
| 81 |
+
from transformers import AutoModel
|
| 82 |
+
import adapters
|
| 83 |
+
|
| 84 |
+
obj.encoder.load_adapter(os.path.join(path, "adapter"))
|
| 85 |
+
obj.encoder.set_active_adapters(component)
|
| 86 |
+
|
| 87 |
+
extras_path = os.path.join(path, "extras.pt")
|
| 88 |
+
if os.path.exists(extras_path):
|
| 89 |
+
extras = torch.load(extras_path, map_location="cpu")
|
| 90 |
+
obj._set_extras(extras)
|
| 91 |
+
|
| 92 |
+
return obj
|
| 93 |
+
|
| 94 |
+
# ------------------------------------------------------------------
|
| 95 |
+
# Subclasses override these to persist additional state (heads, vocabs).
|
| 96 |
+
def _get_extras(self) -> Dict[str, Any]:
|
| 97 |
+
return {}
|
| 98 |
+
|
| 99 |
+
def _set_extras(self, extras: Dict[str, Any]) -> None:
|
| 100 |
+
pass
|
src/models/checkpoints.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities for retaining training model checkpoints."""
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TrainingState:
|
| 11 |
+
"""Persist training counters and randomness alongside a model checkpoint."""
|
| 12 |
+
|
| 13 |
+
def __init__(self, model, path, optimizer, scheduler, loader, resume=False):
|
| 14 |
+
self.model = model
|
| 15 |
+
self.path = path
|
| 16 |
+
self.optimizer = optimizer
|
| 17 |
+
self.scheduler = scheduler
|
| 18 |
+
self.loader = loader
|
| 19 |
+
self.epoch = 0
|
| 20 |
+
self.batch = 0
|
| 21 |
+
self.global_step = 0
|
| 22 |
+
self.total_loss = 0.0
|
| 23 |
+
self.best_score = -1.0
|
| 24 |
+
self.generator = torch.Generator().manual_seed(model.config.seed)
|
| 25 |
+
self.loader.generator = self.generator
|
| 26 |
+
self.loader.sampler.generator = self.generator
|
| 27 |
+
self.epoch_rng = None
|
| 28 |
+
self.epoch_generator = None
|
| 29 |
+
if resume:
|
| 30 |
+
state = torch.load(
|
| 31 |
+
os.path.join(path, "last", "training_state.pt"),
|
| 32 |
+
map_location="cpu",
|
| 33 |
+
weights_only=False,
|
| 34 |
+
)
|
| 35 |
+
if state["batches_per_epoch"] != len(loader):
|
| 36 |
+
raise ValueError("Cannot resume with a different number of training batches")
|
| 37 |
+
optimizer.load_state_dict(state["optimizer"])
|
| 38 |
+
scheduler.load_state_dict(state["scheduler"])
|
| 39 |
+
for name in ("epoch", "batch", "global_step", "total_loss", "best_score",
|
| 40 |
+
"epoch_rng", "epoch_generator"):
|
| 41 |
+
setattr(self, name, state[name])
|
| 42 |
+
self.generator.set_state(state["generator"])
|
| 43 |
+
self.restore_rng(state["rng"])
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def capture_rng():
|
| 47 |
+
return {
|
| 48 |
+
"python": random.getstate(),
|
| 49 |
+
"torch": torch.get_rng_state(),
|
| 50 |
+
"cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None,
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
@staticmethod
|
| 54 |
+
def restore_rng(state):
|
| 55 |
+
random.setstate(state["python"])
|
| 56 |
+
torch.set_rng_state(state["torch"])
|
| 57 |
+
if state["cuda"] is not None and torch.cuda.is_available():
|
| 58 |
+
torch.cuda.set_rng_state_all(state["cuda"])
|
| 59 |
+
|
| 60 |
+
def progress(self, epoch, label):
|
| 61 |
+
self.epoch = epoch
|
| 62 |
+
if self.batch:
|
| 63 |
+
current_rng = self.capture_rng()
|
| 64 |
+
self.generator.set_state(self.epoch_generator)
|
| 65 |
+
self.restore_rng(self.epoch_rng)
|
| 66 |
+
batches = iter(self.loader)
|
| 67 |
+
for _ in range(self.batch):
|
| 68 |
+
next(batches)
|
| 69 |
+
self.restore_rng(current_rng)
|
| 70 |
+
else:
|
| 71 |
+
self.epoch_rng = self.capture_rng()
|
| 72 |
+
self.epoch_generator = self.generator.get_state()
|
| 73 |
+
batches = iter(self.loader)
|
| 74 |
+
return tqdm(
|
| 75 |
+
batches, total=len(self.loader), initial=self.batch,
|
| 76 |
+
desc=f"[{label}] Epoch {epoch + 1}",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def step(self, loss):
|
| 80 |
+
self.batch += 1
|
| 81 |
+
self.global_step += 1
|
| 82 |
+
self.total_loss += loss
|
| 83 |
+
|
| 84 |
+
def state_dict(self):
|
| 85 |
+
return {
|
| 86 |
+
"optimizer": self.optimizer.state_dict(),
|
| 87 |
+
"scheduler": self.scheduler.state_dict(),
|
| 88 |
+
"epoch": self.epoch,
|
| 89 |
+
"batch": self.batch,
|
| 90 |
+
"global_step": self.global_step,
|
| 91 |
+
"total_loss": self.total_loss,
|
| 92 |
+
"best_score": self.best_score,
|
| 93 |
+
"batches_per_epoch": len(self.loader),
|
| 94 |
+
"rng": self.capture_rng(),
|
| 95 |
+
"generator": self.generator.get_state(),
|
| 96 |
+
"epoch_rng": self.epoch_rng,
|
| 97 |
+
"epoch_generator": self.epoch_generator,
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
def finish_epoch(self, score):
|
| 101 |
+
self.epoch += 1
|
| 102 |
+
self.batch = 0
|
| 103 |
+
self.total_loss = 0.0
|
| 104 |
+
previous_best = self.best_score
|
| 105 |
+
self.best_score = max(score, previous_best)
|
| 106 |
+
save_training_models(self.model, self.path, score, previous_best, self.state_dict())
|
| 107 |
+
|
| 108 |
+
def __enter__(self):
|
| 109 |
+
return self
|
| 110 |
+
|
| 111 |
+
def __exit__(self, exception_type, exception, traceback):
|
| 112 |
+
if exception_type is KeyboardInterrupt:
|
| 113 |
+
checkpoint = os.path.join(self.path, "last")
|
| 114 |
+
self.model.save(checkpoint)
|
| 115 |
+
torch.save(self.state_dict(), os.path.join(checkpoint, "training_state.pt"))
|
| 116 |
+
return False
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def save_training_models(
|
| 120 |
+
model: Any, path: str, score: float, best_score: float, training_state=None
|
| 121 |
+
) -> float:
|
| 122 |
+
"""Save the latest model and update the best model when its score improves."""
|
| 123 |
+
model.save(os.path.join(path, "last"))
|
| 124 |
+
if training_state is not None:
|
| 125 |
+
torch.save(training_state, os.path.join(path, "last", "training_state.pt"))
|
| 126 |
+
if score > best_score:
|
| 127 |
+
model.save(os.path.join(path, "best"))
|
| 128 |
+
if training_state is not None:
|
| 129 |
+
torch.save(training_state, os.path.join(path, "best", "training_state.pt"))
|
| 130 |
+
return score
|
| 131 |
+
return best_score
|
src/models/evaluation.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helpers for evaluating component predictions on CoNLL-U validation data."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
from typing import Dict, List, Sequence
|
| 7 |
+
|
| 8 |
+
from eval.conll18_ud_eval import EvalResult, evaluate
|
| 9 |
+
from src.data.conllu import Sentence, write_conllu
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def evaluate_predictions(
|
| 13 |
+
gold_sentences: Sequence[Sentence],
|
| 14 |
+
predicted_sentences: Sequence[Sentence],
|
| 15 |
+
) -> Dict[str, EvalResult]:
|
| 16 |
+
"""Evaluate predicted sentences with the CoNLL-U UD evaluator."""
|
| 17 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 18 |
+
gold_path = os.path.join(temp_dir, "gold.conllu")
|
| 19 |
+
predicted_path = os.path.join(temp_dir, "predicted.conllu")
|
| 20 |
+
write_conllu(list(gold_sentences), gold_path)
|
| 21 |
+
write_conllu(list(predicted_sentences), predicted_path)
|
| 22 |
+
return evaluate(gold_path, predicted_path)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def tokenizer_validation_text(sentences: Sequence[Sentence]) -> str:
|
| 26 |
+
"""Reconstruct text from gold surface tokens for tokenizer validation."""
|
| 27 |
+
sentence_texts = []
|
| 28 |
+
for sentence in sentences:
|
| 29 |
+
sentence_texts.append("".join(
|
| 30 |
+
token.form + (" " if token.space_after else "")
|
| 31 |
+
for token in sentence.surface_tokens()
|
| 32 |
+
))
|
| 33 |
+
return "".join(sentence_texts)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def print_validation_metrics(
|
| 37 |
+
metrics: Dict[str, EvalResult], metric_names: Sequence[str]
|
| 38 |
+
) -> None:
|
| 39 |
+
"""Print selected CoNLL-U validation metrics in the evaluator's format."""
|
| 40 |
+
print(f" {'Metric':<12} {'Precision':>10} {'Recall':>10} {'F1':>10} {'Gold':>8} {'System':>8}")
|
| 41 |
+
print(" " + "-" * 62)
|
| 42 |
+
for name in metric_names:
|
| 43 |
+
result = metrics[name]
|
| 44 |
+
print(
|
| 45 |
+
f" {name:<12} {result.precision:>10.2%} {result.recall:>10.2%}"
|
| 46 |
+
f" {result.f1:>10.2%} {result.gold_count:>8} {result.system_count:>8}"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def average_f1(metrics: Dict[str, EvalResult], metric_names: Sequence[str]) -> float:
|
| 51 |
+
"""Return the mean F1 score across the requested validation metrics."""
|
| 52 |
+
return sum(metrics[name].f1 for name in metric_names) / len(metric_names)
|
src/models/inference.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared, right-padded batches for sentence-level inference."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Iterator, List, Dict
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
from src.data.conllu import Sentence, Token
|
| 12 |
+
from src.models.base import BorgBaseModel
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclass
|
| 16 |
+
class SentenceBatch:
|
| 17 |
+
indices: List[int]
|
| 18 |
+
tokens: List[List[Token]]
|
| 19 |
+
input_ids: torch.Tensor
|
| 20 |
+
attention_mask: torch.Tensor
|
| 21 |
+
word_ids: List[List[int | None]]
|
| 22 |
+
word_positions: List[Dict[int, int]]
|
| 23 |
+
input_char_ids: torch.Tensor | None = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def sentence_batches(
|
| 27 |
+
model: BorgBaseModel,
|
| 28 |
+
sentences: List[Sentence],
|
| 29 |
+
*,
|
| 30 |
+
show_progress: bool = False,
|
| 31 |
+
) -> Iterator[SentenceBatch]:
|
| 32 |
+
batch_size = model.config.eval_batch_size
|
| 33 |
+
if batch_size < 1:
|
| 34 |
+
raise ValueError("eval_batch_size must be positive")
|
| 35 |
+
|
| 36 |
+
token_getter = (
|
| 37 |
+
Sentence.surface_tokens
|
| 38 |
+
if model.component == "mwt"
|
| 39 |
+
else Sentence.regular_tokens
|
| 40 |
+
)
|
| 41 |
+
examples = [
|
| 42 |
+
(index, token_getter(sentence))
|
| 43 |
+
for index, sentence in enumerate(sentences)
|
| 44 |
+
]
|
| 45 |
+
examples = sorted(
|
| 46 |
+
(example for example in examples if example[1]),
|
| 47 |
+
key=lambda example: sum(len(token.form) for token in example[1]),
|
| 48 |
+
)
|
| 49 |
+
for start in tqdm(
|
| 50 |
+
range(0, len(examples), batch_size),
|
| 51 |
+
desc=f"[{type(model).__name__}] Predict",
|
| 52 |
+
unit="batch",
|
| 53 |
+
disable=not show_progress or not examples,
|
| 54 |
+
):
|
| 55 |
+
chunk = examples[start:start + batch_size]
|
| 56 |
+
encoding = model.hf_tokenizer(
|
| 57 |
+
[[token.form for token in tokens] for _, tokens in chunk],
|
| 58 |
+
is_split_into_words=True,
|
| 59 |
+
max_length=model.config.max_seq_length,
|
| 60 |
+
truncation=True,
|
| 61 |
+
padding=False,
|
| 62 |
+
)
|
| 63 |
+
word_ids = [
|
| 64 |
+
encoding.word_ids(batch_index=index)
|
| 65 |
+
for index in range(len(chunk))
|
| 66 |
+
]
|
| 67 |
+
word_positions = []
|
| 68 |
+
for ids in word_ids:
|
| 69 |
+
positions: Dict[int, int] = {}
|
| 70 |
+
for position, word_id in enumerate(ids):
|
| 71 |
+
if word_id is not None:
|
| 72 |
+
positions.setdefault(word_id, position)
|
| 73 |
+
word_positions.append(positions)
|
| 74 |
+
|
| 75 |
+
input_char_ids = None
|
| 76 |
+
if model.component in ("lemmatizer", "mwt"):
|
| 77 |
+
vocab = model.input_vocab
|
| 78 |
+
pad_id = vocab["<PAD>"]
|
| 79 |
+
char_sequences = []
|
| 80 |
+
max_char_length = max(
|
| 81 |
+
len(token.form) + 2
|
| 82 |
+
for _, tokens in chunk
|
| 83 |
+
for token in tokens
|
| 84 |
+
)
|
| 85 |
+
for (_, tokens), ids in zip(chunk, word_ids):
|
| 86 |
+
seen_words = set()
|
| 87 |
+
char_rows = []
|
| 88 |
+
for word_id in ids:
|
| 89 |
+
if word_id is None:
|
| 90 |
+
continue
|
| 91 |
+
if word_id not in seen_words:
|
| 92 |
+
token = tokens[word_id]
|
| 93 |
+
char_ids = [vocab["<SOS>"]]
|
| 94 |
+
char_ids.extend(
|
| 95 |
+
vocab.get(char, vocab["<UNK>"])
|
| 96 |
+
for char in token.form
|
| 97 |
+
)
|
| 98 |
+
char_ids.append(vocab["<EOS>"])
|
| 99 |
+
seen_words.add(word_id)
|
| 100 |
+
else:
|
| 101 |
+
char_ids = [pad_id]
|
| 102 |
+
char_rows.append(
|
| 103 |
+
char_ids + [pad_id] * (max_char_length - len(char_ids))
|
| 104 |
+
)
|
| 105 |
+
char_sequences.append(torch.tensor(char_rows, dtype=torch.long))
|
| 106 |
+
input_char_ids = pad_sequence(
|
| 107 |
+
char_sequences,
|
| 108 |
+
batch_first=True,
|
| 109 |
+
padding_value=pad_id,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# ROOT is position zero in the parser, irrespective of tokenizer padding_side.
|
| 113 |
+
yield SentenceBatch(
|
| 114 |
+
indices=[index for index, _ in chunk],
|
| 115 |
+
tokens=[tokens for _, tokens in chunk],
|
| 116 |
+
input_ids=pad_sequence(
|
| 117 |
+
[torch.tensor(ids, dtype=torch.long) for ids in encoding["input_ids"]],
|
| 118 |
+
batch_first=True,
|
| 119 |
+
padding_value=model.hf_tokenizer.pad_token_id,
|
| 120 |
+
),
|
| 121 |
+
attention_mask=pad_sequence(
|
| 122 |
+
[torch.tensor(mask, dtype=torch.long) for mask in encoding["attention_mask"]],
|
| 123 |
+
batch_first=True,
|
| 124 |
+
padding_value=0,
|
| 125 |
+
),
|
| 126 |
+
word_ids=word_ids,
|
| 127 |
+
word_positions=word_positions,
|
| 128 |
+
input_char_ids=input_char_ids,
|
| 129 |
+
)
|
src/models/lemmatizer.py
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lemmatizer model: edit-script classification."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from dataclasses import replace
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from typing import Any, Dict, List, Optional
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 11 |
+
from torch.utils.data import DataLoader
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
from transformers import get_linear_schedule_with_warmup
|
| 14 |
+
|
| 15 |
+
from src.config import BorgConfig
|
| 16 |
+
from src.data.conllu import Sentence, Token
|
| 17 |
+
from src.data.dataset import (
|
| 18 |
+
LemmatizerDataset,
|
| 19 |
+
_build_vocab
|
| 20 |
+
)
|
| 21 |
+
from src.models.base import BorgBaseModel
|
| 22 |
+
from src.models.inference import sentence_batches
|
| 23 |
+
from src.models.evaluation import (
|
| 24 |
+
average_f1,
|
| 25 |
+
evaluate_predictions,
|
| 26 |
+
print_validation_metrics,
|
| 27 |
+
)
|
| 28 |
+
from src.models.checkpoints import TrainingState
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
MAX_WORD_CHARS = 50
|
| 32 |
+
MAX_TRAINING_WORDS = 128
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _prepare_training_sentences(sentences: List[Sentence]) -> List[Sentence]:
|
| 36 |
+
prepared = []
|
| 37 |
+
for sentence in sentences:
|
| 38 |
+
tokens = []
|
| 39 |
+
word_count = 0
|
| 40 |
+
for token in sentence.tokens:
|
| 41 |
+
if token.is_multiword() or token.is_empty():
|
| 42 |
+
tokens.append(token)
|
| 43 |
+
continue
|
| 44 |
+
|
| 45 |
+
word_count += 1
|
| 46 |
+
tokens.append(replace(
|
| 47 |
+
token,
|
| 48 |
+
form=token.form[:MAX_WORD_CHARS],
|
| 49 |
+
lemma=token.lemma[:MAX_WORD_CHARS],
|
| 50 |
+
))
|
| 51 |
+
if word_count == MAX_TRAINING_WORDS:
|
| 52 |
+
break
|
| 53 |
+
|
| 54 |
+
prepared.append(Sentence(tokens=tokens, comments=list(sentence.comments)))
|
| 55 |
+
return prepared
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _truncate_runtime_sentences(sentences: List[Sentence]) -> List[Sentence]:
|
| 59 |
+
return [
|
| 60 |
+
Sentence(
|
| 61 |
+
tokens=[
|
| 62 |
+
replace(token, form=token.form[:MAX_WORD_CHARS])
|
| 63 |
+
if not token.is_multiword() and not token.is_empty()
|
| 64 |
+
else token
|
| 65 |
+
for token in sentence.tokens
|
| 66 |
+
],
|
| 67 |
+
comments=list(sentence.comments),
|
| 68 |
+
)
|
| 69 |
+
for sentence in sentences
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class LemmatizerModel(BorgBaseModel):
|
| 74 |
+
"""Classifies each token into a lemma edit-script."""
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
config: BorgConfig,
|
| 79 |
+
upos_vocab: Optional[Dict[str, int]] = None,
|
| 80 |
+
input_vocab: Optional[Dict[str, int]] = None,
|
| 81 |
+
output_vocab: Optional[Dict[str, int]] = None,
|
| 82 |
+
):
|
| 83 |
+
super().__init__(config, "lemmatizer")
|
| 84 |
+
|
| 85 |
+
self.upos_vocab = upos_vocab or {
|
| 86 |
+
"<PAD>": 0,
|
| 87 |
+
"<UNK>": 1,
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
self.output_vocab = output_vocab or {
|
| 91 |
+
"<PAD>": 0,
|
| 92 |
+
"<UNK>": 1,
|
| 93 |
+
"<SOS>": 2,
|
| 94 |
+
"<EOS>": 3
|
| 95 |
+
}
|
| 96 |
+
self.input_vocab = input_vocab or {
|
| 97 |
+
"<PAD>": 0,
|
| 98 |
+
"<UNK>": 1,
|
| 99 |
+
"<SOS>": 2,
|
| 100 |
+
"<EOS>": 3
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
self._build_heads()
|
| 104 |
+
|
| 105 |
+
def _build_heads(self) -> None:
|
| 106 |
+
upos_emb_dim = 32
|
| 107 |
+
char_emb_dim = 64
|
| 108 |
+
lstm_size = 200
|
| 109 |
+
|
| 110 |
+
self.upos_embedding = nn.Embedding(
|
| 111 |
+
len(self.upos_vocab),
|
| 112 |
+
upos_emb_dim,
|
| 113 |
+
padding_idx=0,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
self.input_embedding = nn.Embedding(
|
| 117 |
+
len(self.input_vocab),
|
| 118 |
+
char_emb_dim,
|
| 119 |
+
padding_idx=0,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
self.output_embedding = nn.Embedding(
|
| 123 |
+
len(self.output_vocab),
|
| 124 |
+
char_emb_dim,
|
| 125 |
+
padding_idx=0,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
self.output_logit = nn.Linear(
|
| 129 |
+
lstm_size * 2,
|
| 130 |
+
len(self.output_vocab)
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
self.input_encoder=nn.LSTM(
|
| 134 |
+
input_size=upos_emb_dim+char_emb_dim+self.encoder.config.hidden_size,
|
| 135 |
+
hidden_size=lstm_size,
|
| 136 |
+
num_layers=2,
|
| 137 |
+
batch_first=True,
|
| 138 |
+
bidirectional=True,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
self.output_decoder=nn.LSTM(
|
| 142 |
+
input_size=lstm_size * 2+char_emb_dim,
|
| 143 |
+
hidden_size=lstm_size * 2,
|
| 144 |
+
num_layers=1,
|
| 145 |
+
batch_first=True,
|
| 146 |
+
bidirectional=False,
|
| 147 |
+
)
|
| 148 |
+
self.attention=nn.MultiheadAttention(
|
| 149 |
+
embed_dim=lstm_size*2,
|
| 150 |
+
num_heads=1,
|
| 151 |
+
batch_first=True,
|
| 152 |
+
kdim=lstm_size*2,
|
| 153 |
+
vdim=lstm_size*2
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def forward(
|
| 158 |
+
self,
|
| 159 |
+
input_ids: torch.Tensor,
|
| 160 |
+
attention_mask: torch.Tensor,
|
| 161 |
+
upos_ids: torch.Tensor,
|
| 162 |
+
input_char_ids: torch.Tensor,
|
| 163 |
+
output_char_ids: Optional[torch.Tensor] = None,
|
| 164 |
+
max_output_length: int = 200,
|
| 165 |
+
) -> torch.Tensor:
|
| 166 |
+
hidden = self.encode(
|
| 167 |
+
input_ids,
|
| 168 |
+
attention_mask,
|
| 169 |
+
) # (B, L, H)
|
| 170 |
+
|
| 171 |
+
upos_emb = self.upos_embedding(
|
| 172 |
+
upos_ids
|
| 173 |
+
) # (B, L, E)
|
| 174 |
+
|
| 175 |
+
concat = torch.cat(
|
| 176 |
+
[hidden, upos_emb],
|
| 177 |
+
dim=-1,
|
| 178 |
+
) # (B, L, H+E)
|
| 179 |
+
|
| 180 |
+
concat=concat[:,1:-1,:]
|
| 181 |
+
concat=concat.reshape((concat.shape[0]*concat.shape[1], -1))
|
| 182 |
+
input_char_ids=input_char_ids.reshape((input_char_ids.shape[0]*input_char_ids.shape[1], input_char_ids.shape[2]))
|
| 183 |
+
output_char_ids=output_char_ids.reshape((output_char_ids.shape[0]*output_char_ids.shape[1], output_char_ids.shape[2])) if output_char_ids is not None else None
|
| 184 |
+
|
| 185 |
+
input_char_emb = self.input_embedding(input_char_ids)
|
| 186 |
+
concat=concat.unsqueeze(1).repeat(1, input_char_emb.shape[1], 1)
|
| 187 |
+
input_embedding= torch.cat([concat, input_char_emb], dim=-1)
|
| 188 |
+
with torch.autocast(device_type=input_embedding.device.type, enabled=False):
|
| 189 |
+
encoder_states, _=self.input_encoder(input_embedding.float())
|
| 190 |
+
|
| 191 |
+
output_strings=["" for _ in range(input_char_ids.shape[0])]
|
| 192 |
+
finished = [False for _ in output_strings]
|
| 193 |
+
inverse_output_vocab = {value: key for key, value in self.output_vocab.items()}
|
| 194 |
+
output_logits=[]
|
| 195 |
+
last_output_embeddings=torch.zeros((input_char_ids.shape[0], 1, input_char_emb.shape[2]+encoder_states.shape[2]), device=encoder_states.device)
|
| 196 |
+
decoder_hidden=None
|
| 197 |
+
if output_char_ids is not None:
|
| 198 |
+
output_char_ids=torch.clamp(output_char_ids, min=0)
|
| 199 |
+
max_output_length=output_char_ids.shape[1]
|
| 200 |
+
|
| 201 |
+
for step in range(max_output_length):
|
| 202 |
+
with torch.autocast(
|
| 203 |
+
device_type=last_output_embeddings.device.type,
|
| 204 |
+
enabled=False,
|
| 205 |
+
):
|
| 206 |
+
decoder_output, decoder_hidden=self.output_decoder(
|
| 207 |
+
last_output_embeddings.float(),
|
| 208 |
+
decoder_hidden,
|
| 209 |
+
)
|
| 210 |
+
logits=self.output_logit(decoder_output)
|
| 211 |
+
output_logits.append(logits)
|
| 212 |
+
last_output_char_ids=logits.argmax(-1)
|
| 213 |
+
if output_char_ids is not None:
|
| 214 |
+
output_char_emb=self.output_embedding(output_char_ids[:,step:step+1])
|
| 215 |
+
else:
|
| 216 |
+
output_char_emb=self.output_embedding(last_output_char_ids)
|
| 217 |
+
for index, char_id in enumerate(last_output_char_ids[:, 0].tolist()):
|
| 218 |
+
if char_id == self.output_vocab["<EOS>"]:
|
| 219 |
+
finished[index] = True
|
| 220 |
+
elif not finished[index] and char_id not in (
|
| 221 |
+
self.output_vocab["<PAD>"],
|
| 222 |
+
self.output_vocab["<SOS>"],
|
| 223 |
+
):
|
| 224 |
+
output_strings[index] += inverse_output_vocab.get(char_id, "")
|
| 225 |
+
if all(finished):
|
| 226 |
+
break
|
| 227 |
+
attention_output, _=self.attention(
|
| 228 |
+
query=decoder_output,
|
| 229 |
+
key=encoder_states,
|
| 230 |
+
value=encoder_states,
|
| 231 |
+
)
|
| 232 |
+
last_output_embeddings=torch.cat([output_char_emb, attention_output], dim=-1)
|
| 233 |
+
# from ipdb import set_trace; set_trace()
|
| 234 |
+
return {
|
| 235 |
+
"logits": torch.cat(output_logits, dim=1),
|
| 236 |
+
"strings": output_strings
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
# ------------------------------------------------------------------
|
| 240 |
+
def _get_extras(self) -> Dict[str, Any]:
|
| 241 |
+
return {
|
| 242 |
+
"upos_vocab": self.upos_vocab,
|
| 243 |
+
"input_vocab": self.input_vocab,
|
| 244 |
+
"output_vocab": self.output_vocab,
|
| 245 |
+
"upos_embedding": self.upos_embedding.state_dict(),
|
| 246 |
+
"input_embedding": self.input_embedding.state_dict(),
|
| 247 |
+
"output_embedding": self.output_embedding.state_dict(),
|
| 248 |
+
"input_encoder": self.input_encoder.state_dict(),
|
| 249 |
+
"output_decoder": self.output_decoder.state_dict(),
|
| 250 |
+
"output_logit": self.output_logit.state_dict(),
|
| 251 |
+
"attention": self.attention.state_dict(),
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
def _set_extras(
|
| 255 |
+
self,
|
| 256 |
+
extras: Dict[str, Any],
|
| 257 |
+
) -> None:
|
| 258 |
+
self.upos_vocab = extras["upos_vocab"]
|
| 259 |
+
self.input_vocab = extras["input_vocab"]
|
| 260 |
+
self.output_vocab = extras["output_vocab"]
|
| 261 |
+
|
| 262 |
+
self._build_heads()
|
| 263 |
+
|
| 264 |
+
for name in (
|
| 265 |
+
"upos_embedding",
|
| 266 |
+
"input_embedding",
|
| 267 |
+
"output_embedding",
|
| 268 |
+
"input_encoder",
|
| 269 |
+
"output_decoder",
|
| 270 |
+
"output_logit",
|
| 271 |
+
"attention",
|
| 272 |
+
):
|
| 273 |
+
getattr(self, name).load_state_dict(extras[name])
|
| 274 |
+
|
| 275 |
+
# ------------------------------------------------------------------
|
| 276 |
+
@staticmethod
|
| 277 |
+
def train_model(
|
| 278 |
+
train_sentences: List[Sentence],
|
| 279 |
+
dev_sentences: List[Sentence],
|
| 280 |
+
config: BorgConfig,
|
| 281 |
+
model_path: str,
|
| 282 |
+
*,
|
| 283 |
+
resume: bool = False,
|
| 284 |
+
) -> "LemmatizerModel":
|
| 285 |
+
device = config.resolve_device()
|
| 286 |
+
device_type = torch.device(device).type
|
| 287 |
+
train_sentences = _prepare_training_sentences(train_sentences)
|
| 288 |
+
|
| 289 |
+
torch.manual_seed(config.seed)
|
| 290 |
+
|
| 291 |
+
all_upos = [
|
| 292 |
+
t.upos
|
| 293 |
+
for s in train_sentences
|
| 294 |
+
for t in s.regular_tokens()
|
| 295 |
+
]
|
| 296 |
+
all_input_chars = [
|
| 297 |
+
c for s in train_sentences for t in s.regular_tokens() for c in t.form
|
| 298 |
+
]
|
| 299 |
+
all_output_chars = [
|
| 300 |
+
c for s in train_sentences for t in s.regular_tokens() for c in t.lemma
|
| 301 |
+
]
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
upos_vocab = _build_vocab(all_upos)
|
| 305 |
+
input_vocab = _build_vocab(all_input_chars, initial_vocab={"<PAD>": 0, "<UNK>": 1, "<SOS>": 2, "<EOS>": 3})
|
| 306 |
+
output_vocab = _build_vocab(all_output_chars, initial_vocab={"<PAD>": 0, "<UNK>": 1, "<SOS>": 2, "<EOS>": 3})
|
| 307 |
+
|
| 308 |
+
if resume:
|
| 309 |
+
model = LemmatizerModel.load(os.path.join(model_path, "last"), config).to(device)
|
| 310 |
+
upos_vocab = model.upos_vocab
|
| 311 |
+
input_vocab = model.input_vocab
|
| 312 |
+
output_vocab = model.output_vocab
|
| 313 |
+
else:
|
| 314 |
+
model = LemmatizerModel(
|
| 315 |
+
config,
|
| 316 |
+
upos_vocab,
|
| 317 |
+
input_vocab,
|
| 318 |
+
output_vocab,
|
| 319 |
+
).to(device)
|
| 320 |
+
|
| 321 |
+
train_ds = LemmatizerDataset(
|
| 322 |
+
train_sentences,
|
| 323 |
+
config.model_name,
|
| 324 |
+
config.max_seq_length,
|
| 325 |
+
upos_vocab,
|
| 326 |
+
input_vocab,
|
| 327 |
+
output_vocab,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
train_loader = DataLoader(
|
| 331 |
+
train_ds,
|
| 332 |
+
batch_size=config.batch_size,
|
| 333 |
+
shuffle=True,
|
| 334 |
+
collate_fn=train_ds.collate_fn,
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
optimizer = torch.optim.AdamW(
|
| 338 |
+
model.parameters(),
|
| 339 |
+
lr=config.learning_rate,
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
total_steps = (
|
| 343 |
+
len(train_loader)
|
| 344 |
+
* config.num_epochs
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
warmup_steps = int(
|
| 348 |
+
total_steps
|
| 349 |
+
* config.warmup_ratio
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
scheduler = get_linear_schedule_with_warmup(
|
| 353 |
+
optimizer,
|
| 354 |
+
warmup_steps,
|
| 355 |
+
total_steps,
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
loss_fn = nn.CrossEntropyLoss(
|
| 359 |
+
ignore_index=-100
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
with TrainingState(
|
| 363 |
+
model, model_path, optimizer, scheduler, train_loader, resume=resume,
|
| 364 |
+
) as state:
|
| 365 |
+
for epoch in range(state.epoch, config.num_epochs):
|
| 366 |
+
model.train()
|
| 367 |
+
progress = state.progress(epoch, "Lemmatizer")
|
| 368 |
+
for batch in progress:
|
| 369 |
+
input_ids = batch[
|
| 370 |
+
"input_ids"
|
| 371 |
+
].to(device)
|
| 372 |
+
|
| 373 |
+
attention_mask = batch[
|
| 374 |
+
"attention_mask"
|
| 375 |
+
].to(device)
|
| 376 |
+
|
| 377 |
+
upos_ids = batch[
|
| 378 |
+
"upos_ids"
|
| 379 |
+
].to(device)
|
| 380 |
+
|
| 381 |
+
input_char_ids = batch[
|
| 382 |
+
"input_char_ids"
|
| 383 |
+
].to(device)
|
| 384 |
+
|
| 385 |
+
output_char_ids = batch[
|
| 386 |
+
"output_char_ids"
|
| 387 |
+
].to(device)
|
| 388 |
+
|
| 389 |
+
optimizer.zero_grad()
|
| 390 |
+
|
| 391 |
+
with config.autocast_context(device):
|
| 392 |
+
logits = model(
|
| 393 |
+
input_ids,
|
| 394 |
+
attention_mask,
|
| 395 |
+
upos_ids,
|
| 396 |
+
input_char_ids,
|
| 397 |
+
output_char_ids
|
| 398 |
+
)['logits']
|
| 399 |
+
loss = loss_fn(
|
| 400 |
+
logits.view(
|
| 401 |
+
-1,
|
| 402 |
+
logits.shape[-1]
|
| 403 |
+
),
|
| 404 |
+
output_char_ids.view(-1),
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
loss.backward()
|
| 408 |
+
|
| 409 |
+
nn.utils.clip_grad_norm_(
|
| 410 |
+
model.parameters(),
|
| 411 |
+
1.0,
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
optimizer.step()
|
| 415 |
+
scheduler.step()
|
| 416 |
+
|
| 417 |
+
state.step(loss.item())
|
| 418 |
+
|
| 419 |
+
progress.set_postfix(
|
| 420 |
+
loss=f"{loss.item():.4f}",
|
| 421 |
+
avg_loss=(f"{state.total_loss / state.batch:.4f}"),
|
| 422 |
+
lr=(
|
| 423 |
+
f"{scheduler.get_last_lr()[0]:.2e}"
|
| 424 |
+
),
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
avg_loss = state.total_loss / len(train_loader)
|
| 428 |
+
|
| 429 |
+
metrics = evaluate_predictions(
|
| 430 |
+
dev_sentences,
|
| 431 |
+
model.predict(dev_sentences),
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
print(f" loss={avg_loss:.4f}")
|
| 435 |
+
|
| 436 |
+
print_validation_metrics(
|
| 437 |
+
metrics,
|
| 438 |
+
["LEMMA"],
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
score = average_f1(
|
| 442 |
+
metrics,
|
| 443 |
+
["LEMMA"],
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
state.finish_epoch(score)
|
| 447 |
+
|
| 448 |
+
return model
|
| 449 |
+
|
| 450 |
+
# ------------------------------------------------------------------
|
| 451 |
+
def predict(
|
| 452 |
+
self,
|
| 453 |
+
sentences: List[Sentence],
|
| 454 |
+
*,
|
| 455 |
+
show_progress: bool = True,
|
| 456 |
+
) -> List[Sentence]:
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
device = self.config.resolve_device()
|
| 460 |
+
device_type = torch.device(device).type
|
| 461 |
+
|
| 462 |
+
self.eval()
|
| 463 |
+
self.to(device)
|
| 464 |
+
results = list(sentences)
|
| 465 |
+
runtime_sentences = _truncate_runtime_sentences(sentences)
|
| 466 |
+
for batch in sentence_batches(
|
| 467 |
+
self, runtime_sentences, show_progress=show_progress,
|
| 468 |
+
):
|
| 469 |
+
if batch.input_char_ids is None:
|
| 470 |
+
raise RuntimeError("Lemmatizer inference requires input character IDs")
|
| 471 |
+
upos_ids = torch.zeros_like(batch.input_ids)
|
| 472 |
+
for row, word_ids in enumerate(batch.word_ids):
|
| 473 |
+
token_upos = [
|
| 474 |
+
self.upos_vocab.get(token.upos, self.upos_vocab["<UNK>"])
|
| 475 |
+
for token in batch.tokens[row]
|
| 476 |
+
]
|
| 477 |
+
upos_ids[row, :len(word_ids)] = torch.tensor(
|
| 478 |
+
[token_upos[wid] if wid is not None else 0 for wid in word_ids],
|
| 479 |
+
dtype=torch.long,
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
with torch.inference_mode(), self.config.autocast_context(device):
|
| 483 |
+
lemmas = self(
|
| 484 |
+
batch.input_ids.to(device),
|
| 485 |
+
batch.attention_mask.to(device),
|
| 486 |
+
upos_ids.to(device),
|
| 487 |
+
batch.input_char_ids.to(device),
|
| 488 |
+
)["strings"]
|
| 489 |
+
|
| 490 |
+
for row, index in enumerate(batch.indices):
|
| 491 |
+
sent = sentences[index]
|
| 492 |
+
sequence_width = batch.input_ids.shape[1] - 2
|
| 493 |
+
word_lemmas = {
|
| 494 |
+
word_id: lemmas[row * sequence_width + position - 1]
|
| 495 |
+
for word_id, position in batch.word_positions[row].items()
|
| 496 |
+
}
|
| 497 |
+
new_sent = Sentence(comments=sent.comments)
|
| 498 |
+
word_id = 0
|
| 499 |
+
for tok in sent.tokens:
|
| 500 |
+
if tok.is_multiword() or tok.is_empty():
|
| 501 |
+
new_sent.tokens.append(tok)
|
| 502 |
+
continue
|
| 503 |
+
if len(tok.form) > MAX_WORD_CHARS:
|
| 504 |
+
new_sent.tokens.append(
|
| 505 |
+
replace(tok, form=tok.form, lemma=tok.form)
|
| 506 |
+
)
|
| 507 |
+
word_id += 1
|
| 508 |
+
continue
|
| 509 |
+
new_sent.tokens.append(
|
| 510 |
+
replace(tok, lemma=word_lemmas.get(word_id, tok.lemma))
|
| 511 |
+
)
|
| 512 |
+
word_id += 1
|
| 513 |
+
results[index] = new_sent
|
| 514 |
+
|
| 515 |
+
return results
|
src/models/mwt.py
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Character-level multiword-token expansion model."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from dataclasses import replace
|
| 7 |
+
from typing import Any, Dict, List, Optional
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
|
| 12 |
+
from torch.utils.data import DataLoader
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
from src.config import BorgConfig
|
| 16 |
+
from src.data.conllu import Sentence, Token
|
| 17 |
+
from src.data.dataset import MWTDataset
|
| 18 |
+
from src.models.checkpoints import TrainingState
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _mwt_precision_recall(
|
| 22 |
+
expected: List[str],
|
| 23 |
+
predicted: List[str],
|
| 24 |
+
) -> tuple[float, float]:
|
| 25 |
+
true_positives = 0
|
| 26 |
+
false_positives = 0
|
| 27 |
+
false_negatives = 0
|
| 28 |
+
for gold, guess in zip(expected, predicted):
|
| 29 |
+
gold_is_mwt = len(gold.split()) > 1
|
| 30 |
+
guess_is_mwt = len(guess.split()) > 1
|
| 31 |
+
correct_expansion = gold_is_mwt and guess == gold
|
| 32 |
+
true_positives += correct_expansion
|
| 33 |
+
false_positives += guess_is_mwt and not correct_expansion
|
| 34 |
+
false_negatives += gold_is_mwt and not correct_expansion
|
| 35 |
+
|
| 36 |
+
predicted_mwt_count = true_positives + false_positives
|
| 37 |
+
gold_mwt_count = true_positives + false_negatives
|
| 38 |
+
precision = true_positives / predicted_mwt_count if predicted_mwt_count else 0.0
|
| 39 |
+
recall = true_positives / gold_mwt_count if gold_mwt_count else 0.0
|
| 40 |
+
return precision, recall
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class MWTModel(nn.Module):
|
| 44 |
+
"""Expand tokenizer-identified MWT tokens using characters only."""
|
| 45 |
+
|
| 46 |
+
CHAR_EMBEDDING_SIZE = 64
|
| 47 |
+
HIDDEN_SIZE = 128
|
| 48 |
+
MAX_OUTPUT_LENGTH = 128
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
config: BorgConfig,
|
| 53 |
+
output_vocab: Optional[Dict[str, int]] = None,
|
| 54 |
+
input_vocab: Optional[Dict[str, int]] = None,
|
| 55 |
+
):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.config = config
|
| 58 |
+
self.component = "mwt"
|
| 59 |
+
specials = {"<PAD>": 0, "<UNK>": 1, "<SOS>": 2, "<EOS>": 3}
|
| 60 |
+
self.output_vocab = output_vocab or specials.copy()
|
| 61 |
+
self.input_vocab = input_vocab or specials.copy()
|
| 62 |
+
self._build_heads()
|
| 63 |
+
|
| 64 |
+
def _build_heads(self) -> None:
|
| 65 |
+
embedding_size = self.CHAR_EMBEDDING_SIZE
|
| 66 |
+
hidden_size = self.HIDDEN_SIZE
|
| 67 |
+
self.input_embedding = nn.Embedding(
|
| 68 |
+
len(self.input_vocab), embedding_size, padding_idx=self.input_vocab["<PAD>"]
|
| 69 |
+
)
|
| 70 |
+
self.input_encoder = nn.LSTM(
|
| 71 |
+
embedding_size,
|
| 72 |
+
hidden_size,
|
| 73 |
+
num_layers=1,
|
| 74 |
+
batch_first=True,
|
| 75 |
+
bidirectional=True,
|
| 76 |
+
)
|
| 77 |
+
encoder_size = hidden_size * 2
|
| 78 |
+
self.encoder_projection = nn.Linear(encoder_size, encoder_size, bias=False)
|
| 79 |
+
self.query_projection = nn.Linear(encoder_size, encoder_size, bias=False)
|
| 80 |
+
self.attention_score = nn.Linear(encoder_size, 1, bias=False)
|
| 81 |
+
self.output_embedding = nn.Embedding(
|
| 82 |
+
len(self.output_vocab), embedding_size,
|
| 83 |
+
padding_idx=self.output_vocab["<PAD>"],
|
| 84 |
+
)
|
| 85 |
+
self.output_decoder = nn.LSTM(
|
| 86 |
+
embedding_size + encoder_size,
|
| 87 |
+
encoder_size,
|
| 88 |
+
num_layers=1,
|
| 89 |
+
batch_first=True,
|
| 90 |
+
)
|
| 91 |
+
self.output_logit = nn.Linear(encoder_size * 2, len(self.output_vocab))
|
| 92 |
+
|
| 93 |
+
def _encode(self, input_char_ids: torch.Tensor):
|
| 94 |
+
mask = input_char_ids.ne(self.input_vocab["<PAD>"])
|
| 95 |
+
lengths = mask.sum(dim=1).clamp(min=1).cpu()
|
| 96 |
+
embedded = self.input_embedding(input_char_ids)
|
| 97 |
+
packed = pack_padded_sequence(
|
| 98 |
+
embedded, lengths, batch_first=True, enforce_sorted=False
|
| 99 |
+
)
|
| 100 |
+
encoded, _ = self.input_encoder(packed)
|
| 101 |
+
encoded, _ = pad_packed_sequence(
|
| 102 |
+
encoded, batch_first=True, total_length=input_char_ids.shape[1]
|
| 103 |
+
)
|
| 104 |
+
return encoded, mask, self.encoder_projection(encoded)
|
| 105 |
+
|
| 106 |
+
def _decode_step(self, previous_ids, hidden, encoded, mask, projected):
|
| 107 |
+
query = self.query_projection(hidden[0][-1]).unsqueeze(1)
|
| 108 |
+
scores = self.attention_score(torch.tanh(projected + query)).squeeze(-1)
|
| 109 |
+
scores = scores.masked_fill(~mask, torch.finfo(scores.dtype).min)
|
| 110 |
+
weights = torch.softmax(scores, dim=-1)
|
| 111 |
+
context = torch.bmm(weights.unsqueeze(1), encoded)
|
| 112 |
+
decoder_input = torch.cat(
|
| 113 |
+
[self.output_embedding(previous_ids), context], dim=-1
|
| 114 |
+
)
|
| 115 |
+
decoder_output, hidden = self.output_decoder(decoder_input, hidden)
|
| 116 |
+
logits = self.output_logit(torch.cat([decoder_output, context], dim=-1))
|
| 117 |
+
return logits, hidden
|
| 118 |
+
|
| 119 |
+
def forward(
|
| 120 |
+
self,
|
| 121 |
+
input_char_ids: torch.Tensor,
|
| 122 |
+
output_char_ids: Optional[torch.Tensor] = None,
|
| 123 |
+
max_output_length: int = MAX_OUTPUT_LENGTH,
|
| 124 |
+
) -> Dict[str, Any]:
|
| 125 |
+
encoded, mask, projected = self._encode(input_char_ids)
|
| 126 |
+
batch_size = input_char_ids.shape[0]
|
| 127 |
+
hidden_size = self.HIDDEN_SIZE * 2
|
| 128 |
+
hidden = (
|
| 129 |
+
encoded.new_zeros((1, batch_size, hidden_size)),
|
| 130 |
+
encoded.new_zeros((1, batch_size, hidden_size)),
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
if output_char_ids is not None:
|
| 134 |
+
decoder_inputs = output_char_ids[:, :-1].clamp(min=0)
|
| 135 |
+
logits = []
|
| 136 |
+
for step in range(decoder_inputs.shape[1]):
|
| 137 |
+
step_logits, hidden = self._decode_step(
|
| 138 |
+
decoder_inputs[:, step:step + 1], hidden,
|
| 139 |
+
encoded, mask, projected,
|
| 140 |
+
)
|
| 141 |
+
logits.append(step_logits)
|
| 142 |
+
return {"logits": torch.cat(logits, dim=1)}
|
| 143 |
+
|
| 144 |
+
previous_ids = torch.full(
|
| 145 |
+
(batch_size, 1), self.output_vocab["<SOS>"],
|
| 146 |
+
dtype=torch.long, device=input_char_ids.device,
|
| 147 |
+
)
|
| 148 |
+
finished = torch.zeros(batch_size, dtype=torch.bool, device=input_char_ids.device)
|
| 149 |
+
strings = [""] * batch_size
|
| 150 |
+
inverse_vocab = {index: char for char, index in self.output_vocab.items()}
|
| 151 |
+
for _ in range(max_output_length):
|
| 152 |
+
logits, hidden = self._decode_step(
|
| 153 |
+
previous_ids, hidden, encoded, mask, projected
|
| 154 |
+
)
|
| 155 |
+
previous_ids = logits[:, 0].argmax(-1, keepdim=True)
|
| 156 |
+
for row, char_id in enumerate(previous_ids[:, 0].tolist()):
|
| 157 |
+
if char_id == self.output_vocab["<EOS>"]:
|
| 158 |
+
finished[row] = True
|
| 159 |
+
elif not finished[row] and char_id not in (
|
| 160 |
+
self.output_vocab["<PAD>"],
|
| 161 |
+
self.output_vocab["<SOS>"],
|
| 162 |
+
self.output_vocab["<UNK>"],
|
| 163 |
+
):
|
| 164 |
+
strings[row] += inverse_vocab.get(char_id, "")
|
| 165 |
+
if finished.all():
|
| 166 |
+
break
|
| 167 |
+
return {"strings": strings}
|
| 168 |
+
|
| 169 |
+
def _get_extras(self) -> Dict[str, Any]:
|
| 170 |
+
return {
|
| 171 |
+
"input_vocab": self.input_vocab,
|
| 172 |
+
"output_vocab": self.output_vocab,
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
def save(self, path: str) -> None:
|
| 176 |
+
os.makedirs(path, exist_ok=True)
|
| 177 |
+
with open(os.path.join(path, "borg_config.json"), "w") as output:
|
| 178 |
+
values = self.config.to_dict()
|
| 179 |
+
values["component"] = self.component
|
| 180 |
+
values["model_type"] = "character_mwt_v1"
|
| 181 |
+
json.dump(values, output, indent=2)
|
| 182 |
+
torch.save(
|
| 183 |
+
{**self._get_extras(), "model_state": self.state_dict()},
|
| 184 |
+
os.path.join(path, "extras.pt"),
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
@classmethod
|
| 188 |
+
def load(cls, path: str, config: Optional[BorgConfig] = None) -> "MWTModel":
|
| 189 |
+
with open(os.path.join(path, "borg_config.json")) as source:
|
| 190 |
+
values = json.load(source)
|
| 191 |
+
if values.get("model_type") != "character_mwt_v1":
|
| 192 |
+
raise ValueError(
|
| 193 |
+
"This MWT checkpoint uses the previous BERT-conditioned model; "
|
| 194 |
+
"train a new character-only MWT model."
|
| 195 |
+
)
|
| 196 |
+
values.pop("component", None)
|
| 197 |
+
values.pop("model_type", None)
|
| 198 |
+
checkpoint_config = BorgConfig.from_dict(values)
|
| 199 |
+
extras = torch.load(
|
| 200 |
+
os.path.join(path, "extras.pt"), map_location="cpu", weights_only=False
|
| 201 |
+
)
|
| 202 |
+
model = cls(
|
| 203 |
+
config or checkpoint_config,
|
| 204 |
+
output_vocab=extras["output_vocab"],
|
| 205 |
+
input_vocab=extras["input_vocab"],
|
| 206 |
+
)
|
| 207 |
+
model.load_state_dict(extras["model_state"])
|
| 208 |
+
return model
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def train_model(
|
| 212 |
+
train_sentences: List[Sentence],
|
| 213 |
+
dev_sentences: List[Sentence],
|
| 214 |
+
config: BorgConfig,
|
| 215 |
+
model_path: str,
|
| 216 |
+
*,
|
| 217 |
+
resume: bool = False,
|
| 218 |
+
) -> "MWTModel":
|
| 219 |
+
device = config.resolve_device()
|
| 220 |
+
torch.manual_seed(config.seed)
|
| 221 |
+
|
| 222 |
+
if resume:
|
| 223 |
+
model = MWTModel.load(os.path.join(model_path, "last"), config).to(device)
|
| 224 |
+
train_ds = MWTDataset(
|
| 225 |
+
train_sentences, model.output_vocab, model.input_vocab
|
| 226 |
+
)
|
| 227 |
+
else:
|
| 228 |
+
train_ds = MWTDataset(train_sentences)
|
| 229 |
+
model = MWTModel(
|
| 230 |
+
config, train_ds.output_vocab, train_ds.input_vocab
|
| 231 |
+
).to(device)
|
| 232 |
+
if not len(train_ds):
|
| 233 |
+
raise ValueError("The MWT training data contains no MWT tokens")
|
| 234 |
+
|
| 235 |
+
train_loader = DataLoader(
|
| 236 |
+
train_ds,
|
| 237 |
+
batch_size=config.batch_size,
|
| 238 |
+
shuffle=True,
|
| 239 |
+
collate_fn=train_ds.collate_fn,
|
| 240 |
+
)
|
| 241 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
|
| 242 |
+
total_steps = len(train_loader) * config.num_epochs
|
| 243 |
+
warmup_steps = int(total_steps * config.warmup_ratio)
|
| 244 |
+
|
| 245 |
+
def linear_schedule(step: int) -> float:
|
| 246 |
+
if step < warmup_steps:
|
| 247 |
+
return step / max(warmup_steps, 1)
|
| 248 |
+
return max(
|
| 249 |
+
0.0,
|
| 250 |
+
(total_steps - step) / max(total_steps - warmup_steps, 1),
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, linear_schedule)
|
| 254 |
+
loss_fn = nn.CrossEntropyLoss(ignore_index=-100)
|
| 255 |
+
|
| 256 |
+
dev_ds = MWTDataset(
|
| 257 |
+
dev_sentences, model.output_vocab, model.input_vocab
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
with TrainingState(
|
| 261 |
+
model, model_path, optimizer, scheduler, train_loader, resume=resume,
|
| 262 |
+
) as state:
|
| 263 |
+
for epoch in range(state.epoch, config.num_epochs):
|
| 264 |
+
model.train()
|
| 265 |
+
progress = state.progress(epoch, "MWT")
|
| 266 |
+
for batch in progress:
|
| 267 |
+
input_char_ids = batch["input_char_ids"].to(device)
|
| 268 |
+
output_char_ids = batch["output_char_ids"].to(device)
|
| 269 |
+
optimizer.zero_grad()
|
| 270 |
+
outputs = model(input_char_ids, output_char_ids)
|
| 271 |
+
targets = output_char_ids[:, 1:]
|
| 272 |
+
loss = loss_fn(
|
| 273 |
+
outputs["logits"].reshape(-1, outputs["logits"].shape[-1]),
|
| 274 |
+
targets.reshape(-1),
|
| 275 |
+
)
|
| 276 |
+
loss.backward()
|
| 277 |
+
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 278 |
+
optimizer.step()
|
| 279 |
+
scheduler.step()
|
| 280 |
+
state.step(loss.item())
|
| 281 |
+
progress.set_postfix(
|
| 282 |
+
loss=f"{loss.item():.4f}",
|
| 283 |
+
avg_loss=f"{state.total_loss / max(progress.n, 1):.4f}",
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
model.eval()
|
| 287 |
+
expected = [expansion for _, expansion in dev_ds.examples]
|
| 288 |
+
predicted = [
|
| 289 |
+
expansion for _, expansion in model._predict_pairs(
|
| 290 |
+
[form for form, _ in dev_ds.examples], show_progress=False
|
| 291 |
+
)
|
| 292 |
+
]
|
| 293 |
+
precision, recall = _mwt_precision_recall(expected, predicted)
|
| 294 |
+
score = (
|
| 295 |
+
sum(prediction == target for prediction, target in zip(predicted, expected))
|
| 296 |
+
/ len(expected)
|
| 297 |
+
if expected else 0.0
|
| 298 |
+
)
|
| 299 |
+
state.finish_epoch(score)
|
| 300 |
+
print(f" exact expansion accuracy={score:.4f}")
|
| 301 |
+
print(f" MWT precision={precision:.4f} recall={recall:.4f}")
|
| 302 |
+
|
| 303 |
+
return model
|
| 304 |
+
|
| 305 |
+
def _predict_expansions(
|
| 306 |
+
self,
|
| 307 |
+
sentences: List[Sentence],
|
| 308 |
+
*,
|
| 309 |
+
show_progress: bool = True,
|
| 310 |
+
) -> List[List[str]]:
|
| 311 |
+
device = self.config.resolve_device()
|
| 312 |
+
results = [
|
| 313 |
+
[token.form for token in sentence.surface_tokens()]
|
| 314 |
+
for sentence in sentences
|
| 315 |
+
]
|
| 316 |
+
candidates = []
|
| 317 |
+
for sentence_index, sentence in enumerate(sentences):
|
| 318 |
+
for token_index, token in enumerate(sentence.surface_tokens()):
|
| 319 |
+
if token.is_mwt:
|
| 320 |
+
candidates.append((sentence_index, token_index, token.form))
|
| 321 |
+
|
| 322 |
+
batch_size = self.config.eval_batch_size
|
| 323 |
+
if batch_size < 1:
|
| 324 |
+
raise ValueError("eval_batch_size must be positive")
|
| 325 |
+
for start in tqdm(
|
| 326 |
+
range(0, len(candidates), batch_size),
|
| 327 |
+
desc="[MWTModel] Predict",
|
| 328 |
+
unit="batch",
|
| 329 |
+
disable=not show_progress or not candidates,
|
| 330 |
+
):
|
| 331 |
+
batch = candidates[start:start + batch_size]
|
| 332 |
+
char_sequences = [
|
| 333 |
+
MWTDataset.encode_chars(form, self.input_vocab)
|
| 334 |
+
for _, _, form in batch
|
| 335 |
+
]
|
| 336 |
+
input_char_ids = pad_sequence(
|
| 337 |
+
char_sequences,
|
| 338 |
+
batch_first=True,
|
| 339 |
+
padding_value=self.input_vocab["<PAD>"],
|
| 340 |
+
).to(device)
|
| 341 |
+
with torch.inference_mode():
|
| 342 |
+
expansions = self(input_char_ids)["strings"]
|
| 343 |
+
for (sentence_index, token_index, _), expansion in zip(batch, expansions):
|
| 344 |
+
results[sentence_index][token_index] = expansion
|
| 345 |
+
return results
|
| 346 |
+
|
| 347 |
+
def _predict_pairs(
|
| 348 |
+
self,
|
| 349 |
+
forms: List[str],
|
| 350 |
+
*,
|
| 351 |
+
show_progress: bool = True,
|
| 352 |
+
) -> List[tuple[str, str]]:
|
| 353 |
+
device = self.config.resolve_device()
|
| 354 |
+
batch_size = self.config.eval_batch_size
|
| 355 |
+
if batch_size < 1:
|
| 356 |
+
raise ValueError("eval_batch_size must be positive")
|
| 357 |
+
predictions = []
|
| 358 |
+
for start in tqdm(
|
| 359 |
+
range(0, len(forms), batch_size),
|
| 360 |
+
desc="[MWTModel] Validate",
|
| 361 |
+
unit="batch",
|
| 362 |
+
disable=not show_progress or not forms,
|
| 363 |
+
):
|
| 364 |
+
chunk = forms[start:start + batch_size]
|
| 365 |
+
inputs = pad_sequence(
|
| 366 |
+
[MWTDataset.encode_chars(form, self.input_vocab) for form in chunk],
|
| 367 |
+
batch_first=True,
|
| 368 |
+
padding_value=self.input_vocab["<PAD>"],
|
| 369 |
+
).to(device)
|
| 370 |
+
with torch.inference_mode():
|
| 371 |
+
expansions = self(inputs)["strings"]
|
| 372 |
+
predictions.extend(zip(chunk, expansions))
|
| 373 |
+
return predictions
|
| 374 |
+
|
| 375 |
+
def predict(
|
| 376 |
+
self,
|
| 377 |
+
sentences: List[Sentence],
|
| 378 |
+
*,
|
| 379 |
+
show_progress: bool = True,
|
| 380 |
+
) -> List[Sentence]:
|
| 381 |
+
self.eval()
|
| 382 |
+
self.to(self.config.resolve_device())
|
| 383 |
+
predicted_by_sentence = self._predict_expansions(
|
| 384 |
+
sentences, show_progress=show_progress
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
results = []
|
| 388 |
+
for sentence_index, sentence in enumerate(sentences):
|
| 389 |
+
if any(token.is_multiword() for token in sentence.tokens):
|
| 390 |
+
results.append(sentence)
|
| 391 |
+
continue
|
| 392 |
+
new_tokens = []
|
| 393 |
+
next_id = 1
|
| 394 |
+
surface_index = 0
|
| 395 |
+
for token in sentence.tokens:
|
| 396 |
+
if token.is_empty():
|
| 397 |
+
new_tokens.append(token)
|
| 398 |
+
continue
|
| 399 |
+
expansion = predicted_by_sentence[sentence_index][surface_index]
|
| 400 |
+
surface_index += 1
|
| 401 |
+
parts = expansion.split()
|
| 402 |
+
if not token.is_mwt or len(parts) < 2:
|
| 403 |
+
new_tokens.append(replace(token, id=next_id, is_mwt=False))
|
| 404 |
+
next_id += 1
|
| 405 |
+
continue
|
| 406 |
+
|
| 407 |
+
end_id = next_id + len(parts) - 1
|
| 408 |
+
new_tokens.append(Token(
|
| 409 |
+
id=f"{next_id}-{end_id}",
|
| 410 |
+
form=token.form,
|
| 411 |
+
misc=token.misc,
|
| 412 |
+
space_after=token.space_after,
|
| 413 |
+
))
|
| 414 |
+
for part_index, part in enumerate(parts):
|
| 415 |
+
new_tokens.append(Token(
|
| 416 |
+
id=next_id + part_index,
|
| 417 |
+
form=part,
|
| 418 |
+
space_after=(
|
| 419 |
+
token.space_after if part_index == len(parts) - 1 else True
|
| 420 |
+
),
|
| 421 |
+
))
|
| 422 |
+
next_id = end_id + 1
|
| 423 |
+
results.append(Sentence(tokens=new_tokens, comments=sentence.comments))
|
| 424 |
+
return results
|
src/models/parser.py
ADDED
|
@@ -0,0 +1,692 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
| 1 |
+
"""Dependency parser: biaffine attention for HEAD + linear head for DEPREL."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from dataclasses import replace
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
from typing import Any, Dict, List, Optional
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch.utils.data import DataLoader
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
from transformers import get_linear_schedule_with_warmup
|
| 14 |
+
|
| 15 |
+
from src.config import BorgConfig
|
| 16 |
+
from src.data.conllu import Sentence, Token
|
| 17 |
+
from src.data.dataset import ParserDataset, _build_vocab
|
| 18 |
+
from src.models.base import BorgBaseModel
|
| 19 |
+
from src.models.inference import sentence_batches
|
| 20 |
+
from src.models.evaluation import (
|
| 21 |
+
average_f1,
|
| 22 |
+
evaluate_predictions,
|
| 23 |
+
print_validation_metrics,
|
| 24 |
+
)
|
| 25 |
+
from src.models.checkpoints import TrainingState
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# ---------------------------------------------------------------------------
|
| 29 |
+
# Biaffine attention
|
| 30 |
+
# ---------------------------------------------------------------------------
|
| 31 |
+
|
| 32 |
+
class BiaffineAttention(nn.Module):
|
| 33 |
+
"""Biaffine scoring: score[b,i,j] = dep[b,i] W head[b,j]."""
|
| 34 |
+
|
| 35 |
+
def __init__(self, in_features: int, out_features: int = 1):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.out_features = out_features
|
| 38 |
+
|
| 39 |
+
# Weight tensor shape: (out_features, in_features+1, in_features+1)
|
| 40 |
+
self.weight = nn.Parameter(
|
| 41 |
+
torch.empty(
|
| 42 |
+
out_features,
|
| 43 |
+
in_features + 1,
|
| 44 |
+
in_features + 1,
|
| 45 |
+
)
|
| 46 |
+
)
|
| 47 |
+
nn.init.xavier_uniform_(self.weight)
|
| 48 |
+
|
| 49 |
+
def forward(
|
| 50 |
+
self,
|
| 51 |
+
h_dep: torch.Tensor,
|
| 52 |
+
h_head: torch.Tensor,
|
| 53 |
+
) -> torch.Tensor:
|
| 54 |
+
"""
|
| 55 |
+
Args:
|
| 56 |
+
h_dep: (B, N, H)
|
| 57 |
+
h_head: (B, N, H)
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
scores: (B, N, N) when out_features==1
|
| 61 |
+
(B, N, N, out_features) when out_features>1
|
| 62 |
+
"""
|
| 63 |
+
batch, seq_len, hidden = h_dep.shape
|
| 64 |
+
|
| 65 |
+
ones = torch.ones(
|
| 66 |
+
batch,
|
| 67 |
+
seq_len,
|
| 68 |
+
1,
|
| 69 |
+
device=h_dep.device,
|
| 70 |
+
dtype=h_dep.dtype,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
h_dep = torch.cat([h_dep, ones], dim=-1)
|
| 74 |
+
h_head = torch.cat([h_head, ones], dim=-1)
|
| 75 |
+
|
| 76 |
+
# einsum: b i h, o h k, b j k -> b i j o
|
| 77 |
+
scores = torch.einsum(
|
| 78 |
+
"bih,ohk,bjk->bijo",
|
| 79 |
+
h_dep,
|
| 80 |
+
self.weight,
|
| 81 |
+
h_head,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
if self.out_features == 1:
|
| 85 |
+
return scores.squeeze(-1)
|
| 86 |
+
|
| 87 |
+
return scores
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
# Greedy arc decoding
|
| 92 |
+
# ---------------------------------------------------------------------------
|
| 93 |
+
|
| 94 |
+
def greedy_decode(
|
| 95 |
+
scores: torch.Tensor,
|
| 96 |
+
word_positions: Dict[int, int],
|
| 97 |
+
) -> Dict[int, int]:
|
| 98 |
+
"""Decode a dependency tree greedily from raw arc scores.
|
| 99 |
+
|
| 100 |
+
Rather than running Chu-Liu-Edmonds, this sorts every candidate
|
| 101 |
+
(dependent, head) arc by score (descending) and walks through them,
|
| 102 |
+
only keeping an arc if the dependent doesn't already have a head and
|
| 103 |
+
adding it wouldn't close a cycle. This is a simple, fast approximation
|
| 104 |
+
of maximum spanning arborescence decoding.
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
scores: (L, L) raw arc scores for the full sub-word sequence, where
|
| 108 |
+
scores[dep, head] is the score of attaching sub-word position
|
| 109 |
+
``dep`` to sub-word position ``head``. Position 0 (the CLS
|
| 110 |
+
token) represents the virtual ROOT node.
|
| 111 |
+
word_positions: mapping of word-id -> first sub-word position.
|
| 112 |
+
|
| 113 |
+
Returns:
|
| 114 |
+
Mapping of word-id -> head position (0 means ROOT).
|
| 115 |
+
"""
|
| 116 |
+
ROOT = 0
|
| 117 |
+
|
| 118 |
+
positions = list(word_positions.values())
|
| 119 |
+
nodes = [ROOT] + positions
|
| 120 |
+
|
| 121 |
+
# Vectorized score extraction.
|
| 122 |
+
positions_t = torch.tensor(
|
| 123 |
+
positions,
|
| 124 |
+
dtype=torch.long,
|
| 125 |
+
device=scores.device,
|
| 126 |
+
)
|
| 127 |
+
nodes_t = torch.tensor(
|
| 128 |
+
nodes,
|
| 129 |
+
dtype=torch.long,
|
| 130 |
+
device=scores.device,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
sub_scores = scores[positions_t][:, nodes_t]
|
| 134 |
+
|
| 135 |
+
self_loop_mask = (
|
| 136 |
+
positions_t.unsqueeze(1)
|
| 137 |
+
== nodes_t.unsqueeze(0)
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
sub_scores = sub_scores.masked_fill(
|
| 141 |
+
self_loop_mask,
|
| 142 |
+
float("-inf"),
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
flat_order = torch.argsort(
|
| 146 |
+
sub_scores.reshape(-1),
|
| 147 |
+
descending=True,
|
| 148 |
+
).tolist()
|
| 149 |
+
|
| 150 |
+
num_heads = len(nodes)
|
| 151 |
+
flat_scores = sub_scores.reshape(-1).tolist()
|
| 152 |
+
flat_self_loop = self_loop_mask.reshape(-1).tolist()
|
| 153 |
+
|
| 154 |
+
candidates = []
|
| 155 |
+
|
| 156 |
+
for idx in flat_order:
|
| 157 |
+
if flat_self_loop[idx]:
|
| 158 |
+
continue
|
| 159 |
+
|
| 160 |
+
dep_i, head_i = divmod(idx, num_heads)
|
| 161 |
+
|
| 162 |
+
candidates.append(
|
| 163 |
+
(
|
| 164 |
+
flat_scores[idx],
|
| 165 |
+
positions[dep_i],
|
| 166 |
+
nodes[head_i],
|
| 167 |
+
)
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# Group by dependent.
|
| 171 |
+
by_dep: Dict[int, list] = {}
|
| 172 |
+
|
| 173 |
+
for score, dep, head in candidates:
|
| 174 |
+
by_dep.setdefault(dep, []).append(
|
| 175 |
+
(score, head)
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
parent = {n: n for n in nodes}
|
| 179 |
+
|
| 180 |
+
def find(x: int) -> int:
|
| 181 |
+
while parent[x] != x:
|
| 182 |
+
parent[x] = parent[parent[x]]
|
| 183 |
+
x = parent[x]
|
| 184 |
+
|
| 185 |
+
return x
|
| 186 |
+
|
| 187 |
+
def union(a: int, b: int) -> None:
|
| 188 |
+
ra, rb = find(a), find(b)
|
| 189 |
+
|
| 190 |
+
if ra != rb:
|
| 191 |
+
parent[ra] = rb
|
| 192 |
+
|
| 193 |
+
root_used = False
|
| 194 |
+
|
| 195 |
+
def is_allowed(
|
| 196 |
+
dep: int,
|
| 197 |
+
head: int,
|
| 198 |
+
relax_root_cap: bool,
|
| 199 |
+
relax_cycle_check: bool,
|
| 200 |
+
) -> bool:
|
| 201 |
+
if (
|
| 202 |
+
not relax_root_cap
|
| 203 |
+
and head == ROOT
|
| 204 |
+
and root_used
|
| 205 |
+
):
|
| 206 |
+
return False
|
| 207 |
+
|
| 208 |
+
if (
|
| 209 |
+
not relax_cycle_check
|
| 210 |
+
and find(dep) == find(head)
|
| 211 |
+
):
|
| 212 |
+
return False
|
| 213 |
+
|
| 214 |
+
return True
|
| 215 |
+
|
| 216 |
+
def pick_head(
|
| 217 |
+
dep: int,
|
| 218 |
+
relax_root_cap: bool,
|
| 219 |
+
relax_cycle_check: bool,
|
| 220 |
+
) -> Optional[int]:
|
| 221 |
+
for _, head in by_dep.get(dep, []):
|
| 222 |
+
if is_allowed(
|
| 223 |
+
dep,
|
| 224 |
+
head,
|
| 225 |
+
relax_root_cap,
|
| 226 |
+
relax_cycle_check,
|
| 227 |
+
):
|
| 228 |
+
return head
|
| 229 |
+
|
| 230 |
+
return None
|
| 231 |
+
|
| 232 |
+
assigned: Dict[int, int] = {}
|
| 233 |
+
|
| 234 |
+
for score, dep, head in candidates:
|
| 235 |
+
if dep in assigned:
|
| 236 |
+
continue
|
| 237 |
+
|
| 238 |
+
if not is_allowed(
|
| 239 |
+
dep,
|
| 240 |
+
head,
|
| 241 |
+
relax_root_cap=False,
|
| 242 |
+
relax_cycle_check=False,
|
| 243 |
+
):
|
| 244 |
+
continue
|
| 245 |
+
|
| 246 |
+
assigned[dep] = head
|
| 247 |
+
union(dep, head)
|
| 248 |
+
|
| 249 |
+
if head == ROOT:
|
| 250 |
+
root_used = True
|
| 251 |
+
|
| 252 |
+
# Fallback for dependents without a head.
|
| 253 |
+
for dep in positions:
|
| 254 |
+
if dep in assigned:
|
| 255 |
+
continue
|
| 256 |
+
|
| 257 |
+
chosen = pick_head(
|
| 258 |
+
dep,
|
| 259 |
+
relax_root_cap=False,
|
| 260 |
+
relax_cycle_check=False,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
if chosen is None:
|
| 264 |
+
chosen = pick_head(
|
| 265 |
+
dep,
|
| 266 |
+
relax_root_cap=True,
|
| 267 |
+
relax_cycle_check=False,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
if chosen is None:
|
| 271 |
+
chosen = pick_head(
|
| 272 |
+
dep,
|
| 273 |
+
relax_root_cap=True,
|
| 274 |
+
relax_cycle_check=True,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
assert chosen is not None, (
|
| 278 |
+
f"pick_head returned None for dependent {dep} even with both "
|
| 279 |
+
"constraints fully relaxed; every dependent should have at "
|
| 280 |
+
"least a ROOT candidate in `by_dep`"
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
assigned[dep] = chosen
|
| 284 |
+
|
| 285 |
+
if find(dep) != find(chosen):
|
| 286 |
+
union(dep, chosen)
|
| 287 |
+
|
| 288 |
+
if chosen == ROOT:
|
| 289 |
+
root_used = True
|
| 290 |
+
|
| 291 |
+
return {
|
| 292 |
+
wid: assigned[pos]
|
| 293 |
+
for wid, pos in word_positions.items()
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# ---------------------------------------------------------------------------
|
| 298 |
+
# Parser model
|
| 299 |
+
# ---------------------------------------------------------------------------
|
| 300 |
+
|
| 301 |
+
class ParserModel(BorgBaseModel):
|
| 302 |
+
"""Biaffine dependency parser."""
|
| 303 |
+
|
| 304 |
+
ARC_HIDDEN = 512
|
| 305 |
+
REL_HIDDEN = 128
|
| 306 |
+
|
| 307 |
+
def __init__(
|
| 308 |
+
self,
|
| 309 |
+
config: BorgConfig,
|
| 310 |
+
deprel_vocab: Optional[Dict[str, int]] = None,
|
| 311 |
+
):
|
| 312 |
+
super().__init__(config, "parser")
|
| 313 |
+
self.deprel_vocab = deprel_vocab or {
|
| 314 |
+
"<PAD>": 0,
|
| 315 |
+
"<UNK>": 1,
|
| 316 |
+
}
|
| 317 |
+
self._build_heads()
|
| 318 |
+
|
| 319 |
+
def _build_heads(self) -> None:
|
| 320 |
+
H = self.hidden_size
|
| 321 |
+
|
| 322 |
+
# Arc MLP
|
| 323 |
+
self.arc_head_mlp = nn.Sequential(
|
| 324 |
+
nn.Linear(H, self.ARC_HIDDEN),
|
| 325 |
+
nn.ELU(),
|
| 326 |
+
)
|
| 327 |
+
self.arc_dep_mlp = nn.Sequential(
|
| 328 |
+
nn.Linear(H, self.ARC_HIDDEN),
|
| 329 |
+
nn.ELU(),
|
| 330 |
+
)
|
| 331 |
+
self.arc_biaffine = BiaffineAttention(
|
| 332 |
+
self.ARC_HIDDEN,
|
| 333 |
+
out_features=1,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# Relation MLP
|
| 337 |
+
self.rel_head_mlp = nn.Sequential(
|
| 338 |
+
nn.Linear(H, self.REL_HIDDEN),
|
| 339 |
+
nn.ELU(),
|
| 340 |
+
)
|
| 341 |
+
self.rel_dep_mlp = nn.Sequential(
|
| 342 |
+
nn.Linear(H, self.REL_HIDDEN),
|
| 343 |
+
nn.ELU(),
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
n_rels = len(self.deprel_vocab)
|
| 347 |
+
|
| 348 |
+
self.rel_biaffine = BiaffineAttention(
|
| 349 |
+
self.REL_HIDDEN,
|
| 350 |
+
out_features=n_rels,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
def forward(
|
| 354 |
+
self,
|
| 355 |
+
input_ids: torch.Tensor,
|
| 356 |
+
attention_mask: torch.Tensor,
|
| 357 |
+
) -> tuple:
|
| 358 |
+
"""Returns (arc_scores, rel_scores)."""
|
| 359 |
+
hidden = self.encode(
|
| 360 |
+
input_ids,
|
| 361 |
+
attention_mask,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
h_arc_head = self.arc_head_mlp(hidden)
|
| 365 |
+
h_arc_dep = self.arc_dep_mlp(hidden)
|
| 366 |
+
|
| 367 |
+
arc_scores = self.arc_biaffine(
|
| 368 |
+
h_arc_dep,
|
| 369 |
+
h_arc_head,
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
h_rel_head = self.rel_head_mlp(hidden)
|
| 373 |
+
h_rel_dep = self.rel_dep_mlp(hidden)
|
| 374 |
+
|
| 375 |
+
rel_scores = self.rel_biaffine(
|
| 376 |
+
h_rel_dep,
|
| 377 |
+
h_rel_head,
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
return arc_scores, rel_scores
|
| 381 |
+
|
| 382 |
+
# ------------------------------------------------------------------
|
| 383 |
+
def _get_extras(self) -> Dict[str, Any]:
|
| 384 |
+
return {
|
| 385 |
+
"deprel_vocab": self.deprel_vocab,
|
| 386 |
+
"arc_head_mlp": self.arc_head_mlp.state_dict(),
|
| 387 |
+
"arc_dep_mlp": self.arc_dep_mlp.state_dict(),
|
| 388 |
+
"arc_biaffine": self.arc_biaffine.state_dict(),
|
| 389 |
+
"rel_head_mlp": self.rel_head_mlp.state_dict(),
|
| 390 |
+
"rel_dep_mlp": self.rel_dep_mlp.state_dict(),
|
| 391 |
+
"rel_biaffine": self.rel_biaffine.state_dict(),
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
def _set_extras(
|
| 395 |
+
self,
|
| 396 |
+
extras: Dict[str, Any],
|
| 397 |
+
) -> None:
|
| 398 |
+
self.deprel_vocab = extras["deprel_vocab"]
|
| 399 |
+
|
| 400 |
+
self._build_heads()
|
| 401 |
+
|
| 402 |
+
self.arc_head_mlp.load_state_dict(
|
| 403 |
+
extras["arc_head_mlp"]
|
| 404 |
+
)
|
| 405 |
+
self.arc_dep_mlp.load_state_dict(
|
| 406 |
+
extras["arc_dep_mlp"]
|
| 407 |
+
)
|
| 408 |
+
self.arc_biaffine.load_state_dict(
|
| 409 |
+
extras["arc_biaffine"]
|
| 410 |
+
)
|
| 411 |
+
self.rel_head_mlp.load_state_dict(
|
| 412 |
+
extras["rel_head_mlp"]
|
| 413 |
+
)
|
| 414 |
+
self.rel_dep_mlp.load_state_dict(
|
| 415 |
+
extras["rel_dep_mlp"]
|
| 416 |
+
)
|
| 417 |
+
self.rel_biaffine.load_state_dict(
|
| 418 |
+
extras["rel_biaffine"]
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
# ------------------------------------------------------------------
|
| 422 |
+
@staticmethod
|
| 423 |
+
def train_model(
|
| 424 |
+
train_sentences: List[Sentence],
|
| 425 |
+
dev_sentences: List[Sentence],
|
| 426 |
+
config: BorgConfig,
|
| 427 |
+
model_path: str,
|
| 428 |
+
*,
|
| 429 |
+
resume: bool = False,
|
| 430 |
+
) -> "ParserModel":
|
| 431 |
+
device = config.resolve_device()
|
| 432 |
+
device_type = torch.device(device).type
|
| 433 |
+
|
| 434 |
+
torch.manual_seed(config.seed)
|
| 435 |
+
|
| 436 |
+
all_deprels = [
|
| 437 |
+
t.deprel
|
| 438 |
+
for s in train_sentences
|
| 439 |
+
for t in s.regular_tokens()
|
| 440 |
+
]
|
| 441 |
+
deprel_vocab = _build_vocab(all_deprels)
|
| 442 |
+
|
| 443 |
+
if resume:
|
| 444 |
+
model = ParserModel.load(os.path.join(model_path, "last"), config).to(device)
|
| 445 |
+
deprel_vocab = model.deprel_vocab
|
| 446 |
+
else:
|
| 447 |
+
model = ParserModel(
|
| 448 |
+
config,
|
| 449 |
+
deprel_vocab,
|
| 450 |
+
).to(device)
|
| 451 |
+
|
| 452 |
+
train_ds = ParserDataset(
|
| 453 |
+
train_sentences,
|
| 454 |
+
config.model_name,
|
| 455 |
+
config.max_seq_length,
|
| 456 |
+
deprel_vocab,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
train_loader = DataLoader(
|
| 460 |
+
train_ds,
|
| 461 |
+
batch_size=config.batch_size,
|
| 462 |
+
shuffle=True,
|
| 463 |
+
collate_fn=train_ds.collate_fn,
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
optimizer = torch.optim.AdamW(
|
| 467 |
+
model.parameters(),
|
| 468 |
+
lr=config.learning_rate,
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
total_steps = (
|
| 472 |
+
len(train_loader)
|
| 473 |
+
* config.num_epochs
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
warmup_steps = int(
|
| 477 |
+
total_steps
|
| 478 |
+
* config.warmup_ratio
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
scheduler = get_linear_schedule_with_warmup(
|
| 482 |
+
optimizer,
|
| 483 |
+
warmup_steps,
|
| 484 |
+
total_steps,
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
arc_loss_fn = nn.CrossEntropyLoss(
|
| 488 |
+
ignore_index=-100
|
| 489 |
+
)
|
| 490 |
+
rel_loss_fn = nn.CrossEntropyLoss(
|
| 491 |
+
ignore_index=-100
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
with TrainingState(
|
| 495 |
+
model, model_path, optimizer, scheduler, train_loader, resume=resume,
|
| 496 |
+
) as state:
|
| 497 |
+
for epoch in range(state.epoch, config.num_epochs):
|
| 498 |
+
model.train()
|
| 499 |
+
progress = state.progress(epoch, "Parser")
|
| 500 |
+
|
| 501 |
+
for batch in progress:
|
| 502 |
+
input_ids = batch["input_ids"].to(device)
|
| 503 |
+
attention_mask = batch[
|
| 504 |
+
"attention_mask"
|
| 505 |
+
].to(device)
|
| 506 |
+
head_labels = batch[
|
| 507 |
+
"head_labels"
|
| 508 |
+
].to(device)
|
| 509 |
+
deprel_labels = batch[
|
| 510 |
+
"deprel_labels"
|
| 511 |
+
].to(device)
|
| 512 |
+
|
| 513 |
+
optimizer.zero_grad(
|
| 514 |
+
set_to_none=True
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
with config.autocast_context(device):
|
| 518 |
+
arc_scores, rel_scores = model(
|
| 519 |
+
input_ids,
|
| 520 |
+
attention_mask,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
batch_size, seq_length, _ = (
|
| 524 |
+
arc_scores.shape
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
arc_loss = arc_loss_fn(
|
| 528 |
+
arc_scores.reshape(
|
| 529 |
+
batch_size * seq_length,
|
| 530 |
+
seq_length,
|
| 531 |
+
),
|
| 532 |
+
head_labels.reshape(
|
| 533 |
+
batch_size * seq_length
|
| 534 |
+
),
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
head_idx = head_labels.clamp(
|
| 538 |
+
min=0
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
head_expand = (
|
| 542 |
+
head_idx
|
| 543 |
+
.unsqueeze(-1)
|
| 544 |
+
.unsqueeze(-1)
|
| 545 |
+
.expand(
|
| 546 |
+
batch_size,
|
| 547 |
+
seq_length,
|
| 548 |
+
1,
|
| 549 |
+
rel_scores.size(-1),
|
| 550 |
+
)
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
rel_at_gold = (
|
| 554 |
+
rel_scores
|
| 555 |
+
.gather(
|
| 556 |
+
2,
|
| 557 |
+
head_expand,
|
| 558 |
+
)
|
| 559 |
+
.squeeze(2)
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
rel_loss = rel_loss_fn(
|
| 563 |
+
rel_at_gold.reshape(
|
| 564 |
+
batch_size * seq_length,
|
| 565 |
+
-1,
|
| 566 |
+
),
|
| 567 |
+
deprel_labels.reshape(
|
| 568 |
+
batch_size * seq_length
|
| 569 |
+
),
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
loss = arc_loss + rel_loss
|
| 573 |
+
|
| 574 |
+
loss.backward()
|
| 575 |
+
|
| 576 |
+
nn.utils.clip_grad_norm_(
|
| 577 |
+
model.parameters(),
|
| 578 |
+
1.0,
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
optimizer.step()
|
| 582 |
+
scheduler.step()
|
| 583 |
+
|
| 584 |
+
loss_value = loss.item()
|
| 585 |
+
state.step(loss_value)
|
| 586 |
+
|
| 587 |
+
progress.set_postfix(
|
| 588 |
+
loss=f"{loss_value:.4f}",
|
| 589 |
+
arc_loss=f"{arc_loss.item():.4f}",
|
| 590 |
+
rel_loss=f"{rel_loss.item():.4f}",
|
| 591 |
+
avg_loss=(
|
| 592 |
+
f"{state.total_loss / state.batch:.4f}"
|
| 593 |
+
),
|
| 594 |
+
lr=(
|
| 595 |
+
f"{scheduler.get_last_lr()[0]:.2e}"
|
| 596 |
+
),
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
avg_loss = state.total_loss / len(train_loader)
|
| 600 |
+
|
| 601 |
+
metrics = evaluate_predictions(
|
| 602 |
+
dev_sentences,
|
| 603 |
+
model.predict(dev_sentences),
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
print(f" loss={avg_loss:.4f}")
|
| 607 |
+
|
| 608 |
+
print_validation_metrics(
|
| 609 |
+
metrics,
|
| 610 |
+
["UAS", "LAS"],
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
score = average_f1(
|
| 614 |
+
metrics,
|
| 615 |
+
["UAS", "LAS"],
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
state.finish_epoch(score)
|
| 619 |
+
|
| 620 |
+
return model
|
| 621 |
+
|
| 622 |
+
# ------------------------------------------------------------------
|
| 623 |
+
def predict(
|
| 624 |
+
self,
|
| 625 |
+
sentences: List[Sentence],
|
| 626 |
+
*,
|
| 627 |
+
show_progress: bool = True,
|
| 628 |
+
) -> List[Sentence]:
|
| 629 |
+
device = self.config.resolve_device()
|
| 630 |
+
device_type = torch.device(device).type
|
| 631 |
+
|
| 632 |
+
self.eval()
|
| 633 |
+
self.to(device)
|
| 634 |
+
|
| 635 |
+
inv_deprel = {
|
| 636 |
+
v: k
|
| 637 |
+
for k, v in self.deprel_vocab.items()
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
results = list(sentences)
|
| 641 |
+
for batch in sentence_batches(self, sentences, show_progress=show_progress):
|
| 642 |
+
with torch.inference_mode(), self.config.autocast_context(device):
|
| 643 |
+
hidden = self.encode(
|
| 644 |
+
batch.input_ids.to(device),
|
| 645 |
+
batch.attention_mask.to(device),
|
| 646 |
+
)
|
| 647 |
+
arc_scores = self.arc_biaffine(
|
| 648 |
+
self.arc_dep_mlp(hidden),
|
| 649 |
+
self.arc_head_mlp(hidden),
|
| 650 |
+
)
|
| 651 |
+
rel_dep = self.rel_dep_mlp(hidden)
|
| 652 |
+
rel_head = self.rel_head_mlp(hidden)
|
| 653 |
+
|
| 654 |
+
for row, index in enumerate(batch.indices):
|
| 655 |
+
word_positions = batch.word_positions[row]
|
| 656 |
+
inv_positions = {pos: wid for wid, pos in word_positions.items()}
|
| 657 |
+
head_positions = greedy_decode(arc_scores[row], word_positions)
|
| 658 |
+
word_heads = {
|
| 659 |
+
wid: 0 if head == 0 else inv_positions[head] + 1
|
| 660 |
+
for wid, head in head_positions.items()
|
| 661 |
+
}
|
| 662 |
+
word_deprels: Dict[int, str] = {}
|
| 663 |
+
if word_positions:
|
| 664 |
+
dep_positions = list(word_positions.values())
|
| 665 |
+
heads = [head_positions[wid] for wid in word_positions]
|
| 666 |
+
# Treat selected arcs as length-one sequences, not an N x N grid.
|
| 667 |
+
rel_scores = self.rel_biaffine(
|
| 668 |
+
rel_dep[row, dep_positions].unsqueeze(1),
|
| 669 |
+
rel_head[row, heads].unsqueeze(1),
|
| 670 |
+
)
|
| 671 |
+
rel_ids = rel_scores[:, 0, 0].argmax(-1).cpu().tolist()
|
| 672 |
+
word_deprels = {
|
| 673 |
+
wid: inv_deprel.get(rel_id, "_")
|
| 674 |
+
for wid, rel_id in zip(word_positions, rel_ids)
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
sent = sentences[index]
|
| 678 |
+
new_sent = Sentence(comments=sent.comments)
|
| 679 |
+
for tok in sent.tokens:
|
| 680 |
+
if tok.is_multiword() or tok.is_empty():
|
| 681 |
+
new_sent.tokens.append(tok)
|
| 682 |
+
continue
|
| 683 |
+
new_sent.tokens.append(
|
| 684 |
+
replace(
|
| 685 |
+
tok,
|
| 686 |
+
head=word_heads.get(tok.id - 1, 0),
|
| 687 |
+
deprel=word_deprels.get(tok.id - 1, "_"),
|
| 688 |
+
)
|
| 689 |
+
)
|
| 690 |
+
results[index] = new_sent
|
| 691 |
+
|
| 692 |
+
return results
|
src/models/tagger.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tagger model: UPOS / XPOS / FEATS classification."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
from dataclasses import replace
|
| 6 |
+
from typing import Any, Dict, List, Optional
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.utils.data import DataLoader
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from transformers import get_linear_schedule_with_warmup
|
| 13 |
+
|
| 14 |
+
from src.config import BorgConfig
|
| 15 |
+
from src.data.conllu import Sentence, Token
|
| 16 |
+
from src.data.dataset import TaggerDataset, _build_vocab, _feats_to_str
|
| 17 |
+
from src.models.base import BorgBaseModel
|
| 18 |
+
from src.models.inference import sentence_batches
|
| 19 |
+
from src.models.evaluation import (
|
| 20 |
+
average_f1,
|
| 21 |
+
evaluate_predictions,
|
| 22 |
+
print_validation_metrics,
|
| 23 |
+
)
|
| 24 |
+
from src.models.checkpoints import TrainingState
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TaggerModel(BorgBaseModel):
|
| 28 |
+
"""Multi-head sequence labeller for UPOS, XPOS, and FEATS."""
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
config: BorgConfig,
|
| 33 |
+
upos_vocab: Optional[Dict[str, int]] = None,
|
| 34 |
+
xpos_vocab: Optional[Dict[str, int]] = None,
|
| 35 |
+
feats_vocab: Optional[Dict[str, int]] = None,
|
| 36 |
+
):
|
| 37 |
+
super().__init__(config, "tagger")
|
| 38 |
+
self.upos_vocab = upos_vocab or {"<PAD>": 0, "<UNK>": 1}
|
| 39 |
+
self.xpos_vocab = xpos_vocab or {"<PAD>": 0, "<UNK>": 1}
|
| 40 |
+
self.feats_vocab = feats_vocab or {"<PAD>": 0, "<UNK>": 1}
|
| 41 |
+
self._build_heads()
|
| 42 |
+
|
| 43 |
+
def _build_heads(self) -> None:
|
| 44 |
+
self.upos_head = nn.Linear(
|
| 45 |
+
self.hidden_size,
|
| 46 |
+
len(self.upos_vocab),
|
| 47 |
+
)
|
| 48 |
+
self.xpos_head = nn.Linear(
|
| 49 |
+
self.hidden_size,
|
| 50 |
+
len(self.xpos_vocab),
|
| 51 |
+
)
|
| 52 |
+
self.feats_head = nn.Linear(
|
| 53 |
+
self.hidden_size,
|
| 54 |
+
len(self.feats_vocab),
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
def forward(
|
| 58 |
+
self,
|
| 59 |
+
input_ids: torch.Tensor,
|
| 60 |
+
attention_mask: torch.Tensor,
|
| 61 |
+
) -> tuple:
|
| 62 |
+
hidden = self.encode(input_ids, attention_mask) # (B, L, H)
|
| 63 |
+
|
| 64 |
+
return (
|
| 65 |
+
self.upos_head(hidden),
|
| 66 |
+
self.xpos_head(hidden),
|
| 67 |
+
self.feats_head(hidden),
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# ------------------------------------------------------------------
|
| 71 |
+
def _get_extras(self) -> Dict[str, Any]:
|
| 72 |
+
return {
|
| 73 |
+
"upos_vocab": self.upos_vocab,
|
| 74 |
+
"xpos_vocab": self.xpos_vocab,
|
| 75 |
+
"feats_vocab": self.feats_vocab,
|
| 76 |
+
"upos_head": self.upos_head.state_dict(),
|
| 77 |
+
"xpos_head": self.xpos_head.state_dict(),
|
| 78 |
+
"feats_head": self.feats_head.state_dict(),
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
def _set_extras(self, extras: Dict[str, Any]) -> None:
|
| 82 |
+
self.upos_vocab = extras["upos_vocab"]
|
| 83 |
+
self.xpos_vocab = extras["xpos_vocab"]
|
| 84 |
+
self.feats_vocab = extras["feats_vocab"]
|
| 85 |
+
|
| 86 |
+
self._build_heads()
|
| 87 |
+
|
| 88 |
+
self.upos_head.load_state_dict(extras["upos_head"])
|
| 89 |
+
self.xpos_head.load_state_dict(extras["xpos_head"])
|
| 90 |
+
self.feats_head.load_state_dict(extras["feats_head"])
|
| 91 |
+
|
| 92 |
+
# ------------------------------------------------------------------
|
| 93 |
+
@staticmethod
|
| 94 |
+
def train_model(
|
| 95 |
+
train_sentences: List[Sentence],
|
| 96 |
+
dev_sentences: List[Sentence],
|
| 97 |
+
config: BorgConfig,
|
| 98 |
+
model_path: str,
|
| 99 |
+
*,
|
| 100 |
+
resume: bool = False,
|
| 101 |
+
) -> "TaggerModel":
|
| 102 |
+
device = config.resolve_device()
|
| 103 |
+
device_type = torch.device(device).type
|
| 104 |
+
|
| 105 |
+
torch.manual_seed(config.seed)
|
| 106 |
+
|
| 107 |
+
# Build vocabularies from training data.
|
| 108 |
+
all_upos = [
|
| 109 |
+
t.upos
|
| 110 |
+
for s in train_sentences
|
| 111 |
+
for t in s.regular_tokens()
|
| 112 |
+
]
|
| 113 |
+
all_xpos = [
|
| 114 |
+
t.xpos
|
| 115 |
+
for s in train_sentences
|
| 116 |
+
for t in s.regular_tokens()
|
| 117 |
+
]
|
| 118 |
+
all_feats = [
|
| 119 |
+
_feats_to_str(t)
|
| 120 |
+
for s in train_sentences
|
| 121 |
+
for t in s.regular_tokens()
|
| 122 |
+
]
|
| 123 |
+
|
| 124 |
+
upos_vocab = _build_vocab(all_upos)
|
| 125 |
+
xpos_vocab = _build_vocab(all_xpos)
|
| 126 |
+
feats_vocab = _build_vocab(all_feats)
|
| 127 |
+
|
| 128 |
+
if resume:
|
| 129 |
+
model = TaggerModel.load(os.path.join(model_path, "last"), config).to(device)
|
| 130 |
+
upos_vocab = model.upos_vocab
|
| 131 |
+
xpos_vocab = model.xpos_vocab
|
| 132 |
+
feats_vocab = model.feats_vocab
|
| 133 |
+
else:
|
| 134 |
+
model = TaggerModel(
|
| 135 |
+
config,
|
| 136 |
+
upos_vocab,
|
| 137 |
+
xpos_vocab,
|
| 138 |
+
feats_vocab,
|
| 139 |
+
).to(device)
|
| 140 |
+
|
| 141 |
+
train_ds = TaggerDataset(
|
| 142 |
+
train_sentences,
|
| 143 |
+
config.model_name,
|
| 144 |
+
config.max_seq_length,
|
| 145 |
+
upos_vocab,
|
| 146 |
+
xpos_vocab,
|
| 147 |
+
feats_vocab,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
train_loader = DataLoader(
|
| 151 |
+
train_ds,
|
| 152 |
+
batch_size=config.batch_size,
|
| 153 |
+
shuffle=True,
|
| 154 |
+
collate_fn=train_ds.collate_fn,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
optimizer = torch.optim.AdamW(
|
| 158 |
+
model.parameters(),
|
| 159 |
+
lr=config.learning_rate,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
total_steps = len(train_loader) * config.num_epochs
|
| 163 |
+
warmup_steps = int(total_steps * config.warmup_ratio)
|
| 164 |
+
|
| 165 |
+
scheduler = get_linear_schedule_with_warmup(
|
| 166 |
+
optimizer,
|
| 167 |
+
warmup_steps,
|
| 168 |
+
total_steps,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
loss_fn = nn.CrossEntropyLoss(ignore_index=-100)
|
| 172 |
+
|
| 173 |
+
with TrainingState(
|
| 174 |
+
model, model_path, optimizer, scheduler, train_loader, resume=resume,
|
| 175 |
+
) as state:
|
| 176 |
+
for epoch in range(state.epoch, config.num_epochs):
|
| 177 |
+
model.train()
|
| 178 |
+
progress = state.progress(epoch, "Tagger")
|
| 179 |
+
|
| 180 |
+
for batch in progress:
|
| 181 |
+
input_ids = batch["input_ids"].to(device)
|
| 182 |
+
attention_mask = batch["attention_mask"].to(device)
|
| 183 |
+
upos_lbl = batch["upos_labels"].to(device)
|
| 184 |
+
xpos_lbl = batch["xpos_labels"].to(device)
|
| 185 |
+
feats_lbl = batch["feats_labels"].to(device)
|
| 186 |
+
|
| 187 |
+
optimizer.zero_grad()
|
| 188 |
+
|
| 189 |
+
with config.autocast_context(device):
|
| 190 |
+
u_logits, x_logits, f_logits = model(
|
| 191 |
+
input_ids,
|
| 192 |
+
attention_mask,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
upos_loss = loss_fn(
|
| 196 |
+
u_logits.view(-1, len(upos_vocab)),
|
| 197 |
+
upos_lbl.view(-1),
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
xpos_loss = loss_fn(
|
| 201 |
+
x_logits.view(-1, len(xpos_vocab)),
|
| 202 |
+
xpos_lbl.view(-1),
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
feats_loss = loss_fn(
|
| 206 |
+
f_logits.view(-1, len(feats_vocab)),
|
| 207 |
+
feats_lbl.view(-1),
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
loss = (
|
| 211 |
+
upos_loss
|
| 212 |
+
+ xpos_loss
|
| 213 |
+
+ feats_loss
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
loss.backward()
|
| 217 |
+
|
| 218 |
+
nn.utils.clip_grad_norm_(
|
| 219 |
+
model.parameters(),
|
| 220 |
+
1.0,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
optimizer.step()
|
| 224 |
+
scheduler.step()
|
| 225 |
+
|
| 226 |
+
state.step(loss.item())
|
| 227 |
+
|
| 228 |
+
progress.set_postfix(
|
| 229 |
+
loss=f"{loss.item():.4f}",
|
| 230 |
+
upos_loss=f"{upos_loss.item():.4f}",
|
| 231 |
+
xpos_loss=f"{xpos_loss.item():.4f}",
|
| 232 |
+
feats_loss=f"{feats_loss.item():.4f}",
|
| 233 |
+
avg_loss=f"{state.total_loss / state.batch:.4f}",
|
| 234 |
+
lr=f"{scheduler.get_last_lr()[0]:.2e}",
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
avg_loss = state.total_loss / len(train_loader)
|
| 238 |
+
|
| 239 |
+
metrics = evaluate_predictions(
|
| 240 |
+
dev_sentences,
|
| 241 |
+
model.predict(dev_sentences),
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
print(f" loss={avg_loss:.4f}")
|
| 245 |
+
|
| 246 |
+
print_validation_metrics(
|
| 247 |
+
metrics,
|
| 248 |
+
["UPOS", "XPOS", "FEATS"],
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
score = average_f1(
|
| 252 |
+
metrics,
|
| 253 |
+
["UPOS", "XPOS", "FEATS"],
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
state.finish_epoch(score)
|
| 257 |
+
|
| 258 |
+
return model
|
| 259 |
+
|
| 260 |
+
# ------------------------------------------------------------------
|
| 261 |
+
def predict(
|
| 262 |
+
self,
|
| 263 |
+
sentences: List[Sentence],
|
| 264 |
+
*,
|
| 265 |
+
show_progress: bool = True,
|
| 266 |
+
) -> List[Sentence]:
|
| 267 |
+
device = self.config.resolve_device()
|
| 268 |
+
device_type = torch.device(device).type
|
| 269 |
+
|
| 270 |
+
self.eval()
|
| 271 |
+
self.to(device)
|
| 272 |
+
|
| 273 |
+
inv_upos = {
|
| 274 |
+
v: k for k, v in self.upos_vocab.items()
|
| 275 |
+
}
|
| 276 |
+
inv_xpos = {
|
| 277 |
+
v: k for k, v in self.xpos_vocab.items()
|
| 278 |
+
}
|
| 279 |
+
inv_feats = {
|
| 280 |
+
v: k for k, v in self.feats_vocab.items()
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
results = list(sentences)
|
| 284 |
+
for batch in sentence_batches(self, sentences, show_progress=show_progress):
|
| 285 |
+
with torch.inference_mode(), self.config.autocast_context(device):
|
| 286 |
+
u_logits, x_logits, f_logits = self(
|
| 287 |
+
batch.input_ids.to(device),
|
| 288 |
+
batch.attention_mask.to(device),
|
| 289 |
+
)
|
| 290 |
+
predictions = torch.stack(
|
| 291 |
+
[u_logits.argmax(-1), x_logits.argmax(-1), f_logits.argmax(-1)],
|
| 292 |
+
dim=-1,
|
| 293 |
+
).cpu().tolist()
|
| 294 |
+
|
| 295 |
+
for row, index in enumerate(batch.indices):
|
| 296 |
+
sent = sentences[index]
|
| 297 |
+
word_tags = {
|
| 298 |
+
wid: (
|
| 299 |
+
inv_upos.get(predictions[row][pos][0], "_"),
|
| 300 |
+
inv_xpos.get(predictions[row][pos][1], "_"),
|
| 301 |
+
inv_feats.get(predictions[row][pos][2], "_"),
|
| 302 |
+
)
|
| 303 |
+
for wid, pos in batch.word_positions[row].items()
|
| 304 |
+
}
|
| 305 |
+
new_sent = Sentence(comments=sent.comments)
|
| 306 |
+
for tok in sent.tokens:
|
| 307 |
+
if tok.is_multiword() or tok.is_empty():
|
| 308 |
+
new_sent.tokens.append(tok)
|
| 309 |
+
continue
|
| 310 |
+
upos, xpos, feats = word_tags.get(tok.id - 1, ("_", "_", "_"))
|
| 311 |
+
new_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tokenizer model: sentence and token boundary detection."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from typing import Any, Dict, List
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch.utils.data import DataLoader
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
from transformers import get_linear_schedule_with_warmup
|
| 14 |
+
|
| 15 |
+
from src.config import BorgConfig
|
| 16 |
+
from src.data.conllu import Sentence, Token
|
| 17 |
+
from src.data.dataset import TokenizerDataset
|
| 18 |
+
from eval.conll18_ud_eval import EvalResult
|
| 19 |
+
from src.models.base import BorgBaseModel
|
| 20 |
+
from src.models.checkpoints import TrainingState
|
| 21 |
+
from src.models.evaluation import (
|
| 22 |
+
average_f1,
|
| 23 |
+
evaluate_predictions,
|
| 24 |
+
print_validation_metrics,
|
| 25 |
+
tokenizer_validation_text,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
_LABELS = {0: "C", 1: "T", 2: "S"} # Continuation / Token-start / Sentence-start
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _mwt_surface_metrics(
|
| 33 |
+
gold_sentences: List[Sentence],
|
| 34 |
+
predicted_sentences: List[Sentence],
|
| 35 |
+
text: str,
|
| 36 |
+
) -> EvalResult:
|
| 37 |
+
def positive_spans(sentences: List[Sentence], *, gold: bool) -> set[tuple[int, int]]:
|
| 38 |
+
spans = set()
|
| 39 |
+
cursor = 0
|
| 40 |
+
for sentence in sentences:
|
| 41 |
+
for token in sentence.surface_tokens():
|
| 42 |
+
start = text.find(token.form, cursor)
|
| 43 |
+
if start < 0:
|
| 44 |
+
continue
|
| 45 |
+
end = start + len(token.form)
|
| 46 |
+
is_mwt = token.is_multiword() if gold else token.is_mwt
|
| 47 |
+
if is_mwt:
|
| 48 |
+
spans.add((start, end))
|
| 49 |
+
cursor = end
|
| 50 |
+
while cursor < len(text) and text[cursor].isspace():
|
| 51 |
+
cursor += 1
|
| 52 |
+
return spans
|
| 53 |
+
|
| 54 |
+
gold_spans = positive_spans(gold_sentences, gold=True)
|
| 55 |
+
predicted_spans = positive_spans(predicted_sentences, gold=False)
|
| 56 |
+
true_positives = len(gold_spans & predicted_spans)
|
| 57 |
+
false_positives = len(predicted_spans - gold_spans)
|
| 58 |
+
false_negatives = len(gold_spans - predicted_spans)
|
| 59 |
+
precision = (
|
| 60 |
+
true_positives / (true_positives + false_positives)
|
| 61 |
+
if true_positives + false_positives else 0.0
|
| 62 |
+
)
|
| 63 |
+
recall = (
|
| 64 |
+
true_positives / (true_positives + false_negatives)
|
| 65 |
+
if true_positives + false_negatives else 0.0
|
| 66 |
+
)
|
| 67 |
+
f_score = (
|
| 68 |
+
2 * precision * recall / (precision + recall)
|
| 69 |
+
if precision + recall else 0.0
|
| 70 |
+
)
|
| 71 |
+
return EvalResult(
|
| 72 |
+
precision=precision,
|
| 73 |
+
recall=recall,
|
| 74 |
+
f1=f_score,
|
| 75 |
+
aligned_count=true_positives,
|
| 76 |
+
gold_count=len(gold_spans),
|
| 77 |
+
system_count=len(predicted_spans),
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class TokenizerModel(BorgBaseModel):
|
| 82 |
+
"""Predicts sentence/token boundaries at sub-word level."""
|
| 83 |
+
|
| 84 |
+
NUM_LABELS = 3 # CONTINUATION, TOKEN_START, SENTENCE_START
|
| 85 |
+
|
| 86 |
+
def __init__(self, config: BorgConfig):
|
| 87 |
+
super().__init__(config, "tokenizer")
|
| 88 |
+
self.classifier = nn.Linear(self.hidden_size, self.NUM_LABELS)
|
| 89 |
+
self.mwt_classifier = nn.Linear(self.hidden_size, 2)
|
| 90 |
+
|
| 91 |
+
def forward(
|
| 92 |
+
self,
|
| 93 |
+
input_ids: torch.Tensor,
|
| 94 |
+
attention_mask: torch.Tensor,
|
| 95 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 96 |
+
hidden = self.encode(input_ids, attention_mask) # (B, L, H)
|
| 97 |
+
return self.classifier(hidden), self.mwt_classifier(hidden)
|
| 98 |
+
|
| 99 |
+
# ------------------------------------------------------------------
|
| 100 |
+
def _get_extras(self) -> Dict[str, Any]:
|
| 101 |
+
return {
|
| 102 |
+
"classifier": self.classifier.state_dict(),
|
| 103 |
+
"mwt_classifier": self.mwt_classifier.state_dict(),
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
def _set_extras(self, extras: Dict[str, Any]) -> None:
|
| 107 |
+
# `BorgBaseModel.load` reconstructs instances via `BorgBaseModel.__init__`
|
| 108 |
+
# rather than `TokenizerModel.__init__`, so `self.classifier` may not
|
| 109 |
+
# exist yet. Rebuild it before loading the saved weights.
|
| 110 |
+
self.classifier = nn.Linear(self.hidden_size, self.NUM_LABELS)
|
| 111 |
+
self.classifier.load_state_dict(extras["classifier"])
|
| 112 |
+
self.mwt_classifier = nn.Linear(self.hidden_size, 2)
|
| 113 |
+
if "mwt_classifier" in extras:
|
| 114 |
+
self.mwt_classifier.load_state_dict(extras["mwt_classifier"])
|
| 115 |
+
else:
|
| 116 |
+
nn.init.zeros_(self.mwt_classifier.weight)
|
| 117 |
+
nn.init.zeros_(self.mwt_classifier.bias)
|
| 118 |
+
|
| 119 |
+
# ------------------------------------------------------------------
|
| 120 |
+
@staticmethod
|
| 121 |
+
def train_model(
|
| 122 |
+
train_sentences: List[Sentence],
|
| 123 |
+
dev_sentences: List[Sentence],
|
| 124 |
+
config: BorgConfig,
|
| 125 |
+
model_path: str,
|
| 126 |
+
*,
|
| 127 |
+
resume: bool = False,
|
| 128 |
+
) -> "TokenizerModel":
|
| 129 |
+
device = config.resolve_device()
|
| 130 |
+
device_type = torch.device(device).type
|
| 131 |
+
|
| 132 |
+
torch.manual_seed(config.seed)
|
| 133 |
+
|
| 134 |
+
if resume:
|
| 135 |
+
model = TokenizerModel.load(os.path.join(model_path, "last"), config).to(device)
|
| 136 |
+
else:
|
| 137 |
+
model = TokenizerModel(config).to(device)
|
| 138 |
+
|
| 139 |
+
train_ds = TokenizerDataset(
|
| 140 |
+
train_sentences,
|
| 141 |
+
config.model_name,
|
| 142 |
+
config.max_seq_length,
|
| 143 |
+
show_progress=True,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
train_loader = DataLoader(
|
| 147 |
+
train_ds,
|
| 148 |
+
batch_size=config.batch_size,
|
| 149 |
+
shuffle=True,
|
| 150 |
+
collate_fn=train_ds.collate_fn,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
optimizer = torch.optim.AdamW(
|
| 154 |
+
model.parameters(),
|
| 155 |
+
lr=config.learning_rate,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
total_steps = len(train_loader) * config.num_epochs
|
| 159 |
+
warmup_steps = int(total_steps * config.warmup_ratio)
|
| 160 |
+
|
| 161 |
+
scheduler = get_linear_schedule_with_warmup(
|
| 162 |
+
optimizer,
|
| 163 |
+
warmup_steps,
|
| 164 |
+
total_steps,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
loss_fn = nn.CrossEntropyLoss(ignore_index=-100)
|
| 168 |
+
|
| 169 |
+
with TrainingState(
|
| 170 |
+
model, model_path, optimizer, scheduler, train_loader, resume=resume,
|
| 171 |
+
) as state:
|
| 172 |
+
for epoch in range(state.epoch, config.num_epochs):
|
| 173 |
+
model.train()
|
| 174 |
+
progress = state.progress(epoch, "Tokenizer")
|
| 175 |
+
|
| 176 |
+
for batch in progress:
|
| 177 |
+
input_ids = batch["input_ids"].to(device)
|
| 178 |
+
attention_mask = batch["attention_mask"].to(device)
|
| 179 |
+
labels = batch["labels"].to(device)
|
| 180 |
+
mwt_labels = batch["mwt_labels"].to(device)
|
| 181 |
+
|
| 182 |
+
optimizer.zero_grad()
|
| 183 |
+
|
| 184 |
+
with config.autocast_context(device):
|
| 185 |
+
boundary_logits, mwt_logits = model(
|
| 186 |
+
input_ids,
|
| 187 |
+
attention_mask,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
loss = loss_fn(
|
| 191 |
+
boundary_logits.view(-1, TokenizerModel.NUM_LABELS),
|
| 192 |
+
labels.view(-1),
|
| 193 |
+
) + loss_fn(
|
| 194 |
+
mwt_logits.view(-1, 2),
|
| 195 |
+
mwt_labels.view(-1),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
loss.backward()
|
| 199 |
+
|
| 200 |
+
nn.utils.clip_grad_norm_(
|
| 201 |
+
model.parameters(),
|
| 202 |
+
1.0,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
optimizer.step()
|
| 206 |
+
scheduler.step()
|
| 207 |
+
|
| 208 |
+
state.step(loss.item())
|
| 209 |
+
|
| 210 |
+
progress.set_postfix(
|
| 211 |
+
loss=f"{loss.item():.4f}",
|
| 212 |
+
avg_loss=f"{state.total_loss / state.batch:.4f}",
|
| 213 |
+
lr=f"{scheduler.get_last_lr()[0]:.2e}",
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
avg_loss = state.total_loss / len(train_loader)
|
| 217 |
+
|
| 218 |
+
validation_text = tokenizer_validation_text(dev_sentences)
|
| 219 |
+
predicted_sentences = model.predict(validation_text)
|
| 220 |
+
|
| 221 |
+
metrics = evaluate_predictions(
|
| 222 |
+
dev_sentences,
|
| 223 |
+
predicted_sentences,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
print(f" loss={avg_loss:.4f}")
|
| 227 |
+
|
| 228 |
+
metrics["MWT"] = _mwt_surface_metrics(
|
| 229 |
+
dev_sentences,
|
| 230 |
+
predicted_sentences,
|
| 231 |
+
validation_text,
|
| 232 |
+
)
|
| 233 |
+
print_validation_metrics(
|
| 234 |
+
metrics,
|
| 235 |
+
["Tokens", "Sentences", "MWT"],
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
score = average_f1(
|
| 239 |
+
metrics,
|
| 240 |
+
["Tokens", "Sentences"],
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
state.finish_epoch(score)
|
| 244 |
+
|
| 245 |
+
return model
|
| 246 |
+
|
| 247 |
+
# ------------------------------------------------------------------
|
| 248 |
+
def predict(self, text: str, *, show_progress: bool = True) -> List[Sentence]:
|
| 249 |
+
"""Segment *text* into sentences and tokens, preserving whitespace."""
|
| 250 |
+
device = self.config.resolve_device()
|
| 251 |
+
device_type = torch.device(device).type
|
| 252 |
+
|
| 253 |
+
self.eval()
|
| 254 |
+
self.to(device)
|
| 255 |
+
|
| 256 |
+
hf_tok = self.hf_tokenizer
|
| 257 |
+
|
| 258 |
+
encoding = hf_tok(
|
| 259 |
+
text,
|
| 260 |
+
return_offsets_mapping=True,
|
| 261 |
+
add_special_tokens=False,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
token_ids = encoding["input_ids"]
|
| 265 |
+
offset_mapping = encoding["offset_mapping"]
|
| 266 |
+
|
| 267 |
+
max_seq_length = min(
|
| 268 |
+
self.config.max_seq_length,
|
| 269 |
+
self.encoder.config.max_position_embeddings,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
special_tokens = hf_tok.num_special_tokens_to_add(pair=False)
|
| 273 |
+
window_size = max_seq_length - special_tokens
|
| 274 |
+
|
| 275 |
+
if window_size < 1:
|
| 276 |
+
raise ValueError(
|
| 277 |
+
"max_seq_length must leave room for at least one token"
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
overlap = min(window_size // 4, window_size - 1)
|
| 281 |
+
window_step = window_size - overlap
|
| 282 |
+
|
| 283 |
+
score_sums = torch.zeros(
|
| 284 |
+
(len(token_ids), self.NUM_LABELS)
|
| 285 |
+
)
|
| 286 |
+
mwt_score_sums = torch.zeros((len(token_ids), 2))
|
| 287 |
+
score_counts = torch.zeros(len(token_ids))
|
| 288 |
+
batch_size = self.config.eval_batch_size
|
| 289 |
+
if batch_size < 1:
|
| 290 |
+
raise ValueError("eval_batch_size must be positive")
|
| 291 |
+
if device_type == "mps":
|
| 292 |
+
batch_size = 1
|
| 293 |
+
window_starts = range(0, len(token_ids), window_step)
|
| 294 |
+
|
| 295 |
+
with torch.inference_mode():
|
| 296 |
+
for batch_start in tqdm(
|
| 297 |
+
range(0, len(window_starts), batch_size),
|
| 298 |
+
desc="[TokenizerModel] Predict",
|
| 299 |
+
unit="batch",
|
| 300 |
+
disable=not show_progress or not token_ids,
|
| 301 |
+
):
|
| 302 |
+
starts = window_starts[batch_start:batch_start + batch_size]
|
| 303 |
+
windows = [
|
| 304 |
+
token_ids[start:start + window_size]
|
| 305 |
+
for start in starts
|
| 306 |
+
]
|
| 307 |
+
model_inputs = [
|
| 308 |
+
hf_tok.prepare_for_model(
|
| 309 |
+
window,
|
| 310 |
+
add_special_tokens=True,
|
| 311 |
+
return_attention_mask=True,
|
| 312 |
+
)
|
| 313 |
+
for window in windows
|
| 314 |
+
]
|
| 315 |
+
input_ids = pad_sequence(
|
| 316 |
+
[torch.tensor(item["input_ids"], dtype=torch.long) for item in model_inputs],
|
| 317 |
+
batch_first=True,
|
| 318 |
+
padding_value=hf_tok.pad_token_id,
|
| 319 |
+
).to(device)
|
| 320 |
+
attention_mask = pad_sequence(
|
| 321 |
+
[torch.tensor(item["attention_mask"], dtype=torch.long) for item in model_inputs],
|
| 322 |
+
batch_first=True,
|
| 323 |
+
padding_value=0,
|
| 324 |
+
).to(device)
|
| 325 |
+
with self.config.autocast_context(device):
|
| 326 |
+
model_outputs = self(
|
| 327 |
+
input_ids,
|
| 328 |
+
attention_mask,
|
| 329 |
+
)
|
| 330 |
+
boundary_logits, mwt_logits = model_outputs
|
| 331 |
+
boundary_logits = boundary_logits.float().cpu()
|
| 332 |
+
mwt_logits = mwt_logits.float().cpu()
|
| 333 |
+
|
| 334 |
+
for row, (start, window) in enumerate(zip(starts, windows)):
|
| 335 |
+
try:
|
| 336 |
+
special_mask = hf_tok.get_special_tokens_mask(
|
| 337 |
+
window,
|
| 338 |
+
already_has_special_tokens=False,
|
| 339 |
+
)
|
| 340 |
+
except AssertionError:
|
| 341 |
+
special_mask = hf_tok.get_special_tokens_mask(
|
| 342 |
+
model_inputs[row]["input_ids"],
|
| 343 |
+
already_has_special_tokens=True,
|
| 344 |
+
)
|
| 345 |
+
content_positions = [
|
| 346 |
+
index for index, is_special in enumerate(special_mask)
|
| 347 |
+
if not is_special
|
| 348 |
+
]
|
| 349 |
+
score_sums[start:start + len(window)] += boundary_logits[row, content_positions]
|
| 350 |
+
mwt_score_sums[start:start + len(window)] += mwt_logits[row, content_positions]
|
| 351 |
+
score_counts[start:start + len(window)] += 1
|
| 352 |
+
|
| 353 |
+
scores = score_sums / score_counts.unsqueeze(1)
|
| 354 |
+
mwt_scores = mwt_score_sums / score_counts.unsqueeze(1)
|
| 355 |
+
character_positions = []
|
| 356 |
+
subword_indices = []
|
| 357 |
+
for index, (start, end) in enumerate(offset_mapping):
|
| 358 |
+
while start < end and text[start].isspace():
|
| 359 |
+
start += 1
|
| 360 |
+
if start < end:
|
| 361 |
+
character_positions.append(start)
|
| 362 |
+
subword_indices.append(index)
|
| 363 |
+
|
| 364 |
+
positions, inverse = torch.unique(
|
| 365 |
+
torch.tensor(character_positions, dtype=torch.long),
|
| 366 |
+
sorted=True,
|
| 367 |
+
return_inverse=True,
|
| 368 |
+
)
|
| 369 |
+
character_scores = scores.new_zeros((len(positions), self.NUM_LABELS))
|
| 370 |
+
character_scores.index_add_(0, inverse, scores[subword_indices])
|
| 371 |
+
labels = character_scores.argmax(-1).tolist()
|
| 372 |
+
character_mwt_scores = mwt_scores.new_zeros((len(positions), 2))
|
| 373 |
+
character_mwt_scores.index_add_(0, inverse, mwt_scores[subword_indices])
|
| 374 |
+
mwt_labels = character_mwt_scores.argmax(-1).tolist()
|
| 375 |
+
|
| 376 |
+
first_character = next(
|
| 377 |
+
(index for index, char in enumerate(text) if not char.isspace()),
|
| 378 |
+
None,
|
| 379 |
+
)
|
| 380 |
+
if first_character is None:
|
| 381 |
+
return []
|
| 382 |
+
|
| 383 |
+
first_mwt_label = mwt_labels[0] if mwt_labels else 0
|
| 384 |
+
boundaries = [(first_character, TokenizerDataset.SENTENCE_START, first_mwt_label)]
|
| 385 |
+
boundaries.extend(
|
| 386 |
+
(position, label, mwt_label)
|
| 387 |
+
for position, label, mwt_label in zip(
|
| 388 |
+
positions.tolist()[1:], labels[1:], mwt_labels[1:]
|
| 389 |
+
)
|
| 390 |
+
if label != TokenizerDataset.CONTINUATION
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
sentences: List[Sentence] = []
|
| 394 |
+
current_sentence = Sentence()
|
| 395 |
+
for index, (start, label, is_mwt) in enumerate(boundaries):
|
| 396 |
+
if label == TokenizerDataset.SENTENCE_START and current_sentence.tokens:
|
| 397 |
+
sentences.append(current_sentence)
|
| 398 |
+
current_sentence = Sentence()
|
| 399 |
+
|
| 400 |
+
end = boundaries[index + 1][0] if index + 1 < len(boundaries) else len(text)
|
| 401 |
+
token_text = text[start:end]
|
| 402 |
+
current_sentence.tokens.append(
|
| 403 |
+
Token(
|
| 404 |
+
id=len(current_sentence.tokens) + 1,
|
| 405 |
+
form="".join(token_text.split()),
|
| 406 |
+
space_after=token_text[-1].isspace(),
|
| 407 |
+
is_mwt=bool(is_mwt),
|
| 408 |
+
)
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
if current_sentence.tokens:
|
| 412 |
+
sentences.append(current_sentence)
|
| 413 |
+
|
| 414 |
+
return sentences
|
src/pipeline/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""src.pipeline package."""
|
src/pipeline/hf/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hub export support for borg-cube's custom Transformers pipeline."""
|
| 2 |
+
|
| 3 |
+
from src.pipeline.hf.export import export_hf_repo
|
| 4 |
+
|
| 5 |
+
__all__ = ["export_hf_repo"]
|
src/pipeline/hf/config.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "borg_cube",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"BorgHFModel"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_borg.BorgHFConfig",
|
| 8 |
+
"AutoModel": "modeling_borg.BorgHFModel"
|
| 9 |
+
},
|
| 10 |
+
"custom_pipelines": {
|
| 11 |
+
"borg-cube": {
|
| 12 |
+
"impl": "pipeline.BorgHFPipeline",
|
| 13 |
+
"pt": [
|
| 14 |
+
"AutoModel"
|
| 15 |
+
],
|
| 16 |
+
"tf": []
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"borg_config": {},
|
| 20 |
+
"components": [],
|
| 21 |
+
"checkpoint": "best"
|
| 22 |
+
}
|
src/pipeline/hf/configuration_borg.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face configuration for exported borg-cube pipelines."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import Any, Dict, List, Optional
|
| 5 |
+
|
| 6 |
+
from transformers import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class BorgHFConfig(PretrainedConfig):
|
| 10 |
+
model_type = "borg_cube"
|
| 11 |
+
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
borg_config: Optional[Dict[str, Any]] = None,
|
| 15 |
+
components: Optional[List[str]] = None,
|
| 16 |
+
checkpoint: str = "best",
|
| 17 |
+
**kwargs,
|
| 18 |
+
):
|
| 19 |
+
super().__init__(**kwargs)
|
| 20 |
+
self.borg_config = borg_config or {}
|
| 21 |
+
self.components = components if components is not None else []
|
| 22 |
+
self.checkpoint = checkpoint
|
src/pipeline/hf/export.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Create a Hub repository directory for ``transformers.pipeline``."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import shutil
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Optional, Sequence, Union
|
| 8 |
+
|
| 9 |
+
from src.config import BorgConfig
|
| 10 |
+
from src.pipeline.hf.configuration_borg import BorgHFConfig
|
| 11 |
+
from src.pipeline.hf.modeling_borg import BorgHFModel
|
| 12 |
+
from src.pipeline.hf.pipeline import _COMPONENTS
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def export_hf_repo(
|
| 16 |
+
output_dir: Union[str, Path],
|
| 17 |
+
*,
|
| 18 |
+
config: Optional[BorgConfig] = None,
|
| 19 |
+
components: Optional[Sequence[str]] = None,
|
| 20 |
+
checkpoint: str = "best",
|
| 21 |
+
) -> Path:
|
| 22 |
+
"""Export a Hub pipeline that references separately uploaded adapters.
|
| 23 |
+
|
| 24 |
+
The output directory is ready to upload to the base Hub repository. It
|
| 25 |
+
includes the generated ``config.json`` and remote runtime code. Component
|
| 26 |
+
checkpoints are uploaded separately to repositories named
|
| 27 |
+
``<base-repo>-<component>``.
|
| 28 |
+
"""
|
| 29 |
+
if checkpoint not in ("best", "last"):
|
| 30 |
+
raise ValueError("checkpoint must be 'best' or 'last'")
|
| 31 |
+
|
| 32 |
+
output_path = Path(output_dir).expanduser()
|
| 33 |
+
selected_components = tuple(
|
| 34 |
+
_COMPONENTS if components is None else components
|
| 35 |
+
)
|
| 36 |
+
if not selected_components:
|
| 37 |
+
raise ValueError("At least one component must be selected")
|
| 38 |
+
if isinstance(components, str):
|
| 39 |
+
raise TypeError("components must be a sequence of component names")
|
| 40 |
+
unknown = set(selected_components) - set(_COMPONENTS)
|
| 41 |
+
if unknown:
|
| 42 |
+
raise ValueError(f"Unknown components: {', '.join(sorted(unknown))}")
|
| 43 |
+
if len(set(selected_components)) != len(selected_components):
|
| 44 |
+
raise ValueError("components must not contain duplicates")
|
| 45 |
+
|
| 46 |
+
if output_path.exists() and any(output_path.iterdir()):
|
| 47 |
+
raise FileExistsError(f"Export directory is not empty: {output_path}")
|
| 48 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
|
| 50 |
+
package_root = Path(__file__).resolve().parents[3]
|
| 51 |
+
copy_ignore = shutil.ignore_patterns("__pycache__", "*.pyc")
|
| 52 |
+
for package in ("src", "eval"):
|
| 53 |
+
shutil.copytree(
|
| 54 |
+
package_root / package,
|
| 55 |
+
output_path / package,
|
| 56 |
+
ignore=copy_ignore,
|
| 57 |
+
)
|
| 58 |
+
for source_name, target_name in (
|
| 59 |
+
("configuration_borg.py", "configuration_borg.py"),
|
| 60 |
+
("modeling_borg.py", "modeling_borg.py"),
|
| 61 |
+
("pipeline.py", "pipeline.py"),
|
| 62 |
+
):
|
| 63 |
+
shutil.copyfile(
|
| 64 |
+
Path(__file__).with_name(source_name),
|
| 65 |
+
output_path / target_name,
|
| 66 |
+
)
|
| 67 |
+
requirements_path = package_root / "requirements.txt"
|
| 68 |
+
if requirements_path.is_file():
|
| 69 |
+
shutil.copyfile(requirements_path, output_path / "requirements.txt")
|
| 70 |
+
else:
|
| 71 |
+
(output_path / "requirements.txt").write_text(
|
| 72 |
+
"torch>=2.0.0\n"
|
| 73 |
+
"transformers>=4.35.0\n"
|
| 74 |
+
"huggingface_hub>=0.19.0\n"
|
| 75 |
+
"adapters>=0.1.1\n"
|
| 76 |
+
"numpy>=1.24.0\n"
|
| 77 |
+
"tqdm>=4.65.0\n"
|
| 78 |
+
"sentencepiece>=0.1.99\n"
|
| 79 |
+
"protobuf>=3.20.0\n",
|
| 80 |
+
encoding="utf-8",
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
with Path(__file__).with_name("config.json").open(encoding="utf-8") as source:
|
| 84 |
+
hub_config_values = json.load(source)
|
| 85 |
+
hub_config_values.update(
|
| 86 |
+
borg_config=config.to_dict() if config is not None else {},
|
| 87 |
+
components=list(selected_components),
|
| 88 |
+
checkpoint=checkpoint,
|
| 89 |
+
)
|
| 90 |
+
hub_config = BorgHFConfig(**hub_config_values)
|
| 91 |
+
hub_model = BorgHFModel(hub_config)
|
| 92 |
+
hub_model.save_pretrained(str(output_path), safe_serialization=False)
|
| 93 |
+
|
| 94 |
+
(output_path / "README.md").write_text(
|
| 95 |
+
"# Borg Cube\n\n"
|
| 96 |
+
"This repository contains the borg-cube pipeline configuration and "
|
| 97 |
+
"runtime code, but not its component weights. Publish each component "
|
| 98 |
+
"to a model repository named by appending `-<component>` to this "
|
| 99 |
+
"repository ID (for example, `racai-ai/mixed-tokenizer`). The pipeline "
|
| 100 |
+
"downloads the listed components at runtime. Pass `adapter_variant` "
|
| 101 |
+
"to select repositories with an additional suffix, such as "
|
| 102 |
+
"`racai/borg-tokenizer-combined`; omit it for default repositories. "
|
| 103 |
+
"Its custom pipeline code is loaded by Transformers; review it before enabling "
|
| 104 |
+
"`trust_remote_code`.\n\n"
|
| 105 |
+
"Install the dependencies listed in `requirements.txt`, then run:\n\n"
|
| 106 |
+
"```python\n"
|
| 107 |
+
"from transformers import pipeline\n\n"
|
| 108 |
+
'nlp = pipeline(model="your-username/your-nlp-repo", '
|
| 109 |
+
"trust_remote_code=True, adapter_variant='combined')\n"
|
| 110 |
+
'result = nlp("Your input text here")\n'
|
| 111 |
+
"```\n",
|
| 112 |
+
encoding="utf-8",
|
| 113 |
+
)
|
| 114 |
+
return output_path
|
src/pipeline/hf/modeling_borg.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lightweight AutoModel used to load a custom borg-cube pipeline from the Hub."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import PreTrainedModel
|
| 8 |
+
|
| 9 |
+
from .configuration_borg import BorgHFConfig
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class BorgHFModel(PreTrainedModel):
|
| 13 |
+
config_class = BorgHFConfig
|
| 14 |
+
base_model_prefix = "borg_cube"
|
| 15 |
+
|
| 16 |
+
def __init__(self, config: BorgHFConfig):
|
| 17 |
+
super().__init__(config)
|
| 18 |
+
self.register_buffer("_pipeline_marker", torch.zeros(1))
|
| 19 |
+
self.post_init()
|
| 20 |
+
|
| 21 |
+
def forward(self, *args: Any, **kwargs: Any):
|
| 22 |
+
raise RuntimeError(
|
| 23 |
+
"BorgHFModel is a Hub loading marker; inference runs through "
|
| 24 |
+
"the registered BorgHFPipeline."
|
| 25 |
+
)
|
src/pipeline/hf/pipeline.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transformers Pipeline adapter for borg-cube checkpoints."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Dict, List, Optional, Sequence
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import snapshot_download
|
| 10 |
+
from transformers.pipelines import Pipeline
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_COMPONENTS = ("tokenizer", "mwt", "tagger", "parser", "lemmatizer")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _read_component(path: Path) -> str:
|
| 17 |
+
with (path / "borg_config.json").open(encoding="utf-8") as source:
|
| 18 |
+
component = json.load(source).get("component")
|
| 19 |
+
if component not in _COMPONENTS:
|
| 20 |
+
raise ValueError(f"Checkpoint at {str(path)!r} has an invalid component")
|
| 21 |
+
return component
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _discover_checkpoints(
|
| 25 |
+
model_path: Path,
|
| 26 |
+
components: Sequence[str],
|
| 27 |
+
checkpoint: str,
|
| 28 |
+
) -> Dict[str, Path]:
|
| 29 |
+
if not model_path.is_dir():
|
| 30 |
+
raise FileNotFoundError(f"Borg model directory not found: {model_path}")
|
| 31 |
+
|
| 32 |
+
direct_config = model_path / "borg_config.json"
|
| 33 |
+
if direct_config.is_file():
|
| 34 |
+
component = _read_component(model_path)
|
| 35 |
+
if component not in components:
|
| 36 |
+
raise ValueError(
|
| 37 |
+
f"The checkpoint contains {component!r}, which is not in components"
|
| 38 |
+
)
|
| 39 |
+
return {component: model_path}
|
| 40 |
+
|
| 41 |
+
if model_path.name in _COMPONENTS:
|
| 42 |
+
checkpoint_path = model_path / checkpoint
|
| 43 |
+
if (checkpoint_path / "borg_config.json").is_file():
|
| 44 |
+
return {model_path.name: checkpoint_path}
|
| 45 |
+
|
| 46 |
+
found: Dict[str, Path] = {}
|
| 47 |
+
for component in components:
|
| 48 |
+
component_path = model_path / component
|
| 49 |
+
if (component_path / "borg_config.json").is_file():
|
| 50 |
+
found[component] = component_path
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
checkpoint_path = component_path / checkpoint
|
| 54 |
+
if (checkpoint_path / "borg_config.json").is_file():
|
| 55 |
+
found[component] = checkpoint_path
|
| 56 |
+
|
| 57 |
+
if not found:
|
| 58 |
+
raise FileNotFoundError(
|
| 59 |
+
f"No {checkpoint!r} Borg checkpoints found under {model_path}"
|
| 60 |
+
)
|
| 61 |
+
return found
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _load_config(path: Path):
|
| 65 |
+
from src.config import BorgConfig
|
| 66 |
+
|
| 67 |
+
with (path / "borg_config.json").open(encoding="utf-8") as source:
|
| 68 |
+
return BorgConfig.from_dict(json.load(source))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _sentence_to_dict(sentence) -> Dict[str, Any]:
|
| 72 |
+
return {
|
| 73 |
+
"comments": list(sentence.comments),
|
| 74 |
+
"tokens": [
|
| 75 |
+
{
|
| 76 |
+
"id": token.id,
|
| 77 |
+
"form": token.form,
|
| 78 |
+
"lemma": token.lemma,
|
| 79 |
+
"upos": token.upos,
|
| 80 |
+
"xpos": token.xpos,
|
| 81 |
+
"feats": token.feats_str(),
|
| 82 |
+
"head": token.head,
|
| 83 |
+
"deprel": token.deprel,
|
| 84 |
+
"deps": token.deps,
|
| 85 |
+
"misc": token.misc,
|
| 86 |
+
"space_after": token.space_after,
|
| 87 |
+
"is_mwt": token.is_mwt,
|
| 88 |
+
}
|
| 89 |
+
for token in sentence.tokens
|
| 90 |
+
],
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class _PassthroughTokenizer:
|
| 95 |
+
pad_token_id = 0
|
| 96 |
+
padding_side = "right"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _repository_path(model) -> Path:
|
| 100 |
+
model_id = getattr(model.config, "_name_or_path", None)
|
| 101 |
+
if not model_id:
|
| 102 |
+
raise ValueError("The Borg model config does not identify its Hub repository")
|
| 103 |
+
|
| 104 |
+
path = Path(model_id).expanduser()
|
| 105 |
+
if path.is_dir():
|
| 106 |
+
return path
|
| 107 |
+
return Path(
|
| 108 |
+
snapshot_download(
|
| 109 |
+
model_id,
|
| 110 |
+
revision=getattr(model.config, "_commit_hash", None),
|
| 111 |
+
)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _runtime_device(config, device) -> Any:
|
| 116 |
+
import torch
|
| 117 |
+
|
| 118 |
+
if device is not None:
|
| 119 |
+
if isinstance(device, int):
|
| 120 |
+
config.device = "cpu" if device < 0 else f"cuda:{device}"
|
| 121 |
+
else:
|
| 122 |
+
config.device = str(device)
|
| 123 |
+
return torch.device(config.resolve_device())
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _adapter_repo_id(base_repo_id: str, component: str, variant: Optional[str]) -> str:
|
| 127 |
+
if variant is None:
|
| 128 |
+
return f"{base_repo_id}-{component}"
|
| 129 |
+
if (
|
| 130 |
+
not isinstance(variant, str)
|
| 131 |
+
or not variant
|
| 132 |
+
or variant.strip() != variant
|
| 133 |
+
or "/" in variant
|
| 134 |
+
or "\\" in variant
|
| 135 |
+
):
|
| 136 |
+
raise ValueError("adapter_variant must be a non-empty repository name suffix")
|
| 137 |
+
return f"{base_repo_id}-{component}-{variant}"
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _load_engine(model, device, adapter_variant: Optional[str] = None):
|
| 141 |
+
repo_path = _repository_path(model)
|
| 142 |
+
repo_string = str(repo_path)
|
| 143 |
+
if repo_string not in sys.path:
|
| 144 |
+
sys.path.insert(0, repo_string)
|
| 145 |
+
|
| 146 |
+
from src.config import BorgConfig
|
| 147 |
+
from src.pipeline.pipeline import BorgPipeline
|
| 148 |
+
|
| 149 |
+
adapter_checkpoints = []
|
| 150 |
+
for component in model.config.components:
|
| 151 |
+
adapter_repo_id = _adapter_repo_id(
|
| 152 |
+
model.config._name_or_path,
|
| 153 |
+
component,
|
| 154 |
+
adapter_variant,
|
| 155 |
+
)
|
| 156 |
+
adapter_repo_path = Path(snapshot_download(adapter_repo_id))
|
| 157 |
+
checkpoint_path = adapter_repo_path / model.config.checkpoint
|
| 158 |
+
if not (checkpoint_path / "borg_config.json").is_file():
|
| 159 |
+
if not (adapter_repo_path / "borg_config.json").is_file():
|
| 160 |
+
raise FileNotFoundError(
|
| 161 |
+
f"Repository {adapter_repo_id!r} has no "
|
| 162 |
+
f"{model.config.checkpoint!r} checkpoint for {component!r}"
|
| 163 |
+
)
|
| 164 |
+
checkpoint_path = adapter_repo_path
|
| 165 |
+
adapter_checkpoints.append((component, checkpoint_path))
|
| 166 |
+
|
| 167 |
+
if not adapter_checkpoints:
|
| 168 |
+
raise ValueError("The Borg pipeline config does not list any adapters")
|
| 169 |
+
|
| 170 |
+
if model.config.borg_config:
|
| 171 |
+
config = BorgConfig.from_dict(model.config.borg_config)
|
| 172 |
+
else:
|
| 173 |
+
config = _load_config(adapter_checkpoints[0][1])
|
| 174 |
+
runtime_device = _runtime_device(config, device)
|
| 175 |
+
engine = BorgPipeline(config)
|
| 176 |
+
for component, checkpoint_path in adapter_checkpoints:
|
| 177 |
+
engine.load_component(component, str(checkpoint_path))
|
| 178 |
+
|
| 179 |
+
return engine, runtime_device
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class BorgHFPipeline(Pipeline):
|
| 183 |
+
"""Hub-loadable pipeline for complete borg-cube checkpoints."""
|
| 184 |
+
|
| 185 |
+
def __init__(
|
| 186 |
+
self,
|
| 187 |
+
model,
|
| 188 |
+
tokenizer=None,
|
| 189 |
+
framework: Optional[str] = None,
|
| 190 |
+
task: str = "borg-cube",
|
| 191 |
+
device=None,
|
| 192 |
+
adapter_variant: Optional[str] = None,
|
| 193 |
+
**kwargs,
|
| 194 |
+
):
|
| 195 |
+
self.engine, runtime_device = _load_engine(
|
| 196 |
+
model,
|
| 197 |
+
device,
|
| 198 |
+
adapter_variant=adapter_variant,
|
| 199 |
+
)
|
| 200 |
+
super().__init__(
|
| 201 |
+
model=model,
|
| 202 |
+
tokenizer=(
|
| 203 |
+
tokenizer if tokenizer is not None else _PassthroughTokenizer()
|
| 204 |
+
),
|
| 205 |
+
framework=framework or "pt",
|
| 206 |
+
task=task,
|
| 207 |
+
device=runtime_device,
|
| 208 |
+
**kwargs,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def _sanitize_parameters(self, show_progress: bool = False, **kwargs):
|
| 212 |
+
if kwargs:
|
| 213 |
+
raise TypeError(
|
| 214 |
+
f"Unexpected pipeline parameters: {', '.join(sorted(kwargs))}"
|
| 215 |
+
)
|
| 216 |
+
return {}, {"show_progress": show_progress}, {}
|
| 217 |
+
|
| 218 |
+
def preprocess(self, input_: Any, **preprocess_parameters) -> Dict[str, Any]:
|
| 219 |
+
if not isinstance(input_, str):
|
| 220 |
+
raise TypeError("BorgHFPipeline inputs must be strings")
|
| 221 |
+
return {"text": input_}
|
| 222 |
+
|
| 223 |
+
def _forward(self, input_tensors: Dict[str, Any], show_progress: bool = False):
|
| 224 |
+
texts = input_tensors["text"]
|
| 225 |
+
if isinstance(texts, str):
|
| 226 |
+
texts = [texts]
|
| 227 |
+
return {
|
| 228 |
+
"sentences": [
|
| 229 |
+
self.engine.process(text, show_progress=show_progress)
|
| 230 |
+
for text in texts
|
| 231 |
+
]
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
def postprocess(self, model_outputs: Any) -> List[Dict[str, Any]]:
|
| 235 |
+
if isinstance(model_outputs, dict):
|
| 236 |
+
sentences = model_outputs["sentences"][0]
|
| 237 |
+
else:
|
| 238 |
+
sentences = model_outputs
|
| 239 |
+
return [_sentence_to_dict(sentence) for sentence in sentences]
|
src/pipeline/pipeline.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pipeline orchestration: loads components, runs end-to-end inference."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
|
| 7 |
+
from src.config import BorgConfig
|
| 8 |
+
from src.data.conllu import Sentence, read_conllu, write_conllu
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class BorgPipeline:
|
| 12 |
+
"""Orchestrates tokenizer → MWT expansion → tagger → parser → lemmatizer."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, config: Optional[BorgConfig] = None):
|
| 15 |
+
self.config = config or BorgConfig()
|
| 16 |
+
self.tokenizer_model = None
|
| 17 |
+
self.mwt_model = None
|
| 18 |
+
self.tagger_model = None
|
| 19 |
+
self.parser_model = None
|
| 20 |
+
self.lemmatizer_model = None
|
| 21 |
+
|
| 22 |
+
# ------------------------------------------------------------------
|
| 23 |
+
def load_component(self, component: str, model_path: str) -> None:
|
| 24 |
+
"""Load a trained component from *model_path*."""
|
| 25 |
+
if component == "tokenizer":
|
| 26 |
+
from src.models.tokenizer import TokenizerModel
|
| 27 |
+
self.tokenizer_model = TokenizerModel.load(model_path, self.config)
|
| 28 |
+
elif component == "mwt":
|
| 29 |
+
from src.models.mwt import MWTModel
|
| 30 |
+
self.mwt_model = MWTModel.load(model_path, self.config)
|
| 31 |
+
elif component == "tagger":
|
| 32 |
+
from src.models.tagger import TaggerModel
|
| 33 |
+
self.tagger_model = TaggerModel.load(model_path, self.config)
|
| 34 |
+
elif component == "parser":
|
| 35 |
+
from src.models.parser import ParserModel
|
| 36 |
+
self.parser_model = ParserModel.load(model_path, self.config)
|
| 37 |
+
elif component == "lemmatizer":
|
| 38 |
+
from src.models.lemmatizer import LemmatizerModel
|
| 39 |
+
self.lemmatizer_model = LemmatizerModel.load(model_path, self.config)
|
| 40 |
+
else:
|
| 41 |
+
raise ValueError(f"Unknown component: {component}")
|
| 42 |
+
|
| 43 |
+
# ------------------------------------------------------------------
|
| 44 |
+
def train_component(
|
| 45 |
+
self,
|
| 46 |
+
component: str,
|
| 47 |
+
train_file: str,
|
| 48 |
+
dev_file: str,
|
| 49 |
+
model_path: str,
|
| 50 |
+
*,
|
| 51 |
+
resume: bool = False,
|
| 52 |
+
) -> None:
|
| 53 |
+
"""Train a component, optionally resuming its last checkpoint."""
|
| 54 |
+
train_sentences = read_conllu(train_file, show_progress=True)
|
| 55 |
+
dev_sentences = read_conllu(dev_file, show_progress=True)
|
| 56 |
+
component_path = os.path.join(model_path, component)
|
| 57 |
+
|
| 58 |
+
if component == "tokenizer":
|
| 59 |
+
from src.models.tokenizer import TokenizerModel
|
| 60 |
+
TokenizerModel.train_model(train_sentences, dev_sentences, self.config, component_path, resume=resume)
|
| 61 |
+
|
| 62 |
+
elif component == "mwt":
|
| 63 |
+
from src.models.mwt import MWTModel
|
| 64 |
+
MWTModel.train_model(train_sentences, dev_sentences, self.config, component_path, resume=resume)
|
| 65 |
+
|
| 66 |
+
elif component == "tagger":
|
| 67 |
+
from src.models.tagger import TaggerModel
|
| 68 |
+
TaggerModel.train_model(train_sentences, dev_sentences, self.config, component_path, resume=resume)
|
| 69 |
+
|
| 70 |
+
elif component == "parser":
|
| 71 |
+
from src.models.parser import ParserModel
|
| 72 |
+
ParserModel.train_model(train_sentences, dev_sentences, self.config, component_path, resume=resume)
|
| 73 |
+
|
| 74 |
+
elif component == "lemmatizer":
|
| 75 |
+
from src.models.lemmatizer import LemmatizerModel
|
| 76 |
+
LemmatizerModel.train_model(train_sentences, dev_sentences, self.config, component_path, resume=resume)
|
| 77 |
+
|
| 78 |
+
else:
|
| 79 |
+
raise ValueError(f"Unknown component: {component}")
|
| 80 |
+
|
| 81 |
+
# ------------------------------------------------------------------
|
| 82 |
+
def process(self, text: str, *, show_progress: bool = True) -> List[Sentence]:
|
| 83 |
+
"""Run text through the full pipeline.
|
| 84 |
+
|
| 85 |
+
Steps applied in order depending on which components are loaded:
|
| 86 |
+
1. Tokenization (if tokenizer_model present)
|
| 87 |
+
2. MWT expansion
|
| 88 |
+
3. POS tagging
|
| 89 |
+
4. Dependency parsing
|
| 90 |
+
5. Lemmatization
|
| 91 |
+
"""
|
| 92 |
+
# Step 1: tokenize
|
| 93 |
+
if self.tokenizer_model is not None:
|
| 94 |
+
sentences = self.tokenizer_model.predict(
|
| 95 |
+
text, show_progress=show_progress,
|
| 96 |
+
)
|
| 97 |
+
else:
|
| 98 |
+
# Naive fallback: one sentence, whitespace tokens
|
| 99 |
+
from src.data.conllu import Token
|
| 100 |
+
words = text.split()
|
| 101 |
+
sentences = [
|
| 102 |
+
Sentence(tokens=[Token(id=i + 1, form=w) for i, w in enumerate(words)])
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
if self.mwt_model is not None:
|
| 106 |
+
sentences = self.mwt_model.predict(
|
| 107 |
+
sentences, show_progress=show_progress,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# Step 2: tag
|
| 111 |
+
if self.tagger_model is not None:
|
| 112 |
+
sentences = self.tagger_model.predict(
|
| 113 |
+
sentences, show_progress=show_progress,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# Step 3: parse
|
| 117 |
+
if self.parser_model is not None:
|
| 118 |
+
sentences = self.parser_model.predict(
|
| 119 |
+
sentences, show_progress=show_progress,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# Step 4: lemmatize
|
| 123 |
+
if self.lemmatizer_model is not None:
|
| 124 |
+
sentences = self.lemmatizer_model.predict(
|
| 125 |
+
sentences, show_progress=show_progress,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
return sentences
|
| 129 |
+
|
| 130 |
+
# ------------------------------------------------------------------
|
| 131 |
+
def test(
|
| 132 |
+
self,
|
| 133 |
+
model_path: str,
|
| 134 |
+
input_file: str,
|
| 135 |
+
output_file: str,
|
| 136 |
+
) -> None:
|
| 137 |
+
"""Process an input file and write CoNLL-U output.
|
| 138 |
+
|
| 139 |
+
If *input_file* ends with .txt (or contains no CoNLL-U tokens),
|
| 140 |
+
it is treated as raw text and passed through the full pipeline.
|
| 141 |
+
Otherwise it is read as CoNLL-U and only the annotation steps run.
|
| 142 |
+
"""
|
| 143 |
+
_, ext = os.path.splitext(input_file)
|
| 144 |
+
|
| 145 |
+
if ext.lower() in (".txt",):
|
| 146 |
+
# Raw text input
|
| 147 |
+
with open(input_file, encoding="utf-8") as fh:
|
| 148 |
+
text = fh.read()
|
| 149 |
+
sentences = self.process(text)
|
| 150 |
+
else:
|
| 151 |
+
# CoNLL-U input — skip tokenization
|
| 152 |
+
sentences = read_conllu(input_file)
|
| 153 |
+
if self.mwt_model is not None:
|
| 154 |
+
sentences = self.mwt_model.predict(sentences)
|
| 155 |
+
if self.tagger_model is not None:
|
| 156 |
+
sentences = self.tagger_model.predict(sentences)
|
| 157 |
+
if self.parser_model is not None:
|
| 158 |
+
sentences = self.parser_model.predict(sentences)
|
| 159 |
+
if self.lemmatizer_model is not None:
|
| 160 |
+
sentences = self.lemmatizer_model.predict(sentences)
|
| 161 |
+
|
| 162 |
+
write_conllu(sentences, output_file)
|
| 163 |
+
print(f"Written {len(sentences)} sentences to {output_file}")
|