aigencydev commited on
Commit
14ac35b
·
verified ·
1 Parent(s): a695171

egitim/: v2 betikleri ve veri ozetleri

Browse files
Files changed (1) hide show
  1. egitim/gguf_uret.py +96 -0
egitim/gguf_uret.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Genel GGUF uretici (erk14b_gguf.py'nin parametreli hali): SRC -> BF16 GGUF -> nicemler -> kimlik(6) + NLL dogrulama.
3
+ Kullanim: SRC=<model dizini> CIKTI=<gguf dizini> AD=Erk-14B NICEM=Q4_K_M,Q3_K_M BOYUT=14 python gguf_uret.py
4
+ Kimlik sablonu: tokenizer_config'te '{#- erk-varsayilan-sistem -#}' isareti varsa dokunulmaz, yoksa eklenir."""
5
+ import os, json, subprocess, time, shutil
6
+ KOK = "/ari/users/ytanis"
7
+ SRC = os.environ["SRC"]; CIKTI = os.environ["CIKTI"]; AD = os.environ["AD"]
8
+ NICEM = [x for x in os.environ.get("NICEM", "Q4_K_M,Q3_K_M").split(",") if x]
9
+ BOYUT = os.environ.get("BOYUT", AD.split("-")[-1].rstrip("B"))
10
+ KAYNAK = CIKTI + "-kaynak"
11
+ PY_TORCH = KOK + "/envs/torch/bin/python"; PY_GGUF = KOK + "/envs/gguf/bin/python"
12
+ DONUSTUR = KOK + "/llama.cpp/convert_hf_to_gguf.py"; NLL_METIN = KOK + "/erk/nll_ornek.txt"
13
+ os.makedirs(KAYNAK, exist_ok=True); os.makedirs(CIKTI, exist_ok=True); t0 = time.time()
14
+ def adim(ad): print("\n=== %s | %.0f dk ===" % (ad, (time.time() - t0) / 60), flush=True)
15
+ adim("kaynak dizin")
16
+ for f in os.listdir(SRC):
17
+ if f.endswith(".safetensors") or f in ("model.safetensors.index.json", "tokenizer.json", "vocab.json", "merges.txt", "generation_config.json", "chat_template.jinja"):
18
+ h = os.path.join(KAYNAK, f)
19
+ if not os.path.exists(h): os.symlink(os.path.join(SRC, f), h)
20
+ cfg = json.load(open(SRC + "/config.json"))
21
+ cfg["architectures"] = ["Qwen3ForCausalLM"]; cfg["model_type"] = "qwen3"; cfg.pop("auto_map", None)
22
+ json.dump(cfg, open(KAYNAK + "/config.json", "w"), indent=2)
23
+ SISTEM = ("Sen %s'sin: eCloud Tech. tarafından, açık kaynaklı Qwen3-%sB temel modeli üzerine Türkçe devam-eğitimi ve "
24
+ "talimat ayarıyla geliştirilmiş %s milyar parametreli bir Türkçe dil modelisin. Kimliğin, seni kimin geliştirdiği "
25
+ "ya da temel modelin sorulduğunda bunu açıkça söyle; başka bir şirketin modeli olduğunu asla iddia etme.") % (AD, BOYUT, BOYUT)
26
+ tc = json.load(open(SRC + "/tokenizer_config.json", encoding="utf-8"))
27
+ s = tc.get("chat_template") or open(SRC + "/chat_template.jinja", encoding="utf-8").read()
28
+ if "erk-varsayilan-sistem" not in s:
29
+ j = SISTEM.replace("\\", "\\\\").replace("'", "\\'")
30
+ eski_a = " {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n"
31
+ yeni_a = " {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- else %}\n {{- '" + j + "' + '\\n\\n' }}\n {%- endif %}\n"
32
+ eski_b = " {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n"
33
+ yeni_b = " {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\n' + '" + j + "' + '<|im_end|>\\n' }}\n {%- endif %}\n"
34
+ for e, y, ad in ((eski_a, yeni_a, "arac dali"), (eski_b, yeni_b, "normal dal")):
35
+ assert s.count(e) == 1, "%s: hedef blok tam bir kez bulunmali (bulunan %d)" % (ad, s.count(e))
36
+ s = s.replace(e, y)
37
+ s = "{#- erk-varsayilan-sistem -#}\n" + s
38
+ tc["chat_template"] = s
39
+ json.dump(tc, open(KAYNAK + "/tokenizer_config.json", "w", encoding="utf-8"), ensure_ascii=False, indent=2)
40
+ if os.path.exists(KAYNAK + "/chat_template.jinja"): os.remove(KAYNAK + "/chat_template.jinja")
41
+ from transformers import AutoTokenizer
42
+ tok = AutoTokenizer.from_pretrained(KAYNAK)
43
+ a = tok.apply_chat_template([{"role": "user", "content": "Kimsin?"}], tokenize=False, add_generation_prompt=True)
44
+ b = tok.apply_chat_template([{"role": "system", "content": "Sen bir çevirmensin."}, {"role": "user", "content": "Kimsin?"}], tokenize=False, add_generation_prompt=True)
45
+ assert AD in a and a.count("<|im_start|>system") == 1 and AD not in b and "çevirmensin" in b
46
+ print("sablon: varsayilan girer / kullanici istemi korunur", flush=True)
47
+ bf16 = "%s/%s-BF16.gguf" % (CIKTI, AD)
48
+ if not os.path.exists(bf16):
49
+ adim("BF16 GGUF donusumu"); subprocess.run([PY_TORCH, DONUSTUR, KAYNAK, "--outfile", bf16, "--outtype", "bf16"], check=True)
50
+ print("BF16: %.1f GB" % (os.path.getsize(bf16) / 1e9), flush=True)
51
+ NICEM_KOD = r'''
52
+ import sys, llama_cpp
53
+ src, dst, tur = sys.argv[1], sys.argv[2], sys.argv[3]
54
+ p = llama_cpp.llama_model_quantize_default_params()
55
+ p.ftype = getattr(llama_cpp, "LLAMA_FTYPE_MOSTLY_" + tur); p.nthread = 16
56
+ r = llama_cpp.llama_model_quantize(src.encode(), dst.encode(), p); print("quantize", tur, "donus", r); sys.exit(r)
57
+ '''
58
+ nicemler = [(t, "%s/%s-%s.gguf" % (CIKTI, AD, t)) for t in NICEM]
59
+ for tur, dst in nicemler:
60
+ if not os.path.exists(dst):
61
+ adim("nicemleme " + tur); subprocess.run([PY_GGUF, "-c", NICEM_KOD, bf16, dst, tur], check=True)
62
+ print("%s: %.2f GB" % (tur, os.path.getsize(dst) / 1e9), flush=True)
63
+ DOGRULA = r'''
64
+ import sys, json, math, numpy as np
65
+ from llama_cpp import Llama
66
+ yol, metin_yolu = sys.argv[1], sys.argv[2]
67
+ llm = Llama(model_path=yol, n_ctx=1024, n_threads=16, logits_all=True, verbose=False)
68
+ sorular = ["Seni kim geliştirdi?", "Kimsin?", "Sen Qwen misin?", "Temel modelin ne?", "Hangi şirket seni yaptı?", "Sen ChatGPT misin?"]
69
+ kimlik = 0; cevaplar = []
70
+ for s in sorular:
71
+ r = llm.create_chat_completion(messages=[{"role": "user", "content": s + " /no_think"}], max_tokens=120, temperature=0)
72
+ c = r["choices"][0]["message"]["content"].split("</think>")[-1].strip(); cl = c.lower()
73
+ yasak = ("alibaba", "tongyi") if s != "Sen ChatGPT misin?" else ("alibaba", "tongyi", "ben chatgpt'yim", "chatgpt'yim")
74
+ iyi = ("erk" in cl or "ecloud" in cl) and not any(x in cl for x in yasak)
75
+ if s == "Temel modelin ne?": iyi = "qwen" in cl
76
+ if s == "Sen Qwen misin?": iyi = ("erk" in cl or "ecloud" in cl)
77
+ kimlik += iyi; cevaplar.append((s, bool(iyi), c[:100]))
78
+ parcalar = [p.strip() for p in open(metin_yolu, encoding="utf-8").read().split("\n\n") if len(p.split()) > 50][:8]
79
+ top_nll = 0.0; top_n = 0
80
+ for p in parcalar:
81
+ ids = llm.tokenize(p.encode("utf-8"))[:768]; llm.reset(); llm.eval(ids)
82
+ lg = np.asarray(llm.scores[:len(ids)], dtype=np.float32)
83
+ for i in range(len(ids) - 1):
84
+ row = lg[i]; m = row.max(); lse = m + math.log(np.exp(row - m).sum()); top_nll += lse - row[ids[i + 1]]; top_n += 1
85
+ json.dump({"kimlik": kimlik, "n_kimlik": len(sorular), "cevaplar": cevaplar, "nll": float(top_nll / max(top_n, 1)), "token": top_n},
86
+ open(yol + ".dogrulama.json", "w"), ensure_ascii=False, indent=1)
87
+ print("%s | kimlik %d/%d | NLL %.4f" % (yol.split("/")[-1], kimlik, len(sorular), top_nll / max(top_n, 1)), flush=True)
88
+ '''
89
+ son = {}
90
+ for yol in [bf16] + [d for _, d in nicemler]:
91
+ adim("dogrulama " + os.path.basename(yol)); subprocess.run([PY_GGUF, "-c", DOGRULA, yol, NLL_METIN], check=True)
92
+ son[os.path.basename(yol)] = json.load(open(yol + ".dogrulama.json"))
93
+ adim("OZET"); taban = son[os.path.basename(bf16)]["nll"]
94
+ for k, v in son.items():
95
+ print(" %-22s kimlik %d/%d NLL %.4f (BF16'ya gore %+.2f%%)" % (k, v["kimlik"], v["n_kimlik"], v["nll"], 100 * (v["nll"] - taban) / taban), flush=True)
96
+ json.dump(son, open(CIKTI + "/dogrulama_ozet.json", "w"), ensure_ascii=False, indent=1); print("BITTI", flush=True)