-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreference_training_script.py
More file actions
1876 lines (1575 loc) · 73.8 KB
/
reference_training_script.py
File metadata and controls
1876 lines (1575 loc) · 73.8 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 os
import math
import random
import numpy as np
import pyarrow.parquet as pq
SEED = 42
os.environ["PYTHONHASHSEED"] = str(SEED)
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:512'
random.seed(SEED)
np.random.seed(SEED)
import torch
import torch.optim as optim
import polars as pl
from torch.utils.data import DataLoader, TensorDataset, IterableDataset
from torch.amp import autocast, GradScaler
from torch.optim.lr_scheduler import CosineAnnealingLR
# To this:
scaler = GradScaler(
device='cuda',
init_scale=2. ** 10, # Start with higher scale
growth_factor=2.0, # Aggressive growth
backoff_factor=0.5,
growth_interval=2000, # Grow every 2000 iterations
enabled=True
)
torch.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True
torch.use_deterministic_algorithms(False)
# TF32 for Ampere+ GPUs
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
# Memory optimization
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.set_per_process_memory_fraction(0.95)
import time
import wandb
import logging
import pandas as pd
from rich import print
from contextlib import contextmanager
from contexttimer import Timer
from datetime import datetime
# NEW IMPORTS FOR PRODUCER-CONSUMER SYSTEM
import multiprocessing as mp
from multiprocessing import Queue, Process, Event
import threading
from collections import deque
# from hilo_CTG_forecast_multiforecast_v2_larger import (
# EnhancedConvTransformerGenerator as Generator,
# create_generator,
# estimate_model_size
# )
from hilo_CTG_forecast_multiforecast import (
ConvTransformerGenerator as Generator,
create_generator,
estimate_model_size # You'll need to add this function to the v1 file
)
from hilo_evals import (
custom_loss_function,
forecast_focused_loss,
calculate_rmse, calculate_mae, calculate_mape,
calculate_nrmse, calculate_weighted_mae,
calculate_high_low_accuracy, calculate_predictions_within_accuracy_tolerance,
calculate_undershoot_overshoot_ratio
)
from hilo_evals import forecast_focused_loss as custom_loss_function
# Debugs
FLAG_DEBUG_GPU_PROFILING = False
FLAG_DEBUG_PRINT_LOSS = True
FLAG_DEBUG_GRADIENT_FLOW = True
FLAG_DEBUG_TARGET_ALIGNMENT = False
FLAG_LOG_GRADIENTS_WANDB = False
# Control Flags
WANDB_PROJECT_NAME = "hilo-rev3-multitarget"
FLAG_SAVE_MODELS = False
MODEL_NAME = "Hilo_MEGA_CTG_Jun7_4h_20w_MultiTarget"
MODEL_SAVE_THRESHOLD = 0.9169
TOL_TEST_ACC_THRESHOLD = 0.002
# Dataset
BASE_DATA_DIR = 'datasets/unified_2_final'
# Viewing
FLAG_PRINT_TRAINING_PREDICTIONS = False
FLAG_PRINT_VALIDATION_PREDICTIONS = True
FLAG_PRINT_TIMER_BLOCKS = False
FLAG_PRINT_GPU_UTILIZATION = False
FLAG_PRINT_DATA_PRODUCER_DEBUG = False
# Noise Injection
FLAG_NOISE_INPUTS = False
FLAG_NOISE_LABELS = False
NOISE_LEVEL = 0.001
INTERVAL_COUNTS = {
'5m': 571983,
'15m': 190655,
'30m': 95328,
'1h': 47663,
'2h': 23831,
'4h': 11915,
'6h': 7943,
'8h': 5957,
'12h': 3971,
}
# NEW: Multi-target configuration
# Define all available forecast distances (candles forward)
FORECAST_DISTANCES = ['1c', '4c', '6c', '8c', '12c', '24c', '72c']
# Legacy compatibility: if using single forecast_distance, convert to list
def ensure_forecast_distances_list(forecast_distances_or_single):
"""Convert single forecast distance to list for backward compatibility."""
if isinstance(forecast_distances_or_single, (list, tuple)):
return list(forecast_distances_or_single)
else:
return [forecast_distances_or_single]
# Logging
logging.basicConfig(
filename='HILO_TRAINER.log',
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
@contextmanager
def timed_block(name: str):
with Timer() as t:
yield
if FLAG_PRINT_TIMER_BLOCKS:
print(f"{name} took {t.elapsed:.4f} seconds")
'''
Learning Rate Setup:
'''
class GoldilocksZoneScheduler:
"""
Custom scheduler that keeps learning rate in the 'goldilocks zone' for most of training.
Based on your empirical observation that learning happens best between 0.0001-0.00015.
"""
def __init__(self, optimizer, lr_g_init, total_steps, goldilocks_ratio=0.7):
self.optimizer = optimizer
self.total_steps = total_steps
self.goldilocks_ratio = goldilocks_ratio # 70% of training in goldilocks zone
# Your empirically determined goldilocks zone
self.lr_max = lr_g_init # Starting LR
self.goldilocks_high = 0.00022 # Upper goldilocks zone
self.goldilocks_low = 0.00017 # Lower goldilocks zone
self.lr_min = 1e-4 # Final minimum (still useful)
# Calculate phase boundaries
self.ramp_down_steps = int(total_steps * 0.1) # 10% to reach goldilocks zone
self.goldilocks_steps = int(total_steps * goldilocks_ratio) # 70% in goldilocks
self.final_steps = total_steps - self.ramp_down_steps - self.goldilocks_steps # 20% final decay
self.step_count = 0
print(f"🎯 Goldilocks Zone Scheduler:")
print(f" Phase 1 (steps 0-{self.ramp_down_steps:,}): {self.lr_max} → {self.goldilocks_high} (ramp to goldilocks)")
print(f" Phase 2 (steps {self.ramp_down_steps:,}-{self.ramp_down_steps + self.goldilocks_steps:,}): {self.goldilocks_high} → {self.goldilocks_low} (goldilocks zone)")
print(f" Phase 3 (steps {self.ramp_down_steps + self.goldilocks_steps:,}-{total_steps:,}): {self.goldilocks_low} → {self.lr_min} (final polishing)")
def step(self):
if self.step_count < self.ramp_down_steps:
# Phase 1: Quick ramp down to goldilocks zone (10% of training)
progress = self.step_count / self.ramp_down_steps
# Use cosine for smooth transition
cosine_factor = 0.5 * (1 + math.cos(math.pi * progress))
lr = self.goldilocks_high + (self.lr_max - self.goldilocks_high) * cosine_factor
elif self.step_count < self.ramp_down_steps + self.goldilocks_steps:
# Phase 2: Stay in goldilocks zone with gentle decay (70% of training)
goldilocks_progress = (self.step_count - self.ramp_down_steps) / self.goldilocks_steps
# Very gentle decay through goldilocks zone
lr = self.goldilocks_low + (self.goldilocks_high - self.goldilocks_low) * (1 - goldilocks_progress) ** 0.3
else:
# Phase 3: Final decay to minimum (20% of training)
final_progress = (self.step_count - self.ramp_down_steps - self.goldilocks_steps) / self.final_steps
# Smooth final decay
cosine_factor = 0.5 * (1 + math.cos(math.pi * final_progress))
lr = self.lr_min + (self.goldilocks_low - self.lr_min) * cosine_factor
# Update optimizer
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr
self.step_count += 1
return lr
def get_last_lr(self):
"""For compatibility with other schedulers"""
return [param_group['lr'] for param_group in self.optimizer.param_groups]
'''
Data Preparations - Enhanced with Producer-Consumer System
'''
class TimescaleSampler:
def __init__(self, interval_counts, weight_power=1.0, target_boost=None, target_interval=None):
self.intervals = list(interval_counts.keys())
raw_weights = np.array([interval_counts[k] for k in self.intervals], dtype=np.float64)
# Normalize raw weights to form a distribution
norm_weights = raw_weights / raw_weights.sum()
# Apply shaping curve
shaped_weights = norm_weights ** weight_power
# Apply boost for target timescale
if target_boost and target_interval in self.intervals:
idx = self.intervals.index(target_interval)
shaped_weights[idx] *= target_boost
# Final normalization
self.weights = shaped_weights / shaped_weights.sum()
def sample(self, k=1):
return random.choices(self.intervals, weights=self.weights, k=k)
# NEW: Producer function that runs in separate processes - MODIFIED for multi-target
def data_producer_worker(
producer_id,
data_queue,
control_event,
pause_event, # NEW: For pausing during batch size changes
base_dir,
asset_name,
forecast_distances, # CHANGED: Now list of distances instead of single
window_size,
mode,
val_cutoff_date,
validation_timescale,
validation_distance, # NEW: For validation-specific distance
intervals,
weight_power,
target_interval,
target_boost,
batch_size,
seed_offset=0
):
"""
Producer worker that generates batches of data and puts them in the queue.
This runs in a separate process.
MODIFIED: Now handles multiple forecast distances for multi-target learning.
"""
# Set unique seed for this producer
worker_seed = SEED + producer_id + seed_offset
np.random.seed(worker_seed)
random.seed(worker_seed)
# Timing diagnostics
batch_count = 0
total_collect_time = 0
total_stack_time = 0
total_queue_time = 0
try:
# Create the dataset (same logic as before but with multi-target)
dataset = MultiTimescaleParquetDataset(
base_dir=base_dir,
asset_name=asset_name,
forecast_distances=forecast_distances, # CHANGED
window_size=window_size,
mode=mode,
val_cutoff_date=val_cutoff_date,
validation_timescale=validation_timescale,
validation_distance=validation_distance, # NEW
intervals=intervals,
weight_power=weight_power,
target_interval=target_interval,
target_boost=target_boost
)
# Create iterator
data_iter = iter(dataset)
batch_x = []
batch_y = []
while not control_event.is_set():
# Check if we should pause (for batch size changes)
if pause_event.is_set():
# Clear any partial batch when paused
if batch_x or batch_y:
batch_x = []
batch_y = []
time.sleep(0.1)
continue
try:
# TIME: Sample collection
collect_start = time.time()
# Collect batch_size samples with pause checks
batch_complete = True
for _ in range(batch_size):
# Check pause before each sample
if pause_event.is_set():
batch_complete = False
break
x, y = next(data_iter)
batch_x.append(x)
batch_y.append(y)
# Only process if we completed the batch and aren't paused
if not batch_complete or pause_event.is_set():
# Clear partial batch
batch_x = []
batch_y = []
continue
collect_time = time.time() - collect_start
total_collect_time += collect_time
# TIME: Tensor stacking
stack_start = time.time()
batch_x_tensor = torch.stack(batch_x)
batch_y_tensor = torch.stack(batch_y)
stack_time = time.time() - stack_start
total_stack_time += stack_time
# TIME: Queue insertion
queue_start = time.time()
try:
# Check pause one more time before putting in queue
if pause_event.is_set():
batch_x = []
batch_y = []
continue
# Use blocking put initially, then non-blocking
if batch_count < 10: # First 10 batches use blocking to ensure startup
data_queue.put((batch_x_tensor, batch_y_tensor), timeout=5.0)
else:
data_queue.put((batch_x_tensor, batch_y_tensor), timeout=1.0)
queue_time = time.time() - queue_start
total_queue_time += queue_time
except Exception as e:
# If queue is full or we're pausing, just skip this batch
if not pause_event.is_set() and batch_count < 10:
print(f"Producer {producer_id} queue error during startup: {e}")
pass
# Reset batch lists
batch_x = []
batch_y = []
batch_count += 1
# Print timing diagnostics every 50 batches
if batch_count % 50 == 0 and not pause_event.is_set():
avg_collect = total_collect_time / batch_count
avg_stack = total_stack_time / batch_count
avg_queue = total_queue_time / batch_count
if FLAG_PRINT_DATA_PRODUCER_DEBUG:
print(f"Producer {producer_id} (batch_size={batch_size}): "
f"collect={avg_collect:.3f}s, stack={avg_stack:.3f}s, queue={avg_queue:.3f}s per batch")
except StopIteration:
# For validation mode, restart iterator
if mode == 'val':
data_iter = iter(dataset)
else:
# For training, the dataset should be infinite, but just in case
continue
except Exception as e:
print(f"Producer {producer_id} error: {e}")
finally:
print(f"Producer {producer_id} shutting down")
# NEW: Consumer class that manages GPU transfer and provides batches - MODIFIED for multi-target
class AsyncDataLoader:
def __init__(
self,
base_dir,
asset_name,
forecast_distances, # CHANGED: Now list instead of single distance
window_size,
mode,
batch_size,
val_cutoff_date,
validation_timescale=None,
validation_distance=None, # NEW: For validation-specific distance
intervals=None,
weight_power=1.0,
target_interval=None,
target_boost=None,
num_producers=None,
queue_size=None,
gpu_buffer_size=None,
device='cuda'
):
self.device = device
self.batch_size = batch_size
self.mode = mode
# HARD LIMITS - Never exceed these regardless of batch size
MAX_PRODUCERS = 2 # HARD LIMIT: Never more than 2 processes
MAX_QUEUE_SIZE = 20 # INCREASED: Was 10, now 20 for better buffering
MAX_GPU_BUFFER = 8 # INCREASED: Was 3, now 8 for better GPU buffering
# Conservative scaling - much more limited
if num_producers is None:
# CONSERVATIVE: Only 1-2 producers regardless of batch size
self.num_producers = 1 if batch_size <= 16 else 2
else:
self.num_producers = min(num_producers, MAX_PRODUCERS)
if queue_size is None:
# CONSERVATIVE: Small queue regardless of batch size
self.queue_size = min(5 if batch_size <= 16 else 8, MAX_QUEUE_SIZE)
else:
self.queue_size = min(queue_size, MAX_QUEUE_SIZE)
if gpu_buffer_size is None:
# INCREASED: More generous GPU buffer for better performance
self.gpu_buffer_size = min(4 if batch_size <= 16 else 6, MAX_GPU_BUFFER)
else:
self.gpu_buffer_size = min(gpu_buffer_size, MAX_GPU_BUFFER)
print(
f"SAFE AsyncDataLoader: batch_size={batch_size}, producers={self.num_producers}, queue_size={self.queue_size}, gpu_buffer={self.gpu_buffer_size}")
# Estimate memory usage and warn if too high
estimated_ram_gb = self._estimate_memory_usage(forecast_distances)
if estimated_ram_gb > 8.0: # Warning if over 8GB
print(f"⚠️ WARNING: Estimated RAM usage: {estimated_ram_gb:.1f}GB")
print("⚠️ Consider reducing batch size if system becomes unstable")
# Store parameters for batch size changes
self.base_dir = base_dir
self.asset_name = asset_name
self.forecast_distances = forecast_distances # CHANGED
self.window_size = window_size
self.val_cutoff_date = val_cutoff_date
self.validation_timescale = validation_timescale
self.validation_distance = validation_distance # NEW
self.intervals = intervals
self.weight_power = weight_power
self.target_interval = target_interval
self.target_boost = target_boost
# Multiprocessing setup
self.data_queue = Queue(maxsize=self.queue_size)
self.control_event = Event()
self.pause_event = Event()
self.producers = []
# GPU buffer (deque for efficient pop/append)
self.gpu_buffer = deque(maxlen=self.gpu_buffer_size)
self.buffer_lock = threading.Lock()
# Start producer processes
self._start_producers()
# Start GPU transfer thread
self.gpu_thread = threading.Thread(target=self._gpu_transfer_worker, daemon=True)
self.gpu_thread.start()
print(f"AsyncDataLoader started with {self.num_producers} producers, batch_size={batch_size}")
# ADDED: Wait for system to actually be ready before returning
self._wait_for_system_ready()
def _wait_for_system_ready(self):
"""Wait for producers and GPU transfer thread to actually start producing batches."""
print("Waiting for AsyncDataLoader system to be ready...")
start_time = time.time()
# Wait for at least 1 batch to be available in GPU buffer
target_batches = 1
max_wait_time = 60.0 # 60 seconds max
while time.time() - start_time < max_wait_time:
# Check GPU buffer
with self.buffer_lock:
gpu_buffer_size = len(self.gpu_buffer)
if gpu_buffer_size >= target_batches:
elapsed = time.time() - start_time
print(f"✅ AsyncDataLoader ready! {gpu_buffer_size} batches in GPU buffer after {elapsed:.1f}s")
return
# Show progress every 5 seconds
elapsed = time.time() - start_time
if int(elapsed) % 5 == 0 and elapsed >= 5:
try:
cpu_queue_size = self.data_queue.qsize()
except:
cpu_queue_size = "unknown"
print(
f"Still warming up... {elapsed:.0f}s elapsed, GPU buffer: {gpu_buffer_size}, CPU queue: {cpu_queue_size}")
time.sleep(1) # Prevent spam
time.sleep(0.1) # Check every 100ms
# Timeout - but continue anyway
print(f"⚠️ Timeout waiting for system ready, continuing anyway...")
with self.buffer_lock:
final_gpu_size = len(self.gpu_buffer)
try:
final_cpu_size = self.data_queue.qsize()
except:
final_cpu_size = "unknown"
print(f"Final state: GPU buffer: {final_gpu_size}, CPU queue: {final_cpu_size}")
def _warmup_buffer(self):
"""Pre-fill the GPU buffer to avoid cold start delays."""
print("Warming up AsyncDataLoader buffer...")
warmup_start = time.time()
# Wait for buffer to fill to at least 50% capacity
target_fill = max(1, self.gpu_buffer_size // 2)
# First wait for producers to start generating data
print("Waiting for producers to start...")
data_queue_had_items = False
for attempt in range(30): # 3 seconds max to see any queue activity
try:
queue_size = self.data_queue.qsize()
if queue_size > 0:
data_queue_had_items = True
print(f"Producers active - queue has {queue_size} items")
break
except:
pass # qsize() might not be available on all platforms
time.sleep(0.1)
if not data_queue_had_items:
print("⚠️ Warning: No data in queue after 3s")
# Try to get one item directly to test if producers are working
try:
print("Testing direct queue access...")
test_batch = self.data_queue.get(timeout=5.0) # Longer timeout
print("✅ Direct queue access successful - producers are working")
# Put the batch back (approximately)
try:
self.data_queue.put(test_batch, timeout=1.0)
except:
pass
data_queue_had_items = True
except Exception as e:
print(f"❌ Direct queue access failed: {e}")
print("Proceeding without warmup...")
return
# Now wait for GPU buffer to fill
print(f"Waiting for GPU buffer to reach {target_fill} batches...")
buffer_fill_start = time.time()
while len(self.gpu_buffer) < target_fill:
time.sleep(0.05) # Check every 50ms
# Show progress every 2 seconds
elapsed = time.time() - buffer_fill_start
if elapsed > 0 and int(elapsed) % 2 == 0:
with self.buffer_lock:
current_fill = len(self.gpu_buffer)
print(f"Buffer filling: {current_fill}/{target_fill} batches ({elapsed:.1f}s elapsed)")
# Timeout after 15 seconds total
if time.time() - warmup_start > 15.0:
with self.buffer_lock:
current_fill = len(self.gpu_buffer)
print(f"⚠️ Warmup timeout - buffer has {current_fill} batches (target: {target_fill})")
if current_fill > 0:
print("Proceeding with partial buffer...")
break
warmup_time = time.time() - warmup_start
with self.buffer_lock:
final_fill = len(self.gpu_buffer)
print(f"Buffer warmed up in {warmup_time:.2f}s with {final_fill} batches ready")
def _estimate_memory_usage(self, forecast_distances):
"""Estimate memory usage to prevent system crashes. MODIFIED for multi-target."""
# Rough estimates (very conservative)
bytes_per_sample = 100 * 310 * 4 # window_size * features * float32
# CHANGED: Now we have multiple targets (high/low for each distance)
targets_per_sample = len(forecast_distances) * 2 # high + low for each distance
bytes_per_target = targets_per_sample * 4 # float32
total_bytes_per_sample = bytes_per_sample + bytes_per_target
samples_per_batch = self.batch_size
# Memory in queue + GPU buffer
total_batches = self.queue_size + self.gpu_buffer_size
total_samples = total_batches * samples_per_batch
total_bytes = total_samples * total_bytes_per_sample
# Add overhead for processes, etc.
total_bytes_with_overhead = total_bytes * 3 # 3x overhead factor
return total_bytes_with_overhead / (1024 ** 3) # Convert to GB
def _start_producers(self):
"""Start all producer processes."""
for i in range(self.num_producers):
producer = Process(
target=data_producer_worker,
args=(
i, self.data_queue, self.control_event, self.pause_event,
self.base_dir, self.asset_name, self.forecast_distances, self.window_size, # CHANGED
self.mode, self.val_cutoff_date, self.validation_timescale, self.validation_distance, # NEW
self.intervals, self.weight_power, self.target_interval, self.target_boost,
self.batch_size, i * 1000 # seed offset
)
)
producer.start()
self.producers.append(producer)
def _gpu_transfer_worker(self):
"""
Background thread that continuously moves batches from CPU queue to GPU buffer.
Now properly respects pause events during batch size changes.
"""
print(f"GPU transfer thread starting...")
batch_count = 0
consecutive_timeouts = 0
while not self.control_event.is_set():
# Check if we should pause
if self.pause_event.is_set():
time.sleep(0.1)
consecutive_timeouts = 0 # Reset timeout counter during pause
continue
try:
# Get batch from producer queue (with timeout)
cpu_batch = self.data_queue.get(timeout=1.0)
consecutive_timeouts = 0 # Reset on successful get
# Unpack batch
x_cpu, y_cpu = cpu_batch
# Check if we should skip this batch (wrong size during transition)
if x_cpu.shape[0] != self.batch_size:
# Skip batches with wrong size during batch size transitions
print(f"GPU thread: Skipping batch with wrong size {x_cpu.shape[0]} (expected {self.batch_size})")
continue
# Transfer to GPU
x_gpu = x_cpu.to(self.device, non_blocking=True)
y_gpu = y_cpu.to(self.device, non_blocking=True)
# Add to GPU buffer (thread-safe)
with self.buffer_lock:
if len(self.gpu_buffer) < self.gpu_buffer_size:
self.gpu_buffer.append((x_gpu, y_gpu))
batch_count += 1
# Progress every 100 batches
if batch_count % 100 == 0:
print(f"GPU thread: Transferred {batch_count} batches, buffer size: {len(self.gpu_buffer)}")
else:
# Buffer full, wait a bit
time.sleep(0.01)
except Exception as e:
# Only count consecutive timeouts when not paused
if not self.pause_event.is_set():
consecutive_timeouts += 1
# Only log if we're getting many timeouts in a row (not during normal operation)
if consecutive_timeouts > 10:
print(
f"GPU transfer thread: {consecutive_timeouts} consecutive timeouts (this is normal during low activity)")
consecutive_timeouts = 0 # Reset to avoid spam
# Small sleep to prevent tight loop
time.sleep(0.01)
print("GPU transfer thread shutting down")
def change_batch_size(self, new_batch_size):
"""
Efficiently change batch size without recreating the entire loader.
Now with smooth handling like startup - no aggressive timeouts!
"""
if new_batch_size == self.batch_size:
return # No change needed
print(f"\n{'=' * 60}")
print(f"Initiating batch size change: {self.batch_size} → {new_batch_size}")
change_start_time = time.time()
# Step 1: Pause producers and GPU thread
print("Step 1: Pausing producers and GPU thread...")
self.pause_event.set()
# Wait for producers to actually pause (check queue activity)
pause_confirmed = False
pause_wait_start = time.time()
last_queue_size = -1
stable_count = 0
print("Waiting for producers to pause...")
while not pause_confirmed and time.time() - pause_wait_start < 10.0:
try:
current_queue_size = self.data_queue.qsize()
if current_queue_size == last_queue_size:
stable_count += 1
if stable_count >= 5: # Queue size stable for 5 checks
pause_confirmed = True
print(f"✓ Producers paused (queue stable at {current_queue_size} items)")
else:
stable_count = 0
last_queue_size = current_queue_size
except:
# qsize not available, just wait a bit
pass
time.sleep(0.1)
if not pause_confirmed:
print("⚠️ Producers may not be fully paused, continuing anyway...")
# Step 2: Drain CPU queue patiently
print("\nStep 2: Draining CPU queue...")
drained_count = 0
drain_start = time.time()
while True:
try:
# Try to get an item with a short timeout
self.data_queue.get(timeout=0.1)
drained_count += 1
if drained_count % 10 == 0:
print(f" Drained {drained_count} batches...")
except:
# Queue empty or timeout - check if really empty
try:
if self.data_queue.qsize() == 0:
break
except:
# If qsize not available, assume empty after timeout
break
# Safety check - don't drain forever
if time.time() - drain_start > 10.0:
print(f"⚠️ Drain timeout after {drained_count} batches")
break
# Step 3: Clear GPU buffer
print("\nStep 3: Clearing GPU buffer...")
with self.buffer_lock:
gpu_cleared = len(self.gpu_buffer)
self.gpu_buffer.clear()
print(f"✓ Cleared {drained_count} CPU batches and {gpu_cleared} GPU batches")
# Step 4: Update batch size and limits
print("\nStep 4: Updating configuration...")
self.batch_size = new_batch_size
# HARD LIMITS - Never exceed regardless of batch size
MAX_PRODUCERS = 2
MAX_QUEUE_SIZE = 20 # Keep higher limit from your config
MAX_GPU_BUFFER = 8 # Keep higher limit from your config
# Conservative recalculation with hard limits
new_num_producers = min(1 if new_batch_size <= 16 else 2, MAX_PRODUCERS)
new_queue_size = min(10 if new_batch_size <= 16 else 15, MAX_QUEUE_SIZE)
new_gpu_buffer_size = min(4 if new_batch_size <= 16 else 6, MAX_GPU_BUFFER)
self.num_producers = new_num_producers
self.queue_size = new_queue_size
self.gpu_buffer_size = new_gpu_buffer_size
# Estimate memory and warn if too high
estimated_ram_gb = self._estimate_memory_usage(self.forecast_distances)
print(
f"New configuration: producers={self.num_producers}, queue_size={self.queue_size}, gpu_buffer={self.gpu_buffer_size}")
print(f"Estimated RAM usage: {estimated_ram_gb:.1f}GB")
if estimated_ram_gb > 12.0: # Hard limit at 12GB
print(f"❌ ABORT: Estimated RAM usage exceeds 12GB limit!")
print("❌ Keeping current batch size to prevent system crash")
self.pause_event.clear() # Resume with old settings
return
# Resize GPU buffer
self.gpu_buffer = deque(maxlen=self.gpu_buffer_size)
# Create new queue with new size
old_queue = self.data_queue
self.data_queue = Queue(maxsize=self.queue_size)
# Step 5: Gracefully shutdown old producers
print("\nStep 5: Shutting down old producers...")
shutdown_start = time.time()
# First try graceful shutdown
for i, producer in enumerate(self.producers):
if producer.is_alive():
print(f" Waiting for producer {i} (PID: {producer.pid}) to finish...")
producer.join(timeout=5.0) # Give each producer 5 seconds
if producer.is_alive():
print(f" Producer {i} still alive, terminating...")
producer.terminate()
producer.join(timeout=2.0)
if producer.is_alive():
print(f" ⚠️ Producer {i} failed to terminate cleanly")
else:
print(f" ✓ Producer {i} shut down gracefully")
shutdown_time = time.time() - shutdown_start
print(f"Producer shutdown took {shutdown_time:.1f}s")
# Clear the list
self.producers = []
# Step 6: Start new producers
print(f"\nStep 6: Starting new producers with batch_size={new_batch_size}...")
try:
self._start_producers()
print(f"✓ Started {self.num_producers} new producers")
except Exception as e:
print(f"❌ Error starting new producers: {e}")
raise
# Step 7: Clear pause and wait for system to be ready (like startup!)
print("\nStep 7: Resuming system and waiting for readiness...")
self.pause_event.clear()
# Wait for producers to fill queue (similar to startup)
ready_wait_start = time.time()
target_queue_items = min(2, self.queue_size // 2) # Wait for at least 2 items or half queue
print(f"Waiting for at least {target_queue_items} items in queue...")
while time.time() - ready_wait_start < 30.0: # 30 second timeout
try:
queue_size = self.data_queue.qsize()
if queue_size >= target_queue_items:
print(f"✓ Queue has {queue_size} items")
break
except:
pass
# Show progress
if int(time.time() - ready_wait_start) % 5 == 0:
try:
queue_size = self.data_queue.qsize()
print(f" Queue size: {queue_size}, waiting...")
except:
print(f" Waiting for queue to fill...")
time.sleep(0.1)
# Wait for GPU buffer to have at least 1 batch
print("Waiting for GPU buffer to be ready...")
gpu_ready_start = time.time()
while time.time() - gpu_ready_start < 10.0:
with self.buffer_lock:
if len(self.gpu_buffer) > 0:
print(f"✓ GPU buffer has {len(self.gpu_buffer)} batches")
break
time.sleep(0.1)
# Final status
total_time = time.time() - change_start_time
try:
final_queue_size = self.data_queue.qsize()
except:
final_queue_size = "unknown"
with self.buffer_lock:
final_gpu_size = len(self.gpu_buffer)
print(f"\n✅ Batch size change completed in {total_time:.1f}s")
print(f" New batch size: {new_batch_size}")
print(f" CPU queue: {final_queue_size} items")
print(f" GPU buffer: {final_gpu_size} batches")
print(f"{'=' * 60}\n")
def get_batch(self):
"""
Get a batch that's already on GPU. Should be fast since system is pre-warmed.
"""
# Quick check for available batch
with self.buffer_lock:
if self.gpu_buffer:
return self.gpu_buffer.popleft()
# If buffer empty after warmup, something is wrong - but wait a bit
print("⚠️ GPU buffer unexpectedly empty after warmup")
# Wait briefly for GPU transfer thread to catch up
max_wait_time = 2.0 # Short wait since system should be ready
wait_start = time.time()
while time.time() - wait_start < max_wait_time:
with self.buffer_lock:
if self.gpu_buffer:
elapsed = time.time() - wait_start
print(f"✅ Got batch after brief wait {elapsed:.3f}s")
return self.gpu_buffer.popleft()
time.sleep(0.01)
# Final fallback - should be rare after proper warmup
print("Using fallback direct transfer")
try:
cpu_batch = self.data_queue.get(timeout=5.0)
x_cpu, y_cpu = cpu_batch
if x_cpu.shape[0] != self.batch_size:
print(f"Warning: Wrong batch size {x_cpu.shape[0]}, expected {self.batch_size}")
return self.get_batch()
x_gpu = x_cpu.to(self.device, non_blocking=True)
y_gpu = y_cpu.to(self.device, non_blocking=True)
return x_gpu, y_gpu
except Exception as e:
raise RuntimeError(f"Failed to get batch: {e}")
def __iter__(self):
return self
def __next__(self):
return self.get_batch()
def shutdown(self):
"""Clean shutdown of all processes and threads."""
print("Shutting down AsyncDataLoader...")
self.control_event.set()
self.pause_event.set()
# Wait for producers to finish
for producer in self.producers:
producer.join(timeout=2.0)
if producer.is_alive():
producer.terminate()
# Clear the queue
while not self.data_queue.empty():
try:
self.data_queue.get_nowait()
except Exception: # multiprocessing Queue empty
break
def __del__(self):
self.shutdown()
# MODIFIED: Dataset class for multi-target forecasting
class MultiTimescaleParquetDataset(IterableDataset):
def __init__(self, base_dir, asset_name, forecast_distances, window_size,
mode, val_cutoff_date, validation_timescale=None, validation_distance=None,
intervals=None, weight_power=1.0, target_interval=None, target_boost=None):
super().__init__()
self.base_dir = base_dir
self.asset_name = asset_name
self.forecast_distances = forecast_distances # CHANGED: Now list of distances
self.window_size = window_size
self.mode = mode
self.val_cutoff_date = datetime.fromisoformat(val_cutoff_date)
self.validation_timescale = validation_timescale
self.validation_distance = validation_distance # NEW: For validation-specific distance
self.intervals = intervals or ['5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h']
self.weight_power = weight_power
self.target_interval = target_interval
self.target_boost = target_boost
self.sampler = TimescaleSampler(INTERVAL_COUNTS, weight_power, target_boost, target_interval)
# Preload data for all intervals
self.interval_data = {}
for interval in self.intervals:
path = os.path.join(self.base_dir, interval, "unified_training_dataset_softclipped.parquet")
if not os.path.exists(path):