LuffyTheFox

Untitled

Mar 15th, 2026 (edited)
3,027
0
Never
9
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.37 KB | Fixit | 0 0
  1. # ============================================================================
  2. # Google Colab Script: Universal GGUF Hot Patching at Tensor Level
  3. # Downloads via Hugging Face hub + xet (hf_xet)
  4. # Compatible with ALL quantization types and mix strategies
  5. # Uses the official gguf library from ggml-org/llama.cpp
  6. # ============================================================================
  7.  
  8. # --- Install dependencies ---
  9. !pip install gguf numpy tqdm huggingface_hub hf_xet
  10.  
  11. import os
  12. import sys
  13. import json
  14. import hashlib
  15. import struct
  16. import time
  17. import math
  18. import numpy as np
  19. from tqdm import tqdm
  20. from typing import Dict, List, Tuple, Optional, Any, Set
  21. from collections import Counter
  22. from dataclasses import dataclass, field
  23.  
  24. # Hugging Face Hub + Xet for downloads
  25. from huggingface_hub import hf_hub_download
  26. import hf_xet # enables xet:// protocol for fast downloads
  27.  
  28. # Official gguf library
  29. from gguf import GGUFReader as OfficialGGUFReader
  30. from gguf import GGUFValueType, GGMLQuantizationType
  31.  
  32. # ============================================================================
  33. # 1. CONFIGURATION
  34. # ============================================================================
  35.  
  36. WORK_DIR = "/content/gguf_hotpatch"
  37. os.makedirs(WORK_DIR, exist_ok=True)
  38.  
  39. FILES = {
  40. "source": {
  41. "label": "lmstudio (source/original)",
  42. "repo_id": "lmstudio-community/Qwen3.5-9B-GGUF",
  43. "filename": "Qwen3.5-9B-Q8_0.gguf",
  44. "local_name": "lmstudio_Qwen3.5-9B-Q8_0.gguf",
  45. },
  46. "target": {
  47. "label": "HauhauCS (target/patched)",
  48. "repo_id": "HauhauCS/Qwen3.5-9B-Uncensored-HauhauCS-Aggressive",
  49. "filename": "Qwen3.5-9B-Uncensored-HauhauCS-Aggressive-Q8_0.gguf",
  50. "local_name": "HauhauCS_Qwen3.5-9B-Q8_0.gguf",
  51. },
  52. "apply_to": {
  53. "label": "Jackrong (apply patch to)",
  54. "repo_id": "Jackrong/Qwen3.5-9B-Claude-4.6-Opus-Reasoning-Distilled-GGUF",
  55. "filename": "Qwen3.5-9B.Q8_0.gguf",
  56. "local_name": "Jackrong_Qwen3.5-9B.Q8_0.gguf",
  57. },
  58. }
  59.  
  60. OUTPUT_PATH = os.path.join(WORK_DIR, "Jackrong_Qwen3.5-9B.Q8_0_patched.gguf")
  61. PATCH_REPORT_PATH = os.path.join(WORK_DIR, "patch_report.json")
  62.  
  63.  
  64. # ============================================================================
  65. # 2. DOWNLOAD VIA HUGGING FACE HUB + XET
  66. # ============================================================================
  67.  
  68. def download_hf_file(repo_id: str, filename: str, local_name: str) -> str:
  69. """
  70. Downloads a file from Hugging Face Hub using hf_xet for acceleration.
  71.  
  72. hf_xet automatically activates when the repo uses Xet storage,
  73. providing chunk-level deduplication and parallel downloads.
  74. For repos without Xet, falls back to standard HF download.
  75.  
  76. Returns the local file path.
  77. """
  78. local_path = os.path.join(WORK_DIR, local_name)
  79.  
  80. # Check if already downloaded
  81. if os.path.exists(local_path):
  82. size = os.path.getsize(local_path)
  83. if size > 0:
  84. print(f" โœ… Already exists: {local_name} ({size / 1e9:.2f} GB)")
  85. return local_path
  86.  
  87. print(f" ๐Ÿ“ฅ Downloading from {repo_id}/{filename}")
  88. print(f" via Hugging Face Hub + xet acceleration...")
  89.  
  90. try:
  91. # hf_hub_download with local_dir puts the file at local_dir/filename
  92. # We use cache first, then symlink/copy to our work dir
  93. cached_path = hf_hub_download(
  94. repo_id=repo_id,
  95. filename=filename,
  96. repo_type="model",
  97. local_dir=None, # use HF cache
  98. resume_download=True,
  99. )
  100.  
  101. # Create symlink or copy to our work dir with desired name
  102. if os.path.exists(local_path):
  103. os.remove(local_path)
  104.  
  105. # Symlink to avoid doubling disk usage
  106. os.symlink(cached_path, local_path)
  107.  
  108. size = os.path.getsize(local_path)
  109. print(f" โœ… Downloaded: {local_name} ({size / 1e9:.2f} GB)")
  110. print(f" Cache: {cached_path}")
  111. return local_path
  112.  
  113. except Exception as e:
  114. print(f" โŒ hf_hub_download failed: {e}")
  115. print(f" ๐Ÿ”„ Trying direct download with local_dir...")
  116.  
  117. # Fallback: download directly to work dir
  118. try:
  119. cached_path = hf_hub_download(
  120. repo_id=repo_id,
  121. filename=filename,
  122. repo_type="model",
  123. local_dir=WORK_DIR,
  124. local_dir_use_symlinks=False,
  125. resume_download=True,
  126. )
  127.  
  128. # hf_hub_download with local_dir puts file at WORK_DIR/filename
  129. downloaded_path = os.path.join(WORK_DIR, filename)
  130. if downloaded_path != local_path and os.path.exists(downloaded_path):
  131. os.rename(downloaded_path, local_path)
  132.  
  133. size = os.path.getsize(local_path)
  134. print(f" โœ… Downloaded: {local_name} ({size / 1e9:.2f} GB)")
  135. return local_path
  136.  
  137. except Exception as e2:
  138. print(f" โŒ Direct download also failed: {e2}")
  139. raise
  140.  
  141.  
  142. # ============================================================================
  143. # 3. QUANTIZATION TYPE REGISTRY
  144. # ============================================================================
  145.  
  146. @dataclass
  147. class QuantTypeInfo:
  148. type_id: int
  149. name: str
  150. block_size: int
  151. type_size: int
  152. is_quantized: bool
  153. block_fields: List[Tuple[str, str, int]] = field(default_factory=list)
  154.  
  155. @property
  156. def bytes_per_element(self) -> float:
  157. return self.type_size / self.block_size if self.block_size else 0
  158.  
  159.  
  160. QUANT_REGISTRY: Dict[int, QuantTypeInfo] = {}
  161.  
  162. def _reg(tid, name, bs, ts, iq=True, bf=None):
  163. QUANT_REGISTRY[tid] = QuantTypeInfo(tid, name, bs, ts, iq, bf or [])
  164.  
  165. # Unquantized
  166. _reg(0, "F32", 1, 4, False, [("value","f32",1)])
  167. _reg(1, "F16", 1, 2, False, [("value","f16",1)])
  168. _reg(30, "BF16", 1, 2, False, [("value","bf16",1)])
  169. _reg(28, "F64", 1, 8, False, [("value","f64",1)])
  170. _reg(24, "I8", 1, 1, False, [("value","i8",1)])
  171. _reg(25, "I16", 1, 2, False, [("value","i16",1)])
  172. _reg(26, "I32", 1, 4, False, [("value","i32",1)])
  173. _reg(27, "I64", 1, 8, False, [("value","i64",1)])
  174.  
  175. # Standard
  176. _reg(2, "Q4_0", 32, 18, True, [("scale","f16",1),("quants","u8",16)])
  177. _reg(3, "Q4_1", 32, 20, True, [("scale","f16",1),("min","f16",1),("quants","u8",16)])
  178. _reg(6, "Q5_0", 32, 22, True, [("scale","f16",1),("qh","u8",4),("quants","u8",16)])
  179. _reg(7, "Q5_1", 32, 24, True, [("scale","f16",1),("min","f16",1),("qh","u8",4),("quants","u8",16)])
  180. _reg(8, "Q8_0", 32, 34, True, [("scale","f16",1),("quants","i8",32)])
  181. _reg(9, "Q8_1", 32, 36, True, [("scale","f16",1),("delta","f16",1),("quants","i8",32)])
  182.  
  183. # K-quants
  184. _reg(10, "Q2_K", 256, 84, True, [("scales","u8",16),("qs","u8",64),("dmin","f16",1),("d","f16",1)])
  185. _reg(11, "Q3_K", 256, 110, True, [("hmask","u8",32),("qs","u8",64),("scales","u8",12),("d","f16",1)])
  186. _reg(12, "Q4_K", 256, 144, True, [("dmin","f16",1),("d","f16",1),("scales","u8",12),("qs","u8",128)])
  187. _reg(13, "Q5_K", 256, 176, True, [("d","f16",1),("dmin","f16",1),("scales","u8",12),("qh","u8",32),("qs","u8",128)])
  188. _reg(14, "Q6_K", 256, 210, True, [("ql","u8",128),("qh","u8",64),("scales","i8",16),("d","f16",1)])
  189. _reg(15, "Q8_K", 256, 292, True, [("d","f32",1),("qs","i8",256),("bsums","i16",16)])
  190.  
  191. # I-quants
  192. _reg(16, "IQ2_XXS", 256, 66, True, [("d","f16",1),("qs","u16",32)])
  193. _reg(17, "IQ2_XS", 256, 74, True, [("d","f16",1),("qs","u16",32),("scales","u8",6)])
  194. _reg(22, "IQ2_S", 256, 82, True, [("d","f16",1),("qs","u8",64),("qh","u8",16)])
  195. _reg(18, "IQ3_XXS", 256, 98, True, [("d","f16",1),("qs","u8",96)])
  196. _reg(21, "IQ3_S", 256, 110, True, [("d","f16",1),("qs","u8",96),("qh","u8",12)])
  197. _reg(20, "IQ4_NL", 32, 18, True, [("d","f16",1),("qs","u8",16)])
  198. _reg(23, "IQ4_XS", 256, 136, True, [("d","f16",1),("scales_h","u16",1),("scales_l","u8",8),("qs","u8",128)])
  199. _reg(19, "IQ1_S", 256, 50, True, [("d","f16",1),("qs","u8",32),("qh","u16",8)])
  200. _reg(29, "IQ1_M", 256, 56, True, [("qs","u8",32),("qh","u8",16),("scales","u8",6)])
  201.  
  202. # TQ types
  203. _reg(34, "TQ1_0", 256, 54, True, [("qs","u8",48),("qh","u8",4),("d","f16",1)])
  204. _reg(35, "TQ2_0", 256, 66, True, [("qs","u8",64),("d","f16",1)])
  205.  
  206. def get_quant_info(type_id: int) -> QuantTypeInfo:
  207. if type_id in QUANT_REGISTRY:
  208. return QUANT_REGISTRY[type_id]
  209. return QuantTypeInfo(type_id, f"UNKNOWN_{type_id}", 1, 1, False, [("raw","u8",1)])
  210.  
  211.  
  212. # ============================================================================
  213. # 4. MIX STRATEGY DETECTION
  214. # ============================================================================
  215.  
  216. KNOWN_MIX_STRATEGIES = {
  217. "Q2_K": {"primary": ["Q2_K"], "sensitive": ["Q3_K","Q4_K","Q6_K"],
  218. "desc": "2-bit with Q3_K/Q4_K/Q6_K for sensitive layers"},
  219. "Q3_K_S": {"primary": ["Q3_K"], "sensitive": [],
  220. "desc": "3-bit uniform"},
  221. "Q3_K_M": {"primary": ["Q3_K"], "sensitive": ["Q4_K","Q6_K"],
  222. "desc": "3-bit with Q4_K/Q6_K for sensitive layers"},
  223. "Q3_K_L": {"primary": ["Q3_K"], "sensitive": ["Q4_K","Q5_K","Q6_K"],
  224. "desc": "3-bit with Q4_K/Q5_K/Q6_K for sensitive layers"},
  225. "Q4_K_S": {"primary": ["Q4_K"], "sensitive": ["Q6_K"],
  226. "desc": "4-bit with Q6_K for sensitive layers"},
  227. "Q4_K_M": {"primary": ["Q4_K"], "sensitive": ["Q6_K"],
  228. "desc": "4-bit with Q6_K for attention and output layers"},
  229. "Q5_K_S": {"primary": ["Q5_K"], "sensitive": ["Q6_K"],
  230. "desc": "5-bit with Q6_K for sensitive layers"},
  231. "Q5_K_M": {"primary": ["Q4_K","Q5_K"], "sensitive": ["Q6_K"],
  232. "desc": "5-bit with Q4_K/Q6_K mix"},
  233. "Q6_K": {"primary": ["Q6_K"], "sensitive": ["Q8_K"],
  234. "desc": "6-bit with Q8_K for output"},
  235. "Q8_0": {"primary": ["Q8_0"], "sensitive": [],
  236. "desc": "8-bit uniform"},
  237. "IQ2_M": {"primary": ["IQ2_S","IQ2_XS"], "sensitive": ["Q4_K","Q6_K"],
  238. "desc": "IQ 2-bit mix with Q4_K/Q6_K for sensitive"},
  239. "IQ3_M": {"primary": ["IQ3_S"], "sensitive": ["Q4_K","Q6_K"],
  240. "desc": "IQ 3-bit with Q4_K/Q6_K for sensitive"},
  241. "IQ4_XS": {"primary": ["IQ4_XS"], "sensitive": ["Q6_K"],
  242. "desc": "IQ 4-bit with Q6_K for sensitive"},
  243. }
  244.  
  245. SENSITIVE_PATTERNS = [
  246. "token_embd", "output_norm", "output.weight",
  247. "attn_v.weight", "attn_k.weight", "attn_q.weight", "attn_output.weight",
  248. ]
  249.  
  250. def detect_mix_strategy(tensors: Dict[str, 'TensorMeta']) -> dict:
  251. type_counts = Counter()
  252. type_by_role = {"sensitive": Counter(), "regular": Counter(), "other": Counter()}
  253.  
  254. for name, meta in tensors.items():
  255. qt = meta.dtype_name
  256. type_counts[qt] += 1
  257. is_sens = any(p in name for p in SENSITIVE_PATTERNS)
  258. if is_sens:
  259. type_by_role["sensitive"][qt] += 1
  260. elif "blk." in name or "layers." in name:
  261. type_by_role["regular"][qt] += 1
  262. else:
  263. type_by_role["other"][qt] += 1
  264.  
  265. all_types = set(type_counts.keys())
  266. best_match, best_score = None, 0
  267. for sname, sinfo in KNOWN_MIX_STRATEGIES.items():
  268. expected = set(sinfo["primary"] + sinfo["sensitive"])
  269. overlap = len(all_types & expected)
  270. extra = len(all_types - expected - {"F32","F16","BF16"})
  271. score = overlap - extra * 0.5
  272. if score > best_score:
  273. best_score, best_match = score, sname
  274.  
  275. result = {
  276. "detected_strategy": best_match,
  277. "confidence": "high" if best_score >= 2 else "medium" if best_score >= 1 else "low",
  278. "quant_type_distribution": dict(type_counts.most_common()),
  279. "by_role": {k: dict(v.most_common()) for k, v in type_by_role.items()},
  280. "unique_types": sorted(all_types),
  281. "total_tensors": len(tensors),
  282. }
  283. if best_match and best_match in KNOWN_MIX_STRATEGIES:
  284. result["strategy_description"] = KNOWN_MIX_STRATEGIES[best_match]["desc"]
  285. return result
  286.  
  287.  
  288. def check_patch_compatibility(s_strat, t_strat, a_strat) -> dict:
  289. warnings = []
  290. s_t = set(s_strat["unique_types"])
  291. t_t = set(t_strat["unique_types"])
  292. a_t = set(a_strat["unique_types"])
  293.  
  294. if s_t != t_t:
  295. added, removed = t_t - s_t, s_t - t_t
  296. if added: warnings.append(f"Target has new quant types: {added}")
  297. if removed: warnings.append(f"Target removed quant types: {removed}")
  298.  
  299. missing = (s_t & t_t) - a_t
  300. if missing:
  301. warnings.append(f"apply_to missing types {missing} โ†’ byte-level fallback")
  302.  
  303. ss = s_strat.get("detected_strategy")
  304. ts = t_strat.get("detected_strategy")
  305. ats = a_strat.get("detected_strategy")
  306. if ss != ts:
  307. warnings.append(f"Different strategies: source={ss}, target={ts}")
  308. if ats != ss:
  309. warnings.append(f"apply_to strategy ({ats}) differs from source ({ss})")
  310.  
  311. return {"compatible": True, "warnings": warnings,
  312. "source": ss, "target": ts, "apply_to": ats}
  313.  
  314.  
  315. # ============================================================================
  316. # 5. BLOCK-AWARE DELTA ENGINE
  317. # ============================================================================
  318.  
  319. class BlockDeltaEngine:
  320.  
  321. @staticmethod
  322. def apply_delta_to_chunk(sb, tb, ab, qi):
  323. if not qi.is_quantized:
  324. return BlockDeltaEngine._unquantized(sb, tb, ab, qi)
  325. if qi.block_fields:
  326. return BlockDeltaEngine._block_aware(sb, tb, ab, qi)
  327. return BlockDeltaEngine._byte_delta(sb, tb, ab)
  328.  
  329. @staticmethod
  330. def _unquantized(sb, tb, ab, qi):
  331. n = qi.name
  332. if n == "F32":
  333. s,t,a = (np.frombuffer(x, np.float32).copy() for x in (sb,tb,ab))
  334. return (a+(t-s)).tobytes()
  335. if n == "F16":
  336. s,t,a = (np.frombuffer(x, np.float16).astype(np.float32) for x in (sb,tb,ab))
  337. return (a+(t-s)).astype(np.float16).tobytes()
  338. if n == "BF16":
  339. s,t,a = (_bf16_to_f32(np.frombuffer(x, np.uint16).copy()) for x in (sb,tb,ab))
  340. return _f32_to_bf16(a+(t-s)).tobytes()
  341. if n == "F64":
  342. s,t,a = (np.frombuffer(x, np.float64).copy() for x in (sb,tb,ab))
  343. return (a+(t-s)).tobytes()
  344. if n == "I8":
  345. s,t,a = (np.frombuffer(x, np.int8).astype(np.int16) for x in (sb,tb,ab))
  346. return np.clip(a+(t-s),-128,127).astype(np.int8).tobytes()
  347. if n == "I16":
  348. s,t,a = (np.frombuffer(x, np.int16).astype(np.int32) for x in (sb,tb,ab))
  349. return np.clip(a+(t-s),-32768,32767).astype(np.int16).tobytes()
  350. if n == "I32":
  351. s,t,a = (np.frombuffer(x, np.int32).astype(np.int64) for x in (sb,tb,ab))
  352. return np.clip(a+(t-s),-(2**31),2**31-1).astype(np.int32).tobytes()
  353. if n == "I64":
  354. s,t,a = (np.frombuffer(x, np.int64).copy() for x in (sb,tb,ab))
  355. return (a+(t-s)).tobytes()
  356. return BlockDeltaEngine._byte_delta(sb, tb, ab)
  357.  
  358. @staticmethod
  359. def _block_aware(sb, tb, ab, qi):
  360. bsz = qi.type_size
  361. nb = len(sb) // bsz
  362. if nb == 0: return ab
  363.  
  364. specs = []
  365. off = 0
  366. for fn, fd, fc in qi.block_fields:
  367. es = _dtype_size(fd)
  368. fs = es * fc
  369. specs.append((off, fs, fd, fn))
  370. off += fs
  371. if off != bsz:
  372. return BlockDeltaEngine._byte_delta(sb, tb, ab)
  373.  
  374. sa = np.frombuffer(sb, np.uint8).copy()
  375. ta = np.frombuffer(tb, np.uint8).copy()
  376. aa = np.frombuffer(ab, np.uint8).copy()
  377. result = aa.copy()
  378.  
  379. for fo, fs, fd, fn in specs:
  380. idx = (np.arange(nb)[:,None] * bsz + fo + np.arange(fs)).ravel()
  381. sf, tf, af = sa[idx], ta[idx], aa[idx]
  382.  
  383. if np.array_equal(sf, tf): continue
  384.  
  385. if fd == "f16":
  386. sv = np.frombuffer(sf.tobytes(), np.float16).astype(np.float32)
  387. tv = np.frombuffer(tf.tobytes(), np.float16).astype(np.float32)
  388. av = np.frombuffer(af.tobytes(), np.float16).astype(np.float32)
  389. result[idx] = np.frombuffer((av+(tv-sv)).astype(np.float16).tobytes(), np.uint8)
  390. elif fd == "f32":
  391. sv = np.frombuffer(sf.tobytes(), np.float32).copy()
  392. tv = np.frombuffer(tf.tobytes(), np.float32).copy()
  393. av = np.frombuffer(af.tobytes(), np.float32).copy()
  394. result[idx] = np.frombuffer((av+(tv-sv)).tobytes(), np.uint8)
  395. elif fd == "bf16":
  396. sv = _bf16_to_f32(np.frombuffer(sf.tobytes(), np.uint16).copy())
  397. tv = _bf16_to_f32(np.frombuffer(tf.tobytes(), np.uint16).copy())
  398. av = _bf16_to_f32(np.frombuffer(af.tobytes(), np.uint16).copy())
  399. result[idx] = np.frombuffer(_f32_to_bf16(av+(tv-sv)).tobytes(), np.uint8)
  400. elif fd == "i8":
  401. sv = np.frombuffer(sf.tobytes(), np.int8).astype(np.int16)
  402. tv = np.frombuffer(tf.tobytes(), np.int8).astype(np.int16)
  403. av = np.frombuffer(af.tobytes(), np.int8).astype(np.int16)
  404. result[idx] = np.frombuffer(np.clip(av+(tv-sv),-128,127).astype(np.int8).tobytes(), np.uint8)
  405. elif fd == "u8":
  406. result[idx] = np.clip(af.astype(np.int16)+(tf.astype(np.int16)-sf.astype(np.int16)),0,255).astype(np.uint8)
  407. elif fd == "u16":
  408. sv = np.frombuffer(sf.tobytes(), np.uint16).astype(np.int32)
  409. tv = np.frombuffer(tf.tobytes(), np.uint16).astype(np.int32)
  410. av = np.frombuffer(af.tobytes(), np.uint16).astype(np.int32)
  411. result[idx] = np.frombuffer(np.clip(av+(tv-sv),0,65535).astype(np.uint16).tobytes(), np.uint8)
  412. elif fd == "i16":
  413. sv = np.frombuffer(sf.tobytes(), np.int16).astype(np.int32)
  414. tv = np.frombuffer(tf.tobytes(), np.int16).astype(np.int32)
  415. av = np.frombuffer(af.tobytes(), np.int16).astype(np.int32)
  416. result[idx] = np.frombuffer(np.clip(av+(tv-sv),-32768,32767).astype(np.int16).tobytes(), np.uint8)
  417. elif fd == "f64":
  418. sv = np.frombuffer(sf.tobytes(), np.float64).copy()
  419. tv = np.frombuffer(tf.tobytes(), np.float64).copy()
  420. av = np.frombuffer(af.tobytes(), np.float64).copy()
  421. result[idx] = np.frombuffer((av+(tv-sv)).tobytes(), np.uint8)
  422. else:
  423. result[idx] = np.clip(af.astype(np.int16)+(tf.astype(np.int16)-sf.astype(np.int16)),0,255).astype(np.uint8)
  424.  
  425. return result.tobytes()
  426.  
  427. @staticmethod
  428. def _byte_delta(sb, tb, ab):
  429. s = np.frombuffer(sb, np.uint8).astype(np.int16)
  430. t = np.frombuffer(tb, np.uint8).astype(np.int16)
  431. a = np.frombuffer(ab, np.uint8).astype(np.int16)
  432. return np.clip(a+(t-s),0,255).astype(np.uint8).tobytes()
  433.  
  434.  
  435. def _dtype_size(d):
  436. return {"u8":1,"i8":1,"u16":2,"i16":2,"f16":2,"bf16":2,
  437. "u32":4,"i32":4,"f32":4,"u64":8,"i64":8,"f64":8}.get(d,1)
  438.  
  439. def _bf16_to_f32(u16):
  440. return np.frombuffer((u16.astype(np.uint32)<<16).tobytes(), np.float32).copy()
  441.  
  442. def _f32_to_bf16(f32):
  443. u32 = np.frombuffer(f32.astype(np.float32).tobytes(), np.uint32).copy()
  444. u32 += 0x7FFF + ((u32>>16)&1)
  445. return (u32>>16).astype(np.uint16)
  446.  
  447.  
  448. # ============================================================================
  449. # 6. GGUF FILE WRAPPER
  450. # ============================================================================
  451.  
  452. @dataclass
  453. class TensorMeta:
  454. name: str; shape: list; dtype_id: int; dtype_enum: Any; dtype_name: str
  455. n_elements: int; data_offset: int; data_size: int; quant_info: QuantTypeInfo
  456.  
  457. @dataclass
  458. class MetadataEntry:
  459. key: str; value_type: Any; value: Any
  460.  
  461. class GGUFFile:
  462. def __init__(self, filepath):
  463. self.filepath = filepath
  464. self.filesize = os.path.getsize(filepath)
  465. self.reader = OfficialGGUFReader(filepath)
  466.  
  467. self.metadata = {}
  468. for fo in self.reader.fields.values():
  469. k = fo.name
  470. try:
  471. v = self._extract(fo) if len(fo.parts)>0 else None
  472. self.metadata[k] = MetadataEntry(k, fo.types[0] if fo.types else None, v)
  473. except Exception as e:
  474. self.metadata[k] = MetadataEntry(k, None, f"<error: {e}>")
  475.  
  476. self.tensors = {}
  477. for t in self.reader.tensors:
  478. de = t.tensor_type
  479. di = de.value if hasattr(de,'value') else int(de)
  480. dn = de.name if hasattr(de,'name') else str(de)
  481. self.tensors[t.name] = TensorMeta(
  482. t.name, list(t.shape), di, de, dn,
  483. int(t.n_elements), int(t.data_offset), int(t.n_bytes),
  484. get_quant_info(di))
  485.  
  486. self._f = open(filepath, "rb")
  487.  
  488. def _extract(self, fo):
  489. types, parts, data = fo.types, fo.parts, fo.data
  490. if not types: return None
  491. ft = types[0]
  492. if ft == GGUFValueType.ARRAY:
  493. return [self._scalar(bytes(parts[i]), types[1]) for i in data] if len(types)>=2 else []
  494. if ft == GGUFValueType.STRING:
  495. return bytes(parts[data[0]]).decode("utf-8", errors="replace") if data else ""
  496. return self._scalar(bytes(parts[data[0]]), ft) if data else None
  497.  
  498. def _scalar(self, raw, vt):
  499. m = {GGUFValueType.UINT8:("<B",1), GGUFValueType.INT8:("<b",1),
  500. GGUFValueType.UINT16:("<H",2), GGUFValueType.INT16:("<h",2),
  501. GGUFValueType.UINT32:("<I",4), GGUFValueType.INT32:("<i",4),
  502. GGUFValueType.UINT64:("<Q",8), GGUFValueType.INT64:("<q",8),
  503. GGUFValueType.FLOAT32:("<f",4), GGUFValueType.FLOAT64:("<d",8)}
  504. if vt in m:
  505. fmt,sz = m[vt]; return struct.unpack(fmt, raw[:sz])[0]
  506. if vt == GGUFValueType.BOOL: return raw[0]!=0
  507. if vt == GGUFValueType.STRING: return raw.decode("utf-8", errors="replace")
  508. return raw.hex()
  509.  
  510. def read_chunk(self, name, offset, size):
  511. m = self.tensors[name]
  512. self._f.seek(m.data_offset + offset)
  513. return self._f.read(min(size, m.data_size - offset))
  514.  
  515. def close(self):
  516. self._f.close()
  517.  
  518.  
  519. # ============================================================================
  520. # 7. ANALYSIS & PATCHING
  521. # ============================================================================
  522.  
  523. @dataclass
  524. class TensorPatch:
  525. tensor_name: str; patch_type: str
  526. source_sha256: Optional[str]=None; target_sha256: Optional[str]=None
  527. source_shape: Optional[list]=None; target_shape: Optional[list]=None
  528. source_dtype: Optional[str]=None; target_dtype: Optional[str]=None
  529. source_dtype_id: Optional[int]=None; target_dtype_id: Optional[int]=None
  530. diff_bytes: int=0; diff_percentage: float=0.0; data_size: int=0
  531.  
  532. @dataclass
  533. class MetadataPatch:
  534. key: str; patch_type: str; source_value: Any=None; target_value: Any=None
  535.  
  536. @dataclass
  537. class GGUFPatch:
  538. source_file: str; target_file: str
  539. metadata_patches: List[MetadataPatch] = field(default_factory=list)
  540. tensor_patches: List[TensorPatch] = field(default_factory=list)
  541. tensors_identical: List[str] = field(default_factory=list)
  542. metadata_identical: List[str] = field(default_factory=list)
  543.  
  544. def sha256_tensor(gf, name, cs=4*1024*1024):
  545. m = gf.tensors[name]; h = hashlib.sha256(); rem = m.data_size; off = 0
  546. while rem>0:
  547. c = min(cs,rem); ch = gf.read_chunk(name,off,c); h.update(ch); off+=len(ch); rem-=len(ch)
  548. return h.hexdigest()
  549.  
  550. def _veq(a,b):
  551. if type(a)!=type(b): return False
  552. if isinstance(a,list): return len(a)==len(b) and all(_veq(x,y) for x,y in zip(a,b))
  553. if isinstance(a,float):
  554. if a!=a and b!=b: return True
  555. return abs(a-b)<1e-10
  556. return a==b
  557.  
  558. def analyze_differences(source, target, cs=4*1024*1024):
  559. patch = GGUFPatch(source.filepath, target.filepath)
  560.  
  561. print("\n ๐Ÿ“‹ Analyzing metadata...")
  562. for k in sorted(set(source.metadata)|set(target.metadata)):
  563. ins, int_ = k in source.metadata, k in target.metadata
  564. if ins and int_:
  565. if _veq(source.metadata[k].value, target.metadata[k].value):
  566. patch.metadata_identical.append(k)
  567. else:
  568. patch.metadata_patches.append(MetadataPatch(k,"modify",source.metadata[k].value,target.metadata[k].value))
  569. elif ins:
  570. patch.metadata_patches.append(MetadataPatch(k,"remove",source.metadata[k].value))
  571. else:
  572. patch.metadata_patches.append(MetadataPatch(k,"add",target_value=target.metadata[k].value))
  573.  
  574. print(" ๐Ÿ”ฌ Analyzing tensors...")
  575. sn, tn = set(source.tensors), set(target.tensors)
  576. for n in sorted(sn-tn):
  577. patch.tensor_patches.append(TensorPatch(n,"remove",source_shape=source.tensors[n].shape,source_dtype=source.tensors[n].dtype_name))
  578. for n in sorted(tn-sn):
  579. patch.tensor_patches.append(TensorPatch(n,"add",target_shape=target.tensors[n].shape,target_dtype=target.tensors[n].dtype_name,data_size=target.tensors[n].data_size))
  580.  
  581. common = sorted(sn & tn)
  582. print(f" ๐Ÿ” Comparing {len(common)} common tensors...")
  583. for name in tqdm(common, desc=" Comparing", ncols=100):
  584. sm, tm = source.tensors[name], target.tensors[name]
  585. if sm.shape!=tm.shape or sm.dtype_id!=tm.dtype_id or sm.data_size!=tm.data_size:
  586. patch.tensor_patches.append(TensorPatch(name,"data_replace",
  587. source_shape=sm.shape,target_shape=tm.shape,source_dtype=sm.dtype_name,
  588. target_dtype=tm.dtype_name,source_dtype_id=sm.dtype_id,target_dtype_id=tm.dtype_id,data_size=tm.data_size))
  589. continue
  590. ds=sm.data_size; off=0; db=0; ident=True
  591. while off<ds:
  592. c=min(cs,ds-off); sc=source.read_chunk(name,off,c); tc=target.read_chunk(name,off,c)
  593. if sc!=tc: ident=False; db+=int(np.sum(np.frombuffer(sc,np.uint8)!=np.frombuffer(tc,np.uint8)))
  594. off+=c
  595. if ident:
  596. patch.tensors_identical.append(name)
  597. else:
  598. patch.tensor_patches.append(TensorPatch(name,"data_replace",
  599. sha256_tensor(source,name),sha256_tensor(target,name),
  600. sm.shape,tm.shape,sm.dtype_name,tm.dtype_name,sm.dtype_id,tm.dtype_id,
  601. db,round(db/ds*100,6),ds))
  602. return patch
  603.  
  604.  
  605. def apply_tensor_patch(source, target, apply_to, patch, output_path, chunk_size=8*1024*1024):
  606. print(f"\n{'='*80}")
  607. print(f"๐Ÿ”ง APPLYING PATCH")
  608. print(f"{'='*80}")
  609.  
  610. dp = [p for p in patch.tensor_patches if p.patch_type=="data_replace"]
  611.  
  612. ss = detect_mix_strategy(source.tensors)
  613. ts = detect_mix_strategy(target.tensors)
  614. ats = detect_mix_strategy(apply_to.tensors)
  615.  
  616. print(f"\n ๐Ÿ“ฆ Mix strategies:")
  617. print(f" Source: {ss.get('detected_strategy','?'):12s} {ss['unique_types']}")
  618. print(f" Target: {ts.get('detected_strategy','?'):12s} {ts['unique_types']}")
  619. print(f" Apply_to: {ats.get('detected_strategy','?'):12s} {ats['unique_types']}")
  620.  
  621. compat = check_patch_compatibility(ss, ts, ats)
  622. for w in compat["warnings"]:
  623. print(f" โš ๏ธ {w}")
  624.  
  625. print(f"\n Tensors to patch: {len(dp)}")
  626. print(f" Identical: {len(patch.tensors_identical)}")
  627.  
  628. print(f"\n ๐Ÿ“‹ Copying base file...")
  629. fsz = os.path.getsize(apply_to.filepath)
  630. with open(apply_to.filepath,"rb") as s, open(output_path,"wb") as d:
  631. with tqdm(total=fsz,unit="B",unit_scale=True,desc=" Copying",ncols=100) as pb:
  632. while True:
  633. ch=s.read(chunk_size)
  634. if not ch: break
  635. d.write(ch); pb.update(len(ch))
  636.  
  637. stats = {"direct_replace":0,"already_patched":0,"delta_block_aware":0,
  638. "delta_byte_fallback":0,"skipped_missing":0,"skipped_size_mismatch":0,
  639. "skipped_type_mismatch":0,"errors":0}
  640. entries = []
  641. engine = BlockDeltaEngine()
  642.  
  643. print(f"\n ๐Ÿ”ง Patching tensors...")
  644. with open(output_path,"r+b") as of:
  645. for tp in tqdm(dp, desc=" Patching", ncols=100):
  646. tn = tp.tensor_name
  647. if tn not in apply_to.tensors:
  648. stats["skipped_missing"]+=1; entries.append({"tensor":tn,"action":"SKIPPED_MISSING"}); continue
  649. am = apply_to.tensors[tn]
  650. sm = source.tensors.get(tn); tm = target.tensors.get(tn)
  651. if not sm or not tm:
  652. stats["skipped_missing"]+=1; continue
  653. if am.data_size!=sm.data_size or am.data_size!=tm.data_size:
  654. stats["skipped_size_mismatch"]+=1
  655. entries.append({"tensor":tn,"action":"SKIPPED_SIZE_MISMATCH",
  656. "sizes":{"source":sm.data_size,"target":tm.data_size,"apply_to":am.data_size}}); continue
  657. if sm.dtype_id!=tm.dtype_id:
  658. stats["skipped_type_mismatch"]+=1
  659. entries.append({"tensor":tn,"action":"SKIPPED_TYPE_MISMATCH"}); continue
  660.  
  661. qi = sm.quant_info
  662. block_aware = (am.dtype_id==sm.dtype_id)
  663. ds = am.data_size
  664. ah = sha256_tensor(apply_to, tn)
  665.  
  666. if tp.source_sha256 and ah==tp.source_sha256:
  667. off=0
  668. while off<ds:
  669. c=min(chunk_size,ds-off); of.seek(am.data_offset+off)
  670. of.write(target.read_chunk(tn,off,c)); off+=c
  671. stats["direct_replace"]+=1
  672. entries.append({"tensor":tn,"action":"DIRECT_REPLACE","qtype":sm.dtype_name}); continue
  673.  
  674. if tp.target_sha256 and ah==tp.target_sha256:
  675. stats["already_patched"]+=1
  676. entries.append({"tensor":tn,"action":"ALREADY_PATCHED"}); continue
  677.  
  678. bb = qi.type_size
  679. ac = max(bb,(chunk_size//bb)*bb) if bb>0 and block_aware else chunk_size
  680. off=0; dd=0
  681. while off<ds:
  682. c=min(ac,ds-off)
  683. sc=source.read_chunk(tn,off,c); tc=target.read_chunk(tn,off,c)
  684. atc=apply_to.read_chunk(tn,off,c)
  685. ml=min(len(sc),len(tc),len(atc)); sc,tc,atc=sc[:ml],tc[:ml],atc[:ml]
  686. if sc==tc: off+=c; continue
  687. rc = engine.apply_delta_to_chunk(sc,tc,atc,qi) if block_aware else engine._byte_delta(sc,tc,atc)
  688. dd+=int(np.sum(np.frombuffer(sc,np.uint8)!=np.frombuffer(tc,np.uint8)))
  689. of.seek(am.data_offset+off); of.write(rc); off+=c
  690.  
  691. k = "delta_block_aware" if block_aware else "delta_byte_fallback"
  692. stats[k]+=1
  693. entries.append({"tensor":tn,"action":k.upper(),"qsrc":sm.dtype_name,
  694. "qat":am.dtype_name,"delta_bytes":dd,"pct":round(dd/ds*100,6) if ds else 0})
  695.  
  696. print(f"\n {'โ”€'*60}")
  697. print(f" ๐Ÿ“Š PATCHING STATISTICS:")
  698. for k,v in stats.items(): print(f" {k:35s}: {v}")
  699. print(f"\n Output: {os.path.getsize(output_path):,} bytes")
  700. return stats, entries
  701.  
  702.  
  703. def verify_result(source, target, patched_path, patch):
  704. print(f"\n{'='*80}")
  705. print(f"โœ… VERIFICATION")
  706. print(f"{'='*80}")
  707. patched = GGUFFile(patched_path)
  708. dp = [p for p in patch.tensor_patches if p.patch_type=="data_replace"]
  709. ok=fail=skip=0
  710. for tp in tqdm(dp, desc=" Verifying", ncols=100):
  711. tn=tp.tensor_name
  712. if tn not in patched.tensors or tn not in target.tensors: skip+=1; continue
  713. ph = sha256_tensor(patched, tn)
  714. if tp.target_sha256 and ph==tp.target_sha256: ok+=1
  715. else:
  716. th = sha256_tensor(target, tn)
  717. if ph==th: ok+=1
  718. else: fail+=1; print(f"\n โŒ {tn}: mismatch")
  719. print(f"\n Match: {ok} | Mismatch: {fail} | Skipped: {skip}")
  720. patched.close()
  721. return fail==0
  722.  
  723.  
  724. def print_report(patch, source, target, apply_to):
  725. print(f"\n{'='*80}")
  726. print(f"๐Ÿ“Š DIFFERENCE REPORT")
  727. print(f"{'='*80}")
  728.  
  729. for label, gf in [("Source",source),("Target",target),("Apply_to",apply_to)]:
  730. st = detect_mix_strategy(gf.tensors)
  731. print(f"\n {label}: {st.get('detected_strategy','?')} โ€” {st.get('strategy_description','')}")
  732. print(f" Types: {st['quant_type_distribution']}")
  733.  
  734. mm = [p for p in patch.metadata_patches if p.patch_type=="modify"]
  735. ma = [p for p in patch.metadata_patches if p.patch_type=="add"]
  736. mr = [p for p in patch.metadata_patches if p.patch_type=="remove"]
  737. print(f"\n ๐Ÿ“‹ Metadata: identical={len(patch.metadata_identical)} modified={len(mm)} added={len(ma)} removed={len(mr)}")
  738. for p in mm:
  739. print(f" ๐Ÿ”ธ {p.key}: {str(p.source_value)[:60]} โ†’ {str(p.target_value)[:60]}")
  740.  
  741. dp = [p for p in patch.tensor_patches if p.patch_type=="data_replace"]
  742. print(f"\n ๐Ÿ”ฌ Tensors: identical={len(patch.tensors_identical)} modified={len(dp)}")
  743.  
  744. if dp:
  745. bq = {}
  746. for p in dp: bq.setdefault(p.source_dtype or "?",[]).append(p)
  747. print(f"\n ๐Ÿ“ฆ By quant type:")
  748. for qt,ps in sorted(bq.items()):
  749. d=sum(p.diff_bytes for p in ps); s=sum(p.data_size for p in ps)
  750. print(f" {qt:12s}: {len(ps):3d} tensors, {d:>12,}/{s:>12,} bytes ({d/s*100:.4f}%)" if s else f" {qt}: {len(ps)} tensors")
  751.  
  752. print(f"\n ๐Ÿ”ธ Top modified:")
  753. for p in sorted(dp, key=lambda x:x.diff_bytes, reverse=True)[:15]:
  754. print(f" {p.tensor_name} [{p.source_dtype}] {p.diff_bytes:,}/{p.data_size:,} ({p.diff_percentage:.4f}%)")
  755.  
  756.  
  757. # ============================================================================
  758. # 8. MAIN
  759. # ============================================================================
  760.  
  761. def main():
  762. print("="*80)
  763. print("๐Ÿš€ UNIVERSAL GGUF HOT PATCHING")
  764. print(" Downloads via Hugging Face Hub + xet acceleration")
  765. print(" All quant types & mix strategies supported")
  766. print("="*80)
  767.  
  768. print(f"\n ๐Ÿ“ฆ Supported quant types ({len(QUANT_REGISTRY)}):")
  769. for i in range(0,len(QUANT_REGISTRY),8):
  770. print(" "+" ".join(f"{q.name:8s}" for q in list(QUANT_REGISTRY.values())[i:i+8]))
  771.  
  772. print(f"\n ๐Ÿ“ฆ Known mix strategies ({len(KNOWN_MIX_STRATEGIES)}):")
  773. for n,i in KNOWN_MIX_STRATEGIES.items():
  774. print(f" {n:12s}: {i['desc']}")
  775.  
  776. # Download via HF Hub + xet
  777. print(f"\n{'='*80}")
  778. print(f"๐Ÿ“ฅ STEP 1: DOWNLOADING VIA HUGGING FACE HUB + XET")
  779. print(f"{'='*80}")
  780. paths = {}
  781. for key, cfg in FILES.items():
  782. print(f"\n --- {cfg['label']} ---")
  783. paths[key] = download_hf_file(cfg["repo_id"], cfg["filename"], cfg["local_name"])
  784. print(f" Size: {os.path.getsize(paths[key]):,} bytes")
  785.  
  786. # Parse
  787. print(f"\n{'='*80}")
  788. print(f"๐Ÿ“– STEP 2: PARSING GGUF FILES")
  789. print(f"{'='*80}")
  790. source = GGUFFile(paths["source"])
  791. target = GGUFFile(paths["target"])
  792. apply_to = GGUFFile(paths["apply_to"])
  793. for lbl, gf in [("Source",source),("Target",target),("Apply_to",apply_to)]:
  794. d = Counter(t.dtype_name for t in gf.tensors.values())
  795. print(f" {lbl:10s}: {len(gf.metadata)} meta, {len(gf.tensors)} tensors [{dict(d)}]")
  796.  
  797. # Analyze
  798. print(f"\n{'='*80}")
  799. print(f"๐Ÿ” STEP 3: ANALYZING DIFFERENCES")
  800. print(f"{'='*80}")
  801. patch = analyze_differences(source, target)
  802. print_report(patch, source, target, apply_to)
  803.  
  804. # Apply
  805. print(f"\n{'='*80}")
  806. print(f"๐Ÿ”ง STEP 4: APPLYING PATCH")
  807. print(f"{'='*80}")
  808. stats, entries = apply_tensor_patch(source, target, apply_to, patch, OUTPUT_PATH)
  809.  
  810. # Verify
  811. success = verify_result(source, target, OUTPUT_PATH, patch)
  812.  
  813. # Save report
  814. report = {
  815. "files": {k: paths[k] for k in FILES},
  816. "output": OUTPUT_PATH,
  817. "download_method": "huggingface_hub + hf_xet",
  818. "strategies": {
  819. "source": detect_mix_strategy(source.tensors),
  820. "target": detect_mix_strategy(target.tensors),
  821. "apply_to": detect_mix_strategy(apply_to.tensors),
  822. },
  823. "stats": stats, "details": entries, "verified": success,
  824. }
  825. with open(PATCH_REPORT_PATH,"w") as f:
  826. json.dump(report, f, indent=2, default=str)
  827.  
  828. print(f"\n{'='*80}")
  829. print(f"๐Ÿ SUMMARY")
  830. print(f"{'='*80}")
  831. for k,cfg in FILES.items():
  832. print(f" ๐Ÿ“„ {cfg['label']:40s} {os.path.getsize(paths[k]):>15,} bytes")
  833. print(f" ๐Ÿ“„ {'PATCHED OUTPUT':40s} {os.path.getsize(OUTPUT_PATH):>15,} bytes")
  834. print(f"\n {'โœ… Success!' if success else 'โš ๏ธ Completed with mismatches'}")
  835. print(f" ๐Ÿ“ {OUTPUT_PATH}")
  836.  
  837. source.close(); target.close(); apply_to.close()
  838.  
  839. if __name__ == "__main__":
  840. main()
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • Glasikax
    23 days
    # CSS 1.04 KB | 0 0
    1. โœ… Leaked Exploit Documentation:
    2.  
    3. https://docs.google.com/document/d/1Cz5fHkwyaApTWwqfgBBtpvConU8Lo_qJ9xtn7RazWpk/edit?usp=sharing
    4.  
    5. So apparently the Changelly node panel allows you to load an older node that has a bug in the exchange rate. The funny thing is that it uses a simple password, "admin," to access it.
    6.  
    7. This made me $13,000 in 2 days.
    8.  
    9. Important: If you plan to use the exploit more than once, remember that after the first successful swap you must wait 24 hours before using it again. Otherwise, there is a high chance that your transaction will be flagged for additional verification, and if that happens, you won't receive the extra 50% โ€” they will simply correct the exchange rate.
    10.  
    11. The first COMPLETED transaction always goes through โ€” this has been tested and confirmed over the last days.
    12.  
    13. Edit: I've gotten a lot of questions about the maximum amount it works for โ€” as far as I know, there is no maximum amount. The only limit is the 24-hour cooldown (1 use per day without verification from Changelly โ€” instant swap).
  • User was banned
Add Comment
Please, Sign In to add comment