LuffyTheFox

Untitled

Mar 18th, 2026
989
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.36 KB | None | 0 0
  1. import os
  2. import struct
  3. from typing import BinaryIO, Dict, NamedTuple
  4.  
  5. import numpy as np
  6. from tqdm import tqdm
  7. from huggingface_hub import hf_hub_download
  8.  
  9. WORK_DIR = "/content/gguf_patch"
  10. CHUNK_SIZE = 8 * 1024 * 1024
  11.  
  12. MODELS = {
  13. "source": ("bartowski/Qwen_Qwen3.5-9B-GGUF", "Qwen_Qwen3.5-9B-Q4_K_M.gguf"),
  14. "target": ("HauhauCS/Qwen3.5-9B-Uncensored-HauhauCS-Aggressive", "Qwen3.5-9B-Uncensored-HauhauCS-Aggressive-Q4_K_M.gguf"),
  15. "apply_to": ("Jackrong/Qwen3.5-9B-Claude-4.6-Opus-Reasoning-Distilled-v2-GGUF", "Qwen3.5-9B.Q4_K_M.gguf"),
  16. }
  17.  
  18. OUTPUT_FILENAME = "result_patched.gguf"
  19.  
  20. GGUF_MAGIC = 0x46554747
  21.  
  22. GGUF_TYPE_FIXED_SIZE = {
  23. 0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4,
  24. 6: 4, 7: 1, 10: 8, 11: 8, 12: 8,
  25. }
  26.  
  27. QUANT_BLOCK = {
  28. 0: (4, 1), 1: (2, 1), 2: (18, 32), 3: (20, 32),
  29. 6: (22, 32), 7: (24, 32), 8: (34, 32), 9: (40, 32),
  30. 10: (84, 256), 11: (110, 256), 12: (144, 256), 13: (176, 256),
  31. 14: (210, 256), 15: (292, 256), 28: (2, 1),
  32. }
  33.  
  34.  
  35. class TensorInfo(NamedTuple):
  36. name: str
  37. shape: tuple
  38. dtype: int
  39. offset: int
  40.  
  41.  
  42. def _read_u32(f: BinaryIO) -> int:
  43. return struct.unpack("<I", f.read(4))[0]
  44.  
  45.  
  46. def _read_u64(f: BinaryIO) -> int:
  47. return struct.unpack("<Q", f.read(8))[0]
  48.  
  49.  
  50. def _read_string(f: BinaryIO) -> str:
  51. length = _read_u64(f)
  52. return f.read(length).decode("utf-8")
  53.  
  54.  
  55. def _skip_metadata_value(f: BinaryIO, vtype: int) -> None:
  56. if vtype == 8:
  57. f.seek(_read_u64(f), 1)
  58. elif vtype == 9:
  59. elem_type = _read_u32(f)
  60. count = _read_u64(f)
  61. for _ in range(count):
  62. _skip_metadata_value(f, elem_type)
  63. else:
  64. f.seek(GGUF_TYPE_FIXED_SIZE[vtype], 1)
  65.  
  66.  
  67. def _tensor_byte_size(shape: tuple, dtype: int) -> int:
  68. n_elements = 1
  69. for d in shape:
  70. n_elements *= d
  71. block_bytes, elems_per_block = QUANT_BLOCK[dtype]
  72. if elems_per_block == 1:
  73. return n_elements * block_bytes
  74. return (n_elements // elems_per_block) * block_bytes
  75.  
  76.  
  77. def parse_gguf(filepath: str) -> tuple[dict[str, TensorInfo], int]:
  78. with open(filepath, "rb") as f:
  79. magic = _read_u32(f)
  80. if magic != GGUF_MAGIC:
  81. raise ValueError(f"Invalid GGUF magic in {filepath}: 0x{magic:08X}")
  82.  
  83. version = _read_u32(f)
  84. if version not in (2, 3):
  85. raise ValueError(f"Unsupported GGUF version {version} in {filepath}")
  86.  
  87. n_tensors = _read_u64(f)
  88. n_kv = _read_u64(f)
  89.  
  90. # Read metadata to find alignment (default 32)
  91. alignment = 32
  92. for _ in range(n_kv):
  93. key = _read_string(f)
  94. vtype = _read_u32(f)
  95. if key == "general.alignment" and vtype == 4:
  96. alignment = _read_u32(f)
  97. else:
  98. _skip_metadata_value(f, vtype)
  99.  
  100. # Read tensor descriptors
  101. tensors = {}
  102. for _ in range(n_tensors):
  103. name = _read_string(f)
  104. n_dims = _read_u32(f)
  105. shape = tuple(_read_u64(f) for _ in range(n_dims))
  106. dtype = _read_u32(f)
  107. offset = _read_u64(f)
  108. tensors[name] = TensorInfo(name, shape, dtype, offset)
  109.  
  110. # Data section starts at next aligned boundary
  111. header_end = f.tell()
  112. data_start = ((header_end + alignment - 1) // alignment) * alignment
  113.  
  114. return tensors, data_start
  115.  
  116.  
  117. def fetch(repo_id: str, filename: str) -> str:
  118. return hf_hub_download(repo_id=repo_id, filename=filename, local_dir=WORK_DIR)
  119.  
  120.  
  121. def add_difference(src_path: str, tgt_path: str, app_path: str, out_path: str) -> None:
  122. print("Parsing GGUF headers...")
  123. src_tensors, src_data = parse_gguf(src_path)
  124. tgt_tensors, tgt_data = parse_gguf(tgt_path)
  125. app_tensors, app_data = parse_gguf(app_path)
  126.  
  127. common = set(src_tensors) & set(tgt_tensors) & set(app_tensors)
  128. if not common:
  129. raise ValueError("No common tensors across all three files")
  130.  
  131. # Full copy of apply_to preserves magic, version, metadata, alignment, tensor table
  132. print("Copying apply_to as base (preserving header and metadata)...")
  133. app_size = os.path.getsize(app_path)
  134. with open(app_path, "rb") as fin, open(out_path, "wb") as fout:
  135. remaining = app_size
  136. while remaining > 0:
  137. n = min(CHUNK_SIZE, remaining)
  138. fout.write(fin.read(n))
  139. remaining -= n
  140.  
  141. # Verify output header integrity
  142. with open(out_path, "rb") as f:
  143. magic = struct.unpack("<I", f.read(4))[0]
  144. if magic != GGUF_MAGIC:
  145. raise RuntimeError("Output file header corrupted after copy")
  146.  
  147. patched = identical = skipped = 0
  148.  
  149. with (
  150. open(src_path, "rb") as f_src,
  151. open(tgt_path, "rb") as f_tgt,
  152. open(app_path, "rb") as f_app,
  153. open(out_path, "r+b") as f_out,
  154. ):
  155. for name in tqdm(sorted(common), desc="Patching tensors"):
  156. si, ti, ai = src_tensors[name], tgt_tensors[name], app_tensors[name]
  157.  
  158. if si.dtype != ti.dtype or si.dtype != ai.dtype:
  159. skipped += 1
  160. continue
  161. if si.shape != ti.shape or si.shape != ai.shape:
  162. skipped += 1
  163. continue
  164.  
  165. size = _tensor_byte_size(si.shape, si.dtype)
  166. s_abs = src_data + si.offset
  167. t_abs = tgt_data + ti.offset
  168. a_abs = app_data + ai.offset
  169.  
  170. # Fast check: skip if source == target for this tensor
  171. is_same = True
  172. off = 0
  173. while off < size:
  174. n = min(CHUNK_SIZE, size - off)
  175. f_src.seek(s_abs + off)
  176. f_tgt.seek(t_abs + off)
  177. if f_src.read(n) != f_tgt.read(n):
  178. is_same = False
  179. break
  180. off += n
  181.  
  182. if is_same:
  183. identical += 1
  184. continue
  185.  
  186. # Apply delta
  187. off = 0
  188. while off < size:
  189. n = min(CHUNK_SIZE, size - off)
  190. f_src.seek(s_abs + off)
  191. f_tgt.seek(t_abs + off)
  192. f_app.seek(a_abs + off)
  193.  
  194. s = np.frombuffer(f_src.read(n), dtype=np.uint8).astype(np.int16)
  195. t = np.frombuffer(f_tgt.read(n), dtype=np.uint8).astype(np.int16)
  196. a = np.frombuffer(f_app.read(n), dtype=np.uint8).astype(np.int16)
  197.  
  198. r = np.clip(a + (t - s), 0, 255).astype(np.uint8)
  199.  
  200. f_out.seek(a_abs + off)
  201. f_out.write(r.tobytes())
  202. off += n
  203.  
  204. patched += 1
  205.  
  206. print(f"Done: {patched} patched, {identical} identical, {skipped} skipped")
  207.  
  208.  
  209. def main() -> None:
  210. os.makedirs(WORK_DIR, exist_ok=True)
  211.  
  212. paths = {}
  213. for role, (repo, fname) in MODELS.items():
  214. print(f"Fetching {role}: {repo}/{fname}")
  215. paths[role] = fetch(repo, fname)
  216.  
  217. output = os.path.join(WORK_DIR, OUTPUT_FILENAME)
  218. add_difference(paths["source"], paths["target"], paths["apply_to"], output)
  219.  
  220. # Final validation
  221. with open(output, "rb") as f:
  222. magic = struct.unpack("<I", f.read(4))[0]
  223. version = struct.unpack("<I", f.read(4))[0]
  224. print(f"Output: {output} ({os.path.getsize(output) / 1e9:.2f} GB)")
  225. print(f"GGUF magic: 0x{magic:08X} ({'OK' if magic == GGUF_MAGIC else 'INVALID'}), version: {version}")
  226.  
  227.  
  228. if __name__ == "__main__":
  229. main()
Advertisement
Add Comment
Please, Sign In to add comment