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