"""Capture V4's native 15-codebook predictor loop; keep its sampling settings. Uses the StaticCache + CUDA Graph strategy documented by https://github.com/andimarafioti/faster-qwen3-tts (MIT). This implementation targets V4/qwen-tts 0.1.1 / Transformers 4.57.3. """ import torch from transformers.cache_utils import StaticCache class PredictorCache(StaticCache): """Fixed storage, but expose the exact active length in each unrolled step. Unlike a padded static attention mask, these views preserve the baseline SDPA shapes and mask-free kernels; the predictor always has 2..16 tokens. """ active_length = 2 def update(self, key_states, value_states, layer_idx, cache_kwargs=None): key, value = super().update(key_states, value_states, layer_idx, cache_kwargs) return key[:, :, :self.active_length], value[:, :, :self.active_length] class ResidualGraph: def __init__(self, engine, sampling): self.engine = engine self.p = engine.predictor self.sampling = dict(sampling) parameter = next(self.p.parameters()) self.device, self.dtype = parameter.device, parameter.dtype self.cache = PredictorCache(config=self.p.config, max_cache_len=16) self.positions = [torch.arange(2, device=self.device)] + [ torch.tensor([j + 1], device=self.device) for j in range(1, 15)] self.token = torch.zeros((), dtype=torch.long, device=self.device) self.hidden = torch.zeros(1, 1, engine.talker.config.hidden_size, dtype=self.dtype, device=self.device) self.output = torch.zeros(16, dtype=torch.long, device=self.device) self.graph = torch.cuda.CUDAGraph() self._capture() def _sample(self, logits): scores = logits.float()[0] if not self.sampling['subtalker_do_sample']: return scores.argmax().view(1) scores = scores / self.sampling['subtalker_temperature'] k = self.sampling['subtalker_top_k'] if k: cutoff = torch.topk(scores, k).values[-1] scores = scores.masked_fill(scores < cutoff, -float('inf')) return torch.multinomial(scores.softmax(-1), 1) def _loop(self): last = self.engine.talker.get_input_embeddings()(self.token.view(1, 1)) x = self.p.small_to_mtp_projection(torch.cat([self.hidden, last], dim=1)) self.output[0].copy_(self.token) for j in range(15): pos = self.positions[j] self.cache.active_length = j + 2 out = self.p.model(inputs_embeds=x, past_key_values=self.cache, use_cache=True, cache_position=pos, position_ids=pos[None], attention_mask={'full_attention': None}) code = self._sample(self.p.lm_head[j](out.last_hidden_state[:, -1])) self.output[j + 1].copy_(code[0]) if j < 14: x = self.p.small_to_mtp_projection(self.p.model.get_input_embeddings()[j](code.view(1, 1))) return self.output @torch.inference_mode() def _capture(self): # Capture is initialization, not part of the request RNG trajectory. with torch.cuda.device(self.device), torch.random.fork_rng(devices=[self.device.index]): stream = torch.cuda.Stream(device=self.device) stream.wait_stream(torch.cuda.current_stream(self.device)) with torch.cuda.stream(stream): for _ in range(3): self._loop() torch.cuda.current_stream(self.device).wait_stream(stream) torch.cuda.synchronize(self.device) with torch.cuda.graph(self.graph, stream=stream): self._loop() torch.cuda.current_stream(self.device).wait_stream(stream) torch.cuda.synchronize(self.device) @torch.inference_mode() def run(self, token, past_hidden): self.token.copy_(token.reshape(())) self.hidden.copy_(past_hidden) # Causal masks exclude unwritten positions; all used K/V are overwritten. self.graph.replay() return self.output.clone()