File size: 14,110 Bytes
6ae9156 fac4d07 6ae9156 fac4d07 6ae9156 fac4d07 6ae9156 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | """Load/export the command model as JSON plus safetensors, without remote code.
Clone this repository and install its requirements before importing this module.
This is a small project-specific facade, not a Transformers AutoModel class.
All inference runs on CPU and preserves the typed boundary in ``lispm.infer``.
"""
import argparse
from dataclasses import fields
import hashlib
import io
import json
import math
from pathlib import Path
import pickle
import re
import tempfile
from huggingface_hub import snapshot_download
from safetensors import SafetensorError
from safetensors.torch import load_file, save_file
import torch
from actions import InputError, action_argument
from intent_model import IntentClassifier, LABELS, ModelConfig
from lispm import infer
_ARTIFACT_FILES = ("config.json", "model.safetensors")
_CONFIG_FIELDS = {
"artifact_format_version", "architecture", "labels", "vocab", "thresholds",
"source_checkpoint_sha256", "training",
}
def _unique_json_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f"Invalid artifact config: duplicate JSON field {key!r}.")
result[key] = value
return result
def _unit_interval(value):
return (type(value) in (int, float) and 0 <= value <= 1
and math.isfinite(value))
def _validate_config(config):
"""Validate every field that affects tokenization, model shape or admission."""
if not isinstance(config, dict) or not _CONFIG_FIELDS <= config.keys():
raise ValueError("Invalid artifact config: required fields are missing.")
if type(config["artifact_format_version"]) is not int or config["artifact_format_version"] != 1:
raise ValueError("Unsupported artifact_format_version; expected 1.")
if config["labels"] != list(LABELS):
raise ValueError("Artifact labels do not match this implementation's action set and order.")
architecture = config["architecture"]
architecture_fields = {field.name for field in fields(ModelConfig)}
if not isinstance(architecture, dict) or set(architecture) != architecture_fields:
raise ValueError("Invalid architecture: expected the complete ModelConfig fields.")
for key in architecture_fields - {"dropout"}:
if type(architecture[key]) is not int or architecture[key] <= 0:
raise ValueError(f"Invalid architecture.{key}: expected a positive integer.")
if architecture["width"] % architecture["heads"]:
raise ValueError("Invalid architecture: width must be divisible by heads.")
if architecture["char_buckets"] < 2 or architecture["max_words"] < 59:
raise ValueError("Invalid architecture: char_buckets must be >= 2 and max_words >= 59.")
if not _unit_interval(architecture["dropout"]):
raise ValueError("Invalid architecture.dropout: expected a finite value in [0, 1].")
vocab = config["vocab"]
if (not isinstance(vocab, dict) or not vocab
or any(not isinstance(word, str) or not word for word in vocab)
or any(type(index) is not int for index in vocab.values())
or set(vocab.values()) != set(range(len(vocab)))):
raise ValueError("Invalid vocab: token indexes must be unique contiguous integers starting at zero.")
if any(vocab.get(word) != index for index, word in enumerate(("<pad>", "<unk>", "<cls>"))):
raise ValueError("Invalid vocab: <pad>, <unk>, <cls> must have indexes 0, 1, 2.")
thresholds = config["thresholds"]
if (not isinstance(thresholds, dict) or set(thresholds) != {"probability", "margin"}
or not all(_unit_interval(value) for value in thresholds.values())):
raise ValueError("Invalid thresholds: probability and margin must be finite values in [0, 1].")
source_hash = config["source_checkpoint_sha256"]
if not isinstance(source_hash, str) or re.fullmatch(r"[0-9a-f]{64}", source_hash) is None:
raise ValueError("Invalid source_checkpoint_sha256: expected a lowercase SHA-256 digest.")
if not isinstance(config["training"], dict):
raise ValueError("Invalid training metadata: expected a JSON object.")
try:
return json.loads(json.dumps(config, ensure_ascii=False, allow_nan=False))
except (TypeError, ValueError) as error:
raise ValueError("Invalid artifact metadata: values must be finite JSON data.") from error
def _model_from_weights(metadata, weights):
"""Validate CPU tensor contents and exact shapes before assigning parameters."""
if not isinstance(weights, dict) or not all(isinstance(key, str) for key in weights):
raise ValueError("Invalid model weights: expected a named tensor dictionary.")
cfg = ModelConfig(**metadata["architecture"])
# These checks avoid allocating or constructing huge models from an invented
# config whose dimensions disagree with the tensor artifact.
core_shapes = {
"words.weight": (len(metadata["vocab"]), cfg.width),
"characters.weight": (cfg.char_buckets, cfg.width),
"positions.weight": (cfg.max_words, cfg.width),
"output.weight": (len(LABELS), cfg.width),
}
for name, shape in core_shapes.items():
if not isinstance(weights.get(name), torch.Tensor) or tuple(weights[name].shape) != shape:
raise ValueError(f"Invalid model weights: missing or incompatible tensor {name}.")
layer_ids = {int(match.group(1)) for name in weights
if (match := re.match(r"layers\.(\d+)\.", name))}
if (len(layer_ids) != cfg.layers or min(layer_ids, default=-1) != 0
or max(layer_ids, default=-1) != cfg.layers - 1):
raise ValueError("Invalid model weights: Transformer layers do not match architecture.layers.")
try:
with torch.device("meta"):
model = IntentClassifier(len(metadata["vocab"]), cfg).float()
expected = model.state_dict()
if set(weights) != set(expected):
raise ValueError("Invalid model weights: missing or unexpected parameter names.")
for name, target in expected.items():
tensor = weights[name]
if (not isinstance(tensor, torch.Tensor) or tensor.device.type != "cpu"
or tensor.layout != torch.strided or tensor.shape != target.shape
or tensor.dtype != target.dtype):
raise ValueError(f"Invalid model weights: incompatible CPU float32 tensor {name}.")
if not bool(torch.isfinite(tensor).all()):
raise ValueError(f"Invalid model weights: nonfinite values in {name}.")
model.load_state_dict(weights, strict=True, assign=True)
except (RuntimeError, TypeError, OverflowError) as error:
raise ValueError(f"Invalid model weights or architecture: {error}") from error
model.thresholds = metadata["thresholds"]
return model.eval()
class EmacsCommandModel:
"""CPU command inference with local or revision-pinned Hugging Face weights.
``model`` exposes the underlying IntentClassifier, ``vocab`` its vocabulary,
and ``metadata`` the complete validated JSON artifact configuration. Loading
never executes Python from a downloaded repository or changes torch threads.
"""
def __init__(self, model, metadata):
self.model = model
self.metadata = metadata
self.vocab = metadata["vocab"]
@classmethod
def from_pretrained(cls, model_name_or_path, revision=None, local_files_only=False, token=None):
"""Load config/weights from a directory or one resolved Hub snapshot.
Use a commit hash for ``revision`` when immutable remote loading is
required. ``local_files_only`` permits cached snapshots without network.
Network/authentication failures retain the Hugging Face exception type;
malformed or incomplete local artifacts raise ValueError.
"""
location = Path(model_name_or_path).expanduser()
is_local = (isinstance(model_name_or_path, Path) or location.exists()
or str(model_name_or_path).startswith(("/", ".", "~")))
if is_local:
if not location.is_dir():
raise ValueError(f"Model artifact directory does not exist: {location}")
else:
location = Path(snapshot_download(
repo_id=str(model_name_or_path), revision=revision,
local_files_only=local_files_only, token=token,
allow_patterns=list(_ARTIFACT_FILES),
))
try:
config = json.loads((location / "config.json").read_text(encoding="utf-8"),
object_pairs_hook=_unique_json_object)
except (OSError, UnicodeError, json.JSONDecodeError) as error:
raise ValueError(f"Could not read artifact config.json in {location}: {error}") from error
metadata = _validate_config(config)
try:
weights = load_file(location / "model.safetensors", device="cpu")
except (OSError, SafetensorError) as error:
raise ValueError(f"Could not read model.safetensors in {location}: {error}") from error
return cls(_model_from_weights(metadata, weights), metadata)
@classmethod
def from_checkpoint(cls, path):
"""Read a local format-3 torch checkpoint safely for artifact export.
This method performs no network access and uses weights_only=True. It
preserves the remaining JSON-safe checkpoint metadata under ``training``.
"""
path = Path(path).expanduser()
try:
source_bytes = path.read_bytes()
state = torch.load(io.BytesIO(source_bytes), map_location="cpu", weights_only=True)
source_hash = hashlib.sha256(source_bytes).hexdigest()
except (OSError, RuntimeError, ValueError, TypeError, pickle.UnpicklingError, EOFError) as error:
raise ValueError(f"Could not read local model checkpoint {path}: {error}") from error
if not isinstance(state, dict) or type(state.get("format_version")) is not int or state["format_version"] != 3:
raise ValueError("Unsupported checkpoint format_version; expected 3.")
required = {"architecture", "labels", "vocab", "thresholds", "model"}
if not required <= state.keys():
raise ValueError("Invalid checkpoint: required model fields are missing.")
metadata = _validate_config({
"artifact_format_version": 1,
**{key: state[key] for key in ("architecture", "labels", "vocab", "thresholds")},
"source_checkpoint_sha256": source_hash,
"training": {key: value for key, value in state.items()
if key not in required | {"format_version"}},
})
return cls(_model_from_weights(metadata, state["model"]), metadata)
def save_pretrained(self, directory):
"""Write the two artifacts and preserve historical pickle provenance.
Native artifacts identify their SafeTensors bytes as the source. Their
digest must follow a new serialization, whose header may differ even
when every numerical parameter remains unchanged.
"""
metadata = _validate_config(self.metadata)
weights = {name: tensor.detach().cpu().contiguous()
for name, tensor in self.model.state_dict().items()}
_model_from_weights(metadata, weights)
directory = Path(directory).expanduser()
directory.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".emacs-command-", dir=directory) as staging:
staging = Path(staging)
save_file(weights, staging / "model.safetensors", metadata={"format": "pt"})
if metadata.get("source_checkpoint_format") == "safetensors":
metadata["source_checkpoint_sha256"] = hashlib.sha256(
(staging / "model.safetensors").read_bytes()).hexdigest()
(staging / "config.json").write_text(
json.dumps(metadata, indent=2, ensure_ascii=False, allow_nan=False) + "\n",
encoding="utf-8",
)
for filename in ("model.safetensors", "config.json"):
(staging / filename).replace(directory / filename)
self.metadata["source_checkpoint_sha256"] = metadata["source_checkpoint_sha256"]
def predict(self, command):
"""Return a validated Program, or raise InputError for a refused request."""
return infer(self.model, self.vocab, command)
def predict_json(self, command):
"""Return accepted actions with name/path/text argument fields as appropriate."""
program = self.predict(command)
return {"actions": [dict(action=action.kind.value,
**({action_argument(action.kind): action.name}
if action.name is not None else {}))
for action in program.actions]}
def main():
"""Run proposal-only inference; no upload or command execution is performed."""
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument("--model", default=".", help="local artifact directory or Hugging Face model repo ID")
cli.add_argument("--infer", required=True, help="English command with JSON-quoted string arguments")
cli.add_argument("--format", choices=("lisp", "json"), default="lisp")
cli.add_argument("--local-files-only", action="store_true", help="use only local/cached artifacts")
cli.add_argument("--revision", help="Hub branch, tag, or commit hash")
args = cli.parse_args()
torch.set_num_threads(2)
try:
bundle = EmacsCommandModel.from_pretrained(
args.model, revision=args.revision, local_files_only=args.local_files_only)
result = (json.dumps(bundle.predict_json(args.infer), ensure_ascii=False)
if args.format == "json" else bundle.predict(args.infer).to_lisp())
except ValueError as error:
cli.error(str(error))
print(result)
if __name__ == "__main__":
main()
|