MCPcopy Index your code
hub / github.com/FlashSampling/FlashSampling / test_top_k_top_p

Function test_top_k_top_p

tests/test_core.py:105–138  ·  view source on GitHub ↗

Verify that top-k and top-p filtering restricts samples to the expected tokens.

(provider, vocab_size, n_hidden_states)

Source from the content-addressed store, hash-verified

103@pytest.mark.parametrize("vocab_size", [100, 200, 256])
104@pytest.mark.parametrize("provider", ["naive-pt", "naive-compiled", "fused-topk"])
105def test_top_k_top_p(provider, vocab_size, n_hidden_states):
106 """Verify that top-k and top-p filtering restricts samples to the expected tokens."""
107 inputs = make_synthetic_inputs(vocab_size=vocab_size, n_hidden_states=n_hidden_states)
108 temperature = torch.tensor(1.0, device=device)
109 top_k = 10
110 top_p = 0.9
111 num_samples = 5_000
112
113 sampler = get_sampler(provider, weights=inputs.weights)
114 sampler.prepare()
115 samples = sampler.sample(
116 weights=inputs.weights,
117 hidden_states=inputs.hidden_states,
118 num_samples=num_samples,
119 temperature=temperature,
120 top_k=top_k,
121 top_p=top_p,
122 )
123
124 # Use the same bf16 matmul logits the sampler sees, not the exact float32 logits.
125 ref_logits = inputs.hidden_states @ inputs.weights.T
126 for seq_idx in range(n_hidden_states):
127 allowed_tokens = reference_top_k_top_p(
128 logits=ref_logits[seq_idx], temperature=temperature, top_k=top_k, top_p=top_p
129 )
130 unique_sampled = torch.unique(samples[seq_idx])
131 allowed_set = set(allowed_tokens.cpu().tolist())
132 sampled_set = set(unique_sampled.cpu().tolist())
133 assert sampled_set <= allowed_set, (
134 f"seq {seq_idx}: sampled tokens not in allowed set. Extra: {sampled_set - allowed_set}"
135 )
136 assert sampled_set == allowed_set, (
137 f"seq {seq_idx}: not all allowed tokens sampled. Missing: {allowed_set - sampled_set}"
138 )
139
140
141@pytest.mark.parametrize("provider", ["naive-pt", "fused-topk"])

Callers

nothing calls this directly

Calls 5

make_synthetic_inputsFunction · 0.90
get_samplerFunction · 0.90
reference_top_k_top_pFunction · 0.85
prepareMethod · 0.45
sampleMethod · 0.45

Tested by

no test coverage detected