File size: 20,383 Bytes
a70ca2a 2076d1f a70ca2a | 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | import torch
import torch.nn.functional as F
from typing import List, Optional, Dict, Tuple, Union
import math
import random
from tqdm import tqdm
from rosaplus import ROSAPlus, ROSAFallbackLM, ROSACharPredictor
class ROSACudaWrapper:
"""
CUDA-accelerated wrapper for ROSAPlus.
Optimized for batched inference using PyTorch.
"""
def __init__(self, model: ROSAPlus, device: Union[str, torch.device] = "cuda"):
if model.lm is None:
raise RuntimeError("ROSAPlus model must have a built LM before converting to CUDA.")
self.device = torch.device(device)
self.model = model
self.alphabet = model.lm.alphabet
self.char_to_idx = {ch: i for i, ch in enumerate(self.alphabet)}
self.idx_to_char = {i: ch for i, ch in enumerate(self.alphabet)}
self.vocab_size = len(self.alphabet)
# --- Convert SAM Graph to Tensors ---
print(f"Converting SAM graph to CUDA tensors on {self.device}...")
# 1. Suffix Links (c) and Max Length (d)
# Shape: [num_states]
self.c = torch.tensor(model.sam.c, dtype=torch.long, device=self.device)
self.d = torch.tensor(model.sam.d, dtype=torch.long, device=self.device)
# 2. Transitions (b)
# We try to use a dense tensor [num_states, vocab_size] if memory permits.
# Otherwise, we might need a sparse approach (not implemented in this v1).
num_states = len(model.sam.b)
self.num_states = num_states
print(f"Graph stats: {num_states} states, {self.vocab_size} vocab size.")
if num_states * self.vocab_size > 500_000_000: # heuristic limit (~2GB for int32)
print("WARNING: Graph is very large. Dense transition table might consume excessive GPU memory.")
# Initialize with -1 (no transition)
self.transitions = torch.full((num_states, self.vocab_size), -1, dtype=torch.long, device=self.device)
# Fill transitions
# This can be slow in Python, but it's a one-time cost.
# We construct it on CPU first then move to GPU.
b_cpu = torch.full((num_states, self.vocab_size), -1, dtype=torch.long)
for i, trans in enumerate(tqdm(model.sam.b, desc="Building transition table")):
for ch, next_state in trans.items():
if ch in self.char_to_idx:
b_cpu[i, self.char_to_idx[ch]] = next_state
self.transitions = b_cpu.to(self.device)
# 3. LM Counts (freq)
# We need N (total) and T (distinct) for Witten-Bell
# And the actual counts for probability distribution.
# counts_matrix: [num_states, vocab_size]
self.counts_matrix = torch.zeros((num_states, self.vocab_size), dtype=torch.float32, device="cpu")
for i, freq in enumerate(tqdm(model.lm.freq, desc="Building count table")):
for ch, cnt in freq.items():
if ch in self.char_to_idx:
self.counts_matrix[i, self.char_to_idx[ch]] = float(cnt)
self.counts_matrix = self.counts_matrix.to(self.device)
# Pre-compute N and T for Witten-Bell
self.N = self.counts_matrix.sum(dim=1) # [num_states]
self.T = (self.counts_matrix > 0).float().sum(dim=1) # [num_states]
# Unigram counts for fallback
self.unigram_counts = torch.zeros(self.vocab_size, dtype=torch.float32, device=self.device)
for ch, cnt in model.lm.unigram.items():
if ch in self.char_to_idx:
self.unigram_counts[self.char_to_idx[ch]] = float(cnt)
self.unigram_total = self.unigram_counts.sum()
self.max_order = model.max_order
if self.max_order is None:
self.max_order = int(1e9)
print("CUDA initialization complete.")
def _advance_batch(self, current_states: torch.Tensor, next_chars_idx: torch.Tensor) -> torch.Tensor:
"""
Advance states for a batch of characters.
current_states: [batch_size]
next_chars_idx: [batch_size]
Returns: [batch_size] next states
"""
# Look up transitions: transitions[state, char]
# Handle cases where transition doesn't exist (-1)
# We need to handle the case where current_state is -1 (shouldn't happen in valid traversal but good to be safe)
# or where next_chars_idx is padding. Assuming valid inputs for now.
next_states = self.transitions[current_states, next_chars_idx]
# If transition is -1, it means we fall off the graph from that state with that char.
# In the original code:
# while v != -1 and ch not in b[v]: v = c[v]
# if v == -1: return b[0].get(ch, 0)
# else: return b[v][ch]
# The simple lookup above is NOT sufficient because it doesn't follow suffix links on mismatch.
# We need to simulate the 'while' loop for mismatch handling.
# However, for *generation*, we usually sample from valid distributions, so the chosen char
# *should* have a transition if we sampled from the state's distribution?
# WAIT. The generated char might come from a fallback (shorter context).
# If we are at state S (context "ABC"), and we sample char 'X' which only exists in context "C" (parent of parent),
# then S does not have a transition for 'X'.
# We must follow suffix links to find the state that accepts 'X'.
# Correct logic for updating state v with char c:
# v_new = transition(v, c)
# If transition(v, c) exists, great.
# If not, v = suffix_link(v), retry.
# We can implement this "fallback search" in parallel.
active_mask = (next_states == -1)
curr = current_states.clone()
# Limit iterations to avoid infinite loops (though DAG shouldn't loop)
max_depth = 100 # heuristic
# Iterative fallback
for _ in range(max_depth):
if not active_mask.any():
break
# For active ones, move to suffix link
curr[active_mask] = self.c[curr[active_mask]]
# Check if we hit root's parent (-1)
root_parent_mask = (curr == -1) & active_mask
if root_parent_mask.any():
# If we fell off the root, we restart at root (0)
# And check if root has transition
# But wait, original code: if v == -1: return b[0].get(ch, 0)
# So effectively we try transition from 0.
# We can handle this by setting curr to 0 for these, getting transition, and marking done.
# But let's follow the standard logic:
# If curr becomes -1, we try to transition from 0.
pass
# Try transition again for active ones
# If curr is -1, lookup fails. We need to handle -1 index carefully.
# We can use a temporary tensor filled with -1.
valid_curr = curr.clone()
valid_curr[valid_curr == -1] = 0 # Safe lookup, result will be ignored if it was -1
new_trans = self.transitions[valid_curr, next_chars_idx]
# If curr was -1, the result is technically transition from 0?
# Original: if v == -1: return b[0].get(ch, 0)
# So if curr became -1, we take transition from 0.
# Let's handle the -1 case explicitly.
# Update next_states where active
# If curr != -1: try transition. If exists (!= -1), update next_states and deactivate.
# If curr == -1: take transition from 0. Update next_states and deactivate.
is_root_parent = (curr == -1)
# Case 1: curr != -1
mask_normal = active_mask & (~is_root_parent)
if mask_normal.any():
t = self.transitions[curr[mask_normal], next_chars_idx[mask_normal]]
found = (t != -1)
# Indices in the batch that found a match
found_indices = torch.nonzero(mask_normal).squeeze(1)[found]
next_states[found_indices] = t[found]
active_mask[found_indices] = False
# Case 2: curr == -1
mask_root = active_mask & is_root_parent
if mask_root.any():
# transition from 0
t = self.transitions[torch.zeros_like(curr[mask_root]), next_chars_idx[mask_root]]
# If t is -1 (even root doesn't have it), then next state is 0.
t[t == -1] = 0
indices = torch.nonzero(mask_root).squeeze(1)
next_states[indices] = t
active_mask[indices] = False
# For any remaining active (shouldn't happen often), default to 0
next_states[active_mask] = 0
return next_states
def get_probs_batch(self, current_states: torch.Tensor) -> torch.Tensor:
"""
Compute Witten-Bell smoothed probabilities for a batch of states.
Returns: [batch_size, vocab_size]
"""
batch_size = current_states.shape[0]
probs = torch.zeros((batch_size, self.vocab_size), device=self.device)
residual = torch.ones(batch_size, device=self.device) # The remaining probability mass
curr = current_states.clone()
active_mask = torch.ones(batch_size, dtype=torch.bool, device=self.device)
# We iterate up the suffix chain
# Ideally we loop until all active_mask is False
# But we can limit depth
max_depth = 100
for _ in range(max_depth):
if not active_mask.any():
break
# Apply max_order constraint
# If d[curr] > max_order, skip this node (move to parent) without collecting counts
# But we must still move up.
# Gather N and T for current states
# curr can be -1, handle safely
valid_mask = (curr != -1) & active_mask
if not valid_mask.any():
break
# For valid states:
batch_indices = torch.nonzero(valid_mask).squeeze(1)
states_v = curr[batch_indices]
# Check max_order
# If d[state] > max_order, we skip processing but set parent as next
d_v = self.d[states_v]
process_mask = (d_v <= self.max_order)
# Indices to actually process (add counts)
proc_indices = batch_indices[process_mask]
proc_states = states_v[process_mask]
if len(proc_states) > 0:
N_v = self.N[proc_states]
T_v = self.T[proc_states]
# Witten-Bell Lambda
# lam = N / (N + T)
# If T=0, lam = 1.0 (fully trust this, though N must be 0 too then?)
# If N=0, skip
has_counts = (N_v > 0)
# Only update where N > 0
final_proc_indices = proc_indices[has_counts]
final_proc_states = proc_states[has_counts]
if len(final_proc_states) > 0:
N_f = N_v[has_counts]
T_f = T_v[has_counts]
lam = N_f / (N_f + T_f + 1e-9)
# If T is 0, lam should be 1.0
lam[T_f == 0] = 1.0
# Update probs
# probs += residual * lam * (counts / N)
r = residual[final_proc_indices].unsqueeze(1) # [B, 1]
l = lam.unsqueeze(1) # [B, 1]
c = self.counts_matrix[final_proc_states] # [B, V]
n = N_f.unsqueeze(1) # [B, 1]
added_probs = r * l * (c / n)
probs[final_proc_indices] += added_probs
# Update residual
residual[final_proc_indices] *= (1.0 - lam)
# Move to parent
curr[batch_indices] = self.c[states_v]
# Update active mask (if curr becomes -1, stop for that item)
active_mask = active_mask & (curr != -1)
# Optimization: if residual is very small, stop
active_mask = active_mask & (residual > 1e-6)
# Unigram fallback
# probs += residual * (unigram / total_unigram)
if self.unigram_total > 0:
uni_probs = self.unigram_counts / self.unigram_total
probs += residual.unsqueeze(1) * uni_probs.unsqueeze(0)
else:
# Uniform fallback
probs += residual.unsqueeze(1) * (1.0 / self.vocab_size)
# Normalize (just in case)
sum_probs = probs.sum(dim=1, keepdim=True)
probs = probs / (sum_probs + 1e-12)
return probs
def generate_batch(
self,
prompts: List[str],
steps: int = 100,
temperature: float = 1.0,
top_p: float = 0.9,
top_k: int = 50,
seed: Optional[int] = None
) -> List[str]:
"""
Batched generation.
"""
if seed is not None:
torch.manual_seed(seed)
batch_size = len(prompts)
# Encode prompts
# We need to run the state machine for each prompt
# We can do this in parallel too, but lengths differ.
# Simple approach: Process one by one on CPU to get initial state, then batch.
# Or: Batch the prompt processing?
# Let's do batch prompt processing for speed.
# Pad prompts to max length?
# Actually, we can just feed chars step by step.
# 1. Initialize states to 0 (root)
current_states = torch.zeros(batch_size, dtype=torch.long, device=self.device)
# 2. Feed prompts
# Find max length
max_len = max(len(p) for p in prompts)
# Convert prompts to tensor [B, MaxLen], padded with some dummy (will be ignored by masking logic?)
# No, simpler: just iterate max_len times.
print("Processing prompts...")
for i in range(max_len):
# Construct input char indices for this step
# If prompt is shorter, we just don't update state?
# Or we keep feeding it?
# Actually, if prompt ended, we are ready.
# But we must reach the state corresponding to the FULL prompt.
chars = []
mask = [] # True if this index has a char
for p in prompts:
if i < len(p):
if p[i] in self.char_to_idx:
chars.append(self.char_to_idx[p[i]])
else:
chars.append(0) # unknown char placeholder
mask.append(True)
else:
chars.append(0)
mask.append(False)
chars_tensor = torch.tensor(chars, dtype=torch.long, device=self.device)
mask_tensor = torch.tensor(mask, dtype=torch.bool, device=self.device)
if mask_tensor.any():
# Only update states where mask is True
# We need a masked advance
active_states = current_states[mask_tensor]
active_chars = chars_tensor[mask_tensor]
new_states = self._advance_batch(active_states, active_chars)
current_states[mask_tensor] = new_states
# 3. Generation Loop
print(f"Generating {steps} steps for {batch_size} sequences...")
generated_indices = []
for _ in range(steps):
# Get probabilities
probs = self.get_probs_batch(current_states)
# Sampling
# Apply Temperature
if temperature != 1.0:
probs = torch.pow(probs, 1.0 / temperature)
probs = probs / probs.sum(dim=1, keepdim=True)
# Top-K
if top_k > 0:
vals, inds = torch.topk(probs, k=min(top_k, self.vocab_size), dim=1)
probs_topk = torch.zeros_like(probs)
probs_topk.scatter_(1, inds, vals)
probs = probs_topk / probs_topk.sum(dim=1, keepdim=True)
# Top-P (Nucleus) - Simplified implementation
# Sorting is expensive. If top_k is small, maybe skipped.
# PyTorch doesn't have native vectorized top-p easily without sorting.
if top_p < 1.0:
sorted_probs, sorted_indices = torch.sort(probs, descending=True, dim=1)
cumulative_probs = torch.cumsum(sorted_probs, dim=1)
# Remove tokens with cumulative probability above the threshold
sorted_indices_to_remove = cumulative_probs > top_p
# Shift the indices to the right to keep also the first token above the threshold
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
probs[indices_to_remove] = 0
probs = probs / probs.sum(dim=1, keepdim=True)
# Sample
next_chars = torch.multinomial(probs, num_samples=1).squeeze(1)
generated_indices.append(next_chars.cpu())
# Advance state
current_states = self._advance_batch(current_states, next_chars)
# 4. Decode
outputs = []
generated_indices = torch.stack(generated_indices, dim=1) # [B, Steps]
for i in range(batch_size):
indices = generated_indices[i].tolist()
text = "".join([self.idx_to_char.get(idx, "") for idx in indices])
outputs.append(text)
return outputs
# Helper to easily use the CUDA wrapper
def run_cuda_inference(model_path: str, prompts: List[str], steps=100, device="cuda"):
"""
Load a model, convert to CUDA, and run batched inference.
"""
print(f"Loading model from {model_path}...")
model = ROSAPlus.load(model_path)
cuda_model = ROSACudaWrapper(model, device=device)
results = cuda_model.generate_batch(prompts, steps=steps)
return results
if __name__ == "__main__":
from rosaplus import ROSAPlus
# from rosaplus_cuda import run_cuda_inference, ROSACudaWrapper
# 1. 加载原有模型
model = ROSAPlus.load("rosa-model.json")
# 2. 转换为 CUDA 加速版
cuda_model = ROSACudaWrapper(model, device="cuda")
# 3. 批量生成
prompts = ["The sky is", "Once upon a time", "Hello world"]
results = cuda_model.generate_batch(prompts, steps=200, temperature=0.8)
for p, r in zip(prompts, results):
print(f"{p} -> {r}")
# Example usage
import sys
if len(sys.argv) > 1:
model_file = sys.argv[1]
prompts = ["The meaning of life is", "Once upon a time"]
results = run_cuda_inference(model_file, prompts)
for p, r in zip(prompts, results):
print(f"Prompt: {p}")
print(f"Result: {r}")
print("-" * 20)
|