DailyBatchSampler in pytorch_gats_ts.py yields cross-day batches: TSDataSampler.get_index() swaps index labels but not row order
Bug description
DailyBatchSampler (qlib/contrib/model/pytorch_gats_ts.py) assumes rows belonging to the same trading day are contiguous in the data source: it computes per-day counts via groupby("datetime").size(), converts them to start offsets with cumsum, and slices contiguous ranges np.arange(idx, idx + count).
However, TSDataSampler stores data instrument-major — qlib/data/dataset/__init__.py builds it as self.data = data.swaplevel().sort_index() (and the data_index docstring itself says index order <instrument, datetime>). get_index() then returns self.data_index.swaplevel(), which swaps the labels of the MultiIndex back to (datetime, instrument) but does not reorder rows.
As a result each "daily" batch actually contains one instrument across many consecutive days, not one day's cross-section. Any model trained with this sampler (e.g. the GATs benchmark, and code copying this sampler) silently trains its graph/attention over "one stock's history" instead of "one day's cross-section".
Minimal reproduction
import numpy as np
import pandas as pd
from qlib.data.dataset import TSDataSampler
dates = pd.date_range("2020-01-01", periods=5, freq="B")
insts = ["A", "B", "C"]
idx = pd.MultiIndex.from_product([dates, insts], names=["datetime", "instrument"])
df = pd.DataFrame({"f": range(len(idx)), "label": range(len(idx))}, index=idx)
s = TSDataSampler(df, dates[0], dates[-1], step_len=2)
print(s.get_index()[:6].tolist())
# [(2020-01-01, A), (2020-01-02, A), (2020-01-03, A), (2020-01-06, A), (2020-01-07, A), (2020-01-01, B)]
# -> labels say (datetime, instrument), but rows are instrument-major.
# DailyBatchSampler's first "day" batch is rows 0..2 (3 instruments expected),
# which are actually instrument A on three different days.
Note the docstring of get_index() explicitly advertises the day-by-day use case: "Special sampler will be used (e.g. user want to sample day by day)".
Expected behavior
Either:
get_index()documents that row order is instrument-major (andDailyBatchSampleris fixed to not assume contiguity), orDailyBatchSamplergroups actual row positions by datetime instead of assuming contiguous blocks.
Suggested fix (drop-in for DailyBatchSampler)
class DailyBatchSampler(Sampler):
def __init__(self, data_source):
self.data_source = data_source
index = data_source.get_index()
positions = pd.Series(np.arange(len(index)), index=index.get_level_values("datetime"))
self.batches = [g.to_numpy() for _, g in positions.groupby(level=0, sort=True)]
def __iter__(self):
yield from self.batches
def __len__(self):
return len(self.batches)
When using this, downstream index alignment for predictions must follow the sampler's iteration order, e.g. dl_test.get_index()[np.concatenate(self.batches)].
Environment
Verified against current main: qlib/data/dataset/__init__.py (get_index, and data.swaplevel().sort_index() in TSDataSampler.__init__) and qlib/contrib/model/pytorch_gats_ts.py (DailyBatchSampler) are unchanged. Found while implementing a cross-sectional model whose per-day-batch unit test ("each batch contains exactly one datetime") failed against the GATs-style sampler.
Verified both halves precisely. TSDataSampler.init does self.data = data.swaplevel().sort_index(), which physically sorts rows by the post-swap index, instrument first per the data_index docstring. get_index() then does self.data_index.swaplevel(), which only swaps the labels inside each tuple back to (datetime, instrument), it never touches row order. So the returned index reads like day by day pairs but the actual sequence is still grouped by instrument, exactly matching your repro output.
Your replacement for DailyBatchSampler looks correct, grouping by the actual datetime values in positions rather than assuming contiguous blocks sidesteps the whole issue. Given this also affects get_index()'s own docstring claim about day by day sampling being supported, is the fix meant to stay scoped to DailyBatchSampler, or does get_index() itself need a doc fix or a real reordering so other callers relying on that docstring aren't quietly wrong too?
Confirmed the mechanism with a standalone repro (no qlib import needed). The root cause is a row-order assumption:
- TSDataSampler stores rows instrument-major: \data_index\ is a MultiIndex in <instrument, datetime> order (rows physically sorted by instrument).
- \get_index()\ returns \self.data_index.swaplevel()\ — it swaps the LABEL order to <datetime, instrument> but does not reorder the underlying rows.
- \DailyBatchSampler.init\ counts samples per datetime via \groupby("datetime").size()\ (correct counts) and then assumes those groups are CONTIGUOUS in row space: \daily_index = np.roll(np.cumsum(daily_count), 1)\ and slices
p.arange(idx, idx + count).
With instrument-major rows, a contiguous slice of size \daily_count\ is not one trading day — it is a chunk of one instrument's timeline (possibly spilling into the next instrument). Minimal demo (3 instruments x 4 days):
\\python import numpy as np, pandas as pd insts = ["SH600000", "SH600008", "SH600009"] dates = pd.date_range("2026-01-05", periods=4, freq="B") rows = [(i, d) for i in insts for d in dates] data_index = pd.MultiIndex.from_tuples(rows) # instrument-major, as stored get_index = data_index.swaplevel() # labels look datetime-major daily_count = pd.Series(index=get_index).groupby(level=0).size().values # [3,3,3,3] daily_index = np.roll(np.cumsum(daily_count), 1); daily_index[0] = 0 # [0,3,6,9] for idx, count in zip(daily_index, daily_count): print([(i, str(d.date())) for i, d in data_index[idx:idx+count]]) \\
Output — every "batch" mixes 2-3 different dates:
\\ [('SH600000','2026-01-05'), ('SH600000','2026-01-06'), ('SH600000','2026-01-07')] [('SH600000','2026-01-08'), ('SH600008','2026-01-05'), ('SH600008','2026-01-06')] [('SH600008','2026-01-07'), ('SH600008','2026-01-08'), ('SH600009','2026-01-05')] [('SH600009','2026-01-06'), ('SH600009','2026-01-07'), ('SH600009','2026-01-08')] \\
Impact: for GATs/LSTM time-series training the "daily batch" is not a market-day cross-section; each batch spans several trading days of one instrument and drops the other instruments for those days. Validation batches and any per-day statistic are equally affected.
Suggested fix direction: compute each day's row positions from the actual instrument-major layout instead of assuming contiguity, e.g. group the physical row indices by datetime (
p.flatnonzero\ per date, or a positional map from the datetime level), then yield those index arrays. Happy to prepare a PR if this direction looks right.
To close the loop on the scope question (sampler-only vs get_index()): I've prepared PR #2342 which (1) fixes DailyBatchSampler to group actual row positions per day, and (2) documents the contract on get_index() — swaplevel() changes label order only, rows stay physically <instrument, datetime> — so other callers don't silently assume datetime-contiguity. A full row reordering inside get_index() would be a much bigger behavioral change for every existing caller (and expensive for large data), so documenting + fixing the one consumer that relied on the wrong assumption seemed the right scope. Happy to adjust if maintainers prefer the docstring-only route first.
Thanks @tongflau-dongzhu for the PR — the scope you chose is exactly right. To answer @adityaanikam's question from my side as well: I'd also keep the fix at the consumer level and document the contract on get_index() rather than reorder rows inside it. TSDataSampler's whole index mechanism is built on the instrument-major physical layout — slice_idx_map_and_data_index applies the same boolean mask to idx_map and data_index, so a "real reordering" in get_index() would either desync __getitem__ from the returned index or force reordering the internal state too. A much bigger behavioral change, as you said.
I verified the new DailyBatchSampler against the real get_index() shape (swapped labels, instrument-major rows) on a 3-instrument × 4-day grid: each batch is exactly one day's full cross-section, and every physical row is yielded exactly once. The implementation is correct. Two things in the PR need a second look though:
1. GATs.predict now misaligns predictions with the index. The test path in pytorch_gats_ts.py (line ~335 on current main) does:
return pd.Series(np.concatenate(preds), index=dl_test.get_index())
This silently assumes the DataLoader iterates rows in get_index() order. After the sampler fix, iteration order is day-major while get_index() rows stay instrument-major — on the 3×4 grid above, 10 of 12 positions mismatch. So the bug would move from "wrong training batches" to "wrongly aligned predictions", which is arguably worse because nothing crashes. The predict path should reorder the index by the sampler's iteration order, e.g.:
index_order = np.concatenate(list(iter(sampler_test)))
return pd.Series(np.concatenate(preds), index=dl_test.get_index()[index_order])
(In my own fork I expose sampler.index_order = np.concatenate(self.batches) for exactly this.)
2. The new test's fake doesn't match what get_index() actually returns. _instrument_major_index returns the un-swapped <instrument, datetime> index, but the sampler groups with positions.groupby(level=0) — on the fake, level 0 is instrument, so it groups per instrument (3 batches, each one instrument across 4 days, i.e. the original bug shape) and test_batches_are_per_day_cross_sections fails its len(batches) == len(dates) assertion. The real get_index() returns the swapped view, so the fake should end with .swaplevel(), and the label unpacking {day for _, day in labels} becomes {day for day, _ in labels}. As written the test can't pass, which suggests it wasn't run locally.
The __len__ change (number of batches instead of sample count) is correct too — that's what DataLoader reports as its length.
@hugo2046 thanks for the careful review — both points are exactly right, and both are fixed in the updated branch (f034ee4):
-
predict alignment: DailyBatchSampler now exposes index_order (physical rows in iteration order) and GATs.predict returns pd.Series(np.concatenate(preds), index=dl_test.get_index()[sampler_test.index_order]), so predictions stay aligned with the original instrument-major layout.
-
Test fixture: _FakeDataSource now mirrors the real get_index() (stored instrument-major, returns the swaplevel() view), so groupby(level=0) groups by datetime as intended. With the old fixture the sampler grouped by instrument (3 batches, not 4) — the test could not have passed, and I couldn't run it locally (Windows, no pyqlib wheel), which is on me. CI will now validate it for real.
Thanks also for confirming the scope call on get_index() — keeping the fix at the consumer level and documenting the contract matches the physical-layout design.