ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / examples / python / example_test_all_quants.py
| 1 | from ggml import ffi, lib |
| 2 | from ggml.utils import init, numpy, copy |
| 3 | import numpy as np |
| 4 | from math import pi, cos, sin, ceil |
| 5 | |
| 6 | import matplotlib.pyplot as plt |
| 7 | |
| 8 | ctx = init(mem_size=100*1024*1024) # Will be auto-GC'd |
| 9 | n = 256 |
| 10 | |
| 11 | orig = 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) |
| 18 | orig_tensor = lib.ggml_new_tensor_2d(ctx, lib.GGML_TYPE_F32, n, n) |
| 19 | copy(orig, orig_tensor) |
| 20 | |
| 21 | quants = [ |
| 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 | |
| 28 | def get_name(type): |
| 29 | name = lib.ggml_type_name(type) |
| 30 | return ffi.string(name).decode('utf-8') if name else '?' |
| 31 | |
| 32 | quants.sort(key=get_name) |
| 33 | quants.insert(0, None) |
| 34 | print(quants) |
| 35 | |
| 36 | ncols=4 |
| 37 | nrows = ceil(len(quants) / ncols) |
| 38 | |
| 39 | plt.figure(figsize=(ncols * 5, nrows * 5), layout='tight') |
| 40 | |
| 41 | for 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 | |
| 68 | plt.show() |