Greedy decoding with **shared** stopping criteria. We keep two independent KV caches (one per sub‑model) and extend them step‑by‑step.
( # type: ignore[override]
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.LongTensor] = None,
max_new_tokens: int = 20,
stopping_criteria: Optional[StoppingCriteriaList] = None,
do_sample: bool = False, # must be False (greedy) for now
generation_config: Optional[GenerationConfig] = None,
**kwargs,
)
| 110 | # ------------------------------------------------------------------ # |
| 111 | @torch.no_grad() |
| 112 | def generate( # type: ignore[override] |
| 113 | self, |
| 114 | input_ids: torch.LongTensor, |
| 115 | attention_mask: Optional[torch.LongTensor] = None, |
| 116 | max_new_tokens: int = 20, |
| 117 | stopping_criteria: Optional[StoppingCriteriaList] = None, |
| 118 | do_sample: bool = False, # must be False (greedy) for now |
| 119 | generation_config: Optional[GenerationConfig] = None, |
| 120 | **kwargs, |
| 121 | ): |
| 122 | """ |
| 123 | Greedy decoding with **shared** stopping criteria. |
| 124 | We keep two independent KV caches (one per sub‑model) and extend them |
| 125 | step‑by‑step. |
| 126 | """ |
| 127 | if do_sample: |
| 128 | raise ValueError("MemoryDecoder.generate only supports greedy decoding (do_sample=False).") |
| 129 | |
| 130 | device = input_ids.device |
| 131 | batch_size = input_ids.shape[0] |
| 132 | |
| 133 | # Initialise caches with a single forward. |
| 134 | outputs = self.forward( |
| 135 | input_ids=input_ids, |
| 136 | attention_mask=attention_mask, |
| 137 | **kwargs, |
| 138 | ) |
| 139 | next_token_logits = outputs["logits"][:, -1, :] # (B, V) |
| 140 | |
| 141 | base_past = outputs["past_key_values"] |
| 142 | knn_past = outputs["knn_past_key_values"] |
| 143 | |
| 144 | # Greedy select |
| 145 | next_tokens = torch.argmax(next_token_logits, dim=-1).unsqueeze(-1) # (B,1) |
| 146 | generated = torch.cat([input_ids, next_tokens], dim=-1) # (B,T+1) |
| 147 | |
| 148 | # --- main loop -------------------------------------------------- # |
| 149 | num_new_token = 0 |
| 150 | while True: |
| 151 | if stopping_criteria is not None and False not in stopping_criteria(generated, None): |
| 152 | break |
| 153 | if num_new_token >= max_new_tokens: |
| 154 | break |
| 155 | |
| 156 | outputs = self.forward( |
| 157 | input_ids=next_tokens, |
| 158 | attention_mask=None, # past manages causal masking |
| 159 | past_key_values=base_past, |
| 160 | knn_past_key_values=knn_past, |
| 161 | use_cache=True, |
| 162 | **kwargs, |
| 163 | ) |
| 164 | next_token_logits = outputs["logits"][:, -1, :] |
| 165 | base_past = outputs["past_key_values"] |
| 166 | knn_past = outputs["knn_past_key_values"] |
| 167 | |
| 168 | next_tokens = torch.argmax(next_token_logits, dim=-1).unsqueeze(-1) |
| 169 | generated = torch.cat([generated, next_tokens], dim=-1) |
no test coverage detected