|
| 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 | +import argparse |
| 8 | +import os |
| 9 | + |
| 10 | +import torch |
| 11 | +import torch.export._trace |
| 12 | +from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner |
| 13 | +from executorch.exir import EdgeCompileConfig, ExecutorchBackendConfig, to_edge |
| 14 | +from torch.nn.attention import SDPBackend |
| 15 | +from transformers import AutoModelForCausalLM, AutoTokenizer |
| 16 | +from transformers.generation.configuration_utils import GenerationConfig |
| 17 | +from transformers.integrations.executorch import convert_and_export_with_cache |
| 18 | +from transformers.modeling_utils import PreTrainedModel |
| 19 | + |
| 20 | + |
| 21 | +def main() -> None: |
| 22 | + parser = argparse.ArgumentParser() |
| 23 | + parser.add_argument( |
| 24 | + "-hfm", |
| 25 | + "--hf_model_repo", |
| 26 | + required=True, |
| 27 | + default=None, |
| 28 | + help="a valid huggingface model repo name", |
| 29 | + ) |
| 30 | + parser.add_argument( |
| 31 | + "-o", |
| 32 | + "--output_name", |
| 33 | + required=False, |
| 34 | + default=None, |
| 35 | + help="output name of the exported model", |
| 36 | + ) |
| 37 | + |
| 38 | + args = parser.parse_args() |
| 39 | + |
| 40 | + # Configs to HF model |
| 41 | + device = "cpu" |
| 42 | + dtype = torch.float32 |
| 43 | + batch_size = 1 |
| 44 | + max_length = 123 |
| 45 | + cache_implementation = "static" |
| 46 | + attn_implementation = "sdpa" |
| 47 | + |
| 48 | + # Load and configure a HF model |
| 49 | + model = AutoModelForCausalLM.from_pretrained( |
| 50 | + args.hf_model_repo, |
| 51 | + attn_implementation=attn_implementation, |
| 52 | + device_map=device, |
| 53 | + torch_dtype=dtype, |
| 54 | + generation_config=GenerationConfig( |
| 55 | + use_cache=True, |
| 56 | + cache_implementation=cache_implementation, |
| 57 | + max_length=max_length, |
| 58 | + cache_config={ |
| 59 | + "batch_size": batch_size, |
| 60 | + "max_cache_len": max_length, |
| 61 | + }, |
| 62 | + ), |
| 63 | + ) |
| 64 | + print(f"{model.config}") |
| 65 | + print(f"{model.generation_config}") |
| 66 | + |
| 67 | + tokenizer = AutoTokenizer.from_pretrained(args.hf_model_repo) |
| 68 | + input_ids = tokenizer([""], return_tensors="pt").to(device)["input_ids"] |
| 69 | + cache_position = torch.tensor([0], dtype=torch.long) |
| 70 | + |
| 71 | + def _get_constant_methods(model: PreTrainedModel): |
| 72 | + return { |
| 73 | + "get_dtype": 5 if model.config.torch_dtype == torch.float16 else 6, |
| 74 | + "get_bos_id": model.config.bos_token_id, |
| 75 | + "get_eos_id": model.config.eos_token_id, |
| 76 | + "get_head_dim": model.config.hidden_size / model.config.num_attention_heads, |
| 77 | + "get_max_batch_size": model.generation_config.cache_config.batch_size, |
| 78 | + "get_max_seq_len": model.generation_config.cache_config.max_cache_len, |
| 79 | + "get_n_bos": 1, |
| 80 | + "get_n_eos": 1, |
| 81 | + "get_n_kv_heads": model.config.num_key_value_heads, |
| 82 | + "get_n_layers": model.config.num_hidden_layers, |
| 83 | + "get_vocab_size": model.config.vocab_size, |
| 84 | + "use_kv_cache": model.generation_config.use_cache, |
| 85 | + } |
| 86 | + |
| 87 | + with torch.nn.attention.sdpa_kernel([SDPBackend.MATH]), torch.no_grad(): |
| 88 | + |
| 89 | + exported_prog = convert_and_export_with_cache(model, input_ids, cache_position) |
| 90 | + prog = ( |
| 91 | + to_edge( |
| 92 | + exported_prog, |
| 93 | + compile_config=EdgeCompileConfig( |
| 94 | + _check_ir_validity=False, |
| 95 | + _skip_dim_order=True, |
| 96 | + ), |
| 97 | + constant_methods=_get_constant_methods(model), |
| 98 | + ) |
| 99 | + .to_backend(XnnpackPartitioner()) |
| 100 | + .to_executorch(ExecutorchBackendConfig(extract_delegate_segments=True)) |
| 101 | + ) |
| 102 | + out_name = args.output_name if args.output_name else model.config.model_type |
| 103 | + filename = os.path.join("./", f"{out_name}.pte") |
| 104 | + with open(filename, "wb") as f: |
| 105 | + prog.write_to_file(f) |
| 106 | + print(f"Saved exported program to {filename}") |
| 107 | + |
| 108 | + |
| 109 | +if __name__ == "__main__": |
| 110 | + main() |
0 commit comments