add v5 experiment runtime
Browse files
experiments/M31-Python-Agent-220M-v5/runtime/generation_m31.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
@torch.no_grad()
|
| 4 |
+
def generate(model, tokenizer, prompt, max_new_tokens=512, temperature=0.7, top_p=0.9,
|
| 5 |
+
repetition_penalty=1.05, max_context=512, device=None):
|
| 6 |
+
if device is None:
|
| 7 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 8 |
+
model.eval()
|
| 9 |
+
ids = tokenizer.encode(prompt).ids
|
| 10 |
+
if not ids:
|
| 11 |
+
raise ValueError('Prompt produced zero tokenizer tokens.')
|
| 12 |
+
x = torch.tensor([ids[-max_context:]], dtype=torch.long, device=device)
|
| 13 |
+
eos_id = tokenizer.token_to_id('<eos>')
|
| 14 |
+
for _ in range(int(max_new_tokens)):
|
| 15 |
+
x_in = x[:, -max_context:]
|
| 16 |
+
with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=(device == 'cuda')):
|
| 17 |
+
logits, _ = model(x_in)
|
| 18 |
+
logits = logits[:, -1, :].float()
|
| 19 |
+
if repetition_penalty and repetition_penalty > 1.0:
|
| 20 |
+
for token_id in torch.unique(x).tolist():
|
| 21 |
+
score = logits[0, token_id]
|
| 22 |
+
logits[0, token_id] = score / repetition_penalty if score > 0 else score * repetition_penalty
|
| 23 |
+
if temperature is None or temperature <= 0:
|
| 24 |
+
nxt = torch.argmax(logits, dim=-1, keepdim=True)
|
| 25 |
+
else:
|
| 26 |
+
logits = logits / max(float(temperature), 1e-5)
|
| 27 |
+
probs = torch.softmax(logits, dim=-1)
|
| 28 |
+
if top_p is not None and 0 < top_p < 1.0:
|
| 29 |
+
sorted_probs, sorted_idx = torch.sort(probs, descending=True, dim=-1)
|
| 30 |
+
cumulative = torch.cumsum(sorted_probs, dim=-1)
|
| 31 |
+
remove = cumulative > float(top_p)
|
| 32 |
+
remove[..., 0] = False
|
| 33 |
+
sorted_probs = sorted_probs.masked_fill(remove, 0.0)
|
| 34 |
+
probs = torch.zeros_like(probs).scatter(-1, sorted_idx, sorted_probs)
|
| 35 |
+
probs = probs / probs.sum(dim=-1, keepdim=True)
|
| 36 |
+
nxt = torch.multinomial(probs, 1)
|
| 37 |
+
x = torch.cat([x, nxt], dim=1)
|
| 38 |
+
if eos_id is not None and int(nxt.item()) == int(eos_id):
|
| 39 |
+
break
|
| 40 |
+
return tokenizer.decode(x[0].tolist(), skip_special_tokens=False)
|