Coverage for lab/losses.py: 100%

227 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""The ranking and multitask losses (moved unchanged from train.py in V6.7.1): soft Spearman, ListNet, IC, long-short 

2Sharpe, the class-balanced and cost-aware variants, the masked heads and the combined multitask loss. 

3`train.py` re-exports every name. 

4""" 

5 

6from __future__ import annotations 

7 

8from typing import Any 

9 

10import numpy as np 

11import pandas as pd 

12import torch 

13from torch import nn 

14 

15from lab.architectures import horizon_head_specs 

16from lab.objectives import CONTEXT_CLASSES, CONTEXT_OBJECTIVES, RANKING_OBJECTIVES # noqa: F401 (RANKING_OBJECTIVES re-exported for the trainers) 

17 

18# --------------------------------------------------------------------------- 

19# V5.1 Phase 3 (item 1) - cross-sectional ranking losses. Hand-written 

20# (n ~= 70 assets/date => O(n^2) ~= 5k pairwise ops per date, trivial) - 

21# deliberately NOT a compiled dependency like torchsort/fast-soft-sort in a 

22# repo whose live inference is a hand-written NumPy interpreter 

23# (inference/exported_model.py); these losses only ever run at TRAINING 

24# time (never exported/interpreted), so there is no interpreter-parity 

25# concern here, but a new compiled dependency for training alone still 

26# isn't worth it when the pure-torch version is this cheap. 

27# --------------------------------------------------------------------------- 

28 

29 

30def soft_rank_within_groups(scores: torch.Tensor, group_ids: torch.Tensor, temperature: float) -> torch.Tensor: 

31 """Differentiable rank approximation: for each group (date), soft_rank_i 

32 = sum_j sigmoid((s_i - s_j) / temperature), normalized to [0, 1] via 

33 (raw_rank - 0.5) / (n - 1) - the -0.5 removes the self-comparison term 

34 (sigmoid(0) == 0.5 exactly), matching pandas' .rank(pct=True) convention 

35 of assigning the smallest score percentile 0 and the largest 1 in the 

36 low-temperature limit. As temperature -> 0, sigmoid((s_i-s_j)/temperature) 

37 approaches the hard step function 1[s_i > s_j], so soft_rank_i approaches 

38 the TRUE rank exactly (see tests/test_train_ranking_loss.py's 

39 cross-validation against _rank_ic_from_arrays()). 

40 

41 A group of size 1 gets rank 0.5 (no information, the safe neutral 

42 midpoint - never divides by zero).""" 

43 soft_ranks = torch.zeros_like(scores) 

44 for group in torch.unique(group_ids): 

45 group_mask = group_ids == group 

46 group_scores = scores[group_mask] 

47 n = int(group_scores.shape[0]) 

48 if n <= 1: 

49 soft_ranks = soft_ranks.masked_scatter(group_mask, torch.full((n,), 0.5, device=scores.device)) 

50 continue 

51 pairwise = torch.sigmoid((group_scores.unsqueeze(1) - group_scores.unsqueeze(0)) / temperature) 

52 raw_rank = pairwise.sum(dim=1) 

53 normalized = (raw_rank - 0.5) / (n - 1) 

54 soft_ranks = soft_ranks.masked_scatter(group_mask, normalized) 

55 return soft_ranks 

56 

57 

58def soft_spearman_loss( 

59 predictions: torch.Tensor, 

60 targets: torch.Tensor, 

61 group_ids: torch.Tensor, 

62 mask: torch.Tensor, 

63 temperature: float, 

64 date_weights: torch.Tensor | None = None, 

65) -> torch.Tensor: 

66 """Per date, Pearson correlation between soft_rank(predictions) and 

67 targets (already a [0,1] percentile rank, a positive affine transform 

68 of the true rank - Pearson is invariant to that, the EXACT argument 

69 _rank_ic_from_arrays()'s own docstring makes for why ranking the 

70 prediction alone reproduces the true Spearman correlation). Loss = 

71 -mean(correlation) across dates, so minimizing it maximizes rank-IC. 

72 

73 Dates with fewer than 2 valid rows, or zero variance on either side 

74 (every asset tied - undefined correlation), are SKIPPED, not counted 

75 as a 0.0 correlation - same convention _rank_ic_from_arrays() uses for 

76 exactly the same reason (0.0 would misrepresent "undefined" as "no 

77 correlation", pulling the mean toward zero for no real reason). 

78 Returns a true zero (no gradient) when nothing is valid, matching 

79 masked_mse_loss()'s contract. 

80 

81 date_weights (V5.2.8, development/Problems.md #94): optional, one 

82 weight per ROW aligned to `group_ids` (NOT per-group directly - see 

83 compute_gate_friendliness_weight_by_date()'s caller for how this is 

84 built). Within each date, the group's mean weight scales that date's 

85 contribution to the final average - a date entirely populated by 

86 gate-friendly rows (weight ~1.0) contributes normally, a date the 

87 live gates would have mostly blocked contributes less. None (the 

88 default) reproduces today's exact uniform mean - BYTE-IDENTICAL, 

89 enforced by tests/test_train_ranking_loss.py's own parity test, not 

90 just assumed.""" 

91 valid = mask & ~torch.isnan(targets) 

92 if not torch.any(valid): 

93 return torch.zeros((), device=predictions.device) 

94 

95 valid_predictions = predictions[valid] 

96 valid_targets = targets[valid] 

97 valid_group_ids = group_ids[valid] 

98 valid_date_weights = date_weights[valid] if date_weights is not None else None 

99 soft_ranks = soft_rank_within_groups(valid_predictions, valid_group_ids, temperature) 

100 

101 correlations = [] 

102 weights = [] 

103 for group in torch.unique(valid_group_ids): 

104 group_mask = valid_group_ids == group 

105 group_rank = soft_ranks[group_mask] 

106 group_target = valid_targets[group_mask] 

107 if group_rank.shape[0] < 2: 

108 continue 

109 rank_variance = torch.var(group_rank, unbiased=False) 

110 target_variance = torch.var(group_target, unbiased=False) 

111 if rank_variance <= 1e-12 or target_variance <= 1e-12: 

112 continue 

113 rank_centered = group_rank - group_rank.mean() 

114 target_centered = group_target - group_target.mean() 

115 denominator = torch.sqrt((rank_centered**2).sum() * (target_centered**2).sum()) 

116 correlation = (rank_centered * target_centered).sum() / denominator 

117 correlations.append(correlation) 

118 weights.append(valid_date_weights[group_mask].mean() if valid_date_weights is not None else torch.ones((), device=predictions.device)) 

119 

120 if not correlations: 

121 return torch.zeros((), device=predictions.device) 

122 stacked_correlations = torch.stack(correlations) 

123 if date_weights is None: 

124 return -stacked_correlations.mean() 

125 stacked_weights = torch.stack(weights) 

126 return -(stacked_correlations * stacked_weights).sum() / stacked_weights.sum() 

127 

128 

129def listnet_loss( 

130 predictions: torch.Tensor, 

131 targets: torch.Tensor, 

132 group_ids: torch.Tensor, 

133 mask: torch.Tensor, 

134 temperature: float, 

135 date_weights: torch.Tensor | None = None, 

136) -> torch.Tensor: 

137 """Per date, cross-entropy H(softmax(targets/temperature), 

138 softmax(predictions/temperature)) - the standard ListNet objective 

139 (Cao et al. 2007), treating each date's cross-section as a probability 

140 distribution over "which asset is the top performer" rather than 

141 comparing pairwise ranks. Always >= 0 (cross-entropy of two 

142 distributions in [0,1] is non-negative by construction) and minimized 

143 when the two softmax distributions coincide, i.e. when predictions are 

144 a positive affine function of targets. Dates with fewer than 2 valid 

145 rows are skipped. Returns a true zero when nothing is valid. 

146 

147 date_weights: see soft_spearman_loss()'s own docstring - identical 

148 contract and None-default parity guarantee.""" 

149 valid = mask & ~torch.isnan(targets) 

150 if not torch.any(valid): 

151 return torch.zeros((), device=predictions.device) 

152 

153 valid_predictions = predictions[valid] 

154 valid_targets = targets[valid] 

155 valid_group_ids = group_ids[valid] 

156 valid_date_weights = date_weights[valid] if date_weights is not None else None 

157 

158 losses = [] 

159 weights = [] 

160 for group in torch.unique(valid_group_ids): 

161 group_mask = valid_group_ids == group 

162 group_predictions = valid_predictions[group_mask] 

163 group_targets = valid_targets[group_mask] 

164 if group_predictions.shape[0] < 2: 

165 continue 

166 prediction_log_softmax = torch.log_softmax(group_predictions / temperature, dim=0) 

167 target_softmax = torch.softmax(group_targets / temperature, dim=0) 

168 losses.append(-(target_softmax * prediction_log_softmax).sum()) 

169 weights.append(valid_date_weights[group_mask].mean() if valid_date_weights is not None else torch.ones((), device=predictions.device)) 

170 

171 if not losses: 

172 return torch.zeros((), device=predictions.device) 

173 stacked_losses = torch.stack(losses) 

174 if date_weights is None: 

175 return stacked_losses.mean() 

176 stacked_weights = torch.stack(weights) 

177 return (stacked_losses * stacked_weights).sum() / stacked_weights.sum() 

178 

179 

180 

181 

182def ic_pearson_loss( 

183 predictions: torch.Tensor, targets: torch.Tensor, group_ids: torch.Tensor, mask: torch.Tensor, date_weights: torch.Tensor | None = None, 

184) -> torch.Tensor: 

185 """R-LOSS1 L2: minus the mean over dates of the Pearson correlation of the raw prediction with the realised rank. Unlike 

186 soft_spearman_loss it never ranks the prediction, so a date's extreme predictions pull harder. Same skipping rules and date-weight 

187 contract as soft_spearman_loss.""" 

188 valid = mask & ~torch.isnan(targets) 

189 if not torch.any(valid): 

190 return torch.zeros((), device=predictions.device) 

191 correlations, weights = [], [] 

192 for group in torch.unique(group_ids[valid]): 

193 member = valid & (group_ids == group) 

194 prediction, target = predictions[member], targets[member] 

195 if prediction.shape[0] < 2 or torch.var(prediction, unbiased=False) <= 1e-12 or torch.var(target, unbiased=False) <= 1e-12: 

196 continue 

197 p, t = prediction - prediction.mean(), target - target.mean() 

198 correlations.append((p * t).sum() / torch.sqrt((p ** 2).sum() * (t ** 2).sum())) 

199 weights.append(date_weights[member].mean() if date_weights is not None else torch.ones((), device=predictions.device)) 

200 if not correlations: 

201 return torch.zeros((), device=predictions.device) 

202 stacked, stacked_weights = torch.stack(correlations), torch.stack(weights) 

203 return -(stacked * stacked_weights).sum() / stacked_weights.sum() 

204 

205 

206def long_short_sharpe_loss( 

207 predictions: torch.Tensor, returns: torch.Tensor, group_ids: torch.Tensor, mask: torch.Tensor, temperature: float = 0.1, 

208) -> torch.Tensor: 

209 """R-LOSS1 L3: minus a shrunk Sharpe, across a batch's dates, of a softmax long-short book on the realised forward return. 

210 

211 Per date, w = softmax(p / T) - softmax(-p / T) (long the top, short the bottom, net zero, gross 2) and the book's return r = w . ret, 

212 divided by that date's cross-sectional return dispersion so a volatile date does not dominate. Over the dates, loss = -mean(z) / 

213 sqrt(var(z) + 1): a Sharpe with a variance prior of one, so a batch of one date is minus its return and many dates approach the Sharpe. 

214 Dates with fewer than 2 valid rows or no dispersion are skipped.""" 

215 valid = mask & ~torch.isnan(returns) 

216 scores = [] 

217 for group in torch.unique(group_ids[valid]) if torch.any(valid) else (): 

218 member = valid & (group_ids == group) 

219 prediction, realised = predictions[member], returns[member] 

220 spread = torch.std(realised, unbiased=False) 

221 if prediction.shape[0] < 2 or spread <= 1e-12: 

222 continue 

223 weights = torch.softmax(prediction / temperature, dim=0) - torch.softmax(-prediction / temperature, dim=0) 

224 scores.append((weights * realised).sum() / spread) 

225 if not scores: 

226 return torch.zeros((), device=predictions.device) 

227 stacked = torch.stack(scores) 

228 return -stacked.mean() / torch.sqrt(torch.var(stacked, unbiased=False) + 1.0) 

229 

230 

231def row_context_targets(frame: pd.DataFrame, rows: np.ndarray) -> dict[str, torch.Tensor]: 

232 """The `_`-keyed row context an R-LOSS1 objective reads, for `frame`'s rows at `rows`: the asset class (index into CONTEXT_CLASSES from 

233 the `asset_class_<name>` one-hot context columns, len(CONTEXT_CLASSES) for anything else), a ticker id (consistent across the frame's 

234 splits) and the realised 5- and 20-day forward returns (NaN where the dataset lacks them).""" 

235 class_ids = np.full(len(frame), len(CONTEXT_CLASSES), dtype=np.float32) 

236 for index, name in enumerate(CONTEXT_CLASSES): 

237 column = f"asset_class_{name}" 

238 if column in frame.columns: 

239 class_ids[frame[column].to_numpy(dtype=np.float32) > 0.5] = index 

240 ticker_ids = pd.factorize(frame["ticker"])[0].astype(np.float32) 

241 context = {"_class_ids": class_ids[rows], "_ticker_ids": ticker_ids[rows]} 

242 for horizon in ("5d", "20d"): 

243 column = f"target_return_{horizon}" 

244 values = frame[column].to_numpy(dtype=np.float32) if column in frame.columns else np.full(len(frame), np.nan, dtype=np.float32) 

245 context[f"_return_{horizon}"] = values[rows] 

246 return {key: torch.from_numpy(np.ascontiguousarray(value)) for key, value in context.items()} 

247 

248 

249def class_group_ids(group_ids: torch.Tensor, class_ids: torch.Tensor) -> torch.Tensor: 

250 """One group per (date, asset class): a ranking within each class on each date, every class one group (R-LOSS1 L4).""" 

251 return group_ids.long() * (len(CONTEXT_CLASSES) + 1) + class_ids.long() 

252 

253 

254def rank_turnover_penalty(predictions: torch.Tensor, group_ids: torch.Tensor, ticker_ids: torch.Tensor, temperature: float) -> torch.Tensor: 

255 """R-LOSS1 L5's turnover term: the mean absolute change of a ticker's soft rank (within its date) between the consecutive dates of 

256 the batch it appears on. Zero when no ticker appears on two dates.""" 

257 ranks = soft_rank_within_groups(predictions, group_ids, temperature) 

258 changes = [] 

259 for ticker in torch.unique(ticker_ids): 

260 member = ticker_ids == ticker 

261 if int(member.sum()) < 2: 

262 continue 

263 order = torch.argsort(group_ids[member]) 

264 changes.append(torch.abs(torch.diff(ranks[member][order]))) 

265 if not changes: 

266 return torch.zeros((), device=predictions.device) 

267 return torch.cat(changes).mean() 

268 

269 

270def compute_cross_sectional_ranking_loss( 

271 head_output: torch.Tensor, 

272 head_target: torch.Tensor, 

273 group_ids: torch.Tensor, 

274 ranking_loss_config: dict[str, Any], 

275 date_weights: torch.Tensor | None = None, 

276 context: dict[str, torch.Tensor] | None = None, 

277) -> torch.Tensor: 

278 """Dispatcher on ranking_loss_config["objective"] in 

279 {"mse", "soft_spearman", "listnet"} (default "mse", reproducing 

280 masked_mse_loss() exactly - the byte-identical no-op path 

281 compute_combined_multitask_loss() falls back to when Phase 3's config 

282 is absent). For the two real ranking objectives, adds 

283 ranking_loss_config["mse_anchor_weight"] * masked_mse_loss() on top: a 

284 pure ranking loss is invariant to any affine rescaling of the head's 

285 raw output, so without this anchor term the output SCALE drifts 

286 unboundedly during training - harmless for ranking (only order 

287 matters) but it would make the exported head numerically unstable and 

288 would defeat the "raw" (non-normalized) diagnostic reading of the 

289 score. Defaults (temperature=0.05, listnet_temperature=0.1, 

290 mse_anchor_weight=0.1) live in config.json, not here - this function 

291 always reads them from ranking_loss_config, never hardcodes a 

292 fallback, so a caller can never silently diverge from what got 

293 logged/trained with. 

294 

295 date_weights (V5.2.8, development/Problems.md #94): passed straight 

296 through to soft_spearman_loss()/listnet_loss() - see their own 

297 docstrings. Never applied to the mse_anchor_weight term (that term 

298 exists purely to anchor output SCALE, not to express the ranking 

299 objective itself - weighting it the same way would fight its own 

300 purpose). None (the default) is a strict no-op, same as those two 

301 functions' own contract.""" 

302 mask = ~torch.isnan(head_target) 

303 objective = str(ranking_loss_config.get("objective", "mse")) 

304 if objective == "mse": 

305 return masked_mse_loss(head_output, head_target, mask) 

306 

307 temperature = float(ranking_loss_config.get("temperature", 0.05)) 

308 mse_anchor_weight = float(ranking_loss_config.get("mse_anchor_weight", 0.0)) 

309 if objective == "soft_spearman": 

310 ranking_loss = soft_spearman_loss(head_output, head_target, group_ids, mask, temperature, date_weights) 

311 elif objective == "listnet": 

312 listnet_temperature = float(ranking_loss_config.get("listnet_temperature", temperature)) 

313 ranking_loss = listnet_loss(head_output, head_target, group_ids, mask, listnet_temperature, date_weights) 

314 elif objective == "ic_pearson": 

315 ranking_loss = ic_pearson_loss(head_output, head_target, group_ids, mask, date_weights) 

316 elif objective in CONTEXT_OBJECTIVES: 

317 # V6.6.10 (R-LOSS1): these read per-row context the trainer adds to the batch (`_class_ids`, `_ticker_ids`, the head's returns) 

318 missing = [key for key in ("class_ids", "ticker_ids", "returns") if context is None or context.get(key) is None] 

319 if missing: 

320 raise ValueError(f"compute_cross_sectional_ranking_loss: objective {objective!r} needs row context {missing}") 

321 if objective == "ls_sharpe": 

322 ranking_loss = long_short_sharpe_loss(head_output, context["returns"], group_ids, mask, float(ranking_loss_config.get("ls_temperature", 0.1))) 

323 else: 

324 within = class_group_ids(group_ids, context["class_ids"]) 

325 ranking_loss = soft_spearman_loss(head_output, head_target, within, mask, temperature, date_weights) 

326 if objective == "cost_aware": 

327 penalty = float(ranking_loss_config.get("turnover_penalty", 0.1)) 

328 ranking_loss = ranking_loss + penalty * rank_turnover_penalty(head_output, group_ids, context["ticker_ids"], temperature) 

329 else: 

330 raise ValueError(f"compute_cross_sectional_ranking_loss: unknown objective {objective!r}") 

331 

332 anchor_loss = masked_mse_loss(head_output, head_target, mask) if mse_anchor_weight else torch.zeros((), device=head_output.device) 

333 return ranking_loss + mse_anchor_weight * anchor_loss 

334 

335 

336def masked_bce_with_logits_loss(logits: torch.Tensor, targets: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: 

337 """Binary cross-entropy over only the rows where `mask` is True - used 

338 for the horizon-direction heads (direction_5d/20d), whose targets are 

339 NaN for the trailing few rows of each asset's history that don't yet 

340 have a full 5/20-day-forward close, rather than dropped from the 

341 dataset entirely (see engineer_features()'s docstring on why - dropping 

342 would also shrink every per-expert dataset slice downstream). Returns 

343 a true zero (no gradient contribution) rather than NaN/erroring when no 

344 row in this batch has a valid target for this head.""" 

345 if not torch.any(mask): 

346 return torch.zeros((), device=logits.device) 

347 return nn.functional.binary_cross_entropy_with_logits(logits[mask], targets[mask]) 

348 

349 

350def masked_mse_loss(predictions: torch.Tensor, targets: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: 

351 """Same masking convention as masked_bce_with_logits_loss() above, for 

352 regression targets - used by the cross-sectional rank_5d/20d heads 

353 (masked MSE against each row's percentile-rank target).""" 

354 if not torch.any(mask): 

355 return torch.zeros((), device=predictions.device) 

356 return nn.functional.mse_loss(predictions[mask], targets[mask]) 

357 

358 

359def add_rank_label_noise( 

360 batch_targets: dict[str, Any], head_specs: dict[str, Any], noise_std: float, generator: torch.Generator | None 

361) -> dict[str, Any]: 

362 """V6.2.0 regulariser: Gaussian noise of `noise_std` x the batch's own target std on every "rank"-kind head's 

363 targets, clipped to the batch's observed range so a percentile target stays a percentile. NaN (masked) targets 

364 stay NaN and binary / regression heads are untouched. `noise_std <= 0` returns the input dict itself, so a run 

365 without the knob is bit-identical.""" 

366 if noise_std <= 0.0: 

367 return batch_targets 

368 noisy = dict(batch_targets) 

369 for name, (_column, kind, _stride) in head_specs.items(): 

370 target = batch_targets.get(name) 

371 if kind != "rank" or target is None: 

372 continue 

373 finite = torch.isfinite(target) 

374 if int(finite.sum()) < 2: 

375 continue 

376 values = target[finite] 

377 noise = torch.randn(target.shape, generator=generator, dtype=target.dtype) * (float(values.std()) * noise_std) 

378 noisy[name] = torch.where(finite, (target + noise).clamp(float(values.min()), float(values.max())), target) 

379 return noisy 

380 

381 

382def _pairwise_consistency_penalty(values_a: torch.Tensor, values_b: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: 

383 """Core of compute_horizon_consistency_loss() below - shared between the 

384 rank pair (rank_5d/rank_20d, already ~[0,1]-scaled by their own MSE 

385 objective) and the direction pair (direction_5d/direction_20d, sigmoid- 

386 applied first by the caller so they're on the same [0,1] scale). Both 

387 `values_a`/`values_b` are expected centered around 0.5 = "no opinion" - 

388 `-(a-0.5)*(b-0.5)` is negative (relu zeroes it - no penalty) whenever 

389 both sit on the SAME side of 0.5 (both bullish-of-median or both 

390 bearish-of-median), and positive (penalized) whenever they disagree. 

391 Returns a true zero (no gradient contribution) when the mask is empty, 

392 matching masked_bce_with_logits_loss()/masked_mse_loss()'s convention.""" 

393 if not torch.any(mask): 

394 return torch.zeros((), device=values_a.device) 

395 a_centered = values_a[mask] - 0.5 

396 b_centered = values_b[mask] - 0.5 

397 return nn.functional.relu(-(a_centered * b_centered)).mean() 

398 

399 

400def compute_horizon_consistency_loss(outputs: dict[str, torch.Tensor], targets: dict[str, torch.Tensor]) -> torch.Tensor: 

401 """Stage 4 of the rank-pivot roadmap (development/Problems.md#43): an 

402 explicit regularizer penalizing the model for predicting the 5-day and 

403 20-day views of the SAME underlying signal on opposite sides of the 

404 cross-section/direction, rather than letting each head overfit its own 

405 horizon independently with no coherence constraint between them - the 

406 piece previously missing from Stage 4's regularization (rank-IC-based 

407 early stopping and seed-ensembling address the *epoch*/*seed* axes of 

408 overfitting; this addresses the *cross-head* axis). 

409 

410 Two pairs, both using _pairwise_consistency_penalty() with the exact 

411 masking convention every other head loss already uses (only rows where 

412 BOTH targets in the pair are non-NaN contribute - trailing rows missing 

413 one horizon's forward window make "do these two heads agree" 

414 ill-posed, not just unsupervised): 

415 - rank_5d vs rank_20d: used directly (both already ~[0,1]-scaled by 

416 their own masked-MSE objective against a [0,1] percentile-rank 

417 target - no extra activation needed or wanted, since applying one 

418 would put this term on a different scale than the MSE loss actually 

419 training these heads). 

420 - direction_5d vs direction_20d: sigmoid-applied first, since these are 

421 raw BCEWithLogits logits (unbounded) - sigmoid(logit) has the same 

422 SIGN-relative-to-0.5 as the logit relative to 0, but keeps the 

423 product term boundedly scaled instead of letting large logit 

424 magnitudes dominate/destabilize the combined loss. 

425 

426 Callers gate each pair on whether BOTH heads in it are actually enabled 

427 (horizon_head_config) - penalizing agreement between a disabled head's 

428 meaningless output and an enabled one's is not well-defined.""" 

429 rank_mask = ~torch.isnan(targets["rank_5d"]) & ~torch.isnan(targets["rank_20d"]) 

430 rank_penalty = _pairwise_consistency_penalty(outputs["rank_5d"], outputs["rank_20d"], rank_mask) 

431 

432 direction_mask = ~torch.isnan(targets["direction_5d"]) & ~torch.isnan(targets["direction_20d"]) 

433 direction_penalty = _pairwise_consistency_penalty( 

434 torch.sigmoid(outputs["direction_5d"]), torch.sigmoid(outputs["direction_20d"]), direction_mask 

435 ) 

436 return rank_penalty + direction_penalty 

437 

438 

439def compute_combined_multitask_loss( 

440 outputs: dict[str, torch.Tensor], 

441 targets: dict[str, torch.Tensor], 

442 direction_criterion: nn.Module, 

443 magnitude_loss_weight: float, 

444 volatility_loss_weight: float, 

445 horizon_head_config: dict[str, Any], 

446 direction_loss_weight: float = 1.0, 

447 consistency_loss_weight: float = 0.0, 

448 date_group_ids: torch.Tensor | None = None, 

449 ranking_loss_config: dict[str, Any] | None = None, 

450 date_weights: torch.Tensor | None = None, 

451) -> torch.Tensor: 

452 """Combined loss for both AetherNetMultiTaskHorizons and 

453 AetherNetSequenceMultiTaskHorizons (identical head-name dict shape, 

454 see each class's forward()) - BCEWithLogitsLoss(direction) + weighted 

455 MSE(magnitude)/MSE(volatility) + a masked BCE/MSE term per enabled 

456 horizon head (masked since direction_5d/20d/rank_5d/20d are NaN for 

457 the trailing few rows of an asset's history that lack a full forward 

458 window, see engineer_features()'s docstring). 

459 

460 direction_loss_weight (Stage 4 of the rank-pivot roadmap, 

461 development/Problems.md#43): the primary 1-day "direction" head is a 

462 near-noise objective (backtest MCC ~0.02-0.04, and the sequence model's 

463 own copy of it collapsed to a constant during training - positive_rate 

464 0.0002) whose output main.py never even reads (only magnitude/ 

465 volatility/rank_5d/rank_20d feed the trading decision) - it exists only 

466 as an artifact of this model's original single-task ancestor. Its loss 

467 was previously hardcoded at weight 1.0, forcing the shared trunk to keep 

468 fitting a target with no signal and no downstream consumer. Defaults to 

469 1.0 (fully backward-compatible - existing positional callers/tests are 

470 unaffected); config.json sets this low (not 0.0, so the head stays a 

471 harmless diagnostic rather than a dead weight-less no-op) for the 

472 multitask/sequence trainers specifically. 

473 

474 consistency_loss_weight (Stage 4, same roadmap entry): scales 

475 compute_horizon_consistency_loss() above - see its own docstring. 

476 Defaults to 0.0 (fully backward-compatible - a zero-weighted term adds 

477 zero gradient contribution, so every existing positional caller/test is 

478 completely unaffected); only added when BOTH heads of a pair are 

479 enabled (horizon_head_config), matching this function's existing 

480 per-head enabled-gating convention immediately below. 

481 

482 date_group_ids/ranking_loss_config (V5.1 Phase 3, item 1): when BOTH 

483 are provided, every enabled "rank"-kind head (HORIZON_HEAD_SPECS - 

484 rank_5d/20d, sector_neutral_rank_20d, residual_rank_5d/20d, 

485 beta_neutral_rank_20d, generically, no per-head special-casing) routes 

486 through compute_cross_sectional_ranking_loss() instead of a bare 

487 masked_mse_loss() call. GUARDRAIL: when either is None (the default), 

488 this is BYTE-IDENTICAL to the pre-Phase-3 code path - every existing 

489 positional caller/test is completely unaffected. 

490 

491 date_weights (V5.2.8, development/Problems.md #94): optional, passed 

492 straight through to compute_cross_sectional_ranking_loss() whenever 

493 the ranking-loss path is active - built by 

494 compute_gate_friendliness_weight_by_date() and looked up per-row via 

495 date_group_ids by the caller (train_multitask.py/train_sequence.py), 

496 config-gated off by default 

497 (phase_v2.training.gate_aware_ranking_weights.enabled). None is a 

498 strict no-op - has no effect at all unless use_ranking_loss is also 

499 True, matching date_group_ids/ranking_loss_config's own contract.""" 

500 loss = ( 

501 direction_loss_weight * direction_criterion(outputs["direction"], targets["direction"]) 

502 + magnitude_loss_weight * nn.functional.mse_loss(outputs["magnitude"], targets["magnitude"]) 

503 + volatility_loss_weight * nn.functional.mse_loss(outputs["volatility"], targets["volatility"]) 

504 ) 

505 use_ranking_loss = date_group_ids is not None and ranking_loss_config is not None 

506 for head_name, (_column, kind, _stride) in horizon_head_specs(horizon_head_config).items(): 

507 head_config = horizon_head_config[head_name] 

508 if not head_config.get("enabled", True): 

509 continue 

510 mask = ~torch.isnan(targets[head_name]) 

511 if kind == "binary": 

512 head_loss = masked_bce_with_logits_loss(outputs[head_name], targets[head_name], mask) 

513 elif use_ranking_loss: 

514 # V6.6.10: the row context a trainer added under `_`-keys (absent for every objective that needs none) 

515 context = { 

516 "class_ids": targets.get("_class_ids"), "ticker_ids": targets.get("_ticker_ids"), 

517 "returns": targets.get("_return_5d" if "5d" in head_name else "_return_20d"), 

518 } 

519 head_loss = compute_cross_sectional_ranking_loss( 

520 outputs[head_name], targets[head_name], date_group_ids, ranking_loss_config, date_weights, context 

521 ) 

522 else: 

523 head_loss = masked_mse_loss(outputs[head_name], targets[head_name], mask) 

524 loss = loss + float(head_config.get("loss_weight", 1.0)) * head_loss 

525 

526 if consistency_loss_weight: 

527 rank_pair_enabled = horizon_head_config["rank_5d"].get("enabled", True) and horizon_head_config["rank_20d"].get( 

528 "enabled", True 

529 ) 

530 direction_pair_enabled = horizon_head_config["direction_5d"].get( 

531 "enabled", True 

532 ) and horizon_head_config["direction_20d"].get("enabled", True) 

533 if rank_pair_enabled or direction_pair_enabled: 

534 consistency_targets = { 

535 "rank_5d": targets["rank_5d"] if rank_pair_enabled else torch.full_like(targets["rank_5d"], float("nan")), 

536 "rank_20d": targets["rank_20d"] if rank_pair_enabled else torch.full_like(targets["rank_20d"], float("nan")), 

537 "direction_5d": targets["direction_5d"] 

538 if direction_pair_enabled 

539 else torch.full_like(targets["direction_5d"], float("nan")), 

540 "direction_20d": targets["direction_20d"] 

541 if direction_pair_enabled 

542 else torch.full_like(targets["direction_20d"], float("nan")), 

543 } 

544 loss = loss + consistency_loss_weight * compute_horizon_consistency_loss(outputs, consistency_targets) 

545 return loss