Views
No views yet
" → ") and splits bilingual text lines into separate lists.|, tabs \t) into a unified format for consistent parsing.[music]) and promotional phrases (e.g., اشترك في القناة).
model.shared.weight) during the loading state, ensuring semantic alignment.| Metric | Score | Note |
|---|---|---|
| BLEU Score | 28.5 | View Kaggle Logs |
| Validation Loss | 2.18 | Stable convergence |
| Training Loss | 2.33 |
| Type | English Input | Model Output (Masri) | Notes |
|---|---|---|---|
| Good | "Get in the car, we have to go now!" | "ادخل العربية، لازم نمشي دلوقتي!" | Captures urgency and dialect terms. |
| Good | "I have a very bad feeling about this." | "عندي إحساس وحش أوي بخصوص الموضوع ده." | Natural phrasing. |
| Good | "Why are you doing this?" | "انت بتعمل كده ليه؟" | Correct question structure. |
| Bad | "The mitochondria is the powerhouse of the cell." | "الأرياريا هو كتلة الخلايا الجذعية" | Limitation: Struggles with scientific terms. |
| Bad | "Complex philosophical prose with archaic terms." | "الأفكار الفلسفية بالمصطلحات القديمة" | Limitation: Acceptable but not optimized for complex phrasing. |
torch>=2.0.0, transformers>=4.30.01import torch
2import torch.nn as nn
3import re
4from transformers import AutoTokenizer, AutoConfig, AutoModelForSeq2SeqLM
5from safetensors.torch import load_file
6from huggingface_hub import hf_hub_download
7
8# 1. Define Architecture Components
9class 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
19def load_patched_model(repo_id):
20 device = "cuda" if torch.cuda.is_available() else "cpu"
21
22 # Load Config and fix Token IDs (overriding config.json errors)
23 config = AutoConfig.from_pretrained(repo_id)
24
25 tokenizer = AutoTokenizer.from_pretrained(repo_id)
26 model = AutoModelForSeq2SeqLM.from_config(config)
27
28 # Patch LayerNorm -> RMSNorm
29 for name, child in list(model.named_children()):
30 def patch_recursive(m):
31 for n, c in list(m.named_children()):
32 if isinstance(c, nn.LayerNorm):
33 dim = c.normalized_shape[0] if isinstance(c.normalized_shape, (tuple, list)) else c.normalized_shape
34 setattr(m, n, RMSNorm(dim))
35 else:
36 patch_recursive(c)
37 patch_recursive(model)
38
39 # Load Weights
40 try:
41 f = hf_hub_download(repo_id, "model.safetensors")
42 model.load_state_dict(load_file(f), strict=False)
43 except:
44 f = hf_hub_download(repo_id, "pytorch_model.bin")
45 model.load_state_dict(torch.load(f, map_location="cpu"), strict=False)
46
47 return model.to(device).eval(), tokenizer
48
49def fix_arabic(text):
50 if not text: return text
51 # Re-connect prefixes and fix punctuation
52 text = re.sub(r'(^|\s)(ال|لل|وال|بال)\s+(?=\S)', r'\1\2', text)
53 text = re.sub(r'\s+([،؟!.,])', r'\1', text)
54 return text.strip()
55
56# 2. Run Inference
57REPO_NAME = "Shams03/EgyLated"
58model, tokenizer = load_patched_model(REPO_NAME)
59
60def translate(text):
61 inputs = tokenizer(text, return_tensors="pt").to(model.device)
62 if "token_type_ids" in inputs: del inputs["token_type_ids"]
63
64 with torch.no_grad():
65 out = model.generate(
66 **inputs,
67 max_new_tokens=128,
68 num_beams=5,
69 early_stopping=True,
70 )
71
72 raw = tokenizer.decode(out[0], skip_special_tokens=True)
73 return fix_arabic(raw)
74
75print(translate("I am really happy because the model works."))
76# Output: "أنا مبسوط جدا عشان الموديل شغال"