arif commited on
Update model.py
Browse files
model.py
CHANGED
|
@@ -1,138 +1,137 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
from torch.utils.data import Dataset, DataLoader, random_split
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import numpy as np
|
| 6 |
-
from transformers import BertTokenizer
|
| 7 |
-
import os
|
| 8 |
-
from pose_format import Pose
|
| 9 |
-
import matplotlib.pyplot as plt
|
| 10 |
-
from matplotlib import animation
|
| 11 |
-
from
|
| 12 |
-
from
|
| 13 |
-
from
|
| 14 |
-
from
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
self.
|
| 30 |
-
self.
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
self.
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
self.
|
| 43 |
-
self.
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
use_teacher
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
h = self.
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
masked_error
|
| 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 |
-
return distance
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torch.utils.data import Dataset, DataLoader, random_split
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
from transformers import BertTokenizer
|
| 7 |
+
import os
|
| 8 |
+
from pose_format import Pose
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
from matplotlib import animation
|
| 11 |
+
from fastdtw import fastdtw # Keep this import
|
| 12 |
+
from scipy.spatial.distance import cosine
|
| 13 |
+
from config import MAX_TEXT_LEN, TARGET_NUM_FRAME, BATCH_SIZE, TEACHER_FORCING_RATIO, SMOOTHING_ENABLED
|
| 14 |
+
from transformers import BertModel # ✅ Import BERT
|
| 15 |
+
|
| 16 |
+
tokenizer = BertTokenizer.from_pretrained("indobenchmark/indobert-base-p2")
|
| 17 |
+
|
| 18 |
+
# ===== KEYPOINT SELECTION =====
|
| 19 |
+
selected_keypoint_indices = list(np.r_[0:25, 501:522, 522:543])
|
| 20 |
+
NUM_KEYPOINTS = len(selected_keypoint_indices)
|
| 21 |
+
POSE_DIM = NUM_KEYPOINTS * 3
|
| 22 |
+
|
| 23 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 24 |
+
|
| 25 |
+
class TextToPoseSeq2Seq(nn.Module):
|
| 26 |
+
def __init__(self, vocab_size, hidden_dim=512, pose_dim=POSE_DIM, max_len=MAX_TEXT_LEN, target_len=TARGET_NUM_FRAMES):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.hidden_dim = hidden_dim
|
| 29 |
+
self.target_len = target_len
|
| 30 |
+
self.pose_dim = pose_dim
|
| 31 |
+
|
| 32 |
+
# === BERT Encoder ===
|
| 33 |
+
self.encoder = BertModel.from_pretrained("indobenchmark/indobert-base-p2")
|
| 34 |
+
|
| 35 |
+
# === GRU Decoder ===
|
| 36 |
+
self.input_proj = nn.Linear(pose_dim, hidden_dim)
|
| 37 |
+
bert_hidden = self.encoder.config.hidden_size
|
| 38 |
+
self.gru_cell = nn.GRUCell(hidden_dim + bert_hidden, hidden_dim)
|
| 39 |
+
self.dropout = nn.Dropout(0.3)
|
| 40 |
+
|
| 41 |
+
self.fc_pose = nn.Linear(hidden_dim, pose_dim)
|
| 42 |
+
self.fc_conf = nn.Linear(hidden_dim, NUM_KEYPOINTS)
|
| 43 |
+
self.output_scale = 1.0
|
| 44 |
+
|
| 45 |
+
def forward(self, input_ids, attention_mask=None, target_pose=None, teacher_forcing_ratio=TEACHER_FORCING_RATIO):
|
| 46 |
+
B = input_ids.size(0)
|
| 47 |
+
pose_outputs = []
|
| 48 |
+
conf_outputs = []
|
| 49 |
+
input_pose = torch.zeros(B, self.pose_dim).to(input_ids.device)
|
| 50 |
+
|
| 51 |
+
# === BERT Encoding ===
|
| 52 |
+
encoder_outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
|
| 53 |
+
context = encoder_outputs.last_hidden_state[:, 0, :] # [CLS] token
|
| 54 |
+
|
| 55 |
+
h = torch.zeros(B, self.hidden_dim).to(input_ids.device)
|
| 56 |
+
|
| 57 |
+
for t in range(self.target_len):
|
| 58 |
+
use_teacher = self.training and target_pose is not None and torch.rand(1).item() < teacher_forcing_ratio
|
| 59 |
+
if use_teacher and t > 0:
|
| 60 |
+
input_pose = target_pose[:, t - 1, :]
|
| 61 |
+
elif t > 0:
|
| 62 |
+
input_pose = pose_outputs[-1].squeeze(1).detach()
|
| 63 |
+
|
| 64 |
+
pose_emb = self.input_proj(input_pose)
|
| 65 |
+
gru_input = torch.cat([pose_emb, context], dim=-1)
|
| 66 |
+
h = self.gru_cell(gru_input, h)
|
| 67 |
+
h = self.dropout(h)
|
| 68 |
+
|
| 69 |
+
pred_pose = self.fc_pose(h) * self.output_scale
|
| 70 |
+
pred_conf = torch.sigmoid(self.fc_conf(h))
|
| 71 |
+
|
| 72 |
+
pose_outputs.append(pred_pose.unsqueeze(1))
|
| 73 |
+
conf_outputs.append(pred_conf.unsqueeze(1))
|
| 74 |
+
input_pose = pred_pose.detach()
|
| 75 |
+
|
| 76 |
+
return torch.cat(pose_outputs, dim=1), torch.cat(conf_outputs, dim=1)
|
| 77 |
+
|
| 78 |
+
# ===== METRICS =====
|
| 79 |
+
def mpjpe(pred, target, mask=None):
|
| 80 |
+
# Shapes: (B, T, POSE_DIM)
|
| 81 |
+
pred = pred.view(pred.size(0), pred.size(1), NUM_KEYPOINTS, 3)
|
| 82 |
+
target = target.view(target.size(0), target.size(1), NUM_KEYPOINTS, 3)
|
| 83 |
+
|
| 84 |
+
error = torch.norm(pred - target, dim=3) # (B, T, NUM_KEYPOINTS)
|
| 85 |
+
|
| 86 |
+
if mask is not None:
|
| 87 |
+
mask = mask.view(pred.size(0), pred.size(1), NUM_KEYPOINTS) # (B, T, K)
|
| 88 |
+
masked_error = error * mask
|
| 89 |
+
return masked_error.sum() / (mask.sum() + 1e-8)
|
| 90 |
+
else:
|
| 91 |
+
return error.mean()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def per_joint_mpjpe(pred, target, mask=None):
|
| 95 |
+
pred = pred.view(-1, NUM_KEYPOINTS, 3)
|
| 96 |
+
target = target.view(-1, NUM_KEYPOINTS, 3)
|
| 97 |
+
error = torch.norm(pred - target, dim=2) # (B*T, K)
|
| 98 |
+
|
| 99 |
+
if mask is not None:
|
| 100 |
+
mask = mask.view(-1, NUM_KEYPOINTS) # (B*T, K)
|
| 101 |
+
masked_error = error * mask
|
| 102 |
+
joint_means = masked_error.sum(dim=0) / (mask.sum(dim=0) + 1e-8)
|
| 103 |
+
return joint_means.cpu().numpy()
|
| 104 |
+
else:
|
| 105 |
+
return error.mean(dim=0).cpu().numpy()
|
| 106 |
+
|
| 107 |
+
def pose_velocity(pose_seq):
|
| 108 |
+
# pose_seq shape is assumed to be (B, T, POSE_DIM)
|
| 109 |
+
# Calculate difference along the time dimension (dim=1)
|
| 110 |
+
diffs = pose_seq[:, 1:, :] - pose_seq[:, :-1, :]
|
| 111 |
+
# Reshape to (B, T-1, NUM_KEYPOINTS, 3) to get per-joint velocity
|
| 112 |
+
diffs = diffs.view(diffs.size(0), diffs.size(1), NUM_KEYPOINTS, 3)
|
| 113 |
+
# Norm over coordinate dimension (dim=3), then mean over batch and time
|
| 114 |
+
return torch.norm(diffs, dim=3).mean().item()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def cosine_similarity(pred, target):
|
| 118 |
+
# pred and target are (B, T, POSE_DIM)
|
| 119 |
+
pred = pred.view(-1, POSE_DIM).cpu().numpy()
|
| 120 |
+
target = target.view(-1, POSE_DIM).cpu().numpy()
|
| 121 |
+
# Cosine similarity is usually calculated per sample or per timestep.
|
| 122 |
+
# Calculating on flattened data across batch and time might not be meaningful.
|
| 123 |
+
# Returning a scalar mean of pairwise similarities could be an alternative.
|
| 124 |
+
# For simplicity, calculating similarity of flattened arrays.
|
| 125 |
+
if np.linalg.norm(pred) == 0 or np.linalg.norm(target) == 0:
|
| 126 |
+
return 0.0 # Handle zero vectors
|
| 127 |
+
return 1 - cosine(pred.flatten(), target.flatten())
|
| 128 |
+
|
| 129 |
+
def dtw_distance(pred, target):
|
| 130 |
+
# pred and target are (B, T, POSE_DIM)
|
| 131 |
+
# DTW is typically computed sequence-wise (T, POSE_DIM)
|
| 132 |
+
# Computing on the first sample of the batch as an example
|
| 133 |
+
pred_seq = pred[0].view(-1, POSE_DIM).cpu().numpy()
|
| 134 |
+
target_seq = target[0].view(-1, POSE_DIM).cpu().numpy()
|
| 135 |
+
# Use Euclidean distance as the distance metric for DTW
|
| 136 |
+
distance, _ = fastdtw(pred_seq, target_seq, dist=lambda a, b: np.linalg.norm(a - b))
|
| 137 |
+
return distance
|
|
|