import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "jaweed123/TinyJLLM-Instruct-DPO"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id).eval()
@torch.no_grad()
def respond(instruction, max_new_tokens=40):
prompt = f"### Instruction:\n{instruction}\n\n### Response:\n"
ids = tok(prompt)["input_ids"]
L = len(ids)
seq = ids + [tok.pad_token_id]
for _ in range(max_new_tokens):
inp = torch.tensor([seq])
T = inp.shape[1]
mask = torch.tril(torch.ones(1, 1, T, T, dtype=torch.bool))
mask[:, :, L:, :] = False
mask[:, :, L:, :L] = True
nxt = int(model(inp, attention_mask=mask).logits[0, -1].argmax())
if nxt == tok.eos_token_id:
break
seq.append(nxt)
return tok.decode(seq[L + 1:])
print(respond("What is the capital of France?"))