-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuardian_pipeline_github.py
More file actions
2420 lines (2031 loc) · 106 KB
/
Guardian_pipeline_github.py
File metadata and controls
2420 lines (2031 loc) · 106 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
from clearml import PipelineDecorator, Dataset, Task, OutputModel, Model
import os
import pathlib
import logging
import shutil
import sys
import time
import urllib.request
import zipfile
import json
from datetime import datetime
import ssl
import glob
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
# Record start time
start_time = time.time()
# ============================================================================
# COMPONENT 1: DATASET MANAGEMENT FOR GITHUB ACTIONS
# ============================================================================
@PipelineDecorator.component(return_values=["dataset_path"], cache=True, execution_queue="default")
def download_and_setup_dataset(
dataset_name: str,
dataset_project: str,
local_target_path: str
) -> str | None:
"""Download actual dataset from ClearML with proper error handling."""
import pathlib
import os
import shutil
import logging
from clearml import Dataset
def download_real_dataset_from_clearml(dataset_name: str, project_name: str, local_path: str) -> bool:
"""
Check if dataset exists locally and download it if not.
Args:
dataset_name: Name of the dataset in ClearML
project_name: Name of the project in ClearML
local_path: Local path where the dataset should be stored
Returns:
bool: True if dataset exists or was downloaded successfully, False otherwise
"""
print(f"\nChecking for dataset: {dataset_name}")
# Check if dataset exists locally with expected structure
if os.path.exists(local_path):
# Check for action class directories
expected_classes = ["Falling", "No Action", "Waving"]
has_action_structure = any(os.path.exists(os.path.join(local_path, folder)) for folder in expected_classes)
# Also check for train/valid/test structure
train_test_folders = ["train", "valid", "test"]
has_train_test_structure = all(os.path.exists(os.path.join(local_path, folder)) for folder in train_test_folders)
if has_action_structure or has_train_test_structure:
print(f"Dataset {dataset_name} found locally at {local_path}")
return True
else:
print(f"Dataset {dataset_name} exists but missing required structure. Will download from ClearML.")
# Try to get the latest version from ClearML
try:
print(f"Attempting to connect to ClearML...")
dataset = Dataset.get(dataset_name=dataset_name, dataset_project=project_name, only_completed=True)
if dataset is None:
print(f"Dataset {dataset_name} not found in ClearML project {project_name}")
return False
print(f"Downloading dataset {dataset_name} from ClearML...")
# Create the directory if it doesn't exist
os.makedirs(local_path, exist_ok=True)
# Download to a temporary location first
temp_path = dataset.get_local_copy()
# Move contents from temp location to desired location
for item in os.listdir(temp_path):
s = os.path.join(temp_path, item)
d = os.path.join(local_path, item)
if os.path.isdir(s):
if os.path.exists(d):
shutil.rmtree(d)
shutil.move(s, d)
else:
shutil.copy2(s, d)
# Clean up temporary directory
shutil.rmtree(temp_path)
print(f"Dataset downloaded successfully to {local_path}")
return True
except Exception as e:
print(f"Error downloading dataset from ClearML: {str(e)}")
print(f"This could be due to:")
print(f" 1. Dataset '{dataset_name}' doesn't exist in project '{project_name}'")
print(f" 2. ClearML credentials not properly configured")
print(f" 3. Network connectivity issues")
return False
def validate_and_fix_dataset_structure(dataset_path: pathlib.Path, logger):
"""Validate and fix the dataset structure to match expected format."""
logger.info("Validating dataset structure...")
logger.info(f"Dataset path: {dataset_path}")
# First, let's see what's actually in the dataset
if dataset_path.exists():
all_items = list(dataset_path.iterdir())
logger.info(f"Items in dataset directory: {[item.name for item in all_items]}")
# Show directory structure
dirs = [item for item in all_items if item.is_dir()]
files = [item for item in all_items if item.is_file()]
logger.info(f"Directories: {[d.name for d in dirs]}")
logger.info(f"Files: {[f.name for f in files]}")
# Look deeper into subdirectories
for dir_item in dirs:
sub_items = list(dir_item.iterdir())
logger.info(f"Contents of {dir_item.name}: {[item.name for item in sub_items]}")
else:
logger.error(f"Dataset path does not exist: {dataset_path}")
return
expected_classes = ["Falling", "No Action", "Waving"]
# Check if expected directories exist
missing_dirs = []
for class_name in expected_classes:
class_dir = dataset_path / class_name
if not class_dir.exists():
missing_dirs.append(class_name)
if missing_dirs:
logger.warning(f"Missing expected directories: {missing_dirs}")
# Try to find alternative directory names and map them
existing_dirs = [d.name for d in dataset_path.iterdir() if d.is_dir()]
logger.info(f"Existing directories: {existing_dirs}")
# Enhanced mapping for common variations
class_mappings = {
"falling": "Falling",
"fall": "Falling",
"falls": "Falling",
"no_action": "No Action",
"noaction": "No Action",
"no-action": "No Action",
"no action": "No Action",
"normal": "No Action",
"idle": "No Action",
"standing": "No Action",
"waving": "Waving",
"wave": "Waving",
"waves": "Waving",
"hand_wave": "Waving",
"handwave": "Waving",
"hand-wave": "Waving"
}
# Try to rename directories to match expected format
renamed_count = 0
for existing_dir in existing_dirs:
normalized_name = existing_dir.lower().replace(" ", "_").replace("-", "_")
if normalized_name in class_mappings:
old_path = dataset_path / existing_dir
new_path = dataset_path / class_mappings[normalized_name]
if not new_path.exists():
old_path.rename(new_path)
logger.info(f"Renamed '{existing_dir}' to '{class_mappings[normalized_name]}'")
renamed_count += 1
logger.info(f"Renamed {renamed_count} directories")
# Final check - log what we found after renaming
total_keypoint_files = 0
for class_name in expected_classes:
class_dir = dataset_path / class_name
if class_dir.exists():
keypoint_files = list(class_dir.glob("*keypoints.json"))
json_files = list(class_dir.glob("*.json"))
logger.info(f"Found {len(keypoint_files)} keypoints files and {len(json_files)} total JSON files in {class_name}")
total_keypoint_files += len(keypoint_files)
# Show a few example files
if json_files:
logger.info(f"Example files in {class_name}: {[f.name for f in json_files[:3]]}")
else:
logger.warning(f"Directory {class_name} still missing after validation")
logger.info(f"Total keypoints files found: {total_keypoint_files}")
# If we still don't have the expected structure, check for nested structure
if total_keypoint_files == 0:
logger.info("No keypoints files found in expected locations. Checking for nested structures...")
for item in dataset_path.iterdir():
if item.is_dir():
nested_files = list(item.rglob("*.json"))
if nested_files:
logger.info(f"Found {len(nested_files)} JSON files in nested structure under {item.name}")
logger.info(f"Example nested files: {[str(f.relative_to(dataset_path)) for f in nested_files[:3]]}")
try:
comp_logger = logging.getLogger(f"Component.{download_and_setup_dataset.__name__}")
comp_logger.info(f"Setting up dataset: {dataset_name} from project: {dataset_project}")
# Create Path objects
local_path_obj = pathlib.Path(local_target_path)
# Use the robust download function
success = download_real_dataset_from_clearml(
dataset_name=dataset_name,
project_name=dataset_project,
local_path=str(local_path_obj)
)
if not success:
comp_logger.error(f"Failed to download dataset '{dataset_name}' from ClearML")
return None
# Validate and fix dataset structure
validate_and_fix_dataset_structure(local_path_obj, comp_logger)
# Final check - ensure we have some data
total_files = 0
total_json_files = 0
# Check expected structure first
for class_name in ["Falling", "No Action", "Waving"]:
class_dir = local_path_obj / class_name
if class_dir.exists():
keypoint_files = list(class_dir.glob("*keypoints.json"))
json_files = list(class_dir.glob("*.json"))
total_files += len(keypoint_files)
total_json_files += len(json_files)
comp_logger.info(f"Found {len(keypoint_files)} keypoint files and {len(json_files)} JSON files in {class_name}")
# If no files in expected structure, check for any JSON files in the dataset
if total_files == 0 and total_json_files == 0:
comp_logger.info("No files in expected structure. Checking entire dataset for JSON files...")
all_json_files = list(local_path_obj.rglob("*.json"))
total_json_files = len(all_json_files)
comp_logger.info(f"Found {total_json_files} JSON files total in dataset")
if total_json_files > 0:
comp_logger.info("Dataset contains JSON files but not in expected structure. This may still be usable.")
# Show some example files
example_files = [f.relative_to(local_path_obj) for f in all_json_files[:5]]
comp_logger.info(f"Example files: {example_files}")
if total_files == 0 and total_json_files == 0:
comp_logger.error("No dataset files found")
return None
if total_files > 0:
comp_logger.info(f"Dataset validation complete. Found {total_files} keypoints files in expected structure")
else:
comp_logger.info(f"Dataset validation complete. Found {total_json_files} JSON files (structure may need adjustment)")
return str(local_path_obj) if local_path_obj.exists() and local_path_obj.is_dir() else None
except Exception as e:
comp_logger.error(f"Error in download_and_setup_dataset: {e}", exc_info=True)
return None
# ============================================================================
# COMPONENT 2: DATA PREPARATION (SAME AS ORIGINAL)
# ============================================================================
@PipelineDecorator.component(return_values=["dataset_path", "input_size", "num_classes"])
def prepare_data(dataset_path: str):
"""Prepare data and return metadata for training."""
comp_logger = logging.getLogger(f"Component.{prepare_data.__name__}")
try:
from torch.utils.data import DataLoader, Dataset
from sklearn.model_selection import train_test_split
import numpy as np
import json
import os
import torch
# Embedded dataset class
class PoseDataset(Dataset):
def __init__(self, data_dir, action_classes, max_frames=40):
self.data_dir = data_dir
self.action_classes = action_classes
self.max_frames = max_frames
self.data, self.labels = self.load_data()
def load_data(self):
data = []
labels = []
for i, action in enumerate(self.action_classes):
action_dir = os.path.join(self.data_dir, action)
if not os.path.exists(action_dir):
comp_logger.warning(f"Directory not found: {action_dir}")
continue
keypoint_files = [f for f in os.listdir(action_dir) if f.endswith("_keypoints.json")]
comp_logger.info(f"Found {len(keypoint_files)} keypoint files in {action}")
for filename in keypoint_files:
filepath = os.path.join(action_dir, filename)
try:
with open(filepath, 'r') as f:
keypoints_data = json.load(f)
normalized_keypoints = self.process_keypoints(keypoints_data)
if normalized_keypoints is not None:
data.append(normalized_keypoints)
labels.append(i)
except (json.JSONDecodeError, FileNotFoundError) as e:
comp_logger.error(f"Error loading {filepath}: {e}")
continue
comp_logger.info(f"Loaded {len(data)} samples total")
return data, labels
def process_keypoints(self, keypoints_data):
all_frames_keypoints = []
previous_frame = None
alpha = 0.8
for frame_data in keypoints_data:
if not isinstance(frame_data, dict) or 'keypoints' not in frame_data:
continue
frame_keypoints = frame_data['keypoints']
if not isinstance(frame_keypoints, list) or len(frame_keypoints) == 0:
continue
frame_keypoints_np = np.array(frame_keypoints[0]).reshape(-1, 3)
if frame_keypoints_np.shape != (17, 3):
continue
# Filter out keypoints with low confidence
valid_keypoints = frame_keypoints_np[frame_keypoints_np[:, 2] > 0.2]
if valid_keypoints.size == 0:
continue
# Z-Score Normalization
mean_x = np.mean(valid_keypoints[:, 0])
std_x = np.std(valid_keypoints[:, 0]) + 1e-8
mean_y = np.mean(valid_keypoints[:, 1])
std_y = np.std(valid_keypoints[:, 1]) + 1e-8
normalized_frame_keypoints = frame_keypoints_np.copy()
normalized_frame_keypoints[:, 0] = (normalized_frame_keypoints[:, 0] - mean_x) / std_x
normalized_frame_keypoints[:, 1] = (normalized_frame_keypoints[:, 1] - mean_y) / std_y
# Temporal Smoothing using EMA
if previous_frame is not None:
normalized_frame_keypoints[:, 0] = alpha * normalized_frame_keypoints[:, 0] + (1 - alpha) * previous_frame[:, 0]
normalized_frame_keypoints[:, 1] = alpha * normalized_frame_keypoints[:, 1] + (1 - alpha) * previous_frame[:, 1]
previous_frame = normalized_frame_keypoints
# Flatten and remove confidence scores
normalized_frame_keypoints = normalized_frame_keypoints[:, :2].flatten()
all_frames_keypoints.append(normalized_frame_keypoints)
# Padding (or truncating)
if not all_frames_keypoints:
return None
padded_keypoints = np.zeros((self.max_frames, all_frames_keypoints[0].shape[0]))
for i, frame_kps in enumerate(all_frames_keypoints):
if i < self.max_frames:
padded_keypoints[i, :] = frame_kps
return padded_keypoints
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return torch.tensor(self.data[idx], dtype=torch.float32), torch.tensor(self.labels[idx], dtype=torch.long)
action_classes = ["Falling", "No Action", "Waving"]
dataset = PoseDataset(data_dir=dataset_path, action_classes=action_classes)
if not dataset.data or not dataset.labels:
comp_logger.error("No data or labels loaded by PoseDataset")
return None, 0, 0
# Just verify data can be split, but don't return DataLoaders
train_val_data, test_data, train_val_labels, test_labels = train_test_split(
dataset.data, dataset.labels, test_size=0.2, random_state=42,
stratify=dataset.labels if len(set(dataset.labels)) > 1 else None
)
train_data, val_data, train_labels, val_labels = train_test_split(
train_val_data, train_val_labels, test_size=0.25, random_state=42,
stratify=train_val_labels if len(set(train_val_labels)) > 1 else None
)
input_features_per_frame = 34
num_classes_val = len(action_classes)
comp_logger.info(f"Data preparation completed: {len(train_data)} train, {len(val_data)} val, {len(test_data)} test samples")
return dataset_path, input_features_per_frame, num_classes_val
except Exception as e:
comp_logger.error(f"Error in prepare_data: {e}", exc_info=True)
return None, 0, 0
# ============================================================================
# COMPONENT 3: ENHANCED TRAINING FOR GITHUB ACTIONS
# ============================================================================
@PipelineDecorator.component(
name="Train_BiLSTM_GitHub",
return_values=["task_id", "model_id"],
packages=["torch>=1.9", "clearml", "scikit-learn", "numpy", "matplotlib"],
task_type=Task.TaskTypes.training,
cache=False
)
def train_bilstm_github(
dataset_path: str,
input_size: int = 34,
num_classes: int = 3,
base_lr: float = 0.001,
epochs: int = 50, # Full training epochs
hidden_size: int = 256, # Full model size
num_layers: int = 4, # Full model depth
dropout_rate: float = 0.1,
batch_size: int = 32, # Standard batch size
weight_decay: float = 1e-5,
scheduler_patience: int = 5,
scheduler_factor: float = 0.5,
grad_clip_norm: float = 1.0,
noise_factor: float = 0.0,
use_layer_norm: bool = False,
attention_dropout: float = 0.1
):
"""Enhanced BiLSTM training with full feature set for GitHub Actions."""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from clearml import Task, OutputModel
import numpy as np
import json
import os
import matplotlib.pyplot as plt
# Enhanced model classes with full features
class AttentionLayer(nn.Module):
def __init__(self, hidden_size, dropout_rate=0.1):
super(AttentionLayer, self).__init__()
self.attention_weights = nn.Linear(hidden_size * 2, 1)
self.dropout = nn.Dropout(dropout_rate)
def forward(self, lstm_output):
scores = self.attention_weights(self.dropout(lstm_output))
attention_weights = torch.softmax(scores, dim=1)
context_vector = torch.sum(attention_weights * lstm_output, dim=1)
return context_vector, attention_weights.squeeze(-1)
class ActionRecognitionBiLSTMWithAttention(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes,
dropout_rate=0.5, use_layer_norm=False, attention_dropout=0.1):
super(ActionRecognitionBiLSTMWithAttention, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.use_layer_norm = use_layer_norm
self.lstm = nn.LSTM(input_size, hidden_size, num_layers,
batch_first=True, dropout=dropout_rate if num_layers > 1 else 0,
bidirectional=True)
if use_layer_norm:
self.layer_norm = nn.LayerNorm(hidden_size * 2)
self.attention = AttentionLayer(hidden_size, attention_dropout)
self.fc = nn.Linear(hidden_size * 2, num_classes)
self.dropout = nn.Dropout(dropout_rate)
def forward(self, x):
h0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(x.device)
c0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(x.device)
out, _ = self.lstm(x, (h0, c0))
if self.use_layer_norm:
out = self.layer_norm(out)
out = self.dropout(out)
context_vector, attention_weights = self.attention(out)
out = self.fc(context_vector)
return out, attention_weights
class PoseDataset(Dataset):
def __init__(self, data_dir, action_classes, max_frames=40, noise_factor=0.0):
self.data_dir = data_dir
self.action_classes = action_classes
self.max_frames = max_frames
self.noise_factor = noise_factor
self.data, self.labels = self.load_data()
def load_data(self):
data = []
labels = []
for i, action in enumerate(self.action_classes):
action_dir = os.path.join(self.data_dir, action)
if not os.path.exists(action_dir):
continue
for filename in os.listdir(action_dir):
if filename.endswith("_keypoints.json"):
filepath = os.path.join(action_dir, filename)
try:
with open(filepath, 'r') as f:
keypoints_data = json.load(f)
normalized_keypoints = self.process_keypoints(keypoints_data)
if normalized_keypoints is not None:
data.append(normalized_keypoints)
labels.append(i)
except Exception as e:
continue
return data, labels
def process_keypoints(self, keypoints_data):
all_frames_keypoints = []
previous_frame = None
alpha = 0.8
for frame_data in keypoints_data:
if not isinstance(frame_data, dict) or 'keypoints' not in frame_data:
continue
frame_keypoints = frame_data['keypoints']
if not isinstance(frame_keypoints, list) or len(frame_keypoints) == 0:
continue
frame_keypoints_np = np.array(frame_keypoints[0]).reshape(-1, 3)
if frame_keypoints_np.shape != (17, 3):
continue
valid_keypoints = frame_keypoints_np[frame_keypoints_np[:, 2] > 0.2]
if valid_keypoints.size == 0:
continue
mean_x = np.mean(valid_keypoints[:, 0])
std_x = np.std(valid_keypoints[:, 0]) + 1e-8
mean_y = np.mean(valid_keypoints[:, 1])
std_y = np.std(valid_keypoints[:, 1]) + 1e-8
normalized_frame_keypoints = frame_keypoints_np.copy()
normalized_frame_keypoints[:, 0] = (normalized_frame_keypoints[:, 0] - mean_x) / std_x
normalized_frame_keypoints[:, 1] = (normalized_frame_keypoints[:, 1] - mean_y) / std_y
if previous_frame is not None:
normalized_frame_keypoints[:, 0] = alpha * normalized_frame_keypoints[:, 0] + (1 - alpha) * previous_frame[:, 0]
normalized_frame_keypoints[:, 1] = alpha * normalized_frame_keypoints[:, 1] + (1 - alpha) * previous_frame[:, 1]
previous_frame = normalized_frame_keypoints
normalized_frame_keypoints = normalized_frame_keypoints[:, :2].flatten()
all_frames_keypoints.append(normalized_frame_keypoints)
if not all_frames_keypoints:
return None
padded_keypoints = np.zeros((self.max_frames, all_frames_keypoints[0].shape[0]))
for i, frame_kps in enumerate(all_frames_keypoints):
if i < self.max_frames:
padded_keypoints[i, :] = frame_kps
return padded_keypoints
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
data = self.data[idx].copy()
# Add noise augmentation if specified
if self.noise_factor > 0:
noise = np.random.normal(0, self.noise_factor, data.shape)
data = data + noise
return torch.tensor(data, dtype=torch.float32), torch.tensor(self.labels[idx], dtype=torch.long)
# Initialize task
task = Task.current_task()
if task is None:
task = Task.init(
project_name="Guardian_Training",
task_name="Train_BiLSTM_GitHub"
)
logger = task.get_logger()
# Connect hyperparameters
hyperparams = {
'General/base_lr': base_lr,
'General/epochs': epochs,
'General/hidden_size': hidden_size,
'General/num_layers': num_layers,
'General/dropout_rate': dropout_rate,
'General/input_size': input_size,
'General/num_classes': num_classes,
'General/batch_size': batch_size,
'General/weight_decay': weight_decay,
'General/scheduler_patience': scheduler_patience,
'General/scheduler_factor': scheduler_factor,
'General/grad_clip_norm': grad_clip_norm,
'General/noise_factor': noise_factor,
'General/use_layer_norm': use_layer_norm,
'General/attention_dropout': attention_dropout
}
task.connect(hyperparams)
# Recreate DataLoaders from dataset path
action_classes = ["Falling", "No Action", "Waving"]
dataset = PoseDataset(data_dir=dataset_path, action_classes=action_classes, noise_factor=noise_factor)
if not dataset.data or not dataset.labels:
raise RuntimeError("No data or labels loaded by PoseDataset")
# Split data into train, validation, and test sets
train_val_data, test_data, train_val_labels, test_labels = train_test_split(
dataset.data, dataset.labels, test_size=0.2, random_state=42,
stratify=dataset.labels if len(set(dataset.labels)) > 1 else None
)
train_data, val_data, train_labels, val_labels = train_test_split(
train_val_data, train_val_labels, test_size=0.25, random_state=42,
stratify=train_val_labels if len(set(train_val_labels)) > 1 else None
)
def make_torch_dataset_for_loader(split_data, split_labels, use_noise=False):
temp_ds = PoseDataset(data_dir=dataset_path, action_classes=action_classes,
noise_factor=noise_factor if use_noise else 0.0)
temp_ds.data = split_data
temp_ds.labels = split_labels
return temp_ds
# Create data loaders (only apply noise to training data)
train_loader = DataLoader(make_torch_dataset_for_loader(train_data, train_labels, use_noise=True),
batch_size=batch_size, shuffle=True)
val_loader = DataLoader(make_torch_dataset_for_loader(val_data, val_labels, use_noise=False),
batch_size=batch_size, shuffle=False)
# Initialize model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
model = ActionRecognitionBiLSTMWithAttention(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
num_classes=num_classes,
dropout_rate=dropout_rate,
use_layer_norm=use_layer_norm,
attention_dropout=attention_dropout
).to(device)
optimizer = optim.Adam(model.parameters(), lr=base_lr, weight_decay=weight_decay)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(
optimizer, mode='min', factor=scheduler_factor,
patience=scheduler_patience
)
criterion = nn.CrossEntropyLoss()
# Training loop
best_acc = 0.0
best_model_path = "best_bilstm_github.pth"
train_losses, val_losses, val_accuracies = [], [], []
for epoch in range(epochs):
# Training phase
model.train()
total_train_loss = 0.0
correct_train = 0
total_train = 0
for batch_idx, (x, y) in enumerate(train_loader):
x, y = x.to(device), y.to(device)
optimizer.zero_grad()
outputs, _ = model(x)
loss = criterion(outputs, y)
loss.backward()
# Gradient clipping
if grad_clip_norm > 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip_norm)
optimizer.step()
total_train_loss += loss.item()
_, predicted = outputs.max(1)
total_train += y.size(0)
correct_train += predicted.eq(y).sum().item()
avg_train_loss = total_train_loss / len(train_loader)
train_acc = 100.0 * correct_train / total_train if total_train > 0 else 0.0
# Validation phase
model.eval()
total_val_loss = 0.0
all_val_preds, all_val_labels = [], []
with torch.no_grad():
for x, y in val_loader:
x, y = x.to(device), y.to(device)
outputs, _ = model(x)
loss = criterion(outputs, y)
total_val_loss += loss.item()
_, predicted = outputs.max(1)
all_val_preds.extend(predicted.cpu().tolist())
all_val_labels.extend(y.cpu().tolist())
avg_val_loss = total_val_loss / len(val_loader)
val_acc = accuracy_score(all_val_labels, all_val_preds) * 100
# Store metrics
train_losses.append(avg_train_loss)
val_losses.append(avg_val_loss)
val_accuracies.append(val_acc)
# Log metrics
logger.report_scalar("Loss", "Train", avg_train_loss, epoch)
logger.report_scalar("Loss", "Validation", avg_val_loss, epoch)
logger.report_scalar("Accuracy", "Train", train_acc, epoch)
logger.report_scalar("Accuracy", "Validation", val_acc, epoch)
print(f"Epoch {epoch+1}/{epochs}: "
f"Train Loss: {avg_train_loss:.4f}, Train Acc: {train_acc:.2f}%, "
f"Val Loss: {avg_val_loss:.4f}, Val Acc: {val_acc:.2f}%")
# Step scheduler
scheduler.step(avg_val_loss)
# Save best model
if val_acc > best_acc:
best_acc = val_acc
torch.save(model.state_dict(), best_model_path)
print(f"New best model saved with validation accuracy: {val_acc:.2f}%")
# Generate training plot
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(train_losses, label='Training Loss', color='blue')
plt.plot(val_losses, label='Validation Loss', color='red')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.grid(True, alpha=0.3)
plt.subplot(1, 2, 2)
plt.plot(val_accuracies, label='Validation Accuracy', color='green')
plt.title('Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy (%)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('training_metrics_github.png', dpi=150, bbox_inches='tight')
logger.report_matplotlib_figure("Training Metrics", "GitHub", plt.gcf(), 0)
plt.close()
# Save hyperparameters as JSON file
hyperparams_filename = f"hyperparams_{task.id}.json"
standard_hyperparams_filename = "train_hyperparams.json"
hyperparams_filepath = os.path.join(os.getcwd(), hyperparams_filename)
standard_hyperparams_filepath = os.path.join(os.getcwd(), standard_hyperparams_filename)
hyperparams_data = {
"model_id": task.id,
"hyperparameters": {
"base_lr": base_lr,
"epochs": epochs,
"hidden_size": hidden_size,
"num_layers": num_layers,
"dropout_rate": dropout_rate,
"input_size": input_size,
"num_classes": num_classes,
"batch_size": batch_size,
"weight_decay": weight_decay,
"scheduler_patience": scheduler_patience,
"scheduler_factor": scheduler_factor,
"grad_clip_norm": grad_clip_norm,
"noise_factor": noise_factor,
"use_layer_norm": use_layer_norm,
"attention_dropout": attention_dropout
},
"training_results": {
"best_validation_accuracy": best_acc,
"training_epochs": epochs,
"final_train_losses": train_losses[-5:] if len(train_losses) >= 5 else train_losses,
"final_val_losses": val_losses[-5:] if len(val_losses) >= 5 else val_losses,
"final_val_accuracies": val_accuracies[-5:] if len(val_accuracies) >= 5 else val_accuracies
},
"model_info": {
"architecture": "BiLSTM with Enhanced Attention",
"framework": "PyTorch",
"model_type": "BiLSTM_ActionRecognition"
}
}
try:
# Save with task ID (for ClearML tracking)
with open(hyperparams_filepath, 'w') as f:
json.dump(hyperparams_data, f, indent=2)
print(f"💾 Hyperparameters saved to {hyperparams_filepath}")
# Also save with a standard name for easy reference
with open(standard_hyperparams_filepath, 'w') as f:
json.dump(hyperparams_data, f, indent=2)
print(f"💾 Hyperparameters also saved to {standard_hyperparams_filepath}")
# Upload hyperparameters as artifact
task.upload_artifact(
name="training_hyperparameters",
artifact_object=hyperparams_filepath,
metadata={
"description": "Complete training hyperparameters and results",
"best_accuracy": best_acc,
"epochs": epochs
}
)
print(f"📤 Hyperparameters uploaded as ClearML artifact")
# Clean up any other hyperparameter files (optional during training)
try:
import glob
for hp_file in glob.glob("hyperparams_*.json"):
# Skip the current hyperparams file
if hp_file == hyperparams_filename:
continue
os.remove(hp_file)
print(f"🧹 Removed old hyperparameter file: {hp_file}")
except Exception as cleanup_error:
print(f"⚠️ Error during hyperparameter cleanup: {cleanup_error}")
except Exception as hyperparams_error:
print(f"⚠️ Error saving hyperparameters: {hyperparams_error}")
# Publish model
output_model = OutputModel(task=task, name="BiLSTM_ActionRecognition", framework="PyTorch")
output_model.update_weights(weights_filename=best_model_path)
output_model.update_design(config_dict={
"architecture": "BiLSTM with Enhanced Attention",
"input_size": input_size,
"hidden_size": hidden_size,
"num_layers": num_layers,
"num_classes": num_classes,
"dropout_rate": dropout_rate,
"batch_size": batch_size,
"weight_decay": weight_decay,
"scheduler_patience": scheduler_patience,
"scheduler_factor": scheduler_factor,
"grad_clip_norm": grad_clip_norm,
"noise_factor": noise_factor,
"use_layer_norm": use_layer_norm,
"attention_dropout": attention_dropout,
"best_validation_accuracy": best_acc,
"framework": "PyTorch",
"training_epochs": epochs,
"hyperparams_saved": True
})
print(f"Model published with ID: {output_model.id}")
print(f"Best validation accuracy: {best_acc:.2f}%")
return task.id, output_model.id
# ============================================================================
# COMPONENT 4: HYPERPARAMETER OPTIMIZATION
# ============================================================================
@PipelineDecorator.component(
name="BiLSTM_HPO_GitHub",
return_values=["best_task_id", "best_model_id"],
cache=False,
packages=["clearml"]
)
def bilstm_hyperparam_optimizer_github(
base_task_id: str,
dataset_path: str,
input_size: int,
num_classes: int,
total_max_trials: int = 90
):
"""
Hyperparameter optimization for GitHub Actions with 30 trials.
"""
from clearml.automation import HyperParameterOptimizer, RandomSearch
from clearml.automation import DiscreteParameterRange, UniformParameterRange
from clearml import Task, Model
import json
import os
print(f"Starting hyperparameter optimization with {total_max_trials} trials...")
# Initialize HPO task
hpo_task = Task.init(
project_name="Guardian_Training",
task_name="BiLSTM_HPO_GitHub_Controller",
task_type=Task.TaskTypes.optimizer,
reuse_last_task_id=False
)
# Define search space
optimizer = HyperParameterOptimizer(
base_task_id=base_task_id,
hyper_parameters=[
# Learning rate
UniformParameterRange('General/base_lr', min_value=0.0001, max_value=0.01),
# Hidden size
DiscreteParameterRange('General/hidden_size', values=[128, 192, 256, 320, 384, 512]),
# Number of layers
DiscreteParameterRange('General/num_layers', values=[2, 3, 4, 5]),
# Dropout rate
UniformParameterRange('General/dropout_rate', min_value=0.05, max_value=0.5),
# Epochs
DiscreteParameterRange('General/epochs', values=[30, 40, 50, 60]),
# Batch size
DiscreteParameterRange('General/batch_size', values=[16, 24, 32, 48, 64]),
# Weight decay
UniformParameterRange('General/weight_decay', min_value=1e-6, max_value=1e-3),
# Scheduler patience
DiscreteParameterRange('General/scheduler_patience', values=[3, 5, 7, 10]),
# Scheduler factor
UniformParameterRange('General/scheduler_factor', min_value=0.2, max_value=0.8),
# Gradient clipping
UniformParameterRange('General/grad_clip_norm', min_value=0.5, max_value=3.0),
# Noise factor
UniformParameterRange('General/noise_factor', min_value=0.0, max_value=0.05),
# Layer normalization
DiscreteParameterRange('General/use_layer_norm', values=[True, False]),
# Attention dropout
UniformParameterRange('General/attention_dropout', min_value=0.0, max_value=0.2),
],
# Objective metric
objective_metric_title="Accuracy",
objective_metric_series="Validation",
objective_metric_sign="max",
# Execution settings
max_number_of_concurrent_tasks=2, # Reduced for GitHub Actions
optimizer_class=RandomSearch,
save_top_k_tasks_only=5,
# Fixed arguments
base_task_kwargs={
'dataset_path': dataset_path,
'input_size': input_size,
'num_classes': num_classes
},
total_max_jobs=total_max_trials,
)
print(f"Search space configured for {total_max_trials} trials")
print("Starting optimization...")
# Start optimization
optimizer.start_locally()
optimizer.wait()
optimizer.stop()
print("Hyperparameter optimization completed!")
# Get best experiment
top_exps = optimizer.get_top_experiments(top_k=1)
if not top_exps:
raise RuntimeError("No HPO experiments returned by optimizer.")
best_exp = top_exps[0]
best_exp_id = best_exp.id
# Get validation accuracy
metrics = best_exp.get_last_scalar_metrics()