File size: 2,866 Bytes
bf2848b | 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 | # Author:浅斟
"""LemonJev 4B local Python and CLI entrypoint. See QUICKSTART.md."""
import argparse
import json
from pathlib import Path
import decision_runtime as runtime
class DecisionModel:
"""Load one decision checkpoint and answer typed questions."""
def __init__(self, checkpoint=None, device="auto"):
import torch
from transformers import AutoModel
checkpoint = Path(checkpoint or Path(__file__).resolve().parent).resolve()
if device == "auto":
device = "cuda:0" if torch.cuda.is_available() else "cpu"
self.device = device
self.model = AutoModel.from_pretrained(
str(checkpoint),
trust_remote_code=True,
local_files_only=True,
use_safetensors=True,
dtype=torch.bfloat16,
device_map=device,
attn_implementation="sdpa",
).eval()
self.processor = runtime.load_processor(checkpoint)
self.config = self.model.config
if self.config.decision_protocol != "autojev-v1":
raise ValueError("Unsupported decision protocol")
if tuple(self.model.readout.weight.shape) != (
self.config.max_options,
self.config.text_config.hidden_size,
):
raise ValueError("Readout shape does not match configuration")
for code, token_id in zip(self.config.codes, self.config.token_ids, strict=True):
if self.processor.tokenizer.encode(code, add_special_tokens=False) != [token_id]:
raise ValueError("Tokenizer option mapping mismatch")
def predict(self, request):
state, questions = runtime.validate_request(request)
names = list(questions)
rows = [
{"state": state, "question": questions[name]} for name in names
]
result = runtime.predict_batch(self.model, self.processor, rows)
return {
"model": self.config.model_id,
"answers": dict(zip(names, result["answers"])),
"temperature": result["temperature"],
"usage": {
"input_tokens": result["input_tokens"],
"output_tokens": 0,
},
}
def main():
parser = argparse.ArgumentParser(description="LemonJev 4B decision inference")
parser.add_argument(
"--checkpoint", default=str(Path(__file__).resolve().parent)
)
parser.add_argument("--device", default="auto")
parser.add_argument("--input", help="JSON request file; defaults to example.json")
args = parser.parse_args()
request = json.loads(
Path(args.input or Path(__file__).with_name("example.json")).read_text()
)
model = DecisionModel(args.checkpoint, args.device)
print(json.dumps(model.predict(request), ensure_ascii=False, indent=2))
if __name__ == "__main__":
main() |