Convert formatting to use ruff instead of yapf + isort (#26247)
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
This commit is contained in:
@@ -5,6 +5,7 @@
|
||||
The architecture is the same as granitemoe but with the addition of shared
|
||||
experts.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from itertools import islice
|
||||
from typing import Optional
|
||||
@@ -18,12 +19,17 @@ from vllm.config import CacheConfig, VllmConfig
|
||||
from vllm.distributed import get_pp_group
|
||||
from vllm.model_executor.layers.activation import SiluAndMul
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
|
||||
RowParallelLinear)
|
||||
from vllm.model_executor.layers.linear import (
|
||||
MergedColumnParallelLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
|
||||
DEFAULT_VOCAB_PADDING_SIZE,
|
||||
ParallelLMHead,
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from .granitemoe import GraniteMoeAttention, GraniteMoeModel, GraniteMoeMoE
|
||||
@@ -32,7 +38,6 @@ from .utils import AutoWeightsLoader, make_layers, maybe_prefix
|
||||
|
||||
|
||||
class GraniteMoeSharedMLP(nn.Module):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: GraniteMoeSharedConfig,
|
||||
@@ -48,16 +53,20 @@ class GraniteMoeSharedMLP(nn.Module):
|
||||
output_sizes=[self.hidden_size] * 2,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.input_linear")
|
||||
prefix=f"{prefix}.input_linear",
|
||||
)
|
||||
self.output_linear = RowParallelLinear(
|
||||
self.hidden_size,
|
||||
self.input_size,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.output_linear")
|
||||
prefix=f"{prefix}.output_linear",
|
||||
)
|
||||
if config.hidden_act != "silu":
|
||||
raise ValueError(f"Unsupported activation: {config.hidden_act}. "
|
||||
"Only silu is supported for now.")
|
||||
raise ValueError(
|
||||
f"Unsupported activation: {config.hidden_act}. "
|
||||
"Only silu is supported for now."
|
||||
)
|
||||
self.act_fn = SiluAndMul()
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
@@ -68,7 +77,6 @@ class GraniteMoeSharedMLP(nn.Module):
|
||||
|
||||
|
||||
class GraniteMoeSharedDecoderLayer(nn.Module):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: GraniteMoeSharedConfig,
|
||||
@@ -91,26 +99,28 @@ class GraniteMoeSharedDecoderLayer(nn.Module):
|
||||
cache_config=cache_config,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.self_attn",
|
||||
attention_multiplier=config.attention_multiplier)
|
||||
attention_multiplier=config.attention_multiplier,
|
||||
)
|
||||
self.block_sparse_moe = GraniteMoeMoE(
|
||||
num_experts=config.num_local_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.block_sparse_moe")
|
||||
self.shared_mlp = None if \
|
||||
getattr(config, 'shared_intermediate_size', 0) == 0 \
|
||||
prefix=f"{prefix}.block_sparse_moe",
|
||||
)
|
||||
self.shared_mlp = (
|
||||
None
|
||||
if getattr(config, "shared_intermediate_size", 0) == 0
|
||||
else GraniteMoeSharedMLP(
|
||||
config,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.shared_mlp"
|
||||
config, quant_config=quant_config, prefix=f"{prefix}.shared_mlp"
|
||||
)
|
||||
)
|
||||
|
||||
self.input_layernorm = RMSNorm(config.hidden_size,
|
||||
eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = RMSNorm(config.hidden_size,
|
||||
eps=config.rms_norm_eps)
|
||||
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = RMSNorm(
|
||||
config.hidden_size, eps=config.rms_norm_eps
|
||||
)
|
||||
|
||||
self.residual_multiplier = config.residual_multiplier
|
||||
|
||||
@@ -144,7 +154,6 @@ class GraniteMoeSharedDecoderLayer(nn.Module):
|
||||
|
||||
@support_torch_compile
|
||||
class GraniteMoeSharedModel(nn.Module):
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
|
||||
@@ -156,8 +165,11 @@ class GraniteMoeSharedModel(nn.Module):
|
||||
self.config = config
|
||||
self.quant_config = quant_config # Required by MixtralModel
|
||||
self.padding_idx = config.pad_token_id
|
||||
lora_vocab = (lora_config.lora_extra_vocab_size *
|
||||
(lora_config.max_loras or 1)) if lora_config else 0
|
||||
lora_vocab = (
|
||||
(lora_config.lora_extra_vocab_size * (lora_config.max_loras or 1))
|
||||
if lora_config
|
||||
else 0
|
||||
)
|
||||
self.vocab_size = config.vocab_size + lora_vocab
|
||||
self.org_vocab_size = config.vocab_size
|
||||
|
||||
@@ -174,7 +186,8 @@ class GraniteMoeSharedModel(nn.Module):
|
||||
lambda prefix: GraniteMoeSharedDecoderLayer(
|
||||
config, cache_config, quant_config=quant_config, prefix=prefix
|
||||
),
|
||||
prefix=f"{prefix}.layers")
|
||||
prefix=f"{prefix}.layers",
|
||||
)
|
||||
|
||||
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
@@ -200,40 +213,46 @@ class GraniteMoeSharedModel(nn.Module):
|
||||
for layer in islice(self.layers, self.start_layer, self.end_layer):
|
||||
hidden_states = layer(positions, hidden_states)
|
||||
if not get_pp_group().is_last_rank:
|
||||
return IntermediateTensors({
|
||||
"hidden_states": hidden_states,
|
||||
})
|
||||
return IntermediateTensors(
|
||||
{
|
||||
"hidden_states": hidden_states,
|
||||
}
|
||||
)
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return hidden_states
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str,
|
||||
torch.Tensor]]) -> set[str]:
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
new_weights = {}
|
||||
for n, p in weights:
|
||||
if n.endswith('.block_sparse_moe.input_linear.weight'):
|
||||
if n.endswith(".block_sparse_moe.input_linear.weight"):
|
||||
for e in range(p.size(0)):
|
||||
w1_name = n.replace(
|
||||
'.block_sparse_moe.input_linear.weight',
|
||||
f".block_sparse_moe.experts.{e}.w1.weight")
|
||||
".block_sparse_moe.input_linear.weight",
|
||||
f".block_sparse_moe.experts.{e}.w1.weight",
|
||||
)
|
||||
w3_name = n.replace(
|
||||
'.block_sparse_moe.input_linear.weight',
|
||||
f".block_sparse_moe.experts.{e}.w3.weight")
|
||||
".block_sparse_moe.input_linear.weight",
|
||||
f".block_sparse_moe.experts.{e}.w3.weight",
|
||||
)
|
||||
w1_param, w3_param = p[e].chunk(2, dim=0)
|
||||
assert w1_name not in new_weights
|
||||
assert w3_name not in new_weights
|
||||
new_weights[w1_name] = w1_param
|
||||
new_weights[w3_name] = w3_param
|
||||
elif n.endswith('.block_sparse_moe.output_linear.weight'):
|
||||
elif n.endswith(".block_sparse_moe.output_linear.weight"):
|
||||
for e in range(p.size(0)):
|
||||
w2_name = n.replace(
|
||||
'.block_sparse_moe.output_linear.weight',
|
||||
f".block_sparse_moe.experts.{e}.w2.weight")
|
||||
".block_sparse_moe.output_linear.weight",
|
||||
f".block_sparse_moe.experts.{e}.w2.weight",
|
||||
)
|
||||
w2_param = p[e]
|
||||
assert w2_name not in new_weights
|
||||
new_weights[w2_name] = w2_param
|
||||
elif n.endswith('.block_sparse_moe.router.layer.weight'):
|
||||
gate_name = n.replace('.block_sparse_moe.router.layer.weight',
|
||||
".block_sparse_moe.gate.weight")
|
||||
elif n.endswith(".block_sparse_moe.router.layer.weight"):
|
||||
gate_name = n.replace(
|
||||
".block_sparse_moe.router.layer.weight",
|
||||
".block_sparse_moe.gate.weight",
|
||||
)
|
||||
assert gate_name not in new_weights
|
||||
new_weights[gate_name] = p
|
||||
else:
|
||||
@@ -268,9 +287,9 @@ class GraniteMoeSharedForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
|
||||
self.config = config
|
||||
self.lora_config = lora_config
|
||||
|
||||
self.model = GraniteMoeSharedModel(vllm_config=vllm_config,
|
||||
prefix=maybe_prefix(
|
||||
prefix, "model"))
|
||||
self.model = GraniteMoeSharedModel(
|
||||
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
|
||||
)
|
||||
self.unpadded_vocab_size = config.vocab_size
|
||||
if lora_config:
|
||||
self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
|
||||
@@ -281,16 +300,19 @@ class GraniteMoeSharedForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
|
||||
padding_size=DEFAULT_VOCAB_PADDING_SIZE
|
||||
# We need bigger padding if using lora for kernel
|
||||
# compatibility
|
||||
if not lora_config else lora_config.lora_vocab_padding_size,
|
||||
if not lora_config
|
||||
else lora_config.lora_vocab_padding_size,
|
||||
quant_config=quant_config,
|
||||
prefix=maybe_prefix(prefix, "lm_head"))
|
||||
prefix=maybe_prefix(prefix, "lm_head"),
|
||||
)
|
||||
if config.tie_word_embeddings:
|
||||
self.lm_head.weight = self.model.embed_tokens.weight
|
||||
|
||||
self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
|
||||
config.vocab_size,
|
||||
scale=1 /
|
||||
self.config.logits_scaling)
|
||||
self.logits_processor = LogitsProcessor(
|
||||
self.unpadded_vocab_size,
|
||||
config.vocab_size,
|
||||
scale=1 / self.config.logits_scaling,
|
||||
)
|
||||
|
||||
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.model.get_input_embeddings(input_ids)
|
||||
@@ -302,30 +324,29 @@ class GraniteMoeSharedForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
|
||||
intermediate_tensors: Optional[IntermediateTensors] = None,
|
||||
inputs_embeds: Optional[torch.Tensor] = None,
|
||||
) -> torch.Tensor:
|
||||
hidden_states = self.model(input_ids, positions, intermediate_tensors,
|
||||
inputs_embeds)
|
||||
hidden_states = self.model(
|
||||
input_ids, positions, intermediate_tensors, inputs_embeds
|
||||
)
|
||||
return hidden_states
|
||||
|
||||
def compute_logits(self,
|
||||
hidden_states: torch.Tensor) -> Optional[torch.Tensor]:
|
||||
def compute_logits(self, hidden_states: torch.Tensor) -> Optional[torch.Tensor]:
|
||||
logits = self.logits_processor(self.lm_head, hidden_states)
|
||||
return logits
|
||||
|
||||
def make_empty_intermediate_tensors(
|
||||
self, batch_size: int, dtype: torch.dtype,
|
||||
device: torch.device) -> IntermediateTensors:
|
||||
return IntermediateTensors({
|
||||
"hidden_states":
|
||||
torch.zeros((batch_size, self.config.hidden_size),
|
||||
dtype=dtype,
|
||||
device=device),
|
||||
})
|
||||
self, batch_size: int, dtype: torch.dtype, device: torch.device
|
||||
) -> IntermediateTensors:
|
||||
return IntermediateTensors(
|
||||
{
|
||||
"hidden_states": torch.zeros(
|
||||
(batch_size, self.config.hidden_size), dtype=dtype, device=device
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str,
|
||||
torch.Tensor]]) -> set[str]:
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
skip_prefixes=(["lm_head."]
|
||||
if self.config.tie_word_embeddings else None),
|
||||
skip_prefixes=(["lm_head."] if self.config.tie_word_embeddings else None),
|
||||
)
|
||||
return loader.load_weights(weights)
|
||||
|
||||
Reference in New Issue
Block a user