> ## Documentation Index
> Fetch the complete documentation index at: https://nixtlaverse.nixtla.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Time-LLM

> Time-LLM: Reprograms large language models for time series forecasting. Transforms forecasting tasks into language tasks using off-the-shelf LLM backbones.

Time-LLM is a reprogramming framework to repurpose LLMs for general time
series forecasting with the backbone language models kept intact. In
other words, it transforms a forecasting task into a “language task”
that can be tackled by an off-the-shelf LLM.

**References**

* [Ming Jin, Shiyu Wang, Lintao Ma, Zhixuan Chu,
  James Y. Zhang, Xiaoming Shi, Pin-Yu Chen, Yuxuan Liang, Yuan-Fang Li,
  Shirui Pan, Qingsong Wen. “Time-LLM: Time Series Forecasting by
  Reprogramming Large Language
  Models”](https://arxiv.org/abs/2310.01728)

![Figure 1. Time-LLM Architecture.](https://mintcdn.com/nixtla/wOkzptAA8LlzXeB0/neuralforecast/imgs_models/timellm.png?fit=max\&auto=format\&n=wOkzptAA8LlzXeB0\&q=85\&s=dadfbafee5ced5b903842e207a48a4d0)

*Figure 1. Time-LLM Architecture.*

## 1. Time-LLM

### `TimeLLM`

```python theme={null}
TimeLLM(
    h,
    input_size,
    patch_len=16,
    stride=8,
    d_ff=128,
    top_k=5,
    d_llm=768,
    d_model=32,
    n_heads=8,
    enc_in=7,
    dec_in=7,
    llm=None,
    llm_config=None,
    llm_tokenizer=None,
    llm_num_hidden_layers=32,
    llm_output_attention=True,
    llm_output_hidden_states=True,
    prompt_prefix=None,
    dropout=0.1,
    stat_exog_list=None,
    hist_exog_list=None,
    futr_exog_list=None,
    loss=MAE(),
    valid_loss=None,
    learning_rate=0.0001,
    max_steps=5,
    val_check_steps=100,
    batch_size=32,
    valid_batch_size=None,
    windows_batch_size=1024,
    inference_windows_batch_size=1024,
    start_padding_enabled=False,
    training_data_availability_threshold=0.0,
    step_size=1,
    num_lr_decays=0,
    early_stop_patience_steps=-1,
    val_monitor="ptl/val_loss",
    scaler_type="identity",
    random_seed=1,
    drop_last_loader=False,
    alias=None,
    optimizer=None,
    optimizer_kwargs=None,
    lr_scheduler=None,
    lr_scheduler_kwargs=None,
    dataloader_kwargs=None,
    **trainer_kwargs
)
```

Bases: `BaseModel`

TimeLLM

Time-LLM is a reprogramming framework to repurpose an off-the-shelf LLM for time series forecasting.

It trains a reprogramming layer that translates the observed series into a language task. This is fed to the LLM and an output
projection layer translates the output back to numerical predictions.

**Parameters:**

| Name | Type | Description | Default |
| - | - | - | - |
| `h` | `int` | Forecast horizon. | *required* |
| `input_size` | `int` | autorregresive inputs size, y=\[1,2,3,4] input\_size=2 -> y\_\[t-2:t]=\[1,2]. | *required* |
| `patch_len` | `int` | length of patch. Default: 16 | `16` |
| `stride` | `int` | stride of patch. Default: 8 | `8` |
| `d_ff` | `int` | dimension of fcn. Default: 128 | `128` |
| `top_k` | `int` | top tokens to consider. Default: 5 | `5` |
| `d_llm` | `int` | hidden dimension of LLM. Default: 768 # LLama7b:4096; GPT2-small:768; BERT-base:768 | `768` |
| `d_model` | `int` | dimension of model. Default: 32 | `32` |
| `n_heads` | `int` | number of heads in attention layer. Default: 8 | `8` |
| `enc_in` | `int` | encoder input size. Default: 7 | `7` |
| `dec_in` | `int` | decoder input size. Default: 7 | `7` |
| `llm` | `str` | Path to pretrained LLM model to use. If not specified, it will use GPT-2 from [https://huggingface.co/openai-community/gpt2](https://huggingface.co/openai-community/gpt2)" | `None` |
| `llm_config` | `dict` | Deprecated, configuration of LLM. If not specified, it will use the configuration of GPT-2 from [https://huggingface.co/openai-community/gpt2](https://huggingface.co/openai-community/gpt2)" | `None` |
| `llm_tokenizer` | `str` | Deprecated, tokenizer of LLM. If not specified, it will use the GPT-2 tokenizer from [https://huggingface.co/openai-community/gpt2](https://huggingface.co/openai-community/gpt2)" | `None` |
| `llm_num_hidden_layers` | `int` | hidden layers in LLM. Default: 32 | `32` |
| `llm_output_attention` | `bool` | whether to output attention in encoder. Default: True | `True` |
| `llm_output_hidden_states` | `bool` | whether to output hidden states. Default: True | `True` |
| `prompt_prefix` | `str` | prompt to inform the LLM about the dataset. Default: None | `None` |
| `dropout` | `float` | dropout rate. Default: 0.1 | `0.1` |
| `stat_exog_list` | `list` | static exogenous columns. | `None` |
| `hist_exog_list` | `list` | historic exogenous columns. | `None` |
| `futr_exog_list` | `list` | future exogenous columns. | `None` |
| `loss` | `PyTorch module` | instantiated train loss class from [losses collection](https://nixtlaverse.nixtla.io/neuralforecast/losses.pytorch.html.md). | `MAE()` |
| `valid_loss` | `PyTorch module` | instantiated valid loss class from [losses collection](https://nixtlaverse.nixtla.io/neuralforecast/losses.pytorch.html.md). | `None` |
| `learning_rate` | `float` | Learning rate between (0, 1). Default: 1e-3 | `0.0001` |
| `max_steps` | `int` | maximum number of training steps. Default: 1000 | `5` |
| `val_check_steps` | `int` | Number of training steps between every validation loss check. Default: 100 | `100` |
| `batch_size` | `int` | number of different series in each batch. Default: 32 | `32` |
| `valid_batch_size` | `int` | number of different series in each validation and test batch, if None uses batch\_size. Default: None | `None` |
| `windows_batch_size` | `int` | number of windows to sample in each training batch, default uses all. Default: 1024 | `1024` |
| `inference_windows_batch_size` | `int` | number of windows to sample in each inference batch. Default: 1024 | `1024` |
| `start_padding_enabled` | `bool` | if True, the model will pad the time series with zeros at the beginning, by input size. Default: False | `False` |
| `training_data_availability_threshold` | `Union[float, List[float]]` | minimum fraction of valid data points required for training windows. Single float applies to both insample and outsample; list of two floats specifies \[insample\_fraction, outsample\_fraction]. Default 0.0 allows windows with only 1 valid data point (current behavior). | `0.0` |
| `step_size` | `int` | step size between each window of temporal data. Default: 1 | `1` |
| `num_lr_decays` | `int` | Number of learning rate decays, evenly distributed across max\_steps. Default: -1 | `0` |
| `early_stop_patience_steps` | `int` | Number of validation iterations before early stopping. Default: -1 | `-1` |
| `val_monitor` | `str` | metric to monitor for early stopping. Valid options: "ptl/val\_loss", "valid\_loss", "train\_loss". Default: "ptl/val\_loss" | `'ptl/val_loss'` |
| `scaler_type` | `str` | type of scaler for temporal inputs normalization see [temporal scalers](https://github.com/Nixtla/neuralforecast/blob/main/neuralforecast/common/_scalers.py). Default: 'identity' | `'identity'` |
| `random_seed` | `int` | random\_seed for pytorch initializer and numpy generators. Default: 1 | `1` |
| `drop_last_loader` | `bool` | if True `TimeSeriesDataLoader` drops last non-full batch. Default: False | `False` |
| `alias` | `str` | optional, Custom name of the model. | `None` |
| `optimizer` | `Subclass of 'torch.optim.Optimizer'` | optional, user specified optimizer instead of the default choice (Adam). | `None` |
| `optimizer_kwargs` | `dict` | optional, list of parameters used by the user specified `optimizer`. | `None` |
| `lr_scheduler` | `Subclass of 'torch.optim.lr_scheduler.LRScheduler'` | optional, user specified lr\_scheduler instead of the default choice (StepLR). | `None` |
| `lr_scheduler_kwargs` | `dict` | optional, list of parameters used by the user specified `lr_scheduler`. | `None` |
| `dataloader_kwargs` | `dict` | optional, list of parameters passed into the PyTorch Lightning dataloader by the `TimeSeriesDataLoader`. | `None` |
| `**trainer_kwargs` | `int` | keyword trainer arguments inherited from [PyTorch Lightning's trainer](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer). | |

<details open markdown="1">
  <summary>References</summary>

  * [Ming Jin, Shiyu Wang, Lintao Ma, Zhixuan Chu, James Y. Zhang, Xiaoming Shi, Pin-Yu Chen, Yuxuan Liang, Yuan-Fang Li, Shirui Pan, Qingsong Wen. "Time-LLM: Time Series Forecasting by Reprogramming Large Language Models"](https://arxiv.org/abs/2310.01728)
</details>

#### `TimeLLM.fit`

```python theme={null}
fit(
    dataset, val_size=0, test_size=0, random_seed=None, distributed_config=None
)
```

Fit.

The `fit` method, optimizes the neural network's weights using the
initialization parameters (`learning_rate`, `windows_batch_size`, ...)
and the `loss` function as defined during the initialization.
Within `fit` we use a PyTorch Lightning `Trainer` that
inherits the initialization's `self.trainer_kwargs`, to customize
its inputs, see [PL's trainer arguments](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer).

The method is designed to be compatible with SKLearn-like classes
and in particular to be compatible with the StatsForecast library.

By default the `model` is not saving training checkpoints to protect
disk memory, to get them change `enable_checkpointing=True` in `__init__`.

**Parameters:**

| Name | Type | Description | Default |
| - | - | - | - |
| `dataset` | `TimeSeriesDataset` | NeuralForecast's `TimeSeriesDataset`, see [documentation](https://nixtlaverse.nixtla.io/neuralforecast/tsdataset.html.md). | *required* |
| `val_size` | `int` | Validation size for temporal cross-validation. | `0` |
| `random_seed` | `int` | Random seed for pytorch initializer and numpy generators, overwrites model.**init**'s. | `None` |
| `test_size` | `int` | Test size for temporal cross-validation. | `0` |

**Returns:**

| Type | Description |
| - | - |
| None | |

#### `TimeLLM.predict`

```python theme={null}
predict(
    dataset,
    test_size=None,
    step_size=1,
    random_seed=None,
    quantiles=None,
    h=None,
    explainer_config=None,
    **data_module_kwargs
)
```

Predict.

Neural network prediction with PL's `Trainer` execution of `predict_step`.

**Parameters:**

| Name | Type | Description | Default |
| - | - | - | - |
| `dataset` | `TimeSeriesDataset` | NeuralForecast's `TimeSeriesDataset`, see [documentation](https://nixtlaverse.nixtla.io/neuralforecast/tsdataset.html.md). | *required* |
| `test_size` | `int` | Test size for temporal cross-validation. | `None` |
| `step_size` | `int` | Step size between each window. | `1` |
| `random_seed` | `int` | Random seed for pytorch initializer and numpy generators, overwrites model.**init**'s. | `None` |
| `quantiles` | `list` | Target quantiles to predict. | `None` |
| `h` | `int` | Prediction horizon, if None, uses the model's fitted horizon. Defaults to None. | `None` |
| `explainer_config` | `dict` | configuration for explanations. | `None` |
| `**data_module_kwargs` | `dict` | PL's TimeSeriesDataModule args, see [documentation](https://pytorch-lightning.readthedocs.io/en/1.6.1/extensions/datamodules.html#using-a-datamodule). | |

**Returns:**

| Type | Description |
| - | - |
| None | |

### Usage example

```python theme={null}
import pandas as pd
import matplotlib.pyplot as plt

from neuralforecast import NeuralForecast
from neuralforecast.models import TimeLLM
from neuralforecast.utils import AirPassengersPanel

Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]] # 132 train
Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test

prompt_prefix = "The dataset contains data on monthly air passengers. There is a yearly seasonality"

timellm = TimeLLM(h=12,
                 input_size=36,
                 llm='openai-community/gpt2',
                 prompt_prefix=prompt_prefix,
                 batch_size=16,
                 valid_batch_size=16,
                 windows_batch_size=16)

nf = NeuralForecast(
    models=[timellm],
    freq='ME'
)

nf.fit(df=Y_train_df, val_size=12)
forecasts = nf.predict(futr_df=Y_test_df)
```

## 2. Auxiliary Functions

### `ReprogrammingLayer`

```python theme={null}
ReprogrammingLayer(
    d_model, n_heads, d_keys=None, d_llm=None, attention_dropout=0.1
)
```

Bases: `Module`

ReprogrammingLayer

### `FlattenHead`

```python theme={null}
FlattenHead(n_vars, nf, target_window, head_dropout=0)
```

Bases: `Module`

FlattenHead

### `PatchEmbedding`

```python theme={null}
PatchEmbedding(d_model, patch_len, stride, dropout)
```

Bases: `Module`

PatchEmbedding

### `TokenEmbedding`

```python theme={null}
TokenEmbedding(c_in, d_model)
```

Bases: `Module`

TokenEmbedding

### `ReplicationPad1d`

```python theme={null}
ReplicationPad1d(padding)
```

Bases: `Module`

ReplicationPad1d


## Related topics

- [Forecasting Models](https://nixtlaverse.nixtla.io/neuralforecast/docs/capabilities/overview.html.md)
- [Save and Load Models](https://nixtlaverse.nixtla.io/neuralforecast/docs/capabilities/save_load_models.html.md)
- [NN Modules](https://nixtlaverse.nixtla.io/neuralforecast/common.modules.html.md)
- [TimeMixer](https://nixtlaverse.nixtla.io/neuralforecast/models.timemixer.html.md)
- [TimesNet](https://nixtlaverse.nixtla.io/neuralforecast/models.timesnet.html.md)
