Skip to content

Learning series representations: TS2Vec

TS2Vec learns a vector for every time step without labels, by matching the same moment in two cropped views at several time scales. Score an aligned contrastive loss by hand and see what the vectors are good for.

Advanced ~13 min8 steps

What runs in CodeSplash

You will be able to

  • Explain TS2Vec's positive pairs and its two contrastive losses
  • Compute an aligned temporal contrastive loss and one coarse pooling level
  • Say how overlapping windows and non-causal encoders can leak into later evaluation
  • Evaluate embeddings with a separate downstream task

Read first

01

Labels are scarce, series are not

Read

Machines, sensors and patients produce long series, and labels for them are rare. TS2VecTS2VecA convolutional encoder trained without labels so overlapping crops of a series get the same representation. learns a vector for every time step from the series alone, by contrastive learningContrastive learningLearning representations without labels by pulling two views of the same row together and pushing other rows' views away.. Those vectors can then feed clustering, anomaly scores, a small classifier or a forecaster, each evaluated on its own task.

Its encoder is a stack of dilated convolutionsDilated convolution encoderStacked convolutions whose spacing doubles each block, so each step's representation sees exponentially more neighbors., so each time step's vector sees a window of neighbors whose width doubles with depth.

Reference · SPE020 · Runs in CodeSplashTS2VecTS2Vec learns contextual representations at individual timestamps and larger temporal scales through hierarchical contrastive learning.
02

Two views, same moment

Read

TS2Vec takes two overlapping random crops of a series and encodes both. The same timestamp in the two crops is a positive pair: its two vectors should match. The hierarchical contrastive lossHierarchical contrastive lossContrasts each series with the others and each time step with the other steps, then repeats after halving the time resolution. pushes them together against two kinds of negatives:

  • temporal: other timestamps of the same series;
  • instance: the same timestamp in other series of the batch.

Then it max-pools the vectors over time and repeats, so the loss also acts at coarser scales:

L=∑l[λLinstance(Zl,Zl′)+(1−λ)Ltemporal(Zl,Zl′)],Zl+1=MaxPool⁡(Zl).L = \sum_l \big[\lambda L_{\text{instance}}(Z_l, Z_l') + (1 - \lambda) L_{\text{temporal}}(Z_l, Z_l')\big], \qquad Z_{l+1} = \operatorname{MaxPool}(Z_l).

The contrastive loss on a toy: views of the same item pull together.

DExplorable · InfoNCE: temperature, negatives, collapse

How does contrastive learning learn useful embeddings without labels, and what keeps it from collapsing?

After training with this objective, where do the embeddings end up?

How sure?
0.20

Batch size

Each item's negatives are the rest of the batch.

Objective

Without labels, a batch can't tell them apart. Off: they're masked out.

0.30
300
0.80

Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.

Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

The temporal loss by hand

Explore

The reference embeds four timestamps in 2-D, perturbs them for a second view, and scores each timestamp against all four in the other view at temperature 0.20.2. The aligned temporal loss is 0.750. One max-pooling step turns the four vectors into two: (1.0, 0.3) and (0.2, 1.0).

Python
import numpy as np
def sm(a): e = np.exp(a - a.max(axis=-1, keepdims=True)); return e / e.sum(axis=-1, keepdims=True)
Z = np.array([[1., 0.], [.7, .3], [.2, .8], [0., 1.]])
other = Z + np.array([[.05, -.02], [-.02, .05], [.01, -.03], [-.03, .01]])   # second view
loss = -np.log(np.diag(sm(Z @ other.T / .2))).mean()     # match each step to itself
print(loss, np.stack([Z[:2].max(0), Z[2:].max(0)]))       # one coarser level
R
sm <- function(a) { e <- exp(a - apply(a, 1, max)); e / rowSums(e) }
Z <- rbind(c(1, 0), c(.7, .3), c(.2, .8), c(0, 1))
other <- Z + rbind(c(.05, -.02), c(-.02, .05), c(.01, -.03), c(-.03, .01))  # second view
loss <- -mean(log(diag(sm(Z %*% t(other) / .2))))         # match each step to itself
print(list(loss = loss, coarse = rbind(apply(Z[1:2, ], 2, max), apply(Z[3:4, ], 2, max))))

The instance part and deeper levels are left out here.

04

Embedding overlapping windows

Explore
TS2Vec series embeddings (contrastive time-series representation)Recorded · Python and R agreeRecorded 2026-11-21 · 14 values compared
R

TS2Vec embedded 168 windows of 32 steps of x as 6 numbers each, after 5 epochs of contrastive training.

Final contrastive loss
2.003

Plots

Embeddings on their first two principal componentsWhich levels of a categorical variable does the model treat as alike?
View data
windowComponent 1Component 2
s01:1−0.0946−0.0123
s01:170.05520.0953
s01:330.07500.1277
s01:49−0.09650.0261
s01:65−0.11700.0383
s01:810.13880.0578
s01:970.14540.0939
s02:10.2143−0.2031
s02:170.21870.0584
s02:33−0.0826−0.0073
s02:490.04040.1127
s02:650.12790.0672
s02:81−0.1868−0.1637
s02:970.1987−0.0065
s03:1−0.23830.0634
s03:17−0.07850.1861
s03:33−0.14430.0188
s03:490.00190.1154
s03:65−0.1259−0.0055
s03:81−0.2873−0.1028
s03:970.0890−0.0519
s04:1−0.1110−0.0299
s04:17−0.0627−0.1153
s04:33−0.2257−0.1955
s04:49−0.0057−0.0993
s04:65−0.0473−0.0313
s04:810.17950.1030
s04:970.18840.0839
s05:10.0468−0.0652
s05:170.11120.0799
s05:33−0.0091−0.0774
s05:490.00220.2624
s05:650.02720.1566
s05:810.34830.2047
s05:970.19620.0392
s06:1−0.3706−0.1646
s06:17−0.3220−0.1575
s06:330.18330.0482
s06:490.3700−0.1090
s06:650.4945−0.1872
s06:810.4012−0.1508
s06:97−0.0147−0.0440
s07:10.0216−0.1184
s07:170.0115−0.1166
s07:330.0384−0.0685
s07:490.0278−0.0760
s07:65−0.1032−0.0425
s07:81−0.1050−0.0417
s07:970.2203−0.1348
s08:1−0.2577−0.0084
s08:17−0.2209−0.1445
s08:33−0.1731−0.0378
s08:49−0.13280.0078
s08:65−0.3877−0.0431
s08:81−0.4442−0.1053
s08:97−0.4278−0.0335
s09:1−0.27710.0561
s09:170.04080.1169
s09:330.01910.1410
s09:490.0786−0.0385

First 60 of 168 rows.

Hierarchical contrastive loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
Contrastive2.1301
Contrastive2.1522
Contrastive2.3593
Contrastive2.2194
Contrastive2.0035

Assumptions

  • The embeddings use several directions — The first principal direction holds 59% of the embeddings' variance.

Embeddings (first 6 of 6 numbers)

Window (series:first step)e1e2e3e4e5e6
s01:11.2510.68580.03720.53480.31871.349
s01:171.4080.7806−0.00560.47310.25841.403
s01:331.4650.7564−0.01010.49040.24631.421
s01:491.2680.6917−0.00950.50820.25851.411
s01:651.2570.68890.12430.52710.32231.406
s01:811.4290.8431−0.02530.47420.22261.328
s01:971.4780.8150−0.02680.49610.21261.355
s02:11.4210.73010.00960.33700.24211.089
s02:171.4800.88910.00480.44280.26821.283
s02:331.2300.73590.14020.39440.35411.379
s02:491.4150.76140.03850.42270.32111.429
s02:651.4830.75530.02400.46970.25981.339
s02:811.1270.58580.09290.39880.40751.284
s02:971.4730.81190.10470.41830.27031.240
s03:11.1450.6899−0.01220.53960.29531.502
s03:171.3090.80720.15790.56750.33681.500
s03:331.1960.7167−0.03170.51350.26501.425
s03:491.3170.85250.04030.54040.27141.417
s03:651.2270.6776−0.00740.49960.26031.399
s03:811.0260.63800.01210.50360.26231.392
s03:971.3350.8049−0.01210.45940.17421.268
s04:11.2420.65710.00240.47370.23351.384
s04:171.2400.65450.01560.41010.22871.300
s04:331.0420.62320.03260.41470.27831.298
s04:491.2820.69420.02740.39720.27991.275
s04:651.2810.69480.01210.44450.25291.352
s04:811.4980.84510.01740.44430.25191.351
s04:971.4950.8464−0.01840.47880.19781.330
s05:11.3190.7481−0.00290.34620.34771.280
s05:171.3710.90370.01080.40360.32821.358
s05:331.2620.73680.01730.38090.33941.288
s05:491.4230.82740.03350.49470.37551.550
s05:651.3900.81690.03520.42930.37611.460
s05:811.5901.0590.06180.42380.32971.333
s05:971.4520.87720.00030.42580.34831.265
s06:10.96050.55010.10310.44730.36331.375
s06:171.0370.51710.03740.40190.29571.391
s06:331.4240.9062−0.02790.36520.31181.309
s06:491.5220.9038−0.01670.29170.27651.094
s06:651.6120.8891−0.01750.24070.25270.9786

First 40 of 168 rows.

  • The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).
  • Each step's representation sees about 14 neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.
The exact R script · R R version 4.5.1 (2025-06-13)
# TS2Vec series embeddings (contrastive time-series representation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ts_embed 1.0.0 · spec 8c1486a0bc5318e3
# Dataset: seq_signals (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/seq_signals.parquet", col_select = c("x", "series", "step")))
n_input <- nrow(df)
df[["series"]] <- factor(df[["series"]], levels = c("s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24"))  # stored level order
df <- df[stats::complete.cases(df[c("x", "series", "step")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("x", "series", "step"))  # infinite values stop the run (registry/errors.yaml)

# %% Series
# TS2Vec (Yue et al. 2022): a dilated-convolution encoder trained with the hierarchical contrastive loss on random
# overlapping crops (contextual consistency); each series (or window of one) is embedded by max-pooling its steps.
VALUE <- "x"
SERIES <- "series"
TIME <- "step"
LABEL <- NULL
UNIT <- "window"  # series | window
WINDOW <- 32
STRIDE <- 16
DIMS <- as.integer(6)
HIDDEN <- as.integer(6)
DEPTH <- as.integer(2)
EPOCHS <- as.integer(5)
LR <- as.numeric(0.001)
BATCH <- as.integer(4)
SEED <- 42
d <- df
if (!is.null(SERIES) && !is.null(TIME)) {
  d <- d[order(as.integer(d[[SERIES]]), d[[TIME]], method = "radix"), , drop = FALSE]
} else if (!is.null(SERIES)) {
  d <- d[order(as.integer(d[[SERIES]]), method = "radix"), , drop = FALSE]
} else if (!is.null(TIME)) {
  d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
}
rownames(d) <- NULL
x_all <- as.numeric(d[[VALUE]])
cs_check_rows(nrow(d), 16, "TS2Vec")
cs_check_not_constant(x_all, VALUE)
if (UNIT == "series") {
  if (is.null(SERIES)) {
    cs_error("CS_E_UNDEFINED", what = "Embedding whole series", reason = "it needs a Series column with at least 3 series (pick Windows to embed stretches of one series)")
  }
  cs_check_groups(as.character(d[[SERIES]]), SERIES, minimum = 3)
}
names_ <- if (!is.null(SERIES)) as.character(levels(d[[SERIES]])) else VALUE
ids <- if (!is.null(SERIES)) as.integer(d[[SERIES]]) else rep(1L, nrow(d))
signals <- lapply(seq_along(names_), function(i) x_all[ids == i])
lengths_ <- vapply(signals, length, integer(1))
if (min(lengths_) < 8) {
  cs_error("CS_E_UNDEFINED", what = "TS2Vec",
           reason = sprintf("series %s has %d values (at least 8 are needed)", names_[which.min(lengths_)], min(lengths_)))
}
labels_by_series <- NULL
if (!is.null(LABEL) && UNIT == "series") {
  labels_by_series <- character(length(names_))
  bad <- 0L
  for (i in seq_along(names_)) {
    lv <- unique(as.character(d[[LABEL]][ids == i]))
    bad <- bad + as.integer(length(lv) > 1)
    labels_by_series[i] <- lv[1]
  }
  if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = LABEL, requirement = "the same within each series", count = bad)
}
if (max(lengths_) > 2 * min(lengths_)) {
  warnings <- c(warnings, sprintf("Series lengths run from %d to %d values; training crops never exceed the shortest series in a batch.", min(lengths_), max(lengths_)))
}

# %% Train
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-24289/discover.ts_embed/signals-windows-overlap/out-r")
fit <- cs_ts2vec_fit(signals, hidden = HIDDEN, dims = DIMS, depth = DEPTH, epochs = EPOCHS, lr = LR, batch_size = BATCH, seed = SEED)
Z <- cs_ts2vec_standardize(signals)
if (UNIT == "series") {
  inst_names <- names_
  segments <- Z
} else {
  W <- if (!is.null(WINDOW)) as.integer(WINDOW) else as.integer(min(64L, max(8L, min(lengths_) %/% 4L)))
  if (W > min(lengths_)) {
    cs_error("CS_E_INVALID_OPTION", option = "Window length", allowed = sprintf("at most %d (the shortest series)", min(lengths_)), value = as.character(W))
  }
  S <- if (!is.null(STRIDE)) as.integer(STRIDE) else W
  inst_names <- character(0); segments <- list()
  for (i in seq_along(Z)) {
    z <- Z[[i]]
    for (s in seq(0L, length(z) - W, by = S)) {
      inst_names <- c(inst_names, if (!is.null(SERIES)) sprintf("%s:%d", names_[i], s + 1L) else as.character(s + 1L))
      segments[[length(segments) + 1L]] <- z[(s + 1L):(s + W)]
    }
  }
  if (length(segments) < 3) {
    cs_error("CS_E_UNDEFINED", what = "Embedding windows", reason = sprintf("only %d window(s) fit (at least 3 are needed); shorten the window or the stride", length(segments)))
  }
}
E <- cs_ts2vec_encode(fit, segments)
pc <- cs_ts2vec_pca2(E)
n <- nrow(E)
values <- list(
  n_instances = n, n_series = length(signals), min_length = min(lengths_), dims = DIMS, depth = DEPTH,
  receptive_field = cs_ts2vec_receptive_field(DEPTH), epochs_run = fit$epochs_run, final_loss = fit$final_loss,
  n_params = fit$n_params, pc_share1 = pc$shares[1], pc_share2 = pc$shares[2],
  embed_check = sum(t(outer(seq_len(n), seq_len(DIMS)) * E))
)
if (UNIT == "window") {
  values$window <- W
  values$stride <- S
}

# %% Probe
probe_rows <- list()
if (!is.null(labels_by_series)) {
  classes <- sort(unique(labels_by_series), method = "radix")
  if (length(signals) >= 4 && length(classes) >= 2) {
    acc <- cs_scat_probe(E, labels_by_series)
    chance <- max(vapply(classes, function(cl) sum(labels_by_series == cl), integer(1))) / length(labels_by_series)
    values$probe_acc <- acc
    values$probe_chance <- chance
    probe_rows <- list(list(features = sprintf("TS2Vec embedding (%d numbers)", DIMS), accuracy = acc),
                       list(features = "Always the most common class", accuracy = chance))
  } else {
    warnings <- c(warnings, "The probe needs at least 4 series and 2 classes; it was skipped.")
  }
}

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-24289/discover.ts_embed/signals-windows-overlap/out-r")
mode <- if (UNIT == "series") SERIES else "window"
fdf <- data.frame(level = inst_names, stringsAsFactors = FALSE)
for (k in seq_len(DIMS)) fdf[[sprintf("factor_%d", k)]] <- E[, k]
path <- file.path(out, sprintf("factors_%s.parquet", mode))
nanoparquet::write_parquet(fdf, path)
hist <- data.frame(epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
                   loss = vapply(fit$history, function(h) h$loss, numeric(1)))
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
artifacts <- list(list(key = sprintf("factors_%s", mode), path = path, format = "parquet"),
                  list(key = "history", path = file.path(out, "history.parquet"), format = "parquet"))

# %% Charts
charts <- list(cs_chart("map", "embedding-map", "Embeddings on their first two principal components", list(
  x = cs_col("Component 1", pc$scores[, 1]), y = cs_col("Component 2", pc$scores[, 2]),
  label = cs_col(if (UNIT == "series") SERIES else "window", inst_names, kind = "categorical"))))
charts[[length(charts) + 1]] <- cs_chart("training", "training-components", "Hierarchical contrastive loss by epoch", list(
  x = cs_col("Epoch", hist$epoch, "numeric"),
  value = cs_col("Loss", hist$loss, "numeric"),
  component = cs_col("Part", rep("Contrastive", nrow(hist)), "categorical")))

# %% Tables
show <- min(DIMS, 8L)
emb_cols <- c(list(list(key = "level", label = if (UNIT == "series") SERIES else "Window (series:first step)", type = "string")),
              lapply(seq_len(show), function(k) list(key = sprintf("e%d", k), label = sprintf("e%d", k), type = "number")))
tables <- list(list(key = "embeddings", title = sprintf("Embeddings (first %d of %d numbers)", show, DIMS), columns = emb_cols,
                    rows = lapply(seq_len(min(n, 500L)), function(i) {
                      row <- list(level = inst_names[i])
                      for (k in seq_len(show)) row[[sprintf("e%d", k)]] <- E[i, k]
                      row
                    })))
if (length(probe_rows)) {
  tables[[length(tables) + 1]] <- list(key = "probe", title = "Leave-one-out nearest-neighbor probe",
    columns = list(list(key = "features", label = "Features", type = "string"), list(key = "accuracy", label = "Accuracy", type = "percent")),
    rows = probe_rows)
}
collapse <- DIMS > 1 && pc$shares[1] > 0.9
assumptions <- list(list(
  key = "collapse",
  label = "The embeddings use several directions",
  status = if (collapse) "warn" else "pass",
  detail = paste0(sprintf("The first principal direction holds %.0f%% of the embeddings' variance", 100 * pc$shares[1]),
                  if (collapse) " — nearly everything lies on one line (dimensional collapse)." else ".")
))

# %% Result
what <- if (UNIT == "series") sprintf("%d series", n) else sprintf("%d windows of %d steps", n, W)
summary <- sprintf("TS2Vec embedded %s of %s as %d numbers each, after %d epochs of contrastive training.", what, VALUE, DIMS, as.integer(fit$epochs_run))
if (!is.null(values$probe_acc)) {
  summary <- paste(summary, sprintf("A nearest-neighbor probe on the embeddings recovers %s for %.0f%% of the series (most common class: %.0f%%).",
                                    LABEL, 100 * values$probe_acc, 100 * values$probe_chance))
}
notes <- c("The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).",
           sprintf("Each step's representation sees about %d neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.",
                   cs_ts2vec_receptive_field(DEPTH)))
cs_publish(list(
  title = "TS2Vec series embeddings (contrastive time-series representation)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = n,
  summary = summary,
  statistics = list(list(key = "final_loss", label = "Final contrastive loss", value = values$final_loss)),
  tables = tables,
  charts = charts,
  values = values,
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  artifacts = artifacts
))
Python

TS2Vec embedded 168 windows of 32 steps of x as 6 numbers each, after 5 epochs of contrastive training.

Final contrastive loss
2.003

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • The embeddings use several directions — The first principal direction holds 59% of the embeddings' variance.

Embeddings (first 6 of 6 numbers)

Window (series:first step)e1e2e3e4e5e6
s01:11.2510.68580.03720.53480.31871.349
s01:171.4080.7806−0.00560.47310.25841.403
s01:331.4650.7564−0.01010.49040.24631.421
s01:491.2680.6917−0.00950.50820.25851.411
s01:651.2570.68890.12430.52710.32231.406
s01:811.4290.8431−0.02530.47420.22261.328
s01:971.4780.8150−0.02680.49610.21261.355
s02:11.4210.73010.00960.33700.24211.089
s02:171.4800.88910.00480.44280.26821.283
s02:331.2300.73590.14020.39440.35411.379
s02:491.4150.76140.03850.42270.32111.429
s02:651.4830.75530.02400.46970.25981.339
s02:811.1270.58580.09290.39880.40751.284
s02:971.4730.81190.10470.41830.27031.240
s03:11.1450.6899−0.01220.53960.29531.502
s03:171.3090.80720.15790.56750.33681.500
s03:331.1960.7167−0.03170.51350.26501.425
s03:491.3170.85250.04030.54040.27141.417
s03:651.2270.6776−0.00740.49960.26031.399
s03:811.0260.63800.01210.50360.26231.392
s03:971.3350.8049−0.01210.45940.17421.268
s04:11.2420.65710.00240.47370.23351.384
s04:171.2400.65450.01560.41010.22871.300
s04:331.0420.62320.03260.41470.27831.298
s04:491.2820.69420.02740.39720.27991.275
s04:651.2810.69480.01210.44450.25291.352
s04:811.4980.84510.01740.44430.25191.351
s04:971.4950.8464−0.01840.47880.19781.330
s05:11.3190.7481−0.00290.34620.34771.280
s05:171.3710.90370.01080.40360.32821.358
s05:331.2620.73680.01730.38090.33941.288
s05:491.4230.82740.03350.49470.37551.550
s05:651.3900.81690.03520.42930.37611.460
s05:811.5901.0590.06180.42380.32971.333
s05:971.4520.87720.00030.42580.34831.265
s06:10.96050.55010.10310.44730.36331.375
s06:171.0370.51710.03740.40190.29571.391
s06:331.4240.9062−0.02790.36520.31181.309
s06:491.5220.9038−0.01670.29170.27651.094
s06:651.6120.8891−0.01750.24070.25270.9786

First 40 of 168 rows.

  • The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).
  • Each step's representation sees about 14 neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TS2Vec series embeddings (contrastive time-series representation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ts_embed 1.0.0 · spec 8c1486a0bc5318e3
# Dataset: seq_signals (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import check_groups, check_not_constant
from codesplash.deep import ts2vec  # twin of codesplashr::cs_ts2vec_* (torch, shared initial weights and crops)
from codesplash.ml import forecast as fc
from codesplash.stats import scattering as sc

# %% Data
df = pd.read_parquet("tests/parity/fixtures/seq_signals.parquet", columns=["x", "series", "step"])
n_input = len(df)
df["series"] = pd.Categorical(df["series"], categories=["s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24"])  # stored level order
df = df.dropna(subset=["x", "series", "step"])  # listwise deletion over the analysis columns
df["series"] = df["series"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["x", "series", "step"])  # infinite values stop the run (registry/errors.yaml)

# %% Series
# TS2Vec (Yue et al. 2022): a dilated-convolution encoder trained with the hierarchical contrastive loss on random
# overlapping crops (contextual consistency); each series (or window of one) is embedded by max-pooling its steps.
VALUE = "x"
SERIES = "series"
TIME = "step"
LABEL = None
UNIT = "window"  # series | window
WINDOW = 32
STRIDE = 16
DIMS = int(6)
HIDDEN = int(6)
DEPTH = int(2)
EPOCHS = int(5)
LR = float(0.001)
BATCH = int(4)
SEED = 42
keys = ([SERIES] if SERIES else []) + ([TIME] if TIME else [])
d = df.sort_values(keys, kind="mergesort").reset_index(drop=True) if keys else df.reset_index(drop=True)
x_all = d[VALUE].to_numpy(dtype=float)
cs.check_rows(len(d), 16, "TS2Vec")
check_not_constant(x_all, VALUE)
if UNIT == "series":
    if not SERIES:
        cs.cs_error("CS_E_UNDEFINED", what="Embedding whole series", reason="it needs a Series column with at least 3 series (pick Windows to embed stretches of one series)")
    check_groups(d[SERIES].astype(str), SERIES, minimum=3)
names = [str(v) for v in d[SERIES].cat.categories] if SERIES else [VALUE]
ids = d[SERIES].cat.codes.to_numpy() if SERIES else np.zeros(len(d), dtype=np.int64)
signals = [[float(v) for v in x_all[ids == i]] for i in range(len(names))]
lengths = [len(s) for s in signals]
if min(lengths) < 8:
    short = names[int(np.argmin(lengths))]
    cs.cs_error("CS_E_UNDEFINED", what="TS2Vec", reason=f"series {short} has {min(lengths)} values (at least 8 are needed)")
labels_by_series = None
if LABEL and UNIT == "series":
    labels_by_series = []
    bad = 0
    for i in range(len(names)):
        lv = d[LABEL][ids == i].astype(str).unique()
        bad += int(len(lv) > 1)
        labels_by_series.append(str(lv[0]))
    if bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=LABEL, requirement="the same within each series", count=bad)
if max(lengths) > 2 * min(lengths):
    warnings.append(f"Series lengths run from {min(lengths)} to {max(lengths)} values; training crops never exceed the shortest series in a batch.")

# %% Train
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-24289/discover.ts_embed/signals-windows-overlap/out-python",
)
fit = ts2vec.fit(signals, hidden=HIDDEN, dims=DIMS, depth=DEPTH, epochs=EPOCHS, lr=LR, batch_size=BATCH, seed=SEED)
Z = ts2vec.standardize(signals)
if UNIT == "series":
    inst_names = names
    segments = Z
else:
    W = int(WINDOW) if WINDOW else min(64, max(8, min(lengths) // 4))
    if W > min(lengths):
        cs.cs_error("CS_E_INVALID_OPTION", option="Window length", allowed=f"at most {min(lengths)} (the shortest series)", value=str(W))
    S = int(STRIDE) if STRIDE else W
    inst_names, segments = [], []
    for i, z in enumerate(Z):
        for s in range(0, len(z) - W + 1, S):
            inst_names.append(f"{names[i]}:{s + 1}" if SERIES else str(s + 1))
            segments.append(z[s : s + W])
    if len(segments) < 3:
        cs.cs_error("CS_E_UNDEFINED", what="Embedding windows", reason=f"only {len(segments)} window(s) fit (at least 3 are needed); shorten the window or the stride")
E = ts2vec.encode(fit, segments)
P2, shares = ts2vec.pca2(E)
n = E.shape[0]
values = {
    "n_instances": n,
    "n_series": len(signals),
    "min_length": min(lengths),
    "dims": DIMS,
    "depth": DEPTH,
    "receptive_field": ts2vec.receptive_field(DEPTH),
    "epochs_run": fit["epochs_run"],
    "final_loss": fit["final_loss"],
    "n_params": fit["n_params"],
    "pc_share1": shares[0],
    "pc_share2": shares[1],
    "embed_check": fc._sum([(i + 1) * (k + 1) * float(E[i, k]) for i in range(n) for k in range(DIMS)]),
}
if UNIT == "window":
    values["window"] = W
    values["stride"] = S

# %% Probe
probe_rows = []
if labels_by_series is not None:
    classes = sorted(set(labels_by_series))
    if len(signals) >= 4 and len(classes) >= 2:
        acc = sc.probe(E, labels_by_series)
        chance = max(labels_by_series.count(c) for c in classes) / len(labels_by_series)
        values.update({"probe_acc": acc, "probe_chance": chance})
        probe_rows = [{"features": f"TS2Vec embedding ({DIMS} numbers)", "accuracy": acc}, {"features": "Always the most common class", "accuracy": chance}]
    else:
        warnings.append("The probe needs at least 4 series and 2 classes; it was skipped.")

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-24289/discover.ts_embed/signals-windows-overlap/out-python")
mode = SERIES if UNIT == "series" else "window"
fdf = pd.DataFrame({"level": inst_names})
for k in range(DIMS):
    fdf[f"factor_{k + 1}"] = E[:, k]
path = os.path.join(out, f"factors_{mode}.parquet")
fdf.to_parquet(path, index=False)
history = pd.DataFrame({"epoch": [h["epoch"] for h in fit["history"]], "loss": [h["loss"] for h in fit["history"]]})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
artifacts = [{"key": f"factors_{mode}", "path": path, "format": "parquet"},
             {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"}]

# %% Charts
roles_map = {"x": cs.col("Component 1", P2[:, 0]), "y": cs.col("Component 2", P2[:, 1]),
             "label": cs.col(SERIES if UNIT == "series" else "window", inst_names, kind="categorical")}
charts = [cs.chart("map", "embedding-map", "Embeddings on their first two principal components", roles_map)]
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Hierarchical contrastive loss by epoch", {
    "x": cs.col("Epoch", ep, "numeric"),
    "value": cs.col("Loss", [h["loss"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", ["Contrastive"] * len(ep), "categorical"),
}))

# %% Tables
show = min(DIMS, 8)
tables = [{"key": "embeddings", "title": f"Embeddings (first {show} of {DIMS} numbers)",
           "columns": [{"key": "level", "label": SERIES if UNIT == "series" else "Window (series:first step)", "type": "string"}]
           + [{"key": f"e{k + 1}", "label": f"e{k + 1}", "type": "number"} for k in range(show)],
           "rows": [{"level": inst_names[i], **{f"e{k + 1}": float(E[i, k]) for k in range(show)}} for i in range(min(n, 500))]}]
if probe_rows:
    tables.append({"key": "probe", "title": "Leave-one-out nearest-neighbor probe",
                   "columns": [{"key": "features", "label": "Features", "type": "string"}, {"key": "accuracy", "label": "Accuracy", "type": "percent"}],
                   "rows": probe_rows})
assumptions = [{
    "key": "collapse",
    "label": "The embeddings use several directions",
    "status": "warn" if (DIMS > 1 and shares[0] > 0.9) else "pass",
    "detail": f"The first principal direction holds {shares[0]:.0%} of the embeddings' variance"
              + (" — nearly everything lies on one line (dimensional collapse)." if DIMS > 1 and shares[0] > 0.9 else "."),
}]

# %% Result
what = f"{n} series" if UNIT == "series" else f"{n} windows of {W} steps"
summary = f"TS2Vec embedded {what} of {VALUE} as {DIMS} numbers each, after {fit['epochs_run']} epochs of contrastive training."
if "probe_acc" in values:
    summary += f" A nearest-neighbor probe on the embeddings recovers {LABEL} for {values['probe_acc']:.0%} of the series (most common class: {values['probe_chance']:.0%})."
notes = ["The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).",
         f"Each step's representation sees about {ts2vec.receptive_field(DEPTH)} neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when."]
cs.publish({
    "title": "TS2Vec series embeddings (contrastive time-series representation)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [{"key": "final_loss", "label": "Final contrastive loss", "value": values["final_loss"]}],
    "tables": tables,
    "charts": charts,
    "values": values,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "artifacts": artifacts,
})

Here TS2Vec embeds windows of 32 steps taken every 16 steps, giving 168 windows from 24 series. The first two principal components of the embeddings hold 58.9% and 24.9% of their variance.

Neighboring windows share half their steps. They are not independent examples: keep all windows of a series on one side of any later split.

05

Where embeddings leak

Predict

Predict first

You compute TS2Vec embeddings over a whole series, then use the embedding at time tt to forecast time t+1t + 1. Safe or a leak?

Safe: embeddings carry no labelsCan leak: each step's vector may see later steps
Reveal

It can leak. The encoder's window reaches both ways, so the vector at tt may already contain t+1t + 1. For forecasting, compute each embedding from data up to tt only. Also check that augmentations keep positive pairs truly aligned; a misaligned crop teaches the wrong match.

06

What runs here

Read
07

Check: TS2Vec

Checkpoint

Check yourself

In TS2Vec, what is a positive pair?

Show the answer

Answer: b

Matching timestamps across augmented views are positives; other timestamps and other series supply negatives.

Check yourself

Why does TS2Vec repeat its loss after max-pooling over time?

Show the answer

Answer: a

Each pooling level applies the same contrastive loss to coarser vectors. Fine levels keep local detail; coarse levels capture longer patterns.

Check yourself

Windows of 32 steps are taken every 16 steps. How should you split them for a downstream classifier?

Show the answer

Answer: b

Overlapping windows share data. A random split would test on near-copies of training windows.

Check yourself

How do you show TS2Vec embeddings are useful?

Show the answer

Answer: b

Self-supervised loss doesn't measure usefulness. Evaluate the task you care about, with leakage-safe splits.

08

Recap

Recap
  • TS2Vec learns per-step vectors without labels by matching the same moment in two crops.
  • Its loss contrasts against other times and other series, at several pooled scales.
  • Overlapping windows and two-sided encoders can leak: split by series and keep forecasting causal.
  • Judge embeddings on a downstream task. TS2Vec runs in CodeSplash as discover.ts_embed.

Concepts in this lesson