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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
QED-Base-v3 inference library.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
from qed_infer import load_model, load_tokenizer, run
|
| 6 |
+
|
| 7 |
+
model = load_model("QED-Base-v3.pt")
|
| 8 |
+
tokenizer = load_tokenizer("qed-b3-tok.model")
|
| 9 |
+
|
| 10 |
+
text = run("Once upon a time", model, tokenizer, max_new_tokens=100)
|
| 11 |
+
|
| 12 |
+
# streaming / batched:
|
| 13 |
+
for texts in generate_stream(model, tokenizer, ["prompt A", "prompt B"]):
|
| 14 |
+
... # texts[i] is the completion-so-far for prompt i
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import sys
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Iterator, Optional
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
import sentencepiece as spm
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
DEVICE = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
|
| 31 |
+
DTYPE = torch.bfloat16 if DEVICE == "cuda" else torch.float32
|
| 32 |
+
|
| 33 |
+
DEFAULT_CHECKPOINT = "QED-Base-v3.pt"
|
| 34 |
+
DEFAULT_TOKENIZER = "qed-b3-tok.model"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass
|
| 38 |
+
class Config:
|
| 39 |
+
vocab_size: int = 56000
|
| 40 |
+
hidden_size: int = 768
|
| 41 |
+
num_layers: int = 12
|
| 42 |
+
num_heads: int = 12
|
| 43 |
+
num_kv_heads: int = 4
|
| 44 |
+
intermediate_size: int = 1792
|
| 45 |
+
max_seq_len: int = 2048
|
| 46 |
+
rope_theta: float = 10000.0
|
| 47 |
+
rms_eps: float = 1e-6
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class RMSNorm(nn.Module):
|
| 51 |
+
def __init__(self, dim, eps=1e-6):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 54 |
+
self.eps = eps
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
variance = x.float().pow(2).mean(dim=-1, keepdim=True)
|
| 58 |
+
x = x * torch.rsqrt(variance + self.eps)
|
| 59 |
+
return (self.weight * x).type_as(self.weight)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def rotate_half(x):
|
| 63 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 64 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class RotaryEmbedding(nn.Module):
|
| 68 |
+
def __init__(self, head_dim, max_seq_len, theta):
|
| 69 |
+
super().__init__()
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
|
| 71 |
+
positions = torch.arange(max_seq_len).float()
|
| 72 |
+
freqs = torch.outer(positions, inv_freq)
|
| 73 |
+
emb = torch.cat([freqs, freqs], dim=-1)
|
| 74 |
+
self.register_buffer("cos", emb.cos(), persistent=False)
|
| 75 |
+
self.register_buffer("sin", emb.sin(), persistent=False)
|
| 76 |
+
|
| 77 |
+
def forward(self, q, k, offset: int):
|
| 78 |
+
q_len = q.shape[-2]
|
| 79 |
+
k_len = k.shape[-2]
|
| 80 |
+
|
| 81 |
+
cos_q = self.cos[offset:offset + q_len][None, None, :, :].to(q.dtype)
|
| 82 |
+
sin_q = self.sin[offset:offset + q_len][None, None, :, :].to(q.dtype)
|
| 83 |
+
|
| 84 |
+
k_offset = offset + q_len - k_len
|
| 85 |
+
cos_k = self.cos[k_offset:k_offset + k_len][None, None, :, :].to(k.dtype)
|
| 86 |
+
sin_k = self.sin[k_offset:k_offset + k_len][None, None, :, :].to(k.dtype)
|
| 87 |
+
|
| 88 |
+
return (
|
| 89 |
+
q * cos_q + rotate_half(q) * sin_q,
|
| 90 |
+
k * cos_k + rotate_half(k) * sin_k,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class SwiGLU(nn.Module):
|
| 95 |
+
def __init__(self, hidden, intermediate):
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.gate_proj = nn.Linear(hidden, intermediate, bias=False)
|
| 98 |
+
self.up_proj = nn.Linear(hidden, intermediate, bias=False)
|
| 99 |
+
self.down_proj = nn.Linear(intermediate, hidden, bias=False)
|
| 100 |
+
|
| 101 |
+
def forward(self, x):
|
| 102 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class GQAttention(nn.Module):
|
| 106 |
+
def __init__(self, cfg: Config):
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.num_heads = cfg.num_heads
|
| 109 |
+
self.num_kv_heads = cfg.num_kv_heads
|
| 110 |
+
self.head_dim = cfg.hidden_size // cfg.num_heads
|
| 111 |
+
|
| 112 |
+
self.q_proj = nn.Linear(cfg.hidden_size, cfg.num_heads * self.head_dim, bias=False)
|
| 113 |
+
self.k_proj = nn.Linear(cfg.hidden_size, cfg.num_kv_heads * self.head_dim, bias=False)
|
| 114 |
+
self.v_proj = nn.Linear(cfg.hidden_size, cfg.num_kv_heads * self.head_dim, bias=False)
|
| 115 |
+
self.o_proj = nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=False)
|
| 116 |
+
|
| 117 |
+
self.rope = RotaryEmbedding(self.head_dim, cfg.max_seq_len, cfg.rope_theta)
|
| 118 |
+
|
| 119 |
+
def forward(self, x, offset: int, past_kv: Optional[tuple] = None):
|
| 120 |
+
B, T, C = x.shape
|
| 121 |
+
|
| 122 |
+
q = self.q_proj(x).view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
|
| 123 |
+
k = self.k_proj(x).view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 124 |
+
v = self.v_proj(x).view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 125 |
+
|
| 126 |
+
if past_kv is not None:
|
| 127 |
+
past_k, past_v = past_kv
|
| 128 |
+
k = torch.cat([past_k, k], dim=2)
|
| 129 |
+
v = torch.cat([past_v, v], dim=2)
|
| 130 |
+
|
| 131 |
+
q, k = self.rope(q, k, offset)
|
| 132 |
+
present = (k, v)
|
| 133 |
+
|
| 134 |
+
repeat = self.num_heads // self.num_kv_heads
|
| 135 |
+
k_rep = k.repeat_interleave(repeat, dim=1)
|
| 136 |
+
v_rep = v.repeat_interleave(repeat, dim=1)
|
| 137 |
+
|
| 138 |
+
y = F.scaled_dot_product_attention(q, k_rep, v_rep, is_causal=T > 1)
|
| 139 |
+
|
| 140 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
| 141 |
+
return self.o_proj(y), present
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class QEDBlock(nn.Module):
|
| 145 |
+
def __init__(self, cfg: Config):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.attn_norm = RMSNorm(cfg.hidden_size, cfg.rms_eps)
|
| 148 |
+
self.attention = GQAttention(cfg)
|
| 149 |
+
self.ffn_norm = RMSNorm(cfg.hidden_size, cfg.rms_eps)
|
| 150 |
+
self.ffn = SwiGLU(cfg.hidden_size, cfg.intermediate_size)
|
| 151 |
+
|
| 152 |
+
def forward(self, x, offset: int, past_kv=None):
|
| 153 |
+
attn_out, present = self.attention(self.attn_norm(x), offset, past_kv)
|
| 154 |
+
x = x + attn_out
|
| 155 |
+
x = x + self.ffn(self.ffn_norm(x))
|
| 156 |
+
return x, present
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class QEDBaseV3(nn.Module):
|
| 160 |
+
def __init__(self, cfg: Config):
|
| 161 |
+
super().__init__()
|
| 162 |
+
self.cfg = cfg
|
| 163 |
+
self.embed_tokens = nn.Embedding(cfg.vocab_size, cfg.hidden_size)
|
| 164 |
+
self.layers = nn.ModuleList([QEDBlock(cfg) for _ in range(cfg.num_layers)])
|
| 165 |
+
self.final_norm = RMSNorm(cfg.hidden_size, cfg.rms_eps)
|
| 166 |
+
self.lm_head = nn.Linear(cfg.hidden_size, cfg.vocab_size, bias=False)
|
| 167 |
+
self.lm_head.weight = self.embed_tokens.weight
|
| 168 |
+
|
| 169 |
+
def forward(self, input_ids, offset: int = 0, past_key_values: Optional[list] = None):
|
| 170 |
+
x = self.embed_tokens(input_ids)
|
| 171 |
+
new_past = []
|
| 172 |
+
for i, layer in enumerate(self.layers):
|
| 173 |
+
past_kv = past_key_values[i] if past_key_values is not None else None
|
| 174 |
+
x, present = layer(x, offset, past_kv)
|
| 175 |
+
new_past.append(present)
|
| 176 |
+
x = self.final_norm(x)
|
| 177 |
+
return self.lm_head(x), new_past
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def load_model(model_path: str, cfg: Config = Config()) -> QEDBaseV3:
|
| 181 |
+
path = Path(model_path)
|
| 182 |
+
if not path.exists():
|
| 183 |
+
raise FileNotFoundError(f"Checkpoint not found: {model_path}")
|
| 184 |
+
|
| 185 |
+
package = torch.load(path, map_location="cpu", weights_only=True)
|
| 186 |
+
state_dict = package["state_dict"] if "state_dict" in package else package
|
| 187 |
+
|
| 188 |
+
model = QEDBaseV3(cfg)
|
| 189 |
+
missing, unexpected = model.load_state_dict(state_dict, strict=False)
|
| 190 |
+
if missing:
|
| 191 |
+
print(f"[warn] missing keys: {missing}", file=sys.stderr)
|
| 192 |
+
if unexpected:
|
| 193 |
+
print(f"[warn] unexpected keys: {unexpected}", file=sys.stderr)
|
| 194 |
+
|
| 195 |
+
model.to(DEVICE, dtype=DTYPE)
|
| 196 |
+
model.eval()
|
| 197 |
+
|
| 198 |
+
name = package.get("Name", "QED-Base-v3") if isinstance(package, dict) else "QED-Base-v3"
|
| 199 |
+
author = package.get("Author", "unknown") if isinstance(package, dict) else "unknown"
|
| 200 |
+
print(f"Loaded {name} by {author} on {DEVICE} ({DTYPE})", file=sys.stderr)
|
| 201 |
+
return model
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def load_tokenizer(tokenizer_path: str) -> spm.SentencePieceProcessor:
|
| 205 |
+
if not Path(tokenizer_path).exists():
|
| 206 |
+
raise FileNotFoundError(f"Tokenizer not found: {tokenizer_path}")
|
| 207 |
+
tok = spm.SentencePieceProcessor()
|
| 208 |
+
tok.load(tokenizer_path)
|
| 209 |
+
return tok
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _apply_repetition_penalty(logits: torch.Tensor, generated: torch.Tensor, penalty: float):
|
| 213 |
+
if penalty == 1.0:
|
| 214 |
+
return logits
|
| 215 |
+
for b in range(logits.shape[0]):
|
| 216 |
+
seen = torch.unique(generated[b])
|
| 217 |
+
vals = logits[b, seen]
|
| 218 |
+
logits[b, seen] = torch.where(vals > 0, vals / penalty, vals * penalty)
|
| 219 |
+
return logits
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _top_k_top_p_filter(logits: torch.Tensor, top_k: int, top_p: float):
|
| 223 |
+
if top_k > 0:
|
| 224 |
+
top_k = min(top_k, logits.size(-1))
|
| 225 |
+
kth_val = torch.topk(logits, top_k, dim=-1).values[..., -1, None]
|
| 226 |
+
logits = torch.where(logits < kth_val, torch.full_like(logits, float("-inf")), logits)
|
| 227 |
+
|
| 228 |
+
if top_p < 1.0:
|
| 229 |
+
sorted_logits, sorted_idx = torch.sort(logits, descending=True, dim=-1)
|
| 230 |
+
probs = F.softmax(sorted_logits, dim=-1)
|
| 231 |
+
cum_probs = torch.cumsum(probs, dim=-1)
|
| 232 |
+
|
| 233 |
+
remove = cum_probs > top_p
|
| 234 |
+
remove[..., 1:] = remove[..., :-1].clone()
|
| 235 |
+
remove[..., 0] = False
|
| 236 |
+
|
| 237 |
+
sorted_logits[remove] = float("-inf")
|
| 238 |
+
logits = torch.full_like(logits, float("-inf")).scatter(-1, sorted_idx, sorted_logits)
|
| 239 |
+
|
| 240 |
+
return logits
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@torch.no_grad()
|
| 244 |
+
def generate_stream(
|
| 245 |
+
model: QEDBaseV3,
|
| 246 |
+
tokenizer: spm.SentencePieceProcessor,
|
| 247 |
+
prompts: list[str],
|
| 248 |
+
max_new_tokens: int = 200,
|
| 249 |
+
temperature: float = 0.8,
|
| 250 |
+
top_k: int = 50,
|
| 251 |
+
top_p: float = 0.95,
|
| 252 |
+
repetition_penalty: float = 1.15,
|
| 253 |
+
eos_id: Optional[int] = None,
|
| 254 |
+
seed: Optional[int] = None,
|
| 255 |
+
) -> Iterator[list[str]]:
|
| 256 |
+
if seed is not None:
|
| 257 |
+
torch.manual_seed(seed)
|
| 258 |
+
|
| 259 |
+
if eos_id is None:
|
| 260 |
+
eos_id = tokenizer.eos_id() if tokenizer.eos_id() >= 0 else None
|
| 261 |
+
|
| 262 |
+
encoded = [tokenizer.encode(p) for p in prompts]
|
| 263 |
+
max_len = max(len(e) for e in encoded)
|
| 264 |
+
pad_id = tokenizer.pad_id() if tokenizer.pad_id() >= 0 else 0
|
| 265 |
+
|
| 266 |
+
B = len(prompts)
|
| 267 |
+
input_ids = torch.full((B, max_len), pad_id, dtype=torch.long, device=DEVICE)
|
| 268 |
+
for i, e in enumerate(encoded):
|
| 269 |
+
input_ids[i, max_len - len(e):] = torch.tensor(e, dtype=torch.long, device=DEVICE)
|
| 270 |
+
|
| 271 |
+
generated = input_ids.clone()
|
| 272 |
+
finished = torch.zeros(B, dtype=torch.bool, device=DEVICE)
|
| 273 |
+
text_so_far = ["" for _ in range(B)]
|
| 274 |
+
|
| 275 |
+
logits, past = model(input_ids, offset=0)
|
| 276 |
+
offset = input_ids.shape[1]
|
| 277 |
+
|
| 278 |
+
for _ in range(max_new_tokens):
|
| 279 |
+
next_logits = logits[:, -1, :].float()
|
| 280 |
+
next_logits = _apply_repetition_penalty(next_logits, generated, repetition_penalty)
|
| 281 |
+
|
| 282 |
+
if temperature <= 0:
|
| 283 |
+
next_token = next_logits.argmax(dim=-1, keepdim=True)
|
| 284 |
+
else:
|
| 285 |
+
next_logits = next_logits / temperature
|
| 286 |
+
next_logits = _top_k_top_p_filter(next_logits, top_k, top_p)
|
| 287 |
+
probs = F.softmax(next_logits, dim=-1)
|
| 288 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 289 |
+
|
| 290 |
+
next_token = torch.where(
|
| 291 |
+
finished.unsqueeze(-1), torch.full_like(next_token, pad_id), next_token
|
| 292 |
+
)
|
| 293 |
+
generated = torch.cat([generated, next_token], dim=1)
|
| 294 |
+
|
| 295 |
+
if eos_id is not None:
|
| 296 |
+
finished |= next_token.squeeze(-1) == eos_id
|
| 297 |
+
|
| 298 |
+
for i in range(B):
|
| 299 |
+
if not finished[i]:
|
| 300 |
+
text_so_far[i] = tokenizer.decode(generated[i].tolist())
|
| 301 |
+
|
| 302 |
+
yield list(text_so_far)
|
| 303 |
+
|
| 304 |
+
if bool(finished.all()):
|
| 305 |
+
break
|
| 306 |
+
|
| 307 |
+
logits, past = model(next_token, offset=offset, past_key_values=past)
|
| 308 |
+
offset += 1
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@torch.no_grad()
|
| 312 |
+
def run(
|
| 313 |
+
prompt: str,
|
| 314 |
+
model: QEDBaseV3,
|
| 315 |
+
tokenizer: spm.SentencePieceProcessor,
|
| 316 |
+
max_new_tokens: int = 200,
|
| 317 |
+
temperature: float = 0.7,
|
| 318 |
+
top_k: int = 40,
|
| 319 |
+
top_p: float = 0.95,
|
| 320 |
+
repetition_penalty: float = 1.15,
|
| 321 |
+
seed: Optional[int] = None,
|
| 322 |
+
) -> str:
|
| 323 |
+
final = ""
|
| 324 |
+
for texts in generate_stream(
|
| 325 |
+
model, tokenizer, [prompt],
|
| 326 |
+
max_new_tokens=max_new_tokens,
|
| 327 |
+
temperature=temperature,
|
| 328 |
+
top_k=top_k,
|
| 329 |
+
top_p=top_p,
|
| 330 |
+
repetition_penalty=repetition_penalty,
|
| 331 |
+
seed=seed,
|
| 332 |
+
):
|
| 333 |
+
final = texts[0]
|
| 334 |
+
return final
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _print_help():
|
| 338 |
+
print(
|
| 339 |
+
"commands:\n"
|
| 340 |
+
" <text> generate from this prompt\n"
|
| 341 |
+
" /temp <float> set temperature (0 = greedy)\n"
|
| 342 |
+
" /top_k <int> set top-k (0 = disabled)\n"
|
| 343 |
+
" /top_p <float> set top-p\n"
|
| 344 |
+
" /rep <float> set repetition penalty\n"
|
| 345 |
+
" /tokens <int> set max new tokens\n"
|
| 346 |
+
" /seed <int|none> fix or clear the random seed\n"
|
| 347 |
+
" /help show this message\n"
|
| 348 |
+
" /quit, /exit leave"
|
| 349 |
+
, file=sys.stderr)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _repl():
|
| 353 |
+
checkpoint_path = Path(DEFAULT_CHECKPOINT)
|
| 354 |
+
tokenizer_path = Path(DEFAULT_TOKENIZER)
|
| 355 |
+
|
| 356 |
+
if not checkpoint_path.exists():
|
| 357 |
+
print(f"error: checkpoint not found at {checkpoint_path}", file=sys.stderr)
|
| 358 |
+
sys.exit(1)
|
| 359 |
+
if not tokenizer_path.exists():
|
| 360 |
+
print(f"error: tokenizer not found at {tokenizer_path}", file=sys.stderr)
|
| 361 |
+
sys.exit(1)
|
| 362 |
+
|
| 363 |
+
model = load_model(str(checkpoint_path))
|
| 364 |
+
tokenizer = load_tokenizer(str(tokenizer_path))
|
| 365 |
+
|
| 366 |
+
settings = {
|
| 367 |
+
"max_new_tokens": 200,
|
| 368 |
+
"temperature": 0.7,
|
| 369 |
+
"top_k": 40,
|
| 370 |
+
"top_p": 0.95,
|
| 371 |
+
"repetition_penalty": 1.15,
|
| 372 |
+
"seed": None,
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
_print_help()
|
| 376 |
+
print(file=sys.stderr)
|
| 377 |
+
|
| 378 |
+
while True:
|
| 379 |
+
try:
|
| 380 |
+
line = input(">>> ")
|
| 381 |
+
except (EOFError, KeyboardInterrupt):
|
| 382 |
+
print(file=sys.stderr)
|
| 383 |
+
break
|
| 384 |
+
|
| 385 |
+
line = line.strip()
|
| 386 |
+
if not line:
|
| 387 |
+
continue
|
| 388 |
+
|
| 389 |
+
if line in ("/quit", "/exit"):
|
| 390 |
+
break
|
| 391 |
+
if line == "/help":
|
| 392 |
+
_print_help()
|
| 393 |
+
continue
|
| 394 |
+
if line.startswith("/temp "):
|
| 395 |
+
settings["temperature"] = float(line.split(maxsplit=1)[1])
|
| 396 |
+
print(f"temperature set to {settings['temperature']}", file=sys.stderr)
|
| 397 |
+
continue
|
| 398 |
+
if line.startswith("/top_k "):
|
| 399 |
+
settings["top_k"] = int(line.split(maxsplit=1)[1])
|
| 400 |
+
print(f"top_k set to {settings['top_k']}", file=sys.stderr)
|
| 401 |
+
continue
|
| 402 |
+
if line.startswith("/top_p "):
|
| 403 |
+
settings["top_p"] = float(line.split(maxsplit=1)[1])
|
| 404 |
+
print(f"top_p set to {settings['top_p']}", file=sys.stderr)
|
| 405 |
+
continue
|
| 406 |
+
if line.startswith("/rep "):
|
| 407 |
+
settings["repetition_penalty"] = float(line.split(maxsplit=1)[1])
|
| 408 |
+
print(f"repetition_penalty set to {settings['repetition_penalty']}", file=sys.stderr)
|
| 409 |
+
continue
|
| 410 |
+
if line.startswith("/tokens "):
|
| 411 |
+
settings["max_new_tokens"] = int(line.split(maxsplit=1)[1])
|
| 412 |
+
print(f"max_new_tokens set to {settings['max_new_tokens']}", file=sys.stderr)
|
| 413 |
+
continue
|
| 414 |
+
if line.startswith("/seed "):
|
| 415 |
+
value = line.split(maxsplit=1)[1].strip()
|
| 416 |
+
settings["seed"] = None if value.lower() == "none" else int(value)
|
| 417 |
+
print(f"seed set to {settings['seed']}", file=sys.stderr)
|
| 418 |
+
continue
|
| 419 |
+
if line.startswith("/"):
|
| 420 |
+
print(f"unknown command: {line}", file=sys.stderr)
|
| 421 |
+
continue
|
| 422 |
+
|
| 423 |
+
try:
|
| 424 |
+
output = run(line, model, tokenizer, **settings)
|
| 425 |
+
except Exception as e:
|
| 426 |
+
print(f"error during generation: {e}", file=sys.stderr)
|
| 427 |
+
continue
|
| 428 |
+
|
| 429 |
+
print(output)
|
| 430 |
+
print(file=sys.stderr)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
if __name__ == "__main__":
|
| 434 |
+
_repl()
|