forked from Lightning-AI/litgpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_batch.py
326 lines (259 loc) · 9.75 KB
/
test_batch.py
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
import torch
import pytest
import warnings
from pathlib import Path
import lightning as L
import litgpt
from litgpt.generate.base import (
next_token,
batched_next_token,
batched_generate_fn,
generate_fn,
)
from litgpt.api import LLM, GPT
from litgpt.scripts.download import download_from_hub
from tests.conftest import RunIf
warnings.filterwarnings("ignore")
def create_llm(tmp_path, batch_size, max_seq_length, device) -> tuple[LLM, GPT]:
L.seed_everything(42)
model_name = "microsoft/phi-2"
download_from_hub(repo_id=model_name, tokenizer_only=True, checkpoint_dir=tmp_path)
llm: LLM = LLM.load(
model_name,
tokenizer_dir=Path(tmp_path / model_name),
init="random",
)
model: GPT = llm.model
model.set_kv_cache(
batch_size=batch_size, max_seq_length=max_seq_length, device=device
)
return llm, model
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Test requires a GPU.")
def test_batched_equivalence(tmp_path):
model_name = "microsoft/phi-2"
download_from_hub(repo_id=model_name, tokenizer_only=True, checkpoint_dir=tmp_path)
device = "cuda:0"
batch_size = 3
sample_kwargs = {"top_k": 1}
llm: LLM = LLM.load(
model_name,
tokenizer_dir=Path(tmp_path / model_name),
init="random",
)
model: GPT = llm.model
model.set_kv_cache(batch_size=1, max_seq_length=50, device=device)
input_pos_1 = torch.tensor(
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=torch.int64, device=device
)
input_pos_2 = torch.tensor([10], dtype=torch.int64, device=device)
x = torch.tensor(
[43993, 25, 1867, 466, 32660, 17485, 4483, 30, 198, 26410],
device=device,
dtype=torch.int64,
)
batch_x1 = torch.stack([x] * batch_size, dim=0)
# Single token generation baseline
tok_1 = next_token(model, input_pos_1, x.unsqueeze(0), **sample_kwargs)
tok_2 = next_token(model, input_pos_2, tok_1.unsqueeze(0), **sample_kwargs)
assert tok_1.ndim == 1
assert tok_2.ndim == 1
assert tok_1.size(0) == 1
assert tok_2.size(0) == 1
# Switch to batched generation
model.clear_kv_cache()
model.set_kv_cache(batch_size=batch_size, max_seq_length=50, device="cuda:0")
toks_1: torch.Tensor = batched_next_token(
model, input_pos_1, batch_x1, sample_kwargs
)
toks_2: torch.Tensor = batched_next_token(model, input_pos_2, toks_1, sample_kwargs)
assert toks_1.ndim == 2
assert toks_2.ndim == 2
assert toks_1.size(0) == batch_size
assert toks_2.size(0) == batch_size
# Assert that single and batched next token generation are equivalent
assert all(t == tok_1 for t in toks_1), f"{tok_1} != {toks_1}"
assert all(t == tok_2 for t in toks_2), f"{tok_2} != {toks_2}"
@RunIf(min_cuda_gpus=1)
def test_simple_batch():
old_allow_tf32 = torch.backends.cuda.matmul.allow_tf32
torch.backends.cuda.matmul.allow_tf32 = False
config = litgpt.Config.from_name(
"microsoft/phi-2", padded_vocab_size=10000, n_layer=2, n_head=8, n_embd=256
)
with torch.device("cuda"):
m = litgpt.GPT(config).requires_grad_(False).eval()
x0 = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 7]])
input_pos0 = torch.tensor([[0, 1, 2, 3], [0, 1, 2, 2]])
x1 = torch.tensor([[1], [2]])
input_pos1 = torch.tensor([[4], [3]])
with torch.device("cuda"):
m.set_kv_cache(2)
outs0 = m(x0, input_pos0)
outs1 = m(x1, input_pos1)
with torch.device("cuda"):
m.set_kv_cache(1)
outs0_ref0 = m(x0[:1], input_pos0[0])
outs1_ref0 = m(x1[:1], input_pos1[0])
with torch.device("cuda"):
m.set_kv_cache(1)
outs0_ref1 = m(x0[1:], input_pos0[1])
outs1_ref1 = m(x1[1:], input_pos1[1])
outs0_ref = torch.cat([outs0_ref0, outs0_ref1])
outs1_ref = torch.cat([outs1_ref0, outs1_ref1])
print(outs0_ref - outs0)
print(outs0.shape)
torch.testing.assert_close(outs0, outs0_ref)
torch.testing.assert_close(outs1, outs1_ref)
torch.backends.cuda.matmul.allow_tf32 = old_allow_tf32
@RunIf(min_cuda_gpus=1)
def test_batch_generate(tmp_path):
torch.use_deterministic_algorithms(True)
device = "cuda:0"
batch_size = 3
sample_kwargs = {"top_k": 1}
llm, model = create_llm(tmp_path, batch_size, 50, device)
batch_x = torch.tensor(
[
[43993, 25, 1867, 466, 32660, 17485, 4483, 30, 198, 26410],
[25, 1867, 466, 32660, 17485, 4483, 30, 198, 26410, 7596],
[1867, 466, 32660, 17485, 4483, 30, 198, 26410, 7596, 7596],
],
device=device,
dtype=torch.int64,
)
# Generate tokens
tokens = []
for l in batched_generate_fn(
model,
prompts=batch_x,
max_returned_tokens=50,
sample_args=sample_kwargs,
include_prompt=True,
include_eos=False,
):
tokens.append([t.item() if t is not None else None for t in l])
def find_unique_stop(triplets):
# Initialize a dictionary to count all number occurrences
number_count = {}
# Count occurrences of each number across all positions
for triplet in triplets:
for num in triplet:
number_count[num] = number_count.get(num, 0) + 1
# Initialize lists to store unique numbers for each position
unique_first = []
unique_second = []
unique_third = []
# Check each triplet
for a, b, c in triplets:
if number_count[a] == 1:
unique_first.append(a)
if number_count[b] == 1:
unique_second.append(b)
if number_count[c] == 1:
unique_third.append(c)
import random # Seeded earlier
random.shuffle(unique_first)
random.shuffle(unique_second)
random.shuffle(unique_third)
return [unique_first[0], unique_second[0], unique_third[0]]
# Now that we know the randomly generated tokens, sample some tokens to stop each stream at.
stops = find_unique_stop(tokens[batch_x.size(1) :])
first_stream = [t[0] for t in tokens if t[0] is not None]
second_stream = [t[1] for t in tokens if t[1] is not None]
third_stream = [t[2] for t in tokens if t[2] is not None]
# Let's slice the streams at the stop tokens.
stop_idxes = [
first_stream.index(stops[0]),
second_stream.index(stops[1]),
third_stream.index(stops[2]),
]
# While we're at it, grab the last token that would be generated before stopping.
last_tokens = [
first_stream[stop_idxes[0] - 1],
second_stream[stop_idxes[1] - 1],
third_stream[stop_idxes[2] - 1],
]
for t in tokens:
print(t)
# Now we generate again, stopping early at the stop tokens.
tokens = []
for l in batched_generate_fn(
model,
prompts=batch_x,
max_returned_tokens=50,
stop_tokens=[(s,) for s in stops],
sample_args=sample_kwargs,
include_prompt=True,
include_eos=False,
):
tokens.append([t.item() if t is not None else None for t in l])
# Finally, assert that the streams are correct.
first_stream = [t[0] for t in tokens if t[0] is not None]
print(first_stream)
print(len(first_stream), stop_idxes[0])
assert len(first_stream) == stop_idxes[0]
assert first_stream[-1] == last_tokens[0]
second_stream = [t[1] for t in tokens if t[1] is not None]
print(second_stream)
print(len(second_stream), stop_idxes[1])
assert len(second_stream) == stop_idxes[1]
assert second_stream[-1] == last_tokens[1]
third_stream = [t[2] for t in tokens if t[2] is not None]
print(third_stream)
print(len(third_stream), stop_idxes[2])
assert len(third_stream) == stop_idxes[2]
assert third_stream[-1] == last_tokens[2]
torch.use_deterministic_algorithms(False)
# for t in llm.tokenizer.decode_stream([torch.tensor(i) for i in first_stream]):
# print(t, end="", flush=True)
# print()
@RunIf(min_cuda_gpus=1)
def test_batch_generate_equivalence(tmp_path):
torch.use_deterministic_algorithms(True)
device = "cuda:0"
batch_size = 3
sample_kwargs = {"top_k": 1}
llm, model = create_llm(tmp_path, batch_size, 50, device)
batch_x = torch.tensor(
[
[43993, 25, 1867, 466, 32660, 17485, 4483, 30, 198, 26410],
[25, 1867, 466, 32660, 17485, 4483, 30, 198, 26410, 7596],
[1867, 466, 32660, 17485, 4483, 30, 198, 26410, 7596, 7596],
],
device=device,
dtype=torch.int64,
)
# The other test tests the stop_tokens functionality much more exhaustively, we'll just generate and compare 50 tokens here.
batch_tokens = []
for l in batched_generate_fn(
model,
prompts=batch_x,
max_returned_tokens=50,
sample_args=sample_kwargs,
include_prompt=False,
include_eos=False,
):
batch_tokens.append([t.item() if t is not None else None for t in l])
first_stream = [t[0] for t in batch_tokens if t[0] is not None]
batch_size = 1
llm, model = create_llm(tmp_path, batch_size, 50, device)
tokens = []
for t in generate_fn(
model,
prompt=batch_x[0],
max_returned_tokens=50,
include_prompt=False,
include_eos=False,
**sample_kwargs,
):
if t.size(0) == 1:
tokens.append(t.item())
else:
tokens.extend(t.tolist())
torch.use_deterministic_algorithms(False)
# TODO: (apaz-cli) This consistency test doesn't actually work at the moment. It's inconsistent.
# The output is really close... Something is going on here. For the moment, maybe this is close enough?
# Enough at least that we can start prototyping.
print(first_stream)
print(tokens)
# assert first_stream == tokens