|
| 1 | +# Copyright © 2022 BAAI. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License") |
| 4 | +import os |
| 5 | +import torch |
| 6 | +from torch.utils.data import Dataset |
| 7 | +import gc |
| 8 | +import json |
| 9 | + |
| 10 | +gc.collect() |
| 11 | +torch.cuda.empty_cache() |
| 12 | + |
| 13 | +from transformers import AutoModelForCausalLM, AutoTokenizer |
| 14 | +from transformers.models.llama import LlamaConfig, LlamaForCausalLM |
| 15 | +from llama_bmt_monkey_patch import ( |
| 16 | + replace_llama_attn_with_bmt, |
| 17 | +) |
| 18 | + |
| 19 | +from flagai.env_args import EnvArgs |
| 20 | +from flagai.env_trainer_v1 import EnvTrainer |
| 21 | +from flagai.data.dataset.indexed_dataset.build_index_mappings import _build_train_valid_test_datasets, _build_train_valid_test_weighted_datasets |
| 22 | +import bmtrain as bmt |
| 23 | + |
| 24 | +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 25 | + |
| 26 | +# You can input all parameters by the command line. |
| 27 | +# For example: python train_env_trainer.py --epochs=300 --batch_size=4 --env_type=pytorch |
| 28 | +env_args = EnvArgs( |
| 29 | + env_type="bmtrain", |
| 30 | + experiment_name="llama3", |
| 31 | + batch_size=1, |
| 32 | + gradient_accumulation_steps=1, |
| 33 | + lr=2e-4, |
| 34 | + weight_decay=1e-3, |
| 35 | + epochs=10000, |
| 36 | + log_interval=1, |
| 37 | + eval_interval=5000, |
| 38 | + num_gpus=1, |
| 39 | + load_dir=None, |
| 40 | + pytorch_device=device, |
| 41 | + save_dir="checkpoints_out", |
| 42 | + checkpoint_activations=False, |
| 43 | + save_interval=100, |
| 44 | + fp16=True, |
| 45 | + training_script=__file__, |
| 46 | +) |
| 47 | +env_args = env_args.parse_args() |
| 48 | +#env_args.wandb = False |
| 49 | + |
| 50 | +# overwrite |
| 51 | +if env_args.yaml_config: |
| 52 | + import yaml |
| 53 | + file_data = open(env_args.yaml_config, 'r', encoding="utf-8").read() |
| 54 | + data = yaml.load_all(file_data, Loader=yaml.SafeLoader) |
| 55 | + delattr(env_args, 'yaml_config') |
| 56 | + arg_dict = env_args.__dict__ |
| 57 | + for subdata in data: |
| 58 | + for key, value in subdata.items(): |
| 59 | + if isinstance(value, list): |
| 60 | + for v in value: |
| 61 | + arg_dict[key].append(v) |
| 62 | + else: |
| 63 | + arg_dict[key] = value |
| 64 | +trainer = EnvTrainer(env_args) |
| 65 | + |
| 66 | +# Trainer as Trigger |
| 67 | +if not env_args.not_call_launch: |
| 68 | + import sys |
| 69 | + sys.exit(0) |
| 70 | + |
| 71 | +print(f"Trainer effective env_args={env_args} local_rank={os.environ['LOCAL_RANK']}", |
| 72 | + flush=True) |
| 73 | +checkpoints = env_args.pre_load_dir |
| 74 | +model_name = env_args.model_name |
| 75 | + |
| 76 | +print('*' * 20, "model_name", model_name, flush=True) |
| 77 | + |
| 78 | +cache_dir = os.path.join(checkpoints, model_name) |
| 79 | +print('*' * 20, "cache_dir", cache_dir) |
| 80 | +tokenizer = AutoTokenizer.from_pretrained(cache_dir) |
| 81 | +print('*' * 20, "tokenizer", tokenizer) |
| 82 | + |
| 83 | +# avoid sync loading models in case of Mem OOM |
| 84 | +if env_args.bmt_async_load: |
| 85 | + import time |
| 86 | + time.sleep(10 * 60 * (os.environ['LOCAL_RANK'] % 4)) |
| 87 | + |
| 88 | +config_file = os.path.join(cache_dir, 'config.json') |
| 89 | +with open(config_file, 'r') as f: |
| 90 | + model_args = json.load(f) |
| 91 | + |
| 92 | +# bmt |
| 93 | +replace_llama_attn_with_bmt() |
| 94 | + |
| 95 | +model = LlamaForCausalLM.from_pretrained(cache_dir) |
| 96 | + |
| 97 | +## bmt_pre_load |
| 98 | + |
| 99 | +trainer.pre_train(model) |
| 100 | + |
| 101 | +print('*' * 20, "model", model, flush=True) |
| 102 | + |
| 103 | +## Use Prebuilt DataSets |
| 104 | +data_prefix = '../indexed_dataset/data/demo_text_document' |
| 105 | +data_impl = 'mmap' |
| 106 | +splits_string = '90,10' |
| 107 | +train_valid_test_num_samples = [90, 10] |
| 108 | +seq_length = 1024 |
| 109 | +seed = 2023 |
| 110 | +skip_warmup = True |
| 111 | + |
| 112 | +train_dataset, valid_dataset, _ = _build_train_valid_test_datasets( |
| 113 | + data_prefix, data_impl, splits_string, train_valid_test_num_samples, |
| 114 | + seq_length, seed, skip_warmup) |
| 115 | +print("Total train_dataset: ", len(train_dataset), flush=True) |
| 116 | +print("Total valid_dataset: ", len(valid_dataset), flush=True) |
| 117 | + |
| 118 | + |
| 119 | +def collate_fn(batch): |
| 120 | + |
| 121 | + def padding(indice, max_length, pad_idx=0): |
| 122 | + pad_indice = [ |
| 123 | + item.tolist() + [pad_idx] * max(0, max_length - len(item.tolist())) |
| 124 | + for item in indice |
| 125 | + ] |
| 126 | + return torch.tensor(pad_indice) |
| 127 | + |
| 128 | + input_ids = [data["input_ids"] for data in batch] |
| 129 | + max_length = max([len(t) for t in input_ids]) |
| 130 | + input_ids = padding(input_ids, max_length)[:, :seq_length] |
| 131 | + |
| 132 | + data = {"input_ids": input_ids, "labels": input_ids} |
| 133 | + return data |
| 134 | + |
| 135 | + |
| 136 | +trainer.do_train(train_dataset=train_dataset, |
| 137 | + valid_dataset=None, |
| 138 | + collate_fn=collate_fn, |
| 139 | + optimizer=None, |
| 140 | + rank_split=False) |
| 141 | + |
0 commit comments