Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4f1999da0 | ||
|
|
49065737a1 | ||
|
|
ae59da2457 | ||
|
|
f15d8b34ea | ||
|
|
ef9a168bca | ||
|
|
3d55dce049 | ||
|
|
e0c9101da2 | ||
|
|
cf68b03ca7 | ||
|
|
3c7d73e74b |
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
# --- START OF FILE engine_finetune (1).py (MODIFIED) ---
|
# engine_finetune.py
|
||||||
|
|
||||||
import torch.distributed as dist
|
import torch.distributed as dist
|
||||||
import math
|
import math
|
||||||
@@ -10,12 +10,10 @@ import pandas as pd
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import os
|
import os
|
||||||
|
|
||||||
# Assuming these imports are correct in your project structure
|
|
||||||
import NormWear.downstream_pipeline.analysis as analysis
|
import NormWear.downstream_pipeline.analysis as analysis
|
||||||
import NormWear.pretrain_pipeline.misc as misc
|
import NormWear.pretrain_pipeline.misc as misc
|
||||||
import NormWear.modules.lr_sched as lr_sched
|
import NormWear.modules.lr_sched as lr_sched
|
||||||
|
|
||||||
|
|
||||||
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
|
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
|
||||||
data_loader: Iterable, optimizer: torch.optim.Optimizer,
|
data_loader: Iterable, optimizer: torch.optim.Optimizer,
|
||||||
device: torch.device, epoch: int, loss_scaler, max_norm: Optional[float] = None,
|
device: torch.device, epoch: int, loss_scaler, max_norm: Optional[float] = None,
|
||||||
@@ -23,8 +21,7 @@ def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
|
|||||||
args=None):
|
args=None):
|
||||||
model.train(True)
|
model.train(True)
|
||||||
metric_logger = misc.MetricLogger(delimiter=" ")
|
metric_logger = misc.MetricLogger(delimiter=" ")
|
||||||
metric_logger.add_meter('lr', misc.SmoothedValue(
|
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
|
||||||
window_size=1, fmt='{value:.6f}'))
|
|
||||||
header = 'Epoch: [{}]'.format(epoch)
|
header = 'Epoch: [{}]'.format(epoch)
|
||||||
print_freq = 20
|
print_freq = 20
|
||||||
accum_iter = args.accum_iter if args else 1
|
accum_iter = args.accum_iter if args else 1
|
||||||
@@ -33,49 +30,55 @@ def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
|
|||||||
if log_writer is not None:
|
if log_writer is not None:
|
||||||
print('log_dir: {}'.format(log_writer.log_dir))
|
print('log_dir: {}'.format(log_writer.log_dir))
|
||||||
|
|
||||||
|
# [新增] 确定混合精度类型
|
||||||
|
dtype = torch.bfloat16 if args.precision == 'bf16' and torch.cuda.is_bf16_supported() else torch.float16
|
||||||
|
if args.precision == 'fp32': dtype = torch.float32
|
||||||
|
|
||||||
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
||||||
# Adjust learning rate
|
|
||||||
if args and (data_iter_step % accum_iter == 0):
|
if args and (data_iter_step % accum_iter == 0):
|
||||||
# Note: The original code had a check for lr_sched, which is good practice.
|
|
||||||
if lr_sched:
|
if lr_sched:
|
||||||
current_progress = data_iter_step / len(data_loader) + epoch
|
current_progress = data_iter_step / len(data_loader) + epoch
|
||||||
lr_sched.adjust_learning_rate(
|
lr_sched.adjust_learning_rate(optimizer, current_progress, args)
|
||||||
optimizer, current_progress, args)
|
|
||||||
|
|
||||||
samples_cwt = batch['input_cwt'].to(device, non_blocking=True)
|
samples_cwt = batch['input_cwt'].to(device, non_blocking=True)
|
||||||
samples_1d = batch['input_1d'].to(device, non_blocking=True)
|
samples_1d = batch['input_1d'].to(device, non_blocking=True)
|
||||||
targets = batch['label'].to(device, non_blocking=True)
|
targets = batch['label'].to(device, non_blocking=True)
|
||||||
with torch.amp.autocast(device_type=device.type, enabled=args.use_amp):
|
|
||||||
|
# [修改] 使用正确的 dtype
|
||||||
|
with torch.amp.autocast(device_type=device.type, enabled=args.use_amp, dtype=dtype):
|
||||||
outputs, z = model(samples_cwt, samples_1d)
|
outputs, z = model(samples_cwt, samples_1d)
|
||||||
loss = criterion(outputs, targets)
|
loss = criterion(outputs, targets)
|
||||||
|
|
||||||
loss_value = loss.item()
|
loss_value = loss.item()
|
||||||
if not math.isfinite(loss_value):
|
if not math.isfinite(loss_value):
|
||||||
print(
|
print(f"Loss is {loss_value}, stopping training at Epoch {epoch}, Step {data_iter_step}")
|
||||||
f"Loss is {loss_value}, stopping training at Epoch {epoch}, Step {data_iter_step}")
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
loss_to_scale = loss / accum_iter
|
loss_to_scale = loss / accum_iter
|
||||||
|
|
||||||
# Using the callable NativeScaler for cleaner code
|
# [修改] 适配 HFR 的梯度裁剪逻辑
|
||||||
loss_scaler(
|
if loss_scaler is not None:
|
||||||
loss_to_scale,
|
loss_scaler(
|
||||||
optimizer,
|
loss_to_scale,
|
||||||
clip_grad=max_norm,
|
optimizer,
|
||||||
parameters=model.parameters(),
|
clip_grad=max_norm,
|
||||||
update_grad=(data_iter_step + 1) % accum_iter == 0
|
parameters=model.parameters(),
|
||||||
)
|
update_grad=(data_iter_step + 1) % accum_iter == 0
|
||||||
|
)
|
||||||
if (data_iter_step + 1) % accum_iter == 0:
|
else:
|
||||||
optimizer.zero_grad()
|
loss_to_scale.backward()
|
||||||
|
if (data_iter_step + 1) % accum_iter == 0:
|
||||||
|
if max_norm is not None:
|
||||||
|
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
|
||||||
|
optimizer.step()
|
||||||
|
optimizer.zero_grad()
|
||||||
|
|
||||||
metric_logger.update(loss=loss_value)
|
metric_logger.update(loss=loss_value)
|
||||||
current_lr = optimizer.param_groups[0]["lr"]
|
current_lr = optimizer.param_groups[0]["lr"]
|
||||||
metric_logger.update(lr=current_lr)
|
metric_logger.update(lr=current_lr)
|
||||||
|
|
||||||
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
|
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
|
||||||
epoch_1000x = int(
|
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
|
||||||
(data_iter_step / len(data_loader) + epoch) * 1000)
|
|
||||||
log_writer.add_scalar('train/loss', loss_value, epoch_1000x)
|
log_writer.add_scalar('train/loss', loss_value, epoch_1000x)
|
||||||
log_writer.add_scalar('train/lr', current_lr, epoch_1000x)
|
log_writer.add_scalar('train/lr', current_lr, epoch_1000x)
|
||||||
|
|
||||||
@@ -83,10 +86,8 @@ def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
|
|||||||
print("Averaged stats for epoch {}:".format(epoch), metric_logger)
|
print("Averaged stats for epoch {}:".format(epoch), metric_logger)
|
||||||
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, epoch=None, plot_save_dir=None):
|
def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, epoch=None, plot_save_dir=None):
|
||||||
# The 'analysis' module might not be available, handle it gracefully.
|
|
||||||
try:
|
try:
|
||||||
analyzer = analysis.Analyzer(print_conf_mat=print_analyzer)
|
analyzer = analysis.Analyzer(print_conf_mat=print_analyzer)
|
||||||
except (NameError, AttributeError):
|
except (NameError, AttributeError):
|
||||||
@@ -101,6 +102,10 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
all_session_ids = []
|
all_session_ids = []
|
||||||
all_sample_ids = []
|
all_sample_ids = []
|
||||||
|
|
||||||
|
# [新增] 确定混合精度类型
|
||||||
|
dtype = torch.bfloat16 if args.precision == 'bf16' and torch.cuda.is_bf16_supported() else torch.float16
|
||||||
|
if args.precision == 'fp32': dtype = torch.float32
|
||||||
|
|
||||||
for batch_content in metric_logger.log_every(data_loader, 10, header):
|
for batch_content in metric_logger.log_every(data_loader, 10, header):
|
||||||
images_cwt = batch_content['input_cwt'].to(device, non_blocking=True)
|
images_cwt = batch_content['input_cwt'].to(device, non_blocking=True)
|
||||||
images_1d = batch_content['input_1d'].to(device, non_blocking=True)
|
images_1d = batch_content['input_1d'].to(device, non_blocking=True)
|
||||||
@@ -108,7 +113,7 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
session_ids = batch_content['session_id']
|
session_ids = batch_content['session_id']
|
||||||
sample_ids = batch_content['sample_id']
|
sample_ids = batch_content['sample_id']
|
||||||
|
|
||||||
with torch.amp.autocast(device_type=device.type, enabled=args.use_amp):
|
with torch.amp.autocast(device_type=device.type, enabled=args.use_amp, dtype=dtype):
|
||||||
output, z = model(images_cwt, images_1d)
|
output, z = model(images_cwt, images_1d)
|
||||||
loss = criterion(output, target)
|
loss = criterion(output, target)
|
||||||
|
|
||||||
@@ -127,10 +132,8 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
|
|
||||||
if misc.is_dist_avail_and_initialized():
|
if misc.is_dist_avail_and_initialized():
|
||||||
dist.barrier()
|
dist.barrier()
|
||||||
predictions_list = [torch.zeros_like(
|
predictions_list = [torch.zeros_like(predictions_cat) for _ in range(misc.get_world_size())]
|
||||||
predictions_cat) for _ in range(misc.get_world_size())]
|
targets_list = [torch.zeros_like(targets_cat) for _ in range(misc.get_world_size())]
|
||||||
targets_list = [torch.zeros_like(targets_cat)
|
|
||||||
for _ in range(misc.get_world_size())]
|
|
||||||
dist.all_gather(predictions_list, predictions_cat)
|
dist.all_gather(predictions_list, predictions_cat)
|
||||||
dist.all_gather(targets_list, targets_cat)
|
dist.all_gather(targets_list, targets_cat)
|
||||||
|
|
||||||
@@ -142,10 +145,8 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
if misc.is_main_process():
|
if misc.is_main_process():
|
||||||
predictions_np = torch.cat(predictions_list, dim=0).cpu().numpy()
|
predictions_np = torch.cat(predictions_list, dim=0).cpu().numpy()
|
||||||
targets_np = torch.cat(targets_list, dim=0).cpu().numpy()
|
targets_np = torch.cat(targets_list, dim=0).cpu().numpy()
|
||||||
all_session_ids = [
|
all_session_ids = [item for sublist in session_ids_list for item in sublist]
|
||||||
item for sublist in session_ids_list for item in sublist]
|
all_sample_ids = [item for sublist in sample_ids_list for item in sublist]
|
||||||
all_sample_ids = [
|
|
||||||
item for sublist in sample_ids_list for item in sublist]
|
|
||||||
else:
|
else:
|
||||||
return {'loss': epoch_loss}, {}
|
return {'loss': epoch_loss}, {}
|
||||||
else:
|
else:
|
||||||
@@ -155,7 +156,6 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
if not misc.is_main_process():
|
if not misc.is_main_process():
|
||||||
return {'loss': epoch_loss}, {}
|
return {'loss': epoch_loss}, {}
|
||||||
|
|
||||||
# Truncate to actual dataset size to handle drop_last=False in distributed mode
|
|
||||||
num_samples = len(data_loader.dataset)
|
num_samples = len(data_loader.dataset)
|
||||||
targets_np = targets_np[:num_samples]
|
targets_np = targets_np[:num_samples]
|
||||||
predictions_np = predictions_np[:num_samples]
|
predictions_np = predictions_np[:num_samples]
|
||||||
@@ -166,8 +166,7 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
per_sample_results = {}
|
per_sample_results = {}
|
||||||
|
|
||||||
if args.task == 'cls' and args.num_classes == 2:
|
if args.task == 'cls' and args.num_classes == 2:
|
||||||
probs_np = torch.nn.functional.softmax(
|
probs_np = torch.nn.functional.softmax(torch.from_numpy(predictions_np), dim=1).cpu().numpy()
|
||||||
torch.from_numpy(predictions_np), dim=1).cpu().numpy()
|
|
||||||
positive_probs = probs_np[:, 1]
|
positive_probs = probs_np[:, 1]
|
||||||
|
|
||||||
best_f1 = 0.0
|
best_f1 = 0.0
|
||||||
@@ -175,32 +174,26 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
thresholds = np.arange(0.05, 0.96, 0.01)
|
thresholds = np.arange(0.05, 0.96, 0.01)
|
||||||
for threshold in thresholds:
|
for threshold in thresholds:
|
||||||
pred_labels_at_thresh = (positive_probs >= threshold).astype(int)
|
pred_labels_at_thresh = (positive_probs >= threshold).astype(int)
|
||||||
f1 = sklearn.metrics.f1_score(
|
f1 = sklearn.metrics.f1_score(targets_np, pred_labels_at_thresh, pos_label=1, zero_division=0)
|
||||||
targets_np, pred_labels_at_thresh, pos_label=1, zero_division=0)
|
|
||||||
if f1 > best_f1:
|
if f1 > best_f1:
|
||||||
best_f1 = f1
|
best_f1 = f1
|
||||||
best_threshold = threshold
|
best_threshold = threshold
|
||||||
|
|
||||||
print(
|
print(f"[*] Optimal threshold search: Best F1-score = {best_f1:.4f} at threshold = {best_threshold:.2f}")
|
||||||
f"[*] Optimal threshold search: Best F1-score = {best_f1:.4f} at threshold = {best_threshold:.2f}")
|
|
||||||
|
|
||||||
pred_labels_np = (positive_probs >= best_threshold).astype(int)
|
pred_labels_np = (positive_probs >= best_threshold).astype(int)
|
||||||
|
|
||||||
accuracy = sklearn.metrics.accuracy_score(targets_np, pred_labels_np)
|
accuracy = sklearn.metrics.accuracy_score(targets_np, pred_labels_np)
|
||||||
precision = sklearn.metrics.precision_score(
|
precision = sklearn.metrics.precision_score(targets_np, pred_labels_np, pos_label=1, zero_division=0)
|
||||||
targets_np, pred_labels_np, pos_label=1, zero_division=0)
|
recall = sklearn.metrics.recall_score(targets_np, pred_labels_np, pos_label=1, zero_division=0)
|
||||||
recall = sklearn.metrics.recall_score(
|
|
||||||
targets_np, pred_labels_np, pos_label=1, zero_division=0)
|
|
||||||
f1 = best_f1
|
f1 = best_f1
|
||||||
|
|
||||||
unique_targets = np.unique(targets_np)
|
unique_targets = np.unique(targets_np)
|
||||||
roc_auc, ap = 0.0, 0.0
|
roc_auc, ap = 0.0, 0.0
|
||||||
if len(unique_targets) > 1:
|
if len(unique_targets) > 1:
|
||||||
try:
|
try:
|
||||||
roc_auc = sklearn.metrics.roc_auc_score(
|
roc_auc = sklearn.metrics.roc_auc_score(targets_np, positive_probs)
|
||||||
targets_np, positive_probs)
|
ap = sklearn.metrics.average_precision_score(targets_np, positive_probs)
|
||||||
ap = sklearn.metrics.average_precision_score(
|
|
||||||
targets_np, positive_probs)
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
print(f"Warning: Could not compute AUC/AP: {e}")
|
print(f"Warning: Could not compute AUC/AP: {e}")
|
||||||
|
|
||||||
@@ -210,10 +203,8 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
'best_threshold': best_threshold
|
'best_threshold': best_threshold
|
||||||
})
|
})
|
||||||
|
|
||||||
print(
|
print(f"* Test Metrics (Optimal Threshold): Loss {metrics_dict['loss']:.4f}, Accuracy {accuracy:.4f}, ROC_AUC {roc_auc:.4f}, AP {ap:.4f}")
|
||||||
f"* Test Metrics (Optimal Threshold): Loss {metrics_dict['loss']:.4f}, Accuracy {accuracy:.4f}, ROC_AUC {roc_auc:.4f}, AP {ap:.4f}")
|
print(f"* Precision {precision:.4f}, Recall {recall:.4f}, F1-Score {f1:.4f}")
|
||||||
print(
|
|
||||||
f"* Precision {precision:.4f}, Recall {recall:.4f}, F1-Score {f1:.4f}")
|
|
||||||
|
|
||||||
per_sample_results = {
|
per_sample_results = {
|
||||||
'session_id': all_session_ids, 'sample_id': all_sample_ids,
|
'session_id': all_session_ids, 'sample_id': all_sample_ids,
|
||||||
@@ -222,33 +213,25 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
if analyzer:
|
if analyzer:
|
||||||
classification_metrics = analyzer.analyze_classification(
|
classification_metrics = analyzer.analyze_classification(pred_labels_np, targets_np, np.arange(args.num_classes))
|
||||||
pred_labels_np, targets_np, np.arange(args.num_classes))
|
|
||||||
metrics_dict.update(classification_metrics)
|
metrics_dict.update(classification_metrics)
|
||||||
|
|
||||||
elif args.task == 'cls':
|
elif args.task == 'cls':
|
||||||
probs_np = torch.nn.functional.softmax(
|
probs_np = torch.nn.functional.softmax(torch.from_numpy(predictions_np), dim=1).cpu().numpy()
|
||||||
torch.from_numpy(predictions_np), dim=1).cpu().numpy()
|
|
||||||
pred_labels_np = np.argmax(probs_np, axis=1)
|
pred_labels_np = np.argmax(probs_np, axis=1)
|
||||||
metrics_dict['accuracy'] = np.mean(pred_labels_np == targets_np)
|
metrics_dict['accuracy'] = np.mean(pred_labels_np == targets_np)
|
||||||
|
|
||||||
elif args.task == 'reg':
|
elif args.task == 'reg':
|
||||||
# Assuming predictions_np is the output for regression
|
|
||||||
mae = sklearn.metrics.mean_absolute_error(targets_np, predictions_np)
|
mae = sklearn.metrics.mean_absolute_error(targets_np, predictions_np)
|
||||||
metrics_dict['mae'] = mae
|
metrics_dict['mae'] = mae
|
||||||
|
|
||||||
# --- [OPTIMIZED] Save raw, per-sample data for accurate plotting ---
|
|
||||||
if plot_save_dir and misc.is_main_process() and args.task == 'cls' and args.num_classes == 2:
|
if plot_save_dir and misc.is_main_process() and args.task == 'cls' and args.num_classes == 2:
|
||||||
raw_df = pd.DataFrame({
|
raw_df = pd.DataFrame({
|
||||||
'true_label': targets_np,
|
'true_label': targets_np,
|
||||||
'positive_prob': positive_probs
|
'positive_prob': positive_probs
|
||||||
})
|
})
|
||||||
raw_output_path = os.path.join(
|
raw_output_path = os.path.join(plot_save_dir, f'raw_predictions_epoch_{epoch}.csv')
|
||||||
plot_save_dir, f'raw_predictions_epoch_{epoch}.csv')
|
|
||||||
raw_df.to_csv(raw_output_path, index=False)
|
raw_df.to_csv(raw_output_path, index=False)
|
||||||
print(f"[*] Saved RAW per-sample predictions to {raw_output_path}")
|
print(f"[*] Saved RAW per-sample predictions to {raw_output_path}")
|
||||||
# --- [OPTIMIZED END] ---
|
|
||||||
|
|
||||||
return metrics_dict, per_sample_results
|
return metrics_dict, per_sample_results
|
||||||
|
|
||||||
# --- END OF FILE engine_finetune (1).py (MODIFIED) ---
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
# inference.py
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import os
|
import os
|
||||||
import pickle
|
import pickle
|
||||||
@@ -6,23 +8,17 @@ import torch.nn.functional as F
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
import json
|
import json
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# 从您的项目中导入所有必要的模块 (这部分保持不变)
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
from NormWear.modules.normwear import NormWear
|
from NormWear.modules.normwear import NormWear
|
||||||
from NormWear.modules.custom_blocks import OneD_CNN_Extractor
|
|
||||||
# 导入您最终的微调模型类 (FinetuneModel 或 FusionModel)
|
|
||||||
from NormWear.downstream_pipeline.main_finetune import FinetuneModel
|
from NormWear.downstream_pipeline.main_finetune import FinetuneModel
|
||||||
# 导入数据预处理函数
|
from NormWear.pretrain_pipeline.dataset import cwt_wrap
|
||||||
from NormWear.pretrain_pipeline.dataset import cwt_wrap, ricker_wavelet, cwt_ricker
|
|
||||||
|
|
||||||
class Predictor:
|
class Predictor:
|
||||||
def __init__(self, checkpoint_path, args):
|
def __init__(self, checkpoint_path, args):
|
||||||
self.device = torch.device(args.device)
|
self.device = torch.device(args.device)
|
||||||
self.args = args
|
self.args = args
|
||||||
|
|
||||||
# 1. 实例化一个与微调时完全相同的模型结构
|
print("Instantiating HFR model...")
|
||||||
print("Instantiating model...")
|
|
||||||
backbone = NormWear(
|
backbone = NormWear(
|
||||||
img_size=(args.window_size, 65),
|
img_size=(args.window_size, 65),
|
||||||
patch_size=(9, 5),
|
patch_size=(9, 5),
|
||||||
@@ -33,7 +29,12 @@ class Predictor:
|
|||||||
decoder_embed_dim=args.decoder_embed_dim,
|
decoder_embed_dim=args.decoder_embed_dim,
|
||||||
decoder_depth=args.decoder_depth,
|
decoder_depth=args.decoder_depth,
|
||||||
decoder_num_heads=args.decoder_num_heads,
|
decoder_num_heads=args.decoder_num_heads,
|
||||||
nvar=args.n_vars
|
nvar=args.n_vars,
|
||||||
|
# [新增] HFR 参数
|
||||||
|
fluid_kernel_size=args.fluid_kernel_size,
|
||||||
|
modality_dropout_prob=0.0, # 推理时不需要 dropout
|
||||||
|
loss_weight_1d_token=0.3,
|
||||||
|
loss_weight_1d_signal=0.3
|
||||||
)
|
)
|
||||||
|
|
||||||
self.model = FinetuneModel(
|
self.model = FinetuneModel(
|
||||||
@@ -43,16 +44,15 @@ class Predictor:
|
|||||||
num_classes=args.num_classes
|
num_classes=args.num_classes
|
||||||
).to(self.device)
|
).to(self.device)
|
||||||
|
|
||||||
# 2. 加载微调好的模型权重
|
|
||||||
print(f"Loading fine-tuned checkpoint from: {checkpoint_path}")
|
print(f"Loading fine-tuned checkpoint from: {checkpoint_path}")
|
||||||
checkpoint = torch.load(checkpoint_path, map_location='cpu')
|
checkpoint = torch.load(checkpoint_path, map_location='cpu')
|
||||||
|
state_dict = checkpoint.get('model', checkpoint)
|
||||||
# 兼容DDP和非DDP保存的权重
|
|
||||||
state_dict = checkpoint['model']
|
# 处理 DDP 前缀
|
||||||
new_state_dict = {}
|
new_state_dict = {}
|
||||||
for k, v in state_dict.items():
|
for k, v in state_dict.items():
|
||||||
if k.startswith('module.'):
|
if k.startswith('module.'):
|
||||||
new_state_dict[k[7:]] = v # remove `module.`
|
new_state_dict[k[7:]] = v
|
||||||
else:
|
else:
|
||||||
new_state_dict[k] = v
|
new_state_dict[k] = v
|
||||||
|
|
||||||
@@ -60,20 +60,12 @@ class Predictor:
|
|||||||
print("Model loading message:", msg)
|
print("Model loading message:", msg)
|
||||||
|
|
||||||
self.model.eval()
|
self.model.eval()
|
||||||
|
|
||||||
# 3. 初始化CWT参数
|
|
||||||
self.cwt_scales = torch.arange(1, 65 + 1).to(self.device)
|
self.cwt_scales = torch.arange(1, 65 + 1).to(self.device)
|
||||||
|
|
||||||
|
# ... (_create_windows, _preprocess_window, predict 方法保持不变) ...
|
||||||
def _create_windows(self, long_signal):
|
def _create_windows(self, long_signal):
|
||||||
"""
|
|
||||||
使用滑动窗口将长序列切分成多个片段。
|
|
||||||
long_signal: [n_vars, L_long]
|
|
||||||
"""
|
|
||||||
n_vars, L_long = long_signal.shape
|
n_vars, L_long = long_signal.shape
|
||||||
|
|
||||||
if L_long < self.args.window_size:
|
if L_long < self.args.window_size:
|
||||||
print(
|
|
||||||
f"Warning: Signal length ({L_long}) is shorter than window size ({self.args.window_size}). Padding signal.")
|
|
||||||
pad_size = self.args.window_size - L_long
|
pad_size = self.args.window_size - L_long
|
||||||
pad_values = long_signal[:, 0:1].expand(-1, pad_size)
|
pad_values = long_signal[:, 0:1].expand(-1, pad_size)
|
||||||
long_signal = torch.cat((pad_values, long_signal), dim=1)
|
long_signal = torch.cat((pad_values, long_signal), dim=1)
|
||||||
@@ -81,64 +73,39 @@ class Predictor:
|
|||||||
|
|
||||||
windows = []
|
windows = []
|
||||||
start_indices = []
|
start_indices = []
|
||||||
|
|
||||||
num_windows = (L_long - self.args.window_size) // self.args.stride + 1
|
num_windows = (L_long - self.args.window_size) // self.args.stride + 1
|
||||||
for i in range(num_windows):
|
for i in range(num_windows):
|
||||||
start = i * self.args.stride
|
start = i * self.args.stride
|
||||||
end = start + self.args.window_size
|
end = start + self.args.window_size
|
||||||
windows.append(long_signal[:, start:end])
|
windows.append(long_signal[:, start:end])
|
||||||
start_indices.append(start)
|
start_indices.append(start)
|
||||||
|
|
||||||
return windows, start_indices
|
return windows, start_indices
|
||||||
|
|
||||||
def _preprocess_window(self, signal_window):
|
def _preprocess_window(self, signal_window):
|
||||||
"""
|
|
||||||
对单个窗口进行与训练时相同的预处理。
|
|
||||||
"""
|
|
||||||
# 1. 标准化1D信号
|
|
||||||
signal_1d = torch.nan_to_num(signal_window, 0.0)
|
signal_1d = torch.nan_to_num(signal_window, 0.0)
|
||||||
mean = torch.mean(signal_1d, dim=1, keepdim=True)
|
mean = torch.mean(signal_1d, dim=1, keepdim=True)
|
||||||
std = torch.std(signal_1d, dim=1, keepdim=True)
|
std = torch.std(signal_1d, dim=1, keepdim=True)
|
||||||
std[std == 0] = 1.0
|
std[std == 0] = 1.0
|
||||||
processed_signal_1d = (signal_1d - mean) / (std + 1e-8)
|
processed_signal_1d = (signal_1d - mean) / (std + 1e-8)
|
||||||
|
cwt_image = cwt_wrap(processed_signal_1d.to(self.device), scales=self.cwt_scales)
|
||||||
# 2. CWT变换
|
|
||||||
cwt_image = cwt_wrap(processed_signal_1d.to(
|
|
||||||
self.device), scales=self.cwt_scales)
|
|
||||||
|
|
||||||
return cwt_image, processed_signal_1d.to(self.device)
|
return cwt_image, processed_signal_1d.to(self.device)
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def predict(self, pkl_file_path):
|
def predict(self, pkl_file_path):
|
||||||
"""
|
|
||||||
对单个.pkl文件中的长序列进行推理。
|
|
||||||
"""
|
|
||||||
# 1. 加载数据
|
|
||||||
# 【修改】在循环中打印文件名,而不是在这里
|
|
||||||
with open(pkl_file_path, 'rb') as f:
|
with open(pkl_file_path, 'rb') as f:
|
||||||
data = pickle.load(f)
|
data = pickle.load(f)
|
||||||
|
uid = data.get('uid', os.path.splitext(os.path.basename(pkl_file_path))[0])
|
||||||
uid = data.get('uid', os.path.splitext(
|
|
||||||
os.path.basename(pkl_file_path))[0])
|
|
||||||
long_signal = torch.from_numpy(data['data']).float()
|
long_signal = torch.from_numpy(data['data']).float()
|
||||||
|
|
||||||
# 确保变量数与模型期望的一致
|
|
||||||
if long_signal.shape[0] != self.args.n_vars:
|
if long_signal.shape[0] != self.args.n_vars:
|
||||||
raise ValueError(
|
raise ValueError(f"Input signal has {long_signal.shape[0]} variables, but model expects {self.args.n_vars}.")
|
||||||
f"Input signal has {long_signal.shape[0]} variables, but model expects {self.args.n_vars}.")
|
|
||||||
|
|
||||||
# 2. 创建滑动窗口
|
|
||||||
windows, start_indices = self._create_windows(long_signal)
|
windows, start_indices = self._create_windows(long_signal)
|
||||||
|
|
||||||
# 3. 批量推理
|
|
||||||
results = []
|
results = []
|
||||||
batch_size = self.args.batch_size
|
batch_size = self.args.batch_size
|
||||||
|
|
||||||
# 【修改】为tqdm添加更具体的文件名描述
|
|
||||||
for i in tqdm(range(0, len(windows), batch_size), desc=f"Inferencing on {uid}", leave=False):
|
for i in tqdm(range(0, len(windows), batch_size), desc=f"Inferencing on {uid}", leave=False):
|
||||||
batch_windows = windows[i:i+batch_size]
|
batch_windows = windows[i:i+batch_size]
|
||||||
|
|
||||||
# 预处理当前batch
|
|
||||||
batch_cwt = []
|
batch_cwt = []
|
||||||
batch_1d = []
|
batch_1d = []
|
||||||
for window in batch_windows:
|
for window in batch_windows:
|
||||||
@@ -146,17 +113,12 @@ class Predictor:
|
|||||||
batch_cwt.append(cwt_image)
|
batch_cwt.append(cwt_image)
|
||||||
batch_1d.append(signal_1d)
|
batch_1d.append(signal_1d)
|
||||||
|
|
||||||
# 堆叠成batch张量
|
|
||||||
batch_cwt_tensor = torch.stack(batch_cwt)
|
batch_cwt_tensor = torch.stack(batch_cwt)
|
||||||
batch_1d_tensor = torch.stack(batch_1d)
|
batch_1d_tensor = torch.stack(batch_1d)
|
||||||
|
|
||||||
# 模型推理
|
|
||||||
logits, _ = self.model(batch_cwt_tensor, batch_1d_tensor)
|
logits, _ = self.model(batch_cwt_tensor, batch_1d_tensor)
|
||||||
|
|
||||||
# 计算概率
|
|
||||||
probabilities = F.softmax(logits, dim=1)
|
probabilities = F.softmax(logits, dim=1)
|
||||||
|
|
||||||
# 收集结果
|
|
||||||
for j, prob in enumerate(probabilities):
|
for j, prob in enumerate(probabilities):
|
||||||
window_start = start_indices[i+j]
|
window_start = start_indices[i+j]
|
||||||
window_end = window_start + self.args.window_size
|
window_end = window_start + self.args.window_size
|
||||||
@@ -165,99 +127,54 @@ class Predictor:
|
|||||||
'end_index': window_end,
|
'end_index': window_end,
|
||||||
'probabilities': prob.cpu().numpy().tolist()
|
'probabilities': prob.cpu().numpy().tolist()
|
||||||
})
|
})
|
||||||
|
|
||||||
return {'uid': uid, 'predictions': results}
|
return {'uid': uid, 'predictions': results}
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# 参数解析器 (已修改)
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def get_args_parser():
|
def get_args_parser():
|
||||||
# 【修改】更新脚本描述
|
parser = argparse.ArgumentParser('NormWear HFR Inference', add_help=False)
|
||||||
parser = argparse.ArgumentParser(
|
parser.add_argument('--input_dir', required=True, type=str)
|
||||||
'NormWear Batch Inference Script', add_help=False)
|
parser.add_argument('--checkpoint', required=True, type=str)
|
||||||
|
parser.add_argument('--output_file', required=True, type=str)
|
||||||
# --- 核心参数 (已修改) ---
|
parser.add_argument('--window_size', default=387, type=int)
|
||||||
# 将 --input_file 改为 --input_dir
|
parser.add_argument('--stride', default=100, type=int)
|
||||||
parser.add_argument('--input_dir', required=True, type=str,
|
parser.add_argument('--n_vars', type=int, required=True)
|
||||||
help='Path to the directory containing .pkl files.')
|
parser.add_argument('--num_classes', type=int, required=True)
|
||||||
parser.add_argument('--checkpoint', required=True, type=str,
|
|
||||||
help='Path to the fine-tuned model checkpoint.')
|
|
||||||
parser.add_argument('--output_file', required=True, type=str,
|
|
||||||
help='Path to save the single JSON output file with all predictions.')
|
|
||||||
|
|
||||||
# --- 滑动窗口参数 (保持不变) ---
|
|
||||||
parser.add_argument('--window_size', default=387,
|
|
||||||
type=int, help='Length of the sliding window.')
|
|
||||||
parser.add_argument('--stride', default=100, type=int,
|
|
||||||
help='Stride of the sliding window.')
|
|
||||||
|
|
||||||
# --- 模型架构参数 (保持不变) ---
|
|
||||||
parser.add_argument('--n_vars', type=int, required=True,
|
|
||||||
help='Number of variables in the data.')
|
|
||||||
parser.add_argument('--num_classes', type=int, required=True,
|
|
||||||
help='Number of output classes for the fine-tuned model.')
|
|
||||||
parser.add_argument('--embed_dim', type=int, default=768)
|
parser.add_argument('--embed_dim', type=int, default=768)
|
||||||
parser.add_argument('--depth', type=int, default=12)
|
parser.add_argument('--depth', type=int, default=12)
|
||||||
parser.add_argument('--num_heads', type=int, default=12)
|
parser.add_argument('--num_heads', type=int, default=12)
|
||||||
parser.add_argument('--decoder_embed_dim', type=int, default=512)
|
parser.add_argument('--decoder_embed_dim', type=int, default=512)
|
||||||
parser.add_argument('--decoder_depth', type=int, default=8)
|
parser.add_argument('--decoder_depth', type=int, default=8)
|
||||||
parser.add_argument('--decoder_num_heads', type=int, default=16)
|
parser.add_argument('--decoder_num_heads', type=int, default=16)
|
||||||
|
|
||||||
# --- 运行参数 (保持不变) ---
|
# [新增] HFR 参数
|
||||||
parser.add_argument('--batch_size', default=128,
|
parser.add_argument('--fluid_kernel_size', type=int, default=3)
|
||||||
type=int, help='Batch size for inference.')
|
|
||||||
parser.add_argument('--device', default='cuda', help='Device to use.')
|
parser.add_argument('--batch_size', default=128, type=int)
|
||||||
|
parser.add_argument('--device', default='cuda')
|
||||||
return parser
|
return parser
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# 主函数 (已修改为批处理逻辑)
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def main(args):
|
def main(args):
|
||||||
# 1. 创建推理器实例 (此部分不变)
|
|
||||||
predictor = Predictor(args.checkpoint, args)
|
predictor = Predictor(args.checkpoint, args)
|
||||||
|
|
||||||
# 2. 查找输入文件夹中的所有 .pkl 文件
|
|
||||||
if not os.path.isdir(args.input_dir):
|
if not os.path.isdir(args.input_dir):
|
||||||
print(f"Error: Input directory not found at '{args.input_dir}'")
|
print(f"Error: Input directory not found at '{args.input_dir}'")
|
||||||
return
|
return
|
||||||
|
pkl_files = [os.path.join(args.input_dir, f) for f in os.listdir(args.input_dir) if f.lower().endswith('.pkl')]
|
||||||
pkl_files = [os.path.join(args.input_dir, f) for f in os.listdir(
|
|
||||||
args.input_dir) if f.lower().endswith('.pkl')]
|
|
||||||
|
|
||||||
if not pkl_files:
|
if not pkl_files:
|
||||||
print(f"No .pkl files found in '{args.input_dir}'.")
|
print(f"No .pkl files found in '{args.input_dir}'.")
|
||||||
return
|
return
|
||||||
|
|
||||||
print(f"Found {len(pkl_files)} .pkl files to process.")
|
print(f"Found {len(pkl_files)} .pkl files to process.")
|
||||||
|
|
||||||
# 3. 循环对每个文件进行预测,并收集结果
|
|
||||||
all_results = []
|
all_results = []
|
||||||
# 使用tqdm显示总体进度
|
|
||||||
for pkl_file_path in tqdm(pkl_files, desc="Overall Progress"):
|
for pkl_file_path in tqdm(pkl_files, desc="Overall Progress"):
|
||||||
try:
|
try:
|
||||||
# 调用未修改的 predict 方法处理单个文件
|
|
||||||
result = predictor.predict(pkl_file_path)
|
result = predictor.predict(pkl_file_path)
|
||||||
all_results.append(result)
|
all_results.append(result)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# 如果单个文件处理失败,打印错误并继续
|
print(f"\n!!!!!! Failed to process file: {os.path.basename(pkl_file_path)} !!!!!!")
|
||||||
print(
|
|
||||||
f"\n!!!!!! Failed to process file: {os.path.basename(pkl_file_path)} !!!!!!")
|
|
||||||
print(f"Error: {e}")
|
print(f"Error: {e}")
|
||||||
print("Skipping this file and continuing...")
|
print(f"\nSaving all {len(all_results)} prediction results to {args.output_file}...")
|
||||||
|
|
||||||
# 4. 将所有结果保存到一个JSON文件中
|
|
||||||
print(
|
|
||||||
f"\nSaving all {len(all_results)} prediction results to {args.output_file}...")
|
|
||||||
with open(args.output_file, 'w') as f:
|
with open(args.output_file, 'w') as f:
|
||||||
json.dump(all_results, f, indent=4)
|
json.dump(all_results, f, indent=4)
|
||||||
print("Done!")
|
print("Done!")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
args = get_args_parser().parse_args()
|
args = get_args_parser().parse_args()
|
||||||
main(args)
|
main(args)
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
# --- START OF FILE main_finetune (1).py (MODIFIED) ---
|
# main_finetune.py
|
||||||
|
|
||||||
from NormWear.modules.custom_blocks import OneD_CNN_Extractor
|
from NormWear.modules.custom_blocks import OneD_CNN_Extractor
|
||||||
import argparse
|
import argparse
|
||||||
import datetime
|
import datetime
|
||||||
@@ -7,7 +8,7 @@ import numpy as np
|
|||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import pandas as pd # <-- [ADDED] Import pandas
|
import pandas as pd
|
||||||
import torch
|
import torch
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
@@ -17,7 +18,6 @@ import torch.distributed as dist
|
|||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
from torch.utils.tensorboard import SummaryWriter
|
from torch.utils.tensorboard import SummaryWriter
|
||||||
|
|
||||||
# Assuming project structure allows these imports
|
|
||||||
from .config import DATASET_CONFIG
|
from .config import DATASET_CONFIG
|
||||||
from NormWear.modules.normwear import NormWear
|
from NormWear.modules.normwear import NormWear
|
||||||
from NormWear.modules.head import RegressionHead, MLPClassificationHead, ClassificationHead
|
from NormWear.modules.head import RegressionHead, MLPClassificationHead, ClassificationHead
|
||||||
@@ -31,12 +31,8 @@ from peft import LoraConfig, get_peft_model, TaskType
|
|||||||
class FinetuneModel(nn.Module):
|
class FinetuneModel(nn.Module):
|
||||||
def __init__(self, backbone, num_channel, embed_dim, num_classes):
|
def __init__(self, backbone, num_channel, embed_dim, num_classes):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
# backbone 是完整的、预训练好的、可能被LoRA包装的 NormWear 模型
|
|
||||||
self.backbone = backbone
|
self.backbone = backbone
|
||||||
|
|
||||||
# 分类头,输入维度基于CLS Token
|
|
||||||
head_input_dim = num_channel * embed_dim
|
head_input_dim = num_channel * embed_dim
|
||||||
|
|
||||||
self.finetune_head = nn.Sequential(
|
self.finetune_head = nn.Sequential(
|
||||||
nn.Linear(head_input_dim, head_input_dim // 2),
|
nn.Linear(head_input_dim, head_input_dim // 2),
|
||||||
nn.BatchNorm1d(head_input_dim // 2),
|
nn.BatchNorm1d(head_input_dim // 2),
|
||||||
@@ -46,35 +42,86 @@ class FinetuneModel(nn.Module):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def forward(self, x_cwt, x_1d):
|
def forward(self, x_cwt, x_1d):
|
||||||
# 1. 直接调用统一的融合推理接口
|
|
||||||
z = self.backbone.get_signal_embedding(x_cwt, x_1d)
|
z = self.backbone.get_signal_embedding(x_cwt, x_1d)
|
||||||
|
cls_tokens = z[:, :, 0, :]
|
||||||
# 2. 从特征中提取CLS Token进行分类
|
flat_features = cls_tokens.flatten(1)
|
||||||
# z 形状: [bs, n_vars, num_patches+1, embed_dim]
|
|
||||||
cls_tokens = z[:, :, 0, :] # [bs, n_vars, embed_dim]
|
|
||||||
|
|
||||||
# 3. 展平并送入分类头
|
|
||||||
flat_features = cls_tokens.flatten(1) # [bs, n_vars * embed_dim]
|
|
||||||
logits = self.finetune_head(flat_features)
|
logits = self.finetune_head(flat_features)
|
||||||
|
|
||||||
return logits, flat_features
|
return logits, flat_features
|
||||||
|
|
||||||
|
|
||||||
def str2bool(v):
|
def get_args_parser():
|
||||||
if isinstance(v, bool):
|
parser = argparse.ArgumentParser(
|
||||||
return v
|
'NormWear HFR Fine-tuning', add_help=False)
|
||||||
if v.lower() in ('yes', 'true', 't', 'y', '1'):
|
|
||||||
return True
|
|
||||||
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
|
|
||||||
return False
|
|
||||||
else:
|
|
||||||
raise argparse.ArgumentTypeError('Boolean value expected.')
|
|
||||||
|
|
||||||
|
# --- 核心参数 ---
|
||||||
|
parser.add_argument('--checkpoint', required=True,
|
||||||
|
type=str, help='model checkpoint')
|
||||||
|
parser.add_argument('--ds_name', default='ecg_binary8', type=str)
|
||||||
|
parser.add_argument('--data_dir', default='../data', type=str)
|
||||||
|
parser.add_argument(
|
||||||
|
'--output_dir', default='../data/results_finetune', help='path where to save')
|
||||||
|
parser.add_argument('--log_dir', default='../data/results_finetune/logs',
|
||||||
|
help='path where to tensorboard log')
|
||||||
|
parser.add_argument('--device', default='cuda')
|
||||||
|
parser.add_argument('--eval', action='store_true')
|
||||||
|
|
||||||
def parse_tuple(arg_str):
|
# --- 模型架构参数 (HFR & MAE) ---
|
||||||
if arg_str.startswith('(') and arg_str.endswith(')'):
|
parser.add_argument('--embed_dim', type=int, default=768)
|
||||||
arg_str = arg_str[1:-1]
|
parser.add_argument('--depth', type=int, default=12)
|
||||||
return tuple(map(int, arg_str.split(',')))
|
parser.add_argument('--num_heads', type=int, default=12)
|
||||||
|
parser.add_argument('--decoder_embed_dim', type=int, default=512)
|
||||||
|
parser.add_argument('--decoder_depth', type=int, default=8)
|
||||||
|
parser.add_argument('--decoder_num_heads', type=int, default=16)
|
||||||
|
|
||||||
|
# [HFR 参数]
|
||||||
|
parser.add_argument('--fluid_kernel_size', type=int, default=3)
|
||||||
|
|
||||||
|
# [MAE 参数]
|
||||||
|
parser.add_argument('--modality_dropout', type=float, default=0.15)
|
||||||
|
parser.add_argument('--loss_weight_1d_token', type=float, default=0.3)
|
||||||
|
parser.add_argument('--loss_weight_1d_signal', type=float, default=0.3)
|
||||||
|
|
||||||
|
# --- 训练参数 ---
|
||||||
|
parser.add_argument('--batch_size', default=128, type=int)
|
||||||
|
parser.add_argument('--epochs', default=100, type=int)
|
||||||
|
parser.add_argument('--accum_iter', default=1, type=int)
|
||||||
|
parser.add_argument('--lr', type=float, default=None, metavar='LR')
|
||||||
|
parser.add_argument('--blr', type=float, default=1e-4, metavar='LR')
|
||||||
|
parser.add_argument('--weight_decay', type=float, default=0.05)
|
||||||
|
parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N')
|
||||||
|
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR')
|
||||||
|
parser.add_argument('--use_focal_loss', action='store_true')
|
||||||
|
parser.add_argument('--focal_gamma', type=float, default=2.0)
|
||||||
|
|
||||||
|
# --- 混合精度 ---
|
||||||
|
parser.add_argument('--use_amp', action='store_true')
|
||||||
|
parser.add_argument('--no_amp', action='store_false', dest='use_amp')
|
||||||
|
parser.set_defaults(use_amp=True)
|
||||||
|
parser.add_argument('--precision', default='bf16',
|
||||||
|
type=str, choices=['fp32', 'fp16', 'bf16'])
|
||||||
|
|
||||||
|
parser.add_argument('--remark', default='finetune_hfr',
|
||||||
|
help='A remark for the run')
|
||||||
|
parser.add_argument('--seed', default=42, type=int)
|
||||||
|
parser.add_argument('--num_workers', default=4, type=int)
|
||||||
|
parser.add_argument('--pin_mem', action='store_true')
|
||||||
|
parser.set_defaults(pin_mem=True)
|
||||||
|
parser.add_argument('--world_size', default=1, type=int)
|
||||||
|
parser.add_argument('--local_rank', default=-1, type=int)
|
||||||
|
parser.add_argument('--dist_on_itp', action='store_true')
|
||||||
|
parser.add_argument('--dist_url', default='env://')
|
||||||
|
|
||||||
|
# --- LoRA & Subset ---
|
||||||
|
parser.add_argument('--use_lora', action='store_true')
|
||||||
|
parser.add_argument('--lora_r', type=int, default=16)
|
||||||
|
parser.add_argument('--lora_alpha', type=int, default=32)
|
||||||
|
parser.add_argument('--lora_dropout', type=float, default=0.1)
|
||||||
|
parser.add_argument('--use_hybrid_embed', action='store_true')
|
||||||
|
parser.add_argument('--subset_fraction', type=float, default=1.0)
|
||||||
|
|
||||||
|
return parser
|
||||||
|
|
||||||
|
# ... (FocalLoss, save_prediction_summary 等辅助函数保持不变) ...
|
||||||
|
|
||||||
|
|
||||||
class FocalLoss(nn.Module):
|
class FocalLoss(nn.Module):
|
||||||
@@ -103,88 +150,6 @@ class FocalLoss(nn.Module):
|
|||||||
return loss
|
return loss
|
||||||
|
|
||||||
|
|
||||||
def get_args_parser():
|
|
||||||
# ... (get_args_parser function remains unchanged) ...
|
|
||||||
parser = argparse.ArgumentParser('NormWear Fine-tuning', add_help=False)
|
|
||||||
# dataset args
|
|
||||||
|
|
||||||
parser.add_argument('--checkpoint', default='../data/results/model_moco_amp_float16/run_14/checkpoint-199.pth',
|
|
||||||
type=str, help='model checkpoint for fine-tuning')
|
|
||||||
parser.add_argument('--ds_name', default='ecg_binary8',
|
|
||||||
type=str, help='dataset name')
|
|
||||||
parser.add_argument('--data_dir', default='../data',
|
|
||||||
type=str, help='dataset path')
|
|
||||||
parser.add_argument('--output_dir', default='../data/results_finetune',
|
|
||||||
help='path where to save, empty for no saving')
|
|
||||||
parser.add_argument('--log_dir', default='../data/results_finetune/logs',
|
|
||||||
help='path where to tensorboard log')
|
|
||||||
|
|
||||||
parser.add_argument('--device', default='cuda',
|
|
||||||
help='device to use for training / testing')
|
|
||||||
parser.add_argument('--eval', action='store_true',
|
|
||||||
help='Perform evaluation only')
|
|
||||||
|
|
||||||
# model args
|
|
||||||
parser.add_argument('--embed_dim', type=int, default=768,
|
|
||||||
help='Embedding dimension of the backbone')
|
|
||||||
parser.add_argument('--depth', type=int, default=12,
|
|
||||||
help='Depth of the transformer backbone')
|
|
||||||
parser.add_argument('--num_heads', type=int, default=12,
|
|
||||||
help='Number of attention heads in the backbone')
|
|
||||||
parser.add_argument('--decoder_embed_dim', type=int, default=512,
|
|
||||||
help='Decoder embedding dimension')
|
|
||||||
parser.add_argument('--decoder_depth', type=int, default=8,
|
|
||||||
help='Decoder depth')
|
|
||||||
parser.add_argument('--decoder_num_heads', type=int, default=16,
|
|
||||||
help='Number of attention heads in decoder')
|
|
||||||
# finetune args
|
|
||||||
parser.add_argument('--use_meanpooling', type=int,
|
|
||||||
default=0, help='meanpooling cls fusion in backbone')
|
|
||||||
parser.add_argument('--batch_size', default=128, type=int)
|
|
||||||
parser.add_argument('--epochs', default=100, type=int)
|
|
||||||
parser.add_argument('--accum_iter', default=1, type=int)
|
|
||||||
parser.add_argument('--lr', type=float, default=None, metavar='LR')
|
|
||||||
parser.add_argument('--blr', type=float, default=1e-4, metavar='LR')
|
|
||||||
parser.add_argument('--weight_decay', type=float, default=0.05)
|
|
||||||
parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N')
|
|
||||||
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR')
|
|
||||||
parser.add_argument('--use_focal_loss', action='store_true',
|
|
||||||
help='Use Focal Loss for classification')
|
|
||||||
parser.add_argument('--focal_gamma', type=float,
|
|
||||||
default=2.0, help='Gamma for Focal Loss')
|
|
||||||
parser.add_argument('--use_amp', action='store_true',
|
|
||||||
help='Enable Automatic Mixed Precision (AMP) training.')
|
|
||||||
parser.add_argument('--no_amp', action='store_false', dest='use_amp',
|
|
||||||
help='Disable Automatic Mixed Precision (AMP) training.')
|
|
||||||
parser.set_defaults(use_amp=True)
|
|
||||||
parser.add_argument('--remark', default='finetune_moco',
|
|
||||||
help='A remark for the run')
|
|
||||||
parser.add_argument('--seed', default=42, type=int)
|
|
||||||
parser.add_argument('--num_workers', default=4, type=int)
|
|
||||||
parser.add_argument('--pin_mem', action='store_true')
|
|
||||||
parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
|
|
||||||
parser.set_defaults(pin_mem=True)
|
|
||||||
parser.add_argument('--world_size', default=1, type=int)
|
|
||||||
parser.add_argument('--local_rank', default=-1, type=int)
|
|
||||||
parser.add_argument('--dist_on_itp', action='store_true')
|
|
||||||
parser.add_argument('--dist_url', default='env://')
|
|
||||||
|
|
||||||
# 用于控制架构和数据量的参数
|
|
||||||
parser.add_argument('--use_lora', action='store_true',
|
|
||||||
help='Set this flag to enable LoRA for fine-tuning.')
|
|
||||||
parser.add_argument('--lora_r', type=int, default=16,
|
|
||||||
help='The rank of the LoRA update matrices.')
|
|
||||||
parser.add_argument('--lora_alpha', type=int, default=32,
|
|
||||||
help='The alpha scaling factor for LoRA.')
|
|
||||||
parser.add_argument('--lora_dropout', type=float,
|
|
||||||
default=0.1, help='Dropout for the LoRA layers.')
|
|
||||||
parser.add_argument('--use_hybrid_embed', action='store_true',
|
|
||||||
help='Set this flag to use the Hybrid (CNN+Transformer) embedding architecture.')
|
|
||||||
parser.add_argument('--subset_fraction', type=float, default=1.0,
|
|
||||||
help='Fraction of the training data to use (e.g., 0.1 for 10%).')
|
|
||||||
return parser
|
|
||||||
|
|
||||||
|
|
||||||
def save_prediction_summary(per_sample_results, output_dir, epoch):
|
def save_prediction_summary(per_sample_results, output_dir, epoch):
|
||||||
"""
|
"""
|
||||||
Aggregates per-sample results, calculates statistics, and saves to a CSV file.
|
Aggregates per-sample results, calculates statistics, and saves to a CSV file.
|
||||||
@@ -239,7 +204,7 @@ def main(args):
|
|||||||
np.random.seed(seed)
|
np.random.seed(seed)
|
||||||
cudnn.benchmark = True
|
cudnn.benchmark = True
|
||||||
|
|
||||||
# === [OPTIMIZED] Setup Logging and Directories ===
|
# --- Logging Setup (保持不变) ---
|
||||||
log_writer = None
|
log_writer = None
|
||||||
plot_save_dir = None
|
plot_save_dir = None
|
||||||
summary_save_dir = None
|
summary_save_dir = None
|
||||||
@@ -247,22 +212,17 @@ def main(args):
|
|||||||
run_name = f"{args.remark}_{args.ds_name}_{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}"
|
run_name = f"{args.remark}_{args.ds_name}_{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}"
|
||||||
args.output_dir = os.path.join(args.output_dir, run_name)
|
args.output_dir = os.path.join(args.output_dir, run_name)
|
||||||
args.log_dir = os.path.join(args.output_dir, 'logs')
|
args.log_dir = os.path.join(args.output_dir, 'logs')
|
||||||
|
|
||||||
os.makedirs(args.output_dir, exist_ok=True)
|
os.makedirs(args.output_dir, exist_ok=True)
|
||||||
os.makedirs(args.log_dir, exist_ok=True)
|
os.makedirs(args.log_dir, exist_ok=True)
|
||||||
|
|
||||||
log_writer = SummaryWriter(log_dir=args.log_dir)
|
log_writer = SummaryWriter(log_dir=args.log_dir)
|
||||||
|
|
||||||
# Directory for raw per-sample data (for accurate plotting)
|
|
||||||
plot_save_dir = os.path.join(
|
plot_save_dir = os.path.join(
|
||||||
args.output_dir, 'raw_predictions_per_epoch')
|
args.output_dir, 'raw_predictions_per_epoch')
|
||||||
os.makedirs(plot_save_dir, exist_ok=True)
|
os.makedirs(plot_save_dir, exist_ok=True)
|
||||||
|
|
||||||
# Directory for aggregated summary CSVs
|
|
||||||
summary_save_dir = os.path.join(
|
summary_save_dir = os.path.join(
|
||||||
args.output_dir, 'prediction_summary_csv')
|
args.output_dir, 'prediction_summary_csv')
|
||||||
os.makedirs(summary_save_dir, exist_ok=True)
|
os.makedirs(summary_save_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# --- Dataset Setup (保持不变) ---
|
||||||
dataset_config = DATASET_CONFIG[args.ds_name]
|
dataset_config = DATASET_CONFIG[args.ds_name]
|
||||||
args.num_channel = dataset_config["n_ch"]
|
args.num_channel = dataset_config["n_ch"]
|
||||||
args.num_classes = dataset_config["n_cl"]
|
args.num_classes = dataset_config["n_cl"]
|
||||||
@@ -271,19 +231,14 @@ def main(args):
|
|||||||
args.img_size = (args.max_len - 2, 65)
|
args.img_size = (args.max_len - 2, 65)
|
||||||
train_augmentations = {'noise_std': 0.01, 'scale_range': (0.9, 1.1)}
|
train_augmentations = {'noise_std': 0.01, 'scale_range': (0.9, 1.1)}
|
||||||
train_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name),
|
train_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name),
|
||||||
is_train=True,
|
is_train=True, max_len=args.max_len, use_spec=True,
|
||||||
max_len=args.max_len,
|
augmentations=train_augmentations, img_size=args.img_size,
|
||||||
use_spec=True,
|
|
||||||
augmentations=train_augmentations,
|
|
||||||
img_size=args.img_size,
|
|
||||||
subset_fraction=args.subset_fraction)
|
subset_fraction=args.subset_fraction)
|
||||||
test_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name),
|
test_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name),
|
||||||
is_train=False,
|
is_train=False, max_len=args.max_len, use_spec=True,
|
||||||
max_len=args.max_len,
|
augmentations=None, img_size=args.img_size,
|
||||||
use_spec=True,
|
|
||||||
augmentations=None,
|
|
||||||
img_size=args.img_size,
|
|
||||||
subset_fraction=args.subset_fraction)
|
subset_fraction=args.subset_fraction)
|
||||||
|
|
||||||
if args.distributed:
|
if args.distributed:
|
||||||
sampler_train = torch.utils.data.DistributedSampler(
|
sampler_train = torch.utils.data.DistributedSampler(
|
||||||
train_dataset, shuffle=True)
|
train_dataset, shuffle=True)
|
||||||
@@ -292,15 +247,14 @@ def main(args):
|
|||||||
else:
|
else:
|
||||||
sampler_train = torch.utils.data.RandomSampler(train_dataset)
|
sampler_train = torch.utils.data.RandomSampler(train_dataset)
|
||||||
sampler_val = torch.utils.data.SequentialSampler(test_dataset)
|
sampler_val = torch.utils.data.SequentialSampler(test_dataset)
|
||||||
|
|
||||||
train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=sampler_train,
|
train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=sampler_train,
|
||||||
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True)
|
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True)
|
||||||
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=sampler_val,
|
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=sampler_val,
|
||||||
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
|
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
|
||||||
|
|
||||||
# === Model Loading and Weight Extraction ===
|
# --- Model Loading (HFR Version) ---
|
||||||
print(f"Loading pre-trained MoCo checkpoint from: {args.checkpoint}")
|
print(f"Loading pre-trained HFR checkpoint from: {args.checkpoint}")
|
||||||
print(f"Using Hybrid Embedding: {args.use_hybrid_embed}")
|
|
||||||
print(f"Loading pre-trained 1D+2D fusion model from: {args.checkpoint}")
|
|
||||||
backbone = NormWear(
|
backbone = NormWear(
|
||||||
img_size=(args.max_len, 65),
|
img_size=(args.max_len, 65),
|
||||||
patch_size=(9, 5),
|
patch_size=(9, 5),
|
||||||
@@ -311,26 +265,30 @@ def main(args):
|
|||||||
decoder_embed_dim=args.decoder_embed_dim,
|
decoder_embed_dim=args.decoder_embed_dim,
|
||||||
decoder_depth=args.decoder_depth,
|
decoder_depth=args.decoder_depth,
|
||||||
decoder_num_heads=args.decoder_num_heads,
|
decoder_num_heads=args.decoder_num_heads,
|
||||||
nvar=args.num_channel
|
nvar=args.num_channel,
|
||||||
|
# [新增] HFR & MAE 参数
|
||||||
|
fluid_kernel_size=args.fluid_kernel_size,
|
||||||
|
modality_dropout_prob=args.modality_dropout,
|
||||||
|
loss_weight_1d_token=args.loss_weight_1d_token,
|
||||||
|
loss_weight_1d_signal=args.loss_weight_1d_signal
|
||||||
)
|
)
|
||||||
|
|
||||||
# 3. 加载完整的预训练模型权重
|
|
||||||
checkpoint = torch.load(args.checkpoint, map_location='cpu')
|
checkpoint = torch.load(args.checkpoint, map_location='cpu')
|
||||||
state_dict = checkpoint['model']
|
state_dict = checkpoint.get('model', checkpoint)
|
||||||
# strict=False 会忽略掉优化器等无关的键,以及解码器相关的权重(如果微调时不需要)
|
|
||||||
msg = backbone.load_state_dict(state_dict, strict=False)
|
msg = backbone.load_state_dict(state_dict, strict=False)
|
||||||
print("Backbone loading message:", msg)
|
print("Backbone loading message:", msg)
|
||||||
|
|
||||||
if args.use_lora:
|
if args.use_lora:
|
||||||
print(f"Applying LoRA to the backbone with r={args.lora_r}")
|
print(f"Applying LoRA to the backbone with r={args.lora_r}")
|
||||||
# 冻结所有原始参数
|
|
||||||
for param in backbone.parameters():
|
for param in backbone.parameters():
|
||||||
param.requires_grad = False
|
param.requires_grad = False
|
||||||
|
# HFR 的线性层名称可能不同,请根据 hfr.py 确认
|
||||||
|
# HFR_Mechanism 中有 q_proj, k_proj, v_proj, out_proj
|
||||||
lora_config = LoraConfig(
|
lora_config = LoraConfig(
|
||||||
r=args.lora_r,
|
r=args.lora_r,
|
||||||
lora_alpha=args.lora_alpha,
|
lora_alpha=args.lora_alpha,
|
||||||
target_modules=["attn.qkv", "attn.proj"],
|
target_modules=["attn.q_proj", "attn.k_proj",
|
||||||
|
"attn.v_proj", "attn.out_proj"], # [修改] 适配 HFR 模块名
|
||||||
lora_dropout=args.lora_dropout,
|
lora_dropout=args.lora_dropout,
|
||||||
bias="none",
|
bias="none",
|
||||||
task_type=TaskType.SEQ_CLS
|
task_type=TaskType.SEQ_CLS
|
||||||
@@ -339,14 +297,13 @@ def main(args):
|
|||||||
if misc.is_main_process():
|
if misc.is_main_process():
|
||||||
backbone.print_trainable_parameters()
|
backbone.print_trainable_parameters()
|
||||||
|
|
||||||
# 6. 构建最终的微调模型
|
|
||||||
model = FinetuneModel(
|
model = FinetuneModel(
|
||||||
backbone=backbone,
|
backbone=backbone,
|
||||||
num_channel=args.num_channel,
|
num_channel=args.num_channel,
|
||||||
embed_dim=args.embed_dim,
|
embed_dim=args.embed_dim,
|
||||||
num_classes=dataset_config["n_cl"]
|
num_classes=dataset_config["n_cl"]
|
||||||
).to(device)
|
).to(device)
|
||||||
# ... (This section remains unchanged) ...
|
|
||||||
model_without_ddp = model
|
model_without_ddp = model
|
||||||
if args.distributed:
|
if args.distributed:
|
||||||
model = torch.nn.parallel.DistributedDataParallel(
|
model = torch.nn.parallel.DistributedDataParallel(
|
||||||
@@ -361,18 +318,20 @@ def main(args):
|
|||||||
if args.lr is None:
|
if args.lr is None:
|
||||||
args.lr = args.blr * eff_batch_size / 256
|
args.lr = args.blr * eff_batch_size / 256
|
||||||
print("LR: %.2e" % args.lr)
|
print("LR: %.2e" % args.lr)
|
||||||
|
|
||||||
optimizer = torch.optim.AdamW(
|
optimizer = torch.optim.AdamW(
|
||||||
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
||||||
loss_scaler = NativeScaler()
|
|
||||||
|
# 仅在 FP16 时使用 Scaler
|
||||||
|
loss_scaler = NativeScaler() if args.precision == 'fp16' else None
|
||||||
|
|
||||||
if args.task == 'cls':
|
if args.task == 'cls':
|
||||||
criterion = FocalLoss(
|
criterion = FocalLoss(
|
||||||
gamma=args.focal_gamma) if args.use_focal_loss else torch.nn.CrossEntropyLoss()
|
gamma=args.focal_gamma) if args.use_focal_loss else torch.nn.CrossEntropyLoss()
|
||||||
else:
|
else:
|
||||||
criterion = torch.nn.L1Loss()
|
criterion = torch.nn.L1Loss()
|
||||||
print("Using criterion:", str(criterion))
|
|
||||||
|
|
||||||
# === Training Loop ===
|
# --- Training Loop (保持不变) ---
|
||||||
print(f"Start fine-tuning for {args.epochs} epochs")
|
print(f"Start fine-tuning for {args.epochs} epochs")
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
max_metric = -float('inf')
|
max_metric = -float('inf')
|
||||||
@@ -389,7 +348,6 @@ def main(args):
|
|||||||
args, test_loader, model, device, criterion, print_analyzer=False, epoch=epoch, plot_save_dir=plot_save_dir)
|
args, test_loader, model, device, criterion, print_analyzer=False, epoch=epoch, plot_save_dir=plot_save_dir)
|
||||||
|
|
||||||
if misc.is_main_process():
|
if misc.is_main_process():
|
||||||
# --- [OPTIMIZED] Call the new function to save the aggregated summary ---
|
|
||||||
save_prediction_summary(
|
save_prediction_summary(
|
||||||
per_sample_results, summary_save_dir, epoch)
|
per_sample_results, summary_save_dir, epoch)
|
||||||
|
|
||||||
@@ -400,13 +358,7 @@ def main(args):
|
|||||||
current_metric = -test_stats.get('mae', float('inf'))
|
current_metric = -test_stats.get('mae', float('inf'))
|
||||||
metric_name = 'mae'
|
metric_name = 'mae'
|
||||||
|
|
||||||
print(
|
print(f"Epoch {epoch}: Test Loss: {test_stats.get('loss', 0):.4f}, AUC: {test_stats.get('roc_auc', 0):.4f}, F1: {test_stats.get('f1_score', 0):.4f}")
|
||||||
f"Epoch {epoch}: Test Loss: {test_stats.get('loss', 0):.4f}, "
|
|
||||||
f"AUC: {test_stats.get('roc_auc', 0):.4f}, "
|
|
||||||
f"AP: {test_stats.get('ap', 0):.4f}, "
|
|
||||||
f"F1: {test_stats.get('f1_score', 0):.4f}, "
|
|
||||||
f"Accuracy: {test_stats.get('accuracy', 0):.4f}"
|
|
||||||
)
|
|
||||||
|
|
||||||
if current_metric > max_metric:
|
if current_metric > max_metric:
|
||||||
max_metric = current_metric
|
max_metric = current_metric
|
||||||
@@ -429,30 +381,22 @@ def main(args):
|
|||||||
if args.distributed:
|
if args.distributed:
|
||||||
dist.barrier()
|
dist.barrier()
|
||||||
|
|
||||||
# === Final Evaluation ===
|
# --- Final Evaluation (保持不变) ---
|
||||||
# ... (This section remains unchanged) ...
|
|
||||||
if misc.is_main_process():
|
if misc.is_main_process():
|
||||||
print('\n####### Loading the best model for final evaluation ######')
|
print('\n####### Loading the best model for final evaluation ######')
|
||||||
# Corrected filename based on misc.save_model
|
|
||||||
best_model_path = os.path.join(args.output_dir, 'checkpoint-best.pth')
|
best_model_path = os.path.join(args.output_dir, 'checkpoint-best.pth')
|
||||||
if os.path.exists(best_model_path):
|
if os.path.exists(best_model_path):
|
||||||
print(f'Loading best model from epoch {best_epoch}')
|
print(f'Loading best model from epoch {best_epoch}')
|
||||||
checkpoint = torch.load(best_model_path, map_location='cpu')
|
checkpoint = torch.load(best_model_path, map_location='cpu')
|
||||||
model_without_ddp.load_state_dict(checkpoint['model'])
|
model_without_ddp.load_state_dict(checkpoint['model'])
|
||||||
|
|
||||||
final_plot_dir = os.path.join(args.output_dir, 'final_plots')
|
final_plot_dir = os.path.join(args.output_dir, 'final_plots')
|
||||||
os.makedirs(final_plot_dir, exist_ok=True)
|
os.makedirs(final_plot_dir, exist_ok=True)
|
||||||
|
|
||||||
test_stats_best, _ = evaluate(args, test_loader, model, device, criterion,
|
test_stats_best, _ = evaluate(args, test_loader, model, device, criterion,
|
||||||
print_analyzer=True, epoch="best", plot_save_dir=final_plot_dir)
|
print_analyzer=True, epoch="best", plot_save_dir=final_plot_dir)
|
||||||
|
|
||||||
print(
|
print(
|
||||||
f"\n--- Final Evaluation (Best Model from Epoch {best_epoch}) ---")
|
f"\n--- Final Evaluation (Best Model from Epoch {best_epoch}) ---")
|
||||||
for metric, value in test_stats_best.items():
|
for metric, value in test_stats_best.items():
|
||||||
print(f" {metric.capitalize()}: {value:.5f}")
|
print(f" {metric.capitalize()}: {value:.5f}")
|
||||||
else:
|
|
||||||
print(
|
|
||||||
f"Warning: Best model checkpoint {best_model_path} not found. Skipping final evaluation.")
|
|
||||||
|
|
||||||
total_time = time.time() - start_time
|
total_time = time.time() - start_time
|
||||||
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
||||||
|
|||||||
@@ -1,360 +0,0 @@
|
|||||||
# --- START OF FILE main_finetune (1).py (MODIFIED) ---
|
|
||||||
from NormWear.modules.custom_blocks import OneD_CNN_Extractor
|
|
||||||
import argparse
|
|
||||||
import datetime
|
|
||||||
import json
|
|
||||||
import numpy as np
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
from pathlib import Path
|
|
||||||
import pandas as pd # <-- [ADDED] Import pandas
|
|
||||||
import torch
|
|
||||||
import torch.nn as nn
|
|
||||||
import torch.nn.functional as F
|
|
||||||
import torch.backends.cudnn as cudnn
|
|
||||||
from torch.utils.data import DataLoader
|
|
||||||
import torch.distributed as dist
|
|
||||||
from tqdm import tqdm
|
|
||||||
from torch.utils.tensorboard import SummaryWriter
|
|
||||||
from sklearn.model_selection import GroupKFold
|
|
||||||
# Assuming project structure allows these imports
|
|
||||||
from .config import DATASET_CONFIG
|
|
||||||
from NormWear.modules.normwear import NormWear
|
|
||||||
from NormWear.modules.head import RegressionHead, MLPClassificationHead, ClassificationHead
|
|
||||||
from .engine_finetune import train_one_epoch, evaluate
|
|
||||||
import NormWear.pretrain_pipeline.misc as misc
|
|
||||||
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount as NativeScaler
|
|
||||||
from NormWear.pretrain_pipeline.dataset import dataset_class, KFoldDataset
|
|
||||||
from peft import LoraConfig, get_peft_model, TaskType
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# --- 2. 模型和辅助函数定义 (保持不变) ---
|
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
|
|
||||||
class FinetuneModel(nn.Module):
|
|
||||||
def __init__(self, backbone, num_channel, embed_dim, num_classes):
|
|
||||||
super().__init__()
|
|
||||||
self.backbone = backbone
|
|
||||||
head_input_dim = num_channel * embed_dim
|
|
||||||
self.finetune_head = nn.Sequential(
|
|
||||||
nn.Linear(head_input_dim, head_input_dim // 2),
|
|
||||||
nn.BatchNorm1d(head_input_dim // 2),
|
|
||||||
nn.ReLU(),
|
|
||||||
nn.Dropout(0.3),
|
|
||||||
nn.Linear(head_input_dim // 2, num_classes)
|
|
||||||
)
|
|
||||||
|
|
||||||
def forward(self, x_cwt, x_1d):
|
|
||||||
z = self.backbone.get_signal_embedding(x_cwt, x_1d)
|
|
||||||
cls_tokens = z[:, :, 0, :]
|
|
||||||
flat_features = cls_tokens.flatten(1)
|
|
||||||
logits = self.finetune_head(flat_features)
|
|
||||||
return logits, flat_features
|
|
||||||
|
|
||||||
|
|
||||||
class FocalLoss(nn.Module):
|
|
||||||
def __init__(self, alpha=None, gamma=2.0, reduction='mean'):
|
|
||||||
super(FocalLoss, self).__init__()
|
|
||||||
self.alpha = alpha
|
|
||||||
self.gamma = gamma
|
|
||||||
self.reduction = reduction
|
|
||||||
|
|
||||||
def forward(self, inputs, targets):
|
|
||||||
ce_loss = F.cross_entropy(inputs, targets, reduction='none')
|
|
||||||
pt = torch.exp(-ce_loss)
|
|
||||||
focal_term = (1 - pt).pow(self.gamma)
|
|
||||||
loss = focal_term * ce_loss
|
|
||||||
if self.alpha is not None:
|
|
||||||
if self.alpha.device != loss.device:
|
|
||||||
self.alpha = self.alpha.to(loss.device)
|
|
||||||
alpha_t = self.alpha.gather(0, targets)
|
|
||||||
loss = alpha_t * loss
|
|
||||||
if self.reduction == 'mean':
|
|
||||||
return loss.mean()
|
|
||||||
elif self.reduction == 'sum':
|
|
||||||
return loss.sum()
|
|
||||||
else:
|
|
||||||
return loss
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# --- 3. 参数解析器 ---
|
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
|
|
||||||
def get_args_parser():
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
'NormWear K-Fold Fine-tuning', add_help=False)
|
|
||||||
|
|
||||||
# --- 数据集和路径 ---
|
|
||||||
parser.add_argument('--checkpoint', required=True, type=str,
|
|
||||||
help='Path to the pre-trained model checkpoint.')
|
|
||||||
parser.add_argument('--ds_name', required=True, type=str,
|
|
||||||
help='Dataset name (e.g., ppg_for_kfold).')
|
|
||||||
parser.add_argument('--data_dir', default='../data',
|
|
||||||
type=str, help='Root directory of datasets.')
|
|
||||||
parser.add_argument(
|
|
||||||
'--output_dir', default='../data/results_finetune_kfold', help='Path to save results.')
|
|
||||||
parser.add_argument('--log_dir', default=None,
|
|
||||||
help='Path for Tensorboard logs. Defaults to output_dir/logs.')
|
|
||||||
|
|
||||||
# --- K-Fold 配置 ---
|
|
||||||
parser.add_argument('--n_splits', type=int, default=5,
|
|
||||||
help='Number of splits for Group K-Fold cross-validation.')
|
|
||||||
|
|
||||||
# --- 模型参数 (与预训练保持一致) ---
|
|
||||||
parser.add_argument('--embed_dim', type=int, default=768)
|
|
||||||
parser.add_argument('--depth', type=int, default=12)
|
|
||||||
parser.add_argument('--num_heads', type=int, default=12)
|
|
||||||
parser.add_argument('--decoder_embed_dim', type=int, default=512)
|
|
||||||
parser.add_argument('--decoder_depth', type=int, default=8)
|
|
||||||
parser.add_argument('--decoder_num_heads', type=int, default=16)
|
|
||||||
|
|
||||||
# --- 微调参数 ---
|
|
||||||
parser.add_argument('--batch_size', default=128, type=int)
|
|
||||||
parser.add_argument('--epochs', default=100, type=int)
|
|
||||||
parser.add_argument('--accum_iter', default=1, type=int)
|
|
||||||
parser.add_argument('--blr', type=float, default=1e-4,
|
|
||||||
metavar='LR', help='Base learning rate.')
|
|
||||||
parser.add_argument('--lr', type=float, default=None, metavar='LR',
|
|
||||||
help='Actual learning rate, calculated if not set.')
|
|
||||||
parser.add_argument('--weight_decay', type=float, default=0.05)
|
|
||||||
parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N')
|
|
||||||
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR')
|
|
||||||
parser.add_argument('--use_focal_loss', action='store_true',
|
|
||||||
help='Use Focal Loss for classification.')
|
|
||||||
parser.add_argument('--focal_gamma', type=float, default=2.0)
|
|
||||||
parser.add_argument('--use_amp', action='store_true', default=True)
|
|
||||||
parser.add_argument('--no_amp', action='store_false', dest='use_amp')
|
|
||||||
|
|
||||||
# --- LoRA 参数 ---
|
|
||||||
parser.add_argument('--use_lora', action='store_true')
|
|
||||||
parser.add_argument('--lora_r', type=int, default=16)
|
|
||||||
parser.add_argument('--lora_alpha', type=int, default=32)
|
|
||||||
parser.add_argument('--lora_dropout', type=float, default=0.1)
|
|
||||||
|
|
||||||
# --- 运行环境 ---
|
|
||||||
parser.add_argument('--remark', default='finetune_kfold',
|
|
||||||
help='A remark for the run.')
|
|
||||||
parser.add_argument('--seed', default=42, type=int)
|
|
||||||
parser.add_argument('--num_workers', default=4, type=int)
|
|
||||||
parser.add_argument('--pin_mem', action='store_true', default=True)
|
|
||||||
parser.add_argument('--device', default='cuda')
|
|
||||||
|
|
||||||
# --- 分布式训练 (K-Fold通常在单机多卡上运行) ---
|
|
||||||
parser.add_argument('--world_size', default=1, type=int)
|
|
||||||
parser.add_argument('--local_rank', default=-1, type=int)
|
|
||||||
parser.add_argument('--dist_on_itp', action='store_true')
|
|
||||||
parser.add_argument('--dist_url', default='env://')
|
|
||||||
|
|
||||||
return parser
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# --- 4. 主函数 ---
|
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
|
|
||||||
def main(args):
|
|
||||||
misc.init_distributed_mode(args)
|
|
||||||
|
|
||||||
device = torch.device(args.device)
|
|
||||||
seed = args.seed + misc.get_rank()
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
np.random.seed(seed)
|
|
||||||
cudnn.benchmark = True
|
|
||||||
|
|
||||||
# --- 1. 设置日志和输出目录 ---
|
|
||||||
if misc.is_main_process():
|
|
||||||
run_name = f"{args.remark}_{args.ds_name}_{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}"
|
|
||||||
args.output_dir = os.path.join(args.output_dir, run_name)
|
|
||||||
os.makedirs(args.output_dir, exist_ok=True)
|
|
||||||
if args.log_dir is None:
|
|
||||||
args.log_dir = os.path.join(args.output_dir, 'logs')
|
|
||||||
os.makedirs(args.log_dir, exist_ok=True)
|
|
||||||
print(f"Output directory: {args.output_dir}")
|
|
||||||
print(f"Logs directory: {args.log_dir}")
|
|
||||||
|
|
||||||
# --- 2. 加载K-Fold数据集信息 ---
|
|
||||||
dataset_config = DATASET_CONFIG[args.ds_name]
|
|
||||||
args.num_channel = dataset_config["n_ch"]
|
|
||||||
args.num_classes = dataset_config["n_cl"]
|
|
||||||
args.task = dataset_config.get("task", "cls")
|
|
||||||
args.max_len = dataset_config.get("max_len", 390)
|
|
||||||
args.img_size = (args.max_len - 2, 65)
|
|
||||||
|
|
||||||
dataset_root_path = os.path.join(args.data_dir, args.ds_name)
|
|
||||||
split_file_path = os.path.join(
|
|
||||||
dataset_root_path, 'kfold_split_with_groups.json')
|
|
||||||
with open(split_file_path, 'r') as f:
|
|
||||||
all_samples_info = json.load(f)['samples']
|
|
||||||
|
|
||||||
all_samples_info_np = np.array(all_samples_info)
|
|
||||||
all_labels = np.array([s['binary_label'] for s in all_samples_info])
|
|
||||||
all_groups = np.array([s['subject_id'] for s in all_samples_info])
|
|
||||||
|
|
||||||
if misc.is_main_process():
|
|
||||||
print(
|
|
||||||
f"Loaded {len(all_samples_info)} total samples for {len(np.unique(all_groups))} subjects.")
|
|
||||||
|
|
||||||
# --- 3. K-Fold 交叉验证主循环 ---
|
|
||||||
gkf = GroupKFold(n_splits=args.n_splits)
|
|
||||||
fold_results = []
|
|
||||||
|
|
||||||
for fold, (train_idx, test_idx) in enumerate(gkf.split(all_samples_info_np, all_labels, all_groups)):
|
|
||||||
if misc.is_main_process():
|
|
||||||
print("\n" + "="*80)
|
|
||||||
print(f" FOLD {fold + 1} / {args.n_splits}")
|
|
||||||
print("="*80)
|
|
||||||
|
|
||||||
# --- a. 为当前折创建数据集 ---
|
|
||||||
train_samples_info = all_samples_info_np[train_idx].tolist()
|
|
||||||
test_samples_info = all_samples_info_np[test_idx].tolist()
|
|
||||||
|
|
||||||
train_augmentations = {'noise_std': 0.01, 'scale_range': (0.9, 1.1)}
|
|
||||||
|
|
||||||
train_dataset = KFoldDataset(data_root_dir=dataset_root_path,
|
|
||||||
samples_info=train_samples_info,
|
|
||||||
is_train=True,
|
|
||||||
augmentations=train_augmentations,
|
|
||||||
max_len=args.max_len,
|
|
||||||
use_spec=True,
|
|
||||||
img_size=args.img_size)
|
|
||||||
test_dataset = KFoldDataset(data_root_dir=dataset_root_path,
|
|
||||||
samples_info=test_samples_info,
|
|
||||||
is_train=False,
|
|
||||||
max_len=args.max_len,
|
|
||||||
use_spec=True,
|
|
||||||
img_size=args.img_size)
|
|
||||||
|
|
||||||
sampler_train = torch.utils.data.DistributedSampler(
|
|
||||||
train_dataset, shuffle=True) if args.distributed else torch.utils.data.RandomSampler(train_dataset)
|
|
||||||
sampler_val = torch.utils.data.DistributedSampler(
|
|
||||||
test_dataset, shuffle=False) if args.distributed else torch.utils.data.SequentialSampler(test_dataset)
|
|
||||||
|
|
||||||
train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=sampler_train,
|
|
||||||
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True)
|
|
||||||
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=sampler_val,
|
|
||||||
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
|
|
||||||
|
|
||||||
# --- b. 重新初始化模型和优化器 ---
|
|
||||||
backbone = NormWear(
|
|
||||||
img_size=(args.max_len, 65), patch_size=(9, 5), in_chans=3,
|
|
||||||
embed_dim=args.embed_dim, depth=args.depth, num_heads=args.num_heads,
|
|
||||||
decoder_embed_dim=args.decoder_embed_dim, decoder_depth=args.decoder_depth,
|
|
||||||
decoder_num_heads=args.decoder_num_heads, nvar=args.num_channel
|
|
||||||
)
|
|
||||||
checkpoint = torch.load(args.checkpoint, map_location='cpu')
|
|
||||||
msg = backbone.load_state_dict(checkpoint['model'], strict=False)
|
|
||||||
if misc.is_main_process():
|
|
||||||
print("Backbone loading message:", msg)
|
|
||||||
|
|
||||||
if args.use_lora:
|
|
||||||
# ... (LoRA init logic) ...
|
|
||||||
pass
|
|
||||||
|
|
||||||
model = FinetuneModel(
|
|
||||||
backbone=backbone, num_channel=args.num_channel,
|
|
||||||
embed_dim=args.embed_dim, num_classes=args.num_classes
|
|
||||||
).to(device)
|
|
||||||
|
|
||||||
if args.distributed:
|
|
||||||
model = torch.nn.parallel.DistributedDataParallel(
|
|
||||||
model, device_ids=[args.gpu], find_unused_parameters=True)
|
|
||||||
|
|
||||||
model_without_ddp = model.module if args.distributed else model
|
|
||||||
|
|
||||||
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
|
|
||||||
if args.lr is None:
|
|
||||||
args.lr = args.blr * eff_batch_size / 256
|
|
||||||
|
|
||||||
optimizer = torch.optim.AdamW(
|
|
||||||
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
|
||||||
loss_scaler = NativeScaler()
|
|
||||||
criterion = FocalLoss(
|
|
||||||
gamma=args.focal_gamma) if args.use_focal_loss else torch.nn.CrossEntropyLoss()
|
|
||||||
|
|
||||||
log_writer = SummaryWriter(log_dir=os.path.join(
|
|
||||||
args.log_dir, f"fold_{fold+1}")) if misc.is_main_process() else None
|
|
||||||
|
|
||||||
# --- c. 训练和评估当前折 ---
|
|
||||||
max_metric = -float('inf')
|
|
||||||
best_epoch_stats = {}
|
|
||||||
|
|
||||||
for epoch in range(args.epochs):
|
|
||||||
if args.distributed:
|
|
||||||
train_loader.sampler.set_epoch(epoch)
|
|
||||||
|
|
||||||
train_one_epoch(model, criterion, train_loader, optimizer, device,
|
|
||||||
epoch, loss_scaler, max_norm=1.0, log_writer=log_writer, args=args)
|
|
||||||
|
|
||||||
# 只在主进程上进行评估,以避免冗余计算和文件写入
|
|
||||||
if misc.is_main_process():
|
|
||||||
test_stats, _ = evaluate(
|
|
||||||
args, test_loader, model, device, criterion, print_analyzer=False)
|
|
||||||
|
|
||||||
current_metric = test_stats.get('roc_auc', 0.0)
|
|
||||||
if current_metric > max_metric:
|
|
||||||
max_metric = current_metric
|
|
||||||
best_epoch_stats = test_stats
|
|
||||||
# 保存当前折的最佳模型
|
|
||||||
misc.save_model(args=args, model=model, model_without_ddp=model_without_ddp,
|
|
||||||
optimizer=optimizer, loss_scaler=loss_scaler, epoch=f"fold_{fold+1}_best")
|
|
||||||
|
|
||||||
if args.distributed:
|
|
||||||
dist.barrier() # 等待所有进程完成当前epoch
|
|
||||||
|
|
||||||
if misc.is_main_process():
|
|
||||||
print(
|
|
||||||
f"\n--- Best Result for Fold {fold + 1} (AUC: {max_metric:.4f}) ---")
|
|
||||||
print(pd.Series(best_epoch_stats))
|
|
||||||
fold_results.append(best_epoch_stats)
|
|
||||||
if log_writer:
|
|
||||||
log_writer.close()
|
|
||||||
|
|
||||||
# --- 4. 聚合和报告最终结果 ---
|
|
||||||
if misc.is_main_process():
|
|
||||||
print("\n" + "="*80)
|
|
||||||
print(" CROSS-VALIDATION FINAL RESULTS")
|
|
||||||
print("="*80)
|
|
||||||
|
|
||||||
if not fold_results:
|
|
||||||
print("No fold results to summarize. Exiting.")
|
|
||||||
else:
|
|
||||||
results_df = pd.DataFrame(fold_results)
|
|
||||||
|
|
||||||
# --- 【核心修复】 ---
|
|
||||||
# 在调用 .mean() 和 .std() 之前,先选择只包含数值类型的列。
|
|
||||||
# numeric_only=True 参数会自动帮你完成这件事。
|
|
||||||
final_summary_mean = results_df.mean(numeric_only=True)
|
|
||||||
final_summary_std = results_df.std(numeric_only=True)
|
|
||||||
# --- [修复结束] ---
|
|
||||||
|
|
||||||
# 将均值和标准差合并到一个DataFrame中以便美观地打印
|
|
||||||
summary_df = pd.DataFrame(
|
|
||||||
{'mean': final_summary_mean, 'std': final_summary_std})
|
|
||||||
|
|
||||||
print("--- Performance Summary (mean ± std) across all folds ---")
|
|
||||||
# 使用 to_string() 可以确保打印所有行和列
|
|
||||||
print(summary_df.to_string())
|
|
||||||
|
|
||||||
# 保存详细的每折结果 (包括非数值列)
|
|
||||||
summary_path = os.path.join(
|
|
||||||
args.output_dir, "cv_summary_results.csv")
|
|
||||||
try:
|
|
||||||
results_df.to_csv(summary_path, index_label="fold")
|
|
||||||
print(f"\nSaved detailed fold results to {summary_path}")
|
|
||||||
except Exception as e:
|
|
||||||
print(
|
|
||||||
f"\nCould not save detailed results to CSV due to non-serializable data: {e}")
|
|
||||||
# 如果保存失败,可以尝试只保存数值部分
|
|
||||||
results_df.select_dtypes(include=np.number).to_csv(
|
|
||||||
summary_path, index_label="fold")
|
|
||||||
print(f"Saved only numeric fold results to {summary_path}")
|
|
||||||
|
|
||||||
print('Done!')
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
args = get_args_parser()
|
|
||||||
args = args.parse_args()
|
|
||||||
main(args)
|
|
||||||
@@ -6,7 +6,67 @@ from timm.models.layers import DropPath, Mlp
|
|||||||
# 以确保与您项目中其他部分兼容
|
# 以确保与您项目中其他部分兼容
|
||||||
from timm.models.vision_transformer import Attention
|
from timm.models.vision_transformer import Attention
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# from mamba_ssm import Mamba
|
||||||
|
# except ImportError:
|
||||||
|
# print("Warning: mamba_ssm is not installed. BiMambaBlock will not be available.")
|
||||||
|
# print("Please install it via: pip install mamba-ssm causal-conv1d")
|
||||||
|
# Mamba = None
|
||||||
|
|
||||||
|
# class BiMambaBlock(nn.Module):
|
||||||
|
# """
|
||||||
|
# 一个双向的 Mamba 块,用于非因果序列建模任务,如 MAE。
|
||||||
|
# 它包含一个前向 Mamba 和一个后向 Mamba。
|
||||||
|
# """
|
||||||
|
# def __init__(self, dim, d_state=16, d_conv=4, expand=2):
|
||||||
|
# super().__init__()
|
||||||
|
# if Mamba is None:
|
||||||
|
# raise ImportError("mamba_ssm is not installed.")
|
||||||
|
|
||||||
|
# self.norm = nn.LayerNorm(dim)
|
||||||
|
|
||||||
|
# # 前向 Mamba
|
||||||
|
# self.mamba_fw = Mamba(
|
||||||
|
# d_model=dim,
|
||||||
|
# d_state=d_state,
|
||||||
|
# d_conv=d_conv,
|
||||||
|
# expand=expand,
|
||||||
|
# )
|
||||||
|
|
||||||
|
# # 后向 Mamba
|
||||||
|
# self.mamba_bw = Mamba(
|
||||||
|
# d_model=dim,
|
||||||
|
# d_state=d_state,
|
||||||
|
# d_conv=d_conv,
|
||||||
|
# expand=expand,
|
||||||
|
# )
|
||||||
|
|
||||||
|
# # 用于融合前向和后向输出的线性层
|
||||||
|
# self.proj = nn.Linear(dim * 2, dim)
|
||||||
|
|
||||||
|
# def forward(self, x):
|
||||||
|
# # x 形状: [Batch, Num_Patches, Embed_Dim]
|
||||||
|
|
||||||
|
# # 预归一化
|
||||||
|
# x_norm = self.norm(x)
|
||||||
|
|
||||||
|
# # 前向传递
|
||||||
|
# fw_out = self.mamba_fw(x_norm)
|
||||||
|
|
||||||
|
# # 后向传递
|
||||||
|
# # 1. 反转序列
|
||||||
|
# x_reversed = torch.flip(x_norm, dims=[1])
|
||||||
|
# # 2. 通过后向 Mamba
|
||||||
|
# bw_out_reversed = self.mamba_bw(x_reversed)
|
||||||
|
# # 3. 将输出反转回来
|
||||||
|
# bw_out = torch.flip(bw_out_reversed, dims=[1])
|
||||||
|
|
||||||
|
# # 拼接并融合
|
||||||
|
# merged_out = torch.cat([fw_out, bw_out], dim=-1)
|
||||||
|
# fused_out = self.proj(merged_out)
|
||||||
|
|
||||||
|
# # 残差连接
|
||||||
|
# return x + fused_out
|
||||||
class OneD_CNN_Extractor(nn.Module):
|
class OneD_CNN_Extractor(nn.Module):
|
||||||
"""
|
"""
|
||||||
一个从1D原始信号中提取特征的CNN模块。
|
一个从1D原始信号中提取特征的CNN模块。
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# hfr.py
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
from timm.models.layers import DropPath, Mlp
|
||||||
|
|
||||||
|
class HFR_Mechanism(nn.Module):
|
||||||
|
"""
|
||||||
|
Holographic Fluid Resonance (HFR) Mechanism
|
||||||
|
核心机制:流体局部性 + 全息状态压缩 + 共振门控
|
||||||
|
复杂度:O(N)
|
||||||
|
"""
|
||||||
|
def __init__(self, dim, num_heads=4, qkv_bias=False, attn_drop=0., proj_drop=0., fluid_kernel_size=3):
|
||||||
|
super().__init__()
|
||||||
|
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
||||||
|
self.num_heads = num_heads
|
||||||
|
self.head_dim = dim // num_heads
|
||||||
|
self.scale = self.head_dim ** -0.5
|
||||||
|
|
||||||
|
# 1. 流体层 (Fluidity): 捕捉局部特征 (替代了原有的 ConvEnhancedBlock 中的并行卷积)
|
||||||
|
# 使用 Depthwise Conv1d 模拟局部流动
|
||||||
|
self.local_fluid = nn.Conv1d(dim, dim, kernel_size=fluid_kernel_size,
|
||||||
|
padding=fluid_kernel_size//2, groups=dim)
|
||||||
|
|
||||||
|
# 2. 投影层
|
||||||
|
self.q_proj = nn.Linear(dim, dim, bias=qkv_bias)
|
||||||
|
self.k_proj = nn.Linear(dim, dim, bias=qkv_bias)
|
||||||
|
self.v_proj = nn.Linear(dim, dim, bias=qkv_bias)
|
||||||
|
|
||||||
|
# 3. 共振门控 (Resonance Gating): 动态调节输出权重
|
||||||
|
self.resonance_gate = nn.Sequential(
|
||||||
|
nn.Linear(dim, dim),
|
||||||
|
nn.Sigmoid()
|
||||||
|
)
|
||||||
|
|
||||||
|
self.out_proj = nn.Linear(dim, dim)
|
||||||
|
self.proj_drop = nn.Dropout(proj_drop)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
# x shape: [Batch, Seq_Len, Dim]
|
||||||
|
B, N, C = x.shape
|
||||||
|
|
||||||
|
# --- 阶段 A: 流体局部处理 (Fluid Processing) ---
|
||||||
|
# 转换维度以适应 Conv1d: [B, C, N]
|
||||||
|
x_fluid = x.transpose(1, 2)
|
||||||
|
x_fluid = self.local_fluid(x_fluid)
|
||||||
|
x_fluid = x_fluid.transpose(1, 2) # 还原 [B, N, C]
|
||||||
|
|
||||||
|
# 残差连接,保留原始信息
|
||||||
|
x = x + x_fluid
|
||||||
|
|
||||||
|
# --- 阶段 B: 全息状态压缩 (Holographic State Compression) ---
|
||||||
|
# 线性注意力的核心:Feature Map 映射 (ELU + 1 保证非负)
|
||||||
|
q = self.q_proj(x).reshape(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
|
||||||
|
k = self.k_proj(x).reshape(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
|
||||||
|
v = self.v_proj(x).reshape(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
|
||||||
|
|
||||||
|
q = F.elu(q) + 1.0
|
||||||
|
k = F.elu(k) + 1.0
|
||||||
|
|
||||||
|
# 核心优化:先计算 K^T * V,生成 "全息状态矩阵" (Holographic State)
|
||||||
|
# 复杂度: O(N) 而不是 O(N^2)
|
||||||
|
# kv_state: [B, Heads, D_h, D_h]
|
||||||
|
kv_state = torch.matmul(k.transpose(-2, -1), v)
|
||||||
|
|
||||||
|
# 归一化因子 (分母)
|
||||||
|
z = 1 / (torch.matmul(q, k.sum(dim=2, keepdim=True).transpose(-2, -1)) + 1e-6)
|
||||||
|
|
||||||
|
# 从全息状态中读取信息: Q * State
|
||||||
|
out = torch.matmul(q, kv_state) * z
|
||||||
|
|
||||||
|
# 重组 Heads
|
||||||
|
out = out.permute(0, 2, 1, 3).reshape(B, N, C)
|
||||||
|
|
||||||
|
# --- 阶段 C: 共振门控 (Resonance Gating) ---
|
||||||
|
# 根据输入内容的"惊奇度"决定保留多少检索到的记忆
|
||||||
|
gate = self.resonance_gate(x)
|
||||||
|
out = out * gate
|
||||||
|
|
||||||
|
out = self.out_proj(out)
|
||||||
|
out = self.proj_drop(out)
|
||||||
|
return out
|
||||||
|
|
||||||
|
class HFRBlock(nn.Module):
|
||||||
|
"""
|
||||||
|
HFR Block: 替代标准的 Transformer Block
|
||||||
|
结构: Norm -> HFR -> Add -> Norm -> MLP -> Add
|
||||||
|
"""
|
||||||
|
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False,
|
||||||
|
drop=0., attn_drop=0., drop_path=0.,
|
||||||
|
act_layer=nn.GELU, norm_layer=nn.LayerNorm,
|
||||||
|
fluid_kernel_size=3):
|
||||||
|
super().__init__()
|
||||||
|
self.norm1 = norm_layer(dim)
|
||||||
|
|
||||||
|
# 使用 HFR 机制替代 Attention
|
||||||
|
self.attn = HFR_Mechanism(
|
||||||
|
dim, num_heads=num_heads, qkv_bias=qkv_bias,
|
||||||
|
attn_drop=attn_drop, proj_drop=drop,
|
||||||
|
fluid_kernel_size=fluid_kernel_size
|
||||||
|
)
|
||||||
|
|
||||||
|
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
||||||
|
self.norm2 = norm_layer(dim)
|
||||||
|
|
||||||
|
mlp_hidden_dim = int(dim * mlp_ratio)
|
||||||
|
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
# HFR Path
|
||||||
|
x = x + self.drop_path(self.attn(self.norm1(x)))
|
||||||
|
# MLP Path
|
||||||
|
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
||||||
|
return x
|
||||||
@@ -3,16 +3,18 @@
|
|||||||
import torch
|
import torch
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from .custom_blocks import ConvEnhancedBlock, OneD_CNN_Extractor
|
# [修改] 移除旧的 ConvEnhancedBlock,导入新的 HFRBlock
|
||||||
|
# from .custom_blocks import ConvEnhancedBlock, OneD_CNN_Extractor
|
||||||
|
from .custom_blocks import OneD_CNN_Extractor
|
||||||
|
from .hfr import HFRBlock # <--- 导入 HFR 模块
|
||||||
from .pos_embed import get_2d_sincos_pos_embed_flexible
|
from .pos_embed import get_2d_sincos_pos_embed_flexible
|
||||||
from .patch_embed import HybridPatchEmbed
|
from .patch_embed import HybridPatchEmbed
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# MAE 辅助函数 (保持不变)
|
# MAE 辅助函数 (保持不变)
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def random_masking(x, mask_ratio):
|
def random_masking(x, mask_ratio):
|
||||||
|
# ... (代码保持不变) ...
|
||||||
N, L, D = x.shape
|
N, L, D = x.shape
|
||||||
len_keep = int(L * (1.0 - mask_ratio))
|
len_keep = int(L * (1.0 - mask_ratio))
|
||||||
noise = torch.rand(N, L, device=x.device)
|
noise = torch.rand(N, L, device=x.device)
|
||||||
@@ -27,24 +29,24 @@ def random_masking(x, mask_ratio):
|
|||||||
return x_masked, mask, ids_restore
|
return x_masked, mask, ids_restore
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# 最终的 NormWear 类 (多模态重建MAE版本)
|
# 最终的 NormWear 类 (HFR 升级版)
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
class NormWear(nn.Module):
|
class NormWear(nn.Module):
|
||||||
def __init__(self, img_size=(387, 65), patch_size=(9, 5), in_chans=3,
|
def __init__(self, img_size=(387, 65), patch_size=(9, 5), in_chans=3,
|
||||||
embed_dim=768, depth=12, num_heads=12,
|
embed_dim=768, depth=12, num_heads=12,
|
||||||
decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16,
|
decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16,
|
||||||
mlp_ratio=4., norm_layer=nn.LayerNorm,
|
mlp_ratio=4., norm_layer=nn.LayerNorm,
|
||||||
loss_weight_1d_token=0.3, # [修改] 权重参数重命名
|
loss_weight_1d_token=0.3,
|
||||||
loss_weight_1d_signal=0.3, # [新增] 新的1D信号重建损失权重
|
loss_weight_1d_signal=0.3,
|
||||||
modality_dropout_prob=0.0,
|
modality_dropout_prob=0.0,
|
||||||
nvar=4,
|
nvar=4,
|
||||||
|
# [新增] HFR 特有的参数
|
||||||
|
fluid_kernel_size=3,
|
||||||
**kwargs):
|
**kwargs):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.patch_size = patch_size
|
self.patch_size = patch_size
|
||||||
# [修改] 初始化新的权重参数
|
|
||||||
self.loss_weight_1d_token = loss_weight_1d_token
|
self.loss_weight_1d_token = loss_weight_1d_token
|
||||||
self.loss_weight_1d_signal = loss_weight_1d_signal
|
self.loss_weight_1d_signal = loss_weight_1d_signal
|
||||||
assert 0 <= self.loss_weight_1d_token + self.loss_weight_1d_signal <= 1.0, \
|
assert 0 <= self.loss_weight_1d_token + self.loss_weight_1d_signal <= 1.0, \
|
||||||
@@ -67,30 +69,44 @@ class NormWear(nn.Module):
|
|||||||
self.norm_1d_tokens = nn.LayerNorm(embed_dim)
|
self.norm_1d_tokens = nn.LayerNorm(embed_dim)
|
||||||
self.fusion_gate = nn.Parameter(torch.zeros(1))
|
self.fusion_gate = nn.Parameter(torch.zeros(1))
|
||||||
|
|
||||||
# --- 编码器主体 (保持不变) ---
|
# --- 编码器主体 (HFR Upgrade) ---
|
||||||
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
||||||
self.pos_embed = nn.Parameter(torch.zeros(
|
self.pos_embed = nn.Parameter(torch.zeros(
|
||||||
1, num_patches + 1, embed_dim), requires_grad=False)
|
1, num_patches + 1, embed_dim), requires_grad=False)
|
||||||
|
|
||||||
|
# [修改] 使用 HFRBlock 替代 ConvEnhancedBlock
|
||||||
|
# HFRBlock 内部集成了流体卷积,所以不需要额外的 ConvEnhancedBlock 结构
|
||||||
self.encoder_blocks = nn.ModuleList([
|
self.encoder_blocks = nn.ModuleList([
|
||||||
ConvEnhancedBlock(dim=embed_dim, num_heads=num_heads,
|
HFRBlock(
|
||||||
mlp_ratio=mlp_ratio, norm_layer=norm_layer)
|
dim=embed_dim,
|
||||||
|
num_heads=num_heads,
|
||||||
|
mlp_ratio=mlp_ratio,
|
||||||
|
norm_layer=norm_layer,
|
||||||
|
fluid_kernel_size=fluid_kernel_size # 传递流体核大小
|
||||||
|
)
|
||||||
for _ in range(depth)])
|
for _ in range(depth)])
|
||||||
self.norm = norm_layer(embed_dim)
|
self.norm = norm_layer(embed_dim)
|
||||||
|
|
||||||
# --- 解码器 (保持不变) ---
|
# --- 解码器 (HFR Upgrade) ---
|
||||||
self.decoder_embed = nn.Linear(embed_dim, decoder_embed_dim, bias=True)
|
self.decoder_embed = nn.Linear(embed_dim, decoder_embed_dim, bias=True)
|
||||||
self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_embed_dim))
|
self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_embed_dim))
|
||||||
self.decoder_pos_embed = nn.Parameter(torch.zeros(
|
self.decoder_pos_embed = nn.Parameter(torch.zeros(
|
||||||
1, num_patches + 1, decoder_embed_dim), requires_grad=False)
|
1, num_patches + 1, decoder_embed_dim), requires_grad=False)
|
||||||
from timm.models.vision_transformer import Block
|
|
||||||
|
# [修改] 解码器也使用 HFRBlock,实现全链路线性复杂度
|
||||||
|
# 以前是: from timm.models.vision_transformer import Block
|
||||||
self.decoder_blocks = nn.ModuleList([
|
self.decoder_blocks = nn.ModuleList([
|
||||||
Block(dim=decoder_embed_dim, num_heads=decoder_num_heads,
|
HFRBlock(
|
||||||
mlp_ratio=mlp_ratio, norm_layer=norm_layer)
|
dim=decoder_embed_dim,
|
||||||
|
num_heads=decoder_num_heads,
|
||||||
|
mlp_ratio=mlp_ratio,
|
||||||
|
norm_layer=norm_layer,
|
||||||
|
fluid_kernel_size=fluid_kernel_size
|
||||||
|
)
|
||||||
for _ in range(decoder_depth)])
|
for _ in range(decoder_depth)])
|
||||||
self.decoder_norm = norm_layer(decoder_embed_dim)
|
self.decoder_norm = norm_layer(decoder_embed_dim)
|
||||||
|
|
||||||
# --- [核心修改] 三路重建头 ---
|
# --- 三路重建头 (保持不变) ---
|
||||||
# 1. CWT像素重建头 (保持不变)
|
|
||||||
self.decoder_pred_cwt = nn.Sequential(
|
self.decoder_pred_cwt = nn.Sequential(
|
||||||
nn.ConvTranspose2d(decoder_embed_dim, decoder_embed_dim //
|
nn.ConvTranspose2d(decoder_embed_dim, decoder_embed_dim //
|
||||||
2, kernel_size=3, stride=2, padding=1, output_padding=1),
|
2, kernel_size=3, stride=2, padding=1, output_padding=1),
|
||||||
@@ -102,13 +118,9 @@ class NormWear(nn.Module):
|
|||||||
kernel_size=3, stride=2, padding=1, output_padding=1)
|
kernel_size=3, stride=2, padding=1, output_padding=1)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2. 1D Token重建头 (保持不变)
|
|
||||||
self.decoder_pred_1d_token = nn.Linear(
|
self.decoder_pred_1d_token = nn.Linear(
|
||||||
decoder_embed_dim, embed_dim, bias=True)
|
decoder_embed_dim, embed_dim, bias=True)
|
||||||
|
|
||||||
# 3. [新增] 1D 原始信号重建头
|
|
||||||
# 这个头将学习一个近似的逆小波变换
|
|
||||||
# HybridPatchEmbed 降采样了 2*2*2=8 倍,所以我们需要上采样8倍
|
|
||||||
self.decoder_pred_1d_signal = nn.Sequential(
|
self.decoder_pred_1d_signal = nn.Sequential(
|
||||||
nn.ConvTranspose1d(decoder_embed_dim, decoder_embed_dim //
|
nn.ConvTranspose1d(decoder_embed_dim, decoder_embed_dim //
|
||||||
4, kernel_size=3, stride=2, padding=1, output_padding=1),
|
4, kernel_size=3, stride=2, padding=1, output_padding=1),
|
||||||
@@ -122,8 +134,9 @@ class NormWear(nn.Module):
|
|||||||
|
|
||||||
self.initialize_weights()
|
self.initialize_weights()
|
||||||
|
|
||||||
# --- [修改] 重命名 decoder_pred_1d -> decoder_pred_1d_token ---
|
# --- 后续函数保持不变 ---
|
||||||
def initialize_weights(self):
|
def initialize_weights(self):
|
||||||
|
# ... (保持不变) ...
|
||||||
pos_embed = get_2d_sincos_pos_embed_flexible(
|
pos_embed = get_2d_sincos_pos_embed_flexible(
|
||||||
self.pos_embed.shape[-1], self.patch_embed.patch_hw, cls_token=True)
|
self.pos_embed.shape[-1], self.patch_embed.patch_hw, cls_token=True)
|
||||||
self.pos_embed.data.copy_(
|
self.pos_embed.data.copy_(
|
||||||
@@ -137,6 +150,7 @@ class NormWear(nn.Module):
|
|||||||
self.apply(self._init_weights)
|
self.apply(self._init_weights)
|
||||||
|
|
||||||
def _init_weights(self, m):
|
def _init_weights(self, m):
|
||||||
|
# ... (保持不变) ...
|
||||||
if isinstance(m, nn.Linear):
|
if isinstance(m, nn.Linear):
|
||||||
torch.nn.init.xavier_uniform_(m.weight)
|
torch.nn.init.xavier_uniform_(m.weight)
|
||||||
if m.bias is not None:
|
if m.bias is not None:
|
||||||
@@ -144,14 +158,13 @@ class NormWear(nn.Module):
|
|||||||
elif isinstance(m, (nn.LayerNorm, nn.BatchNorm1d, nn.BatchNorm2d)):
|
elif isinstance(m, (nn.LayerNorm, nn.BatchNorm1d, nn.BatchNorm2d)):
|
||||||
nn.init.constant_(m.bias, 0)
|
nn.init.constant_(m.bias, 0)
|
||||||
nn.init.constant_(m.weight, 1.0)
|
nn.init.constant_(m.weight, 1.0)
|
||||||
# [修改] 增加 ConvTranspose1d
|
|
||||||
elif isinstance(m, (nn.Conv1d, nn.Conv2d, nn.ConvTranspose1d, nn.ConvTranspose2d)):
|
elif isinstance(m, (nn.Conv1d, nn.Conv2d, nn.ConvTranspose1d, nn.ConvTranspose2d)):
|
||||||
torch.nn.init.xavier_uniform_(m.weight)
|
torch.nn.init.xavier_uniform_(m.weight)
|
||||||
if m.bias is not None:
|
if m.bias is not None:
|
||||||
nn.init.constant_(m.bias, 0)
|
nn.init.constant_(m.bias, 0)
|
||||||
|
|
||||||
# --- 其他辅助函数 (保持不变) ---
|
|
||||||
def _forward_features(self, x_cwt, x_1d):
|
def _forward_features(self, x_cwt, x_1d):
|
||||||
|
# ... (保持不变) ...
|
||||||
cwt_tokens = self.patch_embed(x_cwt)
|
cwt_tokens = self.patch_embed(x_cwt)
|
||||||
cnn_1d_features = self.cnn_1d_extractor(
|
cnn_1d_features = self.cnn_1d_extractor(
|
||||||
x_1d.unsqueeze(1)).transpose(1, 2)
|
x_1d.unsqueeze(1)).transpose(1, 2)
|
||||||
@@ -166,6 +179,7 @@ class NormWear(nn.Module):
|
|||||||
return fused_tokens, cwt_tokens, cnn_1d_tokens
|
return fused_tokens, cwt_tokens, cnn_1d_tokens
|
||||||
|
|
||||||
def forward_encoder(self, fused_tokens, mask_ratio):
|
def forward_encoder(self, fused_tokens, mask_ratio):
|
||||||
|
# ... (保持不变) ...
|
||||||
tokens_with_pos = fused_tokens + self.pos_embed[:, 1:, :]
|
tokens_with_pos = fused_tokens + self.pos_embed[:, 1:, :]
|
||||||
tokens_masked, mask, ids_restore = random_masking(
|
tokens_masked, mask, ids_restore = random_masking(
|
||||||
tokens_with_pos, mask_ratio)
|
tokens_with_pos, mask_ratio)
|
||||||
@@ -178,6 +192,7 @@ class NormWear(nn.Module):
|
|||||||
return x, mask, ids_restore
|
return x, mask, ids_restore
|
||||||
|
|
||||||
def forward_decoder(self, x, ids_restore):
|
def forward_decoder(self, x, ids_restore):
|
||||||
|
# ... (保持不变) ...
|
||||||
x = self.decoder_embed(x)
|
x = self.decoder_embed(x)
|
||||||
mask_tokens = self.mask_token.repeat(
|
mask_tokens = self.mask_token.repeat(
|
||||||
x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1)
|
x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1)
|
||||||
@@ -191,16 +206,9 @@ class NormWear(nn.Module):
|
|||||||
x = self.decoder_norm(x)
|
x = self.decoder_norm(x)
|
||||||
return x
|
return x
|
||||||
|
|
||||||
# --- [核心修改] forward_loss 函数,计算三路损失 ---
|
def forward_loss(self, pred_cwt_imgs, x_cwt_orig, pred_1d_tokens, cnn_1d_tokens_orig, pred_1d_signal, x_1d_orig, mask):
|
||||||
def forward_loss(self,
|
# ... (保持不变) ...
|
||||||
pred_cwt_imgs, x_cwt_orig,
|
# 1. CWT重建损失
|
||||||
pred_1d_tokens, cnn_1d_tokens_orig,
|
|
||||||
pred_1d_signal, x_1d_orig,
|
|
||||||
mask):
|
|
||||||
"""
|
|
||||||
计算三路重建损失。
|
|
||||||
"""
|
|
||||||
# 1. CWT重建损失 (在像素空间)
|
|
||||||
pred_cwt_imgs = pred_cwt_imgs[:, :,
|
pred_cwt_imgs = pred_cwt_imgs[:, :,
|
||||||
:x_cwt_orig.shape[2], :x_cwt_orig.shape[3]]
|
:x_cwt_orig.shape[2], :x_cwt_orig.shape[3]]
|
||||||
loss_cwt = (pred_cwt_imgs - x_cwt_orig) ** 2
|
loss_cwt = (pred_cwt_imgs - x_cwt_orig) ** 2
|
||||||
@@ -217,28 +225,23 @@ class NormWear(nn.Module):
|
|||||||
|
|
||||||
loss_cwt = (loss_cwt * mask_pixel).sum() / (mask_pixel.sum() + 1e-8)
|
loss_cwt = (loss_cwt * mask_pixel).sum() / (mask_pixel.sum() + 1e-8)
|
||||||
|
|
||||||
# 2. 1D Token重建损失 (在特征空间)
|
# 2. 1D Token重建损失
|
||||||
loss_1d_token = ((pred_1d_tokens - cnn_1d_tokens_orig)
|
loss_1d_token = ((pred_1d_tokens - cnn_1d_tokens_orig)
|
||||||
** 2).mean(dim=-1)
|
** 2).mean(dim=-1)
|
||||||
loss_1d_token = (loss_1d_token * mask).sum() / (mask.sum() + 1e-8)
|
loss_1d_token = (loss_1d_token * mask).sum() / (mask.sum() + 1e-8)
|
||||||
|
|
||||||
# 3. [新增] 1D 原始信号重建损失 (在信号空间)
|
# 3. 1D 原始信号重建损失
|
||||||
# 创建一个与原始信号长度匹配的掩码
|
|
||||||
mask_signal = mask.reshape(
|
mask_signal = mask.reshape(
|
||||||
mask.shape[0], self.patch_embed.patch_hw[0], self.patch_embed.patch_hw[1])
|
mask.shape[0], self.patch_embed.patch_hw[0], self.patch_embed.patch_hw[1])
|
||||||
# 我们只关心时间维度的掩码
|
mask_signal = mask_signal[:, :, 0]
|
||||||
mask_signal = mask_signal[:, :, 0] # Shape: [B, H_patches]
|
|
||||||
mask_signal = mask_signal.unsqueeze(-1).repeat_interleave(
|
mask_signal = mask_signal.unsqueeze(-1).repeat_interleave(
|
||||||
self.patch_size[0], dim=-1).flatten(1, 2)
|
self.patch_size[0], dim=-1).flatten(1, 2)
|
||||||
mask_signal = mask_signal[:, :x_1d_orig.shape[1]] # 裁剪到精确长度
|
mask_signal = mask_signal[:, :x_1d_orig.shape[1]]
|
||||||
|
|
||||||
loss_1d_signal = (pred_1d_signal - x_1d_orig) ** 2
|
loss_1d_signal = (pred_1d_signal - x_1d_orig) ** 2
|
||||||
loss_1d_signal = (loss_1d_signal * mask_signal).sum() / \
|
loss_1d_signal = (loss_1d_signal * mask_signal).sum() / \
|
||||||
(mask_signal.sum() + 1e-8)
|
(mask_signal.sum() + 1e-8)
|
||||||
if torch.rand(1) < 0.01: # 每1%的概率打印一次,避免刷屏
|
|
||||||
print(
|
|
||||||
f"\n[Loss Debug] CWT: {loss_cwt.item():.4f}, Token: {loss_1d_token.item():.4f}, Signal: {loss_1d_signal.item():.4f}")
|
|
||||||
|
|
||||||
# 4. 加权总损失
|
# 4. 加权总损失
|
||||||
loss_cwt_weight = 1 - self.loss_weight_1d_token - self.loss_weight_1d_signal
|
loss_cwt_weight = 1 - self.loss_weight_1d_token - self.loss_weight_1d_signal
|
||||||
total_loss = (loss_cwt_weight * loss_cwt +
|
total_loss = (loss_cwt_weight * loss_cwt +
|
||||||
@@ -247,13 +250,12 @@ class NormWear(nn.Module):
|
|||||||
|
|
||||||
return total_loss, loss_cwt, loss_1d_token, loss_1d_signal
|
return total_loss, loss_cwt, loss_1d_token, loss_1d_signal
|
||||||
|
|
||||||
# --- [核心修改] 主 forward 函数 ---
|
|
||||||
def forward(self, x_cwt, x_1d, mask_ratio=0.75):
|
def forward(self, x_cwt, x_1d, mask_ratio=0.75):
|
||||||
|
# ... (保持不变) ...
|
||||||
N, nvar, ch, L, F_ = x_cwt.shape
|
N, nvar, ch, L, F_ = x_cwt.shape
|
||||||
x_cwt_reshaped = x_cwt.reshape(N * nvar, ch, L, F_)
|
x_cwt_reshaped = x_cwt.reshape(N * nvar, ch, L, F_)
|
||||||
x_1d_reshaped = x_1d.reshape(N * nvar, L)
|
x_1d_reshaped = x_1d.reshape(N * nvar, L)
|
||||||
|
|
||||||
# --- 步骤 1: 计算所有原始目标 ---
|
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
orig_cnn_1d_features = self.cnn_1d_extractor(
|
orig_cnn_1d_features = self.cnn_1d_extractor(
|
||||||
x_1d_reshaped.unsqueeze(1)).transpose(1, 2)
|
x_1d_reshaped.unsqueeze(1)).transpose(1, 2)
|
||||||
@@ -261,10 +263,8 @@ class NormWear(nn.Module):
|
|||||||
cnn_1d_tokens_orig_target = orig_cnn_1d_features.unsqueeze(
|
cnn_1d_tokens_orig_target = orig_cnn_1d_features.unsqueeze(
|
||||||
2).expand(-1, -1, num_freq_patches, -1).flatten(1, 2)
|
2).expand(-1, -1, num_freq_patches, -1).flatten(1, 2)
|
||||||
|
|
||||||
# 原始1D信号本身就是目标
|
|
||||||
x_1d_orig_target = x_1d_reshaped
|
x_1d_orig_target = x_1d_reshaped
|
||||||
|
|
||||||
# --- 步骤 2: 模态丢弃 ---
|
|
||||||
x_cwt_for_encoder = x_cwt_reshaped
|
x_cwt_for_encoder = x_cwt_reshaped
|
||||||
x_1d_for_encoder = x_1d_reshaped
|
x_1d_for_encoder = x_1d_reshaped
|
||||||
if self.training and self.modality_dropout_prob > 0 and torch.rand(1).item() < self.modality_dropout_prob:
|
if self.training and self.modality_dropout_prob > 0 and torch.rand(1).item() < self.modality_dropout_prob:
|
||||||
@@ -274,58 +274,48 @@ class NormWear(nn.Module):
|
|||||||
elif modal_to_drop == 1:
|
elif modal_to_drop == 1:
|
||||||
x_1d_for_encoder = torch.zeros_like(x_1d_reshaped)
|
x_1d_for_encoder = torch.zeros_like(x_1d_reshaped)
|
||||||
|
|
||||||
# --- 步骤 3: 特征提取和融合 ---
|
|
||||||
fused_tokens, _, _ = self._forward_features(
|
fused_tokens, _, _ = self._forward_features(
|
||||||
x_cwt_for_encoder, x_1d_for_encoder)
|
x_cwt_for_encoder, x_1d_for_encoder)
|
||||||
|
|
||||||
# --- 步骤 4: 编码、解码 ---
|
|
||||||
latent, mask, ids_restore = self.forward_encoder(
|
latent, mask, ids_restore = self.forward_encoder(
|
||||||
fused_tokens, mask_ratio)
|
fused_tokens, mask_ratio)
|
||||||
decoded_features = self.forward_decoder(latent, ids_restore)
|
decoded_features = self.forward_decoder(latent, ids_restore)
|
||||||
|
|
||||||
# --- 步骤 5: 三路重建 ---
|
|
||||||
decoded_patches = decoded_features[:, 1:, :]
|
decoded_patches = decoded_features[:, 1:, :]
|
||||||
h_patch, w_patch = self.patch_embed.patch_hw
|
h_patch, w_patch = self.patch_embed.patch_hw
|
||||||
decoded_feature_map = decoded_patches.reshape(
|
decoded_feature_map = decoded_patches.reshape(
|
||||||
decoded_patches.shape[0], h_patch, w_patch, -1).permute(0, 3, 1, 2)
|
decoded_patches.shape[0], h_patch, w_patch, -1).permute(0, 3, 1, 2)
|
||||||
|
|
||||||
# 5.1 CWT 图像重建
|
|
||||||
pred_cwt_imgs = self.decoder_pred_cwt(decoded_feature_map)
|
pred_cwt_imgs = self.decoder_pred_cwt(decoded_feature_map)
|
||||||
pred_cwt_imgs = pred_cwt_imgs[:, :, :L, :F_]
|
pred_cwt_imgs = pred_cwt_imgs[:, :, :L, :F_]
|
||||||
|
|
||||||
# 5.2 1D Token 重建
|
|
||||||
pred_1d_tokens = self.decoder_pred_1d_token(decoded_features)[:, 1:, :]
|
pred_1d_tokens = self.decoder_pred_1d_token(decoded_features)[:, 1:, :]
|
||||||
|
|
||||||
# 5.3 [新增] 1D 原始信号重建
|
|
||||||
# 我们需要从2D特征图解码,所以先对频率维度做平均池化,得到时间序列特征
|
|
||||||
decoded_features_for_1d_signal = torch.mean(
|
decoded_features_for_1d_signal = torch.mean(
|
||||||
decoded_feature_map, dim=3) # Shape: [B, D_decoder, H_patch]
|
decoded_feature_map, dim=3)
|
||||||
pred_1d_signal_unshaped = self.decoder_pred_1d_signal(
|
pred_1d_signal_unshaped = self.decoder_pred_1d_signal(
|
||||||
decoded_features_for_1d_signal)
|
decoded_features_for_1d_signal)
|
||||||
pred_1d_signal = pred_1d_signal_unshaped.squeeze(
|
pred_1d_signal = pred_1d_signal_unshaped.squeeze(
|
||||||
1)[:, :L] # Shape: [B, L]
|
1)[:, :L]
|
||||||
|
|
||||||
# --- 步骤 6: 计算损失 ---
|
|
||||||
loss, _, _, _ = self.forward_loss(
|
loss, _, _, _ = self.forward_loss(
|
||||||
pred_cwt_imgs=pred_cwt_imgs,
|
pred_cwt_imgs=pred_cwt_imgs,
|
||||||
x_cwt_orig=x_cwt_reshaped,
|
x_cwt_orig=x_cwt_reshaped,
|
||||||
pred_1d_tokens=pred_1d_tokens,
|
pred_1d_tokens=pred_1d_tokens,
|
||||||
cnn_1d_tokens_orig=cnn_1d_tokens_orig_target,
|
cnn_1d_tokens_orig=cnn_1d_tokens_orig_target,
|
||||||
pred_1d_signal=pred_1d_signal, # <-- 新增
|
pred_1d_signal=pred_1d_signal,
|
||||||
x_1d_orig=x_1d_orig_target, # <-- 新增
|
x_1d_orig=x_1d_orig_target,
|
||||||
mask=mask
|
mask=mask
|
||||||
)
|
)
|
||||||
|
|
||||||
# --- 步骤 7: 返回值 ---
|
|
||||||
pred_pixels_unshaped = pred_cwt_imgs.view(N, nvar, ch, L, F_)
|
pred_pixels_unshaped = pred_cwt_imgs.view(N, nvar, ch, L, F_)
|
||||||
pred_signal_unshaped = pred_1d_signal.view(N, nvar, L) # [新增]
|
pred_signal_unshaped = pred_1d_signal.view(N, nvar, L)
|
||||||
mask_unshaped = mask.view(N, nvar, -1)
|
mask_unshaped = mask.view(N, nvar, -1)
|
||||||
|
|
||||||
# [修改] 返回值中可以加入重建的信号,方便可视化
|
|
||||||
return loss, pred_pixels_unshaped, pred_signal_unshaped, mask_unshaped
|
return loss, pred_pixels_unshaped, pred_signal_unshaped, mask_unshaped
|
||||||
|
|
||||||
# --- get_signal_embedding (保持不变) ---
|
|
||||||
def get_signal_embedding(self, x_cwt, x_1d):
|
def get_signal_embedding(self, x_cwt, x_1d):
|
||||||
|
# ... (保持不变) ...
|
||||||
self.eval()
|
self.eval()
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
N, nvar, ch, L, F_ = x_cwt.shape
|
N, nvar, ch, L, F_ = x_cwt.shape
|
||||||
@@ -347,4 +337,4 @@ class NormWear(nn.Module):
|
|||||||
|
|
||||||
BN, P, E = x.shape
|
BN, P, E = x.shape
|
||||||
final_features = torch.reshape(x, (N, nvar, P, E))
|
final_features = torch.reshape(x, (N, nvar, P, E))
|
||||||
return final_features
|
return final_features
|
||||||
@@ -2,222 +2,20 @@
|
|||||||
|
|
||||||
import pickle
|
import pickle
|
||||||
import os
|
import os
|
||||||
from torch.utils.data import Dataset
|
|
||||||
import random
|
import random
|
||||||
from tqdm import tqdm
|
|
||||||
import torch
|
|
||||||
from torch.utils.data import DataLoader
|
|
||||||
from torch.utils.data._utils.collate import default_collate
|
|
||||||
import torch.nn.functional as F
|
|
||||||
import json
|
import json
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import torch.nn.functional as F
|
||||||
|
from torch.utils.data import Dataset, DataLoader
|
||||||
|
from torch.utils.data._utils.collate import default_collate
|
||||||
from torchvision import transforms
|
from torchvision import transforms
|
||||||
|
from tqdm import tqdm
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
class LinearProbDataset(Dataset):
|
# CWT 工具函数 (保持不变,逻辑清晰)
|
||||||
def __init__(self, fnames, task):
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
# self.dataset_path = os.path.join(data_dir,dataset_name,'samples')
|
|
||||||
self.fnames = fnames
|
|
||||||
self.max_L = 387 # fix length
|
|
||||||
self.task = task
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
return len(self.fnames)
|
|
||||||
|
|
||||||
def __getitem__(self, idx):
|
|
||||||
f_path = self.fnames[idx]
|
|
||||||
|
|
||||||
with open(f_path, 'rb') as f:
|
|
||||||
data_dict = pickle.load(f)
|
|
||||||
|
|
||||||
# x = torch.from_numpy(data_dict['cwt']).permute(0, 3, 1, 2) # n_var, 3, L, 65
|
|
||||||
x = torch.from_numpy(data_dict['cwt']) # n_var, 3, L, 65
|
|
||||||
'''
|
|
||||||
在使用cwt_wrap函数时已经进行了变换
|
|
||||||
'''
|
|
||||||
|
|
||||||
if torch.isnan(x).any():
|
|
||||||
return None # Ignore the sample with NaN values
|
|
||||||
|
|
||||||
n_var, n_channels, L, H = x.size()
|
|
||||||
padded_inputs = torch.zeros((n_var, n_channels, self.max_L, H))
|
|
||||||
|
|
||||||
if L < self.max_L:
|
|
||||||
padded_inputs[:, :, -L:, :] = x
|
|
||||||
else:
|
|
||||||
padded_inputs = x[:, :, -self.max_L:, :]
|
|
||||||
|
|
||||||
label = data_dict['label']
|
|
||||||
|
|
||||||
if isinstance(label, dict):
|
|
||||||
values = [label[key] for key in label.keys()]
|
|
||||||
label = values
|
|
||||||
|
|
||||||
if self.task == "reg":
|
|
||||||
label = torch.tensor(label).float()
|
|
||||||
else:
|
|
||||||
label = torch.tensor(label).long()
|
|
||||||
|
|
||||||
return {
|
|
||||||
'input': padded_inputs,
|
|
||||||
'label': label,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def linprob_collate_fn(batch):
|
|
||||||
batch = [b for b in batch if b is not None]
|
|
||||||
return default_collate(batch)
|
|
||||||
|
|
||||||
########################################################################################################################################################
|
|
||||||
########################################################################################################################################################
|
|
||||||
########################################################################################################################################################
|
|
||||||
########################################################################################################################################################
|
|
||||||
|
|
||||||
|
|
||||||
class PretrainDataset(Dataset):
|
|
||||||
# [修改] 增加 subset_fraction 参数
|
|
||||||
def __init__(self, data_dir, dataset_names, is_test=0,
|
|
||||||
window_size=387,
|
|
||||||
stride=100,
|
|
||||||
img_size=(387, 65),
|
|
||||||
cache_name: str = None,
|
|
||||||
subset_fraction: float = 0.15): # [新增] 控制数据量的参数
|
|
||||||
|
|
||||||
self.window_size = window_size
|
|
||||||
self.stride = stride
|
|
||||||
|
|
||||||
# --- [修改] 缓存逻辑 ---
|
|
||||||
# 1. 如果手动指定了缓存名,则直接使用它,这是最优先、最稳定的方式。
|
|
||||||
if cache_name:
|
|
||||||
# 确保它是一个 .pkl 文件
|
|
||||||
if not cache_name.endswith('.pkl'):
|
|
||||||
cache_name += '.pkl'
|
|
||||||
cache_path = os.path.join(data_dir, cache_name)
|
|
||||||
print(
|
|
||||||
f"Attempting to load from manually specified cache: {cache_path}")
|
|
||||||
else:
|
|
||||||
# 2. 如果没有手动指定,则使用稳定的方法生成文件名 (不再使用不稳定的 hash)
|
|
||||||
# 将数据集名称排序并用'-'连接,这比哈希更稳定
|
|
||||||
dataset_str = "-".join(sorted(dataset_names))
|
|
||||||
cache_filename = f"pretrain_windows_ds_{dataset_str}_ws{window_size}_s{stride}.pkl"
|
|
||||||
cache_path = os.path.join(data_dir, cache_filename)
|
|
||||||
|
|
||||||
# 3. 检查缓存是否存在 (测试模式下总会重新计算,不使用缓存)
|
|
||||||
if os.path.exists(cache_path) and not is_test:
|
|
||||||
print(f"Loading pre-computed windows from cache: {cache_path}")
|
|
||||||
with open(cache_path, 'rb') as f:
|
|
||||||
self.windows = pickle.load(f)
|
|
||||||
else:
|
|
||||||
# 4. 如果缓存不存在,则执行耗时的计算过程
|
|
||||||
if is_test:
|
|
||||||
print("Running in test mode, bypassing cache...")
|
|
||||||
else:
|
|
||||||
print(
|
|
||||||
f"No cache found at '{cache_path}'. Preprocessing dataset (this will happen only once for this configuration)...")
|
|
||||||
|
|
||||||
fnames = [
|
|
||||||
os.path.join(data_dir, dataset_name, fn)
|
|
||||||
for dataset_name in dataset_names
|
|
||||||
for fn in sorted(os.listdir(os.path.join(data_dir, dataset_name)))
|
|
||||||
if fn[0] != "."
|
|
||||||
]
|
|
||||||
if is_test == 1:
|
|
||||||
fnames = fnames[:20]
|
|
||||||
|
|
||||||
self.windows = []
|
|
||||||
for fname in tqdm(fnames, desc="Calculating windows"):
|
|
||||||
try:
|
|
||||||
with open(fname, 'rb') as f:
|
|
||||||
data_dict = pickle.load(f)
|
|
||||||
|
|
||||||
_, L = torch.from_numpy(data_dict['data']).float().shape
|
|
||||||
|
|
||||||
if L < self.window_size:
|
|
||||||
continue
|
|
||||||
|
|
||||||
num_windows = (L - self.window_size) // self.stride + 1
|
|
||||||
for i in range(num_windows):
|
|
||||||
self.windows.append((fname, i * self.stride))
|
|
||||||
except Exception as e:
|
|
||||||
# print(f"Warning: Could not process file {fname}. Error: {e}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 5. 如果不是测试模式,将计算结果保存到缓存文件
|
|
||||||
if not is_test:
|
|
||||||
print(
|
|
||||||
f"Saving computed windows to cache for future use: {cache_path}")
|
|
||||||
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
|
||||||
with open(cache_path, 'wb') as f:
|
|
||||||
pickle.dump(self.windows, f)
|
|
||||||
|
|
||||||
# [新增] 根据 subset_fraction 参数对数据进行子集采样
|
|
||||||
if subset_fraction < 1.0:
|
|
||||||
if not (0.0 < subset_fraction <= 1.0):
|
|
||||||
raise ValueError("subset_fraction must be between 0.0 and 1.0")
|
|
||||||
|
|
||||||
num_samples = int(len(self.windows) * subset_fraction)
|
|
||||||
|
|
||||||
# 使用固定的种子来确保每次采样的子集是相同的,保证实验可复现
|
|
||||||
rng = random.Random(42)
|
|
||||||
rng.shuffle(self.windows)
|
|
||||||
|
|
||||||
self.windows = self.windows[:num_samples]
|
|
||||||
print(
|
|
||||||
f"[INFO] Pre-training with a subset of {len(self.windows)} windows ({subset_fraction * 100:.1f}% of the total).")
|
|
||||||
|
|
||||||
print(f"Dataset initialized with {len(self.windows)} windows.")
|
|
||||||
|
|
||||||
# --- CWT 和数据增强部分保持不变 ---
|
|
||||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
|
||||||
self.transform = transforms.Compose([
|
|
||||||
transforms.RandomResizedCrop(
|
|
||||||
size=(img_size[1], img_size[0]), scale=(0.5, 1.0), antialias=True),
|
|
||||||
transforms.RandomHorizontalFlip(), # 水平翻转对于时频谱图是有效增强
|
|
||||||
])
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
return len(self.windows)
|
|
||||||
|
|
||||||
def __getitem__(self, idx):
|
|
||||||
try:
|
|
||||||
fname, start_idx = self.windows[idx]
|
|
||||||
|
|
||||||
with open(fname, 'rb') as f:
|
|
||||||
data_dict = pickle.load(f)
|
|
||||||
|
|
||||||
full_signal = torch.from_numpy(data_dict['data']).float()
|
|
||||||
raw_signal_window = full_signal[:,
|
|
||||||
start_idx: start_idx + self.window_size]
|
|
||||||
|
|
||||||
# 清理和标准化1D信号
|
|
||||||
if not torch.all(torch.isfinite(raw_signal_window)):
|
|
||||||
raw_signal_window = torch.nan_to_num(
|
|
||||||
raw_signal_window, nan=0.0)
|
|
||||||
mean = torch.mean(raw_signal_window, dim=1, keepdim=True)
|
|
||||||
std = torch.std(raw_signal_window, dim=1, keepdim=True)
|
|
||||||
std[std == 0] = 1.0
|
|
||||||
processed_signal_1d = (raw_signal_window - mean) / (std + 1e-8)
|
|
||||||
|
|
||||||
# 2. 生成CWT图像
|
|
||||||
cwt_images = cwt_wrap(processed_signal_1d, self.cwt_scales)
|
|
||||||
if not torch.all(torch.isfinite(cwt_images)):
|
|
||||||
return None
|
|
||||||
|
|
||||||
# 3. 对CWT图像进行数据增强,作为模型的输入
|
|
||||||
cwt_images_permuted = cwt_images.permute(0, 1, 3, 2)
|
|
||||||
augmented_cwt_permuted = self.transform(cwt_images_permuted)
|
|
||||||
augmented_cwt = augmented_cwt_permuted.permute(0, 1, 3, 2)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'input_cwt': augmented_cwt,
|
|
||||||
'input_1d': processed_signal_1d, # 预测目标
|
|
||||||
}
|
|
||||||
except Exception as e:
|
|
||||||
# print(f"Error processing window at index {idx}: {e}. Skipping.")
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def ricker_wavelet(points, scale):
|
def ricker_wavelet(points, scale):
|
||||||
"""Generate the Ricker (Mexican hat) wavelet for a given scale."""
|
"""Generate the Ricker (Mexican hat) wavelet for a given scale."""
|
||||||
@@ -230,196 +28,216 @@ def ricker_wavelet(points, scale):
|
|||||||
gauss = torch.exp(-xsq / (2 * wsq))
|
gauss = torch.exp(-xsq / (2 * wsq))
|
||||||
return A * mod * gauss
|
return A * mod * gauss
|
||||||
|
|
||||||
|
|
||||||
def cwt_ricker(x, scales, wavelet_len):
|
def cwt_ricker(x, scales, wavelet_len):
|
||||||
"""
|
"""Compute the CWT using the Ricker wavelet."""
|
||||||
Compute the CWT using the Ricker wavelet.
|
|
||||||
Args:
|
|
||||||
x (torch.Tensor): Input time-series of shape (batch, sequence_length).
|
|
||||||
scales (torch.Tensor): 1D Tensor of scales to use.
|
|
||||||
wavelet_len (int): Length of the wavelet kernel.
|
|
||||||
"""
|
|
||||||
batch_size, sequence_length = x.shape
|
batch_size, sequence_length = x.shape
|
||||||
x = x.unsqueeze(1) # -> (batch, 1, sequence_length)
|
x = x.unsqueeze(1)
|
||||||
|
|
||||||
num_scales = scales.shape[0]
|
num_scales = scales.shape[0]
|
||||||
scales = scales.to(x.device)
|
scales = scales.to(x.device)
|
||||||
|
|
||||||
effective_wavelet_len = min(wavelet_len, sequence_length)
|
effective_wavelet_len = min(wavelet_len, sequence_length)
|
||||||
wavelets = torch.stack(
|
wavelets = torch.stack([ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
|
||||||
[ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
|
|
||||||
# -> (num_scales, 1, wavelet_len)
|
|
||||||
wavelets = wavelets.view(num_scales, 1, -1)
|
wavelets = wavelets.view(num_scales, 1, -1)
|
||||||
|
|
||||||
cwt_output = F.conv1d(x, wavelets, padding='same')
|
cwt_output = F.conv1d(x, wavelets, padding='same')
|
||||||
return cwt_output # -> (batch, num_scales, sequence_length)
|
return cwt_output
|
||||||
|
|
||||||
|
|
||||||
def cwt_wrap(x, scales):
|
def cwt_wrap(x, scales):
|
||||||
"""
|
"""
|
||||||
Wrapper for CWT computation.
|
Wrapper for CWT computation.
|
||||||
Args:
|
Returns: (n_var, 3, L, num_scales) -> permuted later if needed
|
||||||
x (torch.Tensor): Input signal of shape (n_var, L).
|
|
||||||
scales (torch.Tensor): 1D Tensor of scales to use for CWT.
|
|
||||||
Returns:
|
|
||||||
torch.Tensor: CWT result of shape (n_var, 3, L, num_scales).
|
|
||||||
"""
|
"""
|
||||||
n_var, L = x.shape
|
n_var, L = x.shape
|
||||||
|
|
||||||
# 1. Calculate derivatives
|
|
||||||
d1 = x[:, 1:] - x[:, :-1]
|
d1 = x[:, 1:] - x[:, :-1]
|
||||||
d2 = d1[:, 1:] - d1[:, :-1]
|
d2 = d1[:, 1:] - d1[:, :-1]
|
||||||
|
|
||||||
# 2. Align signals by padding them to the same length L
|
|
||||||
original_x = x
|
original_x = x
|
||||||
d1_padded = F.pad(d1, (1, 0), 'replicate')
|
d1_padded = F.pad(d1, (1, 0), 'replicate')
|
||||||
d2_padded = F.pad(d2, (2, 0), 'replicate')
|
d2_padded = F.pad(d2, (2, 0), 'replicate')
|
||||||
|
stacked_x = torch.stack([original_x, d1_padded, d2_padded], dim=1)
|
||||||
# 3. Stack the aligned signals
|
|
||||||
stacked_x = torch.stack(
|
|
||||||
[original_x, d1_padded, d2_padded], dim=1) # -> (n_var, 3, L)
|
|
||||||
|
|
||||||
n_var, n_channels, L_stacked = stacked_x.shape
|
n_var, n_channels, L_stacked = stacked_x.shape
|
||||||
flat_x = stacked_x.reshape(n_var * n_channels, L_stacked)
|
flat_x = stacked_x.reshape(n_var * n_channels, L_stacked)
|
||||||
|
wavelet_len = 257
|
||||||
# 4. Compute CWT
|
|
||||||
wavelet_len = 257 # A fixed reasonable length
|
|
||||||
# -> (n_var * 3, num_scales, L)
|
|
||||||
cwt_res = cwt_ricker(flat_x, scales, wavelet_len)
|
cwt_res = cwt_ricker(flat_x, scales, wavelet_len)
|
||||||
|
|
||||||
_, n_scales, _ = cwt_res.shape
|
_, n_scales, _ = cwt_res.shape
|
||||||
|
final_cwt = cwt_res.reshape(n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
|
||||||
# 5. Reshape to final format
|
|
||||||
final_cwt = cwt_res.reshape(
|
|
||||||
n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
|
|
||||||
|
|
||||||
return final_cwt
|
return final_cwt
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# 预训练数据集 (PretrainDataset)
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
def collate_fn(batch, pad_nvar=5):
|
class PretrainDataset(Dataset):
|
||||||
|
def __init__(self, data_dir, dataset_names, is_test=0,
|
||||||
|
window_size=387, stride=100, img_size=(387, 65),
|
||||||
|
cache_name: str = None, subset_fraction: float = 0.1,
|
||||||
|
force_recompute: bool = False): # [新增] 强制重算参数
|
||||||
|
|
||||||
|
self.window_size = window_size
|
||||||
|
self.stride = stride
|
||||||
|
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||||
|
|
||||||
|
# 数据增强
|
||||||
|
self.transform = transforms.Compose([
|
||||||
|
transforms.RandomResizedCrop(size=(img_size[1], img_size[0]), scale=(0.5, 1.0), antialias=True),
|
||||||
|
transforms.RandomHorizontalFlip(),
|
||||||
|
])
|
||||||
|
|
||||||
|
# --- 缓存逻辑 ---
|
||||||
|
if cache_name:
|
||||||
|
if not cache_name.endswith('.pkl'): cache_name += '.pkl'
|
||||||
|
cache_path = os.path.join(data_dir, cache_name)
|
||||||
|
else:
|
||||||
|
dataset_str = "-".join(sorted(dataset_names))
|
||||||
|
cache_filename = f"pretrain_windows_ds_{dataset_str}_ws{window_size}_s{stride}.pkl"
|
||||||
|
cache_path = os.path.join(data_dir, cache_filename)
|
||||||
|
|
||||||
|
if os.path.exists(cache_path) and not is_test and not force_recompute:
|
||||||
|
print(f"Loading pre-computed windows from cache: {cache_path}")
|
||||||
|
with open(cache_path, 'rb') as f:
|
||||||
|
self.windows = pickle.load(f)
|
||||||
|
else:
|
||||||
|
if is_test: print("Running in test mode, bypassing cache...")
|
||||||
|
else: print(f"Preprocessing dataset (cache not found or forced)...")
|
||||||
|
|
||||||
|
fnames = [
|
||||||
|
os.path.join(data_dir, dataset_name, fn)
|
||||||
|
for dataset_name in dataset_names
|
||||||
|
for fn in sorted(os.listdir(os.path.join(data_dir, dataset_name)))
|
||||||
|
if fn[0] != "."
|
||||||
|
]
|
||||||
|
if is_test == 1: fnames = fnames[:20]
|
||||||
|
|
||||||
|
self.windows = []
|
||||||
|
for fname in tqdm(fnames, desc="Calculating windows"):
|
||||||
|
try:
|
||||||
|
with open(fname, 'rb') as f:
|
||||||
|
data_dict = pickle.load(f)
|
||||||
|
_, L = torch.from_numpy(data_dict['data']).float().shape
|
||||||
|
if L < self.window_size: continue
|
||||||
|
num_windows = (L - self.window_size) // self.stride + 1
|
||||||
|
for i in range(num_windows):
|
||||||
|
self.windows.append((fname, i * self.stride))
|
||||||
|
except Exception: continue
|
||||||
|
|
||||||
|
if not is_test:
|
||||||
|
print(f"Saving computed windows to cache: {cache_path}")
|
||||||
|
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
||||||
|
with open(cache_path, 'wb') as f:
|
||||||
|
pickle.dump(self.windows, f)
|
||||||
|
|
||||||
|
# --- 子集采样 ---
|
||||||
|
if subset_fraction < 1.0:
|
||||||
|
num_samples = int(len(self.windows) * subset_fraction)
|
||||||
|
random.Random(42).shuffle(self.windows)
|
||||||
|
self.windows = self.windows[:num_samples]
|
||||||
|
print(f"[INFO] Pre-training with subset: {len(self.windows)} windows ({subset_fraction*100:.1f}%).")
|
||||||
|
|
||||||
|
print(f"Dataset initialized with {len(self.windows)} windows.")
|
||||||
|
|
||||||
|
def __len__(self): return len(self.windows)
|
||||||
|
|
||||||
|
def __getitem__(self, idx):
|
||||||
|
try:
|
||||||
|
fname, start_idx = self.windows[idx]
|
||||||
|
with open(fname, 'rb') as f:
|
||||||
|
data_dict = pickle.load(f)
|
||||||
|
|
||||||
|
full_signal = torch.from_numpy(data_dict['data']).float()
|
||||||
|
raw_signal_window = full_signal[:, start_idx: start_idx + self.window_size]
|
||||||
|
|
||||||
|
if not torch.all(torch.isfinite(raw_signal_window)):
|
||||||
|
raw_signal_window = torch.nan_to_num(raw_signal_window, nan=0.0)
|
||||||
|
|
||||||
|
# 标准化
|
||||||
|
mean = torch.mean(raw_signal_window, dim=1, keepdim=True)
|
||||||
|
std = torch.std(raw_signal_window, dim=1, keepdim=True)
|
||||||
|
std[std == 0] = 1.0
|
||||||
|
processed_signal_1d = (raw_signal_window - mean) / (std + 1e-8)
|
||||||
|
|
||||||
|
# CWT
|
||||||
|
cwt_images = cwt_wrap(processed_signal_1d, self.cwt_scales)
|
||||||
|
if not torch.all(torch.isfinite(cwt_images)): return None
|
||||||
|
|
||||||
|
# Augmentation
|
||||||
|
cwt_images_permuted = cwt_images.permute(0, 1, 3, 2)
|
||||||
|
augmented_cwt_permuted = self.transform(cwt_images_permuted)
|
||||||
|
augmented_cwt = augmented_cwt_permuted.permute(0, 1, 3, 2)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'input_cwt': augmented_cwt,
|
||||||
|
'input_1d': processed_signal_1d,
|
||||||
|
}
|
||||||
|
except Exception: return None
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# 微调数据集基类 (BaseFineTuneDataset) - 减少代码冗余
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class BaseFineTuneDataset(Dataset):
|
||||||
"""
|
"""
|
||||||
一个为MAE预训练设计的collate_fn。
|
微调数据集的基类,封装了通用的信号处理、增强和CWT逻辑。
|
||||||
- 过滤无效样本 (None)。
|
|
||||||
- 处理分布式训练中可能出现的空batch。
|
|
||||||
- 对每个样本的变量数量(n_vars)进行填充或采样,使其在batch内保持一致。
|
|
||||||
"""
|
"""
|
||||||
# --- 1. 过滤和处理无效样本 (与MoCo版本相同,非常鲁棒) ---
|
def __init__(self, max_len=390, use_spec=False, augmentations=None, img_size=(387, 65)):
|
||||||
|
self.max_len = max_len
|
||||||
|
self.use_spec = use_spec
|
||||||
|
self.augmentations = augmentations
|
||||||
|
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||||
|
|
||||||
# 过滤掉在__getitem__中返回None的样本
|
def process_signal(self, tss):
|
||||||
batch = [b for b in batch if b is not None]
|
# 1. 数据增强
|
||||||
|
if self.augmentations:
|
||||||
|
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||||
|
tss = tss + torch.randn_like(tss) * self.augmentations['noise_std']
|
||||||
|
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||||
|
scale = torch.rand(1).item() * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
|
||||||
|
tss = tss * scale
|
||||||
|
|
||||||
# 如果过滤后整个batch为空,则返回None,让训练循环处理
|
# 2. 长度处理
|
||||||
if not batch:
|
current_L = tss.shape[1]
|
||||||
|
if current_L > self.max_len:
|
||||||
|
tss = tss[:, -self.max_len:]
|
||||||
|
elif current_L < self.max_len:
|
||||||
|
pad_size = self.max_len - current_L
|
||||||
|
pad_values = tss[:, 0:1].expand(-1, pad_size)
|
||||||
|
tss = torch.cat((pad_values, tss), dim=1)
|
||||||
|
|
||||||
|
# 3. 标准化
|
||||||
|
mean = torch.mean(tss, dim=1, keepdim=True)
|
||||||
|
std = torch.std(tss, dim=1, keepdim=True)
|
||||||
|
std[std == 0] = 1.0
|
||||||
|
processed_signal_1d = (tss - mean) / (std + 1e-8)
|
||||||
|
|
||||||
|
return processed_signal_1d
|
||||||
|
|
||||||
|
def compute_cwt(self, signal):
|
||||||
|
if self.use_spec:
|
||||||
|
cwt = cwt_wrap(signal, scales=self.cwt_scales)
|
||||||
|
if not torch.all(torch.isfinite(cwt)): return None
|
||||||
|
return cwt
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 为了处理分布式训练中一个进程的batch为空的情况,
|
# --------------------------------------------------------------------------
|
||||||
# 我们可以选择复制第一个有效样本来填充,但对于MAE,
|
# 标准微调数据集 (dataset_class)
|
||||||
# 更简单的做法是如果batch为空就直接跳过。
|
# --------------------------------------------------------------------------
|
||||||
# 这里我们假设batch不为空,因为上面已经检查过了。
|
|
||||||
|
|
||||||
# --- 2. 对每个样本的变量数量(n_vars)进行填充或采样 ---
|
class dataset_class(BaseFineTuneDataset):
|
||||||
|
def __init__(self, data_dir, is_train=True, max_len=390, use_spec=False,
|
||||||
processed_batch = []
|
augmentations=None, img_size=(387, 65), subset_fraction: float = 1.0):
|
||||||
for item in batch:
|
super().__init__(max_len, use_spec, augmentations if is_train else None, img_size)
|
||||||
# 获取当前样本的变量数
|
|
||||||
# 我们以CWT输入的第一个维度为准
|
|
||||||
n_var = item['input_cwt'].size(0)
|
|
||||||
|
|
||||||
# 如果变量数与目标填充数相同,则不做任何处理
|
|
||||||
if n_var == pad_nvar:
|
|
||||||
processed_batch.append(item)
|
|
||||||
continue
|
|
||||||
|
|
||||||
new_item = {}
|
|
||||||
|
|
||||||
# 如果变量数大于目标数,则随机采样
|
|
||||||
if n_var > pad_nvar:
|
|
||||||
indices = random.sample(range(n_var), pad_nvar)
|
|
||||||
indices = torch.tensor(indices)
|
|
||||||
|
|
||||||
new_item['input_cwt'] = item['input_cwt'][indices]
|
|
||||||
new_item['input_1d'] = item['input_1d'][indices]
|
|
||||||
|
|
||||||
# 如果变量数小于目标数,则进行填充
|
|
||||||
elif n_var < pad_nvar:
|
|
||||||
# 复制最后一个有效变量来进行填充
|
|
||||||
last_cwt = item['input_cwt'][-1:].expand(
|
|
||||||
pad_nvar - n_var, -1, -1, -1)
|
|
||||||
last_1d = item['input_1d'][-1:].expand(pad_nvar - n_var, -1)
|
|
||||||
|
|
||||||
new_item['input_cwt'] = torch.cat(
|
|
||||||
[item['input_cwt'], last_cwt], dim=0)
|
|
||||||
new_item['input_1d'] = torch.cat(
|
|
||||||
[item['input_1d'], last_1d], dim=0)
|
|
||||||
|
|
||||||
processed_batch.append(new_item)
|
|
||||||
|
|
||||||
# --- 3. 使用PyTorch默认的collate函数进行最终的批处理 ---
|
|
||||||
# default_collate会将字典列表 [{k1:v1, k2:v2}, ...]
|
|
||||||
# 转换为一个字典 {k1:[v1, ...], k2:[v2, ...]} 并将值堆叠成张量
|
|
||||||
return default_collate(processed_batch)
|
|
||||||
# --- 3. 返回一个包含所有处理好数据的字典 ---
|
|
||||||
|
|
||||||
|
|
||||||
#################################################################################
|
|
||||||
class dataset_class(Dataset):
|
|
||||||
"""
|
|
||||||
A robust Dataset class for fine-tuning tasks.
|
|
||||||
- Handles explicit label mapping for binary classification (e.g., healthy vs. unhealthy).
|
|
||||||
- Includes session_id and sample_id in the output for detailed evaluation.
|
|
||||||
- Applies 1D time-series augmentations during training.
|
|
||||||
- Performs real-time CWT calculation if specified.
|
|
||||||
- Includes robust padding and error handling.
|
|
||||||
"""
|
|
||||||
# [修改] 增加 subset_fraction 参数
|
|
||||||
|
|
||||||
def __init__(self, data_dir, is_train=True, max_len=390, use_spec=False, augmentations=None, img_size=(387, 65), subset_fraction: float = 1.0):
|
|
||||||
super(dataset_class, self).__init__()
|
|
||||||
self.data_dir = data_dir
|
self.data_dir = data_dir
|
||||||
self.is_train = is_train
|
self.is_train = is_train
|
||||||
|
|
||||||
# 1. 加载数据集划分
|
|
||||||
with open(os.path.join(self.data_dir, 'train_test_split.json'), 'r') as file:
|
with open(os.path.join(self.data_dir, 'train_test_split.json'), 'r') as file:
|
||||||
split = json.load(file)
|
split = json.load(file)
|
||||||
self.file_list = split['train'] if self.is_train else split['test']
|
self.file_list = split['train'] if self.is_train else split['test']
|
||||||
|
|
||||||
# [新增] 根据 subset_fraction 参数对训练数据进行子集采样
|
|
||||||
# 注意:只对训练集进行采样,测试集应保持完整以进行公正评估
|
|
||||||
if self.is_train and subset_fraction < 1.0:
|
if self.is_train and subset_fraction < 1.0:
|
||||||
if not (0.0 < subset_fraction <= 1.0):
|
|
||||||
raise ValueError("subset_fraction must be between 0.0 and 1.0")
|
|
||||||
|
|
||||||
num_samples = int(len(self.file_list) * subset_fraction)
|
num_samples = int(len(self.file_list) * subset_fraction)
|
||||||
|
random.Random(42).shuffle(self.file_list)
|
||||||
# 使用固定的种子来确保每次采样的子集是相同的,保证实验可复现
|
|
||||||
rng = random.Random(42)
|
|
||||||
rng.shuffle(self.file_list)
|
|
||||||
|
|
||||||
self.file_list = self.file_list[:num_samples]
|
self.file_list = self.file_list[:num_samples]
|
||||||
print(
|
print(f"[INFO] Fine-tuning subset: {len(self.file_list)} files.")
|
||||||
f"[INFO] Fine-tuning with a subset of {len(self.file_list)} files ({subset_fraction * 100:.1f}% of the original training set).")
|
|
||||||
|
|
||||||
# 2. 明确定义标签映射
|
self.label_map = {1: 0, 2: 1}
|
||||||
# 0: 健康 (Negative class)
|
|
||||||
# 1: 有病 (Positive class)
|
|
||||||
self.label_map = {
|
|
||||||
1: 0, # 原始标签1是'健康',映射为索引0
|
|
||||||
2: 1, # 原始标签2是'有病',映射为索引1
|
|
||||||
}
|
|
||||||
if is_train:
|
|
||||||
print(
|
|
||||||
f"Using predefined label map for fine-tuning: {self.label_map}")
|
|
||||||
|
|
||||||
self.max_len = max_len
|
def __len__(self): return len(self.file_list)
|
||||||
self.use_spec = use_spec
|
|
||||||
|
|
||||||
# 3. 初始化 CWT scales
|
|
||||||
if not isinstance(img_size, tuple) or len(img_size) != 2:
|
|
||||||
img_size = (max_len - 2, 65)
|
|
||||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
|
||||||
|
|
||||||
# 4. 初始化数据增强
|
|
||||||
self.augmentations = augmentations if self.is_train else None
|
|
||||||
|
|
||||||
def __getitem__(self, idx):
|
def __getitem__(self, idx):
|
||||||
try:
|
try:
|
||||||
@@ -427,189 +245,112 @@ class dataset_class(Dataset):
|
|||||||
with open(os.path.join(self.data_dir, 'sample_for_downstream', curr_fn), 'rb') as file:
|
with open(os.path.join(self.data_dir, 'sample_for_downstream', curr_fn), 'rb') as file:
|
||||||
data = pickle.load(file)
|
data = pickle.load(file)
|
||||||
|
|
||||||
if 'uid' in data:
|
sample_id = str(data.get('uid', os.path.splitext(curr_fn)[0]))
|
||||||
sample_id = str(data['uid'])
|
|
||||||
else:
|
|
||||||
sample_id = os.path.splitext(curr_fn)[0]
|
|
||||||
|
|
||||||
parts = sample_id.split('_')
|
parts = sample_id.split('_')
|
||||||
session_id = f"{parts[0]}_{parts[1]}" if len(
|
session_id = f"{parts[0]}_{parts[1]}" if len(parts) >= 2 else parts[0]
|
||||||
parts) >= 2 else parts[0]
|
|
||||||
|
|
||||||
# 1. 加载并清理1D信号
|
|
||||||
tss = torch.from_numpy(data['data']).float()
|
tss = torch.from_numpy(data['data']).float()
|
||||||
tss = torch.nan_to_num(tss, 0.0)
|
tss = torch.nan_to_num(tss, 0.0)
|
||||||
|
|
||||||
original_label = data['label'][0]['class']
|
original_label = data['label'][0]['class']
|
||||||
if original_label not in self.label_map:
|
if original_label not in self.label_map: return None
|
||||||
return None
|
label = torch.tensor(self.label_map[original_label], dtype=torch.long)
|
||||||
mapped_label = self.label_map[original_label]
|
|
||||||
label = torch.tensor(mapped_label, dtype=torch.long)
|
|
||||||
|
|
||||||
# 2. [训练时] 应用1D数据增强
|
# 使用基类方法处理信号
|
||||||
if self.augmentations:
|
processed_signal_1d = self.process_signal(tss)
|
||||||
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
|
|
||||||
tss = tss + \
|
|
||||||
torch.randn_like(tss) * self.augmentations['noise_std']
|
|
||||||
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
|
|
||||||
scale = torch.rand(1).item(
|
|
||||||
) * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
|
|
||||||
tss = tss * scale
|
|
||||||
|
|
||||||
# 3. 序列长度处理 (填充或裁剪)
|
|
||||||
current_L = tss.shape[1]
|
|
||||||
if current_L > self.max_len:
|
|
||||||
tss = tss[:, -self.max_len:]
|
|
||||||
elif current_L < self.max_len:
|
|
||||||
pad_size = self.max_len - current_L
|
|
||||||
pad_values = tss[:, 0:1].expand(-1, pad_size)
|
|
||||||
tss = torch.cat((pad_values, tss), dim=1)
|
|
||||||
|
|
||||||
# --- [核心修改] ---
|
|
||||||
|
|
||||||
# 4. 标准化1D信号,这将作为1D CNN的输入
|
|
||||||
mean = torch.mean(tss, dim=1, keepdim=True)
|
|
||||||
std = torch.std(tss, dim=1, keepdim=True)
|
|
||||||
std[std == 0] = 1.0 # 增加保护
|
|
||||||
processed_signal_1d = (tss - mean) / (std + 1e-8)
|
|
||||||
|
|
||||||
# 5. 构建包含所有需要信息的返回字典
|
|
||||||
output_dict = {
|
output_dict = {
|
||||||
'label': label,
|
'label': label,
|
||||||
'session_id': session_id,
|
'session_id': session_id,
|
||||||
'sample_id': sample_id,
|
'sample_id': sample_id,
|
||||||
'input_1d': processed_signal_1d, # <-- [新增] 返回处理好的1D信号
|
'input_1d': processed_signal_1d,
|
||||||
}
|
}
|
||||||
|
|
||||||
# 6. 如果需要,计算CWT并添加到字典中
|
|
||||||
if self.use_spec:
|
if self.use_spec:
|
||||||
cwt = cwt_wrap(processed_signal_1d, scales=self.cwt_scales)
|
cwt = self.compute_cwt(processed_signal_1d)
|
||||||
if not torch.all(torch.isfinite(cwt)):
|
if cwt is None: return None
|
||||||
# print(f"Warning: NaN in CWT for {curr_fn}. Skipping.")
|
output_dict['input_cwt'] = cwt
|
||||||
return None
|
|
||||||
output_dict['input_cwt'] = cwt # <-- [修改] 键名改为 'input_cwt'
|
|
||||||
else:
|
else:
|
||||||
# 如果不使用CWT,为了兼容性,可以把1D信号也放入'input'键
|
|
||||||
output_dict['input'] = processed_signal_1d
|
output_dict['input'] = processed_signal_1d
|
||||||
|
|
||||||
return output_dict
|
return output_dict
|
||||||
|
except Exception: return None
|
||||||
|
|
||||||
except Exception as e:
|
# --------------------------------------------------------------------------
|
||||||
# print(f"Error processing sample at index {idx} (file: {self.file_list[idx]}): {e}. Skipping.")
|
# K折交叉验证数据集 (KFoldDataset)
|
||||||
return None
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
def __len__(self):
|
class KFoldDataset(BaseFineTuneDataset):
|
||||||
return len(self.file_list)
|
def __init__(self, data_root_dir, samples_info, is_train, max_len=390,
|
||||||
|
use_spec=True, augmentations=None, img_size=(387, 65)):
|
||||||
|
super().__init__(max_len, use_spec, augmentations if is_train else None, img_size)
|
||||||
class KFoldDataset(Dataset):
|
|
||||||
"""
|
|
||||||
一个为分组K折交叉验证设计的专用数据集类。
|
|
||||||
它直接从一个包含样本信息的列表中初始化,而不是从磁盘读取划分文件。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self,
|
|
||||||
data_root_dir: str,
|
|
||||||
samples_info: list,
|
|
||||||
is_train: bool,
|
|
||||||
max_len: int = 390,
|
|
||||||
use_spec: bool = True,
|
|
||||||
augmentations: dict = None,
|
|
||||||
img_size: tuple = (387, 65)):
|
|
||||||
"""
|
|
||||||
初始化 KFoldDataset。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
data_root_dir (str): 数据集的根目录 (例如, '.../data/ppg_for_kfold')。
|
|
||||||
samples_info (list): 一个字典列表,每个字典包含一个样本的信息。
|
|
||||||
例如: [{'filename': 's1_c0.pkl', 'subject_id': 's1', 'binary_label': 1}, ...]
|
|
||||||
is_train (bool): 指示当前是训练集还是测试集,用于决定是否应用数据增强。
|
|
||||||
max_len (int): 信号序列的最大长度。
|
|
||||||
use_spec (bool): 是否计算并返回 CWT 时频谱图。
|
|
||||||
augmentations (dict, optional): 用于训练时的数据增强配置。
|
|
||||||
img_size (tuple): CWT 图像的尺寸。
|
|
||||||
"""
|
|
||||||
super().__init__()
|
|
||||||
self.samples_dir = os.path.join(data_root_dir, 'samples')
|
self.samples_dir = os.path.join(data_root_dir, 'samples')
|
||||||
self.samples_info = samples_info
|
self.samples_info = samples_info
|
||||||
self.is_train = is_train
|
|
||||||
|
|
||||||
# --- 其他配置 (与您原来的 dataset_class 保持一致) ---
|
def __len__(self): return len(self.samples_info)
|
||||||
self.max_len = max_len
|
|
||||||
self.use_spec = use_spec
|
|
||||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
|
||||||
|
|
||||||
# 只有在 is_train 为 True 时才应用数据增强
|
|
||||||
self.augmentations = augmentations if self.is_train else None
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
return len(self.samples_info)
|
|
||||||
|
|
||||||
def __getitem__(self, idx):
|
def __getitem__(self, idx):
|
||||||
try:
|
try:
|
||||||
# 1. 从列表中获取当前样本的信息
|
|
||||||
sample_meta = self.samples_info[idx]
|
sample_meta = self.samples_info[idx]
|
||||||
|
|
||||||
filename = sample_meta['filename']
|
filename = sample_meta['filename']
|
||||||
label = torch.tensor(sample_meta['binary_label'], dtype=torch.long)
|
label = torch.tensor(sample_meta['binary_label'], dtype=torch.long)
|
||||||
subject_id = sample_meta['subject_id']
|
subject_id = sample_meta['subject_id']
|
||||||
|
|
||||||
# 2. 加载并处理数据文件
|
|
||||||
file_path = os.path.join(self.samples_dir, filename)
|
file_path = os.path.join(self.samples_dir, filename)
|
||||||
with open(file_path, 'rb') as file:
|
with open(file_path, 'rb') as file:
|
||||||
data = pickle.load(file)
|
data = pickle.load(file)
|
||||||
|
|
||||||
# 提取 sample_id (通常是 chunk_id)
|
|
||||||
sample_id = data.get('uid', os.path.splitext(filename)[0])
|
sample_id = data.get('uid', os.path.splitext(filename)[0])
|
||||||
|
|
||||||
# 3. 加载并清理1D信号
|
|
||||||
tss = torch.from_numpy(data['data']).float()
|
tss = torch.from_numpy(data['data']).float()
|
||||||
tss = torch.nan_to_num(tss, 0.0)
|
tss = torch.nan_to_num(tss, 0.0)
|
||||||
|
|
||||||
# 4. [训练时] 应用1D数据增强
|
# 使用基类方法处理信号
|
||||||
if self.augmentations:
|
processed_signal_1d = self.process_signal(tss)
|
||||||
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
|
|
||||||
tss = tss + \
|
|
||||||
torch.randn_like(tss) * self.augmentations['noise_std']
|
|
||||||
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
|
|
||||||
scale = torch.rand(1).item(
|
|
||||||
) * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
|
|
||||||
tss = tss * scale
|
|
||||||
|
|
||||||
# 5. 序列长度处理 (填充或裁剪) - 与原来逻辑一致
|
|
||||||
current_L = tss.shape[1]
|
|
||||||
if current_L > self.max_len:
|
|
||||||
tss = tss[:, -self.max_len:]
|
|
||||||
elif current_L < self.max_len:
|
|
||||||
pad_size = self.max_len - current_L
|
|
||||||
pad_values = tss[:, 0:1].expand(-1, pad_size)
|
|
||||||
tss = torch.cat((pad_values, tss), dim=1)
|
|
||||||
|
|
||||||
# 6. 标准化1D信号
|
|
||||||
mean = torch.mean(tss, dim=1, keepdim=True)
|
|
||||||
std = torch.std(tss, dim=1, keepdim=True)
|
|
||||||
std[std == 0] = 1.0
|
|
||||||
processed_signal_1d = (tss - mean) / (std + 1e-8)
|
|
||||||
|
|
||||||
# 7. 构建返回字典
|
|
||||||
output_dict = {
|
output_dict = {
|
||||||
'label': label,
|
'label': label,
|
||||||
'session_id': subject_id, # 使用 subject_id 作为 session_id
|
'session_id': subject_id,
|
||||||
'sample_id': sample_id,
|
'sample_id': sample_id,
|
||||||
'input_1d': processed_signal_1d,
|
'input_1d': processed_signal_1d,
|
||||||
}
|
}
|
||||||
|
|
||||||
# 8. 如果需要,计算CWT
|
|
||||||
if self.use_spec:
|
if self.use_spec:
|
||||||
# 假设 cwt_wrap 函数在您的项目中可用
|
cwt = self.compute_cwt(processed_signal_1d)
|
||||||
from .dataset import cwt_wrap # 或者其他正确的导入路径
|
if cwt is None: return None
|
||||||
cwt = cwt_wrap(processed_signal_1d, scales=self.cwt_scales)
|
|
||||||
if not torch.all(torch.isfinite(cwt)):
|
|
||||||
return None
|
|
||||||
output_dict['input_cwt'] = cwt
|
output_dict['input_cwt'] = cwt
|
||||||
|
|
||||||
return output_dict
|
return output_dict
|
||||||
|
except Exception: return None
|
||||||
|
|
||||||
except Exception as e:
|
# --------------------------------------------------------------------------
|
||||||
# print(f"Error processing sample at index {idx} (file: {self.samples_info[idx]['filename']}): {e}. Skipping.")
|
# Collate Function (保持不变)
|
||||||
return None
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def collate_fn(batch, pad_nvar=5):
|
||||||
|
batch = [b for b in batch if b is not None]
|
||||||
|
if not batch: return None
|
||||||
|
|
||||||
|
processed_batch = []
|
||||||
|
for item in batch:
|
||||||
|
n_var = item['input_cwt'].size(0)
|
||||||
|
if n_var == pad_nvar:
|
||||||
|
processed_batch.append(item)
|
||||||
|
continue
|
||||||
|
|
||||||
|
new_item = {}
|
||||||
|
if n_var > pad_nvar:
|
||||||
|
indices = torch.tensor(random.sample(range(n_var), pad_nvar))
|
||||||
|
new_item['input_cwt'] = item['input_cwt'][indices]
|
||||||
|
new_item['input_1d'] = item['input_1d'][indices]
|
||||||
|
elif n_var < pad_nvar:
|
||||||
|
last_cwt = item['input_cwt'][-1:].expand(pad_nvar - n_var, -1, -1, -1)
|
||||||
|
last_1d = item['input_1d'][-1:].expand(pad_nvar - n_var, -1)
|
||||||
|
new_item['input_cwt'] = torch.cat([item['input_cwt'], last_cwt], dim=0)
|
||||||
|
new_item['input_1d'] = torch.cat([item['input_1d'], last_1d], dim=0)
|
||||||
|
processed_batch.append(new_item)
|
||||||
|
|
||||||
|
return default_collate(processed_batch)
|
||||||
|
|
||||||
|
def linprob_collate_fn(batch):
|
||||||
|
batch = [b for b in batch if b is not None]
|
||||||
|
return default_collate(batch)
|
||||||
@@ -4,7 +4,6 @@ import math
|
|||||||
import sys
|
import sys
|
||||||
from typing import Iterable, Optional
|
from typing import Iterable, Optional
|
||||||
import torch
|
import torch
|
||||||
from torch.amp.autocast_mode import autocast
|
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import os
|
import os
|
||||||
@@ -16,58 +15,47 @@ except ImportError:
|
|||||||
import NormWear.modules.lr_sched as lr_sched
|
import NormWear.modules.lr_sched as lr_sched
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# [新增] CWT 与 1D 信号配对可视化函数
|
# 可视化辅助函数 (保持不变,逻辑是正确的)
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def save_cwt_signal_pair_visualization(original_signal, cwt_image, save_path, epoch, step):
|
def save_cwt_signal_pair_visualization(original_signal, cwt_image, save_path, epoch, step):
|
||||||
"""
|
"""
|
||||||
将1D原始信号及其对应的CWT图像一起可视化,以检查它们之间的关系。
|
将1D原始信号及其对应的CWT图像一起可视化。
|
||||||
original_signal: [n_var, L]
|
original_signal: [n_var, L]
|
||||||
cwt_image: [n_var, C, H, W]
|
cwt_image: [n_var, C, H, W]
|
||||||
"""
|
"""
|
||||||
original_signal = original_signal.detach().cpu().float().numpy()
|
original_signal = original_signal.detach().cpu().float().numpy()
|
||||||
cwt_image = cwt_image.detach().cpu().float().numpy()
|
cwt_image = cwt_image.detach().cpu().float().numpy()
|
||||||
|
|
||||||
# 只可视化第一个变量和第一个通道
|
# 只可视化第一个变量
|
||||||
sig_1d = original_signal[0]
|
sig_1d = original_signal[0]
|
||||||
img_cwt = cwt_image[0, 0] # 取第一个通道的CWT
|
img_cwt = cwt_image[0, 0]
|
||||||
|
|
||||||
# --- 绘图 ---
|
|
||||||
fig, axs = plt.subplots(2, 1, figsize=(
|
fig, axs = plt.subplots(2, 1, figsize=(
|
||||||
15, 6), sharex=True, gridspec_kw={'height_ratios': [1, 2]})
|
15, 6), sharex=True, gridspec_kw={'height_ratios': [1, 2]})
|
||||||
fig.suptitle(
|
fig.suptitle(
|
||||||
f'1D Signal and its CWT (Epoch {epoch}, Step {step})', fontsize=16)
|
f'1D Signal and its CWT (Epoch {epoch}, Step {step})', fontsize=16)
|
||||||
|
|
||||||
# 上方子图: 1D 信号
|
|
||||||
axs[0].plot(sig_1d)
|
axs[0].plot(sig_1d)
|
||||||
axs[0].set_title('Original 1D Signal')
|
axs[0].set_title('Original 1D Signal')
|
||||||
axs[0].set_ylabel('Amplitude')
|
axs[0].set_ylabel('Amplitude')
|
||||||
axs[0].grid(True)
|
axs[0].grid(True)
|
||||||
|
|
||||||
# 下方子图: 2D CWT 图像
|
|
||||||
# imshow 的 extent 参数可以帮助对齐坐标轴,但为了简单起见,共享x轴已足够直观
|
|
||||||
im = axs[1].imshow(img_cwt, cmap='viridis', aspect='auto', origin='lower')
|
im = axs[1].imshow(img_cwt, cmap='viridis', aspect='auto', origin='lower')
|
||||||
axs[1].set_title('Corresponding CWT Image (Channel 0)')
|
axs[1].set_title('Corresponding CWT Image (Channel 0)')
|
||||||
axs[1].set_xlabel('Time Steps')
|
axs[1].set_xlabel('Time Steps')
|
||||||
axs[1].set_ylabel('CWT Scales')
|
axs[1].set_ylabel('CWT Scales')
|
||||||
fig.colorbar(im, ax=axs[1], label='Magnitude')
|
fig.colorbar(im, ax=axs[1], label='Magnitude')
|
||||||
|
|
||||||
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # 调整布局以适应主标题
|
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
|
||||||
|
|
||||||
os.makedirs(save_path, exist_ok=True)
|
os.makedirs(save_path, exist_ok=True)
|
||||||
plt.savefig(os.path.join(
|
plt.savefig(os.path.join(
|
||||||
save_path, f'cwt_signal_pair_epoch_{epoch}_step_{step}.png'))
|
save_path, f'cwt_signal_pair_epoch_{epoch}_step_{step}.png'))
|
||||||
plt.close(fig)
|
plt.close(fig)
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# [已存在] CWT图像重建可视化函数
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
def save_mae_image_reconstruction(original_img, pred_img, mask, save_path, epoch, step, patch_size, patch_hw):
|
def save_mae_image_reconstruction(original_img, pred_img, mask, save_path, epoch, step, patch_size, patch_hw):
|
||||||
"""
|
|
||||||
将MAE的CWT图像重建结果可视化并保存。
|
|
||||||
"""
|
|
||||||
original_img = original_img.detach().cpu().float().numpy()
|
original_img = original_img.detach().cpu().float().numpy()
|
||||||
pred_img = pred_img.detach().cpu().float().numpy()
|
pred_img = pred_img.detach().cpu().float().numpy()
|
||||||
mask = mask.detach().cpu().float().numpy()
|
mask = mask.detach().cpu().float().numpy()
|
||||||
@@ -118,15 +106,8 @@ def save_mae_image_reconstruction(original_img, pred_img, mask, save_path, epoch
|
|||||||
save_path, f'reconstruction_cwt_epoch_{epoch}_step_{step}.png'))
|
save_path, f'reconstruction_cwt_epoch_{epoch}_step_{step}.png'))
|
||||||
plt.close(fig)
|
plt.close(fig)
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# [已存在] 1D原始信号重建可视化函数
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def save_mae_signal_reconstruction(original_signal, pred_signal, mask, save_path, epoch, step, patch_size, patch_hw):
|
def save_mae_signal_reconstruction(original_signal, pred_signal, mask, save_path, epoch, step, patch_size, patch_hw):
|
||||||
"""
|
|
||||||
将MAE的1D信号重建结果可视化并保存。
|
|
||||||
"""
|
|
||||||
original_signal = original_signal.detach().cpu().float().numpy()
|
original_signal = original_signal.detach().cpu().float().numpy()
|
||||||
pred_signal = pred_signal.detach().cpu().float().numpy()
|
pred_signal = pred_signal.detach().cpu().float().numpy()
|
||||||
mask = mask.detach().cpu().float().numpy()
|
mask = mask.detach().cpu().float().numpy()
|
||||||
@@ -170,7 +151,7 @@ def save_mae_signal_reconstruction(original_signal, pred_signal, mask, save_path
|
|||||||
plt.close(fig)
|
plt.close(fig)
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# 修改后的 train_one_epoch 函数
|
# 训练引擎
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@@ -192,9 +173,10 @@ def train_one_epoch(model: torch.nn.Module,
|
|||||||
header = 'Epoch: [{}]'.format(epoch)
|
header = 'Epoch: [{}]'.format(epoch)
|
||||||
print_freq = 20
|
print_freq = 20
|
||||||
|
|
||||||
# ... (可视化路径和模型参数获取) ...
|
|
||||||
vis_save_path = os.path.join(args.output_dir, 'mae_visualizations')
|
vis_save_path = os.path.join(args.output_dir, 'mae_visualizations')
|
||||||
vis_freq = 100
|
vis_freq = 100
|
||||||
|
|
||||||
|
# 获取模型配置用于可视化
|
||||||
model_without_ddp = model.module if hasattr(model, 'module') else model
|
model_without_ddp = model.module if hasattr(model, 'module') else model
|
||||||
patch_hw = model_without_ddp.patch_embed.patch_hw
|
patch_hw = model_without_ddp.patch_embed.patch_hw
|
||||||
patch_size = model_without_ddp.patch_size
|
patch_size = model_without_ddp.patch_size
|
||||||
@@ -206,6 +188,7 @@ def train_one_epoch(model: torch.nn.Module,
|
|||||||
print('log_dir: {}'.format(log_writer.log_dir))
|
print('log_dir: {}'.format(log_writer.log_dir))
|
||||||
|
|
||||||
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
||||||
|
# 学习率调整
|
||||||
if (data_iter_step) % accum_iter == 0:
|
if (data_iter_step) % accum_iter == 0:
|
||||||
lr_sched.adjust_learning_rate(
|
lr_sched.adjust_learning_rate(
|
||||||
optimizer, data_iter_step / len(data_loader) + epoch, args)
|
optimizer, data_iter_step / len(data_loader) + epoch, args)
|
||||||
@@ -216,6 +199,7 @@ def train_one_epoch(model: torch.nn.Module,
|
|||||||
samples_cwt = batch['input_cwt'].to(device, non_blocking=True)
|
samples_cwt = batch['input_cwt'].to(device, non_blocking=True)
|
||||||
samples_1d = batch['input_1d'].to(device, non_blocking=True)
|
samples_1d = batch['input_1d'].to(device, non_blocking=True)
|
||||||
|
|
||||||
|
# [修改] 确保 autocast 使用正确的 dtype (BF16 或 FP16)
|
||||||
with torch.amp.autocast(device_type=device.type, dtype=dtype):
|
with torch.amp.autocast(device_type=device.type, dtype=dtype):
|
||||||
loss, pred_pixels, pred_signal, mask = model(
|
loss, pred_pixels, pred_signal, mask = model(
|
||||||
x_cwt=samples_cwt,
|
x_cwt=samples_cwt,
|
||||||
@@ -231,80 +215,60 @@ def train_one_epoch(model: torch.nn.Module,
|
|||||||
optimizer.zero_grad(set_to_none=True)
|
optimizer.zero_grad(set_to_none=True)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# --- [核心修复:增加防御性检查和清晰的逻辑分支] ---
|
# --- 反向传播与梯度更新 ---
|
||||||
|
|
||||||
grad_norm = None
|
grad_norm = None
|
||||||
is_update_step = (data_iter_step + 1) % accum_iter == 0
|
is_update_step = (data_iter_step + 1) % accum_iter == 0
|
||||||
|
|
||||||
# 分支 1: 使用 fp16 和 GradScaler
|
# 分支 1: FP16 (使用 GradScaler)
|
||||||
if loss_scaler is not None:
|
if loss_scaler is not None:
|
||||||
# 这是一个防御性检查,确保我们不会调用一个 None 对象
|
|
||||||
if data_iter_step == 0 and misc.is_main_process():
|
|
||||||
print(">>> Training with FP16 NativeScaler.")
|
|
||||||
|
|
||||||
grad_norm = loss_scaler(
|
grad_norm = loss_scaler(
|
||||||
loss, optimizer, parameters=model.parameters(),
|
loss, optimizer, parameters=model.parameters(),
|
||||||
update_grad=is_update_step,
|
update_grad=is_update_step,
|
||||||
clip_grad=args.clip_grad if hasattr(
|
clip_grad=args.clip_grad
|
||||||
args, 'clip_grad') else None
|
|
||||||
)
|
)
|
||||||
# 在非更新步骤,loss_scaler 会返回 None,这是正常的
|
|
||||||
if is_update_step and grad_norm is None:
|
if is_update_step and grad_norm is None:
|
||||||
# 如果是更新步骤但 grad_norm 仍然是 None,说明可能跳过了更新(例如梯度为inf/nan)
|
|
||||||
# 我们可以给它一个默认值0来记录
|
|
||||||
grad_norm = 0.0
|
grad_norm = 0.0
|
||||||
|
|
||||||
# 分支 2: 使用 bf16/fp32,无 GradScaler
|
# 分支 2: BF16 / FP32 (无 GradScaler)
|
||||||
else:
|
else:
|
||||||
if data_iter_step == 0 and misc.is_main_process():
|
|
||||||
print(">>> Training without NativeScaler (BF16/FP32 mode).")
|
|
||||||
|
|
||||||
# 直接反向传播
|
|
||||||
loss.backward()
|
loss.backward()
|
||||||
|
|
||||||
if is_update_step:
|
if is_update_step:
|
||||||
# 在更新步骤,我们手动计算梯度范数并更新优化器
|
# HFR 建议始终进行梯度裁剪
|
||||||
parameters = [p for p in model.parameters() if p.requires_grad]
|
if args.clip_grad is not None:
|
||||||
|
|
||||||
if hasattr(args, 'clip_grad') and args.clip_grad is not None:
|
|
||||||
grad_norm = torch.nn.utils.clip_grad_norm_(
|
grad_norm = torch.nn.utils.clip_grad_norm_(
|
||||||
parameters, max_norm=args.clip_grad)
|
model.parameters(), args.clip_grad)
|
||||||
else:
|
else:
|
||||||
# 手动计算总梯度范unorm
|
# 仅计算范数用于日志
|
||||||
total_norm = 0.0
|
parameters = [p for p in model.parameters()
|
||||||
for p in parameters:
|
if p.grad is not None]
|
||||||
if p.grad is not None:
|
total_norm = torch.norm(torch.stack(
|
||||||
param_norm = p.grad.data.norm(2)
|
[torch.norm(p.grad.detach(), 2) for p in parameters]), 2)
|
||||||
total_norm += param_norm.item() ** 2
|
grad_norm = total_norm.item()
|
||||||
grad_norm = total_norm ** 0.5
|
|
||||||
|
|
||||||
optimizer.step()
|
optimizer.step()
|
||||||
optimizer.zero_grad(set_to_none=True)
|
optimizer.zero_grad(set_to_none=True)
|
||||||
|
|
||||||
torch.cuda.synchronize()
|
torch.cuda.synchronize()
|
||||||
|
|
||||||
# 记录未缩放的loss
|
# --- 日志记录 (修复了重复记录的问题) ---
|
||||||
|
# 注意:这里记录的是还原后的真实 Loss (loss_value * accum_iter)
|
||||||
metric_logger.update(loss=loss_value * accum_iter)
|
metric_logger.update(loss=loss_value * accum_iter)
|
||||||
lr = optimizer.param_groups[0]["lr"]
|
metric_logger.update(lr=optimizer.param_groups[0]["lr"])
|
||||||
metric_logger.update(lr=lr)
|
|
||||||
|
|
||||||
# 只有在计算了 grad_norm 的步骤才更新它
|
|
||||||
if grad_norm is not None:
|
if grad_norm is not None:
|
||||||
metric_logger.update(grad_norm=grad_norm.item(
|
metric_logger.update(grad_norm=grad_norm)
|
||||||
) if hasattr(grad_norm, 'item') else grad_norm)
|
|
||||||
|
|
||||||
# --- [核心修改] 可视化逻辑,现在调用三个可视化函数 ---
|
# --- 可视化 ---
|
||||||
if misc.is_main_process() and (data_iter_step % vis_freq == 0):
|
if misc.is_main_process() and (data_iter_step % vis_freq == 0):
|
||||||
# 1. [新增] 可视化 CWT 与 1D 信号的配对关系
|
# 1. CWT 与 1D 信号配对
|
||||||
save_cwt_signal_pair_visualization(
|
save_cwt_signal_pair_visualization(
|
||||||
original_signal=samples_1d[0], # 这是原始的1D信号
|
original_signal=samples_1d[0],
|
||||||
cwt_image=samples_cwt[0], # 这是原始的CWT图像
|
cwt_image=samples_cwt[0],
|
||||||
save_path=vis_save_path,
|
save_path=vis_save_path,
|
||||||
epoch=epoch,
|
epoch=epoch,
|
||||||
step=data_iter_step
|
step=data_iter_step
|
||||||
)
|
)
|
||||||
|
# 2. CWT 重建
|
||||||
# 2. 可视化CWT图像重建
|
|
||||||
save_mae_image_reconstruction(
|
save_mae_image_reconstruction(
|
||||||
original_img=samples_cwt[0],
|
original_img=samples_cwt[0],
|
||||||
pred_img=pred_pixels[0],
|
pred_img=pred_pixels[0],
|
||||||
@@ -315,7 +279,7 @@ def train_one_epoch(model: torch.nn.Module,
|
|||||||
patch_size=patch_size,
|
patch_size=patch_size,
|
||||||
patch_hw=patch_hw
|
patch_hw=patch_hw
|
||||||
)
|
)
|
||||||
# 3. 可视化1D信号重建
|
# 3. 1D 信号重建
|
||||||
save_mae_signal_reconstruction(
|
save_mae_signal_reconstruction(
|
||||||
original_signal=samples_1d[0],
|
original_signal=samples_1d[0],
|
||||||
pred_signal=pred_signal[0],
|
pred_signal=pred_signal[0],
|
||||||
@@ -327,12 +291,6 @@ def train_one_epoch(model: torch.nn.Module,
|
|||||||
patch_hw=patch_hw
|
patch_hw=patch_hw
|
||||||
)
|
)
|
||||||
|
|
||||||
torch.cuda.synchronize()
|
|
||||||
|
|
||||||
metric_logger.update(loss=loss_value)
|
|
||||||
lr = optimizer.param_groups[0]["lr"]
|
|
||||||
metric_logger.update(lr=lr)
|
|
||||||
|
|
||||||
metric_logger.synchronize_between_processes()
|
metric_logger.synchronize_between_processes()
|
||||||
print("Averaged stats:", metric_logger)
|
print("Averaged stats:", metric_logger)
|
||||||
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
||||||
+94
-101
@@ -1,3 +1,5 @@
|
|||||||
|
# find_lr.py
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import os
|
import os
|
||||||
import torch
|
import torch
|
||||||
@@ -6,81 +8,74 @@ import numpy as np
|
|||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
from torch.cuda.amp import autocast
|
from torch.cuda.amp import autocast
|
||||||
# --------------------------------------------------------------------------
|
import sys
|
||||||
# 从您的项目中导入必要的模块
|
|
||||||
# 确保路径正确
|
# 添加项目根目录到路径
|
||||||
# --------------------------------------------------------------------------
|
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||||
|
|
||||||
from NormWear.modules.normwear import NormWear
|
from NormWear.modules.normwear import NormWear
|
||||||
from NormWear.pretrain_pipeline.dataset import PretrainDataset, collate_fn, cwt_wrap
|
from NormWear.pretrain_pipeline.dataset import PretrainDataset, collate_fn
|
||||||
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount as NativeScaler
|
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount as NativeScaler
|
||||||
import NormWear.pretrain_pipeline.misc as misc
|
import NormWear.pretrain_pipeline.misc as misc
|
||||||
from torch.utils.data import DataLoader, DistributedSampler, RandomSampler
|
from torch.utils.data import DataLoader, DistributedSampler, RandomSampler
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# 主函数和辅助函数
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def get_args_parser():
|
def get_args_parser():
|
||||||
parser = argparse.ArgumentParser('NormWear LR Finder', add_help=False)
|
parser = argparse.ArgumentParser('NormWear HFR LR Finder', add_help=False)
|
||||||
|
|
||||||
# --- 核心参数 ---
|
# --- 核心参数 ---
|
||||||
parser.add_argument('--resume', type=str, default='',
|
parser.add_argument('--resume', type=str, default='', help='Path to checkpoint.')
|
||||||
help='Path to the checkpoint file to resume from (e.g., after warmup).')
|
parser.add_argument('--output_dir', required=True, type=str, help='Path to save plot.')
|
||||||
parser.add_argument('--output_dir', required=True, type=str,
|
|
||||||
help='Path to save the LR finder plot.')
|
|
||||||
|
|
||||||
# --- LR Finder 参数 ---
|
# --- LR Finder 参数 ---
|
||||||
parser.add_argument('--start_lr', default=1e-7, type=float,
|
parser.add_argument('--start_lr', default=1e-7, type=float)
|
||||||
help='Starting learning rate for the test.')
|
parser.add_argument('--end_lr', default=1e-1, type=float)
|
||||||
parser.add_argument('--end_lr', default=1e-1, type=float,
|
parser.add_argument('--num_iter', default=200, type=int)
|
||||||
help='Ending learning rate for the test.')
|
|
||||||
parser.add_argument('--num_iter', default=200, type=int,
|
|
||||||
help='Number of iterations (batches) to run the test.')
|
|
||||||
|
|
||||||
# --- 数据集参数 (必须与训练时一致) ---
|
# --- 数据集参数 ---
|
||||||
parser.add_argument('--data_dir', required=True, type=str,
|
parser.add_argument('--data_dir', required=True, type=str)
|
||||||
help='Path to the pre-training data directory.')
|
parser.add_argument('--dataset_names', nargs='+', default=['temp'])
|
||||||
parser.add_argument('--dataset_names', nargs='+',
|
|
||||||
default=['temp'], help='List of dataset names.')
|
|
||||||
parser.add_argument('--window_size', default=387, type=int)
|
parser.add_argument('--window_size', default=387, type=int)
|
||||||
|
parser.add_argument('--dataset_stride', default=150, type=int)
|
||||||
parser.add_argument('--batch_size', default=128, type=int)
|
parser.add_argument('--batch_size', default=128, type=int)
|
||||||
parser.add_argument('--num_workers', default=4, type=int)
|
parser.add_argument('--num_workers', default=4, type=int)
|
||||||
|
|
||||||
# --- 模型架构参数 (必须与检查点中的模型一致) ---
|
# --- 模型架构参数 (HFR & MAE) ---
|
||||||
parser.add_argument('--n_vars', type=int, required=True,
|
parser.add_argument('--nvar', type=int, required=True, help='Number of variables (n_vars).')
|
||||||
help='Number of variables in the data.')
|
|
||||||
parser.add_argument('--embed_dim', type=int, default=768)
|
parser.add_argument('--embed_dim', type=int, default=768)
|
||||||
parser.add_argument('--depth', type=int, default=12)
|
parser.add_argument('--depth', type=int, default=12)
|
||||||
parser.add_argument('--num_heads', type=int, default=12)
|
parser.add_argument('--num_heads', type=int, default=12)
|
||||||
|
parser.add_argument('--mlp_ratio', type=float, default=4.0)
|
||||||
|
|
||||||
|
# [HFR 参数]
|
||||||
|
parser.add_argument('--fluid_kernel_size', type=int, default=3)
|
||||||
|
|
||||||
|
# [MAE 参数]
|
||||||
parser.add_argument('--decoder_embed_dim', type=int, default=512)
|
parser.add_argument('--decoder_embed_dim', type=int, default=512)
|
||||||
parser.add_argument('--decoder_depth', type=int, default=8)
|
parser.add_argument('--decoder_depth', type=int, default=8)
|
||||||
parser.add_argument('--decoder_num_heads', type=int, default=16)
|
parser.add_argument('--decoder_num_heads', type=int, default=16)
|
||||||
parser.add_argument('--mask_ratio', type=float, default=0.75)
|
parser.add_argument('--mask_ratio', type=float, default=0.75)
|
||||||
|
parser.add_argument('--modality_dropout', type=float, default=0.15)
|
||||||
|
parser.add_argument('--loss_weight_1d_token', type=float, default=0.3)
|
||||||
|
parser.add_argument('--loss_weight_1d_signal', type=float, default=0.3)
|
||||||
|
|
||||||
|
# --- 硬件参数 ---
|
||||||
|
parser.add_argument('--device', default='cuda')
|
||||||
|
parser.add_argument('--world_size', default=1, type=int)
|
||||||
|
parser.add_argument('--local_rank', default=-1, type=int)
|
||||||
|
parser.add_argument('--dist_on_itp', action='store_true')
|
||||||
|
parser.add_argument('--dist_url', default='env://', type=str)
|
||||||
|
parser.add_argument('--precision', default='bf16', type=str, choices=['fp32', 'fp16', 'bf16'])
|
||||||
|
|
||||||
# training args
|
|
||||||
# --- 分布式训练参数 (可选,但推荐) ---
|
|
||||||
parser.add_argument('--device', default='cuda',
|
|
||||||
help='Device to use for training / testing.')
|
|
||||||
parser.add_argument('--world_size', default=1, type=int,
|
|
||||||
help='Number of distributed processes.')
|
|
||||||
parser.add_argument('--local_rank', default=-1, type=int) # torchrun会自动设置
|
|
||||||
parser.add_argument('--dist_on_itp', action='store_true',
|
|
||||||
help='Whether to use itp for distributed training.')
|
|
||||||
parser.add_argument('--dist_url', default='env://',
|
|
||||||
help='URL used to set up distributed training.')
|
|
||||||
return parser
|
return parser
|
||||||
|
|
||||||
|
|
||||||
def find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype):
|
def find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype):
|
||||||
"""
|
|
||||||
执行学习率范围测试。
|
|
||||||
"""
|
|
||||||
model.train()
|
model.train()
|
||||||
|
|
||||||
|
# 计算指数增长的 gamma
|
||||||
gamma = (args.end_lr / args.start_lr) ** (1 / args.num_iter)
|
gamma = (args.end_lr / args.start_lr) ** (1 / args.num_iter)
|
||||||
lr_scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma)
|
lr_scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma)
|
||||||
|
|
||||||
|
# 初始化 LR
|
||||||
for param_group in optimizer.param_groups:
|
for param_group in optimizer.param_groups:
|
||||||
param_group['lr'] = args.start_lr
|
param_group['lr'] = args.start_lr
|
||||||
|
|
||||||
@@ -103,46 +98,49 @@ def find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype):
|
|||||||
optimizer.zero_grad()
|
optimizer.zero_grad()
|
||||||
|
|
||||||
with autocast(dtype=dtype):
|
with autocast(dtype=dtype):
|
||||||
loss, _, _ = model(x_cwt=samples_cwt,
|
# [修改] HFR 返回 4 个值
|
||||||
x_1d=samples_1d, mask_ratio=args.mask_ratio)
|
loss, _, _, _ = model(
|
||||||
|
x_cwt=samples_cwt,
|
||||||
|
x_1d=samples_1d,
|
||||||
|
mask_ratio=args.mask_ratio
|
||||||
|
)
|
||||||
|
|
||||||
current_lr = optimizer.param_groups[0]['lr']
|
current_lr = optimizer.param_groups[0]['lr']
|
||||||
learning_rates.append(current_lr)
|
learning_rates.append(current_lr)
|
||||||
|
|
||||||
loss_item = loss.item()
|
loss_item = loss.item()
|
||||||
|
|
||||||
|
# 记录平滑 Loss
|
||||||
if i == 0:
|
if i == 0:
|
||||||
losses.append(loss_item)
|
losses.append(loss_item)
|
||||||
else:
|
else:
|
||||||
smoothed_loss = 0.98 * losses[-1] + 0.02 * loss_item
|
smoothed_loss = 0.98 * losses[-1] + 0.02 * loss_item
|
||||||
losses.append(smoothed_loss)
|
losses.append(smoothed_loss)
|
||||||
|
|
||||||
|
# 检查发散
|
||||||
if loss_item > 4 * (min(losses) if losses else 1.0) and i > 10:
|
if loss_item > 4 * (min(losses) if losses else 1.0) and i > 10:
|
||||||
print("Loss diverged, stopping LR Finder.")
|
print("Loss diverged, stopping LR Finder.")
|
||||||
break
|
break
|
||||||
|
|
||||||
|
# 反向传播
|
||||||
if loss_scaler is not None:
|
if loss_scaler is not None:
|
||||||
# 将所有操作合并为一次调用
|
loss_scaler(loss, optimizer, parameters=model.parameters(), update_grad=True)
|
||||||
loss_scaler(
|
|
||||||
loss,
|
|
||||||
optimizer,
|
|
||||||
parameters=model.parameters(),
|
|
||||||
# 在LR Finder中,我们每个step都更新梯度
|
|
||||||
update_grad=True
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
loss.backward()
|
loss.backward()
|
||||||
|
# HFR 建议裁剪梯度
|
||||||
|
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
||||||
optimizer.step()
|
optimizer.step()
|
||||||
|
|
||||||
lr_scheduler.step()
|
lr_scheduler.step()
|
||||||
|
|
||||||
# 只在主进程上绘图和分析
|
# 绘图与分析
|
||||||
if misc.is_main_process():
|
if misc.is_main_process():
|
||||||
plt.figure(figsize=(10, 6))
|
plt.figure(figsize=(10, 6))
|
||||||
plt.plot(learning_rates, losses)
|
plt.plot(learning_rates, losses)
|
||||||
plt.xscale("log")
|
plt.xscale("log")
|
||||||
plt.xlabel("Learning Rate (log scale)")
|
plt.xlabel("Learning Rate (log scale)")
|
||||||
plt.ylabel("Smoothed Loss")
|
plt.ylabel("Smoothed Loss")
|
||||||
plt.title("Learning Rate Finder")
|
plt.title("Learning Rate Finder (HFR)")
|
||||||
plt.grid(True)
|
plt.grid(True)
|
||||||
|
|
||||||
os.makedirs(args.output_dir, exist_ok=True)
|
os.makedirs(args.output_dir, exist_ok=True)
|
||||||
@@ -150,38 +148,43 @@ def find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype):
|
|||||||
plt.savefig(save_path)
|
plt.savefig(save_path)
|
||||||
print(f"\nLR Finder plot saved to: {save_path}")
|
print(f"\nLR Finder plot saved to: {save_path}")
|
||||||
|
|
||||||
if len(losses) > 10: # 确保有足够的数据点进行分析
|
if len(losses) > 10:
|
||||||
rates = np.array(learning_rates)
|
rates = np.array(learning_rates)
|
||||||
losses_arr = np.array(losses)
|
losses_arr = np.array(losses)
|
||||||
|
|
||||||
# 找到损失最低点
|
|
||||||
min_loss_idx = np.argmin(losses_arr)
|
min_loss_idx = np.argmin(losses_arr)
|
||||||
min_loss_lr = rates[min_loss_idx]
|
min_loss_lr = rates[min_loss_idx]
|
||||||
|
|
||||||
# 找到梯度最陡峭的点 (一个常用的启发式方法)
|
# 经验法则:最陡下降点通常在最低点的 1/10 左右
|
||||||
# 我们通常选择比最低点小一个数量级的学习率
|
|
||||||
recommended_lr = min_loss_lr / 10
|
recommended_lr = min_loss_lr / 10
|
||||||
|
|
||||||
print(f"\n--- LR Finder Results ---")
|
print(f"\n--- LR Finder Results ---")
|
||||||
print(f"Lowest loss found at LR: {min_loss_lr:.2e}")
|
print(f"Lowest loss found at LR: {min_loss_lr:.2e}")
|
||||||
print(
|
print(f"Recommended LR (rule of thumb): {recommended_lr:.2e}")
|
||||||
f"Recommended LR for subsequent training (rule of thumb): {recommended_lr:.2e}")
|
|
||||||
print("-------------------------")
|
print("-------------------------")
|
||||||
print("Please inspect the plot to make a final decision.")
|
|
||||||
|
|
||||||
# in find_lr.py
|
|
||||||
|
|
||||||
|
|
||||||
def main(args):
|
def main(args):
|
||||||
misc.init_distributed_mode(args)
|
misc.init_distributed_mode(args)
|
||||||
device = torch.device(args.device)
|
device = torch.device(args.device)
|
||||||
|
|
||||||
# --- 数据集 (不变) ---
|
# --- 精度设置 ---
|
||||||
|
if args.precision == 'bf16':
|
||||||
|
dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
||||||
|
elif args.precision == 'fp16':
|
||||||
|
dtype = torch.float16
|
||||||
|
else:
|
||||||
|
dtype = torch.float32
|
||||||
|
|
||||||
|
if misc.is_main_process():
|
||||||
|
print(f"Using precision: {dtype}")
|
||||||
|
|
||||||
|
# --- 数据集 ---
|
||||||
dataset = PretrainDataset(
|
dataset = PretrainDataset(
|
||||||
data_dir=args.data_dir,
|
data_dir=args.data_dir,
|
||||||
dataset_names=args.dataset_names,
|
dataset_names=args.dataset_names,
|
||||||
window_size=args.window_size
|
window_size=args.window_size,
|
||||||
|
stride=args.dataset_stride
|
||||||
)
|
)
|
||||||
|
|
||||||
if misc.is_dist_avail_and_initialized():
|
if misc.is_dist_avail_and_initialized():
|
||||||
sampler = DistributedSampler(dataset, shuffle=True)
|
sampler = DistributedSampler(dataset, shuffle=True)
|
||||||
else:
|
else:
|
||||||
@@ -194,10 +197,10 @@ def main(args):
|
|||||||
num_workers=args.num_workers,
|
num_workers=args.num_workers,
|
||||||
pin_memory=True,
|
pin_memory=True,
|
||||||
drop_last=True,
|
drop_last=True,
|
||||||
collate_fn=collate_fn
|
collate_fn=lambda x: collate_fn(x, pad_nvar=args.nvar) # 确保使用正确的 collate_fn
|
||||||
)
|
)
|
||||||
|
|
||||||
# --- 模型 (不变) ---
|
# --- 模型初始化 (HFR Version) ---
|
||||||
model = NormWear(
|
model = NormWear(
|
||||||
img_size=(args.window_size, 65),
|
img_size=(args.window_size, 65),
|
||||||
patch_size=(9, 5),
|
patch_size=(9, 5),
|
||||||
@@ -208,49 +211,39 @@ def main(args):
|
|||||||
decoder_embed_dim=args.decoder_embed_dim,
|
decoder_embed_dim=args.decoder_embed_dim,
|
||||||
decoder_depth=args.decoder_depth,
|
decoder_depth=args.decoder_depth,
|
||||||
decoder_num_heads=args.decoder_num_heads,
|
decoder_num_heads=args.decoder_num_heads,
|
||||||
use_hybrid_embed=True,
|
mlp_ratio=args.mlp_ratio,
|
||||||
nvar=args.n_vars,
|
# MAE & HFR 参数
|
||||||
target_len=args.window_size
|
modality_dropout_prob=args.modality_dropout,
|
||||||
|
loss_weight_1d_token=args.loss_weight_1d_token,
|
||||||
|
loss_weight_1d_signal=args.loss_weight_1d_signal,
|
||||||
|
nvar=args.nvar,
|
||||||
|
fluid_kernel_size=args.fluid_kernel_size
|
||||||
).to(device)
|
).to(device)
|
||||||
|
|
||||||
model_without_ddp = model
|
model_without_ddp = model
|
||||||
if misc.is_dist_avail_and_initialized():
|
if misc.is_dist_avail_and_initialized():
|
||||||
model = torch.nn.parallel.DistributedDataParallel(
|
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
|
||||||
model, device_ids=[args.gpu])
|
|
||||||
model_without_ddp = model.module
|
model_without_ddp = model.module
|
||||||
|
|
||||||
# --- 优化器和AMP (不变) ---
|
# --- 优化器 ---
|
||||||
optimizer = torch.optim.AdamW(
|
optimizer = torch.optim.AdamW(model_without_ddp.parameters(), lr=args.start_lr)
|
||||||
model_without_ddp.parameters(), lr=args.start_lr)
|
|
||||||
loss_scaler = NativeScaler()
|
# 仅在 FP16 时使用 Scaler
|
||||||
|
loss_scaler = NativeScaler() if dtype == torch.float16 else None
|
||||||
|
|
||||||
# --- [核心修复] 整合并简化检查点加载逻辑 ---
|
# --- 加载检查点 ---
|
||||||
# 检查 --resume 参数是否被提供、非空,并且是一个存在的文件
|
|
||||||
if args.resume and os.path.isfile(args.resume):
|
if args.resume and os.path.isfile(args.resume):
|
||||||
print(f"Resuming from checkpoint: {args.resume}")
|
print(f"Resuming from checkpoint: {args.resume}")
|
||||||
checkpoint = torch.load(args.resume, map_location='cpu')
|
checkpoint = torch.load(args.resume, map_location='cpu')
|
||||||
|
state_dict = checkpoint.get('model', checkpoint)
|
||||||
# 从检查点中加载模型权重
|
|
||||||
if 'model' in checkpoint:
|
|
||||||
state_dict = checkpoint['model']
|
|
||||||
else:
|
|
||||||
state_dict = checkpoint # 兼容只保存了state_dict的情况
|
|
||||||
|
|
||||||
msg = model_without_ddp.load_state_dict(state_dict, strict=False)
|
msg = model_without_ddp.load_state_dict(state_dict, strict=False)
|
||||||
print("Model loading message:", msg)
|
print("Model loading message:", msg)
|
||||||
else:
|
else:
|
||||||
if args.resume: # 如果提供了路径但文件不存在
|
print("Starting LR Finder from scratch.")
|
||||||
print(
|
|
||||||
f"Warning: Checkpoint file not found at '{args.resume}'. Starting from scratch.")
|
|
||||||
else: # 如果没有提供路径
|
|
||||||
print(
|
|
||||||
"No checkpoint provided. Starting LR Finder from scratch (random initialization).")
|
|
||||||
|
|
||||||
# --- 执行LR Finder ---
|
# --- 执行 ---
|
||||||
dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
|
||||||
find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype)
|
find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
args = get_args_parser().parse_args()
|
args = get_args_parser().parse_args()
|
||||||
main(args)
|
main(args)
|
||||||
+102
-115
@@ -1,12 +1,4 @@
|
|||||||
# main_pretrain.py (or demo.py)
|
# main_pretrain.py
|
||||||
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount
|
|
||||||
from NormWear.pretrain_pipeline.dataset import PretrainDataset, collate_fn, DataLoader
|
|
||||||
from NormWear.pretrain_pipeline.engine_pretrain import train_one_epoch
|
|
||||||
from NormWear.modules.normwear import NormWear
|
|
||||||
from functools import partial
|
|
||||||
import timm.optim.optim_factory as optim_factory
|
|
||||||
from NormWear.pretrain_pipeline.misc import get_next_run_number
|
|
||||||
from NormWear.pretrain_pipeline import misc
|
|
||||||
import argparse
|
import argparse
|
||||||
import datetime
|
import datetime
|
||||||
import json
|
import json
|
||||||
@@ -14,47 +6,44 @@ import numpy as np
|
|||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
import torch.backends.cudnn as cudnn
|
import torch.backends.cudnn as cudnn
|
||||||
from torch.utils.tensorboard import SummaryWriter
|
from torch.utils.tensorboard import SummaryWriter
|
||||||
# from torch.cuda.amp import GradScaler
|
|
||||||
import sys
|
|
||||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
|
||||||
torch.autograd.set_detect_anomaly(True)
|
|
||||||
# [修改] 确保引入的是带窗口化和缓存功能的 PretrainDataset
|
|
||||||
|
|
||||||
|
# 添加项目根目录到路径
|
||||||
|
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||||
|
|
||||||
|
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount, get_next_run_number
|
||||||
|
from NormWear.pretrain_pipeline.dataset import PretrainDataset, collate_fn, DataLoader
|
||||||
|
from NormWear.pretrain_pipeline.engine_pretrain import train_one_epoch
|
||||||
|
from NormWear.modules.normwear import NormWear
|
||||||
|
from NormWear.pretrain_pipeline import misc
|
||||||
|
|
||||||
|
# 开启异常检测有助于调试 HFR 这种自定义反向传播较多的模型
|
||||||
|
torch.autograd.set_detect_anomaly(True)
|
||||||
|
|
||||||
def get_args_parser():
|
def get_args_parser():
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser('NormWear HFR Pre-training', add_help=False)
|
||||||
'NormWear MAE Pre-training', add_help=False)
|
parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)')
|
||||||
parser.add_argument('--modality_dropout', type=float, default=0.15,
|
# --- 基础训练参数 ---
|
||||||
help='Probability of dropping an entire modality during training (e.g., 0.15 for 15%). Set to 0 to disable.')
|
parser.add_argument('--batch_size', default=768, type=int, help='Batch size per GPU')
|
||||||
# --- [新增] 精度选择参数 ---
|
|
||||||
parser.add_argument('--precision', default='bf16', type=str, choices=['fp32', 'fp16', 'bf16'],
|
|
||||||
help='Floating point precision for training. bf16 is recommended on supported hardware (A100, H100, RTX 30/40).')
|
|
||||||
|
|
||||||
# pretrain args
|
|
||||||
# MAEargs
|
|
||||||
parser.add_argument('--blr', type=float, default=1e-3,
|
|
||||||
metavar='LR', help='base learning rate')
|
|
||||||
parser.add_argument('--mask_ratio', default=0.75,
|
|
||||||
type=float, help='Ratio of patches to mask')
|
|
||||||
parser.add_argument('--norm_pix_loss', action='store_true',
|
|
||||||
help='Normalize pixels for loss calculation')
|
|
||||||
parser.set_defaults(norm_pix_loss=False)
|
|
||||||
# [核心新增] 添加用于控制随机模态丢弃的参数
|
|
||||||
# training args
|
|
||||||
parser.add_argument('--reconstruction_prob', type=float, default=0.25,
|
|
||||||
help='Probability of a variable being chosen as a reconstruction target (e.g., 0.25 for 25%).')
|
|
||||||
|
|
||||||
parser.add_argument('--batch_size', default=768,
|
|
||||||
type=int, help='Batch size per GPU')
|
|
||||||
parser.add_argument('--epochs', default=300, type=int)
|
parser.add_argument('--epochs', default=300, type=int)
|
||||||
parser.add_argument('--accum_iter', default=1, type=int)
|
parser.add_argument('--accum_iter', default=1, type=int, help='Accumulate gradient iterations')
|
||||||
parser.add_argument('--remark', default='model768', help='model_remark')
|
parser.add_argument('--save_every_epoch', default=10, type=int) # 建议调大一点,每轮都存太占空间
|
||||||
parser.add_argument('--save_every_epoch', default=1, type=int)
|
parser.add_argument('--remark', default='hfr_base', help='Experiment remark')
|
||||||
parser.add_argument(
|
|
||||||
'--model', default='moco_normwear_base', type=str, metavar='MODEL')
|
# --- 优化器参数 ---
|
||||||
|
parser.add_argument('--blr', type=float, default=1e-3, metavar='LR', help='base learning rate')
|
||||||
|
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR')
|
||||||
|
parser.add_argument('--weight_decay', type=float, default=0.05)
|
||||||
|
parser.add_argument('--warmup_epochs', type=int, default=20, metavar='N') # HFR 可能需要更长的 warmup
|
||||||
|
parser.add_argument('--clip_grad', type=float, default=1.0, help='Clip gradient norm') # HFR 建议设为 1.0
|
||||||
|
|
||||||
|
# --- 模型架构参数 (HFR & MAE) ---
|
||||||
|
parser.add_argument('--model', default='normwear_hfr', type=str, metavar='MODEL')
|
||||||
parser.add_argument('--img_size', default=(387, 65), nargs=2, type=int)
|
parser.add_argument('--img_size', default=(387, 65), nargs=2, type=int)
|
||||||
parser.add_argument('--patch_size', type=int, default=(9, 5), nargs=2)
|
parser.add_argument('--patch_size', type=int, default=(9, 5), nargs=2)
|
||||||
parser.add_argument('--in_chans', type=int, default=3)
|
parser.add_argument('--in_chans', type=int, default=3)
|
||||||
@@ -63,50 +52,47 @@ def get_args_parser():
|
|||||||
parser.add_argument('--depth', type=int, default=12)
|
parser.add_argument('--depth', type=int, default=12)
|
||||||
parser.add_argument('--num_heads', type=int, default=12)
|
parser.add_argument('--num_heads', type=int, default=12)
|
||||||
parser.add_argument('--mlp_ratio', type=float, default=4.0)
|
parser.add_argument('--mlp_ratio', type=float, default=4.0)
|
||||||
parser.add_argument('--fuse_freq', type=int, default=2)
|
|
||||||
parser.add_argument('--use_cwt', type=bool, default=True)
|
# [HFR 特有参数]
|
||||||
parser.add_argument('--use_meanpooling', type=int, default=0)
|
parser.add_argument('--fluid_kernel_size', type=int, default=3, help='Kernel size for HFR fluid layer')
|
||||||
# [新增] MAE解码器参数
|
|
||||||
parser.add_argument('--decoder_embed_dim', default=512,
|
# [MAE 解码器参数]
|
||||||
type=int, help='Dimensionality of decoder embeddings')
|
parser.add_argument('--decoder_embed_dim', default=512, type=int)
|
||||||
parser.add_argument('--decoder_depth', default=8, type=int,
|
parser.add_argument('--decoder_depth', default=8, type=int)
|
||||||
help='Number of layers in the decoder')
|
parser.add_argument('--decoder_num_heads', default=16, type=int)
|
||||||
parser.add_argument('--decoder_num_heads', default=16,
|
|
||||||
type=int, help='Number of attention heads in the decoder')
|
# [MAE 掩码与重建参数]
|
||||||
|
parser.add_argument('--mask_ratio', default=0.75, type=float, help='Ratio of patches to mask')
|
||||||
|
parser.add_argument('--norm_pix_loss', action='store_true', help='Normalize pixels for loss calculation')
|
||||||
|
parser.set_defaults(norm_pix_loss=False)
|
||||||
|
parser.add_argument('--modality_dropout', type=float, default=0.15, help='Prob of dropping a modality')
|
||||||
|
parser.add_argument('--loss_weight_1d_token', type=float, default=0.3)
|
||||||
|
parser.add_argument('--loss_weight_1d_signal', type=float, default=0.3)
|
||||||
|
|
||||||
# learning rate schedule args
|
# --- 数据集参数 ---
|
||||||
parser.add_argument('--weight_decay', type=float, default=0.1)
|
parser.add_argument('--data_path', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/', type=str)
|
||||||
parser.add_argument('--lr', type=float, default=None, metavar='LR')
|
parser.add_argument('--output_dir', default="./output_dir", type=str)
|
||||||
parser.add_argument('--min_lr', type=float, default=0., metavar='LR')
|
parser.add_argument('--log_dir', default='./output_dir/log', type=str)
|
||||||
parser.add_argument('--warmup_epochs', type=int, default=8, metavar='N')
|
parser.add_argument('--dataset_stride', type=int, default=150, help='Stride for sliding window dataset')
|
||||||
parser.add_argument('--clip_grad', type=float, default=None,
|
parser.add_argument('--num_workers', default=8, type=int)
|
||||||
help='Clip gradient norm (default: None, no clipping)')
|
parser.add_argument('--pin_mem', action='store_true')
|
||||||
# device args
|
parser.set_defaults(pin_mem=True)
|
||||||
|
|
||||||
|
# --- 硬件与分布式参数 ---
|
||||||
parser.add_argument('--device', default='cuda', type=str)
|
parser.add_argument('--device', default='cuda', type=str)
|
||||||
parser.add_argument('--seed', default=42, type=int)
|
parser.add_argument('--seed', default=42, type=int)
|
||||||
parser.add_argument('--resume', default='', type=str)
|
parser.add_argument('--resume', default='', type=str)
|
||||||
parser.add_argument('--is_test', default=0, type=int)
|
|
||||||
parser.add_argument('--start_epoch', default=0, type=int, metavar='N')
|
parser.add_argument('--start_epoch', default=0, type=int, metavar='N')
|
||||||
|
|
||||||
# dataset args
|
|
||||||
parser.add_argument(
|
|
||||||
'--data_path', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/', type=str)
|
|
||||||
parser.add_argument(
|
|
||||||
'--output_dir', default="/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/result", type=str)
|
|
||||||
parser.add_argument(
|
|
||||||
'--log_dir', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/result/log', type=str)
|
|
||||||
parser.add_argument('--num_workers', default=4, type=int)
|
|
||||||
parser.add_argument('--pin_mem', action='store_true')
|
|
||||||
parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
|
|
||||||
parser.set_defaults(pin_mem=True)
|
|
||||||
|
|
||||||
# distribute args
|
|
||||||
parser.add_argument('--world_size', default=1, type=int)
|
parser.add_argument('--world_size', default=1, type=int)
|
||||||
parser.add_argument('--local_rank', default=-1, type=int)
|
parser.add_argument('--local_rank', default=-1, type=int)
|
||||||
parser.add_argument('--dist_on_itp', action='store_true')
|
parser.add_argument('--dist_on_itp', action='store_true')
|
||||||
parser.add_argument('--dist_url', default='env://', type=str)
|
parser.add_argument('--dist_url', default='env://', type=str)
|
||||||
return parser
|
|
||||||
|
# --- 精度控制 ---
|
||||||
|
parser.add_argument('--precision', default='bf16', type=str, choices=['fp32', 'fp16', 'bf16'],
|
||||||
|
help='Training precision. bf16 recommended for A100/H100/RTX30+')
|
||||||
|
|
||||||
|
return parser
|
||||||
|
|
||||||
def main(args):
|
def main(args):
|
||||||
misc.init_distributed_mode(args)
|
misc.init_distributed_mode(args)
|
||||||
@@ -115,33 +101,35 @@ def main(args):
|
|||||||
|
|
||||||
device = torch.device(args.device)
|
device = torch.device(args.device)
|
||||||
|
|
||||||
# --- [修改] 根据选择的精度设置 dtype 和检查硬件支持 ---
|
# --- 精度设置 ---
|
||||||
if args.precision == 'bf16':
|
if args.precision == 'bf16':
|
||||||
if not torch.cuda.is_bf16_supported():
|
if not torch.cuda.is_bf16_supported():
|
||||||
raise SystemExit(
|
print("Warning: BF16 not supported, falling back to FP16.")
|
||||||
"BF16 is not supported on this device, please use --precision fp16 or fp32.")
|
args.precision = 'fp16'
|
||||||
dtype = torch.bfloat16
|
dtype = torch.float16
|
||||||
|
else:
|
||||||
|
dtype = torch.bfloat16
|
||||||
elif args.precision == 'fp16':
|
elif args.precision == 'fp16':
|
||||||
dtype = torch.float16
|
dtype = torch.float16
|
||||||
else:
|
else:
|
||||||
dtype = torch.float32
|
dtype = torch.float32
|
||||||
|
|
||||||
if misc.is_main_process():
|
if misc.is_main_process():
|
||||||
print(f"Using precision: {args.precision} with dtype: {dtype}")
|
print(f"🚀 Using precision: {args.precision} ({dtype})")
|
||||||
|
|
||||||
|
# --- 随机种子 ---
|
||||||
seed = args.seed + misc.get_rank()
|
seed = args.seed + misc.get_rank()
|
||||||
torch.manual_seed(seed)
|
torch.manual_seed(seed)
|
||||||
np.random.seed(seed)
|
np.random.seed(seed)
|
||||||
cudnn.benchmark = True
|
cudnn.benchmark = True
|
||||||
|
|
||||||
# [修改] 创建数据集时传入窗口化参数
|
# --- 数据集构建 ---
|
||||||
dataset_train = PretrainDataset(
|
dataset_train = PretrainDataset(
|
||||||
data_dir=args.data_path,
|
data_dir=args.data_path,
|
||||||
dataset_names=["temp"], # 您可以按需修改
|
dataset_names=["temp"], # 建议参数化
|
||||||
is_test=args.is_test,
|
is_test=0, # Pretrain 始终不是 test
|
||||||
window_size=args.img_size[0],
|
window_size=args.img_size[0],
|
||||||
# cache_name="pretrain_windows_ds527821_ws387_s100",
|
stride=args.dataset_stride # 使用参数控制
|
||||||
stride=150 # 建议将此值也设为命令行参数
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if args.distributed:
|
if args.distributed:
|
||||||
@@ -153,6 +141,7 @@ def main(args):
|
|||||||
else:
|
else:
|
||||||
sampler_train = torch.utils.data.RandomSampler(dataset_train)
|
sampler_train = torch.utils.data.RandomSampler(dataset_train)
|
||||||
|
|
||||||
|
# --- 日志记录器 ---
|
||||||
if misc.is_main_process() and args.log_dir is not None:
|
if misc.is_main_process() and args.log_dir is not None:
|
||||||
log_dir = os.path.join(args.log_dir, args.remark)
|
log_dir = os.path.join(args.log_dir, args.remark)
|
||||||
os.makedirs(log_dir, exist_ok=True)
|
os.makedirs(log_dir, exist_ok=True)
|
||||||
@@ -173,75 +162,74 @@ def main(args):
|
|||||||
drop_last=True,
|
drop_last=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# --- 模型初始化 (HFR Version) ---
|
||||||
model = NormWear(
|
model = NormWear(
|
||||||
img_size=(387, 65),
|
img_size=args.img_size,
|
||||||
patch_size=(9, 5),
|
patch_size=args.patch_size,
|
||||||
in_chans=3,
|
in_chans=args.in_chans,
|
||||||
embed_dim=args.embed_dim,
|
embed_dim=args.embed_dim,
|
||||||
depth=args.depth,
|
depth=args.depth,
|
||||||
num_heads=args.num_heads,
|
num_heads=args.num_heads,
|
||||||
decoder_embed_dim=args.decoder_embed_dim,
|
decoder_embed_dim=args.decoder_embed_dim,
|
||||||
decoder_depth=args.decoder_depth,
|
decoder_depth=args.decoder_depth,
|
||||||
decoder_num_heads=args.decoder_num_heads,
|
decoder_num_heads=args.decoder_num_heads,
|
||||||
mlp_ratio=4.0,
|
mlp_ratio=args.mlp_ratio,
|
||||||
|
# MAE 相关
|
||||||
modality_dropout_prob=args.modality_dropout,
|
modality_dropout_prob=args.modality_dropout,
|
||||||
use_hybrid_embed=True, # MAE强依赖HybridEmbed
|
loss_weight_1d_token=args.loss_weight_1d_token,
|
||||||
nvar=args.nvar # 确保传递n_vars
|
loss_weight_1d_signal=args.loss_weight_1d_signal,
|
||||||
|
nvar=args.nvar,
|
||||||
|
# HFR 相关
|
||||||
|
fluid_kernel_size=args.fluid_kernel_size
|
||||||
).to(device)
|
).to(device)
|
||||||
|
|
||||||
model.to(device)
|
|
||||||
model_without_ddp = model
|
model_without_ddp = model
|
||||||
|
|
||||||
if args.distributed:
|
if args.distributed:
|
||||||
model = torch.nn.parallel.DistributedDataParallel(
|
model = torch.nn.parallel.DistributedDataParallel(
|
||||||
model, device_ids=[args.gpu], find_unused_parameters=True)
|
model, device_ids=[args.gpu], find_unused_parameters=True) # HFR 可能需要 find_unused_parameters=False 如果图是静态的
|
||||||
model_without_ddp = model.module
|
model_without_ddp = model.module
|
||||||
|
|
||||||
|
# --- 学习率与优化器 ---
|
||||||
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
|
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
|
||||||
if args.lr is None:
|
if args.lr is None:
|
||||||
args.lr = args.blr * eff_batch_size / 256
|
args.lr = args.blr * eff_batch_size / 256
|
||||||
|
|
||||||
if misc.is_main_process():
|
if misc.is_main_process():
|
||||||
print(
|
print(f"base lr: {args.blr:.2e}, actual lr: {args.lr:.2e}, effective batch size: {eff_batch_size}")
|
||||||
f"base lr: {args.blr:.2e}, actual lr: {args.lr:.2e}, effective batch size: {eff_batch_size}")
|
|
||||||
|
|
||||||
|
# HFR 对参数比较敏感,AdamW 是个好选择,但 beta2 可以稍微调低一点 (e.g., 0.95) 如果训练不稳定
|
||||||
optimizer = torch.optim.AdamW(
|
optimizer = torch.optim.AdamW(
|
||||||
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
||||||
|
|
||||||
# --- [修改] 条件性地创建 GradScaler ---
|
# --- Loss Scaler ---
|
||||||
# 只有在 fp16 模式下才需要 GradScaler,bf16 和 fp32 不需要
|
# BF16 不需要 scaler,FP16 需要
|
||||||
loss_scaler = NativeScalerWithGradNormCount() if dtype == torch.float16 else None
|
loss_scaler = NativeScalerWithGradNormCount() if args.precision == 'fp16' else None
|
||||||
if misc.is_main_process():
|
|
||||||
if loss_scaler:
|
|
||||||
print("Using custom NativeScaler for FP16 training.")
|
|
||||||
else:
|
|
||||||
print("GradScaler is disabled for BF16/FP32 training.")
|
|
||||||
|
|
||||||
misc.load_model(args=args, model_without_ddp=model_without_ddp,
|
misc.load_model(args=args, model_without_ddp=model_without_ddp,
|
||||||
optimizer=optimizer, loss_scaler=loss_scaler)
|
optimizer=optimizer, loss_scaler=loss_scaler)
|
||||||
|
|
||||||
print(f"Start training for {args.epochs} epochs on rank {misc.get_rank()}")
|
print(f"🔥 Start training for {args.epochs} epochs on rank {misc.get_rank()}")
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
|
||||||
for epoch in range(args.start_epoch, args.epochs):
|
for epoch in range(args.start_epoch, args.epochs):
|
||||||
if args.distributed:
|
if args.distributed:
|
||||||
data_loader_train.sampler.set_epoch(epoch)
|
data_loader_train.sampler.set_epoch(epoch)
|
||||||
|
|
||||||
# [修改] 将 dtype 传入训练引擎
|
|
||||||
train_stats = train_one_epoch(
|
train_stats = train_one_epoch(
|
||||||
model, data_loader_train,
|
model, data_loader_train,
|
||||||
optimizer, device, epoch, loss_scaler,
|
optimizer, device, epoch, loss_scaler,
|
||||||
log_writer=log_writer,
|
log_writer=log_writer,
|
||||||
args=args,
|
args=args,
|
||||||
dtype=dtype # 传入选择的精度
|
dtype=dtype # 传入精度类型
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 保存逻辑
|
||||||
if args.output_dir and (epoch % args.save_every_epoch == 0 or epoch + 1 == args.epochs):
|
if args.output_dir and (epoch % args.save_every_epoch == 0 or epoch + 1 == args.epochs):
|
||||||
misc.save_model(
|
misc.save_model(
|
||||||
args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer,
|
args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer,
|
||||||
loss_scaler=loss_scaler, epoch=epoch) # [修改] 保存当前epoch
|
loss_scaler=loss_scaler, epoch=epoch)
|
||||||
|
|
||||||
log_stats = {**{f'train_{k}': v for k,
|
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 'epoch': epoch}
|
||||||
v in train_stats.items()}, 'epoch': epoch}
|
|
||||||
|
|
||||||
if args.output_dir and misc.is_main_process():
|
if args.output_dir and misc.is_main_process():
|
||||||
if log_writer is not None:
|
if log_writer is not None:
|
||||||
@@ -253,10 +241,9 @@ def main(args):
|
|||||||
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
||||||
print(f'Training time {total_time_str} on rank {misc.get_rank()}')
|
print(f'Training time {total_time_str} on rank {misc.get_rank()}')
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
args = get_args_parser()
|
args = get_args_parser()
|
||||||
args = args.parse_args()
|
args = args.parse_args()
|
||||||
if args.output_dir:
|
if args.output_dir:
|
||||||
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
||||||
main(args)
|
main(args)
|
||||||
Reference in new issue
Block a user