fix problem from claude
This commit is contained in:
@@ -1,46 +1,100 @@
|
||||
import threading
|
||||
|
||||
import torch
|
||||
|
||||
from app.config.logging import logger
|
||||
from app.ml.model_manager import model_manager
|
||||
from app.ml.prediction_result import PredictionResult
|
||||
|
||||
# Длинный текст режем на перекрывающиеся окна: раньше всё после первых
|
||||
# 512 токенов модель не видела. Окно 128, а не 512: в длинном окне одна
|
||||
# токсичная фраза «тонет» в нейтральном тексте (проверено на textdetox:
|
||||
# фраза в конце ~1000 токенов — 0.06 при окне 512 и 0.99 при 128).
|
||||
# Короткие тексты (до ~126 токенов) идут в модель как раньше.
|
||||
MAX_TOKENS = 128
|
||||
WINDOW_STRIDE = 32
|
||||
|
||||
|
||||
def split_windows(ids: list[int], size: int, overlap: int) -> list[list[int]]:
|
||||
"""Перекрывающиеся окна по size токенов; последнее окно всегда до конца текста."""
|
||||
if len(ids) <= size:
|
||||
return [ids]
|
||||
step = max(size - overlap, 1)
|
||||
starts = list(range(0, len(ids) - size + 1, step))
|
||||
if starts[-1] + size < len(ids):
|
||||
starts.append(len(ids) - size)
|
||||
return [ids[start:start + size] for start in starts]
|
||||
|
||||
|
||||
def toxic_label_index(id2label: dict) -> int:
|
||||
"""Индекс класса «токсично»: по имени метки, иначе класс 1 (так у textdetox)."""
|
||||
for index, label in id2label.items():
|
||||
name = str(label).lower()
|
||||
if "toxic" in name and not name.startswith(("non", "not")):
|
||||
return int(index)
|
||||
return 1
|
||||
|
||||
|
||||
class TextClassifier:
|
||||
def predict(self, text: str):
|
||||
inputs = model_manager.text_tokenizer(
|
||||
text,
|
||||
return_tensors="pt",
|
||||
truncation=True,
|
||||
max_length=512,
|
||||
padding=True
|
||||
|
||||
def __init__(self):
|
||||
# Быстрый токенизатор HF не потокобезопасен при truncation/padding:
|
||||
# параллельные вызовы падают с «RuntimeError: Already borrowed».
|
||||
self._tokenizer_lock = threading.Lock()
|
||||
|
||||
def predict(self, text: str) -> PredictionResult:
|
||||
tokenizer = model_manager.text_tokenizer
|
||||
# Окна режем сами: return_overflowing_tokens у токенизаторов transformers 5
|
||||
# отдаёт не все куски, и конец текста модель не видела
|
||||
with self._tokenizer_lock:
|
||||
ids = tokenizer(
|
||||
text,
|
||||
add_special_tokens=False,
|
||||
truncation=False,
|
||||
verbose=False
|
||||
)["input_ids"]
|
||||
# Шаблон спецтокенов одиночной последовательности: [CLS] … [SEP]
|
||||
special = tokenizer("")["input_ids"]
|
||||
|
||||
prefix, suffix = special[:1], special[1:]
|
||||
windows = [
|
||||
prefix + window + suffix
|
||||
for window in split_windows(ids, MAX_TOKENS - len(special), WINDOW_STRIDE)
|
||||
]
|
||||
|
||||
width = max(len(window) for window in windows)
|
||||
pad_id = tokenizer.pad_token_id or 0
|
||||
input_ids = torch.tensor(
|
||||
[window + [pad_id] * (width - len(window)) for window in windows]
|
||||
)
|
||||
attention_mask = torch.tensor(
|
||||
[[1] * len(window) + [0] * (width - len(window)) for window in windows]
|
||||
)
|
||||
|
||||
inputs = {
|
||||
key: value.to(model_manager.device)
|
||||
for key, value in inputs.items()
|
||||
"input_ids": input_ids.to(model_manager.device),
|
||||
"attention_mask": attention_mask.to(model_manager.device),
|
||||
}
|
||||
|
||||
print(inputs)
|
||||
|
||||
with torch.no_grad():
|
||||
with torch.inference_mode():
|
||||
outputs = model_manager.text_model(**inputs)
|
||||
|
||||
print(outputs)
|
||||
|
||||
# [окна × классы]; итог — самое токсичное окно
|
||||
probabilities = torch.softmax(outputs.logits, dim=1)
|
||||
print("Labels:", model_manager.text_model.config.id2label)
|
||||
print("Logits:", outputs.logits)
|
||||
print("Probabilities:", probabilities)
|
||||
id2label = model_manager.text_model.config.id2label
|
||||
toxic_index = toxic_label_index(id2label)
|
||||
|
||||
print(probabilities)
|
||||
raw_scores = probabilities[0].tolist()
|
||||
score = raw_scores[1]
|
||||
window = int(torch.argmax(probabilities[:, toxic_index]).item())
|
||||
raw_scores = probabilities[window].tolist()
|
||||
score = raw_scores[toxic_index]
|
||||
|
||||
label = (
|
||||
model_manager.text_model.config.id2label.get(1, "LABEL_1")
|
||||
logger.debug(
|
||||
"Text toxicity: windows=%d, score=%.4f",
|
||||
probabilities.shape[0], score
|
||||
)
|
||||
|
||||
return PredictionResult(
|
||||
label=label,
|
||||
label=id2label.get(toxic_index, f"LABEL_{toxic_index}"),
|
||||
score=score,
|
||||
approved=False,
|
||||
raw_scores=raw_scores
|
||||
|
||||
Reference in New Issue
Block a user