|
| 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 | +# pyre-unsafe |
| 8 | + |
| 9 | +import json |
| 10 | +from typing import Any, Dict |
| 11 | + |
| 12 | +import torch |
| 13 | +from executorch.examples.models.checkpoint import ( |
| 14 | + get_checkpoint_dtype, |
| 15 | + get_default_model_resource_dir, |
| 16 | +) |
| 17 | + |
| 18 | +from executorch.examples.models.model_base import EagerModelBase |
| 19 | +from torchtune.models.llama3_2._model_builders import llama3_2_1b |
| 20 | +from torchtune.models.convert_weights import meta_to_tune |
| 21 | + |
| 22 | + |
| 23 | +class Llama3_2(EagerModelBase): |
| 24 | + """ |
| 25 | + Llama3.2 as from TorchTune. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, **kwargs): |
| 29 | + # Set member vars from kwargs. |
| 30 | + self.max_seq_len = kwargs.get( |
| 31 | + "max_seq_len", 8192 |
| 32 | + ) # Trained to be a lot larger, but this value is kept small because of static kv cache at the moment. |
| 33 | + self.encoder_max_seq_len = kwargs.get( |
| 34 | + "encoder_max_seq_len", int(4 * (448 / 14) ** 2 + 1) |
| 35 | + ) # Same as above. |
| 36 | + self.output_prune_map_path = kwargs.get("output_prune_map_path", None) |
| 37 | + self.use_kv_cache = kwargs.get("use_kv_cache", False) |
| 38 | + self.verbose = kwargs.get("verbose", False) |
| 39 | + self.args = kwargs.get("args", None) |
| 40 | + |
| 41 | + ckpt_dir = get_default_model_resource_dir(__file__) |
| 42 | + # Single checkpoint file. |
| 43 | + checkpoint_path = kwargs.get("checkpoint", ckpt_dir / "demo_rand_params.pth") |
| 44 | + # Sharded checkpoint. |
| 45 | + checkpoint_dir = kwargs.get("checkpoint_dir", None) |
| 46 | + params_path = kwargs.get("params", ckpt_dir / "demo_config.json") |
| 47 | + |
| 48 | + self.causal_mask = torch.tril( |
| 49 | + torch.ones( |
| 50 | + size=(self.max_seq_len, self.max_seq_len), |
| 51 | + dtype=torch.bool, |
| 52 | + ) |
| 53 | + ) |
| 54 | + self.input_pos = torch.arange(self.max_seq_len) |
| 55 | + |
| 56 | + # Load checkpoint and params. |
| 57 | + device = "cpu" |
| 58 | + if checkpoint_dir is not None: |
| 59 | + raise NotImplementedError( |
| 60 | + "Sharded checkpoint not yet supported for Llama3_2Decoder." |
| 61 | + ) |
| 62 | + else: |
| 63 | + checkpoint = torch.load(checkpoint_path, map_location=device, mmap=True) |
| 64 | + checkpoint = meta_to_tune(checkpoint) |
| 65 | + with open(params_path, "r") as f: |
| 66 | + params = json.loads(f.read()) |
| 67 | + |
| 68 | + # Find dtype from checkpoint. (skip for now) |
| 69 | + self.dtype = get_checkpoint_dtype(checkpoint) |
| 70 | + |
| 71 | + # Load model. |
| 72 | + self.model_ = llama3_2_1b() |
| 73 | + |
| 74 | + # Save params for future use. |
| 75 | + for param_name, param_val in params.items(): |
| 76 | + setattr(self.model_, param_name, param_val) |
| 77 | + |
| 78 | + # Quantize. (skip for now) |
| 79 | + |
| 80 | + # Load checkpoint. |
| 81 | + missing, unexpected = self.model_.load_state_dict( |
| 82 | + checkpoint, |
| 83 | + strict=False, |
| 84 | + assign=True, |
| 85 | + ) |
| 86 | + if kwargs.get("verbose", False): |
| 87 | + print("============= missing keys ================") |
| 88 | + print(missing) |
| 89 | + print("============= /missing ================") |
| 90 | + print("============= unexpected keys ================") |
| 91 | + print(unexpected) |
| 92 | + print("============= /unexpected ================") |
| 93 | + |
| 94 | + # Prune the output layer if output_prune_map is provided. |
| 95 | + output_prune_map = None |
| 96 | + if self.output_prune_map_path is not None: |
| 97 | + from executorch.examples.models.llama2.source_transformation.prune_output import ( |
| 98 | + prune_output_vocab, |
| 99 | + ) |
| 100 | + |
| 101 | + with open(self.output_prune_map_path, "r") as f: |
| 102 | + output_prune_map = json.load(f) |
| 103 | + # Change keys from string to int (json only supports string keys) |
| 104 | + output_prune_map = {int(k): v for (k, v) in output_prune_map.items()} |
| 105 | + |
| 106 | + self.model_ = prune_output_vocab(self.model_, output_prune_map) |
| 107 | + |
| 108 | + if self.use_kv_cache: |
| 109 | + print("Setting up KV cache on the model...") |
| 110 | + self.model_.setup_caches( |
| 111 | + batch_size=1, |
| 112 | + dtype=self.dtype, |
| 113 | + decoder_max_seq_len=self.max_seq_len, |
| 114 | + ) |
| 115 | + |
| 116 | + def get_eager_model(self) -> torch.nn.Module: |
| 117 | + if self.dtype: |
| 118 | + return self.model_.to(self.dtype) |
| 119 | + else: |
| 120 | + return self.model_.to(torch.float16) |
| 121 | + |
| 122 | + def get_example_inputs(self): |
| 123 | + return (torch.ones(1, 32, dtype=torch.long),) |
| 124 | + |
| 125 | + def get_example_kwarg_inputs(self): |
| 126 | + # For export we must use the prefill versions of the |
| 127 | + # causal mask and input_pos. |
| 128 | + if self.use_kv_cache: |
| 129 | + return { |
| 130 | + "input_pos": self.input_pos[None, :32], |
| 131 | + "mask": self.causal_mask[None, :32], |
| 132 | + } |
| 133 | + else: |
| 134 | + return None |
| 135 | + |
| 136 | + def get_dynamic_shapes(self): |
| 137 | + batch_size = 1 |
| 138 | + dim_seq_len = torch.export.Dim("token_dim", min=1, max=self.max_seq_len) |
| 139 | + if self.use_kv_cache: |
| 140 | + dynamic_shapes = { |
| 141 | + "tokens": {0: batch_size, 1: dim_seq_len}, |
| 142 | + "input_pos" : {0: batch_size, 1: dim_seq_len}, |
| 143 | + "mask": {0: batch_size, 1: dim_seq_len, 2: None}, |
| 144 | + } |
| 145 | + else: |
| 146 | + dynamic_shapes = { |
| 147 | + "tokens": {0: batch_size, 1: dim_seq_len}, |
| 148 | + } |
| 149 | + return dynamic_shapes |
| 150 | + |
0 commit comments