mdxss's picture
Publish Luxfer early beta with runnable weights and language metadata
7b6f2cc verified
Raw History Blame Contribute Delete
21.8 kB
# Derived from PFN PLaMo; see docs/LICENSING.md.
import enum
import math
import warnings
from typing import Any, Dict, List, Literal, NamedTuple, Optional, Tuple, Union
import torch
from torch import nn
from torch.nn import functional as F
from transformers import GenerationMixin, PretrainedConfig, PreTrainedModel
from transformers.cache_utils import DynamicCache
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from architecture.config import LuxferConfig, is_full_attn
from layers.normalization import LuxferRMSNorm
from embeddings.rotary import RotaryEmbedding, _rotary_pos_emb
from embeddings.token import LuxferEmbedding
from layers.mlp import MLP
from attention.core import Attention, _make_causal_mask, _expand_mask
class DecoderInput(NamedTuple):
hidden_states: torch.Tensor
attention_mask: Optional[torch.Tensor] = None
past_states: Optional[DynamicCache] = None
output_hidden_states: Optional[bool] = False
output_attentions: Optional[bool] = False
gradient_checkpointing: bool = False
input_ids: Optional[torch.Tensor] = None
class DecoderOutput(NamedTuple):
hidden_states: torch.Tensor
all_hidden_states: Optional[Tuple[torch.Tensor, ...]]
all_self_attns: Optional[Tuple[torch.Tensor, ...]]
class LuxferDecoderLayer(torch.nn.Module):
def __init__(self, config: LuxferConfig, layer_idx: int) -> None:
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.mixer: torch.nn.Module
self.mixer = Attention(config, layer_idx)
self.mlp = MLP(config)
"""
Notes: The model performance was degraded when setting all offsets to 1.
"""
self.pre_mixer_norm = LuxferRMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0)
self.post_mixer_norm = LuxferRMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0 / 5)
self.pre_mlp_norm = LuxferRMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0)
self.post_mlp_norm = LuxferRMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0 / (5**1.5))
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
past_state: Optional[DynamicCache] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[Any, ...]:
# from LlamaDecoder
residual = hidden_states
hidden_states = self.pre_mixer_norm(hidden_states)
# Self Attention
hidden_states_sa, self_attn_weights, present_key_value = self.mixer(
hidden_states=hidden_states,
attention_mask=attention_mask,
past_states=past_state,
output_attentions=output_attentions,
)
hidden_states_sa = self.post_mixer_norm(hidden_states_sa)
hidden_states = residual + hidden_states_sa
residual = hidden_states
hidden_states = self.pre_mlp_norm(hidden_states)
# Fully Connected
hidden_states_mlp = self.mlp(hidden_states)
# Residual
hidden_states_mlp = self.post_mlp_norm(hidden_states_mlp)
hidden_states = residual + hidden_states_mlp
outputs: Any = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
return outputs
class LuxferDecoder(torch.nn.Module):
def __init__(self, config: LuxferConfig) -> None:
super().__init__()
self.layers = torch.nn.ModuleList(
[LuxferDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]
)
self.gradient_checkpointing = False
def forward(self, x: DecoderInput) -> DecoderOutput:
if not isinstance(x, DecoderInput):
x = DecoderInput(*x)
# Unpack DecoderInput fields to locals for torch.fx compatibility.
hidden_states = x.hidden_states
attention_mask = x.attention_mask
past_states = x.past_states
output_hidden_states = x.output_hidden_states
output_attentions = x.output_attentions
gradient_checkpointing = x.gradient_checkpointing
all_hidden_states: Optional[Tuple[torch.Tensor, ...]] = () if output_hidden_states else None
all_self_attns: Optional[Tuple[torch.Tensor, ...]] = () if output_attentions else None
for decoder_layer in self.layers:
if output_hidden_states:
assert all_hidden_states is not None
all_hidden_states += (hidden_states,)
if self.training and gradient_checkpointing:
layer_outputs = self._gradient_checkpointing_func( # type: ignore
decoder_layer.__call__,
hidden_states,
attention_mask,
past_states,
output_attentions,
)
else:
layer_outputs = decoder_layer(
hidden_states,
attention_mask=attention_mask,
past_state=past_states,
output_attentions=output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
assert layer_outputs[1] is not None
assert all_self_attns is not None
all_self_attns += (layer_outputs[1],)
return DecoderOutput(hidden_states, all_hidden_states, all_self_attns)
class LuxferPreTrainedModel(PreTrainedModel): # type: ignore
config_class = LuxferConfig
_no_split_modules: List[str]
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["LuxferDecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
def _init_weights(self, module: torch.nn.Module) -> None:
std = 0.02
if isinstance(module, nn.Linear):
if getattr(module.weight, "_is_hf_initialized", False):
if module.bias is not None:
assert getattr(module.bias, "_is_hf_initialized", False)
return
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
if getattr(module.weight, "_is_hf_initialized", False):
return
module.weight.data.normal_(mean=0.0, std=std)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, RotaryEmbedding):
# Transformers may materialize this buffer on a different device during loading.
if module.inv_freq.device.type != "meta":
module.device = module.inv_freq.device
module._compute_buffers()
class LuxferModel(LuxferPreTrainedModel):
def __init__(self, config: LuxferConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens: nn.Embedding
if config.scale_embedding:
self.embed_tokens = LuxferEmbedding(config.vocab_size, config.hidden_size, self.padding_idx)
else:
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
if config.image_feature_size is not None:
if config.image_proj_type == "mlp":
self.image_proj = MLPImageProjector(config) # type: ignore
elif config.image_proj_type == "linear":
self.image_proj = nn.Linear(config.image_feature_size, config.hidden_size, bias=False) # type: ignore
else:
raise ValueError(f"Unknown image_proj_type: {config.image_proj_type}")
self.layers = LuxferDecoder(config) # type: ignore
self.norm = LuxferRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> torch.nn.Embedding:
return self.embed_tokens
def set_input_embeddings(self, value: torch.nn.Embedding) -> None:
self.embed_tokens = value
def _prepare_decoder_attention_mask(
self,
attention_mask: torch.Tensor,
input_shape: Tuple[int, int],
inputs_embeds: torch.Tensor,
cache_position: torch.LongTensor,
) -> Optional[torch.Tensor]:
# create causal mask
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
combined_attention_mask = _make_causal_mask(
input_shape,
inputs_embeds.dtype,
device=inputs_embeds.device,
seq_len=attention_mask.shape[-1],
cache_position=cache_position,
)
input_shape = (input_shape[0], combined_attention_mask.shape[2])
if attention_mask.dim() == 4:
# Custom 4D attention mask
expanded_attn_mask = attention_mask
else:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
inputs_embeds.device
)
combined_attention_mask = (
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
)
return combined_attention_mask
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
past_key_values: Optional[DynamicCache] = None,
inputs_embeds: Optional[torch.Tensor] = None,
image_features: Optional[torch.Tensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Any,
) -> BaseModelOutputWithPast:
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
if output_attentions:
raise NotImplementedError("PLaMo 3 does not support output_attentions=True with its SDPA implementation.")
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
# retrieve input_ids and inputs_embeds
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if self.gradient_checkpointing and self.training and use_cache:
use_cache = False
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
batch_size, seq_length, _ = inputs_embeds.shape
seq_length_with_past = seq_length
past_key_values_length = 0
if past_key_values is not None:
past_key_values_length = past_key_values.get_seq_length()
seq_length_with_past = seq_length_with_past + past_key_values_length
if cache_position is None:
cache_position = torch.arange(
past_key_values_length,
past_key_values_length + seq_length,
device=inputs_embeds.device,
) # type: ignore
if image_features is not None:
assert self.config.image_token_id is not None
image_embeds = self.image_proj(image_features)
assert image_embeds.shape == inputs_embeds.shape, (image_embeds.shape, inputs_embeds.shape)
mask = input_ids == self.config.image_token_id
inputs_embeds[mask] = image_embeds[mask]
# embed positions
require_attn_mask = False
if not self.training or past_key_values is not None:
require_attn_mask = True
if seq_length_with_past > self.config.window_size + 1:
require_attn_mask = True
if require_attn_mask and attention_mask is None:
attention_mask = torch.ones(
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
)
if attention_mask is not None:
attention_mask = self._prepare_decoder_attention_mask(
attention_mask,
(batch_size, seq_length),
inputs_embeds,
cache_position, # type: ignore
)
hidden_states = inputs_embeds
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=self.config)
# decoder layers
out = self.layers(
DecoderInput(
hidden_states,
attention_mask,
past_key_values,
output_hidden_states,
output_attentions,
self.gradient_checkpointing,
)
)
assert isinstance(out, DecoderOutput)
hidden_states = out.hidden_states
all_hidden_states = out.all_hidden_states
all_self_attns = out.all_self_attns
hidden_states = self.norm(hidden_states)
# add hidden states from the last decoder layer
if output_hidden_states:
assert all_hidden_states is not None
all_hidden_states += (hidden_states,)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
hidden_states=all_hidden_states,
attentions=all_self_attns,
)
class LuxferForCausalLM(LuxferPreTrainedModel, GenerationMixin): # type: ignore
# Without this, the model cannot be loaded into a meta device.
# Relevant code:
# https://github.com/huggingface/transformers/blob/v4.44.2/src/transformers/modeling_utils.py#L4376-L4381
# https://github.com/huggingface/transformers/blob/v4.44.2/src/transformers/modeling_utils.py#L356
# https://github.com/pytorch/pytorch/blob/v2.4.1/torch/nn/modules/module.py#L2068
_supports_param_buffer_assignment = False
def __init__(self, config: LuxferConfig) -> None:
super().__init__(config)
self.model = LuxferModel(config)
self.vocab_size = config.vocab_size
vocab_size = ((self.vocab_size + 15) // 16) * 16
self.lm_head: torch.nn.Module = nn.Linear(config.hidden_size, vocab_size, bias=False)
if self.config.tie_word_embeddings:
self._tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> torch.nn.Embedding:
return self.model.embed_tokens
def set_input_embeddings(self, value: torch.nn.Embedding) -> None:
self.model.embed_tokens = value
def get_output_embeddings(self) -> torch.nn.Module:
return self.lm_head
def set_output_embeddings(self, new_embeddings: torch.nn.Module) -> None:
self.lm_head = new_embeddings
def set_decoder(self, decoder: LuxferModel) -> None:
self.model = decoder
def get_decoder(self) -> LuxferModel:
return self.model
def forward( # type: ignore
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
past_key_values: Optional[DynamicCache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
image_features: Optional[torch.Tensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: int | torch.Tensor = 0,
**kwargs: Any,
) -> CausalLMOutputWithPast:
r"""
Args:
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
"""
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
)
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
image_features=image_features,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs[0]
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
logits = logits[..., : self.vocab_size]
loss = None
if labels is not None:
if len(kwargs) > 0 and set(kwargs.keys()) != set(["ignore_index"]):
warnings.warn(
f"The following kwargs may not be supported: {', '.join(kwargs.keys())}. ",
stacklevel=2,
)
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def prepare_inputs_for_generation(
self,
input_ids: torch.Tensor,
past_key_values: Optional[DynamicCache] = None,
attention_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
image_features: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> Dict[str, Any]:
past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = kwargs.get("cache_position")
# Transformers 5.14 supplies positions; newer 5.x releases supply the pending length.
input_length = kwargs.get("next_sequence_length")
use_inputs_embeds = inputs_embeds is not None and kwargs.get("is_first_iteration", past_length == 0)
if input_length is None:
if cache_position is not None:
input_length = cache_position.shape[0]
elif attention_mask is not None:
input_length = attention_mask.shape[1] - past_length
elif use_inputs_embeds:
input_length = inputs_embeds.shape[1] - past_length
elif input_ids.shape[1] > past_length:
input_length = input_ids.shape[1] - past_length
else:
# The caller has already removed the cached prefix.
input_length = input_ids.shape[1]
if input_length <= 0:
raise ValueError("Generation requires at least one input token not already present in the cache.")
if use_inputs_embeds:
model_inputs: Dict[str, Any] = {"inputs_embeds": inputs_embeds[:, -input_length:, :]}
else:
model_inputs = {"input_ids": input_ids[:, -input_length:]}
if image_features is not None:
image_features = image_features[:, -input_length:, :]
position_ids = kwargs.get("position_ids", None)
if attention_mask is not None and position_ids is None:
# create position_ids on the fly for batch generation
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if position_ids is not None:
position_ids = position_ids[:, -input_length:]
model_inputs.update(
{
"position_ids": position_ids,
"cache_position": cache_position,
"past_key_values": past_key_values,
"use_cache": kwargs.get("use_cache"),
"output_attentions": kwargs.get("output_attentions"),
"output_hidden_states": kwargs.get("output_hidden_states"),
"logits_to_keep": kwargs.get("logits_to_keep"),
"attention_mask": attention_mask,
"image_features": image_features,
}
)
return model_inputs
@staticmethod
def _reorder_cache(past_key_values: DynamicCache, beam_idx: torch.Tensor) -> DynamicCache:
past_key_values.reorder_cache(beam_idx)
return past_key_values
# Legacy source aliases; canonical public names use Luxfer.
Plamo3DecoderLayer = LuxferDecoderLayer
Plamo3Decoder = LuxferDecoder
Plamo3PreTrainedModel = LuxferPreTrainedModel
Plamo3Model = LuxferModel
Plamo3ForCausalLM = LuxferForCausalLM