xtft 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. xtft/__init__.py +80 -0
  2. xtft/_configs.py +220 -0
  3. xtft/_deps.py +145 -0
  4. xtft/_dummies.py +119 -0
  5. xtft/_log.py +137 -0
  6. xtft/_log.yml +59 -0
  7. xtft/_optdeps.py +162 -0
  8. xtft/_util.py +44 -0
  9. xtft/api/bunch.py +721 -0
  10. xtft/api/docs.py +2690 -0
  11. xtft/api/property.py +2256 -0
  12. xtft/api/summary.py +180 -0
  13. xtft/api/types.py +256 -0
  14. xtft/api/util.py +5175 -0
  15. xtft/backends/__init__.py +31 -0
  16. xtft/backends/_framework.py +263 -0
  17. xtft/backends/array/base.py +138 -0
  18. xtft/backends/array/cupy.py +303 -0
  19. xtft/backends/array/dask.py +466 -0
  20. xtft/backends/array/devices.py +360 -0
  21. xtft/backends/array/nn.py +1270 -0
  22. xtft/backends/array/numpy.py +261 -0
  23. xtft/backends/array/scipy.py +245 -0
  24. xtft/backends/array/selector.py +1017 -0
  25. xtft/compat/__init__.py +41 -0
  26. xtft/compat/_config.py +199 -0
  27. xtft/compat/keras.py +925 -0
  28. xtft/compat/keras_fit.py +475 -0
  29. xtft/compat/kt.py +125 -0
  30. xtft/compat/numpy.py +98 -0
  31. xtft/compat/pandas.py +660 -0
  32. xtft/compat/scipy.py +393 -0
  33. xtft/compat/sklearn.py +1150 -0
  34. xtft/compat/tf.py +1182 -0
  35. xtft/compat/torch.py +99 -0
  36. xtft/compat/types.py +85 -0
  37. xtft/core/array_manager.py +4649 -0
  38. xtft/core/checks.py +7479 -0
  39. xtft/core/diagnose_q.py +2237 -0
  40. xtft/core/handlers.py +2685 -0
  41. xtft/core/io.py +2705 -0
  42. xtft/core/utils.py +3128 -0
  43. xtft/data/__init__.py +19 -0
  44. xtft/data/panel.py +549 -0
  45. xtft/data/seasonality.py +203 -0
  46. xtft/decorators.py +5154 -0
  47. xtft/evaluation/__init__.py +57 -0
  48. xtft/evaluation/bands.py +489 -0
  49. xtft/evaluation/conformal.py +637 -0
  50. xtft/evaluation/metrics.py +559 -0
  51. xtft/evaluation/stats.py +326 -0
  52. xtft/exceptions.py +336 -0
  53. xtft/metrics/__init__.py +32 -0
  54. xtft/metrics/_cas.py +470 -0
  55. xtft/metrics/_metrics.py +3500 -0
  56. xtft/metrics/_registry.py +217 -0
  57. xtft/nn/__init__.py +124 -0
  58. xtft/nn/tf/__init__.py +60 -0
  59. xtft/nn/tf/_shapes.py +1124 -0
  60. xtft/nn/tf/_tensor_validation.py +3845 -0
  61. xtft/nn/tf/_utils.py +7549 -0
  62. xtft/nn/tf/anomaly_detection.py +1065 -0
  63. xtft/nn/tf/calibration.py +312 -0
  64. xtft/nn/tf/callbacks.py +1317 -0
  65. xtft/nn/tf/components/__init__.py +154 -0
  66. xtft/nn/tf/components/_attention_utils.py +160 -0
  67. xtft/nn/tf/components/_config.py +207 -0
  68. xtft/nn/tf/components/_loss_utils.py +215 -0
  69. xtft/nn/tf/components/_temporal_utils.py +469 -0
  70. xtft/nn/tf/components/attention.py +1195 -0
  71. xtft/nn/tf/components/encoder_decoder.py +616 -0
  72. xtft/nn/tf/components/gating_norm.py +1081 -0
  73. xtft/nn/tf/components/heads.py +694 -0
  74. xtft/nn/tf/components/layer_utils.py +360 -0
  75. xtft/nn/tf/components/losses.py +940 -0
  76. xtft/nn/tf/components/masks.py +130 -0
  77. xtft/nn/tf/components/misc.py +1066 -0
  78. xtft/nn/tf/components/temporal.py +357 -0
  79. xtft/nn/tf/components/utils.py +243 -0
  80. xtft/nn/tf/custom_metrics.py +211 -0
  81. xtft/nn/tf/hybrid/__init__.py +11 -0
  82. xtft/nn/tf/hybrid/_base_extreme.py +636 -0
  83. xtft/nn/tf/hybrid/_super_xtft.py +677 -0
  84. xtft/nn/tf/hybrid/_xtft.py +607 -0
  85. xtft/nn/tf/hybrid/utils.py +852 -0
  86. xtft/nn/tf/keras_metrics.py +1313 -0
  87. xtft/nn/tf/keras_validator.py +643 -0
  88. xtft/nn/tf/losses.py +1139 -0
  89. xtft/nn/tf/transformers/__init__.py +10 -0
  90. xtft/nn/tf/transformers/_adj_tft.py +777 -0
  91. xtft/nn/tf/transformers/_tft.py +1060 -0
  92. xtft/nn/torch/__init__.py +16 -0
  93. xtft/nn/torch/layers/__init__.py +24 -0
  94. xtft/nn/torch/layers/attention.py +332 -0
  95. xtft/nn/torch/layers/grn.py +215 -0
  96. xtft/nn/torch/layers/missing.py +226 -0
  97. xtft/nn/torch/layers/multiresolution.py +348 -0
  98. xtft/nn/torch/layers/variable_selection.py +193 -0
  99. xtft/nn/torch/models/__init__.py +5 -0
  100. xtft/nn/torch/models/xtft.py +638 -0
  101. xtft/nn/torch/probabilistic/__init__.py +11 -0
  102. xtft/nn/torch/probabilistic/losses.py +139 -0
  103. xtft/nn/torch/probabilistic/quantile_head.py +154 -0
  104. xtft/nn/torch/trainer.py +357 -0
  105. xtft/utils/_array_api.py +183 -0
  106. xtft/utils/_dependency.py +187 -0
  107. xtft/utils/base_utils.py +1532 -0
  108. xtft/utils/calibrate.py +950 -0
  109. xtft/utils/data_utils.py +1278 -0
  110. xtft/utils/deps_utils.py +1401 -0
  111. xtft/utils/forecast_utils.py +4507 -0
  112. xtft/utils/generic_utils.py +4018 -0
  113. xtft/utils/io_utils.py +3465 -0
  114. xtft/utils/sequence_utils.py +1701 -0
  115. xtft/utils/shapes.py +1183 -0
  116. xtft/utils/sys_utils.py +3161 -0
  117. xtft/utils/ts_utils.py +4975 -0
  118. xtft/utils/validator.py +7647 -0
  119. xtft/utils/version.py +581 -0
  120. xtft-0.1.0.dist-info/METADATA +310 -0
  121. xtft-0.1.0.dist-info/RECORD +124 -0
  122. xtft-0.1.0.dist-info/WHEEL +5 -0
  123. xtft-0.1.0.dist-info/licenses/LICENSE +28 -0
  124. xtft-0.1.0.dist-info/top_level.txt +1 -0
xtft/nn/tf/_shapes.py ADDED
@@ -0,0 +1,1124 @@
1
+ ## -*- coding: utf-8 -*-
2
+ # License: BSD-3-Clause
3
+ # Author : LKouadio <etanoyau@gmail.com>
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any, Callable, Dict, Optional, Sequence, Tuple
8
+ import numpy as np
9
+
10
+ from xtft.nn.tf import KERAS_DEPS, dependency_message
11
+
12
+ # ---------------------------------------------------------------------
13
+ # Dev note:
14
+ # This module provides **shape-safe** helpers used by metrics/losses.
15
+ # Goal: avoid silent broadcasting bugs (esp. Keras 3 multi-output)
16
+ # when targets/preds carry quantile axes or accidental tiling.
17
+ # ---------------------------------------------------------------------
18
+
19
+ Tensor = KERAS_DEPS.Tensor
20
+
21
+ tf_float32 = KERAS_DEPS.float32
22
+ tf_convert_to_tensor = KERAS_DEPS.convert_to_tensor
23
+ tf_expand_dims = KERAS_DEPS.expand_dims
24
+ tf_squeeze = KERAS_DEPS.squeeze
25
+ tf_shape = KERAS_DEPS.shape
26
+ tf_cast = KERAS_DEPS.cast
27
+ tf_reduce_sum = KERAS_DEPS.reduce_sum
28
+ tf_size = KERAS_DEPS.size
29
+ tf_reshape = KERAS_DEPS.reshape
30
+ tf_broadcast_to = KERAS_DEPS.broadcast_to
31
+ tf_gather = KERAS_DEPS.gather
32
+ tf_where = KERAS_DEPS.where
33
+ tf_equal = KERAS_DEPS.equal
34
+ tf_executing_eagerly =KERAS_DEPS.executing_eagerly
35
+ tf_rank = KERAS_DEPS.rank
36
+ tf_cond = KERAS_DEPS.cond
37
+ tf_sort = KERAS_DEPS.sort
38
+ tf_reduce_mean = KERAS_DEPS.reduce_mean
39
+ tf_transpose =KERAS_DEPS.transpose
40
+ tf_abs = KERAS_DEPS.abs
41
+
42
+ DEP_MSG = dependency_message("nn._shapes")
43
+
44
+
45
+ def _infer_quantile_axis(t: Tensor, n_q: int = 3):
46
+ """Infer quantile axis (static, conservative)."""
47
+ shape = getattr(t, "shape", None)
48
+ rank = getattr(shape, "rank", None)
49
+
50
+ if rank is None:
51
+ return None
52
+
53
+ # Canonical: (B,H,Q,O) => axis=2
54
+ if rank == 4:
55
+ d2 = shape[2]
56
+ d3 = shape[3]
57
+
58
+ if d2 == n_q:
59
+ return 2
60
+
61
+ # Alternate: (B,H,O,Q) => axis=3
62
+ if d3 == n_q:
63
+ return 3
64
+
65
+ return None
66
+
67
+ # Rank-3: only accept (B,H,Q) on last axis
68
+ if rank == 3:
69
+ return 2 if shape[2] == n_q else None
70
+
71
+ return None
72
+
73
+
74
+ def _as_BHO(y_true: Tensor, y_pred: Tensor | None = None):
75
+ """Normalize y_true to (B,H,O) float32."""
76
+ y = tf_convert_to_tensor(y_true)
77
+
78
+ # (B,H) -> (B,H,1)
79
+ if y.shape.rank == 2:
80
+ y = tf_expand_dims(y, axis=-1)
81
+
82
+ # (B,H,O,1) -> (B,H,O)
83
+ if (y.shape.rank == 4) and (y.shape[-1] == 1):
84
+ y = tf_squeeze(y, axis=-1)
85
+
86
+ # If targets got tiled to (B,H,Q,O), drop Q.
87
+ if (y.shape.rank == 4) and (y_pred is not None):
88
+ yp_shape = getattr(y_pred, "shape", None)
89
+ yp_rank = getattr(yp_shape, "rank", None)
90
+
91
+ # Dev note: in this codebase rank-4 preds mean (B,H,Q,O)
92
+ # so any rank-4 y_true is suspicious and should be untiled.
93
+ if yp_rank == 4:
94
+ y = y[:, :, 0, :]
95
+
96
+ return tf_cast(y, tf_float32)
97
+
98
+ def _as_BHQO(y_pred: Any, n_q: int = 3) -> Any:
99
+ """
100
+ Canonicalize predictions to (B, H, Q, O) for debug.
101
+
102
+ Supports:
103
+ (B,H,Q,O), (B,Q,H,O), (B,H,O,Q)
104
+ (B,H,Q), (B,Q,H)
105
+ """
106
+ y = tf_convert_to_tensor(y_pred)
107
+ r = int(y.shape.rank or 0)
108
+
109
+ if r == 4:
110
+ if y.shape[2] == n_q:
111
+ return y
112
+ if y.shape[1] == n_q: # (B,Q,H,O)
113
+ return tf_transpose(y, (0, 2, 1, 3))
114
+ if y.shape[3] == n_q: # (B,H,O,Q)
115
+ return tf_transpose(y, (0, 1, 3, 2))
116
+ return y
117
+
118
+ if r == 3:
119
+ if y.shape[2] == n_q: # (B,H,Q)
120
+ return tf_expand_dims(y, axis=-1)
121
+ if y.shape[1] == n_q: # (B,Q,H)
122
+ y = tf_transpose(y, (0, 2, 1))
123
+ return tf_expand_dims(y, axis=-1)
124
+ return tf_expand_dims(y, axis=-1)
125
+
126
+ return y
127
+
128
+ def _as_BHO_like_pred(x: Tensor, dtype=tf_float32):
129
+ """Normalize (B,H,*) to (B,H,1)/(B,H,O)."""
130
+ t = tf_convert_to_tensor(x)
131
+
132
+ # (B,H) -> (B,H,1)
133
+ if t.shape.rank == 2:
134
+ t = tf_expand_dims(t, axis=-1)
135
+
136
+ return tf_cast(t, dtype)
137
+
138
+
139
+ def _weighted_sum_and_count(
140
+ values: Tensor,
141
+ sample_weight: Tensor | None = None,
142
+ ):
143
+ """Return (sum, count) as float32."""
144
+ v = tf_cast(values, tf_float32)
145
+
146
+ # Unweighted: count is number of elements.
147
+ if sample_weight is None:
148
+ s = tf_reduce_sum(v)
149
+ c = tf_cast(tf_size(v), tf_float32)
150
+ return s, c
151
+
152
+ w = tf_cast(sample_weight, tf_float32)
153
+
154
+ # Make weights broadcastable to v.
155
+ # Common: (B,), (B,H), (B,H,1), (B,H,O)
156
+ if (
157
+ (w.shape.rank == 1)
158
+ and (v.shape.rank is not None)
159
+ and (v.shape.rank >= 2)
160
+ ):
161
+ w = tf_reshape(w, [-1, 1, 1])
162
+
163
+ elif (
164
+ (w.shape.rank == 2)
165
+ and (v.shape.rank is not None)
166
+ and (v.shape.rank >= 3)
167
+ ):
168
+ w = tf_expand_dims(w, axis=-1)
169
+
170
+ w = tf_broadcast_to(w, tf_shape(v))
171
+
172
+ s = tf_reduce_sum(v * w)
173
+ c = tf_reduce_sum(w)
174
+
175
+ return s, c
176
+
177
+
178
+ def _q50_as_BHO(
179
+ y_pred: Tensor,
180
+ q_axis: int = 2,
181
+ q_index: int = 1,
182
+ ):
183
+ """Extract q50 forecast as (B,H,O)/(B,H,1)."""
184
+ yp = tf_convert_to_tensor(y_pred)
185
+ r = yp.shape.rank
186
+
187
+ # Rank-4: (B,H,Q,O)
188
+ if r == 4:
189
+ # Quantiles: pick q_index along q_axis.
190
+ if yp.shape[q_axis] == 3:
191
+ out = tf_gather(yp, q_index, axis=q_axis)
192
+ return tf_cast(out, tf_float32)
193
+
194
+ # Packed interval: (...,2) -> midpoint.
195
+ if yp.shape[-1] == 2:
196
+ mid = 0.5 * (yp[..., 0] + yp[..., 1])
197
+ return tf_cast(mid, tf_float32)
198
+
199
+ # Trailing singleton: (B,H,O,1) -> (B,H,O)
200
+ if yp.shape[-1] == 1:
201
+ out = tf_squeeze(yp, axis=-1)
202
+ return tf_cast(out, tf_float32)
203
+
204
+ # Last-resort: take first "O" slice.
205
+ return tf_cast(yp[:, :, :, 0], tf_float32)
206
+
207
+ # Rank-3: (B,H,Q) or (B,H,O)
208
+ if r == 3:
209
+ # (B,H,Q) -> pick q_index -> (B,H,1)
210
+ if yp.shape[-1] == 3:
211
+ out = tf_gather(yp, q_index, axis=-1)
212
+ out = tf_expand_dims(out, axis=-1)
213
+ return tf_cast(out, tf_float32)
214
+
215
+ # Already (B,H,O)
216
+ return tf_cast(yp, tf_float32)
217
+
218
+ # Rank-2: (B,H) -> (B,H,1)
219
+ if r == 2:
220
+ out = tf_expand_dims(yp, axis=-1)
221
+ return tf_cast(out, tf_float32)
222
+
223
+ return tf_cast(yp, tf_float32)
224
+
225
+
226
+ def _interval80_as_BHO(y_pred: Tensor, q_axis: int = 2):
227
+ """Return (lo, hi) broadcastable to (B,H,O)."""
228
+ yp = tf_convert_to_tensor(y_pred)
229
+ qax = _infer_quantile_axis(yp, n_q=3)
230
+
231
+ # Quantiles: pick q10 and q90.
232
+ if qax is not None:
233
+ lo = tf_gather(yp, 0, axis=qax)
234
+ hi = tf_gather(yp, -1, axis=qax)
235
+ return (
236
+ tf_cast(lo, tf_float32),
237
+ tf_cast(hi, tf_float32),
238
+ )
239
+
240
+ # Packed interval: (...,2) == (lo,hi)
241
+ if (yp.shape.rank is not None) and (yp.shape[-1] == 2):
242
+ lo = yp[..., 0]
243
+ hi = yp[..., 1]
244
+ return (
245
+ tf_cast(lo, tf_float32),
246
+ tf_cast(hi, tf_float32),
247
+ )
248
+
249
+ # Fallback: treat point forecast as (lo==hi).
250
+ p = _q50_as_BHO(yp, q_axis=q_axis)
251
+ return tf_cast(p, tf_float32), tf_cast(p, tf_float32)
252
+
253
+ def infer_quantile_axis(t, n_q=3):
254
+ """
255
+ Infer which axis holds quantiles of length n_q (typically 3: q10,q50,q90).
256
+
257
+ Returns
258
+ -------
259
+ int | None
260
+ Axis index of the quantile dimension, or None if not found / packed.
261
+ """
262
+ shape = getattr(t, "shape", None)
263
+ if shape is None:
264
+ return None
265
+
266
+ rank = shape.rank
267
+ if rank is None:
268
+ # Can't safely infer in graph if rank unknown; treat as "no quantile axis".
269
+ return None
270
+
271
+ # ---- 1) Packed interval guard: (...,2) means (lo,hi) not quantiles ----
272
+ # Covers (B,H,2), (B,H,O,2), etc.
273
+ if shape[-1] == 2:
274
+ return None
275
+
276
+ # ---- 2) Collect candidate axes with dim == n_q (static only) ----
277
+ dims = list(shape)
278
+ cand = [i for i, d in enumerate(dims) if d == n_q]
279
+
280
+ # If exactly one axis matches, it's almost certainly the quantile axis.
281
+ if len(cand) == 1:
282
+ return cand[0]
283
+
284
+ # ---- 3) Strong conventions / common layouts ----
285
+ # (B,H,Q,O)
286
+ if rank == 4 and dims[2] == n_q and dims[-1] not in (n_q, 2):
287
+ return 2
288
+
289
+ # (B,H,O,Q)
290
+ if rank == 4 and dims[-1] == n_q:
291
+ return rank - 1
292
+
293
+ # (B,H,Q)
294
+ if rank == 3 and dims[-1] == n_q:
295
+ return rank - 1
296
+
297
+ # ---- 4) Ambiguous: multiple axes have size n_q ----
298
+ if len(cand) >= 2:
299
+ # Prefer "quantiles before output dim" when last dim looks like O.
300
+ # Typical: (B,H,Q,O) => rank-2
301
+ pref = rank - 2
302
+ if pref in cand and dims[-1] not in (n_q, 2):
303
+ return pref
304
+
305
+ # Otherwise, prefer last axis if it's a candidate (B,H,O,Q style)
306
+ if (rank - 1) in cand:
307
+ return rank - 1
308
+
309
+ # Otherwise pick the last non-batch candidate
310
+ non_batch = [c for c in cand if c != 0]
311
+ return non_batch[-1] if non_batch else cand[-1]
312
+
313
+ return None
314
+
315
+
316
+ def _mean_crossing_score(
317
+ arr: np.ndarray,
318
+ q_axis: int,
319
+ q_idx: Sequence[int] = (0, 1, 2),
320
+ ) -> float:
321
+ # Compute quantile crossing score:
322
+ # mean(q10>q50) + mean(q50>q90) + mean(q10>q90)
323
+ q10 = np.take(arr, int(q_idx[0]), axis=q_axis)
324
+ q50 = np.take(arr, int(q_idx[1]), axis=q_axis)
325
+ q90 = np.take(arr, int(q_idx[2]), axis=q_axis)
326
+
327
+ # squeeze last dim if O=1
328
+ if q10.ndim >= 1 and q10.shape[-1] == 1:
329
+ q10 = q10[..., 0]
330
+ q50 = q50[..., 0]
331
+ q90 = q90[..., 0]
332
+
333
+ c1 = float(np.mean(q10 > q50))
334
+ c2 = float(np.mean(q50 > q90))
335
+ c3 = float(np.mean(q10 > q90))
336
+ return c1 + c2 + c3
337
+
338
+
339
+ def _safe_transpose(
340
+ y: np.ndarray,
341
+ axes: Tuple[int, int, int, int],
342
+ ) -> np.ndarray:
343
+ return np.transpose(y, axes)
344
+
345
+
346
+ def canonicalize_BHQO_quantiles_np(
347
+ y: Any,
348
+ n_q: int = 3,
349
+ *,
350
+ verbose: int = 0,
351
+ log_fn: Callable[[str], None] = print,
352
+ ) -> Any:
353
+ """
354
+ Return y in canonical (B,H,Q,O).
355
+
356
+ Accepts common layouts:
357
+ - (B,H,Q,O) -> unchanged
358
+ - (B,Q,H,O) -> transpose(0,2,1,3)
359
+ - (B,H,O,Q) -> transpose(0,1,3,2)
360
+
361
+ If ambiguous (multiple axes match n_q), choose the transform
362
+ with minimal quantile crossing score.
363
+ """
364
+ y_np = np.asarray(y)
365
+
366
+ # Not quantile tensor (we only canonicalize rank-4).
367
+ if y_np.ndim != 4:
368
+ if verbose:
369
+ log_fn(
370
+ "canonicalize_BHQO_quantiles_np: "
371
+ f"rank={y_np.ndim}, skipping."
372
+ )
373
+ return y
374
+
375
+ n_q = int(n_q)
376
+ if n_q <= 0:
377
+ raise ValueError("n_q must be a positive integer.")
378
+
379
+ # candidates: interpret which axis is Q among {1,2,3}
380
+ cand = [ax for ax in (1, 2, 3) if y_np.shape[ax] == n_q]
381
+
382
+ # No axis matches n_q => not quantile mode, return unchanged.
383
+ if not cand:
384
+ if verbose:
385
+ log_fn(
386
+ "canonicalize_BHQO_quantiles_np: "
387
+ f"no axis matches n_q={n_q}, "
388
+ "return unchanged."
389
+ )
390
+ return y_np
391
+
392
+ options: list[tuple[str, np.ndarray]] = []
393
+
394
+ # already (B,H,Q,O): q_axis=2 and O axis=3
395
+ if y_np.shape[2] == n_q:
396
+ # Keep as-is. This is the canonical layout.
397
+ options.append(("BHQO", y_np))
398
+
399
+ # (B,Q,H,O) -> (B,H,Q,O)
400
+ if y_np.shape[1] == n_q:
401
+ # Swap axes 1 and 2.
402
+ options.append(
403
+ (
404
+ "BQHO->BHQO",
405
+ _safe_transpose(y_np, (0, 2, 1, 3)),
406
+ )
407
+ )
408
+
409
+ # (B,H,O,Q) -> (B,H,Q,O)
410
+ if y_np.shape[3] == n_q:
411
+ # Swap axes 2 and 3.
412
+ options.append(
413
+ (
414
+ "BHOQ->BHQO",
415
+ _safe_transpose(y_np, (0, 1, 3, 2)),
416
+ )
417
+ )
418
+
419
+ # If nothing matched the supported transforms, keep unchanged.
420
+ if not options:
421
+ if verbose:
422
+ log_fn(
423
+ "canonicalize_BHQO_quantiles_np: "
424
+ "no supported transform matched; "
425
+ "return unchanged."
426
+ )
427
+ return y_np
428
+
429
+ # If only one option, pick it directly.
430
+ if len(options) == 1:
431
+ name, arr = options[0]
432
+ if verbose:
433
+ log_fn(
434
+ "canonicalize_BHQO_quantiles_np: "
435
+ f"chose={name} (only option)."
436
+ )
437
+ return arr
438
+
439
+ # Multiple candidates (e.g., H==Q==3):
440
+ # pick best by minimal quantile crossing score.
441
+ best_name: Optional[str] = None
442
+ best_arr: Optional[np.ndarray] = None
443
+ best_score = float("inf")
444
+
445
+ for name, arr in options:
446
+ # score in canonical BHQO along axis=2
447
+ sc = _mean_crossing_score(arr, q_axis=2)
448
+ if verbose >= 2:
449
+ log_fn(
450
+ "canonicalize_BHQO_quantiles_np: "
451
+ f"candidate={name} score={sc:.6f}"
452
+ )
453
+
454
+ if sc < best_score:
455
+ best_score = sc
456
+ best_name = name
457
+ best_arr = arr
458
+
459
+ if best_arr is None:
460
+ # Defensive fallback; should not happen.
461
+ if verbose:
462
+ log_fn(
463
+ "canonicalize_BHQO_quantiles_np: "
464
+ "no best candidate found; "
465
+ "return unchanged."
466
+ )
467
+ return y_np
468
+
469
+ if verbose:
470
+ log_fn(
471
+ "canonicalize_BHQO_quantiles_np: "
472
+ f"chose={best_name} score={best_score:.6f}"
473
+ )
474
+
475
+ return best_arr
476
+
477
+ def _to_numpy(x: Any) -> np.ndarray:
478
+ """Convert tensor/array-like to numpy array."""
479
+ if hasattr(x, "numpy"):
480
+ return np.asarray(x.numpy())
481
+ return np.asarray(x)
482
+
483
+
484
+ def _static_shape(x: Any) -> Optional[Tuple[int, ...]]:
485
+ """Return static shape tuple if available."""
486
+ shp = getattr(x, "shape", None)
487
+ if shp is None:
488
+ return None
489
+
490
+ # tf.TensorShape
491
+ if hasattr(shp, "as_list"):
492
+ lst = shp.as_list()
493
+ if lst is None:
494
+ return None
495
+ out = []
496
+ for d in lst:
497
+ out.append(-1 if d is None else int(d))
498
+ return tuple(out)
499
+
500
+ # numpy / python
501
+ try:
502
+ return tuple(int(d) for d in shp)
503
+ except Exception:
504
+ return None
505
+
506
+
507
+ def infer_q_axis(
508
+ yq: Any,
509
+ n_q: int = 3,
510
+ default: int = 2,
511
+ prefer: Sequence[int] = (2, 1, 3, 0),
512
+ verbose: int = 0,
513
+ log_fn: Callable[[str], None] = print,
514
+ ) -> int:
515
+ """
516
+ Infer quantile axis for common BHQO layouts.
517
+
518
+ Supports (B,H,Q,1) and (B,Q,H,1) (and similar ranks).
519
+ """
520
+ if n_q is None or int(n_q) <= 0:
521
+ raise ValueError("n_q must be a positive integer.")
522
+
523
+ n_q = int(n_q)
524
+ default = int(default)
525
+
526
+ shp = _static_shape(yq)
527
+ if shp is not None and len(shp) > 0:
528
+ axes = [i for i, d in enumerate(shp) if d == n_q]
529
+ if len(axes) == 1:
530
+ return int(axes[0])
531
+
532
+ if len(axes) > 1:
533
+ for ax in prefer:
534
+ if int(ax) in axes:
535
+ return int(ax)
536
+ return int(axes[0])
537
+
538
+ if not tf_executing_eagerly():
539
+ if verbose:
540
+ msg = (
541
+ "infer_q_axis: non-eager mode; "
542
+ f"returning default={default}"
543
+ )
544
+ log_fn(msg)
545
+ return default
546
+
547
+ try:
548
+ dyn = tf_shape(yq)
549
+ rank = int(tf_rank(yq).numpy())
550
+ except :
551
+ if verbose:
552
+ msg = (
553
+ "infer_q_axis: dynamic shape failed; "
554
+ f"returning default={default}"
555
+ )
556
+ log_fn(msg)
557
+ return default
558
+
559
+ # We only resolve common ranks safely.
560
+ if rank < 2:
561
+ return default
562
+
563
+ axes_try = list(prefer)
564
+ axes_try = [ax for ax in axes_try if ax < rank]
565
+
566
+ for ax in axes_try:
567
+ try:
568
+ if int(dyn[ax].numpy()) == n_q:
569
+ return int(ax)
570
+ except Exception:
571
+ continue
572
+
573
+ if verbose:
574
+ msg = (
575
+ "infer_q_axis: could not locate n_q axis; "
576
+ f"rank={rank}, returning default={default}"
577
+ )
578
+ log_fn(msg)
579
+
580
+ return default
581
+
582
+
583
+ def _crossing_rates(
584
+ q_lo: np.ndarray,
585
+ q_mid: np.ndarray,
586
+ q_hi: np.ndarray,
587
+ ) -> Tuple[float, float, float]:
588
+ """Compute basic crossing rates."""
589
+ c1 = float(np.mean(q_lo > q_mid))
590
+ c2 = float(np.mean(q_mid > q_hi))
591
+ c3 = float(np.mean(q_lo > q_hi))
592
+ return c1, c2, c3
593
+
594
+
595
+ def debug_val_interval(
596
+ model: Any,
597
+ ds: Any,
598
+ n_q: int = 3,
599
+ max_batches: int = 2,
600
+ y_key: str = "subs_pred",
601
+ out_key: str = "subs_pred",
602
+ default_q_axis: int = 2,
603
+ verbose: int = 1,
604
+ log_fn: Callable[[str], None] = print,
605
+ ) -> Dict[str, Any]:
606
+ """
607
+ Debug quantile crossing on a tf.data.Dataset.
608
+
609
+ Returns a small summary dict.
610
+ """
611
+
612
+ if max_batches is None:
613
+ max_batches = 2
614
+ max_batches = int(max_batches)
615
+
616
+ summary: Dict[str, Any] = {
617
+ "batches": 0,
618
+ "q_axis": None,
619
+ "crossings": [],
620
+ }
621
+
622
+ if verbose:
623
+ log_fn("debug_val_interval: start")
624
+
625
+ for i, (xb, yb) in enumerate(ds.take(max_batches)):
626
+ out = model(xb, training=False)
627
+ s = out[out_key]
628
+ y = yb[y_key]
629
+
630
+ s_np = _to_numpy(s)
631
+ y_np = _to_numpy(y)
632
+
633
+ q_axis = infer_q_axis(
634
+ s,
635
+ n_q=n_q,
636
+ default=default_q_axis,
637
+ verbose=max(0, verbose - 1),
638
+ log_fn=log_fn,
639
+ )
640
+
641
+ summary["batches"] += 1
642
+ summary["q_axis"] = int(q_axis)
643
+
644
+ if verbose:
645
+ msg = (
646
+ f"\n[BATCH {i}] "
647
+ f"y_true={y_np.shape} "
648
+ f"pred={s_np.shape} "
649
+ f"q_axis={q_axis}"
650
+ )
651
+ log_fn(msg)
652
+
653
+ # Expect a 4D tensor for quantiles.
654
+ if s_np.ndim != 4:
655
+ if verbose:
656
+ msg = (
657
+ " expected rank-4 preds; "
658
+ f"got rank={s_np.ndim}"
659
+ )
660
+ log_fn(msg)
661
+ continue
662
+
663
+ # Slice (assumes last dim is output=1).
664
+ try:
665
+ if q_axis == 2:
666
+ q10 = s_np[:, :, 0, 0]
667
+ q50 = s_np[:, :, 1, 0]
668
+ q90 = s_np[:, :, 2, 0]
669
+ elif q_axis == 1:
670
+ q10 = s_np[:, 0, :, 0]
671
+ q50 = s_np[:, 1, :, 0]
672
+ q90 = s_np[:, 2, :, 0]
673
+ elif q_axis == 3:
674
+ # Rare layout: (B,H,1,Q)
675
+ q10 = s_np[:, :, 0, 0]
676
+ q50 = s_np[:, :, 0, 1]
677
+ q90 = s_np[:, :, 0, 2]
678
+ else:
679
+ if verbose:
680
+ msg = (
681
+ " unsupported q_axis="
682
+ f"{q_axis}; skipping"
683
+ )
684
+ log_fn(msg)
685
+ continue
686
+ except Exception as e:
687
+ if verbose:
688
+ msg = (
689
+ " slicing failed: "
690
+ f"{type(e).__name__}: {e}"
691
+ )
692
+ log_fn(msg)
693
+ continue
694
+
695
+ cr = _crossing_rates(q10, q50, q90)
696
+ summary["crossings"].append(cr)
697
+
698
+ if verbose:
699
+ msg = (
700
+ " crossing (q10>q50, q50>q90, q10>q90): "
701
+ f"{cr}"
702
+ )
703
+ log_fn(msg)
704
+
705
+ if verbose:
706
+ log_fn("\ndebug_val_interval: done")
707
+
708
+ return summary
709
+
710
+
711
+ def debug_tensor_interval(
712
+ y_true: Any,
713
+ s_q: Any,
714
+ n_q: int = 3,
715
+ name: str = "RAW",
716
+ default_q_axis: int = 2,
717
+ verbose: int = 1,
718
+ log_fn: Callable[[str], None] = print,
719
+ ) -> Dict[str, Any]:
720
+ """
721
+ Debug quantile crossing for pre-collected tensors/arrays.
722
+ """
723
+ y_np = _to_numpy(y_true)
724
+ s_np = _to_numpy(s_q)
725
+
726
+ out: Dict[str, Any] = {
727
+ "name": str(name),
728
+ "y_shape": tuple(y_np.shape),
729
+ "s_shape": tuple(s_np.shape),
730
+ "q_axis": None,
731
+ "crossing": None,
732
+ }
733
+
734
+ if verbose:
735
+ msg = (
736
+ f"\n[{name}] "
737
+ f"y_true shape={y_np.shape} "
738
+ f"s_q shape={s_np.shape}"
739
+ )
740
+ log_fn(msg)
741
+
742
+ if s_np.ndim != 4:
743
+ if verbose:
744
+ msg = (
745
+ f"[{name}] expected rank-4 s_q; "
746
+ f"got rank={s_np.ndim}"
747
+ )
748
+ log_fn(msg)
749
+ return out
750
+
751
+ # Infer q axis using static shape only.
752
+ q_axis = None
753
+ if s_np.shape[2] == n_q:
754
+ q_axis = 2
755
+ elif s_np.shape[1] == n_q:
756
+ q_axis = 1
757
+ elif s_np.shape[3] == n_q:
758
+ q_axis = 3
759
+ else:
760
+ q_axis = int(default_q_axis)
761
+
762
+ out["q_axis"] = int(q_axis)
763
+
764
+ if verbose:
765
+ log_fn(f"[{name}] inferred q_axis={q_axis}")
766
+
767
+ if int(n_q) < 3:
768
+ if verbose:
769
+ msg = (
770
+ f"[{name}] n_q={n_q} < 3; "
771
+ "crossing checks need >= 3."
772
+ )
773
+ log_fn(msg)
774
+ return out
775
+
776
+ try:
777
+ if q_axis == 2:
778
+ q10 = s_np[:, :, 0, 0]
779
+ q50 = s_np[:, :, 1, 0]
780
+ q90 = s_np[:, :, 2, 0]
781
+ elif q_axis == 1:
782
+ q10 = s_np[:, 0, :, 0]
783
+ q50 = s_np[:, 1, :, 0]
784
+ q90 = s_np[:, 2, :, 0]
785
+ elif q_axis == 3:
786
+ q10 = s_np[:, :, 0, 0]
787
+ q50 = s_np[:, :, 0, 1]
788
+ q90 = s_np[:, :, 0, 2]
789
+ else:
790
+ if verbose:
791
+ msg = (
792
+ f"[{name}] unsupported q_axis={q_axis}; "
793
+ "skipping."
794
+ )
795
+ log_fn(msg)
796
+ return out
797
+ except Exception as e:
798
+ if verbose:
799
+ msg = (
800
+ f"[{name}] slicing failed: "
801
+ f"{type(e).__name__}: {e}"
802
+ )
803
+ log_fn(msg)
804
+ return out
805
+
806
+ cr = _crossing_rates(q10, q50, q90)
807
+ out["crossing"] = cr
808
+
809
+ if verbose:
810
+ msg = (
811
+ f"[{name}] cross q10>q50: {cr[0]:.6f}\n"
812
+ f"[{name}] cross q50>q90: {cr[1]:.6f}\n"
813
+ f"[{name}] cross q10>q90: {cr[2]:.6f}"
814
+ )
815
+ log_fn(msg)
816
+
817
+ return out
818
+
819
+ def _logs_to_py(logs, *, keep_none=True):
820
+ out = {}
821
+ for k, v in (logs or {}).items():
822
+ if v is None:
823
+ if keep_none:
824
+ out[k] = None
825
+ continue
826
+
827
+ # tf.Tensor / tf.Variable
828
+ if hasattr(v, "numpy"):
829
+ v = v.numpy()
830
+
831
+ # numpy scalar / array
832
+ if isinstance(v, np.ndarray):
833
+ if v.shape == ():
834
+ v = v.item()
835
+ else:
836
+ v = v.tolist()
837
+ elif isinstance(v, np.generic):
838
+ v = v.item()
839
+
840
+ out[k] = v
841
+ return out
842
+
843
+ def canonicalize_to_BHQO_using_contract(
844
+ s_pred,
845
+ *,
846
+ q_values=(0.1, 0.5, 0.9),
847
+ enforce_monotone=True,
848
+ ):
849
+
850
+ n_q = len(q_values)
851
+
852
+ if s_pred.shape.rank == 3:
853
+ s_pred = tf_expand_dims(s_pred, axis=-1)
854
+
855
+ if s_pred.shape.rank != 4:
856
+ return s_pred
857
+
858
+ # Accept BHQO
859
+ if s_pred.shape[2] == n_q:
860
+ out = s_pred
861
+
862
+ # Accept BQHO -> transpose to BHQO
863
+ elif s_pred.shape[1] == n_q:
864
+ out = tf_transpose(s_pred, [0, 2, 1, 3])
865
+
866
+ # Accept BHOQ -> transpose to BHQO
867
+ elif s_pred.shape[3] == n_q:
868
+ out = tf_transpose(s_pred, [0, 1, 3, 2])
869
+
870
+ else:
871
+ raise ValueError(
872
+ "Cannot locate quantile axis. "
873
+ f"shape={s_pred.shape}, n_q={n_q}"
874
+ )
875
+
876
+ if enforce_monotone:
877
+ out = tf_sort(out, axis=2)
878
+
879
+ return out
880
+
881
+ def canonicalize_to_BHQO_using_ytrue(
882
+ s_pred, y_true, q_values=(0.1,0.5,0.9)
883
+ ):
884
+ """
885
+ s_pred: (B,?, ?,1) rank-4
886
+ y_true: (B,H,1)
887
+ Returns: s_pred_BHQO (B,H,Q,1)
888
+ """
889
+
890
+ q_values = list(q_values)
891
+ med = int(min(range(len(
892
+ q_values)), key=lambda i: abs(q_values[i]-0.5)))
893
+
894
+ # Candidate A: assume BHQO already
895
+ A = s_pred
896
+ A_q50 = A[:, :, med, :] # (B,H,1)
897
+
898
+ # Candidate B: assume BQHO -> transpose to BHQO
899
+ B = tf_transpose(s_pred, [0, 2, 1, 3])
900
+ B_q50 = B[:, :, med, :] # (B,H,1)
901
+
902
+ # Score by MAE against y_true in model space
903
+ maeA = tf_reduce_mean(tf_abs(A_q50 - y_true))
904
+ maeB = tf_reduce_mean(tf_abs(B_q50 - y_true))
905
+
906
+ out = tf_cond(maeB < maeA, lambda: B, lambda: A)
907
+
908
+ # Enforce monotonic quantiles after canonicalization (prevents inverted bounds)
909
+ out = tf_sort(out, axis=2)
910
+ return out
911
+
912
+ def debug_quantile_crossing_np(
913
+ s_pred: Any,
914
+ n_q: int = 3,
915
+ *,
916
+ name: str = "subs_pred",
917
+ verbose: int = 1,
918
+ log_fn: Callable[[str], None] = print,
919
+ try_repair: bool = False,
920
+ repair_mode: str = "sort",
921
+ ) -> Dict[str, Any]:
922
+ """
923
+ Debug quantile crossing rates for two common layouts.
924
+
925
+ Checks both:
926
+ A) (B,H,Q,1) => q_axis=2
927
+ B) (B,Q,H,1) => q_axis=1
928
+
929
+ Optionally suggests / applies a repair:
930
+ - repair_mode="flip": reverse quantile order along Q axis
931
+ - repair_mode="sort": enforce monotonic quantiles via sort
932
+ """
933
+ s_np = _to_numpy(s_pred)
934
+
935
+ out: Dict[str, Any] = {
936
+ "name": str(name),
937
+ "shape": tuple(s_np.shape),
938
+ "n_q": int(n_q),
939
+ "layout_A": None,
940
+ "layout_B": None,
941
+ "best_layout": None,
942
+ "best_score": None,
943
+ "repaired": False,
944
+ "repair_mode": None,
945
+ "notes": [],
946
+ }
947
+
948
+ if verbose:
949
+ log_fn(
950
+ f"\n[debug_quantile_crossing_np] "
951
+ f"name={name} shape={s_np.shape}"
952
+ )
953
+
954
+ if s_np.ndim != 4:
955
+ out["notes"].append("expected rank-4 tensor")
956
+ if verbose:
957
+ log_fn(
958
+ "[debug_quantile_crossing_np] "
959
+ f"expected rank-4, got {s_np.ndim}"
960
+ )
961
+ return out
962
+
963
+ if int(n_q) < 3:
964
+ out["notes"].append("n_q < 3; need >=3")
965
+ if verbose:
966
+ log_fn(
967
+ "[debug_quantile_crossing_np] "
968
+ f"n_q={n_q} < 3; skipping"
969
+ )
970
+ return out
971
+
972
+ # We assume O=1 (last dim) for this debug utility.
973
+ if s_np.shape[-1] != 1:
974
+ out["notes"].append("last dim != 1 (O != 1)")
975
+ if verbose:
976
+ log_fn(
977
+ "[debug_quantile_crossing_np] "
978
+ "expected last dim O=1"
979
+ )
980
+
981
+ def _rates_and_score(
982
+ q10: np.ndarray,
983
+ q50: np.ndarray,
984
+ q90: np.ndarray,
985
+ ) -> Tuple[Tuple[float, float, float], float]:
986
+ rates = _crossing_rates(q10, q50, q90)
987
+ score = float(rates[0] + rates[1] + rates[2])
988
+ return rates, score
989
+
990
+ # ---- Layout A: (B,H,Q,1) ----
991
+ if s_np.shape[2] == n_q:
992
+ try:
993
+ q10 = s_np[:, :, 0, 0]
994
+ q50 = s_np[:, :, 1, 0]
995
+ q90 = s_np[:, :, 2, 0]
996
+ rates, score = _rates_and_score(q10, q50, q90)
997
+ out["layout_A"] = {
998
+ "layout": "(B,H,Q,1)",
999
+ "q_axis": 2,
1000
+ "rates": rates,
1001
+ "score": score,
1002
+ }
1003
+ if verbose:
1004
+ log_fn(
1005
+ "layout (B,H,Q,1) crossing: "
1006
+ f"{rates} score={score:.6f}"
1007
+ )
1008
+ except Exception as e:
1009
+ out["notes"].append(f"layout_A slicing failed: {e}")
1010
+
1011
+ # ---- Layout B: (B,Q,H,1) ----
1012
+ if s_np.shape[1] == n_q:
1013
+ try:
1014
+ q10 = s_np[:, 0, :, 0]
1015
+ q50 = s_np[:, 1, :, 0]
1016
+ q90 = s_np[:, 2, :, 0]
1017
+ rates, score = _rates_and_score(q10, q50, q90)
1018
+ out["layout_B"] = {
1019
+ "layout": "(B,Q,H,1)",
1020
+ "q_axis": 1,
1021
+ "rates": rates,
1022
+ "score": score,
1023
+ }
1024
+ if verbose:
1025
+ log_fn(
1026
+ "layout (B,Q,H,1) crossing: "
1027
+ f"{rates} score={score:.6f}"
1028
+ )
1029
+ except Exception as e:
1030
+ out["notes"].append(f"layout_B slicing failed: {e}")
1031
+
1032
+ # Pick best available layout by minimal score.
1033
+ cand = []
1034
+ if out["layout_A"] is not None:
1035
+ cand.append(("A", out["layout_A"]["score"]))
1036
+ if out["layout_B"] is not None:
1037
+ cand.append(("B", out["layout_B"]["score"]))
1038
+
1039
+ if not cand:
1040
+ out["notes"].append("no matching Q axis found")
1041
+ if verbose:
1042
+ log_fn(
1043
+ "[debug_quantile_crossing_np] "
1044
+ "no axis matched n_q"
1045
+ )
1046
+ return out
1047
+
1048
+ best_layout, best_score = min(cand, key=lambda x: x[1])
1049
+ out["best_layout"] = best_layout
1050
+ out["best_score"] = float(best_score)
1051
+
1052
+ if verbose:
1053
+ log_fn(
1054
+ "[debug_quantile_crossing_np] "
1055
+ f"best_layout={best_layout} "
1056
+ f"best_score={best_score:.6f}"
1057
+ )
1058
+
1059
+ # Optional repair suggestion / apply.
1060
+ if not try_repair:
1061
+ return out
1062
+
1063
+ # Only repair when we can interpret canonical BHQO first.
1064
+ repaired = None
1065
+ repair_mode = str(repair_mode).lower().strip()
1066
+
1067
+ if best_layout == "B":
1068
+ # Convert to BHQO first.
1069
+ repaired = np.transpose(s_np, (0, 2, 1, 3))
1070
+ else:
1071
+ repaired = s_np
1072
+
1073
+ # Now repaired is BHQO (best guess).
1074
+ if repaired.shape[2] != n_q:
1075
+ out["notes"].append("repair: not BHQO after step")
1076
+ return out
1077
+
1078
+ if repair_mode == "flip":
1079
+ repaired = repaired[:, :, ::-1, :]
1080
+ out["repaired"] = True
1081
+ out["repair_mode"] = "flip"
1082
+ if verbose:
1083
+ log_fn(
1084
+ "[debug_quantile_crossing_np] "
1085
+ "repair applied: flip Q axis"
1086
+ )
1087
+
1088
+ elif repair_mode == "sort":
1089
+ # Enforce q10<=q50<=q90 pointwise.
1090
+ repaired = np.sort(repaired, axis=2)
1091
+ out["repaired"] = True
1092
+ out["repair_mode"] = "sort"
1093
+ if verbose:
1094
+ log_fn(
1095
+ "[debug_quantile_crossing_np] "
1096
+ "repair applied: sort on Q axis"
1097
+ )
1098
+ else:
1099
+ out["notes"].append(
1100
+ "repair_mode must be 'flip' or 'sort'"
1101
+ )
1102
+ return out
1103
+
1104
+ # Re-score repaired tensor.
1105
+ try:
1106
+ q10 = repaired[:, :, 0, 0]
1107
+ q50 = repaired[:, :, 1, 0]
1108
+ q90 = repaired[:, :, 2, 0]
1109
+ rates, score = _rates_and_score(q10, q50, q90)
1110
+ out["after_repair"] = {
1111
+ "layout": "(B,H,Q,1)",
1112
+ "q_axis": 2,
1113
+ "rates": rates,
1114
+ "score": score,
1115
+ }
1116
+ if verbose:
1117
+ log_fn(
1118
+ "after repair crossing: "
1119
+ f"{rates} score={score:.6f}"
1120
+ )
1121
+ except Exception as e:
1122
+ out["notes"].append(f"after_repair failed: {e}")
1123
+
1124
+ return out