File size: 3,166 Bytes
2eb3475
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Architecture-agnostic loader for fine-tuned classification checkpoints.

Handles BERT / RoBERTa / ELECTRA / any HF AutoModelForSequenceClassification.
Tokenizer is loaded either from the model dir (if it has tokenizer files) or
from a configured base-tokenizer name (e.g. ``roberta-base``).

Also supports PEFT LoRA adapters: pass ``is_peft=True`` and the adapter path,
and we'll load the base model first then apply the adapter.
"""
from __future__ import annotations

from typing import Optional, Tuple

import torch
from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer


def load_classification_model(
    pretrained_path: str,
    *,
    num_labels: Optional[int] = None,
    base_tokenizer: Optional[str] = None,
    do_lower_case: Optional[bool] = None,
    is_peft: bool = False,
    base_model: Optional[str] = None,
) -> Tuple[torch.nn.Module, "AutoTokenizer"]:
    config_kwargs = {"output_attentions": True, "output_hidden_states": True}
    if num_labels is not None:
        config_kwargs["num_labels"] = num_labels

    if is_peft:
        # Load the base model first, then apply the PEFT adapter.
        from peft import PeftModel, PeftConfig
        peft_config = PeftConfig.from_pretrained(pretrained_path)
        base_name = base_model or peft_config.base_model_name_or_path
        base_cfg = AutoConfig.from_pretrained(base_name, **config_kwargs)
        base = AutoModelForSequenceClassification.from_pretrained(base_name, config=base_cfg)
        model = PeftModel.from_pretrained(base, pretrained_path)
        # Merge the adapter so attention/hidden_state outputs work cleanly.
        model = model.merge_and_unload()
        model.eval()
        # Tokenizer comes from the base model.
        tok_kwargs = {}
        if do_lower_case is not None:
            tok_kwargs["do_lower_case"] = do_lower_case
        tokenizer = AutoTokenizer.from_pretrained(base_tokenizer or base_name, **tok_kwargs)
        return model, tokenizer

    config = AutoConfig.from_pretrained(pretrained_path, **config_kwargs)
    model = AutoModelForSequenceClassification.from_pretrained(pretrained_path, config=config)
    model.eval()

    tok_kwargs = {}
    if do_lower_case is not None:
        tok_kwargs["do_lower_case"] = do_lower_case
    # Try the model dir first; fall back to ``base_tokenizer`` if it lacks tokenizer files.
    try:
        tokenizer = AutoTokenizer.from_pretrained(pretrained_path, **tok_kwargs)
    except (OSError, ValueError):
        if not base_tokenizer:
            raise
        tokenizer = AutoTokenizer.from_pretrained(base_tokenizer, **tok_kwargs)
    return model, tokenizer


# Back-compat alias used by 01_extract_predictions_and_attention.py.
def load_bert_for_classification(
    pretrained_path: str,
    num_labels: int = 2,
    do_lower_case: bool = False,
) -> Tuple[torch.nn.Module, "AutoTokenizer"]:
    return load_classification_model(
        pretrained_path,
        num_labels=num_labels,
        base_tokenizer=None,
        do_lower_case=do_lower_case,
    )


def move(model: torch.nn.Module, device: torch.device) -> torch.nn.Module:
    return model.to(device)