Skip to navigation

nemo_automodel.components.models.baichuan.model

View as MarkdownOpen in Claude

Native Baichuan2 model implementation for NeMo Automodel.

Adapted from the Baichuan2 remote-code model on HuggingFace with the following changes:

  • Removed xformers / quantization / chat / streaming dependencies.
  • Added **kwargs to forward signatures so that extra batch keys (padding_mask, loss_mask, …) pass through without error.
  • Uses HFCheckpointingMixin for unified checkpointing.
  • Uses torch.nn.functional.scaled_dot_product_attention only.

Example (YAML)::

model: target: nemo_automodel.NeMoAutoModelForCausalLM.from_pretrained pretrained_model_name_or_path: baichuan-inc/Baichuan2-7B-Chat

Module Contents

Classes

Functions

Data

ModelClass

logger

API

class nemo_automodel.components.models.baichuan.model.Attention(
)

Bases: Module

W_pack
head_dim
= self.hidden_size // self.num_heads
hidden_size
= config.hidden_size
max_position_embeddings
= config.max_position_embeddings
num_heads
= config.num_attention_heads
o_proj
rotary_emb
nemo_automodel.components.models.baichuan.model.Attention.forward(
hidden_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_value: typing.Tuple[torch.Tensor] | None = None,
output_attentions: bool = False,
use_cache: bool = False
) -> typing.Tuple[torch.Tensor, torch.Tensor | None, typing.Tuple[torch.Tensor] | None]
class nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM(
logits_dtype: torch.dtype | None = None
)

Bases: HFCheckpointingMixin, BaichuanPreTrainedModel, GenerationMixin

lm_head
model
= BaichuanModel(config)
tie_word_embeddings_support
TieSupport = TieSupport.UNTIED_ONLY
nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM._reorder_cache(
past_key_values,
beam_idx
)
staticmethod
nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM.forward(
input_ids: torch.LongTensor = None,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values: typing.List[torch.FloatTensor] | None = None,
inputs_embeds: torch.FloatTensor | None = None,
labels: torch.LongTensor | None = None,
use_cache: bool | None = None,
output_attentions: bool | None = None,
output_hidden_states: bool | None = None,
return_dict: bool | None = None,
logits_to_keep: typing.Union[int, torch.Tensor] = 0,
kwargs = {}
) -> typing.Union[typing.Tuple, transformers.modeling_outputs.CausalLMOutputWithPast]

Run the backbone and project the kept positions to vocabulary logits.

Parameters:

input_ids
torch.LongTensorDefaults to None

Token IDs of shape [batch, sequence].

attention_mask
torch.Tensor | NoneDefaults to None

Optional Tensor of shape [batch, past + sequence], 1 at valid tokens and 0 at padding, or a per-query mask of shape [batch, sequence, sequence]; it is combined with the causal mask, and None masks no tokens.

position_ids
torch.LongTensor | NoneDefaults to None

Optional positions of shape [batch, sequence]; None numbers them from the cached length.

past_key_values
List[torch.FloatTensor] | NoneDefaults to None

Optional cache, either a DynamicCache or one (key, value) pair per layer, each of shape [batch, heads, past, head_dim].

inputs_embeds
torch.FloatTensor | NoneDefaults to None

Optional embeddings of shape [batch, sequence, hidden] used instead of input_ids.

labels
torch.LongTensor | NoneDefaults to None

Optional target IDs of shape [batch, sequence] for the shifted next-token cross-entropy, which ignores -100; config.z_loss_weight, when set, adds that weight times the mean squared max logit.

use_cache
bool | NoneDefaults to None

Whether to return the updated cache; None reads config.use_cache.

output_attentions
bool | NoneDefaults to None

Passed to the backbone, whose SDPA attention returns no weights.

output_hidden_states
bool | NoneDefaults to None

Whether the output carries the final hidden states; None reads config.output_hidden_states.

return_dict
bool | NoneDefaults to None

Whether to return CausalLMOutputWithPast instead of a tuple.

logits_to_keep
Union[int, torch.Tensor]Defaults to 0

0 keeps every position, a positive int keeps the last N positions, and an integer Tensor of shape [kept] keeps those positions.

**kwargs
Defaults to {}

Extra batch keys, such as padding_mask or packed-sequence metadata, which are ignored.

Returns: Union[Tuple, CausalLMOutputWithPast]

CausalLMOutputWithPast, or the matching tuple when return_dict is False. logits have shape

nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM.get_decoder()
nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM.get_input_embeddings()
nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM.get_output_embeddings()
nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM.prepare_inputs_for_generation(
input_ids,
past_key_values = None,
attention_mask = None,
inputs_embeds = None,
kwargs = {}
)
nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM.set_decoder(
decoder
)
nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM.set_input_embeddings(
value
)
nemo_automodel.components.models.baichuan.model.BaichuanForCausalLM.set_output_embeddings(
new_embeddings
)
class nemo_automodel.components.models.baichuan.model.BaichuanModel(
)

Bases: BaichuanPreTrainedModel

embed_tokens
layers
norm
padding_idx
= config.pad_token_id
vocab_size
= config.vocab_size
nemo_automodel.components.models.baichuan.model.BaichuanModel._prepare_decoder_attention_mask(
attention_mask,
input_shape,
inputs_embeds,
past_key_values_length
)
nemo_automodel.components.models.baichuan.model.BaichuanModel.forward(
input_ids: torch.LongTensor = None,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values: typing.List[torch.FloatTensor] | None = None,
inputs_embeds: torch.FloatTensor | None = None,
use_cache: bool | None = None,
output_attentions: bool | None = None,
output_hidden_states: bool | None = None,
return_dict: bool | None = None,
kwargs = {}
) -> typing.Union[typing.Tuple, transformers.modeling_outputs.BaseModelOutputWithPast]
nemo_automodel.components.models.baichuan.model.BaichuanModel.get_input_embeddings()
nemo_automodel.components.models.baichuan.model.BaichuanModel.set_input_embeddings(
value
)
class nemo_automodel.components.models.baichuan.model.BaichuanPreTrainedModel()

Bases: PreTrainedModel

_no_split_modules
= ['DecoderLayer']
base_model_prefix
= 'model'
nemo_automodel.components.models.baichuan.model.BaichuanPreTrainedModel._init_weights(
module
)
nemo_automodel.components.models.baichuan.model.BaichuanPreTrainedModel._set_gradient_checkpointing(
module,
value = False
)
class nemo_automodel.components.models.baichuan.model.DecoderLayer(
)

Bases: Module

hidden_size
= config.hidden_size
input_layernorm
mlp
post_attention_layernorm
self_attn
= Attention(config=config)
nemo_automodel.components.models.baichuan.model.DecoderLayer.forward(
hidden_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_value: typing.Tuple[torch.Tensor] | None = None,
output_attentions: bool | None = False,
use_cache: bool | None = False
) -> typing.Tuple[torch.FloatTensor, ...]
class nemo_automodel.components.models.baichuan.model.MLP(
hidden_size,
intermediate_size,
hidden_act
)

Bases: Module

act_fn
= ACT2FN[hidden_act]
down_proj
gate_proj
up_proj
nemo_automodel.components.models.baichuan.model.MLP.forward(
x
)
class nemo_automodel.components.models.baichuan.model.NormHead(
hidden_size: int,
vocab_size: int,
bias: bool = False,
logits_dtype: torch.dtype | None = None
)

Bases: Module

weight
nemo_automodel.components.models.baichuan.model.NormHead.forward(
hidden_states
)

Project hidden states with the row-normalized head weight.

Training normalizes each vocabulary row of the weight to unit L2 norm on every call. The first eval call after training normalizes the stored weight in place, and later eval calls reuse it.

Parameters:

hidden_states

Tensor of shape […, hidden], for example [batch, kept, hidden].

Returns:

Logits of shape […, vocab], in logits_dtype when set and otherwise in the weight dtype, which

class nemo_automodel.components.models.baichuan.model.RMSNorm(
hidden_size,
eps = 1e-06
)

Bases: Module

weight
= nn.Parameter(torch.ones(hidden_size))
nemo_automodel.components.models.baichuan.model.RMSNorm.forward(
hidden_states
)
class nemo_automodel.components.models.baichuan.model.RotaryEmbedding(
dim,
max_position_embeddings = 2048,
base = 10000,
device = None
)

Bases: Module

cos_cached
= emb.cos()[None, None, :, :].to(torch.float32)
inv_freq
sin_cached
= emb.sin()[None, None, :, :].to(torch.float32)
nemo_automodel.components.models.baichuan.model.RotaryEmbedding.forward(
x,
seq_len = None
)
nemo_automodel.components.models.baichuan.model._apply_rotary_pos_emb(
q,
k,
cos_,
sin_,
position_ids
)
nemo_automodel.components.models.baichuan.model._expand_mask(
mask,
dtype,
tgt_len = None
)
nemo_automodel.components.models.baichuan.model._make_causal_mask(
input_ids_shape,
dtype,
device,
past_key_values_length = 0
)
nemo_automodel.components.models.baichuan.model._rotate_half(
x
)
nemo_automodel.components.models.baichuan.model.ModelClass = BaichuanForCausalLM
nemo_automodel.components.models.baichuan.model.logger = logging.get_logger(__name__)