File size: 15,281 Bytes
88564ad | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | from typing import Optional
import unittest
import torch
import torch.nn.functional as F
from unittest.mock import MagicMock
from generate_uadf import generate as generated_generate_uadf_tokens
from canonical import generate as canonical_generate_uadf_tokens
# Assuming your canonical implementation is in a file named 'canonical_uad_generation.py'
# and your generated implementation is in 'generated_uad_generation.py'
# For the purpose of this example, I'll put both in the same file for simplicity.
# --- Canonical Implementation (provided in the problem description) ---
class LLaMA:
def __init__(self, config_block_size=1024):
self.config = MagicMock()
self.config.block_size = config_block_size
def __call__(self, x, max_seq_length, input_pos):
# Mock LLM behavior: returns logits for the next token
# For testing, we'll return a predictable sequence of logits
# This mock LLM will 'predict' tokens 100, 101, 102...
vocab_size = 50000 # Example vocab size
logits = torch.ones(1, x.size(1), vocab_size) * 0.01 # Baseline low logits
# Make the 'correct' next token highly probable
#next_token_logit = (input_pos.item() + 100) % vocab_size
next_token_logit = (input_pos + 100) % vocab_size
if x.size(1) > 0: # Ensure input_pos is valid for indexing
logits[0, -1, next_token_logit] = 5.0 # High logit for the 'correct' next token
return logits
def eval(self):
pass # Mock eval method
def reset_cache(self):
pass # Mock reset_cache method
# --- Generated Implementation (will be the same as canonical for this example) ---
# In a real scenario, this would be your code to be tested.
# For now, we'll just alias the canonical one.
class TestUADFTokenGeneration(unittest.TestCase):
def setUp(self):
# Mock LLM Model
self.mock_model = LLaMA(config_block_size=1024)
# Mock ASR Decoder Inference Callable
# This mock will return predictable logits.
# For simplicity, let's assume ASR consistently predicts token '99'
# with high probability, or alternates based on input.
def mock_asr_inference(token_ids, asr_emb):
vocab_size = 50000 # Must match LLM's assumed vocab size
logits = torch.ones(1, vocab_size) * 0.01
# ASR "prefers" token 99, 100, 101...
asr_preferred_token = (token_ids.size(1) + 99) % vocab_size
logits[0, asr_preferred_token] = 4.0
return logits # Return logits and a dummy None for the second return value
self.mock_asr_inference = MagicMock(side_effect=mock_asr_inference)
# Common test parameters
self.idx = [0, 1, 2]
self.idx = torch.tensor(self.idx).long()
self.asr_emb = [[0.1, 0.2], [0.3, 0.4]] # Dummy embeddings
self.max_new_tokens = 5
self.max_seq_length = 10
self.temperature_asr = 0.5
self.temperature_llm = 0.8
self.eos_id = 50000 # A high ID unlikely to be generated by chance
def test_basic_functionality(self):
"""
Tests if the generated function produces the same output as the canonical
for a straightforward generation scenario with deterministic mocks.
"""
canonical_output = canonical_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
generated_output = generated_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
self.assertTrue(torch.allclose(canonical_output, generated_output), "Outputs should be identical for basic generation.")
self.assertEqual(len(generated_output), len(self.idx) + self.max_new_tokens,
"Generated output length should match initial + max_new_tokens.")
def test_eos_token_stops_generation(self):
"""
Tests if generation stops when the eos_id is encountered.
We'll set the mock LLM/ASR to predict the EOS token early.
"""
early_eos_id = 105 # A specific token ID that will be generated early
# Configure mock LLM to predict early_eos_id at a specific step
def mock_llm_predict_eos(x, max_seq_length, input_pos):
vocab_size = 50000
logits = torch.ones(1, x.size(1), vocab_size) * 0.01
if input_pos.item() == len(self.idx) + 1: # Predict EOS after 2 new tokens
logits[0, -1, early_eos_id] = 10.0 # Make EOS highly probable
else:
logits[0, -1, (input_pos.item() + 100) % vocab_size] = 5.0
return logits
self.mock_model.side_effect = mock_llm_predict_eos
# Configure mock ASR to also predict early_eos_id at a specific step
def mock_asr_predict_eos(token_ids, asr_emb):
vocab_size = 50000
logits = torch.ones(1, vocab_size) * 0.01
if token_ids.size(1) == len(self.idx) + 1: # Predict EOS after 2 new tokens
logits[0, early_eos_id] = 8.0 # Make EOS highly probable
else:
logits[0, (token_ids.size(1) + 99) % vocab_size] = 4.0
return logits, None
self.mock_asr_inference.side_effect = mock_asr_predict_eos
canonical_output = canonical_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=early_eos_id
)
generated_output = generated_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=early_eos_id
)
self.assertTrue(torch.allclose(canonical_output, generated_output), "Outputs should be identical when EOS token is encountered.")
# Expected length: initial tokens + 2 new tokens + EOS token
expected_length = len(self.idx) + 2
self.assertLessEqual(len(generated_output), len(self.idx) + self.max_new_tokens,
"Generation should stop before max_new_tokens if EOS is hit.")
def test_different_temperatures(self):
"""
Tests if the function behaves consistently when different calibration temperatures are used.
"""
temp_asr = 2.0
temp_llm = 0.1
canonical_output = canonical_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=temp_asr,
temperature_llm=temp_llm,
eos_id=self.eos_id
)
generated_output = generated_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=temp_asr,
temperature_llm=temp_llm,
eos_id=self.eos_id
)
self.assertTrue(torch.allclose(canonical_output, generated_output), "Outputs should be identical with different temperature values.")
def test_max_new_tokens_zero(self):
"""
Tests behavior when max_new_tokens is zero.
Should return the initial token IDs.
"""
canonical_output = canonical_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=0,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
generated_output = generated_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=0,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
self.assertEqual(canonical_output.tolist(), self.idx.tolist(),
"Output should be initial tokens when max_new_tokens is 0 (canonical).")
self.assertEqual(generated_output.tolist(), self.idx.tolist(),
"Output should be initial tokens when max_new_tokens is 0 (generated).")
self.assertTrue(torch.allclose(canonical_output, generated_output),
"Outputs should be identical when no new tokens are generated.")
def test_llm_uncertainty_impact(self):
"""
Tests how LLM uncertainty influences the fusion weight.
We'll manipulate mock LLM outputs to create high/low uncertainty.
Since we compare against canonical (which uses the same logic),
this primarily verifies that the `torch.dot` and `sigmoid` operations
are correctly applied and produce identical results.
"""
# Scenario 1: LLM is highly certain (low entropy -> low llm_uc)
def mock_llm_high_certainty(x, max_seq_length, input_pos):
vocab_size = 50000
logits = torch.ones(1, x.size(1), vocab_size) * -10.0 # Very low logits
logits[0, -1, 100] = 10.0 # One token overwhelmingly probable
return logits
# Scenario 2: LLM is highly uncertain (high entropy -> high llm_uc)
def mock_llm_high_uncertainty(x, max_seq_length, input_pos):
vocab_size = 50000
# Distribute probability more evenly across many tokens
logits = torch.ones(1, x.size(1), vocab_size) * 0.01
for i in range(10): # Give 10 tokens similar probability
logits[0, -1, 100 + i] = 1.0
return logits
original_llm_call = self.mock_model.__call__
# Test with high certainty
self.mock_model.__call__ = mock_llm_high_certainty
canonical_output_high_cert = canonical_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
generated_output_high_cert = generated_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
self.assertTrue(torch.allclose(canonical_output_high_cert, generated_output_high_cert),
"Outputs should be identical with high LLM certainty.")
# Test with high uncertainty
self.mock_model.__call__.side_effect = mock_llm_high_uncertainty
canonical_output_high_uncert = canonical_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
generated_output_high_uncert = generated_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=self.max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
self.assertTrue(torch.allclose(canonical_output_high_cert, generated_output_high_cert),
"Outputs should be identical with high LLM uncertainty.")
# Restore original side effect
self.mock_model.__call__.side_effect = original_llm_call
def test_max_seq_length_clipping(self):
"""
Tests that the max_seq_length parameter is respected,
potentially by making the LLM's input `x` get clipped if the sequence grows too long.
This test mainly checks if the code handles the `max_seq_length` logic consistently.
"""
# Set a very small max_seq_length
small_max_seq_length = len(self.idx) + 1
canonical_output = canonical_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=small_max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
generated_output = generated_generate_uadf_tokens(
model=self.mock_model,
idx=self.idx,
asr_emb=self.asr_emb,
asr_inference=self.mock_asr_inference,
max_new_tokens=self.max_new_tokens,
max_seq_length=small_max_seq_length,
temperature_asr=self.temperature_asr,
temperature_llm=self.temperature_llm,
eos_id=self.eos_id
)
self.assertTrue(torch.allclose(canonical_output, generated_output),
"Outputs should be identical when max_seq_length is constrained.")
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
|