interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / examples / python / ggml / utils.py

182 lines · 8965 bytes Raw Blame History
1"""
2 Common helpers for working with ggml + numpy
3"""
4from ggml import ffi, lib
5from typing import Union, Optional
6import numpy as np
7
8def init(mem_size: int, mem_buffer: ffi.CData = ffi.NULL, no_alloc: bool = False) -> ffi.CData:
9 """
10 Initialize a ggml context, which will be freed automatically when the pointer is garbage collected.
11 """
12 params = ffi.new('struct ggml_init_params*')
13 params.mem_size = mem_size
14 params.mem_buffer = mem_buffer
15 params.no_alloc = no_alloc
16 return ffi.gc(lib.ggml_init(params[0]), lib.ggml_free)
17
18TensorLike = Union[ffi.CData, np.ndarray]
19
20def copy(from_tensor: TensorLike, to_tensor: TensorLike, allow_requantize: bool = True):
21 """
22 Copy the contents of one tensor to another, doing any necessary (de/re)quantization transparently.
23 Works across numpy & ggml tensors, but they must have the same shape (and be contiguous).
24
25 Parameters
26 ----------
27 from_tensor : TensorLike
28 The tensor to copy from (a numpy array or possibly-quantized ggml tensor)
29 to_tensor : TensorLike
30 The tensor to copy to (a numpy array or possibly-quantized ggml tensor)
31 allow_requantize : bool
32 If False, will throw an error if requantization is required (i.e. both from_tensor
33 and to_tensor are quantized with different quantization types)
34 """
35 if id(from_tensor) == id(to_tensor):
36 return
37
38 __expect_same_layout("source", from_tensor, "destination", to_tensor)
39 __check_shape_consistent_with_type(from_tensor)
40 __check_shape_consistent_with_type(to_tensor)
41
42 from_type = __get_type(from_tensor)
43 to_type = __get_type(to_tensor)
44
45 if from_type == to_type:
46 ffi.memmove(__get_data(to_tensor), __get_data(from_tensor), __get_nbytes(from_tensor))
47 else:
48 assert allow_requantize or not lib.ggml_is_quantized(from_type) or not lib.ggml_is_quantized(to_type), \
49 f"Requantizing from {__type_name(from_type)} to {__type_name(to_type)} is disabled. Force with allow_requantize=True"
50
51 __set_floats(to_tensor, __get_floats(from_tensor))
52
53def numpy(tensor: ffi.CData, allow_copy: Union[bool, np.ndarray] = False, allow_requantize=False) -> np.ndarray:
54 """
55 Convert a ggml tensor to a numpy array.
56 If the tensor isn't quantized, the returned numpy array will be a view over its data.
57
58 If it is quantized (and allow_copy is True), the copy will involve dequantization and the returned array will
59 be a copy of the original tensor (any changes to the numpy array won't then be reflected back to the tensor).
60
61 Parameters
62 ----------
63 tensor : ffi.CData
64 The tensor to convert to a numpy array
65 allow_copy : bool or np.ndarray
66 If False, will throw an error if the tensor is quantized (since dequantization requires extra memory).
67 If True, will dequantize the tensor and return a copy of the data in a new float32 numpy array.
68 If an np.ndarray, will copy the data into the given array (which must be the same shape as the tensor) when dequantization is needed
69 allow_requantize : bool
70 If allow_copy is a tensor with a different quantization type than the source tensor, will throw an error unless allow_requantize is True.
71 """
72 shape = __get_shape(tensor)
73
74 if lib.ggml_is_quantized(tensor.type):
75 if allow_copy == False:
76 raise ValueError(f"{__describe(tensor)} is quantized, conversion to numpy requires a copy (pass allow_copy=True; changes to the numpy array won't affect the original).")
77 elif isinstance(allow_copy, np.ndarray):
78 __expect_same_layout("source tensor", tensor, "dequantization output tensor", allow_copy)
79 destination = allow_copy
80 else:
81 destination = np.empty(shape, dtype=np.float32)
82
83 copy(tensor, destination, allow_requantize=allow_requantize)
84 return destination
85 else:
86 dtype = __type_to_dtype(tensor.type)
87 if not dtype:
88 raise NotImplementedError(f'Cannot convert {__describe(tensor)} to numpy')
89
90 assert __is_contiguous(tensor), f"Cannot convert {__describe(tensor)} to numpy (support contiguous tensors only)"
91 nbytes = lib.ggml_nelements(tensor) * lib.ggml_type_size(tensor.type)
92 array = np.frombuffer(ffi.buffer(lib.ggml_get_data(tensor), nbytes), dtype=dtype)
93 array.shape = shape
94 return array
95
96def __type_name(type: int) -> str:
97 name = lib.ggml_type_name(type)
98 return ffi.string(name).decode('utf-8') if name else None
99
100__k_quant_types = set([
101 lib.GGML_TYPE_Q2_K,
102 lib.GGML_TYPE_Q3_K,
103 lib.GGML_TYPE_Q4_K,
104 lib.GGML_TYPE_Q5_K,
105 lib.GGML_TYPE_Q6_K,
106 lib.GGML_TYPE_Q8_K,
107])
108
109__type_to_dtype_dict = {
110 lib.GGML_TYPE_I8: np.int8,
111 lib.GGML_TYPE_I16: np.int16,
112 lib.GGML_TYPE_I32: np.int32,
113 lib.GGML_TYPE_F16: np.float16,
114 lib.GGML_TYPE_F32: np.float32,
115}
116
117def __type_to_dtype(type: int) -> Optional[np.dtype]: return __type_to_dtype_dict.get(type)
118def __dtype_to_type(dtype: np.dtype):
119 if dtype == np.float32: return lib.GGML_TYPE_F32
120 elif dtype == np.float16: return lib.GGML_TYPE_F16
121 elif dtype == np.int32: return lib.GGML_TYPE_I32
122 elif dtype == np.int16: return lib.GGML_TYPE_I16
123 elif dtype == np.int8: return lib.GGML_TYPE_I8
124 else: raise ValueError(f"Unsupported dtype: {dtype}")
125
126def __describe(tensor: ffi.CType): return f'Tensor[{__type_name(__get_type(tensor))}, {__get_shape(tensor)}]'
127def __get_type(tensor: TensorLike): return __dtype_to_type(tensor.dtype) if isinstance(tensor, np.ndarray) else tensor.type
128def __get_shape(x: TensorLike): return x.shape if isinstance(x, np.ndarray) else tuple([x.ne[i] for i in range(x.n_dims)])
129def __get_strides(x: TensorLike): return x.strides if isinstance(x, np.ndarray) else tuple([x.nb[i] for i in range(x.n_dims)])
130def __get_data(x: TensorLike) -> ffi.CData: return ffi.from_buffer(x) if isinstance(x, np.ndarray) else lib.ggml_get_data(x)
131def __get_nbytes(tensor: TensorLike): return tensor.nbytes if isinstance(tensor, np.ndarray) else lib.ggml_nbytes(tensor)
132def __get_nelements(tensor: TensorLike): return tensor.size if isinstance(tensor, np.ndarray) else lib.ggml_nelements(tensor)
133def __is_contiguous(tensor: TensorLike): return tensor.flags['C_CONTIGUOUS'] if isinstance(tensor, np.ndarray) else lib.ggml_is_contiguous(tensor)
134
135def __get_floats(tensor: TensorLike) -> ffi.CData:
136 data, type = __get_data(tensor), __get_type(tensor)
137 if type == lib.GGML_TYPE_F32:
138 return ffi.cast('float*', data)
139 else:
140 nelements = __get_nelements(tensor)
141 floats = ffi.new('float[]', nelements)
142 if type == lib.GGML_TYPE_F16:
143 lib.ggml_fp16_to_fp32_row(ffi.cast('uint16_t*', data), floats, nelements)
144 elif lib.ggml_is_quantized(type):
145 qtype = lib.ggml_internal_get_type_traits(type)
146 assert qtype.to_float, f"Type {__type_name(type)} is not supported by ggml"
147 qtype.to_float(data, floats, nelements)
148 else:
149 raise NotImplementedError(f'Cannot read floats from {__describe(tensor)}')
150 return floats
151
152def __set_floats(tensor: TensorLike, f32_data: ffi.CData) -> None:
153 data, type, nbytes = __get_data(tensor), __get_type(tensor), __get_nbytes(tensor)
154 if type == lib.GGML_TYPE_F32:
155 ffi.memmove(data, f32_data, nbytes)
156 else:
157 nelements = __get_nelements(tensor)
158 if type == lib.GGML_TYPE_F16:
159 lib.ggml_fp32_to_fp16_row(f32_data, ffi.cast('uint16_t*', data), nelements)
160 elif lib.ggml_is_quantized(type):
161 qtype = lib.ggml_internal_get_type_traits(type)
162 assert qtype.from_float, f"Type {__type_name(type)} is not supported by ggml"
163 qtype.from_float(f32_data, data, nelements)
164 else:
165 raise NotImplementedError(f'Cannot write floats to {__describe(tensor)}')
166
167def __expect_same_layout(name1: str, tensor1: TensorLike, name2: str, tensor2: TensorLike):
168 shape1, shape2 = __get_shape(tensor1), __get_shape(tensor2)
169 assert shape1 == shape2, f"Shape mismatch: {name1} has {shape1} but {name2} has {shape2}"
170 assert __is_contiguous(tensor1) and __is_contiguous(tensor2), f"Only contiguous tensors are supported (got {name1} with strides {__get_strides(tensor1)} and {name2} with strides {__get_strides(tensor2)})"
171
172def __check_shape_consistent_with_type(tensor: TensorLike):
173 type = __get_type(tensor)
174 if not lib.ggml_is_quantized(type):
175 return
176 shape = __get_shape(tensor)
177
178 block_size = lib.ggml_blck_size(type)
179 assert not (block_size == 0 and type in __k_quant_types), f"Can't quantize, native library was not compiled with USE_K_QUANTS!"
180 assert block_size > 0, f"Invalid block size {block_size} for type {__type_name(type)}"
181 for i, d in enumerate(shape):
182 assert d % block_size == 0, f"Dimension {i} of {__describe(tensor)} is not divisible by {block_size}, required for quantization."