hydra.py 27.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
from __future__ import annotations

import json
import time
import typing

from collections import defaultdict
from itertools import chain
from math import floor

import logging
logger = logging.getLogger(__name__)
logger.debug('Hydra says hi!')

import morfeusz2

import torch
from transformers import AutoTokenizer, PreTrainedTokenizerBase

from datasets.features import ClassLabel, Features, List, Sequence, Value

from .dataset_utils import  masked_word_ids, morf_tokenize
from .hybrid_tree_utils import make_lemma, correct_lemma, EXC, drop_rozpodabniacz, get_heads, get_graph_edges, make_tree, tree2dict, get_tree_dict_yield
from .conllu_utils import get_conllu
from .ner_utils import get_nes
from .model_utils import get_model_class, MultiTargetTokenClassification

from .constants import (
    SEG_BEGIN,
    SEGS,
    LEMMAS,
    LEMMA_CASES,
    LEMMA_RULES,
    TAGS,
    HEADS,
    ADJACENCY_MATRIX,
    DEPRELS,
    GRAPH_HEADS,
    GRAPH_ADJACENCY_MATRIX,
    GRAPH_DEPRELS,
    SPINES,
    ANCHORS,
    ANCHOR_HS,
    NE_IOBS,
    MASK_VALUE,
    EAGER,
    CLE,
)
from .type_utils import TokenList, IntLabelList, StrLabelList, SimpleLabelList, AnyLabelList, LabelDict, TreeDict, HydraAnalysis

def maybe_int(s: str) -> str | int:
    if s and (s.isdigit() or s[0] == '-' and s[1:].isdigit()):
        return int(s)
    return s

def keys_hook(d: dict[str, typing.Any]) -> dict[str | int, typing.Any]:
    return { maybe_int(k) : v for k, v in d.items() }

def category_names(
    segmentation: bool = False,
    lemmatisation: bool = False,
    tagging: bool = False,
    dependency: bool = False,
    graph: bool = False,
    hybrid: bool = False,
    nonterminal_features: list[str] | None = None,
    named_entities: bool = False
) -> list[str]:
    
    categories: list[str] = []
        
    if segmentation:
        categories.append(SEGS)
    
    if lemmatisation:
        categories.append(LEMMA_CASES)
        categories.append(LEMMA_RULES)
    
    if tagging:
        categories.append(TAGS)
    
    if dependency:
        categories.append(ADJACENCY_MATRIX)
        categories.append(DEPRELS)
    
    if graph:
        categories.append(GRAPH_ADJACENCY_MATRIX)
        categories.append(GRAPH_DEPRELS)
        
    if hybrid:
        categories.append(SPINES)
        categories.append(ANCHORS)
        categories.append(ANCHOR_HS)
    
    if nonterminal_features:
        categories += nonterminal_features
    
    if named_entities:
        categories.append(NE_IOBS)
    
    return categories

def get_feature_labels(feature: ClassLabel | Sequence | List | Value) -> list[str] | None:
    if isinstance(feature, ClassLabel):
        return feature.names # type: ignore[no-any-return]
    elif isinstance(feature, (Sequence, List)):
        return get_feature_labels(feature.feature)
    else:
        return None

def get_labels(features: Features, categories: list[str]) -> dict[str, list[str]]:
    labels = {}
    for cat in categories:
        _labels = get_feature_labels(features[cat])
        if _labels is not None:
            labels[cat] = _labels
    return labels

def _get_param(config: dict[str, typing.Any], key: str, alt_keys: list[str] | None = None, default: typing.Any = None, allow_none: bool = False) -> typing.Any:
    if key in config:
        return config[key]
    if alt_keys:
        for k in alt_keys:
            if k in config:
                logger.warning(f'Warning: `{k}` parameter in parser config is obsolete and has been renamed to `{key}`. Setting `{key}` to `{k}` value for now.')
                return config[k]
    if default is not None or allow_none:
        return default
    raise KeyError(f'`{key}` parameter missing from config.')

class Hydra(object):
    
    def __init__(
        self,
        pretrained_path: str,
        model_type: str,
        model: MultiTargetTokenClassification,
        labels: dict[str, list[str]],
        segmentation: bool = False,
        lemmatisation: bool = False,
        tagging: bool = False,
        dependency: bool = False,
        graph: bool = False,
        hybrid: bool = False,
        nonterminal_features: list[str] | None = None,
        named_entities: bool = False,
        morfeusz_dict_path: str | None ='polimorf',
        morfeusz_dict_name: str | None = None,
        pretrained_tokenizer: PreTrainedTokenizerBase | None = None,
        tokenizer_kwargs: dict[str, typing.Any] | None = None,
    ) -> None:
        self.pretrained_path = pretrained_path
        self.model_type = model_type
        self.model = model
        self.segmentation = segmentation
        self.lemmatisation = lemmatisation
        self.tagging = tagging
        self.dependency = dependency
        self.graph=graph
        self.hybrid = hybrid
        self.nonterminal_features = nonterminal_features if nonterminal_features is not None else []
        self.named_entities = named_entities
        self.morfeusz_dict_path = morfeusz_dict_path
        self.morfeusz_dict_name = morfeusz_dict_name
        self.categories = category_names(
            segmentation, lemmatisation, tagging, dependency, graph, hybrid, nonterminal_features, named_entities)
        self.labels = labels
        self.tokenizer_kwargs = tokenizer_kwargs if tokenizer_kwargs is not None else {}
        if pretrained_tokenizer is not None:
            self.pretrained_tokenizer = pretrained_tokenizer
        else:
            self.pretrained_tokenizer = AutoTokenizer.from_pretrained(pretrained_path, **self.tokenizer_kwargs)
        if self.segmentation or self.lemmatisation or self.tagging:
            self.morfeusz = morfeusz2.Morfeusz(
                generate=False,
                dict_path=self.morfeusz_dict_path,
                dict_name=self.morfeusz_dict_name,
                expand_tags=True,
                aggl='isolated'
            )
        else:
            self.morfeusz = None
            self.morfeusz_dict_path = None
            self.morfeusz_dict_name = None
    
    def save(self, path: str) -> None:
        self.model.save_pretrained(f'{path}/model')
        config = {
            'segmentation'         : self.segmentation,
            'lemmatisation'        : self.lemmatisation,
            'tagging'              : self.tagging,
            'dependency'           : self.dependency,
            'graph'                : self.graph,
            'hybrid'               : self.hybrid,
            'nonterminal_features' : self.nonterminal_features,
            'named_entities'       : self.named_entities,
            'morfeusz_dict_path'   : self.morfeusz_dict_path,
            'morfeusz_dict_name'   : self.morfeusz_dict_name,
            'pretrained_path'      : self.pretrained_path,
            'tokenizer_kwargs'     : self.tokenizer_kwargs,
            'model_type'           : self.model_type,
            'labels'               : self.labels,
        }
        with open(f'{path}/config.json', 'w') as f:
            json.dump(config, f, ensure_ascii=False)
    
    @classmethod
    def create(
        cls,
        pretrained_path: str,
        model_type: str,
        features: Features,
        segmentation: bool = False,
        lemmatisation: bool = False,
        tagging: bool = False,
        dependency: bool = False,
        graph: bool = False,
        hybrid: bool = False,
        nonterminal_features: list[str] | None = None,
        named_entities: bool = False,
        morfeusz_dict_path: str | None = None,
        morfeusz_dict_name: str | None = 'polimorf',
        pretrained_tokenizer: PreTrainedTokenizerBase | None = None,
        tokenizer_kwargs: dict[str, typing.Any] | None = None,
    ) -> Hydra:
        if hybrid and not dependency:
            logger.warning('Hybrid parsing requires dependency parsing, setting `dependency` to True.')
            dependency = True
        categories = category_names(
            segmentation, lemmatisation, tagging, dependency, graph, hybrid, nonterminal_features, named_entities)
        labels = get_labels(features, categories)
        model = get_model_class(model_type).from_pretrained(
            pretrained_path,
            categories=categories,
            labels=labels,
        )
        
        return cls(
            pretrained_path,
            model_type,
            model,
            labels,
            segmentation=segmentation,
            lemmatisation=lemmatisation,
            tagging=tagging,
            dependency=dependency,
            graph=graph,
            hybrid=hybrid,
            nonterminal_features=nonterminal_features,
            named_entities=named_entities,
            morfeusz_dict_path=morfeusz_dict_path,
            morfeusz_dict_name=morfeusz_dict_name,
            pretrained_tokenizer=pretrained_tokenizer,
            tokenizer_kwargs=tokenizer_kwargs if tokenizer_kwargs is not None else {},
        )
    
    @classmethod
    def load(cls, path: str, morfeusz_dict_path: str | None = None) -> Hydra:
        with open(f'{path}/config.json') as f:
            config = json.load(f, object_hook=keys_hook)
        labels =               _get_param(config, 'labels')
        segmentation =         _get_param(config, 'segmentation')
        lemmatisation =        _get_param(config, 'lemmatisation')
        tagging =              _get_param(config, 'tagging')
        dependency =           _get_param(config, 'dependency')
        graph =                _get_param(config, 'graph', default=False)
        hybrid =               _get_param(config, 'hybrid', alt_keys=['spines'])
        nonterminal_features = _get_param(config, 'nonterminal_features')
        named_entities =       _get_param(config, 'named_entities')
        if not morfeusz_dict_path:
            morfeusz_dict_path =   _get_param(config, 'morfeusz_dict_path', allow_none=True)
        morfeusz_dict_name =   _get_param(config, 'morfeusz_dict_name', allow_none=True)
        logger.debug(f'morfeusz_dict_path: {morfeusz_dict_path}, morfeusz_dict_name: {morfeusz_dict_name}')
        # for backwards compatibility when only BERT was possible
        pretrained_path =      _get_param(config, 'pretrained_path', alt_keys=['bert_path'])
        model_type =           _get_param(config, 'model_type', default='bert')
        tokenizer_kwargs =     _get_param(config, 'tokenizer_kwargs', default={})
        categories = category_names(
            segmentation, lemmatisation, tagging, dependency, graph, hybrid, nonterminal_features, named_entities)
        if lemmatisation and len(labels[LEMMA_CASES]) == 2:
            logger.warning('This model uses legacy rules for lemma casing, consider training a new model.')
        model = get_model_class(model_type).from_pretrained(
            f'{path}/model',
            # use gpu if available
            device_map='auto',
            categories=categories,
            labels=labels,
        )
        
        return cls(
            pretrained_path,
            model_type,
            model,
            labels,
            segmentation=segmentation,
            lemmatisation=lemmatisation,
            tagging=tagging,
            dependency=dependency,
            graph=graph,
            hybrid=hybrid,
            nonterminal_features=nonterminal_features,
            named_entities=named_entities,
            morfeusz_dict_path=morfeusz_dict_path,
            morfeusz_dict_name=morfeusz_dict_name,
            tokenizer_kwargs=tokenizer_kwargs,
        )
    
    def retokenize_mask(self, tokens: TokenList, seg: StrLabelList, min_tokens: TokenList) -> tuple[TokenList, IntLabelList]:
        tok2 = ''
        index = 0
        assert(len(tokens) == len(seg))
        tokens2 = []
        mask: list[int | None] = []
        for token, seglabel in zip(tokens, seg):
            if seglabel == SEG_BEGIN or tok2 == min_tokens[index]:
                tokens2.append(token)
                mask.append(1)
            else:
                tokens2[-1] += token
                mask.append(None)
            if tok2 == min_tokens[index]:
                tok2 = ''
                index += 1
            tok2 += token
        return tokens2, mask
    
    def select_unmasked(self, labels: AnyLabelList, mask: IntLabelList, category: str) -> AnyLabelList:
        matrix = category in (ADJACENCY_MATRIX, GRAPH_ADJACENCY_MATRIX, GRAPH_DEPRELS)
        return [ # type: ignore [return-value]
            lbl if not matrix else self.select_unmasked(lbl, mask, '') # type: ignore[arg-type] # make matrix == False in the nested call
            for lbl, m in zip(labels, mask) if m is not None
        ]
    
    def process_labels(
        self,
        labels: LabelDict,
        tokens: TokenList,
        correct_lemmata: bool = False,
        morph_postprocess: typing.Callable[[str, str, str], tuple[str, str]] | None = None,
        mst: str = CLE,
        allow_masked: bool = False,
    ) -> LabelDict:
        
        if self.lemmatisation:
            rules = labels.pop(LEMMA_RULES)
            cases = labels.pop(LEMMA_CASES)
            legacy_casing = len(self.labels[LEMMA_CASES]) == 2
            labels[LEMMAS] = [make_lemma(*x, legacy_casing=legacy_casing) for x in zip(tokens, cases, rules)] # type: ignore[arg-type]
        else:
            labels[LEMMAS] = ['_' for _ in tokens]
        
        if correct_lemmata:
            tags = labels[TAGS]
            lemmas = labels[LEMMAS]
            # may be an empty sentence...
            if tags:
                new_lemmas, new_tags = map(list, zip(*(correct_lemma(*x, self.morfeusz) for x in zip(tokens, lemmas, tags)))) # type: ignore[arg-type]
                labels[LEMMAS] = new_lemmas
                labels[TAGS] = new_tags
        
        if morph_postprocess:
            tags = labels[TAGS]
            lemmas = labels[LEMMAS]
            # may be an empty sentence...
            if tags:
                new_lemmas, new_tags = map(list, zip(*(morph_postprocess(*x) for x in zip(tokens, lemmas, tags)))) # type: ignore[arg-type]
                labels[LEMMAS] = new_lemmas
                labels[TAGS] = new_tags
        
        if self.dependency:
            matrix = labels.pop(ADJACENCY_MATRIX)
            if allow_masked and set(chain.from_iterable(matrix)) == {MASK_VALUE}:
                labels[HEADS] = [MASK_VALUE for _ in tokens]
            else:
                labels[HEADS] = get_heads(matrix, mst=mst) # type: ignore[arg-type] # ints/floats
                # !!! dodane 26.07.2025
                if labels[HEADS]: # check in case of an empty input string
                    labels[DEPRELS][labels[HEADS].index(None)] = 'root'
        
        if self.graph:
            graph = labels.pop(GRAPH_ADJACENCY_MATRIX)
            deprels = labels.pop(GRAPH_DEPRELS)
            if allow_masked and set(chain.from_iterable(graph)) == {MASK_VALUE}:
                labels[GRAPH_HEADS] = [[MASK_VALUE] for _ in tokens]
                labels[GRAPH_DEPRELS] = [[None] for _ in tokens]
            else:
                labels[GRAPH_HEADS], labels[GRAPH_DEPRELS] = get_graph_edges(graph, deprels)
        
        return labels
    
    def get_nps(self, sentence: str, tokens: TokenList) -> list[bool]:
        nps = []
        for i, token in enumerate(tokens):
            if i == 0:
                nps.append(False)
            else:
                nps.append(sentence.startswith(token))
                while not sentence.startswith(token):
                    sentence = sentence[1:]
            assert(sentence.startswith(token))
            sentence = sentence[len(token):]
        assert (not sentence)
        return nps

    def add_nps(self, tree_dict: TreeDict, nps: list[bool]) -> None:
        terminals = sorted(get_tree_dict_yield(tree_dict), key=lambda x: x['span']['from'])
        assert len(terminals) == len(nps)
        for terminal, _nps in zip(terminals, nps):
            if 'features' not in terminal:
                terminal['features'] = {}
            terminal['features']['nps'] = _nps
    
    def add_oov(self, tree_dict: TreeDict) -> None:
        for terminal in get_tree_dict_yield(tree_dict):
            orth = terminal['orth']
            base = terminal['base']
            tag = terminal['tag']
            oov = (orth, base, tag) not in EXC
            if oov:
                for i, j, interp in self.morfeusz.analyse(orth):
                    o, b, t = interp[:3]
                    b = drop_rozpodabniacz(b, t)
                    if (o, b, t) == (orth, base, tag):
                        oov = False
            if 'features' not in terminal:
                terminal['features'] = {}
            terminal['features']['oov'] = oov
    
    def parse(
        self,
        sentences: list[str] | str,
        correct_lemmata: bool = False,
        return_jsons: bool = False,
        return_conllu: bool = False,
        return_trees: bool = False,
        return_labels: bool = False,
        return_logits: bool = False,
        root_label: str | None = None,
        force_root_label: bool = False,
        skip_long: bool = False,
        is_tokenized: bool = False,
        morph_postprocess: typing.Callable[[str, str, str], tuple[str, str]] | None = None,
        mst: str = CLE,
        return_times: bool = False,
        mem_limit: int | None = None,
        verbose: bool = False,
    ) -> list[HydraAnalysis] | tuple[list[HydraAnalysis], dict[str, int]]:
        
        t1 = time.perf_counter_ns()
        
        if return_logits and sum((return_jsons, return_conllu, return_trees, return_labels)):
            logger.warning('`return_logits` can’t be used with other formats, disabling all other formats.')
            return_jsons = False
            return_conllu = False
            return_trees = False
            return_labels = False
        if not is_tokenized and not self.segmentation:
            raise RuntimeError('This model can’t tokenize, please use is_tokenized=True and pass a space-separated tokenized sentence, e.g ‘Miał em kota .’')
        if correct_lemmata and not (self.lemmatisation and self.tagging):
            logger.warning('This model can’t lemmatise and/or tag, setting `correct_lemmata` to False.')
            correct_lemmata = False
        if correct_lemmata and not (self.lemmatisation and self.tagging):
            logger.warning('This model can’t lemmatise and/or tag, ignoring the `morph_postprocess` argument.')
            morph_postprocess = None
        if return_jsons and not self.hybrid:
            logger.warning('This model can’t perform hybrid parsing and won’t return jsons, setting `return_jsons` to False.')
            return_jsons = False
        if return_trees and not self.hybrid:
            logger.warning('This model can’t perform hybrid parsing and won’t return trees, setting `return_trees` to False.')
            return_trees = False
        if force_root_label and not self.hybrid:
            logger.warning('This model can’t perform hybrid parsing, `force_root_label` will have no effect.')
            force_root_label = False
        if force_root_label and not root_label:
            logger.critical('`force_root_label` was set to true with no `root_label` provided.')
            raise RuntimeError
        if return_conllu and not self.dependency:
            logger.warning('This model can’t perform dependency parsing and won’t return conllu, setting `return_conllu` to False.')
            return_conllu = False
        if not return_jsons and not return_labels and self.named_entities:
            logger.info('This model can do NER. Use return_jsons=True or return_labels=True to retrieve them.')
        if verbose and not return_jsons:
            logger.warning('verbose=True has no effect with return_jsons=False. Use return_jsons=True to get verbose info.')
        if sum((return_jsons, return_conllu, return_trees, return_labels, return_logits)) == 0:
            logger.critical('At least one of the parameters must be set to True: ' + \
                    '`return_jsons`, `return_conllu`, `return_trees`, `return_labels`, `return_logits`.')
            raise RuntimeError
        
        if isinstance(sentences, str):
            sentences = [sentences]
    
        # some tokenizers replace spaces with '▁'
        sentences = [self.pretrained_tokenizer._tokenizer.normalizer.normalize_str(s).replace('▁', ' ').strip() for s in sentences]
        
        tokens = [s.split() for s in sentences]
        if self.segmentation and not is_tokenized:
            #tokens = [morf_tokenize(' '.join(toks), self.morfeusz) for toks in tokens]
            tokens = [list(chain.from_iterable(morf_tokenize(t, self.morfeusz) for t in toks)) for toks in tokens]
        
        num_lm_tokens = self.pretrained_tokenizer(
            tokens,
            is_split_into_words=True,
            truncation=False,
            padding=False,
            return_length=True
        )['length']
        
        max_seq_len = max(num_lm_tokens)
        max_valid_len = self.pretrained_tokenizer.model_max_length
        
        if max_seq_len > max_valid_len and not skip_long:
            raise RuntimeError(f'LM tokenizer produced a sequence of {max_seq_len} tokens which exceeds the model’s limit ({self.pretrained_tokenizer.model_max_length}). Parse shorter sentences or call parse with skip_long=True.')
        
        valid_indices = [i for i, l in enumerate(num_lm_tokens) if l <= max_valid_len]
        invalid_indices = [i for i, l in enumerate(num_lm_tokens) if l > max_valid_len]
        sequence_is_valid = [l <= max_valid_len for l in num_lm_tokens]
        
        tokenized = self.pretrained_tokenizer(
            [tokens[i] for i in valid_indices],
            is_split_into_words=True,
            return_offsets_mapping=True,
            padding=True,
            return_tensors='pt',
        )
        
        t2 = time.perf_counter_ns()
        
        self.model.eval()  # type: ignore[no-untyped-call]
        
        device = self.model.device
        num_samples = tokenized['input_ids'].shape[0]
        if mem_limit is not None:
            k = 64#2 * 128
            batch_size = min(num_samples, max(1, floor(k * mem_limit / (max_seq_len * max_seq_len))))
        else:
            batch_size = num_samples
        logits_lists = defaultdict(list)
        with torch.no_grad():
            for i in range(0, num_samples, batch_size):
                batch = {k: v[i:(i + batch_size)].to(device) for k, v in tokenized.items()}
                for k, v in self.model(**batch).logits.items():
                    logits_lists[k].append(v.cpu())
        predicted = {k : torch.cat(v, dim=0) for k, v in logits_lists.items()}
        
        t3 = time.perf_counter_ns()
        
        # values are logits if return_logits == True, labels otherwise
        labels = dict()
        for cat, pred in predicted.items():
            if return_logits and cat != SEGS:
                _lbls = pred.numpy()
            else:
                if cat == ADJACENCY_MATRIX:
                    _lbls = torch.nn.functional.softmax(pred, dim=-1).numpy()
                elif cat == GRAPH_ADJACENCY_MATRIX:
                    _lbls = torch.round(torch.nn.functional.sigmoid(pred)).numpy()
                elif cat == GRAPH_DEPRELS:
                    label_ids = torch.argmax(pred, dim=-1).numpy()
                    _lbls = [[[self.labels[cat][i] for i in row_ids] for row_ids in instance_ids] for instance_ids in label_ids]
                else:
                    label_ids = torch.argmax(pred, dim=-1).numpy()
                    _lbls = [[self.labels[cat][i] for i in l_ids] for l_ids in label_ids]
            labels[cat] = _lbls
        
        trees = []
        
        idx = 0
        
        for i, (is_valid, tkns, sentence, num_lm_toks) in enumerate(zip(sequence_is_valid, tokens, sentences, num_lm_tokens)):
            
            TREE: HydraAnalysis = {
                'sentence' : sentence,
                'tokens'   : tkns,
                # leaving 'bert_tokens' key for backwards compatibility, 'lm_tokens' would be better
                'metadata' : { 'bert_tokens' : num_lm_toks },
            }
            
            if not is_valid:
                TREE['metadata']['error'] = 'too long'
                trees.append(TREE)
                continue
            
            mask = masked_word_ids(tokenized.word_ids(idx))
            # values are logits if return_logits == True, labels otherwise, except for segments (always labels!)
            selected_labels = {cat : self.select_unmasked(lbls[idx], mask, cat) for cat, lbls in labels.items()}
            nps = None
            
            # empty sentence can happen for automatically sentenced text, eg. single '\u200b' bert-normalised to ''
            if self.segmentation and sentence:
                # remove the seg labels
                seg: StrLabelList = selected_labels.pop(SEGS) # type: ignore[assignment] # we know they’re labels
                if not is_tokenized:
                    # can’t start with ‘I’nside segment
                    seg[0] = SEG_BEGIN
                    tkns, mask = self.retokenize_mask(tkns, seg, sentence.split())
                    selected_labels = {cat : self.select_unmasked(lbl, mask, cat) for cat, lbl in selected_labels.items()}
                    nps = self.get_nps(sentence, tkns)
                    TREE['tokens'] = tkns
            
            if return_logits:
                TREE['logits'] = selected_labels
                trees.append(TREE)
                continue
            
            processed_labels = self.process_labels(
                selected_labels, # type: ignore[arg-type] # dict/LabelDict, but at this point we know they’re labels (return_logits == False)
                tkns,
                correct_lemmata=correct_lemmata,
                morph_postprocess=morph_postprocess,
                mst=mst
            )
            
            if return_trees or return_jsons:
                if not sentence:
                    if return_trees:
                        TREE['tree'] = None
                    if return_jsons:
                        TREE['json'] = None
                else:
                    tree, info, heads = make_tree(tkns, processed_labels, self.nonterminal_features,
                                           root_label=root_label,
                                           force_root_label=force_root_label)
                    processed_labels[HEADS] = heads
                    if return_trees:
                        TREE['tree'] = tree
                    if return_jsons:
                        tree_dict = tree2dict(tree)
                        if self.segmentation and not is_tokenized:
                            assert (nps is not None)
                            self.add_nps(tree_dict, nps)
                        if self.tagging and self.lemmatisation:
                            self.add_oov(tree_dict)
                        if self.named_entities:
                            tree_dict['named_entities'] = get_nes(tkns, processed_labels[NE_IOBS])
                        if verbose:
                            tree_dict['info'] = info
                        TREE['json'] = tree_dict

            if return_conllu:
                TREE['conllu'] = get_conllu(tkns, processed_labels, nps)
            
            # do this last as make_tree might slightly change the the tree
            if return_labels:
                if not is_tokenized:
                    assert (nps is not None)
                    processed_labels['nps'] = nps
                TREE['labels'] = processed_labels
            
            trees.append(TREE)
            
            idx += 1
        
        t4 = time.perf_counter_ns()
        
        if return_times:
            return trees, { 'total' : t4 - t1, 'preprocessing': t2 - t1, 'prediction' : t3 - t2, 'postprocessing' : t4 - t3 }
        else:
            return trees