MesserMMP commited on
Commit
c2d9714
·
1 Parent(s): 3ca1d12

add full model files

Browse files
full_model/rnn_dataset.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import pydicom
4
+ import numpy as np
5
+ import torch
6
+
7
+ from typing import Callable, Optional, Tuple
8
+
9
+ from torch import Tensor
10
+ from torch.utils.data import Dataset
11
+ from sklearn.preprocessing import RobustScaler
12
+
13
+ DTYPE = torch.float16
14
+
15
+
16
+ class SyntaxDataset(Dataset):
17
+ def __init__(
18
+ self,
19
+ root: str, # dataset dir
20
+ meta: str, # metadata
21
+ train: bool, # training mode
22
+ length: int, # video length
23
+ label: str, # label field name
24
+ artery: str, # left or right artery
25
+ inference: bool = False,
26
+ validation: bool = False,
27
+ transform: Optional[Callable] = None
28
+
29
+ ) -> None:
30
+ self.root = root
31
+ self.train = train
32
+ self.length = length
33
+ self.label = label
34
+ self.artery = artery
35
+ self.inference = inference
36
+ self.transform = transform
37
+ self.validation = validation
38
+ meta_path = meta if os.path.isabs(meta) else os.path.join(root, meta)
39
+
40
+ with open(meta_path) as f:
41
+ dataset = json.load(f)
42
+
43
+ if not self.inference:
44
+ dataset = [rec for rec in dataset if len(rec[f"videos_{artery}"]) > 0]
45
+
46
+ if validation:
47
+ dataset = [rec for rec in dataset if rec[self.label] > 0]
48
+
49
+ self.dataset = dataset
50
+
51
+ artery_bin = {"left":0, "right":1}.get(artery.lower())
52
+ if artery_bin is None:
53
+ raise ValueError(f"Unknown artery '{artery}'")
54
+
55
+ self.artery_bin = artery_bin
56
+
57
+ def __len__(self):
58
+ return len(self.dataset)
59
+
60
+
61
+ def get_sample_weights(self):
62
+ # пороги для левой (0) и правой (1) артерии
63
+ bin_thresholds = {
64
+ 0: [0, 5, 10, 15], # левая
65
+ 1: [0, 2, 5, 8], # правая
66
+ }
67
+
68
+ # выберем пороги для текущей артерии
69
+ thresholds = bin_thresholds[self.artery_bin]
70
+
71
+ thr0, thr1, thr2, thr3 = thresholds
72
+
73
+ # разбиваем датасет по интервалам
74
+ self.dataset_0 = [rec for rec in self.dataset if rec[self.label] == thr0]
75
+ self.dataset_1 = [rec for rec in self.dataset if thr0 < rec[self.label] <= thr1]
76
+ self.dataset_2 = [rec for rec in self.dataset if thr1 < rec[self.label] <= thr2]
77
+ self.dataset_3 = [rec for rec in self.dataset if thr2 < rec[self.label] <= thr3]
78
+ self.dataset_4 = [rec for rec in self.dataset if rec[self.label] > thr3]
79
+
80
+
81
+ total = len(self.dataset_0) + len(self.dataset_1) + len(self.dataset_2) + len(self.dataset_3) + len(self.dataset_4)
82
+
83
+
84
+ def safe_weight(count):
85
+ return total / count if count > 0 else 0.0
86
+
87
+ self.weights_0 = safe_weight(len(self.dataset_0))
88
+ self.weights_1 = safe_weight(len(self.dataset_1))
89
+ self.weights_2 = safe_weight(len(self.dataset_2))
90
+ self.weights_3 = safe_weight(len(self.dataset_3))
91
+ self.weights_4 = safe_weight(len(self.dataset_4))
92
+
93
+ # print("Weights: ", self.weights_0, self.weights_1, self.weights_2, self.weights_3, self.weights_4)
94
+ print("Counts: ", len(self.dataset_0), len(self.dataset_1), len(self.dataset_2), len(self.dataset_3), len(self.dataset_4))
95
+
96
+ weights = []
97
+ for rec in self.dataset:
98
+ syntax_score = rec[self.label]
99
+ if syntax_score == thr0:
100
+ weights.append(self.weights_0)
101
+ elif thr0 < syntax_score <= thr1:
102
+ weights.append(self.weights_1)
103
+ elif thr1 < syntax_score <= thr2:
104
+ weights.append(self.weights_2)
105
+ elif thr2 < syntax_score <= thr3:
106
+ weights.append(self.weights_3)
107
+ else:
108
+ weights.append(self.weights_4)
109
+
110
+ self.weights = torch.tensor(weights, dtype=DTYPE)
111
+ return self.weights
112
+
113
+ def __getitem__(self, idx: int) -> Tuple[Tensor, int]:
114
+
115
+ rec = self.dataset[idx]
116
+ suid = rec["study_uid"]
117
+
118
+
119
+ if self.label:
120
+ bin_thresholds = {
121
+ 0: 15, # левая
122
+ 1: 5, # правая
123
+ }
124
+
125
+ label = torch.tensor([int(rec[self.label] > bin_thresholds[self.artery_bin])], dtype=DTYPE)
126
+ target = torch.tensor([np.log(1.0+rec[self.label])], dtype=DTYPE)
127
+ else:
128
+ label = torch.tensor([0], dtype=DTYPE)
129
+ target = torch.tensor([0], dtype=DTYPE)
130
+
131
+ nv = len(rec[f"videos_{self.artery}"])
132
+ if self.inference:
133
+ if nv == 0:
134
+ return 0, label, target, suid
135
+ seq = range(nv)
136
+ else:
137
+ seq = torch.randint(low=0, high=nv, size = (4,))
138
+
139
+ videos = []
140
+ for vi in seq:
141
+ video_rec = rec[f"videos_{self.artery}"][vi]
142
+ path = video_rec["path"]
143
+ if os.path.isabs(path):
144
+ full_path = path
145
+ else:
146
+ full_path = os.path.join(self.root, path)
147
+
148
+ video = pydicom.dcmread(full_path).pixel_array # Time, HW or WH
149
+
150
+ if video.dtype == np.uint16:
151
+ vmax = np.max(video)
152
+ assert vmax > 0
153
+ video = video.astype(np.float32)
154
+ video = video * (255. / vmax)
155
+ video = video.astype(np.uint8)
156
+ assert video.dtype == np.uint8
157
+
158
+ while len(video) < self.length:
159
+ video = np.concatenate([video, video])
160
+ t = len(video)
161
+ if self.train:
162
+ begin = torch.randint(low=0, high=t-self.length+1, size=(1,))
163
+ end = begin + self.length
164
+ video = video[begin:end, :, :]
165
+ else:
166
+ begin = (t - self.length) // 2
167
+ end = begin + self.length
168
+ video = video[begin:end, :, :]
169
+
170
+ video = torch.tensor(np.stack([video, video, video], axis=-1))
171
+
172
+ if self.transform is not None:
173
+ video = self.transform(video)
174
+ videos.append(video)
175
+ videos = torch.stack(videos, dim=0)
176
+
177
+
178
+ return videos, label, target, suid
full_model/rnn_model.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from torch import nn, optim
5
+ import lightning.pytorch as pl
6
+ import torchvision.models.video as tvmv
7
+ import sklearn.metrics as skm
8
+ import numpy as np
9
+
10
+
11
+ class SyntaxLightningModule(pl.LightningModule):
12
+ """
13
+ Полная модель: 3D-ResNet backbone + RNN/Transformer head для SYNTAX score.
14
+
15
+ Варианты head (variant):
16
+ - mean_out: среднее по выходам backbone
17
+ - mean: среднее эмбеддингов + FC
18
+ - lstm_mean/lstm_last: LSTM (mean/last)
19
+ - gru_mean/gru_last: GRU (mean/last)
20
+ - bert_mean/bert_cls/bert_cls2: Transformer encoder
21
+ """
22
+
23
+ SUPPORTED_VARIANTS = [
24
+ "mean_out", "mean", "lstm_mean", "lstm_last",
25
+ "gru_mean", "gru_last", "bert_mean", "bert_cls", "bert_cls2"
26
+ ]
27
+
28
+ def __init__(
29
+ self,
30
+ num_classes: int,
31
+ lr: float,
32
+ variant: str,
33
+ weight_decay: float = 0.0,
34
+ max_epochs: int = None,
35
+ weight_path: str = None, # путь к backbone-чекпоинту (.ckpt)
36
+ pl_weight_path: str = None, # путь к полной модели (.ckpt или .pt)
37
+ pt_weights_format: bool = False, # True → .pt формат (torch.save), False → Lightning .ckpt
38
+ sigma_a: float = 0.0,
39
+ sigma_b: float = 1.0,
40
+ **kwargs,
41
+ ):
42
+ super().__init__()
43
+ self.save_hyperparameters()
44
+
45
+ # Проверяем вариант head
46
+ if variant not in self.SUPPORTED_VARIANTS:
47
+ raise ValueError(f"variant must be one of {self.SUPPORTED_VARIANTS}")
48
+
49
+ self.num_classes = num_classes
50
+ self.variant = variant
51
+ self.lr = lr
52
+ self.weight_decay = weight_decay
53
+ self.max_epochs = max_epochs
54
+ self.sigma_a = sigma_a
55
+ self.sigma_b = sigma_b
56
+
57
+ # Backbone: 3D-ResNet
58
+ self.model = tvmv.r3d_18(weights=tvmv.R3D_18_Weights.DEFAULT)
59
+ in_features = self.model.fc.in_features
60
+
61
+ # Для большинства head заменяем fc на Identity (эмбеддинги)
62
+ if variant != "mean_out":
63
+ self.model.fc = nn.Identity()
64
+ else:
65
+ # mean_out использует финальные logits backbone
66
+ self.model.fc = nn.Linear(in_features, 2, bias=True)
67
+
68
+ # Загрузка backbone (если передан weight_path)
69
+ if weight_path is not None:
70
+ print(f"Loading backbone weights from {weight_path}")
71
+ self.load_weights_backbone(weight_path, self.model)
72
+
73
+ # Инициализация head в зависимости от variant
74
+ self._init_head(in_features, num_classes)
75
+
76
+ # Загрузка полной модели (если передан pl_weight_path)
77
+ if pl_weight_path is not None:
78
+ print(f"Loading full model weights from {pl_weight_path} (pt_format={pt_weights_format})")
79
+ self.load_full_model(pl_weight_path, pt_weights_format)
80
+
81
+ # Лоссы
82
+ self.loss_clf = nn.BCEWithLogitsLoss(reduction="none")
83
+ self.loss_reg = nn.MSELoss(reduction="none")
84
+
85
+ # Буферы метрик
86
+ self.y_val, self.p_val, self.r_val = [], [], []
87
+ self.ty_val, self.tp_val = [], []
88
+
89
+ def _init_head(self, in_features: int, num_classes: int):
90
+ """Инициализация head в зависимости от variant."""
91
+ if self.variant == "mean_out":
92
+ return # используем self.model.fc
93
+
94
+ elif self.variant in ("gru_mean", "gru_last"):
95
+ self.rnn = nn.GRU(in_features, in_features // 4, batch_first=True)
96
+ self.dropout = nn.Dropout(0.2)
97
+ self.fc = nn.Linear(in_features // 4, num_classes, bias=True)
98
+
99
+ elif self.variant in ("lstm_mean", "lstm_last"):
100
+ self.lstm = nn.LSTM(
101
+ input_size=in_features,
102
+ hidden_size=in_features // 4,
103
+ proj_size=num_classes,
104
+ batch_first=True,
105
+ )
106
+
107
+ elif self.variant == "mean":
108
+ self.fc = nn.Linear(in_features, num_classes, bias=True)
109
+
110
+ elif self.variant in ("bert_mean", "bert_cls", "bert_cls2"):
111
+ encoder_layer = nn.TransformerEncoderLayer(
112
+ d_model=in_features,
113
+ nhead=4,
114
+ batch_first=True,
115
+ dim_feedforward=in_features // 4,
116
+ )
117
+ self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=1)
118
+ self.dropout = nn.Dropout(0.2)
119
+ self.fc = nn.Linear(in_features, num_classes, bias=True)
120
+ if self.variant == "bert_cls2":
121
+ self.cls = nn.Parameter(torch.randn(1, 1, in_features))
122
+
123
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
124
+ """
125
+ x: (batch, N_videos, C, T, H, W)
126
+ → (batch, N_videos, embed_dim) → head → (batch, num_classes)
127
+ """
128
+ batch_size, seq_len, *video_shape = x.shape
129
+ x = torch.flatten(x, start_dim=0, end_dim=1) # (batch*seq, C, T, H, W)
130
+ x = self.model(x) # (batch*seq, embed_dim)
131
+ x = torch.unflatten(x, 0, (batch_size, seq_len)) # (batch, seq, embed_dim)
132
+
133
+ # Head
134
+ if self.variant == "mean_out":
135
+ x = torch.mean(x, dim=1) # mean по последовательности
136
+
137
+ elif self.variant in ("gru_mean", "gru_last"):
138
+ all_outs, last_out = self.rnn(x)
139
+ x = torch.mean(all_outs, dim=1) if self.variant == "gru_mean" else last_out
140
+ x = self.dropout(x)
141
+ x = self.fc(x)
142
+
143
+ elif self.variant in ("lstm_mean", "lstm_last"):
144
+ all_outs, (last_out, _) = self.lstm(x)
145
+ x = torch.mean(all_outs, dim=1) if self.variant == "lstm_mean" else last_out
146
+
147
+ elif self.variant == "mean":
148
+ x = torch.mean(x, dim=1)
149
+ x = self.fc(x)
150
+
151
+ elif self.variant in ("bert_mean", "bert_cls", "bert_cls2"):
152
+ if self.variant == "bert_cls":
153
+ x = F.pad(x, (0, 0, 1, 0), "constant", 0) # prepend CLS
154
+ elif self.variant == "bert_cls2":
155
+ bs = x.size(0)
156
+ x = torch.cat([self.cls.expand(bs, -1, -1), x], dim=1)
157
+ x = self.encoder(x)
158
+ x = torch.mean(x, dim=1) if self.variant == "bert_mean" else x[:, 0, :]
159
+ x = self.dropout(x)
160
+ x = self.fc(x)
161
+
162
+ return x
163
+
164
+ def training_step(self, batch, batch_idx):
165
+ x, y, target, path = batch
166
+ y_hat = self(x)
167
+ yp_clf, yp_reg = y_hat[:, 0:1], y_hat[:, 1:]
168
+
169
+ # BCE с down-weight для отрицательных примеров
170
+ weights_clf = torch.where(y > 0, 1.0, 0.45)
171
+ clf_loss = (self.loss_clf(yp_clf, y) * weights_clf).mean()
172
+
173
+ # Регрессия с вариабельностью
174
+ reg_loss_raw = self.loss_reg(yp_reg, target)
175
+ sigma = self.sigma_a * target + self.sigma_b
176
+ reg_loss = (reg_loss_raw / (sigma ** 2)).mean()
177
+
178
+ loss = clf_loss + 0.5 * reg_loss
179
+
180
+ # Логирование
181
+ y_pred = torch.sigmoid(yp_clf)
182
+ y_bin = torch.round(y.detach().cpu()).int()
183
+ y_pred_bin = torch.round(y_pred.detach().cpu()).int()
184
+
185
+ self.log("train_clf_loss", clf_loss, prog_bar=True, sync_dist=True)
186
+ self.log("train_val_loss", reg_loss, prog_bar=True, sync_dist=True)
187
+ self.log("train_full_loss", loss, prog_bar=True, sync_dist=True)
188
+ self.log("train_f1", skm.f1_score(y_bin, y_pred_bin, zero_division=0),
189
+ prog_bar=True, sync_dist=True)
190
+ self.log("train_acc", skm.accuracy_score(y_bin, y_pred_bin),
191
+ prog_bar=True, sync_dist=True)
192
+
193
+ return loss
194
+
195
+ def validation_step(self, batch, batch_idx):
196
+ x, y, target, path = batch
197
+ y_hat = self(x)
198
+ yp_clf, yp_reg = y_hat[:, 0:1], y_hat[:, 1:]
199
+
200
+ # Аккумулируем для метрик
201
+ y_pred = torch.sigmoid(yp_clf)
202
+ self.y_val.append(int(y[..., 0].cpu()))
203
+ self.p_val.append(float(y_pred[..., 0].cpu()))
204
+ self.r_val.append(round(float(y_pred[..., 0].cpu())))
205
+ self.ty_val.append(float(target[..., 0].cpu()))
206
+ self.tp_val.append(float(yp_reg[..., 0].cpu()))
207
+
208
+ # Лосс (тот же, что и в train)
209
+ clf_loss = self.loss_clf(yp_clf, y).mean()
210
+ reg_loss_raw = self.loss_reg(yp_reg, target)
211
+ sigma = self.sigma_a * target + self.sigma_b
212
+ reg_loss = (reg_loss_raw / (sigma ** 2)).mean()
213
+ loss = clf_loss + 0.5 * reg_loss
214
+
215
+ return loss
216
+
217
+ def on_validation_epoch_end(self):
218
+ try:
219
+ auc = skm.roc_auc_score(self.y_val, self.p_val)
220
+ f1 = skm.f1_score(self.y_val, self.r_val, zero_division=0)
221
+ acc = skm.accuracy_score(self.y_val, self.r_val)
222
+ mae = skm.mean_absolute_error(self.y_val, self.r_val)
223
+ rmse = skm.root_mean_squared_error(self.ty_val, self.tp_val)
224
+
225
+ self.log("val_auc", auc, prog_bar=True, sync_dist=True)
226
+ self.log("val_f1", f1, prog_bar=True, sync_dist=True)
227
+ self.log("val_acc", acc, prog_bar=True, sync_dist=True)
228
+ self.log("val_mae", mae, prog_bar=True, sync_dist=True)
229
+ self.log("val_rmse", rmse, prog_bar=True, sync_dist=True)
230
+
231
+ except ValueError as err:
232
+ print(err)
233
+ print("Y_VAL", self.y_val[:10], "...")
234
+ print("P_VAL", self.p_val[:10], "...")
235
+
236
+ # Очистка буферов
237
+ [buf.clear() for buf in [self.y_val, self.p_val, self.r_val, self.ty_val, self.tp_val]]
238
+
239
+ def on_train_epoch_end(self):
240
+ lr = self.optimizers().optimizer.param_groups[0]["lr"]
241
+ self.log("lr", lr, on_epoch=True, sync_dist=True)
242
+
243
+ def configure_optimizers(self):
244
+ # Pretrain (заморозка backbone) или full fine-tune
245
+ if self.weight_path:
246
+ # Pretrain: обучаем только head
247
+ trainable_modules = self._get_trainable_head_modules()
248
+ for param in self.parameters():
249
+ param.requires_grad = False
250
+ for module in trainable_modules:
251
+ for param in module.parameters():
252
+ param.requires_grad = True
253
+ params = [p for module in trainable_modules for p in module.parameters()]
254
+ else:
255
+ # Full: всё
256
+ for param in self.parameters():
257
+ param.requires_grad = True
258
+ params = self.parameters()
259
+
260
+ optimizer = optim.Adam(params, lr=self.lr, weight_decay=self.weight_decay)
261
+ if self.max_epochs:
262
+ scheduler = optim.lr_scheduler.OneCycleLR(
263
+ optimizer, max_lr=self.lr, total_steps=self.max_epochs
264
+ )
265
+ return [optimizer], [scheduler]
266
+ return optimizer
267
+
268
+ def _get_trainable_head_modules(self):
269
+ """Возвращает список обучаемых модулей head."""
270
+ if self.variant == "mean_out":
271
+ return [self.model.fc]
272
+ elif self.variant in ("gru_mean", "gru_last"):
273
+ return [self.rnn, self.fc]
274
+ elif self.variant in ("lstm_mean", "lstm_last"):
275
+ return [self.lstm]
276
+ elif self.variant == "mean":
277
+ return [self.fc]
278
+ elif self.variant in ("bert_mean", "bert_cls", "bert_cls2"):
279
+ modules = [self.encoder, self.fc]
280
+ if self.variant == "bert_cls2":
281
+ modules.append(self.cls)
282
+ return modules
283
+ return []
284
+
285
+ def load_weights_backbone(self, weight_path: str, model):
286
+ """Загрузка backbone из Lightning .ckpt."""
287
+ ckpt = torch.load(weight_path, map_location="cpu", weights_only=False)
288
+ state_dict = ckpt["state_dict"]
289
+ new_state_dict = {k.replace("model.", ""): v for k, v in state_dict.items()}
290
+ model.load_state_dict(new_state_dict, strict=False)
291
+
292
+ def load_full_model(self, pl_weight_path: str, pt_weights_format: bool):
293
+ """Загрузка полной модели (.ckpt или .pt)."""
294
+ if pt_weights_format:
295
+ # .pt формат (torch.save)
296
+ state_dict = torch.load(pl_weight_path, map_location="cpu", weights_only=False)
297
+ else:
298
+ # Lightning .ckpt
299
+ ckpt = torch.load(pl_weight_path, map_location="cpu", weights_only=False)
300
+ state_dict = ckpt["state_dict"]
301
+
302
+ # Backbone
303
+ self.load_weights(state_dict, self.model, "model")
304
+
305
+ # Head
306
+ trainable_modules = self._get_trainable_head_modules()
307
+ for module in trainable_modules:
308
+ prefix = module.__class__.__name__.lower()
309
+ self.load_weights(state_dict, module, prefix)
310
+
311
+ if self.variant == "bert_cls2":
312
+ if "cls" in state_dict:
313
+ self.cls.data.copy_(state_dict["cls"])
314
+
315
+ def load_weights(self, state_dict, module, prefix: str):
316
+ """Загрузка весов модуля по префиксу."""
317
+ module_state = {
318
+ k.replace(f"{prefix}.", ""): v
319
+ for k, v in state_dict.items()
320
+ if k.startswith(prefix)
321
+ }
322
+ missing, unexpected = module.load_state_dict(module_state, strict=False)
323
+ if missing:
324
+ print(f"Missing keys for {prefix}: {len(missing)}")
325
+ if unexpected:
326
+ print(f"Unexpected keys for {prefix}: {len(unexpected)}")
327
+
328
+ def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any:
329
+ x, y, target, path = batch
330
+ y_hat = self(x)
331
+ yp_clf, yp_reg = y_hat[:, 0:1], y_hat[:, 1:]
332
+ y_prob = torch.sigmoid(yp_clf)
333
+ return {
334
+ "y": y,
335
+ "y_pred": torch.round(y_prob),
336
+ "y_prob": y_prob,
337
+ "y_reg": yp_reg,
338
+ "target": target,
339
+ }
full_model/rnn_train.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import torch
4
+ import numpy as np
5
+ import click
6
+ import lightning.pytorch as pl
7
+ from lightning.pytorch.loggers import TensorBoardLogger
8
+ from lightning.pytorch.callbacks import ModelCheckpoint, LearningRateMonitor
9
+
10
+ from pytorchvideo.transforms import Normalize, Permute, RandAugment
11
+ from torch.utils.data import DataLoader
12
+ from torchvision.transforms import transforms as T
13
+ from torchvision.transforms._transforms_video import ToTensorVideo
14
+ from torchvision.transforms import InterpolationMode
15
+
16
+ from rnn_dataset import SyntaxDataset
17
+ from rnn_model import SyntaxLightningModule
18
+
19
+ torch.set_float32_matmul_precision("medium")
20
+
21
+
22
+ """
23
+ Обучение RNN-head поверх предобученного backbone для SYNTAX score.
24
+
25
+ Этапы:
26
+ 1) pretrain — обучается только head (backbone заморожен);
27
+ 2) full — fine-tuning всей модели (backbone + head).
28
+ """
29
+
30
+
31
+ def get_transforms(video_size, imagenet_mean, imagenet_std, train=True):
32
+ """Трансформации для видео (train с аугментациями, test без)."""
33
+ interpolation_choices = [InterpolationMode.BILINEAR, InterpolationMode.BICUBIC]
34
+ if train:
35
+ return T.Compose([
36
+ ToTensorVideo(),
37
+ Permute(dims=[1, 0, 2, 3]), # C,T,H,W → T,C,H,W
38
+ RandAugment(magnitude=10, num_layers=2),
39
+ T.RandomHorizontalFlip(),
40
+ Permute(dims=[1, 0, 2, 3]), # T,C,H,W → C,T,H,W
41
+ T.RandomChoice([
42
+ T.Resize(size=video_size, interpolation=interp, antialias=True)
43
+ for interp in interpolation_choices
44
+ ]),
45
+ Normalize(mean=imagenet_mean, std=imagenet_std),
46
+ ])
47
+ return T.Compose([
48
+ ToTensorVideo(),
49
+ T.Resize(size=video_size, interpolation=InterpolationMode.BICUBIC, antialias=True),
50
+ Normalize(mean=imagenet_mean, std=imagenet_std),
51
+ ])
52
+
53
+
54
+ def make_dataloader(dataset, batch_size, num_workers):
55
+ """DataLoader с shuffle (sampler закомментирован)."""
56
+ # dataset.get_sample_weights() # можно включить WeightedRandomSampler
57
+ return DataLoader(
58
+ dataset,
59
+ batch_size=batch_size,
60
+ num_workers=num_workers,
61
+ shuffle=True if not dataset.inference else False,
62
+ drop_last=True,
63
+ pin_memory=True,
64
+ )
65
+
66
+
67
+ def make_model(num_classes, video_shape, lr, variant, weight_decay, max_epochs,
68
+ weight_path=None, pl_weight_path=None, pt_weights_format=False):
69
+ """Создание SyntaxLightningModule."""
70
+ return SyntaxLightningModule(
71
+ num_classes=num_classes,
72
+ lr=lr,
73
+ variant=variant,
74
+ weight_decay=weight_decay,
75
+ max_epochs=max_epochs,
76
+ weight_path=weight_path,
77
+ pl_weight_path=pl_weight_path,
78
+ pt_weights_format=pt_weights_format,
79
+ )
80
+
81
+
82
+ def make_callbacks(artery: str, fold: int, phase: str):
83
+ """Callbacks: LR monitor + checkpoint по val_mae."""
84
+ lr_monitor = LearningRateMonitor(logging_interval="epoch")
85
+ if phase == "pre":
86
+ checkpoint = ModelCheckpoint(
87
+ monitor="val_mae",
88
+ save_top_k=1,
89
+ mode="min",
90
+ filename="model-{epoch:02d}-{val_rmse:.3f}",
91
+ save_last=True,
92
+ )
93
+ elif phase == "full":
94
+ checkpoint = ModelCheckpoint(
95
+ monitor="val_mae",
96
+ save_top_k=3,
97
+ mode="min",
98
+ filename="model-{epoch:02d}-{val_rmse:.3f}",
99
+ save_last=True,
100
+ )
101
+ else:
102
+ raise ValueError(f"phase must be 'pre' or 'full'")
103
+ return [lr_monitor, checkpoint]
104
+
105
+
106
+ def make_trainer(max_epochs, logger_name, callbacks):
107
+ """Lightning Trainer с TensorBoard."""
108
+ logger = TensorBoardLogger(save_dir="rnn_logs", name=logger_name)
109
+ trainer = pl.Trainer(
110
+ max_epochs=max_epochs,
111
+ accelerator="gpu",
112
+ devices=1, # легко поменять
113
+ strategy="ddp_find_unused_parameters_true",
114
+ precision="bf16-mixed",
115
+ callbacks=callbacks,
116
+ log_every_n_steps=10,
117
+ logger=logger,
118
+ )
119
+ return trainer
120
+
121
+
122
+ @click.command()
123
+ @click.option(
124
+ "-r", "--dataset-root", type=click.Path(exists=True), required=True,
125
+ help="Корень датасета (где лежат folds/*.json и DICOM).",
126
+ )
127
+ @click.option("--fold", type=int, default=0, help="Номер фолда (0-4).")
128
+ @click.option("-a", "--artery", type=str, default="right", help="'left' или 'right'.")
129
+ @click.option("--variant", type=str, default="lstm_mean", help="Тип head (lstm_mean и др.).")
130
+ @click.option("-nc", "--num-classes", type=int, default=2)
131
+ @click.option("-b", "--batch-size", type=int, default=8)
132
+ @click.option("-f", "--frames-per-clip", type=int, default=32)
133
+ @click.option("-v", "--video-size", type=click.Tuple([int, int]), default=(256, 256))
134
+ @click.option("--max-epochs", type=int, default=10)
135
+ @click.option("--num-workers", type=int, default=8)
136
+ @click.option("--fast-dev-run", is_flag=True)
137
+ @click.option("--seed", type=int, default=42)
138
+ @click.option("--backbone-ckpt", type=str, help="Путь к backbone-чекпоинту для pretrain.")
139
+ def main(
140
+ dataset_root, fold, artery, variant, num_classes, batch_size, frames_per_clip,
141
+ video_size, max_epochs, num_workers, fast_dev_run, seed, backbone_ckpt,
142
+ ):
143
+ pl.seed_everything(seed)
144
+ artery = artery.lower()
145
+ artery_bin = {"left": 0, "right": 1}[artery]
146
+
147
+ print(f"Training {variant} head for {artery} artery, fold {fold}")
148
+
149
+ imagenet_mean = [0.485, 0.456, 0.406]
150
+ imagenet_std = [0.229, 0.224, 0.225]
151
+
152
+ # Datasets с относительными путями
153
+ train_meta = os.path.join("rnn_folds", f"step2_rnn_fold{fold:02d}_train.json")
154
+ val_meta = os.path.join("rnn_folds", f"step2_rnn_fold{fold:02d}_eval.json")
155
+
156
+ train_set = SyntaxDataset(
157
+ root=dataset_root,
158
+ meta=train_meta,
159
+ train=True,
160
+ length=frames_per_clip,
161
+ label=f"syntax_{artery}",
162
+ artery=artery,
163
+ transform=get_transforms(video_size, imagenet_mean, imagenet_std, train=True),
164
+ )
165
+ val_set = SyntaxDataset(
166
+ root=dataset_root,
167
+ meta=val_meta,
168
+ train=False,
169
+ length=frames_per_clip,
170
+ label=f"syntax_{artery}",
171
+ artery=artery,
172
+ validation=True,
173
+ transform=get_transforms(video_size, imagenet_mean, imagenet_std, train=False),
174
+ )
175
+
176
+ # DataLoaders
177
+ train_loader_pre = make_dataloader(train_set, batch_size * 2, num_workers)
178
+ train_loader_post = make_dataloader(train_set, batch_size, num_workers)
179
+ val_loader = make_dataloader(val_set, 1, num_workers)
180
+
181
+ # Форма видео
182
+ x, *_ = next(iter(train_loader_pre))
183
+ video_shape = x.shape[1:]
184
+
185
+ # Pretrain head
186
+ callbacks_pre = make_callbacks(artery, fold, "pre")
187
+ model_pre = make_model(
188
+ num_classes, video_shape, lr=1e-4, variant=variant,
189
+ weight_decay=0.01, max_epochs=max_epochs, weight_path=backbone_ckpt,
190
+ )
191
+ trainer_pre = make_trainer(max_epochs, f"{artery}_{variant}_pre_fold{fold:02d}", callbacks_pre)
192
+ trainer_pre.fit(model_pre, train_loader_pre, val_loader)
193
+
194
+ # Full fine-tune
195
+ callbacks_full = make_callbacks(artery, fold, "full")
196
+ model_full = make_model(
197
+ num_classes, video_shape, lr=2e-5, variant=variant,
198
+ weight_decay=0.01, max_epochs=max_epochs,
199
+ pl_weight_path=trainer_pre.checkpoint_callback.best_model_path,
200
+ )
201
+ trainer_full = make_trainer(max_epochs, f"{artery}_{variant}_full_fold{fold:02d}", callbacks_full)
202
+ trainer_full.fit(model_full, train_loader_post, val_loader)
203
+
204
+
205
+ if __name__ == "__main__":
206
+ main()