|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""Compare GGML LLM runner prefill and decoding with a tiny eager HF Llama.""" |
| 8 | + |
| 9 | +import argparse |
| 10 | +import base64 |
| 11 | +import re |
| 12 | +import subprocess |
| 13 | +import tempfile |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +import torch |
| 17 | +from executorch.backends.native.examples.hf_llm.export_hf_llm import LastTokenLM |
| 18 | +from executorch.exir.native import to_native |
| 19 | +from transformers import LlamaConfig, LlamaForCausalLM |
| 20 | + |
| 21 | + |
| 22 | +@torch.no_grad() |
| 23 | +def main() -> None: |
| 24 | + parser = argparse.ArgumentParser(description=__doc__) |
| 25 | + parser.add_argument("--runner", required=True, type=Path) |
| 26 | + args = parser.parse_args() |
| 27 | + |
| 28 | + torch.manual_seed(0) |
| 29 | + torch.set_num_threads(4) |
| 30 | + max_seq_length = 48 |
| 31 | + max_new_tokens = 8 |
| 32 | + config = LlamaConfig( |
| 33 | + vocab_size=512, |
| 34 | + hidden_size=32, |
| 35 | + intermediate_size=64, |
| 36 | + num_hidden_layers=2, |
| 37 | + num_attention_heads=4, |
| 38 | + num_key_value_heads=2, |
| 39 | + max_position_embeddings=max_seq_length, |
| 40 | + bos_token_id=256, |
| 41 | + eos_token_id=257, |
| 42 | + attn_implementation="sdpa", |
| 43 | + ) |
| 44 | + model = LlamaForCausalLM(config).eval() |
| 45 | + model.generation_config.use_cache = True |
| 46 | + model.generation_config.cache_implementation = "static" |
| 47 | + wrapper = LastTokenLM(model, max_seq_length).eval() |
| 48 | + seq = torch.export.Dim("seq", min=1, max=max_seq_length - 1) |
| 49 | + exported = torch.export.export( |
| 50 | + wrapper, |
| 51 | + (torch.zeros((1, 6), dtype=torch.long), torch.arange(6)), |
| 52 | + dynamic_shapes={"input_ids": {1: seq}, "cache_position": {0: seq}}, |
| 53 | + strict=True, |
| 54 | + ) |
| 55 | + |
| 56 | + with tempfile.TemporaryDirectory() as directory: |
| 57 | + root = Path(directory) |
| 58 | + package = root / "llama.ptn" |
| 59 | + to_native(exported).save(str(package)) |
| 60 | + tokenizer = root / "tokenizer.model" |
| 61 | + # The byte vocabulary puts Llama's BOS at 256, followed by 255 specials. |
| 62 | + tokenizer.write_text( |
| 63 | + "".join( |
| 64 | + f"{base64.b64encode(bytes([i])).decode()} {i}\n" for i in range(256) |
| 65 | + ) |
| 66 | + ) |
| 67 | + prompt = "abc" |
| 68 | + tokens = [config.bos_token_id, *prompt.encode()] |
| 69 | + expected = [] |
| 70 | + # Recompute the full prefix without a cache for an independent reference. |
| 71 | + for _ in range(max_new_tokens): |
| 72 | + logits = model(torch.tensor([tokens]), use_cache=False).logits |
| 73 | + token = int(logits[0, -1].argmax()) |
| 74 | + expected.append(token) |
| 75 | + tokens.append(token) |
| 76 | + |
| 77 | + result = subprocess.run( |
| 78 | + [ |
| 79 | + str(args.runner.resolve()), |
| 80 | + "--device=cpu", |
| 81 | + "--cpu_threads=4", |
| 82 | + f"--package={package}", |
| 83 | + f"--tokenizer={tokenizer}", |
| 84 | + f"--prompt={prompt}", |
| 85 | + f"--eos_ids={config.vocab_size}", |
| 86 | + f"--max_new_tokens={max_new_tokens}", |
| 87 | + f"--max_seq_length={max_seq_length}", |
| 88 | + "--print_token_ids", |
| 89 | + ], |
| 90 | + capture_output=True, |
| 91 | + text=True, |
| 92 | + errors="replace", |
| 93 | + timeout=120, |
| 94 | + ) |
| 95 | + print(result.stdout, end="") |
| 96 | + print(result.stderr, end="") |
| 97 | + result.check_returncode() |
| 98 | + match = re.search(r"^token_ids: ([0-9,]+)$", result.stdout, re.MULTILINE) |
| 99 | + if match is None: |
| 100 | + raise AssertionError("Runner did not report generated token IDs") |
| 101 | + actual = [int(token) for token in match[1].split(",")] |
| 102 | + if actual != expected: |
| 103 | + raise AssertionError(f"Generated tokens {actual} != eager {expected}") |
| 104 | + print(f"GGML HF LLM runner matched all {max_new_tokens} eager token IDs") |
| 105 | + |
| 106 | + |
| 107 | +if __name__ == "__main__": |
| 108 | + main() |
0 commit comments