ml.models.architectures.rwkv
Defines modules for RWKV blocks.
RWKV blocks are similar to Transformer blocks, but use a different attention mechanism that doesn’t require a linearly growing KV cache.
Training requires CUDA kernel requires installing triton
:
pip install triton
- class ml.models.architectures.rwkv.WkvWithEps(*args, **kwargs)[source]
Bases:
Function
- static forward(ctx: FunctionCtx, w: Tensor, u: Tensor, k: Tensor, v: Tensor, state: Tensor) tuple[torch.Tensor, torch.Tensor] [source]
This function is to be overridden by all subclasses. There are two ways to define forward:
Usage 1 (Combined forward and ctx):
@staticmethod def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any: pass
It must accept a context ctx as the first argument, followed by any number of arguments (tensors or other types).
See combining-forward-context for more details
Usage 2 (Separate forward and ctx):
@staticmethod def forward(*args: Any, **kwargs: Any) -> Any: pass @staticmethod def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None: pass
The forward no longer accepts a ctx argument.
Instead, you must also override the
torch.autograd.Function.setup_context()
staticmethod to handle setting up thectx
object.output
is the output of the forward,inputs
are a Tuple of inputs to the forward.See extending-autograd for more details
The context can be used to store arbitrary data that can be then retrieved during the backward pass. Tensors should not be stored directly on ctx (though this is not currently enforced for backward compatibility). Instead, tensors should be saved either with
ctx.save_for_backward()
if they are intended to be used inbackward
(equivalently,vjp
) orctx.save_for_forward()
if they are intended to be used for injvp
.
- static backward(ctx: FunctionCtx, grad_wkv: Tensor, grad_state: Tensor) tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor] [source]
Defines a formula for differentiating the operation with backward mode automatic differentiation (alias to the vjp function).
This function is to be overridden by all subclasses.
It must accept a context
ctx
as the first argument, followed by as many outputs as theforward()
returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs toforward()
. Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.The context can be used to retrieve tensors saved during the forward pass. It also has an attribute
ctx.needs_input_grad
as a tuple of booleans representing whether each input needs gradient. E.g.,backward()
will havectx.needs_input_grad[0] = True
if the first input toforward()
needs gradient computed w.r.t. the output.
- ml.models.architectures.rwkv.wkv_with_eps(w: Tensor, u: Tensor, k: Tensor, v: Tensor, state: Tensor) tuple[torch.Tensor, torch.Tensor] [source]
Runs the core WKV computation.
- Parameters:
w – The decay tensor, with shape (D)
u – The output multiplier tensor, with shape (D)
k – The K tensor, with shape (B, T, D)
v – The V tensor, with shape (B, T, D)
state – The state tensor, with shape (B, 3, T, D), consisting of the alpha, beta and eps tensors, each with shape (B, 1, T, D)
- Returns:
The WKV tensor, with shape (B, T, D), and the next state, with shape (B, 3, 1, D), consisting of the next alpha, beta and eps tensors, each with shape (B, 1, 1, D)
- class ml.models.architectures.rwkv.WkvLogSpace(*args, **kwargs)[source]
Bases:
Function
- static forward(ctx: FunctionCtx, w: Tensor, u: Tensor, k: Tensor, v: Tensor, state: Tensor) tuple[torch.Tensor, torch.Tensor] [source]
This function is to be overridden by all subclasses. There are two ways to define forward:
Usage 1 (Combined forward and ctx):
@staticmethod def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any: pass
It must accept a context ctx as the first argument, followed by any number of arguments (tensors or other types).
See combining-forward-context for more details
Usage 2 (Separate forward and ctx):
@staticmethod def forward(*args: Any, **kwargs: Any) -> Any: pass @staticmethod def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None: pass
The forward no longer accepts a ctx argument.
Instead, you must also override the
torch.autograd.Function.setup_context()
staticmethod to handle setting up thectx
object.output
is the output of the forward,inputs
are a Tuple of inputs to the forward.See extending-autograd for more details
The context can be used to store arbitrary data that can be then retrieved during the backward pass. Tensors should not be stored directly on ctx (though this is not currently enforced for backward compatibility). Instead, tensors should be saved either with
ctx.save_for_backward()
if they are intended to be used inbackward
(equivalently,vjp
) orctx.save_for_forward()
if they are intended to be used for injvp
.
- static backward(ctx: FunctionCtx, grad_wkv: Tensor, grad_state: Tensor) tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor] [source]
Defines a formula for differentiating the operation with backward mode automatic differentiation (alias to the vjp function).
This function is to be overridden by all subclasses.
It must accept a context
ctx
as the first argument, followed by as many outputs as theforward()
returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs toforward()
. Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.The context can be used to retrieve tensors saved during the forward pass. It also has an attribute
ctx.needs_input_grad
as a tuple of booleans representing whether each input needs gradient. E.g.,backward()
will havectx.needs_input_grad[0] = True
if the first input toforward()
needs gradient computed w.r.t. the output.
- ml.models.architectures.rwkv.wkv_log_space(w: Tensor, u: Tensor, k: Tensor, v: Tensor, state: Tensor) tuple[torch.Tensor, torch.Tensor] [source]
Runs the core WKV computation.
- Parameters:
w – The decay tensor, with shape (D)
u – The output multiplier tensor, with shape (D)
k – The K tensor, with shape (B, T, D)
v – The V tensor, with shape (B, T, D)
state – The state tensor, with shape (B, 3, D), consisting of the alpha plus, alpha minus and beta tensors, each with shape (B, 1, D)
- Returns:
The WKV tensor, with shape (B, T, D), and the next state, with shape (B, 2, D), consisting of the next alpha plus, alpha minus and beta tensors, each with shape (B, 1, D)
- ml.models.architectures.rwkv.get_wkv_fn(key: Literal['eps', 'log']) Callable[[Tensor, Tensor, Tensor, Tensor, Tensor], tuple[torch.Tensor, torch.Tensor]] [source]
- ml.models.architectures.rwkv.get_wkv_fn_cuda(key: Literal['eps', 'log']) Callable[[Tensor, Tensor, Tensor, Tensor, Tensor], tuple[torch.Tensor, torch.Tensor]] [source]
- class ml.models.architectures.rwkv.RwkvAttention(dim: int, wkv_key: Literal['eps', 'log'] | None = None)[source]
Bases:
Module
Initializes internal Module state, shared by both nn.Module and ScriptModule.
- init_x: Tensor
- init_state: Tensor
- forward(x: Tensor, state: tuple[torch.Tensor, torch.Tensor] | None) tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]] [source]
Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
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 registered hooks while the latter silently ignores them.
- class ml.models.architectures.rwkv.RwkvFeedForward(dim: int, ffn_dim: int)[source]
Bases:
Module
Initializes internal Module state, shared by both nn.Module and ScriptModule.
- init_state: Tensor
- forward(x: Tensor, state: Tensor | None = None) tuple[torch.Tensor, torch.Tensor] [source]
Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
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 registered hooks while the latter silently ignores them.
- class ml.models.architectures.rwkv.RwkvBlock(emb_dim: int, pre_norm: bool, wkv_key: Literal['eps', 'log'] | None = None)[source]
Bases:
Module
Initializes internal Module state, shared by both nn.Module and ScriptModule.
- run_attn(x: Tensor, state: tuple[tuple[torch.Tensor, torch.Tensor], torch.Tensor] | None = None) tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]] [source]
- run_ffn(x: Tensor, state: tuple[tuple[torch.Tensor, torch.Tensor], torch.Tensor] | None = None) tuple[torch.Tensor, torch.Tensor] [source]
- forward(x: Tensor, state: tuple[tuple[torch.Tensor, torch.Tensor], torch.Tensor] | None = None) tuple[torch.Tensor, tuple[tuple[torch.Tensor, torch.Tensor], torch.Tensor]] [source]
Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
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 registered hooks while the latter silently ignores them.
- class ml.models.architectures.rwkv.RwkvStack(emb_dim: int, num_layers: int, wkv_key: Literal['eps', 'log'] | None = None)[source]
Bases:
Module
Defines a stack of RWKV modules.
- Parameters:
emb_dim – The number of embedding dimensions in each block
num_layers – The number of layers in the stack
wkv_key – The WKV algorithm to use
- Inputs:
x: The input tensor, with shape
(B, T, D)
state: The previous state- Outputs:
The output tensor, with shape
(B, T, D)
, and the next state
Initializes internal Module state, shared by both nn.Module and ScriptModule.
- forward(x: Tensor, state: list[tuple[tuple[torch.Tensor, torch.Tensor], torch.Tensor]] | None = None) tuple[torch.Tensor, list[tuple[tuple[torch.Tensor, torch.Tensor], torch.Tensor]]] [source]
Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
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 registered hooks while the latter silently ignores them.