From 713658adc70fedf553abe2671fe204d3d99c35a2 Mon Sep 17 00:00:00 2001 From: Jingyan Wang Date: Fri, 31 May 2024 19:13:19 +0000 Subject: [PATCH 1/4] Add phi-3 instructions --- phi3-finetune/README.md | 58 ++ phi3-finetune/aml_submit_clm.py | 137 ++++ phi3-finetune/environment/Dockerfile | 14 + phi3-finetune/finetune-clm/run_clm.py | 733 +++++++++++++++++++ phi3-finetune/finetune-clm/zero_stage_2.json | 39 + phi3-finetune/ws_config_template.json | 5 + 6 files changed, 986 insertions(+) create mode 100644 phi3-finetune/README.md create mode 100644 phi3-finetune/aml_submit_clm.py create mode 100644 phi3-finetune/environment/Dockerfile create mode 100644 phi3-finetune/finetune-clm/run_clm.py create mode 100644 phi3-finetune/finetune-clm/zero_stage_2.json create mode 100755 phi3-finetune/ws_config_template.json diff --git a/phi3-finetune/README.md b/phi3-finetune/README.md new file mode 100644 index 00000000..8c40399f --- /dev/null +++ b/phi3-finetune/README.md @@ -0,0 +1,58 @@ +# Phi-3 Model Fine-tuning Demo + +This demo will show how to use ACPT (Azure Container for PyTorch) along with accelerators such as onnxruntime training (through ORTModule) and DeepSpeed to fine-tune Phi-3 model. + +## Background + +[Phi-3](https://www.microsoft.com/en-us/research/blog/phi-3-the-surprising-power-of-small-language-models/) is 2.7 billion-parameter language model with nex-t word prediction objective. It has been trained using mixture of Synthetic and Web datasets. + +## Set up + +### AzureML +The easiest option to run the demo will be using AzureML as the environment details are already included, there is another option to run directly on the machine which is provided later. For AzureML, please complete the following prerequisites: + +#### Local environment +Set up your local environment with az-cli and azureml dependency for script submission: + +``` +az-cli && az login +pip install azure-ai-ml azure-identity +``` + +#### AzureML Workspace +- An AzureML workspace is required to run this demo. Download the config.json file ([How to get config.json file from Azure Portal](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-configure-environment#workspace)) for your workspace. Make sure to put this config file in this folder and name it ws_config.json. +- The workspace should have a gpu cluster. This demo was tested with GPU cluster of SKU [Standard_ND40rs_v2](https://docs.microsoft.com/en-us/azure/virtual-machines/ndv2-series). See this document for [creating gpu cluster](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-create-attach-compute-cluster?tabs=python). We do not recommend running this demo on `NC` series VMs which uses old architecture (K80). +- Additionally, you'll need to create a [Custom Curated Environment ACPT](https://learn.microsoft.com/en-us/azure/machine-learning/resource-curated-environments) with PyTorch >=2.2.0 and the steps in the Dockerfile. + +## Run Experiments +The demo is ready to be run. + +#### `aml_submit.py` submits an training job to AML for both Pytorch+DeepSpeedStage2 and ORT+DeepSpeedStage2. This job builds the training environment and runs the fine-tuning script in it. + +```bash +python aml_submit.py +``` + +The above script will generate two URLs, one for Pytorch and another for ONNX Runtime training. + +We observe **~11% speedup** for Phi-3 trained leveraging ONNX Runtime Training with 8 V100 GPUs with 32GB memory, with a batch size of 3 and Triton turned on. + +### Run directly on your compute + +If you are using CLI by directly logging into your machine then you can follow the below instructions. The below steps assume you have the required packages like Pytorch, ONNX Runtime training, Transformers and more already installed in your system. For easier setup, you can look at the environment folder. + +```bash +cd finetune-clm + +# To run the model using Pytorch +torchrun --nproc_per_node 8 run_clm.py --model_name_or_path microsoft/phi-3 --dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train --save_strategy 'no' --fp16 --block_size 2048 --max_steps -1 --per_device_train_batch_size 1 --num_train_epochs 2 --output_dir output_dir --overwrite_output_dir --deepspeed zero_stage_2.json --evaluation_strategy no --remove_unused_columns False + +# To run the model using ONNX Runtime training, you need to export couple of variables and run the same command above, overall these would be your steps: +export APPLY_ORT="True" +export ORTMODULE_FALLBACK_POLICY="FALLBACK_DISABLE" +export ORTMODULE_DEEPCOPY_BEFORE_MODEL_EXPORT=0 +# Optionally you can enable/disable Triton, for faster performance it is turned on +export ORTMODULE_USE_TRITON=1 +torchrun --nproc_per_node 8 run_clm.py --model_name_or_path microsoft/phi-3 --dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train --save_strategy 'no' --fp16 --block_size 2048 --max_steps -1 --per_device_train_batch_size 1 --num_train_epochs 2 --output_dir output_dir --overwrite_output_dir --deepspeed zero_stage_2.json --evaluation_strategy no --remove_unused_columns False +``` + diff --git a/phi3-finetune/aml_submit_clm.py b/phi3-finetune/aml_submit_clm.py new file mode 100644 index 00000000..fec16b78 --- /dev/null +++ b/phi3-finetune/aml_submit_clm.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2023 Microsoft Corp. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and + +import argparse +from pathlib import Path +import json +import os + +from azure.ai.ml import MLClient, command +from azure.ai.ml.entities import Environment, BuildContext +from azure.identity import AzureCliCredential + +# run test on automode workspace +ws_config = json.load(open("ws_config.json")) +subscription_id = ws_config["subscription_id"] +resource_group = ws_config["resource_group"] +workspace_name = ws_config["workspace_name"] +compute = ws_config["compute"] +nproc_per_node = ws_config["nproc_per_node"] + +def get_args(raw_args=None): + parser = argparse.ArgumentParser() + + parser.add_argument("--experiment_name", default="Phi-2-ORT-CLM-Stage2-Experiment", help="Experiment name for AML Workspace") + + args = parser.parse_args(raw_args) + return args + +def main(raw_args=None): + args = get_args(raw_args) + + ml_client = MLClient( + AzureCliCredential(), subscription_id, resource_group, workspace_name + ) + + root_dir = Path(__file__).resolve().parent + environment_dir = root_dir / "environment" + code_dir = root_dir / "finetune-clm" + + model = "microsoft/phi-3" + num_train_epochs = 2 + bsz = 3 + max_steps = -1 + + dataset_name = "wikitext" + dataset_config_name = "wikitext-2-raw-v1" + text_column_name = "text" + label_column_name = "label" + + pytorch_job = command( + code=code_dir, # local path where the code is stored + command=f"torchrun --nproc_per_node {nproc_per_node} run_clm.py \ + --model_name_or_path {model} \ + --dataset_name {dataset_name} \ + --dataset_config_name {dataset_config_name} \ + --do_train \ + --save_strategy 'no' \ + --per_device_train_batch_size {bsz} \ + --num_train_epochs {num_train_epochs} \ + --output_dir results --overwrite_output_dir \ + --fp16 --max_steps {max_steps} \ + --block_size 2048 \ + --deepspeed zero_stage_2.json \ + --evaluation_strategy no --remove_unused_columns False", + environment=Environment(build=BuildContext(path=environment_dir)), + experiment_name="Phi-3-Pytorch-CLM-LORA-Stage2-Experiment", + compute=compute, + display_name=model.replace( + "microsoft/phi-2", + f"pytorch+DS2-{bsz}" + ), + description=f"Finetune HuggingFace's Phi-3 using PyTorch", + tags={"model": model, + "bsz": bsz, + "dataset_name": dataset_name}, + shm_size="16g" + ) + + print("submitting PyTorch job for " + model) + pytorch_returned_job = ml_client.create_or_update(pytorch_job) + print("submitted job") + + pytorch_aml_url = pytorch_returned_job.studio_url + print("job link:", pytorch_aml_url) + + ort_job = command( + code=code_dir, # local path where the code is stored + command=f"torchrun --nproc_per_node {nproc_per_node} run_clm.py \ + --model_name_or_path {model} \ + --dataset_name {dataset_name} \ + --dataset_config_name {dataset_config_name} \ + --do_train \ + --save_strategy 'no' \ + --per_device_train_batch_size {bsz} \ + --num_train_epochs {num_train_epochs} \ + --output_dir results --overwrite_output_dir \ + --fp16 --max_steps {max_steps} \ + --block_size 2048 \ + --deepspeed zero_stage_2.json \ + --evaluation_strategy no --remove_unused_columns False", + environment=Environment(build=BuildContext(path=environment_dir)), + environment_variables={"APPLY_ORT": "True", + "ORTMODULE_FALLBACK_POLICY": "FALLBACK_DISABLE"}, + experiment_name="Phi-3-ORT-CLM-Stage2-Experiment", + compute=compute, + display_name=model.replace( + "microsoft/phi-3", + f"ort+DS2-{bsz}" + ), + description=f"Finetune HuggingFace's Phi-3 using ONNX Runtime", + tags={"model": model, + "bsz": bsz, + "dataset_name": dataset_name}, + shm_size="16g" + ) + + print("submitting ORT job for " + model) + ort_returned_job = ml_client.create_or_update(ort_job) + print("submitted job") + + ort_aml_url = ort_returned_job.studio_url + print("job link:", ort_aml_url) + +if __name__ == "__main__": + main() diff --git a/phi3-finetune/environment/Dockerfile b/phi3-finetune/environment/Dockerfile new file mode 100644 index 00000000..08762418 --- /dev/null +++ b/phi3-finetune/environment/Dockerfile @@ -0,0 +1,14 @@ +FROM mcr.microsoft.com/aifx/acpt/stable-ubuntu2004-cu118-py38-torch220 + +RUN pip uninstall onnxruntime-training -y && \ + pip install -i https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ORT/pypi/simple/ onnxruntime-training && \ + TORCH_CUDA_ARCH_LIST="5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX" python -m onnxruntime.training.ortmodule.torch_cpp_extensions.install + +RUN pip install -U datasets evaluate accelerate scikit-learn transformers==4.36.2 +RUN pip install git+https://github.com/huggingface/optimum.git + +RUN pip install einops +RUN pip install --upgrade pytest +RUN pip install peft + +RUN pip list diff --git a/phi3-finetune/finetune-clm/run_clm.py b/phi3-finetune/finetune-clm/run_clm.py new file mode 100644 index 00000000..08cbb095 --- /dev/null +++ b/phi3-finetune/finetune-clm/run_clm.py @@ -0,0 +1,733 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset. + +Here is the full list of checkpoints on the hub that can be fine-tuned by this script: +https://huggingface.co/models?filter=text-generation +""" +# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments. + +import logging +import math +import os +import sys +import warnings +from dataclasses import dataclass, field +from itertools import chain +from typing import Optional + +import datasets +import evaluate +import torch +from datasets import load_dataset + +import transformers +from transformers import ( + CONFIG_MAPPING, + MODEL_FOR_CAUSAL_LM_MAPPING, + AutoConfig, + AutoModelForCausalLM, + AutoTokenizer, + HfArgumentParser, + Trainer, + TrainingArguments, + default_data_collator, + is_torch_xla_available, + set_seed, +) +from transformers.testing_utils import CaptureLogger +from transformers.trainer_utils import get_last_checkpoint +from transformers.utils import check_min_version, send_example_telemetry +from transformers.utils.versions import require_version + + +# Will error if the minimal version of Transformers is not installed. Remove at your own risks. +check_min_version("4.41.0.dev0") + +require_version("datasets>=2.14.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt") + +logger = logging.getLogger(__name__) + + +MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys()) +MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. + """ + + model_name_or_path: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch." + ) + }, + ) + model_type: Optional[str] = field( + default=None, + metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)}, + ) + config_overrides: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override some existing default config settings when a model is trained from scratch. Example: " + "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" + ) + }, + ) + config_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + tokenizer_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} + ) + cache_dir: Optional[str] = field( + default=None, + metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, + ) + use_fast_tokenizer: bool = field( + default=True, + metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, + ) + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + ) + token: str = field( + default=None, + metadata={ + "help": ( + "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token " + "generated when running `huggingface-cli login` (stored in `~/.huggingface`)." + ) + }, + ) + use_auth_token: bool = field( + default=None, + metadata={ + "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": ( + "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option " + "should only be set to `True` for repositories you trust and in which you have read the code, as it will " + "execute code present on the Hub on your local machine." + ) + }, + ) + torch_dtype: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the " + "dtype will be automatically derived from the model's weights." + ), + "choices": ["auto", "bfloat16", "float16", "float32"], + }, + ) + low_cpu_mem_usage: bool = field( + default=False, + metadata={ + "help": ( + "It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded. " + "set True will benefit LLM loading time and RAM consumption." + ) + }, + ) + + def __post_init__(self): + if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): + raise ValueError( + "--config_overrides can't be used in combination with --config_name or --model_name_or_path" + ) + + +@dataclass +class DataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + """ + + dataset_name: Optional[str] = field( + default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} + ) + dataset_config_name: Optional[str] = field( + default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} + ) + train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."}) + validation_file: Optional[str] = field( + default=None, + metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}, + ) + max_train_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of training examples to this " + "value if set." + ) + }, + ) + max_eval_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of evaluation examples to this " + "value if set." + ) + }, + ) + streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"}) + block_size: Optional[int] = field( + default=None, + metadata={ + "help": ( + "Optional input sequence length after tokenization. " + "The training dataset will be truncated in block of this size for training. " + "Default to the model max input length for single sentence inputs (take into account special tokens)." + ) + }, + ) + overwrite_cache: bool = field( + default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} + ) + validation_split_percentage: Optional[int] = field( + default=5, + metadata={ + "help": "The percentage of the train set used as validation set in case there's no validation split" + }, + ) + preprocessing_num_workers: Optional[int] = field( + default=None, + metadata={"help": "The number of processes to use for the preprocessing."}, + ) + keep_linebreaks: bool = field( + default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."} + ) + + def __post_init__(self): + if self.streaming: + require_version("datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`") + + if self.dataset_name is None and self.train_file is None and self.validation_file is None: + raise ValueError("Need either a dataset name or a training/validation file.") + else: + if self.train_file is not None: + extension = self.train_file.split(".")[-1] + assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." + if self.validation_file is not None: + extension = self.validation_file.split(".")[-1] + assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." + + +def main(): + apply_ort = os.getenv("APPLY_ORT", "").lower() == "true" + apply_4bit = os.getenv("APPLY_4BIT", "").lower() == "true" + apply_tc = os.getenv("APPLY_TORCH_COMPILE", "").lower() == "true" + # See all possible arguments in src/transformers/training_args.py + # or by passing the --help flag to this script. + # We now keep distinct sets of args, for a cleaner separation of concerns. + + if apply_ort: + from optimum.onnxruntime import ORTTrainingArguments + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, ORTTrainingArguments)) + else: + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) + + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + if model_args.use_auth_token is not None: + warnings.warn( + "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead.", + FutureWarning, + ) + if model_args.token is not None: + raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.") + model_args.token = model_args.use_auth_token + + # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The + # information sent is the one passed as arguments along with your Python/PyTorch versions. + send_example_telemetry("run_clm", model_args, data_args) + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + + if training_args.should_log: + # The default of training_args.log_level is passive, so we set log level at info here to have that default. + transformers.utils.logging.set_verbosity_info() + + log_level = training_args.get_process_log_level() + logger.setLevel(log_level) + datasets.utils.logging.set_verbosity(log_level) + transformers.utils.logging.set_verbosity(log_level) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + # Log on each process the small summary: + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " + + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}" + ) + logger.info(f"Training/evaluation parameters {training_args}") + + # Detecting last checkpoint. + last_checkpoint = None + if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(training_args.output_dir) + if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: + raise ValueError( + f"Output directory ({training_args.output_dir}) already exists and is not empty. " + "Use --overwrite_output_dir to overcome." + ) + elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + + # Set seed before initializing model. + set_seed(training_args.seed) + + # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) + # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ + # (the dataset will be downloaded automatically from the datasets Hub). + # + # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called + # 'text' is found. You can easily tweak this behavior (see below). + # + # In distributed training, the load_dataset function guarantee that only one local process can concurrently + # download the dataset. + if data_args.dataset_name is not None: + # Downloading and loading a dataset from the hub. + raw_datasets = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + cache_dir=model_args.cache_dir, + token=model_args.token, + streaming=data_args.streaming, + ) + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + split=f"train[:{data_args.validation_split_percentage}%]", + cache_dir=model_args.cache_dir, + token=model_args.token, + streaming=data_args.streaming, + ) + raw_datasets["train"] = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + split=f"train[{data_args.validation_split_percentage}%:]", + cache_dir=model_args.cache_dir, + token=model_args.token, + streaming=data_args.streaming, + ) + else: + data_files = {} + dataset_args = {} + if data_args.train_file is not None: + data_files["train"] = data_args.train_file + if data_args.validation_file is not None: + data_files["validation"] = data_args.validation_file + extension = ( + data_args.train_file.split(".")[-1] + if data_args.train_file is not None + else data_args.validation_file.split(".")[-1] + ) + if extension == "txt": + extension = "text" + dataset_args["keep_linebreaks"] = data_args.keep_linebreaks + raw_datasets = load_dataset( + extension, + data_files=data_files, + cache_dir=model_args.cache_dir, + token=model_args.token, + **dataset_args, + ) + # If no validation data is there, validation_split_percentage will be used to divide the dataset. + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + extension, + data_files=data_files, + split=f"train[:{data_args.validation_split_percentage}%]", + cache_dir=model_args.cache_dir, + token=model_args.token, + **dataset_args, + ) + raw_datasets["train"] = load_dataset( + extension, + data_files=data_files, + split=f"train[{data_args.validation_split_percentage}%:]", + cache_dir=model_args.cache_dir, + token=model_args.token, + **dataset_args, + ) + + # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at + # https://huggingface.co/docs/datasets/loading_datasets. + + # Load pretrained model and tokenizer + # + # Distributed training: + # The .from_pretrained methods guarantee that only one local process can concurrently + # download model & vocab. + + config_kwargs = { + "cache_dir": model_args.cache_dir, + "revision": model_args.model_revision, + "token": model_args.token, + "trust_remote_code": model_args.trust_remote_code, + } + if model_args.config_name: + config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs) + elif model_args.model_name_or_path: + config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs) + else: + config = CONFIG_MAPPING[model_args.model_type]() + logger.warning("You are instantiating a new config instance from scratch.") + if model_args.config_overrides is not None: + logger.info(f"Overriding config: {model_args.config_overrides}") + config.update_from_string(model_args.config_overrides) + logger.info(f"New config: {config}") + + tokenizer_kwargs = { + "cache_dir": model_args.cache_dir, + "use_fast": model_args.use_fast_tokenizer, + "revision": model_args.model_revision, + "token": model_args.token, + "trust_remote_code": model_args.trust_remote_code, + } + if model_args.tokenizer_name: + tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs) + elif model_args.model_name_or_path: + tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs) + else: + raise ValueError( + "You are instantiating a new tokenizer from scratch. This is not supported by this script. " + "You can do it from another script, save it, and load it from here, using --tokenizer_name." + ) + # print("#*#*#* Overriding config.num_hidden_layers=1") + # config.num_hidden_layers = 1 + + if model_args.model_name_or_path: + torch_dtype = ( + model_args.torch_dtype + if model_args.torch_dtype in ["auto", None] + else getattr(torch, model_args.torch_dtype) + ) + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + token=model_args.token, + trust_remote_code=model_args.trust_remote_code, + torch_dtype=torch_dtype, + low_cpu_mem_usage=model_args.low_cpu_mem_usage, + ) + else: + model = AutoModelForCausalLM.from_config(config, trust_remote_code=model_args.trust_remote_code) + n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values()) + logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params") + + # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch + # on a small vocab and want a smaller embedding size, remove this test. + embedding_size = model.get_input_embeddings().weight.shape[0] + if len(tokenizer) > embedding_size: + model.resize_token_embeddings(len(tokenizer)) + + # Use LoRA performance efficient fine tuning + from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training + + target_modules = ["qkv_proj"] + # target_modules = ["qkv_proj", "o_proj", "gate_up_proj", "down_proj"] + + peft_config = LoraConfig( + task_type=TaskType.CAUSAL_LM, + inference_mode=False, + r=8, + lora_alpha=32, + lora_dropout=0.1, + target_modules=target_modules + ) + if apply_4bit is True: + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False) + + if training_args.local_rank == 0: + print("#*#*#* model before LoRA", model) + model = get_peft_model(model, peft_config) + if training_args.local_rank == 0: + print("#*#*#* model after LoRA", model) + + # Preprocessing the datasets. + # First we tokenize all the texts. + if training_args.do_train: + column_names = list(raw_datasets["train"].features) + else: + column_names = list(raw_datasets["validation"].features) + text_column_name = "text" if "text" in column_names else column_names[0] + + # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function + tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base") + + def tokenize_function(examples): + with CaptureLogger(tok_logger) as cl: + output = tokenizer(examples[text_column_name]) + # clm input could be much much longer than block_size + if "Token indices sequence length is longer than the" in cl.out: + tok_logger.warning( + "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits" + " before being passed to the model." + ) + return output + + with training_args.main_process_first(desc="dataset map tokenization"): + if not data_args.streaming: + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + num_proc=data_args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not data_args.overwrite_cache, + desc="Running tokenizer on dataset", + ) + else: + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + remove_columns=column_names, + ) + if hasattr(config, "max_position_embeddings"): + max_pos_embeddings = config.max_position_embeddings + else: + # Define a default value if the attribute is missing in the config. + max_pos_embeddings = 1024 + + if data_args.block_size is None: + block_size = tokenizer.model_max_length + if block_size > max_pos_embeddings: + logger.warning( + f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). " + f"Using block_size={min(1024, max_pos_embeddings)} instead. You can change that default value by passing --block_size xxx." + ) + if max_pos_embeddings > 0: + block_size = min(1024, max_pos_embeddings) + else: + block_size = 1024 + else: + if data_args.block_size > tokenizer.model_max_length: + logger.warning( + f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model " + f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." + ) + block_size = min(data_args.block_size, tokenizer.model_max_length) + + # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. + def group_texts(examples): + # Concatenate all texts. + concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} + total_length = len(concatenated_examples[list(examples.keys())[0]]) + # We drop the small remainder, and if the total_length < block_size we exclude this batch and return an empty dict. + # We could add padding if the model supported it instead of this drop, you can customize this part to your needs. + total_length = (total_length // block_size) * block_size + # Split by chunks of max_len. + result = { + k: [t[i : i + block_size] for i in range(0, total_length, block_size)] + for k, t in concatenated_examples.items() + } + result["labels"] = result["input_ids"].copy() + return result + + # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder + # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower + # to preprocess. + # + # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: + # https://huggingface.co/docs/datasets/process#map + + with training_args.main_process_first(desc="grouping texts together"): + if not data_args.streaming: + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + num_proc=data_args.preprocessing_num_workers, + load_from_cache_file=not data_args.overwrite_cache, + desc=f"Grouping texts in chunks of {block_size}", + ) + else: + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + ) + + if training_args.do_train: + if "train" not in tokenized_datasets: + raise ValueError("--do_train requires a train dataset") + train_dataset = lm_datasets["train"] + if data_args.max_train_samples is not None: + max_train_samples = min(len(train_dataset), data_args.max_train_samples) + train_dataset = train_dataset.select(range(max_train_samples)) + + if training_args.do_eval: + if "validation" not in tokenized_datasets: + raise ValueError("--do_eval requires a validation dataset") + eval_dataset = lm_datasets["validation"] + if data_args.max_eval_samples is not None: + max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) + eval_dataset = eval_dataset.select(range(max_eval_samples)) + + def preprocess_logits_for_metrics(logits, labels): + if isinstance(logits, tuple): + # Depending on the model and config, logits may contain extra tensors, + # like past_key_values, but logits always come first + logits = logits[0] + return logits.argmax(dim=-1) + + metric = evaluate.load("accuracy", cache_dir=model_args.cache_dir) + + def compute_metrics(eval_preds): + preds, labels = eval_preds + # preds have the same shape as the labels, after the argmax(-1) has been calculated + # by preprocess_logits_for_metrics but we need to shift the labels + labels = labels[:, 1:].reshape(-1) + preds = preds[:, :-1].reshape(-1) + return metric.compute(predictions=preds, references=labels) + + if apply_ort: + from optimum.onnxruntime import ORTTrainer + trainer_cls = ORTTrainer + else: + trainer_cls = Trainer + + if apply_tc: + model = torch.compile(model) + # Initialize our Trainer + trainer = trainer_cls( + model=model, + args=training_args, + train_dataset=train_dataset if training_args.do_train else None, + eval_dataset=eval_dataset if training_args.do_eval else None, + tokenizer=tokenizer, + # Data collator will default to DataCollatorWithPadding, so we change it. + data_collator=default_data_collator, + compute_metrics=compute_metrics if training_args.do_eval and not is_torch_xla_available() else None, + preprocess_logits_for_metrics=preprocess_logits_for_metrics + if training_args.do_eval and not is_torch_xla_available() + else None, + ) + + # Training + if training_args.do_train: + checkpoint = None + if training_args.resume_from_checkpoint is not None: + checkpoint = training_args.resume_from_checkpoint + elif last_checkpoint is not None: + checkpoint = last_checkpoint + train_result = trainer.train(resume_from_checkpoint=checkpoint) + trainer.save_model() # Saves the tokenizer too for easy upload + + metrics = train_result.metrics + + max_train_samples = ( + data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) + ) + metrics["train_samples"] = min(max_train_samples, len(train_dataset)) + + trainer.log_metrics("train", metrics) + trainer.save_metrics("train", metrics) + trainer.save_state() + + # Evaluation + if training_args.do_eval: + logger.info("*** Evaluate ***") + + metrics = trainer.evaluate() + + max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) + metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) + try: + perplexity = math.exp(metrics["eval_loss"]) + except OverflowError: + perplexity = float("inf") + metrics["perplexity"] = perplexity + + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"} + if data_args.dataset_name is not None: + kwargs["dataset_tags"] = data_args.dataset_name + if data_args.dataset_config_name is not None: + kwargs["dataset_args"] = data_args.dataset_config_name + kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" + else: + kwargs["dataset"] = data_args.dataset_name + + if training_args.push_to_hub: + trainer.push_to_hub(**kwargs) + else: + trainer.create_model_card(**kwargs) + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + +def print_env_info(): + import subprocess + import torch.distributed as dist + + if dist.get_rank() == 0: + print("\n\n===== Environment Info =====") + docker_sh = "echo Docker:$HOST_HOSTNAME" + subprocess.run(docker_sh, shell=True) + env_variable_sh = "printenv | grep 'ORTMODULE_\|APPLY_' " + print("\n", env_variable_sh) + subprocess.run(env_variable_sh, shell=True) + package_ver_sh = "pip list | grep 'transformers\|optimum\|onnx\|torch\|accelerate'" + print("\n", package_ver_sh) + subprocess.run(package_ver_sh, shell=True) + optimum_commit = "cd ../optimum && git show --oneline -s" + print("\n optimum commit") + subprocess.run(optimum_commit, shell=True) + transformers_commit = "cd ../transformers && git show --oneline -s" + print("\n transfromers commit") + subprocess.run(transformers_commit, shell=True) + print("=======================================") + +if __name__ == "__main__": + main() + print_env_info() diff --git a/phi3-finetune/finetune-clm/zero_stage_2.json b/phi3-finetune/finetune-clm/zero_stage_2.json new file mode 100644 index 00000000..746bb29c --- /dev/null +++ b/phi3-finetune/finetune-clm/zero_stage_2.json @@ -0,0 +1,39 @@ +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "zero_optimization": { + "stage": 2, + "allgather_partitions": true, + "allgather_bucket_size": 200000000, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": 200000000, + "contiguous_gradients": false, + "cpu_offload": false + }, + "zero_allow_untested_optimizer": true, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + "steps_per_print": 2000, + "train_micro_batch_size_per_gpu": "auto" +} \ No newline at end of file diff --git a/phi3-finetune/ws_config_template.json b/phi3-finetune/ws_config_template.json new file mode 100755 index 00000000..8255a6b9 --- /dev/null +++ b/phi3-finetune/ws_config_template.json @@ -0,0 +1,5 @@ +{ + "subscription_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + "resource_group": "rg-name", + "workspace_name": "ws-name" +} \ No newline at end of file From a346153794074f7f93254aa9b190eb7764d9ba5d Mon Sep 17 00:00:00 2001 From: Jingyan Wang Date: Sat, 1 Jun 2024 00:39:05 +0000 Subject: [PATCH 2/4] Update --- phi3-finetune/README.md | 2 +- phi3-finetune/finetune-clm/run_clm.py | 30 --------------------------- 2 files changed, 1 insertion(+), 31 deletions(-) diff --git a/phi3-finetune/README.md b/phi3-finetune/README.md index 8c40399f..c9c26fb0 100644 --- a/phi3-finetune/README.md +++ b/phi3-finetune/README.md @@ -35,7 +35,7 @@ python aml_submit.py The above script will generate two URLs, one for Pytorch and another for ONNX Runtime training. -We observe **~11% speedup** for Phi-3 trained leveraging ONNX Runtime Training with 8 V100 GPUs with 32GB memory, with a batch size of 3 and Triton turned on. +We observe **~% speedup** for Phi-3 trained leveraging ONNX Runtime Training with 8 V100 GPUs with 32GB memory, with a batch size of . ### Run directly on your compute diff --git a/phi3-finetune/finetune-clm/run_clm.py b/phi3-finetune/finetune-clm/run_clm.py index 08cbb095..6dd6aa02 100644 --- a/phi3-finetune/finetune-clm/run_clm.py +++ b/phi3-finetune/finetune-clm/run_clm.py @@ -438,8 +438,6 @@ def main(): "You are instantiating a new tokenizer from scratch. This is not supported by this script. " "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) - # print("#*#*#* Overriding config.num_hidden_layers=1") - # config.num_hidden_layers = 1 if model_args.model_name_or_path: torch_dtype = ( @@ -486,12 +484,6 @@ def main(): if apply_4bit is True: model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False) - if training_args.local_rank == 0: - print("#*#*#* model before LoRA", model) - model = get_peft_model(model, peft_config) - if training_args.local_rank == 0: - print("#*#*#* model after LoRA", model) - # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: @@ -706,28 +698,6 @@ def _mp_fn(index): # For xla_spawn (TPUs) main() -def print_env_info(): - import subprocess - import torch.distributed as dist - - if dist.get_rank() == 0: - print("\n\n===== Environment Info =====") - docker_sh = "echo Docker:$HOST_HOSTNAME" - subprocess.run(docker_sh, shell=True) - env_variable_sh = "printenv | grep 'ORTMODULE_\|APPLY_' " - print("\n", env_variable_sh) - subprocess.run(env_variable_sh, shell=True) - package_ver_sh = "pip list | grep 'transformers\|optimum\|onnx\|torch\|accelerate'" - print("\n", package_ver_sh) - subprocess.run(package_ver_sh, shell=True) - optimum_commit = "cd ../optimum && git show --oneline -s" - print("\n optimum commit") - subprocess.run(optimum_commit, shell=True) - transformers_commit = "cd ../transformers && git show --oneline -s" - print("\n transfromers commit") - subprocess.run(transformers_commit, shell=True) - print("=======================================") if __name__ == "__main__": main() - print_env_info() From 5d1b7e96e7dbb2bf55776e4bb3914fbe0f1253cf Mon Sep 17 00:00:00 2001 From: Jingyan Wang Date: Wed, 19 Jun 2024 07:18:57 +0000 Subject: [PATCH 3/4] Updated recipe, fixed comments --- phi3-finetune/README.md | 13 +++++------ phi3-finetune/aml_submit_clm.py | 31 ++++++++++++++++----------- phi3-finetune/environment/Dockerfile | 14 ++++++++---- phi3-finetune/finetune-clm/run_clm.py | 1 + 4 files changed, 36 insertions(+), 23 deletions(-) diff --git a/phi3-finetune/README.md b/phi3-finetune/README.md index c9c26fb0..87e0ea64 100644 --- a/phi3-finetune/README.md +++ b/phi3-finetune/README.md @@ -4,7 +4,7 @@ This demo will show how to use ACPT (Azure Container for PyTorch) along with acc ## Background -[Phi-3](https://www.microsoft.com/en-us/research/blog/phi-3-the-surprising-power-of-small-language-models/) is 2.7 billion-parameter language model with nex-t word prediction objective. It has been trained using mixture of Synthetic and Web datasets. +[Phi-3](https://www.microsoft.com/en-us/research/blog/phi-3-the-surprising-power-of-small-language-models/) is 3.8 billion-parameter language model with next word prediction objective. It has been trained using mixture of Synthetic and Web datasets. ## Set up @@ -12,25 +12,26 @@ This demo will show how to use ACPT (Azure Container for PyTorch) along with acc The easiest option to run the demo will be using AzureML as the environment details are already included, there is another option to run directly on the machine which is provided later. For AzureML, please complete the following prerequisites: #### Local environment +Follow [Install Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=apt#install-azure-cli) to install Azure CLI. Set up your local environment with az-cli and azureml dependency for script submission: ``` -az-cli && az login +az login pip install azure-ai-ml azure-identity ``` #### AzureML Workspace - An AzureML workspace is required to run this demo. Download the config.json file ([How to get config.json file from Azure Portal](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-configure-environment#workspace)) for your workspace. Make sure to put this config file in this folder and name it ws_config.json. -- The workspace should have a gpu cluster. This demo was tested with GPU cluster of SKU [Standard_ND40rs_v2](https://docs.microsoft.com/en-us/azure/virtual-machines/ndv2-series). See this document for [creating gpu cluster](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-create-attach-compute-cluster?tabs=python). We do not recommend running this demo on `NC` series VMs which uses old architecture (K80). +- The workspace should have a gpu cluster. This demo was tested with GPU cluster of SKU [Standard_ND96asr_A100_v4](https://learn.microsoft.com/en-us/azure/virtual-machines/nda100-v4-series). [Standard_ND40rs_v2](https://docs.microsoft.com/en-us/azure/virtual-machines/ndv2-series) should also work with reduced block size. See this document for [creating gpu cluster](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-create-attach-compute-cluster?tabs=python). We do not recommend running this demo on `NC` series VMs which uses old architecture (K80). - Additionally, you'll need to create a [Custom Curated Environment ACPT](https://learn.microsoft.com/en-us/azure/machine-learning/resource-curated-environments) with PyTorch >=2.2.0 and the steps in the Dockerfile. ## Run Experiments The demo is ready to be run. -#### `aml_submit.py` submits an training job to AML for both Pytorch+DeepSpeedStage2 and ORT+DeepSpeedStage2. This job builds the training environment and runs the fine-tuning script in it. +#### `aml_submit_clm.py` submits an training job to AML for both Pytorch+DeepSpeedStage2+LoRA and ORT+DeepSpeedStage2+LoRA. This job builds the training environment and runs the fine-tuning script in it. ```bash -python aml_submit.py +python aml_submit_clm.py ``` The above script will generate two URLs, one for Pytorch and another for ONNX Runtime training. @@ -53,6 +54,6 @@ export ORTMODULE_FALLBACK_POLICY="FALLBACK_DISABLE" export ORTMODULE_DEEPCOPY_BEFORE_MODEL_EXPORT=0 # Optionally you can enable/disable Triton, for faster performance it is turned on export ORTMODULE_USE_TRITON=1 -torchrun --nproc_per_node 8 run_clm.py --model_name_or_path microsoft/phi-3 --dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train --save_strategy 'no' --fp16 --block_size 2048 --max_steps -1 --per_device_train_batch_size 1 --num_train_epochs 2 --output_dir output_dir --overwrite_output_dir --deepspeed zero_stage_2.json --evaluation_strategy no --remove_unused_columns False +torchrun --nproc_per_node 8 run_clm.py --model_name_or_path microsoft/Phi-3-mini-4k-instruct --dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train --save_strategy 'no' --fp16 --block_size 2048 --max_steps -1 --per_device_train_batch_size 1 --num_train_epochs 2 --output_dir output_dir --overwrite_output_dir --deepspeed zero_stage_2.json --evaluation_strategy no --remove_unused_columns False ``` diff --git a/phi3-finetune/aml_submit_clm.py b/phi3-finetune/aml_submit_clm.py index fec16b78..bf651e0c 100644 --- a/phi3-finetune/aml_submit_clm.py +++ b/phi3-finetune/aml_submit_clm.py @@ -33,7 +33,7 @@ def get_args(raw_args=None): parser = argparse.ArgumentParser() - parser.add_argument("--experiment_name", default="Phi-2-ORT-CLM-Stage2-Experiment", help="Experiment name for AML Workspace") + parser.add_argument("--experiment_name", default="Phi-3-ORT-CLM-Stage2-Experiment", help="Experiment name for AML Workspace") args = parser.parse_args(raw_args) return args @@ -49,10 +49,11 @@ def main(raw_args=None): environment_dir = root_dir / "environment" code_dir = root_dir / "finetune-clm" - model = "microsoft/phi-3" - num_train_epochs = 2 - bsz = 3 + model = "microsoft/Phi-3-mini-4k-instruct" + num_train_epochs = 5 + bsz = 1 max_steps = -1 + block_size = 64 dataset_name = "wikitext" dataset_config_name = "wikitext-2-raw-v1" @@ -71,20 +72,22 @@ def main(raw_args=None): --num_train_epochs {num_train_epochs} \ --output_dir results --overwrite_output_dir \ --fp16 --max_steps {max_steps} \ - --block_size 2048 \ + --block_size {block_size} \ --deepspeed zero_stage_2.json \ - --evaluation_strategy no --remove_unused_columns False", + --evaluation_strategy epoch --remove_unused_columns False --save_strategy no \ + --report_to tensorboard --logging_steps 100", environment=Environment(build=BuildContext(path=environment_dir)), experiment_name="Phi-3-Pytorch-CLM-LORA-Stage2-Experiment", compute=compute, display_name=model.replace( "microsoft/phi-2", - f"pytorch+DS2-{bsz}" + f"pytorch+DS2_lora-{bsz}" ), - description=f"Finetune HuggingFace's Phi-3 using PyTorch", + description=f"Finetune HuggingFace's Phi-3 using PyTorch and transformers branch", tags={"model": model, "bsz": bsz, - "dataset_name": dataset_name}, + "dataset_name": dataset_name, + "block_size": block_size}, shm_size="16g" ) @@ -112,17 +115,19 @@ def main(raw_args=None): --evaluation_strategy no --remove_unused_columns False", environment=Environment(build=BuildContext(path=environment_dir)), environment_variables={"APPLY_ORT": "True", - "ORTMODULE_FALLBACK_POLICY": "FALLBACK_DISABLE"}, + "ORTMODULE_FALLBACK_POLICY": "FALLBACK_DISABLE", + "ORTMODULE_DEEPCOPY_BEFORE_MODEL_EXPORT": "0"}, experiment_name="Phi-3-ORT-CLM-Stage2-Experiment", compute=compute, display_name=model.replace( "microsoft/phi-3", - f"ort+DS2-{bsz}" + f"ort+DS2+Lora-{bsz}" ), - description=f"Finetune HuggingFace's Phi-3 using ONNX Runtime", + description=f"Finetune HuggingFace's Phi-3 using ONNX Runtime and transformers branch", tags={"model": model, "bsz": bsz, - "dataset_name": dataset_name}, + "dataset_name": dataset_name, + "block_size": block_size}, shm_size="16g" ) diff --git a/phi3-finetune/environment/Dockerfile b/phi3-finetune/environment/Dockerfile index 08762418..c6b42b54 100644 --- a/phi3-finetune/environment/Dockerfile +++ b/phi3-finetune/environment/Dockerfile @@ -1,12 +1,18 @@ FROM mcr.microsoft.com/aifx/acpt/stable-ubuntu2004-cu118-py38-torch220 -RUN pip uninstall onnxruntime-training -y && \ - pip install -i https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ORT/pypi/simple/ onnxruntime-training && \ - TORCH_CUDA_ARCH_LIST="5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX" python -m onnxruntime.training.ortmodule.torch_cpp_extensions.install +# RUN pip uninstall onnxruntime-training -y && \ +# pip install -i https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ORT/pypi/simple/ onnxruntime-training && \ +# TORCH_CUDA_ARCH_LIST="5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX" python -m onnxruntime.training.ortmodule.torch_cpp_extensions.install -RUN pip install -U datasets evaluate accelerate scikit-learn transformers==4.36.2 +# RUN pip install -U datasets evaluate accelerate scikit-learn transformers==4.40.1 +RUN pip install -U datasets evaluate accelerate scikit-learn +RUN pip install git+https://github.com/jingyanwangms/transformers.git@jingywa/phi-3-tutorial RUN pip install git+https://github.com/huggingface/optimum.git +# Insall numpy 1.26.4 because numpy 2.0.0 are not supported with many libraries +RUN pip uninstall numpy -y && \ + pip install numpy==1.26.4 + RUN pip install einops RUN pip install --upgrade pytest RUN pip install peft diff --git a/phi3-finetune/finetune-clm/run_clm.py b/phi3-finetune/finetune-clm/run_clm.py index 6dd6aa02..dd9cc798 100644 --- a/phi3-finetune/finetune-clm/run_clm.py +++ b/phi3-finetune/finetune-clm/run_clm.py @@ -484,6 +484,7 @@ def main(): if apply_4bit is True: model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False) + model = get_peft_model(model, peft_config) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: From 3061469b96ddc97d6e1dfbb6b573e3da5cda99c2 Mon Sep 17 00:00:00 2001 From: Jingyan Wang Date: Mon, 24 Jun 2024 18:58:18 +0000 Subject: [PATCH 4/4] Add llama-3 recipe and fixes --- llama3-finetune/README.md | 59 ++ llama3-finetune/aml_submit_clm.py | 160 ++++ llama3-finetune/environment/Dockerfile | 24 + llama3-finetune/finetune-clm/run_clm.py | 704 ++++++++++++++++++ .../finetune-clm/zero_stage_2.json | 39 + llama3-finetune/ws_config_template.json | 5 + phi3-finetune/README.md | 4 +- phi3-finetune/aml_submit_clm.py | 54 +- phi3-finetune/environment/Dockerfile | 14 +- phi3-finetune/finetune-clm/run_clm.py | 4 +- 10 files changed, 1034 insertions(+), 33 deletions(-) create mode 100644 llama3-finetune/README.md create mode 100644 llama3-finetune/aml_submit_clm.py create mode 100644 llama3-finetune/environment/Dockerfile create mode 100644 llama3-finetune/finetune-clm/run_clm.py create mode 100644 llama3-finetune/finetune-clm/zero_stage_2.json create mode 100755 llama3-finetune/ws_config_template.json diff --git a/llama3-finetune/README.md b/llama3-finetune/README.md new file mode 100644 index 00000000..5200405f --- /dev/null +++ b/llama3-finetune/README.md @@ -0,0 +1,59 @@ +# Llama-3 Model Fine-tuning Demo + +This demo will show how to use ACPT (Azure Container for PyTorch) along with accelerators such as onnxruntime training (through ORTModule) and DeepSpeed to fine-tune Llama-3 model. + +## Background + +[Llama-3-8b](https://huggingface.co/blog/llama3) the latest large language model from Meta, is built on the architecture of Llama 2 and comes in two sizes (8B and 70B parameters) with pre-trained and instruction-tuned versions. Here we show fine-tuning on 8b model. + +## Set up + +### AzureML +The easiest option to run the demo will be using AzureML as the environment details are already included, there is another option to run directly on the machine which is provided later. For AzureML, please complete the following prerequisites: + +#### Local environment +Follow [Install Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=apt#install-azure-cli) to install Azure CLI. +Set up your local environment with az-cli and azureml dependency for script submission: + +``` +az login +pip install azure-ai-ml azure-identity +``` + +#### AzureML Workspace +- An AzureML workspace is required to run this demo. Download the config.json file ([How to get config.json file from Azure Portal](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-configure-environment#workspace)) for your workspace. Make sure to put this config file in this folder and name it ws_config.json. +- The workspace should have a gpu cluster. This demo was tested with GPU cluster of SKU [Standard_ND96asr_A100_v4](https://learn.microsoft.com/en-us/azure/virtual-machines/nda100-v4-series). [Standard_ND40rs_v2](https://docs.microsoft.com/en-us/azure/virtual-machines/ndv2-series) should also work with reduced block size. See this document for [creating gpu cluster](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-create-attach-compute-cluster?tabs=python). We do not recommend running this demo on `NC` series VMs which uses old architecture (K80). +- Additionally, you'll need to create a [Custom Curated Environment ACPT](https://learn.microsoft.com/en-us/azure/machine-learning/resource-curated-environments) with PyTorch >=2.2.0 and the steps in the Dockerfile. + +## Run Experiments +The demo is ready to be run. + +#### `aml_submit_clm.py` submits an training job to AML for both Pytorch+DeepSpeedStage2+LoRA and ORT+DeepSpeedStage2+LoRA. This job builds the training environment and runs the fine-tuning script in it. + +```bash +python aml_submit_clm.py +``` + +The above script will generate two URLs, one for Pytorch and another for ONNX Runtime training. + +We observe **12% speedup** for Llama-3 trained leveraging ONNX Runtime Training with 8 V100 GPUs with 32GB memory with batch size of 1. + +### Run directly on your compute + +If you are using CLI by directly logging into your machine then you can follow the below instructions. The below steps assume you have the required packages like Pytorch, ONNX Runtime training, Transformers and more already installed in your system. For easier setup, you can look at the environment folder. + +```bash +cd finetune-clm + +# To run the model using Pytorch +torchrun --nproc_per_node 8 run_clm.py --model_name_or_path meta-llama/Meta-Llama-3-8B --dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train --save_strategy 'no' --fp16 --block_size 2048 --max_steps -1 --per_device_train_batch_size 1 --num_train_epochs 2 --output_dir output_dir --overwrite_output_dir --deepspeed zero_stage_2.json --evaluation_strategy no --remove_unused_columns False + +# To run the model using ONNX Runtime training, you need to export couple of variables and run the same command above, overall these would be your steps: +export APPLY_ORT="True" +export ORTMODULE_FALLBACK_POLICY="FALLBACK_DISABLE" +export ORTMODULE_DEEPCOPY_BEFORE_MODEL_EXPORT=0 +# Optionally you can enable/disable Triton, for faster performance it is turned on +export ORTMODULE_USE_TRITON=1 +torchrun --nproc_per_node 8 run_clm.py --model_name_or_path meta-llama/Meta-Llama-3-8B --dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train --save_strategy 'no' --fp16 --block_size 2048 --max_steps -1 --per_device_train_batch_size 1 --num_train_epochs 2 --output_dir output_dir --overwrite_output_dir --deepspeed zero_stage_2.json --evaluation_strategy no --remove_unused_columns False +``` + diff --git a/llama3-finetune/aml_submit_clm.py b/llama3-finetune/aml_submit_clm.py new file mode 100644 index 00000000..6add4d63 --- /dev/null +++ b/llama3-finetune/aml_submit_clm.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2023 Microsoft Corp. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and + +import argparse +from pathlib import Path +import json +import os + +from azure.ai.ml import MLClient, command +from azure.ai.ml.entities import Environment, BuildContext +from azure.identity import AzureCliCredential + +# run test on automode workspace +ws_config = json.load(open("ws_config.json")) +subscription_id = ws_config["subscription_id"] +resource_group = ws_config["resource_group"] +workspace_name = ws_config["workspace_name"] +compute = ws_config["compute"] +nproc_per_node = ws_config["nproc_per_node"] + +hf_token = os.getenv("HUGGINGFACE_TOKEN", None) + + +def get_args(raw_args=None): + parser = argparse.ArgumentParser() + + parser.add_argument("--experiment_name", default="Llama-3-ORT-CLM-Stage2-Experiment", help="Experiment name for AML Workspace") + + args = parser.parse_args(raw_args) + return args + +def main(raw_args=None): + args = get_args(raw_args) + + ml_client = MLClient( + AzureCliCredential(), subscription_id, resource_group, workspace_name + ) + + root_dir = Path(__file__).resolve().parent + environment_dir = root_dir / "environment" + code_dir = root_dir / "finetune-clm" + + model = "meta-llama/Meta-Llama-3-8B" + + num_train_epochs = 15 + bsz = 1 + max_steps = -1 + block_size = 2048 + + dataset_name = "wikitext" + dataset_config_name = "wikitext-2-raw-v1" + text_column_name = "text" + label_column_name = "label" + + # Pytorch eager + pytorch_job = command( + code=code_dir, # local path where the code is stored + command=f"gmon torchrun --nproc_per_node {nproc_per_node} run_clm.py \ + --model_name_or_path {model} \ + --dataset_name {dataset_name} \ + --dataset_config_name {dataset_config_name} \ + --do_train \ + --save_strategy 'no' \ + --per_device_train_batch_size {bsz} \ + --num_train_epochs {num_train_epochs} \ + --output_dir ./outputs --overwrite_output_dir \ + --fp16 --max_steps {max_steps} \ + --block_size {block_size} \ + --deepspeed zero_stage_2.json \ + --evaluation_strategy epoch --remove_unused_columns False \ + --token $HUGGINGFACE_TOKEN", + environment=Environment(build=BuildContext(path=environment_dir)), + environment_variables={ + "HUGGINGFACE_TOKEN": hf_token + }, + experiment_name="Llama-3-Pytorch-CLM-LORA-Stage2-Experiment", + compute=compute, + display_name=model.replace( + "meta-llama/Meta-Llama-3", + f"TorchEager+DS2_lora-{bsz}-{block_size}-{num_train_epochs}epoch" + ), + description=f"Finetune HuggingFace's Llama-3 using PyTorch.", + tags={"model": model, + "bsz": bsz, + "dataset_name": dataset_name, + "block_size": block_size}, + shm_size="16g", + job_tier="Premium", #https://learn.microsoft.com/en-us/python/api/azure-ai-ml/azure.ai.ml?view=azure-python + priority="High" + ) + + print("submitting PyTorch job for " + model) + pytorch_returned_job = ml_client.create_or_update(pytorch_job) + print("submitted job") + + pytorch_aml_url = pytorch_returned_job.studio_url + print("job link:", pytorch_aml_url) + + # ORT perf + ort_job = command( + code=code_dir, # local path where the code is stored + command=f"gmon torchrun --nproc_per_node {nproc_per_node} run_clm.py \ + --model_name_or_path {model} \ + --dataset_name {dataset_name} \ + --dataset_config_name {dataset_config_name} \ + --do_train \ + --save_strategy 'no' \ + --per_device_train_batch_size {bsz} \ + --num_train_epochs {num_train_epochs} \ + --output_dir ./outputs --overwrite_output_dir \ + --fp16 --max_steps {max_steps} \ + --block_size {block_size} \ + --deepspeed zero_stage_2.json \ + --evaluation_strategy epoch --remove_unused_columns False \ + --token $HUGGINGFACE_TOKEN", + environment=Environment(build=BuildContext(path=environment_dir)), + environment_variables={ + "HUGGINGFACE_TOKEN": hf_token, + "APPLY_ORT": "True", + "ORTMODULE_FALLBACK_POLICY": "FALLBACK_DISABLE", + "ORTMODULE_DEEPCOPY_BEFORE_MODEL_EXPORT": "0"}, + experiment_name="Llama-3-ORT-CLM-Stage2-Experiment", + compute=compute, + display_name=model.replace( + "meta-llama/Meta-Llama-3", + f"ORT+DS2_lora-{bsz}-{block_size}-{num_train_epochs}epoch" + ), + description=f"Finetune HuggingFace's Llama-3 using ONNX Runtime.", + tags={"model": model, + "bsz": bsz, + "dataset_name": dataset_name, + "block_size": block_size, + "epoch": num_train_epochs}, + shm_size="16g", + job_tier="Premium", + priority="High" + ) + + print("submitting ORT job for " + model) + ort_returned_job = ml_client.create_or_update(ort_job) + print("submitted job") + + ort_aml_url = ort_returned_job.studio_url + print("job link:", ort_aml_url) + + +if __name__ == "__main__": + main() diff --git a/llama3-finetune/environment/Dockerfile b/llama3-finetune/environment/Dockerfile new file mode 100644 index 00000000..94a14d3c --- /dev/null +++ b/llama3-finetune/environment/Dockerfile @@ -0,0 +1,24 @@ + +FROM mcr.microsoft.com/aifx/acpt/stable-ubuntu2004-cu118-py310-torch222 + +# RUN pip install -U datasets evaluate accelerate scikit-learn transformers==4.40.1 +RUN pip install -U datasets evaluate accelerate scikit-learn +RUN pip install git+https://github.com/huggingface/transformers.git +RUN pip install git+https://github.com/huggingface/optimum.git + + +# Insall numpy 1.26.4 because numpy 2.0.0 are not supported with many libraries +RUN pip uninstall numpy -y && \ + pip install numpy==1.26.4 + +# Error with deepspeed=0.14.2 +RUN pip uninstall deepspeed -y && \ + pip install deepspeed==0.13.1 + +RUN pip install einops +RUN pip install --upgrade pytest +RUN pip install peft + + +RUN pip list + diff --git a/llama3-finetune/finetune-clm/run_clm.py b/llama3-finetune/finetune-clm/run_clm.py new file mode 100644 index 00000000..f8ea81d2 --- /dev/null +++ b/llama3-finetune/finetune-clm/run_clm.py @@ -0,0 +1,704 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset. + +Here is the full list of checkpoints on the hub that can be fine-tuned by this script: +https://huggingface.co/models?filter=text-generation +""" +# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments. + +import logging +import math +import os +import sys +import warnings +from dataclasses import dataclass, field +from itertools import chain +from typing import Optional + +import datasets +import evaluate +import torch +from datasets import load_dataset + +import transformers +from transformers import ( + CONFIG_MAPPING, + MODEL_FOR_CAUSAL_LM_MAPPING, + AutoConfig, + AutoModelForCausalLM, + AutoTokenizer, + HfArgumentParser, + Trainer, + TrainingArguments, + default_data_collator, + is_torch_xla_available, + set_seed, +) +from transformers.testing_utils import CaptureLogger +from transformers.trainer_utils import get_last_checkpoint +from transformers.utils import check_min_version, send_example_telemetry +from transformers.utils.versions import require_version + + +# Will error if the minimal version of Transformers is not installed. Remove at your own risks. +check_min_version("4.41.0.dev0") + +require_version("datasets>=2.14.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt") + +logger = logging.getLogger(__name__) + + +MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys()) +MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. + """ + + model_name_or_path: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch." + ) + }, + ) + model_type: Optional[str] = field( + default=None, + metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)}, + ) + config_overrides: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override some existing default config settings when a model is trained from scratch. Example: " + "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" + ) + }, + ) + config_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + tokenizer_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} + ) + cache_dir: Optional[str] = field( + default=None, + metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, + ) + use_fast_tokenizer: bool = field( + default=True, + metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, + ) + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + ) + token: str = field( + default=None, + metadata={ + "help": ( + "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token " + "generated when running `huggingface-cli login` (stored in `~/.huggingface`)." + ) + }, + ) + use_auth_token: bool = field( + default=None, + metadata={ + "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": ( + "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option " + "should only be set to `True` for repositories you trust and in which you have read the code, as it will " + "execute code present on the Hub on your local machine." + ) + }, + ) + torch_dtype: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the " + "dtype will be automatically derived from the model's weights." + ), + "choices": ["auto", "bfloat16", "float16", "float32"], + }, + ) + low_cpu_mem_usage: bool = field( + default=False, + metadata={ + "help": ( + "It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded. " + "set True will benefit LLM loading time and RAM consumption." + ) + }, + ) + + def __post_init__(self): + if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): + raise ValueError( + "--config_overrides can't be used in combination with --config_name or --model_name_or_path" + ) + + +@dataclass +class DataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + """ + + dataset_name: Optional[str] = field( + default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} + ) + dataset_config_name: Optional[str] = field( + default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} + ) + train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."}) + validation_file: Optional[str] = field( + default=None, + metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}, + ) + max_train_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of training examples to this " + "value if set." + ) + }, + ) + max_eval_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of evaluation examples to this " + "value if set." + ) + }, + ) + streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"}) + block_size: Optional[int] = field( + default=None, + metadata={ + "help": ( + "Optional input sequence length after tokenization. " + "The training dataset will be truncated in block of this size for training. " + "Default to the model max input length for single sentence inputs (take into account special tokens)." + ) + }, + ) + overwrite_cache: bool = field( + default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} + ) + validation_split_percentage: Optional[int] = field( + default=5, + metadata={ + "help": "The percentage of the train set used as validation set in case there's no validation split" + }, + ) + preprocessing_num_workers: Optional[int] = field( + default=None, + metadata={"help": "The number of processes to use for the preprocessing."}, + ) + keep_linebreaks: bool = field( + default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."} + ) + + def __post_init__(self): + if self.streaming: + require_version("datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`") + + if self.dataset_name is None and self.train_file is None and self.validation_file is None: + raise ValueError("Need either a dataset name or a training/validation file.") + else: + if self.train_file is not None: + extension = self.train_file.split(".")[-1] + assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." + if self.validation_file is not None: + extension = self.validation_file.split(".")[-1] + assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." + + +def main(): + apply_ort = os.getenv("APPLY_ORT", "").lower() == "true" + apply_4bit = os.getenv("APPLY_4BIT", "").lower() == "true" + apply_tc = os.getenv("APPLY_TORCH_COMPILE", "").lower() == "true" + # See all possible arguments in src/transformers/training_args.py + # or by passing the --help flag to this script. + # We now keep distinct sets of args, for a cleaner separation of concerns. + + if apply_ort: + from optimum.onnxruntime import ORTTrainingArguments + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, ORTTrainingArguments)) + else: + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) + + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + if model_args.use_auth_token is not None: + warnings.warn( + "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead.", + FutureWarning, + ) + if model_args.token is not None: + raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.") + model_args.token = model_args.use_auth_token + + # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The + # information sent is the one passed as arguments along with your Python/PyTorch versions. + send_example_telemetry("run_clm", model_args, data_args) + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + + if training_args.should_log: + # The default of training_args.log_level is passive, so we set log level at info here to have that default. + transformers.utils.logging.set_verbosity_info() + + log_level = training_args.get_process_log_level() + logger.setLevel(log_level) + datasets.utils.logging.set_verbosity(log_level) + transformers.utils.logging.set_verbosity(log_level) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + # Log on each process the small summary: + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " + + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}" + ) + logger.info(f"Training/evaluation parameters {training_args}") + + # Detecting last checkpoint. + last_checkpoint = None + if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(training_args.output_dir) + if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: + raise ValueError( + f"Output directory ({training_args.output_dir}) already exists and is not empty. " + "Use --overwrite_output_dir to overcome." + ) + elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + + # Set seed before initializing model. + set_seed(training_args.seed) + + # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) + # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ + # (the dataset will be downloaded automatically from the datasets Hub). + # + # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called + # 'text' is found. You can easily tweak this behavior (see below). + # + # In distributed training, the load_dataset function guarantee that only one local process can concurrently + # download the dataset. + if data_args.dataset_name is not None: + # Downloading and loading a dataset from the hub. + raw_datasets = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + cache_dir=model_args.cache_dir, + token=model_args.token, + streaming=data_args.streaming, + ) + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + split=f"train[:{data_args.validation_split_percentage}%]", + cache_dir=model_args.cache_dir, + token=model_args.token, + streaming=data_args.streaming, + ) + raw_datasets["train"] = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + split=f"train[{data_args.validation_split_percentage}%:]", + cache_dir=model_args.cache_dir, + token=model_args.token, + streaming=data_args.streaming, + ) + else: + data_files = {} + dataset_args = {} + if data_args.train_file is not None: + data_files["train"] = data_args.train_file + if data_args.validation_file is not None: + data_files["validation"] = data_args.validation_file + extension = ( + data_args.train_file.split(".")[-1] + if data_args.train_file is not None + else data_args.validation_file.split(".")[-1] + ) + if extension == "txt": + extension = "text" + dataset_args["keep_linebreaks"] = data_args.keep_linebreaks + raw_datasets = load_dataset( + extension, + data_files=data_files, + cache_dir=model_args.cache_dir, + token=model_args.token, + **dataset_args, + ) + # If no validation data is there, validation_split_percentage will be used to divide the dataset. + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + extension, + data_files=data_files, + split=f"train[:{data_args.validation_split_percentage}%]", + cache_dir=model_args.cache_dir, + token=model_args.token, + **dataset_args, + ) + raw_datasets["train"] = load_dataset( + extension, + data_files=data_files, + split=f"train[{data_args.validation_split_percentage}%:]", + cache_dir=model_args.cache_dir, + token=model_args.token, + **dataset_args, + ) + + # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at + # https://huggingface.co/docs/datasets/loading_datasets. + + # Load pretrained model and tokenizer + # + # Distributed training: + # The .from_pretrained methods guarantee that only one local process can concurrently + # download model & vocab. + + config_kwargs = { + "cache_dir": model_args.cache_dir, + "revision": model_args.model_revision, + "token": model_args.token, + "trust_remote_code": model_args.trust_remote_code, + "force_download": True # for transient accessing cached config file error + } + if model_args.config_name: + config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs) + elif model_args.model_name_or_path: + config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs) + else: + config = CONFIG_MAPPING[model_args.model_type]() + logger.warning("You are instantiating a new config instance from scratch.") + if model_args.config_overrides is not None: + logger.info(f"Overriding config: {model_args.config_overrides}") + config.update_from_string(model_args.config_overrides) + logger.info(f"New config: {config}") + + tokenizer_kwargs = { + "cache_dir": model_args.cache_dir, + "use_fast": model_args.use_fast_tokenizer, + "revision": model_args.model_revision, + "token": model_args.token, + "trust_remote_code": model_args.trust_remote_code, + } + if model_args.tokenizer_name: + tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs) + elif model_args.model_name_or_path: + tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs) + else: + raise ValueError( + "You are instantiating a new tokenizer from scratch. This is not supported by this script. " + "You can do it from another script, save it, and load it from here, using --tokenizer_name." + ) + + if model_args.model_name_or_path: + torch_dtype = ( + model_args.torch_dtype + if model_args.torch_dtype in ["auto", None] + else getattr(torch, model_args.torch_dtype) + ) + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + token=model_args.token, + trust_remote_code=model_args.trust_remote_code, + torch_dtype=torch_dtype, + low_cpu_mem_usage=model_args.low_cpu_mem_usage, + ) + else: + model = AutoModelForCausalLM.from_config(config, trust_remote_code=model_args.trust_remote_code) + n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values()) + logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params") + + # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch + # on a small vocab and want a smaller embedding size, remove this test. + embedding_size = model.get_input_embeddings().weight.shape[0] + if len(tokenizer) > embedding_size: + model.resize_token_embeddings(len(tokenizer)) + + # Use LoRA performance efficient fine tuning + from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training + + target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"] + + peft_config = LoraConfig( + task_type=TaskType.CAUSAL_LM, + inference_mode=False, + r=8, + lora_alpha=32, + lora_dropout=0.1, + target_modules=target_modules + ) + if apply_4bit is True: + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False) + + model = get_peft_model(model, peft_config) + # Preprocessing the datasets. + # First we tokenize all the texts. + if training_args.do_train: + column_names = list(raw_datasets["train"].features) + else: + column_names = list(raw_datasets["validation"].features) + text_column_name = "text" if "text" in column_names else column_names[0] + + # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function + tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base") + + def tokenize_function(examples): + with CaptureLogger(tok_logger) as cl: + output = tokenizer(examples[text_column_name]) + # clm input could be much much longer than block_size + if "Token indices sequence length is longer than the" in cl.out: + tok_logger.warning( + "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits" + " before being passed to the model." + ) + return output + + with training_args.main_process_first(desc="dataset map tokenization"): + if not data_args.streaming: + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + num_proc=data_args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not data_args.overwrite_cache, + desc="Running tokenizer on dataset", + ) + else: + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + remove_columns=column_names, + ) + if hasattr(config, "max_position_embeddings"): + max_pos_embeddings = config.max_position_embeddings + else: + # Define a default value if the attribute is missing in the config. + max_pos_embeddings = 1024 + + if data_args.block_size is None: + block_size = tokenizer.model_max_length + if block_size > max_pos_embeddings: + logger.warning( + f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). " + f"Using block_size={min(1024, max_pos_embeddings)} instead. You can change that default value by passing --block_size xxx." + ) + if max_pos_embeddings > 0: + block_size = min(1024, max_pos_embeddings) + else: + block_size = 1024 + else: + if data_args.block_size > tokenizer.model_max_length: + logger.warning( + f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model " + f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." + ) + block_size = min(data_args.block_size, tokenizer.model_max_length) + + # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. + def group_texts(examples): + # Concatenate all texts. + concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} + total_length = len(concatenated_examples[list(examples.keys())[0]]) + # We drop the small remainder, and if the total_length < block_size we exclude this batch and return an empty dict. + # We could add padding if the model supported it instead of this drop, you can customize this part to your needs. + total_length = (total_length // block_size) * block_size + # Split by chunks of max_len. + result = { + k: [t[i : i + block_size] for i in range(0, total_length, block_size)] + for k, t in concatenated_examples.items() + } + result["labels"] = result["input_ids"].copy() + return result + + # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder + # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower + # to preprocess. + # + # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: + # https://huggingface.co/docs/datasets/process#map + + with training_args.main_process_first(desc="grouping texts together"): + if not data_args.streaming: + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + num_proc=data_args.preprocessing_num_workers, + load_from_cache_file=not data_args.overwrite_cache, + desc=f"Grouping texts in chunks of {block_size}", + ) + else: + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + ) + + if training_args.do_train: + if "train" not in tokenized_datasets: + raise ValueError("--do_train requires a train dataset") + train_dataset = lm_datasets["train"] + if data_args.max_train_samples is not None: + max_train_samples = min(len(train_dataset), data_args.max_train_samples) + train_dataset = train_dataset.select(range(max_train_samples)) + + if training_args.do_eval: + if "validation" not in tokenized_datasets: + raise ValueError("--do_eval requires a validation dataset") + eval_dataset = lm_datasets["validation"] + if data_args.max_eval_samples is not None: + max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) + eval_dataset = eval_dataset.select(range(max_eval_samples)) + + def preprocess_logits_for_metrics(logits, labels): + if isinstance(logits, tuple): + # Depending on the model and config, logits may contain extra tensors, + # like past_key_values, but logits always come first + logits = logits[0] + return logits.argmax(dim=-1) + + metric = evaluate.load("accuracy", cache_dir=model_args.cache_dir) + + def compute_metrics(eval_preds): + preds, labels = eval_preds + # preds have the same shape as the labels, after the argmax(-1) has been calculated + # by preprocess_logits_for_metrics but we need to shift the labels + labels = labels[:, 1:].reshape(-1) + preds = preds[:, :-1].reshape(-1) + return metric.compute(predictions=preds, references=labels) + + if apply_ort: + from optimum.onnxruntime import ORTTrainer + trainer_cls = ORTTrainer + else: + trainer_cls = Trainer + + if apply_tc: + model = torch.compile(model) + # Initialize our Trainer + trainer = trainer_cls( + model=model, + args=training_args, + train_dataset=train_dataset if training_args.do_train else None, + eval_dataset=eval_dataset if training_args.do_eval else None, + tokenizer=tokenizer, + # Data collator will default to DataCollatorWithPadding, so we change it. + data_collator=default_data_collator, + compute_metrics=compute_metrics if training_args.do_eval and not is_torch_xla_available() else None, + preprocess_logits_for_metrics=preprocess_logits_for_metrics + if training_args.do_eval and not is_torch_xla_available() + else None, + ) + + # Training + if training_args.do_train: + checkpoint = None + if training_args.resume_from_checkpoint is not None: + checkpoint = training_args.resume_from_checkpoint + elif last_checkpoint is not None: + checkpoint = last_checkpoint + train_result = trainer.train(resume_from_checkpoint=checkpoint) + trainer.save_model() # Saves the tokenizer too for easy upload + + metrics = train_result.metrics + + max_train_samples = ( + data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) + ) + metrics["train_samples"] = min(max_train_samples, len(train_dataset)) + + trainer.log_metrics("train", metrics) + trainer.save_metrics("train", metrics) + trainer.save_state() + + # Evaluation + if training_args.do_eval: + logger.info("*** Evaluate ***") + + metrics = trainer.evaluate() + + max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) + metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) + try: + perplexity = math.exp(metrics["eval_loss"]) + except OverflowError: + perplexity = float("inf") + metrics["perplexity"] = perplexity + + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"} + if data_args.dataset_name is not None: + kwargs["dataset_tags"] = data_args.dataset_name + if data_args.dataset_config_name is not None: + kwargs["dataset_args"] = data_args.dataset_config_name + kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" + else: + kwargs["dataset"] = data_args.dataset_name + + if training_args.push_to_hub: + trainer.push_to_hub(**kwargs) + else: + trainer.create_model_card(**kwargs) + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/llama3-finetune/finetune-clm/zero_stage_2.json b/llama3-finetune/finetune-clm/zero_stage_2.json new file mode 100644 index 00000000..746bb29c --- /dev/null +++ b/llama3-finetune/finetune-clm/zero_stage_2.json @@ -0,0 +1,39 @@ +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "zero_optimization": { + "stage": 2, + "allgather_partitions": true, + "allgather_bucket_size": 200000000, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": 200000000, + "contiguous_gradients": false, + "cpu_offload": false + }, + "zero_allow_untested_optimizer": true, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + "steps_per_print": 2000, + "train_micro_batch_size_per_gpu": "auto" +} \ No newline at end of file diff --git a/llama3-finetune/ws_config_template.json b/llama3-finetune/ws_config_template.json new file mode 100755 index 00000000..8255a6b9 --- /dev/null +++ b/llama3-finetune/ws_config_template.json @@ -0,0 +1,5 @@ +{ + "subscription_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + "resource_group": "rg-name", + "workspace_name": "ws-name" +} \ No newline at end of file diff --git a/phi3-finetune/README.md b/phi3-finetune/README.md index 87e0ea64..bd7bf531 100644 --- a/phi3-finetune/README.md +++ b/phi3-finetune/README.md @@ -4,7 +4,7 @@ This demo will show how to use ACPT (Azure Container for PyTorch) along with acc ## Background -[Phi-3](https://www.microsoft.com/en-us/research/blog/phi-3-the-surprising-power-of-small-language-models/) is 3.8 billion-parameter language model with next word prediction objective. It has been trained using mixture of Synthetic and Web datasets. +[Phi-3](https://www.microsoft.com/en-us/research/blog/phi-3-the-surprising-power-of-small-language-models/) is a family of small language and multimodal models developed by Microsoft, featuring a dense, decoder-only transformer architecture. The Phi-3-mini variant, with 3.8 billion parameters, is trained on 3.3 trillion tokens and achieves performance comparable to much larger models like GPT-3.5, making it highly efficient and capable despite its compact size​. This tutorial shows how to run finetine with Phi-3-mini-4k-instruct. ## Set up @@ -36,7 +36,7 @@ python aml_submit_clm.py The above script will generate two URLs, one for Pytorch and another for ONNX Runtime training. -We observe **~% speedup** for Phi-3 trained leveraging ONNX Runtime Training with 8 V100 GPUs with 32GB memory, with a batch size of . +We observe **30% speedup** for Phi-3 trained leveraging ONNX Runtime Training with 8 V100 GPUs with 32GB memory, with a batch size of 2. ### Run directly on your compute diff --git a/phi3-finetune/aml_submit_clm.py b/phi3-finetune/aml_submit_clm.py index bf651e0c..17bfde7f 100644 --- a/phi3-finetune/aml_submit_clm.py +++ b/phi3-finetune/aml_submit_clm.py @@ -50,19 +50,21 @@ def main(raw_args=None): code_dir = root_dir / "finetune-clm" model = "microsoft/Phi-3-mini-4k-instruct" + num_train_epochs = 5 bsz = 1 max_steps = -1 - block_size = 64 + block_size = 2048 dataset_name = "wikitext" dataset_config_name = "wikitext-2-raw-v1" text_column_name = "text" label_column_name = "label" + # Pytorch eager pytorch_job = command( code=code_dir, # local path where the code is stored - command=f"torchrun --nproc_per_node {nproc_per_node} run_clm.py \ + command=f"gmon torchrun --nproc_per_node {nproc_per_node} run_clm.py \ --model_name_or_path {model} \ --dataset_name {dataset_name} \ --dataset_config_name {dataset_config_name} \ @@ -70,24 +72,23 @@ def main(raw_args=None): --save_strategy 'no' \ --per_device_train_batch_size {bsz} \ --num_train_epochs {num_train_epochs} \ - --output_dir results --overwrite_output_dir \ + --output_dir ./outputs --overwrite_output_dir \ --fp16 --max_steps {max_steps} \ --block_size {block_size} \ --deepspeed zero_stage_2.json \ - --evaluation_strategy epoch --remove_unused_columns False --save_strategy no \ - --report_to tensorboard --logging_steps 100", + --evaluation_strategy epoch --remove_unused_columns False", environment=Environment(build=BuildContext(path=environment_dir)), experiment_name="Phi-3-Pytorch-CLM-LORA-Stage2-Experiment", compute=compute, display_name=model.replace( - "microsoft/phi-2", - f"pytorch+DS2_lora-{bsz}" + "microsoft/Phi-3", + f"TorchEager+DS2_lora-{bsz}-{block_size}-{num_train_epochs}epoch" ), - description=f"Finetune HuggingFace's Phi-3 using PyTorch and transformers branch", + description=f"Finetune HuggingFace's Phi-3 using PyTorch.", tags={"model": model, - "bsz": bsz, - "dataset_name": dataset_name, - "block_size": block_size}, + "bsz": bsz, + "dataset_name": dataset_name, + "block_size": block_size}, shm_size="16g" ) @@ -98,9 +99,10 @@ def main(raw_args=None): pytorch_aml_url = pytorch_returned_job.studio_url print("job link:", pytorch_aml_url) + # ORT perf ort_job = command( code=code_dir, # local path where the code is stored - command=f"torchrun --nproc_per_node {nproc_per_node} run_clm.py \ + command=f"gmon torchrun --nproc_per_node {nproc_per_node} run_clm.py \ --model_name_or_path {model} \ --dataset_name {dataset_name} \ --dataset_config_name {dataset_config_name} \ @@ -108,27 +110,30 @@ def main(raw_args=None): --save_strategy 'no' \ --per_device_train_batch_size {bsz} \ --num_train_epochs {num_train_epochs} \ - --output_dir results --overwrite_output_dir \ + --output_dir ./outputs --overwrite_output_dir \ --fp16 --max_steps {max_steps} \ - --block_size 2048 \ + --block_size {block_size} \ --deepspeed zero_stage_2.json \ - --evaluation_strategy no --remove_unused_columns False", + --evaluation_strategy epoch --remove_unused_columns False ", environment=Environment(build=BuildContext(path=environment_dir)), - environment_variables={"APPLY_ORT": "True", - "ORTMODULE_FALLBACK_POLICY": "FALLBACK_DISABLE", - "ORTMODULE_DEEPCOPY_BEFORE_MODEL_EXPORT": "0"}, + environment_variables={ + "APPLY_ORT": "True", + "ORTMODULE_FALLBACK_POLICY": "FALLBACK_DISABLE", + "ORTMODULE_DEEPCOPY_BEFORE_MODEL_EXPORT": "0"}, experiment_name="Phi-3-ORT-CLM-Stage2-Experiment", compute=compute, display_name=model.replace( - "microsoft/phi-3", - f"ort+DS2+Lora-{bsz}" + "microsoft/Phi-3", + f"ORT+DS2_lora-{bsz}-{block_size}-{num_train_epochs}epoch" ), - description=f"Finetune HuggingFace's Phi-3 using ONNX Runtime and transformers branch", + description=f"Finetune HuggingFace's Phi-3 using ONNX Runtime.", tags={"model": model, - "bsz": bsz, - "dataset_name": dataset_name, - "block_size": block_size}, + "bsz": bsz, + "dataset_name": dataset_name, + "block_size": block_size, + "epoch": num_train_epochs}, shm_size="16g" + ) print("submitting ORT job for " + model) @@ -138,5 +143,6 @@ def main(raw_args=None): ort_aml_url = ort_returned_job.studio_url print("job link:", ort_aml_url) + if __name__ == "__main__": main() diff --git a/phi3-finetune/environment/Dockerfile b/phi3-finetune/environment/Dockerfile index c6b42b54..94a14d3c 100644 --- a/phi3-finetune/environment/Dockerfile +++ b/phi3-finetune/environment/Dockerfile @@ -1,20 +1,24 @@ -FROM mcr.microsoft.com/aifx/acpt/stable-ubuntu2004-cu118-py38-torch220 -# RUN pip uninstall onnxruntime-training -y && \ -# pip install -i https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ORT/pypi/simple/ onnxruntime-training && \ -# TORCH_CUDA_ARCH_LIST="5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX" python -m onnxruntime.training.ortmodule.torch_cpp_extensions.install +FROM mcr.microsoft.com/aifx/acpt/stable-ubuntu2004-cu118-py310-torch222 # RUN pip install -U datasets evaluate accelerate scikit-learn transformers==4.40.1 RUN pip install -U datasets evaluate accelerate scikit-learn -RUN pip install git+https://github.com/jingyanwangms/transformers.git@jingywa/phi-3-tutorial +RUN pip install git+https://github.com/huggingface/transformers.git RUN pip install git+https://github.com/huggingface/optimum.git + # Insall numpy 1.26.4 because numpy 2.0.0 are not supported with many libraries RUN pip uninstall numpy -y && \ pip install numpy==1.26.4 +# Error with deepspeed=0.14.2 +RUN pip uninstall deepspeed -y && \ + pip install deepspeed==0.13.1 + RUN pip install einops RUN pip install --upgrade pytest RUN pip install peft + RUN pip list + diff --git a/phi3-finetune/finetune-clm/run_clm.py b/phi3-finetune/finetune-clm/run_clm.py index dd9cc798..c28bd70b 100644 --- a/phi3-finetune/finetune-clm/run_clm.py +++ b/phi3-finetune/finetune-clm/run_clm.py @@ -409,6 +409,7 @@ def main(): "revision": model_args.model_revision, "token": model_args.token, "trust_remote_code": model_args.trust_remote_code, + "force_download": True # for transient accessing cached config file error } if model_args.config_name: config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs) @@ -470,8 +471,7 @@ def main(): # Use LoRA performance efficient fine tuning from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training - target_modules = ["qkv_proj"] - # target_modules = ["qkv_proj", "o_proj", "gate_up_proj", "down_proj"] + target_modules = ["qkv_proj"] peft_config = LoraConfig( task_type=TaskType.CAUSAL_LM,