-
Notifications
You must be signed in to change notification settings - Fork 2
/
train.py
733 lines (646 loc) · 32 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import os
# os.environ['LD_LIBRARY_PATH'] = '/nfs/scistore19/alistgrp/imodoran/miniconda3/envs/llm_foundry/lib/'
import sys
PROJECTS_ROOT = os.environ.get('PROJECTS_ROOT', None)
if PROJECTS_ROOT is None or not os.path.isdir(PROJECTS_ROOT):
print(f'Please set PROJECTS_ROOT environment variable')
sys.exit(666)
PATH_LIB_LLM_FOUNDRY = os.path.join(PROJECTS_ROOT, 'MicroAdam', 'llm-foundry')
PATH_LM_EVAL_HARNESS = os.path.join(PROJECTS_ROOT, 'lm-evaluation-harness')
sys.path.append(PATH_LIB_LLM_FOUNDRY)
sys.path.append(PATH_LM_EVAL_HARNESS)
from evaluation import evaluate_model # this is from PATH_LM_EVAL_HARNESS
import copy
import gc
import logging
import time
import warnings
from typing import Any, Dict, List, Optional, Union
import torch
from composer import Trainer
from composer.core.callback import Callback
from composer.loggers import MosaicMLLogger
from composer.loggers.mosaicml_logger import (MOSAICML_ACCESS_TOKEN_ENV_VAR,
MOSAICML_PLATFORM_ENV_VAR)
from composer.metrics.nlp import InContextLearningMetric
from composer.profiler import (JSONTraceHandler, Profiler, TraceHandler,
cyclic_schedule)
from composer.utils import dist, get_device, reproducibility
from omegaconf import DictConfig, ListConfig
from omegaconf import OmegaConf as om
from rich.traceback import install
install()
from transformers import PreTrainedTokenizerBase
from streaming.base.util import clean_stale_shared_memory
from llmfoundry import COMPOSER_MODEL_REGISTRY
from llmfoundry.callbacks import AsyncEval
from llmfoundry.data.dataloader import build_dataloader
from llmfoundry.registry import import_file
from llmfoundry.utils.builders import (add_metrics_to_eval_loaders,
build_algorithm, build_callback,
build_evaluators, build_logger,
build_optimizer, build_scheduler,
build_tokenizer)
from llmfoundry.utils.config_utils import (log_config, pop_config,
process_init_device,
update_batch_size_info)
log = logging.getLogger(__name__)
def validate_config(cfg: DictConfig):
"""Validates compatible model and dataloader selection."""
loaders = [cfg.train_loader]
if 'eval_loader' in cfg:
eval_loader = cfg.eval_loader
if isinstance(eval_loader, ListConfig):
for loader in eval_loader:
if loader.label is None:
raise ValueError(
'When specifying multiple evaluation datasets, each one must include the \
`label` attribute.')
loaders.append(loader)
else:
loaders.append(eval_loader)
for loader in loaders:
if loader.name == 'text':
if cfg.model.name in ['hf_prefix_lm', 'hf_t5']:
raise ValueError(
f'Model type "{cfg.model.name}" is not supported when using the "text " ' +\
f'dataloader. Please use the "text_denoising" dataloader to pre-train that model type.')
elif loader.name == 'text_denoising':
if cfg.model.name == 'hf_causal_lm':
raise ValueError(
f'Model type "{cfg.model.name}" is not supported when using the "text_denoising" ' +\
f'dataloader. Please use the "text" dataloader to pre-train that model type.')
if loader.mixture_of_denoisers.decoder_only_format and cfg.model.name == 'hf_t5':
warnings.warn(
'Model type "hf_t5" requires `decoder_only_format` to be ``False``. ' +\
'Overriding `decoder_only_format` from ``True`` to ``False``.')
loader.mixture_of_denoisers.decoder_only_format = False
if (not loader.mixture_of_denoisers.decoder_only_format
) and cfg.model.name == 'hf_prefix_lm':
warnings.warn(
'Model type "hf_prefix_lm" requires `decoder_only_format` to be ``True``. ' +\
'Overriding `decoder_only_format` from ``False`` to ``True``.')
loader.mixture_of_denoisers.decoder_only_format = True
elif loader.name == 'finetuning':
if cfg.model.name == 'hf_prefix_lm':
is_prefix_lm = True
elif cfg.model.name == 'mpt_causal_lm':
is_prefix_lm = cfg.model.get('attn_config',
{}).get('prefix_lm', False)
else:
# Note: This only covers the two prefix-lms introduced in this repo
is_prefix_lm = False
target_responses = loader.dataset.get('target_responses', 'last')
target_prompts = loader.dataset.get('target_prompts', 'none')
prefix_lm_safe = target_responses == 'last' and target_prompts == 'none'
if is_prefix_lm and not prefix_lm_safe:
raise ValueError(
'The model configuration is building a Prefix-LM, which requires that the finetuning ' +\
'dataloader uses `target_responses`="last" and `target_prompts`="none".'
)
if 'icl_tasks' in cfg:
if cfg.model.name == 'hf_t5':
raise ValueError(
'ICL evaluation does not currently support Encoder-Decoder models, such as "hf_t5".'
)
if (cfg.model.get('fc_type', 'torch') != 'te' and 'te' not in cfg.model.get(
'ffn_config', {}).get('ffn_type', 'mptmlp') and
'fp8' in cfg.precision):
warnings.warn(
"fp8 only supported for te.Linear layers. Either set `cfg.model.fc_typ='te'` or "
+
"`cfg.model.ffn_config.ffn_type='te_ln_mlp'` to enable layers using fp8 precision."
)
if (cfg.model.get('fc_type', 'torch') == 'te' or
'te' in cfg.model.get('ffn_config', {}).get('ffn_type', 'mptmlp')):
fsdp_config = cfg.get('fsdp_config', None)
act_ckpt = fsdp_config.get('activation_checkpointing', False)
act_ckpt_reentrant = fsdp_config.get(
'activation_checkpointing_reentrant', True)
if fsdp_config is not None and act_ckpt == True and act_ckpt_reentrant == False:
warnings.warn(
'`te.Linear` layers do not support activation_checkpointing with '
+ '`activation_checkpointing_reentrant = False`. ' +
'Setting cfg.fsdp_config.activation_checkpointing_reentrant=True.'
)
cfg.fsdp_config.activation_checkpointing_reentrant = True
if 'te' in cfg.model.get('ffn_config', {}).get('ffn_type', 'mptmlp'):
warnings.warn(
'`te.LayerNormMLP` requires has issues with torch._dynamo. ' +
'Setting `torch._dynamo.config.suppress_errors = True` and falling back to eager.'
)
torch._dynamo.config.suppress_errors = True # type: ignore (third-party)
if cfg.model.get('load_in_8bit', False):
raise ValueError(
'`load_in_8bit` is only supported for evaluation rather than training.'
)
def build_composer_model(model_cfg: DictConfig,
tokenizer: PreTrainedTokenizerBase):
warnings.filterwarnings(
action='ignore',
message='Torchmetrics v0.9 introduced a new argument class property')
if model_cfg.name not in COMPOSER_MODEL_REGISTRY:
raise ValueError(
f'Not sure how to build model with name={model_cfg.name}')
return COMPOSER_MODEL_REGISTRY[model_cfg.name](model_cfg, tokenizer)
def main(cfg: DictConfig):
# Filter deprecation warning from torch internal usage
warnings.filterwarnings(
action='ignore',
category=UserWarning,
message=
'torch.distributed.*_base is a private function and will be deprecated.*'
)
task: str = pop_config(cfg, 'task', must_exist=True)
# Run user provided code if specified
code_paths = pop_config(cfg,
'code_paths',
must_exist=False,
default_value=[],
convert=True)
# Import any user provided code
for code_path in code_paths:
import_file(code_path)
# Check for incompatibilities between the model and data loaders
validate_config(cfg)
# Resolve all interpolation variables as early as possible
om.resolve(cfg)
# Create copy of config for logging
logged_cfg: DictConfig = copy.deepcopy(cfg)
# Get max split size mb
max_split_size_mb: Optional[int] = cfg.pop('max_split_size_mb', None)
if max_split_size_mb is not None:
os.environ[
'PYTORCH_CUDA_ALLOC_CONF'] = f'max_split_size_mb:{max_split_size_mb}'
# Set CUDA lazy loading
# This can save a bit of memory if not all modules are needed
cuda_load_lazy: bool = cfg.pop('cuda_load_lazy', False)
if cuda_load_lazy:
os.environ['CUDA_MODULE_LOADING'] = 'LAZY'
# Set seed first
seed: int = pop_config(cfg, 'seed', must_exist=True)
reproducibility.seed_all(seed)
# Initialize pytorch distributed training process groups
dist_timeout: Union[int, float] = pop_config(cfg,
'dist_timeout',
must_exist=False,
default_value=600.0)
dist.initialize_dist(get_device(None), timeout=dist_timeout)
# Get global and device batch size information from distributed/single node setting
cfg = update_batch_size_info(cfg)
logged_cfg.update(cfg, merge=True)
# Mandatory model training configs
model_config: DictConfig = pop_config(cfg, 'model', must_exist=True)
tokenizer_config: Dict[str, Any] = pop_config(cfg,
'tokenizer',
must_exist=True,
convert=True)
optimizer_config: Dict[str, Any] = pop_config(cfg,
'optimizer',
must_exist=True,
convert=True)
scheduler_config: Dict[str, Any] = pop_config(cfg,
'scheduler',
must_exist=True,
convert=True)
train_loader_config: DictConfig = pop_config(cfg,
'train_loader',
must_exist=True)
# Optional fsdp data, fine-tuning, and eval configs
fsdp_config: Optional[Dict[str, Any]] = pop_config(cfg,
'fsdp_config',
must_exist=False,
default_value=None,
convert=True)
eval_loader_config: Optional[Union[DictConfig, ListConfig]] = pop_config(
cfg, 'eval_loader', must_exist=False, default_value=None)
icl_tasks_config: Optional[Union[ListConfig,
str]] = pop_config(cfg,
'icl_tasks',
must_exist=False,
default_value=None)
eval_gauntlet_config: Optional[Union[DictConfig,
str]] = pop_config(cfg,
'eval_gauntlet',
must_exist=False,
default_value=None)
icl_subset_num_batches: Optional[int] = pop_config(cfg,
'icl_subset_num_batches',
must_exist=False,
default_value=None)
icl_seq_len: Optional[int] = pop_config(cfg,
'icl_seq_len',
must_exist=False,
default_value=None)
# Optional logging, evaluation and callback configs
logger_configs: Optional[DictConfig] = pop_config(cfg,
'loggers',
must_exist=False,
default_value=None,
convert=True)
callback_configs: Optional[DictConfig] = pop_config(cfg,
'callbacks',
must_exist=False,
default_value=None,
convert=True)
algorithm_configs: Optional[DictConfig] = pop_config(cfg,
'algorithms',
must_exist=False,
default_value=None)
# Mandatory hyperparameters for training
device_train_batch_size: int = pop_config(cfg,
'device_train_batch_size',
must_exist=True)
device_eval_batch_size: int = pop_config(cfg,
'device_eval_batch_size',
must_exist=True)
max_duration: Union[int, str] = pop_config(cfg,
'max_duration',
must_exist=True)
eval_interval: Union[int, str] = pop_config(cfg,
'eval_interval',
default_value=1,
must_exist=False)
precision: str = pop_config(cfg, 'precision', must_exist=True)
max_seq_len: int = pop_config(cfg, 'max_seq_len', must_exist=True)
# Optional parameters will be set to default values if not specified.
default_run_name: str = os.environ.get('RUN_NAME', 'llm')
run_name: str = pop_config(cfg,
'run_name',
must_exist=False,
default_value=default_run_name)
save_folder: Optional[str] = pop_config(cfg,
'save_folder',
must_exist=False,
default_value=None)
is_state_dict_sharded: bool = (fsdp_config.get('state_dict_type', 'full')
== 'sharded') if fsdp_config else False
save_latest_filename: str = pop_config(
cfg,
'save_latest_filename',
must_exist=False,
default_value='latest-sharded-rank{rank}'
if is_state_dict_sharded else 'latest-rank{rank}.pt')
save_overwrite: bool = pop_config(cfg,
'save_overwrite',
must_exist=False,
default_value=False)
save_weights_only: bool = pop_config(cfg,
'save_weights_only',
must_exist=False,
default_value=False)
save_filename: str = pop_config(
cfg,
'save_filename',
must_exist=False,
default_value='ep{epoch}-ba{batch}-rank{rank}.pt')
save_interval: Union[str, int] = pop_config(cfg,
'save_interval',
must_exist=False,
default_value='1000ba')
save_num_checkpoints_to_keep: int = pop_config(
cfg, 'save_num_checkpoints_to_keep', must_exist=False, default_value=-1)
progress_bar = pop_config(cfg,
'progress_bar',
must_exist=False,
default_value=False)
log_to_console: bool = pop_config(cfg,
'log_to_console',
must_exist=False,
default_value=True)
python_log_level: Optional[str] = pop_config(cfg,
'python_log_level',
must_exist=False,
default_value='debug')
console_log_interval: Union[int, str] = pop_config(cfg,
'console_log_interval',
must_exist=False,
default_value='1ba')
device_train_microbatch_size: Union[str, int] = pop_config(
cfg,
'device_train_microbatch_size',
must_exist=False,
default_value='auto')
eval_subset_num_batches: int = pop_config(cfg,
'eval_subset_num_batches',
must_exist=False,
default_value=-1)
eval_first: bool = pop_config(cfg,
'eval_first',
must_exist=False,
default_value=False)
load_path: str = pop_config(cfg,
'load_path',
must_exist=False,
default_value=None)
load_weights_only: bool = pop_config(cfg,
'load_weights_only',
must_exist=False,
default_value=False)
load_strict_model_weights: bool = pop_config(cfg,
'load_strict_model_weights',
must_exist=False,
default_value=True)
load_ignore_keys: Optional[List[str]] = pop_config(cfg,
'load_ignore_keys',
must_exist=False,
default_value=None)
compile_config: Optional[Dict[str, Any]] = pop_config(cfg,
'compile_config',
must_exist=False,
default_value=None)
metadata: Optional[Dict[str, str]] = pop_config(cfg,
'metadata',
must_exist=False,
default_value=None,
convert=True)
should_log_config: bool = pop_config(cfg,
'log_config',
must_exist=False,
default_value=True)
wandb_groups_config: Dict[str, Any] = pop_config(cfg,
'wandb_groups',
must_exist=True,
convert=True)
optimizer_name: str = optimizer_config.pop('name')
logger_configs['wandb']['group'] = wandb_groups_config[optimizer_name]['group']
wandb_project = logger_configs['wandb']['project']
wandb_group = logger_configs['wandb']['group']
wandb_job_type = logger_configs['wandb']['job_type']
wandb_name = logger_configs['wandb']['name']
run_name = f'{wandb_group}_{wandb_job_type}_{wandb_name}'
save_folder = os.path.join(save_folder, wandb_project, run_name)
callback_configs['hf_checkpointer']['save_folder'] = save_folder
print()
print(f'{save_folder=}')
print(f'{run_name=}')
print()
# Enable autoresume from model checkpoints if possible
autoresume_default: bool = False
if logged_cfg.get('run_name', None) is not None \
and save_folder is not None \
and not save_overwrite \
and not save_weights_only:
autoresume_default = True
if cfg.get('autoresume') is None and autoresume_default:
log.info('As run_name, save_folder, and save_latest_filename are set, \
changing autoresume default to True...')
autoresume: bool = pop_config(cfg,
'autoresume',
must_exist=False,
default_value=autoresume_default)
# Pop known unused parameters that are used as interpolation variables or
# created by update_batch_size_info.
pop_config(cfg, 'data_local', must_exist=False)
pop_config(cfg, 'data_remote', must_exist=False)
pop_config(cfg, 'global_seed', must_exist=False)
pop_config(cfg, 'global_train_batch_size', must_exist=False)
pop_config(cfg, 'n_gpus', must_exist=False)
pop_config(cfg, 'device_train_grad_accum', must_exist=False)
# Warn users for unused parameters
for key in cfg:
warnings.warn(
f'Unused parameter {key} found in cfg. Please check your yaml to ensure this parameter is necessary.'
)
# Warn if fsdp is enabled but user only has 1 GPU
if dist.get_world_size() == 1 and fsdp_config is not None:
warnings.warn(
'FSDP is not applicable for single-GPU training. Reverting to DDP.')
fsdp_config = None
# set logging level
if python_log_level is not None:
logging.basicConfig(
# Example of format string
# 2022-06-29 11:22:26,152: rank0[822018][MainThread]: INFO: Message here
format=
f'%(asctime)s: rank{dist.get_global_rank()}[%(process)d][%(threadName)s]: %(levelname)s: %(name)s: %(message)s'
)
logging.getLogger('llmfoundry').setLevel(
python_log_level.upper()) # Foundry module
logging.getLogger(__name__).setLevel(
python_log_level.upper()) # Train script
# Initialize context
init_context = process_init_device(model_config, fsdp_config)
logged_cfg.update({'fsdp_config': fsdp_config}, merge=True)
clean_stale_shared_memory()
# Build tokenizer
log.info('Building tokenizer...')
tokenizer_name = tokenizer_config['name']
tokenizer_kwargs = tokenizer_config.get('kwargs', {})
tokenizer = build_tokenizer(tokenizer_name, tokenizer_kwargs)
# Scheduler
scheduler_name: str = scheduler_config.pop('name')
scheduler = build_scheduler(scheduler_name, scheduler_config)
# Loggers
loggers = [
build_logger(str(name), logger_cfg)
for name, logger_cfg in logger_configs.items()
] if logger_configs else []
mosaicml_logger = next(
(logger for logger in loggers if isinstance(logger, MosaicMLLogger)),
None)
if mosaicml_logger is None:
if os.environ.get(MOSAICML_PLATFORM_ENV_VAR, 'false').lower(
) == 'true' and os.environ.get(MOSAICML_ACCESS_TOKEN_ENV_VAR):
# Adds mosaicml logger to composer if the run was sent from Mosaic platform, access token is set, and mosaic logger wasn't previously added
mosaicml_logger = MosaicMLLogger()
loggers.append(mosaicml_logger)
if metadata is not None:
# Flatten the metadata for logging
logged_cfg.pop('metadata', None)
logged_cfg.update(metadata, merge=True)
if mosaicml_logger is not None:
mosaicml_logger.log_metrics(metadata)
mosaicml_logger._flush_metadata(force_flush=True)
# Profiling
profiler: Optional[Profiler] = None
profiler_cfg: Optional[DictConfig] = pop_config(cfg,
'profiler',
must_exist=False,
convert=False,
default_value=None)
if profiler_cfg:
profiler_schedule_cfg: Dict = pop_config(profiler_cfg,
'schedule',
must_exist=True,
convert=True)
profiler_schedule = cyclic_schedule(**profiler_schedule_cfg)
# Only support json trace handler
profiler_trace_handlers: List[TraceHandler] = []
profiler_trace_cfg: Optional[Dict] = pop_config(profiler_cfg,
'json_trace_handler',
must_exist=False,
default_value=None,
convert=True)
if profiler_trace_cfg:
profiler_trace_handlers.append(
JSONTraceHandler(**profiler_trace_cfg))
profiler = Profiler(**profiler_cfg,
trace_handlers=profiler_trace_handlers,
schedule=profiler_schedule)
# Callbacks
callbacks: List[Callback] = [
build_callback(str(name), callback_cfg, om.to_container(logged_cfg))
for name, callback_cfg in callback_configs.items()
] if callback_configs else []
use_async_eval = any(isinstance(c, AsyncEval) for c in callbacks)
# Algorithms
algorithms = [
build_algorithm(str(name), algorithm_cfg)
for name, algorithm_cfg in algorithm_configs.items()
] if algorithm_configs else None
# Dataloaders
log.info('Building train loader...')
train_loader = build_dataloader(
train_loader_config,
tokenizer,
device_train_batch_size,
)
if mosaicml_logger is not None:
mosaicml_logger.log_metrics({'data_validated': time.time()})
## Evaluation
if use_async_eval:
evaluators = []
if eval_first:
warnings.warn(
'AsyncEval callback does not support eval_first=True. Ignoring.'
)
eval_first = False
else:
log.info('Building eval loader...')
eval_icl_seq_len: int = icl_seq_len if icl_seq_len else max_seq_len
evaluators, _, eval_gauntlet_callback = build_evaluators(
eval_loader_config,
icl_tasks_config,
eval_gauntlet_config,
tokenizer=tokenizer,
device_eval_batch_size=device_eval_batch_size,
icl_seq_len=eval_icl_seq_len,
icl_subset_num_batches=icl_subset_num_batches,
)
if eval_gauntlet_callback is not None:
callbacks.append(eval_gauntlet_callback)
# Build Model
log.info('Initializing model...')
with init_context:
model = build_composer_model(model_config, tokenizer)
if model_config.get('master_weights_dtype') in ('bf16', 'bfloat16'):
model = model.to(dtype=torch.bfloat16)
elif model_config.get('master_weights_dtype') in ('f16', 'float16'):
model = model.to(dtype=torch.float16)
# Log number of parameters
n_params = sum(p.numel() for p in model.parameters())
n_trainable_params = sum(
p.numel() for p in model.parameters() if p.requires_grad)
logged_cfg.update({
'n_params': n_params,
'n_trainable_params': n_trainable_params,
})
# Optimizer
optimizer = build_optimizer(model, optimizer_name, optimizer_config)
# Now add the eval metrics
if eval_loader_config is not None and not use_async_eval:
eval_metrics = model.get_metrics(is_train=False)
non_icl_metrics = [
metric_name for metric_name, metric in eval_metrics.items()
if not isinstance(metric, InContextLearningMetric)
]
evaluators = add_metrics_to_eval_loaders(evaluators, non_icl_metrics)
# from helpers.tools import print_model_architecture
# print_model_architecture(model,
# file=f'/nfs/scistore19/alistgrp/imodoran/workplace/M-FAC_extensions/architectures/llama2-7b_gsm8k.txt',
# exit666=False)
# Build the Trainer
log.info('Building trainer...')
trainer = Trainer(
run_name=run_name,
seed=seed,
model=model,
train_dataloader=train_loader,
eval_dataloader=evaluators,
optimizers=optimizer,
schedulers=scheduler,
max_duration=max_duration,
eval_interval=eval_interval,
eval_subset_num_batches=eval_subset_num_batches,
progress_bar=progress_bar,
log_to_console=log_to_console,
console_log_interval=console_log_interval,
loggers=loggers,
callbacks=callbacks,
precision=precision,
algorithms=algorithms,
device_train_microbatch_size=device_train_microbatch_size,
fsdp_config=fsdp_config,
save_folder=save_folder,
save_filename=save_filename,
save_latest_filename=save_latest_filename,
save_interval=save_interval,
save_num_checkpoints_to_keep=save_num_checkpoints_to_keep,
save_overwrite=save_overwrite,
save_weights_only=save_weights_only,
load_path=load_path,
load_weights_only=load_weights_only,
load_strict_model_weights=load_strict_model_weights,
load_ignore_keys=load_ignore_keys,
autoresume=autoresume,
python_log_level=python_log_level,
dist_timeout=dist_timeout,
profiler=profiler,
compile_config=compile_config,
)
if should_log_config:
log.info('Logging config')
log_config(logged_cfg)
with torch.cuda.device(f'cuda:{torch.distributed.get_rank()}'):
torch.cuda.empty_cache()
gc.collect()
# Eval first if requested
if eval_first and trainer.state.timestamp.batch.value == 0:
trainer.eval()
log.info('Starting training...')
time_train_start = time.time()
trainer.fit()
time_train_end = time.time()
log.info('Done.')
with torch.cuda.device(f'cuda:{torch.distributed.get_rank()}'):
torch.cuda.empty_cache()
gc.collect()
delete_pt_files(save_folder)
def convert_seconds_to_hours_minutes_seconds(ss):
ss = int(ss)
hh = ss // 3600
ss %= 3600
mm = ss // 60
ss %= 60
return f'{hh}h {mm}m {ss}s'
time_eval_start = time.time()
acc, acc_std = evaluate_model(ft_model_path=os.path.join(save_folder, 'huggingface'), task=task)
time_eval_end = time.time()
elapsed_train = convert_seconds_to_hours_minutes_seconds(time_train_end - time_train_start)
elapsed_eval = convert_seconds_to_hours_minutes_seconds(time_eval_end - time_eval_start)
loggers[0].log_metrics(dict(acc=acc, acc_std=acc_std, elapsed_train=elapsed_train, elapsed_eval=elapsed_eval))
def delete_pt_files(folder):
"""
This method deletes the pt files that are created in save_folder.
For evaluation we use the HF format saved in save_folder/huggingface
"""
for file in os.listdir(folder):
if file.endswith('.pt'):
f = os.path.join(folder, file)
os.remove(f)
print(f'Deleted {f}')
if __name__ == '__main__':
yaml_path, args_list = sys.argv[1], sys.argv[2:]
# Disable resolving environment variables through omegaconf.
om.clear_resolver('oc.env')
# Load yaml and cli arguments.
with open(yaml_path) as f:
yaml_cfg = om.load(f)
cli_cfg = om.from_cli(args_list)
cfg = om.merge(yaml_cfg, cli_cfg)
om.resolve(cfg)
assert isinstance(cfg, DictConfig)
main(cfg)