turnstone-lambda-671 / fp32_common.py
eousphoros's picture
Add files using upload-large-folder tool
9fae48b verified
Raw History Blame Contribute Delete
24.9 kB
"""Shared code of the FP32 master-weights tools (masters_to_bf16.py, to_fp8.py, merge_lora.py and the checks).
Needs python >= 3.9 and torch (a CPU build is enough). Nothing else: the weight files are read and written here,
so the bytes of an output do not depend on the version of any serialization library. Tested with python 3.14.4 and
torch 2.14.0 on x86-64 Linux.
WEIGHT FILE LAYOUT (what write_shard writes: the usual layout of .safetensors files, readable by any loader of them)
8 bytes little-endian unsigned length N of the header
N bytes the header: compact JSON (separators "," and ":"), first key "__metadata__" = {"format":"pt"}, then one
key per tensor {"dtype","shape","data_offsets":[begin,end]}, padded with spaces to a multiple of 8 bytes
the rest the tensors' little-endian bytes, back to back, in header order
Header order: by dtype (F32, then BF16, then F8_E4M3), then by name (byte order).
ROUNDING RULES (every tool uses these and nothing else)
FP32 -> BF16 round to nearest, ties to even: with u the 32 bits of the FP32 value as an unsigned integer,
bf16 = (u + 0x7FFF + ((u >> 16) & 1)) >> 16. [bf16_bits_exact]
FP32 -> FP8 e4m3 (after the caller's division and saturation at +-448) round to nearest, ties to the even
code: for a = |y|, e = exponent of a (a = m * 2^e, m in [0.5, 1)), e taken as -5 for
a < 2^-6; n = round_half_even(a * 2^(4 - e)); code = 8 * (e + 5) + n; sign bit 0x80.
[e4m3_bytes_exact]
The tools use the torch casts (x.to(torch.bfloat16), y.to(torch.float8_e4m3fn)), which implement the same rules,
and check that at start-up on a set of tie and boundary values (self_test); --exact-rounding uses the integer
formulas above for every element instead.
"""
import ctypes
import hashlib
import json
import os
import re
import shutil
import struct
import sys
import time
from concurrent.futures import ThreadPoolExecutor
import torch
NL = chr(10)
INDEX = "model.safetensors.index.json"
MANIFEST = "fp32-release.json"
SUMS = "SHA256SUMS"
MTP_FILE = "mtp.safetensors"
MTP_NOTE = "mtp.json"
MANIFEST_FORMAT = "fp32-masters-v1"
# The linear-attention decay parameters: FP32 in the BF16 and FP8 folders too, as trained.
A_LOG = re.compile("model[.]language_model[.]layers[.][0-9]+[.]linear_attn[.]A_log")
BLOCK = 128
FP8_MAX = 448.0
TORCH_DTYPE = {"F32": torch.float32, "BF16": torch.bfloat16, "F8_E4M3": torch.uint8} # FP8 payloads are raw bytes
ITEM = {"F32": 4, "BF16": 2, "F8_E4M3": 1}
HEADER_RANK = {"F32": 0, "BF16": 1, "F8_E4M3": 2}
FP8_NATIVE = getattr(torch, "float8_e4m3fn", None)
def fail(message):
raise SystemExit("refusing: " + message)
def say(*parts):
print(*parts, flush=True)
# ------------------------------------------------------------------------------------------------ weight files
def _buffer(tensor):
"""The tensor's memory as a ctypes byte array (the tensor must be contiguous and stay alive)."""
return (ctypes.c_char * (tensor.numel() * tensor.element_size())).from_address(tensor.data_ptr())
def count_of(shape):
n = 1
for d in shape:
n *= d
return n
class TensorFile:
"""One weight file: its header, and reads of single tensors."""
def __init__(self, path):
self.path = str(path)
size = os.path.getsize(self.path)
with open(self.path, "rb") as f:
raw = f.read(8)
if len(raw) != 8:
fail("%s is too short to be a weight file" % self.path)
n = struct.unpack("<Q", raw)[0]
if n > min(size, 1 << 28):
fail("%s: header length %d is not plausible" % (self.path, n))
header = json.loads(f.read(n).decode("utf-8"))
self.metadata = header.pop("__metadata__", None)
self.entries = header
self.base = 8 + n
end = 0
for name, entry in header.items():
if entry["dtype"] not in ITEM:
fail("%s: tensor %s has dtype %s; only F32, BF16 and F8_E4M3 are handled" % (self.path, name, entry["dtype"]))
a, b = entry["data_offsets"]
if b - a != count_of(entry["shape"]) * ITEM[entry["dtype"]]:
fail("%s: tensor %s has a size that does not fit its shape" % (self.path, name))
end = max(end, b)
if size != self.base + end:
fail("%s: file size %d differs from the header's %d" % (self.path, size, self.base + end))
def names(self):
return list(self.entries)
def dtype(self, name):
return self.entries[name]["dtype"]
def shape(self, name):
return list(self.entries[name]["shape"])
def read(self, name, first=None):
"""The tensor (F32 as float32, BF16 as bfloat16, F8_E4M3 as uint8 codes). FIRST: only the first FIRST
elements, flat."""
entry = self.entries[name]
count = count_of(entry["shape"])
if first is not None:
count = min(count, first)
tensor = torch.empty([count] if first is not None else entry["shape"], dtype=TORCH_DTYPE[entry["dtype"]])
if count:
view = memoryview(_buffer(tensor)).cast("B")
with open(self.path, "rb", buffering=0) as f:
f.seek(self.base + entry["data_offsets"][0])
got = 0
while got < len(view):
k = f.readinto(view[got:got + (1 << 28)])
if not k:
fail("%s: short read in tensor %s" % (self.path, name))
got += k
return tensor
class Folder:
"""A model folder: model.safetensors.index.json and the weight files it names."""
def __init__(self, path):
self.path = str(path)
index_path = os.path.join(self.path, INDEX)
if not os.path.isfile(index_path):
fail("%s has no %s" % (self.path, INDEX))
with open(index_path) as f:
index = json.load(f)
self.weight_map = index["weight_map"] # in the file's order
self.total_size = (index.get("metadata") or {}).get("total_size")
self.files = {}
seen = {}
for shard in sorted(set(self.weight_map.values())):
self.files[shard] = TensorFile(os.path.join(self.path, shard))
for name in self.files[shard].names():
if name in seen or self.weight_map.get(name) != shard:
fail("%s: tensor %s is in %s but the index says %s" % (self.path, name, shard, self.weight_map.get(name)))
seen[name] = shard
if set(seen) != set(self.weight_map):
fail("%s: the index and the weight files name different tensors" % self.path)
def names(self):
return list(self.weight_map)
def shards(self):
return sorted(self.files)
def names_in(self, shard):
return [n for n, s in self.weight_map.items() if s == shard]
def dtype(self, name):
return self.files[self.weight_map[name]].dtype(name)
def shape(self, name):
return self.files[self.weight_map[name]].shape(name)
def read(self, name, first=None):
return self.files[self.weight_map[name]].read(name, first)
def write_shard(path, tensors):
"""Write {name: (dtype name, tensor)} as one weight file in the layout of the module text.
Returns (sha256 of the file, its size in bytes)."""
names = sorted(tensors, key=lambda n: (HEADER_RANK[tensors[n][0]], n))
header = {"__metadata__": {"format": "pt"}}
offset = 0
for name in names:
kind, tensor = tensors[name]
if tensor.dtype != TORCH_DTYPE[kind]:
raise ValueError("%s: a %s tensor was handed over as %s" % (name, kind, tensor.dtype))
size = tensor.numel() * ITEM[kind]
header[name] = {"dtype": kind, "shape": list(tensor.shape), "data_offsets": [offset, offset + size]}
offset += size
blob = json.dumps(header, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
blob += b" " * (-len(blob) % 8)
digest = hashlib.sha256()
head = struct.pack("<Q", len(blob)) + blob
temporary = str(path) + ".tmp"
with open(temporary, "wb") as f:
f.write(head)
digest.update(head)
for name in names:
tensor = tensors[name][1].contiguous()
if tensor.numel():
view = memoryview(_buffer(tensor)).cast("B")
for a in range(0, len(view), 1 << 26):
f.write(view[a:a + (1 << 26)])
digest.update(view[a:a + (1 << 26)])
os.replace(temporary, str(path))
return digest.hexdigest(), len(head) + offset
def tensor_bytes(kind, tensor):
return tensor.numel() * ITEM[kind]
# ------------------------------------------------------------------------------------------------ checksums
def sha256_file(path):
digest = hashlib.sha256()
with open(path, "rb", buffering=0) as f:
buffer = bytearray(1 << 24)
view = memoryview(buffer)
while True:
k = f.readinto(buffer)
if not k:
break
digest.update(view[:k])
return digest.hexdigest()
def sha256_bytes(data):
return hashlib.sha256(data).hexdigest()
def tensor_sha256(tensor):
tensor = tensor.contiguous()
digest = hashlib.sha256()
if tensor.numel():
digest.update(memoryview(_buffer(tensor)).cast("B"))
return digest.hexdigest()
def folder_files(folder):
return sorted(n for n in os.listdir(folder) if os.path.isfile(os.path.join(folder, n)) and n != SUMS)
def write_sums(folder, known=None, workers=8):
"""Write FOLDER/SHA256SUMS over every file of the folder (not its sub-folders, not SHA256SUMS itself), in the
format of the sha256sum tool, names sorted. KNOWN: digests already computed while writing."""
known = dict(known or {})
names = folder_files(folder)
todo = [n for n in names if n not in known]
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
for name, digest in zip(todo, pool.map(lambda n: sha256_file(os.path.join(folder, n)), todo)):
known[name] = digest
text = "".join("%s %s%s" % (known[n], n, NL) for n in names)
with open(os.path.join(folder, SUMS), "w") as f:
f.write(text)
return {n: known[n] for n in names}
def read_sums(path):
out = {}
with open(path) as f:
for line in f.read().split(NL):
if not line.strip():
continue
digest, _, name = line.partition(" ")
name = name.strip()
if name.startswith("*"):
name = name[1:]
if len(digest) != 64 or not name or name in out:
fail("%s: not a SHA256SUMS line: %r" % (path, line))
out[name] = digest.lower()
if not out:
fail("%s lists no files" % path)
return out
def check_sums(folder, published, workers=8):
"""Compare every file of FOLDER with the PUBLISHED SHA256SUMS. True when the two name the same files with the
same digests; prints what differs otherwise."""
expected = read_sums(published)
own = os.path.join(folder, SUMS)
actual = read_sums(own) if os.path.isfile(own) else {}
names = folder_files(folder)
if set(actual) != set(names):
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
actual = dict(zip(names, pool.map(lambda n: sha256_file(os.path.join(folder, n)), names)))
missing = sorted(set(expected) - set(actual))
extra = sorted(set(actual) - set(expected))
differ = sorted(n for n in expected if n in actual and expected[n] != actual[n])
same = len(expected) - len(missing) - len(differ)
say("CHECK against %s: %d files identical, %d differ, %d listed but absent, %d present but not listed" % (
published, same, len(differ), len(missing), len(extra)))
for label, group in (("differs", differ), ("absent", missing), ("not listed", extra)):
for name in group[:10]:
say(" %s: %s" % (label, name))
ok = not (missing or extra or differ)
say("CHECK", "OK" if ok else "FAILED")
return ok
# ------------------------------------------------------------------------------------------------ rounding
def bf16_bits_exact(x):
"""FP32 -> the BF16 bit patterns (int16, same shape), round to nearest, ties to even, by integer arithmetic."""
u = x.contiguous().reshape(-1).view(torch.int32).to(torch.int64) & 0xFFFFFFFF
r = (u + 0x7FFF + ((u >> 16) & 1)) >> 16
r = torch.where(r >= 0x8000, r - 0x10000, r)
return r.to(torch.int16).reshape(x.shape)
def to_bf16(x, exact=False):
"""FP32 -> BF16, round to nearest, ties to even."""
if x.dtype != torch.float32:
raise ValueError("to_bf16 takes FP32")
if exact:
return bf16_bits_exact(x).reshape(-1).view(torch.bfloat16).reshape(x.shape)
return x.to(torch.bfloat16)
def bits16(x):
return x.contiguous().reshape(-1).view(torch.int16)
def bits32(x):
return x.contiguous().reshape(-1).view(torch.int32)
def e4m3_bytes_exact(y):
"""FP32 values with |y| <= 448 -> e4m3 codes (uint8, same shape), round to nearest, ties to the even code."""
a = y.abs()
_, e = torch.frexp(a)
e = torch.where(a < 2.0 ** -6, torch.full_like(e, -5), e)
n = torch.round(torch.ldexp(a, 4 - e)).to(torch.int32)
code = 8 * (e + 5) + n
code = code + torch.signbit(y).to(torch.int32) * 128
return code.to(torch.uint8)
def to_e4m3(y, exact=False):
if y.dtype != torch.float32:
raise ValueError("to_e4m3 takes FP32")
if exact:
return e4m3_bytes_exact(y)
return y.to(FP8_NATIVE).view(torch.uint8)
def e4m3_values():
"""The value of each of the 256 e4m3 codes as FP32 (code 127 and 255, the NaNs, as NaN)."""
values = []
for code in range(256):
e, m = (code >> 3) & 15, code & 7
v = m * 2.0 ** -9 if e == 0 else (1 + m / 8) * 2.0 ** (e - 7)
if code & 127 == 127:
v = float("nan")
values.append(-v if code & 128 else v)
return torch.tensor(values, dtype=torch.float32)
def e4m3_decode(codes):
"""uint8 codes -> FP32 values."""
return e4m3_values()[codes.reshape(-1).to(torch.int64)].reshape(codes.shape)
def self_test(fp8=False):
"""Check this torch build's casts against the integer rules on tie and boundary values. Refuses on a
difference (use --exact-rounding then)."""
generator = torch.Generator().manual_seed(20261125)
bits = torch.randint(-2 ** 31, 2 ** 31 - 1, (1 << 18,), generator=generator, dtype=torch.int64)
low = torch.tensor([0x7FFF, 0x8000, 0x8001, 0x0000, 0xFFFF], dtype=torch.int64)
ties = (bits[: 1 << 16, None] & ~0xFFFF) | low[None, :]
every = torch.cat([bits, ties.reshape(-1)])
every = every[((every >> 23) & 0xFF) != 0xFF] # finite values only
every = torch.where(every >= 2 ** 31, every - 2 ** 32, every).to(torch.int32)
x = every.view(torch.float32)
if not torch.equal(bits16(x.to(torch.bfloat16)), bf16_bits_exact(x)):
fail("this torch build's FP32 -> BF16 cast is not round-to-nearest-even on the test values; "
"run with --exact-rounding")
if not fp8:
return
if FP8_NATIVE is None:
fail("this torch build has no float8_e4m3fn; run with --exact-rounding")
values = e4m3_values()[:127].double()
mids = (values[:-1] + values[1:]) / 2
points = torch.cat([values, mids]).float()
points = torch.cat([points, torch.nextafter(points, torch.full_like(points, 1000.0)),
torch.nextafter(points, torch.full_like(points, -1000.0))])
points = points[points.abs() <= FP8_MAX]
spread = (torch.rand(1 << 18, generator=generator) * 2 - 1) * FP8_MAX
small = torch.exp(torch.rand(1 << 16, generator=generator) * -30.0)
y = torch.cat([points, -points, spread, small, -small, torch.tensor([0.0, -0.0, FP8_MAX, -FP8_MAX])])
if not torch.equal(y.to(FP8_NATIVE).view(torch.uint8), e4m3_bytes_exact(y)):
fail("this torch build's FP32 -> FP8 e4m3 cast is not round-to-nearest-even on the test values; "
"run with --exact-rounding")
back = e4m3_decode(e4m3_bytes_exact(y))
if not bool(((back - y).abs() <= (y.abs() / 16).clamp_min(2.0 ** -10)).all()):
raise RuntimeError("the e4m3 rule and its value table disagree")
def fp8_quantize(x, scale_rule="stored", exact=False):
"""FP8 e4m3 quantization of a matrix in 128 x 128 blocks.
x FP32 [R, C]
scale per block, FP32: max(|x|) / 448 (FP32 division); stored as weight_scale_inv = bf16(scale)
codes e4m3(saturate(x / divisor, -448, 448)), with an FP32 division, where
divisor = fp32(bf16(scale)) for scale_rule "stored" (the value a loader multiplies by)
divisor = scale for scale_rule "unrounded" (how our first FP8 conversion was made)
and divisor = 1 for an all-zero block.
Returns (codes uint8 [R, C], weight_scale_inv bfloat16 [ceil(R/128), ceil(C/128)])."""
if x.dtype != torch.float32 or x.dim() != 2:
raise ValueError("fp8_quantize takes an FP32 matrix")
if scale_rule not in ("stored", "unrounded"):
raise ValueError("unknown scale rule")
rows, cols = x.shape
rb, cb = -(-rows // BLOCK), -(-cols // BLOCK)
if rows % BLOCK or cols % BLOCK:
padded = torch.zeros(rb * BLOCK, cb * BLOCK, dtype=torch.float32)
padded[:rows, :cols] = x
x = padded
blocks = x.reshape(rb, BLOCK, cb, BLOCK).permute(0, 2, 1, 3)
scale = blocks.abs().amax(dim=(-1, -2), keepdim=True) / FP8_MAX
stored = to_bf16(scale, exact)
divisor = stored.float() if scale_rule == "stored" else scale
if bool(((divisor == 0) & (scale > 0)).any()):
fail("a block's scale rounds to zero in BF16")
divisor = torch.where(divisor > 0, divisor, torch.ones_like(divisor))
y = (blocks / divisor).clamp_(-FP8_MAX, FP8_MAX)
codes = to_e4m3(y, exact)
codes = codes.permute(0, 2, 1, 3).reshape(rb * BLOCK, cb * BLOCK)[:rows, :cols].contiguous()
return codes, stored[..., 0, 0].contiguous()
def fp8_dequantize(codes, scale_inv):
"""The FP32 values a loader computes: value(code) * fp32(weight_scale_inv) per block."""
rows, cols = codes.shape
rb, cb = scale_inv.shape
values = e4m3_decode(codes)
scale = scale_inv.float().repeat_interleave(BLOCK, dim=0)[:rows].repeat_interleave(BLOCK, dim=1)[:, :cols]
return values * scale
def finite(name, x):
if not bool(torch.isfinite(x).all()):
fail("%s holds a NaN or an infinity" % name)
# ------------------------------------------------------------------------------------------------ release folders
def load_manifest(masters):
path = os.path.join(masters, MANIFEST)
if not os.path.isfile(path):
fail("%s has no %s; it is not an FP32 master-weights folder" % (masters, MANIFEST))
with open(path) as f:
manifest = json.load(f)
if manifest.get("format") != MANIFEST_FORMAT:
fail("%s: format %r, expected %s" % (path, manifest.get("format"), MANIFEST_FORMAT))
return manifest
def open_masters(path):
"""(Folder, manifest) of an FP32 master-weights folder; refuses anything that is not all FP32 or lists the
draft head."""
manifest = load_manifest(path)
folder = Folder(path)
wrong = [n for n in folder.names() if folder.dtype(n) != "F32"]
if wrong:
fail("%s: %d tensors are not FP32 (first: %s)" % (path, len(wrong), wrong[0]))
listed = [n for n in folder.names() if n.startswith("mtp.")]
if listed:
fail("%s: the index lists draft-head tensors (%s); they belong in %s" % (path, listed[0], MTP_FILE))
return folder, manifest
def open_mtp(masters, manifest, mtp, no_mtp):
"""The draft (MTP) head's file, or None for --no-mtp. Default: MASTERS/mtp.safetensors."""
if no_mtp:
if mtp:
fail("--mtp and --no-mtp exclude each other")
return None
path = mtp or os.path.join(masters, MTP_FILE)
if not os.path.isfile(path):
fail("no draft head at %s; name one with --mtp FILE, or pass --no-mtp to write a folder without it" % path)
head = TensorFile(path)
expected = manifest["mtp"]["bf16_shards"]
if set(head.names()) != set(expected):
fail("%s holds other tensors than the release's draft head (%d against %d names)" % (
path, len(head.names()), len(expected)))
wrong = [n for n in head.names() if head.dtype(n) != "F32"]
if wrong:
fail("%s: %s is not FP32" % (path, wrong[0]))
return head
def export_plan(folder, manifest, head):
"""[(shard file, [(tensor name, source)])] of an export, and its tensor order: the masters' tensors in index
order, then the draft head's by name, each in the shard the BF16 release has it in."""
order = [(name, folder) for name in folder.names()]
shard_of = dict(folder.weight_map)
if head is not None:
for name in sorted(head.names()):
order.append((name, head))
shard_of[name] = manifest["mtp"]["bf16_shards"][name]
plan = {}
for name, source in order:
plan.setdefault(shard_of[name], []).append((name, source))
return sorted(plan.items()), [name for name, _ in order], shard_of
def start_output(out):
out = os.path.abspath(out)
partial = out + ".partial"
if os.path.exists(out) or os.path.exists(partial):
fail("%s (or its .partial) exists; choose a new name" % out)
if not os.path.isdir(os.path.dirname(out)):
fail("%s is not a folder" % os.path.dirname(out))
os.mkdir(partial)
return out, partial
def copy_small_files(source, names, destination, skip=()):
for name in names:
if name in skip:
continue
path = os.path.join(source, name)
if not os.path.isfile(path):
fail("%s lacks %s, which the release's file list names" % (source, name))
shutil.copyfile(path, os.path.join(destination, name))
def run_shards(jobs, work, workers):
"""work(job) for every job on WORKERS threads; results in job order. The first failure stops the run."""
started = time.time()
results = []
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
futures = [pool.submit(work, job) for job in jobs]
try:
for number, future in enumerate(futures, 1):
results.append(future.result())
if number % 8 == 0 or number == len(futures):
say(" %d of %d weight files done, %.0f s" % (number, len(futures), time.time() - started))
except BaseException:
for future in futures:
future.cancel()
raise
return results
def finish(partial, out, digests, sums, workers):
"""Write SHA256SUMS, move the folder into place, and compare it with the published list SUMS when one is
given. Exit status 1 on a failed comparison (the folder stays, for inspection)."""
write_sums(partial, digests, workers)
os.rename(partial, out)
if sums:
if not check_sums(out, sums, workers):
sys.exit(1)
def published_sums(args, default):
"""The list --check compares with: --sums FILE, or DEFAULT (a file of the source folder). None without
--check. Refuses before any work when the list is missing."""
if not (args.check or args.check_only):
if args.sums:
fail("--sums is the list for --check; pass --check too")
return None
path = args.sums or default
if not path:
fail("--check needs --sums FILE here")
if not os.path.isfile(path):
fail("--check: no list at %s" % path)
return path
def add_common_arguments(parser):
parser.add_argument("--workers", type=int, default=8, help="weight files converted at a time (default 8)")
parser.add_argument("--threads", type=int, default=4, help="torch threads per worker (default 4)")
parser.add_argument("--exact-rounding", action="store_true",
help="round every element with the integer formulas instead of the torch casts")
parser.add_argument("--check", action="store_true",
help="after writing, compare every output file with the published list; exit 1 on a difference")
parser.add_argument("--sums", metavar="FILE", help="the list --check compares with, when not the source folder's")
parser.add_argument("--check-only", action="store_true",
help="write nothing: compare the existing output folder with the published list")
def versions():
return "python %s, torch %s" % (sys.version.split()[0], torch.__version__)