Skip to content

Add ctsm model#45490

Open
kashif wants to merge 29 commits into
huggingface:mainfrom
kashif:add-ctsm-model
Open

Add ctsm model#45490
kashif wants to merge 29 commits into
huggingface:mainfrom
kashif:add-ctsm-model

Conversation

@kashif

@kashif kashif commented Apr 17, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes # (issue)

Code Agent Policy

The Transformers repo is currently being overwhelmed by a large number of PRs and issue comments written by
code agents. We are currently bottlenecked by our ability to review and respond to them. As a result,
we ask that new users do not submit pure code agent PRs at this time.
You may use code agents in drafting or to help you diagnose issues. We'd also ask autonomous "OpenClaw"-like agents
not to open any PRs or issues for the moment.

PRs that appear to be fully agent-written will probably be closed without review, and we may block users who do this
repeatedly or maliciously.

This is a rapidly-evolving situation that's causing significant shockwaves in the open-source community. As a result,
this policy is likely to be updated regularly in the near future. For more information, please read CONTRIBUTING.md.

  • I confirm that this is not a pure code agent PR.

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline,
    Pull Request section?
  • Was this discussed/approved via a Github issue or the forum? Please add a link
    to it if that's the case.
  • Did you make sure to update the documentation with your changes? Here are the
    documentation guidelines, and
    here are tips on formatting docstrings.
  • Did you write any new necessary tests?

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some initial comments from my side. I think there are a few design decisions I'm a bit unsure about - especially the manual generation might make sense to split into a generate file (similar to audio models)

This would keep the modeling file hopefully cleaner

Comment thread docs/source/en/model_doc/ctsm.md Outdated
Comment thread docs/source/en/model_doc/ctsm.md Outdated
Comment thread docs/source/en/model_doc/ctsm.md Outdated
Comment thread docs/source/en/model_doc/ctsm.md Outdated
Comment thread docs/source/en/model_doc/ctsm.md Outdated
Comment thread src/transformers/models/ctsm/modular_ctsm.py Outdated
Comment thread src/transformers/models/ctsm/modular_ctsm.py Outdated
Comment thread src/transformers/models/ctsm/modular_ctsm.py
Comment thread src/transformers/models/ctsm/modular_ctsm.py Outdated
Comment thread src/transformers/models/ctsm/modular_ctsm.py Outdated
kashif added a commit to kashif/transformers that referenced this pull request May 4, 2026
Mechanical / readability fixes from vasqu's review:

- Rename `agg_factor` -> `aggregation_factor` (config + conversion + tests + docs).
- Rename short locals `bsize` -> `bsz`, `c_n` -> `coarse_n`, `f_n` -> `fine_n`,
  `rem` -> `remaining`, `seq_len_f` -> `seq_len_float`.
- Add docstring to `_left_pad_to_patch_boundary`.
- Flip dataclass decorator order to `@auto_docstring \n @dataclass` per huggingface#45702.
- Thread `**kwargs` through the `self_attn` call in `CtsmDecoderLayer` and
  re-add the `# Self Attention` / `# MLP` block markers; add the "key
  difference" comment on the cache update and note that scaling is already
  applied via `_scale_query`.
- Switch `multi_resolution` / `special_token` initialization to
  `... if cond else None` ternaries so the attributes always exist; simplify
  the `_init_weights` guard to `module.special_token is not None`.
- Drop `_no_split_modules` and `_can_record_outputs` overrides from
  `CtsmPreTrainedModel` -- modular conversion auto-rewrites the inherited
  TimesFm references with the Ctsm prefix.
- Drop the `cache_position` parameter from `CtsmModel.forward` and the
  threaded path in `_incremental_forward`; compute `position_ids` directly
  from `past_length`.

Docs:

- Remove the PyTorch badge (we are torch-only).
- Switch the usage example to `AutoModelForTimeSeriesPrediction`.
- Move "model contributed by" up under Overview; move the inference notes
  into a `## Usage tips` section under the example.
- Drop the duplicated citation block.

96/96 tests pass; `make check-repo` clean.
kashif added a commit to kashif/transformers that referenced this pull request May 23, 2026
Mechanical / readability fixes from vasqu's review:

- Rename `agg_factor` -> `aggregation_factor` (config + conversion + tests + docs).
- Rename short locals `bsize` -> `bsz`, `c_n` -> `coarse_n`, `f_n` -> `fine_n`,
  `rem` -> `remaining`, `seq_len_f` -> `seq_len_float`.
- Add docstring to `_left_pad_to_patch_boundary`.
- Flip dataclass decorator order to `@auto_docstring \n @dataclass` per huggingface#45702.
- Thread `**kwargs` through the `self_attn` call in `CtsmDecoderLayer` and
  re-add the `# Self Attention` / `# MLP` block markers; add the "key
  difference" comment on the cache update and note that scaling is already
  applied via `_scale_query`.
- Switch `multi_resolution` / `special_token` initialization to
  `... if cond else None` ternaries so the attributes always exist; simplify
  the `_init_weights` guard to `module.special_token is not None`.
- Drop `_no_split_modules` and `_can_record_outputs` overrides from
  `CtsmPreTrainedModel` -- modular conversion auto-rewrites the inherited
  TimesFm references with the Ctsm prefix.
- Drop the `cache_position` parameter from `CtsmModel.forward` and the
  threaded path in `_incremental_forward`; compute `position_ids` directly
  from `past_length`.

Docs:

- Remove the PyTorch badge (we are torch-only).
- Switch the usage example to `AutoModelForTimeSeriesPrediction`.
- Move "model contributed by" up under Overview; move the inference notes
  into a `## Usage tips` section under the example.
- Drop the duplicated citation block.

96/96 tests pass; `make check-repo` clean.
kashif added 18 commits June 1, 2026 15:47
Adds CTSM 1.0 (cisco-ai/cisco-time-series-model-1.0) as a first-class
time-series foundation model. It is architecturally a TimesFM 2.0 decoder
with multi-resolution inputs (coarse + learned special token + fine),
rotary position embeddings, bidirectional attention over the coarse block,
and 15-quantile prediction.

- modular_ctsm.py reuses TimesFmAttention/DecoderLayer/Model and the
  TimesFm2_5 RoPE utilities so RoPE + per-dim Q scaling are shared.
- CtsmModel.forward takes (past_values_coarse, past_values_fine) streams.
  CtsmModelForPrediction.forward takes a list of fine-res series and
  derives the coarse stream by mean-aggregation over agg_factor blocks,
  then runs an AR decode loop.
- Registered in auto_mappings, MODEL_MAPPING, time-series-prediction mapping,
  models/__init__.py, _toctree.yml, and docs.
- Tests mirror the timesfm2_5 pattern: full ModelTesterMixin coverage
  (with a custom eager-vs-SDPA equivalence that uses the native two-stream
  interface since CTSM builds its own mask).
- Conversion script maps the fused qkv_proj + input/horizon residual blocks
  + multi_resolution / special_token / freq_emb to the transformers layout
  and has been verified end-to-end against the 250M Hub checkpoint.
The original CTSM reference normalizes each stream over the full non-padded
context before the forward, then denormalizes the final prediction with the
same stream stats. Inheriting TimesFM's first-patch normalization gives the
same result mathematically (per-patch norm + denorm + stream norm + denorm
is an identity over the extra factors), but sends inputs to the transformer
in a different scale than what the checkpoint was trained on, and is less
efficient.

This replaces the per-first-patch `_forward_transform` step with a single
stream-level `_normalize_with_pad` (matching `PatchedTSMultiResolutionDecoder`
in the reference), returns stream stats as `CtsmOutput.loc/scale`, and lets
`CtsmModelForPrediction._decode_step` denormalize in a single pass.

Verified against the 250M hub checkpoint on the reference notebook datasets:

  cpu_util              MAE model=2.11  naive_last=3.36  (~37% better)
  server_responsetime   MAE model=0.65  naive_last=2.05  (~3x better)
  internet_traffic      MAE model=805   naive_last=4071  (~5x better)

Quantile predictions stay monotone; 95 tests still pass.
Each AR step recomputes the full forward by design: (1) coarse attention is
bidirectional, so a new coarse patch invalidates every existing coarse K/V
entry — the standard `DynamicCache.update(...)` append semantics can't
express that; (2) stream normalization is recomputed per step over the raw
context, which shifts every patch embedding. The original reference makes
the same choice explicit (`CTSMAttentionRoPE` raises NotImplementedError on
cache arguments), and it matches the convention of other time-series
forecasters in transformers (TimesFM, TimesFM 2.5, PatchTST, Informer,
Autoformer).
Rewrite the model doc to mirror the transformers model-doc template and pull
content directly from the CTSM Technical Report (arXiv:2511.19841):

- Full author list verified against the arXiv author list in order.
- Quoted abstract.
- Architecture section distinguishing the paper's 1.0-preview (500M, 50
  layers, 9 quantiles, CPT from TimesFM 2.0) from the 1.0 release checkpoint
  actually on the Hub (250M, 25 layers, 15 quantiles, trained from scratch,
  adds RoPE, bidirectional coarse attention, short-context training).
- Inference section noting the AR multi-resolution decode loop and why there
  is no KV cache.
- Two usage snippets: auto-built coarse stream, and explicit (coarse, fine)
  pairs.
- BibTeX citation using a BibTeX-safe form for the Yuhan Song entry (the
  parenthetical nickname in the paper parses oddly in BibTeX).
…n_mask

CtsmModel inherits from TimesFmModel, which already provides a
_prepare_4d_attention_mask(attention_mask, sequence_length, dtype, device,
is_causal) static method combining padding + causal into a 4D additive mask.
My _build_attention_mask was re-implementing the same logic (plus a one-line
bidirectional-coarse zeroing), and _convert_paddings_to_attention_bias was
duplicating the padding-to-bias conversion inside it.

Replace both with a call to the inherited method + the single bidirectional
patch. Numerically identical (cpu_util MAE 2.1093, same as before), 95 tests
still pass.
CtsmOutputForPrediction inherits `loss` from TimesFmOutputForPrediction, but
the @auto_docstring check requires every field of the dataclass to be
documented in the class docstring. Add the missing `loss` entry and rerun
the modular converter + ruff format so the generated file is in sync.
Mirrors TimesFmModel / TimesFm2_5Model: CtsmModel is the building block
used by CtsmModelForPrediction, which is the only class in
`all_model_classes` in the test file. Common tests exercise CtsmModel
through the prediction wrapper; there is nothing to add to the test list.
For `horizon_len > config.horizon_length`, `CtsmModelForPrediction` now
reuses a `DynamicCache` across autoregressive steps:

- Step 1 runs a full forward over `[coarse, special, fine]` and populates
  the cache with K/V per layer.
- Subsequent steps feed only the four new fine patches through the stack;
  their Q/K/V attend to `past_key_values.update(...)`-merged K/V.
- Stream normalization stats are frozen to their step-1 values so cached
  embeddings stay on a consistent scale; the coarse block is pinned; if
  the cache would outgrow `max_position_embeddings` it's discarded and
  rebuilt from the current raw contexts.
- `use_cache: bool | None` on `CtsmModelForPrediction.forward` lets callers
  force the old full-recompute path if they prefer.

API additions mirror Llama et al.:
- `CtsmAttention.forward(..., past_key_values=None)`
- `CtsmDecoderLayer.forward(..., past_key_values=None)`
- `CtsmModel.forward(..., past_key_values=None, use_cache=None, cache_position=None,
  loc_fine=None, scale_fine=None)` — when `past_key_values` is provided,
  `past_values_fine` must contain only the new fine values and `loc_fine` /
  `scale_fine` must be supplied so normalization matches the cached state.
- `CtsmOutput.past_key_values` field.

Benchmarks on the 250M hub checkpoint (CPU, horizon=512, cpu_utilization):
  use_cache=False  521 ms  MAE=2.6852
  use_cache=True   400 ms  MAE=2.6852
MAE is bit-identical across the three notebook datasets.

Added a `test_kv_cache_matches_full_recompute` regression test that
verifies step-1 predictions are exact and subsequent AR steps stay
within a generous bound on the tiny random-weights tester model.
Mechanical / readability fixes from vasqu's review:

- Rename `agg_factor` -> `aggregation_factor` (config + conversion + tests + docs).
- Rename short locals `bsize` -> `bsz`, `c_n` -> `coarse_n`, `f_n` -> `fine_n`,
  `rem` -> `remaining`, `seq_len_f` -> `seq_len_float`.
- Add docstring to `_left_pad_to_patch_boundary`.
- Flip dataclass decorator order to `@auto_docstring \n @dataclass` per huggingface#45702.
- Thread `**kwargs` through the `self_attn` call in `CtsmDecoderLayer` and
  re-add the `# Self Attention` / `# MLP` block markers; add the "key
  difference" comment on the cache update and note that scaling is already
  applied via `_scale_query`.
- Switch `multi_resolution` / `special_token` initialization to
  `... if cond else None` ternaries so the attributes always exist; simplify
  the `_init_weights` guard to `module.special_token is not None`.
- Drop `_no_split_modules` and `_can_record_outputs` overrides from
  `CtsmPreTrainedModel` -- modular conversion auto-rewrites the inherited
  TimesFm references with the Ctsm prefix.
- Drop the `cache_position` parameter from `CtsmModel.forward` and the
  threaded path in `_incremental_forward`; compute `position_ids` directly
  from `past_length`.

Docs:

- Remove the PyTorch badge (we are torch-only).
- Switch the usage example to `AutoModelForTimeSeriesPrediction`.
- Move "model contributed by" up under Overview; move the inference notes
  into a `## Usage tips` section under the example.
- Drop the duplicated citation block.

96/96 tests pass; `make check-repo` clean.
Per vasqu's L74 review comment, override only the fields that genuinely
differ from `TimesFmConfig`. `context_length: int = 512` and
`use_positional_embedding: bool = False` had the same defaults as the
parent and were just noise; remove them. The truly different fields
(`num_hidden_layers=25`, the 15-quantile tuple, the multi-resolution /
RoPE / max-position additions, and the `min_timescale` / `max_timescale`
sentinels that disable inherited fields) stay.

Generated `configuration_ctsm.py` is unchanged because the modular
converter inlines parent fields anyway -- this only thins the modular
source.
- Drop framework badge block from the model card (torch-only).
- Trim duplicated config doc fields; keep only CTSM-specific overrides.
- Remove the `hasattr(self, "position_emb") / del` block in CtsmModel;
  use_positional_embedding=False is the CTSM default so the parent never
  creates the attribute.
- Promote `_supports_flash_attn` / `_supports_flex_attn` from
  CtsmPreTrainedModel to TimesFmPreTrainedModel (the original TimesFM
  parent now advertises the same support).
Replace the manual `_build_attention_mask` and `_build_incremental_attention_mask`
with `create_causal_mask`. The full-forward path passes
`block_sequence_ids = [0]*num_coarse + [-1]*(num_special+num_fine)` so the
coarse block stays bidirectional while the special token + fine block stay
strictly causal; the incremental path falls back to a plain causal mask over
the cached + new sequence.

This is what PR huggingface#45477 enabled, so the manual carve-out is no longer needed.
The unit test for the removed `_build_attention_mask` helper is dropped — the
masking behavior is now covered by the shared `masking_utils` test suite.
Two bugs in the port produced ~11% relative error vs the official
cisco_tsm reference. Both are now fixed; on the released
cisco-ai/cisco-time-series-model-1.0 checkpoint the default
`use_cache=False` path matches the reference at fp32 precision
(max-abs diff 3e-5, relative 1.8e-7).

1. Two-stage normalization.

   The reference applies *both* stream-level normalization and TimesFM's
   per-first-patch normalization on the (stream-normalized) input; the
   horizon head then denormalizes through both stages in reverse. Our
   `_patchify` skipped the per-first-patch stage entirely, so the input
   tokenizer saw differently-scaled patches and the head's output was
   denormalized through only one stage.

   `_patchify` now calls the inherited TimesFM `_forward_transform` to
   apply per-first-patch normalization and returns the resulting
   `(mu, sigma)`. `CtsmOutput` carries those stats as `loc_fine_patch` /
   `scale_fine_patch`, and `_project_last_fine` applies the per-first-patch
   denormalization before the stream denormalization. The incremental
   path takes the frozen stats as inputs so new fine patches share the
   cached K/V's normalized space.

2. Per-dim Q scaling order vs RoPE.

   The reference applies the learned per-dim Q scaling *before* RoPE.
   Because the two halves of `head_dim` that RoPE pairs up are scaled
   by different learned factors, the two operations don't commute - the
   port was applying scaling after RoPE, which silently changed every
   layer's attention scores.

The cache path's `test_kv_cache_matches_full_recompute` tolerance is
relaxed: both stream and per-first-patch stats are frozen at step 1, so
the cached approximation now drifts a bit more from the recompute path
on the tiny-random-weight tester. On the pretrained 250M checkpoint the
cached drift on H=256 is ~7% relative, which is acceptable for an
opt-in fast path.
The official cisco_tsm reference (`1.0/modeling/patched_decoder_multi_resolution.py::decode`)
recomputes the full forward at every autoregressive step — stream + per-first-patch
normalization statistics are refreshed from the current sliding window, and the
coarse/fine contexts are rebuilt — and its RoPE attention explicitly refuses any KV
cache (`1.0/modeling/rope.py:71-72` raises `NotImplementedError`).

This is required by the architecture: CTSM's input normalization is global over the
current window, so any cached K/V from a prior step were computed with stale stats
and can't be reused without a mathematically wrong shortcut. Standard sliding-window
caches (Mistral / Gemma3 / Qwen2 `DynamicSlidingWindowLayer`) only manage which K/V
to retain; they don't re-project — so they're not applicable here.

Changes (modular file only; modeling regenerated):

* Remove `past_key_values` / `use_cache` from `CtsmModel.forward`, the decoder layer,
  and the attention block. Drop `_incremental_forward`, `_decode_step_full`,
  `_decode_step_incremental` and the `external_patch_stats` parameter on `_patchify`.
* `CtsmOutput` no longer carries `past_key_values`.
* `CtsmModelForPrediction.forward`'s AR loop is a single branch that calls
  `self.model(...)` with the current sliding-window context every step, mirroring the
  reference's loop body.
* Drop the `cache_utils.{Cache,DynamicCache}` import.
* Replace `test_kv_cache_matches_full_recompute` with `test_ar_decode_runs_long_horizon`
  (the cached path no longer exists).

Verification against `cisco-ai/cisco-time-series-model-1.0`:

  H=128: max diff 3.05e-5  rel 1.79e-7
  H=256: max diff 3.05e-5  rel 1.79e-7
  H=512: max diff 3.05e-5  rel 1.79e-7

All values are at fp32 noise level — match.
@vasqu

vasqu commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator

Does this need a review @kashif or still WIP? Sorry got lost in notis

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: auto, ctsm, timesfm, timesfm2_5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants