|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). |
| 4 | +# You may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +""" |
| 15 | +Memory-efficient per-token log-probability computation using KV cache. |
| 16 | +
|
| 17 | +Implements a :class:`HeadModel` that accumulates per-token log-probs |
| 18 | +(and optionally entropies) instead of a scalar loss. Plug it into |
| 19 | +:class:`LongContextInferenceModel` and the existing chunked forward |
| 20 | +infrastructure handles everything — no new forward loop needed. |
| 21 | +
|
| 22 | +Usage:: |
| 23 | +
|
| 24 | + from keys_values.logprobs import compute_logprobs |
| 25 | +
|
| 26 | + logps, entropies = compute_logprobs( |
| 27 | + gpt_model=model, |
| 28 | + input_ids=input_ids, |
| 29 | + targets=completion_ids, |
| 30 | + cache_name="h2o-torch-quantized8", |
| 31 | + cache_length=16384, |
| 32 | + chunk_size=1024, |
| 33 | + ) |
| 34 | +""" |
| 35 | + |
| 36 | +from typing import Optional, Tuple |
| 37 | + |
| 38 | +import torch |
| 39 | +import torch.nn.functional as F |
| 40 | + |
| 41 | +from keys_values.config import Config |
| 42 | +from keys_values.head_model import HeadModel |
| 43 | +from keys_values.kvcache.factory import KVCacheFactory |
| 44 | +from keys_values.long_context import LongContextInferenceModel |
| 45 | +from keys_values.model import GPT |
| 46 | + |
| 47 | + |
| 48 | +class LogProbsHeadModel(HeadModel): |
| 49 | + """HeadModel that accumulates per-token log-probs instead of a loss. |
| 50 | +
|
| 51 | + Wraps the same logic as :class:`CrossEntropyOnLogits` but instead of |
| 52 | + reducing to a scalar loss, it gathers the log-probability of each target |
| 53 | + token and stores it. After the full chunked forward pass completes, |
| 54 | + call :meth:`get_results` to retrieve the accumulated tensors. |
| 55 | +
|
| 56 | + This is meant to be used with :class:`LongContextInferenceModel` — the |
| 57 | + existing chunk/cell/layer loop calls ``forward()`` chunk by chunk, and |
| 58 | + this class collects log-probs as they come. |
| 59 | + """ |
| 60 | + |
| 61 | + NAME = "log_probs" |
| 62 | + |
| 63 | + def __init__( |
| 64 | + self, config: Config, temperature: float = 1.0, compute_entropy: bool = False |
| 65 | + ): |
| 66 | + super().__init__() |
| 67 | + self._vocab_size = config.padded_vocab_size |
| 68 | + self._temperature = temperature |
| 69 | + self._compute_entropy = compute_entropy |
| 70 | + self._logps_chunks: list[torch.Tensor] = [] |
| 71 | + self._entropy_chunks: list[torch.Tensor] = [] |
| 72 | + |
| 73 | + def needs_logits(self) -> bool: |
| 74 | + return True |
| 75 | + |
| 76 | + def forward( |
| 77 | + self, |
| 78 | + model_outputs: torch.Tensor, |
| 79 | + targets: Optional[torch.Tensor], |
| 80 | + input_pos: int, |
| 81 | + ) -> torch.Tensor: |
| 82 | + """Accumulate log-probs for target tokens in this chunk. |
| 83 | +
|
| 84 | + Called by LongContextInferenceModel for each chunk. When targets |
| 85 | + is None (prompt-only chunk), we skip. When targets are present, |
| 86 | + we gather log-probs and optionally entropy. |
| 87 | + """ |
| 88 | + if input_pos == 0: |
| 89 | + self._logps_chunks.clear() |
| 90 | + self._entropy_chunks.clear() |
| 91 | + |
| 92 | + diff = self._check_model_outputs_targets( |
| 93 | + model_outputs, targets, final_dim=self._vocab_size |
| 94 | + ) |
| 95 | + |
| 96 | + if diff is not None: |
| 97 | + logits = model_outputs[:, diff:, :] |
| 98 | + if self._temperature != 1.0: |
| 99 | + logits = logits / self._temperature |
| 100 | + |
| 101 | + # Per-token log-probs |
| 102 | + log_probs = F.log_softmax(logits, dim=-1) |
| 103 | + token_logps = torch.gather( |
| 104 | + log_probs, dim=-1, index=targets.unsqueeze(-1) |
| 105 | + ).squeeze(-1) |
| 106 | + self._logps_chunks.append(token_logps) |
| 107 | + |
| 108 | + if self._compute_entropy: |
| 109 | + ent = -(log_probs.exp() * log_probs).sum(dim=-1) |
| 110 | + self._entropy_chunks.append(ent) |
| 111 | + |
| 112 | + # Return zeros |
| 113 | + return torch.zeros( |
| 114 | + model_outputs.shape[0], |
| 115 | + device=model_outputs.device, |
| 116 | + dtype=model_outputs.dtype, |
| 117 | + ) |
| 118 | + |
| 119 | + def num_target_entries(self, targets: torch.Tensor) -> Optional[torch.Tensor]: |
| 120 | + return None |
| 121 | + |
| 122 | + def get_results(self) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: |
| 123 | + """Retrieve accumulated log-probs and entropies after forward pass. |
| 124 | +
|
| 125 | + Returns |
| 126 | + ------- |
| 127 | + logps : torch.Tensor |
| 128 | + Shape ``(batch_size, num_target_tokens)``. |
| 129 | + entropies : torch.Tensor | None |
| 130 | + Shape ``(batch_size, num_target_tokens)`` or None. |
| 131 | + """ |
| 132 | + logps = torch.cat(self._logps_chunks, dim=1) |
| 133 | + entropies = ( |
| 134 | + torch.cat(self._entropy_chunks, dim=1) if self._entropy_chunks else None |
| 135 | + ) |
| 136 | + return logps, entropies |
| 137 | + |
| 138 | + def _empty_clone(self, device: Optional[torch.device] = None) -> "HeadModel": |
| 139 | + config = Config() |
| 140 | + config.padded_vocab_size = self._vocab_size |
| 141 | + return LogProbsHeadModel( |
| 142 | + config, |
| 143 | + temperature=self._temperature, |
| 144 | + compute_entropy=self._compute_entropy, |
| 145 | + ) |
| 146 | + |
| 147 | + |
| 148 | +def compute_logprobs( |
| 149 | + gpt_model: GPT, |
| 150 | + input_ids: torch.Tensor, |
| 151 | + targets: torch.Tensor, |
| 152 | + cache_name: str = "h2o-torch-quantized8", |
| 153 | + cache_length: int = 16384, |
| 154 | + chunk_size: int = 1024, |
| 155 | + cache_kwargs: Optional[dict] = None, |
| 156 | + temperature: float = 1.0, |
| 157 | + compute_entropy: bool = False, |
| 158 | +) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: |
| 159 | + """Compute per-token log-probs via LongContextInferenceModel. |
| 160 | +
|
| 161 | + This is the primary entry point. It creates a :class:`LogProbsHeadModel`, |
| 162 | + plugs it into :class:`LongContextInferenceModel`, and runs the existing |
| 163 | + chunked forward pass. All KV cache management, chunk/cell grouping, and |
| 164 | + layer processing is handled by the existing infrastructure. |
| 165 | +
|
| 166 | + Args: |
| 167 | + gpt_model: KeysAndValues GPT model. |
| 168 | + input_ids: Full sequence (prompt + completion), shape |
| 169 | + ``(batch_size, seq_length)``. |
| 170 | + targets: Target tokens (right-aligned with input_ids), shape |
| 171 | + ``(batch_size, num_completion_tokens)``. |
| 172 | + cache_name: KV cache policy name. |
| 173 | + cache_length: Number of slots in the KV cache. |
| 174 | + chunk_size: Chunk size for post-prefill processing. |
| 175 | + cache_kwargs: Extra args for KV cache construction. |
| 176 | + temperature: Scales logits before softmax. |
| 177 | + compute_entropy: Whether to also return per-token entropy. |
| 178 | +
|
| 179 | + Returns: |
| 180 | + Tuple of (log_probs, entropies). |
| 181 | + """ |
| 182 | + batch_size = input_ids.shape[0] |
| 183 | + config = gpt_model.config |
| 184 | + dtype = next(gpt_model.parameters()).dtype |
| 185 | + |
| 186 | + head = LogProbsHeadModel( |
| 187 | + config, temperature=temperature, compute_entropy=compute_entropy |
| 188 | + ) |
| 189 | + |
| 190 | + caches_created = False |
| 191 | + if gpt_model.get_kv_caches()[0] is None: |
| 192 | + gpt_model.assign_kv_caches( |
| 193 | + KVCacheFactory.create( |
| 194 | + gpt_model=gpt_model, |
| 195 | + name=cache_name, |
| 196 | + max_batch_size=batch_size, |
| 197 | + cache_length=cache_length, |
| 198 | + dtype=dtype, |
| 199 | + cache_kwargs=cache_kwargs or {}, |
| 200 | + ) |
| 201 | + ) |
| 202 | + caches_created = True |
| 203 | + |
| 204 | + inference_model = LongContextInferenceModel( |
| 205 | + gpt_model=gpt_model, |
| 206 | + head_model=head, |
| 207 | + chunk_size=chunk_size, |
| 208 | + ) |
| 209 | + |
| 210 | + # Run the forward pass |
| 211 | + inference_model(input_ids=input_ids, targets=targets) |
| 212 | + |
| 213 | + logps, entropies = head.get_results() |
| 214 | + |
| 215 | + if caches_created: |
| 216 | + from keys_values.kvcache.factory import deallocate_kv_cache_buffers_of_model |
| 217 | + |
| 218 | + deallocate_kv_cache_buffers_of_model(gpt_model) |
| 219 | + gpt_model.assign_kv_caches([None] * config.n_layer) |
| 220 | + |
| 221 | + return logps, entropies |
0 commit comments