MesseMMP commited on
Commit
8e84d85
·
1 Parent(s): e608c8f

Publish safetensors weights and align training and inference workflows

Browse files
Files changed (45) hide show
  1. .gitignore +5 -0
  2. README.md +180 -112
  3. backbone/pl_model.py +7 -3
  4. backbone/pl_train.py +47 -17
  5. backbone_weights/{leftBinSyntax_R3D_full_fold00.pt → leftBinSyntax_R3D_full_fold00.safetensors} +2 -2
  6. backbone_weights/{leftBinSyntax_R3D_full_fold01.pt → leftBinSyntax_R3D_full_fold01.safetensors} +2 -2
  7. backbone_weights/{leftBinSyntax_R3D_full_fold02.pt → leftBinSyntax_R3D_full_fold02.safetensors} +2 -2
  8. backbone_weights/{leftBinSyntax_R3D_full_fold03.pt → leftBinSyntax_R3D_full_fold03.safetensors} +2 -2
  9. backbone_weights/leftBinSyntax_R3D_full_fold04.pt +0 -3
  10. backbone_weights/leftBinSyntax_R3D_full_fold04.safetensors +3 -0
  11. backbone_weights/rightBinSyntax_R3D_full_fold00.pt +0 -3
  12. backbone_weights/rightBinSyntax_R3D_full_fold00.safetensors +3 -0
  13. backbone_weights/rightBinSyntax_R3D_full_fold01.pt +0 -3
  14. backbone_weights/rightBinSyntax_R3D_full_fold01.safetensors +3 -0
  15. backbone_weights/rightBinSyntax_R3D_full_fold02.pt +0 -3
  16. backbone_weights/rightBinSyntax_R3D_full_fold02.safetensors +3 -0
  17. backbone_weights/rightBinSyntax_R3D_full_fold03.pt +0 -3
  18. backbone_weights/rightBinSyntax_R3D_full_fold03.safetensors +3 -0
  19. backbone_weights/rightBinSyntax_R3D_full_fold04.pt +0 -3
  20. backbone_weights/rightBinSyntax_R3D_full_fold04.safetensors +3 -0
  21. classifier_weights/r3d_art.safetensors +3 -0
  22. full_model/rnn_model.py +46 -91
  23. full_model/rnn_train.py +55 -26
  24. full_model_weights/LeftBinSyntax_R3D_fold00_lstm_mean_post_best.pt +0 -3
  25. full_model_weights/LeftBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors +3 -0
  26. full_model_weights/LeftBinSyntax_R3D_fold01_lstm_mean_post_best.pt +0 -3
  27. full_model_weights/LeftBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors +3 -0
  28. full_model_weights/LeftBinSyntax_R3D_fold02_lstm_mean_post_best.pt +0 -3
  29. full_model_weights/LeftBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors +3 -0
  30. full_model_weights/LeftBinSyntax_R3D_fold03_lstm_mean_post_best.pt +0 -3
  31. full_model_weights/LeftBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors +3 -0
  32. full_model_weights/LeftBinSyntax_R3D_fold04_lstm_mean_post_best.pt +0 -3
  33. full_model_weights/LeftBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors +3 -0
  34. full_model_weights/RightBinSyntax_R3D_fold00_lstm_mean_post_best.pt +0 -3
  35. full_model_weights/RightBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors +3 -0
  36. full_model_weights/RightBinSyntax_R3D_fold01_lstm_mean_post_best.pt +0 -3
  37. full_model_weights/RightBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors +3 -0
  38. full_model_weights/RightBinSyntax_R3D_fold02_lstm_mean_post_best.pt +0 -3
  39. full_model_weights/RightBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors +3 -0
  40. full_model_weights/RightBinSyntax_R3D_fold03_lstm_mean_post_best.pt +0 -3
  41. full_model_weights/RightBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors +3 -0
  42. full_model_weights/RightBinSyntax_R3D_fold04_lstm_mean_post_best.pt +0 -3
  43. full_model_weights/RightBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors +3 -0
  44. inference/rnn_apply.py +23 -18
  45. requirements.txt +3 -1
.gitignore CHANGED
@@ -142,3 +142,8 @@ runs/
142
  tensorboard/
143
  results/
144
  visualizations/
 
 
 
 
 
 
142
  tensorboard/
143
  results/
144
  visualizations/
145
+
146
+ # Local training artifacts (publish only explicitly selected weights)
147
+ trained_weights/
148
+ *.ckpt
149
+ .DS_Store
README.md CHANGED
@@ -33,8 +33,9 @@ coronary-syntax-prediction/
33
  │ ├── rnn_apply.py # Ensemble inference script
34
  │ ├── metrics_visualization.py # Plotly-based metrics & visualization
35
  │ └── __init__.py
36
- ├── backbone_weights/ # Backbone .pt checkpoints (5 folds × 2 arteries)
37
- ├── full_model_weights/ # Full model .pt checkpoints (5 folds × 2 arteries × variants)
 
38
  ├── scaling_coeffs/ # Calibration coefficients (a, b) per fold
39
  ├── requirements.txt
40
  └── README.md
@@ -43,9 +44,13 @@ coronary-syntax-prediction/
43
  ## Installation
44
 
45
  ```bash
 
 
 
46
  # Clone the repository
47
  git clone https://huggingface.co/MesserMMP/coronary-syntax-prediction
48
  cd coronary-syntax-prediction
 
49
 
50
  # Install dependencies
51
  pip install -r requirements.txt
@@ -57,7 +62,8 @@ Key packages:
57
  - PyTorch 2.0+ with CUDA support
58
  - Lightning 2.x
59
  - torchvision, pytorchvideo
60
- - numpy, scikit-learn, pandas
 
61
  - plotly for visualization
62
  - click for CLI
63
 
@@ -65,105 +71,118 @@ See `requirements.txt` for full list.
65
 
66
  ## Training
67
 
68
- ### Stage 1: Backbone Training (Single-View)
 
 
 
69
 
70
- Train 3D ResNet-18 on single angiographic projections (left/right coronary artery separately):
71
 
72
- ```bash
73
- python backbone/pl_train.py \
74
- -r /path/to/dataset_root \
75
- --fold 0 \
76
- -a right \
77
- --num-classes 2 \
78
- -b 50 \
79
- -f 32 \
80
- -v 256 256 \
81
- --max-epochs 10 \
82
- --num-workers 8 \
83
- --devices 0 \
84
- --precision bf16-mixed \
85
- --logdir ./logs/backbone \
86
- --use-weighted-sampler
87
  ```
88
 
89
- **Parameters:**
90
- - `-r, --dataset-root`: Path to dataset root (default: `.`)
91
- - `--fold`: Fold number (0-4, default: 4)
92
- - `-a, --artery`: `left` or `right` (default: `right`)
93
- - `-nc, --num-classes`: Output units: 2 for (classification, regression) (default: 2)
94
- - `-b, --batch-size`: Batch size (default: 50)
95
- - `-f, --frames-per-clip`: Frames per clip (default: 32)
96
- - `-v, --video-size`: Frame resolution H W (default: 256 256)
97
- - `--max-epochs`: Epochs for full training (default: 10)
98
- - `--num-workers`: DataLoader workers (default: 8)
99
- - `--devices`: GPU device IDs (default: )
100
- - `--precision`: Training precision mode (default: `bf16-mixed`)
101
- - `--logdir`: Log directory (default: `./logs/backbone`)
102
- - `--use-weighted-sampler`: Balance classes by score intervals (flag)
103
- - `--seed`: Random seed (default: 42)
104
 
105
- **Output:** TensorBoard logs + `.ckpt` checkpoints in `--logdir`
 
 
106
 
107
- ### Stage 2: RNN Head Training (Multi-View)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- Train LSTM/GRU/Transformer aggregation head on multi-view studies:
 
 
110
 
111
- ```bash
112
- python full_model/rnn_train.py \
113
- -r /path/to/dataset_root \
114
- --fold 0 \
115
- -a right \
116
- --variant lstm_mean \
117
- --num-classes 2 \
118
- -b 8 \
119
- -f 32 \
120
- -v 256 256 \
121
- --max-epochs 15 \
122
- --num-workers 16 \
123
- --devices 0 \
124
- --precision bf16-mixed \
125
- --logdir ./logs/rnn \
126
- --backbone-pt-dir backbone_weights \
127
- --backbone-from-pt \
128
- --rnn-folds-dir rnn_folds
129
  ```
130
 
131
- **Key Parameters:**
132
- - `--variant`: Head architecture:
133
- - `mean_out`: Mean of projection scores (no RNN)
134
- - `mean`: MLP on mean pooled backbone features
135
- - `lstm_mean`: LSTM with mean pooling of hidden states
136
- - `lstm_last`: LSTM, use last hidden state
137
- - `gru_mean`, `gru_last`: GRU variants
138
- - `bert_mean`, `bert_cls`, `bert_cls2`: Transformer encoder variants
139
- - (default: `lstm_mean`)
140
- - `--backbone-pt-dir`: Path to .pt backbone weights (default: `backbone_weights`)
141
- - `--backbone-from-pt`: Load backbone from `.pt` files (flag, default: True)
142
- - `--backbone-logdir`: Alternative: load backbone from Lightning logs
143
- - `--rnn-folds-dir`: Directory with `rnn_fold{fold}_train.json`, `rnn_fold{fold}_eval.json` (default: `rnn_folds`)
144
- - `--use-weighted-sampler`: Balance by score (flag)
145
- - `--pt-weights-format`: If loading pre-trained head, expect `.pt` instead of `.ckpt` (flag)
146
-
147
- **Output:** Full model checkpoints in `--logdir/{artery}BinSyntax_R3D_fold{fold:02d}_{variant}_post/...`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  ## Inference
150
 
151
  Run ensemble inference on test datasets:
152
 
153
  ```bash
154
- python inference/rnn_apply.py \
155
- -d "test_philips_100.json" "test_siemens_20.json" \
156
- -n "Philips Test" "Siemens Test" \
157
- -p "philips_100" "siemens_20" \
158
  -r /path/to/dataset_root \
159
  --model-dir full_model_weights \
160
  -v 256 256 \
161
  --frames-per-clip 32 \
162
  --num-workers 8 \
163
  --variant lstm_mean \
164
- --pt-weights-format \
165
  --use-scaling \
166
- --scaling-file scaling_coeffs.json \
167
  -e "Ensemble_lstm_mean" \
168
  -m metrics.json
169
  ```
@@ -173,12 +192,13 @@ python inference/rnn_apply.py \
173
  - `-n, --dataset-names`: Display names for each dataset (must match `-d` count)
174
  - `-p, --postfixes`: Suffixes for result files (must match `-d` count)
175
  - `-r, --dataset-root`: Dataset root (default: `.`)
176
- - `--model-dir`: Directory with full model `.pt` weights (default: `full_model_weights`)
177
  - `-v, --video-size`: Frame resolution H W (default: 256 256)
178
  - `--frames-per-clip`: Frames per clip (default: 32)
 
179
  - `--num-workers`: DataLoader workers (default: 8)
180
  - `--variant`: Head model variant (default: `lstm_mean`)
181
- - `--pt-weights-format`: Model weights are `.pt` raw state_dict (flag, default: True)
182
  - `--use-scaling`: Apply post-calibration scaling a*x+b from JSON (flag)
183
  - `--scaling-file`: Calibration coefficients file relative to `--dataset-root`
184
  - `-e, --ensemble-name`: Experiment name for metrics (e.g., "Ensemble_lstm_mean")
@@ -188,7 +208,11 @@ python inference/rnn_apply.py \
188
  **Output:**
189
  - Per-dataset predictions: `results/{postfix}.json`
190
  - Ensemble metrics: `{metrics_file}` with Pearson correlation, balanced accuracy, per-fold statistics
191
- - Plotly HTML plots: `visualizations/{postfix}.html`
 
 
 
 
192
 
193
  ## Dataset
194
 
@@ -408,13 +432,13 @@ Used for training the full RNN model (`full_model/` scripts). Each record repres
408
  | `path` | str | Relative path to DICOM video file |
409
  | `shape` | list[int] | Video dimensions: [T, H, W] |
410
  | `artery` | int | Artery classification: 0 = left, 1 = right |
411
- | `artery_prob` | float | Model confidence (0–1); threshold typically 0.5 for `videos_left`/`videos_right` inclusion |
412
 
413
  ***
414
 
415
  #### Test Set Format (Multi-Expert Annotations)
416
 
417
- Test data (`test_philips_100.json`, `test_siemens_20.json`) follows Format 2 with additional expert annotations:
418
 
419
  ```json
420
  [
@@ -465,49 +489,93 @@ Each DICOM file contains:
465
 
466
  | Set | Files | Size | Equipment | Artery Classification |
467
  |-----|-------|------|-----------|----------------------|
468
- | **Backbone training** | `folds/fold{0-4}_train.json` | ~8,000 videos | Philips | Single video |
469
- | **Backbone validation** | `folds/fold{0-4}_eval.json` | ~1,000 videos | Philips | Single video |
470
- | **RNN training** | `rnn_folds/rnn_fold{0-4}_train.json` | ~2,200 studies | Philips | Multi-view (patient) |
471
- | **RNN validation** | `rnn_folds/rnn_fold{0-4}_eval.json` | ~290 studies | Philips | Multi-view (patient) |
472
- | **Test 1 (Philips)** | `test_philips_100.json` | 100 studies | Philips Allura Clarity | 6 experts |
473
- | **Test 2 (Siemens)** | `test_siemens_20.json` | 20 studies | Siemens AXIOM-Artis | 6 experts |
474
 
475
  **SYNTAX > 0 prevalence:** 39.26% in training data
476
 
477
  ## Results
478
 
479
- ### Baseline Model Performance (5-Fold Ensemble)
 
 
 
480
 
481
- | Metric | Test Set (Philips) | Test Set (Siemens) | Description |
482
- |--------|--------------------|--------------------|------------|
483
- | Pearson r | 0.814 | 0.482 | Raw predictions |
484
- | Balanced Accuracy | 0.687 | 0.566 | Pre-calibration, SYNTAX > 22 |
485
- | **Post-Calibration** | | | |
486
- | Pearson r | 0.816 | 0.482 | After scaling |
487
- | Balanced Accuracy | **0.825** | **0.643** | After scaling, SYNTAX > 22 |
488
 
489
- **Key findings:**
490
- - Strong performance on in-distribution (Philips) test data
491
- - Domain shift effect on out-of-distribution (Siemens) data
492
- - Calibration effective for Philips, limited benefit for Siemens
493
- - Inter-observer variability constrains upper bound on accuracy
494
 
495
  ### Model Architecture
496
 
497
  - **Backbone:** R3D-18 (video ResNet) pre-trained on Kinetics-400
498
- - **Head (default):** LSTM with mean-pooling aggregation + linear regressor
499
  - **Output:** 2 channels (classification logit + log-transformed regression)
500
  - **Loss:** Weighted BCE (classification) + scaled MSE (regression)
501
 
502
  ## Weights & Checkpoints
503
 
504
- Pre-trained weights available in repository:
505
-
506
- - `backbone_weights/`: `.pt` files for 5 folds × 2 arteries
507
- - Example: `RightBinSyntax_R3D_full_fold00.pt`
508
- - `full_model_weights/`: `.pt` files for ensemble variants
509
- - Example: `RightBinSyntax_R3D_fold00_lstm_mean_post_best.pt`
510
- - `scaling_coeffs/`: Calibration parameters (a, b) per fold
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
 
512
  ## Citation
513
 
@@ -538,4 +606,4 @@ For issues, questions, or contributions, please refer to the [HuggingFace reposi
538
 
539
  ***
540
 
541
- **Last updated:** January 2026
 
33
  │ ├── rnn_apply.py # Ensemble inference script
34
  │ ├── metrics_visualization.py # Plotly-based metrics & visualization
35
  │ └── __init__.py
36
+ ├── backbone_weights/ # Backbone safetensors weights (5 folds × 2 arteries)
37
+ ├── full_model_weights/ # Full model safetensors weights (5 folds × 2 arteries × variants)
38
+ ├── classifier_weights/ # R3D-18 artery classifier (safetensors)
39
  ├── scaling_coeffs/ # Calibration coefficients (a, b) per fold
40
  ├── requirements.txt
41
  └── README.md
 
44
  ## Installation
45
 
46
  ```bash
47
+ # Git LFS must be installed to download the model tensors
48
+ git lfs install
49
+
50
  # Clone the repository
51
  git clone https://huggingface.co/MesserMMP/coronary-syntax-prediction
52
  cd coronary-syntax-prediction
53
+ git lfs pull
54
 
55
  # Install dependencies
56
  pip install -r requirements.txt
 
62
  - PyTorch 2.0+ with CUDA support
63
  - Lightning 2.x
64
  - torchvision, pytorchvideo
65
+ - numpy, scikit-learn 1.4+
66
+ - safetensors for tensor-only model weights
67
  - plotly for visualization
68
  - click for CLI
69
 
 
71
 
72
  ## Training
73
 
74
+ Run commands from the repository root with `python -m ...`. JSON paths are
75
+ relative to `--dataset-root`; each DICOM `path` is relative to its JSON's
76
+ folder (absolute DICOM paths also work). Data folders are read-only inputs;
77
+ logs and exported weights go to the explicitly selected output directories.
78
 
79
+ Expected files for fold 00 (no renaming is needed):
80
 
81
+ ```text
82
+ folds/fold00_train.json
83
+ folds/fold00_eval.json
84
+ rnn_folds/rnn_fold00_train.json
85
+ rnn_folds/rnn_fold00_eval.json
 
 
 
 
 
 
 
 
 
 
86
  ```
87
 
88
+ ### Backbone → full model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ This sequence trains one artery and one fold. `&&` starts the full model only
91
+ after backbone training and export succeed. Both stages select the best
92
+ checkpoint by validation RMSE and export tensor-only weights automatically.
93
 
94
+ ```bash
95
+ DATA_ROOT=/mnt/s3-data2/home/mikhailmmp
96
+ OUTPUT_ROOT=/home/mikhailmmp/syntax-training
97
+
98
+ python -m backbone.pl_train \
99
+ -r "$DATA_ROOT" --fold 0 -a right --num-classes 2 \
100
+ -b 50 -f 32 -v 256 256 --pre-epochs 10 --max-epochs 10 \
101
+ --num-workers 8 --devices 0 --precision bf16-mixed \
102
+ --logdir "$OUTPUT_ROOT/logs/backbone" \
103
+ --weights-dir "$OUTPUT_ROOT/weights/backbone" \
104
+ --use-weighted-sampler && \
105
+ python -m full_model.rnn_train \
106
+ -r "$DATA_ROOT" --fold 0 -a right --variant lstm_mean --num-classes 2 \
107
+ -b 8 -f 32 -v 256 256 --pre-epochs 15 --max-epochs 15 \
108
+ --num-workers 8 --devices 0 --precision bf16-mixed \
109
+ --backbone-weights-dir "$OUTPUT_ROOT/weights/backbone" \
110
+ --rnn-folds-dir rnn_folds \
111
+ --logdir "$OUTPUT_ROOT/logs/rnn" \
112
+ --weights-dir "$OUTPUT_ROOT/weights/full_model"
113
+ ```
114
 
115
+ Adjust batch sizes to GPU memory. Use `--devices 1` for GPU1; repeat the option
116
+ for multiple GPUs (`--devices 0 --devices 1`). GPU indices are relative to
117
+ `CUDA_VISIBLE_DEVICES`. With no CUDA device, training uses one CPU process.
118
 
119
+ The backbone first trains its output head, then fine-tunes the network. The
120
+ full model first trains its aggregation head with frozen backbone parameters,
121
+ then fine-tunes the complete model. Transitions load the selected pretraining
122
+ weights from `.safetensors`. OneCycleLR advances on each optimizer step in
123
+ both models. Training requires two outputs (classification and regression).
124
+
125
+ Outputs for this example:
126
+
127
+ ```text
128
+ $OUTPUT_ROOT/weights/backbone/rightBinSyntax_R3D_full_fold00.safetensors
129
+ $OUTPUT_ROOT/weights/full_model/RightBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors
 
 
 
 
 
 
 
130
  ```
131
 
132
+ Repeat for `left` and folds 0–4 to build all ten models required by ensemble
133
+ inference. Newly trained models need their own calibration; the supplied
134
+ scaling coefficients belong to the supplied pretrained ensemble.
135
+
136
+ ### Training options and checkpoints
137
+
138
+ - `--pre-epochs`: head-only epochs; backbone default 10, full-model default
139
+ equals `--max-epochs`.
140
+ - `--max-epochs`: fine-tuning epochs (default 10).
141
+ - `--weights-dir`: export directory; defaults to `./trained_weights/backbone`
142
+ or `./trained_weights/rnn`. Existing files with the same artery/fold name
143
+ are replaced. Published weights are not overwritten by default.
144
+ - `--logdir`: TensorBoard logs, intermediate `.safetensors`, and Lightning
145
+ `.ckpt` files containing optimizer/scheduler state. These local training
146
+ checkpoints are distinct from the tensor-only files intended for publication.
147
+ - `--backbone-weights-dir`: full-model input directory, default
148
+ `backbone_weights`; `--backbone-pt-dir` remains an alias. Safetensors is the
149
+ default input format; no legacy format flag is needed.
150
+ - `--backbone-from-checkpoints --backbone-logdir PATH`: legacy alternative
151
+ selecting the most recently written backbone `.ckpt` from Lightning logs.
152
+ - `--pt-weights-format`: retained for compatibility; safetensors transitions
153
+ detect their format automatically and do not depend on this flag.
154
+ - `--use-weighted-sampler`: sample training records by score-bin weights.
155
+ - `--seed`: random seed, default 42.
156
+
157
+ The existing dataset filtering is retained: backbone validation and both
158
+ full-model splits keep positive artery scores; full-model records also need
159
+ at least one projection for the chosen artery. Each full-model training or
160
+ validation item samples four projections, with replacement. Validation batch
161
+ size is one. At least `2 * batch-size` training records and one validation
162
+ record must remain after filtering.
163
+
164
+ For a brief pipeline check, prepare separate small JSON subsets with the same
165
+ filenames, point `-r` at that temporary directory, and use `-b 1 --pre-epochs 1
166
+ --max-epochs 1`. Keep the original DICOM paths absolute in these subsets.
167
 
168
  ## Inference
169
 
170
  Run ensemble inference on test datasets:
171
 
172
  ```bash
173
+ python -m inference.rnn_apply \
174
+ -d "philips_100.json" -d "siemens_20.json" \
175
+ -n "Philips Test" -n "Siemens Test" \
176
+ -p "philips_100" -p "siemens_20" \
177
  -r /path/to/dataset_root \
178
  --model-dir full_model_weights \
179
  -v 256 256 \
180
  --frames-per-clip 32 \
181
  --num-workers 8 \
182
  --variant lstm_mean \
183
+ --device cuda:0 \
184
  --use-scaling \
185
+ --scaling-file "$PWD/scaling_coeffs/scaling_coeffs.json" \
186
  -e "Ensemble_lstm_mean" \
187
  -m metrics.json
188
  ```
 
192
  - `-n, --dataset-names`: Display names for each dataset (must match `-d` count)
193
  - `-p, --postfixes`: Suffixes for result files (must match `-d` count)
194
  - `-r, --dataset-root`: Dataset root (default: `.`)
195
+ - `--model-dir`: Directory with full model `.safetensors` weights (default: `full_model_weights`)
196
  - `-v, --video-size`: Frame resolution H W (default: 256 256)
197
  - `--frames-per-clip`: Frames per clip (default: 32)
198
+ - `--device`: `cuda:0`, `cuda:1` or `cpu`; defaults to `cuda:0` if available, otherwise CPU.
199
  - `--num-workers`: DataLoader workers (default: 8)
200
  - `--variant`: Head model variant (default: `lstm_mean`)
201
+ - `--pt-weights-format`: Legacy `.pt` / `.ckpt` format flag; `.safetensors` files are detected automatically.
202
  - `--use-scaling`: Apply post-calibration scaling a*x+b from JSON (flag)
203
  - `--scaling-file`: Calibration coefficients file relative to `--dataset-root`
204
  - `-e, --ensemble-name`: Experiment name for metrics (e.g., "Ensemble_lstm_mean")
 
208
  **Output:**
209
  - Per-dataset predictions: `results/{postfix}.json`
210
  - Ensemble metrics: `{metrics_file}` with Pearson correlation, balanced accuracy, per-fold statistics
211
+ - Plotly HTML plots: `visualizations/Ensemble.html` or `Ensemble_scaled.html`
212
+
213
+ Existing `results/{postfix}.json` files are reused. Use a new postfix or remove
214
+ the old result file when changing weights, data or preprocessing. All five
215
+ folds for both arteries must be present; missing weights raise an error.
216
 
217
  ## Dataset
218
 
 
432
  | `path` | str | Relative path to DICOM video file |
433
  | `shape` | list[int] | Video dimensions: [T, H, W] |
434
  | `artery` | int | Artery classification: 0 = left, 1 = right |
435
+ | `artery_prob` | float | Right-artery probability (0–1); high-confidence grouping: left <= 0.1, right >= 0.9 |
436
 
437
  ***
438
 
439
  #### Test Set Format (Multi-Expert Annotations)
440
 
441
+ Test data (`philips_100.json`, `siemens_20.json`) follows Format 2 with additional expert annotations:
442
 
443
  ```json
444
  [
 
489
 
490
  | Set | Files | Size | Equipment | Artery Classification |
491
  |-----|-------|------|-----------|----------------------|
492
+ | **Backbone training** | `folds/fold{00-04}_train.json` | Varies by fold | Philips | Single video |
493
+ | **Backbone validation** | `folds/fold{00-04}_eval.json` | Varies by fold | Philips | Single video |
494
+ | **RNN training** | `rnn_folds/rnn_fold{00-04}_train.json` | Varies by fold | Philips | Multi-view (patient) |
495
+ | **RNN validation** | `rnn_folds/rnn_fold{00-04}_eval.json` | Varies by fold | Philips | Multi-view (patient) |
496
+ | **Test 1 (Philips)** | `philips_100.json` | 100 studies | Philips Allura Clarity | 6 experts |
497
+ | **Test 2 (Siemens)** | `siemens_20.json` | 20 studies | Siemens AXIOM-Artis | 6 experts |
498
 
499
  **SYNTAX > 0 prevalence:** 39.26% in training data
500
 
501
  ## Results
502
 
503
+ ### Verified inference (5-fold ensemble)
504
+
505
+ The supplied `lstm_mean` safetensors ensemble was run on October 15, 2026
506
+ with 32-frame, 256×256 clips and the supplied scaling coefficients:
507
 
508
+ | Dataset | Studies | Pearson r | Balanced accuracy (SYNTAX >= 22) |
509
+ |---------|---------|-----------|---------------------------------|
510
+ | Philips (`philips_100.json`) | 100 | 0.8144 | 0.8182 |
511
+ | Siemens (`siemens_20.json`) | 20 | 0.3849 | 0.6429 |
 
 
 
512
 
513
+ These are measured results for these test files and settings, not metrics
514
+ from the short training smoke test. Environment: NVIDIA A100, PyTorch
515
+ 2.14.1+cu130, torchvision 0.29.1+cu130. Dataset composition and preprocessing
516
+ must match when comparing runs.
 
517
 
518
  ### Model Architecture
519
 
520
  - **Backbone:** R3D-18 (video ResNet) pre-trained on Kinetics-400
521
+ - **Head (default):** LSTM with a two-output projection and mean pooling
522
  - **Output:** 2 channels (classification logit + log-transformed regression)
523
  - **Loss:** Weighted BCE (classification) + scaled MSE (regression)
524
 
525
  ## Weights & Checkpoints
526
 
527
+ The repository includes 21 tensor-only `.safetensors` files:
528
+
529
+ - `backbone_weights/`: five folds for each artery, e.g.
530
+ `rightBinSyntax_R3D_full_fold00.safetensors` (lowercase artery name).
531
+ These backbones have a one-output head. Use `num_classes=1` to load a
532
+ standalone backbone; the current two-output training loss expects a different
533
+ head. The RNN loader discards this head for aggregation variants and strictly
534
+ validates all feature-extractor weights. `mean_out` requires a two-output
535
+ backbone; use a newly trained backbone for that variant.
536
+ - `full_model_weights/`: five folds for each artery, e.g.
537
+ `RightBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors`.
538
+ The supplied full-model variant is `lstm_mean`.
539
+ - `classifier_weights/r3d_art.safetensors`: left/right artery classifier.
540
+ - `scaling_coeffs/`: calibration parameters (a, b) per fold.
541
+
542
+ Safetensors files load directly as tensor dictionaries on CPU. Existing `.pt`
543
+ and Lightning `.ckpt` loading remains available for trusted legacy checkpoints.
544
+ Use `--backbone-weights-dir` for published or newly trained `.safetensors`
545
+ backbones. The old `--backbone-pt-dir` and `--backbone-from-pt` names remain
546
+ available for compatibility. `--pt-weights-format`
547
+ only affects legacy files; safetensors is detected from the filename.
548
+
549
+ ### Artery classifier
550
+
551
+ `classifier_weights/r3d_art.safetensors` contains a torchvision R3D-18 classifier
552
+ with a single-output `Linear(512, 1)` head. Apply sigmoid to its output to obtain
553
+ the probability of the **right coronary artery**: class `0` is left, class `1`
554
+ is right. The binary decision uses a 0.5 threshold (the reference uses
555
+ `round(p)`, so exactly 0.5 maps to class 0). For high-confidence grouping,
556
+ probabilities `<= 0.1` indicate left and `>= 0.9` indicate right; intermediate
557
+ values form the uncertain group.
558
+
559
+ The input is a float tensor `(batch, 3, frames, 224, 224)`. Grayscale video is
560
+ replicated into three channels, scaled from uint8 to `[0, 1]`, resized to
561
+ 224×224, and normalized using ImageNet mean `[0.485, 0.456, 0.406]` and standard
562
+ deviation `[0.229, 0.224, 0.225]`. The classifier accepts a variable number of
563
+ frames. Load its tensor-only weights as follows:
564
+
565
+ ```python
566
+ import torch
567
+ from torchvision.models.video import r3d_18
568
+ from safetensors.torch import load_file
569
+
570
+ model = r3d_18(weights=None)
571
+ model.fc = torch.nn.Linear(model.fc.in_features, 1)
572
+ model.load_state_dict(
573
+ load_file("classifier_weights/r3d_art.safetensors", device="cpu"),
574
+ strict=True,
575
+ )
576
+ model.eval()
577
+ # For a normalized video batch x: p_right = torch.sigmoid(model(x))
578
+ ```
579
 
580
  ## Citation
581
 
 
606
 
607
  ***
608
 
609
+ **Last updated:** October 15, 2026
backbone/pl_model.py CHANGED
@@ -2,6 +2,7 @@ from typing import Any, Optional
2
 
3
  import numpy as np
4
  import torch
 
5
  from torch import nn, optim
6
  import lightning.pytorch as pl
7
  import torchvision.models.video as tvmv
@@ -69,11 +70,14 @@ class SyntaxLightningModule(pl.LightningModule):
69
  """
70
  Load backbone weights from either:
71
  - a Lightning checkpoint (dict with a 'state_dict' key)
72
- - or a raw state_dict saved via model.state_dict() (.pt/.pth)
73
 
74
  Prints the source type and key statistics.
75
  """
76
- obj = torch.load(weight_path, map_location="cpu", weights_only=False)
 
 
 
77
 
78
  if isinstance(obj, dict) and "state_dict" in obj:
79
  state_dict = obj["state_dict"]
@@ -83,7 +87,7 @@ class SyntaxLightningModule(pl.LightningModule):
83
  state_dict = obj
84
  src_type = "raw_state_dict"
85
 
86
- incompatible = self.model.load_state_dict(state_dict, strict=False)
87
 
88
  loaded_keys = [k for k in state_dict.keys() if k not in incompatible.missing_keys]
89
  print(
 
2
 
3
  import numpy as np
4
  import torch
5
+ from safetensors.torch import load_file
6
  from torch import nn, optim
7
  import lightning.pytorch as pl
8
  import torchvision.models.video as tvmv
 
70
  """
71
  Load backbone weights from either:
72
  - a Lightning checkpoint (dict with a 'state_dict' key)
73
+ - or safetensors / a raw state_dict saved via model.state_dict() (.pt/.pth)
74
 
75
  Prints the source type and key statistics.
76
  """
77
+ if str(weight_path).endswith(".safetensors"):
78
+ obj = load_file(str(weight_path), device="cpu")
79
+ else:
80
+ obj = torch.load(weight_path, map_location="cpu", weights_only=False)
81
 
82
  if isinstance(obj, dict) and "state_dict" in obj:
83
  state_dict = obj["state_dict"]
 
87
  state_dict = obj
88
  src_type = "raw_state_dict"
89
 
90
+ incompatible = self.model.load_state_dict(state_dict, strict=True)
91
 
92
  loaded_keys = [k for k in state_dict.keys() if k not in incompatible.missing_keys]
93
  print(
backbone/pl_train.py CHANGED
@@ -4,6 +4,7 @@ import warnings
4
  import click
5
  import lightning.pytorch as pl
6
  import torch
 
7
  from lightning.pytorch.callbacks import LearningRateMonitor, ModelCheckpoint
8
  from lightning.pytorch.loggers import TensorBoardLogger
9
  from pytorchvideo.transforms import Normalize, Permute, RandAugment
@@ -68,7 +69,7 @@ def make_dataloader(dataset, batch_size: int, num_workers: int, use_weighted_sam
68
  shuffle = False
69
  else:
70
  sampler = None
71
- shuffle = True
72
 
73
  return DataLoader(
74
  dataset,
@@ -76,7 +77,7 @@ def make_dataloader(dataset, batch_size: int, num_workers: int, use_weighted_sam
76
  num_workers=num_workers,
77
  sampler=sampler,
78
  shuffle=shuffle,
79
- drop_last=True,
80
  pin_memory=True,
81
  persistent_workers=(num_workers > 0),
82
  )
@@ -116,7 +117,7 @@ def make_callbacks(phase: str):
116
  return [lr_monitor, checkpoint]
117
 
118
 
119
- def make_trainer(max_epochs: int, logdir: str, logger_name: str, devices: list[int], precision: str):
120
  """
121
  Build a Trainer with the requested settings:
122
  - logdir: TensorBoard log directory
@@ -131,15 +132,30 @@ def make_trainer(max_epochs: int, logdir: str, logger_name: str, devices: list[i
131
  return pl.Trainer(
132
  max_epochs=max_epochs,
133
  accelerator="gpu" if torch.cuda.is_available() else "cpu",
134
- devices=devices,
135
- strategy=strategy,
136
  precision=precision,
137
- callbacks=[],
138
  log_every_n_steps=10,
139
  logger=logger,
140
  )
141
 
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  @click.command()
144
  @click.option(
145
  "-r",
@@ -166,7 +182,7 @@ def make_trainer(max_epochs: int, logdir: str, logger_name: str, devices: list[i
166
  show_default=True,
167
  help="Number of output units, usually 2 for clf + reg.",
168
  )
169
- @click.option("-b", "--batch-size", type=int, default=50, show_default=True, help="Batch size.")
170
  @click.option("-f", "--frames-per-clip", type=int, default=32, show_default=True, help="Frames per clip.")
171
  @click.option(
172
  "-v",
@@ -176,15 +192,15 @@ def make_trainer(max_epochs: int, logdir: str, logger_name: str, devices: list[i
176
  show_default=True,
177
  help="Frame size (H, W).",
178
  )
179
- @click.option("--max-epochs", type=int, default=10, show_default=True, help="Number of full-train epochs.")
180
  @click.option("--num-workers", type=int, default=8, show_default=True, help="Number of DataLoader workers.")
181
  @click.option(
182
  "--devices",
183
- type=list[int],
184
  multiple=True,
185
  default=[0],
186
  show_default=True,
187
- help="List of GPU ids",
188
  )
189
  @click.option("--precision", type=str, default="bf16-mixed", show_default=True, help="Precision mode.")
190
  @click.option(
@@ -201,6 +217,10 @@ def make_trainer(max_epochs: int, logdir: str, logger_name: str, devices: list[i
201
  show_default=True,
202
  help="Use a WeightedRandomSampler by score bins.",
203
  )
 
 
 
 
204
  @click.option("--seed", type=int, default=42, show_default=True, help="Seed for reproducibility.")
205
  def main(
206
  dataset_root,
@@ -217,14 +237,18 @@ def main(
217
  logdir,
218
  use_weighted_sampler,
219
  seed,
 
 
220
  ):
221
  """
222
  Entry point for backbone training.
223
 
224
  Sequence:
225
  1) pretrain: train only the fc layer
226
- 2) full train: fine-tune the full model from the latest pretrain checkpoint
227
  """
 
 
228
  pl.seed_everything(seed)
229
 
230
  artery = artery.lower()
@@ -235,8 +259,8 @@ def main(
235
  imagenet_mean = [0.485, 0.456, 0.406]
236
  imagenet_std = [0.229, 0.224, 0.225]
237
 
238
- train_meta = f"folds/step2_fold{fold:02d}_train.json"
239
- eval_meta = f"folds/step2_fold{fold:02d}_eval.json"
240
 
241
  train_set = SyntaxDataset(
242
  root=dataset_root,
@@ -264,6 +288,9 @@ def main(
264
  train_loader_post = make_dataloader(train_set, batch_size, num_workers, use_weighted_sampler)
265
  val_loader = make_dataloader(val_set, 1, num_workers, use_weighted_sampler=False)
266
 
 
 
 
267
  x, *_ = next(iter(train_loader_pre))
268
  video_shape = x.shape[1:]
269
  print(f"Backbone input video shape: {video_shape}")
@@ -272,7 +299,7 @@ def main(
272
  callbacks_full = make_callbacks(phase="full")
273
 
274
  # ------------------- Pretrain (fc only) -------------------
275
- num_pre_epochs = 10
276
 
277
  model_pre = make_model(
278
  num_classes=num_classes,
@@ -288,17 +315,19 @@ def main(
288
  logger_name=f"{artery}BinSyntax_R3D_pre_fold{fold:02d}",
289
  devices=devices,
290
  precision=precision,
 
291
  )
292
- trainer_pre.callbacks.extend(callbacks_pre)
293
  trainer_pre.fit(model_pre, train_loader_pre, val_loader)
294
 
 
 
295
  # ------------------- Full train (fine-tune) -------------------
296
  model_full = make_model(
297
  num_classes=num_classes,
298
  lr=1e-4,
299
  weight_decay=0.01,
300
  max_epochs=max_epochs,
301
- weight_path=trainer_pre.checkpoint_callback.last_model_path,
302
  )
303
 
304
  trainer_full = make_trainer(
@@ -307,9 +336,10 @@ def main(
307
  logger_name=f"{artery}BinSyntax_R3D_full_fold{fold:02d}",
308
  devices=devices,
309
  precision=precision,
 
310
  )
311
- trainer_full.callbacks.extend(callbacks_full)
312
  trainer_full.fit(model_full, train_loader_post, val_loader)
 
313
 
314
 
315
  if __name__ == "__main__":
 
4
  import click
5
  import lightning.pytorch as pl
6
  import torch
7
+ from safetensors.torch import save_file
8
  from lightning.pytorch.callbacks import LearningRateMonitor, ModelCheckpoint
9
  from lightning.pytorch.loggers import TensorBoardLogger
10
  from pytorchvideo.transforms import Normalize, Permute, RandAugment
 
69
  shuffle = False
70
  else:
71
  sampler = None
72
+ shuffle = dataset.train
73
 
74
  return DataLoader(
75
  dataset,
 
77
  num_workers=num_workers,
78
  sampler=sampler,
79
  shuffle=shuffle,
80
+ drop_last=dataset.train,
81
  pin_memory=True,
82
  persistent_workers=(num_workers > 0),
83
  )
 
117
  return [lr_monitor, checkpoint]
118
 
119
 
120
+ def make_trainer(max_epochs: int, logdir: str, logger_name: str, devices: list[int], precision: str, callbacks):
121
  """
122
  Build a Trainer with the requested settings:
123
  - logdir: TensorBoard log directory
 
132
  return pl.Trainer(
133
  max_epochs=max_epochs,
134
  accelerator="gpu" if torch.cuda.is_available() else "cpu",
135
+ devices=list(devices) if torch.cuda.is_available() else 1,
136
+ strategy=strategy if torch.cuda.is_available() else "auto",
137
  precision=precision,
138
+ callbacks=callbacks,
139
  log_every_n_steps=10,
140
  logger=logger,
141
  )
142
 
143
 
144
+ def export_weights(trainer, destination):
145
+ """Export tensors from the selected local training checkpoint, on rank zero."""
146
+ if trainer.is_global_zero:
147
+ checkpoint = trainer.checkpoint_callback.best_model_path
148
+ if not checkpoint:
149
+ raise RuntimeError("No checkpoint selected: check validation data and val_rmse.")
150
+ state = torch.load(checkpoint, map_location="cpu", weights_only=False)["state_dict"]
151
+ state = {k.removeprefix("model."): v for k, v in state.items()}
152
+ os.makedirs(os.path.dirname(os.path.abspath(destination)), exist_ok=True)
153
+ save_file({k: v.detach().cpu().contiguous() for k, v in state.items()}, destination)
154
+ print(f"Exported safetensors: {destination}")
155
+ trainer.strategy.barrier()
156
+ return destination
157
+
158
+
159
  @click.command()
160
  @click.option(
161
  "-r",
 
182
  show_default=True,
183
  help="Number of output units, usually 2 for clf + reg.",
184
  )
185
+ @click.option("-b", "--batch-size", type=click.IntRange(min=1), default=50, show_default=True, help="Batch size.")
186
  @click.option("-f", "--frames-per-clip", type=int, default=32, show_default=True, help="Frames per clip.")
187
  @click.option(
188
  "-v",
 
192
  show_default=True,
193
  help="Frame size (H, W).",
194
  )
195
+ @click.option("--max-epochs", type=click.IntRange(min=1), default=10, show_default=True, help="Number of full-train epochs.")
196
  @click.option("--num-workers", type=int, default=8, show_default=True, help="Number of DataLoader workers.")
197
  @click.option(
198
  "--devices",
199
+ type=click.IntRange(min=0),
200
  multiple=True,
201
  default=[0],
202
  show_default=True,
203
+ help="GPU index; repeat for multiple GPUs, e.g. --devices 0 --devices 1.",
204
  )
205
  @click.option("--precision", type=str, default="bf16-mixed", show_default=True, help="Precision mode.")
206
  @click.option(
 
217
  show_default=True,
218
  help="Use a WeightedRandomSampler by score bins.",
219
  )
220
+ @click.option("--weights-dir", type=click.Path(), default="./trained_weights/backbone",
221
+ show_default=True, help="Directory for exported safetensors weights.")
222
+ @click.option("--pre-epochs", type=click.IntRange(min=1), default=10,
223
+ help="Head-only epochs; default: 10.")
224
  @click.option("--seed", type=int, default=42, show_default=True, help="Seed for reproducibility.")
225
  def main(
226
  dataset_root,
 
237
  logdir,
238
  use_weighted_sampler,
239
  seed,
240
+ weights_dir,
241
+ pre_epochs,
242
  ):
243
  """
244
  Entry point for backbone training.
245
 
246
  Sequence:
247
  1) pretrain: train only the fc layer
248
+ 2) full train: fine-tune the full model from the best pretrain weights
249
  """
250
+ if num_classes != 2:
251
+ raise click.BadParameter("Training requires two outputs: classification and regression.", param_hint="--num-classes")
252
  pl.seed_everything(seed)
253
 
254
  artery = artery.lower()
 
259
  imagenet_mean = [0.485, 0.456, 0.406]
260
  imagenet_std = [0.229, 0.224, 0.225]
261
 
262
+ train_meta = f"folds/fold{fold:02d}_train.json"
263
+ eval_meta = f"folds/fold{fold:02d}_eval.json"
264
 
265
  train_set = SyntaxDataset(
266
  root=dataset_root,
 
288
  train_loader_post = make_dataloader(train_set, batch_size, num_workers, use_weighted_sampler)
289
  val_loader = make_dataloader(val_set, 1, num_workers, use_weighted_sampler=False)
290
 
291
+ if len(train_loader_pre) == 0 or len(val_loader) == 0:
292
+ raise click.ClickException("Need at least 2 * batch-size training samples and one validation sample after filtering.")
293
+
294
  x, *_ = next(iter(train_loader_pre))
295
  video_shape = x.shape[1:]
296
  print(f"Backbone input video shape: {video_shape}")
 
299
  callbacks_full = make_callbacks(phase="full")
300
 
301
  # ------------------- Pretrain (fc only) -------------------
302
+ num_pre_epochs = pre_epochs
303
 
304
  model_pre = make_model(
305
  num_classes=num_classes,
 
315
  logger_name=f"{artery}BinSyntax_R3D_pre_fold{fold:02d}",
316
  devices=devices,
317
  precision=precision,
318
+ callbacks=callbacks_pre,
319
  )
 
320
  trainer_pre.fit(model_pre, train_loader_pre, val_loader)
321
 
322
+ pre_weights = export_weights(trainer_pre, os.path.join(trainer_pre.log_dir, "backbone_pre.safetensors"))
323
+
324
  # ------------------- Full train (fine-tune) -------------------
325
  model_full = make_model(
326
  num_classes=num_classes,
327
  lr=1e-4,
328
  weight_decay=0.01,
329
  max_epochs=max_epochs,
330
+ weight_path=pre_weights,
331
  )
332
 
333
  trainer_full = make_trainer(
 
336
  logger_name=f"{artery}BinSyntax_R3D_full_fold{fold:02d}",
337
  devices=devices,
338
  precision=precision,
339
+ callbacks=callbacks_full,
340
  )
 
341
  trainer_full.fit(model_full, train_loader_post, val_loader)
342
+ export_weights(trainer_full, os.path.join(weights_dir, f"{artery}BinSyntax_R3D_full_fold{fold:02d}.safetensors"))
343
 
344
 
345
  if __name__ == "__main__":
backbone_weights/{leftBinSyntax_R3D_full_fold00.pt → leftBinSyntax_R3D_full_fold00.safetensors} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:299db032713b8b8247fa42e1bfcf993d6c0ea162a2d47211cd4ef83e8e7083ac
3
- size 398135752
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:089192f0616a790d944f6433ef4f1b970d65b61406f4b4df128cd36493b2676a
3
+ size 132717204
backbone_weights/{leftBinSyntax_R3D_full_fold01.pt → leftBinSyntax_R3D_full_fold01.safetensors} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fef1d7fdc6d2fc3e8b64b807c21a3d15af832bad8dfd1cbe59c1122c5f020a62
3
- size 398135752
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4540ac86305368f158837b0882b4503068837113172d4cb1051b45f30cba6eef
3
+ size 132717204
backbone_weights/{leftBinSyntax_R3D_full_fold02.pt → leftBinSyntax_R3D_full_fold02.safetensors} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:81b7f04e2d6735c505fe50101c2f7dedacb1503681c14f28c6fd8007bb7a4255
3
- size 398135752
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd825715d75fd9701f0397d4ea960305ff8feb31327c9815b65e05d7ed93476e
3
+ size 132717204
backbone_weights/{leftBinSyntax_R3D_full_fold03.pt → leftBinSyntax_R3D_full_fold03.safetensors} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7decf5e0fec66d734901a8cb0c47a09b0d7ec33a341f245caa7aeee0011162fc
3
- size 398135752
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c95fc2996d03106c94d16d1c9e09c15fc904e7de52a92e8af2629e2a6dedfb2a
3
+ size 132717204
backbone_weights/leftBinSyntax_R3D_full_fold04.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e85aa8b198f29e9375d93a37e11eb130b73b9d8a03f68a60c7aa7fd16d899f0f
3
- size 398135752
 
 
 
 
backbone_weights/leftBinSyntax_R3D_full_fold04.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db5f294a659255a4fbd73cbf2b2f32625ff9519d7ea91738582b8fc2b3f8ae5a
3
+ size 132717204
backbone_weights/rightBinSyntax_R3D_full_fold00.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:f6285307728b4c15a5f9ded2c311981d9c71f81bfbab4c11663fa73af57ffd35
3
- size 398135752
 
 
 
 
backbone_weights/rightBinSyntax_R3D_full_fold00.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20fcfc4c4c46efaff9f51ca0bc3fe16511f585263a43478b3f77876ab0710780
3
+ size 132717204
backbone_weights/rightBinSyntax_R3D_full_fold01.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b77467117b220d4245d7c0bc00b9072719c0c563672a34a643d986986be32866
3
- size 398135752
 
 
 
 
backbone_weights/rightBinSyntax_R3D_full_fold01.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8bdb37cb61def8c0b590ac9354d9e439a78f56c25fc1eb51c5fe9fca74c1294
3
+ size 132717204
backbone_weights/rightBinSyntax_R3D_full_fold02.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:3d0d1fb3aac64364e2e99b0c25d17bf1650b15b9da71cbba4ea6dd3ce2cb2bb0
3
- size 398135752
 
 
 
 
backbone_weights/rightBinSyntax_R3D_full_fold02.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03da1fea66f38c483a3814a6877177d0f226ff414222f8d5f1225c4c12c2dd51
3
+ size 132717204
backbone_weights/rightBinSyntax_R3D_full_fold03.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:2c3387e5bb99b615d7c8d5a67b41d53f4cc4d872e82f7b391be4da3321490fdb
3
- size 398135752
 
 
 
 
backbone_weights/rightBinSyntax_R3D_full_fold03.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad777b1f38239a0342f111d6fa9f52bde06d15963823d18b52b84f0218a37fa5
3
+ size 132717204
backbone_weights/rightBinSyntax_R3D_full_fold04.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7e3cf35b8d0450f23bb105d6367efc8ab32bc73a0bc4170e0fc07fbe54e593f9
3
- size 398135752
 
 
 
 
backbone_weights/rightBinSyntax_R3D_full_fold04.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68194699e1c87f39b0b032a1d31cf2cdbf997c72fa407a0a897c450f4678cacf
3
+ size 132717204
classifier_weights/r3d_art.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3516fbad1d4b82927a553763bc1b5751ea5196e78299743d33326c5e0cbd312
3
+ size 132717196
full_model/rnn_model.py CHANGED
@@ -1,5 +1,6 @@
1
  from typing import Any, Callable, Optional, Tuple
2
  import torch
 
3
  import torch.nn.functional as F
4
  from torch import nn, optim
5
  import lightning.pytorch as pl
@@ -24,8 +25,8 @@ class SyntaxLightningModule(pl.LightningModule):
24
  sigma_b: float = 1,
25
  **kwargs,
26
  ):
27
- self.save_hyperparameters()
28
  super().__init__()
 
29
  self.num_classes = num_classes
30
  self.save_path = save_path
31
  self.weight_path = weight_path
@@ -82,31 +83,14 @@ class SyntaxLightningModule(pl.LightningModule):
82
  if pl_weight_path is not None:
83
  print(f"Load LightningModule weights from {pl_weight_path}")
84
 
85
- if pt_weights_format:
86
- pl_state_dict = torch.load(pl_weight_path, weights_only=False)
 
 
87
  else:
88
- pl_state_dict = torch.load(pl_weight_path, weights_only=False)["state_dict"]
89
-
90
- self.load_weights(pl_state_dict, self.model, "model")
91
 
92
- if self.variant == "mean_out":
93
- pass
94
- elif self.variant in ("gru_mean", "gru_last"):
95
- self.load_weights(pl_state_dict, self.rnn, "rnn")
96
- self.load_weights(pl_state_dict, self.fc, "fc")
97
- elif self.variant in ("lstm_mean", "lstm_last"):
98
- self.load_weights(pl_state_dict, self.lstm, "lstm")
99
- elif self.variant == "mean":
100
- self.load_weights(pl_state_dict, self.fc, "fc")
101
- elif self.variant in ("bert_mean", "bert_cls", "bert_cls2"):
102
- self.load_weights(pl_state_dict, self.encoder, "encoder")
103
- self.load_weights(pl_state_dict, self.fc, "fc")
104
- if self.variant == "bert_cls2":
105
- old_shape = self.cls.shape
106
- self.cls = nn.Parameter(pl_state_dict["cls"])
107
- assert old_shape == self.cls.shape
108
- else:
109
- raise ValueError(f"Unknown model variant {self.variant}")
110
 
111
  self.max_epochs = max_epochs
112
  self.weight_decay = weight_decay
@@ -123,12 +107,16 @@ class SyntaxLightningModule(pl.LightningModule):
123
 
124
  - If the file is a Lightning checkpoint (a dict with 'state_dict'),
125
  extract state_dict['state_dict'] and strip the 'model.' prefix.
126
- - If the file is a raw state_dict (.pt/.pth) saved via model.state_dict(),
127
  load it directly.
128
 
129
- Before loading, drop any keys whose tensor shapes do not match the module.
 
130
  """
131
- obj = torch.load(weight_path, weights_only=False, map_location="cpu")
 
 
 
132
 
133
  if isinstance(obj, dict) and "state_dict" in obj:
134
  raw_state = obj["state_dict"]
@@ -139,44 +127,14 @@ class SyntaxLightningModule(pl.LightningModule):
139
  src_type = "raw_state_dict"
140
 
141
  current_state = model.state_dict()
142
- filtered_state = {}
143
- mismatched_keys = []
144
-
145
- for k, v in state_dict.items():
146
- if k in current_state and current_state[k].shape == v.shape:
147
- filtered_state[k] = v
148
- else:
149
- mismatched_keys.append(k)
150
-
151
- incompatible = model.load_state_dict(filtered_state, strict=False)
152
-
153
- loaded_keys = [k for k in filtered_state.keys() if k not in incompatible.missing_keys]
154
- print(
155
- f"[Backbone] Loaded weights from '{weight_path}' "
156
- f"(type={src_type}): {len(loaded_keys)} params, "
157
- f"missing={len(incompatible.missing_keys)}, "
158
- f"unexpected={len(incompatible.unexpected_keys)}, "
159
- f"skipped_mismatched={len(mismatched_keys)}"
160
- )
161
- if mismatched_keys:
162
- print(f"[Backbone] Size‑mismatched keys (skipped), example: {mismatched_keys[:5]}")
163
- if incompatible.missing_keys:
164
- print(f"[Backbone] Missing keys after filtering, example: {incompatible.missing_keys[:5]}")
165
- if incompatible.unexpected_keys:
166
- print(f"[Backbone] Unexpected keys after filtering, example: {incompatible.unexpected_keys[:5]}")
167
-
168
- def load_weights(self, state_dict, module, prefix: str):
169
- """Filter and load only the weights that belong to the given module."""
170
- module_state = {
171
- k.replace(f"{prefix}.", ""): v
172
- for k, v in state_dict.items()
173
- if k.startswith(prefix)
174
- }
175
- missing, unexpected = module.load_state_dict(module_state, strict=False)
176
- if missing:
177
- print(f"Missing keys for {prefix}: {missing}")
178
- if unexpected:
179
- print(f"Unexpected keys for {prefix}: {unexpected}")
180
 
181
  def forward(self, x):
182
  batch_seq_shape = x.shape[0:2]
@@ -187,7 +145,8 @@ class SyntaxLightningModule(pl.LightningModule):
187
  if self.variant == "mean_out":
188
  x = torch.mean(x, dim=1)
189
  elif self.variant in ("gru_mean", "gru_last"):
190
- _all_outs_, [_last_out_] = self.rnn(x)
 
191
  if self.variant == "gru_mean":
192
  x = torch.mean(_all_outs_, dim=1)
193
  else:
@@ -199,7 +158,7 @@ class SyntaxLightningModule(pl.LightningModule):
199
  if self.variant == "lstm_mean":
200
  x = torch.mean(_all_outs_, dim=1)
201
  else:
202
- x = _last_out_
203
  elif self.variant == "mean":
204
  x = torch.mean(x, dim=1)
205
  x = self.fc(x)
@@ -280,23 +239,18 @@ class SyntaxLightningModule(pl.LightningModule):
280
  return loss
281
 
282
  def on_validation_epoch_end(self):
283
- try:
284
- auc = skm.roc_auc_score(self.y_val, self.p_val)
285
- f1 = skm.f1_score(self.y_val, self.r_val, zero_division=0)
286
- acc = skm.accuracy_score(self.y_val, self.r_val)
287
- mae = skm.mean_absolute_error(self.y_val, self.r_val)
288
- self.log("val_auc", auc, prog_bar=True, sync_dist=True)
289
- self.log("val_f1", f1, prog_bar=True, sync_dist=True)
290
- self.log("val_acc", acc, prog_bar=True, sync_dist=True)
291
- self.log("val_mae", mae, prog_bar=True, sync_dist=True)
292
-
293
- rmse = skm.root_mean_squared_error(self.ty_val, self.tp_val)
294
- self.log("val_rmse", rmse, prog_bar=True, sync_dist=True)
295
-
296
- except ValueError as err:
297
- print(err)
298
- print("Y_VAL", self.y_val)
299
- print("P_VAL", self.p_val)
300
  self.y_val.clear()
301
  self.p_val.clear()
302
  self.r_val.clear()
@@ -332,11 +286,10 @@ class SyntaxLightningModule(pl.LightningModule):
332
  for param in self.parameters():
333
  param.requires_grad = False
334
 
335
- for m in trainable_modules:
336
- for p in m.parameters():
337
- p.requires_grad = True
338
-
339
- params = [p for m in trainable_modules for p in m.parameters()]
340
  else:
341
  for param in self.parameters():
342
  param.requires_grad = True
@@ -346,9 +299,11 @@ class SyntaxLightningModule(pl.LightningModule):
346
 
347
  if self.max_epochs is not None:
348
  lr_scheduler = optim.lr_scheduler.OneCycleLR(
349
- optimizer=optimizer, max_lr=self.lr, total_steps=self.max_epochs
 
350
  )
351
- return [optimizer], [lr_scheduler]
 
352
  else:
353
  return optimizer
354
 
 
1
  from typing import Any, Callable, Optional, Tuple
2
  import torch
3
+ from safetensors.torch import load_file
4
  import torch.nn.functional as F
5
  from torch import nn, optim
6
  import lightning.pytorch as pl
 
25
  sigma_b: float = 1,
26
  **kwargs,
27
  ):
 
28
  super().__init__()
29
+ self.save_hyperparameters()
30
  self.num_classes = num_classes
31
  self.save_path = save_path
32
  self.weight_path = weight_path
 
83
  if pl_weight_path is not None:
84
  print(f"Load LightningModule weights from {pl_weight_path}")
85
 
86
+ if str(pl_weight_path).endswith(".safetensors"):
87
+ pl_state_dict = load_file(str(pl_weight_path), device="cpu")
88
+ elif pt_weights_format:
89
+ pl_state_dict = torch.load(pl_weight_path, map_location="cpu", weights_only=False)
90
  else:
91
+ pl_state_dict = torch.load(pl_weight_path, map_location="cpu", weights_only=False)["state_dict"]
 
 
92
 
93
+ self.load_state_dict(pl_state_dict, strict=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  self.max_epochs = max_epochs
96
  self.weight_decay = weight_decay
 
107
 
108
  - If the file is a Lightning checkpoint (a dict with 'state_dict'),
109
  extract state_dict['state_dict'] and strip the 'model.' prefix.
110
+ - If the file is safetensors or a raw state_dict (.pt/.pth),
111
  load it directly.
112
 
113
+ Validate all keys and shapes strictly, except the fc head discarded
114
+ by aggregation variants.
115
  """
116
+ if str(weight_path).endswith(".safetensors"):
117
+ obj = load_file(str(weight_path), device="cpu")
118
+ else:
119
+ obj = torch.load(weight_path, weights_only=False, map_location="cpu")
120
 
121
  if isinstance(obj, dict) and "state_dict" in obj:
122
  raw_state = obj["state_dict"]
 
127
  src_type = "raw_state_dict"
128
 
129
  current_state = model.state_dict()
130
+ for key in ("fc.weight", "fc.bias"):
131
+ if key in state_dict and state_dict[key].shape != current_state[key].shape:
132
+ if self.variant == "mean_out":
133
+ raise ValueError("mean_out requires a two-output backbone head.")
134
+ # Aggregation variants replace fc with Identity immediately after loading.
135
+ state_dict[key] = current_state[key]
136
+ model.load_state_dict(state_dict, strict=True)
137
+ print(f"[Backbone] Loaded {len(state_dict)} tensors from '{weight_path}' ({src_type})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  def forward(self, x):
140
  batch_seq_shape = x.shape[0:2]
 
145
  if self.variant == "mean_out":
146
  x = torch.mean(x, dim=1)
147
  elif self.variant in ("gru_mean", "gru_last"):
148
+ _all_outs_, hidden = self.rnn(x)
149
+ _last_out_ = hidden[-1]
150
  if self.variant == "gru_mean":
151
  x = torch.mean(_all_outs_, dim=1)
152
  else:
 
158
  if self.variant == "lstm_mean":
159
  x = torch.mean(_all_outs_, dim=1)
160
  else:
161
+ x = _last_out_[-1]
162
  elif self.variant == "mean":
163
  x = torch.mean(x, dim=1)
164
  x = self.fc(x)
 
239
  return loss
240
 
241
  def on_validation_epoch_end(self):
242
+ if self.ty_val:
243
+ self.log("val_rmse", skm.root_mean_squared_error(self.ty_val, self.tp_val),
244
+ prog_bar=True, sync_dist=True)
245
+ if len(set(self.y_val)) > 1:
246
+ self.log("val_auc", skm.roc_auc_score(self.y_val, self.p_val),
247
+ prog_bar=True, sync_dist=True)
248
+ self.log("val_f1", skm.f1_score(self.y_val, self.r_val, zero_division=0),
249
+ prog_bar=True, sync_dist=True)
250
+ self.log("val_acc", skm.accuracy_score(self.y_val, self.r_val),
251
+ prog_bar=True, sync_dist=True)
252
+ self.log("val_mae", skm.mean_absolute_error(self.y_val, self.r_val),
253
+ prog_bar=True, sync_dist=True)
 
 
 
 
 
254
  self.y_val.clear()
255
  self.p_val.clear()
256
  self.r_val.clear()
 
286
  for param in self.parameters():
287
  param.requires_grad = False
288
 
289
+ params = [p for m in trainable_modules
290
+ for p in ([m] if isinstance(m, nn.Parameter) else m.parameters())]
291
+ for p in params:
292
+ p.requires_grad = True
 
293
  else:
294
  for param in self.parameters():
295
  param.requires_grad = True
 
299
 
300
  if self.max_epochs is not None:
301
  lr_scheduler = optim.lr_scheduler.OneCycleLR(
302
+ optimizer=optimizer, max_lr=self.lr,
303
+ total_steps=self.trainer.estimated_stepping_batches
304
  )
305
+ return {"optimizer": optimizer,
306
+ "lr_scheduler": {"scheduler": lr_scheduler, "interval": "step"}}
307
  else:
308
  return optimizer
309
 
full_model/rnn_train.py CHANGED
@@ -5,6 +5,7 @@ from typing import Any
5
  import click
6
  import lightning.pytorch as pl
7
  import torch
 
8
  from lightning.pytorch.callbacks import LearningRateMonitor, ModelCheckpoint
9
  from lightning.pytorch.loggers import TensorBoardLogger
10
  from pytorchvideo.transforms import Normalize, Permute, RandAugment
@@ -60,7 +61,7 @@ def make_dataloader(dataset, batch_size: int, num_workers: int, use_weighted_sam
60
  num_workers=num_workers,
61
  sampler=sampler,
62
  shuffle=shuffle,
63
- drop_last=True,
64
  pin_memory=True,
65
  persistent_workers=(num_workers > 0),
66
  )
@@ -79,8 +80,8 @@ def make_model(
79
  """
80
  Create the head model.
81
 
82
- weight_path — pretrained backbone weights (r3d_18), .pt or .ckpt.
83
- pl_weight_path — full head-model checkpoint (Lightning .ckpt or raw .pt).
84
  pt_weights_format=True → pl_weight_path is a raw state_dict (.pt).
85
  pt_weights_format=False → pl_weight_path is a Lightning .ckpt with 'state_dict'.
86
  """
@@ -92,7 +93,7 @@ def make_model(
92
  max_epochs=max_epochs,
93
  weight_path=weight_path,
94
  pl_weight_path=pl_weight_path,
95
- yulie_model=pt_weights_format,
96
  )
97
 
98
 
@@ -130,8 +131,8 @@ def make_trainer(max_epochs: int, logdir: str, logger_name: str, devices: list[i
130
  trainer = pl.Trainer(
131
  max_epochs=max_epochs,
132
  accelerator="gpu" if torch.cuda.is_available() else "cpu",
133
- devices=devices,
134
- strategy=strategy,
135
  precision=precision,
136
  callbacks=callbacks,
137
  log_every_n_steps=10,
@@ -164,22 +165,36 @@ def find_backbone_ckpt_lightning(backbone_logdir: str, artery: str, fold: int, p
164
 
165
  def build_backbone_pt_path(backbone_pt_dir: str, artery: str, fold: int) -> str:
166
  """
167
- Build the backbone .pt path using the naming convention:
168
- rightBinSyntax_R3D_full_fold00.pt
169
- leftBinSyntax_R3D_full_fold00.pt
170
  ...
171
  """
172
- fname = f"{artery}BinSyntax_R3D_full_fold{fold:02d}.pt"
173
  path = os.path.join(backbone_pt_dir, fname)
174
  if not os.path.exists(path):
175
  raise FileNotFoundError(
176
- f"Backbone .pt not found for artery={artery}, fold={fold} in '{backbone_pt_dir}'\n"
177
  f"Expected file: {fname}"
178
  )
179
- print(f"[Backbone] Using .pt file: {path}")
180
  return path
181
 
182
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  @click.command()
184
  @click.option(
185
  "-r",
@@ -207,7 +222,7 @@ def build_backbone_pt_path(backbone_pt_dir: str, artery: str, fold: int) -> str:
207
  )
208
  @click.option("-nc", "--num-classes", type=int, default=2, show_default=True,
209
  help="Number of head-model outputs (clf + reg).")
210
- @click.option("-b", "--batch-size", type=int, default=8, show_default=True, help="Batch size.")
211
  @click.option("-f", "--frames-per-clip", type=int, default=32, show_default=True,
212
  help="Frames per clip.")
213
  @click.option(
@@ -218,15 +233,15 @@ def build_backbone_pt_path(backbone_pt_dir: str, artery: str, fold: int) -> str:
218
  show_default=True,
219
  help="Frame size (H, W).",
220
  )
221
- @click.option("--max-epochs", type=int, default=10, show_default=True, help="Number of full-train epochs.")
222
  @click.option("--num-workers", type=int, default=16, show_default=True, help="DataLoader workers.")
223
  @click.option(
224
  "--devices",
225
- type=list[int],
226
  multiple=True,
227
  default=[0],
228
  show_default=True,
229
- help="List of GPU ids",
230
  )
231
  @click.option("--precision", type=str, default="bf16-mixed", show_default=True, help="Numeric precision mode.")
232
  @click.option(
@@ -243,18 +258,18 @@ def build_backbone_pt_path(backbone_pt_dir: str, artery: str, fold: int) -> str:
243
  help="Directory with backbone logs (Lightning .ckpt files).",
244
  )
245
  @click.option(
246
- "--backbone-pt-dir",
247
- type=click.Path(exists=True),
248
  default="backbone_weights",
249
  show_default=True,
250
- help="Directory with backbone .pt files (rightBinSyntax_R3D_full_foldXX.pt, leftBinSyntax_R3D_full_foldXX.pt).",
251
  )
252
  @click.option(
253
- "--backbone-from-pt",
254
  is_flag=True,
255
  default=True,
256
  show_default=True,
257
- help="When enabled, load the backbone from .pt files in backbone-pt-dir; otherwise use Lightning logs in backbone-logdir.",
258
  )
259
  @click.option(
260
  "--rnn-folds-dir",
@@ -275,8 +290,12 @@ def build_backbone_pt_path(backbone_pt_dir: str, artery: str, fold: int) -> str:
275
  is_flag=True,
276
  default=False,
277
  show_default=True,
278
- help="pl_weight_path format for full training: True uses .pt raw state_dict, False uses Lightning .ckpt.",
279
  )
 
 
 
 
280
  @click.option("--seed", type=int, default=42, show_default=True, help="Random seed.")
281
  def main(
282
  dataset_root: str,
@@ -289,7 +308,7 @@ def main(
289
  video_size: Any,
290
  max_epochs: int,
291
  num_workers: int,
292
- devices: int,
293
  precision: str,
294
  logdir: str,
295
  backbone_logdir: str | None,
@@ -299,6 +318,8 @@ def main(
299
  use_weighted_sampler: bool,
300
  pt_weights_format: bool,
301
  seed: int,
 
 
302
  ):
303
  """Train the RNN head on top of the backbone."""
304
  VARIANTS = "mean_out mean lstm_mean lstm_last gru_mean gru_last bert_mean bert_cls bert_cls2".split()
@@ -309,6 +330,8 @@ def main(
309
  if artery not in ("left", "right"):
310
  raise ValueError(f"Unknown artery '{artery}', expected 'left' or 'right'")
311
 
 
 
312
  pl.seed_everything(seed)
313
 
314
  imagenet_mean = [0.485, 0.456, 0.406]
@@ -345,6 +368,9 @@ def main(
345
  train_loader_post = make_dataloader(train_set, batch_size, num_workers, use_weighted_sampler)
346
  val_loader = make_dataloader(val_set, 1, num_workers, use_weighted_sampler=False)
347
 
 
 
 
348
  x, *_ = next(iter(train_loader_pre))
349
  video_shape = x.shape[2:]
350
  print(f"RNN head input per clip: {video_shape}")
@@ -363,6 +389,7 @@ def main(
363
  phase="full",
364
  )
365
 
 
366
  callbacks_pre = make_callbacks(phase="pre")
367
 
368
  model_pre = make_model(
@@ -370,14 +397,14 @@ def main(
370
  lr=1e-4,
371
  variant=variant,
372
  weight_decay=0.01,
373
- max_epochs=max_epochs,
374
  weight_path=backbone_weight_path,
375
  pl_weight_path=None,
376
  pt_weights_format=False,
377
  )
378
 
379
  trainer_pre = make_trainer(
380
- max_epochs=max_epochs,
381
  logdir=logdir,
382
  logger_name=f"{artery}BinSyntax_R3D_fold{fold:02d}_{variant}_pre",
383
  devices=devices,
@@ -386,6 +413,7 @@ def main(
386
  )
387
  trainer_pre.fit(model_pre, train_dataloaders=train_loader_pre, val_dataloaders=val_loader)
388
 
 
389
  callbacks_full = make_callbacks(phase="full")
390
 
391
  model_full = make_model(
@@ -395,7 +423,7 @@ def main(
395
  weight_decay=0.01,
396
  max_epochs=max_epochs,
397
  weight_path=None,
398
- pl_weight_path=trainer_pre.checkpoint_callback.best_model_path,
399
  pt_weights_format=pt_weights_format,
400
  )
401
 
@@ -408,6 +436,7 @@ def main(
408
  callbacks=callbacks_full,
409
  )
410
  trainer_full.fit(model_full, train_dataloaders=train_loader_post, val_dataloaders=val_loader)
 
411
 
412
 
413
  if __name__ == "__main__":
 
5
  import click
6
  import lightning.pytorch as pl
7
  import torch
8
+ from safetensors.torch import save_file
9
  from lightning.pytorch.callbacks import LearningRateMonitor, ModelCheckpoint
10
  from lightning.pytorch.loggers import TensorBoardLogger
11
  from pytorchvideo.transforms import Normalize, Permute, RandAugment
 
61
  num_workers=num_workers,
62
  sampler=sampler,
63
  shuffle=shuffle,
64
+ drop_last=dataset.train,
65
  pin_memory=True,
66
  persistent_workers=(num_workers > 0),
67
  )
 
80
  """
81
  Create the head model.
82
 
83
+ weight_path — pretrained backbone (.safetensors, legacy .pt or .ckpt).
84
+ pl_weight_path — full-model .safetensors or a legacy checkpoint.
85
  pt_weights_format=True → pl_weight_path is a raw state_dict (.pt).
86
  pt_weights_format=False → pl_weight_path is a Lightning .ckpt with 'state_dict'.
87
  """
 
93
  max_epochs=max_epochs,
94
  weight_path=weight_path,
95
  pl_weight_path=pl_weight_path,
96
+ pt_weights_format=pt_weights_format,
97
  )
98
 
99
 
 
131
  trainer = pl.Trainer(
132
  max_epochs=max_epochs,
133
  accelerator="gpu" if torch.cuda.is_available() else "cpu",
134
+ devices=list(devices) if torch.cuda.is_available() else 1,
135
+ strategy=strategy if torch.cuda.is_available() else "auto",
136
  precision=precision,
137
  callbacks=callbacks,
138
  log_every_n_steps=10,
 
165
 
166
  def build_backbone_pt_path(backbone_pt_dir: str, artery: str, fold: int) -> str:
167
  """
168
+ Build the backbone .safetensors path using the naming convention:
169
+ rightBinSyntax_R3D_full_fold00.safetensors
170
+ leftBinSyntax_R3D_full_fold00.safetensors
171
  ...
172
  """
173
+ fname = f"{artery}BinSyntax_R3D_full_fold{fold:02d}.safetensors"
174
  path = os.path.join(backbone_pt_dir, fname)
175
  if not os.path.exists(path):
176
  raise FileNotFoundError(
177
+ f"Backbone .safetensors not found for artery={artery}, fold={fold} in '{backbone_pt_dir}'\n"
178
  f"Expected file: {fname}"
179
  )
180
+ print(f"[Backbone] Using .safetensors file: {path}")
181
  return path
182
 
183
 
184
+ def export_weights(trainer, destination):
185
+ """Export tensors from the selected local training checkpoint, on rank zero."""
186
+ if trainer.is_global_zero:
187
+ checkpoint = trainer.checkpoint_callback.best_model_path
188
+ if not checkpoint:
189
+ raise RuntimeError("No checkpoint selected: check validation data and val_rmse.")
190
+ state = torch.load(checkpoint, map_location="cpu", weights_only=False)["state_dict"]
191
+ os.makedirs(os.path.dirname(os.path.abspath(destination)), exist_ok=True)
192
+ save_file({k: v.detach().cpu().contiguous() for k, v in state.items()}, destination)
193
+ print(f"Exported safetensors: {destination}")
194
+ trainer.strategy.barrier()
195
+ return destination
196
+
197
+
198
  @click.command()
199
  @click.option(
200
  "-r",
 
222
  )
223
  @click.option("-nc", "--num-classes", type=int, default=2, show_default=True,
224
  help="Number of head-model outputs (clf + reg).")
225
+ @click.option("-b", "--batch-size", type=click.IntRange(min=1), default=8, show_default=True, help="Batch size.")
226
  @click.option("-f", "--frames-per-clip", type=int, default=32, show_default=True,
227
  help="Frames per clip.")
228
  @click.option(
 
233
  show_default=True,
234
  help="Frame size (H, W).",
235
  )
236
+ @click.option("--max-epochs", type=click.IntRange(min=1), default=10, show_default=True, help="Number of full-train epochs.")
237
  @click.option("--num-workers", type=int, default=16, show_default=True, help="DataLoader workers.")
238
  @click.option(
239
  "--devices",
240
+ type=click.IntRange(min=0),
241
  multiple=True,
242
  default=[0],
243
  show_default=True,
244
+ help="GPU index; repeat for multiple GPUs, e.g. --devices 0 --devices 1.",
245
  )
246
  @click.option("--precision", type=str, default="bf16-mixed", show_default=True, help="Numeric precision mode.")
247
  @click.option(
 
258
  help="Directory with backbone logs (Lightning .ckpt files).",
259
  )
260
  @click.option(
261
+ "--backbone-weights-dir", "--backbone-pt-dir", "backbone_pt_dir",
262
+ type=click.Path(),
263
  default="backbone_weights",
264
  show_default=True,
265
+ help="Directory with backbone .safetensors files (rightBinSyntax_R3D_full_foldXX.safetensors, leftBinSyntax_R3D_full_foldXX.safetensors).",
266
  )
267
  @click.option(
268
+ "--backbone-from-pt/--backbone-from-checkpoints",
269
  is_flag=True,
270
  default=True,
271
  show_default=True,
272
+ help="When enabled, load the backbone from .safetensors files in backbone-pt-dir; otherwise use Lightning logs in backbone-logdir.",
273
  )
274
  @click.option(
275
  "--rnn-folds-dir",
 
290
  is_flag=True,
291
  default=False,
292
  show_default=True,
293
+ help="Legacy raw state_dict flag; safetensors stage transitions detect their format automatically.",
294
  )
295
+ @click.option("--weights-dir", type=click.Path(), default="./trained_weights/rnn",
296
+ show_default=True, help="Directory for exported safetensors weights.")
297
+ @click.option("--pre-epochs", type=click.IntRange(min=1), default=None,
298
+ help="Head-only epochs; defaults to --max-epochs.")
299
  @click.option("--seed", type=int, default=42, show_default=True, help="Random seed.")
300
  def main(
301
  dataset_root: str,
 
308
  video_size: Any,
309
  max_epochs: int,
310
  num_workers: int,
311
+ devices: tuple[int, ...],
312
  precision: str,
313
  logdir: str,
314
  backbone_logdir: str | None,
 
318
  use_weighted_sampler: bool,
319
  pt_weights_format: bool,
320
  seed: int,
321
+ weights_dir: str,
322
+ pre_epochs: int | None,
323
  ):
324
  """Train the RNN head on top of the backbone."""
325
  VARIANTS = "mean_out mean lstm_mean lstm_last gru_mean gru_last bert_mean bert_cls bert_cls2".split()
 
330
  if artery not in ("left", "right"):
331
  raise ValueError(f"Unknown artery '{artery}', expected 'left' or 'right'")
332
 
333
+ if num_classes != 2:
334
+ raise click.BadParameter("Training requires two outputs: classification and regression.", param_hint="--num-classes")
335
  pl.seed_everything(seed)
336
 
337
  imagenet_mean = [0.485, 0.456, 0.406]
 
368
  train_loader_post = make_dataloader(train_set, batch_size, num_workers, use_weighted_sampler)
369
  val_loader = make_dataloader(val_set, 1, num_workers, use_weighted_sampler=False)
370
 
371
+ if len(train_loader_pre) == 0 or len(val_loader) == 0:
372
+ raise click.ClickException("Need at least 2 * batch-size training samples and one validation sample after filtering.")
373
+
374
  x, *_ = next(iter(train_loader_pre))
375
  video_shape = x.shape[2:]
376
  print(f"RNN head input per clip: {video_shape}")
 
389
  phase="full",
390
  )
391
 
392
+ pre_epochs = pre_epochs if pre_epochs is not None else max_epochs
393
  callbacks_pre = make_callbacks(phase="pre")
394
 
395
  model_pre = make_model(
 
397
  lr=1e-4,
398
  variant=variant,
399
  weight_decay=0.01,
400
+ max_epochs=pre_epochs,
401
  weight_path=backbone_weight_path,
402
  pl_weight_path=None,
403
  pt_weights_format=False,
404
  )
405
 
406
  trainer_pre = make_trainer(
407
+ max_epochs=pre_epochs,
408
  logdir=logdir,
409
  logger_name=f"{artery}BinSyntax_R3D_fold{fold:02d}_{variant}_pre",
410
  devices=devices,
 
413
  )
414
  trainer_pre.fit(model_pre, train_dataloaders=train_loader_pre, val_dataloaders=val_loader)
415
 
416
+ pre_weights = export_weights(trainer_pre, os.path.join(trainer_pre.log_dir, "full_model_pre.safetensors"))
417
  callbacks_full = make_callbacks(phase="full")
418
 
419
  model_full = make_model(
 
423
  weight_decay=0.01,
424
  max_epochs=max_epochs,
425
  weight_path=None,
426
+ pl_weight_path=pre_weights,
427
  pt_weights_format=pt_weights_format,
428
  )
429
 
 
436
  callbacks=callbacks_full,
437
  )
438
  trainer_full.fit(model_full, train_dataloaders=train_loader_post, val_dataloaders=val_loader)
439
+ export_weights(trainer_full, os.path.join(weights_dir, f"{artery.capitalize()}BinSyntax_R3D_fold{fold:02d}_{variant}_post_best.safetensors"))
440
 
441
 
442
  if __name__ == "__main__":
full_model_weights/LeftBinSyntax_R3D_fold00_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a1e9b585f99e863620185bc88f724488f0ac09e8cf25aa8ddc9a120fd893a99b
3
- size 133809489
 
 
 
 
full_model_weights/LeftBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d60de48ea47a3fbe516ca5d90ba79ec5d7dea5b04b037df20cf75e3a6f78ad66
3
+ size 133773944
full_model_weights/LeftBinSyntax_R3D_fold01_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6e8132d382b352afd22bb3fe3e1d4d7e3a9781f8a927018db9bc5085d0e8d109
3
- size 133809489
 
 
 
 
full_model_weights/LeftBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:829b51322384437b6838fdc92ac5ca35c0d3de21e00d1ac95985e2ddb436f712
3
+ size 133773944
full_model_weights/LeftBinSyntax_R3D_fold02_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:c18065b289591280a8051af4aa4124ffa03a42df69c876f125be5abaf7912486
3
- size 133809489
 
 
 
 
full_model_weights/LeftBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79bfe68701be33d232037f8755b98729c48944f330b48fb6fa489d8151485221
3
+ size 133773944
full_model_weights/LeftBinSyntax_R3D_fold03_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:cf88400ea1a47d5a376ef9b366d0126036ddd02e3c1ba9071522fbac42b941bc
3
- size 133809489
 
 
 
 
full_model_weights/LeftBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57f5cb930f30d42f16111dc8f66cbd419f6f11adb5bab601ccd8980b763daa93
3
+ size 133773944
full_model_weights/LeftBinSyntax_R3D_fold04_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:eea9012bb3d975ee9cb2d5b651e401c47801400d3a2cc6da04b3c1f761be1793
3
- size 133809489
 
 
 
 
full_model_weights/LeftBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8746300aa112d9077639664754e7c116d13c4ab88fa594eac7ffa1e35bd4dfe
3
+ size 133773944
full_model_weights/RightBinSyntax_R3D_fold00_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:1f47a7bd428011d8570bfcca7b36ff8cc074d07303e0e6477a0b9e398d72bbe2
3
- size 133809614
 
 
 
 
full_model_weights/RightBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b89a9368b9b040e7683b1590468d18d7c77cb44827749bc1ae7c95a7270eb696
3
+ size 133773944
full_model_weights/RightBinSyntax_R3D_fold01_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a3f0857954b5af689d6582fb95bad39f7e9e7575bc49187cc36dbd19211847dc
3
- size 133809614
 
 
 
 
full_model_weights/RightBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca2936688de41045cc1149364275d151c82d5da6d1aa9be123bed086fa3a48a3
3
+ size 133773944
full_model_weights/RightBinSyntax_R3D_fold02_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:59b3b3719e67aed73e8d087f1e748da852f7c30a390610d4b4f676d60fbc3f89
3
- size 133809614
 
 
 
 
full_model_weights/RightBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:804f8a7b1c1bfce0e290b83923f7f81e8043e44af19cef96e3b88af25ba5cec6
3
+ size 133773944
full_model_weights/RightBinSyntax_R3D_fold03_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:15adb5ce5a9f3473dfcead2ac841c3c3e83ef9ad46dea9d4fa7f373e3b0df7c5
3
- size 133809614
 
 
 
 
full_model_weights/RightBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:faf9994b09d27b4b48c7498bb2cbb4dde79636b4e766e6d6ee9f8ff61734ce1c
3
+ size 133773944
full_model_weights/RightBinSyntax_R3D_fold04_lstm_mean_post_best.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:c2312b11b6c865bf8f751a421557b1a9813a33f71906978518588d0a4d193f3e
3
- size 133809614
 
 
 
 
full_model_weights/RightBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:290a6dd922290fde6a4010146015404e4cdb748631bbb578bdbc0a94db025bda
3
+ size 133773944
inference/rnn_apply.py CHANGED
@@ -18,8 +18,6 @@ from full_model.rnn_model import SyntaxLightningModule
18
  from inference.metrics_visualization import visualize_final_syntax_plotly_multi
19
 
20
 
21
- DEVICE = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
22
- print(f"DEVICE: {DEVICE}")
23
 
24
 
25
  def safe_sample_std(values):
@@ -67,7 +65,7 @@ def compute_metrics(y_true, y_pred, thr=22.0):
67
  type=click.Path(exists=True),
68
  default="full_model_weights",
69
  show_default=True,
70
- help="Directory with .pt/.ckpt full-model weights (RNN head + backbone).",
71
  )
72
  @click.option("-v", "--video-size", type=click.Tuple([int, int]), default=(256, 256),
73
  show_default=True, help="Video size (H, W).")
@@ -75,6 +73,7 @@ def compute_metrics(y_true, y_pred, thr=22.0):
75
  show_default=True, help="Frames per clip.")
76
  @click.option("--num-workers", type=int, default=8,
77
  show_default=True, help="Number of DataLoader workers.")
 
78
  @click.option("--seed", type=int, default=42,
79
  show_default=True, help="Random seed.")
80
  @click.option(
@@ -82,7 +81,7 @@ def compute_metrics(y_true, y_pred, thr=22.0):
82
  is_flag=True,
83
  default=True,
84
  show_default=True,
85
- help="Full-model weight format: True uses .pt raw state_dict, False uses Lightning .ckpt.",
86
  )
87
  @click.option("--use-scaling", is_flag=True, default=False,
88
  show_default=True, help="Apply a*x+b scaling from JSON.")
@@ -95,29 +94,35 @@ def compute_metrics(y_true, y_pred, thr=22.0):
95
  show_default=True,
96
  help="Head-model variant: mean, lstm_mean, lstm_last, gru_mean, gru_last, bert_mean, bert_cls, bert_cls2.",
97
  )
98
- @click.option("-e", "--ensemble-name",
99
  help="Ensemble name in metrics.json.")
100
- @click.option("-m", "--metrics-file",
101
  help="JSON file with experiment metrics.")
102
  def main(dataset_paths, dataset_names, postfixes, dataset_root, model_dir, video_size,
103
  frames_per_clip, num_workers, seed, pt_weights_format, use_scaling,
104
- scaling_file, variant, ensemble_name, metrics_file):
105
 
 
 
 
 
106
  pl.seed_everything(seed)
107
  postfix_plotly = "Ensemble"
108
 
109
  model_paths = {
110
  "left": [
111
- os.path.join(model_dir, f"LeftBinSyntax_R3D_fold{fold:02d}_{variant}_post_best.pt")
112
  for fold in range(5)
113
  ],
114
  "right": [
115
- os.path.join(model_dir, f"RightBinSyntax_R3D_fold{fold:02d}_{variant}_post_best.pt")
116
  for fold in range(5)
117
  ],
118
  }
119
 
120
  scaling_params_dict = {}
 
 
121
  if use_scaling:
122
  postfix_plotly += "_scaled"
123
  ensemble_name += "_scaled"
@@ -127,7 +132,7 @@ def main(dataset_paths, dataset_names, postfixes, dataset_root, model_dir, video
127
  scaling_params_dict = json.load(f)
128
  print(f"Loaded scaling from {scaling_path}")
129
  else:
130
- print(f"⚠️ Scaling file not found: {scaling_path}")
131
 
132
  ensemble_results = {
133
  "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
@@ -146,7 +151,7 @@ def main(dataset_paths, dataset_names, postfixes, dataset_root, model_dir, video
146
  return params[0], params[1]
147
 
148
  for dataset_path, dataset_name, postfix in zip(dataset_paths, dataset_names, postfixes):
149
- abs_dataset_path = os.path.join(dataset_root, dataset_path)
150
  results_file = os.path.join("results", f"{postfix}.json")
151
 
152
  if os.path.exists(results_file):
@@ -161,12 +166,12 @@ def main(dataset_paths, dataset_names, postfixes, dataset_root, model_dir, video
161
  left_preds_all, left_sids = run_artery(
162
  abs_dataset_path, "left", model_paths["left"],
163
  video_size, frames_per_clip, num_workers,
164
- variant=variant, pt_weights_format=pt_weights_format,
165
  )
166
  right_preds_all, right_sids = run_artery(
167
  abs_dataset_path, "right", model_paths["right"],
168
  video_size, frames_per_clip, num_workers,
169
- variant=variant, pt_weights_format=pt_weights_format,
170
  )
171
  assert left_sids == right_sids
172
 
@@ -263,8 +268,9 @@ def main(dataset_paths, dataset_names, postfixes, dataset_root, model_dir, video
263
 
264
 
265
  def run_artery(dataset_path, artery, model_paths, video_size, frames_per_clip,
266
- num_workers, variant: str, pt_weights_format: bool):
267
  """Inference for one artery across five folds."""
 
268
  imagenet_mean = [0.485, 0.456, 0.406]
269
  imagenet_std = [0.229, 0.224, 0.225]
270
  test_transform = T.Compose([
@@ -295,8 +301,7 @@ def run_artery(dataset_path, artery, model_paths, video_size, frames_per_clip,
295
  models = []
296
  for path in model_paths:
297
  if not os.path.exists(path):
298
- print(f"⚠️ Model not found: {path}")
299
- continue
300
 
301
  model = SyntaxLightningModule(
302
  num_classes=2,
@@ -308,7 +313,7 @@ def run_artery(dataset_path, artery, model_paths, video_size, frames_per_clip,
308
  pl_weight_path=path,
309
  pt_weights_format=pt_weights_format,
310
  )
311
- model.to(DEVICE)
312
  model.eval()
313
  models.append(model)
314
 
@@ -321,7 +326,7 @@ def run_artery(dataset_path, artery, model_paths, video_size, frames_per_clip,
321
  if len(x.shape) == 1:
322
  val_syntax_list = [0.0] * len(models)
323
  else:
324
- x = x.to(DEVICE)
325
  val_syntax_list = []
326
  for model in models:
327
  y_hat = model(x)
 
18
  from inference.metrics_visualization import visualize_final_syntax_plotly_multi
19
 
20
 
 
 
21
 
22
 
23
  def safe_sample_std(values):
 
65
  type=click.Path(exists=True),
66
  default="full_model_weights",
67
  show_default=True,
68
+ help="Directory with .safetensors full-model weights (RNN head + backbone).",
69
  )
70
  @click.option("-v", "--video-size", type=click.Tuple([int, int]), default=(256, 256),
71
  show_default=True, help="Video size (H, W).")
 
73
  show_default=True, help="Frames per clip.")
74
  @click.option("--num-workers", type=int, default=8,
75
  show_default=True, help="Number of DataLoader workers.")
76
+ @click.option("--device", default=None, help="Inference device, e.g. cuda:0, cuda:1 or cpu; default: cuda:0 when available.")
77
  @click.option("--seed", type=int, default=42,
78
  show_default=True, help="Random seed.")
79
  @click.option(
 
81
  is_flag=True,
82
  default=True,
83
  show_default=True,
84
+ help="Legacy format: True uses .pt raw state_dict, False uses Lightning .ckpt. Safetensors is detected automatically.",
85
  )
86
  @click.option("--use-scaling", is_flag=True, default=False,
87
  show_default=True, help="Apply a*x+b scaling from JSON.")
 
94
  show_default=True,
95
  help="Head-model variant: mean, lstm_mean, lstm_last, gru_mean, gru_last, bert_mean, bert_cls, bert_cls2.",
96
  )
97
+ @click.option("-e", "--ensemble-name", default="Ensemble",
98
  help="Ensemble name in metrics.json.")
99
+ @click.option("-m", "--metrics-file", default="metrics.json",
100
  help="JSON file with experiment metrics.")
101
  def main(dataset_paths, dataset_names, postfixes, dataset_root, model_dir, video_size,
102
  frames_per_clip, num_workers, seed, pt_weights_format, use_scaling,
103
+ scaling_file, variant, ensemble_name, metrics_file, device):
104
 
105
+ if not dataset_paths or not (len(dataset_paths) == len(dataset_names) == len(postfixes)):
106
+ raise click.UsageError("Provide equally many -d, -n and -p arguments (one set per dataset).")
107
+ device = torch.device(device or ("cuda:0" if torch.cuda.is_available() else "cpu"))
108
+ print(f"DEVICE: {device}")
109
  pl.seed_everything(seed)
110
  postfix_plotly = "Ensemble"
111
 
112
  model_paths = {
113
  "left": [
114
+ os.path.join(model_dir, f"LeftBinSyntax_R3D_fold{fold:02d}_{variant}_post_best.safetensors")
115
  for fold in range(5)
116
  ],
117
  "right": [
118
+ os.path.join(model_dir, f"RightBinSyntax_R3D_fold{fold:02d}_{variant}_post_best.safetensors")
119
  for fold in range(5)
120
  ],
121
  }
122
 
123
  scaling_params_dict = {}
124
+ if use_scaling and not scaling_file:
125
+ raise click.UsageError("--use-scaling requires --scaling-file.")
126
  if use_scaling:
127
  postfix_plotly += "_scaled"
128
  ensemble_name += "_scaled"
 
132
  scaling_params_dict = json.load(f)
133
  print(f"Loaded scaling from {scaling_path}")
134
  else:
135
+ raise FileNotFoundError(f"Scaling file not found: {scaling_path}")
136
 
137
  ensemble_results = {
138
  "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
 
151
  return params[0], params[1]
152
 
153
  for dataset_path, dataset_name, postfix in zip(dataset_paths, dataset_names, postfixes):
154
+ abs_dataset_path = os.path.abspath(os.path.join(dataset_root, dataset_path))
155
  results_file = os.path.join("results", f"{postfix}.json")
156
 
157
  if os.path.exists(results_file):
 
166
  left_preds_all, left_sids = run_artery(
167
  abs_dataset_path, "left", model_paths["left"],
168
  video_size, frames_per_clip, num_workers,
169
+ variant=variant, pt_weights_format=pt_weights_format, device=device,
170
  )
171
  right_preds_all, right_sids = run_artery(
172
  abs_dataset_path, "right", model_paths["right"],
173
  video_size, frames_per_clip, num_workers,
174
+ variant=variant, pt_weights_format=pt_weights_format, device=device,
175
  )
176
  assert left_sids == right_sids
177
 
 
268
 
269
 
270
  def run_artery(dataset_path, artery, model_paths, video_size, frames_per_clip,
271
+ num_workers, variant: str, pt_weights_format: bool, device=None):
272
  """Inference for one artery across five folds."""
273
+ device = torch.device(device or ("cuda:0" if torch.cuda.is_available() else "cpu"))
274
  imagenet_mean = [0.485, 0.456, 0.406]
275
  imagenet_std = [0.229, 0.224, 0.225]
276
  test_transform = T.Compose([
 
301
  models = []
302
  for path in model_paths:
303
  if not os.path.exists(path):
304
+ raise FileNotFoundError(f"Model not found: {path}")
 
305
 
306
  model = SyntaxLightningModule(
307
  num_classes=2,
 
313
  pl_weight_path=path,
314
  pt_weights_format=pt_weights_format,
315
  )
316
+ model.to(device)
317
  model.eval()
318
  models.append(model)
319
 
 
326
  if len(x.shape) == 1:
327
  val_syntax_list = [0.0] * len(models)
328
  else:
329
+ x = x.to(device)
330
  val_syntax_list = []
331
  for model in models:
332
  y_hat = model(x)
requirements.txt CHANGED
@@ -6,7 +6,7 @@ pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo@main#egg=pyt
6
 
7
  # Data processing
8
  numpy>=1.24.0
9
- scikit-learn>=1.3.0
10
  tqdm>=4.65.0
11
  pydicom>=2.4.0
12
  python-gdcm>=3.0.10
@@ -19,3 +19,5 @@ tensorboardX>=2.6
19
 
20
  # CLI & Utilities
21
  click>=8.1.0
 
 
 
6
 
7
  # Data processing
8
  numpy>=1.24.0
9
+ scikit-learn>=1.4.0
10
  tqdm>=4.65.0
11
  pydicom>=2.4.0
12
  python-gdcm>=3.0.10
 
19
 
20
  # CLI & Utilities
21
  click>=8.1.0
22
+
23
+ safetensors>=0.8.0