(
logprob_rows: list[dict[str, torch.Tensor]],
config: DistributionQuantizationConfig | LegacyLogitCompressionConfig,
batch_size: int = 256,
device: str = "cuda",
missing_prob_handling: MissingProbabilityHandling = MissingProbabilityHandling.ZERO,
)
| 145 | |
| 146 | |
| 147 | def eval_compression_quality( |
| 148 | logprob_rows: list[dict[str, torch.Tensor]], |
| 149 | config: DistributionQuantizationConfig | LegacyLogitCompressionConfig, |
| 150 | batch_size: int = 256, |
| 151 | device: str = "cuda", |
| 152 | missing_prob_handling: MissingProbabilityHandling = MissingProbabilityHandling.ZERO, |
| 153 | ) -> CompressionEvalResult: |
| 154 | compressor = ( |
| 155 | LogprobCompressor( |
| 156 | config=config |
| 157 | if isinstance(config, DistributionQuantizationConfig) |
| 158 | else None, |
| 159 | legacy_config=( |
| 160 | config if isinstance(config, LegacyLogitCompressionConfig) else None |
| 161 | ), |
| 162 | ) |
| 163 | if config != "bf16" |
| 164 | else None |
| 165 | ) |
| 166 | |
| 167 | vocab_size = None |
| 168 | bytes_per_token = None |
| 169 | if config == "bf16": |
| 170 | vocab_size = VOCAB_SIZE |
| 171 | bytes_per_token = 2 * vocab_size |
| 172 | elif isinstance(config, DistributionQuantizationConfig): |
| 173 | vocab_size = config.d |
| 174 | bytes_per_token = (config.total_bits() + 7) // 8 |
| 175 | elif isinstance(config, LegacyLogitCompressionConfig): |
| 176 | vocab_size = config.vocab_size |
| 177 | bytes_per_token = compressor.legacy_compressor.bytes_per_token() |
| 178 | else: |
| 179 | raise ValueError("Invalid config type") |
| 180 | |
| 181 | kld_fwd_list = [] |
| 182 | kld_bwd_list = [] |
| 183 | jsd_list = [] |
| 184 | mse_list = [] |
| 185 | for i_0 in tqdm.tqdm(range(0, len(logprob_rows), batch_size), desc="Evaluating"): |
| 186 | i_1 = min(i_0 + batch_size, len(logprob_rows)) |
| 187 | batch = logprob_rows[i_0:i_1] |
| 188 | logprobs = torch.stack([row["logprobs"] for row in batch], dim=0).to(device) |
| 189 | mask = (torch.stack([row["attention_mask"] for row in batch], dim=0) > 0).to( |
| 190 | device |
| 191 | ) |
| 192 | logprobs = logprobs.float().masked_fill(mask.unsqueeze(-1), -1e6) |
| 193 | |
| 194 | if config != "bf16": |
| 195 | batch_out = compressor.compress(logprobs) |
| 196 | rt_ids, rt_logp = compressor.decompress_to_sparse(batch_out) |
| 197 | del batch_out |
| 198 | rt_logp_dense = densify( |
| 199 | rt_ids, |
| 200 | rt_logp.float(), |
| 201 | vocab_size, |
| 202 | missing=missing_prob_handling, |
| 203 | renormalize=True, |
| 204 | fill_value=-1e12, |
no test coverage detected