"""Read safetensors BF16 directly; never instantiate a model or use pickle.""" import json import math import mmap import re import struct import numpy as np DTYPES = {'BF16': (' 100_000_000: raise ValueError('Oversized safetensors header') header = json.loads(f.read(size)) for name, meta in header.items(): if name == '__metadata__': continue if name in tensors: raise ValueError(f'Duplicate tensor name: {name}') tensors[name] = Tensor(file, 8 + size, name, meta) if not tensors: raise ValueError('No safetensors found') return tensors def metrics(x, y): """x is member; y is representative. Float64 accumulation.""" x, y = x.astype(np.float64), y.astype(np.float64) xx, yy, xy = float(x @ x), float(y @ y), float(x @ y) delta = float((x - y) @ (x - y)) return finish(xx, yy, xy, delta, float(x.sum()), float(y.sum()), x.size) def finish(xx, yy, xy, delta, sx, sy, n): tiny = 1e-30 vx, vy = max(0., xx - sx * sx / n), max(0., yy - sy * sy / n) return {'cosine': xy / np.sqrt(xx * yy) if xx * yy > tiny else None, 'pearson': (xy - sx * sy / n) / np.sqrt(vx * vy) if vx * vy > tiny else None, 'error_member_to_rep': np.sqrt(delta / max(xx, tiny)), 'error_rep_to_member': np.sqrt(delta / max(yy, tiny)), 'symmetric_error': np.sqrt(2 * delta / max(xx + yy, tiny)), 'scaled_error': np.sqrt(max(0., xx - xy * xy / max(yy, tiny)) / max(xx, tiny)), 'scale': xy / max(yy, tiny)}