Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 15 additions & 21 deletions smallthinker/get_no_moe_weights_ffn.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from pathlib import Path



try:
from gguf.gguf_reader import GGUFReader, ReaderTensor
from gguf.constants import GGUF_MAGIC, GGUFEndian
Expand All @@ -16,10 +15,10 @@
from gguf.constants import GGUF_MAGIC, GGUFEndian



def looks_like_moe(name: str) -> bool:
return 'exps' in name


def align_offset(offset: int, alignment: int) -> int:
if alignment == 0:
return offset
Expand All @@ -35,29 +34,28 @@ def main(src_path: str, dst_path: str):

tensors_to_keep: list[ReaderTensor] = [t for t in reader.tensors if not looks_like_moe(t.name)]
if len(tensors_to_keep) == len(reader.tensors):
print(" COPY!")
print(" COPY!")

alignment = reader.alignment
endian_char = '<' if reader.endianess == GGUFEndian.LITTLE else '>'

with open(dst_path, 'wb') as fout:
header_format = f"{endian_char}I I Q Q"
kv_count = int(reader.fields['GGUF.kv_count'].parts[-1][0])
gguf_version = int(reader.fields['GGUF.version'].parts[-1][0])

new_header = struct.pack(
header_format, GGUF_MAGIC, gguf_version, len(tensors_to_keep), kv_count
# GGUF magic has a fixed byte order, even for big-endian files.
new_header = struct.pack('<I', GGUF_MAGIC) + struct.pack(
f"{endian_char}I Q Q", gguf_version, len(tensors_to_keep), kv_count
)
fout.write(new_header)


header_size = struct.calcsize(header_format)
header_size = len(new_header)
first_tensor_info_offset = reader.tensors[0].field.offset if reader.tensors else reader.data_offset
metadata_size = first_tensor_info_offset - header_size
metadata_bytes = reader.data[header_size : header_size + metadata_size]

metadata_bytes = reader.data[header_size:header_size + metadata_size]
fout.write(metadata_bytes)

current_data_offset = 0
for tensor in tensors_to_keep:
name_bytes = tensor.name.encode('utf-8')
Expand All @@ -68,40 +66,36 @@ def main(src_path: str, dst_path: str):
fout.write(struct.pack(f"{endian_char}Q", dim))
fout.write(struct.pack(f"{endian_char}I", tensor.tensor_type.value))
fout.write(struct.pack(f"{endian_char}Q", current_data_offset))



current_data_offset += tensor.n_bytes
current_data_offset = align_offset(current_data_offset, alignment)



tensor_info_end_offset = fout.tell()
data_block_start_offset = align_offset(tensor_info_end_offset, alignment)
padding_size = data_block_start_offset - tensor_info_end_offset
if padding_size > 0:
fout.write(b'\x00' * padding_size)

with open(src_path, 'rb') as fin:
total_data_written = 0
for tensor in tensors_to_keep:
fin.seek(tensor.data_offset)
tensor_bytes = fin.read(tensor.n_bytes)
if len(tensor_bytes) != tensor.n_bytes:
raise IOError(f"Error: expect {tensor.n_bytes} bytes, but get {len(tensor_bytes)}")

fout.write(tensor_bytes)
total_data_written += len(tensor_bytes)


padding_to_add = align_offset(tensor.n_bytes, alignment) - tensor.n_bytes
if padding_to_add > 0:
fout.write(b'\x00' * padding_to_add)




if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("src", help="input path")
parser.add_argument("dst", help="output path")
args = parser.parse_args()

main(args.src, args.dst)
main(args.src, args.dst)
84 changes: 84 additions & 0 deletions smallthinker/tests/test_get_no_moe_weights.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""Model-free roundtrip tests for the documented MoE weight filter."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest

SMALLTHINKER = Path(__file__).resolve().parents[1]
GGUF_PY = SMALLTHINKER / "gguf-py"
sys.path.insert(0, str(GGUF_PY))

import numpy as np # noqa: E402
from gguf import GGUFEndian, GGUFReader, GGUFWriter # noqa: E402


class FilterMoEWeightsTests(unittest.TestCase):
def check_roundtrip(self, endian, tensor_names):
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp) / "input.gguf"
destination = Path(tmp) / "output.gguf"
writer = GGUFWriter(source, "smallthinker", endianess=endian)
writer.add_name("tiny endianness fixture")
for index, name in enumerate(tensor_names):
values = np.arange(6, dtype=np.float32).reshape(2, 3) + index
writer.add_tensor(name, values)
writer.write_header_to_file()
writer.write_kv_data_to_file()
writer.write_tensors_to_file()
writer.close()

result = subprocess.run(
[sys.executable, str(SMALLTHINKER / "get_no_moe_weights_ffn.py"),
str(source), str(destination)],
env=dict(os.environ, PYTHONPATH=str(GGUF_PY)),
capture_output=True, text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
# The magic is a fixed byte sequence, independent of the file's
# integer and tensor byte order (as in GGUFWriter/GGUFReader).
self.assertEqual(destination.read_bytes()[:4], b"GGUF")

original = GGUFReader(source)
converted = GGUFReader(destination)
try:
self.assertEqual(converted.endianess, endian)
self.assertEqual(
converted.fields["general.name"].parts[-1].tobytes(),
original.fields["general.name"].parts[-1].tobytes(),
)
retained = [t for t in original.tensors if "exps" not in t.name]
self.assertEqual([t.name for t in converted.tensors], [t.name for t in retained])
for before, after in zip(retained, converted.tensors):
np.testing.assert_array_equal(after.shape, before.shape)
self.assertEqual(after.tensor_type, before.tensor_type)
self.assertEqual(after.data.tobytes(), before.data.tobytes())
self.assertEqual(after.data_offset % converted.alignment, 0)
finally:
# GGUFReader uses mmap. Release all tensor views before the
# temporary directory is removed on Windows.
original.data._mmap.close()
converted.data._mmap.close()

def test_little_endian_filter(self):
self.check_roundtrip(GGUFEndian.LITTLE, ["token_embd.weight", "blk.0.ffn_up_exps.weight"])

def test_big_endian_filter(self):
self.check_roundtrip(GGUFEndian.BIG, ["token_embd.weight", "blk.0.ffn_up_exps.weight"])

def test_little_endian_no_experts(self):
self.check_roundtrip(GGUFEndian.LITTLE, ["token_embd.weight"])

def test_big_endian_no_experts(self):
self.check_roundtrip(GGUFEndian.BIG, ["token_embd.weight"])

def test_little_endian_only_experts(self):
self.check_roundtrip(GGUFEndian.LITTLE, ["blk.0.ffn_up_exps.weight"])

def test_big_endian_only_experts(self):
self.check_roundtrip(GGUFEndian.BIG, ["blk.0.ffn_up_exps.weight"])


if __name__ == "__main__":
unittest.main()