| 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 os |
| 11 | from typing import Optional |
| 12 | |
| 13 | import torch |
| 14 | |
| 15 | from fairscale.nn.model_parallel.mappings import reduce_from_model_parallel_region |
| 16 | from llama_models.llama3.api.model import Transformer, TransformerBlock |
| 17 | from llama_stack.apis.inference import QuantizationType |
| 18 | |
| 19 | from llama_stack.apis.inference.config import ( |
| 20 | CheckpointQuantizationFormat, |
| 21 | MetaReferenceImplConfig, |
| 22 | ) |
| 23 | |
| 24 | from termcolor import cprint |
| 25 | from torch import Tensor |
| 26 | |
| 27 | |
| 28 | def is_fbgemm_available() -> bool: |
| 29 | try: |
| 30 | import fbgemm_gpu.experimental.gen_ai # noqa: F401 |
| 31 | |
| 32 | return True |
| 33 | except ImportError: |
| 34 | return False |
| 35 | |
| 36 | |
| 37 | def swiglu_wrapper( |
| 38 | self, |
| 39 | x: Tensor, |
| 40 | ): |
| 41 | from .fp8_impls import ffn_swiglu |
| 42 | |
| 43 | out = ffn_swiglu(x, self.w1.weight, self.w3.weight, self.w2.weight) |
| 44 | return reduce_from_model_parallel_region(out) |
| 45 | |
| 46 | |
| 47 | def convert_to_quantized_model( |
| 48 | model: Transformer, |
| 49 | config: MetaReferenceImplConfig, |
| 50 | fp8_activation_scale_ub: Optional[float] = 1200.0, |
| 51 | ) -> Transformer: |
| 52 | if config.quantization.type == QuantizationType.bf16.value: |
| 53 | return model |
| 54 | |
| 55 | elif config.quantization.type != QuantizationType.fp8.value: |
| 56 | raise ValueError("Only FP8 quantization is supported") |
| 57 | |
| 58 | from .fp8_impls import Fp8ScaledWeights, load_fp8, quantize_fp8 |
| 59 | |
| 60 | checkpoint = config.checkpoint_config.checkpoint |
| 61 | # Move weights to GPU with quantization |
| 62 | if checkpoint.quantization_format == CheckpointQuantizationFormat.fp8_mixed.value: |
| 63 | cprint("Loading fp8 scales...", "yellow") |
| 64 | fp8_scales_path = os.path.join( |
| 65 | checkpoint.checkpoint_dir, f"fp8_scales_{get_model_parallel_rank()}.pt" |
| 66 | ) |
| 67 | assert os.path.isfile( |
| 68 | fp8_scales_path |
| 69 | ), f"fp8_scales_path not found for rank {get_model_parallel_rank()}" |
| 70 | fp8_scales = torch.load(fp8_scales_path, weights_only=True) |
| 71 | |
| 72 | for block in model.layers: |
| 73 | if isinstance(block, TransformerBlock): |
| 74 | if block.layer_id == 0 or block.layer_id == (model.n_layers - 1): |
| 75 | continue |
| 76 | |
| 77 | block.feed_forward.forward = swiglu_wrapper.__get__(block.feed_forward) |
| 78 | for key in ("w1", "w3", "w2"): |
| 79 | param = getattr(block.feed_forward, key) |
| 80 | param.weight = load_fp8( |
| 81 | param.weight, |
| 82 | fp8_scales[ |
| 83 | f"{block.layer_id}_feed_forward.{key}_{get_model_parallel_rank()}" |
| 84 | ], |
| 85 | fp8_activation_scale_ub, |
| 86 | ) |
| 87 | else: |
| 88 | cprint("Quantizing fp8 weights from bf16...", "yellow") |
| 89 | for block in model.layers: |
| 90 | if isinstance(block, TransformerBlock): |
| 91 | if block.layer_id == 0 or block.layer_id == (model.n_layers - 1): |
| 92 | continue |
| 93 | block.feed_forward.forward = swiglu_wrapper.__get__(block.feed_forward) |
| 94 | for key in ("w1", "w3", "w2"): |
| 95 | param = getattr(block.feed_forward, key) |
| 96 | param.weight = quantize_fp8( |
| 97 | param.weight, |
| 98 | fp8_activation_scale_ub, |
| 99 | output_device=torch.device("cuda"), |
| 100 | ) |
| 101 | |
| 102 | for _, parameter in model.named_parameters(): |
| 103 | if not isinstance(parameter, Fp8ScaledWeights): |
| 104 | parameter.data = parameter.to(device="cuda") |
| 105 | return model |