Spaces:
Sleeping
Sleeping
Download src/decision_model/encoding.py from xstard/decision-model: direct link, hf CLI and curl.
- Browser
- Download file 3.78 kB
-
https://huggingface.co/spaces/xstard/decision-model/resolve/main/src/decision_model/encoding.py
- Command line
-
hf download hf://spaces/xstard/decision-model/src/decision_model/encoding.py
-
curl -L -o encoding.py https://huggingface.co/spaces/xstard/decision-model/resolve/main/src/decision_model/encoding.py
3.78 kB
| 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) | |
| 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) | |