Ekmek commited on
Hızlı çıkarım: işlemcide int8, ekran kartında CUDA graph
Browse filesFiles changed (5)
- README.md+11-6
- chat.py+32-13
- model_cpu_int8.onnxAdded+3
- requirements.txt+1
- trenet/fast.pyAdded+96
51 unmodified lines525354555657582 unmodified lines6162636465666768697071727374757677787951 unmodified lines## Kullanım```bashpip install torch tokenizers safetensorspython chat.py```2 unmodified lines## HızModel küçük olduğu için ekran kartı şart değil; işlemcide de akıcı çalışır. Masaüstü bir işlemcide (Intel Core Ultra 7 265KF)`chat.py` ile ölçülen üretim hızı:| Ortam | Hız ||---|---|| İşlemci, 4-8 çekirdek | ~97 token/sn (en fazla ~98) || İşlemci, 1 çekirdek | ~80 token/sn |## Dosyalar| Dosya | İçerik ||---|---|| `model.safetensors` | Ağırlıklar || `config.json` | Model yapılandırması || `tokenizer.json` | Türkçe tokenizer || `trenet/`, `chat.py` | Modeli çalıştırmak için gereken kod |51 unmodified lines525354555657582 unmodified lines61626364656667686970717273747576777879808182838451 unmodified lines## Kullanım```bashpip install torch tokenizers safetensors onnxruntimepython chat.py```2 unmodified lines## HızModel küçük olduğu için ekran kartı şart değil. `chat.py` kendiliğinden hızlı yolu seçer:işlemcide 8 bit (int8) ONNX sürümü (`onnxruntime` gerekir), ekran kartında CUDA graph.| Ortam | Üretim hızı ||---|---|| İşlemci (Intel Core Ultra 7 265KF, 4 çekirdek), int8 | ~400-500 token/sn || Ekran kartı (RTX 5070 Ti) | ~550-600 token/sn || Ekran kartı, `--compile` | ~900 token/sn'ye kadar |İşlemcideki int8 sürümü tam hassasiyetli modele çok yakın cevaplar verir (kayıp ~%1). Tam hassasiyet için `--slow`(yaklaşık 85 token/sn).## Dosyalar| Dosya | İçerik ||---|---|| `model.safetensors` | Ağırlıklar || `model_cpu_int8.onnx` | İşlemci için hızlı, 8 bitlik sürüm || `config.json` | Model yapılandırması || `tokenizer.json` | Türkçe tokenizer || `trenet/`, `chat.py` | Modeli çalıştırmak için gereken kod |
1 unmodified line2345679 unmodified lines17181920212223242526276 unmodified lines34353637383940414243444546474849505152533 unmodified lines575859606162636465666768695 unmodified lines757677787980818283841 unmodified linepython chat.pypython chat.py --temperature 0.3 --no-calculatorKomutlar: /yeni (geçmişi sil), /sicaklik 0.5, /cik"""import argparse9 unmodified linessys.path.insert(0, ROOT)from trenet import build_model # noqa: E402from trenet.common import sample # noqa: E402from chat_calculator import ChatCalculator # noqa: E402class ChatModel:def __init__(self, folder=ROOT, device=None):cfg = json.load(open(os.path.join(folder, "config.json"), encoding="utf-8"))self.dev = device or ("cuda" if torch.cuda.is_available() else "cpu")self.model = build_model(cfg)6 unmodified linesself.digit_ids = {i for t, i in self.tok.get_vocab().items() if t.lstrip("Ġ").isdigit()}self.max_ctx = cfg["max_context"]self.name = cfg.get("name", "trenet")@torch.no_grad()def reply(self, history, user_msg, max_new=200, temperature=0.3, top_k=40, rep_penalty=1.15, no_repeat=4):text = "".join(f"<|user|>\n{u}\n<|assistant|>\n{a}\n" for u, a in history)text += f"<|user|>\n{user_msg}\n<|assistant|>\n"ids = self.tok.encode(text).ids[-(self.max_ctx - max_new):]m = self.modelidx = torch.tensor([ids], device=self.dev)cache = m.init_cache(1, idx.size(1) + max_new + 1, dtype=next(m.parameters()).dtype)logits = m.forward_step(idx, cache, 0)[:, -1].float()out, pos = [], idx.size(1)for _ in range(max_new):if rep_penalty != 1.0 and out: # tekrar cezasırecent = torch.tensor(out[-64:], device=self.dev).unique()vals = logits[0, recent]logits[0, recent] = torch.where(vals > 0, vals / rep_penalty, vals * rep_penalty)if no_repeat and len(out) >= no_repeat - 1: # n-gram tekrar yasağı (rakamlar hariç)3 unmodified linesif tuple(out[i:i + no_repeat - 1]) == ctx} - self.digit_idsif banned:logits[0, list(banned)] = -float("inf")nxt = sample(logits, temperature, top_k)t = nxt.item()if t in self.stop:breakout.append(t)logits = m.forward_step(nxt, cache, pos)[:, -1].float()pos += 1text = self.tok.decode(out, skip_special_tokens=False).split("<|assistant|>")[0]if "<|/think|>" in text:text = text.split("<|/think|>", 1)[1]5 unmodified linesap.add_argument("--temperature", type=float, default=0.3)ap.add_argument("--no-calculator", action="store_true", help="dört işlemi de modelin kendisi cevaplasın")ap.add_argument("--device", default=None, help="cuda | cpu (varsayılan: varsa cuda)")args = ap.parse_args()bot = ChatModel(device=args.device)temp = args.temperatureprint(f"{bot.name} ({bot.model.num_params() / 1e6:.1f}M parametre, {bot.dev})")print("komutlar: /yeni /sicaklik <x> /cik\n")history = []calc = None if args.no_calculator else ChatCalculator()1 unmodified line234567899 unmodified lines1920212223242526272829306 unmodified lines373839404142434445464748495051525354555657585960616263646566676869703 unmodified lines74757677787980818283845 unmodified lines909192939495969798991001011021031 unmodified linepython chat.pypython chat.py --temperature 0.3 --no-calculatorpython chat.py --device cpu (işlemci: int8 ONNX ile hızlı yol, onnxruntime gerekir)python chat.py --compile (ekran kartı: en hızlı yol)Komutlar: /yeni (geçmişi sil), /sicaklik 0.5, /cik"""import argparse9 unmodified linessys.path.insert(0, ROOT)from trenet import build_model # noqa: E402from trenet.common import sample # noqa: E402from trenet.fast import GraphEngine, OnnxEngine, TorchEngine # noqa: E402from chat_calculator import ChatCalculator # noqa: E402class ChatModel:def __init__(self, folder=ROOT, device=None, engine="auto", compile=False, threads=None):cfg = json.load(open(os.path.join(folder, "config.json"), encoding="utf-8"))self.dev = device or ("cuda" if torch.cuda.is_available() else "cpu")self.model = build_model(cfg)6 unmodified linesself.digit_ids = {i for t, i in self.tok.get_vocab().items() if t.lstrip("Ġ").isdigit()}self.max_ctx = cfg["max_context"]self.name = cfg.get("name", "trenet")onnx_path = os.path.join(folder, "model_cpu_int8.onnx")self.engine_name = "torch"self.engine = Noneif engine == "auto" and self.dev == "cuda":try:self.engine = GraphEngine(self.model, self.max_ctx + 1, compile=compile)self.engine_name = "cuda graph" + (" + compile" if compile else "")except Exception as e: # noqa: BLE001print(f"(hızlı GPU yolu açılamadı: {e})")elif engine == "auto" and self.dev == "cpu" and os.path.exists(onnx_path):try:self.engine = OnnxEngine(self.model, onnx_path, threads)self.engine_name = "onnx int8"except ImportError:print("(onnxruntime kurulu değil; yavaş yol kullanılıyor: pip install onnxruntime)")if self.engine is None:self.engine = TorchEngine(self.model, self.max_ctx + 1)@torch.no_grad()def reply(self, history, user_msg, max_new=200, temperature=0.3, top_k=40, rep_penalty=1.15, no_repeat=4):text = "".join(f"<|user|>\n{u}\n<|assistant|>\n{a}\n" for u, a in history)text += f"<|user|>\n{user_msg}\n<|assistant|>\n"ids = self.tok.encode(text).ids[-(self.max_ctx - max_new):]logits = self.engine.start(ids)[None]out = []for _ in range(max_new):if rep_penalty != 1.0 and out: # tekrar cezasırecent = torch.tensor(out[-64:]).unique()vals = logits[0, recent]logits[0, recent] = torch.where(vals > 0, vals / rep_penalty, vals * rep_penalty)if no_repeat and len(out) >= no_repeat - 1: # n-gram tekrar yasağı (rakamlar hariç)3 unmodified linesif tuple(out[i:i + no_repeat - 1]) == ctx} - self.digit_idsif banned:logits[0, list(banned)] = -float("inf")t = sample(logits, temperature, top_k).item()if t in self.stop:breakout.append(t)logits = self.engine.step(t)[None].clone()text = self.tok.decode(out, skip_special_tokens=False).split("<|assistant|>")[0]if "<|/think|>" in text:text = text.split("<|/think|>", 1)[1]5 unmodified linesap.add_argument("--temperature", type=float, default=0.3)ap.add_argument("--no-calculator", action="store_true", help="dört işlemi de modelin kendisi cevaplasın")ap.add_argument("--device", default=None, help="cuda | cpu (varsayılan: varsa cuda)")ap.add_argument("--compile", action="store_true", help="GPU'da derleyerek daha da hızlandır (ilk açılış ~20 sn)")ap.add_argument("--slow", action="store_true", help="hızlandırma kullanma, düz PyTorch")ap.add_argument("--threads", type=int, default=None, help="işlemci çekirdek sayısı (varsayılan 4)")args = ap.parse_args()bot = ChatModel(device=args.device, engine="torch" if args.slow else "auto", compile=args.compile,threads=args.threads)temp = args.temperatureprint(f"{bot.name} ({bot.model.num_params() / 1e6:.1f}M parametre, {bot.dev}, {bot.engine_name})")print("komutlar: /yeni /sicaklik <x> /cik\n")history = []calc = None if args.no_calculator else ChatCalculator()
123version https://git-lfs.github.com/spec/v1oid sha256:84a8f74a0b7137359a28f884afe6fbb7e398fc1d29e64d9ae4fb32b961d12661size 38793062123torch>=2.2tokenizerssafetensors1234torch>=2.2tokenizerssafetensorsonnxruntime
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import os
import numpy as npimport torch
from .common import GraphDecoder
class OnnxEngine:
def __init__(self, model, path, threads=None): import onnxruntime as ort so = ort.SessionOptions() so.intra_op_num_threads = threads or min(4, os.cpu_count() or 4) so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL self.sess = ort.InferenceSession(path, so, providers=["CPUExecutionProvider"]) c = model.config self.model = model self.R = c.kv_rank self.nl = c.n_layers self.cos = model.cos.float().cpu().numpy() self.sin = model.sin.float().cpu().numpy() self.cache = [np.zeros((c.max_seq_len, c.kv_rank + c.qk_rope_dim), np.float32) for _ in range(self.nl)] self.pos = 0
@torch.no_grad() def start(self, ids): n = len(ids) cache = self.model.init_cache(1, n, dtype=torch.float32) logits = self.model.forward_step(torch.tensor([ids]), cache, 0)[0, -1] for i, lc in enumerate(cache["main"]): self.cache[i][:n, :self.R] = lc.c[0, :n].numpy() self.cache[i][:n, self.R:] = lc.kr[0, 0, :n].numpy() self.pos = n return logits.float()
def step(self, tok): p = self.pos feed = {"tok": np.array([tok], np.int64), "cos": self.cos[p], "sin": self.sin[p]} for i in range(self.nl): feed[f"c{i}"] = self.cache[i][:p] r = self.sess.run(None, feed) for i in range(self.nl): self.cache[i][p] = r[1 + i][0] self.pos = p + 1 return torch.from_numpy(r[0][0])
class GraphEngine:
def __init__(self, model, max_len, compile=False): if compile: model.compile_blocks(dynamic=True) self.model = model self.dev = next(model.parameters()).device self.cache = model.init_cache(1, max_len, dtype=next(model.parameters()).dtype) self.graph = GraphDecoder(model, self.cache, 1) self.tok = torch.zeros(1, 1, dtype=torch.long, device=self.dev) self.pos = 0 if compile: for n in (5, 9, 17): self.start([0] * n)
@torch.no_grad() def start(self, ids): logits = self.model.forward_step(torch.tensor([ids], device=self.dev), self.cache, 0)[0, -1] self.pos = len(ids) return logits.float().cpu()
def step(self, tok): self.tok.fill_(tok) out = self.graph(self.tok, self.pos) self.pos += 1 return out[0, -1].float().cpu()
class TorchEngine:
def __init__(self, model, max_len): self.model = model self.dev = next(model.parameters()).device self.dtype = next(model.parameters()).dtype self.max_len = max_len
@torch.no_grad() def start(self, ids): self.cache = self.model.init_cache(1, self.max_len, dtype=self.dtype) logits = self.model.forward_step(torch.tensor([ids], device=self.dev), self.cache, 0)[0, -1] self.pos = len(ids) return logits.float().cpu()
@torch.no_grad() def step(self, tok): out = self.model.forward_step(torch.tensor([[tok]], device=self.dev), self.cache, self.pos) self.pos += 1 return out[0, -1].float().cpu()README.md+11-6
chat.py+32-13
model_cpu_int8.onnxAdded+3
requirements.txt+1
trenet/fast.pyAdded+96