-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_pointcloud.py
More file actions
1774 lines (1541 loc) · 64.6 KB
/
Copy pathtrain_pointcloud.py
File metadata and controls
1774 lines (1541 loc) · 64.6 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
#!/usr/bin/env python3
"""
Point Cloud Training Script for SAFE Architecture.
Trains the SAFE architecture on point cloud data to validate that the
architecture generalizes beyond audio modality.
Usage:
# Classification on ModelNet40
python train_pointcloud.py --config modelnet40 --phase classification
# Captioning on Cap3D
python train_pointcloud.py --config cap3d --phase captioning
"""
from __future__ import annotations
import argparse
import json
import math
import os
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Optional
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.optim import AdamW
from torch.optim.lr_scheduler import LambdaLR
from tqdm import tqdm
try:
import wandb
except ImportError:
wandb = None
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))
from safe.models.safe_pointcloud_model import SAFEPointCloudModel
from safe.models.pointcloud_classifier import PointCloudClassifier
from safe.models.pointcloud_llm_probe import SAFEPointCloudLLMProbe
from safe.data.pointcloud_datasets import (
ModelNet40Dataset,
Cap3DDataset,
ShapeNetPartDataset,
collate_pointcloud_batch,
create_pointcloud_dataloader,
)
from configs.pointcloud_configs import get_pointcloud_config, list_pointcloud_configs
import numpy as np
import torch.nn.functional as F
class LabelSmoothingCrossEntropy(nn.Module):
"""
Cross entropy loss with label smoothing.
Smoothing of 0.1 means 90% confidence on true class,
10% distributed uniformly across other classes.
"""
def __init__(self, smoothing: float = 0.1, reduction: str = 'mean'):
super().__init__()
self.smoothing = smoothing
self.reduction = reduction
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
n_classes = pred.size(-1)
# Create smoothed target distribution
with torch.no_grad():
smooth_target = torch.zeros_like(pred)
smooth_target.fill_(self.smoothing / (n_classes - 1))
smooth_target.scatter_(1, target.unsqueeze(1), 1.0 - self.smoothing)
# Compute cross entropy with soft targets
log_probs = F.log_softmax(pred, dim=-1)
loss = -(smooth_target * log_probs).sum(dim=-1)
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
return loss
def mixup_pointcloud_data(
pointclouds: torch.Tensor,
labels: torch.Tensor,
alpha: float = 0.4,
) -> tuple:
"""
Mixup augmentation for point cloud classification.
Args:
pointclouds: Tensor of shape (B, N, 3) containing point clouds
labels: Tensor of class labels
alpha: Beta distribution parameter (higher = more mixing)
Returns:
mixed_pointclouds: Mixed point cloud tensor
labels_a: Original labels
labels_b: Shuffled labels
lam: Mixing coefficient
"""
if alpha <= 0:
return pointclouds, labels, labels, 1.0
batch_size = pointclouds.size(0)
lam = np.random.beta(alpha, alpha)
# Random permutation for mixing
index = torch.randperm(batch_size, device=pointclouds.device)
# Mix point clouds (simple linear interpolation in 3D space)
mixed_pointclouds = lam * pointclouds + (1 - lam) * pointclouds[index]
labels_a = labels
labels_b = labels[index]
return mixed_pointclouds, labels_a, labels_b, lam
def mixup_criterion(
criterion: nn.Module,
pred: torch.Tensor,
labels_a: torch.Tensor,
labels_b: torch.Tensor,
lam: float,
) -> torch.Tensor:
"""Compute mixup loss as weighted combination of two label losses."""
return lam * criterion(pred, labels_a) + (1 - lam) * criterion(pred, labels_b)
def _grad_summary(params: List[torch.nn.Parameter]) -> Dict[str, float]:
total = 0
with_grad = 0
none_grad = 0
nan_grad = 0
inf_grad = 0
l2_sum = 0.0
max_abs = 0.0
for p in params:
if not getattr(p, "requires_grad", False):
continue
total += 1
g = getattr(p, "grad", None)
if g is None:
none_grad += 1
continue
with_grad += 1
g_detached = g.detach()
if not torch.isfinite(g_detached).all():
nan_grad += int(torch.isnan(g_detached).any().item())
inf_grad += int(torch.isinf(g_detached).any().item())
l2_sum += float(g_detached.float().pow(2).sum().item())
try:
max_abs = max(max_abs, float(g_detached.abs().max().item()))
except Exception:
pass
l2_norm = math.sqrt(l2_sum) if l2_sum > 0 else 0.0
return {
"params_total": float(total),
"params_with_grad": float(with_grad),
"params_none_grad": float(none_grad),
"nan_grad_any": float(nan_grad),
"inf_grad_any": float(inf_grad),
"grad_l2": float(l2_norm),
"grad_max_abs": float(max_abs),
}
def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Train SAFE architecture on point cloud data"
)
# Config
parser.add_argument(
"--config",
type=str,
default="modelnet40",
choices=list_pointcloud_configs(),
help="Configuration name",
)
# Task
parser.add_argument(
"--phase",
type=str,
default="classification",
choices=["classification", "captioning"],
help="Training phase/task",
)
# Data
parser.add_argument(
"--data-path",
type=str,
default="./data",
help="Root data directory",
)
# Training
parser.add_argument("--num-epochs", type=int, default=20)
parser.add_argument("--batch-size", type=int, default=None)
parser.add_argument("--lr", type=float, default=1e-4)
parser.add_argument("--safe-lr", type=float, default=None, help="LLM-probe: LR for projector+fusion params")
parser.add_argument("--head-lr", type=float, default=None, help="LLM-probe: LR for classifier head")
parser.add_argument("--weight-decay", type=float, default=0.01)
parser.add_argument("--head-weight-decay", type=float, default=0.0, help="LLM-probe: weight decay for head")
parser.add_argument("--warmup-steps", type=int, default=100)
parser.add_argument("--lr-scheduler", type=str, default="cosine",
choices=["cosine", "constant", "linear"],
help="LR scheduler type (cosine decays to min_lr, constant keeps LR fixed, linear decays linearly)")
parser.add_argument("--min-lr", type=float, default=1e-6,
help="Minimum learning rate (floor for cosine/linear decay)")
parser.add_argument("--gradient-accumulation", type=int, default=1)
parser.add_argument("--max-grad-norm", type=float, default=1.0)
parser.add_argument("--label-smoothing", type=float, default=0.0,
help="Label smoothing factor (0 = disabled)")
parser.add_argument("--mixup-alpha", type=float, default=0.0,
help="Mixup alpha parameter (0 = disabled)")
# Point cloud augmentation (based on PointNeXt best practices)
parser.add_argument("--no-augment", action="store_true",
help="Disable all point cloud augmentation")
parser.add_argument("--no-aug-rotate", action="store_true",
help="Disable random rotation augmentation")
parser.add_argument("--no-aug-scale", action="store_true",
help="Disable random scaling augmentation")
parser.add_argument("--no-aug-jitter", action="store_true",
help="Disable random jitter augmentation")
parser.add_argument("--no-aug-translate", action="store_true",
help="Disable random translation augmentation")
parser.add_argument("--aug-dropout", action="store_true",
help="Enable random point dropout augmentation (disabled by default)")
# Evaluation
parser.add_argument("--eval-every", type=int, default=1, help="Eval every N epochs")
parser.add_argument("--max-eval-batches", type=int, default=50)
# Output
parser.add_argument("--output-dir", type=str, default="./checkpoints/pointcloud")
parser.add_argument("--save-every", type=int, default=5)
parser.add_argument(
"--resume",
type=str,
default=None,
help="Path to checkpoint to resume from (e.g., best_latest.pt or checkpoint_latest.pt)",
)
# Hardware
parser.add_argument("--device", type=str, default="cuda")
parser.add_argument("--fp16", action="store_true")
parser.add_argument("--num-workers", type=int, default=4)
# Classification mode
parser.add_argument(
"--classification-head",
action="store_true",
help="Use a simple encoder+MLP classification head (non-generative baseline)",
)
parser.add_argument(
"--llm-probe-head",
action="store_true",
help="Use full SAFE (projector+fusion+LLM) with a classification head over pooled LLM hidden states",
)
parser.add_argument(
"--probe-pooling",
type=str,
default="mean",
choices=["last", "mean"],
help="Pooling strategy for LLM probe hidden states",
)
parser.add_argument(
"--probe-head-type",
type=str,
default="linear",
choices=["linear", "mlp"],
help="Head type for LLM probe",
)
parser.add_argument(
"--fusion-mode",
type=str,
default=None,
choices=["residual", "film", "kv_augment"],
help="Override fusion_config.fusion_mode from the config (useful for KV-augment experiments)",
)
parser.add_argument(
"--kv-reg-weight",
type=float,
default=0.1,
help="KV-aug entropy regularization weight to prevent collapse (default: 0.1)",
)
parser.add_argument(
"--ablation-loss-weight",
type=float,
default=0.5,
help="Weight for hinge loss that enforces pointclouds help (KV-aug only, default: 0.5)",
)
parser.add_argument(
"--ablation-loss-margin",
type=float,
default=0.1,
help="Margin for ablation hinge: loss(no-pc) - loss(with-pc) must exceed this value (default: 0.1)",
)
parser.add_argument(
"--ablation-loss-every",
type=int,
default=50,
help="Compute ablation hinge every N steps to save compute (default: 50).",
)
parser.add_argument(
"--fusion-layer-indices",
type=str,
default=None,
help="Comma-separated fusion layer indices (e.g., '12,24,36'). Overrides config.",
)
parser.add_argument(
"--num-pointcloud-tokens",
type=int,
default=None,
help="Number of point cloud tokens to inject (default: from config, typically 8)",
)
parser.add_argument(
"--fusion-injection-point",
type=str,
default=None,
choices=["pre_ffn", "post_layer"],
help="Override fusion injection point (pre_ffn or post_layer)",
)
# Debug
parser.add_argument("--debug", action="store_true")
parser.add_argument(
"--debug-checks",
action="store_true",
help="Extra sanity checks (finite activations, grad flow); more verbose",
)
parser.add_argument(
"--debug-check-every",
type=int,
default=50,
help="How often to run debug checks (in steps)",
)
parser.add_argument(
"--debug-fusion",
action="store_true",
help="Log fusion strength (||delta||/||hidden||) at injection sites",
)
parser.add_argument(
"--debug-fusion-every",
type=int,
default=50,
help="How often fusion strength logs print (in hook calls)",
)
parser.add_argument("--max-train-samples", type=int, default=None)
parser.add_argument(
"--log-every",
type=int,
default=10,
help="Log every N steps when tqdm is disabled (e.g., Slurm logs)",
)
# Logging
parser.add_argument("--wandb", action="store_true", help="Enable wandb logging")
parser.add_argument("--wandb-project", type=str, default="SAFE", help="Wandb project")
parser.add_argument("--wandb-run-name", type=str, default=None, help="Wandb run name")
parser.add_argument("--wandb-entity", type=str, default=None, help="Wandb entity (optional)")
parser.add_argument("--wandb-group", type=str, default=None, help="Wandb group (optional)")
parser.add_argument("--wandb-tags", type=str, default=None, help="Comma-separated wandb tags")
parser.add_argument("--wandb-notes", type=str, default=None, help="Wandb notes (optional)")
# Encoder checkpoint
parser.add_argument(
"--encoder-checkpoint",
type=str,
default=None,
help="Path to pre-trained PointBERT checkpoint",
)
parser.add_argument(
"--unfreeze-encoder-last-n",
type=int,
default=0,
help="Unfreeze last N pointcloud encoder transformer blocks (0 = fully frozen)",
)
parser.add_argument(
"--early-stopping-patience",
type=int,
default=0,
help="Stop training if val accuracy doesn't improve for N epochs (0 = disabled)",
)
return parser.parse_args()
def create_dataset(
args: argparse.Namespace,
config: Dict[str, Any],
split: str,
) -> Any:
"""Create dataset based on config and phase."""
dataset_name = config.get("dataset", "modelnet40")
num_points = config.get("num_points", 1024)
if dataset_name in ["modelnet40", "modelnet40_cls"]:
# Augmentation settings (only for training)
augment = not getattr(args, 'no_augment', False) and split == "train"
dataset = ModelNet40Dataset(
data_path=args.data_path,
split=split,
num_points=num_points,
augment=augment,
aug_rotate=not getattr(args, 'no_aug_rotate', False),
aug_scale=not getattr(args, 'no_aug_scale', False),
aug_jitter=not getattr(args, 'no_aug_jitter', False),
aug_translate=not getattr(args, 'no_aug_translate', False),
aug_dropout=getattr(args, 'aug_dropout', False),
)
elif dataset_name in ["cap3d", "cap3d_captioning"]:
dataset = Cap3DDataset(
data_path=args.data_path,
split=split,
num_points=num_points,
max_samples=args.max_train_samples,
)
elif dataset_name == "shapenet_part":
dataset = ShapeNetPartDataset(
data_path=args.data_path,
split=split,
num_points=num_points,
task="classification" if args.phase == "classification" else "captioning",
)
else:
raise ValueError(f"Unknown dataset: {dataset_name}")
return dataset
def create_model(
config: Dict[str, Any],
device: str,
encoder_checkpoint: Optional[str] = None,
unfreeze_encoder_last_n: int = 0,
) -> SAFEPointCloudModel:
"""Create model from config."""
# Get encoder config and add checkpoint path if provided
encoder_config = dict(config.get("pointcloud_encoder_config", {}))
if encoder_checkpoint:
encoder_config["checkpoint_path"] = encoder_checkpoint
print(f"Using encoder checkpoint: {encoder_checkpoint}")
if int(unfreeze_encoder_last_n) > 0:
encoder_config["unfreeze_last_n_blocks"] = int(unfreeze_encoder_last_n)
# Extract constructor arguments
model_kwargs = {
"llm_model_name": config.get("llm_model_name", "llava-hf/llava-1.5-13b-hf"),
"vision_model_name": config.get("vision_model_name", "openai/clip-vit-large-patch14"),
"pointcloud_encoder_type": config.get("pointcloud_encoder_type", "pointbert"),
"pointcloud_encoder_config": encoder_config,
"projector_type": config.get("projector_type", "standard"),
"num_tokens": config.get("num_tokens", 8),
"projector_config": config.get("projector_config", {}),
"fusion_type": config.get("fusion_type", "multilayer"),
"fusion_layer_indices": config.get("fusion_layer_indices", [12, 24, 36]),
"lora_rank": config.get("lora_rank", 8),
"fusion_config": config.get("fusion_config", {}),
"freeze_base_vl": config.get("freeze_base_vl", True),
"freeze_pointcloud_encoder": config.get("freeze_pointcloud_encoder", True),
"label_smoothing": config.get("label_smoothing", 0.0),
"llm_hidden_size": config.get("llm_hidden_size", 5120),
"pointcloud_embed_dim": config.get("pointcloud_embed_dim", 768),
}
model = SAFEPointCloudModel(**model_kwargs)
model.enable_pointcloud_training()
model = model.to(device)
return model
def create_classifier_model(
config: Dict[str, Any],
device: str,
encoder_checkpoint: Optional[str] = None,
unfreeze_encoder_last_n: int = 0,
) -> PointCloudClassifier:
"""Create a simple point cloud classifier (encoder+MLP)."""
encoder_config = dict(config.get("pointcloud_encoder_config", {}))
if encoder_checkpoint:
encoder_config["checkpoint_path"] = encoder_checkpoint
print(f"Using encoder checkpoint: {encoder_checkpoint}")
if int(unfreeze_encoder_last_n) > 0:
encoder_config["unfreeze_last_n_blocks"] = int(unfreeze_encoder_last_n)
num_classes = int(config.get("num_classes", 40))
model = PointCloudClassifier(
num_classes=num_classes,
encoder_model_name=encoder_config.get("model_name", "pointbert-base"),
encoder_num_points=int(config.get("num_points", encoder_config.get("num_points", 1024))),
encoder_embed_dim=int(config.get("pointcloud_embed_dim", encoder_config.get("embed_dim", 768))),
encoder_checkpoint_path=encoder_config.get("checkpoint_path"),
unfreeze_last_n_blocks=int(unfreeze_encoder_last_n),
hidden_dim=int(config.get("classifier_hidden_dim", 512)),
dropout=float(config.get("classifier_dropout", 0.3)),
).to(device)
return model
def create_llm_probe_model(
config: Dict[str, Any],
device: str,
encoder_checkpoint: Optional[str] = None,
pooling: str = "last",
head_type: str = "linear",
unfreeze_encoder_last_n: int = 0,
) -> SAFEPointCloudLLMProbe:
"""Create a pointcloud LLM probe model (SAFE + classifier head)."""
safe_config = dict(config)
encoder_config = dict(config.get("pointcloud_encoder_config", {}))
if encoder_checkpoint:
encoder_config["checkpoint_path"] = encoder_checkpoint
safe_config["pointcloud_encoder_config"] = encoder_config
print(f"Using encoder checkpoint: {encoder_checkpoint}")
if int(unfreeze_encoder_last_n) > 0:
encoder_config["unfreeze_last_n_blocks"] = int(unfreeze_encoder_last_n)
safe_config["pointcloud_encoder_config"] = encoder_config
num_classes = int(config.get("num_classes", 40))
safe_config.setdefault("freeze_base_vl", True)
safe_config.setdefault("freeze_pointcloud_encoder", True)
model = SAFEPointCloudLLMProbe(
safe_config=safe_config,
num_classes=num_classes,
head_type=head_type,
pooling=pooling,
).to(device)
return model
def train_epoch_classification(
model: SAFEPointCloudModel,
dataloader: DataLoader,
optimizer: torch.optim.Optimizer,
scheduler: Optional[torch.optim.lr_scheduler._LRScheduler],
device: str,
args: argparse.Namespace,
epoch: int,
) -> Dict[str, float]:
"""Train one epoch for classification task."""
model.train()
total_loss = 0.0
correct = 0
total = 0
num_batches = 0
use_tqdm = sys.stdout.isatty()
pbar = tqdm(dataloader, desc=f"Epoch {epoch+1}", disable=not use_tqdm)
for batch_idx, batch in enumerate(pbar):
step_start = time.time()
if batch.get("pointclouds") is None:
continue
pointclouds = batch["pointclouds"].to(device)
labels = batch["labels"].to(device)
questions = batch["questions"]
answers = batch["answers"]
# Tokenize question + answer for training
tokenizer = model.base_vl.tokenizer
texts = [f"Question: {q} Answer: {a}" for q, a in zip(questions, answers)]
encoded = tokenizer(
texts,
padding=True,
truncation=True,
max_length=128,
return_tensors="pt",
)
input_ids = encoded["input_ids"].to(device)
attention_mask = encoded["attention_mask"].to(device)
# Create labels (shift by 1 for causal LM)
lm_labels = input_ids.clone()
lm_labels[lm_labels == tokenizer.pad_token_id] = -100
# Forward
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=lm_labels,
pointcloud=pointclouds,
)
loss = outputs["loss"]
loss = loss / args.gradient_accumulation
if args.debug:
print(f"[DEBUG] Step {batch_idx}: before backward", flush=True)
loss.backward()
if args.debug:
print(f"[DEBUG] Step {batch_idx}: after backward", flush=True)
if (batch_idx + 1) % args.gradient_accumulation == 0:
torch.nn.utils.clip_grad_norm_(
model.get_trainable_parameters(),
args.max_grad_norm,
)
if args.debug:
print(f"[DEBUG] Step {batch_idx}: optimizer step", flush=True)
optimizer.step()
optimizer.zero_grad()
if scheduler is not None:
scheduler.step()
total_loss += loss.item() * args.gradient_accumulation
num_batches += 1
# Simple accuracy tracking (compare generated to target)
# For classification, we just track if the model is learning
total += len(labels)
correct += len(labels) # Placeholder - real eval done separately
avg_loss = total_loss / num_batches
do_log = (batch_idx % max(args.log_every, 1)) == 0
if use_tqdm:
pbar.set_postfix({"loss": avg_loss})
if do_log:
step_ms = (time.time() - step_start) * 1000.0
if not use_tqdm:
print(
f"[TRAIN] epoch={epoch+1} step={batch_idx} loss={avg_loss:.4f} step_ms={step_ms:.0f}",
flush=True,
)
if getattr(args, "wandb", False) and wandb is not None:
global_step = epoch * len(dataloader) + batch_idx
wandb.log(
{
"train/loss": avg_loss,
"train/step_ms": step_ms,
"epoch": epoch + 1,
"lr": optimizer.param_groups[0]["lr"],
},
step=global_step,
)
return {
"loss": total_loss / max(num_batches, 1),
}
def train_epoch_classification_head(
model: PointCloudClassifier,
dataloader: DataLoader,
optimizer: torch.optim.Optimizer,
scheduler: Optional[torch.optim.lr_scheduler._LRScheduler],
device: str,
args: argparse.Namespace,
epoch: int,
) -> Dict[str, float]:
"""Train one epoch for classification using a direct classification head."""
model.train()
total_loss = 0.0
correct = 0
total = 0
num_batches = 0
use_tqdm = sys.stdout.isatty()
pbar = tqdm(dataloader, desc=f"Epoch {epoch+1}", disable=not use_tqdm)
loss_fct = nn.CrossEntropyLoss()
for batch_idx, batch in enumerate(pbar):
step_start = time.time()
if batch.get("pointclouds") is None:
continue
pointclouds = batch["pointclouds"].to(device)
labels = batch["labels"].to(device, dtype=torch.long)
logits = model(pointclouds)
loss = loss_fct(logits, labels) / args.gradient_accumulation
if args.debug:
print(f"[DEBUG] Step {batch_idx}: before backward", flush=True)
loss.backward()
if args.debug:
print(f"[DEBUG] Step {batch_idx}: after backward", flush=True)
if (batch_idx + 1) % args.gradient_accumulation == 0:
torch.nn.utils.clip_grad_norm_(
model.parameters(),
args.max_grad_norm,
)
if args.debug:
print(f"[DEBUG] Step {batch_idx}: optimizer step", flush=True)
optimizer.step()
optimizer.zero_grad()
if scheduler is not None:
scheduler.step()
total_loss += loss.item() * args.gradient_accumulation
num_batches += 1
preds = logits.argmax(dim=-1)
correct += (preds == labels).sum().item()
total += labels.numel()
avg_loss = total_loss / num_batches
avg_acc = correct / max(total, 1)
do_log = (batch_idx % max(args.log_every, 1)) == 0
if use_tqdm:
pbar.set_postfix({"loss": avg_loss, "acc": avg_acc})
if do_log:
step_ms = (time.time() - step_start) * 1000.0
if not use_tqdm:
print(
f"[TRAIN] epoch={epoch+1} step={batch_idx} loss={avg_loss:.4f} acc={avg_acc:.4f} "
f"step_ms={step_ms:.0f}",
flush=True,
)
if getattr(args, "wandb", False) and wandb is not None:
global_step = epoch * len(dataloader) + batch_idx
wandb.log(
{
"train/loss": avg_loss,
"train/accuracy": avg_acc,
"train/step_ms": step_ms,
"epoch": epoch + 1,
"lr": optimizer.param_groups[0]["lr"],
},
step=global_step,
)
return {"loss": total_loss / max(num_batches, 1), "accuracy": correct / max(total, 1)}
def evaluate_classification(
model: SAFEPointCloudModel,
dataloader: DataLoader,
device: str,
args: argparse.Namespace,
) -> Dict[str, float]:
"""Evaluate classification accuracy."""
model.eval()
correct = 0
total = 0
class_correct = {}
class_total = {}
tokenizer = model.base_vl.tokenizer
with torch.no_grad():
for batch_idx, batch in enumerate(tqdm(dataloader, desc="Evaluating")):
if batch_idx >= args.max_eval_batches:
break
pointclouds = batch["pointclouds"].to(device)
true_answers = batch["answers"]
questions = batch["questions"]
# Generate predictions
prompts = [f"Question: {q} Answer:" for q in questions]
encoded = tokenizer(
prompts,
padding=True,
truncation=True,
max_length=64,
return_tensors="pt",
)
input_ids = encoded["input_ids"].to(device)
attention_mask = encoded["attention_mask"].to(device)
outputs = model.generate(
input_ids=input_ids,
attention_mask=attention_mask,
pointcloud=pointclouds,
max_new_tokens=10,
num_beams=1, # Greedy for speed
)
# Decode predictions
predictions = tokenizer.batch_decode(
outputs[:, input_ids.shape[1]:],
skip_special_tokens=True,
)
# Compare
for pred, true in zip(predictions, true_answers):
pred_clean = pred.strip().lower()
true_clean = true.strip().lower()
total += 1
if true_clean not in class_total:
class_total[true_clean] = 0
class_correct[true_clean] = 0
class_total[true_clean] += 1
# Avoid counting empty/short generations as correct:
# in Python, "" in "chair" is True.
if pred_clean and true_clean and (true_clean in pred_clean):
correct += 1
class_correct[true_clean] += 1
accuracy = correct / max(total, 1)
# Per-class accuracy
per_class_acc = {
cls: class_correct[cls] / class_total[cls]
for cls in class_total
}
return {
"accuracy": accuracy,
"correct": correct,
"total": total,
"per_class_accuracy": per_class_acc,
}
def evaluate_classification_head(
model: PointCloudClassifier,
dataloader: DataLoader,
device: str,
args: argparse.Namespace,
) -> Dict[str, float]:
"""Evaluate direct classification head accuracy."""
model.eval()
correct = 0
total = 0
num_classes = None
with torch.no_grad():
for batch_idx, batch in enumerate(tqdm(dataloader, desc="Evaluating")):
if batch_idx >= args.max_eval_batches:
break
pointclouds = batch["pointclouds"].to(device)
labels = batch["labels"].to(device, dtype=torch.long)
logits = model(pointclouds)
if num_classes is None:
num_classes = logits.shape[-1]
preds = logits.argmax(dim=-1)
correct += (preds == labels).sum().item()
total += labels.numel()
return {
"accuracy": correct / max(total, 1),
"correct": correct,
"total": total,
"num_classes": num_classes,
}
def train_epoch_llm_probe_head(
model: SAFEPointCloudLLMProbe,
dataloader: DataLoader,
optimizer: torch.optim.Optimizer,
scheduler: Optional[torch.optim.lr_scheduler._LRScheduler],
device: str,
args: argparse.Namespace,
epoch: int,
) -> Dict[str, float]:
"""Train one epoch for classification using LLM hidden-state probe head."""
model.train()
total_loss = 0.0
correct = 0
total = 0
num_batches = 0
use_tqdm = sys.stdout.isatty()
pbar = tqdm(dataloader, desc=f"Epoch {epoch+1}", disable=not use_tqdm)
# Set up loss function with optional label smoothing
label_smoothing = getattr(args, 'label_smoothing', 0.0)
if label_smoothing > 0:
loss_fct = LabelSmoothingCrossEntropy(smoothing=label_smoothing)
else:
loss_fct = nn.CrossEntropyLoss()
# Check if mixup is enabled
use_mixup = getattr(args, 'mixup_alpha', 0.0) > 0
tokenizer = model.safe_model.base_vl.tokenizer
for batch_idx, batch in enumerate(pbar):
step_start = time.time()
if args.debug_fusion and batch_idx == 0:
try:
model.safe_model.set_fusion_debug(True, log_every=args.debug_fusion_every)
except Exception:
pass
if batch.get("pointclouds") is None:
continue
pointclouds = batch["pointclouds"].to(device)
labels = batch["labels"].to(device, dtype=torch.long)
questions = batch["questions"]
# Apply mixup if enabled
if use_mixup:
pointclouds, labels_a, labels_b, lam = mixup_pointcloud_data(
pointclouds, labels, args.mixup_alpha
)
else:
labels_a = labels
labels_b = labels
lam = 1.0
if args.debug_checks and epoch == 0 and batch_idx == 0:
pc_finite = torch.isfinite(pointclouds).all().item()
pc_min = pointclouds.min().item()
pc_max = pointclouds.max().item()
pc_mean = pointclouds.mean().item()
pc_std = pointclouds.float().std().item()
print(
f"[DEBUG] PC input: shape={tuple(pointclouds.shape)} finite={pc_finite} "
f"min={pc_min:.4f} max={pc_max:.4f} mean={pc_mean:.4f} std={pc_std:.4f}",
flush=True,
)
print(
f"[DEBUG] Labels: shape={tuple(labels.shape)} min={labels.min().item()} max={labels.max().item()}",
flush=True,
)
encoded = tokenizer(
list(questions),
padding=True,
truncation=True,
max_length=64,
return_tensors="pt",
)
input_ids = encoded["input_ids"].to(device)
attention_mask = encoded.get("attention_mask")
if attention_mask is not None:
attention_mask = attention_mask.to(device)
probe_out = model(
input_ids=input_ids,
attention_mask=attention_mask,
pointcloud=pointclouds,
)
logits = probe_out.logits
if args.debug_checks and epoch == 0 and batch_idx == 0:
pooled = probe_out.pooled
print(
f"[DEBUG] Pooled: shape={tuple(pooled.shape)} finite={torch.isfinite(pooled).all().item()} "
f"min={pooled.min().item():.4f} max={pooled.max().item():.4f}",
flush=True,
)
print(
f"[DEBUG] Logits: shape={tuple(logits.shape)} finite={torch.isfinite(logits).all().item()} "
f"min={logits.min().item():.4f} max={logits.max().item():.4f}",
flush=True,
)
# Compute loss (with mixup if enabled)
if use_mixup:
loss = mixup_criterion(loss_fct, logits, labels_a, labels_b, lam) / args.gradient_accumulation
else:
loss = loss_fct(logits, labels) / args.gradient_accumulation
if args.debug:
print(f"[DEBUG] Step {batch_idx}: before backward", flush=True)
loss.backward()
if args.debug:
print(f"[DEBUG] Step {batch_idx}: after backward", flush=True)
if (batch_idx + 1) % args.gradient_accumulation == 0:
total_norm = torch.nn.utils.clip_grad_norm_(model.get_trainable_params(), args.max_grad_norm)
do_checks = args.debug_checks and ((batch_idx % max(args.debug_check_every, 1)) == 0)
if do_checks:
safe_stats = _grad_summary(model.get_safe_params())
head_stats = _grad_summary(model.get_head_params())
print(
f"[DEBUG] GradClip: total_norm={float(total_norm):.4f} "
f"safe_l2={safe_stats['grad_l2']:.4f} safe_max={safe_stats['grad_max_abs']:.4g} "
f"safe_none={int(safe_stats['params_none_grad'])}/{int(safe_stats['params_total'])} "
f"head_l2={head_stats['grad_l2']:.4f} head_max={head_stats['grad_max_abs']:.4g} "
f"head_none={int(head_stats['params_none_grad'])}/{int(head_stats['params_total'])} "
f"nan_any={int(safe_stats['nan_grad_any']+head_stats['nan_grad_any'])} "
f"inf_any={int(safe_stats['inf_grad_any']+head_stats['inf_grad_any'])}",
flush=True,
)
if args.debug:
print(f"[DEBUG] Step {batch_idx}: optimizer step", flush=True)
optimizer.step()
optimizer.zero_grad()
if scheduler is not None: