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41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465

import os
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models

try:
    import timm
except ImportError:
    timm = None

try:
    import utils
    from modules.criterions import SeqKD
    from modules import BiLSTMLayer, TemporalConv
except:
    from . import utils
    from .modules.criterions import SeqKD
    from .modules import BiLSTMLayer, TemporalConv

# PoseAssistEncoder is defined below in this file, so always available
POSE_ASSIST_AVAILABLE = True


# 全局日志文件路径(会在第一次使用时设置)
_MODEL_LOG_FILE = None


def _log_model_info(msg):
    """同时输出到stdout和日志文件"""
    print(msg, flush=True)
    sys.stdout.flush()  # 强制刷新stdout

    global _MODEL_LOG_FILE
    if _MODEL_LOG_FILE is None:
        # 尝试找到work_dir
        import glob
        work_dirs = glob.glob('work_dir/*/log.txt')
        if work_dirs:
            log_path = work_dirs[0]
            _MODEL_LOG_FILE = log_path

    if _MODEL_LOG_FILE and os.path.exists(os.path.dirname(_MODEL_LOG_FILE)):
        try:
            with open(_MODEL_LOG_FILE, 'a') as f:
                f.write(msg + '\n')
                f.flush()
        except:
            pass  # 如果写入失败,至少print了


class Identity(nn.Module):
    def __init__(self):
        super(Identity, self).__init__()

    def forward(self, x):
        return x


class NormLinear(nn.Module):
    def __init__(self, in_dim, out_dim):
        super(NormLinear, self).__init__()
        self.weight = nn.Parameter(torch.Tensor(in_dim, out_dim))
        nn.init.xavier_uniform_(self.weight, gain=nn.init.calculate_gain('relu'))

    def forward(self, x):
        outputs = torch.matmul(x, F.normalize(self.weight, dim=0))
        return outputs


class TimmBackbone(nn.Module):
    """Small wrapper so timm backbones behave like torchvision CNNs."""

    def __init__(self, model):
        super().__init__()
        self.model = model

    def forward(self, x):
        outputs = self.model(x)
        if isinstance(outputs, (tuple, list)):
            outputs = outputs[0]
        # ViT-style models can return (B, Tokens, Dim); take CLS token.
        if outputs.dim() == 3:
            outputs = outputs[:, 0]
        return outputs


class PoseAssistEncoder(nn.Module):
    """Simplified pose assistance encoder using ViT backbone with frozen weights."""

    def __init__(self, target_dim=512, checkpoint_path=None):
        super().__init__()
        _log_model_info("=" * 70)
        _log_model_info("[PoseAssist] Initializing Pose Assistance Encoder")
        _log_model_info("=" * 70)
        _log_model_info("[PoseAssist] Loading ViT-base-patch16-224 from timm...")
        _log_model_info("[PoseAssist] This may take a moment if downloading pretrained weights...")

        import time
        start_time = time.time()

        # Use ViT-base for feature extraction
        self.backbone = timm.create_model('vit_base_patch16_224', pretrained=True, num_classes=0)

        load_time = time.time() - start_time
        _log_model_info(f"[PoseAssist] ✓ ViT backbone loaded in {load_time:.2f} seconds")

        # Count parameters
        vit_params = sum(p.numel() for p in self.backbone.parameters())
        _log_model_info(f"[PoseAssist] ViT parameters: {vit_params:,}")

        _log_model_info("[PoseAssist] Initializing temporal attention and projection layers...")
        self.temporal_attention = nn.MultiheadAttention(768, num_heads=8)
        self.temporal_norm = nn.LayerNorm(768)

        # Project to match ResNet output dimension
        self.projection = nn.Linear(768, target_dim)
        _log_model_info(f"[PoseAssist] Projection layer: 768 → {target_dim}")

        # Load from checkpoint if provided
        if checkpoint_path and os.path.exists(checkpoint_path):
            _log_model_info(f"[PoseAssist] Found video2text checkpoint: {checkpoint_path}")
            self._load_from_video2text_checkpoint(checkpoint_path)
        else:
            if checkpoint_path:
                _log_model_info(f"[PoseAssist] ⚠ Checkpoint not found: {checkpoint_path}")
            _log_model_info("[PoseAssist] Using timm pretrained ViT weights only")

        # Freeze all parameters
        _log_model_info("[PoseAssist] Freezing all parameters...")
        for param in self.parameters():
            param.requires_grad = False

        total_params = sum(p.numel() for p in self.parameters())
        trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
        _log_model_info(f"[PoseAssist] Total parameters: {total_params:,}")
        _log_model_info(f"[PoseAssist] Trainable parameters: {trainable_params:,}")
        _log_model_info(f"[PoseAssist] ✓ All parameters frozen (requires_grad=False)")
        _log_model_info("=" * 70)

    def _load_from_video2text_checkpoint(self, checkpoint_path):
        """Load weights from video2text checkpoint."""
        try:
            _log_model_info(f"[PoseAssist] Loading weights from {checkpoint_path}")
            checkpoint = torch.load(checkpoint_path, map_location='cpu')

            # Extract video2pose state dict
            if 'model_state_dict' in checkpoint:
                model_state = checkpoint['model_state_dict']
                # Filter video2pose weights
                video2pose_state = {
                    k.replace('video2pose.', ''): v
                    for k, v in model_state.items()
                    if k.startswith('video2pose.')
                }

                if video2pose_state:
                    # Load matching weights (strict=False to allow partial loading)
                    missing, unexpected = self.load_state_dict(video2pose_state, strict=False)
                    _log_model_info(f"[PoseAssist] Loaded weights from checkpoint")
                    if missing:
                        _log_model_info(f"[PoseAssist] Missing keys: {len(missing)}")
                    if unexpected:
                        _log_model_info(f"[PoseAssist] Unexpected keys: {len(unexpected)}")
                else:
                    _log_model_info("[PoseAssist] No video2pose weights found in checkpoint, using pretrained ViT")
            else:
                _log_model_info("[PoseAssist] Checkpoint format not recognized, using pretrained ViT")
        except Exception as e:
            _log_model_info(f"[PoseAssist] Failed to load checkpoint: {e}, using pretrained ViT")

    def forward(self, x):
        """
        Args:
            x: [B*F, 3, H, W] frames
        Returns:
            features: [B*F, target_dim] frame-level features
        """
        with torch.no_grad():  # Ensure no gradients
            # Extract features using ViT
            features = self.backbone(x)  # [B*F, 768]
            features = self.projection(features)  # [B*F, target_dim]
        return features


class SLRModel(nn.Module):
    def __init__(
            self, num_classes, c2d_type, conv_type, use_bn=False,
            hidden_size=1024, gloss_dict=None, loss_weights=None,
            weight_norm=True, share_classifier=True, backbone_weights=None,
            backbone_checkpoint=False, multimodal_pose_assist=False,
            pose_assist_checkpoint=None, pose_assist_weight=0.01,
            pose_assist_learnable=True, pose_assist_dropout=0.0
    ):
        super(SLRModel, self).__init__()
        self.decoder = None
        self.loss = dict()
        self.criterion_init()
        self.num_classes = num_classes
        self.loss_weights = loss_weights
        self.multimodal_pose_assist = multimodal_pose_assist
        self.pose_assist_weight_init = pose_assist_weight  # 保存初始值
        self.pose_assist_learnable = pose_assist_learnable
        self.pose_assist_dropout_rate = pose_assist_dropout

        self.conv2d, self.backbone_feat_dim = self._init_backbone(
            c2d_type, backbone_weights, backbone_checkpoint
        )

        # Initialize pose assistance encoder if enabled
        self.pose_assist_encoder = None
        self.pose_assist_weight_param = None
        self.pose_assist_dropout = None
        if self.multimodal_pose_assist:
            if not POSE_ASSIST_AVAILABLE:
                _log_model_info("[Warning] multimodal_pose_assist=True but pose assist not available, disabling")
                self.multimodal_pose_assist = False
            else:
                _log_model_info(f"[SLRModel] Enabling multimodal pose assistance (initial_weight={pose_assist_weight})")
                self.pose_assist_encoder = PoseAssistEncoder(
                    target_dim=self.backbone_feat_dim,
                    checkpoint_path=pose_assist_checkpoint
                )

                # 创建可学习的权重参数
                if pose_assist_learnable:
                    # 使用sigmoid约束,确保权重在[0, initial_weight]范围内
                    # weight = initial_weight * sigmoid(learnable_param)
                    # 初始化使得sigmoid(0) = 0.5,即初始权重为 0.5 * initial_weight
                    # 如果想初始就是initial_weight,需要让sigmoid→1,即param→+∞
                    # 折中方案:初始化为2.0,sigmoid(2.0)≈0.88
                    self.pose_assist_weight_param = nn.Parameter(torch.tensor(2.0))
                    _log_model_info(f"[SLRModel] Pose assist weight is LEARNABLE (max={pose_assist_weight})")
                else:
                    # 固定权重,不学习
                    self.register_buffer('pose_assist_weight_param', torch.tensor(1.0))
                    _log_model_info(f"[SLRModel] Pose assist weight is FIXED at {pose_assist_weight}")

                # 创建dropout层(用于regularization,防止过度依赖pose特征)
                if pose_assist_dropout > 0:
                    self.pose_assist_dropout = nn.Dropout(p=pose_assist_dropout)
                    _log_model_info(f"[SLRModel] Pose assist dropout enabled (p={pose_assist_dropout})")
                else:
                    _log_model_info(f"[SLRModel] Pose assist dropout disabled")

                _log_model_info(f"[SLRModel] Pose assist encoder initialized")

        self.conv1d = TemporalConv(input_size=self.backbone_feat_dim,
                                   hidden_size=hidden_size,
                                   conv_type=conv_type,
                                   use_bn=use_bn,
                                   num_classes=num_classes)
        self.decoder = utils.Decode(gloss_dict, num_classes, 'beam')
        self.temporal_model = BiLSTMLayer(rnn_type='LSTM', input_size=hidden_size, hidden_size=hidden_size,
                                          num_layers=2, bidirectional=True)
        if weight_norm:
            self.classifier = NormLinear(hidden_size, self.num_classes)
            self.conv1d.fc = NormLinear(hidden_size, self.num_classes)
        else:
            self.classifier = nn.Linear(hidden_size, self.num_classes)
            self.classifier = nn.Linear(hidden_size, self.num_classes)
        if share_classifier:
            self.conv1d.fc = self.classifier
        self.register_backward_hook(self.backward_hook)

    def backward_hook(self, module, grad_input, grad_output):
        for g in grad_input:
            g[g != g] = 0

    def get_pose_assist_weight(self):
        """
        获取当前的姿势辅助权重
        如果learnable=True: weight = initial_weight * sigmoid(param)
        如果learnable=False: weight = initial_weight

        约束:权重永远不超过initial_weight
        """
        if not self.multimodal_pose_assist or self.pose_assist_weight_param is None:
            return 0.0

        if self.pose_assist_learnable:
            # 使用sigmoid约束到[0, 1],然后乘以初始权重
            # 这确保了权重范围是 [0, initial_weight]
            alpha = torch.sigmoid(self.pose_assist_weight_param)
            weight = self.pose_assist_weight_init * alpha
        else:
            # 固定权重
            weight = self.pose_assist_weight_init

        return weight

    def _init_backbone(self, c2d_type, backbone_weights, backbone_checkpoint):
        """
        Build the requested visual backbone. Falls back to timm when torchvision
        does not provide the requested architecture.
        """
        if hasattr(models, c2d_type):
            backbone = getattr(models, c2d_type)(pretrained=True)
            feat_dim = self._infer_backbone_dim(backbone)
            if hasattr(backbone, 'fc'):
                backbone.fc = Identity()
            return backbone, feat_dim

        if timm is None:
            raise ValueError(
                f"Backbone '{c2d_type}' is not part of torchvision.models and timm "
                f"is not installed. Install timm>=1.0.20 to use DINO/DINOv3 models."
            )

        pool_type = 'token'
        name_lower = c2d_type.lower()
        if 'convnext' in name_lower or 'cnn' in name_lower:
            pool_type = 'avg'

        # 明确打印权重加载方式
        use_pretrained = not bool(backbone_weights)
        _log_model_info(f"[SLRModel] 初始化 backbone: {c2d_type}")
        _log_model_info(f"[SLRModel] backbone_weights参数: {backbone_weights}")
        _log_model_info(f"[SLRModel] 使用timm预训练权重: {use_pretrained}")

        model = timm.create_model(
            c2d_type,
            pretrained=use_pretrained,
            num_classes=0,
            global_pool=pool_type,
        )
        _log_model_info(f"[SLRModel] timm模型创建完成, num_features={getattr(model, 'num_features', 'unknown')}")

        if backbone_weights:
            state_dict = self._load_external_state(backbone_weights)
            missing, unexpected = model.load_state_dict(state_dict, strict=False)
            if missing:
                _log_model_info(f"[SLRModel] Warning: missing keys when loading {c2d_type}: {missing[:5]}...")
            if unexpected:
                _log_model_info(f"[SLRModel] Warning: unexpected keys when loading {c2d_type}: {unexpected[:5]}...")
        if backbone_checkpoint and hasattr(model, 'set_grad_checkpointing'):
            model.set_grad_checkpointing(True)
        elif backbone_checkpoint and hasattr(model, 'grad_checkpointing'):
            model.grad_checkpointing = True
        feat_dim = getattr(model, 'num_features', None)
        if feat_dim is None:
            raise ValueError(f"Unable to infer feature dim for backbone '{c2d_type}'")

        # 检查并打印训练模式
        trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
        total_params = sum(p.numel() for p in model.parameters())
        _log_model_info(f"[SLRModel] Backbone参数统计:")
        _log_model_info(f"[SLRModel]   可训练参数: {trainable_params:,} / {total_params:,}")
        _log_model_info(f"[SLRModel]   训练模式: {'全量训练 (所有层)' if trainable_params == total_params else '微调 (部分层冻结)'}")

        return TimmBackbone(model), feat_dim

    @staticmethod
    def _load_external_state(weight_path):
        if not os.path.isfile(weight_path):
            raise FileNotFoundError(f"Backbone weights not found: {weight_path}")
        try:
            checkpoint = torch.load(weight_path, map_location='cpu', weights_only=True)
        except TypeError:
            checkpoint = torch.load(weight_path, map_location='cpu')
        if isinstance(checkpoint, dict):
            if 'model' in checkpoint:
                checkpoint = checkpoint['model']
            elif 'state_dict' in checkpoint:
                checkpoint = checkpoint['state_dict']
        return checkpoint

    @staticmethod
    def _infer_backbone_dim(backbone):
        if hasattr(backbone, 'fc') and hasattr(backbone.fc, 'in_features'):
            return backbone.fc.in_features
        if hasattr(backbone, 'classifier') and hasattr(backbone.classifier, 'in_features'):
            return backbone.classifier.in_features
        if hasattr(backbone, 'num_features'):
            return backbone.num_features
        raise ValueError("Unable to infer feature dimension from backbone.")

    def masked_bn(self, inputs, len_x):
        def pad(tensor, length):
            return torch.cat([tensor, tensor.new(length - tensor.size(0), *tensor.size()[1:]).zero_()])

        x = torch.cat([inputs[len_x[0] * idx:len_x[0] * idx + lgt] for idx, lgt in enumerate(len_x)])

        # Extract ResNet features
        resnet_features = self.conv2d(x)

        # Add pose assistance features if enabled AND in training mode
        # Disable during evaluation to save memory
        if self.multimodal_pose_assist and self.pose_assist_encoder is not None and self.training:
            pose_features = self.pose_assist_encoder(inputs)  # Use original inputs
            pose_features = torch.cat([pose_features[len_x[0] * idx:len_x[0] * idx + lgt] for idx, lgt in enumerate(len_x)])

            # Apply dropout to pose features (only during training)
            # This helps prevent over-reliance on pose features and improves robustness
            if self.pose_assist_dropout is not None:
                pose_features = self.pose_assist_dropout(pose_features)

            # 获取动态计算的权重(可能是可学习的)
            current_weight = self.get_pose_assist_weight()

            # Combine features: ResNet + dynamic_weight * PoseAssist
            combined_features = resnet_features + current_weight * pose_features
        else:
            combined_features = resnet_features

        x = torch.cat([pad(combined_features[sum(len_x[:idx]):sum(len_x[:idx + 1])], len_x[0])
                       for idx, lgt in enumerate(len_x)])
        return x

    def forward(self, x, len_x, label=None, label_lgt=None):
        if len(x.shape) == 5:
            # videos
            batch, temp, channel, height, width = x.shape
            inputs = x.reshape(batch * temp, channel, height, width)
            framewise = self.masked_bn(inputs, len_x)
            framewise = framewise.reshape(batch, temp, -1).transpose(1, 2)
        else:
            # frame-wise features
            framewise = x

        conv1d_outputs = self.conv1d(framewise, len_x)
        # x: T, B, C
        x = conv1d_outputs['visual_feat']
        lgt = conv1d_outputs['feat_len']
        tm_outputs = self.temporal_model(x, lgt)
        outputs = self.classifier(tm_outputs['predictions'])
        pred = None if self.training \
            else self.decoder.decode(outputs, lgt, batch_first=False, probs=False)
        conv_pred = None if self.training \
            else self.decoder.decode(conv1d_outputs['conv_logits'], lgt, batch_first=False, probs=False)

        return {
            "framewise_features": framewise,
            "visual_features": x,
            "feat_len": lgt,
            "conv_logits": conv1d_outputs['conv_logits'],
            "sequence_logits": outputs,
            "conv_sents": conv_pred,
            "recognized_sents": pred,
        }

    def criterion_calculation(self, ret_dict, label, label_lgt):
        loss = 0
        for k, weight in self.loss_weights.items():
            if k == 'ConvCTC':
                loss += weight * self.loss['CTCLoss'](ret_dict["conv_logits"].log_softmax(-1),
                                                      label.cpu().int(), ret_dict["feat_len"].cpu().int(),
                                                      label_lgt.cpu().int()).mean()
            elif k == 'SeqCTC':
                loss += weight * self.loss['CTCLoss'](ret_dict["sequence_logits"].log_softmax(-1),
                                                      label.cpu().int(), ret_dict["feat_len"].cpu().int(),
                                                      label_lgt.cpu().int()).mean()
            elif k == 'Dist':
                loss += weight * self.loss['distillation'](ret_dict["conv_logits"],
                                                           ret_dict["sequence_logits"].detach(),
                                                           use_blank=False)
        return loss

    def criterion_init(self):
        self.loss['CTCLoss'] = torch.nn.CTCLoss(reduction='none', zero_infinity=False)
        self.loss['distillation'] = SeqKD(T=8)
        return self.loss