"""Minimal inference helper and checkpoint loader for Classical FP32 and Adaptive V5 NLI models.""" from __future__ import annotations import argparse import json from pathlib import Path from typing import Dict import torch import torch.nn.functional as F from safetensors.torch import load_file from tokenizers import Tokenizer from data_xnli import CLS_TOKEN, PAD_TOKEN, SEP_TOKEN from model import BilingualNLIConfig, BilingualNLITransformer from progressive_quant import unpack_quantized_state_dict PROJECT_DIR = Path(__file__).resolve().parent ID2LABEL: Dict[int, str] = {0: "entailment", 1: "neutral", 2: "contradiction"} def _infer_config_from_state( state: Dict[str, torch.Tensor], vocab_size: int, use_quantization: bool, config_path: str | Path | None = None, ) -> BilingualNLIConfig: if config_path is not None and Path(config_path).exists(): raw = json.loads(Path(config_path).read_text(encoding="utf-8")) mc = raw.get("model_config", raw) return BilingualNLIConfig(**{k: v for k, v in mc.items() if hasattr(BilingualNLIConfig, k)}) is_100m_v6 = ("__odpe_packed_version__" in state) or ("blocks.0.ffn_gate.bit_widths" in state) if is_100m_v6 and "tok_emb.weight" in state and state["tok_emb.weight"].shape[1] == 768: return BilingualNLIConfig( vocab_size=vocab_size, max_len=128, d_model=768, n_heads=12, n_layers=12, d_ff=2240, initial_bits=10, protect_attention_and_head=use_quantization, attn_init_bits=16, head_init_bits=40, ste_clip=True, use_tier_scales=True, group_size=64, precision_tenths=True, backbone_max_bits=80, head_max_bits=160, use_rms_norm=True, use_rope=True, use_qk_norm=True, use_swiglu=True, ) return BilingualNLIConfig( vocab_size=vocab_size, max_len=128, protect_attention_and_head=use_quantization, attn_init_bits=2, head_init_bits=4, ) def load_nli_model( checkpoint_path: str | Path, tokenizer_path: str | Path = PROJECT_DIR / "artifacts" / "xnli_bpe_tokenizer.json", use_quantization: bool = True, device: str | torch.device = "cpu", cfg: BilingualNLIConfig | None = None, config_path: str | Path | None = None, ) -> tuple[BilingualNLITransformer, Tokenizer]: """Load Classical FP32, Adaptive V5, or packed Adaptive V6 safetensors checkpoint.""" tokenizer = Tokenizer.from_file(str(tokenizer_path)) state = load_file(str(checkpoint_path), device="cpu") if cfg is None: cfg = _infer_config_from_state( state, vocab_size=tokenizer.get_vocab_size(), use_quantization=use_quantization, config_path=config_path ) model = BilingualNLITransformer(cfg, use_quantization=use_quantization).to(device) if "__odpe_packed_version__" in state: unpack_quantized_state_dict(model, state) else: model.load_state_dict({k: v.to(device) for k, v in state.items()}, strict=False) for layer in model.modules(): if hasattr(layer, "reallocate_blocks") and getattr(layer, "use_quantization", False): layer.reallocate_blocks() model.eval() return model, tokenizer @torch.no_grad() def predict_nli( model: BilingualNLITransformer, tokenizer: Tokenizer, premise: str, hypothesis: str, device: str | torch.device = "cpu", max_len: int = 128, ) -> Dict[str, object]: """Run single-pair Russian or English NLI prediction.""" pad_id = tokenizer.token_to_id(PAD_TOKEN) cls_id = tokenizer.token_to_id(CLS_TOKEN) sep_id = tokenizer.token_to_id(SEP_TOKEN) p_ids = tokenizer.encode(premise).ids h_ids = tokenizer.encode(hypothesis).ids budget = max_len - 3 while len(p_ids) + len(h_ids) > budget: if len(p_ids) > len(h_ids): p_ids = p_ids[:-1] else: h_ids = h_ids[:-1] seq = [cls_id] + p_ids + [sep_id] + h_ids + [sep_id] seg = [0] * (len(p_ids) + 2) + [1] * (len(h_ids) + 1) mask = [True] * len(seq) pad_len = max_len - len(seq) input_ids = torch.tensor([seq + [pad_id] * pad_len], dtype=torch.long, device=device) token_type_ids = torch.tensor([seg + [0] * pad_len], dtype=torch.long, device=device) attention_mask = torch.tensor([mask + [False] * pad_len], dtype=torch.bool, device=device) logits = model(input_ids, token_type_ids, attention_mask) probs = F.softmax(logits, dim=-1)[0].tolist() pred_id = int(max(range(len(probs)), key=lambda i: probs[i])) return { "label": ID2LABEL[pred_id], "probabilities": {ID2LABEL[i]: float(p) for i, p in enumerate(probs)}, } if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--checkpoint", type=str, default=str(PROJECT_DIR / "checkpoints" / "adaptive_v6_100m_best_val.safetensors"), ) parser.add_argument("--config", type=str, default=None) parser.add_argument("--classical", action="store_true") parser.add_argument("--premise", type=str, default="Машина быстро едет по трассе.") parser.add_argument("--hypothesis", type=str, default="Транспортное средство движется.") args = parser.parse_args() dev = "cuda" if torch.cuda.is_available() else "cpu" mdl, tok = load_nli_model( args.checkpoint, use_quantization=not args.classical, device=dev, config_path=args.config ) print(predict_nli(mdl, tok, args.premise, args.hypothesis, device=dev))