Skip to content

rwkv

mindnlp.transformers.models.rwkv.modeling_rwkv

MindSpore RWKV model.

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvBlock

Bases: Module

RWKV block

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
class RwkvBlock(nn.Module):
    """RWKV block"""
    def __init__(self, config, layer_id):
        """
        Initialize the RwkvBlock.

        Args:
            self: The instance of the RwkvBlock class.
            config:
                An object containing configuration settings for the block.

                - Type: object
                - Purpose: Specifies the configuration settings for the block.
            layer_id:
                An integer representing the layer id.

                - Type: int
                - Purpose: Identifies the layer to which the block belongs.
                - Restrictions: Must be a non-negative integer.

        Returns:
            None.

        Raises:
            ValueError: If layer_id is a negative integer.
        """
        super().__init__()
        self.config = config
        self.layer_id = layer_id

        if layer_id == 0:
            self.pre_ln = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_epsilon)

        self.ln1 = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_epsilon)
        self.ln2 = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_epsilon)

        self.attention = RwkvSelfAttention(config, layer_id)
        self.feed_forward = RwkvFeedForward(config, layer_id)

    def forward(self, hidden, state=None, use_cache=False, output_attentions=False):
        """
        Method to forward a RwkvBlock.

        Args:
            self: The instance of the RwkvBlock class.
            hidden (Tensor): The input hidden tensor to be processed.
            state (Tensor, optional): The current state tensor. Defaults to None.
            use_cache (bool, optional): Flag indicating whether to use cache. Defaults to False.
            output_attentions (bool): Flag indicating whether to output attentions.

        Returns:
            Tuple: A tuple containing the processed hidden tensor and the updated state tensor.
                If output_attentions is True, the tuple also includes the attention tensor; otherwise, it includes None.

        Raises:
            None.
        """
        if self.layer_id == 0:
            hidden = self.pre_ln(hidden)

        attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache)
        hidden = hidden + attention

        feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
        hidden = hidden + feed_forward

        outputs = (hidden, state)
        if output_attentions:
            outputs += (attention,)
        else:
            outputs += (None,)

        return outputs

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvBlock.__init__(config, layer_id)

Initialize the RwkvBlock.

PARAMETER DESCRIPTION
self

The instance of the RwkvBlock class.

config

An object containing configuration settings for the block.

  • Type: object
  • Purpose: Specifies the configuration settings for the block.

layer_id

An integer representing the layer id.

  • Type: int
  • Purpose: Identifies the layer to which the block belongs.
  • Restrictions: Must be a non-negative integer.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If layer_id is a negative integer.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def __init__(self, config, layer_id):
    """
    Initialize the RwkvBlock.

    Args:
        self: The instance of the RwkvBlock class.
        config:
            An object containing configuration settings for the block.

            - Type: object
            - Purpose: Specifies the configuration settings for the block.
        layer_id:
            An integer representing the layer id.

            - Type: int
            - Purpose: Identifies the layer to which the block belongs.
            - Restrictions: Must be a non-negative integer.

    Returns:
        None.

    Raises:
        ValueError: If layer_id is a negative integer.
    """
    super().__init__()
    self.config = config
    self.layer_id = layer_id

    if layer_id == 0:
        self.pre_ln = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_epsilon)

    self.ln1 = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_epsilon)
    self.ln2 = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_epsilon)

    self.attention = RwkvSelfAttention(config, layer_id)
    self.feed_forward = RwkvFeedForward(config, layer_id)

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvBlock.forward(hidden, state=None, use_cache=False, output_attentions=False)

Method to forward a RwkvBlock.

PARAMETER DESCRIPTION
self

The instance of the RwkvBlock class.

hidden

The input hidden tensor to be processed.

TYPE: Tensor

state

The current state tensor. Defaults to None.

TYPE: Tensor DEFAULT: None

use_cache

Flag indicating whether to use cache. Defaults to False.

TYPE: bool DEFAULT: False

output_attentions

Flag indicating whether to output attentions.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Tuple

A tuple containing the processed hidden tensor and the updated state tensor. If output_attentions is True, the tuple also includes the attention tensor; otherwise, it includes None.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def forward(self, hidden, state=None, use_cache=False, output_attentions=False):
    """
    Method to forward a RwkvBlock.

    Args:
        self: The instance of the RwkvBlock class.
        hidden (Tensor): The input hidden tensor to be processed.
        state (Tensor, optional): The current state tensor. Defaults to None.
        use_cache (bool, optional): Flag indicating whether to use cache. Defaults to False.
        output_attentions (bool): Flag indicating whether to output attentions.

    Returns:
        Tuple: A tuple containing the processed hidden tensor and the updated state tensor.
            If output_attentions is True, the tuple also includes the attention tensor; otherwise, it includes None.

    Raises:
        None.
    """
    if self.layer_id == 0:
        hidden = self.pre_ln(hidden)

    attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache)
    hidden = hidden + attention

    feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
    hidden = hidden + feed_forward

    outputs = (hidden, state)
    if output_attentions:
        outputs += (attention,)
    else:
        outputs += (None,)

    return outputs

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvCausalLMOutput dataclass

Bases: ModelOutput

Base class for causal language model (or autoregressive) outputs.

PARAMETER DESCRIPTION
loss

Language modeling loss (for next-token prediction).

TYPE: `mindspore.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided DEFAULT: None

logits

Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

TYPE: `mindspore.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)` DEFAULT: None

state

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.

TYPE: list of five `mindspore.Tensor` of shape `(batch_size, hidden_size, num_hidden_layers)` DEFAULT: None

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
@dataclass
class RwkvCausalLMOutput(ModelOutput):
    """
    Base class for causal language model (or autoregressive) outputs.

    Args:
        loss (`mindspore.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`mindspore.Tensor` 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 `mindspore.Tensor` 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(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed
            or when `config.output_hidden_states=True`):
            Tuple of `mindspore.Tensor` (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(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed
            or when `config.output_attentions=True`):
            Tuple of `mindspore.Tensor` (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.
    """
    loss: Optional[mindspore.Tensor] = None
    logits: mindspore.Tensor = None
    state: Optional[List[mindspore.Tensor]] = None
    hidden_states: Optional[Tuple[mindspore.Tensor, ...]] = None
    attentions: Optional[Tuple[mindspore.Tensor, ...]] = None

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvFeedForward

Bases: Module

RWKV feed forward

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
class RwkvFeedForward(nn.Module):
    """RWKV feed forward"""
    def __init__(self, config, layer_id=0):
        """
        Initializes a new instance of the RwkvFeedForward class.

        Args:
            self: The instance of the RwkvFeedForward class.
            config:
                The configuration for the feedforward layer, containing the hidden size and intermediate size parameters.

                - Type: object
                - Purpose: Specifies the configuration settings for the feedforward layer.
                - Restrictions: None
            layer_id:
                The ID of the layer.

                - ype: int
                - Purpose: Specifies the ID of the layer.
                - Restrictions: Defaults to 0 if not provided.

        Returns:
            None.

        Raises:
            None
        """
        super().__init__()
        self.config = config
        self.layer_id = layer_id
        hidden_size = config.hidden_size
        intermediate_size = (
            config.intermediate_size if config.intermediate_size is not None else 4 * config.hidden_size
        )

        self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
        self.time_mix_key = Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_key')
        self.time_mix_receptance =Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_receptance')

        self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
        self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
        self.value = nn.Linear(intermediate_size, hidden_size, bias=False)

    def forward(self, hidden, state=None):
        """
        This method 'forward' is defined in the class 'RwkvFeedForward' and is responsible for forwarding the value
        and state based on the input parameters.

        Args:
            self: The instance of the RwkvFeedForward class.
            hidden (array): The input array representing the hidden state. It is used to calculate the key, value,
                and receptance. The array should have the shape (batch_size, sequence_length, feature_dim).
            state (array, optional): The optional input array representing the state. It is used for calculating
                the shifted value. If provided, it should have the same shape as 'hidden' (batch_size, sequence_length,
                feature_dim). Default is None.

        Returns:
            tuple: A tuple containing the calculated receptance and the updated state.
                The receptance is a weighted value based on the key and shifted values.
                The updated state represents the modified state based on the input hidden array.

        Raises:
            ValueError: If the shape of the 'hidden' array is not compatible for the calculations required in the method.
            IndexError: If the 'state' is provided and its shape does not match with the 'hidden' array.
            TypeError: If the input parameters are not of the expected type.
        """
        if hidden.shape[1] == 1 and state is not None:
            shifted = state[0][:, :, self.layer_id]
        else:
            shifted = self.time_shift(hidden)
            if state is not None:
                shifted[:, 0] = state[0][:, :, self.layer_id]
        key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
        receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)

        key = ops.square(ops.relu(self.key(key)))
        value = self.value(key)
        receptance = ops.sigmoid(self.receptance(receptance))

        if state is not None:
            state[0][:, :, self.layer_id] = hidden[:, -1]

        return receptance * value, state

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvFeedForward.__init__(config, layer_id=0)

Initializes a new instance of the RwkvFeedForward class.

PARAMETER DESCRIPTION
self

The instance of the RwkvFeedForward class.

config

The configuration for the feedforward layer, containing the hidden size and intermediate size parameters.

  • Type: object
  • Purpose: Specifies the configuration settings for the feedforward layer.
  • Restrictions: None

layer_id

The ID of the layer.

  • ype: int
  • Purpose: Specifies the ID of the layer.
  • Restrictions: Defaults to 0 if not provided.

DEFAULT: 0

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def __init__(self, config, layer_id=0):
    """
    Initializes a new instance of the RwkvFeedForward class.

    Args:
        self: The instance of the RwkvFeedForward class.
        config:
            The configuration for the feedforward layer, containing the hidden size and intermediate size parameters.

            - Type: object
            - Purpose: Specifies the configuration settings for the feedforward layer.
            - Restrictions: None
        layer_id:
            The ID of the layer.

            - ype: int
            - Purpose: Specifies the ID of the layer.
            - Restrictions: Defaults to 0 if not provided.

    Returns:
        None.

    Raises:
        None
    """
    super().__init__()
    self.config = config
    self.layer_id = layer_id
    hidden_size = config.hidden_size
    intermediate_size = (
        config.intermediate_size if config.intermediate_size is not None else 4 * config.hidden_size
    )

    self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
    self.time_mix_key = Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_key')
    self.time_mix_receptance =Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_receptance')

    self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
    self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
    self.value = nn.Linear(intermediate_size, hidden_size, bias=False)

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvFeedForward.forward(hidden, state=None)

This method 'forward' is defined in the class 'RwkvFeedForward' and is responsible for forwarding the value and state based on the input parameters.

PARAMETER DESCRIPTION
self

The instance of the RwkvFeedForward class.

hidden

The input array representing the hidden state. It is used to calculate the key, value, and receptance. The array should have the shape (batch_size, sequence_length, feature_dim).

TYPE: array

state

The optional input array representing the state. It is used for calculating the shifted value. If provided, it should have the same shape as 'hidden' (batch_size, sequence_length, feature_dim). Default is None.

TYPE: array DEFAULT: None

RETURNS DESCRIPTION
tuple

A tuple containing the calculated receptance and the updated state. The receptance is a weighted value based on the key and shifted values. The updated state represents the modified state based on the input hidden array.

RAISES DESCRIPTION
ValueError

If the shape of the 'hidden' array is not compatible for the calculations required in the method.

IndexError

If the 'state' is provided and its shape does not match with the 'hidden' array.

TypeError

If the input parameters are not of the expected type.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
def forward(self, hidden, state=None):
    """
    This method 'forward' is defined in the class 'RwkvFeedForward' and is responsible for forwarding the value
    and state based on the input parameters.

    Args:
        self: The instance of the RwkvFeedForward class.
        hidden (array): The input array representing the hidden state. It is used to calculate the key, value,
            and receptance. The array should have the shape (batch_size, sequence_length, feature_dim).
        state (array, optional): The optional input array representing the state. It is used for calculating
            the shifted value. If provided, it should have the same shape as 'hidden' (batch_size, sequence_length,
            feature_dim). Default is None.

    Returns:
        tuple: A tuple containing the calculated receptance and the updated state.
            The receptance is a weighted value based on the key and shifted values.
            The updated state represents the modified state based on the input hidden array.

    Raises:
        ValueError: If the shape of the 'hidden' array is not compatible for the calculations required in the method.
        IndexError: If the 'state' is provided and its shape does not match with the 'hidden' array.
        TypeError: If the input parameters are not of the expected type.
    """
    if hidden.shape[1] == 1 and state is not None:
        shifted = state[0][:, :, self.layer_id]
    else:
        shifted = self.time_shift(hidden)
        if state is not None:
            shifted[:, 0] = state[0][:, :, self.layer_id]
    key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
    receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)

    key = ops.square(ops.relu(self.key(key)))
    value = self.value(key)
    receptance = ops.sigmoid(self.receptance(receptance))

    if state is not None:
        state[0][:, :, self.layer_id] = hidden[:, -1]

    return receptance * value, state

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvForCausalLM

Bases: RwkvPreTrainedModel

RWKV for causal LM

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
class RwkvForCausalLM(RwkvPreTrainedModel):
    """RWKV for causal LM"""
    _tied_weights_keys = ["head.weight"]

    def __init__(self, config):
        """
        Initializes an instance of the RwkvForCausalLM class.

        Args:
            self (RwkvForCausalLM): The instance of the RwkvForCausalLM class.
            config (object): The configuration object containing various settings for the model.

        Returns:
            None

        Raises:
            None
        """
        super().__init__(config)
        self.rwkv = RwkvModel(config)
        self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        # Initialize weights and apply final processing
        self.post_init()

    def get_output_embeddings(self):
        """get output embeddings"""
        return self.head

    def set_output_embeddings(self, new_embeddings):
        """set output embeddings"""
        self.head = new_embeddings

    def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
        """prepare inputs"""
        # only last token for inputs_ids if the state is passed along.
        if state is not None:
            input_ids = input_ids[:, -1].unsqueeze(-1)

        # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
        if inputs_embeds is not None and state is None:
            model_inputs = {"inputs_embeds": inputs_embeds}
        else:
            model_inputs = {"input_ids": input_ids}

        model_inputs["state"] = state
        return model_inputs

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,  # noqa
        inputs_embeds: Optional[mindspore.Tensor] = None,
        state: Optional[List[mindspore.Tensor]] = None,
        labels: Optional[mindspore.Tensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, RwkvCausalLMOutput]:
        r"""
        Args:
            labels (`mindspore.Tensor` 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]`
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        rwkv_outputs = self.rwkv(
            input_ids,
            inputs_embeds=inputs_embeds,
            state=state,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        hidden_states = rwkv_outputs[0]

        logits = self.head(hidden_states)

        loss = None
        if labels is not None:
            # Shift so that tokens < n predict n
            shift_logits = logits[..., :-1, :]
            shift_labels = labels[..., 1:]
            # Flatten the tokens
            loss = ops.cross_entropy(shift_logits.view(-1, shift_logits.shape[-1]), shift_labels.view(-1))

        if not return_dict:
            output = (logits,) + rwkv_outputs[1:]
            return ((loss,) + output) if loss is not None else output

        return RwkvCausalLMOutput(
            loss=loss,
            logits=logits,
            state=rwkv_outputs.state,
            hidden_states=rwkv_outputs.hidden_states,
            attentions=rwkv_outputs.attentions,
        )

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvForCausalLM.__init__(config)

Initializes an instance of the RwkvForCausalLM class.

PARAMETER DESCRIPTION
self

The instance of the RwkvForCausalLM class.

TYPE: RwkvForCausalLM

config

The configuration object containing various settings for the model.

TYPE: object

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
def __init__(self, config):
    """
    Initializes an instance of the RwkvForCausalLM class.

    Args:
        self (RwkvForCausalLM): The instance of the RwkvForCausalLM class.
        config (object): The configuration object containing various settings for the model.

    Returns:
        None

    Raises:
        None
    """
    super().__init__(config)
    self.rwkv = RwkvModel(config)
    self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvForCausalLM.forward(input_ids=None, attention_mask=None, inputs_embeds=None, state=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

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]

TYPE: `mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional* DEFAULT: None

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,  # noqa
    inputs_embeds: Optional[mindspore.Tensor] = None,
    state: Optional[List[mindspore.Tensor]] = None,
    labels: Optional[mindspore.Tensor] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, RwkvCausalLMOutput]:
    r"""
    Args:
        labels (`mindspore.Tensor` 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]`
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    rwkv_outputs = self.rwkv(
        input_ids,
        inputs_embeds=inputs_embeds,
        state=state,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    hidden_states = rwkv_outputs[0]

    logits = self.head(hidden_states)

    loss = None
    if labels is not None:
        # Shift so that tokens < n predict n
        shift_logits = logits[..., :-1, :]
        shift_labels = labels[..., 1:]
        # Flatten the tokens
        loss = ops.cross_entropy(shift_logits.view(-1, shift_logits.shape[-1]), shift_labels.view(-1))

    if not return_dict:
        output = (logits,) + rwkv_outputs[1:]
        return ((loss,) + output) if loss is not None else output

    return RwkvCausalLMOutput(
        loss=loss,
        logits=logits,
        state=rwkv_outputs.state,
        hidden_states=rwkv_outputs.hidden_states,
        attentions=rwkv_outputs.attentions,
    )

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvForCausalLM.get_output_embeddings()

get output embeddings

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
850
851
852
def get_output_embeddings(self):
    """get output embeddings"""
    return self.head

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvForCausalLM.prepare_inputs_for_generation(input_ids, state=None, inputs_embeds=None, **kwargs)

prepare inputs

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
858
859
860
861
862
863
864
865
866
867
868
869
870
871
def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
    """prepare inputs"""
    # only last token for inputs_ids if the state is passed along.
    if state is not None:
        input_ids = input_ids[:, -1].unsqueeze(-1)

    # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
    if inputs_embeds is not None and state is None:
        model_inputs = {"inputs_embeds": inputs_embeds}
    else:
        model_inputs = {"input_ids": input_ids}

    model_inputs["state"] = state
    return model_inputs

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvForCausalLM.set_output_embeddings(new_embeddings)

set output embeddings

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
854
855
856
def set_output_embeddings(self, new_embeddings):
    """set output embeddings"""
    self.head = new_embeddings

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvLinearAttention

Bases: Module

RWKV linear attention

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
class RwkvLinearAttention(nn.Module):
    """RWKV linear attention"""
    def __init__(self, config):
        """
        Initializes an instance of the RwkvLinearAttention class.

        Args:
            self (RwkvLinearAttention): The instance of the RwkvLinearAttention class.
            config (object): The configuration object containing the context length parameter.
                It is used to set the maximum sequence length and load CUDA kernels.
                Must have the attribute 'context_length' specifying the context length.

        Returns:
            None.

        Raises:
            KeyError: If the 'config' object does not have the 'context_length' attribute.
            RuntimeError: If there is an issue loading the CUDA kernels.
        """
        super().__init__()
        self.max_seq_length = config.context_length
        self.wkv_forward_with_state = load_wkv_cuda_kernel('wkv_forward_with_state', config.context_length)
        self.wkv_forward = load_wkv_cuda_kernel('wkv_forward', config.context_length)

        self.wkv_backward = load_wkv_cuda_kernel('wkv_backward', config.context_length)

    def forward(self, time_decay, time_first, key, value, state=None, return_state=False):
        """
        Constructs the linear attention mechanism for the RwkvLinearAttention class.

        Args:
            self: The instance of the RwkvLinearAttention class.
            time_decay (Union[int, float]): The time decay factor for the attention mechanism.
            time_first (Union[int, float]): The time first factor for the attention mechanism.
            key (Tensor): The input tensor representing the keys for the attention mechanism. 
                The shape of the tensor should be (batch_size, seq_len, hidden_size).
            value (Tensor): The input tensor representing the values for the attention mechanism. 
                The shape of the tensor should be (batch_size, seq_len, hidden_size).
            state (Tensor, optional): The optional input tensor representing the state for the attention mechanism. 
                It has a default value of None. The shape of the tensor should be (batch_size, hidden_size, 3).
            return_state (bool, optional): A flag indicating whether to return the state. 
                It has a default value of False.

        Returns:
            Tuple[Tensor, Tensor]: A tuple containing the output tensor of the attention mechanism 
            and the state tensor if return_state is True. The output tensor represents the result of
            the attention mechanism.
            The state tensor represents the updated state of the attention mechanism if return_state is True.

        Raises:
            ValueError: If the sequence length is greater than the maximum sequence length allowed by the model.
            ValueError: If the product of batch size and hidden size is not a round multiple of the minimum of the
                hidden size and 32.
        """
        batch_size, seq_len, hidden_size = key.shape
        if seq_len > self.max_seq_length:
            raise ValueError(
                f"Cannot process a batch with {seq_len} tokens at the same time, use a maximum of "
                f"{self.max_seq_length} with this model."
            )
        if batch_size * hidden_size % min(hidden_size, 32) != 0:
            raise ValueError(
                f"The product of batch size ({batch_size}) and hidden size ({hidden_size}) needs to be a round "
                f"multiple of {min(hidden_size, 32)}."
            )

        input_dtype = key.dtype

        time_decay = ops.neg(ops.exp(time_decay.astype(mindspore.float32)))
        if key.dtype == mindspore.float16:
            time_first = time_first.astype(mindspore.float32)
            key = key.astype(mindspore.float32)
            value = value.astype(mindspore.float32)
        # The CUDA kernel will fill this tensor.

        if return_state:
            if state is None:
                state = ops.zeros((batch_size, hidden_size, 3), dtype=mindspore.float32)
                state[:, :, 2] -= 1e38
            else:
                state = ops.cat([s.expand_dims(2) for s in state], axis=2)
            output = self.wkv_forward_with_state(time_decay, time_first, key, value, state)
        else:
            output = self.wkv_forward(time_decay, time_first, key, value)

        if state is not None:
            state = [s.squeeze(2) for s in ops.chunk(state, 3, axis=2)]

        return output.astype(input_dtype), state

    # g stands for grad
    def bprop(self, w, u, k, v, s, return_state, y, gy):
        """bporp for wkv"""
        dtype = k.dtype
        k = k.astype(mindspore.float32)
        v = v.astype(mindspore.float32)
        gy = gy[0].astype(mindspore.float32)
        gw, gu, gk, gv = self.wkv_backward(w, u, k, v, gy)
        gw = ops.sum(gw, 0)
        gu = ops.sum(gu, 0)

        return (gw, gu, gk.astype(dtype), gv.astype(dtype))

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvLinearAttention.__init__(config)

Initializes an instance of the RwkvLinearAttention class.

PARAMETER DESCRIPTION
self

The instance of the RwkvLinearAttention class.

TYPE: RwkvLinearAttention

config

The configuration object containing the context length parameter. It is used to set the maximum sequence length and load CUDA kernels. Must have the attribute 'context_length' specifying the context length.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
KeyError

If the 'config' object does not have the 'context_length' attribute.

RuntimeError

If there is an issue loading the CUDA kernels.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def __init__(self, config):
    """
    Initializes an instance of the RwkvLinearAttention class.

    Args:
        self (RwkvLinearAttention): The instance of the RwkvLinearAttention class.
        config (object): The configuration object containing the context length parameter.
            It is used to set the maximum sequence length and load CUDA kernels.
            Must have the attribute 'context_length' specifying the context length.

    Returns:
        None.

    Raises:
        KeyError: If the 'config' object does not have the 'context_length' attribute.
        RuntimeError: If there is an issue loading the CUDA kernels.
    """
    super().__init__()
    self.max_seq_length = config.context_length
    self.wkv_forward_with_state = load_wkv_cuda_kernel('wkv_forward_with_state', config.context_length)
    self.wkv_forward = load_wkv_cuda_kernel('wkv_forward', config.context_length)

    self.wkv_backward = load_wkv_cuda_kernel('wkv_backward', config.context_length)

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvLinearAttention.bprop(w, u, k, v, s, return_state, y, gy)

bporp for wkv

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
172
173
174
175
176
177
178
179
180
181
182
def bprop(self, w, u, k, v, s, return_state, y, gy):
    """bporp for wkv"""
    dtype = k.dtype
    k = k.astype(mindspore.float32)
    v = v.astype(mindspore.float32)
    gy = gy[0].astype(mindspore.float32)
    gw, gu, gk, gv = self.wkv_backward(w, u, k, v, gy)
    gw = ops.sum(gw, 0)
    gu = ops.sum(gu, 0)

    return (gw, gu, gk.astype(dtype), gv.astype(dtype))

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvLinearAttention.forward(time_decay, time_first, key, value, state=None, return_state=False)

Constructs the linear attention mechanism for the RwkvLinearAttention class.

PARAMETER DESCRIPTION
self

The instance of the RwkvLinearAttention class.

time_decay

The time decay factor for the attention mechanism.

TYPE: Union[int, float]

time_first

The time first factor for the attention mechanism.

TYPE: Union[int, float]

key

The input tensor representing the keys for the attention mechanism. The shape of the tensor should be (batch_size, seq_len, hidden_size).

TYPE: Tensor

value

The input tensor representing the values for the attention mechanism. The shape of the tensor should be (batch_size, seq_len, hidden_size).

TYPE: Tensor

state

The optional input tensor representing the state for the attention mechanism. It has a default value of None. The shape of the tensor should be (batch_size, hidden_size, 3).

TYPE: Tensor DEFAULT: None

return_state

A flag indicating whether to return the state. It has a default value of False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

Tuple[Tensor, Tensor]: A tuple containing the output tensor of the attention mechanism

and the state tensor if return_state is True. The output tensor represents the result of

the attention mechanism.

The state tensor represents the updated state of the attention mechanism if return_state is True.

RAISES DESCRIPTION
ValueError

If the sequence length is greater than the maximum sequence length allowed by the model.

ValueError

If the product of batch size and hidden size is not a round multiple of the minimum of the hidden size and 32.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def forward(self, time_decay, time_first, key, value, state=None, return_state=False):
    """
    Constructs the linear attention mechanism for the RwkvLinearAttention class.

    Args:
        self: The instance of the RwkvLinearAttention class.
        time_decay (Union[int, float]): The time decay factor for the attention mechanism.
        time_first (Union[int, float]): The time first factor for the attention mechanism.
        key (Tensor): The input tensor representing the keys for the attention mechanism. 
            The shape of the tensor should be (batch_size, seq_len, hidden_size).
        value (Tensor): The input tensor representing the values for the attention mechanism. 
            The shape of the tensor should be (batch_size, seq_len, hidden_size).
        state (Tensor, optional): The optional input tensor representing the state for the attention mechanism. 
            It has a default value of None. The shape of the tensor should be (batch_size, hidden_size, 3).
        return_state (bool, optional): A flag indicating whether to return the state. 
            It has a default value of False.

    Returns:
        Tuple[Tensor, Tensor]: A tuple containing the output tensor of the attention mechanism 
        and the state tensor if return_state is True. The output tensor represents the result of
        the attention mechanism.
        The state tensor represents the updated state of the attention mechanism if return_state is True.

    Raises:
        ValueError: If the sequence length is greater than the maximum sequence length allowed by the model.
        ValueError: If the product of batch size and hidden size is not a round multiple of the minimum of the
            hidden size and 32.
    """
    batch_size, seq_len, hidden_size = key.shape
    if seq_len > self.max_seq_length:
        raise ValueError(
            f"Cannot process a batch with {seq_len} tokens at the same time, use a maximum of "
            f"{self.max_seq_length} with this model."
        )
    if batch_size * hidden_size % min(hidden_size, 32) != 0:
        raise ValueError(
            f"The product of batch size ({batch_size}) and hidden size ({hidden_size}) needs to be a round "
            f"multiple of {min(hidden_size, 32)}."
        )

    input_dtype = key.dtype

    time_decay = ops.neg(ops.exp(time_decay.astype(mindspore.float32)))
    if key.dtype == mindspore.float16:
        time_first = time_first.astype(mindspore.float32)
        key = key.astype(mindspore.float32)
        value = value.astype(mindspore.float32)
    # The CUDA kernel will fill this tensor.

    if return_state:
        if state is None:
            state = ops.zeros((batch_size, hidden_size, 3), dtype=mindspore.float32)
            state[:, :, 2] -= 1e38
        else:
            state = ops.cat([s.expand_dims(2) for s in state], axis=2)
        output = self.wkv_forward_with_state(time_decay, time_first, key, value, state)
    else:
        output = self.wkv_forward(time_decay, time_first, key, value)

    if state is not None:
        state = [s.squeeze(2) for s in ops.chunk(state, 3, axis=2)]

    return output.astype(input_dtype), state

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvModel

Bases: RwkvPreTrainedModel

RWKV Model

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
class RwkvModel(RwkvPreTrainedModel):
    """RWKV Model"""
    def __init__(self, config):
        """
        Initializes an instance of the RwkvModel class.

        Args:
            self: The instance of the class.
            config:
                An object containing the configuration parameters for the model.

                - Type: Any valid object
                - Purpose: Specifies the model configuration.
                - Restrictions: None

        Returns:
            None

        Raises:
            None
        """
        super().__init__(config)

        self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
        self.blocks = nn.ModuleList([RwkvBlock(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
        self.ln_out = nn.LayerNorm([config.hidden_size])

        self.layers_are_rescaled = False

        # Initialize weights and apply final processing
        self.post_init()

    def get_input_embeddings(self):
        """
        This method returns the input embeddings used in the RwkvModel class.

        Args:
            self: The instance of the RwkvModel class.

        Returns:
            embeddings: This method returns the input embeddings associated with the RwkvModel instance.

        Raises:
            None.
        """
        return self.embeddings

    def set_input_embeddings(self, new_embeddings):
        """
        Sets the input embeddings for the RwkvModel.

        Args:
            self (RwkvModel): The instance of the RwkvModel class.
            new_embeddings: A new set of input embeddings to be assigned to the RwkvModel.
                This should be of the same type and shape as the current embeddings.
                The input embeddings are used as the initial embeddings for the model.

        Returns:
            None.

        Raises:
            None.
        """
        self.embeddings = new_embeddings

    # def __call__(self, *args, **kwargs):
    #     if self.training == self.layers_are_rescaled:
    #         self._rescale_layers()
    #     return super().__call__(*args, **kwargs)

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,  # noqa
        inputs_embeds: Optional[mindspore.Tensor] = None,
        state: Optional[List[mindspore.Tensor]] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, RwkvOutput]:
        """
        This method forwards the RwkvModel based on the provided input and configuration parameters.

        Args:
            self: The instance of the RwkvModel class.
            input_ids (Optional[mindspore.Tensor]): The input tensor containing token indices. Default is None.
            attention_mask (Optional[mindspore.Tensor]): The attention mask tensor to mask out specific tokens.
                Default is None.
            inputs_embeds (Optional[mindspore.Tensor]): The input embeddings tensor. Default is None.
            state (Optional[List[mindspore.Tensor]]): The list of state tensors for caching. Default is None.
            use_cache (Optional[bool]): Flag indicating whether to use caching. Default is None.
            output_attentions (Optional[bool]): Flag indicating whether to output attentions. Default is None.
            output_hidden_states (Optional[bool]): Flag indicating whether to output hidden states. Default is None.
            return_dict (Optional[bool]): Flag indicating whether to return a dictionary. Default is None.

        Returns:
            Union[Tuple, RwkvOutput]: The output of the method, which can be a tuple of hidden states, states,
                hidden states history, and attentions, or an instance of RwkvOutput.

        Raises:
            ValueError: If both input_ids and inputs_embeds are specified at the same time, or if neither input_ids
                nor inputs_embeds are specified.
        """
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if self.training == self.layers_are_rescaled:
            self._rescale_layers()

        if input_ids is not None and inputs_embeds is not None:
            raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
        if input_ids is None and inputs_embeds is None:
            raise ValueError("You have to specify either input_ids or inputs_embeds")
        if inputs_embeds is None:
            inputs_embeds = self.embeddings(input_ids)

        if use_cache and state is None:
            shape = (inputs_embeds.shape[0], self.config.hidden_size, self.config.num_hidden_layers)
            state = [
                ops.zeros(shape, dtype=inputs_embeds.dtype if i <= 1 else mindspore.float32)
                for i in range(5)
            ]
            state[4] -= 1e30

        hidden_states = inputs_embeds

        all_self_attentions = () if output_attentions else None
        all_hidden_states = () if output_hidden_states else None
        for idx, block in enumerate(self.blocks):
            hidden_states, state, attentions = block(
                hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions
            )

            if (
                self.layers_are_rescaled
                and self.config.rescale_every > 0
                and (idx + 1) % self.config.rescale_every == 0
            ):
                hidden_states = hidden_states / 2

            if output_hidden_states:
                all_hidden_states = all_hidden_states + (hidden_states,)

            if output_attentions:
                all_self_attentions = all_self_attentions + (attentions,)

        hidden_states = self.ln_out(hidden_states)

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        if not return_dict:
            return tuple(x for x in [hidden_states, state, all_hidden_states, all_self_attentions] if x is not None)

        return RwkvOutput(
            last_hidden_state=hidden_states,
            state=state,
            hidden_states=all_hidden_states,
            attentions=all_self_attentions,
        )

    def _rescale_layers(self):
        """
        Rescales the layers of the RwkvModel based on the training status.

        Args:
            self (RwkvModel): The instance of the RwkvModel class.

        Returns:
            None.

        Raises:
            None
        """
        # Layers should be rescaled for inference only.
        if self.layers_are_rescaled == (not self.training):
            return
        if self.config.rescale_every > 0:
            for block_id, block in enumerate(self.blocks):
                if self.training:
                    block.attention.output.weight.set_data(block.attention.output.weight * \
                                                           (2 ** int(block_id // self.config.rescale_every)))
                    block.feed_forward.value.weight.set_data(block.feed_forward.value.weight * \
                                                             (2 ** int(block_id // self.config.rescale_every)))
                else:
                    # Deal with quantization statistics
                    if hasattr(block.attention.output.weight, "SCB"):
                        block.attention.output.weight.SCB.set_data(block.attention.output.weight.SCB / \
                                                                   (2 ** int(block_id // self.config.rescale_every)))
                        block.feed_forward.value.weight.SCB.set_data(block.feed_forward.value.weight.SCB / \
                                                                     (2 ** int(block_id // self.config.rescale_every)))
                    else:
                        block.attention.output.weight.set_data(block.attention.output.weight / \
                                                            (2 ** int(block_id // self.config.rescale_every)))
                        block.feed_forward.value.weight.set_data(block.feed_forward.value.weight / \
                                                                (2 ** int(block_id // self.config.rescale_every)))
        self.layers_are_rescaled = not self.training

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvModel.__init__(config)

Initializes an instance of the RwkvModel class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing the configuration parameters for the model.

  • Type: Any valid object
  • Purpose: Specifies the model configuration.
  • Restrictions: None

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
def __init__(self, config):
    """
    Initializes an instance of the RwkvModel class.

    Args:
        self: The instance of the class.
        config:
            An object containing the configuration parameters for the model.

            - Type: Any valid object
            - Purpose: Specifies the model configuration.
            - Restrictions: None

    Returns:
        None

    Raises:
        None
    """
    super().__init__(config)

    self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
    self.blocks = nn.ModuleList([RwkvBlock(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
    self.ln_out = nn.LayerNorm([config.hidden_size])

    self.layers_are_rescaled = False

    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvModel.forward(input_ids=None, attention_mask=None, inputs_embeds=None, state=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

This method forwards the RwkvModel based on the provided input and configuration parameters.

PARAMETER DESCRIPTION
self

The instance of the RwkvModel class.

input_ids

The input tensor containing token indices. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask tensor to mask out specific tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The input embeddings tensor. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

state

The list of state tensors for caching. Default is None.

TYPE: Optional[List[Tensor]] DEFAULT: None

use_cache

Flag indicating whether to use caching. Default is None.

TYPE: Optional[bool] DEFAULT: None

output_attentions

Flag indicating whether to output attentions. Default is None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Flag indicating whether to output hidden states. Default is None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Flag indicating whether to return a dictionary. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, RwkvOutput]

Union[Tuple, RwkvOutput]: The output of the method, which can be a tuple of hidden states, states, hidden states history, and attentions, or an instance of RwkvOutput.

RAISES DESCRIPTION
ValueError

If both input_ids and inputs_embeds are specified at the same time, or if neither input_ids nor inputs_embeds are specified.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,  # noqa
    inputs_embeds: Optional[mindspore.Tensor] = None,
    state: Optional[List[mindspore.Tensor]] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, RwkvOutput]:
    """
    This method forwards the RwkvModel based on the provided input and configuration parameters.

    Args:
        self: The instance of the RwkvModel class.
        input_ids (Optional[mindspore.Tensor]): The input tensor containing token indices. Default is None.
        attention_mask (Optional[mindspore.Tensor]): The attention mask tensor to mask out specific tokens.
            Default is None.
        inputs_embeds (Optional[mindspore.Tensor]): The input embeddings tensor. Default is None.
        state (Optional[List[mindspore.Tensor]]): The list of state tensors for caching. Default is None.
        use_cache (Optional[bool]): Flag indicating whether to use caching. Default is None.
        output_attentions (Optional[bool]): Flag indicating whether to output attentions. Default is None.
        output_hidden_states (Optional[bool]): Flag indicating whether to output hidden states. Default is None.
        return_dict (Optional[bool]): Flag indicating whether to return a dictionary. Default is None.

    Returns:
        Union[Tuple, RwkvOutput]: The output of the method, which can be a tuple of hidden states, states,
            hidden states history, and attentions, or an instance of RwkvOutput.

    Raises:
        ValueError: If both input_ids and inputs_embeds are specified at the same time, or if neither input_ids
            nor inputs_embeds are specified.
    """
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    if self.training == self.layers_are_rescaled:
        self._rescale_layers()

    if input_ids is not None and inputs_embeds is not None:
        raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
    if input_ids is None and inputs_embeds is None:
        raise ValueError("You have to specify either input_ids or inputs_embeds")
    if inputs_embeds is None:
        inputs_embeds = self.embeddings(input_ids)

    if use_cache and state is None:
        shape = (inputs_embeds.shape[0], self.config.hidden_size, self.config.num_hidden_layers)
        state = [
            ops.zeros(shape, dtype=inputs_embeds.dtype if i <= 1 else mindspore.float32)
            for i in range(5)
        ]
        state[4] -= 1e30

    hidden_states = inputs_embeds

    all_self_attentions = () if output_attentions else None
    all_hidden_states = () if output_hidden_states else None
    for idx, block in enumerate(self.blocks):
        hidden_states, state, attentions = block(
            hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions
        )

        if (
            self.layers_are_rescaled
            and self.config.rescale_every > 0
            and (idx + 1) % self.config.rescale_every == 0
        ):
            hidden_states = hidden_states / 2

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        if output_attentions:
            all_self_attentions = all_self_attentions + (attentions,)

    hidden_states = self.ln_out(hidden_states)

    if output_hidden_states:
        all_hidden_states = all_hidden_states + (hidden_states,)

    if not return_dict:
        return tuple(x for x in [hidden_states, state, all_hidden_states, all_self_attentions] if x is not None)

    return RwkvOutput(
        last_hidden_state=hidden_states,
        state=state,
        hidden_states=all_hidden_states,
        attentions=all_self_attentions,
    )

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvModel.get_input_embeddings()

This method returns the input embeddings used in the RwkvModel class.

PARAMETER DESCRIPTION
self

The instance of the RwkvModel class.

RETURNS DESCRIPTION
embeddings

This method returns the input embeddings associated with the RwkvModel instance.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
653
654
655
656
657
658
659
660
661
662
663
664
665
666
def get_input_embeddings(self):
    """
    This method returns the input embeddings used in the RwkvModel class.

    Args:
        self: The instance of the RwkvModel class.

    Returns:
        embeddings: This method returns the input embeddings associated with the RwkvModel instance.

    Raises:
        None.
    """
    return self.embeddings

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvModel.set_input_embeddings(new_embeddings)

Sets the input embeddings for the RwkvModel.

PARAMETER DESCRIPTION
self

The instance of the RwkvModel class.

TYPE: RwkvModel

new_embeddings

A new set of input embeddings to be assigned to the RwkvModel. This should be of the same type and shape as the current embeddings. The input embeddings are used as the initial embeddings for the model.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
def set_input_embeddings(self, new_embeddings):
    """
    Sets the input embeddings for the RwkvModel.

    Args:
        self (RwkvModel): The instance of the RwkvModel class.
        new_embeddings: A new set of input embeddings to be assigned to the RwkvModel.
            This should be of the same type and shape as the current embeddings.
            The input embeddings are used as the initial embeddings for the model.

    Returns:
        None.

    Raises:
        None.
    """
    self.embeddings = new_embeddings

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvOutput dataclass

Bases: ModelOutput

Class for the RWKV model outputs.

PARAMETER DESCRIPTION
last_hidden_state

Sequence of hidden-states at the output of the last layer of the model.

TYPE: `mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)` DEFAULT: None

state

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.

TYPE: list of five `mindspore.Tensor` of shape `(batch_size, hidden_size, num_hidden_layers)` DEFAULT: None

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
@dataclass
class RwkvOutput(ModelOutput):
    """
    Class for the RWKV model outputs.

    Args:
        last_hidden_state (`mindspore.Tensor` 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 `mindspore.Tensor` 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(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed
            or when `config.output_hidden_states=True`):
            Tuple of `mindspore.Tensor` (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(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed
            or when `config.output_attentions=True`):
            Tuple of `mindspore.Tensor` (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.
    """
    last_hidden_state: mindspore.Tensor = None
    state: Optional[List[mindspore.Tensor]] = None
    hidden_states: Optional[Tuple[mindspore.Tensor, ...]] = None
    attentions: Optional[Tuple[mindspore.Tensor, ...]] = None

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvPreTrainedModel

Bases: PreTrainedModel

An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
class RwkvPreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    config_class = RwkvConfig
    base_model_prefix = "rwkv"
    _no_split_modules = ["RwkvBlock"]
    _keep_in_fp32_modules = ["time_decay", "time_first"]

    def _init_weights(self, cell):
        """Initialize the weights."""
        if isinstance(cell, RwkvSelfAttention):
            layer_id = cell.layer_id
            num_hidden_layers = cell.config.num_hidden_layers
            hidden_size = cell.config.hidden_size
            attention_hidden_size = cell.attention_hidden_size

            ratio_0_to_1 = layer_id / (num_hidden_layers - 1)  # 0 to 1
            ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers)  # 1 to ~0

            time_weight = Tensor(
                [i / hidden_size for i in range(hidden_size)],
                dtype=cell.time_mix_key.dtype,
            )
            time_weight = time_weight[None, None, :]

            decay_speed = [
                -5 + 8 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
                for h in range(attention_hidden_size)
            ]
            decay_speed = Tensor(decay_speed, dtype=cell.time_decay.dtype)
            zigzag = (
                Tensor(
                    [(i + 1) % 3 - 1 for i in range(attention_hidden_size)],
                    dtype=cell.time_first.dtype
                )
                * 0.5
            )

            cell.time_decay.set_data(decay_speed)
            cell.time_first.set_data(ops.ones_like(cell.time_first * math.log(0.3) + zigzag))

            cell.time_mix_key.set_data(ops.pow(time_weight, ratio_1_to_almost0))
            cell.time_mix_value.set_data(ops.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1)
            cell.time_mix_receptance.set_data(ops.pow(time_weight, 0.5 * ratio_1_to_almost0))

        elif isinstance(cell, RwkvFeedForward):
            layer_id = cell.layer_id
            num_hidden_layers = cell.config.num_hidden_layers
            hidden_size = cell.config.hidden_size

            ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers)  # 1 to ~0

            time_weight = Tensor(
                [i / hidden_size for i in range(hidden_size)],
                dtype=cell.time_mix_key.dtype
            )
            time_weight = time_weight[None, None, :]

            cell.time_mix_key.set_data(ops.pow(time_weight, ratio_1_to_almost0))
            cell.time_mix_receptance.set_data(ops.pow(time_weight, ratio_1_to_almost0))

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvSelfAttention

Bases: Module

RWKV self attention

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
class RwkvSelfAttention(nn.Module):
    """RWKV self attention"""
    def __init__(self, config, layer_id=0):
        """
        Initializes an instance of the RwkvSelfAttention class.

        Args:
            self (RwkvSelfAttention): The instance of the class.
            config (object): The configuration object containing various settings.
            layer_id (int, optional): The ID of the layer. Defaults to 0.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.config = config
        device_target = mindspore.get_context('device_target')
        if device_target == 'GPU':
            self.rwkv_linear_attention = RwkvLinearAttention(config)
        else:
            self.rwkv_linear_attention = rwkv_linear_attention_cpu

        self.layer_id = layer_id
        hidden_size = config.hidden_size
        attention_hidden_size = (
            config.attention_hidden_size if config.attention_hidden_size is not None else hidden_size
        )
        self.attention_hidden_size = attention_hidden_size

        self.time_decay = Parameter(Tensor(np.zeros(attention_hidden_size), mindspore.float32), 'time_decay')
        self.time_first = Parameter(Tensor(np.zeros(attention_hidden_size), mindspore.float32), 'time_decay')

        self.time_mix_key = Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_key')
        self.time_mix_value = Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_value')
        self.time_mix_receptance = Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_receptance')

        self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
        self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
        self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
        self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
        self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)

    def extract_key_value(self, hidden, state=None):
        """extrac key value"""
        # Mix hidden with the previous timestep to produce key, value, receptance
        if hidden.shape[1] == 1 and state is not None:
            shifted = state[1][:, :, self.layer_id]
        else:
            shifted = self.time_shift(hidden)
            if state is not None:
                shifted[:, 0] = state[1][:, :, self.layer_id]
        key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
        value = hidden * self.time_mix_value + shifted * (1 - self.time_mix_value)
        receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)

        key = self.key(key)
        value = self.value(value)
        receptance = ops.sigmoid(self.receptance(receptance))
        if state is not None:
            state[1][:, :, self.layer_id] = hidden[:, -1]
        return receptance, key, value, state

    def forward(self, hidden, state=None, use_cache=False):
        """
        Construct method in the RwkvSelfAttention class.

        This method forwards the self-attention mechanism for the Rwkv model. It takes in the hidden input,
        the state, and a flag indicating whether to use cache or not. It returns the output of the attention mechanism
        and the updated state.

        Args:
            self: The RwkvSelfAttention object.
            hidden: A tensor containing the hidden input.
            state: A tensor containing the current state (default: None).
            use_cache: A boolean flag indicating whether to use cache (default: False).

        Returns:
            A tuple containing the output of the attention mechanism and the updated state.

        Raises:
            None.
        """
        receptance, key, value, state = self.extract_key_value(hidden, state=state)
        layer_state = tuple(s[:, :, self.layer_id] for s in state[2:]) if state is not None else None
        rwkv, layer_state = self.rwkv_linear_attention(
            self.time_decay,
            self.time_first,
            key,
            value,
            state=layer_state,
            return_state=use_cache,
        )

        if layer_state is not None:
            state[2][:, :, self.layer_id] = layer_state[0]
            state[3][:, :, self.layer_id] = layer_state[1]
            state[4][:, :, self.layer_id] = layer_state[2]

        return self.output(receptance * rwkv), state

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvSelfAttention.__init__(config, layer_id=0)

Initializes an instance of the RwkvSelfAttention class.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: RwkvSelfAttention

config

The configuration object containing various settings.

TYPE: object

layer_id

The ID of the layer. Defaults to 0.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def __init__(self, config, layer_id=0):
    """
    Initializes an instance of the RwkvSelfAttention class.

    Args:
        self (RwkvSelfAttention): The instance of the class.
        config (object): The configuration object containing various settings.
        layer_id (int, optional): The ID of the layer. Defaults to 0.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.config = config
    device_target = mindspore.get_context('device_target')
    if device_target == 'GPU':
        self.rwkv_linear_attention = RwkvLinearAttention(config)
    else:
        self.rwkv_linear_attention = rwkv_linear_attention_cpu

    self.layer_id = layer_id
    hidden_size = config.hidden_size
    attention_hidden_size = (
        config.attention_hidden_size if config.attention_hidden_size is not None else hidden_size
    )
    self.attention_hidden_size = attention_hidden_size

    self.time_decay = Parameter(Tensor(np.zeros(attention_hidden_size), mindspore.float32), 'time_decay')
    self.time_first = Parameter(Tensor(np.zeros(attention_hidden_size), mindspore.float32), 'time_decay')

    self.time_mix_key = Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_key')
    self.time_mix_value = Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_value')
    self.time_mix_receptance = Parameter(Tensor(np.zeros((1, 1, hidden_size)), mindspore.float32), 'time_mix_receptance')

    self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
    self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
    self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
    self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
    self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvSelfAttention.extract_key_value(hidden, state=None)

extrac key value

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def extract_key_value(self, hidden, state=None):
    """extrac key value"""
    # Mix hidden with the previous timestep to produce key, value, receptance
    if hidden.shape[1] == 1 and state is not None:
        shifted = state[1][:, :, self.layer_id]
    else:
        shifted = self.time_shift(hidden)
        if state is not None:
            shifted[:, 0] = state[1][:, :, self.layer_id]
    key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
    value = hidden * self.time_mix_value + shifted * (1 - self.time_mix_value)
    receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)

    key = self.key(key)
    value = self.value(value)
    receptance = ops.sigmoid(self.receptance(receptance))
    if state is not None:
        state[1][:, :, self.layer_id] = hidden[:, -1]
    return receptance, key, value, state

mindnlp.transformers.models.rwkv.modeling_rwkv.RwkvSelfAttention.forward(hidden, state=None, use_cache=False)

Construct method in the RwkvSelfAttention class.

This method forwards the self-attention mechanism for the Rwkv model. It takes in the hidden input, the state, and a flag indicating whether to use cache or not. It returns the output of the attention mechanism and the updated state.

PARAMETER DESCRIPTION
self

The RwkvSelfAttention object.

hidden

A tensor containing the hidden input.

state

A tensor containing the current state (default: None).

DEFAULT: None

use_cache

A boolean flag indicating whether to use cache (default: False).

DEFAULT: False

RETURNS DESCRIPTION

A tuple containing the output of the attention mechanism and the updated state.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
def forward(self, hidden, state=None, use_cache=False):
    """
    Construct method in the RwkvSelfAttention class.

    This method forwards the self-attention mechanism for the Rwkv model. It takes in the hidden input,
    the state, and a flag indicating whether to use cache or not. It returns the output of the attention mechanism
    and the updated state.

    Args:
        self: The RwkvSelfAttention object.
        hidden: A tensor containing the hidden input.
        state: A tensor containing the current state (default: None).
        use_cache: A boolean flag indicating whether to use cache (default: False).

    Returns:
        A tuple containing the output of the attention mechanism and the updated state.

    Raises:
        None.
    """
    receptance, key, value, state = self.extract_key_value(hidden, state=state)
    layer_state = tuple(s[:, :, self.layer_id] for s in state[2:]) if state is not None else None
    rwkv, layer_state = self.rwkv_linear_attention(
        self.time_decay,
        self.time_first,
        key,
        value,
        state=layer_state,
        return_state=use_cache,
    )

    if layer_state is not None:
        state[2][:, :, self.layer_id] = layer_state[0]
        state[3][:, :, self.layer_id] = layer_state[1]
        state[4][:, :, self.layer_id] = layer_state[2]

    return self.output(receptance * rwkv), state

mindnlp.transformers.models.rwkv.modeling_rwkv.load_wkv_cuda_kernel(func_name, context_length)

load wkv cuda kernel

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def load_wkv_cuda_kernel(func_name, context_length):
    """load wkv cuda kernel"""
    device_target = mindspore.get_context('device_target')
    if device_target != 'GPU':
        raise RuntimeError('WKV operator only support GPU currently.')

    logger.info(f"Loading CUDA kernel for RWKV at context length of {context_length}.")

    from ...kernel_utils import compile_kernel
    so_path = compile_kernel(kernel_name="wkv", Tmax=context_length)
    wkv_op = ops.Custom(
        str(so_path) + ':' + func_name,
        out_shape=WKV_SHAPE_INFER[func_name],
        out_dtype=WKV_DTYPE_INFER[func_name],
        func_type='aot'
    )
    wkv_op.add_prim_attr('primitive_target', device_target)
    return wkv_op

mindnlp.transformers.models.rwkv.modeling_rwkv.rwkv_linear_attention_cpu(time_decay, time_first, key, value, state=None, return_state=False)

CPU WKV implementation.

Source code in mindnlp/transformers/models/rwkv/modeling_rwkv.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def rwkv_linear_attention_cpu(time_decay, time_first, key, value, state=None, return_state=False):
    """CPU WKV implementation."""
    # For CPU fallback. Will be slower and probably take more memory than the custom CUDA kernel
    _, seq_length, _ = key.shape
    output = ops.zeros_like(key)

    if state is None:
        num_state = ops.zeros_like(key[:, 0], dtype=mindspore.float32)
        den_state = ops.zeros_like(key[:, 0], dtype=mindspore.float32)
        max_state = ops.zeros_like(key[:, 0], dtype=mindspore.float32) - 1e38
    else:
        num_state, den_state, max_state = state
    # For numerical stability
    #    real_numerator_state = num_state * ops.exp(max_state)
    #    real_denominator_state = den_state * ops.exp(max_state)

    time_decay = -ops.exp(time_decay)

    for current_index in range(seq_length):
        current_key = key[:, current_index].float()
        current_value = value[:, current_index]

        # wkv computation at time t
        max_for_output = ops.maximum(max_state, current_key + time_first)
        e1 = ops.exp(max_state - max_for_output)
        e2 = ops.exp(current_key + time_first - max_for_output)
        numerator = e1 * num_state + e2 * current_value
        denominator = e1 * den_state + e2
        output[:, current_index] = (numerator / denominator).to(output.dtype)

        # Update state for next iteration
        max_for_state = ops.maximum(max_state + time_decay, current_key)
        e1 = ops.exp(max_state + time_decay - max_for_state)
        e2 = ops.exp(current_key - max_for_state)
        num_state = e1 * num_state + e2 * current_value
        den_state = e1 * den_state + e2
        max_state = max_for_state

    if return_state or state is not None:
        state = [num_state, den_state, max_state]

    return output, state

mindnlp.transformers.models.rwkv.configuration_rwkv

RWKV configuration

mindnlp.transformers.models.rwkv.configuration_rwkv.RwkvConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [RwkvModel]. 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 RWKV/rwkv-4-169m-pile architecture.

Configuration objects inherit from [PretrainedConfig] and can be used to control the model outputs. Read the documentation from [PretrainedConfig] for more information.

PARAMETER DESCRIPTION
vocab_size

Vocabulary size of the RWKV model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling [RwkvModel].

TYPE: `int`, *optional*, defaults to 50277 DEFAULT: 50277

context_length

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).

TYPE: `int`, *optional*, defaults to 1024 DEFAULT: 1024

hidden_size

Dimensionality of the embeddings and hidden states.

TYPE: `int`, *optional*, defaults to 4096 DEFAULT: 4096

num_hidden_layers

Number of hidden layers in the model.

TYPE: `int`, *optional*, defaults to 32 DEFAULT: 32

attention_hidden_size

Dimensionality of the attention hidden states. Will default to hidden_size if unset.

TYPE: `int`, *optional* DEFAULT: None

intermediate_size

Dimensionality of the inner feed-forward layers. Will default to 4 times hidden_size if unset.

TYPE: `int`, *optional* DEFAULT: None

layer_norm_eps

The epsilon to use in the layer normalization layers.

TYPE: `float`, *optional*, defaults to 1e-5

bos_token_id

The id of the beginning of sentence token in the vocabulary. Defaults to 0 as RWKV uses the same tokenizer as GPTNeoX.

TYPE: `int`, *optional*, defaults to 0 DEFAULT: 0

eos_token_id

The id of the end of sentence token in the vocabulary. Defaults to 0 as RWKV uses the same tokenizer as GPTNeoX.

TYPE: `int`, *optional*, defaults to 0 DEFAULT: 0

rescale_every

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.

TYPE: `int`, *optional*, default to 6 DEFAULT: 6

tie_word_embeddings

Whether or not to tie the word embeddings with the input token embeddings.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

use_cache

Whether or not the model should return the last state.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

Example
>>> from transformers import RwkvConfig, RwkvModel
...
>>> # Initializing a Rwkv configuration
>>> configuration = RwkvConfig()
...
>>> # Initializing a model (with random weights) from the configuration
>>> model = RwkvModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/rwkv/configuration_rwkv.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
class RwkvConfig(PretrainedConfig):
    """
    This is the configuration class to store the configuration of a [`RwkvModel`]. 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
    [RWKV/rwkv-4-169m-pile](https://hf-mirror.com/RWKV/rwkv-4-169m-pile) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.


    Args:
        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 [`RwkvModel`].
        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:
        ```python
        >>> from transformers import RwkvConfig, RwkvModel
        ...
        >>> # Initializing a Rwkv configuration
        >>> configuration = RwkvConfig()
        ...
        >>> # Initializing a model (with random weights) from the configuration
        >>> model = RwkvModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "rwkv"
    attribute_map = {"max_position_embeddings": "context_length"}
    pretrained_config_archive_map = RWKV_PRETRAINED_CONFIG_ARCHIVE_MAP

    def __init__(
        self,
        vocab_size=50277,
        context_length=1024,
        hidden_size=4096,
        num_hidden_layers=32,
        attention_hidden_size=None,
        intermediate_size=None,
        layer_norm_epsilon=1e-5,
        bos_token_id=0,
        eos_token_id=0,
        rescale_every=6,
        tie_word_embeddings=False,
        use_cache=True,
        **kwargs,
    ):
        """
        Initializes an instance of RwkvConfig.

        Args:
            self: The instance itself.
            vocab_size (int): The size of the vocabulary. Default is 50277.
            context_length (int): The length of the context. Default is 1024.
            hidden_size (int): The size of the hidden layers. Default is 4096.
            num_hidden_layers (int): The number of hidden layers. Default is 32.
            attention_hidden_size (int, optional): The size of the attention hidden layer.
                Defaults to hidden_size if not provided.
            intermediate_size (int, optional): The size of the intermediate layer. Defaults to 4 times hidden_size
                if not provided.
            layer_norm_epsilon (float): The epsilon value for layer normalization. Default is 1e-05.
            bos_token_id (int): The beginning of sentence token id. Default is 0.
            eos_token_id (int): The end of sentence token id. Default is 0.
            rescale_every (int): The frequency of rescaling. Default is 6.
            tie_word_embeddings (bool): Whether to tie word embeddings. Default is False.
            use_cache (bool): Whether to use cache. Default is True.

        Returns:
            None.

        Raises:
            ValueError: If the provided vocab_size, context_length, hidden_size, num_hidden_layers,
                attention_hidden_size, intermediate_size, layer_norm_epsilon, bos_token_id, eos_token_id,
                or rescale_every is not a positive integer.
            TypeError: If any of the provided parameters has an unexpected type.
        """
        self.vocab_size = vocab_size
        self.context_length = context_length
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.attention_hidden_size = attention_hidden_size if attention_hidden_size is not None else hidden_size
        self.intermediate_size = intermediate_size if intermediate_size is not None else 4 * hidden_size
        self.layer_norm_epsilon = layer_norm_epsilon
        self.rescale_every = rescale_every
        self.use_cache = use_cache

        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id

        super().__init__(
            tie_word_embeddings=tie_word_embeddings, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs
        )

mindnlp.transformers.models.rwkv.configuration_rwkv.RwkvConfig.__init__(vocab_size=50277, context_length=1024, hidden_size=4096, num_hidden_layers=32, attention_hidden_size=None, intermediate_size=None, layer_norm_epsilon=1e-05, bos_token_id=0, eos_token_id=0, rescale_every=6, tie_word_embeddings=False, use_cache=True, **kwargs)

Initializes an instance of RwkvConfig.

PARAMETER DESCRIPTION
self

The instance itself.

vocab_size

The size of the vocabulary. Default is 50277.

TYPE: int DEFAULT: 50277

context_length

The length of the context. Default is 1024.

TYPE: int DEFAULT: 1024

hidden_size

The size of the hidden layers. Default is 4096.

TYPE: int DEFAULT: 4096

num_hidden_layers

The number of hidden layers. Default is 32.

TYPE: int DEFAULT: 32

attention_hidden_size

The size of the attention hidden layer. Defaults to hidden_size if not provided.

TYPE: int DEFAULT: None

intermediate_size

The size of the intermediate layer. Defaults to 4 times hidden_size if not provided.

TYPE: int DEFAULT: None

layer_norm_epsilon

The epsilon value for layer normalization. Default is 1e-05.

TYPE: float DEFAULT: 1e-05

bos_token_id

The beginning of sentence token id. Default is 0.

TYPE: int DEFAULT: 0

eos_token_id

The end of sentence token id. Default is 0.

TYPE: int DEFAULT: 0

rescale_every

The frequency of rescaling. Default is 6.

TYPE: int DEFAULT: 6

tie_word_embeddings

Whether to tie word embeddings. Default is False.

TYPE: bool DEFAULT: False

use_cache

Whether to use cache. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the provided vocab_size, context_length, hidden_size, num_hidden_layers, attention_hidden_size, intermediate_size, layer_norm_epsilon, bos_token_id, eos_token_id, or rescale_every is not a positive integer.

TypeError

If any of the provided parameters has an unexpected type.

Source code in mindnlp/transformers/models/rwkv/configuration_rwkv.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def __init__(
    self,
    vocab_size=50277,
    context_length=1024,
    hidden_size=4096,
    num_hidden_layers=32,
    attention_hidden_size=None,
    intermediate_size=None,
    layer_norm_epsilon=1e-5,
    bos_token_id=0,
    eos_token_id=0,
    rescale_every=6,
    tie_word_embeddings=False,
    use_cache=True,
    **kwargs,
):
    """
    Initializes an instance of RwkvConfig.

    Args:
        self: The instance itself.
        vocab_size (int): The size of the vocabulary. Default is 50277.
        context_length (int): The length of the context. Default is 1024.
        hidden_size (int): The size of the hidden layers. Default is 4096.
        num_hidden_layers (int): The number of hidden layers. Default is 32.
        attention_hidden_size (int, optional): The size of the attention hidden layer.
            Defaults to hidden_size if not provided.
        intermediate_size (int, optional): The size of the intermediate layer. Defaults to 4 times hidden_size
            if not provided.
        layer_norm_epsilon (float): The epsilon value for layer normalization. Default is 1e-05.
        bos_token_id (int): The beginning of sentence token id. Default is 0.
        eos_token_id (int): The end of sentence token id. Default is 0.
        rescale_every (int): The frequency of rescaling. Default is 6.
        tie_word_embeddings (bool): Whether to tie word embeddings. Default is False.
        use_cache (bool): Whether to use cache. Default is True.

    Returns:
        None.

    Raises:
        ValueError: If the provided vocab_size, context_length, hidden_size, num_hidden_layers,
            attention_hidden_size, intermediate_size, layer_norm_epsilon, bos_token_id, eos_token_id,
            or rescale_every is not a positive integer.
        TypeError: If any of the provided parameters has an unexpected type.
    """
    self.vocab_size = vocab_size
    self.context_length = context_length
    self.hidden_size = hidden_size
    self.num_hidden_layers = num_hidden_layers
    self.attention_hidden_size = attention_hidden_size if attention_hidden_size is not None else hidden_size
    self.intermediate_size = intermediate_size if intermediate_size is not None else 4 * hidden_size
    self.layer_norm_epsilon = layer_norm_epsilon
    self.rescale_every = rescale_every
    self.use_cache = use_cache

    self.bos_token_id = bos_token_id
    self.eos_token_id = eos_token_id

    super().__init__(
        tie_word_embeddings=tie_word_embeddings, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs
    )