Download convert.py from hugging-mac/d3-lite-CoreAI: direct link, hf CLI and curl.
- Browser
- Download file 4.64 kB
-
https://huggingface.co/hugging-mac/d3-lite-CoreAI/resolve/main/convert.py
- Command line
-
hf download hf://hugging-mac/d3-lite-CoreAI/convert.py
-
curl -L -o convert.py https://huggingface.co/hugging-mac/d3-lite-CoreAI/resolve/main/convert.py
4.64 kB
| """Export the pinned D3 Lite backbone as a three-input, text-only Core AI graph. | |
| Adapted from the Apache-2.0 D3 Edge text exporter by hugging-mac, based on | |
| the original conversion recipe by Max Farrell. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import shutil | |
| from pathlib import Path | |
| import torch | |
| from coreai_torch import TorchConverter, get_decomp_table | |
| from safetensors.torch import load_file | |
| from transformers import Qwen3_5Model | |
| SOURCE = "vllm-sr/d3-lite" | |
| REVISION = "a8d25a91ef75552803f7009d25b7bd435991abd9" | |
| SEQUENCE_LENGTH = 512 | |
| WEIGHTS = "model-00001-of-00001.safetensors" | |
| ORIGINAL_WEIGHTS_SHA256 = "ca6222dbf2b72899ae45580ed84d26d1f0e69a8de212edda295072000e34a4c2" | |
| HOST_FILES = ( | |
| "LICENSE", "NOTICE", "MODEL_MANIFEST.json", "config.json", "decision_config.json", | |
| "chat_template.jinja", "tokenizer.json", "tokenizer_config.json", "vocab.json", | |
| "merges.txt", "d3_format.py", "d3_runtime.py", | |
| ) | |
| class DecisionText(torch.nn.Module): | |
| def __init__(self, language_model, readout): | |
| super().__init__() | |
| self.language_model = language_model | |
| self.register_buffer("readout", readout.float()) | |
| def forward(self, input_ids, attention_mask, position_ids): | |
| hidden = self.language_model( | |
| input_ids=input_ids, | |
| attention_mask={ | |
| "full_attention": attention_mask[:, None, None, :].bool(), | |
| "linear_attention": attention_mask, | |
| }, | |
| position_ids=position_ids, | |
| use_cache=False, | |
| ).last_hidden_state | |
| return hidden[:, -1].float() @ self.readout.T | |
| def convert(source, output): | |
| original = json.loads((source / "MODEL_MANIFEST.json").read_text()) | |
| config = json.loads((source / "decision_config.json").read_text()) | |
| hashes = original["identity"]["files_sha256"] | |
| if ( | |
| original["repo_id"] != SOURCE | |
| or hashes.get(WEIGHTS) != ORIGINAL_WEIGHTS_SHA256 | |
| or config["attention_mode"] != "noncausal_full_attention" | |
| or len(config["codes"]) != 255 | |
| ): | |
| raise ValueError("Unexpected original D3 Lite model identity or readout") | |
| for name, expected in hashes.items(): | |
| with (source / name).open("rb") as file: | |
| if hashlib.file_digest(file, "sha256").hexdigest() != expected: | |
| raise ValueError(f"Source checksum mismatch: {name}") | |
| torch.set_num_threads(4) | |
| print("Verified source hashes; loading the BF16 backbone", flush=True) | |
| backbone = Qwen3_5Model.from_pretrained( | |
| source, local_files_only=True, dtype=torch.bfloat16, attn_implementation="sdpa" | |
| ).eval() | |
| readout = load_file(source / "readout.safetensors")["weight"] | |
| hidden_size = backbone.config.text_config.hidden_size | |
| if tuple(readout.shape) != (len(config["codes"]), hidden_size): | |
| raise ValueError(f"Unexpected readout shape: {tuple(readout.shape)}") | |
| model = DecisionText(backbone.language_model, readout).eval() | |
| del backbone | |
| mask = torch.ones((1, SEQUENCE_LENGTH), dtype=torch.int32) | |
| positions = torch.arange(SEQUENCE_LENGTH, dtype=torch.int32).view(1, 1, -1).expand(4, 1, -1) | |
| print("Exporting and decomposing the text graph", flush=True) | |
| with torch.no_grad(): | |
| exported = torch.export.export(model, (mask, mask.clone(), positions), strict=False) | |
| exported = exported.run_decompositions(get_decomp_table()) | |
| print("Lowering to Core AI", flush=True) | |
| program = TorchConverter().add_exported_program(exported).to_coreai() | |
| program.save_asset(output / "decision.aimodel") | |
| metadata = dict( | |
| source=SOURCE, revision=REVISION, sequence_length=SEQUENCE_LENGTH, hidden_size=hidden_size, | |
| precision="bfloat16", readout_precision="float32", attention_mode=config["attention_mode"], | |
| modality="text", inputs=["input_ids", "attention_mask", "position_ids"], | |
| output=exported.graph_signature.user_outputs[0], function="main", format="Apple Core AI .aimodel", | |
| source_weight_sha256=hashes[WEIGHTS], source_readout_sha256=hashes["readout.safetensors"], | |
| ) | |
| (output / "manifest.json").write_text(json.dumps(metadata, indent=2) + "\n") | |
| for name in HOST_FILES: | |
| shutil.copyfile(source / name, output / name) | |
| print("Saved the text-only graph and runtime assets", flush=True) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--source", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True) | |
| arguments = parser.parse_args() | |
| arguments.output.mkdir(parents=True, exist_ok=True) | |
| convert(arguments.source, arguments.output) | |