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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FinJEPA: Financial Joint-Embedding Predictive Architecture
|
| 3 |
+
A JEPA-based world model for portfolio optimization over a separated action space.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
from typing import Optional, Tuple, Dict, List
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def off_diagonal(x):
|
| 15 |
+
n, m = x.shape
|
| 16 |
+
assert n == m
|
| 17 |
+
return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def sigreg_loss(z_a, z_b, sim_coeff=0.0, std_coeff=16.0, cov_coeff=8.0):
|
| 21 |
+
sim_loss = torch.tensor(0.0, device=z_a.device)
|
| 22 |
+
std_z_a = torch.sqrt(z_a.var(dim=0) + 1e-4)
|
| 23 |
+
std_z_b = torch.sqrt(z_b.var(dim=0) + 1e-4)
|
| 24 |
+
std_loss = torch.mean(F.relu(1 - std_z_a)) + torch.mean(F.relu(1 - std_z_b))
|
| 25 |
+
N = z_a.size(0)
|
| 26 |
+
z_a = z_a - z_a.mean(dim=0)
|
| 27 |
+
z_b = z_b - z_b.mean(dim=0)
|
| 28 |
+
cov_z_a = (z_a.T @ z_a) / (N - 1)
|
| 29 |
+
cov_z_b = (z_b.T @ z_b) / (N - 1)
|
| 30 |
+
cov_loss = off_diagonal(cov_z_a).pow_(2).sum() / z_a.size(1) + off_diagonal(cov_z_b).pow_(2).sum() / z_b.size(1)
|
| 31 |
+
loss = sim_coeff * sim_loss + std_coeff * std_loss + cov_coeff * cov_loss
|
| 32 |
+
return loss, sim_loss, std_loss, cov_loss
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class TimeSeriesTokenizer(nn.Module):
|
| 36 |
+
def __init__(self, in_features: int, embed_dim: int = 128, patch_size: int = 4):
|
| 37 |
+
super().__init__()
|
| 38 |
+
self.patch_size = patch_size
|
| 39 |
+
self.embed_dim = embed_dim
|
| 40 |
+
self.proj = nn.Conv1d(in_features, embed_dim, kernel_size=patch_size, stride=patch_size)
|
| 41 |
+
self.max_patches = 1024
|
| 42 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, self.max_patches, embed_dim))
|
| 43 |
+
nn.init.normal_(self.pos_embed, std=0.02)
|
| 44 |
+
|
| 45 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 46 |
+
B, T, F = x.shape
|
| 47 |
+
x = x.transpose(1, 2)
|
| 48 |
+
x = self.proj(x)
|
| 49 |
+
x = x.transpose(1, 2)
|
| 50 |
+
N = x.size(1)
|
| 51 |
+
pos = self.pos_embed[:, :N]
|
| 52 |
+
x = x + pos
|
| 53 |
+
return x
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class RotaryPositionEmbedding(nn.Module):
|
| 57 |
+
def __init__(self, dim: int, max_seq_len: int = 2048, base: float = 10000.0):
|
| 58 |
+
super().__init__()
|
| 59 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 60 |
+
self.register_buffer("inv_freq", inv_freq)
|
| 61 |
+
self.max_seq_len = max_seq_len
|
| 62 |
+
self.dim = dim
|
| 63 |
+
|
| 64 |
+
def forward(self, x: torch.Tensor, seq_len: int) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 65 |
+
device = x.device
|
| 66 |
+
t = torch.arange(seq_len, device=device).type_as(self.inv_freq)
|
| 67 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 68 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 69 |
+
cos = emb.cos()[None, :, :]
|
| 70 |
+
sin = emb.sin()[None, :, :]
|
| 71 |
+
return cos, sin
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 75 |
+
x1, x2 = x[..., ::2], x[..., 1::2]
|
| 76 |
+
rotated = torch.stack([-x2, x1], dim=-1).flatten(-2)
|
| 77 |
+
return x * cos + rotated * sin
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class AdaLN(nn.Module):
|
| 81 |
+
def __init__(self, dim: int, action_dim: int):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.norm = nn.LayerNorm(dim, elementwise_affine=False)
|
| 84 |
+
self.scale_shift = nn.Linear(action_dim, dim * 2)
|
| 85 |
+
nn.init.zeros_(self.scale_shift.weight)
|
| 86 |
+
nn.init.zeros_(self.scale_shift.bias)
|
| 87 |
+
self.scale_shift.bias.data[:dim] = 1.0
|
| 88 |
+
|
| 89 |
+
def forward(self, x: torch.Tensor, a_emb: torch.Tensor) -> torch.Tensor:
|
| 90 |
+
x = self.norm(x)
|
| 91 |
+
scale, shift = self.scale_shift(a_emb).chunk(2, dim=-1)
|
| 92 |
+
return x * (1 + scale) + shift
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class FinJEPATransformerBlock(nn.Module):
|
| 96 |
+
def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, action_dim: int = 128, dropout: float = 0.0):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.dim = dim
|
| 99 |
+
self.num_heads = num_heads
|
| 100 |
+
self.head_dim = dim // num_heads
|
| 101 |
+
assert dim % num_heads == 0
|
| 102 |
+
self.adaln1 = AdaLN(dim, action_dim)
|
| 103 |
+
self.qkv = nn.Linear(dim, dim * 3)
|
| 104 |
+
self.proj = nn.Linear(dim, dim)
|
| 105 |
+
self.dropout = nn.Dropout(dropout)
|
| 106 |
+
self.adaln2 = AdaLN(dim, action_dim)
|
| 107 |
+
mlp_dim = int(dim * mlp_ratio)
|
| 108 |
+
self.mlp = nn.Sequential(
|
| 109 |
+
nn.Linear(dim, mlp_dim), nn.GELU(), nn.Dropout(dropout),
|
| 110 |
+
nn.Linear(mlp_dim, dim), nn.Dropout(dropout),
|
| 111 |
+
)
|
| 112 |
+
self.rope = RotaryPositionEmbedding(self.head_dim)
|
| 113 |
+
|
| 114 |
+
def forward(self, x: torch.Tensor, a_emb: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, mask=None):
|
| 115 |
+
B, N, D = x.shape
|
| 116 |
+
x_norm = self.adaln1(x, a_emb)
|
| 117 |
+
qkv = self.qkv(x_norm).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
|
| 118 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
| 119 |
+
q = apply_rotary(q, cos, sin)
|
| 120 |
+
k = apply_rotary(k, cos, sin)
|
| 121 |
+
attn = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 122 |
+
if mask is not None:
|
| 123 |
+
attn = attn.masked_fill(mask == 0, float('-inf'))
|
| 124 |
+
attn = F.softmax(attn, dim=-1)
|
| 125 |
+
attn = self.dropout(attn)
|
| 126 |
+
out = (attn @ v).transpose(1, 2).reshape(B, N, D)
|
| 127 |
+
out = self.proj(out)
|
| 128 |
+
x = x + out
|
| 129 |
+
x_norm = self.adaln2(x, a_emb)
|
| 130 |
+
x = x + self.mlp(x_norm)
|
| 131 |
+
return x
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class FinJEPATransformerEncoder(nn.Module):
|
| 135 |
+
def __init__(self, dim=128, depth=4, num_heads=4, mlp_ratio=4.0, dropout=0.0):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.blocks = nn.ModuleList([
|
| 138 |
+
FinJEPATransformerBlock(dim, num_heads, mlp_ratio, action_dim=dim, dropout=dropout)
|
| 139 |
+
for _ in range(depth)
|
| 140 |
+
])
|
| 141 |
+
self.register_buffer("dummy_action", torch.zeros(1, 1, dim))
|
| 142 |
+
self.norm = nn.LayerNorm(dim)
|
| 143 |
+
self.rope = RotaryPositionEmbedding(dim // num_heads)
|
| 144 |
+
|
| 145 |
+
def forward(self, x, mask=None):
|
| 146 |
+
B, N, D = x.shape
|
| 147 |
+
cos, sin = self.rope(x, N)
|
| 148 |
+
a = self.dummy_action.expand(B, N, D)
|
| 149 |
+
for block in self.blocks:
|
| 150 |
+
x = block(x, a, cos, sin, mask)
|
| 151 |
+
x = self.norm(x)
|
| 152 |
+
return x
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class ActionEmbedder(nn.Module):
|
| 156 |
+
def __init__(self, n_assets=10, signal_vocab_size=3, hidden_dim=128, out_dim=128):
|
| 157 |
+
super().__init__()
|
| 158 |
+
self.n_assets = n_assets
|
| 159 |
+
self.weight_proj = nn.Sequential(
|
| 160 |
+
nn.Linear(n_assets, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, hidden_dim),
|
| 161 |
+
)
|
| 162 |
+
self.signal_embed = nn.Embedding(signal_vocab_size, hidden_dim // n_assets)
|
| 163 |
+
self.hedge_embed = nn.Embedding(2, hidden_dim // 2)
|
| 164 |
+
fusion_in = hidden_dim + n_assets * (hidden_dim // n_assets) + hidden_dim // 2
|
| 165 |
+
self.fusion = nn.Sequential(
|
| 166 |
+
nn.Linear(fusion_in, out_dim), nn.GELU(), nn.Linear(out_dim, out_dim),
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
def forward(self, weights, signals, hedge=None):
|
| 170 |
+
w_emb = self.weight_proj(weights)
|
| 171 |
+
s_emb = self.signal_embed(signals).flatten(1)
|
| 172 |
+
if hedge is None:
|
| 173 |
+
h_emb = torch.zeros(weights.size(0), self.fusion[0].in_features - w_emb.size(1) - s_emb.size(1), device=weights.device)
|
| 174 |
+
else:
|
| 175 |
+
h_emb = self.hedge_embed(hedge).squeeze(1)
|
| 176 |
+
a_emb = self.fusion(torch.cat([w_emb, s_emb, h_emb], dim=-1))
|
| 177 |
+
return a_emb
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class FinJEPAPredictor(nn.Module):
|
| 181 |
+
def __init__(self, dim=128, depth=6, num_heads=4, mlp_ratio=4.0, action_dim=128, dropout=0.0, max_target_tokens=64):
|
| 182 |
+
super().__init__()
|
| 183 |
+
self.dim = dim
|
| 184 |
+
self.max_target_tokens = max_target_tokens
|
| 185 |
+
self.target_queries = nn.Parameter(torch.zeros(1, max_target_tokens, dim))
|
| 186 |
+
nn.init.normal_(self.target_queries, std=0.02)
|
| 187 |
+
self.blocks = nn.ModuleList([
|
| 188 |
+
FinJEPATransformerBlock(dim, num_heads, mlp_ratio, action_dim, dropout)
|
| 189 |
+
for _ in range(depth)
|
| 190 |
+
])
|
| 191 |
+
self.norm = nn.LayerNorm(dim)
|
| 192 |
+
self.action_proj = nn.Linear(action_dim, dim)
|
| 193 |
+
self.rope = RotaryPositionEmbedding(dim // num_heads)
|
| 194 |
+
|
| 195 |
+
def forward(self, x, action_emb, n_target_tokens=None, mask=None):
|
| 196 |
+
B, N_ctx, D = x.shape
|
| 197 |
+
n_target = n_target_tokens if n_target_tokens is not None else 1
|
| 198 |
+
queries = self.target_queries[:, :n_target].expand(B, -1, -1)
|
| 199 |
+
x = torch.cat([x, queries], dim=1)
|
| 200 |
+
N_total = x.size(1)
|
| 201 |
+
a_seq = self.action_proj(action_emb).unsqueeze(1).expand(B, N_total, D)
|
| 202 |
+
cos, sin = self.rope(x, N_total)
|
| 203 |
+
for block in self.blocks:
|
| 204 |
+
x = block(x, a_seq, cos, sin, mask)
|
| 205 |
+
x = self.norm(x)
|
| 206 |
+
target_pred = x[:, N_ctx:]
|
| 207 |
+
return target_pred
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class InverseDynamicsModel(nn.Module):
|
| 211 |
+
def __init__(self, z_dim, n_assets, signal_vocab_size=3, hidden_dim=256):
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.n_assets = n_assets
|
| 214 |
+
self.mlp = nn.Sequential(
|
| 215 |
+
nn.Linear(z_dim * 2, hidden_dim), nn.GELU(),
|
| 216 |
+
nn.Linear(hidden_dim, hidden_dim), nn.GELU(),
|
| 217 |
+
)
|
| 218 |
+
self.weight_head = nn.Linear(hidden_dim, n_assets)
|
| 219 |
+
self.signal_head = nn.Linear(hidden_dim, n_assets * signal_vocab_size)
|
| 220 |
+
|
| 221 |
+
def forward(self, z_t, z_tp1):
|
| 222 |
+
h = self.mlp(torch.cat([z_t, z_tp1], dim=-1))
|
| 223 |
+
weights = self.weight_head(h)
|
| 224 |
+
signals_logits = self.signal_head(h).reshape(-1, self.n_assets, 3)
|
| 225 |
+
return {"weights": weights, "signals_logits": signals_logits}
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class FinJEPA(nn.Module):
|
| 229 |
+
def __init__(
|
| 230 |
+
self, in_features=7, n_assets=10, patch_size=4, embed_dim=128,
|
| 231 |
+
encoder_depth=4, encoder_heads=4, predictor_depth=6, predictor_heads=4,
|
| 232 |
+
action_hidden_dim=128, signal_vocab_size=3, mlp_ratio=4.0,
|
| 233 |
+
dropout=0.0, ema_decay=0.996, use_idm=True, use_td_branch=False,
|
| 234 |
+
):
|
| 235 |
+
super().__init__()
|
| 236 |
+
self.embed_dim = embed_dim
|
| 237 |
+
self.ema_decay = ema_decay
|
| 238 |
+
self.use_idm = use_idm
|
| 239 |
+
self.use_td_branch = use_td_branch
|
| 240 |
+
self.n_assets = n_assets
|
| 241 |
+
|
| 242 |
+
self.tokenizer = TimeSeriesTokenizer(in_features, embed_dim, patch_size)
|
| 243 |
+
self.context_encoder = FinJEPATransformerEncoder(embed_dim, encoder_depth, encoder_heads, mlp_ratio, dropout)
|
| 244 |
+
self.target_encoder = FinJEPATransformerEncoder(embed_dim, encoder_depth, encoder_heads, mlp_ratio, dropout)
|
| 245 |
+
for p in self.target_encoder.parameters():
|
| 246 |
+
p.requires_grad = False
|
| 247 |
+
|
| 248 |
+
self.action_embedder = ActionEmbedder(n_assets, signal_vocab_size, action_hidden_dim, embed_dim)
|
| 249 |
+
self.predictor = FinJEPAPredictor(embed_dim, predictor_depth, predictor_heads, mlp_ratio, embed_dim, dropout)
|
| 250 |
+
|
| 251 |
+
if use_idm:
|
| 252 |
+
self.idm = InverseDynamicsModel(embed_dim, n_assets, signal_vocab_size, hidden_dim=256)
|
| 253 |
+
else:
|
| 254 |
+
self.idm = None
|
| 255 |
+
|
| 256 |
+
if use_td_branch:
|
| 257 |
+
self.task_encoder = FinJEPATransformerEncoder(embed_dim, encoder_depth, encoder_heads, mlp_ratio, dropout)
|
| 258 |
+
for p in self.task_encoder.parameters():
|
| 259 |
+
p.requires_grad = False
|
| 260 |
+
self.task_predictor = FinJEPAPredictor(embed_dim, predictor_depth, predictor_heads, mlp_ratio, embed_dim, dropout)
|
| 261 |
+
else:
|
| 262 |
+
self.task_encoder = None
|
| 263 |
+
self.task_predictor = None
|
| 264 |
+
|
| 265 |
+
self._init_target_encoder()
|
| 266 |
+
|
| 267 |
+
def _init_target_encoder(self):
|
| 268 |
+
self.target_encoder.load_state_dict(self.context_encoder.state_dict())
|
| 269 |
+
for p in self.target_encoder.parameters():
|
| 270 |
+
p.requires_grad = False
|
| 271 |
+
|
| 272 |
+
def update_target(self):
|
| 273 |
+
with torch.no_grad():
|
| 274 |
+
for param_s, param_t in zip(self.context_encoder.parameters(), self.target_encoder.parameters()):
|
| 275 |
+
param_t.data.mul_(self.ema_decay).add_(param_s.data, alpha=1 - self.ema_decay)
|
| 276 |
+
|
| 277 |
+
def encode_context(self, x, mask=None):
|
| 278 |
+
tokens = self.tokenizer(x)
|
| 279 |
+
z = self.context_encoder(tokens, mask)
|
| 280 |
+
return z
|
| 281 |
+
|
| 282 |
+
@torch.no_grad()
|
| 283 |
+
def encode_target(self, x, mask=None):
|
| 284 |
+
tokens = self.tokenizer(x)
|
| 285 |
+
z = self.target_encoder(tokens, mask)
|
| 286 |
+
return z
|
| 287 |
+
|
| 288 |
+
def forward(self, context_series, target_series, weights, signals, hedge=None, context_mask=None, target_mask=None):
|
| 289 |
+
z_context = self.encode_context(context_series, context_mask)
|
| 290 |
+
with torch.no_grad():
|
| 291 |
+
z_target = self.encode_target(target_series, target_mask)
|
| 292 |
+
action_emb = self.action_embedder(weights, signals, hedge)
|
| 293 |
+
n_target = z_target.size(1)
|
| 294 |
+
z_pred = self.predictor(z_context, action_emb, n_target_tokens=n_target, mask=context_mask)
|
| 295 |
+
idm_out = None
|
| 296 |
+
if self.use_idm and self.idm is not None:
|
| 297 |
+
z_t = z_context[:, -1]
|
| 298 |
+
z_next = z_target[:, 0]
|
| 299 |
+
idm_out = self.idm(z_t, z_next)
|
| 300 |
+
return {"z_pred": z_pred, "z_target": z_target, "action_emb": action_emb, "idm": idm_out}
|
| 301 |
+
|
| 302 |
+
def predict_next_state(self, state_series, weights, signals, hedge=None, mask=None):
|
| 303 |
+
z = self.encode_context(state_series, mask)
|
| 304 |
+
action_emb = self.action_embedder(weights, signals, hedge)
|
| 305 |
+
z_next = self.predictor(z, action_emb, n_target_tokens=1, mask=mask)
|
| 306 |
+
return z_next
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class FinJEPALoss(nn.Module):
|
| 310 |
+
def __init__(self, pred_loss="l1", alpha=2.0, beta=1.0, delta=4.0, omega=0.5, gamma=0.5, use_sigreg=True):
|
| 311 |
+
super().__init__()
|
| 312 |
+
self.pred_loss = pred_loss
|
| 313 |
+
self.alpha = alpha
|
| 314 |
+
self.beta = beta
|
| 315 |
+
self.delta = delta
|
| 316 |
+
self.omega = omega
|
| 317 |
+
self.gamma = gamma
|
| 318 |
+
self.use_sigreg = use_sigreg
|
| 319 |
+
|
| 320 |
+
def forward(self, outputs, actions_gt=None, rollout_outputs=None):
|
| 321 |
+
z_pred = outputs["z_pred"]
|
| 322 |
+
z_target = outputs["z_target"]
|
| 323 |
+
idm_out = outputs.get("idm")
|
| 324 |
+
|
| 325 |
+
if self.pred_loss == "l1":
|
| 326 |
+
l_pred = F.l1_loss(z_pred, z_target)
|
| 327 |
+
else:
|
| 328 |
+
l_pred = F.mse_loss(z_pred, z_target)
|
| 329 |
+
|
| 330 |
+
B, N, D = z_pred.shape
|
| 331 |
+
z_pred_flat = z_pred.reshape(B * N, D)
|
| 332 |
+
z_target_flat = z_target.reshape(B * N, D)
|
| 333 |
+
l_reg, l_sim, l_std, l_cov = sigreg_loss(
|
| 334 |
+
z_pred_flat, z_target_flat, sim_coeff=0.0, std_coeff=self.alpha, cov_coeff=self.beta
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
if z_pred.size(1) > 1:
|
| 338 |
+
z_diff = (z_pred[:, 1:] - z_pred[:, :-1]).pow(2).mean()
|
| 339 |
+
else:
|
| 340 |
+
z_diff = torch.tensor(0.0, device=z_pred.device)
|
| 341 |
+
l_temporal = self.delta * z_diff
|
| 342 |
+
|
| 343 |
+
l_idm = torch.tensor(0.0, device=z_pred.device)
|
| 344 |
+
if idm_out is not None and actions_gt is not None:
|
| 345 |
+
l_w = F.mse_loss(idm_out["weights"], actions_gt["weights"])
|
| 346 |
+
l_s = F.cross_entropy(idm_out["signals_logits"].reshape(-1, 3), actions_gt["signals"].reshape(-1))
|
| 347 |
+
l_idm = self.omega * (l_w + l_s)
|
| 348 |
+
|
| 349 |
+
l_rollout = torch.tensor(0.0, device=z_pred.device)
|
| 350 |
+
if rollout_outputs is not None and len(rollout_outputs) > 0:
|
| 351 |
+
for ro in rollout_outputs:
|
| 352 |
+
if self.pred_loss == "l1":
|
| 353 |
+
l_rollout += F.l1_loss(ro["z_pred"], ro["z_target"])
|
| 354 |
+
else:
|
| 355 |
+
l_rollout += F.mse_loss(ro["z_pred"], ro["z_target"])
|
| 356 |
+
l_rollout = self.gamma * (l_rollout / len(rollout_outputs))
|
| 357 |
+
|
| 358 |
+
total = l_pred + l_reg + l_temporal + l_idm + l_rollout
|
| 359 |
+
return {
|
| 360 |
+
"loss": total,
|
| 361 |
+
"loss_pred": l_pred.item(),
|
| 362 |
+
"loss_reg": l_reg.item(),
|
| 363 |
+
"loss_sim": l_sim.item(),
|
| 364 |
+
"loss_std": l_std.item(),
|
| 365 |
+
"loss_cov": l_cov.item(),
|
| 366 |
+
"loss_temporal": l_temporal.item(),
|
| 367 |
+
"loss_idm": l_idm.item() if isinstance(l_idm, torch.Tensor) else 0.0,
|
| 368 |
+
"loss_rollout": l_rollout.item() if isinstance(l_rollout, torch.Tensor) else 0.0,
|
| 369 |
+
}
|