"""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)