diff --git a/smallthinker/get_no_moe_weights_ffn.py b/smallthinker/get_no_moe_weights_ffn.py index e08c6b7b5..7199c2dda 100644 --- a/smallthinker/get_no_moe_weights_ffn.py +++ b/smallthinker/get_no_moe_weights_ffn.py @@ -6,7 +6,6 @@ from pathlib import Path - try: from gguf.gguf_reader import GGUFReader, ReaderTensor from gguf.constants import GGUF_MAGIC, GGUFEndian @@ -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 @@ -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(' 0: fout.write(b'\x00' * padding_size) - + with open(src_path, 'rb') as fin: total_data_written = 0 for tensor in tensors_to_keep: @@ -87,16 +83,14 @@ def main(src_path: str, dst_path: str): 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() @@ -104,4 +98,4 @@ def main(src_path: str, dst_path: str): parser.add_argument("dst", help="output path") args = parser.parse_args() - main(args.src, args.dst) \ No newline at end of file + main(args.src, args.dst) diff --git a/smallthinker/tests/test_get_no_moe_weights.py b/smallthinker/tests/test_get_no_moe_weights.py new file mode 100644 index 000000000..833ae16d0 --- /dev/null +++ b/smallthinker/tests/test_get_no_moe_weights.py @@ -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()