Upload handler.py with huggingface_hub
Browse files- handler.py +75 -0
handler.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from typing import Dict, List, Any
|
| 3 |
+
from transformers import AutoTokenizer, AutoConfig, AutoModelForSeq2SeqLM
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
# 1. Define Architecture Patch
|
| 9 |
+
class RMSNorm(nn.Module):
|
| 10 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 11 |
+
super().__init__()
|
| 12 |
+
self.dim = dim
|
| 13 |
+
self.eps = eps
|
| 14 |
+
self.scale = nn.Parameter(torch.ones(dim))
|
| 15 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 16 |
+
rms = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 17 |
+
return x / rms * self.scale
|
| 18 |
+
|
| 19 |
+
def replace_layernorm_with_rmsnorm(module: nn.Module):
|
| 20 |
+
for name, child in list(module.named_children()):
|
| 21 |
+
if isinstance(child, nn.LayerNorm):
|
| 22 |
+
dim = child.normalized_shape[0] if isinstance(child.normalized_shape, (tuple, list)) else child.normalized_shape
|
| 23 |
+
rms = RMSNorm(dim=dim, eps=1e-6)
|
| 24 |
+
setattr(module, name, rms)
|
| 25 |
+
else:
|
| 26 |
+
replace_layernorm_with_rmsnorm(child)
|
| 27 |
+
|
| 28 |
+
# 2. Define The Glue Logic (UPDATED)
|
| 29 |
+
def fix_arabic_output(text):
|
| 30 |
+
if not text: return text
|
| 31 |
+
# Glue Prefixes (Next word)
|
| 32 |
+
prefix_pattern = r'(^|\s)(ال|لل|وال|بال)\s+(?=\S)'
|
| 33 |
+
text = re.sub(prefix_pattern, r'\1\2', text)
|
| 34 |
+
text = re.sub(prefix_pattern, r'\1\2', text)
|
| 35 |
+
# Glue Punctuation (Previous word)
|
| 36 |
+
punctuation_pattern = r'\s+([،؟!.,])'
|
| 37 |
+
text = re.sub(punctuation_pattern, r'\1', text)
|
| 38 |
+
return text.strip()
|
| 39 |
+
|
| 40 |
+
class EndpointHandler:
|
| 41 |
+
def __init__(self, path=""):
|
| 42 |
+
config = AutoConfig.from_pretrained(path)
|
| 43 |
+
self.model = AutoModelForSeq2SeqLM.from_config(config)
|
| 44 |
+
replace_layernorm_with_rmsnorm(self.model)
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
from safetensors.torch import load_file
|
| 48 |
+
import os
|
| 49 |
+
w_path = os.path.join(path, "model.safetensors")
|
| 50 |
+
if os.path.exists(w_path):
|
| 51 |
+
self.model.load_state_dict(load_file(w_path), strict=False) #Must be false
|
| 52 |
+
else:
|
| 53 |
+
self.model.load_state_dict(torch.load(os.path.join(path, "pytorch_model.bin"), map_location="cpu"), strict=True)
|
| 54 |
+
except:
|
| 55 |
+
# Fallback
|
| 56 |
+
self.model = AutoModelForSeq2SeqLM.from_pretrained(path)
|
| 57 |
+
replace_layernorm_with_rmsnorm(self.model)
|
| 58 |
+
|
| 59 |
+
self.tokenizer = AutoTokenizer.from_pretrained(path)
|
| 60 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 61 |
+
self.model.to(self.device).eval()
|
| 62 |
+
|
| 63 |
+
def __call__(self, data: Any) -> List[Dict[str, Any]]:
|
| 64 |
+
inputs = data.pop("inputs", data)
|
| 65 |
+
if isinstance(inputs, str): inputs = [inputs]
|
| 66 |
+
|
| 67 |
+
tokenized_inputs = self.tokenizer(inputs, return_tensors="pt", padding=True).to(self.device)
|
| 68 |
+
if "token_type_ids" in tokenized_inputs: del tokenized_inputs["token_type_ids"]
|
| 69 |
+
|
| 70 |
+
with torch.no_grad():
|
| 71 |
+
generated_ids = self.model.generate(**tokenized_inputs, max_new_tokens=128, num_beams=5, early_stopping=True)
|
| 72 |
+
|
| 73 |
+
decoded_outputs = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
| 74 |
+
final_outputs = [fix_arabic_output(text) for text in decoded_outputs]
|
| 75 |
+
return [{"generated_text": text} for text in final_outputs]
|