test_gpt.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. import re
  2. import pytest
  3. import torch
  4. from einops import rearrange
  5. from flash_attn.models.gpt import (
  6. GPTLMHeadModel,
  7. remap_state_dict_hf_gpt2,
  8. shard_state_dict_tp,
  9. combine_state_dicts_tp,
  10. )
  11. from flash_attn.utils.generation import InferenceParams
  12. from flash_attn.utils.pretrained import state_dict_from_pretrained
  13. from transformers import GPT2Config, GPT2Tokenizer
  14. from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel as GPT2LMHeadModelHF
  15. @pytest.mark.parametrize("model_name", ["gpt2", "gpt2-medium"])
  16. # @pytest.mark.parametrize('model_name', ["gpt2"])
  17. def test_gpt2_state_dict(model_name):
  18. config = GPT2Config.from_pretrained(model_name)
  19. pretrained_state_dict = remap_state_dict_hf_gpt2(state_dict_from_pretrained(model_name), config)
  20. model = GPTLMHeadModel(config)
  21. state_dict = model.state_dict()
  22. assert state_dict.keys() == pretrained_state_dict.keys()
  23. for k in state_dict.keys():
  24. assert state_dict[k].shape == pretrained_state_dict[k].shape
  25. @pytest.mark.parametrize("model_name", ["gpt2", "gpt2-medium"])
  26. # @pytest.mark.parametrize('model_name', ["gpt2"])
  27. def test_gpt2_non_optimized(model_name):
  28. """Check that our implementation of GPT2 (without any optimizations enabled) matches the
  29. HF implementation: the output of our forward pass in fp16 should be around the same as the HF
  30. forward pass in fp16, when compared to the HF forward pass in fp32.
  31. """
  32. dtype = torch.float16
  33. config = GPT2Config.from_pretrained(model_name)
  34. model = GPTLMHeadModel.from_pretrained(model_name, config)
  35. model = model.cuda().to(dtype=dtype)
  36. model_ref = GPT2LMHeadModelHF.from_pretrained(model_name).cuda()
  37. model_hf = GPT2LMHeadModelHF.from_pretrained(model_name).cuda().to(dtype=dtype)
  38. model.eval()
  39. model_ref.eval()
  40. model_hf.eval()
  41. torch.manual_seed(0)
  42. batch_size = 4
  43. max_seqlen = 512
  44. seqlens = torch.randint(max_seqlen // 2, max_seqlen + 1, (batch_size,), device="cuda")
  45. input_ids = torch.randint(
  46. 0, config.vocab_size, (batch_size, max_seqlen), dtype=torch.long, device="cuda"
  47. )
  48. out = model.transformer(input_ids)
  49. out_hf = model_hf.transformer(input_ids).last_hidden_state
  50. out_ref = model_ref.transformer(input_ids).last_hidden_state
  51. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  52. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  53. print(f"HF fp16 max diff: {(out_hf - out_ref).abs().max().item()}")
  54. print(f"HF fp16 mean diff: {(out_hf - out_ref).abs().mean().item()}")
  55. assert (out - out_ref).abs().max().item() < 3 * (out_hf - out_ref).abs().max().item()
  56. logits = model(input_ids).logits
  57. logits_hf = model_hf(input_ids).logits
  58. logits_ref = model_ref(input_ids).logits
  59. print(f"Logits max diff: {(logits - logits_ref).abs().max().item()}")
  60. print(f"Logits mean diff: {(logits - logits_ref).abs().mean().item()}")
  61. print(f"HF fp16 max diff: {(logits_hf - logits_ref).abs().max().item()}")
  62. print(f"HF fp16 mean diff: {(logits_hf - logits_ref).abs().mean().item()}")
  63. assert (logits - logits_ref).abs().max().item() < 3 * (
  64. logits_hf - logits_ref
  65. ).abs().max().item()
  66. @pytest.mark.parametrize("model_name", ["gpt2", "gpt2-medium"])
  67. # @pytest.mark.parametrize('model_name', ["gpt2"])
  68. def test_gpt2_optimized(model_name):
  69. """Check that our implementation of GPT2 (with all optimizations enabled) matches the
  70. HF implementation: the output of our forward pass in fp16 should be around the same as the HF
  71. forward pass in fp16, when compared to the HF forward pass in fp32.
  72. """
  73. dtype = torch.float16
  74. config = GPT2Config.from_pretrained(model_name)
  75. vocab_size_og = config.vocab_size
  76. config.use_flash_attn = True
  77. config.fused_bias_fc = True
  78. config.fused_mlp = True
  79. config.fused_dropout_add_ln = True
  80. config.residual_in_fp32 = True
  81. config.pad_vocab_size_multiple = 8
  82. model = GPTLMHeadModel.from_pretrained(model_name, config)
  83. model = model.cuda().to(dtype=dtype)
  84. model_ref = GPT2LMHeadModelHF.from_pretrained(model_name).cuda()
  85. model_hf = GPT2LMHeadModelHF.from_pretrained(model_name).cuda().to(dtype=dtype)
  86. model.eval()
  87. model_ref.eval()
  88. model_hf.eval()
  89. torch.manual_seed(0)
  90. batch_size = 4
  91. max_seqlen = 512
  92. seqlens = torch.randint(max_seqlen // 2, max_seqlen + 1, (batch_size,), device="cuda")
  93. input_ids = torch.randint(
  94. 0, vocab_size_og, (batch_size, max_seqlen), dtype=torch.long, device="cuda"
  95. )
  96. out = model.transformer(input_ids)
  97. out_hf = model_hf.transformer(input_ids).last_hidden_state
  98. out_ref = model_ref.transformer(input_ids).last_hidden_state
  99. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  100. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  101. print(f"HF fp16 max diff: {(out_hf - out_ref).abs().max().item()}")
  102. print(f"HF fp16 mean diff: {(out_hf - out_ref).abs().mean().item()}")
  103. assert (out - out_ref).abs().max().item() < 3 * (out_hf - out_ref).abs().max().item()
  104. logits = model(input_ids).logits[..., :vocab_size_og]
  105. logits_hf = model_hf(input_ids).logits
  106. logits_ref = model_ref(input_ids).logits
  107. print(f"Logits max diff: {(logits - logits_ref).abs().max().item()}")
  108. print(f"Logits mean diff: {(logits - logits_ref).abs().mean().item()}")
  109. print(f"HF fp16 max diff: {(logits_hf - logits_ref).abs().max().item()}")
  110. print(f"HF fp16 mean diff: {(logits_hf - logits_ref).abs().mean().item()}")
  111. assert (logits - logits_ref).abs().max().item() < 3 * (
  112. logits_hf - logits_ref
  113. ).abs().max().item()
  114. @pytest.mark.parametrize("optimized", [False, True])
  115. # @pytest.mark.parametrize('optimized', [True])
  116. @pytest.mark.parametrize("rotary", [False, True])
  117. # @pytest.mark.parametrize('rotary', [False])
  118. @pytest.mark.parametrize("model_name", ["gpt2"])
  119. def test_gpt2_generation(model_name, rotary, optimized):
  120. """Check that our implementation of GPT2 generation matches the HF implementation:
  121. the scores in fp16 should be around the same as the HF scores in fp16, when compared to
  122. the HF scores in fp32.
  123. """
  124. dtype = torch.float16
  125. device = "cuda"
  126. rtol, atol = 3e-3, 3e-1
  127. config = GPT2Config.from_pretrained(model_name)
  128. if rotary:
  129. config.n_positions = 0
  130. config.rotary_emb_fraction = 0.5
  131. config.rotary_emb_base = 24000
  132. config.residual_in_fp32 = True
  133. if optimized:
  134. config.use_flash_attn = True
  135. config.fused_bias_fc = True
  136. config.fused_mlp = True
  137. config.fused_dropout_add_ln = True
  138. # if not rotary, we load the weight from HF but ignore the position embeddings.
  139. # The model would be nonsense but it doesn't matter for the test.
  140. model = GPTLMHeadModel.from_pretrained(
  141. model_name, config, strict=not rotary, device=device, dtype=dtype
  142. )
  143. model.eval()
  144. if not rotary:
  145. model_ref = GPT2LMHeadModelHF.from_pretrained(model_name).to(device=device)
  146. model_hf = GPT2LMHeadModelHF.from_pretrained(model_name, torch_dtype=dtype).to(
  147. device=device
  148. )
  149. model_ref.eval()
  150. model_hf.eval()
  151. torch.manual_seed(0)
  152. tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
  153. input_ids = tokenizer("Hello, my dog is cute and he", return_tensors="pt").input_ids.to(
  154. device=device
  155. )
  156. max_length = 25
  157. # input_ids = torch.randint(0, 100, (2, 10), dtype=torch.long, device='cuda')
  158. # max_length = input_ids.shape[1] + 40
  159. # Slow generation for reference
  160. sequences = []
  161. scores = []
  162. cur_input_ids = input_ids
  163. with torch.inference_mode():
  164. scores.append(model(cur_input_ids).logits[:, -1])
  165. sequences.append(scores[-1].argmax(dim=-1))
  166. for _ in range(input_ids.shape[1] + 1, max_length):
  167. cur_input_ids = torch.cat([cur_input_ids, rearrange(sequences[-1], "b -> b 1")], dim=-1)
  168. scores.append(model(cur_input_ids).logits[:, -1])
  169. sequences.append(scores[-1].argmax(dim=-1))
  170. sequences = torch.cat([input_ids, torch.stack(sequences, dim=1)], dim=1)
  171. scores = tuple(scores)
  172. out = model.generate(
  173. input_ids=input_ids,
  174. max_length=max_length,
  175. return_dict_in_generate=True,
  176. output_scores=True,
  177. enable_timing=True,
  178. )
  179. print(out.sequences)
  180. print(tokenizer.batch_decode(out.sequences.tolist()))
  181. if getattr(config, "use_flash_attn", False):
  182. out_cg = model.generate(
  183. input_ids=input_ids,
  184. max_length=max_length,
  185. cg=True,
  186. return_dict_in_generate=True,
  187. output_scores=True,
  188. enable_timing=True,
  189. )
  190. print(out_cg.sequences)
  191. assert torch.equal(torch.stack(out.scores, dim=1), torch.stack(out_cg.scores, dim=1))
  192. if not rotary:
  193. out_hf = model_hf.generate(
  194. input_ids=input_ids,
  195. max_length=max_length,
  196. return_dict_in_generate=True,
  197. output_scores=True,
  198. )
  199. out_ref = model_ref.generate(
  200. input_ids=input_ids,
  201. max_length=max_length,
  202. return_dict_in_generate=True,
  203. output_scores=True,
  204. )
  205. print(
  206. f"Scores max diff: {(torch.stack(out.scores, 1) - torch.stack(out_ref.scores, 1)).abs().max().item()}"
  207. )
  208. print(
  209. f"Scores mean diff: {(torch.stack(out.scores, 1) - torch.stack(out_ref.scores, 1)).abs().mean().item()}"
  210. )
  211. print(
  212. f"HF fp16 max diff: {(torch.stack(out_hf.scores, 1) - torch.stack(out_ref.scores, 1)).abs().max().item()}"
  213. )
  214. print(
  215. f"HF fp16 mean diff: {(torch.stack(out_hf.scores, 1) - torch.stack(out_ref.scores, 1)).abs().mean().item()}"
  216. )
  217. print(tokenizer.batch_decode(out_ref.sequences.tolist()))
  218. assert torch.all(out.sequences == sequences)
  219. assert torch.allclose(
  220. torch.stack(out.scores, dim=1), torch.stack(scores, dim=1), rtol=rtol, atol=atol
  221. )
  222. if not rotary:
  223. assert torch.all(out.sequences == out_ref.sequences)
  224. assert torch.all(out.sequences == out_hf.sequences)
  225. assert (
  226. torch.stack(out.scores, 1) - torch.stack(out_ref.scores, 1)
  227. ).abs().max().item() < 3 * (
  228. torch.stack(out_hf.scores, 1) - torch.stack(out_ref.scores, 1)
  229. ).abs().max().item()
  230. def get_logits(model, input_ids, max_length, teacher_outputs=None, **kwargs):
  231. out = model.generate(
  232. input_ids=input_ids,
  233. max_length=max_length,
  234. teacher_outputs=teacher_outputs,
  235. return_dict_in_generate=True,
  236. output_scores=True,
  237. enable_timing=True,
  238. **kwargs,
  239. )
  240. return torch.stack(out.scores, dim=1)
  241. @pytest.mark.parametrize("seqlen,maxlen", [(10, 20), (30, 150), (3000, 3400), (14000, 15000)])
  242. # @pytest.mark.parametrize('seqlen,maxlen', [(10, 20)])
  243. @pytest.mark.parametrize("rotary", [None, "interleaved", "contiguous"])
  244. # @pytest.mark.parametrize('rotary', [None])
  245. @pytest.mark.parametrize("model_name", ["gpt2"])
  246. def test_gpt2_generation_cg(model_name, rotary, seqlen, maxlen):
  247. """Check that decoding with CUDA graph is the same as decoding without CUDA graph."""
  248. dtype = torch.float16
  249. device = "cuda"
  250. rtol, atol = 3e-3, 3e-1
  251. config = GPT2Config.from_pretrained(model_name)
  252. config.n_positions = 16 * 1024
  253. assert seqlen <= maxlen <= config.n_positions
  254. if rotary is not None:
  255. config.n_positions = 0
  256. config.rotary_emb_dim = 32
  257. config.rotary_emb_interleaved = rotary == "interleaved"
  258. config.residual_in_fp32 = True
  259. config.use_flash_attn = True
  260. config.fused_bias_fc = True
  261. config.fused_mlp = True
  262. config.fused_dropout_add_ln = True
  263. model = GPTLMHeadModel(config, device=device, dtype=dtype)
  264. model.eval()
  265. torch.manual_seed(0)
  266. batch_size = 1
  267. input_ids = torch.randint(
  268. 0, config.vocab_size, (batch_size, seqlen), dtype=torch.long, device=device
  269. )
  270. teacher_outputs = torch.randint(
  271. 0, config.vocab_size, (batch_size, maxlen), dtype=torch.long, device=device
  272. )
  273. logits = get_logits(model, input_ids, maxlen, teacher_outputs=teacher_outputs)
  274. logits_cg = get_logits(model, input_ids, maxlen, teacher_outputs=teacher_outputs, cg=True)
  275. assert torch.equal(logits, logits_cg)
  276. # Try increasing batch size and seqlen, then decrease them to see if it's still correct
  277. batch_size = 3
  278. maxlen += 30
  279. input_ids = torch.randint(
  280. 0, config.vocab_size, (batch_size, seqlen), dtype=torch.long, device=device
  281. )
  282. teacher_outputs = torch.randint(
  283. 0, config.vocab_size, (batch_size, maxlen), dtype=torch.long, device=device
  284. )
  285. logits = get_logits(model, input_ids, maxlen, teacher_outputs=teacher_outputs)
  286. logits_cg = get_logits(model, input_ids, maxlen, teacher_outputs=teacher_outputs, cg=True)
  287. assert torch.equal(logits, logits_cg)
  288. batch_size = 2
  289. maxlen -= 35
  290. input_ids = torch.randint(
  291. 0, config.vocab_size, (batch_size, seqlen), dtype=torch.long, device=device
  292. )
  293. teacher_outputs = torch.randint(
  294. 0, config.vocab_size, (batch_size, maxlen), dtype=torch.long, device=device
  295. )
  296. logits = get_logits(model, input_ids, maxlen, teacher_outputs=teacher_outputs)
  297. logits_cg = get_logits(model, input_ids, maxlen, teacher_outputs=teacher_outputs, cg=True)
  298. assert torch.equal(logits, logits_cg)
  299. @pytest.mark.parametrize("optimized", [False, True])
  300. # @pytest.mark.parametrize("optimized", [False])
  301. @pytest.mark.parametrize("model_name", ["gpt2"])
  302. def test_gpt2_multiple_token_generation(model_name, optimized):
  303. """Generation when we pass in multiple tokens at a time, not just one."""
  304. dtype = torch.float16
  305. device = "cuda"
  306. rtol, atol = 3e-3, 3e-1
  307. config = GPT2Config.from_pretrained(model_name)
  308. config.residual_in_fp32 = True
  309. if optimized:
  310. config.use_flash_attn = True
  311. config.fused_bias_fc = True
  312. config.fused_mlp = True
  313. config.fused_dropout_add_ln = True
  314. model = GPTLMHeadModel.from_pretrained(model_name, config, device=device, dtype=dtype)
  315. model.eval()
  316. torch.manual_seed(0)
  317. input_ids = torch.randint(0, config.vocab_size, (1, 20), dtype=torch.long, device=device)
  318. # Reference logits
  319. logits_ref = model(input_ids).logits
  320. # Run 10 tokens, then pass in another 4, then another 6, to see if we get the same logits
  321. inference_params = InferenceParams(max_seqlen=20, max_batch_size=1)
  322. logits_10 = model(input_ids[:, :10], inference_params=inference_params).logits
  323. inference_params.seqlen_offset += 10
  324. position_ids = torch.arange(10, 14, dtype=torch.long, device=device)
  325. logits_1014 = model(
  326. input_ids[:, 10:14], position_ids=position_ids, inference_params=inference_params
  327. ).logits
  328. inference_params.seqlen_offset += 4
  329. position_ids = torch.arange(14, 20, dtype=torch.long, device=device)
  330. logits_1420 = model(
  331. input_ids[:, 14:20], position_ids=position_ids, inference_params=inference_params
  332. ).logits
  333. logits = torch.cat([logits_10, logits_1014, logits_1420], dim=1)
  334. print(f"Logits max diff: {(logits - logits_ref).abs().max().item()}")
  335. print(f"Logits mean diff: {(logits - logits_ref).abs().mean().item()}")
  336. assert torch.allclose(logits, logits_ref, rtol=rtol, atol=atol)
  337. @pytest.mark.parametrize("cg", [False, True])
  338. # @pytest.mark.parametrize("cg", [True])
  339. @pytest.mark.parametrize("optimized", [False, True])
  340. # @pytest.mark.parametrize("optimized", [True])
  341. # @pytest.mark.parametrize("model_name", ["gpt2-medium"])
  342. @pytest.mark.parametrize("model_name", ["gpt2-xl"])
  343. def test_gpt2_speculative_decoding(model_name, optimized, cg):
  344. if cg and not optimized:
  345. pytest.skip() # CG requires use_flash_attn
  346. dtype = torch.float16
  347. device = "cuda"
  348. rtol, atol = 3e-3, 3e-1
  349. config = GPT2Config.from_pretrained(model_name)
  350. config.residual_in_fp32 = True
  351. if optimized:
  352. config.use_flash_attn = True
  353. config.fused_bias_fc = True
  354. config.fused_mlp = True
  355. config.fused_dropout_add_ln = True
  356. config_draft = GPT2Config.from_pretrained("gpt2")
  357. config_draft.residual_in_fp32 = True
  358. if optimized:
  359. config_draft.use_flash_attn = True
  360. config_draft.fused_bias_fc = True
  361. config_draft.fused_mlp = True
  362. config_draft.fused_dropout_add_ln = True
  363. model = GPTLMHeadModel.from_pretrained(model_name, config, device=device, dtype=dtype)
  364. model.eval()
  365. model_draft = GPTLMHeadModel.from_pretrained("gpt2", config_draft, device=device, dtype=dtype)
  366. model_draft.eval()
  367. torch.manual_seed(0)
  368. tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
  369. input_ids = tokenizer("Hello, my dog is cute and he", return_tensors="pt").input_ids.to(
  370. device=device
  371. )
  372. max_length = 100
  373. from flash_attn.utils.generation import decode_speculative
  374. torch.manual_seed(42)
  375. print(f"Speculative decoding, {optimized = }")
  376. out = decode_speculative(
  377. input_ids,
  378. model,
  379. model_draft,
  380. max_length=max_length,
  381. top_k=5,
  382. cg=cg,
  383. speculative_lookahead=4,
  384. enable_timing=True,
  385. # debug=True,
  386. )
  387. print(tokenizer.batch_decode(out.sequences))
  388. print(f"Without speculative decoding, {cg = }")
  389. out_og = model.generate(
  390. input_ids,
  391. max_length=max_length,
  392. top_k=5,
  393. cg=cg,
  394. enable_timing=True,
  395. return_dict_in_generate=True,
  396. )
  397. print(tokenizer.batch_decode(out_og.sequences))
  398. @pytest.mark.parametrize(
  399. "n_heads_q_kv",
  400. [
  401. (8, 8), # Regular attention
  402. (8, 4), # GQA
  403. (8, 2), # MQA
  404. ],
  405. )
  406. def test_gpt2_shard_unshard(n_heads_q_kv):
  407. world_size = 2
  408. config = GPT2Config.from_pretrained("gpt2")
  409. config.vocab_size = 1024
  410. config.n_head, config.n_head_kv = n_heads_q_kv
  411. model = GPTLMHeadModel(config, device="cuda", dtype=torch.float16)
  412. state_dict = model.state_dict()
  413. shards = [
  414. # NOTE: Shallow copy as `state_dict` is modified in-place
  415. shard_state_dict_tp(dict(state_dict), config, world_size, rank)
  416. for rank in range(world_size)
  417. ]
  418. state_dict2 = combine_state_dicts_tp(shards, config)
  419. assert state_dict2.keys() == state_dict.keys()
  420. for k in state_dict.keys():
  421. ref = state_dict[k]
  422. new = state_dict[k]
  423. assert torch.allclose(ref, new, atol=0.0, rtol=0.0)