| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 8 | # This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. |
| 9 | |
| 10 | import json |
| 11 | import os |
| 12 | import shutil |
| 13 | import sys |
| 14 | from pathlib import Path |
| 15 | from typing import Optional |
| 16 | |
| 17 | import fire |
| 18 | |
| 19 | import torch |
| 20 | from fairscale.nn.model_parallel.initialize import ( |
| 21 | get_model_parallel_rank, |
| 22 | initialize_model_parallel, |
| 23 | model_parallel_is_initialized, |
| 24 | ) |
| 25 | from fp8.fp8_impls import FfnQuantizeMode, quantize_fp8 |
| 26 | |
| 27 | from llama.model import ModelArgs, Transformer, TransformerBlock |
| 28 | from llama.tokenizer import Tokenizer |
| 29 | from torch.nn.parameter import Parameter |
| 30 | |
| 31 | |
| 32 | def main( |
| 33 | ckpt_dir: str, |
| 34 | tokenizer_path: str, |
| 35 | quantized_ckpt_dir: str, |
| 36 | max_seq_len: Optional[int] = 512, |
| 37 | max_batch_size: Optional[int] = 4, |
| 38 | model_parallel_size: Optional[int] = None, |
| 39 | ffn_quantize_mode: Optional[FfnQuantizeMode] = FfnQuantizeMode.FP8_ROWWISE, |
| 40 | fp8_activation_scale_ub: Optional[float] = 1200.0, |
| 41 | seed: int = 1, |
| 42 | ): |
| 43 | """ """ |
| 44 | if not os.path.exists(quantized_ckpt_dir): |
| 45 | os.makedirs(quantized_ckpt_dir) |
| 46 | shutil.copy( |
| 47 | os.path.join(ckpt_dir, "params.json"), |
| 48 | os.path.join(quantized_ckpt_dir, "params.json"), |
| 49 | ) |
| 50 | shutil.copy( |
| 51 | os.path.join(ckpt_dir, "tokenizer.model"), |
| 52 | os.path.join(quantized_ckpt_dir, "tokenizer.model"), |
| 53 | ) |
| 54 | |
| 55 | if not torch.distributed.is_initialized(): |
| 56 | torch.distributed.init_process_group("nccl") |
| 57 | if not model_parallel_is_initialized(): |
| 58 | if model_parallel_size is None: |
| 59 | model_parallel_size = int(os.environ.get("WORLD_SIZE", 1)) |
| 60 | initialize_model_parallel(model_parallel_size) |
| 61 | |
| 62 | local_rank = int(os.environ.get("LOCAL_RANK", 0)) |
| 63 | torch.cuda.set_device(local_rank) |
| 64 | |
| 65 | # seed must be the same in all processes |
| 66 | torch.manual_seed(seed) |
| 67 | |
| 68 | if local_rank > 0: |
| 69 | sys.stdout = open(os.devnull, "w") |
| 70 | |
| 71 | checkpoints = sorted(Path(ckpt_dir).glob("*.pth")) |
| 72 | assert len(checkpoints) > 0, f"no checkpoint files found in {ckpt_dir}" |
| 73 | assert model_parallel_size == len( |
| 74 | checkpoints |
| 75 | ), f"Loading a checkpoint for MP={len(checkpoints)} but world size is {model_parallel_size}" |
| 76 | ckpt_path = checkpoints[get_model_parallel_rank()] |
| 77 | checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=True) |
| 78 | with open(Path(ckpt_dir) / "params.json", "r") as f: |
| 79 | params = json.loads(f.read()) |
| 80 | |
| 81 | model_args: ModelArgs = ModelArgs( |
| 82 | max_seq_len=max_seq_len, |
| 83 | max_batch_size=max_batch_size, |
| 84 | **params, |
| 85 | ) |
| 86 | tokenizer = Tokenizer(model_path=tokenizer_path) |
| 87 | assert ( |
| 88 | model_args.vocab_size == tokenizer.n_words |
| 89 | ), f"model_args vocab = {model_args.vocab_size} but tokenizer vocab = {tokenizer.n_words}" |
| 90 | |
| 91 | # load on CPU in bf16 so that fp8 conversion does not find an unexpected (fp32, e.g.) datatype |
| 92 | torch.set_default_tensor_type(torch.BFloat16Tensor) |
| 93 | |
| 94 | model = Transformer(model_args) |
| 95 | model.load_state_dict(checkpoint, strict=False) |
| 96 | |
| 97 | if torch.cuda.is_bf16_supported(): |
| 98 | torch.set_default_tensor_type(torch.cuda.BFloat16Tensor) |
| 99 | else: |
| 100 | torch.set_default_tensor_type(torch.cuda.HalfTensor) |
| 101 | |
| 102 | print(ckpt_path) |
| 103 | assert ( |
| 104 | quantized_ckpt_dir is not None |
| 105 | ), "QUantized checkpoint directory should not be None" |
| 106 | fp8_scales = {} |
| 107 | for block in model.layers: |
| 108 | if isinstance(block, TransformerBlock): |
| 109 | if block.layer_id == 0 or block.layer_id == (model.n_layers - 1): |
| 110 | continue |
| 111 | |
| 112 | fp8_weight = quantize_fp8( |
| 113 | block.feed_forward.w1.weight, |
| 114 | fp8_activation_scale_ub, |
| 115 | ffn_quantize_mode, |
| 116 | output_device=torch.device("cpu"), |
| 117 | ) |
| 118 | with torch.inference_mode(): |
| 119 | block.feed_forward.w1.weight = Parameter(fp8_weight.weight) |
| 120 | fp8_scales[ |
| 121 | f"{block.layer_id}_feed_forward.w1_{get_model_parallel_rank()}" |
| 122 | ] = fp8_weight.scale |
| 123 | |
| 124 | fp8_weight = quantize_fp8( |
| 125 | block.feed_forward.w3.weight, |
| 126 | fp8_activation_scale_ub, |
| 127 | ffn_quantize_mode, |
| 128 | output_device=torch.device("cpu"), |
| 129 | ) |
| 130 | with torch.inference_mode(): |
| 131 | block.feed_forward.w3.weight = Parameter(fp8_weight.weight) |
| 132 | fp8_scales[ |
| 133 | f"{block.layer_id}_feed_forward.w3_{get_model_parallel_rank()}" |
| 134 | ] = fp8_weight.scale |
| 135 | |
| 136 | fp8_weight = quantize_fp8( |
| 137 | block.feed_forward.w2.weight, |
| 138 | fp8_activation_scale_ub, |
| 139 | ffn_quantize_mode, |
| 140 | output_device=torch.device("cpu"), |
| 141 | ) |
| 142 | with torch.inference_mode(): |
| 143 | block.feed_forward.w2.weight = Parameter(fp8_weight.weight) |
| 144 | fp8_scales[ |
| 145 | f"{block.layer_id}_feed_forward.w2_{get_model_parallel_rank()}" |
| 146 | ] = fp8_weight.scale |
| 147 | |
| 148 | fp8_scales_path = os.path.join( |
| 149 | quantized_ckpt_dir, f"fp8_scales_{get_model_parallel_rank()}.pt" |
| 150 | ) |
| 151 | torch.save(fp8_scales, fp8_scales_path) |
| 152 | |
| 153 | ckpt_path = os.path.join( |
| 154 | quantized_ckpt_dir, |
| 155 | "consolidated.{:02d}.pth".format(get_model_parallel_rank()), |
| 156 | ) |
| 157 | torch.save(model.state_dict(), ckpt_path) |
| 158 | |
| 159 | |
| 160 | if __name__ == "__main__": |
| 161 | fire.Fire(main) |