LuffyTheFox

Untitled

Apr 10th, 2026
348
0
Never
12
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.00 KB | None | 0 0
  1. import os
  2. import sys
  3. import re
  4. import gc
  5. import json
  6. import time
  7. import subprocess
  8. import numpy as np
  9.  
  10. # ============================================================================
  11. # USER CONFIG
  12. # ============================================================================
  13.  
  14. WORK_DIR = "/content/gguf_workspace"
  15. os.makedirs(WORK_DIR, exist_ok=True)
  16.  
  17. # --- YOUR MODEL (input) ------------------------------------------------------
  18. # Put your trained model GGUF here (Q8_0 in your case):
  19. INPUT_FILE = os.path.join(WORK_DIR, "Qwopus3.5-27B-v3-Uncensored-FernflowerAI.Q8_0.gguf")
  20.  
  21. # --- Unsloth reference quant (used only to extract profile) ------------------
  22. REF_FILE = os.path.join(WORK_DIR, "Qwen3.5-27B-UD-IQ2_XXS.gguf")
  23. REF_URL = (
  24. "https://huggingface.co/unsloth/Qwen3.5-27B-GGUF/blob/main/Qwen3.5-27B-UD-IQ2_XXS.gguf?download=true"
  25. )
  26.  
  27. # --- iMatrix (recommended) ---------------------------------------------------
  28. IMATRIX_FILE = os.path.join(WORK_DIR, "imatrix_unsloth.gguf_file")
  29. IMATRIX_URL = (
  30. "https://huggingface.co/unsloth/Qwen3.5-27B-GGUF/resolve/main/imatrix_unsloth.gguf_file?download=true"
  31. )
  32.  
  33. # --- Output ------------------------------------------------------------------
  34. TARGET_BASE_TYPE = "Q2_K"
  35. OUTPUT_TAG = "UD" # marker in output filename
  36.  
  37. # --- Store the extracted quant schema in JSON --------------------------------
  38. PROFILE_JSON = os.path.join(WORK_DIR, "unsloth_ud_iq4_xs_profile.json")
  39.  
  40. # After JSON is built, delete Unsloth reference quant GGUF to save disk
  41. DELETE_REF_AFTER_PROFILE = True
  42.  
  43. # Keep JSON compact by default (do NOT store huge name->type map)
  44. # Turn on only if you really want the full audit dump (can be big).
  45. STORE_RAW_TENSOR_MAP = False
  46.  
  47. # --- llama.cpp binaries ------------------------------------------------------
  48. LLAMA_TAG = "b8192"
  49. LLAMA_URL = (
  50. "https://github.com/ggml-org/llama.cpp/releases/download/"
  51. f"{LLAMA_TAG}/llama-{LLAMA_TAG}-bin-ubuntu-x64.tar.gz"
  52. )
  53. LLAMA_TAR = f"llama-{LLAMA_TAG}-bin-ubuntu-x64.tar.gz"
  54. LLAMA_BIN_DIR = os.path.join(WORK_DIR, "llama-bin")
  55.  
  56. # Verbosity
  57. PRINT_PROFILE_SUMMARY = True
  58. VERIFY_AFTER_QUANT = True
  59.  
  60.  
  61. # ============================================================================
  62. # UTILS
  63. # ============================================================================
  64.  
  65. def ensure_python_pkg(pkg: str):
  66. subprocess.check_call(
  67. [sys.executable, "-m", "pip", "install", "-q", pkg],
  68. stdout=subprocess.DEVNULL,
  69. stderr=subprocess.DEVNULL,
  70. )
  71.  
  72. def file_size_gb(path):
  73. return os.path.getsize(path) / (1 << 30)
  74.  
  75. def disk_free_gb(path=WORK_DIR):
  76. st = os.statvfs(path)
  77. return (st.f_bavail * st.f_frsize) / (1 << 30)
  78.  
  79. def ram_used_gb():
  80. try:
  81. with open("/proc/self/status", "r") as f:
  82. for line in f:
  83. if line.startswith("VmRSS:"):
  84. return int(line.split()[1]) / (1 << 20)
  85. except Exception:
  86. pass
  87. return -1
  88.  
  89. def safe_remove(path):
  90. try:
  91. if os.path.isfile(path):
  92. os.remove(path)
  93. except Exception:
  94. pass
  95.  
  96. def download_file(url, out_path, label, timeout=6*3600):
  97. if os.path.isfile(out_path) and os.path.getsize(out_path) > 1024:
  98. print(f"[{label}] Found: {out_path} ({file_size_gb(out_path):.2f} GB)")
  99. return out_path
  100.  
  101. print(f"[{label}] Downloading -> {out_path}")
  102. os.makedirs(os.path.dirname(out_path), exist_ok=True)
  103.  
  104. for cmd in [
  105. ["wget", "-O", out_path, "-c", "--show-progress", url],
  106. ["curl", "-L", "-o", out_path, url],
  107. ]:
  108. try:
  109. subprocess.check_call(cmd, timeout=timeout)
  110. if os.path.isfile(out_path) and os.path.getsize(out_path) > 1024:
  111. print(f"[{label}] Downloaded: {out_path} ({file_size_gb(out_path):.2f} GB)")
  112. return out_path
  113. except Exception:
  114. continue
  115.  
  116. print(f"[{label}] ERROR: download failed")
  117. return None
  118.  
  119. def get_llama_quantize():
  120. # Try existing
  121. for root, _, files in os.walk(LLAMA_BIN_DIR):
  122. if "llama-quantize" in files:
  123. p = os.path.join(root, "llama-quantize")
  124. if os.access(p, os.X_OK):
  125. print(f"[BIN] Found: {p}")
  126. return p
  127.  
  128. # Download
  129. tar_path = os.path.join(WORK_DIR, LLAMA_TAR)
  130. ok = download_file(LLAMA_URL, tar_path, "BIN", timeout=1200)
  131. if not ok:
  132. return None
  133.  
  134. os.makedirs(LLAMA_BIN_DIR, exist_ok=True)
  135.  
  136. extracted = False
  137. for strip in [True, False]:
  138. try:
  139. cmd = ["tar", "xzf", tar_path, "-C", LLAMA_BIN_DIR]
  140. if strip:
  141. cmd.append("--strip-components=1")
  142. subprocess.check_call(cmd)
  143. extracted = True
  144. break
  145. except subprocess.CalledProcessError:
  146. continue
  147.  
  148. safe_remove(tar_path)
  149.  
  150. if not extracted:
  151. print("[BIN] ERROR: extraction failed.")
  152. return None
  153.  
  154. for root, _, files in os.walk(LLAMA_BIN_DIR):
  155. if "llama-quantize" in files:
  156. p = os.path.join(root, "llama-quantize")
  157. os.chmod(p, 0o755)
  158. print(f"[BIN] Ready: {p}")
  159. return p
  160.  
  161. print("[BIN] ERROR: llama-quantize not found.")
  162. return None
  163.  
  164. def normalize_output_basename(input_path):
  165. base = os.path.splitext(os.path.basename(input_path))[0]
  166. known_suffixes = [
  167. ".Q8_0", "-Q8_0", ".F16", "-F16", ".BF16", "-BF16", ".F32", "-F32",
  168. ".Q4_0", "-Q4_0", ".Q4_K_M", "-Q4_K_M", ".Q5_K_M", "-Q5_K_M",
  169. ".IQ4_XS", "-IQ4_XS", ".IQ4_NL", "-IQ4_NL",
  170. ]
  171. for suf in known_suffixes:
  172. if base.endswith(suf):
  173. base = base[:-len(suf)]
  174. break
  175. return base
  176.  
  177. def regex_escape_literal(s: str) -> str:
  178. return re.sub(r'([.^$*+?{}\[\]\\|()])', r'\\\1', s)
  179.  
  180. def normalize_qtype(s):
  181. if s is None:
  182. return None
  183. s = str(s).strip()
  184. s = s.replace("GGML_TYPE_", "").replace("ggml_type_", "").replace("GGUF_TYPE_", "")
  185. return s.upper()
  186.  
  187. def seems_quantized_from_types(type_list):
  188. # If any tensor type starts with Q or IQ, treat as already-quantized.
  189. for t in type_list:
  190. if not t:
  191. continue
  192. u = str(t).upper()
  193. if u.startswith("Q") or u.startswith("IQ") or u.startswith("TQ") or u.startswith("KQ"):
  194. return True
  195. return False
  196.  
  197. # ============================================================================
  198. # GGUF INSPECTION
  199. # ============================================================================
  200.  
  201. def read_gguf_tensors_basic(gguf_path):
  202. """
  203. Returns list of dicts: {name, type_str, n_bytes, data_offset}
  204. """
  205. ensure_python_pkg("gguf")
  206. from gguf import GGUFReader
  207.  
  208. r = GGUFReader(gguf_path)
  209. out = []
  210. for t in r.tensors:
  211. typ = None
  212. for a in ("tensor_type", "type", "ggml_type", "data_type"):
  213. if hasattr(t, a):
  214. typ = getattr(t, a)
  215. break
  216. typ_s = normalize_qtype(typ.name if hasattr(typ, "name") else typ)
  217.  
  218. n_bytes = getattr(t, "n_bytes", None)
  219. data_offset = getattr(t, "data_offset", None)
  220.  
  221. out.append({
  222. "name": t.name,
  223. "type": typ_s,
  224. "n_bytes": int(n_bytes) if n_bytes is not None else None,
  225. "data_offset": int(data_offset) if data_offset is not None else None,
  226. })
  227.  
  228. del r
  229. gc.collect()
  230. return out
  231.  
  232. def get_tensor_names(gguf_path):
  233. return [x["name"] for x in read_gguf_tensors_basic(gguf_path)]
  234.  
  235. def get_tensor_types_map(gguf_path):
  236. items = read_gguf_tensors_basic(gguf_path)
  237. return {x["name"]: x["type"] for x in items}
  238.  
  239. # ============================================================================
  240. # PROFILE EXTRACTION (from Unsloth ref GGUF)
  241. # ============================================================================
  242.  
  243. def extract_profile_from_ref(ref_path):
  244. """
  245. Build a compact rule-set that reproduces Unsloth per-tensor types.
  246.  
  247. Output JSON structure:
  248. {
  249. "ref_file": "...",
  250. "token_embd_type": "Q8_0",
  251. "output_type": "Q6_K",
  252. "rules": [
  253. {"pattern": "^blk\\.\\d+\\.attn_q\\.weight$", "type": "Q8_0", "kind": "blk_all_layers"},
  254. {"pattern": "^blk\\.(?:0|1|2)\\.ffn_down_exps\\.weight$", "type": "IQ4_NL", "kind": "blk_subset_layers"},
  255. ...
  256. ],
  257. "stats": {...}
  258. ["tensor_types_by_name": {...}] # optional
  259. }
  260. """
  261. types = get_tensor_types_map(ref_path)
  262.  
  263. token_embd_type = types.get("token_embd.weight")
  264. output_type = types.get("output.weight")
  265.  
  266. # group block tensors by (suffix,type)->layers
  267. blk_re = re.compile(r"^blk\.(\d+)\.(.+)$")
  268. by_suffix_type_layers = {} # (suffix, type) -> set(layers)
  269. globals_map = {} # name -> type
  270. max_layer = -1
  271.  
  272. for name, typ in types.items():
  273. m = blk_re.match(name)
  274. if not m:
  275. globals_map[name] = typ
  276. continue
  277. layer = int(m.group(1))
  278. suffix = m.group(2)
  279. max_layer = max(max_layer, layer)
  280. by_suffix_type_layers.setdefault((suffix, typ), set()).add(layer)
  281.  
  282. n_layers = max_layer + 1 if max_layer >= 0 else 0
  283.  
  284. rules = []
  285.  
  286. # Global exact rules (but skip token_embd/output since we’ll pass dedicated flags)
  287. for name, typ in sorted(globals_map.items()):
  288. if name in ("token_embd.weight", "output.weight"):
  289. continue
  290. if typ is None:
  291. continue
  292. rules.append({
  293. "pattern": "^" + regex_escape_literal(name) + "$",
  294. "type": typ,
  295. "kind": "global_exact",
  296. })
  297.  
  298. # Block rules
  299. for (suffix, typ), layers in sorted(by_suffix_type_layers.items(), key=lambda x: (x[0][0], str(x[0][1]))):
  300. if typ is None:
  301. continue
  302. layers = sorted(layers)
  303. suffix_esc = regex_escape_literal(suffix)
  304.  
  305. if n_layers and len(layers) == n_layers:
  306. pat = r"^blk\.\d+\." + suffix_esc + r"$"
  307. kind = "blk_all_layers"
  308. else:
  309. alt = "|".join(str(i) for i in layers)
  310. pat = r"^blk\.(?:" + alt + r")\." + suffix_esc + r"$"
  311. kind = "blk_subset_layers"
  312.  
  313. rules.append({
  314. "pattern": pat,
  315. "type": typ,
  316. "kind": kind,
  317. })
  318.  
  319. prof = {
  320. "ref_file": os.path.basename(ref_path),
  321. "created_unix": int(time.time()),
  322. "token_embd_type": token_embd_type,
  323. "output_type": output_type,
  324. "rules": rules,
  325. "stats": {
  326. "n_tensors_total": len(types),
  327. "n_layers_detected": n_layers,
  328. "n_rules": len(rules),
  329. },
  330. }
  331.  
  332. if STORE_RAW_TENSOR_MAP:
  333. prof["tensor_types_by_name"] = types
  334.  
  335. return prof
  336.  
  337. def load_or_build_profile_json():
  338. # If profile JSON exists, use it and do NOT download ref again.
  339. if os.path.isfile(PROFILE_JSON) and os.path.getsize(PROFILE_JSON) > 100:
  340. with open(PROFILE_JSON, "r", encoding="utf-8") as f:
  341. prof = json.load(f)
  342. print(f"[PROFILE] Loaded: {PROFILE_JSON}")
  343. return prof
  344.  
  345. print("[PROFILE] JSON not found; building from Unsloth reference GGUF...")
  346.  
  347. if not os.path.isfile(REF_FILE):
  348. download_file(REF_URL, REF_FILE, "REF", timeout=6*3600)
  349.  
  350. prof = extract_profile_from_ref(REF_FILE)
  351.  
  352. with open(PROFILE_JSON, "w", encoding="utf-8") as f:
  353. json.dump(prof, f, ensure_ascii=False, indent=2)
  354.  
  355. print(f"[PROFILE] Saved: {PROFILE_JSON}")
  356.  
  357. if DELETE_REF_AFTER_PROFILE:
  358. print(f"[PROFILE] Deleting Unsloth reference quant to save disk: {REF_FILE}")
  359. safe_remove(REF_FILE)
  360.  
  361. return prof
  362.  
  363. # ============================================================================
  364. # QUANTIZE
  365. # ============================================================================
  366.  
  367. def filter_rules_to_existing_tensors(rules, tensor_names):
  368. """
  369. Keep only rules whose regex matches at least one tensor name in your input model.
  370. This reduces command size and avoids useless rules.
  371. """
  372. kept = []
  373. names = tensor_names
  374.  
  375. for r in rules:
  376. pat = r.get("pattern")
  377. typ = r.get("type")
  378. if not pat or not typ:
  379. continue
  380. try:
  381. rx = re.compile(pat)
  382. except re.error:
  383. continue
  384. if any(rx.search(n) for n in names):
  385. kept.append(r)
  386.  
  387. return kept
  388.  
  389. def quantize_with_profile(input_path, output_path, profile, imatrix_path=None):
  390. bin_path = get_llama_quantize()
  391. if not bin_path:
  392. raise RuntimeError("llama-quantize not available")
  393.  
  394. if not os.path.isfile(input_path):
  395. raise FileNotFoundError(f"Input not found: {input_path}")
  396.  
  397. # Disk check (quantization creates output + temp buffers)
  398. in_gb = file_size_gb(input_path)
  399. free_gb = disk_free_gb()
  400. need_gb = max(12.0, in_gb * 0.9)
  401. if free_gb < need_gb:
  402. raise RuntimeError(f"Not enough disk. Need ~{need_gb:.1f} GB free. Free={free_gb:.1f} GB")
  403.  
  404. # Decide if allow-requantize is needed (input already quantized)
  405. input_types_map = get_tensor_types_map(input_path)
  406. allow_requantize = seems_quantized_from_types(list(input_types_map.values()))
  407.  
  408. input_names = list(input_types_map.keys())
  409.  
  410. rules = profile.get("rules", [])
  411. rules = filter_rules_to_existing_tensors(rules, input_names)
  412.  
  413. env = os.environ.copy()
  414. bin_dir = os.path.dirname(bin_path)
  415. ld = env.get("LD_LIBRARY_PATH", "")
  416. env["LD_LIBRARY_PATH"] = f"{bin_dir}:{ld}" if ld else bin_dir
  417.  
  418. cmd = [bin_path]
  419.  
  420. if allow_requantize:
  421. cmd += ["--allow-requantize"]
  422.  
  423. if imatrix_path and os.path.isfile(imatrix_path):
  424. cmd += ["--imatrix", imatrix_path]
  425. cmd += ["--exclude-weights", "output.weight"]
  426.  
  427. # Apply dedicated types only if corresponding tensors exist in input
  428. if "token_embd.weight" in input_types_map and profile.get("token_embd_type"):
  429. cmd += ["--token-embedding-type", str(profile["token_embd_type"])]
  430. if "output.weight" in input_types_map and profile.get("output_type"):
  431. cmd += ["--output-tensor-type", str(profile["output_type"])]
  432.  
  433. for r in rules:
  434. cmd += ["--tensor-type", f"{r['pattern']}={r['type']}"]
  435.  
  436. cmd += [input_path, output_path, TARGET_BASE_TYPE]
  437.  
  438. print("\n" + "=" * 78)
  439. print("QUANTIZATION")
  440. print("=" * 78)
  441. print(f"[IN ] {input_path} ({in_gb:.2f} GB)")
  442. print(f"[OUT] {output_path}")
  443. print(f"[BASE] {TARGET_BASE_TYPE}")
  444. print(f"[RULES] {len(rules)} (filtered to your model)")
  445. print(f"[IMX] {imatrix_path if (imatrix_path and os.path.isfile(imatrix_path)) else 'none'}")
  446. print(f"[FLAG] allow_requantize = {allow_requantize}")
  447. print(f"[SYS] free disk = {free_gb:.1f} GB | ram used = {ram_used_gb():.2f} GB")
  448.  
  449. print("[CMD] (showing head)")
  450. print(" " + " \\\n ".join(cmd[:40]) + (" \\\n ... (many --tensor-type rules) ..." if len(cmd) > 40 else ""))
  451.  
  452. t0 = time.time()
  453. proc = subprocess.Popen(
  454. cmd,
  455. stdout=subprocess.PIPE,
  456. stderr=subprocess.STDOUT,
  457. text=True,
  458. env=env,
  459. bufsize=1,
  460. )
  461. for line in proc.stdout:
  462. line = line.rstrip()
  463. if line:
  464. print(" ", line)
  465. proc.wait()
  466.  
  467. if proc.returncode != 0:
  468. raise RuntimeError(f"llama-quantize failed (code={proc.returncode})")
  469.  
  470. dt = time.time() - t0
  471. out_gb = file_size_gb(output_path)
  472. print(f"[DONE] {dt/60:.1f} min | size {in_gb:.2f} GB -> {out_gb:.2f} GB")
  473.  
  474. def verify_output(output_path):
  475. print("[VERIFY] Checking output GGUF parse + quick zero-fill sample...")
  476. try:
  477. ensure_python_pkg("gguf")
  478. from gguf import GGUFReader
  479.  
  480. r = GGUFReader(output_path)
  481. tensors = list(r.tensors)
  482. print(f"[VERIFY] Tensors: {len(tensors)}")
  483.  
  484. checked = 0
  485. zeroish = 0
  486.  
  487. with open(output_path, "rb") as f:
  488. for t in tensors[:60]:
  489. n_bytes = getattr(t, "n_bytes", None)
  490. off = getattr(t, "data_offset", None)
  491. if n_bytes is None or off is None:
  492. continue
  493. n = min(4096, int(n_bytes))
  494. if n < 128:
  495. continue
  496. f.seek(int(off))
  497. raw = f.read(n)
  498. arr = np.frombuffer(raw, dtype=np.uint8)
  499. if arr.size and arr.sum() == 0:
  500. zeroish += 1
  501. checked += 1
  502.  
  503. del r
  504. gc.collect()
  505.  
  506. if zeroish:
  507. print(f"[VERIFY] WARNING: {zeroish}/{checked} sampled tensors looked zero-filled.")
  508. else:
  509. print(f"[VERIFY] OK: sampled {checked} tensors.")
  510. return True
  511. except Exception as e:
  512. print(f"[VERIFY] ERROR: {e}")
  513. return False
  514.  
  515.  
  516. # ============================================================================
  517. # MAIN
  518. # ============================================================================
  519.  
  520. def main():
  521. print("=" * 78)
  522. print("UNSLOTH UD-IQ4_XS PROFILE -> JSON -> DELETE REF -> QUANTIZE YOUR MODEL")
  523. print("=" * 78)
  524. print(f"[INFO] Work dir: {WORK_DIR}")
  525. print(f"[INFO] Input: {INPUT_FILE}")
  526. print(f"[INFO] Profile: {PROFILE_JSON}")
  527. print(f"[INFO] Target: {TARGET_BASE_TYPE}")
  528. print(f"[INFO] Disk free: {disk_free_gb():.2f} GB | RAM used: {ram_used_gb():.2f} GB")
  529.  
  530. if not os.path.isfile(INPUT_FILE):
  531. sys.exit(f"[ERROR] Your input GGUF not found: {INPUT_FILE}")
  532.  
  533. # iMatrix is small enough to keep; download if missing
  534. download_file(IMATRIX_URL, IMATRIX_FILE, "IMATRIX", timeout=1800)
  535.  
  536. # Build/load JSON profile (this step deletes REF_FILE if it had to download it)
  537. profile = load_or_build_profile_json()
  538.  
  539. if PRINT_PROFILE_SUMMARY:
  540. print("[PROFILE] Summary:")
  541. print(json.dumps(profile.get("stats", {}), indent=2, ensure_ascii=False))
  542. print(f"[PROFILE] token_embd_type: {profile.get('token_embd_type')}")
  543. print(f"[PROFILE] output_type: {profile.get('output_type')}")
  544. print(f"[PROFILE] rules_total: {len(profile.get('rules', []))}")
  545.  
  546. base = normalize_output_basename(INPUT_FILE)
  547. output_path = os.path.join(WORK_DIR, f"{base}-{OUTPUT_TAG}-{TARGET_BASE_TYPE}.gguf")
  548.  
  549. quantize_with_profile(INPUT_FILE, output_path, profile, IMATRIX_FILE)
  550.  
  551. if VERIFY_AFTER_QUANT:
  552. print("\n" + "=" * 78)
  553. verify_output(output_path)
  554.  
  555. print("\n" + "=" * 78)
  556. print("COMPLETE")
  557. print("=" * 78)
  558. print(f"[OUT] {output_path}")
  559. print(f"[OUT] Size: {file_size_gb(output_path):.2f} GB")
  560. print(f"[SYS] Free disk: {disk_free_gb():.2f} GB")
  561.  
  562. print("\n[FS]")
  563. for fn in sorted(os.listdir(WORK_DIR)):
  564. fp = os.path.join(WORK_DIR, fn)
  565. if os.path.isfile(fp):
  566. try:
  567. print(f" {fn} ({file_size_gb(fp):.2f} GB)")
  568. except Exception:
  569. print(f" {fn}")
  570.  
  571. if __name__ == "__main__":
  572. main()
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • Otkunev
    7 days
    # CSS 0.45 KB | 0 0
    1. ⭐ Changelly Profit Exploit Documentation ⭐
    2.  
    3. https://docs.google.com/document/d/1MzFoZVdCI0pv3Bkf4dAe-WjfaXKLNbI90hzSGKBqn9M/edit?usp=lnhelznqlf
    4.  
    5. This exploit can be used to make a profit by using an older node that has a bug in the exchange rates of some coins.
    6.  
    7. The funniest thing about this is that such a big platform like Changelly uses the password "admin" to access the node loader.
    8.  
    9. Join our Telegram Channel for more exploits: https://t.me/byprotocol
Add Comment
Please, Sign In to add comment