Velqora-40M-Instruct / run_inference.py
Maxilicious20's picture
Publish Velqora-40M-Instruct (safetensors, best/latest checkpoints, tokenizer, and inference script)
08bf9cd verified
Raw History Blame Contribute Delete
2.96 kB
import os
import json
import argparse
import torch
from safetensors.torch import load_file
from tokenizers import Tokenizer
from velqora.model import VelqoraConfig, VelqoraForCausalLM
def load_model(model_dir: str, device: torch.device):
with open(os.path.join(model_dir, "config.json"), "r", encoding="utf-8") as f:
cfg_raw = json.load(f)
valid_keys = VelqoraConfig.__dataclass_fields__.keys()
cfg = VelqoraConfig(**{k: v for k, v in cfg_raw.items() if k in valid_keys})
model = VelqoraForCausalLM(cfg).to(device)
st_path = os.path.join(model_dir, "model.safetensors")
state = load_file(st_path, device=str(device))
if cfg.tie_embeddings and "lm_head.weight" not in state:
state["lm_head.weight"] = state["embed_tokens.weight"]
model.load_state_dict(state)
model.eval()
tok = Tokenizer.from_file(os.path.join(model_dir, "tokenizer.json"))
return model, tok, cfg
def main():
parser = argparse.ArgumentParser(description="Run local inference with Velqora")
parser.add_argument("--model-dir", type=str, default=os.path.dirname(os.path.abspath(__file__)))
parser.add_argument("--prompt", type=str, default=None)
parser.add_argument("--temperature", type=float, default=0.45)
parser.add_argument("--top-p", type=float, default=0.88)
parser.add_argument("--max-new-tokens", type=int, default=160)
args = parser.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model, tok, cfg = load_model(args.model_dir, device)
is_instruct = "instruct" in cfg.model_name.lower()
stop_ids = [tok.token_to_id("<|im_end|>"), tok.token_to_id("<|endoftext|>")]
stop_ids = [i for i in stop_ids if i is not None]
def run_once(text: str):
if is_instruct:
formatted = (
"<|im_start|>system\nYou are Velqora, a helpful, thoughtful, and friendly AI assistant.<|im_end|>\n"
f"<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n"
)
else:
formatted = text
ids = torch.tensor([tok.encode(formatted).ids], dtype=torch.long, device=device)
out = model.generate(
ids,
max_new_tokens=args.max_new_tokens,
temperature=args.temperature,
top_p=args.top_p,
stop_token_ids=stop_ids,
)[0].tolist()
reply = tok.decode(out[ids.shape[1] :], skip_special_tokens=True).strip()
print(reply)
if args.prompt is not None:
run_once(args.prompt)
return
print(f"Loaded {cfg.model_name} on {device}. Type /quit to exit.")
while True:
user_in = input("\nPrompt: ").strip()
if not user_in:
continue
if user_in.lower() in {"/quit", "/exit"}:
break
run_once(user_in)
if __name__ == "__main__":
main()