georefine-verify 1.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ GeoRefine codec software
2
+ Copyright 2026 Tsotchke Corporation
3
+
4
+ This package is licensed under the Apache License, Version 2.0.
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.1
2
+ Name: georefine-verify
3
+ Version: 1.1.1
4
+ Summary: Prove that a GeoRefine TBE codec bundle decodes bit for bit to the parent model's published safetensors (CPU only)
5
+ Author: Tsotchke Corporation
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Tsotchke-Corporation/GeoRefine
8
+ Project-URL: Model, https://huggingface.co/Tsotchke-Corporation/Qwen3.8-27B-GeoRefine-TBE
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Dist: numpy>=1.22
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
16
+
17
+ # GeoRefine TBE tools
18
+
19
+ `georefine-verify` independently compares a GeoRefine TBE bundle with the
20
+ published parent model, byte for byte. `georefine-export` restores a TBE bundle
21
+ to ordinary Hugging Face safetensors without downloading or reading the parent.
22
+ Both tools use NumPy and the Python standard library, and run on CPU.
23
+
24
+ ```sh
25
+ pip install .
26
+ georefine-export --bundle Tsotchke-Corporation/Qwen3.8-27B-GeoRefine-TBE \
27
+ --output ./Qwen3.8-27B-GeoRefine-BF16 \
28
+ --expect-manifest-sha256 10028416e07c802b47e4dc93a86e9f0dd35ce6021f0e07b96c70bd9cb7a72bc3
29
+ ```
30
+
31
+ The output has `model.safetensors.index.json`, standard safetensors shards,
32
+ and the original config, tokenizer and vision files. Load it with a current
33
+ Transformers release compatible with the parent model:
34
+
35
+ ```python
36
+ from transformers import AutoModelForMultimodalLM, AutoProcessor
37
+ model = AutoModelForMultimodalLM.from_pretrained("./Qwen3.8-27B-GeoRefine-BF16")
38
+ processor = AutoProcessor.from_pretrained("./Qwen3.8-27B-GeoRefine-BF16")
39
+ ```
40
+
41
+ The export is BF16: plan for about 56 GB of output storage, plus one codec shard
42
+ of scratch space when downloading from the Hub, and enough memory or GPU
43
+ capacity to run Qwen3.8-27B. This path establishes portable model compatibility;
44
+ it does not retain the compressed model's runtime memory or speed advantages.
45
+ The native TBE engine is a separate optimized backend. A full 27B export and
46
+ Transformers load remain release gates, beyond the existing small-fixture tests.
@@ -0,0 +1,30 @@
1
+ # GeoRefine TBE tools
2
+
3
+ `georefine-verify` independently compares a GeoRefine TBE bundle with the
4
+ published parent model, byte for byte. `georefine-export` restores a TBE bundle
5
+ to ordinary Hugging Face safetensors without downloading or reading the parent.
6
+ Both tools use NumPy and the Python standard library, and run on CPU.
7
+
8
+ ```sh
9
+ pip install .
10
+ georefine-export --bundle Tsotchke-Corporation/Qwen3.8-27B-GeoRefine-TBE \
11
+ --output ./Qwen3.8-27B-GeoRefine-BF16 \
12
+ --expect-manifest-sha256 10028416e07c802b47e4dc93a86e9f0dd35ce6021f0e07b96c70bd9cb7a72bc3
13
+ ```
14
+
15
+ The output has `model.safetensors.index.json`, standard safetensors shards,
16
+ and the original config, tokenizer and vision files. Load it with a current
17
+ Transformers release compatible with the parent model:
18
+
19
+ ```python
20
+ from transformers import AutoModelForMultimodalLM, AutoProcessor
21
+ model = AutoModelForMultimodalLM.from_pretrained("./Qwen3.8-27B-GeoRefine-BF16")
22
+ processor = AutoProcessor.from_pretrained("./Qwen3.8-27B-GeoRefine-BF16")
23
+ ```
24
+
25
+ The export is BF16: plan for about 56 GB of output storage, plus one codec shard
26
+ of scratch space when downloading from the Hub, and enough memory or GPU
27
+ capacity to run Qwen3.8-27B. This path establishes portable model compatibility;
28
+ it does not retain the compressed model's runtime memory or speed advantages.
29
+ The native TBE engine is a separate optimized backend. A full 27B export and
30
+ Transformers load remain release gates, beyond the existing small-fixture tests.
@@ -0,0 +1,4 @@
1
+ GeoRefine codec software
2
+ Copyright 2026 Tsotchke Corporation
3
+
4
+ This package is licensed under the Apache License, Version 2.0.
@@ -0,0 +1,4 @@
1
+ """georefine-verify: prove that a GeoRefine TBE codec bundle decodes, bit for bit,
2
+ to the parent model's published safetensors. CPU only; numpy and the standard
3
+ library."""
4
+ __version__ = "1.1.1"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,105 @@
1
+ """georefine-verify command line."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+
7
+ from . import __version__
8
+ from .sources import SourceError, eprint
9
+ from .verify import Options, Verifier
10
+
11
+ EPILOG = """\
12
+ examples:
13
+ # full check: download the parent at the pinned commit (sha256-checked against
14
+ # Hugging Face's LFS digests), decode every bundle tensor on the CPU, compare bytes
15
+ georefine-verify --bundle ./Qwen3.8-27B-GeoRefine-TBE --reference Qwen/Qwen3.8-27B@1d4bf0f2
16
+
17
+ # use a parent copy you already have (its shards are still hashed and checked)
18
+ georefine-verify --bundle ./bundle --reference Qwen/Qwen3.8-27B@1d4bf0f2 --reference-dir ~/qwen
19
+
20
+ # quick spot check: layer 0 only, parent bytes fetched by HTTP range request
21
+ georefine-verify --bundle ./bundle --reference Qwen/Qwen3.8-27B@1d4bf0f2 \\
22
+ --reference-mode range --tensors 'layers\\.0\\.'
23
+
24
+ exit status: 0 = PASS (every parent tensor bit-identical, all digests checked),
25
+ 3 = PASS_PARTIAL (everything checked matched, but the check was not complete),
26
+ 1 = FAIL, 2 = usage or I/O error. Re-running with the same --work-dir resumes.
27
+ """
28
+
29
+
30
+ def build_parser() -> argparse.ArgumentParser:
31
+ ap = argparse.ArgumentParser(
32
+ prog="georefine-verify", epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter,
33
+ description="Check that a GeoRefine TBE bundle decodes to the parent's published tensors "
34
+ "bit for bit. CPU only.")
35
+ ap.add_argument("--bundle", required=True,
36
+ help="bundle: local dir, HF repo id[@rev], https:// base URL, or gs://bucket/prefix")
37
+ ap.add_argument("--reference", required=True,
38
+ help="parent as HF_REPO@COMMIT (e.g. Qwen/Qwen3.8-27B@1d4bf0f2), or a local dir")
39
+ ap.add_argument("--reference-dir", help="local copy of the parent's shards (still hashed and "
40
+ "checked against the published LFS sha256)")
41
+ ap.add_argument("--reference-mode", choices=("download", "range"), default="download",
42
+ help="download: fetch whole shards into WORK_DIR/reference and check their "
43
+ "sha256 (default); range: fetch only tensor bytes by HTTP range request "
44
+ "(fast spot checks; shard digests are then NOT checked)")
45
+ ap.add_argument("--bundle-mode", choices=("download", "range"), default="download",
46
+ help="for a remote bundle: download shards into WORK_DIR/bundle (sha256-checked "
47
+ "against the bundle manifest; default) or read tensors by range request")
48
+ ap.add_argument("--work-dir", default="georefine-verify-work",
49
+ help="progress, downloads and receipt (default ./georefine-verify-work)")
50
+ ap.add_argument("--receipt", help="receipt path (default WORK_DIR/receipt.json)")
51
+ ap.add_argument("--tensors", help="only tensors whose name matches this regex")
52
+ ap.add_argument("--limit", type=int, help="only the first N tensors (sorted by name)")
53
+ ap.add_argument("--evict-reference", action="store_true",
54
+ help="delete each downloaded parent shard once its tensors are verified "
55
+ "(peak disk ~4 GB instead of ~56 GB)")
56
+ ap.add_argument("--max-rate", type=float, metavar="MB_PER_S",
57
+ help="cap each download's rate (parent and bundle shards)")
58
+ ap.add_argument("--skip-bundle-shard-hash", action="store_true",
59
+ help="do not sha256 local bundle shards against the bundle manifest")
60
+ ap.add_argument("--expect-manifest-sha256", help="refuse a bundle whose manifest hash differs "
61
+ "(prefix allowed)")
62
+ ap.add_argument("--chunk-tiles", type=int, default=1 << 16,
63
+ help="decode granularity in 64-element tiles (memory ~ 60 B/tile)")
64
+ ap.add_argument("--fresh", action="store_true", help="ignore previous progress in WORK_DIR")
65
+ ap.add_argument("--version", action="version", version=f"georefine-verify {__version__}")
66
+ return ap
67
+
68
+
69
+ def main(argv=None) -> int:
70
+ a = build_parser().parse_args(argv)
71
+ opt = Options(bundle=a.bundle, reference=a.reference, reference_dir=a.reference_dir,
72
+ reference_mode=a.reference_mode, bundle_mode=a.bundle_mode,
73
+ work_dir=a.work_dir, tensors=a.tensors,
74
+ limit=a.limit, evict_reference=a.evict_reference, max_rate_mbps=a.max_rate,
75
+ check_bundle_shards=not a.skip_bundle_shard_hash,
76
+ expect_manifest_sha256=a.expect_manifest_sha256, chunk_tiles=a.chunk_tiles,
77
+ receipt=a.receipt, fresh=a.fresh)
78
+ try:
79
+ rec = Verifier(opt).run()
80
+ except SourceError as exc:
81
+ eprint(f"error: {exc}")
82
+ return 2
83
+ s = rec["summary"]
84
+ print(f"{rec['verdict']}: {s['bit_identical']}/{s['verified']} tensors bit-identical "
85
+ f"(parent has {s['parent_tensors']})")
86
+ for k, v in sorted(s["by_kind"].items()):
87
+ print(f" {k:4s} {v['match']}/{v['n']} {v['bytes'] / 1e9:.2f} GB")
88
+ print(f" parent {rec['parent']['repo']}@{rec['parent']['revision']} "
89
+ f"shards checked vs HF LFS sha256: {s['parent_shards_checked_against_hf_lfs']}")
90
+ print(f" sidecars (config, tokenizer, templates) identical to the parent's: "
91
+ f"{s['sidecars_identical']}/{s['sidecars']}")
92
+ print(f" bundle manifest sha256 {rec['bundle']['manifest_sha256']} "
93
+ f"shards checked: {s['bundle_shards_checked_against_manifest']}")
94
+ for c in rec.get("caveats", []):
95
+ print(f" caveat: {c}")
96
+ bad = [t for t in rec["tensors"] if not t.get("match")]
97
+ for t in bad[:20]:
98
+ print(f" MISMATCH {t['name']}: {t.get('problems')} mismatched={t.get('mismatched')} "
99
+ f"first={t.get('first_mismatch')}")
100
+ print(f" receipt {rec['receipt_path']}")
101
+ return {"PASS": 0, "PASS_PARTIAL": 3}.get(rec["verdict"], 1)
102
+
103
+
104
+ if __name__ == "__main__":
105
+ sys.exit(main())
@@ -0,0 +1,188 @@
1
+ """Export a TBE bundle to ordinary Hugging Face safetensors, without the parent.
2
+
3
+ This is a portable compatibility path. It restores BF16 storage and does not
4
+ provide compressed inference or the GeoRefine native engine's speed.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import struct
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ from .sources import LocalFile, SourceError, download, parse_location, read_safetensors_header, sha256_source
18
+ from .tbe import TBEParams, iter_decode
19
+ from .verify import _dtype_tag
20
+
21
+
22
+ def _digest_file(path: Path) -> str:
23
+ src = LocalFile(path)
24
+ try:
25
+ return sha256_source(src)
26
+ finally:
27
+ src.close()
28
+
29
+
30
+ def _bytes_for(entry: dict) -> int:
31
+ return int(entry["original_bytes"])
32
+
33
+
34
+ def _header(entries: list[dict]) -> bytes:
35
+ hdr, offset = {}, 0
36
+ for entry in entries:
37
+ name = entry["name"]
38
+ size = _bytes_for(entry)
39
+ hdr[name] = {"dtype": _dtype_tag(entry["dtype"]), "shape": entry["shape"],
40
+ "data_offsets": [offset, offset + size]}
41
+ offset += size
42
+ data = json.dumps(hdr, separators=(",", ":"), ensure_ascii=False).encode()
43
+ return data + b" " * (-len(data) % 8)
44
+
45
+
46
+ def _write_tensor(out, entry: dict, src: LocalFile, header: dict) -> None:
47
+ name = entry["name"]
48
+ digest = hashlib.blake2b()
49
+
50
+ def write(data: bytes) -> None:
51
+ out.write(data)
52
+ digest.update(data)
53
+
54
+ if entry["kind"] == "raw":
55
+ stored = header.get(name)
56
+ if stored is None or stored.dtype != _dtype_tag(entry["dtype"]) or \
57
+ list(stored.shape) != entry["shape"] or stored.nbytes != _bytes_for(entry):
58
+ raise SourceError(f"raw tensor metadata differs: {name}")
59
+ for off in range(0, stored.nbytes, 1 << 26):
60
+ write(src.read(stored.offset + off, min(1 << 26, stored.nbytes - off)))
61
+ elif entry["kind"] == "tbe":
62
+ if _dtype_tag(entry["dtype"]) != "BF16":
63
+ raise SourceError(f"TBE tensor is not BF16: {name}")
64
+ n, k = (int(x) for x in (entry.get("coded_shape") or entry["shape"]))
65
+ if n * k * 2 != _bytes_for(entry):
66
+ raise SourceError(f"TBE coded shape disagrees with byte count: {name}")
67
+ params = TBEParams(n=n, k=k, layout=entry["layout"], mode=int(entry["mode"]),
68
+ base=int(entry["base"]), superblock=int(entry.get("superblock", 32)))
69
+ parts = {}
70
+ for part in ("planes", "smb", "esc", "sbbase"):
71
+ parts[part] = header.get(f"{name}.{part}")
72
+ if parts[part] is None:
73
+ raise SourceError(f"TBE part absent: {name}.{part}")
74
+ if parts["planes"].nbytes != params.tiles * 24 or \
75
+ parts["smb"].nbytes != params.tiles * 64 or \
76
+ parts["esc"].nbytes != int(entry["escapes"]):
77
+ raise SourceError(f"TBE part sizes disagree: {name}")
78
+ sb = parts["sbbase"]
79
+ if sb.nbytes != params.n_superblocks * 4:
80
+ raise SourceError(f"TBE superblock index size disagrees: {name}")
81
+ sbbase = np.frombuffer(src.read(sb.offset, sb.nbytes), dtype="<i4")
82
+
83
+ def reader(part):
84
+ a = parts[part]
85
+ return lambda off, size: src.read(a.offset + off, size)
86
+
87
+ for _, words in iter_decode(params, reader("planes"), reader("smb"),
88
+ reader("esc"), sbbase, parts["esc"].nbytes):
89
+ write(words.astype("<u2", copy=False).tobytes())
90
+ else:
91
+ raise SourceError(f"unknown tensor kind: {name}")
92
+ if entry.get("blake2b_source") and digest.hexdigest() != entry["blake2b_source"]:
93
+ raise SourceError(f"decoded tensor digest differs: {name}")
94
+
95
+
96
+ def export(bundle: str, output: Path, expected_manifest_sha256: str | None = None,
97
+ work_dir: Path | None = None) -> dict:
98
+ loc = parse_location(bundle)
99
+ raw = loc.read_small("serve_manifest.json")
100
+ manifest_sha = hashlib.sha256(raw).hexdigest()
101
+ if expected_manifest_sha256 and manifest_sha != expected_manifest_sha256:
102
+ raise SourceError("manifest SHA-256 differs from the expected value")
103
+ manifest = json.loads(raw)
104
+ if manifest.get("format") != "georefine.tbe.serve.v1":
105
+ raise SourceError("unsupported bundle format")
106
+ shards = manifest["shards"]
107
+ entries = manifest["tensors"]
108
+ by_shard: dict[int, list[dict]] = {i: [] for i in range(len(shards))}
109
+ if len({e["name"] for e in entries}) != len(entries):
110
+ raise SourceError("duplicate tensor name")
111
+ for e in entries:
112
+ by_shard[int(e["shard"])].append(e)
113
+ output.mkdir(parents=True, exist_ok=True)
114
+ scratch = work_dir or (output.parent / ".scratch" / f"{output.name}-georefine-export")
115
+ scratch.mkdir(parents=True, exist_ok=True)
116
+ receipt_path = scratch / "receipt.json"
117
+ receipt = json.loads(receipt_path.read_text()) if receipt_path.exists() else {"shards": {}}
118
+ if receipt.get("manifest_sha256") not in (None, manifest_sha):
119
+ raise SourceError("output was started from another bundle manifest")
120
+ receipt["manifest_sha256"] = manifest_sha
121
+ weight_map = {}
122
+ total_size = 0
123
+ for i, shard in enumerate(shards):
124
+ name = f"model-{i + 1:05d}-of-{len(shards):05d}.safetensors"
125
+ target = output / name
126
+ expected = receipt["shards"].get(name)
127
+ if expected and target.is_file() and _digest_file(target) == expected:
128
+ pass
129
+ else:
130
+ source_file = scratch / f"codec-{i:05d}.safetensors"
131
+ if not source_file.is_file() or _digest_file(source_file) != shard["sha256"]:
132
+ if loc.kind == "local":
133
+ source_file = Path(loc.base) / shard["file"]
134
+ else:
135
+ download(loc.url(shard["file"]), source_file, size=shard["bytes"],
136
+ sha256=shard["sha256"])
137
+ if _digest_file(source_file) != shard["sha256"]:
138
+ raise SourceError(f"codec shard hash differs: {shard['file']}")
139
+ src = LocalFile(source_file)
140
+ try:
141
+ codec_header = read_safetensors_header(src)[0]
142
+ ordered = sorted(by_shard[i], key=lambda e: e["name"])
143
+ header = _header(ordered)
144
+ part = scratch / f"{name}.partial"
145
+ with part.open("wb") as out:
146
+ out.write(struct.pack("<Q", len(header)))
147
+ out.write(header)
148
+ for entry in ordered:
149
+ _write_tensor(out, entry, src, codec_header)
150
+ os.replace(part, target)
151
+ receipt["shards"][name] = _digest_file(target)
152
+ receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n")
153
+ finally:
154
+ src.close()
155
+ if loc.kind != "local":
156
+ source_file.unlink(missing_ok=True)
157
+ for entry in by_shard[i]:
158
+ weight_map[entry["name"]] = name
159
+ total_size += _bytes_for(entry)
160
+ for sidecar in manifest["sidecars"]:
161
+ rel = sidecar["file"]
162
+ target = output / rel
163
+ data = loc.read_small(rel)
164
+ if len(data) != sidecar["bytes"] or hashlib.sha256(data).hexdigest() != sidecar["sha256"]:
165
+ raise SourceError(f"sidecar hash differs: {rel}")
166
+ target.parent.mkdir(parents=True, exist_ok=True)
167
+ target.write_bytes(data)
168
+ index = {"metadata": {"total_size": total_size}, "weight_map": weight_map}
169
+ (output / "model.safetensors.index.json").write_text(
170
+ json.dumps(index, indent=2, sort_keys=True) + "\n")
171
+ return {"manifest_sha256": manifest_sha, "tensors": len(weight_map),
172
+ "shards": len(shards), "bf16_bytes": total_size, "output": str(output)}
173
+
174
+
175
+ def main(argv=None) -> int:
176
+ parser = argparse.ArgumentParser(description=__doc__)
177
+ parser.add_argument("--bundle", required=True, help="local dir, HF repo[@revision], or gs://")
178
+ parser.add_argument("--output", required=True, type=Path)
179
+ parser.add_argument("--work-dir", type=Path, help="durable scratch and resume state")
180
+ parser.add_argument("--expect-manifest-sha256")
181
+ args = parser.parse_args(argv)
182
+ result = export(args.bundle, args.output, args.expect_manifest_sha256, args.work_dir)
183
+ print(json.dumps(result, sort_keys=True))
184
+ return 0
185
+
186
+
187
+ if __name__ == "__main__":
188
+ raise SystemExit(main())