Build weights and hidden_states that produce known logits. Creates up to two hidden states: one with ascending logits (favors high token indices) and one with descending logits (favors low token indices). All logits are shifted negative via :func:`shift_logits_negative`.
(
vocab_size: int = 256,
hidden_size: int = 10,
n_hidden_states: int = 2,
device: torch.device = torch.device("cuda"),
tp: TPInfo = TP1,
)
| 25 | |
| 26 | |
| 27 | def make_synthetic_inputs( |
| 28 | vocab_size: int = 256, |
| 29 | hidden_size: int = 10, |
| 30 | n_hidden_states: int = 2, |
| 31 | device: torch.device = torch.device("cuda"), |
| 32 | tp: TPInfo = TP1, |
| 33 | ) -> SyntheticInputs: |
| 34 | """Build weights and hidden_states that produce known logits. |
| 35 | |
| 36 | Creates up to two hidden states: one with ascending logits (favors high |
| 37 | token indices) and one with descending logits (favors low token indices). |
| 38 | All logits are shifted negative via :func:`shift_logits_negative`. |
| 39 | """ |
| 40 | logits1 = torch.arange(-vocab_size / 2, vocab_size / 2, dtype=torch.float32)[None, :] |
| 41 | logits2 = torch.arange(vocab_size / 2, -vocab_size / 2, step=-1, dtype=torch.float32)[None, :] |
| 42 | all_logits = [logits1, logits2] |
| 43 | logits = torch.cat(all_logits[:n_hidden_states], dim=0).to(device) |
| 44 | n_hidden_states = logits.shape[0] |
| 45 | |
| 46 | U, _, _ = torch.linalg.svd(logits, full_matrices=False) # noqa: N806 |
| 47 | |
| 48 | torch.manual_seed(0) |
| 49 | hidden_states = torch.cat( |
| 50 | [U, torch.rand((n_hidden_states, hidden_size - n_hidden_states), device=device)], |
| 51 | dim=1, |
| 52 | ).to(device) |
| 53 | weights = torch.linalg.pinv(hidden_states) @ logits # [D, V] |
| 54 | |
| 55 | weights_bf16 = weights.bfloat16().T.contiguous() # [V, D] |
| 56 | hidden_states_bf16 = hidden_states.bfloat16() |
| 57 | weights_bf16, hidden_states_bf16 = shift_logits_negative( |
| 58 | weights_bf16, |
| 59 | hidden_states_bf16, |
| 60 | offset=float(vocab_size), |
| 61 | ) |
| 62 | |
| 63 | weights_bf16, hidden_states_bf16 = pad_to_tma_alignment(weights_bf16, hidden_states_bf16) |
| 64 | weights_bf16 = shard_weights(weights_bf16, tp) |
| 65 | |
| 66 | return SyntheticInputs( |
| 67 | weights=weights_bf16, |
| 68 | hidden_states=hidden_states_bf16, |
| 69 | logits=logits, |
| 70 | vocab_size=vocab_size, |
| 71 | hidden_size=weights_bf16.shape[1], |
| 72 | ) |
| 73 | |
| 74 | |
| 75 | def pad_to_tma_alignment( |
no test coverage detected