aetherflow-ai 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. aetherflow/__init__.py +322 -0
  2. aetherflow/agent_api.py +234 -0
  3. aetherflow/backends/__init__.py +69 -0
  4. aetherflow/backends/base.py +74 -0
  5. aetherflow/backends/capabilities.py +286 -0
  6. aetherflow/backends/contracts.py +278 -0
  7. aetherflow/backends/cuda/__init__.py +16 -0
  8. aetherflow/backends/cuda/backend.py +1023 -0
  9. aetherflow/backends/cuda/codegen.py +2874 -0
  10. aetherflow/backends/cuda/cublas.py +428 -0
  11. aetherflow/backends/cuda/cudnn.py +305 -0
  12. aetherflow/backends/cuda/cufft.py +384 -0
  13. aetherflow/backends/cuda/cusparse.py +381 -0
  14. aetherflow/backends/cuda/dialect.py +80 -0
  15. aetherflow/backends/cuda/memory.py +243 -0
  16. aetherflow/backends/device_attention.py +257 -0
  17. aetherflow/backends/device_backend.py +1569 -0
  18. aetherflow/backends/device_conv.py +970 -0
  19. aetherflow/backends/device_elementwise.py +629 -0
  20. aetherflow/backends/device_index.py +230 -0
  21. aetherflow/backends/device_linear.py +1301 -0
  22. aetherflow/backends/device_loss.py +109 -0
  23. aetherflow/backends/device_misc.py +249 -0
  24. aetherflow/backends/device_norm.py +197 -0
  25. aetherflow/backends/device_plan.py +1062 -0
  26. aetherflow/backends/device_pool.py +592 -0
  27. aetherflow/backends/device_reduce.py +512 -0
  28. aetherflow/backends/device_scan.py +457 -0
  29. aetherflow/backends/device_shape.py +108 -0
  30. aetherflow/backends/device_shared.py +1107 -0
  31. aetherflow/backends/device_sparse.py +373 -0
  32. aetherflow/backends/discovery.py +286 -0
  33. aetherflow/backends/hardware.py +784 -0
  34. aetherflow/backends/hip/__init__.py +15 -0
  35. aetherflow/backends/hip/backend.py +567 -0
  36. aetherflow/backends/hip/blas.py +227 -0
  37. aetherflow/backends/hip/codegen.py +109 -0
  38. aetherflow/backends/hip/dialect.py +62 -0
  39. aetherflow/backends/hip/memory.py +418 -0
  40. aetherflow/backends/hip/rtc.py +126 -0
  41. aetherflow/backends/hip/runtime.py +2018 -0
  42. aetherflow/backends/kernel_cache.py +240 -0
  43. aetherflow/backends/reference_backend.py +76 -0
  44. aetherflow/backends/registry.py +224 -0
  45. aetherflow/conformance.py +2791 -0
  46. aetherflow/deploy.py +259 -0
  47. aetherflow/dynamic.py +252 -0
  48. aetherflow/frontend/__init__.py +39 -0
  49. aetherflow/frontend/compat.py +118 -0
  50. aetherflow/frontend/eager.py +345 -0
  51. aetherflow/frontend/module.py +320 -0
  52. aetherflow/frontend/torch_export.py +2047 -0
  53. aetherflow/fuzz.py +1093 -0
  54. aetherflow/gguf.py +693 -0
  55. aetherflow/ir/__init__.py +144 -0
  56. aetherflow/ir/control.py +444 -0
  57. aetherflow/ir/grad.py +240 -0
  58. aetherflow/ir/grad_rules.py +1814 -0
  59. aetherflow/ir/graph.py +370 -0
  60. aetherflow/ir/liveness.py +227 -0
  61. aetherflow/ir/loop.py +437 -0
  62. aetherflow/ir/ops.py +6333 -0
  63. aetherflow/ir/second_order.py +111 -0
  64. aetherflow/ir/serialize.py +180 -0
  65. aetherflow/ir/shape_contract.py +146 -0
  66. aetherflow/ir/types.py +363 -0
  67. aetherflow/ir/verifier.py +130 -0
  68. aetherflow/ir/version.py +196 -0
  69. aetherflow/lower/__init__.py +202 -0
  70. aetherflow/lower/cstyle.py +354 -0
  71. aetherflow/lower/elementwise.py +346 -0
  72. aetherflow/lower/indexing.py +170 -0
  73. aetherflow/lower/kernel.py +448 -0
  74. aetherflow/lower/kernels/__init__.py +262 -0
  75. aetherflow/lower/kernels/attention.py +390 -0
  76. aetherflow/lower/kernels/common.py +95 -0
  77. aetherflow/lower/kernels/conv.py +2927 -0
  78. aetherflow/lower/kernels/elementwise.py +676 -0
  79. aetherflow/lower/kernels/image.py +97 -0
  80. aetherflow/lower/kernels/interpolate.py +381 -0
  81. aetherflow/lower/kernels/misc.py +154 -0
  82. aetherflow/lower/kernels/norm.py +675 -0
  83. aetherflow/lower/kernels/pool.py +650 -0
  84. aetherflow/lower/kernels/reduce.py +891 -0
  85. aetherflow/lower/kernels/scan.py +939 -0
  86. aetherflow/lower/kernels/sparse.py +680 -0
  87. aetherflow/lower/plan.py +884 -0
  88. aetherflow/lower/translate.py +382 -0
  89. aetherflow/models/__init__.py +227 -0
  90. aetherflow/models/cached_attention.py +1133 -0
  91. aetherflow/models/cnn.py +208 -0
  92. aetherflow/models/hf_export.py +363 -0
  93. aetherflow/models/llama.py +875 -0
  94. aetherflow/models/lm.py +2888 -0
  95. aetherflow/models/lm_bpe.py +812 -0
  96. aetherflow/models/lm_text.py +159 -0
  97. aetherflow/models/lm_tools.py +1048 -0
  98. aetherflow/models/lm_unigram.py +794 -0
  99. aetherflow/models/lm_wordpiece.py +429 -0
  100. aetherflow/models/mamba.py +917 -0
  101. aetherflow/models/mamba_reference.py +183 -0
  102. aetherflow/models/mlp.py +84 -0
  103. aetherflow/models/moe.py +158 -0
  104. aetherflow/models/quantize.py +775 -0
  105. aetherflow/models/rnn.py +157 -0
  106. aetherflow/models/snn.py +362 -0
  107. aetherflow/models/speculative.py +426 -0
  108. aetherflow/models/ssm.py +179 -0
  109. aetherflow/models/transformer.py +382 -0
  110. aetherflow/passes/__init__.py +73 -0
  111. aetherflow/passes/autocast.py +180 -0
  112. aetherflow/passes/base.py +92 -0
  113. aetherflow/passes/cse.py +85 -0
  114. aetherflow/passes/dce.py +57 -0
  115. aetherflow/passes/fold.py +158 -0
  116. aetherflow/passes/fusion.py +268 -0
  117. aetherflow/passes/layout.py +261 -0
  118. aetherflow/passes/registry.py +213 -0
  119. aetherflow/passes/simplify.py +42 -0
  120. aetherflow/plugin.py +75 -0
  121. aetherflow/runtime/__init__.py +48 -0
  122. aetherflow/runtime/bf16.py +83 -0
  123. aetherflow/runtime/device_control.py +472 -0
  124. aetherflow/runtime/events.py +251 -0
  125. aetherflow/runtime/executor.py +617 -0
  126. aetherflow/runtime/fp8.py +275 -0
  127. aetherflow/runtime/paged_cache.py +897 -0
  128. aetherflow/runtime/prefix_store.py +508 -0
  129. aetherflow/runtime/reference.py +27 -0
  130. aetherflow/runtime/telemetry.py +596 -0
  131. aetherflow/runtime/trace.py +256 -0
  132. aetherflow/serve/__init__.py +20 -0
  133. aetherflow/serve/openai.py +767 -0
  134. aetherflow/train/__init__.py +154 -0
  135. aetherflow/train/_arrays.py +150 -0
  136. aetherflow/train/amp.py +219 -0
  137. aetherflow/train/bn.py +224 -0
  138. aetherflow/train/checkpoint.py +480 -0
  139. aetherflow/train/data.py +219 -0
  140. aetherflow/train/dataset.py +544 -0
  141. aetherflow/train/distributed.py +394 -0
  142. aetherflow/train/ema.py +143 -0
  143. aetherflow/train/grads.py +293 -0
  144. aetherflow/train/host_collective.py +497 -0
  145. aetherflow/train/lm.py +117 -0
  146. aetherflow/train/loop.py +1860 -0
  147. aetherflow/train/loss.py +105 -0
  148. aetherflow/train/monitor.py +208 -0
  149. aetherflow/train/nccl.py +831 -0
  150. aetherflow/train/optim.py +456 -0
  151. aetherflow/train/parallel.py +1296 -0
  152. aetherflow/train/params.py +220 -0
  153. aetherflow/train/pipeline.py +532 -0
  154. aetherflow/train/recompute.py +344 -0
  155. aetherflow/train/schedule.py +212 -0
  156. aetherflow/train/shard_io.py +685 -0
  157. aetherflow/train/sharded.py +490 -0
  158. aetherflow/train/tensor_parallel.py +527 -0
  159. aetherflow/train/zero.py +847 -0
  160. aetherflow/train/zero2.py +410 -0
  161. aetherflow/train/zero3.py +529 -0
  162. aetherflow/tuning/__init__.py +95 -0
  163. aetherflow/tuning/cost.py +535 -0
  164. aetherflow/tuning/paired.py +991 -0
  165. aetherflow/tuning/policy.py +195 -0
  166. aetherflow/tuning/search.py +290 -0
  167. aetherflow/tuning/signature.py +90 -0
  168. aetherflow/tuning/space.py +124 -0
  169. aetherflow/tuning/store.py +280 -0
  170. aetherflow/weights.py +1271 -0
  171. aetherflow_ai-0.2.0.dist-info/METADATA +578 -0
  172. aetherflow_ai-0.2.0.dist-info/RECORD +175 -0
  173. aetherflow_ai-0.2.0.dist-info/WHEEL +5 -0
  174. aetherflow_ai-0.2.0.dist-info/licenses/LICENSE +201 -0
  175. aetherflow_ai-0.2.0.dist-info/top_level.txt +1 -0
aetherflow/gguf.py ADDED
@@ -0,0 +1,693 @@
1
+ """GGUF 权重读取:llama.cpp 生态的容器格式与量化块解码。
2
+
3
+ 为什么要自己读:与 ``weights.py`` 同一条理由——运行期只依赖 numpy。而且 GGUF
4
+ 跟 safetensors 的差别不在"又一个容器",在于**张量本身不是浮点数**:一个
5
+ ``Q4_K`` 张量存的是 256 个元素一组的块(缩放、最小值和 4 bit 码点),不按块
6
+ 解码出来的只是一串噪声。这里把容器解析与块解码放在一起,判据是"解出来能逐元素
7
+ 对上",不是"能读出个数组"。
8
+
9
+ 格式(v2 / v3,均小端):
10
+
11
+ - 头:magic ``GGUF`` + version(u32) + tensor_count(u64) + metadata_kv_count(u64);
12
+ - metadata:key(string) + value_type(u32) + value;value 可以是标量、字符串或
13
+ 同类型数组;
14
+ - tensor info:name + n_dims(u32) + dims(u64 × n_dims) + type(u32) + offset(u64);
15
+ ``offset`` 相对数据区;
16
+ - 数据区起点 = 头结束位置按 ``general.alignment`` 向上取整(缺省 32)。
17
+
18
+ **维度顺序**:ggml 的 ``ne[0]`` 是最内层(变化最快)的维,numpy 的最内层是最后
19
+ 一维,所以 ``info.shape`` 存的是 ``dims[::-1]``,``tensor()`` 直接按它 reshape。
20
+
21
+ **只做能逐元素对上的解码。** F32 / F16 / BF16 / Q4_0 / Q4_1 / Q5_0 / Q5_1 /
22
+ Q8_0 / Q8_1 / Q2_K / Q3_K / Q4_K / Q5_K / Q6_K / Q8_K 解成 float32(fp8 不在
23
+ GGUF 里);I8 / I16 / I32 / I64 原样返回整数;F64 原样返回。IQ 系(格点码本)、
24
+ TQ 系(三值)与 v1 头显式拒绝——不认识的码本"猜一个"会安静地给出错权重,
25
+ 比读不出来更糟。
26
+
27
+ **先校验后读。** 头部长度、字符串长度、数组元素数、张量字节范围全部在切片之前
28
+ 检查;解析失败的错误里带具体字段(哪个张量、哪个偏移、期望多少字节)。
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import mmap
34
+ import os
35
+ import struct
36
+ from dataclasses import dataclass, field
37
+ from typing import Dict, List, Optional, Tuple, Union
38
+
39
+ import numpy as np
40
+
41
+ __all__ = [
42
+ "GGUFError",
43
+ "GGUFTensorInfo",
44
+ "GGUFFile",
45
+ "read_gguf",
46
+ "GGML_TYPES",
47
+ ]
48
+
49
+ _MAGIC = 0x46554747 # "GGUF" 小端
50
+ _SUPPORTED_VERSIONS = (2, 3)
51
+
52
+ # 头 / 元数据里各类计的防爆上限。正常模型 metadata 只有几十项,张量数最多几千;
53
+ # 一个声称"有 40 亿个张量"的文件只可能是在骗读取方先分配内存。
54
+ _MAX_TENSORS = 1 << 20
55
+ _MAX_KV = 1 << 20
56
+ _MAX_STRING_BYTES = 64 << 20
57
+ _MAX_ARRAY_ELEMENTS = 1 << 28
58
+
59
+ # GGUF 的元数据值类型(键 → struct 格式)。STRING / ARRAY 单独处理。
60
+ _VALUE_TYPES = {
61
+ 0: ("UINT8", "<B", 1),
62
+ 1: ("INT8", "<b", 1),
63
+ 2: ("UINT16", "<H", 2),
64
+ 3: ("INT16", "<h", 2),
65
+ 4: ("UINT32", "<I", 4),
66
+ 5: ("INT32", "<i", 4),
67
+ 6: ("FLOAT32", "<f", 4),
68
+ 7: ("BOOL", "<B", 1),
69
+ 10: ("UINT64", "<Q", 8),
70
+ 11: ("INT64", "<q", 8),
71
+ 12: ("FLOAT64", "<d", 8),
72
+ }
73
+ _VALUE_STRING = 8
74
+ _VALUE_ARRAY = 9
75
+
76
+ # ggml 张量类型:名字 → (type id, block_size, block_bytes)。block_size=1 表示
77
+ # 逐元素存储,block_bytes 就是单个元素字节数。只列能逐元素解出来的那些。
78
+ GGML_TYPES: Dict[str, Tuple[int, int, int]] = {
79
+ "F32": (0, 1, 4),
80
+ "F16": (1, 1, 2),
81
+ "Q4_0": (2, 32, 18),
82
+ "Q4_1": (3, 32, 20),
83
+ "Q5_0": (6, 32, 22),
84
+ "Q5_1": (7, 32, 24),
85
+ "Q8_0": (8, 32, 34),
86
+ "Q8_1": (9, 32, 36),
87
+ "Q2_K": (10, 256, 84),
88
+ "Q3_K": (11, 256, 110),
89
+ "Q4_K": (12, 256, 144),
90
+ "Q5_K": (13, 256, 176),
91
+ "Q6_K": (14, 256, 210),
92
+ "Q8_K": (15, 256, 292),
93
+ "I8": (24, 1, 1),
94
+ "I16": (25, 1, 2),
95
+ "I32": (26, 1, 4),
96
+ "I64": (27, 1, 8),
97
+ "F64": (28, 1, 8),
98
+ "BF16": (30, 1, 2),
99
+ }
100
+
101
+ _BY_ID: Dict[int, str] = {spec[0]: name for name, spec in GGML_TYPES.items()}
102
+
103
+
104
+ class GGUFError(ValueError):
105
+ """GGUF 文件不可读、不合规,或用了本实现不支持的块类型。"""
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # 块结构:与 ggml 的 block_* 布局逐字节一致(小端)。
110
+ # ---------------------------------------------------------------------------
111
+
112
+ _BLOCK_LAYOUT: Dict[str, List[Tuple[str, object]]] = {
113
+ "Q4_0": [("d", "<f2"), ("qs", ("u1", 16))],
114
+ "Q4_1": [("d", "<f2"), ("m", "<f2"), ("qs", ("u1", 16))],
115
+ "Q5_0": [("d", "<f2"), ("qh", ("u1", 4)), ("qs", ("u1", 16))],
116
+ "Q5_1": [("d", "<f2"), ("m", "<f2"), ("qh", ("u1", 4)), ("qs", ("u1", 16))],
117
+ "Q8_0": [("d", "<f2"), ("qs", ("i1", 32))],
118
+ "Q8_1": [("d", "<f2"), ("s", "<f2"), ("qs", ("i1", 32))],
119
+ "Q2_K": [("scales", ("u1", 16)), ("qs", ("u1", 64)), ("d", "<f2"), ("dmin", "<f2")],
120
+ "Q3_K": [("hmask", ("u1", 32)), ("qs", ("u1", 64)), ("scales", ("u1", 12)), ("d", "<f2")],
121
+ "Q4_K": [("d", "<f2"), ("dmin", "<f2"), ("scales", ("u1", 12)), ("qs", ("u1", 128))],
122
+ "Q5_K": [
123
+ ("d", "<f2"),
124
+ ("dmin", "<f2"),
125
+ ("scales", ("u1", 12)),
126
+ ("qh", ("u1", 32)),
127
+ ("qs", ("u1", 128)),
128
+ ],
129
+ "Q6_K": [("ql", ("u1", 128)), ("qh", ("u1", 64)), ("scales", ("i1", 16)), ("d", "<f2")],
130
+ "Q8_K": [("d", "<f4"), ("qs", ("i1", 256)), ("bsums", ("<i2", 16))],
131
+ }
132
+
133
+ _BLOCK_DTYPE: Dict[str, np.dtype] = {
134
+ name: np.dtype([(fname, ftype) if isinstance(ftype, str) else (fname, ftype[0], (ftype[1],))
135
+ for fname, ftype in layout])
136
+ for name, layout in _BLOCK_LAYOUT.items()
137
+ }
138
+
139
+ for _name, _spec in GGML_TYPES.items():
140
+ if _name in _BLOCK_DTYPE:
141
+ _actual = _BLOCK_DTYPE[_name].itemsize
142
+ if _actual != _spec[2]:
143
+ raise AssertionError(f"{_name} 块结构 {_actual} 字节与类型表 {_spec[2]} 不一致")
144
+
145
+
146
+ def _f16(blocks: np.ndarray, name: str) -> np.ndarray:
147
+ """半精度字段 → (块数, 1) 的 float32,便于广播。"""
148
+ return blocks[name].astype(np.float32)[:, None]
149
+
150
+
151
+ def _dq_q4_0(raw: bytes, count: int) -> np.ndarray:
152
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q4_0"], count=count)
153
+ q = b["qs"].astype(np.int32)
154
+ out = np.empty((count, 32), dtype=np.float32)
155
+ out[:, :16] = (q & 0xF) - 8
156
+ out[:, 16:] = (q >> 4) - 8
157
+ return (out * _f16(b, "d")).reshape(-1)
158
+
159
+
160
+ def _dq_q4_1(raw: bytes, count: int) -> np.ndarray:
161
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q4_1"], count=count)
162
+ q = b["qs"].astype(np.int32)
163
+ out = np.empty((count, 32), dtype=np.float32)
164
+ out[:, :16] = q & 0xF
165
+ out[:, 16:] = q >> 4
166
+ return (out * _f16(b, "d") + _f16(b, "m")).reshape(-1)
167
+
168
+
169
+ def _qh_bits(blocks: np.ndarray) -> np.ndarray:
170
+ """Q5_0 / Q5_1 的 4 字节 ``qh`` → 32 个低位标志的 ``(块数, 16)``。"""
171
+ bytes_ = blocks["qh"].astype(np.uint32)
172
+ word = (
173
+ bytes_[:, 0]
174
+ | (bytes_[:, 1] << 8)
175
+ | (bytes_[:, 2] << 16)
176
+ | (bytes_[:, 3] << 24)
177
+ )
178
+ low = np.arange(16, dtype=np.uint32)
179
+ x0 = ((word[:, None] >> low) & 1).astype(np.int32) << 4
180
+ x1 = ((word[:, None] >> (low + 16)) & 1).astype(np.int32) << 4
181
+ return np.concatenate([x0, x1], axis=1) # (块数, 32)
182
+
183
+
184
+ def _q5_codes(blocks: np.ndarray) -> np.ndarray:
185
+ q = blocks["qs"].astype(np.int32)
186
+ bits = _qh_bits(blocks)
187
+ low = (q & 0xF) | bits[:, :16]
188
+ high = (q >> 4) | bits[:, 16:]
189
+ return np.concatenate([low, high], axis=1) # 前 16 是低 4 位,后 16 是高 4 位
190
+
191
+
192
+ def _dq_q5_0(raw: bytes, count: int) -> np.ndarray:
193
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q5_0"], count=count)
194
+ return (_q5_codes(b).astype(np.float32) * _f16(b, "d")).reshape(-1)
195
+
196
+
197
+ def _dq_q5_1(raw: bytes, count: int) -> np.ndarray:
198
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q5_1"], count=count)
199
+ return (_q5_codes(b).astype(np.float32) * _f16(b, "d") + _f16(b, "m")).reshape(-1)
200
+
201
+
202
+ def _dq_q8_0(raw: bytes, count: int) -> np.ndarray:
203
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q8_0"], count=count)
204
+ return (b["qs"].astype(np.float32) * _f16(b, "d")).reshape(-1)
205
+
206
+
207
+ def _dq_q8_1(raw: bytes, count: int) -> np.ndarray:
208
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q8_1"], count=count)
209
+ return (b["qs"].astype(np.float32) * _f16(b, "d")).reshape(-1)
210
+
211
+
212
+ def _dq_q8_k(raw: bytes, count: int) -> np.ndarray:
213
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q8_K"], count=count)
214
+ return (b["qs"].astype(np.float32) * b["d"].astype(np.float32)[:, None]).reshape(-1)
215
+
216
+
217
+ def _k4_scale_min(scales: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
218
+ """Q4_K / Q5_K 的 12 字节 6 bit 缩放与最小值 → 两组各 8 个 (缩放, 最小值)。"""
219
+ q = scales.astype(np.int32)
220
+ counts = q.shape[0]
221
+ ds = np.empty((counts, 8), dtype=np.int32)
222
+ ms = np.empty((counts, 8), dtype=np.int32)
223
+ for j in range(4):
224
+ ds[:, j] = q[:, j] & 63
225
+ ms[:, j] = q[:, j + 4] & 63
226
+ for j in range(4, 8):
227
+ ds[:, j] = (q[:, j + 4] & 0xF) | ((q[:, j - 4] >> 6) << 4)
228
+ ms[:, j] = (q[:, j + 4] >> 4) | ((q[:, j] >> 6) << 4)
229
+ return ds, ms
230
+
231
+
232
+ def _dq_q4_k(raw: bytes, count: int) -> np.ndarray:
233
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q4_K"], count=count)
234
+ ds, ms = _k4_scale_min(b["scales"])
235
+ q = b["qs"].astype(np.int32)
236
+ nib = np.stack([q & 0xF, (q >> 4) & 0xF], axis=2) # (块数, 128, 2)
237
+ vals = nib.reshape(count, 4, 32, 2).transpose(0, 1, 3, 2).reshape(count, 256)
238
+ scale = np.repeat(ds, 32, axis=1).astype(np.float32)
239
+ minimum = np.repeat(ms, 32, axis=1).astype(np.float32)
240
+ return (vals.astype(np.float32) * scale * _f16(b, "d") - minimum * _f16(b, "dmin")).reshape(-1)
241
+
242
+
243
+ def _dq_q5_k(raw: bytes, count: int) -> np.ndarray:
244
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q5_K"], count=count)
245
+ ds, ms = _k4_scale_min(b["scales"])
246
+ q = b["qs"].astype(np.int32)
247
+ qh = b["qh"].astype(np.int32)
248
+ low = np.empty((count, 4, 32), dtype=np.int32)
249
+ high = np.empty((count, 4, 32), dtype=np.int32)
250
+ for g in range(4):
251
+ group = q[:, g * 32 : (g + 1) * 32]
252
+ u1 = 1 << (2 * g)
253
+ u2 = 1 << (2 * g + 1)
254
+ low[:, g] = (group & 0xF) + np.where((qh & u1) != 0, 16, 0)
255
+ high[:, g] = (group >> 4) + np.where((qh & u2) != 0, 16, 0)
256
+ vals = np.stack([low, high], axis=2).transpose(0, 1, 3, 2).reshape(count, 256)
257
+ scale = np.repeat(ds, 32, axis=1).astype(np.float32)
258
+ minimum = np.repeat(ms, 32, axis=1).astype(np.float32)
259
+ return (vals.astype(np.float32) * scale * _f16(b, "d") - minimum * _f16(b, "dmin")).reshape(-1)
260
+
261
+
262
+ def _q3_scales(raw: np.ndarray) -> np.ndarray:
263
+ """Q3_K 的 12 字节 6 bit 缩放 → (块数, 16) 的 int32。"""
264
+ counts = raw.shape[0]
265
+ aux = np.zeros((counts, 4), dtype=np.uint32)
266
+ for word in range(3):
267
+ for byte in range(4):
268
+ aux[:, word] |= raw[:, 4 * word + byte].astype(np.uint32) << (8 * byte)
269
+ tmp = aux[:, 2].copy()
270
+ k1 = np.uint32(0x03030303)
271
+ k2 = np.uint32(0x0F0F0F0F)
272
+ a0 = (aux[:, 0] & k2) | (((tmp >> np.uint32(0)) & k1) << np.uint32(4))
273
+ a1 = (aux[:, 1] & k2) | (((tmp >> np.uint32(2)) & k1) << np.uint32(4))
274
+ a2 = ((aux[:, 0] >> np.uint32(4)) & k2) | (((tmp >> np.uint32(4)) & k1) << np.uint32(4))
275
+ a3 = ((aux[:, 1] >> np.uint32(4)) & k2) | (((tmp >> np.uint32(6)) & k1) << np.uint32(4))
276
+ packed = np.stack([a0, a1, a2, a3], axis=1) # (块数, 4)
277
+ bytes_ = np.stack([(packed >> np.uint32(8 * k)) & 0xFF for k in range(4)], axis=2)
278
+ signed = bytes_.reshape(counts, 16).astype(np.int32)
279
+ return np.where(signed >= 128, signed - 256, signed)
280
+
281
+
282
+ def _dq_q2_k(raw: bytes, count: int) -> np.ndarray:
283
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q2_K"], count=count)
284
+ sc = b["scales"].astype(np.int32)
285
+ q = b["qs"].astype(np.int32)
286
+ d = _f16(b, "d")
287
+ dmin = _f16(b, "dmin")
288
+ out = np.empty((count, 256), dtype=np.float32)
289
+ for n in range(2):
290
+ qn = q[:, n * 32 : (n + 1) * 32]
291
+ for j in range(4):
292
+ shift = 2 * j
293
+ idx = n * 8 + 2 * j
294
+ d0 = d * (sc[:, idx] & 0xF)[:, None]
295
+ m0 = dmin * (sc[:, idx] >> 4)[:, None]
296
+ d1 = d * (sc[:, idx + 1] & 0xF)[:, None]
297
+ m1 = dmin * (sc[:, idx + 1] >> 4)[:, None]
298
+ base = n * 128 + j * 32
299
+ out[:, base : base + 16] = ((qn[:, :16] >> shift) & 3) * d0 - m0
300
+ out[:, base + 16 : base + 32] = ((qn[:, 16:] >> shift) & 3) * d1 - m1
301
+ return out.reshape(-1)
302
+
303
+
304
+ def _dq_q3_k(raw: bytes, count: int) -> np.ndarray:
305
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q3_K"], count=count)
306
+ hm = b["hmask"].astype(np.int32)
307
+ q = b["qs"].astype(np.int32)
308
+ sc = _q3_scales(b["scales"])
309
+ d = _f16(b, "d")
310
+ out = np.empty((count, 256), dtype=np.float32)
311
+ for n in range(2):
312
+ qn = q[:, n * 32 : (n + 1) * 32]
313
+ for j in range(4):
314
+ shift = 2 * j
315
+ mask = 1 << (4 * n + j)
316
+ base = n * 128 + j * 32
317
+ dl = d * (sc[:, 2 * (4 * n + j)] - 32)[:, None]
318
+ dl2 = d * (sc[:, 2 * (4 * n + j) + 1] - 32)[:, None]
319
+ low = ((qn[:, :16] >> shift) & 3) - np.where((hm[:, :16] & mask) != 0, 0, 4)
320
+ high = ((qn[:, 16:] >> shift) & 3) - np.where((hm[:, 16:] & mask) != 0, 0, 4)
321
+ out[:, base : base + 16] = low * dl
322
+ out[:, base + 16 : base + 32] = high * dl2
323
+ return out.reshape(-1)
324
+
325
+
326
+ def _dq_q6_k(raw: bytes, count: int) -> np.ndarray:
327
+ b = np.frombuffer(raw, dtype=_BLOCK_DTYPE["Q6_K"], count=count)
328
+ ql = b["ql"].astype(np.int32)
329
+ qh = b["qh"].astype(np.int32)
330
+ sc = b["scales"].astype(np.int32)
331
+ d = _f16(b, "d")
332
+ half = np.arange(32) // 16 # 每 16 个元素换一个缩放
333
+ out = np.empty((count, 256), dtype=np.float32)
334
+ for n in range(2):
335
+ ql_n = ql[:, n * 64 : (n + 1) * 64]
336
+ qh_n = qh[:, n * 32 : (n + 1) * 32]
337
+ sc_n = sc[:, n * 8 : (n + 1) * 8]
338
+ q1 = ((ql_n[:, :32] & 0xF) | (((qh_n >> 0) & 3) << 4)) - 32
339
+ q2 = ((ql_n[:, 32:] & 0xF) | (((qh_n >> 2) & 3) << 4)) - 32
340
+ q3 = ((ql_n[:, :32] >> 4) | (((qh_n >> 4) & 3) << 4)) - 32
341
+ q4 = ((ql_n[:, 32:] >> 4) | (((qh_n >> 6) & 3) << 4)) - 32
342
+ base = n * 128
343
+ out[:, base : base + 32] = q1 * sc_n[:, half] * d
344
+ out[:, base + 32 : base + 64] = q2 * sc_n[:, half + 2] * d
345
+ out[:, base + 64 : base + 96] = q3 * sc_n[:, half + 4] * d
346
+ out[:, base + 96 : base + 128] = q4 * sc_n[:, half + 6] * d
347
+ return out.reshape(-1)
348
+
349
+
350
+ _DEQUANT = {
351
+ "Q4_0": _dq_q4_0,
352
+ "Q4_1": _dq_q4_1,
353
+ "Q5_0": _dq_q5_0,
354
+ "Q5_1": _dq_q5_1,
355
+ "Q8_0": _dq_q8_0,
356
+ "Q8_1": _dq_q8_1,
357
+ "Q2_K": _dq_q2_k,
358
+ "Q3_K": _dq_q3_k,
359
+ "Q4_K": _dq_q4_k,
360
+ "Q5_K": _dq_q5_k,
361
+ "Q6_K": _dq_q6_k,
362
+ "Q8_K": _dq_q8_k,
363
+ }
364
+
365
+
366
+ # ---------------------------------------------------------------------------
367
+ # 容器解析
368
+ # ---------------------------------------------------------------------------
369
+
370
+
371
+ class _Reader:
372
+ """带边界检查的顺序读取器;任何越界都立刻报错,而不是让 numpy 猜。"""
373
+
374
+ def __init__(self, data: Union[bytes, mmap.mmap], limit: int) -> None:
375
+ self.data = data
376
+ self.pos = 0
377
+ self.limit = limit
378
+
379
+ @property
380
+ def remaining(self) -> int:
381
+ return self.limit - self.pos
382
+
383
+ def take(self, n: int, what: str) -> bytes:
384
+ if n < 0:
385
+ raise GGUFError(f"{what} 的长度为负:{n}")
386
+ if n > self.remaining:
387
+ raise GGUFError(
388
+ f"{what} 越过文件末尾:需要 {n} 字节,从偏移 {self.pos} 起只剩 "
389
+ f"{self.remaining} 字节"
390
+ )
391
+ start = self.pos
392
+ self.pos += n
393
+ return bytes(self.data[start : start + n])
394
+
395
+ def scalar(self, fmt: str, what: str):
396
+ size = struct.calcsize(fmt)
397
+ return struct.unpack(fmt, self.take(size, what))[0]
398
+
399
+ def u32(self, what: str) -> int:
400
+ return self.scalar("<I", what)
401
+
402
+ def u64(self, what: str) -> int:
403
+ return self.scalar("<Q", what)
404
+
405
+ def string(self, what: str) -> str:
406
+ length = self.u64(f"{what} 的长度")
407
+ if length > _MAX_STRING_BYTES:
408
+ raise GGUFError(f"{what} 声称有 {length} 字节,超过上限 {_MAX_STRING_BYTES}")
409
+ raw = self.take(length, what)
410
+ try:
411
+ return raw.decode("utf-8")
412
+ except UnicodeDecodeError as exc:
413
+ raise GGUFError(f"{what} 不是合法 UTF-8:{exc}") from exc
414
+
415
+ def value(self, value_type: int, what: str, depth: int = 0):
416
+ if value_type == _VALUE_STRING:
417
+ return self.string(what)
418
+ if value_type == _VALUE_ARRAY:
419
+ if depth >= 4:
420
+ raise GGUFError(f"{what} 的数组嵌套超过 4 层:本实现不接受嵌套数组")
421
+ element_type = self.u32(f"{what} 的元素类型")
422
+ count = self.u64(f"{what} 的元素数")
423
+ if element_type == _VALUE_ARRAY:
424
+ raise GGUFError(f"{what} 是二维数组:GGUF 的元数据数组只允许一维")
425
+ if count > _MAX_ARRAY_ELEMENTS:
426
+ raise GGUFError(f"{what} 声称有 {count} 个元素,超过上限 {_MAX_ARRAY_ELEMENTS}")
427
+ if element_type in _VALUE_TYPES:
428
+ size = _VALUE_TYPES[element_type][2]
429
+ if count * size > self.remaining:
430
+ raise GGUFError(
431
+ f"{what} 需要 {count}×{size} 字节,越过文件末尾"
432
+ )
433
+ elif element_type != _VALUE_STRING:
434
+ raise GGUFError(f"{what} 的元素类型 {element_type} 不支持")
435
+ return [self.value(element_type, f"{what}[{i}]", depth + 1) for i in range(count)]
436
+ spec = _VALUE_TYPES.get(value_type)
437
+ if spec is None:
438
+ raise GGUFError(f"{what} 的元数据值类型 {value_type} 不受支持")
439
+ raw = self.scalar(spec[1], what)
440
+ return bool(raw) if spec[0] == "BOOL" else raw
441
+
442
+
443
+ def _align_up(value: int, alignment: int) -> int:
444
+ return (value + alignment - 1) // alignment * alignment
445
+
446
+
447
+ @dataclass(frozen=True)
448
+ class GGUFTensorInfo:
449
+ """一个张量的头信息;``shape`` 已换成 numpy 的维序(最内层在最后)。"""
450
+
451
+ name: str
452
+ dims: Tuple[int, ...]
453
+ shape: Tuple[int, ...]
454
+ type_name: str
455
+ type_id: int
456
+ offset: int
457
+ n_elements: int
458
+ n_bytes: int
459
+
460
+
461
+ @dataclass
462
+ class GGUFFile:
463
+ """解析好的 GGUF 文件;``tensor()`` 按需解码,不预先展开整份权重。"""
464
+
465
+ path: Optional[str]
466
+ version: int
467
+ metadata: Dict[str, object]
468
+ tensors: Dict[str, GGUFTensorInfo]
469
+ alignment: int
470
+ data_offset: int
471
+ file_size: int
472
+ _buffer: Union[bytes, mmap.mmap] = field(repr=False, default=b"")
473
+ _closed: bool = field(repr=False, default=False)
474
+
475
+ def __len__(self) -> int:
476
+ return len(self.tensors)
477
+
478
+ def __contains__(self, name: object) -> bool:
479
+ return name in self.tensors
480
+
481
+ def __enter__(self) -> "GGUFFile":
482
+ return self
483
+
484
+ def __exit__(self, *exc_info) -> None:
485
+ self.close()
486
+
487
+ def close(self) -> None:
488
+ if self._closed:
489
+ return
490
+ self._closed = True
491
+ if isinstance(self._buffer, mmap.mmap):
492
+ self._buffer.close()
493
+ self._buffer = b""
494
+
495
+ def tensor_info(self, name: str) -> GGUFTensorInfo:
496
+ info = self.tensors.get(name)
497
+ if info is None:
498
+ raise GGUFError(f"文件里没有张量 {name!r}(共有 {len(self.tensors)} 个)")
499
+ return info
500
+
501
+ def tensor(self, name: str) -> np.ndarray:
502
+ """解码一个张量。
503
+
504
+ 量化类型 / F16 / BF16 统一返回 float32;I8 / I16 / I32 / I64 与 F64
505
+ 保持原生 dtype。返回的是新数组,与文件缓冲区不共享内存。
506
+ """
507
+ if self._closed:
508
+ raise GGUFError("GGUFFile 已关闭,不能再读张量")
509
+ info = self.tensor_info(name)
510
+ start = self.data_offset + info.offset
511
+ end = start + info.n_bytes
512
+ raw = self._buffer[start:end]
513
+ if len(raw) != info.n_bytes: # 解析期已校验,这里只防缓冲区被提前释放
514
+ raise GGUFError(
515
+ f"张量 {name!r} 需要 {info.n_bytes} 字节,实际只取到 {len(raw)} 字节"
516
+ )
517
+ return _decode_tensor(info, bytes(raw))
518
+
519
+ def names(self) -> List[str]:
520
+ return list(self.tensors)
521
+
522
+
523
+ def _decode_tensor(info: GGUFTensorInfo, raw: bytes) -> np.ndarray:
524
+ name = info.type_name
525
+ block_size = GGML_TYPES[name][1]
526
+ count = info.n_elements // block_size
527
+ if name == "F32":
528
+ array = np.frombuffer(raw, dtype="<f4").astype(np.float32)
529
+ elif name == "F16":
530
+ array = np.frombuffer(raw, dtype="<f2").astype(np.float32)
531
+ elif name == "BF16":
532
+ # bf16 就是 f32 的高 16 位:左移 16 位后按 f32 位模式解释,是精确的。
533
+ wide = np.frombuffer(raw, dtype="<u2").astype(np.uint32) << 16
534
+ array = wide.view(np.float32)
535
+ elif name == "F64":
536
+ return np.frombuffer(raw, dtype="<f8").astype(np.float64).reshape(info.shape)
537
+ elif name == "I8":
538
+ array = np.frombuffer(raw, dtype="i1")
539
+ elif name == "I16":
540
+ array = np.frombuffer(raw, dtype="<i2")
541
+ elif name == "I32":
542
+ array = np.frombuffer(raw, dtype="<i4")
543
+ elif name == "I64":
544
+ array = np.frombuffer(raw, dtype="<i8")
545
+ else:
546
+ dequant = _DEQUANT.get(name)
547
+ if dequant is None: # 解析期已拒绝,这里防御性兜底
548
+ raise GGUFError(f"张量类型 {name} 没有解码器")
549
+ array = dequant(raw, count)
550
+ if array.size != info.n_elements:
551
+ raise GGUFError(
552
+ f"张量 {info.name!r} 解码出 {array.size} 个元素,头部声明 {info.n_elements} 个"
553
+ )
554
+ return array.reshape(info.shape)
555
+
556
+
557
+ def read_gguf(source: Union[str, os.PathLike, bytes, bytearray]) -> GGUFFile:
558
+ """读一个 GGUF 文件(路径或内存字节)。
559
+
560
+ 路径用 ``mmap`` 打开,``tensor()`` 按需解码,不把整份权重读进内存;用完
561
+ 调 ``close()``,或写成 ``with read_gguf(path) as f``。
562
+ """
563
+ if isinstance(source, (bytes, bytearray)):
564
+ buffer: Union[bytes, mmap.mmap] = bytes(source)
565
+ path = None
566
+ else:
567
+ path = os.fspath(source)
568
+ try:
569
+ handle = open(path, "rb")
570
+ except OSError as exc:
571
+ raise GGUFError(f"打不开 GGUF 文件 {path!r}:{exc}") from exc
572
+ try:
573
+ size = os.fstat(handle.fileno()).st_size
574
+ if size < 24:
575
+ raise GGUFError(f"文件 {path!r} 只有 {size} 字节,连 GGUF 头都放不下")
576
+ buffer = mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ)
577
+ except OSError as exc:
578
+ raise GGUFError(f"映射 GGUF 文件 {path!r} 失败:{exc}") from exc
579
+ finally:
580
+ handle.close()
581
+ size = len(buffer)
582
+
583
+ reader = _Reader(buffer, size)
584
+ magic = reader.u32("magic")
585
+ if magic != _MAGIC:
586
+ raise GGUFError(f"不是 GGUF 文件:magic=0x{magic:08X},期望 0x{_MAGIC:08X}")
587
+ version = reader.u32("version")
588
+ if version not in _SUPPORTED_VERSIONS:
589
+ raise GGUFError(f"GGUF 版本 {version} 不受支持:只读 v2 / v3")
590
+ tensor_count = reader.u64("tensor_count")
591
+ kv_count = reader.u64("metadata_kv_count")
592
+ if tensor_count > _MAX_TENSORS:
593
+ raise GGUFError(f"tensor_count={tensor_count} 超过上限 {_MAX_TENSORS}")
594
+ if kv_count > _MAX_KV:
595
+ raise GGUFError(f"metadata_kv_count={kv_count} 超过上限 {_MAX_KV}")
596
+ # 每条 KV 至少 8 字节 key 长度 + 4 字节类型;每个张量头至少 24 字节。
597
+ if kv_count * 12 > reader.remaining:
598
+ raise GGUFError(
599
+ f"metadata_kv_count={kv_count} 与剩余 {reader.remaining} 字节对不上"
600
+ )
601
+
602
+ metadata: Dict[str, object] = {}
603
+ for _ in range(kv_count):
604
+ key = reader.string("metadata key")
605
+ if key in metadata:
606
+ raise GGUFError(f"metadata key {key!r} 重复出现")
607
+ value_type = reader.u32(f"metadata[{key!r}] 的类型")
608
+ metadata[key] = reader.value(value_type, f"metadata[{key!r}]")
609
+
610
+ alignment = 32
611
+ raw_alignment = metadata.get("general.alignment")
612
+ if raw_alignment is not None:
613
+ if not isinstance(raw_alignment, int) or raw_alignment <= 0:
614
+ raise GGUFError(f"general.alignment={raw_alignment!r} 必须是正整数")
615
+ if raw_alignment & (raw_alignment - 1):
616
+ raise GGUFError(f"general.alignment={raw_alignment} 不是 2 的幂")
617
+ alignment = raw_alignment
618
+
619
+ infos: Dict[str, GGUFTensorInfo] = {}
620
+ if tensor_count * 24 > reader.remaining:
621
+ raise GGUFError(f"tensor_count={tensor_count} 与剩余 {reader.remaining} 字节对不上")
622
+ for index in range(tensor_count):
623
+ try:
624
+ name = reader.string(f"tensor[{index}] 的名字")
625
+ if name in infos:
626
+ raise GGUFError(f"张量名 {name!r} 重复")
627
+ n_dims = reader.u32(f"tensor[{name!r}] 的维数")
628
+ if not 1 <= n_dims <= 4:
629
+ raise GGUFError(f"张量 {name!r} 的维数 {n_dims} 不在 1..4:ggml 最多四维")
630
+ dims = tuple(reader.u64(f"tensor[{name!r}].ne[{d}]") for d in range(n_dims))
631
+ if any(d == 0 for d in dims):
632
+ raise GGUFError(f"张量 {name!r} 的维度里含 0:{dims}")
633
+ type_id = reader.u32(f"tensor[{name!r}] 的类型")
634
+ type_name = _BY_ID.get(type_id)
635
+ if type_name is None:
636
+ raise GGUFError(
637
+ f"张量 {name!r} 用了类型 id={type_id}:IQ 系格点码本 / TQ 系三值 / "
638
+ "分块向量布局本实现不解码,拒绝而不是猜"
639
+ )
640
+ offset = reader.u64(f"tensor[{name!r}] 的偏移")
641
+ except GGUFError as exc:
642
+ # GGUF 没有张量表长度字段,tensor_count 说谎时只能在解析途中发现。
643
+ # 这里补上"第几个、声明了几个",否则现场只看到一条莫名其妙的维度错误。
644
+ raise GGUFError(
645
+ f"第 {index + 1} 个张量信息解析失败(头里声明 {tensor_count} 个,"
646
+ f"与文件内容对不上):{exc}"
647
+ ) from exc
648
+ n_elements = 1
649
+ for d in dims:
650
+ n_elements *= d
651
+ block_size, block_bytes = GGML_TYPES[type_name][1], GGML_TYPES[type_name][2]
652
+ if n_elements % block_size != 0:
653
+ raise GGUFError(
654
+ f"张量 {name!r} 有 {n_elements} 个元素,不是 {type_name} 块大小 "
655
+ f"{block_size} 的整数倍"
656
+ )
657
+ n_bytes = n_elements // block_size * block_bytes
658
+ if offset % alignment != 0:
659
+ raise GGUFError(
660
+ f"张量 {name!r} 的偏移 {offset} 没有按 alignment={alignment} 对齐"
661
+ )
662
+ infos[name] = GGUFTensorInfo(
663
+ name=name,
664
+ dims=dims,
665
+ shape=tuple(reversed(dims)),
666
+ type_name=type_name,
667
+ type_id=type_id,
668
+ offset=offset,
669
+ n_elements=n_elements,
670
+ n_bytes=n_bytes,
671
+ )
672
+
673
+ data_offset = _align_up(reader.pos, alignment)
674
+ if data_offset > size:
675
+ raise GGUFError(f"数据区起点 {data_offset} 越过文件末尾 {size}")
676
+ for info in infos.values():
677
+ end = data_offset + info.offset + info.n_bytes
678
+ if end > size:
679
+ raise GGUFError(
680
+ f"张量 {info.name!r} 的数据 [ {data_offset + info.offset}, {end} ) "
681
+ f"越过文件末尾 {size}"
682
+ )
683
+
684
+ return GGUFFile(
685
+ path=path,
686
+ version=version,
687
+ metadata=metadata,
688
+ tensors=infos,
689
+ alignment=alignment,
690
+ data_offset=data_offset,
691
+ file_size=size,
692
+ _buffer=buffer,
693
+ )