forked from tdrussell/diffusion-pipe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdgls_train.py
More file actions
3001 lines (2427 loc) · 127 KB
/
Copy pathdgls_train.py
File metadata and controls
3001 lines (2427 loc) · 127 KB
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import os
import wandb
import datetime
import shutil
import glob
import json
import inspect
from pathlib import Path
from functools import wraps
import toml
import deepspeed
from deepspeed import comm as dist
from deepspeed.runtime.pipe import module as ds_pipe_module
from torch import nn
from torch.utils.tensorboard import SummaryWriter
import time
from utils import common
from utils.common import is_main_process, get_rank, DTYPE_MAP, empty_cuda_cache
import utils.saver
from utils.patches import apply_patches
from utils.unsloth_utils import unsloth_checkpoint
from utils.pipeline import ManualPipelineModule
from collections import defaultdict
import torch
import gc
import threading
import warnings
import psutil
import types
import bitsandbytes as bnb
import torch.profiler
import torch.cuda.nvtx as nvtx
import torch._dynamo
from functools import partial
import torch.utils.checkpoint
import utils.dataset as dataset_util
from utils.memory_monitor import check_wsl_free_memory, print_detailed_memory_stats, print_gpu_layer_state, aggressive_cpu_cleanup
warnings.filterwarnings("ignore", message="Padding mask is disabled")
from utils.mixed_precision_handler import (
patch_mixed_precision,
get_mixed_precision_clip_function,
CastingHandler)
torch.utils.checkpoint.set_checkpoint_early_stop(False)
#Patch the checkpoint function to disable determinism checking # This disables the metadata checking
torch.utils.checkpoint.checkpoint = partial(
torch.utils.checkpoint.checkpoint,
determinism_check="none")
torch._dynamo.config.suppress_errors = True
wandb_enable = False
"""
Dynamic GPU Layer Swapping Trainer
==================================
Enhanced training with automatic memory optimization.
PERFORMANCE DESIGN NOTE:
This file uses module-level functions with local variable binding for optimal performance.
Hot path functions bind frequently-accessed attributes to locals at function start (LOAD_FAST)
to avoid Python's attribute lookup overhead (LOAD_ATTR). Call chains are minimized to
reduce function call overhead.
Architecture:
- Globals: Intentionally used for performance (documented below)
- Hot functions: Bind globals to locals once per call
- Minimal call depth: Direct function calls without abstraction layers
- Factory pattern: Clean call sites with fast execution
CRITICAL PATH: Functions marked "HOT PATH" - profile before changing!
"""
# =============================================================================
# CONSTANTS & CONFIGURATION
# =============================================================================
# PROCEED WITH CAUTION WITH ZERO OPTIMIZERS, SHARDED, GRADIENT RELEASE OR GENERICOPTIM!
# THESE WILL NOT PLAY WELL WITH LAYER SWAPPING.
TIMESTEP_QUANTILES_FOR_EVAL = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='Path to TOML configuration file.')
parser.add_argument('--local_rank', type=int, default=-1,
help='local rank passed from distributed launcher')
parser.add_argument('--resume_from_checkpoint', nargs='?', const=True, default=None,
help='resume training from checkpoint. If no value is provided, resume from the most recent checkpoint. If a folder name is provided, resume from that specific folder.')
parser.add_argument('--regenerate_cache', action='store_true', help='Force regenerate cache.')
parser.add_argument('--cache_only', action='store_true', help='Cache model inputs then exit.')
parser.add_argument('--trust_cache', action='store_true',
help='Load from metadata cache files if they exist, without checking if any fingerprints have changed. Can make loading much faster for large datasets.')
parser.add_argument('--i_know_what_i_am_doing', action='store_true',
help="Skip certain checks and overrides. You may end up using settings that won't work.")
parser.add_argument('--master_port', type=int, default=29500, help='Master port for distributed training')
parser.add_argument('--dump_dataset', type=Path, default=None,
help='Decode cached latents and dump the dataset to this directory.')
parser.add_argument('--dynamic_swapping', action='store_true', default=True,
help='Smart dynamic layer swapping between GPU and CPU for optimal performance.')
parser.add_argument('--gpu_id', type=int, default=0, help='GPU ID to use (0, 1, 2, etc.)')
parser.add_argument('--device_sync_mode', choices=['early', 'late', 'off'], default='late',
help='When to sync devices: early (post-checkpoint: unstable on 2060), late (pre-optimizer,default, early causes instability in some GPUs), off (disabled)')
parser.add_argument('--sync_only_on_resume', action='store_true',
help='Only run device sync when resuming from checkpoint, not on fresh training')
parser.add_argument('--initial_gpu_layers', type=int, default=1,
help='Number of initial layers to keep permanently on GPU. '
'If not specified, uses reasonable defaults based on estimated VRAM.')
parser.add_argument('--final_gpu_layers', type=int, default=1,
help='Number of final layers to keep permanently on GPU.')
parser.add_argument('--gpu_layers', type=str, default=None,
help='Comma-separated list of layer indices to keep permanently on GPU '
'(e.g., "0,1,2,14,18,19,20,21,22"). Overrides initial_gpu_layers and final_gpu_layers '
'for precise control over which specific layers stay on GPU vs get swapped to CPU. '
'Use this to target problematic layer types while maximizing swappable layers. Your layer types will print at startup.')
parser.add_argument('--prefetch', type=int, nargs='?', const=1, default=0,
help='Number of layers to prefetch ahead (0=off, 1=single layer, 2+=multiple layers), might not work with mixed lyer type models')
parser.add_argument('--threading', action='store_true', default=False,
help='Enable background threading for automatic layer management')
parser.add_argument('--cuda_streams', action='store_true', default=False,
help='Enable CUDA streams for copy-compute overlap (needs more VRAM)')
parser.add_argument('--batch_move', action='store_true', default=False,
help='Use batch layer moving (experimental, may cause device issues)')
parser.add_argument('--cast_target', nargs=2, metavar=('FROM', 'TO'),
help='Cast FROM dtype TO dtype at start-up (e.g., f32 bf16) choices=[f32, bf16, f16, f8_e4m3, f8_e5m2, nf4, fp4]')
parser.add_argument('--selective_packing', type=int,nargs='?', const=64, default=0,
help='Size threshold in MB for using packed transfers (default: 64MB)')
parser.add_argument('--event_sync', action='store_true', default=False,
help='Use CUDA events instead of torch.cuda.synchronize() for better performance')
parser.add_argument('--async_zero_grad', action='store_true', default=False,
help='Zero gradients asynchronously on separate CUDA stream')
parser.add_argument('--lazy_lora_steps', type=int, default=1,
help='Update LoRA adapters every N steps instead of every step (1=disabled)')
parser.add_argument('--compile', action='store_true', default=False,
help='Use torch.compile optimization for resident GPU layers')
parser.add_argument('--autocast', choices=['fp32', 'fp16', 'bf16', 'f8_e4m3', 'f8_e5m2'], default=None,
help='Autocast precision for mixed precision training (fp32=disabled, fp16, bf16, f8_e4m3, f8_e5m2)')
parser.add_argument('--mixed_precision', choices=['auto', 'f32', 'bf16', 'f16'], default='auto',
help='Target dtype for problematic mixed precision conversions. '
'auto: smart fallback (f8→bf16, int8→f16), '
'f32/bf16/f16: convert all problematic dtypes to specified target. '
'Choices: auto, f32, bf16, f16')
parser.add_argument('--verbose', action='store_true', default=False,
help='Enable verbose output with detailed timing and transfer information')
# install_math_guard(mode='move') #set to move for production
parser = deepspeed.add_config_arguments(parser)
args = parser.parse_args()
patch_mixed_precision(mixed_precision_target=args.mixed_precision)
PROFILE = False
VERBOSE = args.verbose #False
TRACING_PROFILER = False
casting_handler = None
if args.cast_target:
casting_handler = CastingHandler()
# =============================================================================
# GLOBALS MANIFEST (intentionally module-level for performance)
# =============================================================================
# Device configuration
PRIMARY_GPU_ID = 0
GPU_DEVICE = None # Set after device detection
CPU_DEVICE = 'cpu'
# Swapping state
swap_stats = {'to_gpu': 0, 'to_cpu': 0}
transfer_events = {}
layer_sizes_mb = {}
expected_steps = 0
# Training state
ds_config = None
model_highest_precision = None
STATS_WINDOW_SIZE = 10
# Required for DeepSpeed to avoid "cannot load mpi library" error
os.environ['WORLD_SIZE'] = '1'
os.environ['RANK'] = '0'
os.environ['LOCAL_RANK'] = '0'
# os.environ['CUDA_LAUNCH_BLOCKING'] = '1' # Synchronous CUDA
# Add global transfer and step stats
transfer_stats = {
'to_gpu_times': [],
'to_cpu_times': [],
'to_gpu_speeds': [],
'to_cpu_speeds': [],
'current_step_gpu_times': [], # Add these new fields
'current_step_cpu_times': [],
'current_step_gpu_speeds': [],
'current_step_cpu_speeds': [],
'step_durations': [],
'step_total_transfer_times': [],
'step_avg_transfer_speeds': []
}
gpu_resident_layers = set()
cpu_swappable_layers = set()
packed_layers = {}
device_cache = None
layers = None
model_engine = None
# Override with command line args if provided
if args.initial_gpu_layers is not None:
initial_gpu_layers = args.initial_gpu_layers
print(f" Overriding initial_gpu_layers: {initial_gpu_layers}")
if args.final_gpu_layers is not None:
final_gpu_layers = args.final_gpu_layers
print(f" Overriding final_gpu_layers: {final_gpu_layers}")
elif args.initial_gpu_layers is not None:
# If only initial is specified, match final to initial
final_gpu_layers = args.initial_gpu_layers
print(f" Setting final_gpu_layers to match initial: {final_gpu_layers}")
print(" Dynamic GPU Layer Swapping Trainer")
print(f" Initial GPU layers: {initial_gpu_layers}")
print(f" Final GPU layers: {final_gpu_layers}")
print(f" Prefetch: {args.prefetch}")
print(f" Threading: {'enabled' if args.threading else 'disabled'}")
if torch.cuda.is_available():
available_gpus = torch.cuda.device_count()
print(f" Available GPUs: {available_gpus}")
# Override with command line argument if provided
if hasattr(args, 'gpu_id') and args.gpu_id != 0: # Only override if explicitly set
PRIMARY_GPU_ID = args.gpu_id
print(f" Command line override: using GPU {PRIMARY_GPU_ID}")
else:
print(f" Using default GPU {PRIMARY_GPU_ID}")
if PRIMARY_GPU_ID >= available_gpus:
print(f" GPU {PRIMARY_GPU_ID} not available, falling back to GPU 0")
PRIMARY_GPU_ID = 0
PRIMARY_GPU_DEVICE = f'cuda:{PRIMARY_GPU_ID}'
print(f" Using GPU {PRIMARY_GPU_ID} ({PRIMARY_GPU_DEVICE})")
# Set the primary device for CUDA operations
torch.cuda.set_device(PRIMARY_GPU_ID)
else:
PRIMARY_GPU_DEVICE = 'cpu'
print(" No CUDA available, using CPU")
# Device strings for easy replacement
GPU_DEVICE = PRIMARY_GPU_DEVICE
CPU_DEVICE = 'cpu'
print(f" Device configuration: GPU={GPU_DEVICE}, CPU={CPU_DEVICE}")
import sys
def in_recompute(max_depth=12):
f = sys._getframe(1) # caller
for _ in range(max_depth):
name = f.f_code.co_name.lower()
file = (f.f_code.co_filename or "").lower()
if ('recompute' in name or 'backward' in name or 'autograd' in file):
return True
f = f.f_back
if f is None:
break
return False
def get_cached_layer_size_mb(idx):
return layer_sizes_mb.get(idx, 0)
def lazy_lora_step(model_engine, step):
"""Only run optimizer.step() every N steps for LoRA"""
if step % args.lazy_lora_steps == 0:
# Normal optimizer step
if VERBOSE:
start_time = time.time()
model_engine.optimizer.step()
if VERBOSE:
optimizer_time = time.time() - start_time
if not hasattr(model_engine, 'optimizer_times'):
model_engine.optimizer_times = []
if VERBOSE:
model_engine.optimizer_times.append(optimizer_time)
print(f" LoRA optimizer step: {optimizer_time:.4f}s")
return True
else:
# Skip optimizer step, but still zero gradients
model_engine.optimizer.zero_grad()
if VERBOSE:
print(f" Skipped LoRA optimizer step {step}")
# Add zero time to keep timing consistent
if not hasattr(model_engine, 'optimizer_times'):
model_engine.optimizer_times = []
if VERBOSE:
model_engine.optimizer_times.append(0.0)
return False
def async_zero_gradients(model_engine):
"""Zero gradients asynchronously if enabled"""
if (args.async_zero_grad and args.cuda_streams and
hasattr(add_smart_swapping_to_layer, 'async_zero_stream')):
with torch.cuda.stream(add_smart_swapping_to_layer.async_zero_stream):
model_engine.optimizer.zero_grad()
zero_event = torch.cuda.Event()
zero_event.record(add_smart_swapping_to_layer.async_zero_stream)
torch.cuda.current_stream().wait_event(zero_event)
else:
model_engine.optimizer.zero_grad()
def reset_current_step_stats():
"""Reset stats for the current step"""
transfer_stats['current_step_gpu_times'] = []
transfer_stats['current_step_cpu_times'] = []
transfer_stats['current_step_gpu_speeds'] = []
transfer_stats['current_step_cpu_speeds'] = []
def calculate_step_transfer_stats():
"""Calculate transfer stats for the current step"""
all_times = transfer_stats['current_step_gpu_times'] + transfer_stats['current_step_cpu_times']
all_speeds = transfer_stats['current_step_gpu_speeds'] + transfer_stats['current_step_cpu_speeds']
if not all_times:
return None, None, None
total_transfer_time = sum(all_times)
avg_transfer_speed = sum(all_speeds) / len(all_speeds) if all_speeds else 0
avg_transfer_duration = sum(all_times) / len(all_times) if all_times else 0
return total_transfer_time, avg_transfer_speed, avg_transfer_duration
def track_step_performance(step_duration, step_num, layer_compute_time, end_of_training):
"""Track step duration with complete timing breakdown"""
# Calculate current step transfer stats
total_transfer_time, avg_transfer_speed, avg_transfer_duration = calculate_step_transfer_stats()
transfer_stats['step_durations'].append(step_duration)
if total_transfer_time is not None:
transfer_stats['step_total_transfer_times'].append(total_transfer_time)
transfer_stats['step_avg_transfer_speeds'].append(avg_transfer_speed)
if step_num % STATS_WINDOW_SIZE == 0 or end_of_training:
# Get available data, up to STATS_WINDOW_SIZE
window_size = min(STATS_WINDOW_SIZE, len(transfer_stats['step_durations']))
recent_step_times = transfer_stats['step_durations'][-window_size:]
avg_step_time = sum(recent_step_times) / len(recent_step_times)
if transfer_stats['step_avg_transfer_speeds']:
recent_transfer_speeds = transfer_stats['step_avg_transfer_speeds'][-window_size:]
avg_transfer_speed_windowed = sum(recent_transfer_speeds) / len(recent_transfer_speeds)
recent_transfer_times = transfer_stats['step_total_transfer_times'][-window_size:]
avg_transfer_time_windowed = sum(recent_transfer_times) / len(recent_transfer_times)
total_seconds = avg_step_time * expected_steps
remaining_seconds = (expected_steps - step_num) * avg_step_time
expected_total_str = str(datetime.timedelta(seconds=int(total_seconds)))
time_remaining_str = str(datetime.timedelta(seconds=int(remaining_seconds)))
print(
f" Last {window_size} steps avg: {avg_step_time:.1f}s step duration, {avg_transfer_time_windowed:.2f}s transfer time, {avg_transfer_speed_windowed:.0f} MB/s, "
f"Expected total time: {expected_total_str}, "
f"Remaining Steps: {expected_steps - step_num}, "
f"Time remaining: {time_remaining_str}")
# Reset for next step
reset_current_step_stats()
# Clear DeepSpeed times for next step
if hasattr(model_engine, 'optimizer_times'):
model_engine.optimizer_times = []
if hasattr(model_engine, 'backward_times'):
model_engine.backward_times = []
add_smart_swapping_to_layer.layer_compute_times = []
def event_based_sync(operation_name, idx=None):
"""Replace torch.cuda.synchronize() with specific event tracking"""
if args.event_sync:
event = torch.cuda.Event()
event.record()
key = f"{operation_name}_{idx}" if idx is not None else operation_name
transfer_events[key] = event
return event
else:
torch.cuda.synchronize()
return None
def wait_for_event(operation_name, idx=None):
"""Wait for specific event to complete"""
if args.event_sync:
key = f"{operation_name}_{idx}" if idx is not None else operation_name
if key in transfer_events:
transfer_events[key].wait()
del transfer_events[key]
class LayerDeviceCache:
def __init__(self, model, layers): # Add layers parameter
self.cache = {}
self.dirty = set()
# Initialize cache using the layers list
for i, layer in enumerate(layers):
self.cache[i] = self.get_layer_device(layer)
def get_layer_device(self, layer):
"""Your existing function"""
try:
return next(layer.parameters()).device
except StopIteration:
return torch.device('cpu')
def get_device(self, layer_idx): # Simplified - no need for model parameter
"""Fast cached lookup"""
if layer_idx in self.dirty:
self.cache[layer_idx] = self.get_layer_device(layers[layer_idx])
self.dirty.remove(layer_idx)
return self.cache[layer_idx]
def mark_moved(self, layer_idx, new_device):
"""Update cache when we move a layer"""
self.cache[layer_idx] = new_device
def safe_move_to_cpu(layer, idx):
"""Move layer back to CPU and clean up GPU memory"""
# Check if layer is already on CPU
if PROFILE: nvtx.range_push(f"CPU_Transfer_L{idx}")
try:
try:
current_device = next(layer.parameters()).device
if current_device.type == 'cpu':
return # Already on CPU
except StopIteration:
# Layer has no parameters
pass
transfer_time = 0
if VERBOSE:
start_time = time.time()
layer_size_mb = get_cached_layer_size_mb(idx)
layer.to(CPU_DEVICE)
add_smart_swapping_to_layer.cleanup_stream = torch.cuda.Stream()
swap_stats['to_cpu'] += 1
if VERBOSE:
end_time = time.time()
transfer_time = end_time - start_time
if transfer_time > 0 and VERBOSE:
speed_mbps = layer_size_mb / transfer_time
# Track current step stats
transfer_stats['current_step_cpu_times'].append(transfer_time)
transfer_stats['current_step_cpu_speeds'].append(speed_mbps)
# if idx % 20 == 0:
# torch.cuda.empty_cache()
device_cache.mark_moved(idx, torch.device('cpu'))
# Only log every 10th layer or if there are issues
# if idx % 10 == 0:
# print(f" Layer {idx} → CPU, memory: {torch.cuda.memory_allocated(0) / 1e9:.1f}GB")
return True
finally:
if PROFILE: nvtx.range_pop()
def safe_move_to_gpu(layer, idx):
"""Move layer to GPU with dtype casting"""
if PROFILE: nvtx.range_push(f"GPU_Transfer_L{idx}")
try:
try:
current_device = device_cache.get_device(idx)
if current_device.type == 'cuda':
return True
if VERBOSE:
start_time = time.time()
layer_size_mb = get_cached_layer_size_mb(idx)
layer.to(GPU_DEVICE, non_blocking=True)
if VERBOSE:
end_time = time.time()
transfer_time = end_time - start_time
if transfer_time > 0 and VERBOSE:
speed_mbps = layer_size_mb / transfer_time
# Track current step stats
transfer_stats['current_step_gpu_times'].append(transfer_time)
transfer_stats['current_step_gpu_speeds'].append(speed_mbps)
event_based_sync("gpu_transfer", idx)
device_cache.mark_moved(idx, torch.device('cuda'))
swap_stats['to_gpu'] += 1
return True
except RuntimeError as e:
if "out of memory" in str(e):
return False
raise e
finally:
if PROFILE: nvtx.range_pop()
# THREADING: Thread-safe GPU operations
def safe_move_to_gpu_threaded(layer, idx):
"""Thread-safe move to GPU"""
with add_smart_swapping_to_layer.gpu_lock:
if device_cache.get_device(idx).type == 'cpu':
return safe_move_to_gpu(layer, idx)
return True
def safe_move_to_cpu_threaded(layer, idx):
"""Thread-safe move to CPU"""
with add_smart_swapping_to_layer.gpu_lock:
if device_cache.get_device(idx).type == 'cuda':
return safe_move_to_cpu(layer, idx)
return True
def stop_background_threading():
"""Stop the background threading system"""
if hasattr(add_smart_swapping_to_layer, 'training_active'):
add_smart_swapping_to_layer.training_active = False
if add_smart_swapping_to_layer.background_thread:
add_smart_swapping_to_layer.background_thread.join(timeout=1.0)
print(" Background threading stopped")
def calculate_needed_layers(layer_idx, is_backward, prefetch):
"""Calculate which layers we need on GPU for current operation"""
needed = set()
needed.add(layer_idx) # Always need current layer
if is_backward:
# Backward pass: need previous layer for activations
if layer_idx - 1 in cpu_swappable_layers and layer_idx - 1 >= 0:
needed.add(layer_idx - 1)
# Add prefetch buffer (going backward)
for i in range(1, prefetch + 1):
prefetch_idx = layer_idx - i - 1
if prefetch_idx in cpu_swappable_layers and prefetch_idx >= 0:
needed.add(prefetch_idx)
else:
# Forward pass: add prefetch buffer (going forward)
for i in range(1, prefetch + 1):
prefetch_idx = layer_idx + i
if prefetch_idx in cpu_swappable_layers and prefetch_idx < len(layers):
needed.add(prefetch_idx)
return needed
def cleanup_excess_layers(keep_layers):
"""Remove layers from GPU that are not in keep_layers set"""
if PROFILE: nvtx.range_push(f"Cleanup_Excess_{len(cpu_swappable_layers - keep_layers)}layers")
try:
if args.batch_move:
# Batch approach (your current code)
layers_to_remove = []
for idx in cpu_swappable_layers:
if (idx < len(layers) and
idx not in keep_layers and
device_cache.get_device(idx).type == 'cuda'):
layers_to_remove.append(idx)
cleaned_count = batch_safe_move_to_cpu(layers_to_remove)
else:
# Individual approach (fallback)
cleaned_count = 0
for idx in cpu_swappable_layers:
if (idx < len(layers) and
idx not in keep_layers and
device_cache.get_device(idx).type == 'cuda'):
safe_move_to_cpu(layers[idx], idx)
cleaned_count += 1
return cleaned_count
finally:
if PROFILE: nvtx.range_pop()
def fetch_missing_layers(needed_layers):
"""Ensure all needed layers are on GPU"""
if PROFILE: nvtx.range_push(f"Fetch_Missing_{len(needed_layers)}layers")
try:
if args.batch_move:
# Batch approach
layers_to_fetch = []
for idx in needed_layers:
if (idx < len(layers) and
idx in cpu_swappable_layers and
device_cache.get_device(idx).type == 'cpu'):
layers_to_fetch.append(idx)
fetched_count = batch_safe_move_to_gpu(layers_to_fetch)
else:
# Individual approach (more stable)
fetched_count = 0
for idx in needed_layers:
if (idx < len(layers) and
idx in cpu_swappable_layers and
device_cache.get_device(idx).type == 'cpu'):
success = safe_move_to_gpu(layers[idx], idx)
if success:
fetched_count += 1
return fetched_count
finally:
if PROFILE: nvtx.range_pop()
def batch_safe_move_to_gpu_packed(layer_indices, threshold_mb=64):
"""Batch move to GPU with selective packing"""
if not layer_indices:
return 0
moved_count = 0
large_layers = []
small_layers = []
# Separate layers by size
for idx in layer_indices:
if (idx < len(layers) and
device_cache.get_device(idx).type == 'cpu'):
layer_size_mb = get_cached_layer_size_mb(idx)
if layer_size_mb > threshold_mb and idx in packed_layers:
large_layers.append(idx)
else:
small_layers.append(idx)
# Handle large layers with packed transfer
if large_layers:
for idx in large_layers:
success = safe_move_to_gpu_packed(layers[idx], idx)
if success:
moved_count += 1
# Handle small layers with direct transfer
if small_layers:
for idx in small_layers:
success = safe_move_to_gpu(layers[idx], idx)
if success:
moved_count += 1
return moved_count
def batch_safe_move_to_cpu_packed(layer_indices, threshold_mb=64):
"""Batch move to CPU with selective packing"""
if not layer_indices:
return 0
moved_count = 0
large_layers = []
small_layers = []
# Separate layers by size
for idx in layer_indices:
if (idx < len(layers) and
device_cache.get_device(idx).type == 'cuda'):
layer_size_mb = get_cached_layer_size_mb(idx)
if layer_size_mb > threshold_mb:
large_layers.append(idx)
else:
small_layers.append(idx)
# Handle large layers with packed transfer
if large_layers:
for idx in large_layers:
success = safe_move_to_cpu_packed(layers[idx], idx)
if success:
moved_count += 1
# Handle small layers with direct transfer
if small_layers:
for idx in small_layers:
success = safe_move_to_cpu(layers[idx], idx)
if success:
moved_count += 1
return moved_count
def cleanup_excess_layers_packed(keep_layers, threshold_mb=64):
"""Remove layers from GPU with selective packing awareness"""
if args.batch_move:
# Collect all layers to remove, then use batch function
layers_to_remove = []
for idx in cpu_swappable_layers:
if (idx < len(layers) and
idx not in keep_layers and
device_cache.get_device(idx).type == 'cuda'):
layers_to_remove.append(idx)
return batch_safe_move_to_cpu_packed(layers_to_remove, threshold_mb)
else:
# Individual processing
moved_count = 0
for idx in cpu_swappable_layers:
if (idx < len(layers) and
idx not in keep_layers and
device_cache.get_device(idx).type == 'cuda'):
layer_size_mb = get_cached_layer_size_mb(idx)
if layer_size_mb > threshold_mb:
success = safe_move_to_cpu_packed(layers[idx], idx)
else:
success = safe_move_to_cpu(layers[idx], idx)
if success:
moved_count += 1
return moved_count
def fetch_missing_layers_packed(needed_layers, threshold_mb=64):
"""Use packed transfers only for large layers, direct for small ones"""
if args.batch_move:
# Use batch function
return batch_safe_move_to_gpu_packed(needed_layers, threshold_mb)
else:
# Individual processing
fetched_count = 0
for idx in needed_layers:
if (idx < len(layers) and
idx in cpu_swappable_layers and
device_cache.get_device(idx).type == 'cpu'):
layer_size_mb = get_cached_layer_size_mb(idx)
if layer_size_mb > threshold_mb and idx in packed_layers:
success = safe_move_to_gpu_packed(layers[idx], idx)
else:
success = safe_move_to_gpu(layers[idx], idx)
if success:
fetched_count += 1
return fetched_count
def background_layer_manager():
"""Background thread that maintains sliding window of layers"""
print("🧵 Background layer manager started")
while add_smart_swapping_to_layer.training_active:
try:
if PROFILE: nvtx.range_push("Background_Manager_Cycle")
current_idx = add_smart_swapping_to_layer.current_layer_idx
is_backward = add_smart_swapping_to_layer.is_backward_pass
needed_layers = calculate_needed_layers(current_idx, is_backward, args.prefetch)
# Collect layers to move instead of moving one by one
layers_to_cpu = []
layers_to_gpu = []
if args.batch_move:
# One in, one out: remove old layers, add new ones
for idx in cpu_swappable_layers:
if idx not in needed_layers and device_cache.get_device(idx).type == 'cuda':
layers_to_cpu.append(idx)
for idx in needed_layers:
if device_cache.get_device(idx).type == 'cpu':
layers_to_gpu.append(idx)
# Batch move with thread safety
if layers_to_cpu or layers_to_gpu:
with add_smart_swapping_to_layer.gpu_lock:
if layers_to_cpu:
batch_safe_move_to_cpu(layers_to_cpu)
if layers_to_gpu:
batch_safe_move_to_gpu(layers_to_gpu)
else:
# One in, one out: remove old layers, add new ones
for idx in cpu_swappable_layers:
if idx not in needed_layers and device_cache.get_device(idx).type == 'cuda':
safe_move_to_cpu_threaded(layers[idx], idx)
for idx in needed_layers:
if device_cache.get_device(idx).type == 'cpu':
safe_move_to_gpu_threaded(layers[idx], idx)
time.sleep(0.000001) #do not touch. very needed for sync
except Exception as e:
print(f" Background thread error: {e}")
time.sleep(0.1)
finally:
if PROFILE: nvtx.range_pop()
def fast_layer_transfer(layer, target_device):
"""Direct parameter movement without .to() overhead"""
for param in layer.parameters():
if param.device != target_device:
param.data = param.data.to(target_device, non_blocking=True)
for buffer in layer.buffers():
if buffer.device != target_device:
buffer.data = buffer.data.to(target_device, non_blocking=True)
def batch_safe_move_to_cpu(layer_indices):
"""Move multiple layers to CPU in batch"""
if not layer_indices:
return 0
if PROFILE: nvtx.range_push(f"Batch_CPU_Transfer_{len(layer_indices)}layers")
try:
moved_count = 0
for idx in layer_indices:
if (idx < len(layers) and
device_cache.get_device(idx).type == 'cuda'):
# Use your existing fast_layer_transfer or layer.to()
# Measure transfer timing
transfer_time = 0
if VERBOSE:
start_time = time.time()
layer_size_mb = get_cached_layer_size_mb(idx)
layers[idx].to(CPU_DEVICE)
if VERBOSE:
end_time = time.time()
transfer_time = end_time - start_time
if transfer_time > 0 and VERBOSE:
speed_mbps = layer_size_mb / transfer_time
# Track current step stats
transfer_stats['current_step_cpu_times'].append(transfer_time)
transfer_stats['current_step_cpu_speeds'].append(speed_mbps)
device_cache.mark_moved(idx, torch.device('cpu'))
swap_stats['to_cpu'] += 1
moved_count += 1
return moved_count
finally:
if PROFILE: nvtx.range_pop()
def batch_safe_move_to_gpu(layer_indices):
"""Batch move to GPU with dtype casting"""
if not layer_indices:
return 0
if PROFILE: nvtx.range_push(f"Batch_GPU_Transfer_{len(layer_indices)}layers")
try:
moved_count = 0
for idx in layer_indices:
if (idx < len(layers) and
device_cache.get_device(idx).type == 'cpu'):
layer = layers[idx]
transfer_time = 0
if VERBOSE:
start_time = time.time()
layer_size_mb = get_cached_layer_size_mb(idx)
layer.to(GPU_DEVICE, non_blocking=True)
if VERBOSE:
end_time = time.time()
transfer_time = end_time - start_time
event_based_sync("gpu_transfer", idx)
if transfer_time > 0 and VERBOSE:
speed_mbps = layer_size_mb / transfer_time
# Track current step stats
transfer_stats['current_step_gpu_times'].append(transfer_time)
transfer_stats['current_step_gpu_speeds'].append(speed_mbps)
device_cache.mark_moved(idx, torch.device('cuda'))
swap_stats['to_gpu'] += 1
moved_count += 1
return moved_count
finally:
if PROFILE: nvtx.range_pop()
# =============================================================================
# PACKED CODE
# =============================================================================
class PackedCPUBlock:
def __init__(self, layer):
self.packed_buffers = {} # One buffer per dtype
self.tensor_specs = []
self.total_elements = 0
self.gpu_blocks = {} # Keep GPU buffers alive when resident
self.gpu_events = {} # CUDA events for synchronization
self.pack_layer(layer)
def pack_layer(self, layer):
"""Pack all layer parameters/buffers into contiguous CPU blocks by dtype"""
dtype_groups = {}
# Build param/buffer maps once (avoid rebuilding in loops)
param_map = layer._parameters
buffer_map = layer._buffers
# Collect parameters by dtype
for name, param in layer.named_parameters(recurse=False):
if param is None:
continue
# Move to CPU first if needed (read-only copy during collection)
src_data = param.detach().to('cpu', copy=True) if param.device.type != 'cpu' else param.data
dtype = param.dtype
if dtype not in dtype_groups:
dtype_groups[dtype] = []
dtype_groups[dtype].append({
'name': name,
'data': src_data.flatten(),
'shape': param.shape,
'is_param': True,
'param_ref': param
})
# Collect buffers by dtype
for name, buffer in layer.named_buffers(recurse=True):
if buffer is None:
continue
# Move to CPU first if needed (read-only copy during collection)
src_data = buffer.detach().to('cpu', copy=True) if buffer.device.type != 'cpu' else buffer.data
dtype = buffer.dtype
if dtype not in dtype_groups:
dtype_groups[dtype] = []
dtype_groups[dtype].append({
'name': name,
'data': src_data.flatten(),
'shape': buffer.shape,
'is_param': False,
'buffer_ref': buffer
})
# Pack each dtype group into contiguous buffers
for dtype, tensors in dtype_groups.items():
if not tensors:
continue
total_size = sum(t['data'].numel() for t in tensors)
packed_buffer = torch.empty(total_size, dtype=dtype)
self.packed_buffers[dtype] = packed_buffer
# Pack data and create specs
offset = 0
for tensor_info in tensors:
data = tensor_info['data']
size = data.numel()
# Copy into packed buffer
packed_buffer[offset:offset + size] = data