Spaces:
Sleeping
Sleeping
File size: 3,777 Bytes
4df9b63 | 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 | from dataclasses import dataclass
import numpy as np
from .schemas import NoulQuestion, ChoiceQuestion
from .settings import ENCODER_ID, ENCODER_REVISION, MAX_TOKENS, HUB_CACHE, TEMPLATE_VERSION
class InputTooLong(ValueError):
pass
def candidates(question):
if isinstance(question, NoulQuestion):
return ["no", "yes"], ["No / Ні", "Yes / Так"]
if isinstance(question, ChoiceQuestion):
return list(question.criteria), list(question.criteria.values())
return [str(i) for i in range(len(question.criteria))], list(question.criteria)
def render_question(state, question):
ids, descriptions = candidates(question)
text = f"<|input|>\n{state}\n<|question|>\n{question.instructions}\n"
spans = []
for description in descriptions:
text += "<|choice|>\n"
start = len(text)
text += description
spans.append((start, len(text)))
text += "\n"
return text, spans, ids
def candidate_masks(offsets, spans):
masks = np.array([
[int(end > start and start >= left and end <= right) for start, end in offsets]
for left, right in spans
], dtype=bool)
if not masks.any(axis=1).all():
raise ValueError("Варіант відповіді не містить доступних токенів.")
return masks
def mean_pool(hidden, masks):
weights = np.asarray(masks, dtype=np.float32)
return weights @ np.asarray(hidden) / weights.sum(axis=1, keepdims=True)
@dataclass
class EncodedQuestion:
features: np.ndarray
input_tokens: int
class CandidateEncoder:
def __init__(self, model_id=ENCODER_ID, revision=None, device="cpu", cache_dir=None):
import torch
from huggingface_hub import HfApi
from transformers import AutoConfig, AutoModel, AutoTokenizer
self.model_id = model_id
self.device = device
self.cache_dir = str(cache_dir or HUB_CACHE)
self.revision = revision or ENCODER_REVISION
self.tokenizer = AutoTokenizer.from_pretrained(
model_id, revision=self.revision, cache_dir=self.cache_dir, use_fast=True,
trust_remote_code=False,
)
if not self.tokenizer.is_fast:
raise ValueError("Потрібен fast tokenizer з offset_mapping.")
config = AutoConfig.from_pretrained(model_id, revision=self.revision, cache_dir=self.cache_dir)
config.reference_compile = False
self.model = AutoModel.from_pretrained(
model_id, revision=self.revision, cache_dir=self.cache_dir, config=config,
dtype=torch.float32, attn_implementation="sdpa", trust_remote_code=False,
).to(device)
self.model.requires_grad_(False)
self.model.eval()
self.hidden_size = config.hidden_size
def encode(self, state, question):
import torch
text, spans, _ = render_question(state, question)
tokens = self.tokenizer(text, return_offsets_mapping=True, truncation=False)
count = len(tokens["input_ids"])
if count > MAX_TOKENS:
raise InputTooLong(f"Запитання займає {count} токенів; максимум {MAX_TOKENS}. Скоротіть текст або критерії.")
masks = candidate_masks(tokens.pop("offset_mapping"), spans)
tensors = {key: torch.tensor([value], device=self.device) for key, value in tokens.items()}
self.model.eval()
with torch.inference_mode():
hidden = self.model(**tensors).last_hidden_state[0]
weights = torch.tensor(masks, dtype=hidden.dtype, device=self.device)
pooled = weights @ hidden / weights.sum(dim=1, keepdim=True)
return EncodedQuestion(pooled.float().cpu().numpy(), count)
|