|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import sys |
| 4 | +from dataclasses import dataclass, field |
| 5 | +from warnings import warn |
| 6 | + |
| 7 | +import torch |
| 8 | +import transformers |
| 9 | +from transformers.trainer_utils import get_last_checkpoint |
| 10 | +from transformers import ( |
| 11 | + AutoConfig, |
| 12 | + AutoModelForCausalLM, |
| 13 | + AutoTokenizer, |
| 14 | + HfArgumentParser, |
| 15 | + Trainer, |
| 16 | + default_data_collator, |
| 17 | + set_seed, |
| 18 | + TrainerCallback, |
| 19 | +) |
| 20 | + |
| 21 | +from utils import ( |
| 22 | + get_metrics_with_perplexity, |
| 23 | + make_supervised_data_module, |
| 24 | +) |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | +@dataclass |
| 29 | +class ModelArguments: |
| 30 | + model_name_or_path: str = field(default="meta-llama/Llama-3.1-8B") |
| 31 | + |
| 32 | +@dataclass |
| 33 | +class TrainingArguments(transformers.TrainingArguments): |
| 34 | + cache_dir: str | None = field(default=None) |
| 35 | + model_max_length: int = field( |
| 36 | + default=2048, |
| 37 | + metadata={ |
| 38 | + "help": ( |
| 39 | + "Maximum sequence length. Sequences will be right padded (and possibly truncated)." |
| 40 | + ) |
| 41 | + }, |
| 42 | + ) |
| 43 | + dataloader_drop_last: bool = field(default=True) |
| 44 | + bf16: bool = field(default=True) |
| 45 | + |
| 46 | +@dataclass |
| 47 | +class DataArguments: |
| 48 | + dataset: str = field( |
| 49 | + default="Daring-Anteater", |
| 50 | + metadata={"help": "Specify the dataset.", "choices": ["Daring-Anteater"]}, |
| 51 | + ) |
| 52 | + train_size: int = field( |
| 53 | + default=0, |
| 54 | + metadata={"help": "Number of training samples to use. If `0`, use default training size."}, |
| 55 | + ) |
| 56 | + eval_size: int = field( |
| 57 | + default=0, |
| 58 | + metadata={ |
| 59 | + "help": "Number of evaluation samples to use. If `0`, use default evaluation size." |
| 60 | + }, |
| 61 | + ) |
| 62 | + |
| 63 | +@dataclass |
| 64 | +class QuantizationArguments: |
| 65 | + quant_scheme: str | None = field( |
| 66 | + default=None, |
| 67 | + metadata={ |
| 68 | + "help": ( |
| 69 | + "Specify the quantization format for PTQ/QAT. if specified, PTQ/QAT will be enabled" |
| 70 | + " with the specified quantization format" |
| 71 | + ), |
| 72 | + "choices": ["MXFP8"], |
| 73 | + }, |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +def train(): |
| 78 | + parser = HfArgumentParser( |
| 79 | + (ModelArguments, TrainingArguments, DataArguments, QuantizationArguments) |
| 80 | + ) |
| 81 | + |
| 82 | + model_args, training_args, data_args, quant_args = parser.parse_args_into_dataclasses() |
| 83 | + |
| 84 | + # Setup logging |
| 85 | + logging.basicConfig( |
| 86 | + level=logging.INFO, |
| 87 | + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", |
| 88 | + datefmt="%m/%d/%Y %H:%M:%S", |
| 89 | + handlers=[logging.StreamHandler(sys.stdout)], |
| 90 | + ) |
| 91 | + |
| 92 | + # Log on each process the small summary: |
| 93 | + logger.warning( |
| 94 | + f"Process rank: {training_args.local_process_index}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " |
| 95 | + + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}" |
| 96 | + ) |
| 97 | + # Set seed before initializing model. |
| 98 | + set_seed(training_args.seed) |
| 99 | + |
| 100 | + logger.info(f"arguments: {model_args}, {training_args}, {data_args}, {quant_args}") |
| 101 | + |
| 102 | + # Detecting last checkpoint. |
| 103 | + last_checkpoint = None |
| 104 | + if os.path.isdir(training_args.output_dir) and training_args.do_train: |
| 105 | + last_checkpoint = get_last_checkpoint(training_args.output_dir) |
| 106 | + logger.info(f"Last checkpoint detected: {last_checkpoint}") |
| 107 | + |
| 108 | + |
| 109 | + model = AutoModelForCausalLM.from_pretrained( |
| 110 | + model_args.model_name_or_path, |
| 111 | + cache_dir=training_args.cache_dir, |
| 112 | + torch_dtype=torch.bfloat16, |
| 113 | + ) |
| 114 | + model.generation_config.do_sample = True |
| 115 | + tokenizer = AutoTokenizer.from_pretrained( |
| 116 | + model_args.model_name_or_path, model_max_length=training_args.model_max_length |
| 117 | + ) |
| 118 | + tokenizer.pad_token_id = tokenizer.eos_token_id |
| 119 | + |
| 120 | + # We set model.config.use_cache to False for training when gradient_checkpointing=False. |
| 121 | + # Currently useful for FSDP2 to allow for setting activation_checkpointing=True in the config file. |
| 122 | + model.config.use_cache = False |
| 123 | + |
| 124 | + # prepare model for quantization |
| 125 | + if quant_args.quant_scheme is not None: |
| 126 | + from neural_compressor.torch.quantization.quantize import prepare_qat |
| 127 | + # inplace |
| 128 | + # default mxfp8 |
| 129 | + prepare_qat(model) |
| 130 | + |
| 131 | + logger.info("Finish model preparation for QAT.") |
| 132 | + |
| 133 | + logger.info("Loading dataset......") |
| 134 | + |
| 135 | + # reuse the dataset function, TODO: preprocess a new dataset |
| 136 | + data_module = make_supervised_data_module( |
| 137 | + dataset=data_args.dataset, |
| 138 | + tokenizer=tokenizer, |
| 139 | + train_size=data_args.train_size, |
| 140 | + eval_size=data_args.eval_size, |
| 141 | + ) |
| 142 | + |
| 143 | + # Ensure calibration size doesn't exceed evaluation dataset size |
| 144 | + eval_dataset_size = len(data_module["eval_dataset"]) |
| 145 | + |
| 146 | + # Training |
| 147 | + checkpoint = None |
| 148 | + if training_args.resume_from_checkpoint is not None: |
| 149 | + checkpoint = training_args.resume_from_checkpoint |
| 150 | + elif last_checkpoint is not None: |
| 151 | + checkpoint = last_checkpoint |
| 152 | + |
| 153 | + # Torch >= 2.4 throws an error if `use_reentrant` is not set explicitly |
| 154 | + if training_args.gradient_checkpointing and training_args.gradient_checkpointing_kwargs is None: |
| 155 | + training_args.gradient_checkpointing_kwargs = {"use_reentrant": True} |
| 156 | + |
| 157 | + trainer = Trainer( |
| 158 | + model=model, |
| 159 | + processing_class=tokenizer, |
| 160 | + args=training_args, |
| 161 | + **data_module, |
| 162 | + ) |
| 163 | + |
| 164 | + if training_args.do_train: |
| 165 | + logger.info("Starting Train...") |
| 166 | + trainer.train(resume_from_checkpoint=checkpoint) |
| 167 | + logger.info("Training completed.") |
| 168 | + |
| 169 | + if training_args.do_eval: |
| 170 | + logger.info("Starting Evaluation...") |
| 171 | + metrics = trainer.evaluate() |
| 172 | + metrics = get_metrics_with_perplexity(metrics) |
| 173 | + logger.info(f"Evaluation results: \n{metrics}") |
| 174 | + |
| 175 | + if training_args.do_train and quant_args.quant_scheme is None: |
| 176 | + logger.info("Saving the model...") |
| 177 | + trainer.save_model(training_args.output_dir) |
| 178 | + elif quant_args.quant_scheme is not None: |
| 179 | + from neural_compressor.torch.export.export_hf import export_hf2compressored_model |
| 180 | + # export quantized model for vllm inference using llm-compressor and compressed_tensor |
| 181 | + export_hf2compressored_model(model, training_args.output_dir, quant_args.quant_scheme) |
| 182 | + if tokenizer is not None: |
| 183 | + tokenizer.save_pretrained(training_args.output_dir) |
| 184 | + |
| 185 | + |
| 186 | +if __name__ == "__main__": |
| 187 | + train() |
0 commit comments