Upload 2 files
Browse fileshttps://zenodo.org/records/18451536
# QUANTIZAÇÃO GEOMÉTRICA PARA MODELOS LLaMA (LLM) EM PYTHON
Authors/Creators
Becker, Bruno (Researcher)
Description
# QUANTIZAÇÃO GEOMÉTRICA PARA MODELOS LLaMA (LLM) EM PYTHON
## Um kernel funcional de compressão estrutural com preservação de contexto
### QUEM QUISER USAR MINHAS TEORIAS PARA IAs GEOMÉTRICAS, O FAÇAM DIREITO, E TENHAM O MINÍMO DE DECÊNCIA DE ME CITAR AO MENOS.
Este repositório apresenta uma implementação funcional de **quantização geométrica aplicada a modelos de linguagem do tipo LLaMA**, desenvolvida em **Python**, compatível com o ecossistema **open-source** (LLaMA, HuggingFace, GGML e derivados).
O trabalho não propõe aumento de parâmetros, expansão artificial de contexto ou tuning estatístico superficial. Em vez disso, introduz um **kernel de quantização estrutural**, baseado em princípios geométricos, que atua diretamente sobre os **graus de liberdade internos** dos tensores, preservando relações locais, simetrias e escalas.
O código disponibilizado é funcional, executável e verificável, demonstrando empiricamente um comportamento relevante: mesmo com redução de throughput (velocidade de tokens), o modelo mantém **estabilidade incomum de contexto**, evitando colapso progressivo em janelas longas.
Esse efeito não decorre de heurísticas de amostragem, mas da **organização geométrica imposta à representação interna**.
---
## Enquadramento Matemático
Seja um tensor de ativações ou pesos:
Particionamos em blocos de tamanho fixo
:
Definimos um operador de quantização geométrica:
tal que:
onde:
- é um vetor discreto quantizado
-
é um fator de escala contínuo local
- a geometria relativa do bloco é preservada
A reconstrução é dada por:
com erro limitado:
A propriedade central não é minimizar o erro global, mas **preservar a geometria local do espaço vetorial**, garantindo continuidade estrutural entre blocos sucessivos.
---
## Implicações para Modelos de Linguagem
Em modelos autorregressivos, a estabilidade do contexto depende da **coerência geométrica acumulada** no espaço latente.
A quantização geométrica atua como um **operador de regularização estrutural**, reduzindo deriva caótica sem impor rigidez excessiva, resultando em:
- degradação graciosa em janelas longas
- menor colapso semântico progressivo
- maior previsibilidade estrutural do estado interno
---
## Escopo e Limitações
Este repositório:
- fornece uma implementação funcional
- demonstra um efeito real e mensurável
- é totalmente open-source
Este repositório não pretende:
- fornecer um modelo completo
- substituir arquiteturas existentes
- esgotar o arcabouço teórico subjacente
O kernel apresentado é uma **instância prática**, conectada a um corpo teórico mais amplo já publicado separadamente pelo autor.
---
## Licença e Ecossistema
- Código: MIT License
- Linguagem: Python
- Modelos: LLaMA (open-weights)
- Ecossistema: HuggingFace / GGML compatível
Este trabalho respeita integralmente as licenças open-source dos projetos utilizados.
---
## Nota Final
Este artefato é publicado como **prova de anterioridade funcional**, não como produto final.
A reprodução, extensão ou adaptação deste trabalho é livre, desde que se compreenda que o código apresentado representa apenas a **superfície de uma estrutura teórica mais profunda**.
- llama-webui.zip +3 -0
- quants.py +1472 -0
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:862d34664bcc1c3255a43a0f5cee2ae35f9576569a9917972d6b8c6325180173
|
| 3 |
+
size 259313999
|
|
@@ -0,0 +1,1472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
from abc import ABC, abstractmethod
|
| 3 |
+
from typing import Any, Callable, Sequence
|
| 4 |
+
from math import log2, ceil
|
| 5 |
+
|
| 6 |
+
from numpy.typing import DTypeLike
|
| 7 |
+
|
| 8 |
+
from .constants import GGML_QUANT_SIZES, GGMLQuantizationType, QK_K
|
| 9 |
+
from .lazy import LazyNumpyTensor
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def quant_shape_to_byte_shape(shape: Sequence[int], quant_type: GGMLQuantizationType) -> tuple[int, ...]:
|
| 15 |
+
block_size, type_size = GGML_QUANT_SIZES[quant_type]
|
| 16 |
+
if shape[-1] % block_size != 0:
|
| 17 |
+
raise ValueError(f"Quantized tensor row size ({shape[-1]}) is not a multiple of {quant_type.name} block size ({block_size})")
|
| 18 |
+
return (*shape[:-1], shape[-1] // block_size * type_size)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def quant_shape_from_byte_shape(shape: Sequence[int], quant_type: GGMLQuantizationType) -> tuple[int, ...]:
|
| 22 |
+
block_size, type_size = GGML_QUANT_SIZES[quant_type]
|
| 23 |
+
if shape[-1] % type_size != 0:
|
| 24 |
+
raise ValueError(f"Quantized tensor bytes per row ({shape[-1]}) is not a multiple of {quant_type.name} type size ({type_size})")
|
| 25 |
+
return (*shape[:-1], shape[-1] // type_size * block_size)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# This is faster than np.vectorize and np.apply_along_axis because it works on more than one row at a time
|
| 29 |
+
def _apply_over_grouped_rows(func: Callable[[np.ndarray], np.ndarray], arr: np.ndarray, otype: DTypeLike, oshape: tuple[int, ...]) -> np.ndarray:
|
| 30 |
+
rows = arr.reshape((-1, arr.shape[-1]))
|
| 31 |
+
osize = 1
|
| 32 |
+
for dim in oshape:
|
| 33 |
+
osize *= dim
|
| 34 |
+
out = np.empty(shape=osize, dtype=otype)
|
| 35 |
+
# compute over groups of 16 rows (arbitrary, but seems good for performance)
|
| 36 |
+
n_groups = (rows.shape[0] // 16) or 1
|
| 37 |
+
np.concatenate([func(group).ravel() for group in np.array_split(rows, n_groups)], axis=0, out=out)
|
| 38 |
+
return out.reshape(oshape)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# round away from zero
|
| 42 |
+
# ref: https://stackoverflow.com/a/59143326/22827863
|
| 43 |
+
def np_roundf(n: np.ndarray) -> np.ndarray:
|
| 44 |
+
a = abs(n)
|
| 45 |
+
floored = np.floor(a)
|
| 46 |
+
b = floored + np.floor(2 * (a - floored))
|
| 47 |
+
return np.sign(n) * b
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class QuantError(Exception): ...
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
_type_traits: dict[GGMLQuantizationType, type[__Quant]] = {}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def quantize(data: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
|
| 57 |
+
if qtype == GGMLQuantizationType.F32:
|
| 58 |
+
return data.astype(np.float32, copy=False)
|
| 59 |
+
elif qtype == GGMLQuantizationType.F16:
|
| 60 |
+
return data.astype(np.float16, copy=False)
|
| 61 |
+
elif (q := _type_traits.get(qtype)) is not None:
|
| 62 |
+
return q.quantize(data)
|
| 63 |
+
else:
|
| 64 |
+
raise NotImplementedError(f"Quantization for {qtype.name} is not yet implemented")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def dequantize(data: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
|
| 68 |
+
if qtype == GGMLQuantizationType.F32:
|
| 69 |
+
return data.view(np.float32)
|
| 70 |
+
elif qtype == GGMLQuantizationType.F16:
|
| 71 |
+
return data.view(np.float16).astype(np.float32)
|
| 72 |
+
elif (q := _type_traits.get(qtype)) is not None:
|
| 73 |
+
return q.dequantize(data)
|
| 74 |
+
else:
|
| 75 |
+
raise NotImplementedError(f"Dequantization for {qtype.name} is not yet implemented")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class __Quant(ABC):
|
| 79 |
+
qtype: GGMLQuantizationType
|
| 80 |
+
block_size: int
|
| 81 |
+
type_size: int
|
| 82 |
+
|
| 83 |
+
grid: np.ndarray[Any, np.dtype[np.float32]] | None = None
|
| 84 |
+
grid_shape: tuple[int, int] = (0, 0)
|
| 85 |
+
grid_map: tuple[int | float, ...] = ()
|
| 86 |
+
grid_hex: bytes | None = None
|
| 87 |
+
|
| 88 |
+
def __init__(self):
|
| 89 |
+
return TypeError("Quant conversion classes can't have instances")
|
| 90 |
+
|
| 91 |
+
def __init_subclass__(cls, qtype: GGMLQuantizationType) -> None:
|
| 92 |
+
cls.qtype = qtype
|
| 93 |
+
cls.block_size, cls.type_size = GGML_QUANT_SIZES[qtype]
|
| 94 |
+
cls.__quantize_lazy = LazyNumpyTensor._wrap_fn(
|
| 95 |
+
cls.__quantize_array,
|
| 96 |
+
meta_noop=(np.uint8, cls.__shape_to_bytes)
|
| 97 |
+
)
|
| 98 |
+
cls.__dequantize_lazy = LazyNumpyTensor._wrap_fn(
|
| 99 |
+
cls.__dequantize_array,
|
| 100 |
+
meta_noop=(np.float32, cls.__shape_from_bytes)
|
| 101 |
+
)
|
| 102 |
+
assert qtype not in _type_traits
|
| 103 |
+
_type_traits[qtype] = cls
|
| 104 |
+
|
| 105 |
+
@classmethod
|
| 106 |
+
def init_grid(cls):
|
| 107 |
+
if cls.grid is not None or cls.grid_hex is None:
|
| 108 |
+
return
|
| 109 |
+
|
| 110 |
+
bits_per_elem = ceil(log2(len(cls.grid_map)))
|
| 111 |
+
assert bits_per_elem != 0, cls.qtype.name
|
| 112 |
+
elems_per_byte = 8 // bits_per_elem
|
| 113 |
+
|
| 114 |
+
grid = np.frombuffer(cls.grid_hex, dtype=np.uint8)
|
| 115 |
+
# decode hexadecimal chars from grid
|
| 116 |
+
grid = grid.reshape((-1, 2))
|
| 117 |
+
grid = (np.where(grid > 0x40, grid + 9, grid) & 0x0F) << np.array([4, 0], dtype=np.uint8).reshape((1, 2))
|
| 118 |
+
grid = grid[..., 0] | grid[..., 1]
|
| 119 |
+
# unpack the grid values
|
| 120 |
+
grid = grid.reshape((-1, 1)) >> np.array([i for i in range(0, 8, 8 // elems_per_byte)], dtype=np.uint8).reshape((1, elems_per_byte))
|
| 121 |
+
grid = (grid & ((1 << bits_per_elem) - 1)).reshape((-1, 1))
|
| 122 |
+
grid_map = np.array(cls.grid_map, dtype=np.float32).reshape((1, -1))
|
| 123 |
+
grid = np.take_along_axis(grid_map, grid, axis=-1)
|
| 124 |
+
cls.grid = grid.reshape((1, 1, *cls.grid_shape))
|
| 125 |
+
|
| 126 |
+
@classmethod
|
| 127 |
+
@abstractmethod
|
| 128 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 129 |
+
raise NotImplementedError
|
| 130 |
+
|
| 131 |
+
@classmethod
|
| 132 |
+
@abstractmethod
|
| 133 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 134 |
+
raise NotImplementedError
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def quantize_rows(cls, rows: np.ndarray) -> np.ndarray:
|
| 138 |
+
rows = rows.astype(np.float32, copy=False)
|
| 139 |
+
shape = rows.shape
|
| 140 |
+
n_blocks = rows.size // cls.block_size
|
| 141 |
+
blocks = rows.reshape((n_blocks, cls.block_size))
|
| 142 |
+
blocks = cls.quantize_blocks(blocks)
|
| 143 |
+
assert blocks.dtype == np.uint8
|
| 144 |
+
assert blocks.shape[-1] == cls.type_size
|
| 145 |
+
return blocks.reshape(cls.__shape_to_bytes(shape))
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def dequantize_rows(cls, rows: np.ndarray) -> np.ndarray:
|
| 149 |
+
rows = rows.view(np.uint8)
|
| 150 |
+
shape = rows.shape
|
| 151 |
+
n_blocks = rows.size // cls.type_size
|
| 152 |
+
blocks = rows.reshape((n_blocks, cls.type_size))
|
| 153 |
+
blocks = cls.dequantize_blocks(blocks)
|
| 154 |
+
assert blocks.dtype == np.float32
|
| 155 |
+
assert blocks.shape[-1] == cls.block_size
|
| 156 |
+
return blocks.reshape(cls.__shape_from_bytes(shape))
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def __shape_to_bytes(cls, shape: Sequence[int]):
|
| 160 |
+
return quant_shape_to_byte_shape(shape, cls.qtype)
|
| 161 |
+
|
| 162 |
+
@classmethod
|
| 163 |
+
def __shape_from_bytes(cls, shape: Sequence[int]):
|
| 164 |
+
return quant_shape_from_byte_shape(shape, cls.qtype)
|
| 165 |
+
|
| 166 |
+
@classmethod
|
| 167 |
+
def __quantize_array(cls, array: np.ndarray) -> np.ndarray:
|
| 168 |
+
return _apply_over_grouped_rows(cls.quantize_rows, arr=array, otype=np.uint8, oshape=cls.__shape_to_bytes(array.shape))
|
| 169 |
+
|
| 170 |
+
@classmethod
|
| 171 |
+
def __dequantize_array(cls, array: np.ndarray) -> np.ndarray:
|
| 172 |
+
cls.init_grid()
|
| 173 |
+
return _apply_over_grouped_rows(cls.dequantize_rows, arr=array, otype=np.float32, oshape=cls.__shape_from_bytes(array.shape))
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def __quantize_lazy(cls, lazy_tensor: LazyNumpyTensor, /) -> Any:
|
| 177 |
+
pass
|
| 178 |
+
|
| 179 |
+
@classmethod
|
| 180 |
+
def __dequantize_lazy(cls, lazy_tensor: LazyNumpyTensor, /) -> Any:
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
@classmethod
|
| 184 |
+
def can_quantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> bool:
|
| 185 |
+
return tensor.shape[-1] % cls.block_size == 0
|
| 186 |
+
|
| 187 |
+
@classmethod
|
| 188 |
+
def quantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> np.ndarray:
|
| 189 |
+
if not cls.can_quantize(tensor):
|
| 190 |
+
raise QuantError(f"Can't quantize tensor with shape {tensor.shape} to {cls.qtype.name}")
|
| 191 |
+
if isinstance(tensor, LazyNumpyTensor):
|
| 192 |
+
return cls.__quantize_lazy(tensor)
|
| 193 |
+
else:
|
| 194 |
+
return cls.__quantize_array(tensor)
|
| 195 |
+
|
| 196 |
+
@classmethod
|
| 197 |
+
def dequantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> np.ndarray:
|
| 198 |
+
if isinstance(tensor, LazyNumpyTensor):
|
| 199 |
+
return cls.__dequantize_lazy(tensor)
|
| 200 |
+
else:
|
| 201 |
+
return cls.__dequantize_array(tensor)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class BF16(__Quant, qtype=GGMLQuantizationType.BF16):
|
| 205 |
+
@classmethod
|
| 206 |
+
# same as ggml_compute_fp32_to_bf16 in ggml-impl.h
|
| 207 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 208 |
+
n = blocks.view(np.uint32)
|
| 209 |
+
# force nan to quiet
|
| 210 |
+
n = np.where((n & 0x7fffffff) > 0x7f800000, (n & np.uint32(0xffff0000)) | np.uint32(64 << 16), n)
|
| 211 |
+
# round to nearest even
|
| 212 |
+
n = (np.uint64(n) + (0x7fff + ((n >> 16) & 1))) >> 16
|
| 213 |
+
return n.astype(np.uint16).view(np.uint8)
|
| 214 |
+
|
| 215 |
+
@classmethod
|
| 216 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 217 |
+
return (blocks.view(np.int16).astype(np.int32) << 16).view(np.float32)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class Q4_0(__Quant, qtype=GGMLQuantizationType.Q4_0):
|
| 221 |
+
@classmethod
|
| 222 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 223 |
+
n_blocks = blocks.shape[0]
|
| 224 |
+
|
| 225 |
+
imax = abs(blocks).argmax(axis=-1, keepdims=True)
|
| 226 |
+
max = np.take_along_axis(blocks, imax, axis=-1)
|
| 227 |
+
|
| 228 |
+
d = max / -8
|
| 229 |
+
with np.errstate(divide="ignore"):
|
| 230 |
+
id = np.where(d == 0, 0, 1 / d)
|
| 231 |
+
qs = np.trunc((blocks * id) + np.float32(8.5), dtype=np.float32).astype(np.uint8).clip(0, 15)
|
| 232 |
+
|
| 233 |
+
qs = qs.reshape((n_blocks, 2, cls.block_size // 2))
|
| 234 |
+
qs = qs[..., 0, :] | (qs[..., 1, :] << np.uint8(4))
|
| 235 |
+
|
| 236 |
+
d = d.astype(np.float16).view(np.uint8)
|
| 237 |
+
|
| 238 |
+
return np.concatenate([d, qs], axis=-1)
|
| 239 |
+
|
| 240 |
+
@classmethod
|
| 241 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 242 |
+
n_blocks = blocks.shape[0]
|
| 243 |
+
|
| 244 |
+
d, qs = np.hsplit(blocks, [2])
|
| 245 |
+
|
| 246 |
+
d = d.view(np.float16).astype(np.float32)
|
| 247 |
+
|
| 248 |
+
qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 249 |
+
qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1)).astype(np.int8) - np.int8(8)
|
| 250 |
+
|
| 251 |
+
return (d * qs.astype(np.float32))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class Q4_1(__Quant, qtype=GGMLQuantizationType.Q4_1):
|
| 255 |
+
@classmethod
|
| 256 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 257 |
+
n_blocks = blocks.shape[0]
|
| 258 |
+
|
| 259 |
+
max = blocks.max(axis=-1, keepdims=True)
|
| 260 |
+
min = blocks.min(axis=-1, keepdims=True)
|
| 261 |
+
|
| 262 |
+
d = (max - min) / 15
|
| 263 |
+
with np.errstate(divide="ignore"):
|
| 264 |
+
id = np.where(d == 0, 0, 1 / d)
|
| 265 |
+
qs = np.trunc((blocks - min) * id + np.float32(0.5), dtype=np.float32).astype(np.uint8).clip(0, 15)
|
| 266 |
+
|
| 267 |
+
qs = qs.reshape((n_blocks, 2, cls.block_size // 2))
|
| 268 |
+
qs = qs[..., 0, :] | (qs[..., 1, :] << np.uint8(4))
|
| 269 |
+
|
| 270 |
+
d = d.astype(np.float16).view(np.uint8)
|
| 271 |
+
m = min.astype(np.float16).view(np.uint8)
|
| 272 |
+
|
| 273 |
+
return np.concatenate([d, m, qs], axis=-1)
|
| 274 |
+
|
| 275 |
+
@classmethod
|
| 276 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 277 |
+
n_blocks = blocks.shape[0]
|
| 278 |
+
|
| 279 |
+
d, rest = np.hsplit(blocks, [2])
|
| 280 |
+
m, qs = np.hsplit(rest, [2])
|
| 281 |
+
|
| 282 |
+
d = d.view(np.float16).astype(np.float32)
|
| 283 |
+
m = m.view(np.float16).astype(np.float32)
|
| 284 |
+
|
| 285 |
+
qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 286 |
+
qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1)).astype(np.float32)
|
| 287 |
+
|
| 288 |
+
return (d * qs) + m
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class Q5_0(__Quant, qtype=GGMLQuantizationType.Q5_0):
|
| 292 |
+
@classmethod
|
| 293 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 294 |
+
n_blocks = blocks.shape[0]
|
| 295 |
+
|
| 296 |
+
imax = abs(blocks).argmax(axis=-1, keepdims=True)
|
| 297 |
+
max = np.take_along_axis(blocks, imax, axis=-1)
|
| 298 |
+
|
| 299 |
+
d = max / -16
|
| 300 |
+
with np.errstate(divide="ignore"):
|
| 301 |
+
id = np.where(d == 0, 0, 1 / d)
|
| 302 |
+
q = np.trunc((blocks * id) + np.float32(16.5), dtype=np.float32).astype(np.uint8).clip(0, 31)
|
| 303 |
+
|
| 304 |
+
qs = q.reshape((n_blocks, 2, cls.block_size // 2))
|
| 305 |
+
qs = (qs[..., 0, :] & np.uint8(0x0F)) | (qs[..., 1, :] << np.uint8(4))
|
| 306 |
+
|
| 307 |
+
qh = np.packbits(q.reshape((n_blocks, 1, 32)) >> np.uint8(4), axis=-1, bitorder="little").reshape(n_blocks, 4)
|
| 308 |
+
|
| 309 |
+
d = d.astype(np.float16).view(np.uint8)
|
| 310 |
+
|
| 311 |
+
return np.concatenate([d, qh, qs], axis=-1)
|
| 312 |
+
|
| 313 |
+
@classmethod
|
| 314 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 315 |
+
n_blocks = blocks.shape[0]
|
| 316 |
+
|
| 317 |
+
d, rest = np.hsplit(blocks, [2])
|
| 318 |
+
qh, qs = np.hsplit(rest, [4])
|
| 319 |
+
|
| 320 |
+
d = d.view(np.float16).astype(np.float32)
|
| 321 |
+
qh = qh.view(np.uint32)
|
| 322 |
+
|
| 323 |
+
qh = qh.reshape((n_blocks, 1)) >> np.array([i for i in range(32)], dtype=np.uint32).reshape((1, 32))
|
| 324 |
+
ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 325 |
+
qh = (qh & np.uint32(0x01)).astype(np.uint8)
|
| 326 |
+
ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1))
|
| 327 |
+
|
| 328 |
+
qs = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(16)
|
| 329 |
+
|
| 330 |
+
return (d * qs.astype(np.float32))
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class Q5_1(__Quant, qtype=GGMLQuantizationType.Q5_1):
|
| 334 |
+
@classmethod
|
| 335 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 336 |
+
n_blocks = blocks.shape[0]
|
| 337 |
+
|
| 338 |
+
max = blocks.max(axis=-1, keepdims=True)
|
| 339 |
+
min = blocks.min(axis=-1, keepdims=True)
|
| 340 |
+
|
| 341 |
+
d = (max - min) / 31
|
| 342 |
+
with np.errstate(divide="ignore"):
|
| 343 |
+
id = np.where(d == 0, 0, 1 / d)
|
| 344 |
+
q = np.trunc((blocks - min) * id + np.float32(0.5), dtype=np.float32).astype(np.uint8).clip(0, 31)
|
| 345 |
+
|
| 346 |
+
qs = q.reshape((n_blocks, 2, cls.block_size // 2))
|
| 347 |
+
qs = (qs[..., 0, :] & np.uint8(0x0F)) | (qs[..., 1, :] << np.uint8(4))
|
| 348 |
+
|
| 349 |
+
qh = np.packbits(q.reshape((n_blocks, 1, 32)) >> np.uint8(4), axis=-1, bitorder="little").reshape(n_blocks, 4)
|
| 350 |
+
|
| 351 |
+
d = d.astype(np.float16).view(np.uint8)
|
| 352 |
+
m = min.astype(np.float16).view(np.uint8)
|
| 353 |
+
|
| 354 |
+
return np.concatenate([d, m, qh, qs], axis=-1)
|
| 355 |
+
|
| 356 |
+
@classmethod
|
| 357 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 358 |
+
n_blocks = blocks.shape[0]
|
| 359 |
+
|
| 360 |
+
d, rest = np.hsplit(blocks, [2])
|
| 361 |
+
m, rest = np.hsplit(rest, [2])
|
| 362 |
+
qh, qs = np.hsplit(rest, [4])
|
| 363 |
+
|
| 364 |
+
d = d.view(np.float16).astype(np.float32)
|
| 365 |
+
m = m.view(np.float16).astype(np.float32)
|
| 366 |
+
qh = qh.view(np.uint32)
|
| 367 |
+
|
| 368 |
+
qh = qh.reshape((n_blocks, 1)) >> np.array([i for i in range(32)], dtype=np.uint32).reshape((1, 32))
|
| 369 |
+
ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 370 |
+
qh = (qh & np.uint32(0x01)).astype(np.uint8)
|
| 371 |
+
ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1))
|
| 372 |
+
|
| 373 |
+
qs = (ql | (qh << np.uint8(4))).astype(np.float32)
|
| 374 |
+
|
| 375 |
+
return (d * qs) + m
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
class Q8_0(__Quant, qtype=GGMLQuantizationType.Q8_0):
|
| 379 |
+
@classmethod
|
| 380 |
+
# Implementation of Q8_0 with bit-exact same results as reference implementation in ggml-quants.c
|
| 381 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 382 |
+
|
| 383 |
+
d = abs(blocks).max(axis=1, keepdims=True) / 127
|
| 384 |
+
with np.errstate(divide="ignore"):
|
| 385 |
+
id = np.where(d == 0, 0, 1 / d)
|
| 386 |
+
qs = np_roundf(blocks * id)
|
| 387 |
+
|
| 388 |
+
# (n_blocks, 2)
|
| 389 |
+
d = d.astype(np.float16).view(np.uint8)
|
| 390 |
+
# (n_blocks, block_size)
|
| 391 |
+
qs = qs.astype(np.int8).view(np.uint8)
|
| 392 |
+
|
| 393 |
+
return np.concatenate([d, qs], axis=1)
|
| 394 |
+
|
| 395 |
+
@classmethod
|
| 396 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 397 |
+
d, x = np.split(blocks, [2], axis=1)
|
| 398 |
+
d = d.view(np.float16).astype(np.float32)
|
| 399 |
+
x = x.view(np.int8).astype(np.float32)
|
| 400 |
+
|
| 401 |
+
return (x * d)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class Q2_K(__Quant, qtype=GGMLQuantizationType.Q2_K):
|
| 405 |
+
@classmethod
|
| 406 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 407 |
+
n_blocks = blocks.shape[0]
|
| 408 |
+
|
| 409 |
+
scales, rest = np.hsplit(blocks, [QK_K // 16])
|
| 410 |
+
qs, rest = np.hsplit(rest, [QK_K // 4])
|
| 411 |
+
d, dmin = np.hsplit(rest, [2])
|
| 412 |
+
|
| 413 |
+
d = d.view(np.float16).astype(np.float32)
|
| 414 |
+
dmin = dmin.view(np.float16).astype(np.float32)
|
| 415 |
+
|
| 416 |
+
# (n_blocks, 16, 1)
|
| 417 |
+
dl = (d * (scales & 0xF).astype(np.float32)).reshape((n_blocks, QK_K // 16, 1))
|
| 418 |
+
ml = (dmin * (scales >> 4).astype(np.float32)).reshape((n_blocks, QK_K // 16, 1))
|
| 419 |
+
|
| 420 |
+
shift = np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
|
| 421 |
+
|
| 422 |
+
qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & np.uint8(3)
|
| 423 |
+
|
| 424 |
+
qs = qs.reshape((n_blocks, QK_K // 16, 16)).astype(np.float32)
|
| 425 |
+
|
| 426 |
+
qs = dl * qs - ml
|
| 427 |
+
|
| 428 |
+
return qs.reshape((n_blocks, -1))
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class Q3_K(__Quant, qtype=GGMLQuantizationType.Q3_K):
|
| 432 |
+
@classmethod
|
| 433 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 434 |
+
n_blocks = blocks.shape[0]
|
| 435 |
+
|
| 436 |
+
hmask, rest = np.hsplit(blocks, [QK_K // 8])
|
| 437 |
+
qs, rest = np.hsplit(rest, [QK_K // 4])
|
| 438 |
+
scales, d = np.hsplit(rest, [12])
|
| 439 |
+
|
| 440 |
+
d = d.view(np.float16).astype(np.float32)
|
| 441 |
+
|
| 442 |
+
# The scales are packed at 6-bit each in this pattern:
|
| 443 |
+
# 0: IIIIAAAA
|
| 444 |
+
# 1: JJJJBBBB
|
| 445 |
+
# 2: KKKKCCCC
|
| 446 |
+
# 3: LLLLDDDD
|
| 447 |
+
# 4: MMMMEEEE
|
| 448 |
+
# 5: NNNNFFFF
|
| 449 |
+
# 6: OOOOGGGG
|
| 450 |
+
# 7: PPPPHHHH
|
| 451 |
+
# 8: MMIIEEAA
|
| 452 |
+
# 9: NNJJFFBB
|
| 453 |
+
# 10: OOKKGGCC
|
| 454 |
+
# 11: PPLLHHDD
|
| 455 |
+
lscales, hscales = np.hsplit(scales, [8])
|
| 456 |
+
lscales = lscales.reshape((n_blocks, 1, 8)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 2, 1))
|
| 457 |
+
lscales = lscales.reshape((n_blocks, 16))
|
| 458 |
+
hscales = hscales.reshape((n_blocks, 1, 4)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 4, 1))
|
| 459 |
+
hscales = hscales.reshape((n_blocks, 16))
|
| 460 |
+
scales = (lscales & np.uint8(0x0F)) | ((hscales & np.uint8(0x03)) << np.uint8(4))
|
| 461 |
+
scales = (scales.astype(np.int8) - np.int8(32)).astype(np.float32)
|
| 462 |
+
|
| 463 |
+
dl = (d * scales).reshape((n_blocks, 16, 1))
|
| 464 |
+
|
| 465 |
+
ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
|
| 466 |
+
qh = hmask.reshape(n_blocks, -1, 1, 32) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8, 1))
|
| 467 |
+
ql = ql.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(3)
|
| 468 |
+
qh = (qh.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(1))
|
| 469 |
+
qh = qh ^ np.uint8(1) # strangely, the offset is zero when the bitmask is 1
|
| 470 |
+
q = (ql.astype(np.int8) - (qh << np.uint8(2)).astype(np.int8)).astype(np.float32)
|
| 471 |
+
|
| 472 |
+
return (dl * q).reshape((n_blocks, QK_K))
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
class Q4_K(__Quant, qtype=GGMLQuantizationType.Q4_K):
|
| 476 |
+
K_SCALE_SIZE = 12
|
| 477 |
+
|
| 478 |
+
@staticmethod
|
| 479 |
+
def get_scale_min(scales: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 480 |
+
n_blocks = scales.shape[0]
|
| 481 |
+
scales = scales.view(np.uint8)
|
| 482 |
+
### Unpacking the following: ###
|
| 483 |
+
# 0 EEAAAAAA
|
| 484 |
+
# 1 FFBBBBBB
|
| 485 |
+
# 2 GGCCCCCC
|
| 486 |
+
# 3 HHDDDDDD
|
| 487 |
+
# 4 eeaaaaaa
|
| 488 |
+
# 5 ffbbbbbb
|
| 489 |
+
# 6 ggcccccc
|
| 490 |
+
# 7 hhdddddd
|
| 491 |
+
# 8 eeeeEEEE
|
| 492 |
+
# 9 ffffFFFF
|
| 493 |
+
# 10 ggggGGGG
|
| 494 |
+
# 11 hhhhHHHH
|
| 495 |
+
scales = scales.reshape((n_blocks, 3, 4))
|
| 496 |
+
d, m, m_d = np.split(scales, 3, axis=-2)
|
| 497 |
+
|
| 498 |
+
sc = np.concatenate([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], axis=-1)
|
| 499 |
+
min = np.concatenate([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], axis=-1)
|
| 500 |
+
|
| 501 |
+
return (sc.reshape((n_blocks, 8)), min.reshape((n_blocks, 8)))
|
| 502 |
+
|
| 503 |
+
@classmethod
|
| 504 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 505 |
+
n_blocks = blocks.shape[0]
|
| 506 |
+
|
| 507 |
+
d, rest = np.hsplit(blocks, [2])
|
| 508 |
+
dmin, rest = np.hsplit(rest, [2])
|
| 509 |
+
scales, qs = np.hsplit(rest, [cls.K_SCALE_SIZE])
|
| 510 |
+
|
| 511 |
+
d = d.view(np.float16).astype(np.float32)
|
| 512 |
+
dmin = dmin.view(np.float16).astype(np.float32)
|
| 513 |
+
|
| 514 |
+
sc, m = Q4_K.get_scale_min(scales)
|
| 515 |
+
|
| 516 |
+
d = (d * sc.astype(np.float32)).reshape((n_blocks, -1, 1))
|
| 517 |
+
dm = (dmin * m.astype(np.float32)).reshape((n_blocks, -1, 1))
|
| 518 |
+
|
| 519 |
+
qs = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 520 |
+
qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1, 32)).astype(np.float32)
|
| 521 |
+
|
| 522 |
+
return (d * qs - dm).reshape((n_blocks, QK_K))
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
class Q5_K(__Quant, qtype=GGMLQuantizationType.Q5_K):
|
| 526 |
+
@classmethod
|
| 527 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 528 |
+
n_blocks = blocks.shape[0]
|
| 529 |
+
|
| 530 |
+
d, rest = np.hsplit(blocks, [2])
|
| 531 |
+
dmin, rest = np.hsplit(rest, [2])
|
| 532 |
+
scales, rest = np.hsplit(rest, [Q4_K.K_SCALE_SIZE])
|
| 533 |
+
qh, qs = np.hsplit(rest, [QK_K // 8])
|
| 534 |
+
|
| 535 |
+
d = d.view(np.float16).astype(np.float32)
|
| 536 |
+
dmin = dmin.view(np.float16).astype(np.float32)
|
| 537 |
+
|
| 538 |
+
sc, m = Q4_K.get_scale_min(scales)
|
| 539 |
+
|
| 540 |
+
d = (d * sc.astype(np.float32)).reshape((n_blocks, -1, 1))
|
| 541 |
+
dm = (dmin * m.astype(np.float32)).reshape((n_blocks, -1, 1))
|
| 542 |
+
|
| 543 |
+
ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 544 |
+
qh = qh.reshape((n_blocks, -1, 1, 32)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8, 1))
|
| 545 |
+
ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1, 32))
|
| 546 |
+
qh = (qh & np.uint8(0x01)).reshape((n_blocks, -1, 32))
|
| 547 |
+
q = (ql | (qh << np.uint8(4))).astype(np.float32)
|
| 548 |
+
|
| 549 |
+
return (d * q - dm).reshape((n_blocks, QK_K))
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class Q6_K(__Quant, qtype=GGMLQuantizationType.Q6_K):
|
| 553 |
+
@classmethod
|
| 554 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 555 |
+
n_blocks = blocks.shape[0]
|
| 556 |
+
|
| 557 |
+
ql, rest = np.hsplit(blocks, [QK_K // 2])
|
| 558 |
+
qh, rest = np.hsplit(rest, [QK_K // 4])
|
| 559 |
+
scales, d = np.hsplit(rest, [QK_K // 16])
|
| 560 |
+
|
| 561 |
+
scales = scales.view(np.int8).astype(np.float32)
|
| 562 |
+
d = d.view(np.float16).astype(np.float32)
|
| 563 |
+
d = (d * scales).reshape((n_blocks, QK_K // 16, 1))
|
| 564 |
+
|
| 565 |
+
ql = ql.reshape((n_blocks, -1, 1, 64)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 566 |
+
ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1, 32))
|
| 567 |
+
qh = qh.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
|
| 568 |
+
qh = (qh & np.uint8(0x03)).reshape((n_blocks, -1, 32))
|
| 569 |
+
q = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(32)
|
| 570 |
+
q = q.reshape((n_blocks, QK_K // 16, -1)).astype(np.float32)
|
| 571 |
+
|
| 572 |
+
return (d * q).reshape((n_blocks, QK_K))
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
class TQ1_0(__Quant, qtype=GGMLQuantizationType.TQ1_0):
|
| 576 |
+
@classmethod
|
| 577 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 578 |
+
n_blocks = blocks.shape[0]
|
| 579 |
+
|
| 580 |
+
d = abs(blocks).max(axis=-1, keepdims=True)
|
| 581 |
+
with np.errstate(divide="ignore"):
|
| 582 |
+
id = np.where(d == 0, 0, 1 / d)
|
| 583 |
+
qs = np_roundf(blocks * id)
|
| 584 |
+
qs = (qs.astype(np.int8) + np.int8(1)).astype(np.uint8)
|
| 585 |
+
|
| 586 |
+
qs0, qs1, qh = qs[..., :(32 * 5)], qs[..., (32 * 5):(48 * 5)], qs[..., (48 * 5):]
|
| 587 |
+
qs0 = qs0.reshape((n_blocks, -1, 5, 32)) * np.array([81, 27, 9, 3, 1], dtype=np.uint8).reshape((1, 1, 5, 1))
|
| 588 |
+
qs0 = np.sum(qs0, axis=-2).reshape((n_blocks, -1))
|
| 589 |
+
qs1 = qs1.reshape((n_blocks, -1, 5, 16)) * np.array([81, 27, 9, 3, 1], dtype=np.uint8).reshape((1, 1, 5, 1))
|
| 590 |
+
qs1 = np.sum(qs1, axis=-2).reshape((n_blocks, -1))
|
| 591 |
+
qh = qh.reshape((n_blocks, -1, 4, 4)) * np.array([81, 27, 9, 3], dtype=np.uint8).reshape((1, 1, 4, 1))
|
| 592 |
+
qh = np.sum(qh, axis=-2).reshape((n_blocks, -1))
|
| 593 |
+
qs = np.concatenate([qs0, qs1, qh], axis=-1)
|
| 594 |
+
qs = (qs.astype(np.uint16) * 256 + (243 - 1)) // 243
|
| 595 |
+
|
| 596 |
+
qs = qs.astype(np.uint8)
|
| 597 |
+
d = d.astype(np.float16).view(np.uint8)
|
| 598 |
+
|
| 599 |
+
return np.concatenate([qs, d], axis=-1)
|
| 600 |
+
|
| 601 |
+
@classmethod
|
| 602 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 603 |
+
n_blocks = blocks.shape[0]
|
| 604 |
+
|
| 605 |
+
qs, rest = np.hsplit(blocks, [(QK_K - 4 * QK_K // 64) // 5])
|
| 606 |
+
qh, d = np.hsplit(rest, [QK_K // 64])
|
| 607 |
+
|
| 608 |
+
d = d.view(np.float16).astype(np.float32)
|
| 609 |
+
|
| 610 |
+
qs0, qs1 = qs[..., :32], qs[..., 32:]
|
| 611 |
+
qs0 = qs0.reshape((n_blocks, -1, 1, 32)) * np.array([1, 3, 9, 27, 81], dtype=np.uint8).reshape((1, 1, 5, 1))
|
| 612 |
+
qs0 = qs0.reshape((n_blocks, -1))
|
| 613 |
+
qs1 = qs1.reshape((n_blocks, -1, 1, 16)) * np.array([1, 3, 9, 27, 81], dtype=np.uint8).reshape((1, 1, 5, 1))
|
| 614 |
+
qs1 = qs1.reshape((n_blocks, -1))
|
| 615 |
+
qh = qh.reshape((n_blocks, -1, 1, 4)) * np.array([1, 3, 9, 27], dtype=np.uint8).reshape((1, 1, 4, 1))
|
| 616 |
+
qh = qh.reshape((n_blocks, -1))
|
| 617 |
+
qs = np.concatenate([qs0, qs1, qh], axis=-1)
|
| 618 |
+
qs = ((qs.astype(np.uint16) * 3) >> 8).astype(np.int8) - np.int8(1)
|
| 619 |
+
|
| 620 |
+
return (d * qs.astype(np.float32))
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class TQ2_0(__Quant, qtype=GGMLQuantizationType.TQ2_0):
|
| 624 |
+
@classmethod
|
| 625 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 626 |
+
n_blocks = blocks.shape[0]
|
| 627 |
+
|
| 628 |
+
d = abs(blocks).max(axis=-1, keepdims=True)
|
| 629 |
+
with np.errstate(divide="ignore"):
|
| 630 |
+
id = np.where(d == 0, 0, 1 / d)
|
| 631 |
+
qs = np_roundf(blocks * id)
|
| 632 |
+
qs = (qs.astype(np.int8) + np.int8(1)).astype(np.uint8)
|
| 633 |
+
|
| 634 |
+
qs = qs.reshape((n_blocks, -1, 4, 32)) << np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
|
| 635 |
+
qs = qs[..., 0, :] | qs[..., 1, :] | qs[..., 2, :] | qs[..., 3, :]
|
| 636 |
+
qs = qs.reshape((n_blocks, -1))
|
| 637 |
+
|
| 638 |
+
d = d.astype(np.float16).view(np.uint8)
|
| 639 |
+
|
| 640 |
+
return np.concatenate([qs, d], axis=-1)
|
| 641 |
+
|
| 642 |
+
@classmethod
|
| 643 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 644 |
+
n_blocks = blocks.shape[0]
|
| 645 |
+
|
| 646 |
+
qs, d = np.hsplit(blocks, [QK_K // 4])
|
| 647 |
+
|
| 648 |
+
d = d.view(np.float16).astype(np.float32)
|
| 649 |
+
|
| 650 |
+
qs = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
|
| 651 |
+
qs = (qs & 0x03).reshape((n_blocks, -1)).astype(np.int8) - np.int8(1)
|
| 652 |
+
|
| 653 |
+
return (d * qs.astype(np.float32))
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
class MXFP4(__Quant, qtype=GGMLQuantizationType.MXFP4):
|
| 657 |
+
# e2m1 values (doubled)
|
| 658 |
+
# ref: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
|
| 659 |
+
kvalues = (0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12)
|
| 660 |
+
|
| 661 |
+
@staticmethod
|
| 662 |
+
# see ggml_e8m0_to_fp32_half in ggml-impl.h
|
| 663 |
+
def e8m0_to_fp32_half(x: np.ndarray) -> np.ndarray:
|
| 664 |
+
bits = np.where(x < 2, np.uint32(0x00200000) << np.uint32(x), np.uint32(x - 1) << np.uint32(23))
|
| 665 |
+
return bits.view(np.float32)
|
| 666 |
+
|
| 667 |
+
@classmethod
|
| 668 |
+
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 669 |
+
n_blocks = blocks.shape[0]
|
| 670 |
+
|
| 671 |
+
d = abs(blocks).max(axis=-1, keepdims=True)
|
| 672 |
+
|
| 673 |
+
with np.errstate(divide="ignore"):
|
| 674 |
+
e = np.where(d > 0, np.floor(np.log2(d)) - 2 + 127, 0).astype(np.uint8)
|
| 675 |
+
|
| 676 |
+
d = cls.e8m0_to_fp32_half(e)
|
| 677 |
+
|
| 678 |
+
kvalues = np.array(cls.kvalues, dtype=np.int8).reshape((1, 1, 16))
|
| 679 |
+
|
| 680 |
+
errs = np.abs(d.reshape((n_blocks, 1, 1)) * kvalues.astype(np.float32) - blocks.reshape((n_blocks, cls.block_size, 1)))
|
| 681 |
+
best = np.argmin(errs, axis=-1, keepdims=True)
|
| 682 |
+
|
| 683 |
+
qs = best.reshape(n_blocks, 2, cls.block_size // 2).astype(np.uint8)
|
| 684 |
+
qs = qs[:, 0] | (qs[:, 1] << np.uint8(4))
|
| 685 |
+
|
| 686 |
+
qs = qs.reshape((n_blocks, cls.block_size // 2))
|
| 687 |
+
|
| 688 |
+
return np.concatenate([e, qs], axis=-1)
|
| 689 |
+
|
| 690 |
+
@classmethod
|
| 691 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 692 |
+
n_blocks = blocks.shape[0]
|
| 693 |
+
|
| 694 |
+
e, qs = np.hsplit(blocks, [1])
|
| 695 |
+
|
| 696 |
+
d = cls.e8m0_to_fp32_half(e)
|
| 697 |
+
|
| 698 |
+
qs = qs.reshape((n_blocks, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 2, 1))
|
| 699 |
+
qs = (qs & np.uint8(0x0F)).view(np.int8)
|
| 700 |
+
|
| 701 |
+
kvalues = np.array(cls.kvalues, dtype=np.int8).reshape(1, 1, 16)
|
| 702 |
+
qs = np.take_along_axis(kvalues, qs, axis=-1).reshape((n_blocks, cls.block_size))
|
| 703 |
+
|
| 704 |
+
return (d * qs.astype(np.float32))
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
class IQ2_XXS(__Quant, qtype=GGMLQuantizationType.IQ2_XXS):
|
| 708 |
+
ksigns: bytes = (
|
| 709 |
+
b"\x00\x81\x82\x03\x84\x05\x06\x87\x88\x09\x0a\x8b\x0c\x8d\x8e\x0f"
|
| 710 |
+
b"\x90\x11\x12\x93\x14\x95\x96\x17\x18\x99\x9a\x1b\x9c\x1d\x1e\x9f"
|
| 711 |
+
b"\xa0\x21\x22\xa3\x24\xa5\xa6\x27\x28\xa9\xaa\x2b\xac\x2d\x2e\xaf"
|
| 712 |
+
b"\x30\xb1\xb2\x33\xb4\x35\x36\xb7\xb8\x39\x3a\xbb\x3c\xbd\xbe\x3f"
|
| 713 |
+
b"\xc0\x41\x42\xc3\x44\xc5\xc6\x47\x48\xc9\xca\x4b\xcc\x4d\x4e\xcf"
|
| 714 |
+
b"\x50\xd1\xd2\x53\xd4\x55\x56\xd7\xd8\x59\x5a\xdb\x5c\xdd\xde\x5f"
|
| 715 |
+
b"\x60\xe1\xe2\x63\xe4\x65\x66\xe7\xe8\x69\x6a\xeb\x6c\xed\xee\x6f"
|
| 716 |
+
b"\xf0\x71\x72\xf3\x74\xf5\xf6\x77\x78\xf9\xfa\x7b\xfc\x7d\x7e\xff"
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
# iq2xxs_grid, but with each byte of the original packed in 2 bits,
|
| 720 |
+
# by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
|
| 721 |
+
grid_shape = (256, 8)
|
| 722 |
+
grid_map = (0x08, 0x19, 0x2b)
|
| 723 |
+
grid_hex = (
|
| 724 |
+
b"00000200050008000a00110014002000220028002a0041004400500058006100"
|
| 725 |
+
b"6400800082008a00a20001010401100115014001840198010002020222028202"
|
| 726 |
+
b"010404041004210424044004420448046004810484049004a404000502050805"
|
| 727 |
+
b"200546056905800591050906100640068406a406000805080808140828084108"
|
| 728 |
+
b"440850085208880804094009020a140a01100410101021104010601084109010"
|
| 729 |
+
b"951000110811201150115a118011241245120014081420142514491480141815"
|
| 730 |
+
b"6215001616160118041810184018811800190519a019511a002002200a204420"
|
| 731 |
+
b"6120802082202921482100220222012404241024402456240025412564259026"
|
| 732 |
+
b"082820289428442a014004401040184021402440404048405640604081408440"
|
| 733 |
+
b"9040004120416141804185410142104248425642684200440844204480449944"
|
| 734 |
+
b"124524450046014804481048404845480049584961498249454a904a00500850"
|
| 735 |
+
b"1150195020508050885004514251a4519152905492540a550156545600581158"
|
| 736 |
+
b"195864584059085a046010604060686000615561186260620064056410651265"
|
| 737 |
+
b"84654268008002800a8041808280048118814081118201840484108415844084"
|
| 738 |
+
b"608400854685948509864086608602880489118a0490109024904090a1901691"
|
| 739 |
+
b"8091459200942294449451958198209902a050a085a009a100a218a450a804a9"
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
@classmethod
|
| 743 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 744 |
+
n_blocks = blocks.shape[0]
|
| 745 |
+
|
| 746 |
+
d, qs = np.hsplit(blocks, [2])
|
| 747 |
+
|
| 748 |
+
d = d.view(np.float16).astype(np.float32)
|
| 749 |
+
|
| 750 |
+
qs = qs.view(np.uint32).reshape(n_blocks, -1, 2)
|
| 751 |
+
|
| 752 |
+
db = d * (np.float32(0.5) + (qs[..., 1] >> 28).astype(np.float32)) * np.float32(0.25)
|
| 753 |
+
db = db.reshape((n_blocks, -1, 1, 1))
|
| 754 |
+
|
| 755 |
+
# get the sign indices and unpack the bits
|
| 756 |
+
signs = qs[..., 1].reshape((n_blocks, -1, 1)) >> np.array([0, 7, 14, 21], dtype=np.uint32).reshape((1, 1, 4))
|
| 757 |
+
ksigns = np.frombuffer(cls.ksigns, dtype=np.uint8).reshape((1, 1, 1, 128))
|
| 758 |
+
signs = (signs & np.uint32(0x7F)).reshape((n_blocks, -1, 4, 1))
|
| 759 |
+
signs = np.take_along_axis(ksigns, signs, axis=-1)
|
| 760 |
+
signs = signs.reshape((n_blocks, -1, 4, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 1, 8))
|
| 761 |
+
signs = signs & np.uint8(0x01)
|
| 762 |
+
signs = np.where(signs == 0, np.float32(1), np.float32(-1))
|
| 763 |
+
signs = signs.reshape((n_blocks, -1, 4, 8))
|
| 764 |
+
|
| 765 |
+
assert cls.grid is not None
|
| 766 |
+
grid = np.take_along_axis(cls.grid, qs[..., 0].copy().view(np.uint8).reshape((n_blocks, -1, 1, 1)), axis=-2)
|
| 767 |
+
grid = grid.reshape((n_blocks, -1, 4, 8))
|
| 768 |
+
|
| 769 |
+
return (db * grid * signs).reshape((n_blocks, -1))
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
class IQ2_XS(__Quant, qtype=GGMLQuantizationType.IQ2_XS):
|
| 773 |
+
# iq2xs_grid, but with each byte of the original packed in 2 bits,
|
| 774 |
+
# by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
|
| 775 |
+
grid_shape = (512, 8)
|
| 776 |
+
grid_map = (0x08, 0x19, 0x2b)
|
| 777 |
+
grid_hex = (
|
| 778 |
+
b"00000200050008000a0011001400160019002000220025002800410044004600"
|
| 779 |
+
b"49005000520055005800610064008000820085008800910094009900a0000101"
|
| 780 |
+
b"04010601090110011201150118011a0121012401400142014501480151015401"
|
| 781 |
+
b"6001680181018401900100020202050208021102140220024102440250025502"
|
| 782 |
+
b"80028a0201040404060409041004120415041804210424044004420445044804"
|
| 783 |
+
b"5104540456046004810484049004000502050505080511051405200541054405"
|
| 784 |
+
b"500561058005010604061006260640064206840600080208050808080a081108"
|
| 785 |
+
b"14082008250841084408500858088008a008aa08010904091009400981098909"
|
| 786 |
+
b"000a200a280a960aa00a01100410061009101010121015101810211024104010"
|
| 787 |
+
b"4210451048105110541060106a10811084109010001102110511081111111411"
|
| 788 |
+
b"2011411144115011801194119611011204120612101240126012001402140514"
|
| 789 |
+
b"0814111414142014411444144914501464148014011504151015401500161416"
|
| 790 |
+
b"49160118041810181218401854188618001905196619511aa91a002002200520"
|
| 791 |
+
b"08200a201120142020204120442050208020a020012104211021402148216521"
|
| 792 |
+
b"002222228022a82201240424102429244024002541255225992501261a26a626"
|
| 793 |
+
b"002808280a28202855288828a22868299029082a202a822a882a8a2a01400440"
|
| 794 |
+
b"0640094010401240154018402140244040404240454048404a40514054406040"
|
| 795 |
+
b"6540814084409040004102410541084111411441204141414441504180418541"
|
| 796 |
+
b"a241014204421042124229424042004402440544084411441444194420444144"
|
| 797 |
+
b"4444504480449444014504451045244540459a4500460a464446504601480448"
|
| 798 |
+
b"1048404845485448624800491149444950496949044a00500250055008501150"
|
| 799 |
+
b"145020502850415044505050805001510451105115514051425100524452aa52"
|
| 800 |
+
b"0154045410542154405460548154a154005508558055885521566856a1560058"
|
| 801 |
+
b"14584158505899581a5940594259855a0160046010604060546062608660a960"
|
| 802 |
+
b"006124624a62926200641664106540654565a46501686a682569066a546a626a"
|
| 803 |
+
b"00800280058008801180148020802a8041804480508080808280a880aa800181"
|
| 804 |
+
b"0481068110814081518159810082208280828282a082a8820184048410841284"
|
| 805 |
+
b"158440846084898400854485a58518866a860088088825885a8880888288a888"
|
| 806 |
+
b"0689228a808a888a968aa88a0190049010904090569084900091229164915692"
|
| 807 |
+
b"89920094059444945094589429959095929541965198a6984999159a609a00a0"
|
| 808 |
+
b"02a008a00aa020a02aa0a0a051a159a1a6a100a202a208a22aa280a2a0a240a4"
|
| 809 |
+
b"95a465a698a60aa820a822a828a8a0a8a8a804a984a986a928aa2aaa91aaaaaa"
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
@classmethod
|
| 813 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 814 |
+
n_blocks = blocks.shape[0]
|
| 815 |
+
|
| 816 |
+
d, rest = np.hsplit(blocks, [2])
|
| 817 |
+
qs, scales = np.hsplit(rest, [2 * QK_K // 8])
|
| 818 |
+
|
| 819 |
+
d = d.view(np.float16).astype(np.float32)
|
| 820 |
+
qs = qs.view(np.uint16)
|
| 821 |
+
|
| 822 |
+
scales = scales.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
|
| 823 |
+
scales = (scales & 0x0F).reshape((n_blocks, -1))
|
| 824 |
+
db = d * (np.float32(0.5) + scales) * np.float32(0.25)
|
| 825 |
+
db = db.reshape((n_blocks, -1, 1, 1))
|
| 826 |
+
|
| 827 |
+
# get the sign indices and unpack the bits
|
| 828 |
+
signs = np.frombuffer(IQ2_XXS.ksigns, dtype=np.uint8).reshape(1, 1, 128)
|
| 829 |
+
signs = np.take_along_axis(signs, (qs >> 9).reshape((n_blocks, -1, 1)), axis=-1)
|
| 830 |
+
signs = signs.reshape((n_blocks, -1, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8))
|
| 831 |
+
signs = signs & np.uint8(0x01)
|
| 832 |
+
signs = np.where(signs == 0, np.float32(1), np.float32(-1))
|
| 833 |
+
signs = signs.reshape((n_blocks, -1, 2, 8))
|
| 834 |
+
|
| 835 |
+
assert cls.grid is not None
|
| 836 |
+
grid = np.take_along_axis(cls.grid, (qs & np.uint16(511)).reshape((n_blocks, -1, 1, 1)), axis=-2)
|
| 837 |
+
grid = grid.reshape((n_blocks, -1, 2, 8))
|
| 838 |
+
|
| 839 |
+
return (db * grid * signs).reshape((n_blocks, -1))
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
class IQ2_S(__Quant, qtype=GGMLQuantizationType.IQ2_S):
|
| 843 |
+
# iq2s_grid, but with each byte of the original packed in 2 bits,
|
| 844 |
+
# by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
|
| 845 |
+
grid_shape = (1024, 8)
|
| 846 |
+
grid_map = (0x08, 0x19, 0x2b)
|
| 847 |
+
grid_hex = (
|
| 848 |
+
b"00000200050008000a0011001400160019002000220025002800410044004600"
|
| 849 |
+
b"490050005200550058006100640066006900800082008500880091009400a000"
|
| 850 |
+
b"a500aa0001010401060109011001120115011801210124014001420145014801"
|
| 851 |
+
b"510154015601590160016501680181018401900192019501a101a40100020202"
|
| 852 |
+
b"050208021102140220022a02410244024602490250025502800285028a029402"
|
| 853 |
+
b"a202010404040604090410041204150418042104240426042904400442044504"
|
| 854 |
+
b"48044a0451045404560459046004620465048104840486048904900495049804"
|
| 855 |
+
b"a104a40400050205050508050a05110514051605190520052505280541054405"
|
| 856 |
+
b"46054905500552055505580561056405800582058505880591059405a0050106"
|
| 857 |
+
b"0406060609061006150640064506480651065406600681068406900600080208"
|
| 858 |
+
b"050808081108140816081908200825082a084108440846084908500852085508"
|
| 859 |
+
b"580861086408800885089408aa08010904091009120915091809210940094509"
|
| 860 |
+
b"480951095409600981099009000a110a140a220a280a2a0a500a990a01100410"
|
| 861 |
+
b"0610091010101210151018102110241026104010421045104810511054105610"
|
| 862 |
+
b"59106010621065106810811084108610901095109810a110a410001102110511"
|
| 863 |
+
b"08110a1111111411161119112011221125112811411144114611491150115211"
|
| 864 |
+
b"5511581161116411801182118511881191119411011204120912101215122112"
|
| 865 |
+
b"2412401245125112541281128412901200140214051408141114141416141914"
|
| 866 |
+
b"2014251428144114441446144914501452145514581461146414801482148514"
|
| 867 |
+
b"881491149414a014011504150615091510151215151518152115241540154215"
|
| 868 |
+
b"4515481551155415601581158415901500160516081611161416201641164416"
|
| 869 |
+
b"50168016aa160118041806180918101815181818211840184218451848185118"
|
| 870 |
+
b"541860188118841800190219051908191119141920194119441950196919a219"
|
| 871 |
+
b"041a101a401a561a00200220052008201120142016201920202025202a204120"
|
| 872 |
+
b"4420502052205520642080208a209420aa200121042110211221152121214021"
|
| 873 |
+
b"4221452151215421602181218421902100220a22222228222a22442250228822"
|
| 874 |
+
b"8a22a82201240424062409241024152418242124242440244224452448245124"
|
| 875 |
+
b"5424602481248424902400250525082511251425202541254425502566258025"
|
| 876 |
+
b"0126042610264026592600280528112814284128442850288a28aa2801290429"
|
| 877 |
+
b"102995290a2a222a642a882a8a2a014004400640094010401240154018401a40"
|
| 878 |
+
b"21402440264040404240454048404a4051405440564059406040624065408140"
|
| 879 |
+
b"8440904095409840a140a4400041024105410841114114411641194120412241"
|
| 880 |
+
b"2541414144414641494150415241554158416141644180418241854188419141"
|
| 881 |
+
b"9441a04101420442104212421542184224424042454248425142544260428142"
|
| 882 |
+
b"844200440244054408440a441144144416441944204422442544284441444444"
|
| 883 |
+
b"46444944504452445544584461446444804482448544884491449444a0440145"
|
| 884 |
+
b"0445064509451045124515451845214524454045424545454845514554456045"
|
| 885 |
+
b"6a4581458445904500460246054608461146144620464146444650468046a546"
|
| 886 |
+
b"0148044809481048124815481848214824484048424845484848514854486048"
|
| 887 |
+
b"84489048004902490549084911491449204941494449504980499649014a044a"
|
| 888 |
+
b"104a404a00500250055008501150145016501950205022502550285041504450"
|
| 889 |
+
b"4650495050505250555058506150645080508250855088509150945001510451"
|
| 890 |
+
b"0651095110511251155118512151245140514251455148515151545160518151"
|
| 891 |
+
b"8451905100520552085211521452205241524452505269528052015404540654"
|
| 892 |
+
b"0954105412541554185421542454405442544554485451545454605481548454"
|
| 893 |
+
b"9054005502550555085511551455205541554455505580550156045610562656"
|
| 894 |
+
b"405600580258055808581158145820584158445850585a588058015904591059"
|
| 895 |
+
b"4059005a195a855aa85a01600460066010601260156018602160246040604560"
|
| 896 |
+
b"4860516054606060846090600061026105610861116114612061416144615061"
|
| 897 |
+
b"806199610462106240625662a162006405640864116414642064416444645064"
|
| 898 |
+
b"806401650465106540654a656865926500669466016804681068656898680069"
|
| 899 |
+
b"2a69426aa16a0080028005800880118014801980208025804180448050805280"
|
| 900 |
+
b"5580588061808080858091809480018104810981108112811581188121812481"
|
| 901 |
+
b"408142814581488151815481818184819081a981008205820a82118214824182"
|
| 902 |
+
b"4482508201840484068409841084128415841884218440844284458448845184"
|
| 903 |
+
b"5484608481848484908400850285058508851185148520854185448550858085"
|
| 904 |
+
b"8a85018604861086298640860088058811881488418844885088a28801890489"
|
| 905 |
+
b"40896589228a588a5a8a828aa28a019004900990109012901590189024904090"
|
| 906 |
+
b"4290459048905190549060908190849090900091059111911491419144915091"
|
| 907 |
+
b"5a910192049210924092a6920094029405940894119414942094419444945094"
|
| 908 |
+
b"8094969401950495109540959895a19500964696649601980498109826984098"
|
| 909 |
+
b"a998009949995299909a00a005a00aa014a022a02aa041a044a050a0a2a0aaa0"
|
| 910 |
+
b"40a165a102a20aa222a228a22aa282a288a28aa2a8a201a404a410a440a489a4"
|
| 911 |
+
b"a4a400a519a551a60aa828a8a2a854a986a908aa0aaa20aa22aa28aa88aaaaaa"
|
| 912 |
+
)
|
| 913 |
+
|
| 914 |
+
@classmethod
|
| 915 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 916 |
+
n_blocks = blocks.shape[0]
|
| 917 |
+
|
| 918 |
+
d, rest = np.hsplit(blocks, [2])
|
| 919 |
+
qs, rest = np.hsplit(rest, [QK_K // 8])
|
| 920 |
+
signs, rest = np.hsplit(rest, [QK_K // 8])
|
| 921 |
+
qh, scales = np.hsplit(rest, [QK_K // 32])
|
| 922 |
+
|
| 923 |
+
d = d.view(np.float16).astype(np.float32)
|
| 924 |
+
|
| 925 |
+
scales = scales.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
|
| 926 |
+
scales = (scales & 0x0F).reshape((n_blocks, -1))
|
| 927 |
+
db = d * (np.float32(0.5) + scales) * np.float32(0.25)
|
| 928 |
+
db = db.reshape((n_blocks, -1, 1, 1))
|
| 929 |
+
|
| 930 |
+
# unpack the sign bits
|
| 931 |
+
signs = signs.reshape((n_blocks, -1, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8))
|
| 932 |
+
signs = signs & np.uint8(0x01)
|
| 933 |
+
signs = np.where(signs == 0, np.float32(1), np.float32(-1))
|
| 934 |
+
signs = signs.reshape((n_blocks, -1, 2, 8))
|
| 935 |
+
|
| 936 |
+
qh = qh.reshape((n_blocks, -1, 1)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4))
|
| 937 |
+
qs = qs.astype(np.uint16) | ((qh & 0x03).astype(np.uint16) << 8).reshape((n_blocks, -1))
|
| 938 |
+
|
| 939 |
+
assert cls.grid is not None
|
| 940 |
+
grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
|
| 941 |
+
grid = grid.reshape((n_blocks, -1, 2, 8))
|
| 942 |
+
|
| 943 |
+
return (db * grid * signs).reshape((n_blocks, -1))
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
class IQ3_XXS(__Quant, qtype=GGMLQuantizationType.IQ3_XXS):
|
| 947 |
+
grid_shape = (256, 4)
|
| 948 |
+
grid_map = (0x04, 0x0c, 0x14, 0x1c, 0x24, 0x2c, 0x34, 0x3e)
|
| 949 |
+
grid_hex = (
|
| 950 |
+
b"0000020004001100130017002000220031004200730075000101030110011201"
|
| 951 |
+
b"2101250130013201410154017001000202020402110220022202310233023702"
|
| 952 |
+
b"5102570275020103070310031203250370031304370444045704730475040105"
|
| 953 |
+
b"0705320552053506640610071407160743076107011003101010121021102310"
|
| 954 |
+
b"3010321034104710501000110211111120112211011203121012121221123012"
|
| 955 |
+
b"7212001302132013311346136613011405145014201524154615711505162217"
|
| 956 |
+
b"4017002002201120132020202220262031204220012103210521102112212121"
|
| 957 |
+
b"3021632167217021002202221122172220222222372240225522012310231423"
|
| 958 |
+
b"7023742335245324032527254125742501270327162745270130103012302130"
|
| 959 |
+
b"2330503065307230003102312031313144314631013203321032253252327232"
|
| 960 |
+
b"1133333330344734723400350635223555351436363663363337603704401740"
|
| 961 |
+
b"3540374053405740744120423742404260426642074345430444514464442545"
|
| 962 |
+
b"4345704505471047124730471250415070500051065126515551145232527252"
|
| 963 |
+
b"0253535310542354275472540255315550562457425724604460466064602161"
|
| 964 |
+
b"6161176264623063366344640565526533660367216703700570077010703270"
|
| 965 |
+
b"5270267140711272457252720073157333736073217441740075027524753076"
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
@classmethod
|
| 969 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 970 |
+
n_blocks = blocks.shape[0]
|
| 971 |
+
|
| 972 |
+
d, rest = np.hsplit(blocks, [2])
|
| 973 |
+
qs, scales = np.hsplit(rest, [QK_K // 4])
|
| 974 |
+
|
| 975 |
+
d = d.view(np.float16).astype(np.float32)
|
| 976 |
+
scales = scales.view(np.uint32)
|
| 977 |
+
|
| 978 |
+
db = d * (np.float32(0.5) + (scales >> 28).astype(np.float32)) * np.float32(0.5)
|
| 979 |
+
db = db.reshape((n_blocks, -1, 1, 1))
|
| 980 |
+
|
| 981 |
+
# get the sign indices and unpack the bits
|
| 982 |
+
signs = scales.reshape((n_blocks, -1, 1)) >> np.array([0, 7, 14, 21], dtype=np.uint32).reshape((1, 1, 4))
|
| 983 |
+
ksigns = np.frombuffer(IQ2_XXS.ksigns, dtype=np.uint8).reshape((1, 1, 1, 128))
|
| 984 |
+
signs = (signs & np.uint32(0x7F)).reshape((n_blocks, -1, 4, 1))
|
| 985 |
+
signs = np.take_along_axis(ksigns, signs, axis=-1)
|
| 986 |
+
signs = signs.reshape((n_blocks, -1, 4, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 1, 8))
|
| 987 |
+
signs = signs & np.uint8(0x01)
|
| 988 |
+
signs = np.where(signs == 0, np.float32(1), np.float32(-1))
|
| 989 |
+
signs = signs.reshape((n_blocks, -1, 4, 8))
|
| 990 |
+
|
| 991 |
+
assert cls.grid is not None
|
| 992 |
+
grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
|
| 993 |
+
grid = grid.reshape((n_blocks, -1, 4, 8))
|
| 994 |
+
|
| 995 |
+
return (db * grid * signs).reshape((n_blocks, -1))
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
class IQ3_S(__Quant, qtype=GGMLQuantizationType.IQ3_S):
|
| 999 |
+
grid_shape = (512, 4)
|
| 1000 |
+
grid_map = (0x01, 0x03, 0x05, 0x07, 0x09, 0x0b, 0x0d, 0x0f)
|
| 1001 |
+
grid_hex = (
|
| 1002 |
+
b"0000010002000500070010001100120014001600200021002500330040004200"
|
| 1003 |
+
b"4500470051005300600062007100740077000001010102010401100111011501"
|
| 1004 |
+
b"2001230127013101350144016101650172010002010205020702100213021602"
|
| 1005 |
+
b"2102250230023402420245024702510253027002730203031103150320032203"
|
| 1006 |
+
b"3103330336034403500352036703710375030004130417042104240432044004"
|
| 1007 |
+
b"4304510470040205040520052205260533054105450547056605730506061106"
|
| 1008 |
+
b"1306310652067106000702070407200722072607330750075407001001100210"
|
| 1009 |
+
b"0410101011101310151017102010221031103410361054105610611072100011"
|
| 1010 |
+
b"0111031106111011141121113011331141115011521170117611001212121512"
|
| 1011 |
+
b"1712201224123212401243125512601272120113041307131013131321132713"
|
| 1012 |
+
b"3013341341136213701303140514121414143114331442144614501454140115"
|
| 1013 |
+
b"1015131521153015321551152016241627164416461601170317101712172117"
|
| 1014 |
+
b"3517411762177017002001200320052007201020122014201620212023202720"
|
| 1015 |
+
b"3020322041204320452050205220672070207320752000210221102113211721"
|
| 1016 |
+
b"2221252131213421422151210122042207222122232230223722412253225722"
|
| 1017 |
+
b"7122742200230223052311232223242331233323422350236623012407242024"
|
| 1018 |
+
b"2324322435244124722475240425112522253725402553257025002602260726"
|
| 1019 |
+
b"2126552661260527112726273027432750270230113013301530173022303130"
|
| 1020 |
+
b"3330353042304430473051306330713001310331053114312131233140316031"
|
| 1021 |
+
b"7231763100321232203232323432503201331033143321332333273330334133"
|
| 1022 |
+
b"4333473355337333033411341634223431345234603464340135103512352535"
|
| 1023 |
+
b"3235443556357335163641360137033720372237353700400440124020402440"
|
| 1024 |
+
b"2740324041405040704002410741114113412241304135414341514155410142"
|
| 1025 |
+
b"0342104215422142334240425742624270420443114313432043224331433543"
|
| 1026 |
+
b"0044024424443744404471440545074521456245134634466046104715473047"
|
| 1027 |
+
b"4347514702501050145022504050445047505250665074500151035105511251"
|
| 1028 |
+
b"2151325172510052115223523052365253520253075310532753445351536553"
|
| 1029 |
+
b"7353015404542054325446541255265551555355425602570457225711601360"
|
| 1030 |
+
b"1560316033606060006120612761646112623462426255626262706200631463"
|
| 1031 |
+
b"2163406325644364626400650365346560650566406611671367007004700770"
|
| 1032 |
+
b"2070227036704070547062700271117124714371457101720472107216722172"
|
| 1033 |
+
b"3072517202733273357353730174057413742074507422754275027631760077"
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
@classmethod
|
| 1037 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 1038 |
+
n_blocks = blocks.shape[0]
|
| 1039 |
+
|
| 1040 |
+
d, rest = np.hsplit(blocks, [2])
|
| 1041 |
+
qs, rest = np.hsplit(rest, [QK_K // 4])
|
| 1042 |
+
qh, rest = np.hsplit(rest, [QK_K // 32])
|
| 1043 |
+
signs, scales = np.hsplit(rest, [QK_K // 8])
|
| 1044 |
+
|
| 1045 |
+
d = d.view(np.float16).astype(np.float32)
|
| 1046 |
+
|
| 1047 |
+
scales = scales.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
|
| 1048 |
+
scales = (scales & 0x0F).reshape((n_blocks, -1))
|
| 1049 |
+
db = d * (1 + 2 * scales)
|
| 1050 |
+
db = db.reshape((n_blocks, -1, 1, 1))
|
| 1051 |
+
|
| 1052 |
+
# unpack the sign bits
|
| 1053 |
+
signs = signs.reshape((n_blocks, -1, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8))
|
| 1054 |
+
signs = signs & np.uint8(0x01)
|
| 1055 |
+
signs = np.where(signs == 0, np.float32(1), np.float32(-1))
|
| 1056 |
+
signs = signs.reshape((n_blocks, -1, 4, 8))
|
| 1057 |
+
|
| 1058 |
+
qh = qh.reshape((n_blocks, -1, 1)) >> np.array([i for i in range(8)], dtype=np.uint8)
|
| 1059 |
+
qh = (qh & 0x01).astype(np.uint16).reshape((n_blocks, -1))
|
| 1060 |
+
qs = qs.astype(np.uint16) | (qh << 8)
|
| 1061 |
+
|
| 1062 |
+
assert cls.grid is not None
|
| 1063 |
+
grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
|
| 1064 |
+
grid = grid.reshape((n_blocks, -1, 4, 8))
|
| 1065 |
+
|
| 1066 |
+
return (db * grid * signs).reshape((n_blocks, -1))
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
class IQ1_S(__Quant, qtype=GGMLQuantizationType.IQ1_S):
|
| 1070 |
+
# iq1s_grid, with each byte packed into 2 bits
|
| 1071 |
+
# -1, 0, 1 <=> 0, 1, 2
|
| 1072 |
+
grid_shape = (2048, 8)
|
| 1073 |
+
grid_map = (-1, 0, 1)
|
| 1074 |
+
grid_hex = (
|
| 1075 |
+
b"00000200050008000a00110015002000220028002a0045005100540056006500"
|
| 1076 |
+
b"8000820088008a009500a000a200a800aa000401050111011401160119011a01"
|
| 1077 |
+
b"2501410146014901520155015a0161016401660168018501910194019601a501"
|
| 1078 |
+
b"0002020208020a0215022002220228022a024502510259026402690280028202"
|
| 1079 |
+
b"88028a02910295029902a002a202a802aa021104140416042504410449045504"
|
| 1080 |
+
b"5a046404650491049904a5040105040505050605150518051a05290540054505"
|
| 1081 |
+
b"4a0550055105540555055605590560056205650568056a058105910595059805"
|
| 1082 |
+
b"9a05a105a405a505a605a9051406190641064406500652065506580660066106"
|
| 1083 |
+
b"6606690685069106940699060008020808080a0815082008220828082a084508"
|
| 1084 |
+
b"5108560865088008820888088a089508a008a208a808aa080509110914091909"
|
| 1085 |
+
b"2409250941095009510955096109640969099109940996099909a509000a020a"
|
| 1086 |
+
b"080a0a0a150a200a220a280a2a0a450a510a590a610a650a800a820a850a880a"
|
| 1087 |
+
b"8a0a950aa00aa20aa80aaa0a1010111014101910241025104110441050105510"
|
| 1088 |
+
b"58106110641065106910911094109610a110a510011104110611091110111211"
|
| 1089 |
+
b"1511181121112411291145114a11501151115211541155115611591160116511"
|
| 1090 |
+
b"841192119511a111a41111121412161225124012461249125212551258125a12"
|
| 1091 |
+
b"641266128512911294129612a512011406140914141415141814191421142614"
|
| 1092 |
+
b"41144514461448144a1451145414551456145914621465146814841489149014"
|
| 1093 |
+
b"94149514981499149a14a114a414a514a914021505150a151115141515151615"
|
| 1094 |
+
b"191520152215251528152a154115441545154615511552155415551556155915"
|
| 1095 |
+
b"5a1561156415651566156915801582158415851588158a159015911594159515"
|
| 1096 |
+
b"961599159a15a015a215a51501160416051606161516161618161a1621162616"
|
| 1097 |
+
b"401642164416451648164a165116551656165816591661166416651668166916"
|
| 1098 |
+
b"6a1686168a1692169516a416a916111816182518411844184618491850185518"
|
| 1099 |
+
b"58185a1860186118641866186918851891189418a5181019121915191a192119"
|
| 1100 |
+
b"25194219441945194819511954195519561959195a19601965196a1989199119"
|
| 1101 |
+
b"921995199819a119a619a919091a161a241a261a441a461a491a501a521a551a"
|
| 1102 |
+
b"581a611a661a691a851a911a961a9a1a0020022008200a201520202022202520"
|
| 1103 |
+
b"28202a20452051205920612065208020822088208a209520a020a220a520a820"
|
| 1104 |
+
b"aa2005211121142119212521422144214921552158215a216121642165216621"
|
| 1105 |
+
b"8521902196219921a521012208220a22112215222022222228222a2245225122"
|
| 1106 |
+
b"562259226522812288228a2291229522a022a222a822aa220524142416241924"
|
| 1107 |
+
b"252444244524462449245224552458245a2466248524912494249924a124a524"
|
| 1108 |
+
b"0925152521252925402545254825512554255525592562256525682589259025"
|
| 1109 |
+
b"9425952598259a25a125a425a625a92505261026122619262526412649265526"
|
| 1110 |
+
b"6026612669268426862690269a260028022808280a2815282028222828282a28"
|
| 1111 |
+
b"45285128542865288028822888288a28a028a228a828aa280929112914291929"
|
| 1112 |
+
b"2529462949295229552961296429662969298529902996299929a429a529002a"
|
| 1113 |
+
b"022a082a0a2a202a222a282a2a2a452a512a562a592a652a802a822a882a8a2a"
|
| 1114 |
+
b"952aa02aa22aa82aaa2a054011401640254049405240554058405a4061406440"
|
| 1115 |
+
b"664094409940a140a6400041014104410641094112411541164118411a412141"
|
| 1116 |
+
b"26412941454148414a41514154415541564159415a41654168416a4181418441"
|
| 1117 |
+
b"8641904192419541a041a141a241054211421442164225424142524255425a42"
|
| 1118 |
+
b"6442694289429442a5420144154419442944454448444a445144544455445644"
|
| 1119 |
+
b"61446244654468446a44814486448944904492449544a044a144a94401450245"
|
| 1120 |
+
b"05450a4511451445154516451945204525452a45414544454545464549455045"
|
| 1121 |
+
b"5145544555455645584559456145644565456645694582458445854588459145"
|
| 1122 |
+
b"94459545964599459a45a545a845aa450146054609461446154618461a462146"
|
| 1123 |
+
b"2446294640464246454648465046514652465546564659466246654668468146"
|
| 1124 |
+
b"85468a4694469546a146a446a6460548114815481a4825484248494850485548"
|
| 1125 |
+
b"5848614864486648694885489148944896489948a5480149054906490a491049"
|
| 1126 |
+
b"144915491849214924492649404945494a495149524954495549564959496049"
|
| 1127 |
+
b"6249654966496a49864989499249954996499849a149a449a649a949164a444a"
|
| 1128 |
+
b"464a494a554a584a5a4a644a694a944aa54a0150045005500650095012501550"
|
| 1129 |
+
b"1a50215024502950405045504850515054505550565059506550685086508950"
|
| 1130 |
+
b"95509850a050a150a650a9500551085109510a51115114511551165118511951"
|
| 1131 |
+
b"20512551265128512a5141514451455146514951505151515251545155515651"
|
| 1132 |
+
b"585159515a51615164516551665169518251855191519451955196519951a051"
|
| 1133 |
+
b"a551aa5101520652125215521a5221522452425245524a525152545255525652"
|
| 1134 |
+
b"595262526552855290529252955299529a52a452045405541154145415541654"
|
| 1135 |
+
b"185419542154255428542a54415444544554465449544a545054515454545554"
|
| 1136 |
+
b"5654585459545a54615462546454655466546954805488548a54915494549554"
|
| 1137 |
+
b"96549954a154a454a554aa540155025504550555065509551055115512551455"
|
| 1138 |
+
b"1555165519551a55215524552555265529554055415542554455455546554855"
|
| 1139 |
+
b"4955505551555255545555555655585559555a55605561556455655566556855"
|
| 1140 |
+
b"69556a5581558455855589558a559055915594559555965598559955a155a455"
|
| 1141 |
+
b"a555a655a9550056015602560456065608560956115614561556185619562056"
|
| 1142 |
+
b"2156225624562556265628562956415645564656485649564a56505651565256"
|
| 1143 |
+
b"545655565656585659565a566156645665566956825685568656885689568a56"
|
| 1144 |
+
b"915695569a56a256a556a656a856a95604580558065809581058155818582158"
|
| 1145 |
+
b"2a58455848584a58515854585558565858585958605862586458655882588958"
|
| 1146 |
+
b"9058925895589858a158a9580159025905590a59115914591559165919592559"
|
| 1147 |
+
b"41594459455946594959505951595259545955595659585959595a5961596459"
|
| 1148 |
+
b"655966596959815985598959915994599559965998599959a559045a085a155a"
|
| 1149 |
+
b"1a5a205a255a265a295a455a485a495a515a555a565a585a595a625a655a685a"
|
| 1150 |
+
b"6a5a815a8a5a925a955a965a985a9a5aa15a0560146016601960256044605060"
|
| 1151 |
+
b"5560566058605a60616064606660696081609660a56001610461066109611261"
|
| 1152 |
+
b"15612161226126612961456149615161556156615961656166616a6184618a61"
|
| 1153 |
+
b"92619561a161a661a96111621662196240624162466255625662586260628562"
|
| 1154 |
+
b"91629662a56211641264156416641a6421642664296440644264456448644a64"
|
| 1155 |
+
b"516454645564566459645a646064626465648464856489649064926494649564"
|
| 1156 |
+
b"966498649a64a164a464a964056508650a651165156516651965446545654665"
|
| 1157 |
+
b"496550655165546555655665596561656465656566656965866589658a659165"
|
| 1158 |
+
b"9565966599659a65a265a565a665a86502660966156620662666286629664066"
|
| 1159 |
+
b"456648664a66516654665566566658665a666066656668668066826685668a66"
|
| 1160 |
+
b"9466966698669966a066a466a666aa661668196825684168526855685a686168"
|
| 1161 |
+
b"6968856891689868a66801690469106915692169246926692969406941694569"
|
| 1162 |
+
b"4669486951695469556956695969606965696a69826984698a699569a169a469"
|
| 1163 |
+
b"a569a969116a166a186a416a446a496a506a556a586a5a6a646a656a696a866a"
|
| 1164 |
+
b"946a986a9a6aa66a0080028008800a802080228028802a804580508051805480"
|
| 1165 |
+
b"5680598065808080828088808a809580a080a280a880aa800581118114811681"
|
| 1166 |
+
b"1981258141814481498150815281558156815881598164816681698185818981"
|
| 1167 |
+
b"948196819981a5810082028208820a8215822082228228822a82518254825982"
|
| 1168 |
+
b"65828082828288828a829582a082a282a882aa82148419844184448451845584"
|
| 1169 |
+
b"5a846184648469849484998401850985128515851a8526852985408541854585"
|
| 1170 |
+
b"4885518554855585568559855a856585668568856a8581858485868589859085"
|
| 1171 |
+
b"928595859885a68511861686198625864186448649864a865086558659865a86"
|
| 1172 |
+
b"618666866a86858691869a86a4860088028808880a8815882088228828882a88"
|
| 1173 |
+
b"41884588518854885988658869888088828888888a889588a088a288a888aa88"
|
| 1174 |
+
b"05890689118914891689258941894489468949895089528955895a8961896489"
|
| 1175 |
+
b"858996899989a589008a028a088a0a8a158a208a228a288a2a8a458a518a548a"
|
| 1176 |
+
b"568a808a828a888a8a8a958aa08aa28aa88aaa8a059011901690189019902590"
|
| 1177 |
+
b"419046904990559058905a9069906a9085909190949096909990a59001910491"
|
| 1178 |
+
b"069109911091159118911a912191249126912991409145915091519154915591"
|
| 1179 |
+
b"569159916291659184918691929195919891a191a491a691a991059211921492"
|
| 1180 |
+
b"19922592449246924992509252925592589266926992859294929692a9920194"
|
| 1181 |
+
b"04940694109415941894269440944a9451945494559456945894599460946194"
|
| 1182 |
+
b"62946594849486949294949495949894a194a9940095059508950a9510951195"
|
| 1183 |
+
b"14951595169519952195259529952a9541954495459546954995509551955295"
|
| 1184 |
+
b"549555955695589559955a956195649565956695699581958595889591959295"
|
| 1185 |
+
b"94959595969599959a95a095a295a595a895aa95019604961096159619962096"
|
| 1186 |
+
b"2696299645964896499651965296559656965996659668968296849689968a96"
|
| 1187 |
+
b"929694969596a496a696a9960598169819982598419846985098529855985698"
|
| 1188 |
+
b"5a98649865988598919896989998a59804990699099910991299159918991a99"
|
| 1189 |
+
b"209921992499269940994299459948994a995199549955995699599962996599"
|
| 1190 |
+
b"66996a99819984999099929995999a99a199a699059a159a259a449a469a499a"
|
| 1191 |
+
b"509a559a589a619a859a919a949a959a969a00a002a008a00aa015a020a022a0"
|
| 1192 |
+
b"28a02aa045a051a054a056a059a080a082a088a08aa095a0a0a0a2a0a8a0aaa0"
|
| 1193 |
+
b"05a109a111a114a116a119a11aa146a149a151a155a158a15aa161a164a185a1"
|
| 1194 |
+
b"90a192a196a199a102a208a20aa210a219a222a228a22aa245a251a256a259a2"
|
| 1195 |
+
b"65a280a282a288a28aa295a2a0a2a2a2a8a2aaa219a425a441a444a450a454a4"
|
| 1196 |
+
b"55a458a45aa461a465a466a468a469a485a406a509a510a512a515a518a526a5"
|
| 1197 |
+
b"29a542a545a551a554a555a556a559a565a56aa581a584a585a586a589a592a5"
|
| 1198 |
+
b"95a598a505a611a616a61aa621a625a644a646a64aa652a655a656a658a660a6"
|
| 1199 |
+
b"62a686a690a695a696a699a6a1a6a4a6a6a600a802a808a80aa820a822a828a8"
|
| 1200 |
+
b"2aa851a854a856a859a880a882a888a88aa895a8a0a8a2a8a8a8aaa805a914a9"
|
| 1201 |
+
b"19a921a925a941a950a955a95aa961a966a969a990a996a900aa02aa08aa0aaa"
|
| 1202 |
+
b"20aa22aa28aa2aaa51aa54aa56aa80aa82aa88aa8aaa95aaa0aaa2aaa8aaaaaa"
|
| 1203 |
+
)
|
| 1204 |
+
|
| 1205 |
+
delta = np.float32(0.125)
|
| 1206 |
+
|
| 1207 |
+
@classmethod
|
| 1208 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 1209 |
+
n_blocks = blocks.shape[0]
|
| 1210 |
+
|
| 1211 |
+
d, rest = np.hsplit(blocks, [2])
|
| 1212 |
+
qs, qh = np.hsplit(rest, [QK_K // 8])
|
| 1213 |
+
|
| 1214 |
+
d = d.view(np.float16).astype(np.float32)
|
| 1215 |
+
qh = qh.view(np.uint16)
|
| 1216 |
+
|
| 1217 |
+
dl = d * (2 * ((qh >> 12) & 7) + 1)
|
| 1218 |
+
dl = dl.reshape((n_blocks, -1, 1, 1))
|
| 1219 |
+
delta = np.where((qh & np.uint16(0x8000)) == 0, cls.delta, -cls.delta)
|
| 1220 |
+
delta = delta.reshape((n_blocks, -1, 1, 1))
|
| 1221 |
+
|
| 1222 |
+
qh = qh.reshape((n_blocks, -1, 1)) >> np.array([0, 3, 6, 9], dtype=np.uint16).reshape((1, 1, 4))
|
| 1223 |
+
qs = qs.astype(np.uint16) | ((qh & 7) << 8).reshape((n_blocks, -1))
|
| 1224 |
+
|
| 1225 |
+
assert cls.grid is not None
|
| 1226 |
+
grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
|
| 1227 |
+
grid = grid.reshape((n_blocks, -1, 4, 8))
|
| 1228 |
+
|
| 1229 |
+
return (dl * (grid + delta)).reshape((n_blocks, -1))
|
| 1230 |
+
|
| 1231 |
+
|
| 1232 |
+
class IQ1_M(__Quant, qtype=GGMLQuantizationType.IQ1_M):
|
| 1233 |
+
grid_shape = IQ1_S.grid_shape
|
| 1234 |
+
grid_map = IQ1_S.grid_map
|
| 1235 |
+
grid_hex = IQ1_S.grid_hex
|
| 1236 |
+
|
| 1237 |
+
delta = IQ1_S.delta
|
| 1238 |
+
|
| 1239 |
+
# Okay *this* type is weird. It's the only one which stores the f16 scales in multiple parts.
|
| 1240 |
+
@classmethod
|
| 1241 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 1242 |
+
n_blocks = blocks.shape[0]
|
| 1243 |
+
|
| 1244 |
+
qs, rest = np.hsplit(blocks, [QK_K // 8])
|
| 1245 |
+
qh, scales = np.hsplit(rest, [QK_K // 16])
|
| 1246 |
+
|
| 1247 |
+
# The f16 scale is packed across multiple bytes
|
| 1248 |
+
scales = scales.view(np.uint16)
|
| 1249 |
+
d = (scales.reshape((n_blocks, 4)) & np.uint16(0xF000)) >> np.array([12, 8, 4, 0], dtype=np.uint16).reshape((1, 4))
|
| 1250 |
+
d = d[..., 0] | d[..., 1] | d[..., 2] | d[..., 3]
|
| 1251 |
+
d = d.view(np.float16).astype(np.float32).reshape((n_blocks, 1))
|
| 1252 |
+
|
| 1253 |
+
scales = scales.reshape(n_blocks, -1, 1) >> np.array([0, 3, 6, 9], dtype=np.uint16).reshape((1, 1, 4))
|
| 1254 |
+
scales = (scales & 0x07).reshape((n_blocks, -1))
|
| 1255 |
+
dl = d * (2 * scales + 1)
|
| 1256 |
+
dl = dl.reshape((n_blocks, -1, 2, 1, 1))
|
| 1257 |
+
|
| 1258 |
+
qh = qh.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
|
| 1259 |
+
qs = qs.astype(np.uint16) | ((qh & 0x07).astype(np.uint16) << 8).reshape((n_blocks, -1))
|
| 1260 |
+
|
| 1261 |
+
delta = np.where(qh & 0x08 == 0, cls.delta, -cls.delta)
|
| 1262 |
+
delta = delta.reshape((n_blocks, -1, 2, 2, 1))
|
| 1263 |
+
|
| 1264 |
+
assert cls.grid is not None
|
| 1265 |
+
grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
|
| 1266 |
+
grid = grid.reshape((n_blocks, -1, 2, 2, 8))
|
| 1267 |
+
|
| 1268 |
+
return (dl * (grid + delta)).reshape((n_blocks, -1))
|
| 1269 |
+
|
| 1270 |
+
|
| 1271 |
+
class IQ4_NL(__Quant, qtype=GGMLQuantizationType.IQ4_NL):
|
| 1272 |
+
kvalues = (-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113)
|
| 1273 |
+
|
| 1274 |
+
@classmethod
|
| 1275 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 1276 |
+
n_blocks = blocks.shape[0]
|
| 1277 |
+
|
| 1278 |
+
d, qs = np.hsplit(blocks, [2])
|
| 1279 |
+
|
| 1280 |
+
d = d.view(np.float16).astype(np.float32)
|
| 1281 |
+
|
| 1282 |
+
qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 1283 |
+
|
| 1284 |
+
qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1, 1))
|
| 1285 |
+
|
| 1286 |
+
kvalues = np.array(cls.kvalues, dtype=np.int8).reshape(1, 1, 16)
|
| 1287 |
+
qs = np.take_along_axis(kvalues, qs, axis=-1).astype(np.float32).reshape((n_blocks, -1))
|
| 1288 |
+
|
| 1289 |
+
return (d * qs)
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
class IQ4_XS(__Quant, qtype=GGMLQuantizationType.IQ4_XS):
|
| 1293 |
+
@classmethod
|
| 1294 |
+
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
|
| 1295 |
+
n_blocks = blocks.shape[0]
|
| 1296 |
+
|
| 1297 |
+
d, rest = np.hsplit(blocks, [2])
|
| 1298 |
+
scales_h, rest = np.hsplit(rest, [2])
|
| 1299 |
+
scales_l, qs = np.hsplit(rest, [QK_K // 64])
|
| 1300 |
+
|
| 1301 |
+
d = d.view(np.float16).astype(np.float32)
|
| 1302 |
+
scales_h = scales_h.view(np.uint16)
|
| 1303 |
+
|
| 1304 |
+
scales_l = scales_l.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
|
| 1305 |
+
scales_h = scales_h.reshape((n_blocks, 1, -1)) >> np.array([2 * i for i in range(QK_K // 32)], dtype=np.uint16).reshape((1, -1, 1))
|
| 1306 |
+
scales_l = scales_l.reshape((n_blocks, -1)) & np.uint8(0x0F)
|
| 1307 |
+
scales_h = scales_h.reshape((n_blocks, -1)).astype(np.uint8) & np.uint8(0x03)
|
| 1308 |
+
|
| 1309 |
+
scales = (scales_l | (scales_h << np.uint8(4))).astype(np.int8) - np.int8(32)
|
| 1310 |
+
dl = (d * scales.astype(np.float32)).reshape((n_blocks, -1, 1))
|
| 1311 |
+
|
| 1312 |
+
qs = qs.reshape((n_blocks, -1, 1, 16)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
|
| 1313 |
+
qs = qs.reshape((n_blocks, -1, 32, 1)) & np.uint8(0x0F)
|
| 1314 |
+
|
| 1315 |
+
kvalues = np.array(IQ4_NL.kvalues, dtype=np.int8).reshape((1, 1, 1, -1))
|
| 1316 |
+
qs = np.take_along_axis(kvalues, qs, axis=-1).astype(np.float32).reshape((n_blocks, -1, 32))
|
| 1317 |
+
|
| 1318 |
+
return (dl * qs).reshape((n_blocks, -1))
|
| 1319 |
+
|
| 1320 |
+
# =============================================================================
|
| 1321 |
+
# Helicoidal-Zeta Kernel (Bruno Becker) — clean (no Tk / no UI)
|
| 1322 |
+
# =============================================================================
|
| 1323 |
+
# This section is intentionally dependency-light and does NOT touch quantization
|
| 1324 |
+
# logic above. It provides the exact HelicoidalZetaCore math used in
|
| 1325 |
+
# ΩFFΣLLIα_Ωmegα_GPT.py (kernel only), with an optional prime-indexed variant
|
| 1326 |
+
# aligned with Artigo.txt.
|
| 1327 |
+
#
|
| 1328 |
+
# Sources:
|
| 1329 |
+
# - ΩFFΣLLIα_Ωmegα_GPT.py: HelicoidalZetaCore (Fn/coords/delta_m/zeta_signature/math_embedding)
|
| 1330 |
+
# - Artigo.txt: helicoidal mapping using p_n (n-th prime) and zeta(1/2 + i p_n)
|
| 1331 |
+
# =============================================================================
|
| 1332 |
+
|
| 1333 |
+
from dataclasses import dataclass, field
|
| 1334 |
+
|
| 1335 |
+
try:
|
| 1336 |
+
from mpmath import mp, zeta as _mp_zeta # type: ignore
|
| 1337 |
+
except Exception: # pragma: no cover
|
| 1338 |
+
mp = None
|
| 1339 |
+
_mp_zeta = None
|
| 1340 |
+
|
| 1341 |
+
|
| 1342 |
+
def _require_mpmath() -> None:
|
| 1343 |
+
if mp is None or _mp_zeta is None:
|
| 1344 |
+
raise ImportError(
|
| 1345 |
+
"mpmath is required for zeta_signature(). Install with: pip install mpmath"
|
| 1346 |
+
)
|
| 1347 |
+
|
| 1348 |
+
|
| 1349 |
+
@dataclass
|
| 1350 |
+
class _PrimeCache:
|
| 1351 |
+
"""
|
| 1352 |
+
Minimal prime cache to obtain p_n (n-th prime) with no external deps.
|
| 1353 |
+
|
| 1354 |
+
NOTE: n is 1-indexed: p_1 = 2, p_2 = 3, ...
|
| 1355 |
+
"""
|
| 1356 |
+
primes: list[int] = field(default_factory=lambda: [2, 3, 5, 7, 11, 13])
|
| 1357 |
+
_checked_upto: int = 13
|
| 1358 |
+
|
| 1359 |
+
@staticmethod
|
| 1360 |
+
def _is_prime(k: int, primes: list[int]) -> bool:
|
| 1361 |
+
if k < 2:
|
| 1362 |
+
return False
|
| 1363 |
+
for p in primes:
|
| 1364 |
+
if p * p > k:
|
| 1365 |
+
return True
|
| 1366 |
+
if k % p == 0:
|
| 1367 |
+
return False
|
| 1368 |
+
return True
|
| 1369 |
+
|
| 1370 |
+
def nth_prime(self, n: int) -> int:
|
| 1371 |
+
if n <= 0:
|
| 1372 |
+
raise ValueError("n must be >= 1 (1-indexed) for nth_prime")
|
| 1373 |
+
candidate = self._checked_upto
|
| 1374 |
+
if candidate % 2 == 0:
|
| 1375 |
+
candidate += 1
|
| 1376 |
+
while len(self.primes) < n:
|
| 1377 |
+
candidate += 2
|
| 1378 |
+
if self._is_prime(candidate, self.primes):
|
| 1379 |
+
self.primes.append(candidate)
|
| 1380 |
+
self._checked_upto = candidate
|
| 1381 |
+
return self.primes[n - 1]
|
| 1382 |
+
|
| 1383 |
+
|
| 1384 |
+
@dataclass
|
| 1385 |
+
class HelicoidalZetaCore:
|
| 1386 |
+
"""
|
| 1387 |
+
Kernel matemático helicoidal-zeta (sem UI).
|
| 1388 |
+
|
| 1389 |
+
Mantém a matemática exatamente como no kernel do arquivo ΩFFΣLLIα_Ωmegα_GPT.py:
|
| 1390 |
+
- phi = (1 + sqrt(5)) / 2
|
| 1391 |
+
- Fn(n) = sin(2π φ n)^2
|
| 1392 |
+
- coords(n) = [x, y, z] com r = Fn(n), θ = 2π φ n, (x,y) = r(cosθ, sinθ), z=n
|
| 1393 |
+
- delta_m(n,m) = 1.0 se n ≡ 0 (mod m) senão 0.42
|
| 1394 |
+
- zeta_signature(n) = (Re, Im) de ζ(1/2 + i n)
|
| 1395 |
+
- math_embedding(n) = concat([coords(n)*delta, [r, θ], zeta_signature(n)])
|
| 1396 |
+
(igual ao código original)
|
| 1397 |
+
"""
|
| 1398 |
+
zeta_dps: int = 25
|
| 1399 |
+
delta_modulus: int = 42
|
| 1400 |
+
delta_else: float = 0.42
|
| 1401 |
+
|
| 1402 |
+
# optional prime-indexing (Artigo.txt): use p_n instead of n
|
| 1403 |
+
use_primes: bool = False
|
| 1404 |
+
_prime_cache: _PrimeCache = field(default_factory=_PrimeCache)
|
| 1405 |
+
|
| 1406 |
+
def __post_init__(self) -> None:
|
| 1407 |
+
self.phi = (1.0 + float(np.sqrt(5.0))) / 2.0
|
| 1408 |
+
if mp is not None:
|
| 1409 |
+
mp.dps = int(self.zeta_dps)
|
| 1410 |
+
|
| 1411 |
+
def _n_to_eval(self, n: int) -> int:
|
| 1412 |
+
if not self.use_primes:
|
| 1413 |
+
return int(n)
|
| 1414 |
+
return int(self._prime_cache.nth_prime(int(n)))
|
| 1415 |
+
|
| 1416 |
+
def Fn(self, n: int) -> float:
|
| 1417 |
+
nn = self._n_to_eval(n)
|
| 1418 |
+
return float(np.sin(2.0 * np.pi * self.phi * nn) ** 2)
|
| 1419 |
+
|
| 1420 |
+
def coords(self, n: int) -> np.ndarray:
|
| 1421 |
+
nn = self._n_to_eval(n)
|
| 1422 |
+
r = float(np.sin(2.0 * np.pi * self.phi * nn) ** 2)
|
| 1423 |
+
t = 2.0 * np.pi * self.phi * nn
|
| 1424 |
+
x = r * float(np.cos(t))
|
| 1425 |
+
y = r * float(np.sin(t))
|
| 1426 |
+
z = float(nn)
|
| 1427 |
+
return np.array([x, y, z], dtype=np.float64)
|
| 1428 |
+
|
| 1429 |
+
def delta_m(self, n: int, m: int | None = None) -> float:
|
| 1430 |
+
nn = self._n_to_eval(n)
|
| 1431 |
+
mm = int(self.delta_modulus if m is None else m)
|
| 1432 |
+
return 1.0 if (nn % mm) == 0 else float(self.delta_else)
|
| 1433 |
+
|
| 1434 |
+
def zeta_signature(self, n: int) -> np.ndarray:
|
| 1435 |
+
_require_mpmath()
|
| 1436 |
+
nn = self._n_to_eval(n)
|
| 1437 |
+
if mp is not None:
|
| 1438 |
+
mp.dps = int(self.zeta_dps)
|
| 1439 |
+
s = mp.mpc(0.5, float(nn))
|
| 1440 |
+
val = _mp_zeta(s)
|
| 1441 |
+
return np.array([float(val.real), float(val.imag)], dtype=np.float64)
|
| 1442 |
+
raise RuntimeError("mpmath not available")
|
| 1443 |
+
|
| 1444 |
+
def math_embedding(self, n: int) -> np.ndarray:
|
| 1445 |
+
nn = self._n_to_eval(n)
|
| 1446 |
+
coords = self.coords(n)
|
| 1447 |
+
r = float(np.sin(2.0 * np.pi * self.phi * nn) ** 2)
|
| 1448 |
+
theta = 2.0 * np.pi * self.phi * nn
|
| 1449 |
+
delta = self.delta_m(n)
|
| 1450 |
+
zeta_vals = self.zeta_signature(n)
|
| 1451 |
+
# Vetor final (compatível com o kernel original):
|
| 1452 |
+
# [xδ, yδ, zδ, r, θ, Re(Zeta), Im(Zeta)]
|
| 1453 |
+
return np.concatenate([coords * delta, np.array([r, theta], dtype=np.float64), zeta_vals])
|
| 1454 |
+
|
| 1455 |
+
def transform(self, x: np.ndarray, n_val: int) -> np.ndarray:
|
| 1456 |
+
emb = self.math_embedding(n_val)
|
| 1457 |
+
return x * float(np.mean(emb))
|
| 1458 |
+
|
| 1459 |
+
|
| 1460 |
+
def helicoidal_zeta_scale(n_val: int, *, use_primes: bool = False, zeta_dps: int = 25) -> float:
|
| 1461 |
+
"""
|
| 1462 |
+
Retorna o escalar multiplicativo usado por transform(): mean(math_embedding).
|
| 1463 |
+
"""
|
| 1464 |
+
core = HelicoidalZetaCore(use_primes=use_primes, zeta_dps=zeta_dps)
|
| 1465 |
+
emb = core.math_embedding(int(n_val))
|
| 1466 |
+
return float(np.mean(emb))
|
| 1467 |
+
|
| 1468 |
+
|
| 1469 |
+
__all__ = [
|
| 1470 |
+
"HelicoidalZetaCore",
|
| 1471 |
+
"helicoidal_zeta_scale",
|
| 1472 |
+
]
|