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 / example_test_all_quants.py

68 lines · 1946 bytes Raw Blame History
1from ggml import ffi, lib
2from ggml.utils import init, numpy, copy
3import numpy as np
4from math import pi, cos, sin, ceil
5
6import matplotlib.pyplot as plt
7
8ctx = init(mem_size=100*1024*1024) # Will be auto-GC'd
9n = 256
10
11orig = np.array([
12 [
13 cos(j * 2 * pi / n) * (sin(i * 2 * pi / n))
14 for j in range(n)
15 ]
16 for i in range(n)
17], np.float32)
18orig_tensor = lib.ggml_new_tensor_2d(ctx, lib.GGML_TYPE_F32, n, n)
19copy(orig, orig_tensor)
20
21quants = [
22 type for type in range(lib.GGML_TYPE_COUNT)
23 if lib.ggml_is_quantized(type) and
24 type not in [lib.GGML_TYPE_Q8_1, lib.GGML_TYPE_Q8_K] # Apparently not supported
25]
26# quants = [lib.GGML_TYPE_Q2_K] # Test a single one
27
28def get_name(type):
29 name = lib.ggml_type_name(type)
30 return ffi.string(name).decode('utf-8') if name else '?'
31
32quants.sort(key=get_name)
33quants.insert(0, None)
34print(quants)
35
36ncols=4
37nrows = ceil(len(quants) / ncols)
38
39plt.figure(figsize=(ncols * 5, nrows * 5), layout='tight')
40
41for i, type in enumerate(quants):
42 plt.subplot(nrows, ncols, i + 1)
43 try:
44 if type == None:
45 plt.title('Original')
46 plt.imshow(orig)
47 else:
48 quantized_tensor = lib.ggml_new_tensor_2d(ctx, type, n, n)
49 copy(orig_tensor, quantized_tensor)
50 quantized = numpy(quantized_tensor, allow_copy=True)
51 d = quantized - orig
52 results = {
53 "l2": np.linalg.norm(d, 2),
54 "linf": np.linalg.norm(d, np.inf),
55 "compression":
56 round(lib.ggml_nbytes(orig_tensor) /
57 lib.ggml_nbytes(quantized_tensor), 1)
58 }
59 name = get_name(type)
60 print(f'{name}: {results}')
61
62 plt.title(f'{name} ({results["compression"]}x smaller)')
63 plt.imshow(quantized, interpolation='nearest')
64
65 except Exception as e:
66 print(f'Error: {e}')
67
68plt.show()