RWKV
Last updated
Last updated
The RWKV model was proposed in
It suggests a tweak in the traditional Transformer attention to make it linear. This way, the model can be used as recurrent network: passing inputs for timestamp 0 and timestamp 1 together is the same as passing inputs at timestamp 0, then inputs at timestamp 1 along with the state of timestamp 0 (see example below).
This can be more efficient than a regular Transformer and can deal with sentence of any length (even if the model uses a fixed context length for training).
This model was contributed by . The original code can be found .
Example of use as an RNN:
Copied
If you want to make sure the model stops generating when '\n\n'
is detected, we recommend using the following stopping criteria:
Copied
( vocab_size = 50277context_length = 1024hidden_size = 4096num_hidden_layers = 32attention_hidden_size = Noneintermediate_size = Nonelayer_norm_epsilon = 1e-05bos_token_id = 0eos_token_id = 0rescale_every = 6tie_word_embeddings = Falseuse_cache = True**kwargs )
Parameters
context_length (int
, optional, defaults to 1024) — The maximum sequence length that this model can be be used with in a single forward (using it in RNN mode lets use any sequence length).
hidden_size (int
, optional, defaults to 4096) — Dimensionality of the embeddings and hidden states.
num_hidden_layers (int
, optional, defaults to 32) — Number of hidden layers in the model.
attention_hidden_size (int
, optional) — Dimensionality of the attention hidden states. Will default to hidden_size
if unset.
intermediate_size (int
, optional) — Dimensionality of the inner feed-forward layers. Will default to 4 times hidden_size
if unset.
layer_norm_eps (float
, optional, defaults to 1e-5) — The epsilon to use in the layer normalization layers.
bos_token_id (int
, optional, defaults to 0) — The id of the beginning of sentence token in the vocabulary. Defaults to 0 as RWKV uses the same tokenizer as GPTNeoX.
eos_token_id (int
, optional, defaults to 0) — The id of the end of sentence token in the vocabulary. Defaults to 0 as RWKV uses the same tokenizer as GPTNeoX.
rescale_every (int
, optional, default to 6) — At inference, the hidden states (and weights of the correponding output layers) are divided by 2 every rescale_every
layer. If set to 0 or a negative number, no rescale is done.
tie_word_embeddings (bool
, optional, defaults to False
) — Whether or not to tie the word embeddings with the input token embeddings.
use_cache (bool
, optional, defaults to True
) — Whether or not the model should return the last state.
Example:
Copied
( config )
Parameters
The bare RWKV Model transformer outputting raw hidden-states without any specific head on top.
forward
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonestate: typing.Optional[typing.List[torch.FloatTensor]] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.rwkv.modeling_rwkv.RwkvOutput
or tuple(torch.FloatTensor)
Parameters
input_ids (torch.LongTensor
of shape (batch_size, input_ids_length)
) — input_ids_length
= sequence_length
if past_key_values
is None
else past_key_values[0][0].shape[-2]
(sequence_length
of input past key value states). Indices of input sequence tokens in the vocabulary.
If past_key_values
is used, only input_ids
that do not have their past calculated should be passed as input_ids
.
attention_mask (torch.LongTensor
of shape (batch_size, input_ids_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
1 for tokens that are not masked,
0 for tokens that are masked.
This is currently not used by RwkvModel
, but will be supported in the future.
inputs_embeds (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
state (tuple of five torch.FloatTensor
of shape (batch_size, hidden_size, num_hidden_layers)
, optional) — If passed along, the model uses the previous state in all the blocks (which will give the output for the input_ids
provided as if the model add state_input_ids + input_ids
as context).
use_cache (bool
, optional) — If set to True
, the last state is returned and can be used to quickly generate the next logits.
output_attentions (bool
, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail.
output_hidden_states (bool
, optional) — Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail.
Returns
transformers.models.rwkv.modeling_rwkv.RwkvOutput
or tuple(torch.FloatTensor)
last_hidden_state (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the model.
state (list of five torch.FloatTensor
of shape (batch_size, hidden_size, num_hidden_layers)
) — The state of the model at the last time step. Can be used in a forward method with the next input_ids
to avoid providing the old input_ids
.
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Example:
Copied
( config )
Parameters
The RWKV Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
forward
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonestate: typing.Optional[typing.List[torch.FloatTensor]] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.rwkv.modeling_rwkv.RwkvCausalLMOutput
or tuple(torch.FloatTensor)
Parameters
input_ids (torch.LongTensor
of shape (batch_size, input_ids_length)
) — input_ids_length
= sequence_length
if past_key_values
is None
else past_key_values[0][0].shape[-2]
(sequence_length
of input past key value states). Indices of input sequence tokens in the vocabulary.
If past_key_values
is used, only input_ids
that do not have their past calculated should be passed as input_ids
.
attention_mask (torch.LongTensor
of shape (batch_size, input_ids_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
1 for tokens that are not masked,
0 for tokens that are masked.
This is currently not used by RwkvModel
, but will be supported in the future.
inputs_embeds (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
state (tuple of five torch.FloatTensor
of shape (batch_size, hidden_size, num_hidden_layers)
, optional) — If passed along, the model uses the previous state in all the blocks (which will give the output for the input_ids
provided as if the model add state_input_ids + input_ids
as context).
use_cache (bool
, optional) — If set to True
, the last state is returned and can be used to quickly generate the next logits.
output_attentions (bool
, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail.
output_hidden_states (bool
, optional) — Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail.
labels (torch.LongTensor
of shape (batch_size, sequence_length)
, optional) — Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can set labels = input_ids
Indices are selected in [-100, 0, ..., config.vocab_size]
All labels set to -100
are ignored (masked), the loss is only computed for labels in [0, ..., config.vocab_size]
Returns
transformers.models.rwkv.modeling_rwkv.RwkvCausalLMOutput
or tuple(torch.FloatTensor)
loss (torch.FloatTensor
of shape (1,)
, optional, returned when labels
is provided) — Language modeling loss (for next-token prediction).
logits (torch.FloatTensor
of shape (batch_size, sequence_length, config.vocab_size)
) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
state (list of five torch.FloatTensor
of shape (batch_size, hidden_size, num_hidden_layers)
) — The state of the model at the last time step. Can be used in a forward method with the next input_ids
to avoid providing the old input_ids
.
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Example:
Copied
vocab_size (int
, optional, defaults to 50277) — Vocabulary size of the RWKV model. Defines the number of different tokens that can be represented by the inputs_ids
passed when calling .
This is the configuration class to store the configuration of a . It is used to instantiate a RWKV model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the RWVK-4 architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
config () — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.
This model inherits from . Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Indices can be obtained using . See and for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
A transformers.models.rwkv.modeling_rwkv.RwkvOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration () and inputs.
The forward method, overrides the __call__
special method.
config () — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.
This model inherits from . Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Indices can be obtained using . See and for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
A transformers.models.rwkv.modeling_rwkv.RwkvCausalLMOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration () and inputs.
The forward method, overrides the __call__
special method.