sz14 commited on
Commit
f2daba0
·
verified ·
1 Parent(s): 0a0d80c

Optimize CUDA graph inference

Browse files
Files changed (1) hide show
  1. modeling_rrt.py +119 -42
modeling_rrt.py CHANGED
@@ -280,6 +280,18 @@ class KVCache:
280
  "Build a fresh cache per batch."
281
  )
282
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  if self.static:
284
  if self.k[i] is None:
285
  shape = (*k.shape[:2], self.max_seq, k.shape[3])
@@ -572,14 +584,12 @@ class Attn(nn.Module):
572
  v = v * scale
573
  q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
574
  else:
575
- q = self.qn(
576
- self.q(x, ai).view(B, Tq, H, Dh),
577
- optimized=optimized and self.cfg.native_rmsnorm,
578
- ).transpose(1, 2)
579
- k = self.kn(
580
- self.k(x, ai).view(B, Tq, Hk, Dh),
581
- optimized=optimized and self.cfg.native_rmsnorm,
582
- ).transpose(1, 2)
583
  v = self.v(x, ai).view(B, Tq, Hk, Dh).transpose(1, 2)
584
  if use_rope:
585
  q = rope_at(q, cos, sin, pos, prepared=rope_prepared)
@@ -1027,18 +1037,24 @@ class RRTForCausalLM(PreTrainedModel, GenerationMixin):
1027
  self.core.cfg.kernel_mode = "optimized"
1028
  return self.eval()
1029
 
1030
- def build_cuda_graph_runner(self, prompt_tokens, max_new_tokens, batch_size=1):
 
 
1031
  """Build a reusable fixed-shape FP32 greedy decoder.
1032
 
1033
  This is an inference wrapper only: it neither replaces nor merges any
1034
  parameters. Runners are keyed by prompt length, output length, and batch
1035
- size, and must be rebuilt after training changes parameter versions.
 
 
 
1036
  """
1037
  return FP32CUDAGraphRunner(
1038
  self,
1039
  prompt_tokens=prompt_tokens,
1040
  max_new_tokens=max_new_tokens,
1041
  batch_size=batch_size,
 
1042
  )
1043
 
1044
  def use_reference_kernels(self):
@@ -1113,8 +1129,7 @@ class RRTForCausalLM(PreTrainedModel, GenerationMixin):
1113
  out = {"input_ids": input_ids[:, -ms:], "use_cache": False}
1114
  if attention_mask is not None:
1115
  out["attention_mask"] = attention_mask[:, -ms:]
1116
- if "logits_to_keep" in kwargs:
1117
- out["logits_to_keep"] = kwargs["logits_to_keep"]
1118
  return out
1119
 
1120
  if past_key_values is None:
@@ -1131,8 +1146,7 @@ class RRTForCausalLM(PreTrainedModel, GenerationMixin):
1131
  out = {"input_ids": ids, "past_key_values": past_key_values, "use_cache": True}
1132
  if attention_mask is not None:
1133
  out["attention_mask"] = attention_mask
1134
- if "logits_to_keep" in kwargs:
1135
- out["logits_to_keep"] = kwargs["logits_to_keep"]
1136
  return out
1137
 
1138
  def _reorder_cache(self, past_key_values, beam_idx):
@@ -1143,6 +1157,10 @@ class RRTForCausalLM(PreTrainedModel, GenerationMixin):
1143
  top_k=50, greedy=False, cache=None):
1144
  """Incremental decode over the recursion-wise cache. Standalone by design:
1145
  it does not touch transformers' generation machinery."""
 
 
 
 
1146
  self.eval()
1147
  dev = next(self.parameters()).device
1148
  ids = tokenizer(prompt, return_tensors="pt").input_ids.to(dev)
@@ -1151,8 +1169,8 @@ class RRTForCausalLM(PreTrainedModel, GenerationMixin):
1151
  max_seq=min(self.config.max_seq, ids.shape[1] + max_new),
1152
  )
1153
  outs = []
1154
- lg = self(input_ids=ids, past_key_values=cache).logits[:, -1].float()
1155
- for _ in range(max_new):
1156
  if greedy or temperature <= 0:
1157
  nxt = lg.argmax(-1, keepdim=True)
1158
  else:
@@ -1161,12 +1179,17 @@ class RRTForCausalLM(PreTrainedModel, GenerationMixin):
1161
  kth = l.topk(min(top_k, l.size(-1)), dim=-1).values[..., -1:]
1162
  l = l.masked_fill(l < kth, float("-inf"))
1163
  nxt = torch.multinomial(l.softmax(-1), 1)
1164
- if tokenizer.eos_token_id is not None and nxt.item() == tokenizer.eos_token_id:
 
 
 
1165
  break
1166
- outs.append(nxt.item())
1167
- if cache.pos >= self.config.max_seq:
1168
  break
1169
- lg = self(input_ids=nxt, past_key_values=cache).logits[:, -1].float()
 
 
1170
  return prompt + tokenizer.decode(outs)
1171
 
1172
 
@@ -1178,12 +1201,16 @@ class FP32CUDAGraphRunner:
1178
  """
1179
 
1180
  @torch.inference_mode()
1181
- def __init__(self, model, prompt_tokens, max_new_tokens, batch_size=1):
 
 
1182
  if not torch.cuda.is_available():
1183
  raise RuntimeError("FP32CUDAGraphRunner requires CUDA")
1184
  parameter = next(model.parameters())
1185
  if parameter.device.type != "cuda" or parameter.dtype != torch.float32:
1186
  raise ValueError("FP32CUDAGraphRunner requires a CUDA FP32 model")
 
 
1187
  if prompt_tokens <= 0 or max_new_tokens <= 0 or batch_size <= 0:
1188
  raise ValueError("prompt_tokens, max_new_tokens, and batch_size must be positive")
1189
  if prompt_tokens + max_new_tokens > model.config.max_seq:
@@ -1196,6 +1223,7 @@ class FP32CUDAGraphRunner:
1196
  self.prompt_tokens = int(prompt_tokens)
1197
  self.max_new_tokens = int(max_new_tokens)
1198
  self.batch_size = int(batch_size)
 
1199
  self.capacity = self.prompt_tokens + self.max_new_tokens
1200
  device = parameter.device
1201
  dummy = torch.ones(
@@ -1207,10 +1235,15 @@ class FP32CUDAGraphRunner:
1207
  warm_cache = self.model.new_cache(
1208
  batch=self.batch_size, max_seq=self.capacity, static=True
1209
  )
1210
- token = self._prefill(dummy, warm_cache)
1211
- for _ in range(1, self.max_new_tokens):
1212
- token = self._decode(token, warm_cache)
1213
- torch.cuda.synchronize()
 
 
 
 
 
1214
  del warm_cache, token
1215
 
1216
  self.cache = self.model.new_cache(
@@ -1218,24 +1251,57 @@ class FP32CUDAGraphRunner:
1218
  )
1219
  first_token = self._prefill(dummy, self.cache)
1220
  self.static_first_token = first_token.clone()
 
1221
  self.generated = torch.empty(
1222
  (self.batch_size, self.max_new_tokens),
1223
  dtype=torch.long,
1224
  device=device,
1225
  )
1226
  self.generated[:, 0].copy_(first_token[:, 0])
1227
- torch.cuda.synchronize()
1228
 
1229
  self.graph = None
1230
- if self.max_new_tokens > 1:
1231
- self.graph = torch.cuda.CUDAGraph()
1232
- with torch.cuda.graph(self.graph):
1233
- token = self.static_first_token
1234
- for step in range(1, self.max_new_tokens):
1235
- token = self._decode(token, self.cache)
1236
- self.generated[:, step].copy_(token[:, 0])
1237
- torch.cuda.synchronize()
1238
- self._parameter_versions = tuple(p._version for p in self.model.parameters())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1239
 
1240
  def _prefill(self, input_ids, cache):
1241
  logits = self.model(
@@ -1258,13 +1324,21 @@ class FP32CUDAGraphRunner:
1258
  def _validate_model(self):
1259
  if self.model.training or torch.is_grad_enabled():
1260
  raise RuntimeError("CUDA graph runners are inference-only; call under inference_mode")
1261
- versions = tuple(p._version for p in self.model.parameters())
1262
- if versions != self._parameter_versions:
1263
  raise RuntimeError("model parameters changed; rebuild the CUDA graph runner")
 
 
 
 
1264
 
1265
  @torch.inference_mode()
1266
  def generate(self, input_ids, clone=True):
1267
- """Generate from an exact-shape, unpadded CUDA token tensor."""
 
 
 
 
 
1268
  self._validate_model()
1269
  expected = (self.batch_size, self.prompt_tokens)
1270
  if tuple(input_ids.shape) != expected:
@@ -1272,10 +1346,13 @@ class FP32CUDAGraphRunner:
1272
  if input_ids.device != self.generated.device or input_ids.dtype != torch.long:
1273
  raise ValueError("input_ids must be a CUDA torch.long tensor on the model device")
1274
 
1275
- self.cache.reset()
1276
- first_token = self._prefill(input_ids, self.cache)
1277
- self.static_first_token.copy_(first_token)
1278
- self.generated[:, 0].copy_(first_token[:, 0])
 
 
 
1279
  if self.graph is not None:
1280
  self.graph.replay()
1281
  self.cache.pos = self.prompt_tokens + self.max_new_tokens - 1
 
280
  "Build a fresh cache per batch."
281
  )
282
 
283
+ # Autocast can produce BF16/FP16 K/V from FP32 parameters. The
284
+ # preallocation uses parameter dtype, so replace empty storage on
285
+ # first use instead of silently upcasting K/V (which breaks SDPA).
286
+ mismatch = self.k[i] is not None and (
287
+ self.k[i].dtype != k.dtype or self.v[i].dtype != v.dtype
288
+ or self.k[i].device != k.device or self.v[i].device != v.device
289
+ )
290
+ if mismatch:
291
+ if self.pos:
292
+ raise ValueError("KV cache dtype/device changed mid-decode; build a fresh cache")
293
+ self.k[i] = self.v[i] = None
294
+
295
  if self.static:
296
  if self.k[i] is None:
297
  shape = (*k.shape[:2], self.max_seq, k.shape[3])
 
584
  v = v * scale
585
  q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
586
  else:
587
+ q = self.q(x, ai).view(B, Tq, H, Dh)
588
+ k = self.k(x, ai).view(B, Tq, Hk, Dh)
589
+ if self.cfg.use_qk_norm:
590
+ q = self.qn(q, optimized=optimized and self.cfg.native_rmsnorm)
591
+ k = self.kn(k, optimized=optimized and self.cfg.native_rmsnorm)
592
+ q, k = q.transpose(1, 2), k.transpose(1, 2)
 
 
593
  v = self.v(x, ai).view(B, Tq, Hk, Dh).transpose(1, 2)
594
  if use_rope:
595
  q = rope_at(q, cos, sin, pos, prepared=rope_prepared)
 
1037
  self.core.cfg.kernel_mode = "optimized"
1038
  return self.eval()
1039
 
1040
+ def build_cuda_graph_runner(
1041
+ self, prompt_tokens, max_new_tokens, batch_size=1, *, capture_prefill=True,
1042
+ ):
1043
  """Build a reusable fixed-shape FP32 greedy decoder.
1044
 
1045
  This is an inference wrapper only: it neither replaces nor merges any
1046
  parameters. Runners are keyed by prompt length, output length, and batch
1047
+ size, and must be rebuilt after training or changing kernel settings.
1048
+ By default the prompt forward is captured too, removing Python/kernel
1049
+ launch overhead for the whole request. Set capture_prefill=False to
1050
+ retain eager prompt processing with a captured decode loop.
1051
  """
1052
  return FP32CUDAGraphRunner(
1053
  self,
1054
  prompt_tokens=prompt_tokens,
1055
  max_new_tokens=max_new_tokens,
1056
  batch_size=batch_size,
1057
+ capture_prefill=capture_prefill,
1058
  )
1059
 
1060
  def use_reference_kernels(self):
 
1129
  out = {"input_ids": input_ids[:, -ms:], "use_cache": False}
1130
  if attention_mask is not None:
1131
  out["attention_mask"] = attention_mask[:, -ms:]
1132
+ out["logits_to_keep"] = kwargs.get("logits_to_keep", 1)
 
1133
  return out
1134
 
1135
  if past_key_values is None:
 
1146
  out = {"input_ids": ids, "past_key_values": past_key_values, "use_cache": True}
1147
  if attention_mask is not None:
1148
  out["attention_mask"] = attention_mask
1149
+ out["logits_to_keep"] = kwargs.get("logits_to_keep", 1)
 
1150
  return out
1151
 
1152
  def _reorder_cache(self, past_key_values, beam_idx):
 
1157
  top_k=50, greedy=False, cache=None):
1158
  """Incremental decode over the recursion-wise cache. Standalone by design:
1159
  it does not touch transformers' generation machinery."""
1160
+ if max_new < 0:
1161
+ raise ValueError("max_new must be nonnegative")
1162
+ if max_new == 0:
1163
+ return prompt
1164
  self.eval()
1165
  dev = next(self.parameters()).device
1166
  ids = tokenizer(prompt, return_tensors="pt").input_ids.to(dev)
 
1169
  max_seq=min(self.config.max_seq, ids.shape[1] + max_new),
1170
  )
1171
  outs = []
1172
+ lg = self(input_ids=ids, past_key_values=cache, logits_to_keep=1).logits[:, -1].float()
1173
+ for step in range(max_new):
1174
  if greedy or temperature <= 0:
1175
  nxt = lg.argmax(-1, keepdim=True)
1176
  else:
 
1179
  kth = l.topk(min(top_k, l.size(-1)), dim=-1).values[..., -1:]
1180
  l = l.masked_fill(l < kth, float("-inf"))
1181
  nxt = torch.multinomial(l.softmax(-1), 1)
1182
+ # Exactly one device-to-host synchronization per token when EOS
1183
+ # stopping is needed. Without EOS, transfer the output just once.
1184
+ token_id = nxt.item() if tokenizer.eos_token_id is not None else None
1185
+ if token_id is not None and token_id == tokenizer.eos_token_id:
1186
  break
1187
+ outs.append(token_id if token_id is not None else nxt)
1188
+ if step + 1 == max_new or cache.pos >= self.config.max_seq:
1189
  break
1190
+ lg = self(input_ids=nxt, past_key_values=cache, logits_to_keep=1).logits[:, -1].float()
1191
+ if tokenizer.eos_token_id is None and outs:
1192
+ outs = torch.cat(outs, dim=1)[0].tolist()
1193
  return prompt + tokenizer.decode(outs)
1194
 
1195
 
 
1201
  """
1202
 
1203
  @torch.inference_mode()
1204
+ def __init__(
1205
+ self, model, prompt_tokens, max_new_tokens, batch_size=1, *, capture_prefill=True,
1206
+ ):
1207
  if not torch.cuda.is_available():
1208
  raise RuntimeError("FP32CUDAGraphRunner requires CUDA")
1209
  parameter = next(model.parameters())
1210
  if parameter.device.type != "cuda" or parameter.dtype != torch.float32:
1211
  raise ValueError("FP32CUDAGraphRunner requires a CUDA FP32 model")
1212
+ if torch.is_autocast_enabled("cuda"):
1213
+ raise ValueError("FP32CUDAGraphRunner must be built with CUDA autocast disabled")
1214
  if prompt_tokens <= 0 or max_new_tokens <= 0 or batch_size <= 0:
1215
  raise ValueError("prompt_tokens, max_new_tokens, and batch_size must be positive")
1216
  if prompt_tokens + max_new_tokens > model.config.max_seq:
 
1223
  self.prompt_tokens = int(prompt_tokens)
1224
  self.max_new_tokens = int(max_new_tokens)
1225
  self.batch_size = int(batch_size)
1226
+ self.capture_prefill = bool(capture_prefill)
1227
  self.capacity = self.prompt_tokens + self.max_new_tokens
1228
  device = parameter.device
1229
  dummy = torch.ones(
 
1235
  warm_cache = self.model.new_cache(
1236
  batch=self.batch_size, max_seq=self.capacity, static=True
1237
  )
1238
+ # PyTorch requires warmup on a side stream before graph capture.
1239
+ stream = torch.cuda.Stream(device=device)
1240
+ stream.wait_stream(torch.cuda.current_stream(device))
1241
+ with torch.cuda.stream(stream):
1242
+ token = self._prefill(dummy, warm_cache)
1243
+ for _ in range(1, self.max_new_tokens):
1244
+ token = self._decode(token, warm_cache)
1245
+ torch.cuda.current_stream(device).wait_stream(stream)
1246
+ torch.cuda.synchronize(device)
1247
  del warm_cache, token
1248
 
1249
  self.cache = self.model.new_cache(
 
1251
  )
1252
  first_token = self._prefill(dummy, self.cache)
1253
  self.static_first_token = first_token.clone()
1254
+ self.static_input_ids = dummy.clone() if self.capture_prefill else None
1255
  self.generated = torch.empty(
1256
  (self.batch_size, self.max_new_tokens),
1257
  dtype=torch.long,
1258
  device=device,
1259
  )
1260
  self.generated[:, 0].copy_(first_token[:, 0])
1261
+ torch.cuda.synchronize(device)
1262
 
1263
  self.graph = None
1264
+ if self.capture_prefill or self.max_new_tokens > 1:
1265
+ if self.capture_prefill:
1266
+ self.cache.reset()
1267
+ with torch.cuda.device(device):
1268
+ self.graph = torch.cuda.CUDAGraph()
1269
+ with torch.cuda.graph(self.graph, stream=stream):
1270
+ if self.capture_prefill:
1271
+ token = self._prefill(self.static_input_ids, self.cache)
1272
+ self.generated[:, 0].copy_(token[:, 0])
1273
+ else:
1274
+ token = self.static_first_token
1275
+ for step in range(1, self.max_new_tokens):
1276
+ token = self._decode(token, self.cache)
1277
+ self.generated[:, step].copy_(token[:, 0])
1278
+ torch.cuda.synchronize(device)
1279
+ self._parameter_signature = self._parameters_signature()
1280
+ self._captured_settings = self._settings_signature()
1281
+
1282
+ def _parameters_signature(self):
1283
+ # CUDA graphs bind storage addresses. Version counters alone miss
1284
+ # Parameter replacement, .data replacement, and dtype/device moves.
1285
+ return tuple(
1286
+ (id(p), p.data_ptr(), p._version, p.device, p.dtype)
1287
+ for p in self.model.parameters()
1288
+ )
1289
+
1290
+ def _settings_signature(self):
1291
+ fields = (
1292
+ "kernel_mode", "native_gqa", "native_rmsnorm", "precompute_rope",
1293
+ "fp32_gqa_decode", "packed_projections", "flashnorm", "flashnorm_qk_cancel",
1294
+ "use_qk_norm", "rope_theta", "max_seq", "norm_eps", "n_recursion",
1295
+ "prelude", "coda", "block_layers", "nope_block_layers", "lora_recursions",
1296
+ "residual_gains", "residual_gain_layout",
1297
+ )
1298
+ return (
1299
+ tuple(getattr(self.model.config, name) for name in fields),
1300
+ tuple(getattr(self.model.core.cfg, name) for name in fields),
1301
+ torch.get_float32_matmul_precision(),
1302
+ torch.backends.cuda.matmul.allow_tf32,
1303
+ id(self.model.core._cos), id(self.model.core._sin),
1304
+ )
1305
 
1306
  def _prefill(self, input_ids, cache):
1307
  logits = self.model(
 
1324
  def _validate_model(self):
1325
  if self.model.training or torch.is_grad_enabled():
1326
  raise RuntimeError("CUDA graph runners are inference-only; call under inference_mode")
1327
+ if self._parameters_signature() != self._parameter_signature:
 
1328
  raise RuntimeError("model parameters changed; rebuild the CUDA graph runner")
1329
+ if self._settings_signature() != self._captured_settings:
1330
+ raise RuntimeError("model execution settings changed; rebuild the CUDA graph runner")
1331
+ if torch.is_autocast_enabled("cuda"):
1332
+ raise RuntimeError("FP32CUDAGraphRunner requires CUDA autocast disabled")
1333
 
1334
  @torch.inference_mode()
1335
  def generate(self, input_ids, clone=True):
1336
+ """Generate exactly max_new_tokens from an unpadded CUDA token tensor.
1337
+
1338
+ This greedy runner does not stop at EOS or apply generation processors.
1339
+ Reuse it for sequential requests of the captured shape. clone=False
1340
+ returns shared storage that is overwritten on the next request.
1341
+ """
1342
  self._validate_model()
1343
  expected = (self.batch_size, self.prompt_tokens)
1344
  if tuple(input_ids.shape) != expected:
 
1346
  if input_ids.device != self.generated.device or input_ids.dtype != torch.long:
1347
  raise ValueError("input_ids must be a CUDA torch.long tensor on the model device")
1348
 
1349
+ if self.capture_prefill:
1350
+ self.static_input_ids.copy_(input_ids)
1351
+ else:
1352
+ self.cache.reset()
1353
+ first_token = self._prefill(input_ids, self.cache)
1354
+ self.static_first_token.copy_(first_token)
1355
+ self.generated[:, 0].copy_(first_token[:, 0])
1356
  if self.graph is not None:
1357
  self.graph.replay()
1358
  self.cache.pos = self.prompt_tokens + self.max_new_tokens - 1