Skip to content

[ENH] Units_v2 Model added - #2165

Open
Muhammad-Rebaal wants to merge 42 commits into
sktime:mainfrom
Muhammad-Rebaal:units_v2
Open

[ENH] Units_v2 Model added#2165
Muhammad-Rebaal wants to merge 42 commits into
sktime:mainfrom
Muhammad-Rebaal:units_v2

Conversation

@Muhammad-Rebaal

@Muhammad-Rebaal Muhammad-Rebaal commented Mar 9, 2026

Copy link
Copy Markdown
Member

Fixes #2158

Hi @fkiraly , @phoeenniixx, @PranavBhatP !

I have implemented the UniTS (Unified Time Series Model) within the PyTorch Forecasting v2 architecture.

Could you please review the PR?

Here is a summary of the changes made:

  • Isolated Layer Abstraction (pytorch_forecasting/layers/_units/): Implemented the core neural network components (_PatchEmbedding, _PositionalEncoding, _TransformerBlock) completely isolated from the standard base estimating logic to strictly adhere to the project's v2 layer standards.
  • Model Construction (pytorch_forecasting/models/units/): Created the main UniTS wrapper which inherently inherits from TslibBaseModel and handles feature input alignments, channel-independence, and forward pass routing to the abstracted layers.
  • V2 Package Management: Established the UniTS_pkg_v2 class representing model metadata (authors, tags) and defined automated testing configurations (get_test_train_params).
  • Comprehensive Test Suite: Included a full Pytest harness for the model (tests/test_models/test_units_v2.py) validating parameter exceptions, tensor shapes, gradient flow bounds, and default hyperparameter states.

Thank you!

@codecov

codecov Bot commented Mar 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.17241% with 7 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@7bcf66c). Learn more about missing BASE report.

Files with missing lines Patch % Lines
pytorch_forecasting/models/units/_units_v2.py 91.13% 7 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2165   +/-   ##
=======================================
  Coverage        ?   87.57%           
=======================================
  Files           ?      180           
  Lines           ?    10308           
  Branches        ?        0           
=======================================
  Hits            ?     9027           
  Misses          ?     1281           
  Partials        ?        0           
Flag Coverage Δ
cpu 87.57% <95.17%> (?)
pytest 87.57% <95.17%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sohamukute sohamukute mentioned this pull request Mar 10, 2026
3 tasks

_tags = {
"info:name": "UniTS",
"authors": ["Muhammad-Rebaal"],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we should also credit the actual author of the model? The one who implemented it originally?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yeah sure, I'll add him as well

Comment thread pytorch_forecasting/models/units/_units_pkg_v2.py
Comment thread pytorch_forecasting/models/__init__.py Outdated
)
from pytorch_forecasting.models.tide import TiDEModel
from pytorch_forecasting.models.timexer import TimeXer
from pytorch_forecasting.models.units import UniTS_pkg_v2

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think you should add the model (and not the pkg) here?

"""
UniTS: Unified Time Series Model.

Patch-based transformer for multivariate time series forecasting.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think it would be good if you could also add the references (like GH link and the paper) here?

@phoeenniixx phoeenniixx added enhancement New feature or request module:models labels Mar 15, 2026
@Muhammad-Rebaal

Copy link
Copy Markdown
Member Author

Hi @phoeenniixx ,

Kindly review the PR, I've updated the PR with the requested changes.

Thank You.

import torch.nn as nn


class _PatchEmbedding(nn.Module):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

would it make sense to add it to _embeddings?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes I think it would make complete sense if we'd place it there in a file called _patch_embedding.py, as the _embeddings directory is already the designated home for embedding abstractions (like _data_embedding.py and _en_embedding.py).

return emb.mean(dim=1)


class _PositionalEncoding(nn.Module):

@phoeenniixx phoeenniixx Mar 22, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

it could go to layers/_encoders?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Actually its just a misinterpretation, it is an embedding not an encoder. We already have a PositionalEmbedding class in _embeddings/_positional_embedding.py doing the exact same math. Instead of duplicating that logic in an _encoder.py file, I created a _PositionalEmbedding child class inside the existing _positional_embedding.py file. It inherits the fixed sinusoidal buffer from the parent and adds the specific dropout and additive forward logic required for UniTS.

return self.drop(x + self.pe[:, : x.size(1), :])


class _TransformerBlock(nn.Module):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

should we add it to layer/_transforms or something?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think creating a new _transforms folder wouldn't be necessary here because it would be confusing for new contributors as transform and transformers are 2 different terminologies. Furthermore, we already have an established layers/_blocks/ directory. A transformer block is standard neural network block logic, so keeping it grouped with other blocks in layers/_blocks/_transformer_block.py works perfectly entirely to our existing layout.

@Muhammad-Rebaal

Copy link
Copy Markdown
Member Author

Hi @phoeenniixx ,
Kindly review the PR

@Muhammad-Rebaal

Copy link
Copy Markdown
Member Author

Hi @phoeenniixx,

Kindly review this and let me know if we're done with this one so I'd add the api-reference for this one.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

what is the use of this folder?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The model file already imports directly from the canonical locations. I'll remove the _units layer folder entirely.

Comment thread tests/test_models/test_units_v2.py Outdated
)


def test_basic_model_initialization(model, basic_metadata):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

i think test framework is enough for these tests?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, the extra tests are redundant I've removed that.

@phoeenniixx phoeenniixx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think it is almost ready. Just please de-duplicate the tests that can already being tested using the test framework

"info:name": "UniTS",
"info:compute": 4,
"authors": ["Muhammad-Rebaal", "gasvn", "sohamukute"],
"python_dependencies": ["torch"],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why do we need this? isnt torch already a core dep here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Actually I implemented this seeing the model extension v2. So I think I its an essential tag to be added torch as dependencies, not knowing the core-dep can't be added. Although I removed that.

{},
{
"patch_len": 8,
"stride": 4,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

please add some loss functions as well here - Is this model only compatible with point prediction losses, or can it also handle quantile and distribution losses?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

In the paper the model it is mentioned only about point prediction losses but we can extend it so I extend it to both quantile and distribution losses.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why do we have this file? I dont understand, it has just have a few fixtures and no clear tests are written,
Can you explain what this file is exactly doing?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Actually the model was initially implemented by the use of TslibBaseModel which later converted to EncoderDecoder so I removed those tests manually and new tests yet to be added which I added in my latest commit.

@phoeenniixx phoeenniixx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please remove the test file, or add some tests there - currently it feels like an AI hallucination

@Muhammad-Rebaal

Copy link
Copy Markdown
Member Author

Changes made in the recent commit:

  • removed the extra tag.
  • Added support of losses (quantile, distribution)
  • Write tests for the model.

return EncoderDecoderTimeSeriesDataModule

@classmethod
def get_base_test_params(cls):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

As I mentioned earlier, get_base_test_params is not going to work for now for v2
use get_test_train_params instead.
for that you need to remove pred_type, y_type tags

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

looping over all the losses is not a good idea rn for v2

@Muhammad-Rebaal Muhammad-Rebaal Jul 28, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Aren't these tags pred_type, y_type be removed from here : https://github.com/sktime/pytorch-forecasting/blob/main/extension_templates/v2/model_simple/model_pkg.py if these are part of get_base_test_params ?

looping over all the losses is not a good idea rn for v2

Can you suggest me the preferred ones ? so I'd add those

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Aren't these tags pred_type, y_type be removed from here : https://github.com/sktime/pytorch-forecasting/blob/main/extension_templates/v2/model_simple/model_pkg.py if these are part of get_base_test_params ?

I have reservations about this :)
Yes, we can remove this, but we will have to add it again, once the work on updating the test framework is done - which is the next work item on my list. As, we dont have much contributors around at this time, we can manage to ignore this. wdyt?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hmm, right

@Muhammad-Rebaal

Copy link
Copy Markdown
Member Author

Hi @phoeenniixx ,
I've made the following changes as mentioned:

  • Remove the tags and renamed get_base_test_params to get_test_train_params

Also I add another change:

  • Removed the Distribution loss because I didn't find any implementation of the Distribution loss in base_model_v2 ? If there's present kindly let me know I'd implement it...

instance. ``create_test_instance`` uses the first (or only) dictionary in
``params``.
"""
from pytorch_forecasting.metrics import NormalDistributionLoss, QuantileLoss

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I am not sure if DistributionLoss works well with v2 rn, does it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

No I didn't find any implementation as well that's why I asked you above. That's why in my last commit I remove the code implementation as well but forget to remove this dead import sorry for confusion

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Is there any open issue regarding the support of Distribution loss in v2 models ?

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

Labels

enhancement New feature or request module:models

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[ENH] Add v2 interface support for UniTS

3 participants